text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
declare namespace adone.collection {
namespace I {
type Long = math.Long;
type Longable = math.I.Longable;
namespace ByteArray {
interface Varint32 {
value: number;
length: number;
}
interface Varint64 {
value: Long;
length: number;
}
interface String {
string: string;
length: number;
}
type Wrappable = string | ByteArray | Buffer | Uint8Array | ArrayBuffer;
type Metrics = "b" | "c";
}
}
/**
* Represents an array of bytes, enhanced Node.js Buffer
*/
class ByteArray {
readonly woffset: number;
readonly roffset: number;
readonly buffer: Buffer;
readonly noAssert: boolean;
/**
* Constructs a new ByteArray
*
* @param capacity Initial capacity. Defaults to ByteArray.DEFAULT_CAPACITY(64)
* @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false)
*/
constructor(capacity?: number, noAssert?: boolean);
/**
* Reads a BitSet as an array of booleans.
*
* @param offset Offset to read from. Will use and increase offset by length if omitted.
*/
readBitSet(offset?: number): boolean[];
/**
* Reads the specified number of bytes.
*
* @param length Number of bytes to read
* @param offset Offset to read from. Will use and increase offset by length if omitted.
*/
read(length: number, offset?: number): ByteArray;
/**
* Reads an 8bit signed integer
*
* @param offset Offset to read from
*/
readInt8(offset?: number): number;
/**
* Reads an 8bit unsigned integer
*
* @param offset Offset to read from
*/
readUInt8(offset?: number): number;
/**
* Reads a 16bit signed le integer
*
* @param offset Offset to read from
*/
readInt16LE(offset?: number): number;
/**
* Reads a 16bit unsigned le integer
*
* @param offset Offset to read from
*/
readUInt16LE(offset?: number): number;
/**
* Reads a 16bit signed be integer
*
* @param offset Offset to read from
*/
readInt16BE(offset?: number): number;
/**
* Reads a 16bit unsigned be integer
*
* @param offset Offset to read from
*/
readUInt16BE(offset?: number): number;
/**
* Reads a 24bit unsigned be integer
*
* @param offset Offset to read from
*/
readUInt24BE(offset?: number): number;
/**
* Reads a 32bit signed le integer
*
* @param offset Offset to read from
*/
readInt32LE(offset?: number): number;
/**
* Reads a 32bit unsigned le integer
*
* @param offset Offset to read from
*/
readUInt32LE(offset?: number): number;
/**
* Reads a 32bit signed be integer
*
* @param offset Offset to read from
*/
readInt32BE(offset?: number): number;
/**
* Reads a 32bit unsigned be integer
*
* @param offset Offset to read from
*/
readUInt32BE(offset?: number): number;
/**
* Reads a 64bit signed le integer as math.Long
*
* @param offset Offset to read from
*/
readInt64LE(offset?: number): math.Long;
/**
* Reads a 64bit unsigned le integer as math.Long
*
* @param offset Offset to read from
*/
readUInt64LE(offset?: number): math.Long;
/**
* Reads a 64bit signed be integer as math.Long
*
* @param offset Offset to read from
*/
readInt64BE(offset?: number): math.Long;
/**
* Reads a 64bit unsigned be integer as math.Long
*
* @param offset Offset to read from
*/
readUInt64BE(offset?: number): math.Long;
/**
* Reads a 32bit le float
*
* @param offset Offset to read from
*/
readFloatLE(offset?: number): number;
/**
* Reads a 32bit be float
*
* @param offset Offset to read from
*/
readFloatBE(offset?: number): number;
/**
* Reads a 64bit le float
*
* @param offset Offset to read from
*/
readDoubleLE(offset?: number): number;
/**
* Reads a 64bit be float
*
* @param offset Offset to read from
*/
readDoubleBE(offset?: number): number;
/**
* Appends some data to this ByteArray.
* This will overwrite any contents behind the specified offset up to the appended data's length.
*
* @param source The source write from
* @param offset Offset to write at
* @param length length to read from the source
* @param encoding encoding to use for wrapping the source in bytearray
*/
write(source: I.ByteArray.Wrappable, offset?: number, length?: number, encoding?: string): this;
/**
* Writes the array as a bitset.
* @param value Array of booleans to write
*/
writeBitSet(value: number[]): this;
/**
* Writes the array as a bitset.
* @param value Array of booleans to write
* @param offset Offset to write at
*/
writeBitSet(value: number[], offset: number): number;
/**
* Writes a buffer at the given offset
* @param buf Buffer to write
* @param offset Offset to write at
*/
writeBuffer(buf: Buffer, offset?: number): this;
/**
* Writes an 8bit signed integer
*
* @param offset Offset to write at
*/
writeInt8(value: number, offset?: number): this;
/**
* Writes an 8bit unsigned integer
*
* @param offset Offset to write at
*/
writeUInt8(value: number, offset?: number): this;
/**
* Writes a 16bit signed le integer
*
* @param offset Offset to write at
*/
writeInt16LE(value: number, offset?: number): this;
/**
* Writes a 16bit signed be integer
*
* @param offset Offset to write at
*/
writeInt16BE(value: number, offset?: number): this;
/**
* Writes a 16bit unsigned le integer
*
* @param offset Offset to write at
*/
writeUInt16LE(value: number, offset?: number): this;
/**
* Writes a 16bit unsigned be integer
*
* @param offset Offset to write at
*/
writeUInt16BE(value: number, offset?: number): this;
/**
* Writes a 24bit unsigned be integer
*
* @param offset Offset to write at
*/
writeUInt24BE(value: number, offset?: number): this;
/**
* Writes a 32bit signed le integer
*
* @param offset Offset to write at
*/
writeInt32LE(value: number, offset?: number): this;
/**
* Writes a 32bit signed be integer
*
* @param offset Offset to write at
*/
writeInt32BE(value: number, offset?: number): this;
/**
* Writes a 32bit unsigned le integer
*
* @param offset Offset to write at
*/
writeUInt32LE(value: number, offset?: number): this;
/**
* Writes a 32bit unsigned be integer
*
* @param offset Offset to write at
*/
writeUInt32BE(value: number, offset?: number): this;
/**
* Writes a 64bit signed le long integer
*
* @param offset Offset to write at
*/
writeInt64LE(value: math.Long | string | number, offset?: number): this;
/**
* Writes a 64bit signed be long integer
*
* @param offset Offset to write at
*/
writeInt64BE(value: math.Long | string | number, offset?: number): this;
/**
* Writes a 64bit unsigned le long integer
*
* @param offset Offset to write at
*/
writeUInt64LE(value: math.Long | string | number, offset?: number): this;
/**
* Writes a 64bit unsigned be long integer
*
* @param offset Offset to write at
*/
writeUInt64BE(value: math.Long | string | number, offset?: number): this;
/**
* Writes a 32bit le float
*
* @param offset Offset to write at
*/
writeFloatLE(value: number, offset?: number): this;
/**
* Writes a 32bit be float
*
* @param offset Offset to write at
*/
writeFloatBE(value: number, offset?: number): this;
/**
* Writes a 64bit le float
*
* @param offset Offset to write at
*/
writeDoubleLE(value: number, offset?: number): this;
/**
* Writes a 64bit be float
*
* @param offset Offset to write at
*/
writeDoubleBE(value: number, offset?: number): this;
/**
* Writes a 32bit base 128 variable-length integer
*/
writeVarint32(value: number): this;
/**
* Writes a 32bit base 128 variable-length integer
*
* @param offset Offset to write at
*/
writeVarint32(value: number, offset: number): number;
/**
* Writes a zig-zag encoded 32bit base 128 variable-length integer
*/
writeVarint32ZigZag(value: number): this;
/**
* Writes a zig-zag encoded 32bit base 128 variable-length integer
*
* @param offset Offset to write at
*/
writeVarint32ZigZag(value: number, offset: number): number;
/**
* Reads a 32bit base 128 variable-length integer
*/
readVarint32(): number;
/**
* Reads a 32bit base 128 variable-length integer
*
* @param offset Offset to read from
*/
readVarint32(offset: number): I.ByteArray.Varint32;
/**
* Reads a zig-zag encoded 32bit base 128 variable-length integer
*/
readVarint32ZigZag(): number;
/**
* Reads a zig-zag encoded 32bit base 128 variable-length integer
*
* @param offset Offset to read from
*/
readVarint32ZigZag(offset: number): I.ByteArray.Varint32;
/**
* Writes a 64bit base 128 variable-length integer
*/
writeVarint64(value: math.Long | string | number): this;
/**
* Writes a 64bit base 128 variable-length integer
*
* @param offset Offset to write at
*/
writeVarint64(value: math.Long | string | number, offset: number): number;
/**
* Writes a zig-zag encoded 64bit base 128 variable-length integer
*/
writeVarint64ZigZag(value: math.Long | string | number): this;
/**
* Writes a zig-zag encoded 64bit base 128 variable-length integer
*
* @param offset Offset to write at
*/
writeVarint64ZigZag(value: math.Long | string | number, offset: number): number;
/**
* Reads a 64bit base 128 variable-length integer
*/
readVarint64(): I.Long;
/**
* Reads a 64bit base 128 variable-length integer
*
* @param offset Offset to read from
*/
readVarint64(offset: number): I.ByteArray.Varint64;
/**
* Reads a zig-zag encoded 64bit base 128 variable-length integer
*/
readVarint64ZigZag(): math.Long;
/**
* Reads a zig-zag encoded 64bit base 128 variable-length integer
*
* @param offset Offset to read from
*/
readVarint64ZigZag(offset: number): I.ByteArray.Varint64;
/**
* Writes a NULL-terminated UTF8 encoded string.
* For this to work the specified string must not contain any NULL characters itself
*/
writeCString(str: string): this;
/**
* Writes a NULL-terminated UTF8 encoded string.
* For this to work the specified string must not contain any NULL characters itself
*
* @param offset Offset to write at
*/
writeCString(str: string, offset: number): number;
/**
* Reads a NULL-terminated UTF8 encoded string.
* For this to work the string read must not contain any NULL characters itself
*/
readCString(): string;
/**
* Reads a NULL-terminated UTF8 encoded string.
* For this to work the string read must not contain any NULL characters itself
*
* @param offset Offset to read from
*/
readCString(offset: number): I.ByteArray.String;
/**
* Writes an UTF8 encoded string
*/
writeString(str: string): this;
/**
* Writes an UTF8 encoded string
*
* @param offset Offset to write at
*/
writeString(str: string, offset: number): number;
/**
* Reads an UTF8 encoded string
*
* @param length Number of characters or bytes to read
* @param metrics Metrics specifying what n is meant to count. Defaults to ByteArray.METRICS_CHARS("c")
*/
readString(length: number, metrics?: I.ByteArray.Metrics): string;
/**
* Reads an UTF8 encoded string
*
* @param length Number of characters or bytes to read
* @param metrics Metrics specifying what n is meant to count. Defaults to ByteArray.METRICS_CHARS("c")
* @param offset Offset to read from
*/
readString(length: number, metrics: I.ByteArray.Metrics, offset: number): I.ByteArray.String;
/**
* Reads an UTF8 encoded string
*
* @param length Number of characters or bytes to read
* @param offset Offset to read from
*/
readString(length: number, offset: number): I.ByteArray.String;
/**
* Writes a length as varint32 prefixed UTF8 encoded string
*/
writeVString(str: string): this;
/**
* Writes a length as varint32 prefixed UTF8 encoded string
*
* @param offset Offset to read from
*/
writeVString(str: string, offset: number): number;
/**
* Reads a length as varint32 prefixed UTF8 encoded string
*/
readVString(): string;
/**
* Reads a length as varint32 prefixed UTF8 encoded string
*
* @param offset Offset to read from
*/
readVString(offset: number): I.ByteArray.String;
/**
* Appends this ByteArray's contents to another ByteArray.
* This will overwrite any contents behind the specified offset up to the length of this ByteArray's data
*
* @param offset Offset to append to
*/
appendTo(target: ByteArray, offset?: number): this;
/**
* Enables or disables assertions of argument types and offsets.
* Assertions are enabled by default but you can opt to disable them if your code already makes sure that everything is valid
*/
assert(assert?: boolean): this;
/**
* Gets the capacity of this ByteArray's backing buffer
*/
capacity(): number;
/**
* Clears this ByteArray's offsets by setting offset to 0 and limit to the backing buffer's capacity
*/
clear(): this;
/**
* Creates a cloned instance of this ByteArray,
* preset with this ByteArray's values for offset, markedOffset and limit
*
* @param copy Whether to copy the backing buffer or to return another view on the same, false by default
*/
clone(copy?: boolean): ByteArray;
/**
* Compacts this ByteArray to be backed by a buffer of its contents' length.
* Will set offset = 0 and limit = capacity and adapt markedOffset to the same relative position if set
*
* @param begin Offset to start at, buffer offset by default
* @param end Offset to end at, buffer limit by default
*/
compact(begin?: number, end?: number): this;
/**
* Creates a copy of this ByteArray's contents.
*
* @param begin Begin offset, buffer offset by default
* @param end End offset, buffer limit by default
*/
copy(begin?: number, end?: number): ByteArray;
/**
* Copies this ByteArray's contents to another ByteArray.
*
* @param targetOffset Offset to copy to. Will use and increase the target's offset by the number of bytes copied if omitted
* @param sourceOffset Offset to start copying from. Will use and increase offset by the number of bytes copied if omitted
* @param sourceLimit Offset to end copying from, defaults to the buffer limit
*/
copyTo(target: ByteArray, targetOffset?: number, souceOffset?: number, sourceLimit?: number): this | ByteArray;
/**
* Makes sure that this ByteArray is backed by a ByteArray#buffer of at least the specified capacity.
* If the current capacity is exceeded, it will be doubled.
* If double the current capacity is less than the required capacity, the required capacity will be used instead
*/
ensureCapacity(capacity: number): this;
/**
* Overwrites this ByteArray's contents with the specified value.
*
* @param value Byte value to fill with. If given as a string, the first character is used
* @param begin Begin offset. Will use and increase offset by the number of bytes written if omitted. defaults to offset
* @param end End offset, defaults to limit.
*/
fill(value: string | number, begin?: number, end?: number): this;
/**
* Makes this ByteArray ready for a new sequence of write or relative read operations.
* Sets limit = offset and offset = 0.
* Make sure always to flip a ByteArray when all relative read or write operations are complete
*/
flip(): this;
/**
* Marks an offset on this ByteArray to be used later
*
* @param offset Offset to mark. Defaults to offset.
*/
mark(offset?: number): this;
/**
* Prepends some data to this ByteArray.
* This will overwrite any contents before the specified offset up to the prepended data's length.
* If there is not enough space available before the specified offset,
* the backing buffer will be resized and its contents moved accordingly
*
* @param source Data to prepend
* @param offset Offset to prepend at. Will use and decrease offset by the number of bytes prepended if omitted.
*/
prepend(source: I.ByteArray.Wrappable, offset: number): this;
/**
* Prepends some data to this ByteArray.
* This will overwrite any contents before the specified offset up to the prepended data's length.
* If there is not enough space available before the specified offset,
* the backing buffer will be resized and its contents moved accordingly
*
* @param source Data to prepend
* @param encoding Encoding if data is a string
* @param offset Offset to prepend at. Will use and decrease offset by the number of bytes prepended if omitted.
*/
prepend(source: I.ByteArray.Wrappable, encoding?: string, offset?: number): this;
/**
* Prepends this ByteArray to another ByteArray.
* This will overwrite any contents before the specified offset up to the prepended data's length.
* If there is not enough space available before the specified offset,
* the backing buffer will be resized and its contents moved accordingly
*
* @param offset Offset to prepend at
*/
prependTo(target: ByteArray, offset?: number): this;
/**
* Gets the number of remaining readable bytes
*/
remaining(): number;
/**
* Resets this ByteArray's offset.
* If an offset has been marked through mark before, offset will be set to markedOffset, which will then be discarded.
* If no offset has been marked, sets offset = 0
*/
reset(): this;
/**
* Resizes this ByteArray to be backed by a buffer of at least the given capacity.
* Will do nothing if already that large or larger.
*
* @param capacity Capacity required
*/
resize(capacity: number): this;
/**
* Reverses this ByteArray's contents.
*
* @param begin Offset to start at, defaults to offset
* @param end Offset to end at, defaults to limit
*/
reverse(begin?: number, end?: number): this;
/**
* Skips the next length bytes. This will just advance
*/
skip(length: number): this;
/**
* Slices this ByteArray by creating a cloned instance with offset = begin and limit = end
*
* @param begin Begin offset, defaults to offset
* @param end End offset, defaults to limit
*/
slice(begin?: number, end?: number): ByteArray;
/**
* Returns a copy of the backing buffer that contains this ByteArray's contents.
*
* @param forceCopy If true returns a copy, otherwise returns a view referencing the same memory if possible, false by default
* @param begin Begin offset, offset by default
* @param end End offset, limit by default
*/
toBuffer(forceCopy?: boolean, begin?: number, end?: number): Buffer;
/**
* Returns a raw buffer compacted to contain this ByteArray's contents
*/
toArrayBuffer(): ArrayBuffer;
/**
* Converts the ByteArray's contents to a string
*
* @param encoding Output encoding
* @param begin Begin offset, offset by default
* @param end End offset, limit by default
*/
toString(encoding?: string, begin?: number, end?: number): string;
/**
* Encodes this ByteArray's contents to a base64 encoded string
*
* @param begin Begin offset, offset by default
* @param end End offset, limit by default
*/
toBase64(begin?: number, end?: number): string;
/**
* Encodes this ByteArray to a binary encoded string, that is using only characters 0x00-0xFF as bytes
*
* @param begin Begin offset, offset by default
* @param end End offset, limit by default
*/
toBinary(begin?: number, end?: number): string;
/**
* Encodes this ByteArray to a hex encoded string with marked offsets
*
* @param columns If true returns two columns hex + ascii, defaults to false
*/
toDebug(columns?: boolean): string;
/**
* Encodes this ByteArray's contents to a hex encoded string
*
* @param begin Begin offset, offset by default
* @param end End offset, limit by default
*/
toHex(begin?: number, end?: number): string;
/**
* Encodes this ByteArray's contents to an UTF8 encoded string
*
* @param begin Begin offset, offset by default
* @param end End offset, limit by default
*/
toUTF8(begin?: number, end?: number): string;
static accessor(): typeof Buffer;
/**
* Allocates a new ByteArray backed by a buffer of the specified capacity.
*
* @param capacity Initial capacity. Defaults to ByteArray.DEFAULT_CAPACITY(64)
* @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false)
*/
static allocate(capacity?: number, noAssert?: boolean): ByteArray;
/**
* Concatenates multiple ByteArrays into one
*
* @param encoding Encoding for strings
* @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false)
*/
static concat(buffers: I.ByteArray.Wrappable[], encoding?: string, noAssert?: boolean): ByteArray;
static type(): typeof Buffer;
/**
* Wraps a buffer or a string.
* Sets the allocated ByteArray's offset to 0 and its limit to the length of the wrapped data
*
* @param encoding Encoding for strings
* @param noAssert Whether to skip assertions of offsets and values. Defaults to ByteArray.DEFAULT_NOASSERT(false)
*/
static wrap(buffer: I.ByteArray.Wrappable, encoding?: string, noAssert?: boolean): ByteArray;
/**
* Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer
*/
static calculateVarint32(value: number): number;
/**
* Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding
*/
static zigZagEncode32(n: number): number;
/**
* Decodes a zigzag encoded signed 32bit integer
*/
static zigZagDecode32(n: number): number;
/**
* Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer
*/
static calculateVarint64(value: number | string): number;
/**
* Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding
*/
static zigZagEncode64(value: number | string | I.Long): I.Long;
/**
* Decodes a zigzag encoded signed 64bit integer.
*/
static zigZagDecode64(value: number | string | I.Long): I.Long;
/**
* Calculates the number of UTF8 characters of a string.
* JavaScript itself uses UTF-16,
* so that a string's length property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF
*/
static calculateUTF8Chars(str: string): number;
/**
* Calculates the number of UTF8 bytes of a string.
*/
static calculateString(str: string): number;
/**
* Decodes a base64 encoded string to a ByteArray
*/
static fromBase64(str: string): ByteArray;
/**
* Encodes a binary string to base64 like window.btoa does
*/
static btoa(str: string): string;
/**
* Decodes a base64 encoded string to binary like window.atob does
*/
static atob(b64: string): string;
/**
* Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteArray
*/
static fromBinary(str: string): ByteArray;
/**
* Decodes a hex encoded string with marked offsets to a ByteArray
*/
static fromDebug(str: string, noAssert?: boolean): ByteArray;
/**
* Decodes a hex encoded string to a ByteArray
*/
static fromHex(str: string, noAssert?: boolean): ByteArray;
/**
* Decodes an UTF8 encoded string to a ByteArray
*/
static fromUTF8(str: string, noAssert?: boolean): ByteArray;
/**
* Default initial capacity
*/
static DEFAULT_CAPACITY: number;
/**
* Default no assertions flag
*/
static DEFAULT_NOASSERT: boolean;
/**
* Maximum number of bytes required to store a 32bit base 128 variable-length integer
*/
static MAX_VARINT32_BYTES: number;
/**
* Maximum number of bytes required to store a 64bit base 128 variable-length integer
*/
static MAX_VARINT64_BYTES: number;
/**
* Metrics representing number of UTF8 characters. Evaluates to `c`.
*/
static METRICS_CHARS: string;
/**
* Metrics representing number of bytes. Evaluates to `b`.
*/
static METRICS_BYTES: string;
}
} | the_stack |
import "../Operator"
import type { Cause } from "../Cause/cause"
import { empty, then } from "../Cause/cause"
/**
* Ported from https://github.com/zio/zio/blob/master/core/shared/src/main/scala/zio/Scope.scala
*
* Copyright 2020 Michael Arnaldi and the Matechs Garage Contributors.
*/
import * as A from "../Collections/Immutable/Array"
import { cause } from "../Effect/cause"
import { succeed, succeedWith, suspend } from "../Effect/core"
import type { UIO } from "../Effect/effect"
import { map_ } from "../Effect/map"
import { uncause } from "../Effect/uncause"
import { zipWith_ } from "../Effect/zipWith"
import * as E from "../Either"
import { AtomicNumber } from "../Support/AtomicNumber"
import { AtomicReference } from "../Support/AtomicReference"
/**
* Represent Common Ops between Global | Local<A>
*/
export interface CommonScope<A> {
/**
* Determines if the scope is closed at the instant the effect executes.
* Returns an effect that will succeed with `true` if the scope is closed,
* and `false` otherwise.
*/
readonly closed: UIO<boolean>
/**
* Prevents a previously added finalizer from being executed when the scope
* is closed. The returned effect will succeed with `true` if the finalizer
* will not be run by this scope, and `false` otherwise.
*/
readonly deny: (key: Key) => UIO<boolean>
/**
* Determines if the scope is empty (has no finalizers) at the instant the
* effect executes. The returned effect will succeed with `true` if the scope
* is empty, and `false` otherwise.
*/
readonly empty: UIO<boolean>
/**
* Adds a finalizer to the scope. If successful, this ensures that when the
* scope exits, the finalizer will be run
*
* The returned effect will succeed with a key if the finalizer was added
* to the scope, and `None` if the scope is already closed.
*/
readonly ensure: (finalizer: (a: A) => UIO<any>) => UIO<E.Either<A, Key>>
/**
* Extends the specified scope so that it will not be closed until this
* scope is closed. Note that extending a scope into the global scope
* will result in the scope *never* being closed!
*
* Scope extension does not result in changes to the scope contract: open
* scopes must *always* be closed.
*/
readonly extend: (that: Scope<any>) => UIO<boolean>
/**
* Determines if the scope is open at the moment the effect is executed.
* Returns an effect that will succeed with `true` if the scope is open,
* and `false` otherwise.
*/
readonly open: UIO<boolean>
/**
* Determines if the scope has been released at the moment the effect is
* executed. A scope can be closed yet unreleased, if it has been
* extended by another scope which is not yet released.
*/
readonly released: UIO<boolean>
readonly unsafeEnsure: (finalizer: (_: A) => UIO<any>) => E.Either<A, Key>
readonly unsafeExtend: (that: Scope<any>) => boolean
readonly unsafeDeny: (key: Key) => boolean
}
/**
* Represents a key in a scope, which is associated with a single finalizer.
*/
export class Key {
/**
* Attempts to remove the finalizer associated with this key from the
* scope. The returned effect will succeed with a boolean, which indicates
* whether the attempt was successful. A value of `true` indicates the
* finalizer will not be executed, while a value of `false` indicates the
* finalizer was already executed.
*/
remove: UIO<boolean> = succeed(false)
constructor(remove?: UIO<boolean>) {
if (remove) {
this.remove = remove
}
}
setRemove(remove: UIO<boolean>) {
this.remove = remove
}
}
/**
* A `Scope<A>` is a value that allows adding finalizers identified by a key.
* Scopes are closed with a value of type `A`, which is provided to all the
* finalizers when the scope is released.
*
* For safety reasons, this interface has no method to close a scope. Rather,
* an open scope may be required with `makeScope`, which returns a function
* that can close a scope. This allows scopes to be safely passed around
* without fear they will be accidentally closed.
*/
export type Scope<A> = Global | Local<A>
/**
* The global scope, which is entirely stateless. Finalizers added to the
* global scope will never be executed (nor kept in memory).
*/
export class Global implements CommonScope<never> {
readonly _tag = "Global"
constructor() {
this.deny = this.deny.bind(this)
this.ensure = this.ensure.bind(this)
this.extend = this.extend.bind(this)
this.unsafeEnsure = this.unsafeEnsure.bind(this)
this.unsafeExtend = this.unsafeExtend.bind(this)
}
private unsafeEnsureResult = E.right(new Key(succeedWith(() => true)))
private ensureResult = succeedWith(() => this.unsafeEnsureResult)
get closed(): UIO<boolean> {
return succeed(false)
}
deny(_key: Key): UIO<boolean> {
return succeed(true)
}
get empty(): UIO<boolean> {
return succeed(false)
}
ensure(_finalizer: (a: never) => UIO<any>): UIO<E.Either<never, Key>> {
return this.ensureResult
}
extend(that: Scope<any>): UIO<boolean> {
return succeedWith(() => this.unsafeExtend(that))
}
get open(): UIO<boolean> {
return map_(this.closed, (c) => !c)
}
get released(): UIO<boolean> {
return succeed(false)
}
unsafeEnsure(_finalizer: (_: never) => UIO<any>): E.Either<never, Key> {
return this.unsafeEnsureResult
}
unsafeExtend(that: Scope<any>): boolean {
switch (that._tag) {
case "Global":
return true
case "Local":
return that.unsafeAddRef()
}
}
unsafeDeny() {
return true
}
}
export class OrderedFinalizer {
constructor(readonly order: number, readonly finalizer: (_: any) => UIO<any>) {}
}
const noCause = empty
const noCauseEffect: UIO<Cause<never>> = succeed(noCause)
export class Local<A> implements CommonScope<A> {
readonly _tag = "Local"
constructor(
readonly finalizerCount: AtomicNumber,
readonly exitValue: AtomicReference<A | null>,
readonly references: AtomicNumber,
readonly finalizers: Map<Key, OrderedFinalizer>
) {}
get closed(): UIO<boolean> {
return succeedWith(() => this.unsafeClosed)
}
get open(): UIO<boolean> {
return map_(this.closed, (c) => !c)
}
deny(key: Key): UIO<boolean> {
return succeedWith(() => this.unsafeDeny(key))
}
get empty(): UIO<boolean> {
return succeedWith(() => this.finalizers.size === 0)
}
ensure(finalizer: (a: A) => UIO<any>): UIO<E.Either<A, Key>> {
return succeedWith(() => this.unsafeEnsure(finalizer))
}
extend(that: Scope<any>): UIO<boolean> {
return succeedWith(() => this.unsafeExtend(that))
}
get released(): UIO<boolean> {
return succeedWith(() => this.unsafeReleased())
}
unsafeExtend(that: Scope<any>): boolean {
if (this === that) {
return true
}
switch (that._tag) {
case "Global":
return true
case "Local":
if (!this.unsafeClosed && !that.unsafeClosed) {
that.unsafeAddRef()
this.unsafeEnsure((_) => that.release)
return true
} else {
return false
}
}
}
get release(): UIO<boolean> {
return suspend(() => {
const result = this.unsafeRelease()
if (result != null) {
return map_(result, () => true)
} else {
return succeed(false)
}
})
}
unsafeReleased() {
return this.references.get <= 0
}
unsafeEnsure(finalizer: (_: A) => UIO<any>): E.Either<A, Key> {
if (this.unsafeClosed) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return E.left(this.exitValue.get!)
}
const key = new Key()
key.setRemove(this.deny(key))
this.finalizers.set(
key,
new OrderedFinalizer(this.finalizerCount.incrementAndGet(), finalizer)
)
return E.right(key)
}
unsafeAddRef(): boolean {
if (this.unsafeClosed) {
return false
}
this.references.incrementAndGet()
return true
}
get unsafeClosed() {
return this.exitValue.get != null
}
unsafeDeny(key: Key) {
if (this.unsafeClosed) {
return false
} else {
return this.finalizers.delete(key)
}
}
unsafeClose(a: A): UIO<any> | null {
this.exitValue.compareAndSet(null, a)
return this.unsafeRelease()
}
unsafeRelease(): UIO<any> | null {
if (this.references.decrementAndGet() === 0) {
const totalSize = this.finalizers.size
if (totalSize === 0) {
return null
}
const array = Array.from(this.finalizers.values())
const sorted = array.sort((l, r) =>
l == null ? -1 : r == null ? 1 : l.order - r.order
)
const a = this.exitValue.get
return uncause(
A.reduce_(sorted, noCauseEffect, (acc, o) =>
o != null ? zipWith_(acc, cause(o.finalizer(a)), (a, b) => then(a, b)) : acc
)
)
} else {
return null
}
}
get unsafeEmpty() {
return this.finalizers.size === 0
}
}
/**
* The global scope, which is entirely stateless. Finalizers added to the
* global scope will never be executed (nor kept in memory).
*/
export const globalScope = new Global()
/**
* A tuple that contains an open scope, together with a function that closes
* the scope.
*/
export class Open<A> {
constructor(readonly close: (_: A) => UIO<boolean>, readonly scope: Local<A>) {}
}
export function unsafeMakeScope<A>() {
const exitValue = new AtomicReference<A | null>(null)
const finalizers = new Map<Key, OrderedFinalizer>()
const scope = new Local(
new AtomicNumber(Number.MIN_SAFE_INTEGER),
exitValue,
new AtomicNumber(1),
finalizers
)
return new Open<A>((a) => {
return suspend(() => {
const result = scope.unsafeClose(a)
if (result != null) {
return map_(result, () => true)
} else {
return succeed(false)
}
})
}, scope)
}
export function makeScope<A>() {
return succeedWith(() => unsafeMakeScope<A>())
} | the_stack |
import sinon from "sinon";
import { EventEmitter } from "events";
import mitt from "mitt";
import { fakeServerResponse, Stub, expectAsyncError } from "./test_utils";
import HTTP from "../src/http";
import {
NetworkTimeoutError,
ServerResponse,
UnparseableResponseError,
} from "../src/errors";
import { Emitter } from "../src/types";
const { expect } = intern.getPlugin("chai");
intern.getPlugin("chai").should();
const { describe, it, beforeEach, afterEach } =
intern.getPlugin("interface.bdd");
/** @test {HTTP} */
describe("HTTP class", () => {
function runSuite(label: string, emitter?: () => Emitter) {
describe(label, () => {
let sandbox: sinon.SinonSandbox, events: Emitter | undefined, http: HTTP;
beforeEach(() => {
sandbox = sinon.createSandbox();
events = emitter ? emitter() : undefined;
http = new HTTP(events, { timeout: 100 });
});
afterEach(() => sandbox.restore());
/** @test {HTTP#constructor} */
describe("#constructor", () => {
it("should expose a passed events instance", () => {
if (emitter) {
const events = emitter();
const http = new HTTP(events);
expect(http.events).to.eql(events);
}
});
it("should accept a requestMode option", () => {
expect(
new HTTP(events, {
requestMode: "no-cors",
}).requestMode
).eql("no-cors");
});
it("should not complain if an events handler is not provided", () => {
expect(() => {
new HTTP();
}).not.to.Throw(Error, /No events handler provided/);
});
});
/** @test {HTTP#request} */
describe("#request()", () => {
describe("Request headers", () => {
let fetchStub: sinon.SinonStub;
beforeEach(() => {
fetchStub = sandbox
.stub(http as any, "fetchFunc")
.returns(fakeServerResponse(200, {}, {}));
});
it("should set default headers", () => {
http.request("/");
expect(fetchStub.firstCall.args[1].headers).eql(
HTTP.DEFAULT_REQUEST_HEADERS
);
});
it("should merge custom headers with default ones", () => {
http.request("/", { headers: { Foo: "Bar" } });
expect(fetchStub.firstCall.args[1].headers.Foo).eql("Bar");
});
it("should drop custom content-type header for multipart body", () => {
http.request("/", {
headers: { "Content-Type": "application/foo" },
body: new FormData(),
});
expect(fetchStub.firstCall.args[1].headers["Content-Type"]).to.be
.undefined;
});
});
describe("Request CORS mode", () => {
let fetchStub: sinon.SinonStub;
it("should use default CORS mode", () => {
const http = new HTTP(events);
fetchStub = sandbox
.stub(http as any, "fetchFunc")
.returns(fakeServerResponse(200, {}, {}));
http.request("/");
expect(fetchStub.firstCall.args[1].mode).eql("cors");
});
it("should use configured custom CORS mode", () => {
const http = new HTTP(events, { requestMode: "no-cors" });
fetchStub = sandbox
.stub(http as any, "fetchFunc")
.returns(fakeServerResponse(200, {}, {}));
http.request("/");
expect(fetchStub.firstCall.args[1].mode).eql("no-cors");
});
});
describe("Succesful request", () => {
beforeEach(() => {
sandbox
.stub(http as any, "fetchFunc")
.returns(fakeServerResponse(200, { a: 1 }, { b: 2 }));
});
it("should resolve with HTTP status", async () => {
const { status } = await http.request("/");
status.should.equal(200);
});
it("should resolve with JSON body", async () => {
const { json } = await http.request("/");
(json as { a: number }).should.deep.equal({ a: 1 });
});
it("should resolve with headers", async () => {
const { headers } = await http.request("/");
headers.get("b")!.should.equal("2");
});
});
describe("Request timeout", () => {
beforeEach(() => {
sandbox.stub(http as any, "fetchFunc").returns(
new Promise((resolve) => {
setTimeout(resolve, 20000);
})
);
});
it("should timeout the request", async () => {
await expectAsyncError(
() => http.request("/"),
undefined,
NetworkTimeoutError
);
});
it("should show request properties in error", async () => {
await expectAsyncError(
() =>
http.request("/", {
mode: "cors",
headers: {
Authorization: "XXX",
"User-agent": "mocha-test",
},
}),
'Timeout while trying to access / with {"mode":"cors","headers":{"accept":"application/json","authorization":"**** (suppressed)","content-type":"application/json","user-agent":"mocha-test"}}'
);
});
});
describe("No content response", () => {
it("should resolve with null JSON if Content-Length header is missing", async () => {
sandbox
.stub(http as any, "fetchFunc")
.returns(fakeServerResponse(200, null, {}));
const { json } = await http.request("/");
expect(json).to.be.null;
});
});
describe("Malformed JSON response", () => {
it("should reject with an appropriate message", async () => {
sandbox.stub(http as any, "fetchFunc").returns(
Promise.resolve({
status: 200,
headers: {
get(name: string) {
if (name !== "Alert") {
return "fake";
}
},
},
text() {
return Promise.resolve("an example of invalid JSON");
},
})
);
await expectAsyncError(
() => http.request("/"),
/Response from server unparseable/,
UnparseableResponseError
);
});
});
describe("Business error responses", () => {
it("should reject on status code > 400", async () => {
sandbox.stub(http as any, "fetchFunc").returns(
fakeServerResponse(400, {
code: 400,
details: [
{
description: "data is missing",
location: "body",
name: "data",
},
],
errno: 107,
error: "Invalid parameters",
message: "data is missing",
})
);
await expectAsyncError(
() => http.request("/"),
/HTTP 400 Invalid parameters: Invalid request parameter \(data is missing\)/,
ServerResponse
);
});
it("should expose JSON error bodies", async () => {
const errorBody = {
code: 400,
details: [
{
description: "data is missing",
location: "body",
name: "data",
},
],
errno: 107,
error: "Invalid parameters",
message: "data is missing",
};
sandbox
.stub(http as any, "fetchFunc")
.returns(fakeServerResponse(400, errorBody));
const error = await expectAsyncError(
() => http.request("/"),
undefined,
ServerResponse
);
error.should.have.deep.property("data", errorBody);
});
it("should reject on status code > 400 even with empty body", async () => {
sandbox.stub(http as any, "fetchFunc").resolves({
status: 400,
statusText: "Cake Is A Lie",
headers: {
get(name: string) {
if (name === "Content-Length") {
return 0;
}
},
},
text() {
return Promise.resolve("");
},
});
await expectAsyncError(
() => http.request("/"),
/HTTP 400 Cake Is A Lie$/,
ServerResponse
);
});
});
describe("Deprecation header", () => {
const eolObject = {
code: "soft-eol",
url: "http://eos-url",
message: "This service will soon be decommissioned",
};
let consoleWarnStub: Stub<typeof console.warn>;
let eventsEmitStub: Stub<Emitter["emit"]> | null;
beforeEach(() => {
consoleWarnStub = sandbox.stub(console, "warn");
eventsEmitStub = events ? sandbox.stub(events, "emit") : null;
});
it("should handle deprecation header", async () => {
sandbox
.stub(http as any, "fetchFunc")
.returns(
fakeServerResponse(
200,
{},
{ Alert: JSON.stringify(eolObject) }
)
);
await http.request("/");
sinon.assert.calledOnce(consoleWarnStub);
sinon.assert.calledWithExactly(
consoleWarnStub,
eolObject.message,
eolObject.url
);
});
it("should handle deprecation header parse error", async () => {
sandbox
.stub(http as any, "fetchFunc")
.returns(fakeServerResponse(200, {}, { Alert: "dafuq" }));
await http.request("/");
sinon.assert.calledOnce(consoleWarnStub);
sinon.assert.calledWithExactly(
consoleWarnStub,
"Unable to parse Alert header message",
"dafuq"
);
});
it("should emit a deprecated event on Alert header", async () => {
sandbox
.stub(http as any, "fetchFunc")
.returns(
fakeServerResponse(
200,
{},
{ Alert: JSON.stringify(eolObject) }
)
);
await http.request("/");
if (events && eventsEmitStub) {
expect(eventsEmitStub.firstCall.args[0]).eql("deprecated");
expect(eventsEmitStub.firstCall.args[1]).eql(eolObject);
}
});
});
describe("Backoff header handling", () => {
let eventsEmitStub: Stub<Emitter["emit"]> | null;
beforeEach(() => {
// Make Date#getTime always returning 1000000, for predictability
sandbox.stub(Date.prototype, "getTime").returns(1000 * 1000);
eventsEmitStub = events ? sandbox.stub(events, "emit") : null;
});
it("should emit a backoff event on set Backoff header", async () => {
sandbox
.stub(http as any, "fetchFunc")
.returns(fakeServerResponse(200, {}, { Backoff: "1000" }));
await http.request("/");
if (events && eventsEmitStub) {
expect(eventsEmitStub.firstCall.args[0]).eql("backoff");
expect(eventsEmitStub.firstCall.args[1]).eql(2000000);
}
});
it("should emit a backoff event even on error responses", async () => {
sandbox
.stub(http as any, "fetchFunc")
.returns(fakeServerResponse(503, {}, { Backoff: "1000" }));
try {
await http.request("/");
} catch (err) {}
if (events && eventsEmitStub) {
expect(eventsEmitStub.firstCall.args[0]).eql("backoff");
expect(eventsEmitStub.firstCall.args[1]).eql(2000000);
}
});
it("should emit a backoff event on missing Backoff header", async () => {
sandbox
.stub(http as any, "fetchFunc")
.returns(fakeServerResponse(200, {}, {}));
await http.request("/");
if (events && eventsEmitStub) {
expect(eventsEmitStub.firstCall.args[0]).eql("backoff");
expect(eventsEmitStub.firstCall.args[1]).eql(0);
}
});
});
describe("Retry-After header handling", () => {
let eventsEmitStub: Stub<Emitter["emit"]> | null;
describe("Event", () => {
beforeEach(() => {
// Make Date#getTime always returning 1000000, for predictability
sandbox.stub(Date.prototype, "getTime").returns(1000 * 1000);
eventsEmitStub = events ? sandbox.stub(events, "emit") : null;
});
it("should emit a retry-after event when Retry-After is set", async () => {
sandbox
.stub(http as any, "fetchFunc")
.returns(
fakeServerResponse(200, {}, { "Retry-After": "1000" })
);
await http.request("/", {}, { retry: 0 });
if (events && eventsEmitStub) {
expect(eventsEmitStub.lastCall.args[0]).eql("retry-after");
expect(eventsEmitStub.lastCall.args[1]).eql(2000000);
}
});
});
describe("Retry loop", () => {
let fetch: sinon.SinonStub;
beforeEach(() => {
fetch = sandbox.stub(http as any, "fetchFunc");
});
it("should not retry the request by default", async () => {
fetch.returns(
fakeServerResponse(503, {}, { "Retry-After": "1" })
);
await expectAsyncError(() => http.request("/"), /HTTP 503/);
});
it("should retry the request if specified", async () => {
const success = { success: true };
fetch
.onCall(0)
.returns(fakeServerResponse(503, {}, { "Retry-After": "1" }));
fetch.onCall(1).returns(fakeServerResponse(200, success));
const { json } = await http.request("/", {}, { retry: 1 });
(json as { success: boolean }).should.deep.equal(success);
});
it("should error when retries are exhausted", async () => {
fetch
.onCall(0)
.returns(fakeServerResponse(503, {}, { "Retry-After": "1" }));
fetch
.onCall(1)
.returns(fakeServerResponse(503, {}, { "Retry-After": "1" }));
fetch
.onCall(2)
.returns(fakeServerResponse(503, {}, { "Retry-After": "1" }));
await expectAsyncError(
() => http.request("/", {}, { retry: 2 }),
/HTTP 503/
);
});
});
});
});
});
}
runSuite("with EventEmitter", () => new EventEmitter());
runSuite("with mitt", () => mitt());
runSuite("without EventEmitter");
}); | the_stack |
import { KubernetesObject } from "kpt-functions";
import * as apiCoreV1 from "./io.k8s.api.core.v1";
import * as apisMetaV1 from "./io.k8s.apimachinery.pkg.apis.meta.v1";
import * as pkgUtilIntstr from "./io.k8s.apimachinery.pkg.util.intstr";
// AllowedCSIDriver represents a single inline CSI Driver that is allowed to be used.
export class AllowedCSIDriver {
// Name is the registered name of the CSI driver
public name: string;
constructor(desc: AllowedCSIDriver) {
this.name = desc.name;
}
}
// AllowedFlexVolume represents a single Flexvolume that is allowed to be used. Deprecated: use AllowedFlexVolume from policy API Group instead.
export class AllowedFlexVolume {
// driver is the name of the Flexvolume driver.
public driver: string;
constructor(desc: AllowedFlexVolume) {
this.driver = desc.driver;
}
}
// AllowedHostPath defines the host volume conditions that will be enabled by a policy for pods to use. It requires the path prefix to be defined. Deprecated: use AllowedHostPath from policy API Group instead.
export class AllowedHostPath {
// pathPrefix is the path prefix that the host volume must match. It does not support `*`. Trailing slashes are trimmed when validating the path prefix with a host path.
//
// Examples: `/foo` would allow `/foo`, `/foo/` and `/foo/bar` `/foo` would not allow `/food` or `/etc/foo`
public pathPrefix?: string;
// when set to true, will allow host volumes matching the pathPrefix only if all volume mounts are readOnly.
public readOnly?: boolean;
}
// DEPRECATED - This group version of DaemonSet is deprecated by apps/v1beta2/DaemonSet. See the release notes for more information. DaemonSet represents the configuration of a daemon set.
export class DaemonSet implements KubernetesObject {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
public metadata: apisMetaV1.ObjectMeta;
// The desired behavior of this daemon set. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
public spec?: DaemonSetSpec;
// The current status of this daemon set. This data may be out of date by some window of time. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
public status?: DaemonSetStatus;
constructor(desc: DaemonSet.Interface) {
this.apiVersion = DaemonSet.apiVersion;
this.kind = DaemonSet.kind;
this.metadata = desc.metadata;
this.spec = desc.spec;
this.status = desc.status;
}
}
export function isDaemonSet(o: any): o is DaemonSet {
return (
o && o.apiVersion === DaemonSet.apiVersion && o.kind === DaemonSet.kind
);
}
export namespace DaemonSet {
export const apiVersion = "extensions/v1beta1";
export const group = "extensions";
export const version = "v1beta1";
export const kind = "DaemonSet";
// named constructs a DaemonSet with metadata.name set to name.
export function named(name: string): DaemonSet {
return new DaemonSet({ metadata: { name } });
}
// DEPRECATED - This group version of DaemonSet is deprecated by apps/v1beta2/DaemonSet. See the release notes for more information. DaemonSet represents the configuration of a daemon set.
export interface Interface {
// Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
metadata: apisMetaV1.ObjectMeta;
// The desired behavior of this daemon set. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
spec?: DaemonSetSpec;
// The current status of this daemon set. This data may be out of date by some window of time. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
status?: DaemonSetStatus;
}
}
// DaemonSetCondition describes the state of a DaemonSet at a certain point.
export class DaemonSetCondition {
// Last time the condition transitioned from one status to another.
public lastTransitionTime?: apisMetaV1.Time;
// A human readable message indicating details about the transition.
public message?: string;
// The reason for the condition's last transition.
public reason?: string;
// Status of the condition, one of True, False, Unknown.
public status: string;
// Type of DaemonSet condition.
public type: string;
constructor(desc: DaemonSetCondition) {
this.lastTransitionTime = desc.lastTransitionTime;
this.message = desc.message;
this.reason = desc.reason;
this.status = desc.status;
this.type = desc.type;
}
}
// DaemonSetList is a collection of daemon sets.
export class DaemonSetList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// A list of daemon sets.
public items: DaemonSet[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
public metadata?: apisMetaV1.ListMeta;
constructor(desc: DaemonSetList) {
this.apiVersion = DaemonSetList.apiVersion;
this.items = desc.items.map(i => new DaemonSet(i));
this.kind = DaemonSetList.kind;
this.metadata = desc.metadata;
}
}
export function isDaemonSetList(o: any): o is DaemonSetList {
return (
o &&
o.apiVersion === DaemonSetList.apiVersion &&
o.kind === DaemonSetList.kind
);
}
export namespace DaemonSetList {
export const apiVersion = "extensions/v1beta1";
export const group = "extensions";
export const version = "v1beta1";
export const kind = "DaemonSetList";
// DaemonSetList is a collection of daemon sets.
export interface Interface {
// A list of daemon sets.
items: DaemonSet[];
// Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
metadata?: apisMetaV1.ListMeta;
}
}
// DaemonSetSpec is the specification of a daemon set.
export class DaemonSetSpec {
// The minimum number of seconds for which a newly created DaemonSet pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready).
public minReadySeconds?: number;
// The number of old history to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. Defaults to 10.
public revisionHistoryLimit?: number;
// A label query over pods that are managed by the daemon set. Must match in order to be controlled. If empty, defaulted to labels on Pod template. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors
public selector?: apisMetaV1.LabelSelector;
// An object that describes the pod that will be created. The DaemonSet will create exactly one copy of this pod on every node that matches the template's node selector (or on every node if no node selector is specified). More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#pod-template
public template: apiCoreV1.PodTemplateSpec;
// DEPRECATED. A sequence number representing a specific generation of the template. Populated by the system. It can be set only during the creation.
public templateGeneration?: number;
// An update strategy to replace existing DaemonSet pods with new pods.
public updateStrategy?: DaemonSetUpdateStrategy;
constructor(desc: DaemonSetSpec) {
this.minReadySeconds = desc.minReadySeconds;
this.revisionHistoryLimit = desc.revisionHistoryLimit;
this.selector = desc.selector;
this.template = desc.template;
this.templateGeneration = desc.templateGeneration;
this.updateStrategy = desc.updateStrategy;
}
}
// DaemonSetStatus represents the current status of a daemon set.
export class DaemonSetStatus {
// Count of hash collisions for the DaemonSet. The DaemonSet controller uses this field as a collision avoidance mechanism when it needs to create the name for the newest ControllerRevision.
public collisionCount?: number;
// Represents the latest available observations of a DaemonSet's current state.
public conditions?: DaemonSetCondition[];
// The number of nodes that are running at least 1 daemon pod and are supposed to run the daemon pod. More info: https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/
public currentNumberScheduled: number;
// The total number of nodes that should be running the daemon pod (including nodes correctly running the daemon pod). More info: https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/
public desiredNumberScheduled: number;
// The number of nodes that should be running the daemon pod and have one or more of the daemon pod running and available (ready for at least spec.minReadySeconds)
public numberAvailable?: number;
// The number of nodes that are running the daemon pod, but are not supposed to run the daemon pod. More info: https://kubernetes.io/docs/concepts/workloads/controllers/daemonset/
public numberMisscheduled: number;
// The number of nodes that should be running the daemon pod and have one or more of the daemon pod running and ready.
public numberReady: number;
// The number of nodes that should be running the daemon pod and have none of the daemon pod running and available (ready for at least spec.minReadySeconds)
public numberUnavailable?: number;
// The most recent generation observed by the daemon set controller.
public observedGeneration?: number;
// The total number of nodes that are running updated daemon pod
public updatedNumberScheduled?: number;
constructor(desc: DaemonSetStatus) {
this.collisionCount = desc.collisionCount;
this.conditions = desc.conditions;
this.currentNumberScheduled = desc.currentNumberScheduled;
this.desiredNumberScheduled = desc.desiredNumberScheduled;
this.numberAvailable = desc.numberAvailable;
this.numberMisscheduled = desc.numberMisscheduled;
this.numberReady = desc.numberReady;
this.numberUnavailable = desc.numberUnavailable;
this.observedGeneration = desc.observedGeneration;
this.updatedNumberScheduled = desc.updatedNumberScheduled;
}
}
export class DaemonSetUpdateStrategy {
// Rolling update config params. Present only if type = "RollingUpdate".
public rollingUpdate?: RollingUpdateDaemonSet;
// Type of daemon set update. Can be "RollingUpdate" or "OnDelete". Default is OnDelete.
public type?: string;
}
// DEPRECATED - This group version of Deployment is deprecated by apps/v1beta2/Deployment. See the release notes for more information. Deployment enables declarative updates for Pods and ReplicaSets.
export class Deployment implements KubernetesObject {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard object metadata.
public metadata: apisMetaV1.ObjectMeta;
// Specification of the desired behavior of the Deployment.
public spec?: DeploymentSpec;
// Most recently observed status of the Deployment.
public status?: DeploymentStatus;
constructor(desc: Deployment.Interface) {
this.apiVersion = Deployment.apiVersion;
this.kind = Deployment.kind;
this.metadata = desc.metadata;
this.spec = desc.spec;
this.status = desc.status;
}
}
export function isDeployment(o: any): o is Deployment {
return (
o && o.apiVersion === Deployment.apiVersion && o.kind === Deployment.kind
);
}
export namespace Deployment {
export const apiVersion = "extensions/v1beta1";
export const group = "extensions";
export const version = "v1beta1";
export const kind = "Deployment";
// named constructs a Deployment with metadata.name set to name.
export function named(name: string): Deployment {
return new Deployment({ metadata: { name } });
}
// DEPRECATED - This group version of Deployment is deprecated by apps/v1beta2/Deployment. See the release notes for more information. Deployment enables declarative updates for Pods and ReplicaSets.
export interface Interface {
// Standard object metadata.
metadata: apisMetaV1.ObjectMeta;
// Specification of the desired behavior of the Deployment.
spec?: DeploymentSpec;
// Most recently observed status of the Deployment.
status?: DeploymentStatus;
}
}
// DeploymentCondition describes the state of a deployment at a certain point.
export class DeploymentCondition {
// Last time the condition transitioned from one status to another.
public lastTransitionTime?: apisMetaV1.Time;
// The last time this condition was updated.
public lastUpdateTime?: apisMetaV1.Time;
// A human readable message indicating details about the transition.
public message?: string;
// The reason for the condition's last transition.
public reason?: string;
// Status of the condition, one of True, False, Unknown.
public status: string;
// Type of deployment condition.
public type: string;
constructor(desc: DeploymentCondition) {
this.lastTransitionTime = desc.lastTransitionTime;
this.lastUpdateTime = desc.lastUpdateTime;
this.message = desc.message;
this.reason = desc.reason;
this.status = desc.status;
this.type = desc.type;
}
}
// DeploymentList is a list of Deployments.
export class DeploymentList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Items is the list of Deployments.
public items: Deployment[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard list metadata.
public metadata?: apisMetaV1.ListMeta;
constructor(desc: DeploymentList) {
this.apiVersion = DeploymentList.apiVersion;
this.items = desc.items.map(i => new Deployment(i));
this.kind = DeploymentList.kind;
this.metadata = desc.metadata;
}
}
export function isDeploymentList(o: any): o is DeploymentList {
return (
o &&
o.apiVersion === DeploymentList.apiVersion &&
o.kind === DeploymentList.kind
);
}
export namespace DeploymentList {
export const apiVersion = "extensions/v1beta1";
export const group = "extensions";
export const version = "v1beta1";
export const kind = "DeploymentList";
// DeploymentList is a list of Deployments.
export interface Interface {
// Items is the list of Deployments.
items: Deployment[];
// Standard list metadata.
metadata?: apisMetaV1.ListMeta;
}
}
// DEPRECATED. DeploymentRollback stores the information required to rollback a deployment.
export class DeploymentRollback {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Required: This must match the Name of a deployment.
public name: string;
// The config of this deployment rollback.
public rollbackTo: RollbackConfig;
// The annotations to be updated to a deployment
public updatedAnnotations?: { [key: string]: string };
constructor(desc: DeploymentRollback) {
this.apiVersion = DeploymentRollback.apiVersion;
this.kind = DeploymentRollback.kind;
this.name = desc.name;
this.rollbackTo = desc.rollbackTo;
this.updatedAnnotations = desc.updatedAnnotations;
}
}
export function isDeploymentRollback(o: any): o is DeploymentRollback {
return (
o &&
o.apiVersion === DeploymentRollback.apiVersion &&
o.kind === DeploymentRollback.kind
);
}
export namespace DeploymentRollback {
export const apiVersion = "extensions/v1beta1";
export const group = "extensions";
export const version = "v1beta1";
export const kind = "DeploymentRollback";
// DEPRECATED. DeploymentRollback stores the information required to rollback a deployment.
export interface Interface {
// Required: This must match the Name of a deployment.
name: string;
// The config of this deployment rollback.
rollbackTo: RollbackConfig;
// The annotations to be updated to a deployment
updatedAnnotations?: { [key: string]: string };
}
}
// DeploymentSpec is the specification of the desired behavior of the Deployment.
export class DeploymentSpec {
// Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready)
public minReadySeconds?: number;
// Indicates that the deployment is paused and will not be processed by the deployment controller.
public paused?: boolean;
// The maximum time in seconds for a deployment to make progress before it is considered to be failed. The deployment controller will continue to process failed deployments and a condition with a ProgressDeadlineExceeded reason will be surfaced in the deployment status. Note that progress will not be estimated during the time a deployment is paused. This is set to the max value of int32 (i.e. 2147483647) by default, which means "no deadline".
public progressDeadlineSeconds?: number;
// Number of desired pods. This is a pointer to distinguish between explicit zero and not specified. Defaults to 1.
public replicas?: number;
// The number of old ReplicaSets to retain to allow rollback. This is a pointer to distinguish between explicit zero and not specified. This is set to the max value of int32 (i.e. 2147483647) by default, which means "retaining all old RelicaSets".
public revisionHistoryLimit?: number;
// DEPRECATED. The config this deployment is rolling back to. Will be cleared after rollback is done.
public rollbackTo?: RollbackConfig;
// Label selector for pods. Existing ReplicaSets whose pods are selected by this will be the ones affected by this deployment.
public selector?: apisMetaV1.LabelSelector;
// The deployment strategy to use to replace existing pods with new ones.
public strategy?: DeploymentStrategy;
// Template describes the pods that will be created.
public template: apiCoreV1.PodTemplateSpec;
constructor(desc: DeploymentSpec) {
this.minReadySeconds = desc.minReadySeconds;
this.paused = desc.paused;
this.progressDeadlineSeconds = desc.progressDeadlineSeconds;
this.replicas = desc.replicas;
this.revisionHistoryLimit = desc.revisionHistoryLimit;
this.rollbackTo = desc.rollbackTo;
this.selector = desc.selector;
this.strategy = desc.strategy;
this.template = desc.template;
}
}
// DeploymentStatus is the most recently observed status of the Deployment.
export class DeploymentStatus {
// Total number of available pods (ready for at least minReadySeconds) targeted by this deployment.
public availableReplicas?: number;
// Count of hash collisions for the Deployment. The Deployment controller uses this field as a collision avoidance mechanism when it needs to create the name for the newest ReplicaSet.
public collisionCount?: number;
// Represents the latest available observations of a deployment's current state.
public conditions?: DeploymentCondition[];
// The generation observed by the deployment controller.
public observedGeneration?: number;
// Total number of ready pods targeted by this deployment.
public readyReplicas?: number;
// Total number of non-terminated pods targeted by this deployment (their labels match the selector).
public replicas?: number;
// Total number of unavailable pods targeted by this deployment. This is the total number of pods that are still required for the deployment to have 100% available capacity. They may either be pods that are running but not yet available or pods that still have not been created.
public unavailableReplicas?: number;
// Total number of non-terminated pods targeted by this deployment that have the desired template spec.
public updatedReplicas?: number;
}
// DeploymentStrategy describes how to replace existing pods with new ones.
export class DeploymentStrategy {
// Rolling update config params. Present only if DeploymentStrategyType = RollingUpdate.
public rollingUpdate?: RollingUpdateDeployment;
// Type of deployment. Can be "Recreate" or "RollingUpdate". Default is RollingUpdate.
public type?: string;
}
// FSGroupStrategyOptions defines the strategy type and options used to create the strategy. Deprecated: use FSGroupStrategyOptions from policy API Group instead.
export class FSGroupStrategyOptions {
// ranges are the allowed ranges of fs groups. If you would like to force a single fs group then supply a single range with the same start and end. Required for MustRunAs.
public ranges?: IDRange[];
// rule is the strategy that will dictate what FSGroup is used in the SecurityContext.
public rule?: string;
}
// HTTPIngressPath associates a path regex with a backend. Incoming urls matching the path are forwarded to the backend.
export class HTTPIngressPath {
// Backend defines the referenced service endpoint to which the traffic will be forwarded to.
public backend: IngressBackend;
// Path is an extended POSIX regex as defined by IEEE Std 1003.1, (i.e this follows the egrep/unix syntax, not the perl syntax) matched against the path of an incoming request. Currently it can contain characters disallowed from the conventional "path" part of a URL as defined by RFC 3986. Paths must begin with a '/'. If unspecified, the path defaults to a catch all sending traffic to the backend.
public path?: string;
constructor(desc: HTTPIngressPath) {
this.backend = desc.backend;
this.path = desc.path;
}
}
// HTTPIngressRuleValue is a list of http selectors pointing to backends. In the example: http://<host>/<path>?<searchpart> -> backend where where parts of the url correspond to RFC 3986, this resource will be used to match against everything after the last '/' and before the first '?' or '#'.
export class HTTPIngressRuleValue {
// A collection of paths that map requests to backends.
public paths: HTTPIngressPath[];
constructor(desc: HTTPIngressRuleValue) {
this.paths = desc.paths;
}
}
// HostPortRange defines a range of host ports that will be enabled by a policy for pods to use. It requires both the start and end to be defined. Deprecated: use HostPortRange from policy API Group instead.
export class HostPortRange {
// max is the end of the range, inclusive.
public max: number;
// min is the start of the range, inclusive.
public min: number;
constructor(desc: HostPortRange) {
this.max = desc.max;
this.min = desc.min;
}
}
// IDRange provides a min/max of an allowed range of IDs. Deprecated: use IDRange from policy API Group instead.
export class IDRange {
// max is the end of the range, inclusive.
public max: number;
// min is the start of the range, inclusive.
public min: number;
constructor(desc: IDRange) {
this.max = desc.max;
this.min = desc.min;
}
}
// DEPRECATED 1.9 - This group version of IPBlock is deprecated by networking/v1/IPBlock. IPBlock describes a particular CIDR (Ex. "192.168.1.1/24") that is allowed to the pods matched by a NetworkPolicySpec's podSelector. The except entry describes CIDRs that should not be included within this rule.
export class IPBlock {
// CIDR is a string representing the IP Block Valid examples are "192.168.1.1/24"
public cidr: string;
// Except is a slice of CIDRs that should not be included within an IP Block Valid examples are "192.168.1.1/24" Except values will be rejected if they are outside the CIDR range
public except?: string[];
constructor(desc: IPBlock) {
this.cidr = desc.cidr;
this.except = desc.except;
}
}
// Ingress is a collection of rules that allow inbound connections to reach the endpoints defined by a backend. An Ingress can be configured to give services externally-reachable urls, load balance traffic, terminate SSL, offer name based virtual hosting etc. DEPRECATED - This group version of Ingress is deprecated by networking.k8s.io/v1beta1 Ingress. See the release notes for more information.
export class Ingress implements KubernetesObject {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
public metadata: apisMetaV1.ObjectMeta;
// Spec is the desired state of the Ingress. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
public spec?: IngressSpec;
// Status is the current state of the Ingress. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
public status?: IngressStatus;
constructor(desc: Ingress.Interface) {
this.apiVersion = Ingress.apiVersion;
this.kind = Ingress.kind;
this.metadata = desc.metadata;
this.spec = desc.spec;
this.status = desc.status;
}
}
export function isIngress(o: any): o is Ingress {
return o && o.apiVersion === Ingress.apiVersion && o.kind === Ingress.kind;
}
export namespace Ingress {
export const apiVersion = "extensions/v1beta1";
export const group = "extensions";
export const version = "v1beta1";
export const kind = "Ingress";
// named constructs a Ingress with metadata.name set to name.
export function named(name: string): Ingress {
return new Ingress({ metadata: { name } });
}
// Ingress is a collection of rules that allow inbound connections to reach the endpoints defined by a backend. An Ingress can be configured to give services externally-reachable urls, load balance traffic, terminate SSL, offer name based virtual hosting etc. DEPRECATED - This group version of Ingress is deprecated by networking.k8s.io/v1beta1 Ingress. See the release notes for more information.
export interface Interface {
// Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
metadata: apisMetaV1.ObjectMeta;
// Spec is the desired state of the Ingress. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
spec?: IngressSpec;
// Status is the current state of the Ingress. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
status?: IngressStatus;
}
}
// IngressBackend describes all endpoints for a given service and port.
export class IngressBackend {
// Specifies the name of the referenced service.
public serviceName: string;
// Specifies the port of the referenced service.
public servicePort: pkgUtilIntstr.IntOrString;
constructor(desc: IngressBackend) {
this.serviceName = desc.serviceName;
this.servicePort = desc.servicePort;
}
}
// IngressList is a collection of Ingress.
export class IngressList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Items is the list of Ingress.
public items: Ingress[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
public metadata?: apisMetaV1.ListMeta;
constructor(desc: IngressList) {
this.apiVersion = IngressList.apiVersion;
this.items = desc.items.map(i => new Ingress(i));
this.kind = IngressList.kind;
this.metadata = desc.metadata;
}
}
export function isIngressList(o: any): o is IngressList {
return (
o && o.apiVersion === IngressList.apiVersion && o.kind === IngressList.kind
);
}
export namespace IngressList {
export const apiVersion = "extensions/v1beta1";
export const group = "extensions";
export const version = "v1beta1";
export const kind = "IngressList";
// IngressList is a collection of Ingress.
export interface Interface {
// Items is the list of Ingress.
items: Ingress[];
// Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
metadata?: apisMetaV1.ListMeta;
}
}
// IngressRule represents the rules mapping the paths under a specified host to the related backend services. Incoming requests are first evaluated for a host match, then routed to the backend associated with the matching IngressRuleValue.
export class IngressRule {
// Host is the fully qualified domain name of a network host, as defined by RFC 3986. Note the following deviations from the "host" part of the URI as defined in the RFC: 1. IPs are not allowed. Currently an IngressRuleValue can only apply to the
// IP in the Spec of the parent Ingress.
// 2. The `:` delimiter is not respected because ports are not allowed.
// Currently the port of an Ingress is implicitly :80 for http and
// :443 for https.
// Both these may change in the future. Incoming requests are matched against the host before the IngressRuleValue. If the host is unspecified, the Ingress routes all traffic based on the specified IngressRuleValue.
public host?: string;
public http?: HTTPIngressRuleValue;
}
// IngressSpec describes the Ingress the user wishes to exist.
export class IngressSpec {
// A default backend capable of servicing requests that don't match any rule. At least one of 'backend' or 'rules' must be specified. This field is optional to allow the loadbalancer controller or defaulting logic to specify a global default.
public backend?: IngressBackend;
// A list of host rules used to configure the Ingress. If unspecified, or no rule matches, all traffic is sent to the default backend.
public rules?: IngressRule[];
// TLS configuration. Currently the Ingress only supports a single TLS port, 443. If multiple members of this list specify different hosts, they will be multiplexed on the same port according to the hostname specified through the SNI TLS extension, if the ingress controller fulfilling the ingress supports SNI.
public tls?: IngressTLS[];
}
// IngressStatus describe the current state of the Ingress.
export class IngressStatus {
// LoadBalancer contains the current status of the load-balancer.
public loadBalancer?: apiCoreV1.LoadBalancerStatus;
}
// IngressTLS describes the transport layer security associated with an Ingress.
export class IngressTLS {
// Hosts are a list of hosts included in the TLS certificate. The values in this list must match the name/s used in the tlsSecret. Defaults to the wildcard host setting for the loadbalancer controller fulfilling this Ingress, if left unspecified.
public hosts?: string[];
// SecretName is the name of the secret used to terminate SSL traffic on 443. Field is left optional to allow SSL routing based on SNI hostname alone. If the SNI host in a listener conflicts with the "Host" header field used by an IngressRule, the SNI host is used for termination and value of the Host header is used for routing.
public secretName?: string;
}
// DEPRECATED 1.9 - This group version of NetworkPolicy is deprecated by networking/v1/NetworkPolicy. NetworkPolicy describes what network traffic is allowed for a set of Pods
export class NetworkPolicy implements KubernetesObject {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
public metadata: apisMetaV1.ObjectMeta;
// Specification of the desired behavior for this NetworkPolicy.
public spec?: NetworkPolicySpec;
constructor(desc: NetworkPolicy.Interface) {
this.apiVersion = NetworkPolicy.apiVersion;
this.kind = NetworkPolicy.kind;
this.metadata = desc.metadata;
this.spec = desc.spec;
}
}
export function isNetworkPolicy(o: any): o is NetworkPolicy {
return (
o &&
o.apiVersion === NetworkPolicy.apiVersion &&
o.kind === NetworkPolicy.kind
);
}
export namespace NetworkPolicy {
export const apiVersion = "extensions/v1beta1";
export const group = "extensions";
export const version = "v1beta1";
export const kind = "NetworkPolicy";
// named constructs a NetworkPolicy with metadata.name set to name.
export function named(name: string): NetworkPolicy {
return new NetworkPolicy({ metadata: { name } });
}
// DEPRECATED 1.9 - This group version of NetworkPolicy is deprecated by networking/v1/NetworkPolicy. NetworkPolicy describes what network traffic is allowed for a set of Pods
export interface Interface {
// Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
metadata: apisMetaV1.ObjectMeta;
// Specification of the desired behavior for this NetworkPolicy.
spec?: NetworkPolicySpec;
}
}
// DEPRECATED 1.9 - This group version of NetworkPolicyEgressRule is deprecated by networking/v1/NetworkPolicyEgressRule. NetworkPolicyEgressRule describes a particular set of traffic that is allowed out of pods matched by a NetworkPolicySpec's podSelector. The traffic must match both ports and to. This type is beta-level in 1.8
export class NetworkPolicyEgressRule {
// List of destination ports for outgoing traffic. Each item in this list is combined using a logical OR. If this field is empty or missing, this rule matches all ports (traffic not restricted by port). If this field is present and contains at least one item, then this rule allows traffic only if the traffic matches at least one port in the list.
public ports?: NetworkPolicyPort[];
// List of destinations for outgoing traffic of pods selected for this rule. Items in this list are combined using a logical OR operation. If this field is empty or missing, this rule matches all destinations (traffic not restricted by destination). If this field is present and contains at least one item, this rule allows traffic only if the traffic matches at least one item in the to list.
public to?: NetworkPolicyPeer[];
}
// DEPRECATED 1.9 - This group version of NetworkPolicyIngressRule is deprecated by networking/v1/NetworkPolicyIngressRule. This NetworkPolicyIngressRule matches traffic if and only if the traffic matches both ports AND from.
export class NetworkPolicyIngressRule {
// List of sources which should be able to access the pods selected for this rule. Items in this list are combined using a logical OR operation. If this field is empty or missing, this rule matches all sources (traffic not restricted by source). If this field is present and contains at least on item, this rule allows traffic only if the traffic matches at least one item in the from list.
public from?: NetworkPolicyPeer[];
// List of ports which should be made accessible on the pods selected for this rule. Each item in this list is combined using a logical OR. If this field is empty or missing, this rule matches all ports (traffic not restricted by port). If this field is present and contains at least one item, then this rule allows traffic only if the traffic matches at least one port in the list.
public ports?: NetworkPolicyPort[];
}
// DEPRECATED 1.9 - This group version of NetworkPolicyList is deprecated by networking/v1/NetworkPolicyList. Network Policy List is a list of NetworkPolicy objects.
export class NetworkPolicyList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Items is a list of schema objects.
public items: NetworkPolicy[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
public metadata?: apisMetaV1.ListMeta;
constructor(desc: NetworkPolicyList) {
this.apiVersion = NetworkPolicyList.apiVersion;
this.items = desc.items.map(i => new NetworkPolicy(i));
this.kind = NetworkPolicyList.kind;
this.metadata = desc.metadata;
}
}
export function isNetworkPolicyList(o: any): o is NetworkPolicyList {
return (
o &&
o.apiVersion === NetworkPolicyList.apiVersion &&
o.kind === NetworkPolicyList.kind
);
}
export namespace NetworkPolicyList {
export const apiVersion = "extensions/v1beta1";
export const group = "extensions";
export const version = "v1beta1";
export const kind = "NetworkPolicyList";
// DEPRECATED 1.9 - This group version of NetworkPolicyList is deprecated by networking/v1/NetworkPolicyList. Network Policy List is a list of NetworkPolicy objects.
export interface Interface {
// Items is a list of schema objects.
items: NetworkPolicy[];
// Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
metadata?: apisMetaV1.ListMeta;
}
}
// DEPRECATED 1.9 - This group version of NetworkPolicyPeer is deprecated by networking/v1/NetworkPolicyPeer.
export class NetworkPolicyPeer {
// IPBlock defines policy on a particular IPBlock. If this field is set then neither of the other fields can be.
public ipBlock?: IPBlock;
// Selects Namespaces using cluster-scoped labels. This field follows standard label selector semantics; if present but empty, it selects all namespaces.
//
// If PodSelector is also set, then the NetworkPolicyPeer as a whole selects the Pods matching PodSelector in the Namespaces selected by NamespaceSelector. Otherwise it selects all Pods in the Namespaces selected by NamespaceSelector.
public namespaceSelector?: apisMetaV1.LabelSelector;
// This is a label selector which selects Pods. This field follows standard label selector semantics; if present but empty, it selects all pods.
//
// If NamespaceSelector is also set, then the NetworkPolicyPeer as a whole selects the Pods matching PodSelector in the Namespaces selected by NamespaceSelector. Otherwise it selects the Pods matching PodSelector in the policy's own Namespace.
public podSelector?: apisMetaV1.LabelSelector;
}
// DEPRECATED 1.9 - This group version of NetworkPolicyPort is deprecated by networking/v1/NetworkPolicyPort.
export class NetworkPolicyPort {
// If specified, the port on the given protocol. This can either be a numerical or named port on a pod. If this field is not provided, this matches all port names and numbers. If present, only traffic on the specified protocol AND port will be matched.
public port?: pkgUtilIntstr.IntOrString;
// Optional. The protocol (TCP, UDP, or SCTP) which traffic must match. If not specified, this field defaults to TCP.
public protocol?: string;
}
// DEPRECATED 1.9 - This group version of NetworkPolicySpec is deprecated by networking/v1/NetworkPolicySpec.
export class NetworkPolicySpec {
// List of egress rules to be applied to the selected pods. Outgoing traffic is allowed if there are no NetworkPolicies selecting the pod (and cluster policy otherwise allows the traffic), OR if the traffic matches at least one egress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy limits all outgoing traffic (and serves solely to ensure that the pods it selects are isolated by default). This field is beta-level in 1.8
public egress?: NetworkPolicyEgressRule[];
// List of ingress rules to be applied to the selected pods. Traffic is allowed to a pod if there are no NetworkPolicies selecting the pod OR if the traffic source is the pod's local node, OR if the traffic matches at least one ingress rule across all of the NetworkPolicy objects whose podSelector matches the pod. If this field is empty then this NetworkPolicy does not allow any traffic (and serves solely to ensure that the pods it selects are isolated by default).
public ingress?: NetworkPolicyIngressRule[];
// Selects the pods to which this NetworkPolicy object applies. The array of ingress rules is applied to any pods selected by this field. Multiple network policies can select the same set of pods. In this case, the ingress rules for each are combined additively. This field is NOT optional and follows standard label selector semantics. An empty podSelector matches all pods in this namespace.
public podSelector: apisMetaV1.LabelSelector;
// List of rule types that the NetworkPolicy relates to. Valid options are "Ingress", "Egress", or "Ingress,Egress". If this field is not specified, it will default based on the existence of Ingress or Egress rules; policies that contain an Egress section are assumed to affect Egress, and all policies (whether or not they contain an Ingress section) are assumed to affect Ingress. If you want to write an egress-only policy, you must explicitly specify policyTypes [ "Egress" ]. Likewise, if you want to write a policy that specifies that no egress is allowed, you must specify a policyTypes value that include "Egress" (since such a policy would not include an Egress section and would otherwise default to just [ "Ingress" ]). This field is beta-level in 1.8
public policyTypes?: string[];
constructor(desc: NetworkPolicySpec) {
this.egress = desc.egress;
this.ingress = desc.ingress;
this.podSelector = desc.podSelector;
this.policyTypes = desc.policyTypes;
}
}
// PodSecurityPolicy governs the ability to make requests that affect the Security Context that will be applied to a pod and container. Deprecated: use PodSecurityPolicy from policy API Group instead.
export class PodSecurityPolicy implements KubernetesObject {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
public metadata: apisMetaV1.ObjectMeta;
// spec defines the policy enforced.
public spec?: PodSecurityPolicySpec;
constructor(desc: PodSecurityPolicy.Interface) {
this.apiVersion = PodSecurityPolicy.apiVersion;
this.kind = PodSecurityPolicy.kind;
this.metadata = desc.metadata;
this.spec = desc.spec;
}
}
export function isPodSecurityPolicy(o: any): o is PodSecurityPolicy {
return (
o &&
o.apiVersion === PodSecurityPolicy.apiVersion &&
o.kind === PodSecurityPolicy.kind
);
}
export namespace PodSecurityPolicy {
export const apiVersion = "extensions/v1beta1";
export const group = "extensions";
export const version = "v1beta1";
export const kind = "PodSecurityPolicy";
// named constructs a PodSecurityPolicy with metadata.name set to name.
export function named(name: string): PodSecurityPolicy {
return new PodSecurityPolicy({ metadata: { name } });
}
// PodSecurityPolicy governs the ability to make requests that affect the Security Context that will be applied to a pod and container. Deprecated: use PodSecurityPolicy from policy API Group instead.
export interface Interface {
// Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
metadata: apisMetaV1.ObjectMeta;
// spec defines the policy enforced.
spec?: PodSecurityPolicySpec;
}
}
// PodSecurityPolicyList is a list of PodSecurityPolicy objects. Deprecated: use PodSecurityPolicyList from policy API Group instead.
export class PodSecurityPolicyList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// items is a list of schema objects.
public items: PodSecurityPolicy[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
public metadata?: apisMetaV1.ListMeta;
constructor(desc: PodSecurityPolicyList) {
this.apiVersion = PodSecurityPolicyList.apiVersion;
this.items = desc.items.map(i => new PodSecurityPolicy(i));
this.kind = PodSecurityPolicyList.kind;
this.metadata = desc.metadata;
}
}
export function isPodSecurityPolicyList(o: any): o is PodSecurityPolicyList {
return (
o &&
o.apiVersion === PodSecurityPolicyList.apiVersion &&
o.kind === PodSecurityPolicyList.kind
);
}
export namespace PodSecurityPolicyList {
export const apiVersion = "extensions/v1beta1";
export const group = "extensions";
export const version = "v1beta1";
export const kind = "PodSecurityPolicyList";
// PodSecurityPolicyList is a list of PodSecurityPolicy objects. Deprecated: use PodSecurityPolicyList from policy API Group instead.
export interface Interface {
// items is a list of schema objects.
items: PodSecurityPolicy[];
// Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
metadata?: apisMetaV1.ListMeta;
}
}
// PodSecurityPolicySpec defines the policy enforced. Deprecated: use PodSecurityPolicySpec from policy API Group instead.
export class PodSecurityPolicySpec {
// allowPrivilegeEscalation determines if a pod can request to allow privilege escalation. If unspecified, defaults to true.
public allowPrivilegeEscalation?: boolean;
// AllowedCSIDrivers is a whitelist of inline CSI drivers that must be explicitly set to be embedded within a pod spec. An empty value means no CSI drivers can run inline within a pod spec.
public allowedCSIDrivers?: AllowedCSIDriver[];
// allowedCapabilities is a list of capabilities that can be requested to add to the container. Capabilities in this field may be added at the pod author's discretion. You must not list a capability in both allowedCapabilities and requiredDropCapabilities.
public allowedCapabilities?: string[];
// allowedFlexVolumes is a whitelist of allowed Flexvolumes. Empty or nil indicates that all Flexvolumes may be used. This parameter is effective only when the usage of the Flexvolumes is allowed in the "volumes" field.
public allowedFlexVolumes?: AllowedFlexVolume[];
// allowedHostPaths is a white list of allowed host paths. Empty indicates that all host paths may be used.
public allowedHostPaths?: AllowedHostPath[];
// AllowedProcMountTypes is a whitelist of allowed ProcMountTypes. Empty or nil indicates that only the DefaultProcMountType may be used. This requires the ProcMountType feature flag to be enabled.
public allowedProcMountTypes?: string[];
// allowedUnsafeSysctls is a list of explicitly allowed unsafe sysctls, defaults to none. Each entry is either a plain sysctl name or ends in "*" in which case it is considered as a prefix of allowed sysctls. Single * means all unsafe sysctls are allowed. Kubelet has to whitelist all allowed unsafe sysctls explicitly to avoid rejection.
//
// Examples: e.g. "foo/*" allows "foo/bar", "foo/baz", etc. e.g. "foo.*" allows "foo.bar", "foo.baz", etc.
public allowedUnsafeSysctls?: string[];
// defaultAddCapabilities is the default set of capabilities that will be added to the container unless the pod spec specifically drops the capability. You may not list a capability in both defaultAddCapabilities and requiredDropCapabilities. Capabilities added here are implicitly allowed, and need not be included in the allowedCapabilities list.
public defaultAddCapabilities?: string[];
// defaultAllowPrivilegeEscalation controls the default setting for whether a process can gain more privileges than its parent process.
public defaultAllowPrivilegeEscalation?: boolean;
// forbiddenSysctls is a list of explicitly forbidden sysctls, defaults to none. Each entry is either a plain sysctl name or ends in "*" in which case it is considered as a prefix of forbidden sysctls. Single * means all sysctls are forbidden.
//
// Examples: e.g. "foo/*" forbids "foo/bar", "foo/baz", etc. e.g. "foo.*" forbids "foo.bar", "foo.baz", etc.
public forbiddenSysctls?: string[];
// fsGroup is the strategy that will dictate what fs group is used by the SecurityContext.
public fsGroup: FSGroupStrategyOptions;
// hostIPC determines if the policy allows the use of HostIPC in the pod spec.
public hostIPC?: boolean;
// hostNetwork determines if the policy allows the use of HostNetwork in the pod spec.
public hostNetwork?: boolean;
// hostPID determines if the policy allows the use of HostPID in the pod spec.
public hostPID?: boolean;
// hostPorts determines which host port ranges are allowed to be exposed.
public hostPorts?: HostPortRange[];
// privileged determines if a pod can request to be run as privileged.
public privileged?: boolean;
// readOnlyRootFilesystem when set to true will force containers to run with a read only root file system. If the container specifically requests to run with a non-read only root file system the PSP should deny the pod. If set to false the container may run with a read only root file system if it wishes but it will not be forced to.
public readOnlyRootFilesystem?: boolean;
// requiredDropCapabilities are the capabilities that will be dropped from the container. These are required to be dropped and cannot be added.
public requiredDropCapabilities?: string[];
// RunAsGroup is the strategy that will dictate the allowable RunAsGroup values that may be set. If this field is omitted, the pod's RunAsGroup can take any value. This field requires the RunAsGroup feature gate to be enabled.
public runAsGroup?: RunAsGroupStrategyOptions;
// runAsUser is the strategy that will dictate the allowable RunAsUser values that may be set.
public runAsUser: RunAsUserStrategyOptions;
// seLinux is the strategy that will dictate the allowable labels that may be set.
public seLinux: SELinuxStrategyOptions;
// supplementalGroups is the strategy that will dictate what supplemental groups are used by the SecurityContext.
public supplementalGroups: SupplementalGroupsStrategyOptions;
// volumes is a white list of allowed volume plugins. Empty indicates that no volumes may be used. To allow all volumes you may use '*'.
public volumes?: string[];
constructor(desc: PodSecurityPolicySpec) {
this.allowPrivilegeEscalation = desc.allowPrivilegeEscalation;
this.allowedCSIDrivers = desc.allowedCSIDrivers;
this.allowedCapabilities = desc.allowedCapabilities;
this.allowedFlexVolumes = desc.allowedFlexVolumes;
this.allowedHostPaths = desc.allowedHostPaths;
this.allowedProcMountTypes = desc.allowedProcMountTypes;
this.allowedUnsafeSysctls = desc.allowedUnsafeSysctls;
this.defaultAddCapabilities = desc.defaultAddCapabilities;
this.defaultAllowPrivilegeEscalation = desc.defaultAllowPrivilegeEscalation;
this.forbiddenSysctls = desc.forbiddenSysctls;
this.fsGroup = desc.fsGroup;
this.hostIPC = desc.hostIPC;
this.hostNetwork = desc.hostNetwork;
this.hostPID = desc.hostPID;
this.hostPorts = desc.hostPorts;
this.privileged = desc.privileged;
this.readOnlyRootFilesystem = desc.readOnlyRootFilesystem;
this.requiredDropCapabilities = desc.requiredDropCapabilities;
this.runAsGroup = desc.runAsGroup;
this.runAsUser = desc.runAsUser;
this.seLinux = desc.seLinux;
this.supplementalGroups = desc.supplementalGroups;
this.volumes = desc.volumes;
}
}
// DEPRECATED - This group version of ReplicaSet is deprecated by apps/v1beta2/ReplicaSet. See the release notes for more information. ReplicaSet ensures that a specified number of pod replicas are running at any given time.
export class ReplicaSet implements KubernetesObject {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// If the Labels of a ReplicaSet are empty, they are defaulted to be the same as the Pod(s) that the ReplicaSet manages. Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
public metadata: apisMetaV1.ObjectMeta;
// Spec defines the specification of the desired behavior of the ReplicaSet. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
public spec?: ReplicaSetSpec;
// Status is the most recently observed status of the ReplicaSet. This data may be out of date by some window of time. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
public status?: ReplicaSetStatus;
constructor(desc: ReplicaSet.Interface) {
this.apiVersion = ReplicaSet.apiVersion;
this.kind = ReplicaSet.kind;
this.metadata = desc.metadata;
this.spec = desc.spec;
this.status = desc.status;
}
}
export function isReplicaSet(o: any): o is ReplicaSet {
return (
o && o.apiVersion === ReplicaSet.apiVersion && o.kind === ReplicaSet.kind
);
}
export namespace ReplicaSet {
export const apiVersion = "extensions/v1beta1";
export const group = "extensions";
export const version = "v1beta1";
export const kind = "ReplicaSet";
// named constructs a ReplicaSet with metadata.name set to name.
export function named(name: string): ReplicaSet {
return new ReplicaSet({ metadata: { name } });
}
// DEPRECATED - This group version of ReplicaSet is deprecated by apps/v1beta2/ReplicaSet. See the release notes for more information. ReplicaSet ensures that a specified number of pod replicas are running at any given time.
export interface Interface {
// If the Labels of a ReplicaSet are empty, they are defaulted to be the same as the Pod(s) that the ReplicaSet manages. Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata
metadata: apisMetaV1.ObjectMeta;
// Spec defines the specification of the desired behavior of the ReplicaSet. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
spec?: ReplicaSetSpec;
// Status is the most recently observed status of the ReplicaSet. This data may be out of date by some window of time. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status
status?: ReplicaSetStatus;
}
}
// ReplicaSetCondition describes the state of a replica set at a certain point.
export class ReplicaSetCondition {
// The last time the condition transitioned from one status to another.
public lastTransitionTime?: apisMetaV1.Time;
// A human readable message indicating details about the transition.
public message?: string;
// The reason for the condition's last transition.
public reason?: string;
// Status of the condition, one of True, False, Unknown.
public status: string;
// Type of replica set condition.
public type: string;
constructor(desc: ReplicaSetCondition) {
this.lastTransitionTime = desc.lastTransitionTime;
this.message = desc.message;
this.reason = desc.reason;
this.status = desc.status;
this.type = desc.type;
}
}
// ReplicaSetList is a collection of ReplicaSets.
export class ReplicaSetList {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// List of ReplicaSets. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller
public items: ReplicaSet[];
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
public metadata?: apisMetaV1.ListMeta;
constructor(desc: ReplicaSetList) {
this.apiVersion = ReplicaSetList.apiVersion;
this.items = desc.items.map(i => new ReplicaSet(i));
this.kind = ReplicaSetList.kind;
this.metadata = desc.metadata;
}
}
export function isReplicaSetList(o: any): o is ReplicaSetList {
return (
o &&
o.apiVersion === ReplicaSetList.apiVersion &&
o.kind === ReplicaSetList.kind
);
}
export namespace ReplicaSetList {
export const apiVersion = "extensions/v1beta1";
export const group = "extensions";
export const version = "v1beta1";
export const kind = "ReplicaSetList";
// ReplicaSetList is a collection of ReplicaSets.
export interface Interface {
// List of ReplicaSets. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller
items: ReplicaSet[];
// Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
metadata?: apisMetaV1.ListMeta;
}
}
// ReplicaSetSpec is the specification of a ReplicaSet.
export class ReplicaSetSpec {
// Minimum number of seconds for which a newly created pod should be ready without any of its container crashing, for it to be considered available. Defaults to 0 (pod will be considered available as soon as it is ready)
public minReadySeconds?: number;
// Replicas is the number of desired replicas. This is a pointer to distinguish between explicit zero and unspecified. Defaults to 1. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller/#what-is-a-replicationcontroller
public replicas?: number;
// Selector is a label query over pods that should match the replica count. If the selector is empty, it is defaulted to the labels present on the pod template. Label keys and values that must match in order to be controlled by this replica set. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors
public selector?: apisMetaV1.LabelSelector;
// Template is the object that describes the pod that will be created if insufficient replicas are detected. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller#pod-template
public template?: apiCoreV1.PodTemplateSpec;
}
// ReplicaSetStatus represents the current status of a ReplicaSet.
export class ReplicaSetStatus {
// The number of available replicas (ready for at least minReadySeconds) for this replica set.
public availableReplicas?: number;
// Represents the latest available observations of a replica set's current state.
public conditions?: ReplicaSetCondition[];
// The number of pods that have labels matching the labels of the pod template of the replicaset.
public fullyLabeledReplicas?: number;
// ObservedGeneration reflects the generation of the most recently observed ReplicaSet.
public observedGeneration?: number;
// The number of ready replicas for this replica set.
public readyReplicas?: number;
// Replicas is the most recently oberved number of replicas. More info: https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller/#what-is-a-replicationcontroller
public replicas: number;
constructor(desc: ReplicaSetStatus) {
this.availableReplicas = desc.availableReplicas;
this.conditions = desc.conditions;
this.fullyLabeledReplicas = desc.fullyLabeledReplicas;
this.observedGeneration = desc.observedGeneration;
this.readyReplicas = desc.readyReplicas;
this.replicas = desc.replicas;
}
}
// DEPRECATED.
export class RollbackConfig {
// The revision to rollback to. If set to 0, rollback to the last revision.
public revision?: number;
}
// Spec to control the desired behavior of daemon set rolling update.
export class RollingUpdateDaemonSet {
// The maximum number of DaemonSet pods that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of total number of DaemonSet pods at the start of the update (ex: 10%). Absolute number is calculated from percentage by rounding up. This cannot be 0. Default value is 1. Example: when this is set to 30%, at most 30% of the total number of nodes that should be running the daemon pod (i.e. status.desiredNumberScheduled) can have their pods stopped for an update at any given time. The update starts by stopping at most 30% of those DaemonSet pods and then brings up new DaemonSet pods in their place. Once the new pods are available, it then proceeds onto other DaemonSet pods, thus ensuring that at least 70% of original number of DaemonSet pods are available at all times during the update.
public maxUnavailable?: pkgUtilIntstr.IntOrString;
}
// Spec to control the desired behavior of rolling update.
export class RollingUpdateDeployment {
// The maximum number of pods that can be scheduled above the desired number of pods. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). This can not be 0 if MaxUnavailable is 0. Absolute number is calculated from percentage by rounding up. By default, a value of 1 is used. Example: when this is set to 30%, the new RC can be scaled up immediately when the rolling update starts, such that the total number of old and new pods do not exceed 130% of desired pods. Once old pods have been killed, new RC can be scaled up further, ensuring that total number of pods running at any time during the update is at most 130% of desired pods.
public maxSurge?: pkgUtilIntstr.IntOrString;
// The maximum number of pods that can be unavailable during the update. Value can be an absolute number (ex: 5) or a percentage of desired pods (ex: 10%). Absolute number is calculated from percentage by rounding down. This can not be 0 if MaxSurge is 0. By default, a fixed value of 1 is used. Example: when this is set to 30%, the old RC can be scaled down to 70% of desired pods immediately when the rolling update starts. Once new pods are ready, old RC can be scaled down further, followed by scaling up the new RC, ensuring that the total number of pods available at all times during the update is at least 70% of desired pods.
public maxUnavailable?: pkgUtilIntstr.IntOrString;
}
// RunAsGroupStrategyOptions defines the strategy type and any options used to create the strategy. Deprecated: use RunAsGroupStrategyOptions from policy API Group instead.
export class RunAsGroupStrategyOptions {
// ranges are the allowed ranges of gids that may be used. If you would like to force a single gid then supply a single range with the same start and end. Required for MustRunAs.
public ranges?: IDRange[];
// rule is the strategy that will dictate the allowable RunAsGroup values that may be set.
public rule: string;
constructor(desc: RunAsGroupStrategyOptions) {
this.ranges = desc.ranges;
this.rule = desc.rule;
}
}
// RunAsUserStrategyOptions defines the strategy type and any options used to create the strategy. Deprecated: use RunAsUserStrategyOptions from policy API Group instead.
export class RunAsUserStrategyOptions {
// ranges are the allowed ranges of uids that may be used. If you would like to force a single uid then supply a single range with the same start and end. Required for MustRunAs.
public ranges?: IDRange[];
// rule is the strategy that will dictate the allowable RunAsUser values that may be set.
public rule: string;
constructor(desc: RunAsUserStrategyOptions) {
this.ranges = desc.ranges;
this.rule = desc.rule;
}
}
// SELinuxStrategyOptions defines the strategy type and any options used to create the strategy. Deprecated: use SELinuxStrategyOptions from policy API Group instead.
export class SELinuxStrategyOptions {
// rule is the strategy that will dictate the allowable labels that may be set.
public rule: string;
// seLinuxOptions required to run as; required for MustRunAs More info: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
public seLinuxOptions?: apiCoreV1.SELinuxOptions;
constructor(desc: SELinuxStrategyOptions) {
this.rule = desc.rule;
this.seLinuxOptions = desc.seLinuxOptions;
}
}
// represents a scaling request for a resource.
export class Scale implements KubernetesObject {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
public apiVersion: string;
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds
public kind: string;
// Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata.
public metadata: apisMetaV1.ObjectMeta;
// defines the behavior of the scale. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status.
public spec?: ScaleSpec;
// current status of the scale. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status. Read-only.
public status?: ScaleStatus;
constructor(desc: Scale.Interface) {
this.apiVersion = Scale.apiVersion;
this.kind = Scale.kind;
this.metadata = desc.metadata;
this.spec = desc.spec;
this.status = desc.status;
}
}
export function isScale(o: any): o is Scale {
return o && o.apiVersion === Scale.apiVersion && o.kind === Scale.kind;
}
export namespace Scale {
export const apiVersion = "extensions/v1beta1";
export const group = "extensions";
export const version = "v1beta1";
export const kind = "Scale";
// named constructs a Scale with metadata.name set to name.
export function named(name: string): Scale {
return new Scale({ metadata: { name } });
}
// represents a scaling request for a resource.
export interface Interface {
// Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata.
metadata: apisMetaV1.ObjectMeta;
// defines the behavior of the scale. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status.
spec?: ScaleSpec;
// current status of the scale. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status. Read-only.
status?: ScaleStatus;
}
}
// describes the attributes of a scale subresource
export class ScaleSpec {
// desired number of instances for the scaled object.
public replicas?: number;
}
// represents the current status of a scale subresource.
export class ScaleStatus {
// actual number of observed instances of the scaled object.
public replicas: number;
// label query over pods that should match the replicas count. More info: http://kubernetes.io/docs/user-guide/labels#label-selectors
public selector?: { [key: string]: string };
// label selector for pods that should match the replicas count. This is a serializated version of both map-based and more expressive set-based selectors. This is done to avoid introspection in the clients. The string will be in the same format as the query-param syntax. If the target type only supports map-based selectors, both this field and map-based selector field are populated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors
public targetSelector?: string;
constructor(desc: ScaleStatus) {
this.replicas = desc.replicas;
this.selector = desc.selector;
this.targetSelector = desc.targetSelector;
}
}
// SupplementalGroupsStrategyOptions defines the strategy type and options used to create the strategy. Deprecated: use SupplementalGroupsStrategyOptions from policy API Group instead.
export class SupplementalGroupsStrategyOptions {
// ranges are the allowed ranges of supplemental groups. If you would like to force a single supplemental group then supply a single range with the same start and end. Required for MustRunAs.
public ranges?: IDRange[];
// rule is the strategy that will dictate what supplemental groups is used in the SecurityContext.
public rule?: string;
} | the_stack |
import {
autorun,
booleanAttribute,
attribute,
numberAttribute,
untrack,
element,
stringAttribute,
reactive,
} from '@lume/element'
import {html} from '@lume/element/dist/html.js'
import {Scene as ThreeScene} from 'three/src/scenes/Scene.js'
import {PerspectiveCamera as ThreePerspectiveCamera} from 'three/src/cameras/PerspectiveCamera.js'
// import {AmbientLight} from 'three/src/lights/AmbientLight.js'
import {Color} from 'three/src/math/Color.js'
import {Fog} from 'three/src/scenes/Fog.js'
import {FogExp2} from 'three/src/scenes/FogExp2.js'
import {WebglRendererThree, ShadowMapTypeString} from '../renderers/WebglRendererThree.js'
import {Css3dRendererThree} from '../renderers/Css3dRendererThree.js'
import {ImperativeBase} from './ImperativeBase.js'
import {defer} from './utils.js'
import {isDisposable} from '../utils/three.js'
import {Motor} from './Motor.js'
import {autoDefineElements} from '../LumeConfig.js'
import type {TColor} from '../utils/three.js'
import type {PerspectiveCamera} from '../cameras/PerspectiveCamera.js'
import type {XYZValuesObject} from '../xyz-values/XYZValues.js'
import type {SizeableAttributes} from './Sizeable.js'
import type {Node} from './Node.js'
export type SceneAttributes =
// Don't expost TransformableAttributes here for now (although they exist). What should modifying those on a Scene do?
| SizeableAttributes
| 'shadowmapType'
| 'vr'
| 'webgl'
| 'enableCss'
| 'swapLayers'
| 'backgroundColor'
| 'backgroundOpacity'
| 'background'
| 'equirectangularBackground'
| 'environment'
| 'fogMode'
| 'fogNear'
| 'fogFar'
| 'fogColor'
| 'fogDensity'
| 'physicallyCorrectLights'
| 'cameraNear'
| 'cameraFar'
| 'perspective'
/**
* @class Scene -
*
* Element: `<lume-scene>`
*
* This is the backing class for `<lume-scene>` elements. All
* [`Node`](/api/core/Node.md) elements must be inside of a `<lume-scene>` element. A `Scene`
* establishes a visual area in a web application where a 3D scene will be
* rendered.
*
* A Scene has some properties that apply to the scene as a whole and will have
* an effect on all LUME elements in the scene. For example, `fog-mode` defines fog
* rendering that changes the color of all WebGL objects in the scene to make them
* have the appearance of being obscured by a haze.
*
* ## Example
*
* The following example shows how to begin making a LUME scene within an HTML
* file. To learn more about how to get started, see the [install guide](../../guide/install.md).
*
* <div id="example1"></div>
*
* <script type="application/javascript">
* new Vue({
* el: '#example1',
* template: '<live-code :template="code" mode="html>iframe" :debounce="200" />',
* data: { code: sceneExample() },
* })
* </script>
*
* @extends ImperativeBase
*/
// TODO @element jsdoc tag
@element('lume-scene', autoDefineElements)
export class Scene extends ImperativeBase {
/**
* @property {true} isScene -
*
* *readonly*
*
* Always `true` for things that are or inherit from `Scene`.
*/
// TODO @readonly jsdoc tag
override readonly isScene = true
/**
* @property {boolean} enableCss -
*
* *attribute*
*
* Default: `true`
*
* When `true`, CSS transforms are applied
* to all LUME elements. This allows regular HTML content placed inside LUME
* elements to be positioned in the scene's 3D space. Set this to `false` if
* you will render only WebGL content and do not need to listen to
* pointer events on the elements; the elements will have the CSS property
* `display:none`. When rendering only WebGL content, leaving this enabled is useful for
* debugging, as the elements are placed in the same locations in 3D
* space as the WebGL graphics, and thus devtools will highlight the
* positions of WebGL objects on the screen when hovering on them in the element inspector.
*/
// TODO @attribute jsdoc tag
// TODO @default jsdoc tag
@booleanAttribute(true) enableCss = true
/**
* @property {boolean} webgl -
*
* *attribute*
*
* Default: `false`
*
* When `true`, enables WebGL rendering.
*/
@booleanAttribute(false) webgl = false
/**
* @property {boolean} swapLayers -
*
* *attribute*
*
* Default: `false`
*
* This is only useful when both CSS and
* WebGL render modes are enabled. When `true`, the CSS layer will render on
* top of the WebGL layer instead of below.
*/
@booleanAttribute(false) swapLayers = false
/**
* @property {'pcf' | 'pcfsoft' | 'basic'} shadowmapType -
*
* *attribute*
*
* Default: `'basic'`
*
* Specifies the type of shadows to use. The value can be 'pcf', 'pcfsoft',
* or 'basic'. See the "Shadow Types" section in Three.js [Renderer
* Constants](https://threejs.org/docs/#api/en/constants/Renderer) for
* descriptions.
*
* Applies only if `webgl` is `true`.
*/
@attribute shadowmapType: ShadowMapTypeString | null = 'basic'
/**
* @property {boolean} vr -
*
* *attribute*
*
* Default: `false`
*
* When `true`, enables VR capabilities. The user
* can click a button to enter VR mode.
*
* Applies only if `webgl` is `true`. CSS content can not be natively
* rendered with the browser's WebXR. There exist some tricks to import CSS
* rendering in the form of an SVG image to use as a texture in WebGL and
* hence WebXR, but it has some limitations including low performance if
* animating CSS features; we may add this feature later.
*/
@booleanAttribute(false) vr = false
/**
* @property {Color | string | number | null} backgroundColor -
*
* *attribute*
*
* Default: `'white'`
*
* The color of the
* scene's background when WebGL rendering is enabled. If the
* [`background`](#background) property is also set, then `backgroundColor` is
* ignored. Make sure to set `backgroundOpacity` to a higher value than the
* default of `0` or the color won't be visible and instead only the color of
* whatever is behind the `<lume-scene>` will be visible.
*
* Applies only if `webgl` is `true`.
*/
@attribute backgroundColor: TColor | null = new Color('white')
/**
* @property {number} backgroundOpacity -
*
* *attribute*
*
* Default: `0`
*
* A number between `0` and `1` that
* defines the opacity (opposite of transparency) of the `backgroundColor`
* when WebGL is enabled. If the value is less than 1, it means that any DOM
* contend behind the `<lume-scene>` element will be visible. A value of `0`
* means the background is fully transparent. This is ignored if the
* [`background`](#background) property is set.
*
* Applies only if `webgl` is `true`.
*/
@numberAttribute(0) backgroundOpacity = 0
/**
* @property {string | null} background -
*
* *attribute*
*
* Default: `null`
*
* Set an image as the scene's
* background. If the image is an [equirectangular environment
* map](https://coeleveld.com/spherical-equirectangular-environment-textures-and-hdri), then set the value of
* [`equirectangularBackground`](#equirectangularbackground) to `true`, otherwise the image
* will be treated as a 2D background image. The value should be a path
* to a jpeg, jpg, or png. Other types not supported yet. This value
* takes priority over the [`backgroundColor`](#backgroundcolor) and
* [`backgroundOpacity`](#backgroundopacity) properties; those properties will be
* ignored. Any transparent parts of the image will be rendered
* as color white.
*
* Applies only if `webgl` is `true`.
*/
@attribute background: string | null = null
/**
* @property {string} equirectangularBackground -
*
* *attribute*
*
* Default: `false`
*
* If the `background`
* is equirectangular, set this to `true` so use it like a skybox,
* otherwise the image will be used as a regular 2D background image.
*
* Applies only if `webgl` is `true`.
*/
@booleanAttribute(false) equirectangularBackground = false
/**
* @property {string | null} environment -
*
* *attribute*
*
* Default: `null`
*
* The environment can be a path to a
* jpeg, jpg, or png (other format not yet supported). It is assumed to
* be an equirectangular image used for env maps for things like
* reflections on metallic objects in the scene.
*
* Applies only if `webgl` is `true`.
*/
@attribute environment: string | null = null
/**
* @property {'none' | 'linear' | 'expo2'} fogMode -
*
* *attribute*
*
* Default: `'none'`
*
* The fog mode to render
* the scene with.
*
* A value of `'none'` means no fog.
*
* A value of `'linear'`
* makes a fog that gets reduces visibility of objects with distance from the camera.
* The `fogNear` and `fogFar` properties specify the distance from the camera when
* linear fog starts being applied to objects and when objects are fully invisible,
* respectively. Any objects before the near point will be fully visible, and any
* objects beyond the far point will be fully invisible.
*
* A value of `'expo2'` creates an exponential squared fog. Unlike linear fog, the near
* and far cannot be configured. Instead, expo2 fog is more realistic, and only it's
* overall "physical" density can be configured with the `fogDensity` property.
*
* Applies only if `webgl` is `true`.
*/
@stringAttribute('none') fogMode: FogMode = 'none'
/**
* @property {number} fogNear -
*
* *attribute*
*
* Default: `0`
*
* When `fogMode` is `'linear'`, this controls
* the distance from the camera where fog starts to appear and objects start
* to be less visible.
*
* Applies only if `webgl` is `true`.
*/
@numberAttribute(0) fogNear = 0
/**
* @property {number} fogFar -
*
* *attribute*
*
* Default: `1000`
*
* When `fogMode` is `'linear'`, this controls
* the distance from the camera where fog reaches maximum density and
* objects are no longer visible.
*
* Applies only if `webgl` is `true`.
*/
@numberAttribute(1000) fogFar = 1000
/**
* @property {string} fogColor -
*
* *attribute*
*
* Default: `'gray'`
*
* If `fogMode` is not `'none'`, this
* configures the fog color. The value should be any valid CSS color string.
*
* You will want to change the value to match that of, or be similar to,
* your scene's `backgroundColor`.
*
* Applies only if `webgl` is `true`.
*/
@stringAttribute('gray') fogColor: string = 'gray'
/**
* @property {number} fogDensity -
*
* *attribute*
*
* Default: `0.0025`
*
* If `fogMode` is set to `'expo2'`, this
* configures the fog density.
*
* Applies only if `webgl` is `true`.
*/
@numberAttribute(0.0025) fogDensity = 0.0025
/**
* @property {boolean} physicallyCorrectLights -
*
* `attribute`
*
* Default: `false`
*
* Whether to use physically correct lighting mode or not. This affects only
* [`PointLight`](../lights/PointLight) <!-- and `SpotLight` --> elements
* <!-- ; `RectArea` lights do this automatically -->. See the [lights /
* physical example](https://threejs.org/examples/#webgl_lights_physical)
* from Three.js and "physicallyCorrectLights" in the Three.js manual's
* [Lights](https://threejs.org/manual/?q=lig#en/lights) doc.
*/
@booleanAttribute(false) physicallyCorrectLights = false
/**
* @property {number} cameraNear -
*
* *attribute*
*
* Default: `0.1`
*
* When not using a custom camera, this
* configures the distance from the default camera of a plane perpendicular
* to the camera's line of sight after which objects objects are visible. Anything between
* the plane and the camera will not be visible. This should be smaller than `cameraFar`. Also see `cameraFar`.
*
* Applies in both CSS and WebGL rendering. Note that the near and far
* values apply only to WebGL rendering and are otherwise infinitely small and
* infinitely big (respectively) when it comes to CSS rendering.
*/
@numberAttribute(0.1) cameraNear = 0.1
/**
* @property {number} cameraFar -
*
* *attribute*
*
* Default: `10000`
*
* When not using a custom camera, this
* configures the distance from the default camera of a plane perpendicular
* to the camera's line of sight before which objects are visible. Anything further than
* the plane will not be visible. This should be bigger than `cameraNear`. Also see `cameraNear`.
*
* Applies in both CSS and WebGL rendering. Note that the near and far
* values apply only to WebGL rendering and are otherwise infinitely small and
* infinitely big (respectively) when it comes to CSS rendering.
*/
@numberAttribute(10000) cameraFar = 10000
/**
* @property {number} perspective -
*
* *attribute*
*
* Default: `400`
*
* This property behaves just like CSS perspective
* when using CSS transforms, but also applies to LUME's WebGL rendering when using a scene's
* default camera. If using a custom camera (for example a `<lume-perspective-camera>` element) then this
* value does not (currently) have any effect.
*
* The value sets the default camera's Z position to the given value (relative to the world
* origin, 0,0,0). Note that the default camera points in the -z direction, therefore a value
* of 800 means the camera is at position 0,0,800 looking directly at the world origin
* at 0,0,0. Furthermore, based on the chosen value, the camera's aspect ratio and zoom
* will be adjusted such that if there were a plane positioned at 0,0,0, perpendicular
* to the camera's line of sight, and having the same dimensions as the scene's viewport
* in screen pixels, then the plane would fit perfectly in the view, and one unit on that
* plane would coincide with one pixel on the screen; essentially that plane would be lined
* up perfectly with the screen surface. This is the same meaning that CSS perspective has.
*
* Applies with both CSS and WebGL rendering.
*/
@numberAttribute(400)
set perspective(value) {
this.#perspective = value
this._updateCameraPerspective()
this._updateCameraProjection()
this.needsUpdate()
}
get perspective() {
return this.#perspective
}
#perspective = 400
/**
* @property {THREE.Camera} threeCamera -
*
* *readonly*
*
* The current active THREE.Camera being
* used by the scene. It will be a default camera if no camera was manually
* specified by a camera element such as `<lume-perspective-camera>`, in
* which case the scene's `perspective` property is used for configuring the
* default camera. If a manual camera element is set active with an
* `active` attribute, then this property will return the currently
* active THREE.Camera represented by the active camera element.
*
* Applies with both CSS and WebGL rendering.
*/
get threeCamera(): ThreePerspectiveCamera {
return this.__threeCamera
}
// this.#threeCamera holds the active camera. There can be many
// cameras in the scene tree, but the last one with active="true"
// will be the one referenced here.
// If there are no cameras in the tree, a virtual default camera is
// referenced here, who's perspective is that of the scene's
// perspective attribute.
__threeCamera!: ThreePerspectiveCamera
// This is toggled by ClipPlanesBehavior, not intended for direct use.
@reactive __localClipping = false
constructor() {
super()
// Used by the `scene` getter in ImperativeBase
// TODO set this in connectedCallback, unset in disconnectedCallback, so
// it has the same semantics as with Node (this.scene is not null when
// scene is connected and has webgl or css rendering turned on)
this._scene = this
// this.sizeMode and this.size have to be overriden here inside the
// constructor in TS 4. This is because class fields on a
// subclass are no longer allowed to be defined outside the
// constructor if a base class has the same properties already defined as
// accessors.
/**
* @property {XYZSizeModeValues} sizeMode -
*
* *override*, *attribute*
*
* Default: ['proportional', 'proportional', 'literal']
*
* This overrides the
* [`Sizeable.sizeMode`](/api/core/Sizeable.md#sizeMode) property to make the default values for the X and
* Y axes both "proportional".
*/
this.sizeMode.set('proportional', 'proportional', 'literal')
/**
* @property {XYZNonNegativeValues} size -
*
* *override*, *attribute*
*
* Default: [1, 1, 0]
*
* This overrides the [`Sizeable.size`](/api/core/Sizeable.md#size)
* property to make the default values for the X and Y axes both `1`.
*/
this.size.set(1, 1, 0)
// The scene should always render CSS properties (it needs to always
// be rendered or resized, for example, because it contains the
// WebGL canvas which also needs to be resized). Namely, we still
// want to apply size values to the scene so that it can size
// relative to it's parent container, or literally if size mode is
// "literal".
this._elementOperations.shouldRender = true
this._createDefaultCamera()
this._calcSize()
this.needsUpdate()
}
static override css = /*css*/ `
:host {
/*
* All items of the scene graph are hidden until they are mounted in
* a scene (this changes to display:block). 'display' gets toggled
* between "none" and "block" by ImperativeBase depending on if CSS
* rendering is enabled.
*/
display: none;
/*
A Scene is strict: it does not leak content, its rendering is not
affected by external layout, and its size is not affected by its
content. It is an absolutely contained drawing area.
*/
contain: size layout paint; /*fallback, TODO remove once Safari goers are caught up*/
contain: strict;
box-sizing: border-box;
position: static;
overflow: hidden;
top: 0;
left: 0;
/*
Defaults to [0.5,0.5,0.5] (the Z axis doesn't apply for DOM elements,
but will for 3D objects in WebGL.)
*/
transform-origin: 50% 50% 0; /* default */
transform-style: preserve-3d;
}
/* The purpose of this is to contain the position:absolute layers so they don't break out of the Scene layout. */
.container {
position: relative
}
.container,
.CSS3DLayer,
.MiscellaneousLayer,
.WebGLLayer,
.WebGLLayer > canvas {
margin: 0; padding: 0;
width: 100%; height: 100%;
display: block;
}
.CSS3DLayer,
.MiscellaneousLayer,
.WebGLLayer {
/* make sure all layers are stacked on top of each other */
position: absolute; top: 0; left: 0;
}
.CSS3DLayer {
transform-style: preserve-3d;
}
.container {
pointer-events: none;
}
.MiscellaneousLayer > * {
/* Allow children of the Misc layer to have pointer events. Needed for the WebXR button, for example */
pointer-events: auto;
}
/*
* This trick is needed in Firefox to remove pointer events from the
* transparent cameraElement from interfering with pointer events on the
* scene objects. We do not wish to interact with this element anyway, as
* it serves only for positioning the view.
*/
.cameraElement > * {
pointer-events: auto;
}
.vrButton {
color: black;
border-color: black;
}
`
// WebGLRendererThree appends its content into here.
_glLayer: HTMLDivElement | null = null
// CSS3DRendererThree appends its content into here.
_cssLayer: HTMLDivElement | null = null
// Miscellaneous layer. The "Enter VR/AR" button is placed here by Scene, for example.
_miscLayer: HTMLDivElement | null = null
override template = () => html`
<div class="container">
<div
ref=${(el: any) => (this._cssLayer = el)}
class="CSS3DLayer"
style=${() => (this.swapLayers ? 'z-index: 1' : '')}
>
${
/* WebGLRendererThree places the CSS3DRendererNested domElement
here, which contains a <slot> element that child elements of
a Scene are distributed into (rendered relative to).
*/ ''
}
</div>
<div ref=${(el: any) => (this._glLayer = el)} class="WebGLLayer">
${/* WebGLRendererThree places the Three.js <canvas> element here. */ ''}
</div>
<div ref=${(el: any) => (this._miscLayer = el)} class="MiscellaneousLayer">
${/* This layer is used by WebXR to insert UI like the Enter VR/AR button. */ ''}
<slot name="misc"></slot>
</div>
</div>
`
drawScene() {
this.#glRenderer && this.#glRenderer.drawScene(this)
this.#cssRenderer && this.#cssRenderer.drawScene(this)
}
override connectedCallback() {
super.connectedCallback()
this._stopFns.push(
autorun(() => {
if (this.webgl) this._triggerLoadGL()
else this._triggerUnloadGL()
this.needsUpdate()
}),
autorun(() => {
if (!this.webgl || !this.background) {
if (isDisposable(this.three.background)) this.three.background.dispose()
this.#glRenderer?.disableBackground(this)
this.needsUpdate()
return
}
if (this.background.match(/\.(jpg|jpeg|png)$/)) {
// Dispose each time we switch to a new one.
if (isDisposable(this.three.background)) this.three.background.dispose()
// destroy the previous one, if any.
this.#glRenderer!.disableBackground(this)
this.#glRenderer!.enableBackground(this, this.equirectangularBackground, texture => {
this.three.background = texture || null
this.needsUpdate()
// TODO emit background load event.
})
} else {
console.warn(
`<${this.tagName.toLowerCase()}> background attribute ignored, the given image type is not currently supported.`,
)
}
}),
autorun(() => {
if (!this.webgl || !this.environment) {
if (isDisposable(this.three.environment)) this.three.environment.dispose()
this.#glRenderer?.disableEnvironment(this)
this.needsUpdate()
return
}
if (this.environment.match(/\.(jpg|jpeg|png)$/)) {
// Dispose each time we switch to a new one.
if (isDisposable(this.three.environment)) this.three.environment.dispose()
// destroy the previous one, if any.
this.#glRenderer!.disableEnvironment(this)
this.#glRenderer!.enableEnvironment(this, texture => {
this.three.environment = texture
this.needsUpdate()
// TODO emit background load event.
})
} else {
console.warn(
`<${this.tagName.toLowerCase()}> environment attribute ignored, the given image type is not currently supported.`,
)
}
}),
autorun(() => {
if (this.enableCss) this._triggerLoadCSS()
else this._triggerUnloadCSS()
this.needsUpdate()
}),
autorun(() => {
this.sizeMode
this.#startOrStopParentSizeObservation()
}),
)
}
override disconnectedCallback() {
super.disconnectedCallback()
this.#stopParentSizeObservation()
}
static override observedAttributes = ['slot']
override attributeChangedCallback(name: string, oldV: string | null, newV: string | null) {
super.attributeChangedCallback!(name, oldV, newV)
if (name === 'slot') {
defer(() => {
throw new Error(
'Assigning a <lume-scene> to a slot is not currently supported and may not work as expected. Instead, wrap the <lume-scene> in another element like a <div>, then assign the wrapper to the slot.',
)
})
}
}
override makeThreeObject3d() {
return new ThreeScene()
}
override makeThreeCSSObject() {
return new ThreeScene()
}
/**
* @method traverseSceneGraph - This traverses the composed tree of LUME 3D
* elements (the scene graph) not including the scene node, starting from
* the scene's children, in pre-order. It skips non-LUME elements. The given
* callback will be called for each node in the traversal.
*
* This is similar to
* [`Node#traverseSceneGraph`](./Node.md#traversescenegraph) but traversal
* does not include the Scene that this is called on, because a Scene is not
* something that is rendered, but a container of things that are rendered.
*
* Example:
*
* ```js
* scene.traverseSceneGraph(node => {
* console.log(scene === node) // never true
* console.log(node instanceof LUME.Node) // true
* })
* ```
*
* @param {(node: Node) => void} visitor - A function called for each
* LUME node in the scene graph (the composed tree).
* @param {boolean} waitForUpgrade - Defaults to `false`. If `true`,
* the traversal will wait for custom elements to be defined (with
* customElements.whenDefined) before traversing to them.
* @returns {void | Promise<void>} - If `waitForUpgrade` is `false`,
* the traversal will complete synchronously, and the return value will be
* `undefined`. If `waitForUpgrade` is `true`, then traversal completes
* asynchronously once all custom elements are defined, and a Promise is
* returned so that it is possible to wait for the traversal to complete.
*/
override traverseSceneGraph(visitor: (node: Node) => void, waitForUpgrade = false): Promise<void> | void {
if (!waitForUpgrade) {
for (const child of this.composedLumeChildren) child.traverseSceneGraph(visitor, waitForUpgrade)
return
}
// if waitForUpgrade is true, we make a promise chain so that
// traversal order is still the same as when waitForUpgrade is false.
let promise: Promise<any> = Promise.resolve()
for (const child of this.composedLumeChildren) {
const isUpgraded = child.matches(':defined')
if (isUpgraded) {
promise = promise!.then(() => child.traverseSceneGraph(visitor, waitForUpgrade))
} else {
promise = promise!
.then(() => customElements.whenDefined(child.tagName.toLowerCase()))
.then(() => child.traverseSceneGraph(visitor, waitForUpgrade))
}
}
return promise
}
_createDefaultCamera() {
// Use untrack so this method is non-reactive.
untrack(() => {
const size = this.calculatedSize
// THREE-COORDS-TO-DOM-COORDS
// We apply Three perspective the same way as CSS3D perspective here.
// TODO CAMERA-DEFAULTS, get defaults from somewhere common.
// TODO the "far" arg will be auto-calculated to encompass the furthest objects (like CSS3D).
// TODO update with calculatedSize in autorun
this.__threeCamera = new ThreePerspectiveCamera(45, size.x / size.y || 1, 0.1, 10000)
this.__threeCamera.name = `${this.tagName}${this.id ? '#' + this.id : ''} DEFAULT CAMERA (webgl, ${
this.__threeCamera.type
})`
this.perspective = this.perspective
})
}
// TODO can this be moved to a render task like _calcSize should also be?
// It depends on size values.
_updateCameraPerspective() {
const perspective = this.#perspective
// This math is what sets the FOV of the default camera so that a
// viewport-sized plane will fit exactly within the view when it is
// positioned at the world origin, as described for in the
// `perspective` property's description.
// For more details: https://discourse.threejs.org/t/269/28
this.__threeCamera.fov = (180 * (2 * Math.atan(this.calculatedSize.y / 2 / perspective))) / Math.PI
this.__threeCamera.position.z = perspective
}
_updateCameraAspect() {
this.__threeCamera.aspect = this.calculatedSize.x / this.calculatedSize.y || 1
}
_updateCameraProjection() {
this.__threeCamera.updateProjectionMatrix()
}
// holds active cameras found in the DOM tree (if this is empty, it
// means no camera elements are in the DOM, but this.#threeCamera
// will still have a reference to the default camera that scenes
// are rendered with when no camera elements exist).
__activeCameras?: Set<PerspectiveCamera>
_addCamera(camera: PerspectiveCamera) {
if (!this.__activeCameras) this.__activeCameras = new Set()
this.__activeCameras.add(camera)
this.__setCamera(camera)
}
_removeCamera(camera: PerspectiveCamera) {
if (!this.__activeCameras) return
this.__activeCameras.delete(camera)
if (this.__activeCameras.size) {
// get the last camera in the Set
this.__activeCameras.forEach(c => (camera = c))
this.__setCamera(camera)
} else {
this.__activeCameras = undefined
this.__setCamera()
}
}
/**
* @property {{x: number, y: number, z: number}} parentSize
*
* `override` `reactive` `readonly`
*
* Overrides [`Sizeable.parentSize`](./Sizeable#parentSize) in order to return the size of a Scene's
* non-LUME parent element where the scene is connected.
* NOTE: `z` size of a non-LUME element is always `0`, since regular DOM
* elements don't have the concept of Z size and are always flat.
*/
override get parentSize(): XYZValuesObject<number> {
return this.composedLumeParent?.calculatedSize ?? this.__elementParentSize
}
// For now, use the same program (with shaders) for all objects.
// Basically it has position, frag colors, point light, directional
// light, and ambient light.
override _loadGL() {
// THREE
// maybe keep this in sceneState in WebGLRendererThree
if (!super._loadGL()) return false
// We don't let Three update any matrices, we supply our own world
// matrices.
this.three.autoUpdate = false
// TODO: default ambient light when no AmbientLight elements are
// present in the Scene.
//const ambientLight = new AmbientLight( 0x353535 )
//this.three.add( ambientLight )
this.#glRenderer = this.#getGLRenderer('three')
// If _loadGL is firing, then this.webgl must be true, therefore
// this.#glRenderer must be defined in any of the below autoruns.
this._glStopFns.push(
autorun(() => {
if (this.fogMode === 'none') {
this.three.fog = null
} else if (this.fogMode === 'linear') {
this.three.fog = new Fog('deeppink')
} else if (this.fogMode === 'expo2') {
this.three.fog = new FogExp2(new Color('deeppink').getHex())
}
this.needsUpdate()
}),
autorun(() => {
if (this.fogMode === 'none') {
// Nothing to do.
} else if (this.fogMode === 'linear') {
const fog = this.three.fog! as Fog
fog.near = this.fogNear
fog.far = this.fogFar
fog.color.set(this.fogColor)
} else if (this.fogMode === 'expo2') {
const fog = this.three.fog! as FogExp2
fog.color.set(this.fogColor)
fog.density = this.fogDensity
}
this.needsUpdate()
}),
autorun(() => {
this.#glRenderer!.localClippingEnabled = this.__localClipping
this.needsUpdate()
}),
autorun(() => {
this.#glRenderer!.setClearColor(this, this.backgroundColor, this.backgroundOpacity)
this.needsUpdate()
}),
autorun(() => {
this.#glRenderer!.setClearAlpha(this, this.backgroundOpacity)
this.needsUpdate()
}),
autorun(() => {
this.#glRenderer!.setShadowMapType(this, this.shadowmapType)
this.needsUpdate()
}),
autorun(() => {
this.#glRenderer!.setPhysicallyCorrectLights(this, this.physicallyCorrectLights)
this.needsUpdate()
}),
autorun(() => {
this.#glRenderer!.enableVR(this, this.vr)
if (this.vr) {
console.log('set vr frame requester!')
Motor.setFrameRequester(fn => {
this.#glRenderer!.requestFrame(this, fn)
// Mock rAF return value for Motor.setFrameRequester.
return 0
})
const button = this.#glRenderer!.createDefaultVRButton(this)
button.classList.add('vrButton')
this._miscLayer!.appendChild(button)
} else if ((this as any).xr) {
// TODO
} else {
// TODO else exit the WebXR headset, return back to normal requestAnimationFrame.
}
this.needsUpdate()
}),
autorun(() => {
this.__threeCamera.near = this.cameraNear
this.__threeCamera.far = this.cameraFar
this.needsUpdate()
}),
)
this.traverseSceneGraph((node: Node) => node._triggerLoadGL(), true)
return true
}
override _unloadGL() {
if (!super._unloadGL()) return false
if (this.#glRenderer) {
this.#glRenderer.uninitialize(this)
this.#glRenderer = null
}
this.traverseSceneGraph((node: Node) => node._triggerUnloadGL())
// Not all things are loaded in _loadGL (they may be loaded
// depending on property/attribute values), but all things, if any, should
// still be disposed in _unloadGL.
{
this.three.environment?.dispose()
if (isDisposable(this.three.background)) this.three.background.dispose()
}
return true
}
override _loadCSS() {
if (!super._loadCSS()) return false
this.#cssRenderer = this.#getCSSRenderer('three')
this.traverseSceneGraph((node: Node) => node._loadCSS(), true)
return true
}
override _unloadCSS() {
if (!super._unloadCSS()) return false
if (this.#cssRenderer) {
this.#cssRenderer.uninitialize(this)
this.#cssRenderer = null
}
this.traverseSceneGraph((node: Node) => node._unloadCSS())
return true
}
#glRenderer: WebglRendererThree | null = null
#cssRenderer: Css3dRendererThree | null = null
// The idea here is that in the future we might have "babylon",
// "playcanvas", etc, on a per scene basis. We'd needed to abstract the
// renderer more, have abstract base classes to define the common
// interfaces.
#getGLRenderer(type: 'three'): WebglRendererThree {
if (this.#glRenderer) return this.#glRenderer
let renderer: WebglRendererThree
if (type === 'three') renderer = WebglRendererThree.singleton()
else throw new Error('invalid WebGL renderer')
renderer.initialize(this)
return renderer
}
#getCSSRenderer(type: 'three') {
if (this.#cssRenderer) return this.#cssRenderer
let renderer: Css3dRendererThree
if (type === 'three') renderer = Css3dRendererThree.singleton()
else throw new Error('invalid CSS renderer. The only type supported is currently "three" (i.e. Three.js).')
renderer.initialize(this)
return renderer
}
__setCamera(camera?: PerspectiveCamera) {
if (!camera) {
this._createDefaultCamera()
} else {
// TODO?: implement an changecamera event/method and emit/call
// that here, then move this logic to the renderer
// handler/method?
this.__threeCamera = camera.three
this._updateCameraAspect()
this._updateCameraProjection()
this.needsUpdate()
}
}
// TODO move the following parent size change stuff to a separate re-usable class.
// size of the element where the Scene is mounted
@reactive __elementParentSize: XYZValuesObject<number> = {x: 0, y: 0, z: 0}
// TODO NESTED SCENES At the moment, we assume Scenes are top-level, connected to regular
// element parents. In the future, we will allow Scenes to be children of
// Nodes, in order to have nested scene rendering (f.e. a WebGL Scene
// rendered on a plane inside a parent Scene, to make portals, etc).
#startOrStopParentSizeObservation() {
if (
// If we will be rendering something...
(this.enableCss || this.webgl) &&
// ...and if one size dimension is proportional...
(this.sizeMode.x == 'proportional' || this.sizeMode.y == 'proportional')
// Note, we don't care about the Z dimension, because Scenes are flat surfaces.
) {
// ...then observe the parent element size (it may not be a LUME
// element, so we observe with ResizeObserver).
this.#startParentSizeObservation()
} else {
this.#stopParentSizeObservation()
}
}
#resizeObserver: ResizeObserver | null = null
// observe size changes on the scene's parent.
#startParentSizeObservation() {
// TODO The only way to make composedParent reactive even for non-LUME
// composed parents without polling is with a combination of monkey
// patching attachShadow and using MutationObserver in all trees to
// observe slot elements for slotchange.
// https://github.com/WICG/webcomponents/issues/941
// TODO NESTED SCENES In the future, we will want to distinguish between Nodes and
// regular elements, and we will only need size observation with regular
// elements.
const parent = /*not reactive*/ this.composedParent
// This shouldn't be possible.
// @prod-prune
if (!parent) throw new Error('A Scene can only be child of HTMLElement or ShadowRoot (f.e. not an SVGElement).')
// TODO use a single ResizeObserver for all scenes.
this.#resizeObserver = new ResizeObserver(changes => {
for (const change of changes) {
// Use the newer API if available.
// NOTE We care about the contentBoxSize (not the
// borderBoxSize) because the content box is the area in
// which we're rendering visuals.
if (change.contentBoxSize) {
// If change.contentBoxSize is an array with more than one
// item, it means the observed element is split across
// multiple CSS columns. But not all browsers support the Array
// form yet (f.e. Firefox) so fallback in that case:
const contentBoxSize = change.contentBoxSize[0] || change.contentBoxSize
// TODO If the Scene is used as display:inline{-block},
// ensure that it is the size of the column in which it is
// located. For now, we only grab the first item in the
// array, assuming that the Scene in not used inside a
// layout with columns.
const {inlineSize, blockSize} = contentBoxSize
const isHorizontal = getComputedStyle(parent).writingMode.includes('horizontal')
// If the text writing mode is horizontal, then inlinSize is
// the width, otherwise in vertical writing mode it is the height.
// For more details: https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserverEntry/contentBoxSize#Syntax
if (isHorizontal) this.#checkElementParentSize(inlineSize, blockSize)
else this.#checkElementParentSize(blockSize, inlineSize)
}
// Otherwise use the older API (possibly polyfilled)
else {
const {width, height} = change.contentRect
this.#checkElementParentSize(width, height)
}
}
})
this.#resizeObserver.observe(parent)
}
#stopParentSizeObservation() {
this.#resizeObserver?.disconnect()
this.#resizeObserver = null
}
// NOTE, the Z dimension of a scene doesn't matter, it's a flat plane, so
// we haven't taken that into consideration here.
#checkElementParentSize(x: number, y: number) {
const parentSize = this.__elementParentSize
// if we have a size change
if (parentSize.x != x || parentSize.y != y) {
parentSize.x = x
parentSize.y = y
this.__elementParentSize = parentSize
}
}
}
// Put initial value on the prototype to make it available during construction
// in a super() call.
// @ts-ignore
Scene.prototype.isScene = true
import type {ElementAttributes} from '@lume/element'
declare module '@lume/element' {
namespace JSX {
interface IntrinsicElements {
'lume-scene': ElementAttributes<Scene, SceneAttributes>
}
}
}
declare global {
interface HTMLElementTagNameMap {
'lume-scene': Scene
}
}
type FogMode = 'none' | 'linear' | 'expo2' | the_stack |
import { Component, OnInit, Input, OnChanges, ViewChild, SimpleChanges, Output, EventEmitter } from '@angular/core';
import {SensorParserConfig} from '../../model/sensor-parser-config';
import {ParseMessageRequest} from '../../model/parse-message-request';
import {SensorParserConfigService} from '../../service/sensor-parser-config.service';
import {StellarService} from '../../service/stellar.service';
import {AutocompleteOption} from '../../model/autocomplete-option';
import {StellarFunctionDescription} from '../../model/stellar-function-description';
import {SensorEnrichmentConfig, EnrichmentConfig, ThreatIntelConfig} from '../../model/sensor-enrichment-config';
import {FieldTransformer} from '../../model/field-transformer';
import {SampleDataComponent} from '../../shared/sample-data/sample-data.component';
import {MetronAlerts} from '../../shared/metron-alerts';
import {SensorEnrichmentConfigService} from '../../service/sensor-enrichment-config.service';
export class FieldSchemaRow {
inputFieldName: string;
outputFieldName: string;
preview: string;
showConfig: boolean;
isRemoved: boolean;
isSimple: boolean;
isNew: boolean;
isParserGenerated: boolean;
conditionalRemove: boolean;
transformConfigured: AutocompleteOption[] = [];
enrichmentConfigured: AutocompleteOption[] = [];
threatIntelConfigured: AutocompleteOption[] = [];
constructor(fieldName: string) {
this.inputFieldName = fieldName;
this.outputFieldName = fieldName;
this.conditionalRemove = false;
this.isParserGenerated = false;
this.showConfig = false;
this.isSimple = true;
this.isRemoved = false;
this.preview = '';
}
}
@Component({
selector: 'metron-config-sensor-field-schema',
templateUrl: './sensor-field-schema.component.html',
styleUrls: ['./sensor-field-schema.component.scss']
})
export class SensorFieldSchemaComponent implements OnInit, OnChanges {
@Input() sensorParserConfig: SensorParserConfig;
@Input() sensorEnrichmentConfig: SensorEnrichmentConfig;
@Input() showFieldSchema: boolean;
@Input() grokStatement: string;
parserResult: any = {};
fieldSchemaRows: FieldSchemaRow[] = [];
savedFieldSchemaRows: FieldSchemaRow[] = [];
transformOptions: AutocompleteOption[] = [];
enrichmentOptions: AutocompleteOption[] = [];
threatIntelOptions: AutocompleteOption[] = [];
transformFunctions: StellarFunctionDescription[];
@ViewChild(SampleDataComponent) sampleData: SampleDataComponent;
@Output() hideFieldSchema: EventEmitter<boolean> = new EventEmitter<boolean>();
@Output() onFieldSchemaChanged: EventEmitter<boolean> = new EventEmitter<boolean>();
sampleThreatIntels: string[] = ['malicious_ip'];
constructor(private sensorParserConfigService: SensorParserConfigService,
private transformationValidationService: StellarService,
private sensorEnrichmentConfigService: SensorEnrichmentConfigService,
private metronAlerts: MetronAlerts) { }
ngOnChanges(changes: SimpleChanges) {
if (changes['showFieldSchema'] && changes['showFieldSchema'].currentValue) {
this.sampleData.getNextSample();
}
}
ngOnInit() {
this.getTransformFunctions();
this.getEnrichmentFunctions();
this.getThreatIntelfunctions();
}
getTransformFunctions() {
this.transformOptions = [];
this.transformationValidationService.listSimpleFunctions().subscribe((result: StellarFunctionDescription[]) => {
this.transformFunctions = result;
for (let fun of result) {
this.transformOptions.push(new AutocompleteOption(fun.name, fun.name, fun.description));
}
});
}
getEnrichmentFunctions() {
this.enrichmentOptions = [];
this.sensorEnrichmentConfigService.getAvailableEnrichments().subscribe((result: string[]) => {
for (let fun of result) {
this.enrichmentOptions.push(new AutocompleteOption(fun));
}
});
}
getThreatIntelfunctions() {
this.threatIntelOptions = [];
for (let threatName of this.sampleThreatIntels) {
this.threatIntelOptions.push(new AutocompleteOption(threatName));
}
}
isSimpleFunction(configuredFunctions: string[]) {
for (let configuredFunction of configuredFunctions) {
if (this.transformFunctions.filter(stellarFunctionDescription => stellarFunctionDescription.name === configuredFunction).length === 0) {
return false;
}
}
return true;
}
isConditionalRemoveTransform(fieldTransformer: FieldTransformer): boolean {
if (fieldTransformer && fieldTransformer.transformation === 'REMOVE' &&
fieldTransformer.config && fieldTransformer.config['condition']) {
return true;
}
return false;
}
createFieldSchemaRows() {
this.fieldSchemaRows = [];
this.savedFieldSchemaRows = [];
let fieldSchemaRowsCreated = {};
// Update rows with Stellar transformations
let stellarTransformations = this.sensorParserConfig.fieldTransformations.filter(fieldTransformer => fieldTransformer.transformation === 'STELLAR');
for (let fieldTransformer of stellarTransformations) {
if (fieldTransformer.config) {
for (let outputFieldName of Object.keys(fieldTransformer.config)) {
let stellarFunctionStatement = fieldTransformer.config[outputFieldName];
let configuredFunctions = stellarFunctionStatement.split('(');
let inputFieldName = configuredFunctions.splice(-1, 1)[0].replace(new RegExp('\\)', 'g'), '');
configuredFunctions.reverse();
if (!fieldSchemaRowsCreated[inputFieldName]) {
fieldSchemaRowsCreated[inputFieldName] = new FieldSchemaRow(inputFieldName);
}
fieldSchemaRowsCreated[inputFieldName].outputFieldName = outputFieldName;
fieldSchemaRowsCreated[inputFieldName].preview = stellarFunctionStatement;
fieldSchemaRowsCreated[inputFieldName].isSimple = this.isSimpleFunction(configuredFunctions);
if (fieldSchemaRowsCreated[inputFieldName].isSimple) {
for (let configuredFunction of configuredFunctions) {
fieldSchemaRowsCreated[inputFieldName].transformConfigured.push(new AutocompleteOption(configuredFunction));
}
}
}
}
}
// Update rows with Remove Transformations
let removeTransformations = this.sensorParserConfig.fieldTransformations.filter(fieldTransformer => fieldTransformer.transformation === 'REMOVE');
for (let fieldTransformer of removeTransformations) {
for (let inputFieldName of fieldTransformer.input) {
if (!fieldSchemaRowsCreated[inputFieldName]) {
fieldSchemaRowsCreated[inputFieldName] = new FieldSchemaRow(inputFieldName);
}
fieldSchemaRowsCreated[inputFieldName].isRemoved = true;
if (fieldTransformer.config && fieldTransformer.config['condition']) {
fieldSchemaRowsCreated[inputFieldName].conditionalRemove = true;
}
}
}
// Update rows with enrichments
if (this.sensorEnrichmentConfig.enrichment.fieldMap) {
for (let enrichment in this.sensorEnrichmentConfig.enrichment.fieldMap) {
if (enrichment !== 'hbaseEnrichment' && enrichment !== 'stellar') {
let fieldNames = this.sensorEnrichmentConfig.enrichment.fieldMap[enrichment];
for (let fieldName of fieldNames) {
if (!fieldSchemaRowsCreated[fieldName]) {
fieldSchemaRowsCreated[fieldName] = new FieldSchemaRow(fieldName);
}
fieldSchemaRowsCreated[fieldName].enrichmentConfigured.push(new AutocompleteOption(enrichment));
}
}
}
}
// Update rows with HBase enrichments
if (this.sensorEnrichmentConfig.enrichment.fieldToTypeMap) {
for (let fieldName of Object.keys(this.sensorEnrichmentConfig.enrichment.fieldToTypeMap)) {
let enrichments = this.sensorEnrichmentConfig.enrichment.fieldToTypeMap[fieldName];
if (!fieldSchemaRowsCreated[fieldName]) {
fieldSchemaRowsCreated[fieldName] = new FieldSchemaRow(fieldName);
}
for (let enrichment of enrichments) {
fieldSchemaRowsCreated[fieldName].enrichmentConfigured.push(new AutocompleteOption(enrichment));
}
}
}
// Update rows with threatIntels
if (this.sensorEnrichmentConfig.threatIntel.fieldToTypeMap) {
for (let fieldName of Object.keys(this.sensorEnrichmentConfig.threatIntel.fieldToTypeMap)) {
let threatIntels = this.sensorEnrichmentConfig.threatIntel.fieldToTypeMap[fieldName];
if (!fieldSchemaRowsCreated[fieldName]) {
fieldSchemaRowsCreated[fieldName] = new FieldSchemaRow(fieldName);
}
for (let threatIntel of threatIntels) {
fieldSchemaRowsCreated[fieldName].threatIntelConfigured.push(new AutocompleteOption(threatIntel));
}
}
}
this.fieldSchemaRows = Object.keys(fieldSchemaRowsCreated).map(key => fieldSchemaRowsCreated[key]);
// Adds rows from parseResult with no transformations/enrichments/threatIntels
let fieldSchemaRowsCreatedKeys = Object.keys(fieldSchemaRowsCreated);
for (let fieldName of Object.keys(this.parserResult).filter(fieldName => fieldSchemaRowsCreatedKeys.indexOf(fieldName) === -1)) {
let field = new FieldSchemaRow(fieldName);
field.isParserGenerated = true;
this.fieldSchemaRows.push(field);
}
// save the initial fieldSchemaRows
for (let fieldSchemaRow of this.fieldSchemaRows) {
this.savedFieldSchemaRows.push(JSON.parse(JSON.stringify(fieldSchemaRow)));
}
}
getChanges(fieldSchemaRow: FieldSchemaRow): string {
if (fieldSchemaRow.isRemoved) {
return 'Disabled';
}
let transformFunction = fieldSchemaRow.transformConfigured.length > 0 ? this.createTransformFunction(fieldSchemaRow) : '';
let enrichments = fieldSchemaRow.enrichmentConfigured.map(autocomplete => autocomplete.name).join(', ');
let threatIntel = fieldSchemaRow.threatIntelConfigured.map(autocomplete => autocomplete.name).join(', ');
transformFunction = transformFunction.length > 30 ? (transformFunction.substring(0, 25) + '...') : transformFunction;
let displayString = transformFunction.length > 0 ? ('Transforms: ' + transformFunction) : '';
displayString += (transformFunction.length > 0 ? ' <br> ' : '') + (enrichments.length > 0 ? ('Enrichments: ' + enrichments) : '');
displayString += (enrichments.length > 0 ? ' <br> ' : '') + (threatIntel.length > 0 ? ('Threat Intel: ' + threatIntel) : '');
return displayString;
}
onSampleDataChanged(sampleData: string) {
let sensorTopicUpperCase = this.sensorParserConfig.sensorTopic.toUpperCase();
let parseMessageRequest = new ParseMessageRequest();
parseMessageRequest.sensorParserConfig = JSON.parse(JSON.stringify(this.sensorParserConfig));
parseMessageRequest.grokStatement = this.grokStatement;
parseMessageRequest.sampleData = sampleData;
if (parseMessageRequest.sensorParserConfig.parserConfig['patternLabel'] == null) {
parseMessageRequest.sensorParserConfig.parserConfig['patternLabel'] = sensorTopicUpperCase;
}
parseMessageRequest.sensorParserConfig.parserConfig['grokPath'] = './' + parseMessageRequest.sensorParserConfig.sensorTopic;
this.sensorParserConfigService.parseMessage(parseMessageRequest).subscribe(
parserResult => {
this.parserResult = parserResult;
this.createFieldSchemaRows();
},
error => {
this.onSampleDataNotAvailable();
});
}
onSampleDataNotAvailable() {
this.createFieldSchemaRows();
}
onDelete(fieldSchemaRow: FieldSchemaRow) {
this.fieldSchemaRows.splice(this.fieldSchemaRows.indexOf(fieldSchemaRow), 1);
this.savedFieldSchemaRows.splice(this.fieldSchemaRows.indexOf(fieldSchemaRow), 1);
}
onRemove(fieldSchemaRow: FieldSchemaRow) {
fieldSchemaRow.isRemoved = true;
this.onSaveChange(fieldSchemaRow);
}
onEnable(fieldSchemaRow: FieldSchemaRow) {
if (fieldSchemaRow.conditionalRemove) {
this.metronAlerts.showErrorMessage('The "' + fieldSchemaRow.outputFieldName + '" field cannot be enabled because the REMOVE transformation has a condition. Please remove the condition in the RAW JSON editor.');
return;
}
fieldSchemaRow.isRemoved = false;
this.onSaveChange(fieldSchemaRow);
}
onSaveChange(savedFieldSchemaRow: FieldSchemaRow) {
savedFieldSchemaRow.showConfig = false;
savedFieldSchemaRow.isNew = false;
let initialSchemaRow = this.savedFieldSchemaRows.filter(fieldSchemaRow => fieldSchemaRow.inputFieldName === savedFieldSchemaRow.inputFieldName)[0];
Object.assign(initialSchemaRow, JSON.parse(JSON.stringify(savedFieldSchemaRow)));
this.onSave();
}
onCancelChange(cancelledFieldSchemaRow: FieldSchemaRow) {
cancelledFieldSchemaRow.showConfig = false;
let initialSchemaRow = this.savedFieldSchemaRows.filter(fieldSchemaRow => fieldSchemaRow.inputFieldName === cancelledFieldSchemaRow.inputFieldName)[0];
Object.assign(cancelledFieldSchemaRow, JSON.parse(JSON.stringify(initialSchemaRow)));
}
onCancel(): void {
this.hideFieldSchema.emit(true);
}
createTransformFunction(fieldSchemaRow: FieldSchemaRow): string {
let func = fieldSchemaRow.inputFieldName;
for (let config of fieldSchemaRow.transformConfigured) {
func = config.name + '(' + func + ')';
}
return func;
}
onTransformsChange(fieldSchemaRow: FieldSchemaRow): void {
fieldSchemaRow.preview = fieldSchemaRow.transformConfigured.length === 0 ? '' : this.createTransformFunction(fieldSchemaRow);
}
addNewRule() {
let fieldSchemaRow = new FieldSchemaRow('new');
fieldSchemaRow.isNew = true;
fieldSchemaRow.showConfig = true;
fieldSchemaRow.inputFieldName = '';
this.fieldSchemaRows.push(fieldSchemaRow);
}
onSave() {
let removeTransformations: string[] = [];
// Remove all STELLAR functions and retain only the REMOVE objects
this.sensorParserConfig.fieldTransformations = this.sensorParserConfig.fieldTransformations.filter(fieldTransformer => {
if (this.isConditionalRemoveTransform(fieldTransformer)) {
return true;
}
return false;
});
let transformConfigObject = new FieldTransformer();
transformConfigObject.output = [];
transformConfigObject.config = {};
transformConfigObject.transformation = 'STELLAR';
let enrichmentConfigObject = new EnrichmentConfig();
enrichmentConfigObject.config = {};
let threatIntelConfigObject = new ThreatIntelConfig();
threatIntelConfigObject.triageConfig = this.sensorEnrichmentConfig.threatIntel.triageConfig;
for (let fieldSchemaRow of this.savedFieldSchemaRows) {
if (fieldSchemaRow.transformConfigured.length > 0) {
transformConfigObject.output.push(fieldSchemaRow.outputFieldName);
transformConfigObject.config[fieldSchemaRow.outputFieldName] = this.createTransformFunction(fieldSchemaRow);
}
if (fieldSchemaRow.isRemoved && !fieldSchemaRow.conditionalRemove) {
removeTransformations.push(fieldSchemaRow.inputFieldName);
}
if (fieldSchemaRow.enrichmentConfigured.length > 0) {
for (let option of fieldSchemaRow.enrichmentConfigured) {
if (option.name === 'geo' || option.name === 'host') {
if (!enrichmentConfigObject.fieldMap[option.name]) {
enrichmentConfigObject.fieldMap[option.name] = [];
}
enrichmentConfigObject.fieldMap[option.name].push(fieldSchemaRow.inputFieldName);
} else {
if (!enrichmentConfigObject.fieldMap['hbaseEnrichment']) {
enrichmentConfigObject.fieldMap['hbaseEnrichment'] = [];
}
enrichmentConfigObject.fieldMap['hbaseEnrichment'].push(fieldSchemaRow.inputFieldName);
if (!enrichmentConfigObject.fieldToTypeMap[fieldSchemaRow.inputFieldName]) {
enrichmentConfigObject.fieldToTypeMap[fieldSchemaRow.inputFieldName] = [];
}
enrichmentConfigObject.fieldToTypeMap[fieldSchemaRow.inputFieldName].push(option.name);
}
}
}
if (fieldSchemaRow.threatIntelConfigured.length > 0) {
for (let option of fieldSchemaRow.threatIntelConfigured) {
if (!threatIntelConfigObject.fieldMap['hbaseThreatIntel']) {
threatIntelConfigObject.fieldMap['hbaseThreatIntel'] = [];
}
threatIntelConfigObject.fieldMap['hbaseThreatIntel'].push(fieldSchemaRow.inputFieldName);
if (!threatIntelConfigObject.fieldToTypeMap[fieldSchemaRow.inputFieldName]) {
threatIntelConfigObject.fieldToTypeMap[fieldSchemaRow.inputFieldName] = [];
}
threatIntelConfigObject.fieldToTypeMap[fieldSchemaRow.inputFieldName].push(option.name);
}
}
}
if (Object.keys(transformConfigObject.config).length > 0) {
this.sensorParserConfig.fieldTransformations.push(transformConfigObject);
}
if (removeTransformations.length > 0) {
let removeConfigObject = new FieldTransformer();
removeConfigObject.transformation = 'REMOVE';
removeConfigObject.input = removeTransformations;
this.sensorParserConfig.fieldTransformations.push(removeConfigObject);
}
this.sensorEnrichmentConfig.enrichment = enrichmentConfigObject;
this.sensorEnrichmentConfig.threatIntel = threatIntelConfigObject;
}
} | the_stack |
import { Construct, } from 'constructs';
import { Aws, App, Stack, Resource, StackProps, CustomResource, Duration, Fn, Token } from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as glue from 'aws-cdk-lib/aws-glue';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as s3assets from 'aws-cdk-lib/aws-s3-assets';
import * as lakeformation from 'aws-cdk-lib/aws-lakeformation';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as cr from 'aws-cdk-lib/custom-resources';
import * as fs from "fs";
import { URL } from "url";
export interface FederatedCrawlerTemplateProps extends StackProps {
databaseDescriptionPath: string;
crawlerDescriptionPath: string;
dataSetName: string;
}
export class FederatedCrawlerTemplate extends Construct{
public readonly glueDatabase: glue.CfnDatabase;
public readonly glueCrawler: glue.CfnCrawler;
public readonly glueRole: iam.Role;
constructor(scope: Construct, id: string, props: FederatedCrawlerTemplateProps) {
super(scope, id);
const databaseObj = require(props.databaseDescriptionPath);
const crawlerObj = require(props.crawlerDescriptionPath);
// import databaseObj from props.databaseDescriptionPath;
// import tablesObj from props.tablesDescriptionPath;
const databaseName = `${databaseObj['Database']['Name']}`
this.glueDatabase = new glue.CfnDatabase(this, 'GlueDatabase', {
catalogId: Aws.ACCOUNT_ID,
databaseInput: {
locationUri: `${databaseObj['Database']['LocationUri']}`,
name: databaseName,
}
});
this.glueRole = new iam.Role(this, `GlueCrawlerRole`, {
assumedBy: new iam.ServicePrincipal('glue.amazonaws.com')
});
this.glueRole.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSGlueServiceRole'));
this.glueRole.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('CloudWatchAgentServerPolicy'));
var protocolPathTuple = databaseObj['Database']['LocationUri'].split("//");
var pathArray = protocolPathTuple[1].split("/");
let s3DataLakePaths = new Array<glue.CfnCrawler.S3TargetProperty>();
this.glueRole.addToPolicy(new iam.PolicyStatement({
actions: ["s3:*"],
resources: [`arn:aws:s3:::${pathArray[0]}`, `arn:aws:s3:::${pathArray[0]}/${pathArray[1]}/*`]
}));
for (let s3Target of crawlerObj['Crawler']['Targets']['S3Targets']) {
s3DataLakePaths.push({
path: s3Target['Path']
//TODO: add exclusions
});
}
this.glueCrawler = new glue.CfnCrawler(this, `awsroda-crawler`,{
name: `${props.dataSetName}_awsroda_crawler`,
targets: {
s3Targets: s3DataLakePaths
},
role: this.glueRole.roleName,
databaseName: databaseName,
schemaChangePolicy: {
deleteBehavior: "DEPRECATE_IN_DATABASE",
updateBehavior: "UPDATE_IN_DATABASE",
},
tablePrefix: "",
classifiers: []
});
}
}
export interface FederatedDataSetProps extends StackProps {
databaseDescriptionPath: string
tablesDescriptionPath: string
}
export class FederatedDataSetTemplate extends Construct{
public readonly glueDatabase: glue.CfnDatabase;
constructor(scope: Construct, id: string, props: FederatedDataSetProps) {
super(scope, id);
const databaseObj = require(props.databaseDescriptionPath);
const tablesObj = require(props.tablesDescriptionPath);
// import databaseObj from props.databaseDescriptionPath;
// import tablesObj from props.tablesDescriptionPath;
const databaseName = `${databaseObj['Database']['Name']}`
this.glueDatabase = new glue.CfnDatabase(this, databaseObj['Database']['Name'], {
catalogId: Aws.ACCOUNT_ID,
databaseInput: {
locationUri: `${databaseObj['Database']['LocationUri']}`,
name: databaseName,
}
});
for (let table of tablesObj['TableList']) {
var columnList = [];
for(let column of table['StorageDescriptor']['Columns']){
columnList.push({
name: column['Name'],
type: column['Type']
});
}
const freshTable = new glue.CfnTable(this, table["Name"], {
catalogId: Aws.ACCOUNT_ID,
databaseName: databaseName,
tableInput: {
name: table["Name"],
parameters: table['Parameters'],
storageDescriptor: {
columns: columnList,
inputFormat: table['StorageDescriptor']['InputFormat'],
outputFormat: table['StorageDescriptor']['OutputFormat'],
location: table['StorageDescriptor']['Location'],
parameters: table['StorageDescriptor']['Parameters'],
serdeInfo: {
parameters: table['StorageDescriptor']['SerdeInfo']['Parameters'],
serializationLibrary: table['StorageDescriptor']['SerdeInfo']['SerializationLibrary']
}
}
}
})
freshTable.addDependsOn(this.glueDatabase);
}
}
}
export interface DataSetEnrollmentProps extends StackProps {
dataLakeBucket: s3.Bucket;
dataSetName: string;
SourceConnectionInput?: glue.CfnConnection.ConnectionInputProperty;
SourceTargets: glue.CfnCrawler.TargetsProperty;
DataLakeTargets: glue.CfnCrawler.TargetsProperty;
GlueScriptPath: string;
GlueScriptArguments: any;
SourceAccessPolicy?: iam.Policy;
MaxDPUs: number;
WorkflowCronScheduleExpression?: string;
}
export class DataSetEnrollment extends Construct {
public readonly Workflow: DataLakeEnrollmentWorkflow;
public readonly SrcCrawlerCompleteTrigger: glue.CfnTrigger;
public readonly ETLCompleteTrigger: glue.CfnTrigger;
public readonly SourceConnection?: glue.CfnConnection;
public readonly DataLakeConnection: glue.CfnConnection;
public readonly DataSetName: string;
public readonly DataSetGlueRole: iam.Role;
public readonly Dataset_Source: glue.CfnDatabase;
public readonly Dataset_Datalake: glue.CfnDatabase;
public readonly Dataset_SourceDatabaseName: string;
public readonly Dataset_DatalakeDatabaseName: string;
public readonly DataLakeBucketName: string;
public readonly DataLakePrefix: string;
public readonly DataLakeTargets: glue.CfnCrawler.TargetsProperty;
private setupCrawler(targetGlueDatabase: glue.CfnDatabase, targets: glue.CfnCrawler.TargetsProperty, isSourceCrawler: boolean, databaseName: string){
var sourceCrawler = isSourceCrawler ? "src" : "dl";
return new glue.CfnCrawler(this, `${this.DataSetName}-${sourceCrawler}-crawler`,{
name: `${this.DataSetName}_${sourceCrawler}_crawler`,
targets: targets,
role: this.DataSetGlueRole.roleName,
databaseName: databaseName,
schemaChangePolicy: {
deleteBehavior: "DEPRECATE_IN_DATABASE",
updateBehavior: "UPDATE_IN_DATABASE",
},
tablePrefix: "",
classifiers: []
});
}
constructor(scope: Construct, id: string, props: DataSetEnrollmentProps) {
super(scope, id);
this.DataLakeTargets = props.DataLakeTargets;
this.DataLakeBucketName = props.GlueScriptArguments['--DL_BUCKET'];
this.DataLakePrefix = props.GlueScriptArguments['--DL_PREFIX'];
this.DataSetName = props.dataSetName;
this.Dataset_SourceDatabaseName = `${props.dataSetName}_src`;
this.Dataset_DatalakeDatabaseName = `${props.dataSetName}_dl`;
this.Dataset_Source = new glue.CfnDatabase(this, `${props.dataSetName}_src`, {
catalogId: Aws.ACCOUNT_ID,
databaseInput: {
name: this.Dataset_SourceDatabaseName,
locationUri: `s3://${props.dataLakeBucket.bucketName}/${props.dataSetName}/`
}
});
this.Dataset_Datalake = new glue.CfnDatabase(this, `${props.dataSetName}_dl`, {
catalogId: Aws.ACCOUNT_ID,
databaseInput: {
name: this.Dataset_DatalakeDatabaseName,
locationUri: `s3://${props.dataLakeBucket.bucketName}/${props.dataSetName}/`
}
});
let connectionArray = [];
if(props.SourceConnectionInput){
this.SourceConnection = new glue.CfnConnection(this, `${props.dataSetName}-src-connection`, {
catalogId: this.Dataset_Source.catalogId,
connectionInput: props.SourceConnectionInput
});
if(props.SourceConnectionInput.name){
connectionArray.push(props.SourceConnectionInput.name);
}
}
this.DataSetGlueRole = new iam.Role(this, `${props.dataSetName}-GlueRole`, {
assumedBy: new iam.ServicePrincipal('glue.amazonaws.com')
});
this.DataSetGlueRole.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSGlueServiceRole'));
this.DataSetGlueRole.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('CloudWatchAgentServerPolicy'));
props.dataLakeBucket.grantReadWrite(this.DataSetGlueRole);
if(typeof props.SourceAccessPolicy !== 'undefined'){
props.SourceAccessPolicy.attachToRole(this.DataSetGlueRole);
}
const sourceCrawler = this.setupCrawler(this.Dataset_Source, props.SourceTargets, true, this.Dataset_SourceDatabaseName);
const glueScript = new s3assets.Asset(this, `${props.dataSetName}-GlueScript`, {
path: props.GlueScriptPath
});
glueScript.grantRead(this.DataSetGlueRole);
/// The spread operator below (...) makes the connections property conditional. Its only used for JDBC sources at the moment.
const jobParams = {
executionProperty: {
maxConcurrentRuns: 1
},
name: `${props.dataSetName}_src_to_dl_etl`,
timeout: 2880,
glueVersion: "2.0",
maxCapacity: props.MaxDPUs,
command: {
scriptLocation: `s3://${glueScript.s3BucketName}/${glueScript.s3ObjectKey}`,
name: "glueetl",
pythonVersion: "3"
},
role: this.DataSetGlueRole.roleArn,
maxRetries: 0,
defaultArguments: props.GlueScriptArguments,
...(typeof props.SourceConnectionInput !== "undefined" && {
connections: {
connections: connectionArray
}
})
}
const etl_job = new glue.CfnJob(this, `${props.dataSetName}-EtlJob`, jobParams );
const datalake_crawler = this.setupCrawler(this.Dataset_Datalake, this.DataLakeTargets, false, this.Dataset_DatalakeDatabaseName);
const datalakeEnrollmentWorkflow = new DataLakeEnrollmentWorkflow(this,`${props.dataSetName}DataLakeWorkflow`,{
workfowName: `${props.dataSetName}_DataLakeEnrollmentWorkflow`,
srcCrawler: sourceCrawler,
etlJob: etl_job,
datalakeCrawler: datalake_crawler,
WorkflowCronScheduleExpression: props.WorkflowCronScheduleExpression
});
}
}
export interface DataLakeEnrollmentWorkflowProps {
workfowName: string;
srcCrawler: glue.CfnCrawler,
etlJob: glue.CfnJob,
datalakeCrawler: glue.CfnCrawler
WorkflowCronScheduleExpression?: string;
}
export class DataLakeEnrollmentWorkflow extends Construct {
public StartTrigger: glue.CfnTrigger;
public readonly SrcCrawlerCompleteTrigger: glue.CfnTrigger;
public readonly ETLCompleteTrigger: glue.CfnTrigger;
public readonly Workflow: glue.CfnWorkflow;
private readonly sourceCrawler: glue.CfnCrawler;
constructor(scope: Construct, id: string, props: DataLakeEnrollmentWorkflowProps) {
super(scope, id);
this.Workflow = new glue.CfnWorkflow(this, "etlWorkflow", {
name: props.workfowName
});
this.sourceCrawler = props.srcCrawler;
if(props.WorkflowCronScheduleExpression == null){
this.StartTrigger = new glue.CfnTrigger(this,"startTrigger",{
actions: [
{
crawlerName: props.srcCrawler.name
}
],
type: "ON_DEMAND",
name: `startWorkflow-${this.Workflow.name}`,
workflowName: this.Workflow.name
});
}else{
this.StartTrigger = new glue.CfnTrigger(this,"startTrigger",{
actions: [
{
crawlerName: this.sourceCrawler.name
}
],
type: "SCHEDULED",
schedule: props.WorkflowCronScheduleExpression,
name: `startWorkflow-${this.Workflow.name}`,
workflowName: this.Workflow.name
});
}
this.SrcCrawlerCompleteTrigger = new glue.CfnTrigger(this,"srcCrawlerCompleteTrigger",{
predicate: {
conditions: [
{
crawlerName: props.srcCrawler.name,
crawlState: "SUCCEEDED",
logicalOperator: "EQUALS"
}
],
logical: "ANY"
},
name: `sourceDataCrawled-${this.Workflow.name}`,
actions: [
{
jobName: props.etlJob.name
}
],
workflowName: this.Workflow.name,
type: "CONDITIONAL",
startOnCreation: true
});
this.ETLCompleteTrigger = new glue.CfnTrigger(this,"etlCompleteTrigger",{
predicate: {
conditions: [
{
state: "SUCCEEDED",
logicalOperator: "EQUALS",
jobName: props.etlJob.name
}
],
logical: "ANY"
},
name: `EtlComplete-${this.Workflow.name}`,
actions: [
{
crawlerName: props.datalakeCrawler.name
}
],
workflowName: this.Workflow.name,
type: "CONDITIONAL"
});
this.StartTrigger.node.addDependency(this.Workflow);
this.SrcCrawlerCompleteTrigger.node.addDependency(this.Workflow);
this.ETLCompleteTrigger.node.addDependency(this.Workflow);
const activateTriggerRole = new iam.Role(this, 'activateTriggerRole', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com')
});
activateTriggerRole.addManagedPolicy(iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSLambdaBasicExecutionRole'));
activateTriggerRole.addToPolicy(new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
resources: ['*'],
actions: ['glue:StartTrigger']
}));
const activateTriggerFunction = new lambda.SingletonFunction(this, 'activateTriggerSingleton', {
role: activateTriggerRole,
uuid: "ActivateGlueTriggerFunction",
code: new lambda.InlineCode(fs.readFileSync('./scripts/lambda.activategluetigger.py', { encoding: 'utf-8' })),
handler: 'index.main',
timeout: Duration.seconds(300),
runtime: lambda.Runtime.PYTHON_3_7,
memorySize: 1024
});
if(props.WorkflowCronScheduleExpression != null){
const CronTrigger_triggerActivationProvider = new cr.Provider(this, 'CronTrigger_triggerActivationProvider', {
onEventHandler: activateTriggerFunction,
});
const CronTrigger_triggerActivation = new CustomResource(this, 'CronTrigger-triggerActivation', {
serviceToken: CronTrigger_triggerActivationProvider.serviceToken,
properties: {
triggerId: this.StartTrigger.name
}
});
}
const srcCrawlerCompleteTrigger_triggerActivationProvider = new cr.Provider(this, 'srcCrawlerCompleteTrigger_triggerActivationProvider', {
onEventHandler: activateTriggerFunction,
});
const srcCrawlerCompleteTrigger_triggerActivation = new CustomResource(this, 'srcCrawlerCompleteTrigger_triggerActivation', {
serviceToken: srcCrawlerCompleteTrigger_triggerActivationProvider.serviceToken,
properties: {
triggerId: this.SrcCrawlerCompleteTrigger.name
}
});
const etlTrigger_triggerActivationProvider = new cr.Provider(this, 'etlTrigger_triggerActivationProvider', {
onEventHandler: activateTriggerFunction,
});
const etlTrigger_triggerActivation = new CustomResource(this, 'etlTrigger-triggerActivation', {
serviceToken: etlTrigger_triggerActivationProvider.serviceToken,
properties: {
triggerId: this.ETLCompleteTrigger.name
}
});
}
} | the_stack |
declare namespace JQueryIdleTimer {
/**
* Interface with all the methods supported by the jQuery Idle Timer plugin. These metods are available on JQuery
* instances as well as on the static JQuery object:
*
* ```javascript
* $.idleTimer(); // shortcut for the below
* $( document ).idleTimer();
* ```
*/
export interface IdleTimerMethods {
/**
* There are two ways to instantiate. Either statically, or on an element. Element bound timers will only watch for
* events inside of them. You may just want page-level activity, in which case you may set up your timers on
* `document`, `document.documentElement`, and `document.body`.
*
* ```javascript
* $(function() {
* // binds to document - shorthand
* $.idleTimer();
*
* // binds to document - explicit
* $( document ).idleTimer();
*
* // bind to different element
* $( "#myTextArea" ).idleTimer();
* });
* ```
* @param element Element to watch, defaults to the document.
* @param id Unique ID for this idle timer, to support multiple timers on the same page.
* @return this JQuery instance for chaining.
*/
idleTimer(element?: Document | HTMLElement, id?: string): this;
/**
* There are two ways to instantiate. Either statically, or on an element. Element bound timers will only watch for
* events inside of them. You may just want page-level activity, in which case you may set up your timers on
* `document`, `document.documentElement`, and `document.body`.
*
* ```javascript
* $(function() {
* // binds to document - shorthand
* $.idleTimer(1000);
*
* // binds to document - explicit
* $( document ).idleTimer(1000);
*
* // bind to different element
* $( "#myTextArea" ).idleTimer(1000);
* });
* ```
*
* @param idleTimeoutMillis The timeout period in milliseconds.
* @param element Element to watch, defaults to the document.
* @param id Unique ID for this idle timer, to support multiple timers on the same page.
* @return this JQuery instance for chaining.
*/
idleTimer(idleTimeoutMillis: number, element?: Document | HTMLElement, id?: string): this;
/**
* There are two ways to instantiate. Either statically, or on an element. Element bound timers will only watch for
* events inside of them. You may just want page-level activity, in which case you may set up your timers on
* `document`, `document.documentElement`, and `document.body`.
*
* ```javascript
* $(function() {
* // binds to document - shorthand
* $.idleTimer({
* timeout:10000,
* idle:true
* });
*
* // binds to document - explicit
* $( document ).idleTimer({
* timeout:10000,
* idle:true
* });
*
* // bind to different element
* $( "#myTextArea" ).idleTimer({
* timeout:10000,
* idle:true
* });
* });
* ```
*
* @param options The options for this idle timer. Any options not specified explicitly are set to their default
* values.
* @param element Element to watch, defaults to the document.
* @param id Unique ID for this idle timer, to support multiple timers on the same page.
* @return this JQuery instance for chaining.
*/
idleTimer(options: Partial<JQueryIdleTimer.IdleTimerOptions>, element?: Document | HTMLElement, id?: string): this;
/**
* Stop the timer, removes data, removes event bindings to come back from this you will need to instantiate again.
*
* @param method The method to be invoked on this idle timer instance.
* @param element Element to watch, defaults to the document.
* @param id Unique ID for this idle timer, to support multiple timers on the same page.
* @return this JQuery instance for chaining.
*/
idleTimer(method: "destroy", element?: Document | HTMLElement, id?: string): this;
/**
* Saves the remaining time, and stops the timer.
*
* @param method The method to be invoked on this idle timer instance.
* @param element Element to watch, defaults to the document.
* @param id Unique ID for this idle timer, to support multiple timers on the same page.
* @return this JQuery instance for chaining.
*/
idleTimer(method: "pause", element?: Document | HTMLElement, id?: string): this;
/**
* Starts the timer with remaining time saved when `pause` was called.
*
* @param method The method to be invoked on this idle timer instance.
* @param element Element to watch, defaults to the document.
* @param id Unique ID for this idle timer, to support multiple timers on the same page.
* @return this JQuery instance for chaining.
*/
idleTimer(method: "resume", element?: Document | HTMLElement, id?: string): this;
/**
* Restore initial idle state, and restart the timer.
*
* @param method The method to be invoked on this idle timer instance.
* @param element Element to watch, defaults to the document.
* @param id Unique ID for this idle timer, to support multiple timers on the same page.
* @return this JQuery instance for chaining.
*/
idleTimer(method: "reset", element?: Document | HTMLElement, id?: string): this;
/**
* Get time left until idle. If currently idle, returns 0.
*
* @param method The method to be invoked on this idle timer instance.
* @param element Element to watch, defaults to the document.
* @param id Unique ID for this idle timer, to support multiple timers on the same page.
* @return The time in milliseconds until the user goes idle. If user is already idle, returns `0`.
*/
idleTimer(method: "getRemainingTime", element?: Document | HTMLElement, id?: string): number;
/**
* Get time elapsed since the user went idle or active.
* - If currently idle, how long the user has been idle.
* - If currently active, how long the user has been active.
*
* @param method The method to be invoked on this idle timer instance.
* @param element Element to watch, defaults to the document.
* @param id Unique ID for this idle timer, to support multiple timers on the same page.
* @return How long the user has been idle or active, in milliseconds.
*/
idleTimer(method: "getElapsedTime", element?: Document | HTMLElement, id?: string): number;
/**
* Get time the last `active.idleTimer` event was fired.
*
* @param method The method to be invoked on this idle timer instance.
* @param element Element to watch, defaults to the document.
* @param id Unique ID for this idle timer, to support multiple timers on the same page.
* @return A timestamp (milliseconds since 1 January 1970 UTC) for when the most recent time the user went from idle
* to active.
*/
idleTimer(method: "getLastActiveTime", element?: Document | HTMLElement, id?: string): number;
/**
* Get whether the user is currently idle.
*
* @param method The method to be invoked on this idle timer instance.
* @param element Element to watch, defaults to the document.
* @param id Unique ID for this idle timer, to support multiple timers on the same page.
* @return `true` if the user is currently idle, or `false` if the user is currently active.
*/
idleTimer(method: "isIdle", element?: Document | HTMLElement, id?: string): boolean;
}
/**
* Optional settings that can be specified when creating an idle timer.
*/
export interface IdleTimerOptions {
/**
* List of events that constitute an activity by the user. Defaults to
*
* ```
* mousemove keydown wheel DOMMouseScroll mousewheel mousedown touchstart touchmove MSPointerDown MSPointerMove
* ```
*/
events: string;
/**
* Indicates if the user is currently idle. Defaults to `false`.
*/
idle: boolean;
/**
* The timeout period in milliseconds. Defaults to `30000`.
*/
timeout: number;
/**
* If set, the use a local storage key to sync activity across browser tabs or windows.
*/
timerSyncId: string;
}
/**
* The event that is triggered when the user comes back.
*/
export interface ActiveEvent<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TDelegateTarget = any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TData = any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TCurrentTarget = any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TTarget = any
> extends JQuery.TriggeredEvent<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: "active";
}
/**
* The event that is triggered when the user goes idle.
*/
export interface IdleEvent<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TDelegateTarget = any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TData = any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TCurrentTarget = any,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TTarget = any
> extends JQuery.TriggeredEvent<TDelegateTarget, TData, TCurrentTarget, TTarget> {
type: "idle";
}
}
// Extend $.fn.* plugins
interface JQuery extends JQueryIdleTimer.IdleTimerMethods {
}
// Extend $.* static properties on the JQuery object
interface JQueryStatic extends JQueryIdleTimer.IdleTimerMethods {
}
// Extend available event types
declare namespace JQuery {
interface TypeToTriggeredEventMap<
TDelegateTarget,
TData,
TCurrentTarget,
TTarget
> {
/**
* Triggered by the {@link JQuery.idleTimer|jQuery Idle Timer plugin}.
*
* Fired when the user becomes active again.
*
* Usually receives the following additional arguments:
* - `elem` (JQuery): The element that the event was triggered on
* - `obj` (object): A copy of the internal data used by idleTimer
* - `triggerevent` (JQuery.TriggeredEvent): The initial event that triggered the element to become active.
*/
["active.idleTimer"]: JQueryIdleTimer.ActiveEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
/**
* Triggered by the {@link JQuery.idleTimer|jQuery Idle Timer plugin}.
*
* Fired when the user goes idle.
*
* Usually receives the following additional arguments:
* - `elem` (JQuery): The element that the event was triggered on.
* - `obj` (object): A copy of the internal data used by idleTimer.
*/
["idle.idleTimer"]: JQueryIdleTimer.IdleEvent<TDelegateTarget, TData, TCurrentTarget, TTarget>;
}
} | the_stack |
import React, { forwardRef, MutableRefObject } from "react";
import Season from "../../models/Season";
import MatchRankImage from "../MatchRankImage";
import HeroImage from "../HeroImage";
import RoleImage from "../RoleImage";
import TimeOfDayEmoji from "../TimeOfDayEmoji";
import DayOfWeekEmoji from "../DayOfWeekEmoji";
import "./MatchTableRow.css";
import Match from "../../models/Match";
import EditMatchButton from "./EditMatchButton";
import RoleCell from "./RoleCell";
import OptionsCell from "./OptionsCell";
import HideSmallCell from "./HideSmallCell";
import NoWrap from "./NoWrap";
import MatchNumberCell from "./MatchNumberCell";
import ResultCell from "./ResultCell";
import SRChangeCell from "./SRChangeCell";
import DarkenSRChange from "./DarkenSRChange";
import RankCell from "./RankCell";
import StreakCell from "./StreakCell";
import MapCell from "./MapCell";
import GroupCell from "./GroupCell";
import { Tooltip, CounterLabel, Box } from "@primer/components";
import GroupList from "./GroupList";
import BadActorLabel from "./BadActorLabel";
import CssTruncateTarget from "../CssTruncateTarget";
const capitalize = (str: string) => {
return str.charAt(0).toUpperCase() + str.substr(1);
};
const groupSizeDescription = (groupSize: number) => {
if (groupSize === 1) {
return "solo queue";
}
if (groupSize === 2) {
return "duo queue";
}
return `${groupSize}-stack`;
};
interface Props {
match: Match;
firstRankedMatchID?: string;
firstMatchWithRank?: Match;
isLast: boolean;
index: number;
priorMatches: Match[];
rankChanges: number[];
longestLossStreak: number;
longestWinStreak: number;
onEdit: (matchID: string) => void;
showBadActor: boolean;
showPlayOfTheGame: boolean;
showJoinedVoice: boolean;
showComment: boolean;
showDayTime: boolean;
showHeroes: boolean;
showGroup: boolean;
showRole: boolean;
theme: string;
}
// Define a type that allows a ForwardedRef object to be mutable
// to workaround a current limitation of TS:
// https://github.com/DefinitelyTyped/DefinitelyTyped/issues/31065#issuecomment-457650501).
type MutableForwardedRef<T> =
| MutableRefObject<T | null>
| ((ref: T | null) => void)
| null;
const MatchTableRow = (
{
isLast,
match,
firstRankedMatchID,
firstMatchWithRank,
rankChanges,
index,
priorMatches,
longestWinStreak,
longestLossStreak,
onEdit,
showBadActor,
showPlayOfTheGame,
showJoinedVoice,
showComment,
showDayTime,
showHeroes,
showGroup,
showRole,
theme
}: Props,
ref: MutableForwardedRef<HTMLTableRowElement>
) => {
const outerClass = () => {
let classes: string[] = [];
if (!isLast) {
classes = classes.concat(["match-row", "pb-2", "mb-2"]);
}
if (match.isPlacement) {
classes.push("match-placement-row");
if (typeof match.rank === "number") {
classes.push("match-last-placement-row");
}
} else if (firstRankedMatchID === match._id) {
classes.push("match-placement-log-row");
}
return classes.join(" ");
};
const throwerTooltip = () => {
const { allyThrower, enemyThrower } = match;
const tooltip = [];
if (allyThrower) {
tooltip.push("Thrower on my team");
}
if (enemyThrower) {
tooltip.push("Thrower on the enemy team");
}
return tooltip.join(" + ");
};
const leaverTooltip = () => {
const { allyLeaver, enemyLeaver } = match;
const tooltip = [];
if (allyLeaver) {
tooltip.push("Leaver on my team");
}
if (enemyLeaver) {
tooltip.push("Leaver on the enemy team");
}
return tooltip.join(" + ");
};
const cheaterTooltip = () => {
const { allyCheater, enemyCheater } = match;
const tooltip = [];
if (allyCheater) {
tooltip.push("Cheater on my team");
}
if (enemyCheater) {
tooltip.push("Cheater on the enemy team");
}
return tooltip.join(" + ");
};
const matchNumber = () => {
let totalPlacementMatches = priorMatches.filter(match => match.isPlacement)
.length;
if (totalPlacementMatches < 1 && firstMatchWithRank) {
totalPlacementMatches = 1;
}
if (match.isPlacement) {
if (match.season >= Season.roleQueueSeasonStart) {
const role = match.role;
const priorMatchesInRole = priorMatches.filter(
priorMatch => priorMatch.role === role
);
return `P${priorMatchesInRole.length + 1}`;
}
return `P${index + 1}`;
}
if (firstRankedMatchID === match._id && totalPlacementMatches === 1) {
return "P";
}
return index - totalPlacementMatches + 1;
};
const getPriorMatchesWithRank = () => {
if (match.season < Season.roleQueueSeasonStart) {
// no role queue
return priorMatches.filter(m => typeof m.rank === "number");
}
// role queue
return priorMatches.filter(
m => m.role === match.role && typeof m.rank === "number"
);
};
const getPriorRank = () => {
const matchesWithRank = getPriorMatchesWithRank();
const priorMatch = matchesWithRank[matchesWithRank.length - 1];
if (priorMatch) {
return priorMatch.rank;
}
};
const getPlacementRank = () => {
let placementMatches = [];
if (match.season < Season.roleQueueSeasonStart) {
// no role queue
placementMatches = priorMatches.filter(
m => m.isPlacement && typeof m.rank === "number"
);
} else {
// role queue
placementMatches = priorMatches.filter(
m =>
m.isPlacement && m.role === match.role && typeof m.rank === "number"
);
}
const lastPlacement = placementMatches[placementMatches.length - 1];
if (lastPlacement) {
return lastPlacement.rank;
}
const matchesWithRank = getPriorMatchesWithRank();
const firstMatchWithRank = matchesWithRank[0];
if (firstMatchWithRank) {
return firstMatchWithRank.rank;
}
};
const editMatch = (
event: React.MouseEvent<HTMLButtonElement, MouseEvent>
) => {
const button = event.currentTarget;
const matchID = button.value;
button.blur();
onEdit(matchID);
};
const commentTooltip = () => {
const { comment } = match;
if (!comment) {
return;
}
return comment.trim().replace(/"/g, "'");
};
const {
rank,
_id,
groupList,
heroList,
comment,
playOfTheGame,
result,
allyThrower,
allyLeaver,
allyCheater,
enemyThrower,
enemyLeaver,
enemyCheater,
map,
role,
rankChange,
dayOfWeek,
timeOfDay,
groupSize,
joinedVoice
} = match;
const timeAndDayPresent =
dayOfWeek && timeOfDay && dayOfWeek.length > 0 && timeOfDay.length > 0;
const isWin = match.isWin();
const isLoss = match.isLoss();
const priorRank = getPriorRank();
const placementRank = getPlacementRank();
const betterThanPlacement =
typeof placementRank === "number"
? typeof match.rank === "number" && placementRank <= match.rank
: undefined;
return (
<tr className={outerClass()} ref={ref}>
<MatchNumberCell isPlacement={match.isPlacement}>
{matchNumber()}
</MatchNumberCell>
{showRole && role && (
<RoleCell isPlacement={match.isPlacement}>
<RoleImage role={role} theme={theme} />
</RoleCell>
)}
<ResultCell result={result} theme={theme}>
{result ? result.charAt(0).toUpperCase() : <span>—</span>}
</ResultCell>
<SRChangeCell
rankChanges={rankChanges}
theme={theme}
result={match.result}
isPlacement={match.isPlacement}
rankChange={match.rankChange}
>
{typeof rankChange === "number" && (
<DarkenSRChange result={match.result} />
)}
{typeof rankChange === "number" ? (
<span style={{ position: "relative" }}>{rankChange}</span>
) : (
<span>—</span>
)}
</SRChangeCell>
<RankCell
isPlacement={match.isPlacement}
theme={theme}
betterThanPlacement={betterThanPlacement}
>
<div className="d-flex flex-items-center flex-justify-center">
{typeof rank === "number" && (
<MatchRankImage
rank={rank}
priorRank={priorRank}
className="d-inline-block mr-1 hide-sm"
/>
)}
{typeof rank === "number" ? rank : <span>—</span>}
</div>
</RankCell>
<StreakCell
result={match.result}
longestWinStreak={longestWinStreak}
longestLossStreak={longestLossStreak}
isPlacement={match.isPlacement}
winStreak={match.winStreak}
lossStreak={match.lossStreak}
>
{isWin || isLoss ? <DarkenSRChange result={match.result} /> : null}
{isWin ? (
<span style={{ position: "relative" }}>{match.winStreak}</span>
) : isLoss ? (
<span style={{ position: "relative" }}>{match.lossStreak}</span>
) : null}
</StreakCell>
<MapCell map={match.map}>
<NoWrap>{map}</NoWrap>
</MapCell>
{showComment && (
<HideSmallCell isPlacement={match.isPlacement}>
<Tooltip aria-label={commentTooltip()} wrap={true}>
<CssTruncateTarget>{comment}</CssTruncateTarget>
</Tooltip>
</HideSmallCell>
)}
{showHeroes && (
<HideSmallCell
style={{ paddingBottom: 0 }}
isPlacement={match.isPlacement}
>
{heroList.map(hero => (
<span
key={hero}
className="tooltipped tooltipped-n d-inline-block hero-portrait-container"
aria-label={hero}
>
<HeroImage hero={hero} className="rounded-1 d-inline-block" />
</span>
))}
</HideSmallCell>
)}
{showDayTime && (
<HideSmallCell isPlacement={match.isPlacement}>
{timeAndDayPresent && dayOfWeek && timeOfDay && (
<div
className="tooltipped tooltipped-n"
aria-label={`${capitalize(dayOfWeek)} ${capitalize(timeOfDay)}`}
>
<DayOfWeekEmoji dayOfWeek={dayOfWeek} />
<span> </span>
<TimeOfDayEmoji timeOfDay={timeOfDay} />
</div>
)}
</HideSmallCell>
)}
{showGroup && (
<GroupCell isPlacement={match.isPlacement}>
{groupList.length > 0 && (
<Tooltip aria-label={groupList.join(", ")} wrap={true}>
<GroupList>{groupList.join(", ")} </GroupList>
</Tooltip>
)}
{typeof groupSize === "number" &&
groupList.length + 1 !== groupSize && (
<CounterLabel>{groupSizeDescription(groupSize)}</CounterLabel>
)}
</GroupCell>
)}
{showBadActor && (
<HideSmallCell isPlacement={match.isPlacement}>
<NoWrap>
{(allyThrower || enemyThrower) && (
<BadActorLabel>
<Tooltip aria-label={throwerTooltip()} wrap={true}>
T
</Tooltip>
</BadActorLabel>
)}
{(allyLeaver || enemyLeaver) && (
<BadActorLabel>
<Tooltip aria-label={leaverTooltip()} wrap={true}>
L
</Tooltip>
</BadActorLabel>
)}
{(allyCheater || enemyCheater) && (
<BadActorLabel>
<Tooltip aria-label={cheaterTooltip()} wrap={true}>
C
</Tooltip>
</BadActorLabel>
)}
</NoWrap>
</HideSmallCell>
)}
{(showPlayOfTheGame || showJoinedVoice) && (
<HideSmallCell isPlacement={match.isPlacement}>
{playOfTheGame && (
<Tooltip aria-label="Play of the game">
<Box
display={showJoinedVoice ? "inline-block" : "inline"}
mr={showJoinedVoice ? 2 : 0}
>
<span role="img" aria-label="Party">
🎉
</span>
</Box>
</Tooltip>
)}
{joinedVoice && (
<Tooltip aria-label="Joined voice chat">
<span role="img" aria-label="Speaker">
🔊
</span>
</Tooltip>
)}
</HideSmallCell>
)}
<OptionsCell>
<EditMatchButton onClick={editMatch} value={_id}>
<Tooltip aria-label="Edit match" direction="w">
<span className="ion ion-md-create" />
</Tooltip>
</EditMatchButton>
</OptionsCell>
</tr>
);
};
export default forwardRef(MatchTableRow); | the_stack |
import * as THREE from 'three';
import { createMusicSource } from './music';
import { createSampleSource } from './sample';
import { createVoiceSource } from './voice';
import { getFrequency } from '../utils/lba';
import { getSample, getVoices } from '../resources';
declare global {
interface Window {
AudioContext?: any;
webkitAudioContext?: any;
}
}
const THEME_MENU = 'THEME_MENU';
let samples = {};
let samplesPerActor = {};
function createAudioContext() {
window.AudioContext = window.AudioContext || window.webkitAudioContext; // needed for Safari
return new AudioContext();
}
export function createAudioManager(state) {
const context = createAudioContext();
const menuContext = createAudioContext();
const isActive = (ctx: AudioContext) => ctx.state === 'running';
const musicSource = createMusicSource(context, state.config.musicVolume);
const menuMusicSource = createMusicSource(menuContext, state.config.musicVolume);
const voiceSource = createVoiceSource(context, state.config.voiceVolume);
let listener = null;
if (state.config.positionalAudio) {
// @ts-ignore
THREE.AudioContext.setContext(context);
listener = new THREE.AudioListener();
listener.setMasterVolume(state.config.soundFxVolume);
listener.rotateY(Math.PI);
}
let queuedMusic = -1;
return {
context,
menuContext,
listener,
dispose: () => {
context.close();
menuContext.close();
},
// music
// Named function to allow a recursive call.
playMusic: function f(index: number) {
menuMusicSource.stop();
if (!musicSource.isPlaying()) {
musicSource.play(index, () => {
if (queuedMusic !== -1) {
f(queuedMusic);
queuedMusic = -1;
}
});
}
},
queueMusic: (index: number) => {
// Corner case where we've walked out of the scene and back in again.
// In this case we don't want the music to play twice, and we want
// to throw away the previous index since we're not in that scene
// anymore.
if (musicSource.getPlaying() === index) {
queuedMusic = -1;
return;
}
queuedMusic = index;
},
getPlayingMusic: () => {
return musicSource.getPlaying();
},
playMusicTheme: () => {
if (!menuMusicSource.isPlaying()) {
menuMusicSource.play(THEME_MENU);
}
},
isPlayingMusic: () => {
return musicSource.isPlaying();
},
stopMusic: () => {
musicSource.stop();
},
stopMusicTheme: () => {
menuMusicSource.stop();
},
preloadMusicTheme: async () => {
await menuMusicSource.preload(THEME_MENU);
},
resumeMusicTheme: () => {
menuMusicSource.resume();
},
// samples
createSamplePositionalAudio: (): THREE.PositionalAudio => {
const sound = new THREE.PositionalAudio(listener);
// sound.setRolloffFactor(40);
// sound.setRefDistance(20);
// sound.setMaxDistance(10000);
sound.setVolume(1);
const filter = sound.context.createBiquadFilter();
filter.type = 'allpass';
sound.setFilter(filter);
return sound;
},
createSamplePositionalAudioDefault: (): THREE.PositionalAudio => {
const sound = new THREE.PositionalAudio(listener);
const filter = sound.context.createBiquadFilter();
filter.type = 'allpass';
sound.setFilter(filter);
return sound;
},
createSampleAudio: (): THREE.Audio => {
const sound = new THREE.Audio(listener);
sound.setVolume(1);
const filter = sound.context.createBiquadFilter();
filter.type = 'allpass';
sound.setFilter(filter);
return sound;
},
playSound: async (
sound: any,
index: number,
frequency: number = 0x1000,
loopCount: number = 0
) => {
const buffer = await getSample(index, context);
if (buffer) {
if (loopCount !== 0) {
sound.setLoop(true);
}
sound.setLoop(loopCount);
const lowPassFilter = sound.getFilters()[0];
lowPassFilter.frequency.value = getFrequency(frequency);
sound.setBuffer(buffer);
if (sound.isPlaying) {
sound.stop();
}
sound.play();
}
},
// @ts-ignore
stopSound: async (sound: any, index?: number) => {
if (sound.isPlaying) {
sound.stop();
}
// TODO find a way to treat multiple audio sources per actor
},
releaseSamples: () => {
Object.keys(samples).forEach((key) => {
samples[key].stop();
delete samples[key];
});
Object.keys(samplesPerActor).forEach((key) => {
Object.keys(samplesPerActor[key]).forEach((kk) => {
samplesPerActor[key][kk].stop();
delete samplesPerActor[key][kk];
});
delete samplesPerActor[key];
});
samples = {};
samplesPerActor = {};
},
// voice
playSoundVoice: async (
sound: any,
index: number,
textBankId: number,
onEndedCallback = null
) => {
const playVoiceSound = async (
sound2: any,
index2: number,
textBankId2: number,
onEndedCallback2 = null
) => {
// voiceSource.play(index, textBankId, onEndedCallback);
const resource = await getVoices(textBankId);
if (!resource) {
return;
}
const entryBuffer = await resource.getEntryAsync(index2);
try {
const buffer = await context.decodeAudioData(entryBuffer.slice(0));
if (buffer) {
sound2.setBuffer(buffer);
if (sound2.isPlaying) {
sound2.stop();
}
sound2.play();
sound2.source.onended = () => {
if (sound.isPlaying && resource.hasHiddenEntries(index)) {
playVoiceSound(
sound2,
resource.getNextHiddenEntry(index),
textBankId2,
onEndedCallback2
);
}
sound2.isPlaying = false;
if (onEndedCallback2) {
onEndedCallback2.call();
}
};
}
} catch (err) {
// tslint:disable-next-line: no-console max-line-length
console.error(`Failed to decode voice, index=${index}, textBankId=${textBankId}:`, err);
}
};
playVoiceSound(
sound,
index,
textBankId,
onEndedCallback
);
},
// voice
playVoice: (index: number, textBankId: number, onEndedCallback = null) => {
voiceSource.play(index, textBankId, onEndedCallback);
},
stopVoice: () => {
voiceSource.stop();
},
// invetory, ambience
playSample: (
index: number,
frequency: number = 0x1000,
loopCount: number = 0,
actorIndex: number = -1,
volume: number = state.config.soundFxVolume
) => {
const sampleSource = createSampleSource(context, volume);
sampleSource.play(index, frequency, loopCount);
samples[index] = sampleSource;
if (!samplesPerActor[actorIndex]) {
samplesPerActor[actorIndex] = {};
}
samplesPerActor[actorIndex][index] = sampleSource;
return sampleSource;
},
isPlayingSample: (index: number) => {
const sampleSource = samples[index];
if (sampleSource) {
return sampleSource.isPlaying();
}
return false;
},
isPlayingSampleForActor: (actorIndex: number, sampleIndex: number) => {
if (!samplesPerActor[actorIndex]) {
return false;
}
if (!samplesPerActor[actorIndex][sampleIndex]) {
return false;
}
return samplesPerActor[actorIndex][sampleIndex].isPlaying();
},
stopSample: (index: number) => {
const sampleSource = samples[index];
if (sampleSource) {
sampleSource.stop();
}
},
stopSamples: () => {
Object.keys(samples).forEach((index: string) => {
const sampleSource = samples[index];
if (sampleSource) {
sampleSource.stop();
}
});
},
stopSamplesForActor: (actorIndex: number) => {
if (!samplesPerActor[actorIndex])
return;
for (const sample in samplesPerActor[actorIndex]) {
samplesPerActor[actorIndex][sample].stop();
}
},
// shared
pause: () => {
context.suspend();
},
resume: () => {
context.resume();
},
resumeContext: () => {
if (!isActive(context)) {
context.resume();
}
if (!isActive(menuContext)) {
menuContext.resume();
}
},
isContextActive: () => {
return isActive(context) || isActive(menuContext);
}
};
} | the_stack |
import {
EarthConstants,
GeoCoordinates,
GeoPolygon,
GeoPolygonCoordinates,
isAntimeridianCrossing,
Projection,
ProjectionType
} from "@here/harp-geoutils";
import { assert } from "@here/harp-utils";
import { PerspectiveCamera, Vector2, Vector3 } from "three";
import { CanvasSide, nextCanvasSide, previousCanvasSide, SphereHorizon } from "./SphereHorizon";
import { MapViewUtils } from "./Utils";
import { ViewBounds } from "./ViewBounds";
// Rough, empirical rule to compute the number of divisions needed for a geopolygon edge to keep
// the deviation from the view bound edge it must follow within acceptable values.
export function computeEdgeDivisions(geoStart: GeoCoordinates, geoEnd: GeoCoordinates): number {
const maxLatitudeSpan = 20;
const maxLongitudeSpan = 5;
const latitudeSpan = Math.abs(geoEnd.latitude - geoStart.latitude);
const longitudeSpan = geoStart.minLongitudeSpanTo(geoEnd);
return Math.ceil(Math.max(latitudeSpan / maxLatitudeSpan, longitudeSpan / maxLongitudeSpan));
}
const ccwCanvasCornersNDC: Array<{ x: number; y: number }> = [
{ x: -1, y: -1 }, // bottom left
{ x: 1, y: -1 }, // bottom right
{ x: 1, y: 1 }, // top right
{ x: -1, y: 1 } // top left
];
/**
* Generates Bounds for a camera view and a spherical projection
*
* @internal
*/
export class SphereViewBounds implements ViewBounds {
constructor(readonly camera: PerspectiveCamera, readonly projection: Projection) {
assert(projection.type === ProjectionType.Spherical);
}
/**
* @override
*/
generate(): GeoPolygon | undefined {
const coordinates = this.findBoundsIntersections();
this.wrapAroundPoles(coordinates);
return coordinates.length > 2
? new GeoPolygon(coordinates as GeoPolygonCoordinates, false, true)
: undefined;
}
private addSideSegmentSubdivisions(
coordinates: GeoCoordinates[],
NDCStart: { x: number; y: number },
NDCEnd: { x: number; y: number },
geoStart: GeoCoordinates,
geoEnd: GeoCoordinates
) {
coordinates.push(geoStart);
const divisionCount = computeEdgeDivisions(geoStart, geoEnd);
if (divisionCount <= 1) {
return;
}
const NDCStep = new Vector2(NDCEnd.x - NDCStart.x, NDCEnd.y - NDCStart.y).multiplyScalar(
1 / divisionCount
);
const NDCDivision = new Vector2(NDCStart.x, NDCStart.y);
for (let i = 0; i < divisionCount - 1; i++) {
NDCDivision.add(NDCStep);
const intersection = MapViewUtils.rayCastWorldCoordinates(
{ camera: this.camera, projection: this.projection },
NDCDivision.x,
NDCDivision.y
);
if (intersection) {
coordinates.push(this.projection.unprojectPoint(intersection));
}
}
}
private addSideIntersections(
coordinates: GeoCoordinates[],
side: CanvasSide,
geoStartCorner?: GeoCoordinates,
geoEndCorner?: GeoCoordinates,
horizon?: SphereHorizon
) {
const startNDCCorner = ccwCanvasCornersNDC[side];
const endNDCCorner = ccwCanvasCornersNDC[nextCanvasSide(side)];
if (geoStartCorner && geoEndCorner) {
// No horizon visible on this side of the canvas, generate polygon vertices from
// intersections of the canvas side with the world.
this.addSideSegmentSubdivisions(
coordinates,
startNDCCorner,
endNDCCorner,
geoStartCorner,
geoEndCorner
);
return;
}
if (!horizon) {
return;
}
// Bounds on this side of the canvas need to be completed with the horizon.
const horizonIntersections = horizon.getSideIntersections(side);
if (horizonIntersections.length === 0) {
return;
}
if (geoStartCorner) {
// Generate polygon vertices from intersections of this canvas side with the world
// from its starting corner till the last intersection with the horizon.
const worldHorizonPoint = horizon.getPoint(
horizonIntersections[horizonIntersections.length - 1]
);
const geoHorizonPoint = this.projection.unprojectPoint(worldHorizonPoint);
this.addSideSegmentSubdivisions(
coordinates,
startNDCCorner,
worldHorizonPoint.project(this.camera),
geoStartCorner,
geoHorizonPoint
);
} else {
// Subdivide horizon from last horizon intersection on previous side to this side first.
const prevSide = previousCanvasSide(side);
let prevSideIntersections = horizon.getSideIntersections(prevSide);
if (prevSideIntersections.length === 0) {
// When bottom canvas side cuts the horizon above its center, right horizon
// tangent is not visible. Last horizon tangent is top one.
prevSideIntersections = horizon.getSideIntersections(previousCanvasSide(prevSide));
}
assert(prevSideIntersections.length > 0);
horizon.getDivisionPoints(
point => {
coordinates.push(this.projection.unprojectPoint(point));
},
prevSideIntersections[prevSideIntersections.length - 1],
horizonIntersections[0]
);
}
if (horizonIntersections.length > 1) {
// Subdivide side segment between two horizon intersections.
const worldHorizonStart = horizon.getPoint(horizonIntersections[0]);
const worldHorizonEnd = horizon.getPoint(horizonIntersections[1]);
const geoHorizonStart = this.projection.unprojectPoint(worldHorizonStart);
const geoHorizonEnd = this.projection.unprojectPoint(worldHorizonEnd);
this.addSideSegmentSubdivisions(
coordinates,
worldHorizonStart.project(this.camera),
worldHorizonEnd.project(this.camera),
geoHorizonStart,
geoHorizonEnd
);
}
if (geoEndCorner) {
// Subdivice side segment from last horizon intersection to the ending corner of this
// canvas side.
const worldHorizonPoint = horizon.getPoint(horizonIntersections[0]);
const geoHorizonPoint = this.projection.unprojectPoint(worldHorizonPoint);
this.addSideSegmentSubdivisions(
coordinates,
worldHorizonPoint.project(this.camera),
endNDCCorner,
geoHorizonPoint,
geoEndCorner
);
}
}
private findBoundsIntersections(): GeoCoordinates[] {
const coordinates: GeoCoordinates[] = [];
const [cornerCoordinates, numCorners] = this.addCanvasCornerIntersection();
// Horizon points need to be added to complete the bounds if not all canvas corners
// intersect with the world.
const horizon =
numCorners < 4
? new SphereHorizon(
this.camera,
cornerCoordinates.map(value => value !== undefined)
)
: undefined;
if (numCorners === 0 && horizon!.isFullyVisible) {
// Bounds are generated entirely from equidistant points obtained from the horizon
// circle.
horizon!.getDivisionPoints(point => {
coordinates.push(this.projection.unprojectPoint(point));
});
return coordinates;
}
for (let side = CanvasSide.Bottom; side < 4; side++) {
const startCorner = cornerCoordinates[side];
const endCorner = cornerCoordinates[nextCanvasSide(side)];
this.addSideIntersections(coordinates, side, startCorner, endCorner, horizon);
}
return coordinates;
}
private wrapAroundPoles(coordinates: GeoCoordinates[]) {
// If one of the poles is inside the view bounds, the polygon would have to cover the pole,
// which is not possible in geo space. Instead, additional vertices (numbered in order from
// 1 to 6 in the diagram below) are added to the polygon so that it wraps around the pole,
// covering the same area(except for the pole circle that cannot be mapped to geospace).
// The globe is cut in two hemispheres by the meridians at the camera longitude (camLon) and
// its antimeridian (at camLon+180). Then, the polygon side crossing the camera antimeridian
// is found, and the new pole wrapping vertices are inserted between its start and end
// vertices.
//
// (end) hem.crossing side (start)
// \|<-------------->|/
// x-------x------6!--------x--------x
// | , - ~5!1 ~ -, |
// | , ' ! ' , |
// | , ! , |
// | , ! , |
// | , ! , |
// | 4 POLE 2 | <- Bounds polygon
// | , ! , |
// | , ! , |
// | , ! , |
// | , ! ,' |
// | ' -_, _ ! _ ,_ -' |
// | 3 |
// x---------------!-----------------x
// ! <- hemisphere partition
const northPoleCenter = new Vector3(0, 0, EarthConstants.EQUATORIAL_RADIUS);
const southPoleCenter = new Vector3(0, 0, -EarthConstants.EQUATORIAL_RADIUS);
const northPoleInView = MapViewUtils.closeToFrustum(northPoleCenter, this.camera);
const southPoleInView = MapViewUtils.closeToFrustum(southPoleCenter, this.camera);
if (!northPoleInView && !southPoleInView) {
return;
}
// Create first wrapping vertex (number 1 in the diagram above).
const camLon = this.projection.unprojectPoint(this.camera.position).lng;
const wrapLat = northPoleInView ? 90 : -90;
const wrapLon = northPoleInView ? camLon + 180 : camLon - 180;
const geoWrapTopRight = new GeoCoordinates(wrapLat, wrapLon);
const geoWrapTopRightNorm = geoWrapTopRight.normalized();
// Find the polygon side crossing the camera antimeridian.
const crossLon = geoWrapTopRightNorm.lng;
let prevLon = coordinates[coordinates.length - 1].lng;
// Check whether the camera antimeridian crossing also crosses greenwich antimerdian.
let isGwAntimerCross = false;
const hSphereCrossEndIndex = coordinates.findIndex((value: GeoCoordinates) => {
const crossesAntimer = isAntimeridianCrossing(prevLon, value.lng);
const sameSign = Math.sign(crossLon - value.lng) === Math.sign(crossLon - prevLon);
if (sameSign === crossesAntimer) {
isGwAntimerCross = crossesAntimer;
return true;
}
prevLon = value.lng;
return false;
});
if (hSphereCrossEndIndex < 0) {
// No polygon side crosses the camera antimeridian, meaning that the polygon doesn't
// actually go above the pole to the other side of the world, no wrapping needed.
return;
}
// Create rest of wrapping vertices at pole's latitude (vertices 2-5 in diagram above).
const wrapSideOffset = northPoleInView ? 90 : -90;
const wrapCornerOffset = northPoleInView ? 0.00001 : -0.00001;
// Added to ensure antimeridian crossing detection when coordinates are wrapped around it by
// GeoPolygon (all polygon sides must have longitude spans smaller than 180 degrees).
const geoWrapRight = new GeoCoordinates(wrapLat, camLon + wrapSideOffset).normalized();
const geoWrapBottom = new GeoCoordinates(wrapLat, camLon).normalized();
// Added to ensure antimeridian crossing detection when coordinates are wrapped around it by
// GeoPolygon (all polygon sides must have longitude spans smaller than 180 degrees).
const geoWrapLeft = new GeoCoordinates(wrapLat, camLon - wrapSideOffset).normalized();
const geoWrapTopLeft = new GeoCoordinates(wrapLat, wrapLon + wrapCornerOffset).normalized();
const hSphereCrossStartIndex =
(hSphereCrossEndIndex + coordinates.length - 1) % coordinates.length;
const crossStart = coordinates[hSphereCrossStartIndex];
const crossEnd = coordinates[hSphereCrossEndIndex];
// Last wrapping vertex (number 6) is linearly interpolated at the polygon side crossing the
// camera antimeridian.
let crossLerp = GeoCoordinates.lerp(crossStart, crossEnd, 0.01, isGwAntimerCross);
if (isGwAntimerCross && northPoleInView) {
crossLerp.longitude -= 360;
} else {
crossLerp = crossLerp.normalized();
}
// Add the wrapping vertices to the array in the proper order (see diagram above).
coordinates.splice(
hSphereCrossEndIndex,
0,
wrapLon < -180 ? geoWrapTopRight : geoWrapTopRightNorm, // 1
geoWrapRight, // 2
geoWrapBottom, // 3
geoWrapLeft, // 4
geoWrapTopLeft, // 5
crossLerp // 6
);
}
// Returns a tuple with the array of canvas corner intersection geocoordinates in ccw order
// (undefined values for corners not intersecting the world) and the number of intersections.
private addCanvasCornerIntersection(): [Array<GeoCoordinates | undefined>, number] {
const geoCorners = new Array<GeoCoordinates | undefined>();
let numIntersections = 0;
ccwCanvasCornersNDC.forEach(corner => {
const intersection = MapViewUtils.rayCastWorldCoordinates(
{ camera: this.camera, projection: this.projection },
corner.x,
corner.y
);
if (intersection) {
geoCorners.push(this.projection.unprojectPoint(intersection));
++numIntersections;
} else {
geoCorners.push(undefined);
}
});
return [geoCorners, numIntersections];
}
} | the_stack |
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
Inject,
Input,
LOCALE_ID,
OnChanges,
OnInit,
Output,
SimpleChanges,
ViewChild,
} from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { convertToBoolProperty, NbBooleanInput } from '../helpers';
import { NbPortalDirective } from '../cdk/overlay/mapping';
import { NbPlatform } from '../cdk/platform/platform-service';
import { NbDateService, NbDayPeriod } from '../calendar-kit/services/date.service';
import { range, rangeFromTo } from '../calendar-kit/helpers';
import { NbCalendarTimeModelService } from '../calendar-kit/services/calendar-time-model.service';
import {
NB_DEFAULT_TIMEPICKER_LOCALIZATION_CONFIG,
NB_TIME_PICKER_CONFIG,
NbSelectedTimePayload,
NbTimePickerConfig,
} from './model';
interface NbTimePartOption {
value: number,
text: string,
}
/**
* The TimePicker components itself.
* Provides a proxy to `TimePicker` options as well as custom picker options.
*/
@Component({
selector: 'nb-timepicker',
templateUrl: './timepicker.component.html',
styleUrls: ['./timepicker.component.scss'],
exportAs: 'nbTimepicker',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class NbTimePickerComponent<D> implements OnChanges, OnInit {
protected blur$: Subject<void> = new Subject<void>();
fullTimeOptions: D[];
hoursColumnOptions: NbTimePartOption[];
minutesColumnOptions: NbTimePartOption[];
secondsColumnOptions: NbTimePartOption[];
readonly dayPeriodColumnOptions = [ NbDayPeriod.AM, NbDayPeriod.PM ];
hostRef: ElementRef;
isAM = true;
/**
* Emits when timepicker looses focus.
*/
get blur(): Observable<void> {
return this.blur$.asObservable();
}
/**
* Defines time format string.
* */
@Input()
get timeFormat(): string {
return this._timeFormat;
}
set timeFormat(timeFormat: string) {
this._timeFormat = timeFormat;
}
protected _timeFormat: string;
/**
* Defines 12 hours format .
* */
@Input()
get twelveHoursFormat(): boolean {
return this._twelveHoursFormat;
}
set twelveHoursFormat(value: boolean) {
this._twelveHoursFormat = convertToBoolProperty(value);
};
protected _twelveHoursFormat: boolean;
static ngAcceptInputType_twelveHoursFormat: NbBooleanInput;
/**
* Show seconds in timepicker.
* Ignored when singleColumn is true
* */
@Input()
get withSeconds(): boolean {
return this._withSeconds;
}
set withSeconds(value: boolean) {
this._withSeconds = convertToBoolProperty(value);
};
protected _withSeconds: boolean;
static ngAcceptInputType_withSeconds: NbBooleanInput;
/**
* Show timepicker values in one column with 60 minutes step by default.
* */
@Input()
get singleColumn(): boolean {
return this._singleColumn;
}
set singleColumn(value: boolean) {
this._singleColumn = convertToBoolProperty(value);
}
_singleColumn: boolean;
static ngAcceptInputType_singleColumn: NbBooleanInput;
/**
* Defines minutes offset for options, when timepicker is in single column mode.
* By default it’s 60 minutes: '12:00, 13:00: 14:00, 15:00...'
* */
@Input()
set step(step: number) {
this._step = step;
}
get step(): number {
return this._step;
}
protected _step: number;
/**
* Date which will be rendered as selected.
* */
@Input()
set date(date: D) {
this._date = date;
this.isAM = this.dateService.getDayPeriod(this.date) === NbDayPeriod.AM;
this.buildColumnOptions();
this.cd.markForCheck();
}
get date(): D {
return this._date;
}
_date: D;
/**
* In timepicker value should be always true
* In calendar-with-time.component should set to false
* @docs-private
*/
@Input() showFooter: boolean = true;
@Input() applyButtonText: string;
@Input() hoursText: string;
@Input() minutesText: string;
@Input() secondsText: string;
@Input() ampmText: string;
@Input() currentTimeButtonText: string;
/**
* Emits date when selected.
* */
@Output() onSelectTime: EventEmitter<NbSelectedTimePayload<D>> = new EventEmitter<NbSelectedTimePayload<D>>();
@ViewChild(NbPortalDirective, {static: true}) portal: NbPortalDirective;
constructor(@Inject(NB_TIME_PICKER_CONFIG) protected config: NbTimePickerConfig,
protected platformService: NbPlatform,
@Inject(LOCALE_ID) locale: string,
public cd: ChangeDetectorRef,
protected calendarTimeModelService: NbCalendarTimeModelService<D>,
protected dateService: NbDateService<D>) {
this.initFromConfig(this.config);
}
ngOnInit(): void {
this.timeFormat = this.setupTimeFormat();
}
ngOnChanges({
step,
twelveHoursFormat,
withSeconds,
singleColumn,
}: SimpleChanges): void {
this.timeFormat = this.setupTimeFormat();
const isConfigChanged = step || twelveHoursFormat || withSeconds || singleColumn;
if (isConfigChanged || !this.fullTimeOptions) {
this.buildColumnOptions();
}
}
setHost(hostRef: ElementRef): void {
this.hostRef = hostRef;
}
attach(hostRef: ElementRef): void {
this.hostRef = hostRef;
}
setCurrentTime(): void {
this.date = this.dateService.today();
this.onSelectTime.emit({
time: this.date,
save: true,
});
}
setHour(value: number): void {
this.updateValue(this.dateService.setHours(this.date, value));
}
setMinute(value: number): void {
this.updateValue(this.dateService.setMinutes(this.date, value));
}
setSecond(value: number): void {
this.updateValue(this.dateService.setSeconds(this.date, value));
}
selectFullTime(value: D): void {
this.updateValue(value);
}
changeDayPeriod(dayPeriodToSet: NbDayPeriod): void {
if (this.dateService.getDayPeriod(this.date) === dayPeriodToSet) {
return;
}
// Subtract hours when switching to AM (before midday, 0-11 in 24-hour) from PM (after midday, 12-24 in 24-hour),
// otherwise add hours because switching to PM from AM.
const direction = dayPeriodToSet === NbDayPeriod.AM ? -1 : 1;
const increment = direction * this.dateService.HOURS_IN_DAY_PERIOD;
this.updateValue(this.dateService.addHours(this.date, increment));
}
updateValue(date: D): void {
this.onSelectTime.emit({time: date});
}
saveValue(): void {
this.onSelectTime.emit({
time: this.date,
save: true,
});
}
trackByTimeValues(index, item: NbTimePartOption): number {
return item.value;
}
trackBySingleColumnValue(index, item: D) {
return this.dateService.valueOf(item);
}
trackByDayPeriod(index, item: NbDayPeriod): string {
return item;
}
showSeconds(): boolean {
return this.withSeconds && !this.singleColumn;
}
isSelectedHour(val: number): boolean {
if (this.date) {
return this.dateService.getHours(this.date) === val;
}
return false;
}
isSelectedMinute(val: number): boolean {
if (this.date) {
return this.dateService.getMinutes(this.date) === val;
}
return false;
}
isSelectedSecond(val: number): boolean {
if (this.date) {
return this.dateService.getSeconds(this.date) === val;
}
return false;
}
isSelectedDayPeriod(dayPeriod: NbDayPeriod): boolean {
if (this.date) {
return dayPeriod === this.dateService.getDayPeriod(this.date);
}
return false;
}
getFullTimeString(item: D): string {
return this.dateService.format(item, this.timeFormat).toUpperCase();
}
isSelectedFullTimeValue(value: D): boolean {
if (this.date) {
return this.dateService.isSameHourAndMinute(value, this.date);
}
return false;
}
protected buildColumnOptions(): void {
this.timeFormat = this.setupTimeFormat();
this.fullTimeOptions = this.singleColumn
? this.calendarTimeModelService.getHoursRange(this.step)
: [];
this.hoursColumnOptions = this.generateHours();
this.minutesColumnOptions = this.generateMinutesOrSeconds();
this.secondsColumnOptions = this.withSeconds ? this.generateMinutesOrSeconds() : [];
}
/**
* @docs-private
*/
isFirefox(): boolean {
return this.platformService.FIREFOX;
}
protected generateHours(): NbTimePartOption[] {
if (!this.twelveHoursFormat) {
return range(24, (v: number) => {
return {value: v, text: this.calendarTimeModelService.paddToTwoSymbols(v)};
});
}
if (this.isAM) {
return (range(12, (v: number) => {
const text = v === 0 ? 12 : v;
return {value: v, text: this.calendarTimeModelService.paddToTwoSymbols(text)}
}));
}
return (rangeFromTo(12, 24, (v: number) => {
const text = v === 12 ? 12 : (v - 12);
return {value: v, text: this.calendarTimeModelService.paddToTwoSymbols(text)}
}));
}
protected generateMinutesOrSeconds(): NbTimePartOption[] {
return range(60, (v: number) => {
return {value: v, text: this.calendarTimeModelService.paddToTwoSymbols(v)};
});
}
protected setupTimeFormat(): string {
if (!this.timeFormat) {
return this.config.format || this.buildTimeFormat();
}
return this.timeFormat;
}
/**
* @docs-private
*/
buildTimeFormat(): string {
if (this.twelveHoursFormat) {
return `${this.withSeconds && !this.singleColumn ? this.dateService.getTwelveHoursFormatWithSeconds()
: this.dateService.getTwelveHoursFormat()}`;
} else {
return `${this.withSeconds && !this.singleColumn ? this.dateService.getTwentyFourHoursFormatWithSeconds()
: this.dateService.getTwentyFourHoursFormat()}`;
}
}
protected initFromConfig(config: NbTimePickerConfig) {
if (config) {
this.twelveHoursFormat = config.twelveHoursFormat;
} else {
this.twelveHoursFormat = this.dateService.getLocaleTimeFormat().includes('h');
}
const localeConfig = { ...NB_DEFAULT_TIMEPICKER_LOCALIZATION_CONFIG, ...config?.localization ?? {} };
this.hoursText = localeConfig.hoursText;
this.minutesText = localeConfig.minutesText;
this.secondsText = localeConfig.secondsText;
this.ampmText = localeConfig.ampmText;
}
} | the_stack |
import * as querystring from 'querystring'
import * as fse from 'fs-extra'
import * as path from 'path'
import * as url from 'url'
import utils from './index'
const bundleWrapper = (code, sourceUrl) => {
const injectedGlobals = [
// ES
'Promise',
// W3C
'window',
'weex',
'service',
'Rax',
'services',
'global',
'screen',
'document',
'navigator',
'location',
'fetch',
'Headers',
'Response',
'Request',
'URL',
'URLSearchParams',
'setTimeout',
'clearTimeout',
'setInterval',
'clearInterval',
'requestAnimationFrame',
'cancelAnimationFrame',
'alert',
// ModuleJS
'define',
'require',
// Weex
'bootstrap',
'register',
'render',
'__d',
'__r',
'__DEV__',
'__weex_define__',
'__weex_require__',
'__weex_viewmodel__',
'__weex_document__',
'__weex_bootstrap__',
'__weex_options__',
'__weex_data__',
'__weex_downgrade__',
'__weex_require_module__',
'Vue',
]
const bundlewrapper = 'function __weex_bundle_entry__(' + injectedGlobals.join(',') + '){'
const rearRegexp = /\/\/#\s*sourceMappingURL(?!.*?\s+.)|$/
const match = /^\/\/\s?{\s?"framework"\s?:\s?"(\w+)"\s?}/.exec(code)
let anno = ''
if (match) {
anno = '$$frameworkFlag["' + (sourceUrl || '@') + '"]="' + match[1] + '"\n'
}
return anno + bundlewrapper + code.replace(rearRegexp, '}\n$&')
}
const transformUrlToLocalUrl = sourceURl => {
const rHttpHeader = /^(https?|taobao|qap):\/\/(?!.*your_current_ip)/i
let bundleUrl
if (rHttpHeader.test(sourceURl)) {
const query = querystring.parse(url.parse(sourceURl).query)
if (query['_wx_tpl']) {
bundleUrl = utils.url.normalize(query['_wx_tpl']).replace(rHttpHeader, '')
} else {
bundleUrl = utils.url.normalize(sourceURl).replace(rHttpHeader, '')
}
} else {
bundleUrl = sourceURl.replace(/^(https?|taobao|qap):\/\/(.*your_current_ip):(\d+)\//i, 'file://')
}
if (bundleUrl.charAt(bundleUrl.length - 1) === '?') {
bundleUrl = bundleUrl.substring(0, bundleUrl.length - 1)
}
if (bundleUrl.charAt(bundleUrl.length - 1) === '?') {
bundleUrl = bundleUrl.substring(0, bundleUrl.length - 1)
}
return '/source/' + bundleUrl
}
const eventConstructor = `// event constructor
function __EventEmitter__() {
this._handlers = {};
}
__EventEmitter__.prototype = {
constructor: __EventEmitter__,
off: function (method, handler) {
if (handler) {
for (var i = 0; i < this._handlers[method].length; i++) {
if (this._handlers[method][i] === handler) {
this._handlers[method].splice(i, 1);
i--;
}
}
}
else {
this._handlers[method] = [];
}
},
once: function (method, handler) {
var self = this;
var fired = false;
function g() {
self.off(method, g);
if (!fired) {
fired = true;
handler.apply(self, Array.prototype.slice.call(arguments));
}
}
this.on(method, g);
},
on: function (method, handler) {
if (this._handlers[method]) {
this._handlers[method].push(handler);
}
else {
this._handlers[method] = [handler];
}
},
_emit: function (method, args, context) {
var handlers = this._handlers[method];
if (handlers && handlers.length > 0) {
handlers.forEach(function (handler) {
handler.apply(context, args)
});
return true;
}
else {
return false;
}
},
emit: function (method) {
var context = {};
var args = Array.prototype.slice.call(arguments, 1);
if (!this._emit(method, args, context)) {
this._emit('*', args, context)
}
this._emit('$finally', args, context);
return context;
}
};`
const mockContextApi = `// Redefine the JSFramework API
var __syncRequest__ = function(data, channelId) {
var request = new XMLHttpRequest();
request.open("POST", \`/syncCallNative/$\{channelId}\`, false); // "false" makes the request synchronous
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.send(JSON.stringify(data));
if (request.status === 200) {
return JSON.parse(request.responseText);
} else {
return {
error: request.responseText
};
}
};
self.callNativeModule = function () {
var message = {
method: 'WxDebug.syncCall',
params: {
method: 'callNativeModule',
args: __protectedAragument__(arguments)
}
}
var result = __syncRequest__(message, __channelId__);
if (result && result.error) {
self.console.error(result.error);
// throw new Error(result.error);
}
else {
return result && result.ret
};
}
self.callNativeComponent = function () {
var args = Array.prototype.slice.call(arguments);
for (var i = 0; i < args.length; i++) {
if (!args[i]) {
args[i] = ''
}
}
var message = {
method: 'WxDebug.syncCall',
params: {
method: 'callNativeComponent',
args: args
}
}
var result = __syncRequest__(message, __channelId__);
if (result.error) {
self.console.error(result.error);
// throw new Error(result.error);
}
else {
return result.ret;
};
};
self.callNative = function (instance, tasks, callback) {
for (var i = 0; i < tasks.length; i++) {
var task = tasks[i];
if (task.method == 'addElement') {
for (var key in task.args[1].style) {
if (Number.isNaN(task.args[1].style[key])) {
self.console.error('invalid value [NaN] for style [' + key + ']', task);
}
}
}
}
var payload = {
method: 'WxDebug.callNative',
params: {
instance: instance,
tasks: tasks,
callback: callback
}
};
__postData__(payload);
};
self.callAddElement = function (instance, ref, dom, index, callback) {
var payload = {
method: 'WxDebug.callAddElement',
params: {
instance: instance,
ref: ref,
dom: dom,
index: index,
callback: callback
}
};
__postData__(payload);
};
self.__updateComponentData = function (instance, componentId, data) {
var payload = {
method: 'WxDebug.callUpdateComponentData',
params: {
instance: instance,
componentId: componentId + '',
data: data
}
};
__postData__(payload);
};
self.nativeLog = function (args) {
self.console.log(args)
};`
const generateSandboxWorkerEntry = env => {
const mockBrowserApi = `// Redefine navigator
Object.defineProperty(navigator, 'appCodeName', {
get: function() {
return '${env.device.name}';
}
});
Object.defineProperty(navigator, 'appName', {
get: function() {
return '${env.environment.WXEnvironment.appName}';
}
});
Object.defineProperty(navigator, 'appVersion', {
get: function() {
return '${env.environment.WXEnvironment.appVersion}';
}
});
Object.defineProperty(navigator, 'product', {
get: function() {
return '${env.device.name}';
}
});
Object.defineProperty(navigator, 'platform', {
get: function() {
return '${env.device.platform}';
}
});
Object.defineProperty(navigator, 'userAgent', {
get: function() {
return '${
env.device.platform === 'android'
? 'Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.114 Mobile Safari/537.36'
: 'Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25'
}';
}
});
// Redefine console
var __origConsole__ = this.console;
var __rewriteLog__ = function () {
var LEVELS = ['error', 'warn', 'info', 'log', 'debug'];
var backupConsole = {
error: __origConsole__.error,
warn: __origConsole__.warn,
info: __origConsole__.info,
log: __origConsole__.log,
debug: __origConsole__.debug
};
function resetConsole() {
self.console.error = backupConsole.error;
self.console.warn = backupConsole.warn;
self.console.info = backupConsole.info;
self.console.log = backupConsole.log;
self.console.debug = backupConsole.debug;
self.console.time = __origConsole__.time;
self.console.timeEnd = __origConsole__.timeEnd;
}
function noop() {}
return function (logLevel) {
resetConsole();
LEVELS.slice(LEVELS.indexOf(logLevel) + 1).forEach(function (level) {
self.console[level] = noop;
})
}
}();
// Redefine timer
var __cachedSetTimeout__ = this.setTimeout;
Object.defineProperty(this, 'setTimeout', {
get: function () {
return __cachedSetTimeout__;
},
set: function () {}
});
var __cachedSetInterval__ = this.setInterval;
Object.defineProperty(this, 'setInterval', {
get: function () {
return __cachedSetInterval__;
},
set: function () {}
});
var __cachedClearTimeout__ = this.clearTimeout;
Object.defineProperty(this, 'clearTimeout', {
get: function () {
return __cachedClearTimeout__;
},
set: function () {}
});
var __cachedClearInterval__ = this.clearInterval;
Object.defineProperty(this, 'clearInterval', {
get: function () {
return __cachedClearInterval__;
},
set: function () {}
});
// Redefine onmessage
var __eventEmitter__ = new __EventEmitter__();
var __postmessage__ = self.postMessage
self.addEventListener('message', function(message) {
__eventEmitter__.emit(message.data && message.data.method, message.data);
}, false);
`
const worker = fse.readFileSync(path.join(__dirname, '../../worker/sandbox_worker.js'))
const mockAndroidApi = env.isLayoutAndSandbox
? `self.callCreateBody = function (instance, domStr) {
if (!domStr) return;
var payload = {
method: 'WxDebug.callCreateBody',
params: {
instance: instance,
domStr: domStr
}
};
__postData__(payload);
};
self.callUpdateFinish = function (instance, tasks, callback) {
var payload = {
method: 'WxDebug.callUpdateFinish',
params: {
instance: instance,
tasks: tasks,
callback: callback
}
};
__postData__(payload);
};
self.callCreateFinish = function (instance) {
var payload = {
method: 'WxDebug.callCreateFinish',
params: {
instance: instance
}
};
__postData__(payload);
}
self.callRefreshFinish = function (instance, tasks, callback) {
var payload = {
method: 'WxDebug.callRefreshFinish',
params: {
instance: instance,
tasks: tasks,
callback: callback
}
};
__postData__(payload);
}
self.callUpdateAttrs = function (instance, ref, data) {
var payload = {
method: 'WxDebug.callUpdateAttrs',
params: {
instance: instance,
ref: ref,
data: data
}
};
__postData__(payload);
}
self.callUpdateStyle = function (instance, ref, data) {
var payload = {
method: 'WxDebug.callUpdateStyle',
params: {
instance: instance,
ref: ref,
data: data
}
};
__postData__(payload);
}
self.callRemoveElement = function (instance, ref) {
var payload = {
method: 'WxDebug.callRemoveElement',
params: {
instance: instance,
ref: ref
}
};
__postData__(payload);
}
self.callMoveElement = function (instance, ref, parentRef, index_str) {
var payload = {
method: 'WxDebug.callMoveElement',
params: {
instance: instance,
ref: ref,
parentRef: parentRef,
index_str: index_str
}
};
__postData__(payload);;
}
self.callAddEvent = function (instance, ref, event) {
var payload = {
method: 'WxDebug.callAddEvent',
params: {
instance: instance,
ref: ref,
event: event
}
};
__postData__(payload);
}
self.callRemoveEvent = function (instance, ref, event) {
var payload = {
method: 'WxDebug.callRemoveEvent',
params: {
instance: instance,
ref: ref,
event: event
}
};
__postData__(payload);
}
`
: ''
let environment = `${eventConstructor}
${mockBrowserApi}
${mockContextApi}
${mockAndroidApi}
`
if (env.jsframework) {
environment += `importScripts('${env.jsframework}');\n`
}
return `${environment}
${worker}
`
}
const generateWorkerEntry = env => {
const mockBrowserApi = `// Redefine navigator
Object.defineProperty(navigator, 'appCodeName', {
get: function() {
return '${env.device.name}';
}
});
Object.defineProperty(navigator, 'appName', {
get: function() {
return '${env.environment.WXEnvironment.appName}';
}
});
Object.defineProperty(navigator, 'appVersion', {
get: function() {
return '${env.environment.WXEnvironment.appVersion}';
}
});
Object.defineProperty(navigator, 'product', {
get: function() {
return '${env.device.name}';
}
});
Object.defineProperty(navigator, 'platform', {
get: function() {
return '${env.device.platform}';
}
});
Object.defineProperty(navigator, 'userAgent', {
get: function() {
return '${
env.device.platform === 'android'
? 'Mozilla/5.0 (Linux; Android 4.4.2; Nexus 4 Build/KOT49H) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.114 Mobile Safari/537.36'
: 'Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25'
}';
}
});
// Redefine console
var __origConsole__ = this.console;
var __rewriteLog__ = function () {
var LEVELS = ['error', 'warn', 'info', 'log', 'debug'];
var backupConsole = {
error: __origConsole__.error,
warn: __origConsole__.warn,
info: __origConsole__.info,
log: __origConsole__.log,
debug: __origConsole__.debug
};
function resetConsole() {
self.console.error = backupConsole.error;
self.console.warn = backupConsole.warn;
self.console.info = backupConsole.info;
self.console.log = backupConsole.log;
self.console.debug = backupConsole.debug;
self.console.time = __origConsole__.time;
self.console.timeEnd = __origConsole__.timeEnd;
}
function noop() {}
return function (logLevel) {
resetConsole();
LEVELS.slice(LEVELS.indexOf(logLevel) + 1).forEach(function (level) {
self.console[level] = noop;
})
}
}();
// Redefine timer
var __cachedSetTimeout__ = this.setTimeout;
Object.defineProperty(this, 'setTimeout', {
get: function () {
return __cachedSetTimeout__;
},
set: function () {}
});
var __cachedSetInterval__ = this.setInterval;
Object.defineProperty(this, 'setInterval', {
get: function () {
return __cachedSetInterval__;
},
set: function () {}
});
var __cachedClearTimeout__ = this.clearTimeout;
Object.defineProperty(this, 'clearTimeout', {
get: function () {
return __cachedClearTimeout__;
},
set: function () {}
});
var __cachedClearInterval__ = this.clearInterval;
Object.defineProperty(this, 'clearInterval', {
get: function () {
return __cachedClearInterval__;
},
set: function () {}
});
// Redefine onmessage
var __eventEmitter__ = new __EventEmitter__();
var __postmessage__ = self.postMessage
self.addEventListener('message', function(message) {
__eventEmitter__.emit(message.data && message.data.method, message.data);
}, false);
`
const worker = fse.readFileSync(path.join(__dirname, '../../worker/worker.js'))
const androidMockApi = env.isLayoutAndSandbox
? `self.callCreateBody = function (instance, domStr) {
if (!domStr) return;
var payload = {
method: 'WxDebug.callCreateBody',
params: {
instance: instance,
domStr: domStr
}
};
__postData__(payload);
};
self.callUpdateFinish = function (instance, tasks, callback) {
var payload = {
method: 'WxDebug.callUpdateFinish',
params: {
instance: instance,
tasks: tasks,
callback: callback
}
};
__postData__(payload);
};
self.callCreateFinish = function (instance) {
var payload = {
method: 'WxDebug.callCreateFinish',
params: {
instance: instance
}
};
__postData__(payload);
}
self.callRefreshFinish = function (instance, tasks, callback) {
var payload = {
method: 'WxDebug.callRefreshFinish',
params: {
instance: instance,
tasks: tasks,
callback: callback
}
};
__postData__(payload);
}
self.callUpdateAttrs = function (instance, ref, data) {
var payload = {
method: 'WxDebug.callUpdateAttrs',
params: {
instance: instance,
ref: ref,
data: data
}
};
__postData__(payload);
}
self.callUpdateStyle = function (instance, ref, data) {
var payload = {
method: 'WxDebug.callUpdateStyle',
params: {
instance: instance,
ref: ref,
data: data
}
};
__postData__(payload);
}
self.callRemoveElement = function (instance, ref) {
var payload = {
method: 'WxDebug.callRemoveElement',
params: {
instance: instance,
ref: ref
}
};
__postData__(payload);
}
self.callMoveElement = function (instance, ref, parentRef, index_str) {
var payload = {
method: 'WxDebug.callMoveElement',
params: {
instance: instance,
ref: ref,
parentRef: parentRef,
index_str: index_str
}
};
__postData__(payload);;
}
self.callAddEvent = function (instance, ref, event) {
var payload = {
method: 'WxDebug.callAddEvent',
params: {
instance: instance,
ref: ref,
event: event
}
};
__postData__(payload);
}
self.callRemoveEvent = function (instance, ref, event) {
var payload = {
method: 'WxDebug.callRemoveEvent',
params: {
instance: instance,
ref: ref,
event: event
}
};
__postData__(payload);
}`
: ''
let environment = `${eventConstructor}
${mockBrowserApi}
${mockContextApi}
${androidMockApi}
self.$$frameworkFlag = {};
`
if (env.jsframework) {
environment += `importScripts('${env.jsframework}');\n`
// environment += `importScripts('/lib/runtime/js-framework.js');\n`
}
if (env.importScripts && env.importScripts.length > 0) {
env.importScripts.forEach(script => {
environment += `importScripts('${script}');\n`
})
}
if (env.sourceUrl) {
environment += `importScripts('${env.sourceUrl}');\n`
}
return `
${environment}
${worker}
`
}
const pickDomain = str => {
if (/file:\/\//.test(str)) {
return str.replace('file://', '')
}
if (/http(s)?/.test(str)) {
return url.parse(str).hostname
}
}
export default {
bundleWrapper,
transformUrlToLocalUrl,
generateSandboxWorkerEntry,
generateWorkerEntry,
pickDomain,
} | the_stack |
import {memory, ones, scalar, Tensor, zeros} from '@tensorflow/tfjs-core';
import * as tfl from '../index';
import {Kwargs} from '../types';
import {describeMathCPUAndGPU, expectTensorsClose} from '../utils/test_utils';
import {Container, ContainerArgs} from './container';
import {execute, FeedDict} from './executor';
import {CallHook, getSourceInputs, Layer, LayerArgs, SymbolicTensor} from './topology';
class LayerForTest extends tfl.layers.Layer {
static className = 'LayerForTest';
constructor(args: LayerArgs) {
super(args);
}
}
class ContainerForTest extends Container {
static className = 'ContainerForTest';
constructor(args: ContainerArgs) {
super(args);
}
}
describeMathCPUAndGPU('Container.fromConfig', () => {
it('creates a minimal Container from simplest config', () => {
// tslint:disable:no-any
const config = {
name: 'test',
layers: [] as any[],
inputLayers: [] as any[],
outputLayers: [] as any[]
};
// tslint:enable
const container =
Container.fromConfig(ContainerForTest, config) as Container;
expect(container.name).toEqual('test');
});
it('creates a simple network', () => {
/* python generating code
a=Input(shape=(32,))
b=Dense(32)(a)
model = Container(inputs=a, outputs=b, name="test")
pprint.pprint(model.get_config())
*/
const config = {
inputLayers: [['input_2', 0, 0]],
layers: [
{
className: 'InputLayer',
config: {
batchInputShape: [null, 32],
dtype: 'float32',
name: 'input_2',
sparse: false
},
inboundNodes: [] as string[][],
name: 'input_2'
},
{
className: 'Dense',
config: {
activation: 'linear',
activityRegularizer: null as string,
biasConstraint: null as string,
biasInitializer: {className: 'Zeros', config: {}},
biasRegularizer: null as string,
kernelConstraint: null as string,
kernelInitializer: {
className: 'VarianceScaling',
config: {
distribution: 'uniform',
mode: 'fanAvg',
scale: 1.0,
seed: null as number
}
},
kernelRegularizer: null as string,
name: 'dense_2',
trainable: null as boolean,
units: 32,
use_bias: true
},
inboundNodes: [[['input_2', 0, 0, {}]]],
name: 'dense_2'
}
],
name: 'test',
outputLayers: [['dense_2', 0, 0]]
};
const container =
Container.fromConfig(ContainerForTest, config) as Container;
expect(container.name).toEqual('test');
const allZeros = zeros([1, 32]);
expectTensorsClose(container.apply(allZeros) as Tensor, allZeros);
});
});
describeMathCPUAndGPU('Container', () => {
const inputLayerName = 'inputLayerName';
const layerName = 'layerName';
const containerName = 'simpleContainer';
let inputTensor: tfl.SymbolicTensor;
let layer: Layer;
let output: tfl.SymbolicTensor;
let simpleContainer: Container;
beforeEach(() => {
inputTensor =
tfl.input({shape: [1], name: inputLayerName, dtype: 'float32'});
layer = new LayerForTest({name: layerName});
output = layer.apply(inputTensor) as tfl.SymbolicTensor;
simpleContainer = new ContainerForTest(
{inputs: [inputTensor], outputs: [output], name: containerName});
});
it('initializes with no inputs or outputs and a default name', () => {
const container = new ContainerForTest({inputs: [], outputs: []});
expect(container.name).toMatch(/^container.+$/);
});
it('initializes with no inputs or outputs and a given name', () => {
const name = 'xyz';
const container = new ContainerForTest({inputs: [], outputs: [], name});
expect(container.name).toMatch(name);
});
it('throws an exception if same input provided twice', () => {
const makeContainer = () => {
// tslint:disable-next-line:no-unused-expression
new ContainerForTest({inputs: [inputTensor, inputTensor], outputs: []});
};
expect(makeContainer).toThrowError(/inputs.*redundant/);
});
it('throws an exception if graph is disconnected', () => {
const makeContainer = () => {
// tslint:disable-next-line:no-unused-expression
new ContainerForTest({inputs: [], outputs: [output]});
};
expect(makeContainer).toThrowError(/disconnected/);
});
it('creates inputLayers', () => {
expect(simpleContainer.inputLayers).toEqual([inputTensor.sourceLayer]);
});
it('creates outputLayers', () => {
expect(simpleContainer.outputLayers).toEqual([layer]);
});
it('creates inputNames', () => {
expect(simpleContainer.inputNames).toEqual([inputLayerName]);
});
it('creates outputNames', () => {
expect(simpleContainer.outputNames).toEqual([layerName]);
});
it('throws exception if given a non-input layer as input', () => {
const makeContainer = () => {
// tslint:disable-next-line:no-unused-expression
new ContainerForTest({inputs: [output], outputs: []});
};
expect(makeContainer).toThrowError(/must be InputLayer objects/);
});
it('creates layers for simplest case', () => {
expect(simpleContainer.layers).toEqual([inputTensor.sourceLayer, layer]);
});
it('creates layers when multiple layers specified', () => {
const layer1 = new LayerForTest({name: 'layer1'});
const layer2 = new LayerForTest({name: 'layer2'});
const output =
layer2.apply(layer1.apply(inputTensor)) as tfl.SymbolicTensor;
const container =
new ContainerForTest({inputs: [inputTensor], outputs: [output]});
expect(container.layers).toEqual([inputTensor.sourceLayer, layer1, layer2]);
});
it('correctly creates model with shared subgraphs.', () => {
/*
The graph:
A
/ \
B X
| |
C B
|
C
*/
const layerA = new LayerForTest({name: 'A'});
const layerB = new LayerForTest({name: 'B'});
const layerC = new LayerForTest({name: 'C'});
const layerX = new LayerForTest({name: 'X'});
const aOutput = layerA.apply(inputTensor);
const output1 = layerC.apply(layerB.apply(aOutput)) as tfl.SymbolicTensor;
const output2 =
layerC.apply(layerB.apply(layerX.apply(aOutput))) as tfl.SymbolicTensor;
const container = new ContainerForTest(
{inputs: [inputTensor], outputs: [output1, output2]});
const compareFunction = (a: Layer, b: Layer) => {
if (a.name < b.name) {
return -1;
} else if (a.name > b.name) {
return 1;
} else {
return 0;
}
};
const sortedLayers = container.layers.slice().sort(compareFunction);
const expectedSortedLayers = [
inputTensor.sourceLayer, layerA, layerB, layerC, layerX
].sort(compareFunction);
expect(sortedLayers).toEqual(expectedSortedLayers);
});
it('throws exception if multiple layers have the same name', () => {
const name = 'abc';
const layer1 = new LayerForTest({name});
const layer2 = new LayerForTest({name});
const output =
layer2.apply(layer1.apply(inputTensor)) as tfl.SymbolicTensor;
const makeContainer = () => {
// tslint:disable-next-line:no-unused-expression
new ContainerForTest({inputs: [inputTensor], outputs: [output]});
};
expect(makeContainer).toThrowError(/layer names should be unique/);
});
it('weights gets all weights.', () => {
const inputShape = [1, 6];
const inputLayer = tfl.layers.input({shape: inputShape});
const layer1 = tfl.layers.dense({units: 2, useBias: false});
const layer2 = tfl.layers.dense({units: 1, useBias: true});
const output = layer2.apply(layer1.apply(inputLayer)) as tfl.SymbolicTensor;
const container =
new ContainerForTest({inputs: [inputLayer], outputs: [output]});
expect(container.weights.length).toEqual(3);
expect(container.weights[0].name).toEqual(layer1.weights[0].name);
expect(container.weights[1].name).toEqual(layer2.weights[0].name);
expect(container.weights[2].name).toEqual(layer2.weights[1].name);
});
it('trainableWeights and nonTrainableWeights.', () => {
const inputShape = [1, 6];
const inputLayer = tfl.layers.input({shape: inputShape});
const layer1 = tfl.layers.dense({units: 2, useBias: false});
const layer2 = tfl.layers.dense({units: 1, useBias: true});
const output = layer2.apply(layer1.apply(inputLayer)) as tfl.SymbolicTensor;
const container =
new ContainerForTest({inputs: [inputLayer], outputs: [output]});
expect(container.trainableWeights.length).toEqual(3);
expect(container.trainableWeights[0].name).toEqual(layer1.weights[0].name);
expect(container.trainableWeights[1].name).toEqual(layer2.weights[0].name);
expect(container.trainableWeights[2].name).toEqual(layer2.weights[1].name);
expect(container.nonTrainableWeights.length).toEqual(0);
});
it('call() executes all layers.', () => {
const inputShape = [1, 6];
const finalShape = [3, 2];
const inputLayer = tfl.layers.input({shape: inputShape});
const layer1 = tfl.layers.reshape({name: 'layer1', targetShape: [2, 3]});
const layer2 =
tfl.layers.reshape({name: 'layer2', targetShape: finalShape});
const output = layer2.apply(layer1.apply(inputLayer)) as tfl.SymbolicTensor;
const container =
new ContainerForTest({inputs: [inputLayer], outputs: [output]});
const result = container.call(ones([1, 1, 6]), {}) as Tensor[];
const resultShape = [1].concat(finalShape);
expectTensorsClose(result[0], ones(resultShape));
});
it('apply() executes all layers with concrete tensors.', () => {
const inputShape = [1, 6];
const finalShape = [3, 2];
const inputLayer = tfl.layers.input({shape: inputShape});
const layer1 = tfl.layers.reshape({name: 'layer1', targetShape: [2, 3]});
const layer2 =
tfl.layers.reshape({name: 'layer2', targetShape: finalShape});
const output = layer2.apply(layer1.apply(inputLayer)) as tfl.SymbolicTensor;
const container =
new ContainerForTest({inputs: [inputLayer], outputs: [output]});
const result = container.apply(ones([1, 1, 6])) as Tensor;
const resultShape = [1].concat(finalShape);
expectTensorsClose(result, ones(resultShape));
});
it('apply() executes all layers with symbolic tensors.', () => {
const inputShape = [1, 6];
const finalShape = [3, 2];
const inputLayer = tfl.layers.input({shape: inputShape});
const layer1 = tfl.layers.reshape({name: 'layer1', targetShape: [2, 3]});
const layer2 =
tfl.layers.reshape({name: 'layer2', targetShape: finalShape});
const output = layer2.apply(layer1.apply(inputLayer)) as tfl.SymbolicTensor;
const container =
new ContainerForTest({inputs: [inputLayer], outputs: [output]});
const newInput = tfl.layers.input({shape: [1, 6]});
const symbolicResult = container.apply(newInput);
expect(symbolicResult instanceof tfl.SymbolicTensor).toEqual(true);
const concreteResult = execute(
symbolicResult as tfl.SymbolicTensor,
new FeedDict([{key: newInput, value: ones([1, 1, 6])}]));
const resultShape = [1].concat(finalShape);
expectTensorsClose(concreteResult as Tensor, ones(resultShape));
});
it('computeOutputShape() computes the correct outputShape', () => {
const inputShape = [2, 3];
const finalShape = [3, 2];
const inputLayer = tfl.layers.input({shape: inputShape});
const layer = tfl.layers.reshape({targetShape: finalShape});
const output = layer.apply(inputLayer) as tfl.SymbolicTensor;
const container =
new ContainerForTest({inputs: [inputLayer], outputs: [output]});
expect(container.computeOutputShape([1].concat(inputShape))).toEqual([
1
].concat(finalShape));
});
it('trainableWeights is initially an empty Array', () => {
expect(simpleContainer.trainableWeights).toEqual([]);
});
it('trainableWeights tracks only trainable weights', () => {
const inputShape = [2, 2];
const inputLayer = tfl.layers.input({shape: inputShape});
const layer1 = tfl.layers.reshape({targetShape: [4], name: 'reshapeLayer'});
const layer1Output = layer1.apply(inputLayer) as tfl.SymbolicTensor;
const layer2 =
tfl.layers.dense({units: 2, useBias: false, name: 'denseLayer'});
const layer2Output = layer2.apply(layer1Output) as tfl.SymbolicTensor;
const container =
new ContainerForTest({inputs: [inputLayer], outputs: [layer2Output]});
expect(container.trainableWeights.length).toEqual(1);
});
it('stateful is initially false', () => {
expect(simpleContainer.stateful).toEqual(false);
});
function createSimpleTwoLayerContainer(): [Container, Layer[]] {
const inputShape = [2, 2];
const inputLayer = tfl.layers.input({shape: inputShape});
const layer1 = tfl.layers.reshape({targetShape: [4], name: 'reshapeLayer'});
const layer1Output = layer1.apply(inputLayer) as tfl.SymbolicTensor;
const layer2 =
tfl.layers.dense({units: 2, useBias: false, name: 'denseLayer'});
const layer2Output = layer2.apply(layer1Output) as tfl.SymbolicTensor;
const container =
new ContainerForTest({inputs: [inputLayer], outputs: [layer2Output]});
return [container, [container.inputLayers[0], layer1, layer2]];
}
it('getLayer works by name', () => {
const [container, layers] = createSimpleTwoLayerContainer();
expect(container.getLayer(layers[0].name)).toEqual(layers[0]);
expect(container.getLayer(layers[1].name)).toEqual(layers[1]);
expect(container.getLayer(layers[2].name)).toEqual(layers[2]);
});
it('getLayer works by index', () => {
const [container, layers] = createSimpleTwoLayerContainer();
expect(container.getLayer(null, 0)).toEqual(layers[0]);
expect(container.getLayer(null, 1)).toEqual(layers[1]);
expect(container.getLayer(null, 2)).toEqual(layers[2]);
});
it('getLayer throws error for nonexistent layer name', () => {
const [container, layers] = createSimpleTwoLayerContainer();
expect(
() => container.getLayer(
layers[0].name + '_suffixToMakeLayerNameNonexistent'))
.toThrowError(/No such layer/);
});
it('getLayer throws error for index out of bound', () => {
const container = createSimpleTwoLayerContainer()[0];
expect(() => container.getLayer(null, 3)).toThrowError(/only has 3 layer/);
});
it('getLayer throws error when neither name or index is specified', () => {
const container = createSimpleTwoLayerContainer()[0];
expect(() => container.getLayer())
.toThrowError(/Provide either a layer name or layer index/);
});
});
describeMathCPUAndGPU('Container.calculateLosses', () => {
function createSimpleOneLayerContainer(useRegularizers: boolean):
[Container, Layer[]] {
const inputShape = [2];
const inputLayer = tfl.layers.input({shape: inputShape});
const kernelRegularizer =
useRegularizers ? tfl.regularizers.l1({l1: 2}) : null;
const biasRegularizer =
useRegularizers ? tfl.regularizers.l2({l2: 3}) : null;
const denseLayer = tfl.layers.dense({
units: 2,
kernelInitializer: 'ones',
biasInitializer: 'ones',
kernelRegularizer,
biasRegularizer,
name: 'denseLayer'
});
const layer2Output = denseLayer.apply(inputLayer) as tfl.SymbolicTensor;
const container =
new ContainerForTest({inputs: [inputLayer], outputs: [layer2Output]});
return [container, [denseLayer]];
}
it('L1 and L2', () => {
const container = createSimpleOneLayerContainer(true)[0];
const losses = container.calculateLosses();
expect(losses.length).toEqual(2);
expectTensorsClose(losses[0], scalar(2 * (1 + 1 + 1 + 1)));
expectTensorsClose(losses[1], scalar(3 * (1 + 1)));
});
it('No regularizers', () => {
const container = createSimpleOneLayerContainer(false)[0];
const losses = container.calculateLosses();
expect(losses.length).toEqual(0);
});
});
describe('getSourceInputs()', () => {
it('returns the single source input', () => {
const inputTensor = tfl.layers.input({shape: [1]});
const layer1 = new LayerForTest({name: 'layer1'});
const layer2 = new LayerForTest({name: 'layer2'});
const output =
layer2.apply(layer1.apply(inputTensor)) as tfl.SymbolicTensor;
expect(getSourceInputs(output)).toEqual([inputTensor]);
});
it('returns all inputs', () => {
const input1 = tfl.layers.input({shape: [1], name: 'input1'});
const input2 = tfl.layers.input({shape: [1], name: 'input2'});
const layer = new LayerForTest({});
const output1 = layer.apply(input1) as tfl.SymbolicTensor;
const output2 = layer.apply(input2) as tfl.SymbolicTensor;
expect(getSourceInputs(output1)).toEqual([input1]);
expect(getSourceInputs(output2)).toEqual([input2]);
});
});
describeMathCPUAndGPU('LayersModel-dispose', () => {
it('Dispose Sequential model frees memory', () => {
const numTensors0 = memory().numTensors;
const model = tfl.sequential();
model.add(
tfl.layers.dense({units: 2, inputShape: [3], activation: 'relu'}));
model.add(tfl.layers.dense({units: 1}));
model.build([3, 3]);
const result = model.dispose();
expect(result.refCountAfterDispose).toEqual(0);
expect(result.numDisposedVariables).toEqual(4);
// The four weight variables of the two layers should have been disposed.
expect(memory().numTensors).toEqual(numTensors0);
});
it('Dispose Sequential model twice leads to Error', () => {
const model = tfl.sequential();
model.add(
tfl.layers.dense({units: 2, inputShape: [3], activation: 'relu'}));
model.add(tfl.layers.dense({units: 1}));
model.build([3, 3]);
model.dispose();
expect(() => model.dispose()).toThrowError(/Container .* already disposed/);
});
it('Using disposed Sequential model leads to Error', async () => {
const model = tfl.sequential();
model.add(
tfl.layers.dense({units: 2, inputShape: [3], activation: 'relu'}));
model.add(tfl.layers.dense({units: 1, activation: 'sigmoid'}));
model.build([3, 3]);
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
model.dispose();
const xs = zeros([3, 3]);
const ys = zeros([3, 1]);
expect(() => model.predict(xs)).toThrowError(/already disposed/);
expect(() => model.evaluate(xs, ys)).toThrowError(/already disposed/);
let errorCaughtDuringFit = false;
try {
await model.fit(xs, ys);
} catch (err) {
errorCaughtDuringFit = true;
}
expect(errorCaughtDuringFit).toEqual(true);
});
it('Dispose functional model frees memory', () => {
const input = tfl.input({shape: [4]});
const dense1 =
tfl.layers.dense({units: 3}).apply(input) as tfl.SymbolicTensor;
const dense2 = tfl.layers.dense({units: 2, useBias: false}).apply(input) as
tfl.SymbolicTensor;
const model = tfl.model({inputs: [input], outputs: [dense1, dense2]});
// Call predict once to make sure that the model's weights are initialized.
model.predict(zeros([2, 4]));
const numTensors0 = memory().numTensors;
const result = model.dispose();
expect(result.refCountAfterDispose).toEqual(0);
expect(result.numDisposedVariables).toEqual(3);
// The 2 + 1 = 3 weight variables of the two layers should have been
// disposed.
expect(memory().numTensors).toEqual(numTensors0 - 3);
});
it('Dispose functional model twice leads to Error', () => {
const input = tfl.input({shape: [4]});
const dense1 =
tfl.layers.dense({units: 3}).apply(input) as tfl.SymbolicTensor;
const dense2 = tfl.layers.dense({units: 2, useBias: false}).apply(input) as
tfl.SymbolicTensor;
const model = tfl.model({inputs: [input], outputs: [dense1, dense2]});
// Call predict once to make sure that the model's weights are initialized.
model.predict(zeros([2, 4]));
model.dispose();
expect(() => model.dispose()).toThrowError(/Container .* already disposed/);
});
it('Layer shared between two functional models is not disposed', () => {
const input1 = tfl.input({shape: [4]});
const input2 = tfl.input({shape: [4]});
const sharedDenseLayer = tfl.layers.dense({units: 3, activation: 'relu'});
const nonSharedDenseLayer1 = tfl.layers.dense({units: 1, useBias: false});
const nonSharedDenseLayer2 = tfl.layers.dense({units: 1, useBias: false});
const output1 = nonSharedDenseLayer1.apply(
sharedDenseLayer.apply(input1)) as tfl.SymbolicTensor;
const output2 = nonSharedDenseLayer2.apply(
sharedDenseLayer.apply(input2)) as tfl.SymbolicTensor;
const model1 = tfl.model({inputs: [input1], outputs: [output1]});
const model2 = tfl.model({inputs: [input2], outputs: [output2]});
// Call predict once to make sure that both models' weights are initialized.
model1.predict(zeros([2, 4]));
model2.predict(zeros([2, 4]));
const xs = zeros([2, 4]);
const numTensors0 = memory().numTensors;
const result1 = model1.dispose();
expect(result1.refCountAfterDispose).toEqual(0);
expect(result1.numDisposedVariables).toEqual(1);
// After model1 is disposed, only the single weight of
// `nonSharedDenseLayer1` should have been freed.
expect(memory().numTensors).toEqual(numTensors0 - 1);
// At this point, calling predict() on model1 should fail, but doing the
// same on model2 should still work.
expect(() => model1.predict(xs)).toThrowError(/already disposed/);
const ys = model2.predict(xs) as Tensor;
expect(ys.shape).toEqual([2, 1]);
ys.dispose();
const result2 = model2.dispose();
expect(result2.refCountAfterDispose).toEqual(0);
expect(result2.numDisposedVariables).toEqual(3);
// After model2 is disposed, the single weight of `nonSharedDenseLayer2`
// and the two weights o `sharedDenseLayer` should be freed.
expect(memory().numTensors).toEqual(numTensors0 - 4);
// At this point, calling predict() on both model1 and model2 should fail.
expect(() => model1.predict(xs)).toThrowError(/already disposed/);
expect(() => model2.predict(xs)).toThrowError(/already disposed/);
});
it('Disposing nested sequential model preserves the inner model', () => {
const innerModel = tfl.sequential();
innerModel.add(tfl.layers.reshape({targetShape: [10], inputShape: [2, 5]}));
innerModel.add(tfl.layers.dense({units: 6, activation: 'relu'}));
innerModel.add(tfl.layers.dense({units: 4, activation: 'relu'}));
const outerModel = tfl.sequential();
outerModel.add(
tfl.layers.reshape({targetShape: [2, 5], inputShape: [5, 2]}));
outerModel.add(innerModel);
outerModel.add(tfl.layers.dense({units: 3, activation: 'softmax'}));
const xsOuter = zeros([1, 5, 2]);
const xsInner = zeros([1, 2, 5]);
outerModel.predict(xsOuter); // Call predict() to initialize the weights.
const numTensors0 = memory().numTensors;
const result1 = outerModel.dispose();
expect(result1.refCountAfterDispose).toEqual(0);
expect(result1.numDisposedVariables).toEqual(2);
// Calling dispose on the outer model should have freed the two weights that
// belong to only the outer model and not to the inner model.
expect(memory().numTensors).toEqual(numTensors0 - 2);
// Calling dispose on the outer model again should lead to Error.
expect(() => outerModel.dispose())
.toThrowError(/Container .* already disposed/);
// Calling predict on the outer model should fail.
expect(() => outerModel.predict(xsOuter)).toThrowError(/already disposed/);
// At this point, the inner model is still usable.
const ysInner = innerModel.predict(xsInner) as Tensor;
expect(ysInner.shape).toEqual([1, 4]);
ysInner.dispose();
// Calling dispose on innerModel should finally freed all the weights.
const result2 = innerModel.dispose();
expect(result2.refCountAfterDispose).toEqual(0);
expect(result2.numDisposedVariables).toEqual(4);
expect(memory().numTensors).toEqual(numTensors0 - 6);
// At this point, the inner model should have become unusable.
expect(() => innerModel.predict(xsInner)).toThrowError(/already disposed/);
});
it('Nested model gets the correct kwargs', async () => {
const innerModel = tfl.sequential();
const layer =
tfl.layers.dense({units: 1, inputShape: [5], activation: 'sigmoid'});
innerModel.add(layer);
const input = tfl.input({shape: [5]});
const output = innerModel.apply(input) as SymbolicTensor;
const model = tfl.model({inputs: input, outputs: output});
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
const kwargsArray: Kwargs[] = [];
const recordKwargsHook: CallHook = (inputs: Tensor|Tensor[], kwargs: {}) =>
kwargsArray.push(kwargs);
layer.setCallHook(recordKwargsHook);
const xs = ones([3, 5]);
const ys = ones([3, 1]);
await model.trainOnBatch(xs, ys);
expect(kwargsArray.length).toEqual(1);
expect(kwargsArray[0]['training']).toEqual(true);
});
it('Dispose Sequential model with a Dropout', () => {
const numTensors0 = memory().numTensors;
const model = tfl.sequential();
model.add(
tfl.layers.dense({units: 2, inputShape: [3], activation: 'relu'}));
model.add(tfl.layers.dense({units: 1}));
model.add(tfl.layers.dropout({rate: 0.8}));
model.build([3, 3]);
const result = model.dispose();
expect(result.refCountAfterDispose).toEqual(0);
expect(result.numDisposedVariables).toEqual(4);
// The four weight variables of the two layers should have been disposed.
// + the rate from the dropout tensor
expect(memory().numTensors).toEqual(numTensors0);
});
}); | the_stack |
* Copyright 2015 Dev Shop Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an 'AS IS' BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// notice_end
import {PreEventProcessor} from './eventProcessors';
import {EventDispatchProcessor, EventProcessors, PostEventProcessor} from './eventProcessors';
import {Observable} from '../reactive';
import {DispatchType, EventEnvelope, ModelEnvelope} from './envelopes';
import {AutoConnectedObservable} from '../reactive/autoConnectedObservable';
import {Guard} from '../system';
import {ObservationStage} from './index';
export interface EventStreamsRegistration {
all: AutoConnectedObservable<EventEnvelope<any, any>>;
preview: AutoConnectedObservable<EventEnvelope<any, any>>;
normal: AutoConnectedObservable<EventEnvelope<any, any>>;
committed: AutoConnectedObservable<EventEnvelope<any, any>>;
final: AutoConnectedObservable<EventEnvelope<any, any>>;
}
interface InternalEventStreamsRegistration {
streams: EventStreamsRegistration;
}
export class ModelRecord {
private readonly _modelId: string;
private readonly _modelObservationStream: AutoConnectedObservable<ModelEnvelope<any>>;
private readonly _eventQueue: any[];
private _model: any;
private _hasReceivedEvent: boolean;
private _wasRemoved: boolean;
private _preEventProcessor: PreEventProcessor;
private _eventDispatchProcessor: EventDispatchProcessor;
private _eventDispatchedProcessor: EventDispatchProcessor;
private _postEventProcessor: PostEventProcessor;
private _eventStreams: Map<string, InternalEventStreamsRegistration>;
private _eventQueueDirtyEpochMs: number;
constructor(modelId: string, model: any, modelObservationStream: AutoConnectedObservable<ModelEnvelope<any>>, options?: EventProcessors) {
this._modelId = modelId;
this._eventQueue = [];
this._hasReceivedEvent = false;
this._wasRemoved = false;
this._eventStreams = new Map();
this._modelObservationStream = modelObservationStream;
this._eventQueueDirtyEpochMs = null;
if (model) {
this.setModel(model, options);
}
}
public get modelId() {
return this._modelId;
}
public get hasModel() {
return !!this._model;
}
public get model() {
return this._model;
}
public get eventQueue() {
return this._eventQueue;
}
public get eventQueueDirtyEpochMs() {
return this._eventQueueDirtyEpochMs;
}
public get hasReceivedEvent() {
return this._hasReceivedEvent;
}
public set hasReceivedEvent(value) {
this._hasReceivedEvent = value;
}
public get wasRemoved() {
return this._wasRemoved;
}
public set wasRemoved(value) {
this._wasRemoved = value;
}
public get preEventProcessor(): PreEventProcessor {
return this._preEventProcessor;
}
public get eventDispatchProcessor(): EventDispatchProcessor {
return this._eventDispatchProcessor;
}
public get eventDispatchedProcessor(): EventDispatchProcessor {
return this._eventDispatchedProcessor;
}
public get postEventProcessor(): PostEventProcessor {
return this._postEventProcessor;
}
public getOrCreateEventStreamsRegistration(eventType: string, dispatchObservable: Observable<EventEnvelope<any, any>>): EventStreamsRegistration {
let eventStreamsRegistration = this._eventStreams.get(eventType);
if (!eventStreamsRegistration) {
let eventStream = dispatchObservable.filter(
envelope =>
envelope.dispatchType === DispatchType.Event &&
envelope.modelId === this.modelId &&
envelope.eventType === eventType
);
eventStreamsRegistration = {
streams: {
preview: eventStream
.filter(envelope => ObservationStage.isPreview(envelope.observationStage))
.share(false),
normal: eventStream
.filter(envelope => ObservationStage.isNormal(envelope.observationStage))
.share(false),
committed: eventStream
.filter(envelope => ObservationStage.isCommitted(envelope.observationStage))
.share(false),
final: eventStream
.filter(envelope => ObservationStage.isFinal(envelope.observationStage))
.share(false),
all: eventStream
.share(false)
}
};
// there is no real reason to cache these stream filters other than less objects get created at runtime
// that's a handy enough reason to aid in debugging and overall performance
this._eventStreams.set(eventType, eventStreamsRegistration);
}
return eventStreamsRegistration.streams;
}
public enqueueEvent(eventType: string, event: any): void {
if (!this._eventQueueDirtyEpochMs) {
this._eventQueueDirtyEpochMs = Date.now();
}
this.eventQueue.push({eventType: eventType, event: event});
}
public eventQueuePurged() {
this._eventQueueDirtyEpochMs = null;
}
public get modelObservationStream(): Observable<any> {
return this._modelObservationStream;
}
public setModel(model: any, eventProcessors?: EventProcessors) {
Guard.isFalsey(this._model, 'Model already set');
this._model = model;
if (this._model) {
this._preEventProcessor = this._createEventProcessor('preProcess', 'preEventProcessor', eventProcessors);
this._eventDispatchProcessor = this._createEventDispatchProcessor('eventDispatch', 'eventDispatchProcessor', eventProcessors);
this._eventDispatchedProcessor = this._createEventDispatchProcessor('eventDispatched', 'eventDispatchedProcessor', eventProcessors);
this._postEventProcessor = this._createEventProcessor('postProcess', 'postEventProcessor', eventProcessors);
}
}
public dispose() {
this._eventQueue.length = 0;
this._modelObservationStream.disconnect();
this._eventStreams.forEach(streamsRegistration => {
streamsRegistration.streams.preview.disconnect();
streamsRegistration.streams.normal.disconnect();
streamsRegistration.streams.committed.disconnect();
streamsRegistration.streams.all.disconnect();
});
}
/**
* Creates an event processor which can be given as externalProcessor, or exist on the model as modelProcessFunctionName (or both).
* If no such process exists a no-op function is returned
*/
_createEventProcessor(modelProcessFunctionName: string, optionsProcessFunctionName: string, eventProcessors: EventProcessors): (model: any, eventsProcessed?: string[]) => void {
let processorFunctionOnOptions: (model: any, eventsProcessed?: string[]) => void;
if (eventProcessors && eventProcessors[optionsProcessFunctionName]) {
Guard.isFunction(eventProcessors[optionsProcessFunctionName], `${optionsProcessFunctionName} on the model options exists but is not a function`);
processorFunctionOnOptions = eventProcessors[optionsProcessFunctionName];
} else {
processorFunctionOnOptions = (model, eventsProcessed) => { /*noop */ };
}
let modelProcessor = (model, eventsProcessed) => {
// dispatch to the model in a late bound manor
if(model[modelProcessFunctionName] && (typeof model[modelProcessFunctionName] === 'function')) {
model[modelProcessFunctionName](eventsProcessed);
}
};
return (model, eventsProcessed) => {
processorFunctionOnOptions(model, eventsProcessed);
modelProcessor(model, eventsProcessed);
};
}
/**
* Creates an event dispatch processor which can exist on the given options as `optionsEventDispatchFunctionName` and/or on the model as `modelEventDispatchFunctionName`.
* If no such process exists a no-op function is returned
*/
_createEventDispatchProcessor<TDelegate>(modelEventDispatchFunctionName: string, optionsEventDispatchFunctionName: string, options: EventProcessors): EventDispatchProcessor {
let processorFunctionOnOptions: EventDispatchProcessor;
if (options && options[optionsEventDispatchFunctionName]) {
Guard.isFunction(options[optionsEventDispatchFunctionName], `${optionsEventDispatchFunctionName} on the model options exists but is not a function`);
processorFunctionOnOptions = options[optionsEventDispatchFunctionName];
} else {
processorFunctionOnOptions = (model: any, eventType: string, event: any, observationStage: ObservationStage) => { /*noop */ };
}
let modelProcessor = (model, eventType: string, event: any, observationStage: ObservationStage) => {
// dispatch to the model in a late bound manor
if(model[modelEventDispatchFunctionName] && (typeof model[modelEventDispatchFunctionName] === 'function')) {
model[modelEventDispatchFunctionName](eventType, event, observationStage);
}
};
return (model: any, eventType: string, event: any, observationStage: ObservationStage) => {
processorFunctionOnOptions(model, eventType, event, observationStage);
modelProcessor(model, eventType, event, observationStage);
};
}
} | the_stack |
import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core';
import { ShopEventBus, PricingService, UserEventBus, I18nEventBus, Util } from './../shared/services/index';
import { PromotionTestConfigComponent } from './components/index';
import { ModalComponent, ModalResult, ModalAction } from './../shared/modal/index';
import { AttributeVO, PromotionVO, ShopVO, Pair, CartVO, PromotionTestVO, SearchResultVO } from './../shared/model/index';
import { FormValidationEvent, Futures, Future } from './../shared/event/index';
import { Config } from './../../environments/environment';
import { UiUtil } from './../shared/ui/index';
import { LogUtil } from './../shared/log/index';
import { StorageUtil } from './../shared/storage/index';
@Component({
selector: 'cw-shop-promotions',
templateUrl: 'shop-promotions.component.html',
})
export class ShopPromotionsComponent implements OnInit, OnDestroy {
private static PROMOTIONS:string = 'promotions';
private static PROMOTION:string = 'promotion';
private static PROMOTIONS_TEST:string = 'promotionstest';
private static COOKIE_SHOP:string = 'ADM_UI_PROMO_SHOP';
private static COOKIE_CURRENCY:string = 'ADM_UI_PROMO_CURR';
private static _selectedShopCode:string;
private static _selectedShop:ShopVO;
private static _selectedCurrency:string;
private static _promoTypes:Pair<AttributeVO, boolean>[] = [];
private static _promoActions:Pair<AttributeVO, boolean>[] = [];
private static _promoOptions:any = {};
public searchHelpShow:boolean = false;
public forceShowAll:boolean = false;
public viewMode:string = ShopPromotionsComponent.PROMOTIONS;
public promotions:SearchResultVO<PromotionVO>;
public promotionFilter:string;
public promotionFilterRequired:boolean = true;
private delayedFiltering:Future;
private delayedFilteringMs:number = Config.UI_INPUT_DELAY;
public selectedPromotion:PromotionVO;
public promotionEdit:PromotionVO;
@ViewChild('deleteConfirmationModalDialog')
private deleteConfirmationModalDialog:ModalComponent;
@ViewChild('disableConfirmationModalDialog')
private disableConfirmationModalDialog:ModalComponent;
public deleteValue:String;
public loading:boolean = false;
public changed:boolean = false;
public validForSave:boolean = false;
public validForSaveAndDisabled:boolean = false;
@ViewChild('selectShopModalDialog')
private selectShopModalDialog:ModalComponent;
@ViewChild('selectCurrencyModalDialog')
private selectCurrencyModalDialog:ModalComponent;
public testCart:CartVO;
@ViewChild('runTestModalDialog')
private runTestModalDialog:PromotionTestConfigComponent;
private userSub:any;
constructor(private _promotionService:PricingService) {
LogUtil.debug('ShopPromotionsComponent constructed');
this.promotions = this.newSearchResultInstance();
}
get selectedShop():ShopVO {
return ShopPromotionsComponent._selectedShop;
}
set selectedShop(selectedShop:ShopVO) {
ShopPromotionsComponent._selectedShop = selectedShop;
}
get selectedShopCode(): string {
return ShopPromotionsComponent._selectedShopCode;
}
set selectedShopCode(value: string) {
ShopPromotionsComponent._selectedShopCode = value;
}
get selectedCurrency():string {
return ShopPromotionsComponent._selectedCurrency;
}
set selectedCurrency(selectedCurrency:string) {
ShopPromotionsComponent._selectedCurrency = selectedCurrency;
}
newPromotionInstance():PromotionVO {
return {
promotionId: 0, code: '', shopCode: this.selectedShop.code, currency: this.selectedCurrency,
rank: 500, name: null, description: null,
displayNames: [], displayDescriptions: [],
promoType: 'O', promoAction: 'P',
eligibilityCondition: null, promoActionContext: null,
couponTriggered: false, canBeCombined: true,
enabled: false, enabledFrom: null, enabledTo: null,
tag: null
};
}
newSearchResultInstance():SearchResultVO<PromotionVO> {
return {
searchContext: {
parameters: {
filter: [],
types: [],
actions: []
},
start: 0,
size: Config.UI_TABLE_PAGE_SIZE,
sortBy: null,
sortDesc: false
},
items: [],
total: 0
};
}
get promoTypes():Pair<AttributeVO, boolean>[] {
return ShopPromotionsComponent._promoTypes;
}
set promoTypes(value:Pair<AttributeVO, boolean>[]) {
ShopPromotionsComponent._promoTypes = value;
}
get promoActions():Pair<AttributeVO, boolean>[] {
return ShopPromotionsComponent._promoActions;
}
set promoActions(value:Pair<AttributeVO, boolean>[]) {
ShopPromotionsComponent._promoActions = value;
}
get promoOptions(): any {
return ShopPromotionsComponent._promoOptions;
}
set promoOptions(value: any) {
ShopPromotionsComponent._promoOptions = value;
}
getAttributeName(attr:AttributeVO):string {
let lang = I18nEventBus.getI18nEventBus().current();
let i18n = attr.displayNames;
let def = attr.name != null ? attr.name : attr.code;
return UiUtil.toI18nString(i18n, def, lang);
}
ngOnInit() {
LogUtil.debug('ShopPromotionsComponent ngOnInit');
this.onRefreshHandler();
this.userSub = UserEventBus.getUserEventBus().userUpdated$.subscribe(user => {
this.presetFromCookie();
});
let that = this;
this.delayedFiltering = Futures.perpetual(function() {
that.getFilteredPromotions();
}, this.delayedFilteringMs);
}
ngOnDestroy() {
LogUtil.debug('ShopPromotionsComponent ngOnDestroy');
if (this.userSub) {
this.userSub.unsubscribe();
}
}
presetFromCookie() {
if (this.selectedShop == null) {
let shopCode = StorageUtil.readValue(ShopPromotionsComponent.COOKIE_SHOP, null);
if (shopCode != null) {
let shops = ShopEventBus.getShopEventBus().currentAll();
if (shops != null) {
shops.forEach(shop => {
if (shop.code == shopCode) {
this.selectedShop = shop;
this.selectedShopCode = shop.code;
LogUtil.debug('ShopPromotionsComponent ngOnInit presetting shop from cookie', shop);
}
});
}
}
}
if (this.selectedCurrency == null) {
let curr = StorageUtil.readValue(ShopPromotionsComponent.COOKIE_CURRENCY, null);
if (curr != null) {
this.selectedCurrency = curr;
LogUtil.debug('ShopPromotionsComponent ngOnInit presetting currency from cookie', curr);
}
}
if (this.promoTypes.length == 0) {
this._promotionService.getPromotionOptions().subscribe(res => {
LogUtil.debug('ShopPromotionsComponent getPromotionOptions', res);
let actions = [];
let promoTypes: Pair<AttributeVO, boolean>[] = [];
let promoActions: Pair<AttributeVO, boolean>[] = [];
let promoOptions:any = {};
res.forEach(tval => {
promoTypes.push({first: tval.first, second: false});
promoOptions[tval.first.val] = [];
tval.second.forEach(aval => {
if (actions.indexOf(aval.val) == -1) {
promoActions.push({first: aval, second: false});
actions.push(aval.val);
}
promoOptions[tval.first.val].push(aval.val);
});
});
this.promoTypes = promoTypes;
this.promoActions = promoActions;
this.promoOptions = promoOptions;
LogUtil.debug('ShopPromotionsComponent ngOnInit presetting options', promoTypes, promoActions, promoOptions);
});
}
}
onShopSelect() {
LogUtil.debug('ShopPromotionsComponent onShopSelect');
this.selectShopModalDialog.show();
}
onShopSelected(event:ShopVO) {
LogUtil.debug('ShopPromotionsComponent onShopSelected');
this.selectedShop = event;
if (this.selectedShop != null) {
this.selectedShopCode = event.code;
StorageUtil.saveValue(ShopPromotionsComponent.COOKIE_SHOP, this.selectedShop.code);
} else {
this.selectedShopCode = null;
}
}
onSelectShopResult(modalresult: ModalResult) {
LogUtil.debug('ShopPromotionsComponent onSelectShopResult modal result is ', modalresult);
if (this.selectedShop == null) {
this.selectShopModalDialog.show();
} else if (this.selectedCurrency == null) {
this.selectCurrencyModalDialog.show();
} else {
this.getFilteredPromotions();
}
}
onCurrencySelect() {
LogUtil.debug('ShopPromotionsComponent onCurrencySelect');
this.selectCurrencyModalDialog.show();
}
onCurrencySelected(event:string) {
LogUtil.debug('ShopPromotionsComponent onCurrencySelected');
this.selectedCurrency = event;
if (this.selectedCurrency != null) {
StorageUtil.saveValue(ShopPromotionsComponent.COOKIE_CURRENCY, this.selectedCurrency);
}
}
onSelectCurrencyResult(modalresult: ModalResult) {
LogUtil.debug('ShopPromotionsComponent onSelectCurrencyResult modal result is ', modalresult);
if (this.selectedCurrency == null) {
this.selectCurrencyModalDialog.show();
} else {
this.getFilteredPromotions();
}
}
onTestRules() {
LogUtil.debug('ShopPromotionsComponent onTestRules');
this.runTestModalDialog.showDialog();
}
onRunTestResult(event:PromotionTestVO) {
LogUtil.debug('ShopPromotionsComponent onRunTestResult', event);
if (event != null && this.selectedShop != null) {
this.loading = true;
event.shopCode = this.selectedShop.code;
event.currency = this.selectedCurrency;
this._promotionService.testPromotions(event).subscribe(
cart => {
this.loading = false;
LogUtil.debug('ShopPromotionsComponent onTestRules', cart);
this.viewMode = ShopPromotionsComponent.PROMOTIONS_TEST;
this.testCart = cart;
}
);
}
}
onFilterChange(event:any) {
this.promotions.searchContext.start = 0; // changing filter means we need to start from first page
this.delayedFiltering.delay();
}
onRefreshHandler() {
LogUtil.debug('ShopPromotionsComponent refresh handler');
if (UserEventBus.getUserEventBus().current() != null) {
this.presetFromCookie();
this.getFilteredPromotions();
}
}
onPageSelected(page:number) {
LogUtil.debug('ShopPromotionsComponent onPageSelected', page);
this.promotions.searchContext.start = page;
this.delayedFiltering.delay();
}
onSortSelected(sort:Pair<string, boolean>) {
LogUtil.debug('ShopPromotionsComponent ononSortSelected', sort);
if (sort == null) {
this.promotions.searchContext.sortBy = null;
this.promotions.searchContext.sortDesc = false;
} else {
this.promotions.searchContext.sortBy = sort.first;
this.promotions.searchContext.sortDesc = sort.second;
}
this.delayedFiltering.delay();
}
onPromotionSelected(data:PromotionVO) {
LogUtil.debug('ShopPromotionsComponent onPromotionSelected', data);
this.selectedPromotion = data;
}
onPromotionChanged(event:FormValidationEvent<PromotionVO>) {
LogUtil.debug('ShopPromotionsComponent onPromotionChanged', event);
this.changed = true;
this.validForSave = event.valid;
this.validForSaveAndDisabled = this.validForSave && !event.source.enabled;
this.promotionEdit = event.source;
}
onSearchHelpToggle() {
this.searchHelpShow = !this.searchHelpShow;
}
onSearchCode() {
this.promotionFilter = '#';
this.searchHelpShow = false;
}
onSearchCondition() {
this.promotionFilter = '?';
this.searchHelpShow = false;
}
onSearchEnabled() {
this.promotionFilter = '++';
this.searchHelpShow = false;
this.getFilteredPromotions();
}
onSearchDate() {
this.promotionFilter = UiUtil.exampleDateSearch();
this.searchHelpShow = false;
this.getFilteredPromotions();
}
onForceShowAll() {
this.forceShowAll = !this.forceShowAll;
this.getFilteredPromotions();
}
onBackToList() {
LogUtil.debug('ShopPromotionsComponent onBackToList handler');
if (this.viewMode === ShopPromotionsComponent.PROMOTION || this.viewMode === ShopPromotionsComponent.PROMOTIONS_TEST) {
this.promotionEdit = null;
this.viewMode = ShopPromotionsComponent.PROMOTIONS;
}
}
onRowNew() {
LogUtil.debug('ShopPromotionsComponent onRowNew handler');
this.changed = false;
this.validForSave = false;
this.validForSaveAndDisabled = false;
if (this.viewMode === ShopPromotionsComponent.PROMOTIONS) {
this.promotionEdit = this.newPromotionInstance();
this.viewMode = ShopPromotionsComponent.PROMOTION;
}
}
onRowDelete(row:any) {
LogUtil.debug('ShopPromotionsComponent onRowDelete handler', row);
this.deleteValue = row.name;
this.deleteConfirmationModalDialog.show();
}
onRowDeleteSelected() {
if (this.selectedPromotion != null) {
this.onRowDelete(this.selectedPromotion);
}
}
onRowEnableSelected() {
if (this.selectedPromotion != null) {
this.deleteValue = this.selectedPromotion.name;
this.disableConfirmationModalDialog.show();
}
}
onRowEditPromotion(row:PromotionVO) {
LogUtil.debug('ShopPromotionsComponent onRowEditPromotion handler', row);
this.promotionEdit = Util.clone(row);
this.changed = false;
this.validForSave = false;
this.validForSaveAndDisabled = false;
this.viewMode = ShopPromotionsComponent.PROMOTION;
}
onRowEditSelected() {
if (this.selectedPromotion != null) {
this.onRowEditPromotion(this.selectedPromotion);
}
}
onRowCopySelected() {
if (this.selectedPromotion != null) {
let copy:PromotionVO = Util.clone(this.selectedPromotion);
copy.promotionId = 0;
copy.enabled = false;
copy.shopCode = this.selectedShopCode;
this.onRowEditPromotion(copy);
}
}
onSaveHandler() {
if (this.validForSaveAndDisabled && this.changed) {
if (this.promotionEdit != null) {
LogUtil.debug('ShopPromotionsComponent Save handler promotion', this.promotionEdit);
this.loading = true;
this._promotionService.savePromotion(this.promotionEdit).subscribe(
rez => {
LogUtil.debug('ShopPromotionsComponent promotion changed', rez);
this.changed = false;
this.selectedPromotion = rez;
this.promotionEdit = null;
this.viewMode = ShopPromotionsComponent.PROMOTIONS;
this.loading = false;
this.getFilteredPromotions();
}
);
}
}
}
onDiscardEventHandler() {
LogUtil.debug('ShopPromotionsComponent discard handler');
if (this.viewMode === ShopPromotionsComponent.PROMOTION) {
if (this.selectedPromotion != null) {
this.onRowEditSelected();
} else {
this.onRowNew();
}
}
}
onDeleteConfirmationResult(modalresult: ModalResult) {
LogUtil.debug('ShopPromotionsComponent onDeleteConfirmationResult modal result is ', modalresult);
if (ModalAction.POSITIVE === modalresult.action) {
if (this.selectedPromotion != null) {
LogUtil.debug('ShopPromotionsComponent onDeleteConfirmationResult', this.selectedPromotion);
this.loading = true;
this._promotionService.removePromotion(this.selectedPromotion).subscribe(res => {
LogUtil.debug('ShopPromotionsComponent removePromotion', this.selectedPromotion);
this.selectedPromotion = null;
this.promotionEdit = null;
this.loading = false;
this.getFilteredPromotions();
});
}
}
}
onDisableConfirmationResult(modalresult: ModalResult) {
LogUtil.debug('ShopPromotionsComponent onDisableConfirmationResult modal result is ', modalresult);
if (ModalAction.POSITIVE === modalresult.action) {
if (this.selectedPromotion != null) {
this.loading = true;
this._promotionService.updatePromotionDisabledFlag(this.selectedPromotion, this.selectedPromotion.enabled).subscribe( done => {
LogUtil.debug('ShopPromotionsComponent updateDisabledFlag', done);
this.selectedPromotion.enabled = !this.selectedPromotion.enabled;
if (this.promotionEdit != null && this.selectedPromotion.promotionId == this.promotionEdit.promotionId) {
this.promotionEdit = Util.clone(this.promotionEdit); // Trigger form INIT
this.promotionEdit.enabled = this.selectedPromotion.enabled;
this.validForSaveAndDisabled = this.validForSave && !this.promotionEdit.enabled;
} else {
this.changed = false;
this.validForSave = false;
this.validForSaveAndDisabled = false;
}
this.loading = false;
});
}
}
}
onClearFilter() {
this.promotionFilter = '';
this.getFilteredPromotions();
}
private getFilteredPromotions() {
this.promotionFilterRequired = !this.forceShowAll && (this.promotionFilter == null || this.promotionFilter.length < 2);
LogUtil.debug('ShopPromotionsComponent getFilteredPromotions' + (this.forceShowAll ? ' forcefully': ''));
if (this.selectedShop != null && this.selectedCurrency != null && !this.promotionFilterRequired) {
this.loading = true;
let types:string[] = [];
ShopPromotionsComponent._promoTypes.forEach((_type:Pair<AttributeVO, boolean>) => {
if (_type.second) {
types.push(_type.first.val);
}
});
let actions:string[] = [];
ShopPromotionsComponent._promoActions.forEach((_action:Pair<AttributeVO, boolean>) => {
if (_action.second) {
actions.push(_action.first.val);
}
});
this.promotions.searchContext.parameters.filter = [ this.promotionFilter ];
this.promotions.searchContext.parameters.shopCode = [ this.selectedShop.code ];
this.promotions.searchContext.parameters.currency = [ this.selectedCurrency ];
this.promotions.searchContext.parameters.types = types;
this.promotions.searchContext.parameters.actions = actions;
this.promotions.searchContext.size = Config.UI_TABLE_PAGE_SIZE;
this._promotionService.getFilteredPromotions(this.promotions.searchContext).subscribe( allpromotions => {
LogUtil.debug('ShopPromotionsComponent getFilteredPromotions', allpromotions);
this.promotions = allpromotions;
this.selectedPromotion = null;
this.promotionEdit = null;
this.viewMode = ShopPromotionsComponent.PROMOTIONS;
this.changed = false;
this.validForSave = false;
this.validForSaveAndDisabled = false;
this.loading = false;
});
} else {
this.promotions = this.newSearchResultInstance();
this.selectedPromotion = null;
this.promotionEdit = null;
this.viewMode = ShopPromotionsComponent.PROMOTIONS;
this.changed = false;
this.validForSave = false;
this.validForSaveAndDisabled = false;
}
}
} | the_stack |
/// <reference types="node"/>
import { IncomingMessage } from 'http';
export interface FieldObjectChoice {
[key: string]: string | FieldObjectChoice;
}
export interface FieldArrayChoice extends Array<[string, string | FieldArrayChoice]> {}
export interface FieldParameters {
/** Optional label text which overrides the default. */
label?: string | undefined;
/** Boolean describing whether the field is mandatory. */
required?: boolean | ValidatorFunction | undefined;
/** An array of functions which validate the field data. */
validators?: ValidatorFunction[] | undefined;
/** A widget object to use when rendering the field. */
widget?: Widget | undefined;
/** An optional id to override the default. */
id?: string | undefined;
/** A list of options, used for multiple choice fields. */
choices?: FieldObjectChoice | FieldArrayChoice | undefined;
/** A list of CSS classes for label and field wrapper. */
cssClasses?: {
field?: string[] | undefined
label?: string[] | undefined
} | undefined;
/** If true, errors won't be rendered automatically. */
hideError?: boolean | undefined;
/** If true, the label text will be displayed after the field, rather than before. */
labelAfterField?: boolean | undefined;
/** If true, the error message will be displayed after the field, rather than before. */
errorAfterField?: boolean | undefined;
/** For widgets with a fieldset (multipleRadio and multipleCheckbox), set classes for the fieldset. */
fieldsetClasses?: string[] | undefined;
/** For widgets with a fieldset (multipleRadio and multipleCheckbox), set classes for the fieldset's legend. */
legendClasses?: string[] | undefined;
}
export type FieldIterator = (name: string, field: FieldBound) => string;
export type Field<Data = unknown> = FieldParameters & {
/** A widget object to use when rendering the field. */
widget: Widget;
/** Coerces the raw data from the request into the correct format for the field, returning the result, e.g. '123' becomes 123 for the number field. */
parse: (rawData: unknown) => Data;
/** Returns a new bound field object. Calls parse on the data and stores in the bound field's data attribute, stores the raw value in the value attribute. */
bind: <RawData = unknown>(rawData: RawData) => FieldBound<Data, RawData>;
/** Returns a string containing a HTML element containing the fields error message, or an empty string if there is no error associated with the field. */
errorHTML: () => string;
/** Returns a string containing the label text from field.label, or defaults to using the field name with underscores replaced with spaces and the first letter capitalised. */
labelText: (name?: string) => string;
/** Returns a string containing a label element with the correct 'for' attribute containing the text from field.labelText(name). */
labelHTML: (name: string, id?: string | boolean) => string;
/** Returns an array of default CSS classes considering the field's attributes, e.g. ['field', 'required', 'error'] for a required field with an error message. */
classes: () => string[];
/**
* Calls the iterator with the name and field object as arguments. Defaults to using forms.render.div as the iterator,
* which returns a HTML representation of the field label, error message and widget wrapped in a div.
*/
toHTML: (name?: string, iterator?: FieldIterator) => string;
};
export type FieldBound<Data = unknown, RawData = unknown> = Field<Data> & {
/** The raw value from the request data. */
value: RawData;
/** The request data coerced to the correct format for this field. */
data: Data;
/** An error message if the field fails validation. */
error: string;
/**
* Checks if the field is required and whether it is empty. Then runs the validator functions in order until one fails or they all pass.
* If a validator fails, the resulting message is stored in the field's error attribute.
*/
validate: (form: Form, callback: (err: string, field: Field) => void) => void;
};
export interface Widget extends WidgetParameters {
formatValue: (value: any) => any;
/** Returns a string containing a HTML representation of the widget for the given field. */
toHTML: (name: string, field?: Field) => string;
}
export interface WidgetParameters {
/** Custom classes to add to the rendered widget. */
classes?: string[] | undefined;
/** Custom classes to add to the choices label when applicable (multipleRadio and multipleCheckbox) */
labelClasses?: string[] | undefined;
/** A string representing the widget type, e.g. 'text' or 'checkbox' */
type?: string | undefined;
}
/**
* A function that accepts a bound form, bound field and a callback as arguments.
* It should apply a test to the field to assert its validity.
* Once processing has completed it must call the callback with no arguments if the field is valid or with an error message if the field is invalid.
*/
export type ValidatorFunction = (form: FormBound, field: FieldBound, callback: (err?: string) => void) => void;
export interface FormFields {
[key: string]: Field | FormFields;
}
export type FormHandleCallback<
Fields extends FormFields = FormFields,
Data extends (IncomingMessage | (Partial<FormData<Fields>> & { [key: string]: unknown })) = FormData<Fields>
> = (form: FormBound<Fields, Data extends IncomingMessage ? FormData<Fields> : Data>) => void;
export type FormData<Fields extends FormFields = FormFields> = {
[Key in keyof Fields]: Fields[Key] extends Field
? ReturnType<Fields[Key]["parse"]>
: never
};
export interface Form<Fields extends FormFields = FormFields> {
/** Field objects this form was created with */
fields: Fields;
/** Inspects a request or object literal and binds any data to the correct fields. */
handle: <Data extends IncomingMessage | (Partial<FormData<Fields>> & { [key: string]: unknown })>(
req: Data|undefined,
callbacks: {
success?: FormHandleCallback<Fields, Data> | undefined
error?: FormHandleCallback<Fields, Data> | undefined
empty?: FormHandleCallback<Fields, Data> | undefined
}
) => void;
/** Binds data to correct fields, returning a new bound form object. */
bind: <Data extends Partial<FormData<Fields>>>(data: (Data & { [key: string]: unknown }) | null | undefined) => FormBound<Fields, Data>;
/**
* Runs toHTML on each field returning the result.
* If an iterator is specified, it is called for each field with the field name and object as it's arguments,
* the iterator's results are concatenated to create the HTML output, allowing for highly customised markup.
*/
toHTML: (iterator?: FieldIterator) => string;
}
export interface FormBound<Fields extends FormFields = any, Data extends Partial<FormData<Fields>> = FormData<Fields>> {
/** Object containing all the parsed data keyed by field name. */
data: FormData<Fields> & Data;
/** Calls validate on each field in the bound form and returns the resulting form object to the callback. */
validate: (callback: (err: string, form: FormBound<Fields, Data>) => void) => void;
/** Checks all fields for an error attribute. Returns false if any exist, otherwise returns true. */
isValid: () => boolean;
}
/** Converts a form definition (an object literal containing field objects) into a form object. */
export function create<Fields extends FormFields = FormFields>(fields: Fields, options?: {
/** If false, the first validation error will halt form validation, otherwise all fields will be validated. */
validatePastFirstError?: boolean | undefined
}): Form<Fields>;
export namespace fields {
function array(params?: FieldParameters): Field<unknown[]>;
function boolean(params?: FieldParameters): Field<boolean>;
function date(params?: FieldParameters): Field<string>;
function email(params?: FieldParameters): Field<string>;
function number(params?: FieldParameters): Field<number>;
function password(params?: FieldParameters): Field<string>;
function string(params?: FieldParameters): Field<string>;
function tel(params?: FieldParameters): Field<string>;
function url(params?: FieldParameters): Field<string>;
}
export namespace validators {
function alphanumeric(errorMessage?: string): ValidatorFunction;
function color(errorMessage?: string): ValidatorFunction;
function date(errorMessage?: string): ValidatorFunction;
function digits(errorMessage?: string): ValidatorFunction;
function integer(errorMessage?: string): ValidatorFunction;
function email(errorMessage?: string): ValidatorFunction;
function matchField(matchedField: string, errorMessage?: string): ValidatorFunction;
function matchValue(valueGetter: () => any, errorMessage?: string): ValidatorFunction;
function max(value: number, errorMessage?: string): ValidatorFunction;
function maxlength(value: number, errorMessage?: string): ValidatorFunction;
function min(value: number, errorMessage?: string): ValidatorFunction;
function minlength(value: number, errorMessage?: string): ValidatorFunction;
function range(min: number, max: number, errorMessage?: string): ValidatorFunction;
function rangelength(min: number, max: number, errorMessage?: string): ValidatorFunction;
function regexp(regexp: RegExp, errorMessage?: string): ValidatorFunction;
function required(errorMessage?: string): ValidatorFunction;
function requiresFieldIfEmpty(alternateField: string, errorMessage?: string): ValidatorFunction;
function url(errorMessage?: string): ValidatorFunction;
}
export namespace widgets {
function checkbox(params?: WidgetParameters): Widget;
function color(params?: WidgetParameters): Widget;
function date(params?: WidgetParameters): Widget;
function email(params?: WidgetParameters): Widget;
function hidden(params?: WidgetParameters): Widget;
function number(params?: WidgetParameters): Widget;
function label(params?: WidgetParameters): Widget;
function multipleCheckbox(params?: WidgetParameters): Widget;
function multipleRadio(params?: WidgetParameters): Widget;
function multipleSelect(params?: WidgetParameters): Widget;
function password(params?: WidgetParameters): Widget;
function select(params?: WidgetParameters): Widget;
function tel(params?: WidgetParameters): Widget;
function text(params?: WidgetParameters): Widget;
function textarea(params?: WidgetParameters & { rows?: number | undefined, cols?: number | undefined }): Widget;
}
/** A function which accepts a name and field as arguments and returns a string containing a HTML representation of the field. */
export type RenderFunction = (name: string, field: Field) => string;
export namespace render {
const div: RenderFunction;
const p: RenderFunction;
const li: RenderFunction;
const table: RenderFunction;
} | the_stack |
declare var beeperOutput: HTMLElement;
declare interface BeeperBuffer {
totalLength: number, // The length a "normal" audio frame buffer would occupy.
startValue: boolean, // Beeper value start value for the buffer.
buffer: Uint16Array, // Contains the length of the beeper values.
bufferLen: number // The length of buffer. For some reason buffer.length does not work in the webview.
}
export class ZxAudioBeeper {
// Start latency of the system.
protected MIN_LATENCY = 0.2; //0.05; //0.1;
// Maximum latency. If latency grows bigger audio frames are dropped.
protected MAX_LATENCY = 0.4; //0.1; //0.2;
// When playing is stopped a fade to 0 volume is done to avoid crackling.
// This is the time for fading.
protected FADE_TO_ZERO_TIME = 0.1; // 100 ms
// The audio context.
protected ctx: AudioContext;
// The volume of all samples. [0;1.0]
protected volume: number;
// Stores the sample rate.
protected sampleRate: number;
// To compare time with Z80 time the start time (after frame rate configuration)
// is stored here.
protected audioCtxStartTime: number;
// The value shown to the user. Is here in order not to update to frequently.
protected lastVisualBeeperState: boolean;
// Used to display a value different from 1 and 0 when the speaker value is constantly changing.
protected visualBeeperChanging: boolean;
// Aggregation time for the changing value.
protected BEEPER_DISPLAY_AGGREGATE_TIME = 100; // 100 ms
//protected logBuf = new Array<any>();
// The next audio buffer. Samples are being prepared here.
// When full it is played.
protected nextBuffer: AudioBuffer;
// The samples for nextBuffer.
protected nextFrame: Float32Array;
// The frame length is put here. Is sample rate * buffer size in secs.
protected fixedFrameLength: number;
// The buffer size in secs.
protected fixedFrameTime: number;
// The next frames start time.
protected nextFrameStartTime: number;
// The total length of unplayed samples. Used to limit the latency.
protected bufferedLength = 0;
// Contains the index inside the audio frame of the next to write.
protected nextFrameIndex: number;
// Value is used e.g. to fill gaps. The last audio sample written to the prepared buffer.
protected lastEnqueuedAudioSampleValue: number;
// true: Use values 0 and 1 for beeper 0 and 1. false: Use values -1 and 0 for beeper 0 and 1.
protected samplesInTopHalf: boolean;
// State: true if stopped, false if playing.
protected stopped: boolean;
// The node used to change the volume.
protected gainNode: GainNode;
/**
* Constructor.
*/
constructor(sampleRate: number) {
//sampleRate = 22050;
this.volume = 0.75;
this.ctx = this.createAudioContext(sampleRate);
this.sampleRate = this.ctx.sampleRate;
if (this.sampleRate != sampleRate) {
// Send warning to vscode
vscode.postMessage({
command: 'warning',
text: "Sample rate of " + sampleRate + "Hz could not be set. Try setting it to e.g. " + this.sampleRate + "Hz instead."
});
}
this.fixedFrameLength = Math.ceil(this.MIN_LATENCY/4 * this.sampleRate);
this.fixedFrameTime = this.fixedFrameLength / this.sampleRate;
this.lastEnqueuedAudioSampleValue = 0;
this.lastVisualBeeperState = (this.lastEnqueuedAudioSampleValue != 0);
this.visualBeeperChanging = false;
this.samplesInTopHalf = true;
this.audioCtxStartTime = 0; // Irrelevant while stopped
this.stopped = true;
// Create gain node
this.gainNode = this.ctx.createGain();
this.gainNode.gain.value = 1.0;
//this.gainNode.gain.setValueAtTime(1.0, this.ctx.currentTime);
this.gainNode.connect(this.ctx.destination);
this.prepareNextFrame();
// Visual update
setInterval(() => {
this.updateVisualBeeper();
}, this.BEEPER_DISPLAY_AGGREGATE_TIME);
}
/**
* For testing this function is overwritten to return a mocked AudioContext.
*/
protected createAudioContext(sampleRate: number): AudioContext {
return new AudioContext({sampleRate});
}
/**
* Stops audio.
* Creates a fading audio frame.
*/
public stop() {
if (!this.stopped) {
// Fade
this.startFadeToZero();
}
}
/**
* Sets the volume.
* @param volume [0;1]
*/
public setVolume(volume: number) {
this.volume = volume;
// Use a "ramp" otherwise changing the volume will introduce some noise
this.gainNode.gain.value = this.gainNode.gain.value; // NOSONAR: required, but I don't know why anymore.
this.gainNode.gain.linearRampToValueAtTime(volume, this.ctx.currentTime + 0.1)
}
/**
* Gets the volume.
* @returns volume [0;1]
*/
public getVolume() {
return this.volume;
}
/**
* Creates an audio frame from the beeperBuffer.
* @param beeperBuffer The beeper changes.
*/
public writeBeeperSamples(beeperBuffer: BeeperBuffer) {
const bufLen = beeperBuffer.bufferLen;
const beeperLengths = beeperBuffer.buffer;
// Update display
this.setVisualBeeperState(beeperBuffer);
// Check if it was stopped before
if (this.stopped) {
// Unstop
this.stopped = false;
this.gainNode.gain.value = this.volume;
this.resetTime();
// Fill with gaps to start with
this.lastEnqueuedAudioSampleValue = 0; // The value to use for filling
// At least 2 buffers:
while (this.bufferedLength < 2*this.fixedFrameLength) {
this.startGapFiller();
}
// Now use the new value
//this.lastEnqueuedAudioSampleValue = this.getAudioValueForBeeper(beeperBuffer.startValue);
// Log
/*
this.logBuf.push({
descr: "writeBeeperSamples START after stop",
startValue: beeperBuffer.startValue,
currentGain: this.gainNode.gain.value
});
*/
}
/*
this.logBuf.push({
descr: "writeBeeperSamples start",
startValue: beeperBuffer.startValue,
nextFrameIndex: this.nextFrameIndex,
lastEnqueuedAudioSampleValue: this.lastEnqueuedAudioSampleValue,
lengths: beeperBuffer.buffer
});
*/
// Fill intermediate buffer
let k = 0;
let tmpBuffer = new Float32Array(beeperBuffer.totalLength);
let beeperValue = beeperBuffer.startValue;
let audioValue = this.getAudioValueForBeeper(beeperValue);
this.lastEnqueuedAudioSampleValue = audioValue;
for (let i = 0; i < bufLen; i++) {
// Get length
const length = beeperLengths[i];
// Set all samples to the same value
for (let j = length; j > 0; j--) {
tmpBuffer[k++] = audioValue;
}
this.lastEnqueuedAudioSampleValue = audioValue;
// Alternate for next length
beeperValue = !beeperValue;
audioValue = this.getAudioValueForBeeper(beeperValue);
}
// Check if audio frame can be played
let remainingLen = beeperBuffer.totalLength;
let offset = 0;
while (remainingLen > 0) {
// Check if buffer full
if (this.nextFrameIndex + remainingLen < this.fixedFrameLength) {
// Buffer not yet full.
// Copy bytes to frame buffer
this.nextFrame.set(tmpBuffer.slice(offset, offset + remainingLen), this.nextFrameIndex);
this.nextFrameIndex += remainingLen;
break;
}
// Buffer full
// Copy as much as possible bytes.
const fillLen = this.fixedFrameLength - this.nextFrameIndex;
this.nextFrame.set(tmpBuffer.slice(offset, offset + fillLen), this.nextFrameIndex);
offset += fillLen;
remainingLen -= fillLen;
// Check next start frame time for upper limit.
// This happens if simulation is too fast.
// In this case the start time is reduced ba a few frames is reduced.
if (this.bufferedLength < this.MAX_LATENCY*this.sampleRate+2*this.fixedFrameLength) {
// Latency still OK: Play audio frame
this.playNextFrame("new frame");
}
else {
// Latency too high, too many buffers, drop frame.
// Re-use buffer for next frame
this.nextFrameIndex = 0;
/*
this.logBuf.push({
descr: "frame skipped",
volume: this.volume,
bufferedLength: this.bufferedLength,
nextFrameStartTime: this.nextFrameStartTime,
});
*/
}
}
/*
this.logBuf.push({descr: "writeBeeperSamples end"});
*/
}
/**
* Resets the ctx time.
*/
protected resetTime() {
this.audioCtxStartTime = this.ctx.currentTime;
this.nextFrameStartTime = this.audioCtxStartTime + (this.MIN_LATENCY + this.MAX_LATENCY) / 2;
this.bufferedLength = 0;
/*
this.logBuf.push({
descr: "time reset",
volume: this.volume,
ctxTime: this.audioCtxStartTime,
nextFrameStartTime: this.nextFrameStartTime
});
*/
}
/**
* Prepares an empty frame.
*/
protected prepareNextFrame() {
this.nextBuffer = this.ctx.createBuffer(1, this.fixedFrameLength, this.sampleRate);
this.nextFrame = this.nextBuffer.getChannelData(0);
this.nextFrameIndex = 0;
}
/**
* Returns an audio sample value [-1;1] from the boolean beeper value.
* @param beeperValue true/false. 1/0
* @returns [-1;1]
*/
protected getAudioValueForBeeper(beeperValue: boolean) {
let audioValue = beeperValue ? 1 : 0;
if (!this.samplesInTopHalf)
audioValue -= 1;
return audioValue;
}
/**
* Creates a gap filler frame with all samples containing value
* and starts it at the next starting time.
* Skips creation if lastEnqueuedAudioSampleValue is 0 and there is no
* pending frame.
* I.e. it will immediately return after a fadeToZero frame(s).
*/
protected startGapFiller() {
// Create the (remaining) samples
const frame = this.nextFrame;
const value = this.getLastAudioValue();
for (let i = this.nextFrameIndex; i < this.fixedFrameLength; i++)
frame[i] = value;
// Start gap filler
this.playNextFrame("gap filler frame");
}
/**
* Returns the last decoded audio value.
*/
protected getLastAudioValue(): number {
if (this.nextFrameIndex == 0)
return this.lastEnqueuedAudioSampleValue;
return this.nextFrame[this.nextFrameIndex - 1];
}
/**
* Creates a frame that fades to 0 if current value is 1 or -1.
* The frame is enqueued. It will be the last played frame until another
* writeBeeperSamples is received.
* This happens while stepping in the simulator.
* If current value is already 0 nothing happens, no fade required.
* @param value The audio value to use.
*/
protected startFadeToZero() {
let prevLastAudioSample = this.getLastAudioValue();
// Get current index
const prevIndex = this.nextFrameIndex;
// Push out the current sample
this.startGapFiller();
this.stopped = true;
// Fade out
const currentGain = this.gainNode.gain.value;
this.gainNode.gain.value = currentGain; // Set start time
const fadeStartTime = this.nextFrameStartTime + prevIndex / this.sampleRate;
this.gainNode.gain.linearRampToValueAtTime(currentGain, fadeStartTime); // Stay at volume until end of last frame
this.gainNode.gain.linearRampToValueAtTime(0.0, fadeStartTime + this.FADE_TO_ZERO_TIME); // Set end time
/*
this.logBuf.push({
descr: "startFadeToZero",
currentGain,
nextFrameStartTime: this.nextFrameStartTime,
linearRampToValueAtTime: this.nextFrameStartTime + this.FADE_TO_ZERO_TIME
});
*/
// Next values in upper or lower half
//this.samplesInTopHalf = (prevLastAudioSample < 0);
if (prevLastAudioSample != 0) {
this.samplesInTopHalf = (prevLastAudioSample < 0);
}
}
/**
* Assumes the audio frame (this.nextFrame) is filled and enqueues it for
* playing.
*/
protected playNextFrame(logDescription: string) {
// Create audio source
const bufferSource = this.ctx.createBufferSource();
bufferSource.buffer = this.nextBuffer;
bufferSource.connect(this.gainNode);
// End listener
const self = this;
bufferSource.addEventListener('ended', function () {
self.bufferedLength -= self.fixedFrameLength;
/*
// Log
self.logBuf.push({
descr: "source ended",
bufferedLength: self.bufferedLength,
stopped: self.stopped,
gainValue: self.gainNode.gain.value,
});
*/
if (self.bufferedLength <= self.fixedFrameLength) {
if (!self.stopped || self.gainNode.gain.value > 0) { // If not stopped
// Start gap filler
self.startGapFiller();
return;
}
}
});
// Play (in near future)
bufferSource.start(this.nextFrameStartTime);
this.bufferedLength += this.fixedFrameLength;
/*
// Log
this.logBuf.push({
descr: logDescription,
firstSampleVolume: this.nextFrame[0],
lastSampleVolume: this.nextFrame[this.fixedFrameLength-1],
bufferedLength: this.bufferedLength,
nextFrameStartTime: this.nextFrameStartTime,
ctxTime: this.ctx.currentTime,
frame: new Float32Array(this.nextFrame)
});
*/
// Next frame
this.nextFrameStartTime += this.fixedFrameTime;
this.prepareNextFrame();
}
/**
* Sets the visual state of the beeper: 0 or 1.
*/
protected setVisualBeeperState(beeperBuffer: BeeperBuffer) {
// Check if changing by the length
if (beeperBuffer.bufferLen >= 2) {
this.visualBeeperChanging = true;
// Check if flipped
if (beeperBuffer.bufferLen % 2 == 0) // Even
this.lastVisualBeeperState = beeperBuffer.startValue;
else
this.lastVisualBeeperState = !beeperBuffer.startValue;
}
else {
// Check if start Value changed
if (this.lastVisualBeeperState != beeperBuffer.startValue) {
// Yes, change detected
this.visualBeeperChanging = true;
// Remember value
this.lastVisualBeeperState = beeperBuffer.startValue;
}
}
}
/**
* Called periodically to update the beeper displayed value.
*/
protected updateVisualBeeper() {
if (this.visualBeeperChanging) {
// Display symbol for changing
beeperOutput.textContent = '*';
this.visualBeeperChanging = false;
}
else {
// Display 0 or 1
beeperOutput.textContent = (this.lastVisualBeeperState) ? "1" : "0";
}
}
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace Formmsdyn_projectteam_Information {
interface tab_General_Sections {
_DC58EBA6_D467_4B9A_AAD8_0C471EBDE29F: DevKit.Controls.Section;
General_section_2: DevKit.Controls.Section;
}
interface tab_Proposed_Resources_Sections {
tab_4_section_2: DevKit.Controls.Section;
}
interface tab_Resource_Requirement_Sections {
RequirementSection: DevKit.Controls.Section;
tab_2_section_2: DevKit.Controls.Section;
tab_2_section_3: DevKit.Controls.Section;
}
interface tab_General extends DevKit.Controls.ITab {
Section: tab_General_Sections;
}
interface tab_Proposed_Resources extends DevKit.Controls.ITab {
Section: tab_Proposed_Resources_Sections;
}
interface tab_Resource_Requirement extends DevKit.Controls.ITab {
Section: tab_Resource_Requirement_Sections;
}
interface Tabs {
General: tab_General;
Proposed_Resources: tab_Proposed_Resources;
Resource_Requirement: tab_Resource_Requirement;
}
interface Body {
Tab: Tabs;
IFRAME_ProposalScheduleBoard: DevKit.Controls.IFrame;
/** Select whether the team member is billable */
msdyn_BillingType: DevKit.Controls.OptionSet;
/** Shows the resource. */
msdyn_bookableresourceid: DevKit.Controls.Lookup;
/** Enter the resource team membership start date. */
msdyn_From: DevKit.Controls.Date;
/** Type the name of the custom entity. */
msdyn_name: DevKit.Controls.String;
/** The organizational unit of the resource performing the work. */
msdyn_organizationalunit: DevKit.Controls.Lookup;
/** Select the project that this team members are part of. */
msdyn_project: DevKit.Controls.Lookup;
/** Select whether the team member can approve time and expenses. */
msdyn_ProjectApprover: DevKit.Controls.Boolean;
/** Select the role this team member is playing in this team. */
msdyn_resourcecategory: DevKit.Controls.Lookup;
/** Unique identifier for Resource Requirement associated with Project Team Member. */
msdyn_resourcerequirementid: DevKit.Controls.Lookup;
/** Enter a description of the role for this team member. */
msdyn_RoleDescription: DevKit.Controls.String;
/** Enter the end date of the resource membership in a team. */
msdyn_To: DevKit.Controls.Date;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
}
interface Navigation {
nav_msdyn_msdyn_projectteam_bookableresourcebooking_projectteamid: DevKit.Controls.NavigationItem,
nav_msdyn_msdyn_projectteam_bookableresourcebookingheader_projectteamid: DevKit.Controls.NavigationItem
}
interface quickForm_Requirement_General_Body {
msdyn_allocationmethod: DevKit.Controls.QuickView;
msdyn_city: DevKit.Controls.QuickView;
msdyn_costprice: DevKit.Controls.QuickView;
msdyn_country: DevKit.Controls.QuickView;
msdyn_duration: DevKit.Controls.QuickView;
msdyn_fromdate: DevKit.Controls.QuickView;
msdyn_percentage: DevKit.Controls.QuickView;
msdyn_requeststatus: DevKit.Controls.QuickView;
msdyn_stateorprovince: DevKit.Controls.QuickView;
msdyn_todate: DevKit.Controls.QuickView;
msdyn_type: DevKit.Controls.QuickView;
msdyn_workhourtemplate: DevKit.Controls.QuickView;
TransactionCurrencyId: DevKit.Controls.QuickView;
}
interface quickForm_ProjectTeam_Requirement_Competencies_Body {
}
interface quickForm_ProjectTeam_Requirement_Others_Body {
}
interface quickForm_Requirement_General extends DevKit.Controls.IQuickView {
Body: quickForm_Requirement_General_Body;
}
interface quickForm_ProjectTeam_Requirement_Competencies extends DevKit.Controls.IQuickView {
Body: quickForm_ProjectTeam_Requirement_Competencies_Body;
}
interface quickForm_ProjectTeam_Requirement_Others extends DevKit.Controls.IQuickView {
Body: quickForm_ProjectTeam_Requirement_Others_Body;
}
interface QuickForm {
Requirement_General: quickForm_Requirement_General;
ProjectTeam_Requirement_Competencies: quickForm_ProjectTeam_Requirement_Competencies;
ProjectTeam_Requirement_Others: quickForm_ProjectTeam_Requirement_Others;
}
}
class Formmsdyn_projectteam_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyn_projectteam_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_projectteam_Information */
Body: DevKit.Formmsdyn_projectteam_Information.Body;
/** The Navigation of form msdyn_projectteam_Information */
Navigation: DevKit.Formmsdyn_projectteam_Information.Navigation;
/** The QuickForm of form msdyn_projectteam_Information */
QuickForm: DevKit.Formmsdyn_projectteam_Information.QuickForm;
}
class msdyn_projectteamApi {
/**
* DynamicsCrm.DevKit msdyn_projectteamApi
* @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;
/** 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;
/** Shows the allocation method used to book resources on the project (full capacity, percentage, and so on). */
msdyn_allocationmethod: DevKit.WebApi.OptionSetValue;
/** Shows the number of applicants for this project team. */
msdyn_Applicantcount: DevKit.WebApi.IntegerValueReadonly;
/** Last Updated time of rollup field Applicant count. */
msdyn_Applicantcount_Date_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** State of rollup field Applicant count. */
msdyn_Applicantcount_State: DevKit.WebApi.IntegerValueReadonly;
/** Shows if there are applicants available for this project team. */
msdyn_Applicantsavailable: DevKit.WebApi.BooleanValueReadonly;
/** Type the total assigned hours for project team member. */
msdyn_AssignedHours: DevKit.WebApi.DecimalValue;
/** Select whether the team member is billable */
msdyn_BillingType: DevKit.WebApi.OptionSetValue;
/** Shows the resource. */
msdyn_bookableresourceid: DevKit.WebApi.LookupValue;
/** Shows the calendar used for staffing this project team. */
msdyn_calendarId: DevKit.WebApi.StringValue;
/** Type the system description. */
msdyn_Description: DevKit.WebApi.StringValue;
/** Enter the resource team membership start date. */
msdyn_From_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Hard Booked Hours */
msdyn_hardbookedhours: DevKit.WebApi.DecimalValue;
/** Duplicate for resource requirement */
msdyn_hours: DevKit.WebApi.DecimalValue;
/** Shows the number of hours required of this team member on the project. */
msdyn_HoursRequested: DevKit.WebApi.DoubleValue;
/** Shows the membership status of this project team member. */
msdyn_MembershipStatus: DevKit.WebApi.OptionSetValue;
/** The id of the project team member in MS Project Client. */
msdyn_msprojectclientid: DevKit.WebApi.StringValue;
/** Type the name of the custom entity. */
msdyn_name: DevKit.WebApi.StringValue;
/** Shows the number of resources requested. */
msdyn_Number: DevKit.WebApi.IntegerValue;
/** The organizational unit of the resource performing the work. */
msdyn_organizationalunit: DevKit.WebApi.LookupValue;
/** Duplicate for resource requirement */
msdyn_percentage: DevKit.WebApi.DecimalValue;
/** Select the project that this team members are part of. */
msdyn_project: DevKit.WebApi.LookupValue;
/** Select whether the team member can approve time and expenses. */
msdyn_ProjectApprover: DevKit.WebApi.BooleanValue;
/** Unique identifier for entity instances */
msdyn_projectteamId: DevKit.WebApi.GuidValue;
/** Required hours of team member from team member requirement */
msdyn_requiredhours: DevKit.WebApi.DecimalValue;
/** Select the role this team member is playing in this team. */
msdyn_resourcecategory: DevKit.WebApi.LookupValue;
/** Unique identifier for Resource Requirement associated with Project Team Member. */
msdyn_resourcerequirementid: DevKit.WebApi.LookupValue;
/** Enter a description of the role for this team member. */
msdyn_RoleDescription: DevKit.WebApi.StringValue;
/** Soft Booked Hours */
msdyn_softbookedhours: DevKit.WebApi.DecimalValue;
/** Enter the end date of the resource membership in a team. */
msdyn_To_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Template to use for generic resource's schedule. Will be ignored if its a user or facility resource */
msdyn_worktemplate: DevKit.WebApi.LookupValue;
/** 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;
/** Shows the status of the project team. */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Project Team */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** 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_projectteam {
enum msdyn_allocationmethod {
/** 192350003 */
By_Hours_Distribute_evenly,
/** 192350005 */
By_Hours_Front_load,
/** 192350001 */
Full_Capacity,
/** 192350000 */
None,
/** 192350004 */
Percentage_Capacity
}
enum msdyn_BillingType {
/** 192350001 */
Chargeable,
/** 192350002 */
Complimentary,
/** 192350000 */
Non_Chargeable,
/** 192350003 */
Not_Available
}
enum msdyn_MembershipStatus {
/** 2 */
Assigned,
/** 3 */
Declined,
/** 1 */
Requested
}
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':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import { expect } from "chai";
import * as sinon from "sinon";
import {
AbstractStatusBarCustomItem, AbstractStatusBarItemUtilities, CommonStatusBarItem, ConditionalBooleanValue, ConditionalStringValue,
isAbstractStatusBarActionItem, isAbstractStatusBarCustomItem, isAbstractStatusBarLabelItem, StatusBarItemsManager, StatusBarSection,
} from "../../appui-abstract";
describe("StatusBarItemsManager", () => {
const createCustomItem = (id: string, section: StatusBarSection, itemPriority: number, itemProps?: Partial<AbstractStatusBarCustomItem>): AbstractStatusBarCustomItem => ({
id, section, itemPriority,
isCustom: true,
...itemProps ? itemProps : {},
});
afterEach(() => sinon.restore());
describe("items", () => {
it("should contain 0 items by default", () => {
const sut = new StatusBarItemsManager();
expect(sut.items.length).to.eq(0);
});
});
describe("type guards", () => {
it("should identify label item", () => {
const item = AbstractStatusBarItemUtilities.createLabelItem("ExtensionTest:StatusBarLabel1", StatusBarSection.Center, 100, "icon-hand-2", "Hello", undefined, { isDisabled: true, isHidden: true });
expect(isAbstractStatusBarLabelItem(item)).to.be.true;
expect(isAbstractStatusBarActionItem(item)).to.be.false;
expect(isAbstractStatusBarCustomItem(item)).to.be.false;
expect(ConditionalBooleanValue.getValue(item.isDisabled)).to.be.true;
expect(ConditionalBooleanValue.getValue(item.isHidden)).to.be.true;
});
it("should identify action item", () => {
const item = AbstractStatusBarItemUtilities.createActionItem("ExtensionTest:StatusBarItem1", StatusBarSection.Center, 100, "icon-developer", "test status bar from extension", () => { });
expect(isAbstractStatusBarActionItem(item)).to.be.true;
expect(isAbstractStatusBarLabelItem(item)).to.be.false;
expect(isAbstractStatusBarCustomItem(item)).to.be.false;
});
it("should identify custom item", () => {
const item = createCustomItem("ExtensionTest:StatusBarItem1", StatusBarSection.Center, 100);
expect(isAbstractStatusBarCustomItem(item)).to.be.true;
expect(isAbstractStatusBarActionItem(item)).to.be.false;
expect(isAbstractStatusBarLabelItem(item)).to.be.false;
});
});
describe("add & remove", () => {
it("should instantiate with item", () => {
const item = AbstractStatusBarItemUtilities.createLabelItem("ExtensionTest:StatusBarLabel1", StatusBarSection.Center, 100, "icon-hand-2", "Hello");
const sut = new StatusBarItemsManager([item]);
sut.items.length.should.eq(1);
});
it("should add item without callback", () => {
const item = AbstractStatusBarItemUtilities.createLabelItem("ExtensionTest:StatusBarLabel1", StatusBarSection.Center, 100, "icon-hand-2", "Hello");
const sut = new StatusBarItemsManager();
const spy = sinon.spy();
sut.onItemsChanged.addListener(spy);
sut.loadItems([item]);
spy.calledOnce.should.false;
sut.items.length.should.eq(1);
});
it("should add & remove one item", () => {
const sut = new StatusBarItemsManager();
const item = AbstractStatusBarItemUtilities.createLabelItem("ExtensionTest:StatusBarLabel1", StatusBarSection.Center, 100, "icon-hand-2", "Hello");
expect(isAbstractStatusBarLabelItem(item)).to.be.true;
expect(isAbstractStatusBarActionItem(item)).to.be.false;
sut.add(item);
expect(sut.items.length).to.eq(1);
sut.remove(item.id);
expect(sut.items.length).to.eq(0);
});
it("attempt to set duplicate items ignores it", () => {
const sut = new StatusBarItemsManager();
const item = AbstractStatusBarItemUtilities.createLabelItem("ExtensionTest:StatusBarLabel1", StatusBarSection.Center, 100, "icon-hand-2", "Hello");
sut.add(item);
expect(sut.items.length).to.eq(1);
sut.items = sut.items;
expect(sut.items.length).to.eq(1);
});
it("add ignores duplicate items", () => {
const sut = new StatusBarItemsManager();
const item1 = AbstractStatusBarItemUtilities.createLabelItem("ExtensionTest:StatusBarLabel1", StatusBarSection.Center, 100, "icon-hand-2", "Hello");
const item2 = AbstractStatusBarItemUtilities.createLabelItem("ExtensionTest:StatusBarLabel1", StatusBarSection.Center, 100, "icon-hand-2", "Hello");
sut.add([item1, item2]);
sut.items.length.should.eq(1);
});
it("attempt to add duplicate item ignores it", () => {
const sut = new StatusBarItemsManager();
const item = AbstractStatusBarItemUtilities.createLabelItem("ExtensionTest:StatusBarLabel1", StatusBarSection.Center, 100, "icon-hand-2", "Hello");
sut.add(item);
expect(sut.items.length).to.eq(1);
sut.add(item);
expect(sut.items.length).to.eq(1);
});
it("should add & remove multiple items to StatusBarManager items", () => {
const sut = new StatusBarItemsManager();
const items: CommonStatusBarItem[] = [
AbstractStatusBarItemUtilities.createLabelItem("ExtensionTest:StatusBarLabel1", StatusBarSection.Center, 100, "icon-hand-2", "Hello"),
AbstractStatusBarItemUtilities.createActionItem("ExtensionTest:StatusBarItem2", StatusBarSection.Center, 100, "icon-developer", "test status bar from extension", () => { }),
createCustomItem("ExtensionTest:StatusBarItem3", StatusBarSection.Center, 100),
];
sut.add(items);
expect(sut.items.length).to.eq(3);
const itemIds = items.map((item) => item.id);
sut.remove(itemIds);
expect(sut.items.length).to.eq(0);
});
it("add via load should not trigger listener", () => {
const sut = new StatusBarItemsManager();
const items: CommonStatusBarItem[] = [
AbstractStatusBarItemUtilities.createLabelItem("ExtensionTest:StatusBarLabel1", StatusBarSection.Center, 100, "icon-hand-2", "Hello"),
AbstractStatusBarItemUtilities.createActionItem("ExtensionTest:StatusBarItem2", StatusBarSection.Center, 100, "icon-developer", "test status bar from extension", () => { }),
createCustomItem("ExtensionTest:StatusBarItem3", StatusBarSection.Center, 100),
];
const spy = sinon.spy();
sut.onItemsChanged.addListener(spy);
sut.loadItems(items);
spy.calledOnce.should.false;
expect(sut.items.length).to.eq(3);
spy.resetHistory();
sut.removeAll();
spy.calledOnce.should.false;
expect(sut.items.length).to.eq(0);
});
});
describe("uisync", () => {
let isVisible = true;
let isEnabled = true;
const setVisibility = (value: boolean) => { isVisible = value; };
const setEnabled = (value: boolean) => { isEnabled = value; };
const syncId = "test-on-display-changed";
const hiddenCondition = new ConditionalBooleanValue(() => !isVisible, [syncId]);
const disabledCondition = new ConditionalBooleanValue(() => !isEnabled, [syncId]);
const conditionalLabel = new ConditionalStringValue(() => isVisible ? "Hello" : "Goodbye", [syncId]);
const conditionalIcon = new ConditionalStringValue(() => isVisible ? "icon-hand-2" : "icon-hand", [syncId]);
const toolTipConditional = new ConditionalStringValue(() => isVisible ? "default tooltip" : "new tooltip", [syncId]);
const sut = new StatusBarItemsManager();
const item1 = AbstractStatusBarItemUtilities.createLabelItem("ExtensionTest:StatusBarLabel1", StatusBarSection.Center, 100, "icon-hand-2", conditionalLabel, undefined,
{ isHidden: hiddenCondition }); // try to init isVisible to false but this should be reset when loaded due to condition function
const item2 = AbstractStatusBarItemUtilities.createLabelItem("ExtensionTest:StatusBarLabel2", StatusBarSection.Center, 110, conditionalIcon, "Hello", undefined,
{ isDisabled: disabledCondition });
const sb3 = AbstractStatusBarItemUtilities.createActionItem("ExtensionTest:StatusBarItem3", StatusBarSection.Center, 120, "icon-developer", toolTipConditional, () => { });
sut.add([item1, item2, sb3]);
const syncIds = StatusBarItemsManager.getSyncIdsOfInterest(sut.items);
expect(syncIds.length).to.be.eq(1);
expect(syncIds[0]).to.be.eq(syncId);
let actionItem = sut.items.find((i) => i.id === "ExtensionTest:StatusBarLabel1");
expect(ConditionalBooleanValue.getValue(actionItem!.isHidden)).to.be.false;
expect(isAbstractStatusBarLabelItem(actionItem!)).to.be.true;
if (isAbstractStatusBarLabelItem(actionItem!)) {
expect(ConditionalStringValue.getValue(actionItem.label)).to.be.equal("Hello");
}
let stageItem = sut.items.find((i) => i.id === "ExtensionTest:StatusBarLabel2");
expect(ConditionalBooleanValue.getValue(stageItem!.isDisabled)).to.be.false;
if (isAbstractStatusBarLabelItem(stageItem!)) {
expect(ConditionalStringValue.getValue(stageItem.icon)).to.be.equal("icon-hand-2");
}
let item3 = sut.items.find((i) => i.id === "ExtensionTest:StatusBarItem3");
expect(ConditionalBooleanValue.getValue(item3!.isDisabled)).to.be.false;
if (isAbstractStatusBarActionItem(item3!)) {
expect(ConditionalStringValue.getValue(item3.tooltip)).to.be.equal("default tooltip");
}
setVisibility(false);
setEnabled(false);
const syncIdSet = new Set<string>([syncId]);
sut.refreshAffectedItems(syncIdSet);
actionItem = sut.items.find((i) => i.id === "ExtensionTest:StatusBarLabel1");
expect(ConditionalBooleanValue.getValue(actionItem!.isHidden)).to.be.true;
expect(isAbstractStatusBarLabelItem(actionItem!)).to.be.true;
if (isAbstractStatusBarLabelItem(actionItem!)) {
expect(ConditionalStringValue.getValue(actionItem.label)).to.be.equal("Goodbye");
}
stageItem = sut.items.find((i) => i.id === "ExtensionTest:StatusBarLabel2");
expect(ConditionalBooleanValue.getValue(stageItem!.isDisabled)).to.be.true;
expect(isAbstractStatusBarLabelItem(stageItem!)).to.be.true;
if (isAbstractStatusBarLabelItem(stageItem!)) {
expect(ConditionalStringValue.getValue(stageItem.icon)).to.be.equal("icon-hand");
}
item3 = sut.items.find((i) => i.id === "ExtensionTest:StatusBarItem3");
expect(ConditionalBooleanValue.getValue(item3!.isDisabled)).to.be.false;
if (isAbstractStatusBarActionItem(item3!)) {
expect(ConditionalStringValue.getValue(item3.tooltip)).to.be.equal("new tooltip");
}
});
}); | the_stack |
import { decimalStr, mweiStr } from '../utils/Converter';
import { logGas } from '../utils/Log';
import { ProxyContext, getProxyContext } from '../utils/ProxyContextV2';
import { assert } from 'chai';
import * as contracts from '../utils/Contracts';
let lp: string;
let project: string;
let trader: string;
let config = {
lpFeeRate: decimalStr("0.002"),
mtFeeRate: decimalStr("0.001"),
k: decimalStr("0.1"),
i: decimalStr("100"),
};
async function init(ctx: ProxyContext): Promise<void> {
lp = ctx.SpareAccounts[0];
project = ctx.SpareAccounts[1];
trader = ctx.SpareAccounts[2];
await ctx.mintTestToken(lp, ctx.DODO, decimalStr("1000000"));
await ctx.mintTestToken(project, ctx.DODO, decimalStr("1000000"));
await ctx.mintTestToken(lp, ctx.USDT, mweiStr("1000000"));
await ctx.mintTestToken(project, ctx.USDT, mweiStr("1000000"));
await ctx.approveProxy(lp);
await ctx.approveProxy(project);
await ctx.approveProxy(trader);
}
async function initCreateDPP(ctx: ProxyContext, token0: string, token1: string, token0Amount: string, token1Amount: string, ethValue: string, i: string): Promise<string> {
let PROXY = ctx.DODOProxyV2;
await PROXY.methods.createDODOPrivatePool(
token0,
token1,
token0Amount,
token1Amount,
config.lpFeeRate,
i,
config.k,
false,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
).send(ctx.sendParam(project, ethValue));
if (token0 == '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE') token0 = ctx.WETH.options.address;
if (token1 == '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE') token1 = ctx.WETH.options.address;
var addr = await ctx.DPPFactory.methods._REGISTRY_(token0, token1, 0).call();
return addr;
}
async function initCreateDVM(ctx: ProxyContext, token0: string, token1: string, token0Amount: string, token1Amount: string, ethValue: string, i: string): Promise<string> {
let PROXY = ctx.DODOProxyV2;
await PROXY.methods.createDODOVendingMachine(
token0,
token1,
token0Amount,
token1Amount,
config.lpFeeRate,
i,
config.k,
false,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
).send(ctx.sendParam(project, ethValue));
if (token0 == '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE') token0 = ctx.WETH.options.address;
if (token1 == '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE') token1 = ctx.WETH.options.address;
var addr = await ctx.DVMFactory.methods._REGISTRY_(token0, token1, 0).call();
return addr;
}
async function initIncentive(ctx: ProxyContext): Promise<void> {
await ctx.DODOIncentive.methods.changePerReward(decimalStr("10")).send(ctx.sendParam(ctx.Deployer));
await ctx.mintTestToken(ctx.DODOIncentive.options.address, ctx.DODO, decimalStr("1000000"));
}
describe("DODOProxyV2.0", () => {
let snapshotId: string;
let ctx: ProxyContext;
let dpp_DODO_USDT: string;
let dvm_WETH_USDT: string;
before(async () => {
let ETH = await contracts.newContract(
contracts.WETH_CONTRACT_NAME
);
ctx = await getProxyContext(ETH.options.address);
await init(ctx);
dpp_DODO_USDT = await initCreateDPP(ctx, ctx.DODO.options.address, ctx.USDT.options.address, decimalStr("100000"), mweiStr("20000"), "0", mweiStr("0.2"));
dvm_WETH_USDT = await initCreateDVM(ctx, '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', ctx.USDT.options.address, decimalStr("5"), mweiStr("3000"), "5", mweiStr("600"));
console.log("dpp_DODO_USDT:", dpp_DODO_USDT);
console.log("dvm_WETH_USDT:", dvm_WETH_USDT);
await initIncentive(ctx);
});
beforeEach(async () => {
snapshotId = await ctx.EVM.snapshot();
});
afterEach(async () => {
await ctx.EVM.reset(snapshotId);
});
describe("DODOIncentive", () => {
it("incentive-switch with trade", async () => {
await ctx.DODOIncentive.methods.changePerReward(decimalStr("10")).send(ctx.sendParam(ctx.Deployer));
var totalReward = await ctx.DODOIncentive.methods.totalReward().call();
var totalDistribution = await ctx.DODOIncentive.methods.totalDistribution().call();
console.log("Init - Total Reward:" + totalReward + "; Total distribution:" + totalDistribution);
//Aim to increase block
await ctx.mintTestToken(lp, ctx.DODO, decimalStr("1000"));
await ctx.mintTestToken(lp, ctx.DODO, decimalStr("1000"));
await ctx.mintTestToken(lp, ctx.DODO, decimalStr("1000"));
await ctx.DODOIncentive.methods.changePerReward(0).send(ctx.sendParam(ctx.Deployer));
totalReward = await ctx.DODOIncentive.methods.totalReward().call();
totalDistribution = await ctx.DODOIncentive.methods.totalDistribution().call();
console.log("Close incentive - Total Reward:" + totalReward + "; Total distribution:" + totalDistribution);
//Aim to increase block
await ctx.mintTestToken(lp, ctx.DODO, decimalStr("1000"));
await ctx.mintTestToken(lp, ctx.DODO, decimalStr("1000"));
await ctx.mintTestToken(lp, ctx.DODO, decimalStr("1000"));
await ctx.DODOIncentive.methods.changePerReward(decimalStr("10")).send(ctx.sendParam(ctx.Deployer));
//Aim to increase block
await ctx.mintTestToken(lp, ctx.DODO, decimalStr("1000"));
await ctx.mintTestToken(lp, ctx.DODO, decimalStr("1000"));
await ctx.mintTestToken(lp, ctx.DODO, decimalStr("1000"));
await ctx.DODOIncentive.methods.changePerReward(decimalStr("10")).send(ctx.sendParam(ctx.Deployer));
totalReward = await ctx.DODOIncentive.methods.totalReward().call();
totalDistribution = await ctx.DODOIncentive.methods.totalDistribution().call();
console.log("End incentive - Total Reward:" + totalReward + "; Total distribution:" + totalDistribution);
assert(totalReward, decimalStr("100"));
});
it("incentive-changeBoost with trade", async () => {
await ctx.DODOIncentive.methods.changePerReward(decimalStr("10")).send(ctx.sendParam(ctx.Deployer));
var totalReward = await ctx.DODOIncentive.methods.totalReward().call();
var totalDistribution = await ctx.DODOIncentive.methods.totalDistribution().call();
console.log("Init - Total Reward:" + totalReward + "; Total distribution:" + totalDistribution);
//Aim to increase block
await ctx.mintTestToken(lp, ctx.DODO, decimalStr("1000"));
await ctx.mintTestToken(lp, ctx.DODO, decimalStr("1000"));
await ctx.mintTestToken(lp, ctx.DODO, decimalStr("1000"));
await ctx.DODOIncentive.methods.changePerReward(decimalStr("20")).send(ctx.sendParam(ctx.Deployer));
totalReward = await ctx.DODOIncentive.methods.totalReward().call();
totalDistribution = await ctx.DODOIncentive.methods.totalDistribution().call();
console.log("change incentive - Total Reward:" + totalReward + "; Total distribution:" + totalDistribution);
//Aim to increase block
await ctx.mintTestToken(lp, ctx.DODO, decimalStr("1000"));
await ctx.mintTestToken(lp, ctx.DODO, decimalStr("1000"));
await ctx.mintTestToken(lp, ctx.DODO, decimalStr("1000"));
await ctx.DODOIncentive.methods.changePerReward(decimalStr("10")).send(ctx.sendParam(ctx.Deployer));
totalReward = await ctx.DODOIncentive.methods.totalReward().call();
totalDistribution = await ctx.DODOIncentive.methods.totalDistribution().call();
console.log("End incentive - Total Reward:" + totalReward + "; Total distribution:" + totalDistribution);
assert(totalReward, decimalStr("140"));
});
it("tigger - incentive", async () => {
await ctx.mintTestToken(trader, ctx.DODO, decimalStr("2000"));
var b_DODO = await ctx.DODO.methods.balanceOf(trader).call()
var b_USDT = await ctx.USDT.methods.balanceOf(trader).call()
console.log("Before DODO:" + b_DODO + "; USDT:" + b_USDT);
var b_totalReward = await ctx.DODOIncentive.methods.totalReward().call();
var b_totalDistribution = await ctx.DODOIncentive.methods.totalDistribution().call();
console.log("Before Total Reward:" + b_totalReward + "; Total distribution:" + b_totalDistribution)
var dodoPairs = [
dpp_DODO_USDT
]
var directions = 0
await logGas(await ctx.DODOProxyV2.methods.dodoSwapV2TokenToToken(
ctx.DODO.options.address,
ctx.USDT.options.address,
decimalStr("500"),
1,
dodoPairs,
directions,
false,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(trader), "swap without incentive first");
await logGas(await ctx.DODOProxyV2.methods.dodoSwapV2TokenToToken(
ctx.DODO.options.address,
ctx.USDT.options.address,
decimalStr("500"),
1,
dodoPairs,
directions,
false,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(trader), "swap without incentive second");
var a_DODO = await ctx.DODO.methods.balanceOf(trader).call()
var a_USDT = await ctx.USDT.methods.balanceOf(trader).call()
console.log("After No Incentive DODO:" + a_DODO + "; USDT:" + a_USDT);
await logGas(await ctx.DODOProxyV2.methods.dodoSwapV2TokenToToken(
ctx.DODO.options.address,
ctx.USDT.options.address,
decimalStr("500"),
1,
dodoPairs,
directions,
true,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(trader), "swap with incentive first");
await logGas(await ctx.DODOProxyV2.methods.dodoSwapV2TokenToToken(
ctx.DODO.options.address,
ctx.USDT.options.address,
decimalStr("500"),
1,
dodoPairs,
directions,
true,
Math.floor(new Date().getTime() / 1000 + 60 * 10)
), ctx.sendParam(trader), "swap with incentive second");
var a_totalReward = await ctx.DODOIncentive.methods.totalReward().call();
var a_totalDistribution = await ctx.DODOIncentive.methods.totalDistribution().call();
console.log("After Total Reward:" + a_totalReward + "; Total distribution:" + a_totalDistribution)
a_DODO = await ctx.DODO.methods.balanceOf(trader).call()
a_USDT = await ctx.USDT.methods.balanceOf(trader).call()
console.log("After Incentive DODO:" + a_DODO + "; USDT:" + a_USDT);
assert(a_DODO, "1095000000000000000");
});
});
}); | the_stack |
import { ethers, network } from "hardhat"
import { expect } from "chai"
import { getBigNumber } from "./utilities"
const JOE_ADDRESS = "0x6e84a6216eA6dACC71eE8E6b0a5B7322EEbC0fDd"
const WAVAX_ADDRESS = "0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7"
const USDT_ADDRESS = "0xc7198437980c041c805A1EDcbA50c1Ce5db95118"
const USDC_ADDRESS = "0xA7D7079b0FEaD91F3e65f86E8915Cb59c1a4C664"
const DAI_ADDRESS = "0xd586E7F844cEa2F87f50152665BCbc2C279D8d70"
const WBTC_ADDRESS = "0x50b7545627a5162F82A992c33b87aDc75187B218"
const LINK_ADDRESS = "0x5947BB275c521040051D82396192181b413227A3"
const TRACTOR_ADDRESS = "0x542fA0B261503333B90fE60c78F2BeeD16b7b7fD"
const ROUTER_ADDRESS = "0x60aE616a2155Ee3d9A68541Ba4544862310933d4"
const JOEAVAX_ADDRESS = "0x454E67025631C065d3cFAD6d71E6892f74487a15"
const LINKAVAX_ADDRESS = "0x6F3a0C89f611Ef5dC9d96650324ac633D02265D3"
const DAIAVAX_ADDRESS = "0x87Dee1cC9FFd464B79e058ba20387c1984aed86a"
const USDCAVAX_ADDRESS = "0xa389f9430876455c36478deea9769b7ca4e3ddb1"
const TRACTORAVAX_ADDRESS = "0x601e0f63be88a52b79dbac667d6b4a167ce39113"
const LINKUSDC_ADDRESS = "0xb9f425bc9af072a91c423e31e9eb7e04f226b39d"
const JOEUSDT_ADDRESS = "0x1643de2efB8e35374D796297a9f95f64C082a8ce"
const USDCDAI_ADDRESS = "0x63ABE32d0Ee76C05a11838722A63e012008416E6"
const WBTCUSDC_ADDRESS = "0x62475f52add016a06b398aa3b2c2f2e540d36859"
const FACTORY_ADDRESS = "0x9Ad6C38BE94206cA50bb0d90783181662f0Cfa10"
const ZAP_ADDRESS = "0x2C7B8e971c704371772eDaf16e0dB381A8D02027"
const BAR_ADDRESS = "0x57319d41F71E81F3c65F2a47CA4e001EbAFd4F33"
// Test values in order to be sure JoeMakerV3 converts as much as JoeMakerV1
const barBalanceJOEAVAX = "67845624860978841228702792"
const barBalanceDAIUSDC = "67845624656456566165626771"
describe("joeMakerV3", function () {
before(async function () {
// ABIs
this.joeMakerV3CF = await ethers.getContractFactory("JoeMakerV3")
this.joeMakerCF = await ethers.getContractFactory("JoeMaker")
this.ERC20CF = await ethers.getContractFactory("JoeERC20")
this.ZapCF = await ethers.getContractFactory("Zap")
this.PairCF = await ethers.getContractFactory("JoePair")
this.RouterCF = await ethers.getContractFactory("JoeRouter02")
// Account
this.signers = await ethers.getSigners()
this.dev = this.signers[0]
this.alice = this.signers[1]
// Contracts
this.factory = await ethers.getContractAt("JoeFactory", FACTORY_ADDRESS)
this.zap = await this.ZapCF.attach(ZAP_ADDRESS, this.dev)
this.router = await this.RouterCF.attach(ROUTER_ADDRESS, this.dev)
// Tokens
this.wavax = await ethers.getContractAt("IWAVAX", WAVAX_ADDRESS, this.dev)
this.joe = await this.ERC20CF.attach(JOE_ADDRESS)
this.usdt = await this.ERC20CF.attach(USDT_ADDRESS)
this.usdc = await this.ERC20CF.attach(USDC_ADDRESS)
this.dai = await this.ERC20CF.attach(DAI_ADDRESS)
this.link = await this.ERC20CF.attach(LINK_ADDRESS)
this.wbtc = await this.ERC20CF.attach(WBTC_ADDRESS)
this.tractor = await this.ERC20CF.attach(TRACTOR_ADDRESS)
// Pairs
this.joeAvax = await this.PairCF.attach(JOEAVAX_ADDRESS, this.dev)
this.linkAvax = await this.PairCF.attach(LINKAVAX_ADDRESS, this.dev)
this.daiAvax = await this.PairCF.attach(DAIAVAX_ADDRESS, this.dev)
this.usdcAvax = await this.PairCF.attach(USDCAVAX_ADDRESS, this.dev)
this.linkUsdc = await this.PairCF.attach(LINKUSDC_ADDRESS, this.dev)
this.joeUsdt = await this.PairCF.attach(JOEUSDT_ADDRESS, this.dev)
this.usdcDai = await this.PairCF.attach(USDCDAI_ADDRESS, this.dev)
this.wbtcUsdc = await this.PairCF.attach(WBTCUSDC_ADDRESS, this.dev)
this.tractorAvax = await this.PairCF.attach(TRACTORAVAX_ADDRESS, this.dev)
})
beforeEach(async function () {
// We reset the state before each tests
await network.provider.request({
method: "hardhat_reset",
params: [
{
forking: {
jsonRpcUrl: "https://api.avax.network/ext/bc/C/rpc",
blockNumber: 6394745,
},
live: false,
saveDeployments: true,
tags: ["test", "local"],
},
],
})
// We redeploy JoeMakerV3 for each tests too
this.joeMakerV3 = await this.joeMakerV3CF.deploy(FACTORY_ADDRESS, BAR_ADDRESS, JOE_ADDRESS, WAVAX_ADDRESS)
await this.joeMakerV3.deployed()
})
describe("setBridge", function () {
it("does not allow to set bridge for Joe", async function () {
await expect(this.joeMakerV3.setBridge(this.joe.address, this.wavax.address)).to.be.revertedWith("JoeMakerV3: Invalid bridge")
})
it("does not allow to set bridge for WAVAX", async function () {
await expect(this.joeMakerV3.setBridge(this.wavax.address, this.joe.address)).to.be.revertedWith("JoeMakerV3: Invalid bridge")
})
it("does not allow to set bridge to itself", async function () {
await expect(this.joeMakerV3.setBridge(this.dai.address, this.dai.address)).to.be.revertedWith("JoeMakerV3: Invalid bridge")
})
it("emits correct event on bridge", async function () {
await expect(this.joeMakerV3.setBridge(this.dai.address, this.joe.address))
.to.emit(this.joeMakerV3, "LogBridgeSet")
.withArgs(this.dai.address, this.joe.address)
})
})
describe("convert", function () {
it("should convert JOE - AVAX", async function () {
await this.zap.zapIn(this.joeAvax.address, { value: "2000000000000000000" })
await this.joeAvax.transfer(this.joeMakerV3.address, await this.joeAvax.balanceOf(this.dev.address))
await this.joeMakerV3.convert(this.joe.address, this.wavax.address)
expect(await this.joe.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect(await this.joeAvax.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect(await this.joe.balanceOf(BAR_ADDRESS)).to.equal(barBalanceJOEAVAX)
})
it("should convert JOE - AVAX using JoeMakerV1 to make sure V3 converts as much as V1", async function () {
this.joeMaker = await this.joeMakerCF.deploy(FACTORY_ADDRESS, BAR_ADDRESS, JOE_ADDRESS, WAVAX_ADDRESS)
await this.joeMaker.deployed()
await this.zap.zapIn(this.joeAvax.address, { value: "2000000000000000000" })
await this.joeAvax.transfer(this.joeMaker.address, await this.joeAvax.balanceOf(this.dev.address))
await this.joeMaker.convert(this.joe.address, this.wavax.address)
expect(await this.joe.balanceOf(this.joeMaker.address)).to.equal(0)
expect(await this.joeAvax.balanceOf(this.joeMaker.address)).to.equal(0)
expect(await this.joe.balanceOf(BAR_ADDRESS)).to.equal(barBalanceJOEAVAX)
})
it("should convert USDC - AVAX", async function () {
await this.zap.zapIn(this.usdcAvax.address, { value: "2000000000000000000" })
await this.usdcAvax.transfer(this.joeMakerV3.address, await this.usdcAvax.balanceOf(this.dev.address))
await this.joeMakerV3.convert(this.usdc.address, this.wavax.address)
expect(await this.joe.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect(await this.usdcAvax.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect(await this.joe.balanceOf(BAR_ADDRESS)).to.equal("67845624709410908108101276")
})
it("should convert LINK - AVAX", async function () {
await this.zap.zapIn(this.linkAvax.address, { value: "2000000000000000000" })
await this.linkAvax.transfer(this.joeMakerV3.address, await this.linkAvax.balanceOf(this.dev.address))
await this.joeMakerV3.convert(this.link.address, this.wavax.address)
expect(await this.joe.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect(await this.linkAvax.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect(await this.joe.balanceOf(BAR_ADDRESS)).to.equal("67845624709451838911952369")
})
it("reverts if convert is called by non auth", async function () {
await this.zap.zapIn(this.joeAvax.address, { value: "2000000000000000000" })
await this.joeAvax.transfer(this.joeMakerV3.address, await this.joeAvax.balanceOf(this.dev.address))
await expect(this.joeMakerV3.connect(this.alice).convert(this.joe.address, this.wavax.address)).to.be.revertedWith("JoeMakerV3: FORBIDDEN")
})
it("should convert USDT - JOE", async function () {
await this.zap.zapIn(this.joeUsdt.address, { value: "2000000000000000000" })
await this.joeUsdt.transfer(this.joeMakerV3.address, await this.joeUsdt.balanceOf(this.dev.address))
await this.joeMakerV3.convert(this.usdt.address, this.joe.address)
expect(await this.joe.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect(await this.joeUsdt.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect(await this.joe.balanceOf(BAR_ADDRESS)).to.equal("67845624860644069497935644")
})
it("should convert using standard AVAX path", async function () {
await this.zap.zapIn(this.daiAvax.address, { value: "2000000000000000000" })
await this.daiAvax.transfer(this.joeMakerV3.address, await this.daiAvax.balanceOf(this.dev.address))
await this.joeMakerV3.convert(this.dai.address, this.wavax.address)
expect(await this.joe.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect(await this.daiAvax.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect(await this.joe.balanceOf(BAR_ADDRESS)).to.equal("67845624709488609524599005")
})
it("converts LINK/USDC using more complex path", async function () {
await this.zap.zapIn(this.linkUsdc.address, { value: "2000000000000000000" })
await this.linkUsdc.transfer(this.joeMakerV3.address, await this.linkUsdc.balanceOf(this.dev.address))
await this.joeMakerV3.setBridge(this.usdt.address, this.joe.address)
await this.joeMakerV3.setBridge(this.usdc.address, this.usdt.address)
await this.joeMakerV3.convert(this.link.address, this.usdc.address)
expect(await this.joe.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect(await this.linkUsdc.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect(await this.joe.balanceOf(BAR_ADDRESS)).to.equal("67845624540931902552332917")
})
it("converts DAI/USDC using more complex path", async function () {
await this.zap.zapIn(this.usdcDai.address, { value: "2000000000000000000" })
await this.usdcDai.transfer(this.joeMakerV3.address, await this.usdcDai.balanceOf(this.dev.address))
await this.joeMakerV3.setBridge(this.usdc.address, this.joe.address)
await this.joeMakerV3.setBridge(this.dai.address, this.usdc.address)
await this.joeMakerV3.convert(this.dai.address, this.usdc.address)
expect(await this.joe.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect(await this.usdcDai.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect(await this.joe.balanceOf(BAR_ADDRESS)).to.equal(barBalanceDAIUSDC)
})
it("converts DAI/USDC using more complex path and JoeMakerV1 to make sure V3 converts as much as V1", async function () {
this.joeMaker = await this.joeMakerCF.deploy(FACTORY_ADDRESS, BAR_ADDRESS, JOE_ADDRESS, WAVAX_ADDRESS)
await this.joeMaker.deployed()
await this.zap.zapIn(this.usdcDai.address, { value: "2000000000000000000" })
await this.usdcDai.transfer(this.joeMaker.address, await this.usdcDai.balanceOf(this.dev.address))
await this.joeMaker.setBridge(this.usdc.address, this.joe.address)
await this.joeMaker.setBridge(this.dai.address, this.usdc.address)
await this.joeMaker.convert(this.dai.address, this.usdc.address)
expect(await this.joe.balanceOf(this.joeMaker.address)).to.equal(0)
expect(await this.usdcDai.balanceOf(this.joeMaker.address)).to.equal(0)
expect(await this.joe.balanceOf(BAR_ADDRESS)).to.equal(barBalanceDAIUSDC)
})
it("should convert reflect tokens TRACTOR/AVAX", async function () {
const reserves = await this.tractorAvax.getReserves()
const reserve0 = reserves["_reserve0"]
const reserve1 = reserves["_reserve1"]
// We swap 1 $AVAX for $TRACTOR, 2% cause of the reflect token and 0.3% Fees on swap.
const amountOutWithFeesAndReflectFees = reserve0.mul(getBigNumber(1)).div(reserve1).mul("98").div("100").mul("997").div("1000")
await this.router.swapAVAXForExactTokens(
amountOutWithFeesAndReflectFees,
[this.wavax.address, this.tractor.address],
this.dev.address,
"1111111111111111",
{ value: "1000000000000000000" }
)
// We get the exact balance.
const balance = await this.tractor.balanceOf(this.dev.address)
this.tractor.approve(this.router.address, "100000000000000000000000000")
this.router.addLiquidityAVAX(this.tractor.address, balance, "0", "0", this.joeMakerV3.address, "11111111111111111", {
value: "1000000000000000000",
})
await this.joeMakerV3.convert(this.tractor.address, this.wavax.address)
expect(await this.joe.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect(await this.usdcDai.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect(await this.joe.balanceOf(BAR_ADDRESS)).to.equal("67845618054287432177393232")
})
it("reverts if it loops back", async function () {
await this.zap.zapIn(this.usdcDai.address, { value: "2000000000000000000" })
await this.usdcDai.transfer(this.joeMakerV3.address, await this.wbtcUsdc.balanceOf(this.dev.address))
await this.joeMakerV3.setBridge(this.wbtc.address, this.usdc.address)
await this.joeMakerV3.setBridge(this.usdc.address, this.wbtc.address)
await expect(this.joeMakerV3.convert(this.dai.address, this.usdc.address)).to.be.reverted
})
it("reverts if caller is not EOA", async function () {
const exploiterCF = await ethers.getContractFactory("JoeMakerExploitMock")
const exploiter = await exploiterCF.deploy(this.joeMakerV3.address)
await exploiter.deployed()
await this.zap.zapIn(this.joeAvax.address, { value: "2000000000000000000" })
await this.joeAvax.transfer(this.joeMakerV3.address, await this.wbtcUsdc.balanceOf(this.dev.address))
await expect(exploiter.convert(this.joe.address, this.wavax.address)).to.be.revertedWith("JoeMakerV3: must use EOA")
})
it("reverts if pair does not exist", async function () {
await expect(this.joeMakerV3.convert(this.joe.address, this.joeAvax.address)).to.be.revertedWith("JoeMakerV3: Invalid pair")
})
})
describe("convertMultiple", function () {
it("should allow to convert multiple", async function () {
await this.zap.zapIn(this.daiAvax.address, { value: "2000000000000000000" })
await this.zap.zapIn(this.joeAvax.address, { value: "2000000000000000000" })
await this.daiAvax.transfer(this.joeMakerV3.address, await this.daiAvax.balanceOf(this.dev.address))
await this.joeAvax.transfer(this.joeMakerV3.address, await this.joeAvax.balanceOf(this.dev.address))
await this.joeMakerV3.convertMultiple([this.dai.address, this.joe.address], [this.wavax.address, this.wavax.address])
expect(await this.joe.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect(await this.daiAvax.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect(await this.joe.balanceOf(BAR_ADDRESS)).to.equal("67845675227962521286137397")
})
})
describe("devCut", function () {
it("should redirect 50% of JOE to dev address", async function () {
await this.joeMakerV3.setDevAddr(this.dev.address)
await this.joeMakerV3.setDevCut("5000")
this.wavaxERC20 = await this.ERC20CF.attach(WAVAX_ADDRESS)
const barBalance = await this.joe.balanceOf(BAR_ADDRESS)
const devBalance = await this.wavaxERC20.balanceOf(this.dev.address)
await this.zap.zapIn(this.usdcAvax.address, { value: "2000000000000000000" })
await this.usdcAvax.transfer(this.joeMakerV3.address, await this.usdcAvax.balanceOf(this.dev.address))
await this.joeMakerV3.convert(this.usdc.address, this.wavax.address)
expect(await this.joe.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect(await this.usdcAvax.balanceOf(this.joeMakerV3.address)).to.equal(0)
expect((await this.joe.balanceOf(BAR_ADDRESS)) - barBalance).to.be.greaterThan(0)
expect((await this.wavaxERC20.balanceOf(this.dev.address)) - devBalance).to.be.greaterThan(0)
})
})
after(async function () {
await network.provider.request({
method: "hardhat_reset",
params: [],
})
})
}) | the_stack |
import { AxiosError, Method } from 'axios';
import { createAction, createReducer } from 'redux-act';
import { FetchStatusFlag } from 'app/constants';
import { MySelectBook, userRidiSelectBookToMySelectBook } from 'app/services/mySelect';
import { UserDTO } from 'app/services/user/helper';
import {
MySelectHistoryResponse,
PurchasesResponse,
SubscriptionResponse,
Ticket,
} from 'app/services/user/requests';
import { DateDTO, ItemListByPage, Paginated } from 'app/types';
export const Actions = {
fetchUserInfo: createAction<{
isFetching: boolean;
}>('fetchUserInfo'),
fetchUserGroupInfo: createAction<{
userGroup: number;
}>('fetchUserGroupInfo'),
initializeUser: createAction<{
userDTO: UserDTO;
}>('initializeUser'),
loadSubscriptionRequest: createAction('loadSubscriptionRequest'),
loadSubscriptionSuccess: createAction<{
response: SubscriptionResponse;
}>('loadSubscriptionSuccess'),
loadSubscriptionFailure: createAction<{
isFetched: boolean;
}>('loadSubscriptionFailure'),
clearPurchases: createAction('clearPurchases'),
loadPurchasesRequest: createAction<{
page: number;
}>('loadPurchasesRequest'),
loadPurchasesSuccess: createAction<{
page: number;
response: PurchasesResponse;
}>('loadPurchasesSuccess'),
loadPurchasesFailure: createAction<{
page: number;
}>('loadPurchasesFailure'),
cancelPurchaseRequest: createAction<{
purchaseId: number;
}>('cancelPurchaseRequest'),
cancelPurchaseSuccess: createAction<{
purchaseId: number;
}>('cancelPurchaseSuccess'),
cancelPurchaseFailure: createAction<{
purchaseId: number;
}>('cancelPurchaseFailure'),
loadMySelectHistoryRequest: createAction<{
page: number;
}>('loadMySelectHistoryRequest'),
loadMySelectHistorySuccess: createAction<{
page: number;
response: MySelectHistoryResponse;
}>('loadMySelectHistorySuccess'),
loadMySelectHistoryFailure: createAction<{
page: number;
error: AxiosError;
}>('loadMySelectHistoryFailure'),
clearMySelectHistory: createAction('clearMySelectHistory'),
deleteMySelectHistoryRequest: createAction<{
mySelectBookIds: number[];
page: number;
}>('deleteMySelectHistoryRequest'),
deleteMySelectHistorySuccess: createAction<{
page: number;
response: MySelectHistoryResponse;
}>('deleteMySelectHistorySuccess'),
deleteMySelectHistoryFailure: createAction('deleteMySelectHistoryFailure'),
resetMySelectHistoryFetchedStatus: createAction('resetMySelectHistoryFetchedStatus'),
unsubscribeRequest: createAction('unsubscribeRequest'),
unsubscribeSuccess: createAction('unsubscribeSuccess'),
unsubscribeFailure: createAction('unsubscribeFailure'),
cancelUnsubscriptionRequest: createAction('cancelUnsubscriptionRequest'),
cancelUnsubscriptionSuccess: createAction('cancelUnsubscriptionSuccess'),
cancelUnsubscriptionFailure: createAction('cancelUnsubscriptionFailure'),
loadAccountsMeRequest: createAction('loadAccountsMeRequest'),
loadAccountsMeSuccess: createAction<{
uId: string;
email: string;
}>('loadAccountsMeSuccess'),
loadAccountsMeFailure: createAction('loadAccountsMeFailure'),
cashReceiptIssueRequest: createAction<{
ticketId: number;
method: Method;
issuePurpose?: string;
issueNumber?: string;
}>('CashReceiptIssueRequest'),
cashReceiptIssueSuccess: createAction<{
ticketId: number;
method: Method;
cashReceiptUrl: string | null;
}>('CashReceiptIssueRequest'),
cashReceiptIssueFailure: createAction('CashReceiptIssueRequest'),
};
export enum CashReceiptIssueType {
INCOME_DEDUCTION = 'INCOME_DEDUCTION',
EXPENSE_EVIDENCE = 'EXPENSE_EVIDENCE',
}
// TODO: 서버에서 내려주는 방식이 string 으로 내려주고 있어서 확인 후 수정 필요.
// 일단 string으로 받도록 interface에 지정.
export enum PaymentMethodType {
EVENT = 0,
CARD = 1,
}
export enum PaymentStatus { // 결제 취소 기능 필요 여부를 논의 중
CANCELED = 'canceled',
CONFIRMED = 'confirmed',
CANCELABLE = 'cancelable',
}
export enum SubscriptionStatus {
unsubscribed = 0,
normal = 1,
/**
* 사실상 아래 네 가지 상태가 존재하는데 어떻게 처리할지 백엔드와 논의 필요
* 1. 한 번도 구독한 적이 없는 상태
* 2. 구독 중인 상태
* 3. 구독은 해지했으나 이용 가능한 상태(기존 구독 만료일 전까지)
* 4. 구독이 완전히 해지된 상태 (취소가 가능하다면 취소 상태 포함)
*/
}
export interface MySelectHistroyState extends Paginated<MySelectBook> {
deletionFetchingStatus: FetchStatusFlag;
}
export interface SubscriptionState {
subscriptionId: number;
ticketStartDate: DateDTO;
subscriptionEndDate: DateDTO;
nextBillDate: DateDTO;
isOptout: boolean;
isOptoutCancellable: boolean;
optoutDate: DateDTO; // Will it be empty?
optoutReason: string | null;
optoutReasonKor: string | null;
paymentMethod: string;
isUsingRidipay: boolean;
currency: string;
monthlyPayPrice: number;
cardBrand: string;
formattedMonthlyPayPrice: string;
maskedCardNo: string;
cardSubscription: string[];
pgType: string;
isOptoutCancellableWithPaymentMethodChange: boolean;
}
export interface PurchaseHistory extends Paginated<Ticket> {
isCancelFetching: boolean;
isCashReceiptIssueFetching: boolean;
latestPurchasedTicket: Ticket | null;
}
export interface UserState {
isFetching: boolean;
isLoggedIn: boolean;
isAccountMeRetried: boolean;
uId: string;
email: string;
availableUntil?: DateDTO;
ticketFetchStatus: FetchStatusFlag;
hasAvailableTicket: boolean;
hasSubscribedBefore: boolean;
subscriptionFetchStatus: FetchStatusFlag;
unsubscriptionFetchStatus: FetchStatusFlag;
unsubscriptionCancellationFetchStatus: FetchStatusFlag;
subscription?: SubscriptionState | null;
mySelectHistory: MySelectHistroyState;
purchaseHistory: PurchaseHistory;
userGroup?: number;
}
export const INITIAL_STATE: UserState = {
isFetching: true,
isLoggedIn: false,
isAccountMeRetried: false,
uId: '',
email: '',
hasAvailableTicket: false,
ticketFetchStatus: FetchStatusFlag.IDLE,
hasSubscribedBefore: false,
subscriptionFetchStatus: FetchStatusFlag.IDLE,
unsubscriptionFetchStatus: FetchStatusFlag.IDLE,
unsubscriptionCancellationFetchStatus: FetchStatusFlag.IDLE,
mySelectHistory: {
itemListByPage: {},
deletionFetchingStatus: FetchStatusFlag.IDLE,
},
purchaseHistory: {
itemListByPage: {},
isCancelFetching: false,
isCashReceiptIssueFetching: false,
latestPurchasedTicket: null,
},
};
export const userReducer = createReducer<UserState>({}, INITIAL_STATE);
userReducer.on(Actions.fetchUserInfo, (state = INITIAL_STATE, payload) => ({
...state,
...payload,
}));
userReducer.on(Actions.fetchUserGroupInfo, (state = INITIAL_STATE, payload) => ({
...state,
...payload,
}));
userReducer.on(Actions.initializeUser, (state = INITIAL_STATE, payload) => ({
...state,
...payload.userDTO,
}));
userReducer.on(Actions.loadSubscriptionRequest, (state = INITIAL_STATE) => ({
...state,
subscriptionFetchStatus: FetchStatusFlag.FETCHING,
}));
userReducer.on(Actions.loadSubscriptionSuccess, (state = INITIAL_STATE, payload) => ({
...state,
subscriptionFetchStatus: FetchStatusFlag.IDLE,
subscription: {
...state.subscription,
...payload.response,
},
}));
userReducer.on(Actions.loadSubscriptionFailure, (state = INITIAL_STATE, payload) => {
const { isFetched } = payload;
return {
...state,
subscriptionFetchStatus: isFetched ? FetchStatusFlag.IDLE : FetchStatusFlag.FETCH_ERROR,
};
});
userReducer.on(Actions.loadAccountsMeRequest, (state = INITIAL_STATE, payload) => ({
...state,
isFetching: true,
}));
userReducer.on(Actions.loadAccountsMeSuccess, (state = INITIAL_STATE, payload) => ({
...state,
isFetching: false,
isAccountMeRetried: true,
isLoggedIn: true,
uId: payload.uId,
email: payload.email,
}));
userReducer.on(Actions.loadAccountsMeFailure, (state = INITIAL_STATE, payload) => ({
...state,
isFetching: false,
isLoggedIn: false,
isAccountMeRetried: true,
}));
userReducer.on(Actions.loadMySelectHistoryRequest, (state = INITIAL_STATE, payload) => ({
...state,
mySelectHistory: {
...state.mySelectHistory,
itemListByPage: {
...state.mySelectHistory.itemListByPage,
[payload.page]: {
...state.mySelectHistory.itemListByPage[payload.page],
fetchStatus: FetchStatusFlag.FETCHING,
},
},
},
}));
userReducer.on(Actions.loadMySelectHistorySuccess, (state = INITIAL_STATE, payload) => {
const {
response: { userRidiSelectBooks, totalCount },
} = payload;
return {
...state,
mySelectHistory: {
...state.mySelectHistory,
itemCount: totalCount,
itemListByPage: {
...state.mySelectHistory.itemListByPage,
[payload.page]: {
isFetched: true,
itemList: userRidiSelectBooks.map(userRidiSelectBookToMySelectBook),
fetchStatus: FetchStatusFlag.IDLE,
},
},
},
};
});
userReducer.on(Actions.loadMySelectHistoryFailure, (state = INITIAL_STATE, payload) => ({
...state,
mySelectHistory: {
...state.mySelectHistory,
itemListByPage: {
...state.mySelectHistory.itemListByPage,
[payload.page]: {
isFetched: false,
itemList: [],
fetchStatus: FetchStatusFlag.FETCH_ERROR,
},
},
},
}));
userReducer.on(Actions.clearMySelectHistory, (state = INITIAL_STATE) => ({
...state,
mySelectHistory: {
...state.mySelectHistory,
itemCount: 0,
pageCount: 0,
itemListByPage: {},
},
}));
userReducer.on(Actions.deleteMySelectHistoryRequest, (state = INITIAL_STATE, payload) => ({
...state,
mySelectHistory: {
...state.mySelectHistory,
deletionFetchingStatus: FetchStatusFlag.FETCHING,
itemListByPage: {
...state.mySelectHistory.itemListByPage,
[payload.page]: {
...state.mySelectHistory.itemListByPage[payload.page],
fetchStatus: FetchStatusFlag.FETCHING,
},
},
},
}));
userReducer.on(Actions.deleteMySelectHistorySuccess, (state = INITIAL_STATE, payload) => {
const {
response: { userRidiSelectBooks, totalCount, totalPage },
page,
} = payload;
return {
...state,
mySelectHistory: {
...state.mySelectHistory,
itemCount: totalCount,
pageCount: totalPage,
deletionFetchingStatus: FetchStatusFlag.IDLE,
itemListByPage: {
...state.mySelectHistory.itemListByPage,
[page]: {
isFetched: true,
itemList: userRidiSelectBooks.map(userRidiSelectBookToMySelectBook),
fetchStatus: FetchStatusFlag.IDLE,
},
},
},
};
});
userReducer.on(Actions.deleteMySelectHistoryFailure, (state = INITIAL_STATE) => ({
...state,
mySelectHistory: {
...state.mySelectHistory,
deletionFetchingStatus: FetchStatusFlag.FETCH_ERROR,
},
}));
userReducer.on(Actions.resetMySelectHistoryFetchedStatus, (state = INITIAL_STATE) => ({
...state,
mySelectHistory: {
...state.mySelectHistory,
itemListByPage: {},
},
}));
userReducer.on(Actions.loadPurchasesRequest, (state = INITIAL_STATE, payload) => ({
...state,
purchaseHistory: {
...state.purchaseHistory,
itemListByPage: {
...state.purchaseHistory.itemListByPage,
[payload.page]: {
fetchStatus: FetchStatusFlag.FETCHING,
itemList: [],
isFetched: false,
},
},
},
}));
userReducer.on(Actions.loadPurchasesSuccess, (state = INITIAL_STATE, payload) => ({
...state,
purchaseHistory: {
...state.purchaseHistory,
itemCount: payload.response.totalCount,
latestPurchasedTicket: payload.response.latestPurchasedTicket,
itemListByPage: {
...state.purchaseHistory.itemListByPage,
[payload.page]: {
fetchStatus: FetchStatusFlag.IDLE,
itemList: payload.response.tickets,
isFetched: false,
},
},
},
}));
userReducer.on(Actions.loadPurchasesFailure, (state = INITIAL_STATE, payload) => ({
...state,
purchaseHistory: {
...state.purchaseHistory,
itemListByPage: {
...state.purchaseHistory.itemListByPage,
[payload.page]: {
fetchStatus: FetchStatusFlag.FETCH_ERROR,
itemList: [],
isFetched: false,
},
},
},
}));
userReducer.on(Actions.clearPurchases, (state = INITIAL_STATE) => ({
...state,
purchaseHistory: {
...state.purchaseHistory,
itemListByPage: {},
isCancelFetching: false,
isCashReceiptIssueFetching: false,
},
}));
userReducer.on(Actions.cancelPurchaseRequest, (state = INITIAL_STATE) => ({
...state,
purchaseHistory: {
...state.purchaseHistory,
isCancelFetching: true,
},
}));
userReducer.on(Actions.cancelPurchaseSuccess, (state = INITIAL_STATE, payload) => ({
...state,
purchaseHistory: {
...state.purchaseHistory,
itemListByPage: Object.keys(state.purchaseHistory.itemListByPage).reduce(
(listByPage, p): ItemListByPage<Ticket> => {
const page = Number(p);
return {
...listByPage,
[page]: {
...state.purchaseHistory.itemListByPage[page],
itemList: state.purchaseHistory.itemListByPage[page].itemList.map(item => ({
...item,
isCancellable: item.id === payload.purchaseId ? false : item.isCancellable,
isCanceled: item.id === payload.purchaseId ? true : item.isCanceled,
})),
},
};
},
{},
),
isCancelFetching: false,
},
}));
userReducer.on(Actions.cancelPurchaseFailure, (state = INITIAL_STATE) => ({
...state,
purchaseHistory: {
...state.purchaseHistory,
isCancelFetching: false,
},
}));
userReducer.on(Actions.unsubscribeRequest, (state = INITIAL_STATE) => ({
...state,
unsubscriptionFetchStatus: FetchStatusFlag.FETCHING,
}));
userReducer.on(Actions.unsubscribeSuccess, (state = INITIAL_STATE) => ({
...state,
unsubscriptionFetchStatus: FetchStatusFlag.IDLE,
}));
userReducer.on(Actions.unsubscribeFailure, (state = INITIAL_STATE) => ({
...state,
unsubscriptionFetchStatus: FetchStatusFlag.FETCH_ERROR,
}));
userReducer.on(Actions.cancelUnsubscriptionRequest, (state = INITIAL_STATE) => ({
...state,
unsubscriptionCancellationFetchStatus: FetchStatusFlag.FETCHING,
}));
userReducer.on(Actions.cancelUnsubscriptionSuccess, (state = INITIAL_STATE) => ({
...state,
unsubscriptionCancellationFetchStatus: FetchStatusFlag.IDLE,
}));
userReducer.on(Actions.cancelUnsubscriptionFailure, (state = INITIAL_STATE) => ({
...state,
unsubscriptionCancellationFetchStatus: FetchStatusFlag.FETCH_ERROR,
}));
userReducer.on(Actions.cashReceiptIssueRequest, (state = INITIAL_STATE) => ({
...state,
purchaseHistory: {
...state.purchaseHistory,
isCashReceiptIssueFetching: true,
},
}));
userReducer.on(Actions.cashReceiptIssueSuccess, (state = INITIAL_STATE, payload) => ({
...state,
purchaseHistory: {
...state.purchaseHistory,
itemListByPage: Object.keys(state.purchaseHistory.itemListByPage).reduce(
(listByPage, p): ItemListByPage<Ticket> => {
const page = Number(p);
return {
...listByPage,
[page]: {
...state.purchaseHistory.itemListByPage[page],
itemList: state.purchaseHistory.itemListByPage[page].itemList.map(item => ({
...item,
cashReceiptUrl:
item.id === payload.ticketId ? payload.cashReceiptUrl : item.cashReceiptUrl,
isCashReceiptIssuable:
item.id !== payload.ticketId
? item.isCashReceiptIssuable
: payload.method !== 'POST',
})),
},
};
},
{},
),
isCashReceiptIssueFetching: false,
},
}));
userReducer.on(Actions.cashReceiptIssueFailure, (state = INITIAL_STATE) => ({
...state,
purchaseHistory: {
...state.purchaseHistory,
isCashReceiptIssueFetching: false,
},
})); | the_stack |
interface CHHapticAdvancedPatternPlayer extends CHHapticPatternPlayer {
completionHandler: (p1: NSError) => void;
loopEnabled: boolean;
loopEnd: number;
playbackRate: number;
pauseAtTimeError(time: number): boolean;
resumeAtTimeError(time: number): boolean;
seekToOffsetError(offsetTime: number): boolean;
}
declare var CHHapticAdvancedPatternPlayer: {
prototype: CHHapticAdvancedPatternPlayer;
};
declare var CHHapticAudioResourceKeyUseVolumeEnvelope: string;
interface CHHapticDeviceCapability {
supportsAudio: boolean;
supportsHaptics: boolean;
attributesForDynamicParameterError(inParameter: string): CHHapticParameterAttributes;
attributesForEventParameterEventTypeError(inParameter: string, type: string): CHHapticParameterAttributes;
}
declare var CHHapticDeviceCapability: {
prototype: CHHapticDeviceCapability;
};
declare class CHHapticDynamicParameter extends NSObject {
static alloc(): CHHapticDynamicParameter; // inherited from NSObject
static new(): CHHapticDynamicParameter; // inherited from NSObject
readonly parameterID: string;
relativeTime: number;
value: number;
constructor(o: { parameterID: string; value: number; relativeTime: number; });
initWithParameterIDValueRelativeTime(parameterID: string, value: number, time: number): this;
}
declare var CHHapticDynamicParameterIDAudioAttackTimeControl: string;
declare var CHHapticDynamicParameterIDAudioBrightnessControl: string;
declare var CHHapticDynamicParameterIDAudioDecayTimeControl: string;
declare var CHHapticDynamicParameterIDAudioPanControl: string;
declare var CHHapticDynamicParameterIDAudioPitchControl: string;
declare var CHHapticDynamicParameterIDAudioReleaseTimeControl: string;
declare var CHHapticDynamicParameterIDAudioVolumeControl: string;
declare var CHHapticDynamicParameterIDHapticAttackTimeControl: string;
declare var CHHapticDynamicParameterIDHapticDecayTimeControl: string;
declare var CHHapticDynamicParameterIDHapticIntensityControl: string;
declare var CHHapticDynamicParameterIDHapticReleaseTimeControl: string;
declare var CHHapticDynamicParameterIDHapticSharpnessControl: string;
declare class CHHapticEngine extends NSObject {
static alloc(): CHHapticEngine; // inherited from NSObject
static capabilitiesForHardware(): CHHapticDeviceCapability;
static new(): CHHapticEngine; // inherited from NSObject
autoShutdownEnabled: boolean;
readonly currentTime: number;
isMutedForAudio: boolean;
isMutedForHaptics: boolean;
playsHapticsOnly: boolean;
resetHandler: () => void;
stoppedHandler: (p1: CHHapticEngineStoppedReason) => void;
constructor();
constructor(o: { audioSession: AVAudioSession; });
createAdvancedPlayerWithPatternError(pattern: CHHapticPattern): CHHapticAdvancedPatternPlayer;
createPlayerWithPatternError(pattern: CHHapticPattern): CHHapticPatternPlayer;
initAndReturnError(): this;
initWithAudioSessionError(audioSession: AVAudioSession): this;
notifyWhenPlayersFinished(finishedHandler: (p1: NSError) => CHHapticEngineFinishedAction): void;
playPatternFromDataError(data: NSData): boolean;
playPatternFromURLError(fileURL: NSURL): boolean;
registerAudioResourceOptionsError(resourceURL: NSURL, options: NSDictionary<any, any>): number;
startAndReturnError(): boolean;
startWithCompletionHandler(completionHandler: (p1: NSError) => void): void;
stopWithCompletionHandler(completionHandler: (p1: NSError) => void): void;
unregisterAudioResourceError(resourceID: number): boolean;
}
declare const enum CHHapticEngineFinishedAction {
StopEngine = 1,
LeaveEngineRunning = 2
}
declare const enum CHHapticEngineStoppedReason {
AudioSessionInterrupt = 1,
ApplicationSuspended = 2,
IdleTimeout = 3,
NotifyWhenFinished = 4,
EngineDestroyed = 5,
GameControllerDisconnect = 6,
SystemError = -1
}
declare const enum CHHapticErrorCode {
EngineNotRunning = -4805,
OperationNotPermitted = -4806,
EngineStartTimeout = -4808,
NotSupported = -4809,
ServerInitFailed = -4810,
ServerInterrupted = -4811,
InvalidPatternPlayer = -4812,
InvalidPatternData = -4813,
InvalidPatternDictionary = -4814,
InvalidAudioSession = -4815,
InvalidEngineParameter = -4816,
InvalidParameterType = -4820,
InvalidEventType = -4821,
InvalidEventTime = -4822,
InvalidEventDuration = -4823,
InvalidAudioResource = -4824,
ResourceNotAvailable = -4825,
BadEventEntry = -4830,
BadParameterEntry = -4831,
InvalidTime = -4840,
FileNotFound = -4851,
InsufficientPower = -4897,
UnknownError = -4898,
MemoryError = -4899
}
declare class CHHapticEvent extends NSObject {
static alloc(): CHHapticEvent; // inherited from NSObject
static new(): CHHapticEvent; // inherited from NSObject
duration: number;
readonly eventParameters: NSArray<CHHapticEventParameter>;
relativeTime: number;
readonly type: string;
constructor(o: { audioResourceID: number; parameters: NSArray<CHHapticEventParameter> | CHHapticEventParameter[]; relativeTime: number; });
constructor(o: { audioResourceID: number; parameters: NSArray<CHHapticEventParameter> | CHHapticEventParameter[]; relativeTime: number; duration: number; });
constructor(o: { eventType: string; parameters: NSArray<CHHapticEventParameter> | CHHapticEventParameter[]; relativeTime: number; });
constructor(o: { eventType: string; parameters: NSArray<CHHapticEventParameter> | CHHapticEventParameter[]; relativeTime: number; duration: number; });
initWithAudioResourceIDParametersRelativeTime(resID: number, eventParams: NSArray<CHHapticEventParameter> | CHHapticEventParameter[], time: number): this;
initWithAudioResourceIDParametersRelativeTimeDuration(resID: number, eventParams: NSArray<CHHapticEventParameter> | CHHapticEventParameter[], time: number, duration: number): this;
initWithEventTypeParametersRelativeTime(type: string, eventParams: NSArray<CHHapticEventParameter> | CHHapticEventParameter[], time: number): this;
initWithEventTypeParametersRelativeTimeDuration(type: string, eventParams: NSArray<CHHapticEventParameter> | CHHapticEventParameter[], time: number, duration: number): this;
}
declare class CHHapticEventParameter extends NSObject {
static alloc(): CHHapticEventParameter; // inherited from NSObject
static new(): CHHapticEventParameter; // inherited from NSObject
readonly parameterID: string;
value: number;
constructor(o: { parameterID: string; value: number; });
initWithParameterIDValue(parameterID: string, value: number): this;
}
declare var CHHapticEventParameterIDAttackTime: string;
declare var CHHapticEventParameterIDAudioBrightness: string;
declare var CHHapticEventParameterIDAudioPan: string;
declare var CHHapticEventParameterIDAudioPitch: string;
declare var CHHapticEventParameterIDAudioVolume: string;
declare var CHHapticEventParameterIDDecayTime: string;
declare var CHHapticEventParameterIDHapticIntensity: string;
declare var CHHapticEventParameterIDHapticSharpness: string;
declare var CHHapticEventParameterIDReleaseTime: string;
declare var CHHapticEventParameterIDSustained: string;
declare var CHHapticEventTypeAudioContinuous: string;
declare var CHHapticEventTypeAudioCustom: string;
declare var CHHapticEventTypeHapticContinuous: string;
declare var CHHapticEventTypeHapticTransient: string;
interface CHHapticParameterAttributes extends NSObjectProtocol {
defaultValue: number;
maxValue: number;
minValue: number;
}
declare var CHHapticParameterAttributes: {
prototype: CHHapticParameterAttributes;
};
declare class CHHapticParameterCurve extends NSObject {
static alloc(): CHHapticParameterCurve; // inherited from NSObject
static new(): CHHapticParameterCurve; // inherited from NSObject
readonly controlPoints: NSArray<CHHapticParameterCurveControlPoint>;
readonly parameterID: string;
relativeTime: number;
constructor(o: { parameterID: string; controlPoints: NSArray<CHHapticParameterCurveControlPoint> | CHHapticParameterCurveControlPoint[]; relativeTime: number; });
initWithParameterIDControlPointsRelativeTime(parameterID: string, controlPoints: NSArray<CHHapticParameterCurveControlPoint> | CHHapticParameterCurveControlPoint[], relativeTime: number): this;
}
declare class CHHapticParameterCurveControlPoint extends NSObject {
static alloc(): CHHapticParameterCurveControlPoint; // inherited from NSObject
static new(): CHHapticParameterCurveControlPoint; // inherited from NSObject
relativeTime: number;
value: number;
constructor(o: { relativeTime: number; value: number; });
initWithRelativeTimeValue(time: number, value: number): this;
}
declare class CHHapticPattern extends NSObject {
static alloc(): CHHapticPattern; // inherited from NSObject
static new(): CHHapticPattern; // inherited from NSObject
readonly duration: number;
constructor(o: { dictionary: NSDictionary<string, any>; });
constructor(o: { events: NSArray<CHHapticEvent> | CHHapticEvent[]; parameterCurves: NSArray<CHHapticParameterCurve> | CHHapticParameterCurve[]; });
constructor(o: { events: NSArray<CHHapticEvent> | CHHapticEvent[]; parameters: NSArray<CHHapticDynamicParameter> | CHHapticDynamicParameter[]; });
exportDictionaryAndReturnError(): NSDictionary<string, any>;
initWithDictionaryError(patternDict: NSDictionary<string, any>): this;
initWithEventsParameterCurvesError(events: NSArray<CHHapticEvent> | CHHapticEvent[], parameterCurves: NSArray<CHHapticParameterCurve> | CHHapticParameterCurve[]): this;
initWithEventsParametersError(events: NSArray<CHHapticEvent> | CHHapticEvent[], parameters: NSArray<CHHapticDynamicParameter> | CHHapticDynamicParameter[]): this;
}
declare var CHHapticPatternKeyEvent: string;
declare var CHHapticPatternKeyEventDuration: string;
declare var CHHapticPatternKeyEventParameters: string;
declare var CHHapticPatternKeyEventType: string;
declare var CHHapticPatternKeyEventWaveformPath: string;
declare var CHHapticPatternKeyEventWaveformUseVolumeEnvelope: string;
declare var CHHapticPatternKeyParameter: string;
declare var CHHapticPatternKeyParameterCurve: string;
declare var CHHapticPatternKeyParameterCurveControlPoints: string;
declare var CHHapticPatternKeyParameterID: string;
declare var CHHapticPatternKeyParameterValue: string;
declare var CHHapticPatternKeyPattern: string;
declare var CHHapticPatternKeyTime: string;
declare var CHHapticPatternKeyVersion: string;
interface CHHapticPatternPlayer extends NSObjectProtocol {
isMuted: boolean;
cancelAndReturnError(): boolean;
scheduleParameterCurveAtTimeError(parameterCurve: CHHapticParameterCurve, time: number): boolean;
sendParametersAtTimeError(parameters: NSArray<CHHapticDynamicParameter> | CHHapticDynamicParameter[], time: number): boolean;
startAtTimeError(time: number): boolean;
stopAtTimeError(time: number): boolean;
}
declare var CHHapticPatternPlayer: {
prototype: CHHapticPatternPlayer;
}; | the_stack |
declare namespace DapJS {
export interface IHID {
write(data: ArrayBuffer): Promise<void>;
read(): Promise<Uint8Array>;
close(): Promise<void>;
// sends each of commands and expects one packet in response
// this makes for better performance when HID access is proxied
sendMany?(commands: Uint8Array[]): Promise<Uint8Array[]>;
}
export class DAP {
constructor(device: IHID);
reconnect(): Promise<void>;
init(): Promise<void>;
close(): Promise<void>;
}
/**
* # Memory Interface
*
* Controls access to the target's memory.
*
* ## Usage
*
* Using an instance of `CortexM`, as described before, we can simply read and
* write numbers to memory as follows:
*
* ```typescript
* const mem = core.memory;
*
* // NOTE: the address parameter must be word (4-byte) aligned.
* await mem.write32(0x200000, 12345);
* const val = await mem.read32(0x200000);
*
* // val === 12345
*
* // NOTE: the address parameter must be half-word (2-byte) aligned
* await mem.write16(0x2000002, 65534);
* const val16 = await mem.read16(0x2000002);
*
* // val16 === 65534
* ```
*
* To write a larger block of memory, we can use `readBlock` and `writeBlock`. Again,
* these blocks must be written to word-aligned addresses in memory.
*
* ```typescript
* const data = new Uint32Array([0x1234, 0x5678, 0x9ABC, 0xDEF0]);
* await mem.writeBlock(0x200000, data);
*
* const readData = await mem.readBlock(0x200000, data.length, 0x100);
* ```
*
* ## See also
*
* `PreparedMemoryCommand` provides an equivalent API with better performance (in some
* cases) by enabling batched memory operations.
*/
export class Memory {
private dev;
constructor(dev: DAP);
/**
* Write a 32-bit word to the specified (word-aligned) memory address.
*
* @param addr Memory address to write to
* @param data Data to write (values above 2**32 will be truncated)
*/
write32(addr: number, data: number): Promise<void>;
/**
* Write a 16-bit word to the specified (half word-aligned) memory address.
*
* @param addr Memory address to write to
* @param data Data to write (values above 2**16 will be truncated)
*/
write16(addr: number, data: number): Promise<void>;
/**
* Read a 32-bit word from the specified (word-aligned) memory address.
*
* @param addr Memory address to read from.
*/
read32(addr: number): Promise<number>;
/**
* Read a 16-bit word from the specified (half word-aligned) memory address.
*
* @param addr Memory address to read from.
*/
read16(addr: number): Promise<number>;
/**
* Reads a block of memory from the specified memory address.
*
* @param addr Address to read from
* @param words Number of words to read
* @param pageSize Memory page size
*/
readBlock(addr: number, words: number, pageSize: number): Promise<Uint8Array>;
/**
* Write a block of memory to the specified memory address.
*
* @param addr Memory address to write to.
* @param words Array of 32-bit words to write to memory.
*/
writeBlock(addr: number, words: Uint32Array): Promise<void>;
private readBlockCore(addr, words);
private writeBlockCore(addr, words);
}
/**
* # Cortex M
*
* Manages access to a CPU core, and its associated memory and debug functionality.
*
* > **NOTE:** all of the methods that involve interaction with the CPU core
* > are asynchronous, so must be `await`ed, or explicitly handled as a Promise.
*
* ## Usage
*
* First, let's create an instance of `CortexM`, using an associated _Debug Access
* Port_ (DAP) instance that we created earlier.
*
* ```typescript
* const core = new CortexM(dap);
* ```
*
* Now, we can halt and resume the core just like this:
*
* > **NOTE:** If you're not using ES2017, you can replace the use of `async` and
* > `await` with direct use of Promises. These examples also need to be run within
* > an `async` function for `async` to be used.
*
* ```typescript
* await core.halt();
* await core.resume();
* ```
*
* Resetting the core is just as easy:
*
* ```typescript
* await core.reset();
* ```
*
* You can even halt immediately after reset:
*
* ```typescript
* await core.reset(true);
* ```
*
* We can also read and write 32-bit values to/from core registers:
*
* ```typescript
* const sp = await core.readCoreRegister(CortexReg.SP);
*
* await core.writeCoreRegister(CortexReg.R0, 0x1000);
* await core.writeCoreRegister(CortexReg.PC, 0x1234);
* ```
*
* ### See also
*
* For details on debugging and memory features, see the documentation for
* `Debug` and `Memory`.
*/
export class CortexM {
/**
* Read and write to on-chip memory associated with this CPU core.
*/
memory: Memory;
/**
* Control the CPU's debugging features.
*/
debug: Debug;
/**
* Underlying Debug Access Port (DAP).
*/
private dev;
constructor(device: DAP);
/**
* Initialise the debug access port on the device, and read the device type.
*/
init(): Promise<void>;
/**
* Read the current state of the CPU.
*
* @returns A member of the `CoreState` enum corresponding to the current status of the CPU.
*/
getState(): Promise<CoreState>;
/**
* Read a core register from the CPU (e.g. r0...r15, pc, sp, lr, s0...)
*
* @param no Member of the `CortexReg` enum - an ARM Cortex CPU general-purpose register.
*/
readCoreRegister(no: CortexReg): Promise<number>;
/**
* Write a 32-bit word to the specified CPU general-purpose register.
*
* @param no Member of the `CortexReg` enum - an ARM Cortex CPU general-purpose register.
* @param val Value to be written.
*/
writeCoreRegister(no: CortexReg, val: number): Promise<void>;
/**
* Halt the CPU core.
*/
halt(): Promise<void>;
/**
* Resume the CPU core.
*/
resume(): Promise<void>;
/**
* Find out whether the CPU is halted.
*/
isHalted(): Promise<boolean>;
/**
* Read the current status of the CPU.
*
* @returns Object containing the contents of the `DHCSR` register, the `DFSR` register, and a boolean value
* stating the current halted state of the CPU.
*/
status(): Promise<{
dfsr: number;
dhscr: number;
isHalted: boolean;
}>;
/**
* Reset the CPU core. This currently does a software reset - it is also technically possible to perform a 'hard'
* reset using the reset pin from the debugger.
*/
reset(halt?: boolean): Promise<void>;
/**
* Run specified machine code natively on the device. Assumes usual C calling conventions
* - returns the value of r0 once the program has terminated. The program _must_ terminate
* in order for this function to return. This can be achieved by placing a `bkpt`
* instruction at the end of the function.
*
* @param code array containing the machine code (32-bit words).
* @param address memory address at which to place the code.
* @param pc initial value of the program counter.
* @param lr initial value of the link register.
* @param sp initial value of the stack pointer.
* @param upload should we upload the code before running it.
* @param args set registers r0...rn before running code
*
* @returns A promise for the value of r0 on completion of the function call.
*/
runCode(code: Uint32Array, address: number, pc: number, lr: number, sp: number, upload: boolean, ...args: number[]): Promise<number>;
/**
* Spin until the chip has halted.
*/
waitForHalt(timeout?: number): Promise<void>;
prepareCommand(): PreparedCortexMCommand;
private softwareReset();
}
/**
* # Cortex M: Prepared Command
*
* Allows batching of Cortex M-related commands, such as writing to a register,
* halting and resuming the core.
*
* ## Example
*
* When preparing the sequence of commands, we can use the same API to prepare
* a command as we would to execute them immediately.
*
* ```typescript
* // Note that only the .go method is asynchronous.
*
* const prep = core.prepareCommand();
* prep.writeCoreRegister(CortexReg.R0, 0x1000);
* prep.writeCoreRegister(CortexReg.R1, 0x0);
* prep.writeCoreRegister(CortexReg.PC, 0x2000000);
* prep.resume();
* ```
*
* We can then execute them as efficiently as possible by combining them together
* and executing them like so.
*
* ```typescript
* await prep.go();
* ```
*
* The code above is equivalent to the following _non-prepared_ command:
*
* ```typescript
* await core.writeCoreRegister(CortexReg.R0, 0x1000);
* await core.writeCoreRegister(CortexReg.R1, 0x0);
* await core.writeCoreRegister(CortexReg.PC, 0x2000000);
* await core.resume();
* ```
*
* Since the batched version of this code avoids making three round-trips to the
* target, we are able to significantly improve performance. This is especially
* noticable when uploading a binary to flash memory, where are large number of
* repetetive commands are being used.
*
* ## Explanation
*
* For a detailed explanation of why prepared commands are used in DAP.js, see the
* documentation for `PreparedDapCommand`.
*/
export class PreparedCortexMCommand {
private cmd;
constructor(dap: DAP);
/**
* Schedule a 32-bit integer to be written to a core register.
*
* @param no Core register to be written.
* @param val Value to write.
*/
writeCoreRegister(no: CortexReg, val: number): void;
/**
* Schedule a halt command to be written to the CPU.
*/
halt(): void;
/**
* Schedule a resume command to be written to the CPU.
*/
resume(): void;
/**
* Execute all scheduled commands.
*/
go(): Promise<void>;
}
export const enum CortexReg {
R0 = 0,
R1 = 1,
R2 = 2,
R3 = 3,
R4 = 4,
R5 = 5,
R6 = 6,
R7 = 7,
R8 = 8,
R9 = 9,
R10 = 10,
R11 = 11,
R12 = 12,
SP = 13,
LR = 14,
PC = 15,
XPSR = 16,
MSP = 17,
PSP = 18,
PRIMASK = 20,
CONTROL = 20,
}
export const enum CoreState {
TARGET_RESET = 0,
TARGET_LOCKUP = 1,
TARGET_SLEEPING = 2,
TARGET_HALTED = 3,
TARGET_RUNNING = 4,
}
/**
* # Debug Interface
*
* Keeps track of breakpoints set on the target, as well as deciding whether to
* use a hardware breakpoint or a software breakpoint.
*
* ## Usage
*
* ```typescript
* const dbg = core.debug;
*
* await dbg.setBreakpoint(0x123456);
*
* // resume the core and wait for the breakpoint
* await core.resume();
* await core.waitForHalt();
*
* // step forward one instruction
* await dbg.step();
*
* // remove the breakpoint
* await dbg.deleteBreakpoint(0x123456);
* ```
*/
export class Debug {
private core;
private breakpoints;
private availableHWBreakpoints;
private totalHWBreakpoints;
private enabled;
constructor(core: CortexM);
init(): Promise<void>;
/**
* Enable debugging on the target CPU
*/
enable(): Promise<void>;
/**
* Set breakpoints at specified memory addresses.
*
* @param addrs An array of memory addresses at which to set breakpoints.
*/
setBreakpoint(addr: number): Promise<void>;
deleteBreakpoint(addr: number): Promise<void>;
/**
* Step the processor forward by one instruction.
*/
step(): Promise<void>;
/**
* Set up (and disable) the Flash Patch & Breakpoint unit. It will be enabled when
* the first breakpoint is set.
*
* Also reads the number of available hardware breakpoints.
*/
private setupFpb();
/**
* Enable or disable the Flash Patch and Breakpoint unit (FPB).
*
* @param enabled
*/
private setFpbEnabled(enabled?);
}
} | the_stack |
import Position from '../utils/cursor/position'
import Range from '../utils/cursor/range'
import { detect, forEach, reduce, filter, values, commonItems } from '../utils/array-utils'
import { Direction } from '../utils/key'
import LifecycleCallbacks, { LifecycleCallback } from '../models/lifecycle-callbacks'
import assert, { assertType } from '../utils/assert'
import { normalizeTagName } from '../utils/dom-utils'
import PostInserter from './post/post-inserter'
import deprecate from '../utils/deprecate'
import toRange from '../utils/to-range'
import { Option, Maybe } from '../utils/types'
import Editor, { TextUnit } from './editor'
import PostNodeBuilder, { PostNode } from '../models/post-node-builder'
import Markerable, { isMarkerable } from '../models/_markerable'
import Section from '../models/_section'
import Markuperable from '../utils/markuperable'
import Post from '../models/post'
import ListSection, { isListSection } from '../models/list-section'
import ListItem, { isListItem } from '../models/list-item'
import Card, { isCardSection } from '../models/card'
import LinkedList from '../utils/linked-list'
import { Cloneable } from '../models/_cloneable'
import HasChildSections, { hasChildSections } from '../models/_has-child-sections'
import { Attributable } from '../models/_attributable'
import Markup from '../models/markup'
import { isMarkupSection } from '../models/markup-section'
import { TagNameable } from '../models/_tag-nameable'
const { FORWARD, BACKWARD } = Direction
function isListSectionTagName(tagName: string) {
return tagName === 'ul' || tagName === 'ol'
}
function shrinkRange(range: Range) {
const { head, tail } = range
if (tail.offset === 0 && head.section !== tail.section) {
range.tail = new Position(tail.section!.prev, tail.section!.prev!.length)
}
return range
}
const CALLBACK_QUEUES = {
BEFORE_COMPLETE: 'beforeComplete',
COMPLETE: 'complete',
AFTER_COMPLETE: 'afterComplete',
}
// There are only two events that we're concerned about for Undo, that is inserting text and deleting content.
// These are the only two states that go on a "run" and create a combined undo, everything else has it's own
// deadicated undo.
export const enum EditAction {
INSERT_TEXT = 1,
DELETE = 2,
}
interface SectionTransformation {
from: Section
to: Section
}
/**
* The PostEditor is used to modify a post. It should not be instantiated directly.
* Instead, a new instance of a PostEditor is created by the editor and passed
* as the argument to the callback in {@link Editor#run}.
*
* Usage:
* ```
* editor.run((postEditor) => {
* // postEditor is an instance of PostEditor that can operate on the
* // editor's post
* });
* ```
*/
export default class PostEditor {
/**
* @private
*/
editor: Editor
builder: PostNodeBuilder
editActionTaken: Option<EditAction>
_callbacks: LifecycleCallbacks
_range!: Range
_didComplete: boolean
_renderRange: () => void
_postDidChange: () => void
_rerender: () => void
_shouldCancelSnapshot!: boolean
constructor(editor: Editor) {
this.editor = editor
this.builder = this.editor.builder
this._callbacks = new LifecycleCallbacks(values(CALLBACK_QUEUES))
this._didComplete = false
this.editActionTaken = null
this._renderRange = () => this.editor.selectRange(this._range)
this._postDidChange = () => this.editor._postDidChange()
this._rerender = () => this.editor.rerender()
}
addCallback(queueName: string, callback: LifecycleCallback) {
this._callbacks.addCallback(queueName, callback)
}
addCallbackOnce(queueName: string, callback: LifecycleCallback) {
this._callbacks.addCallbackOnce(queueName, callback)
}
runCallbacks(queueName: string) {
this._callbacks.runCallbacks(queueName)
}
begin() {
// cache the editor's range
this._range = this.editor.range
}
/**
* Schedules to select the given range on the editor after the postEditor
* has completed its work. This also updates the postEditor's active range
* (so that multiple calls to range-changing methods on the postEditor will
* update the correct range).
*
* Usage:
* let range = editor.range;
* editor.run(postEditor => {
* let nextPosition = postEditor.deleteRange(range);
*
* // Will position the editor's cursor at `nextPosition` after
* // the postEditor finishes work and the editor rerenders.
* postEditor.setRange(nextPosition);
* });
* @param {Range|Position} range
* @public
*/
setRange(range: Range | Position) {
range = toRange(range)
// TODO validate that the range is valid
// (does not contain marked-for-removal head or tail sections?)
this._range = range
this.scheduleAfterRender(this._renderRange, true)
}
/**
* Delete a range from the post
*
* Usage:
* ```
* let { range } = editor;
* editor.run((postEditor) => {
* let nextPosition = postEditor.deleteRange(range);
* postEditor.setRange(nextPosition);
* });
* ```
* @param {Range} range Cursor Range object with head and tail Positions
* @return {Position} The position where the cursor would go after deletion
* @public
*/
deleteRange(range: Range): Position {
assert('Must pass MobiledocKit Range to `deleteRange`', range instanceof Range)
this.editActionTaken = EditAction.DELETE
const { head, tail } = range
let headSection = head.section!
let tailSection = tail.section!
const { editor } = this
const { post } = editor
if (headSection === tailSection) {
return this.cutSection(headSection, head, tail)
}
let nextSection = headSection!.nextLeafSection()
let nextPos = this.cutSection(headSection, head, headSection!.tailPosition())
// cutSection can replace the section, so re-read headSection here
headSection = nextPos.section!
// Remove sections in the middle of the range
while (nextSection !== tailSection) {
let tmp = nextSection!
nextSection = nextSection!.nextLeafSection()
this.removeSection(tmp)
}
let tailPos = this.cutSection(tailSection, tailSection!.headPosition(), tail)
// cutSection can replace the section, so re-read tailSection here
tailSection = tailPos.section!
if (tailSection.isBlank) {
this.removeSection(tailSection)
} else {
// If head and tail sections are markerable, join them
// Note: They may not be the same section type. E.g. this may join
// a tail section that was a list item onto a markup section, or vice versa.
// (This is the desired behavior.)
if (isMarkerable(headSection) && isMarkerable(tailSection)) {
headSection.join(tailSection)
this._markDirty(headSection)
this.removeSection(tailSection)
} else if (headSection.isBlank) {
this.removeSection(headSection)
nextPos = tailPos
}
}
if (post.isBlank) {
post.sections.append(this.builder.createMarkupSection('p'))
nextPos = post.headPosition()
}
return nextPos
}
/**
* Note: This method may replace `section` with a different section.
*
* "Cut" out the part of the section inside `headOffset` and `tailOffset`.
* If section is markerable this splits markers that straddle the head or tail (if necessary),
* and removes markers that are wholly inside the offsets.
* If section is a card, this may replace it with a blank markup section if the
* positions contain the entire card.
*
* @param {Section} section
* @param {Position} head
* @param {Position} tail
* @return {Position}
* @private
*/
cutSection(section: Section, head: Position, tail: Position): Position {
assert(
'Must pass head position and tail position to `cutSection`',
head instanceof Position && tail instanceof Position
)
assert('Must pass positions within same section to `cutSection`', head.section === tail.section)
if (section.isBlank || head.isEqual(tail)) {
return head
}
if (section.isCardSection) {
if (head.isHead() && tail.isTail()) {
let newSection = this.builder.createMarkupSection()
this.replaceSection(section, newSection)
return newSection.headPosition()
} else {
return tail
}
}
let range = head.toRange(tail)
this.splitMarkers(range).forEach(m => this.removeMarker(m))
return head
}
_coalesceMarkers(section: Section) {
if (isMarkerable(section)) {
this._removeBlankMarkers(section)
this._joinSimilarMarkers(section)
}
}
_removeBlankMarkers(section: Markerable) {
forEach(
filter(section.markers, m => m.isBlank),
m => this.removeMarker(m)
)
}
// joins markers that have identical markups
_joinSimilarMarkers(section: Markerable) {
let marker = section.markers.head
let nextMarker: Markuperable
while (marker && marker.next) {
nextMarker = marker.next
if (marker.canJoin(nextMarker)) {
nextMarker.value = marker.value + nextMarker.value
this._markDirty(nextMarker)
this.removeMarker(marker)
}
marker = nextMarker
}
}
removeMarker(marker: Markuperable) {
this._scheduleForRemoval(marker)
if (marker.section) {
this._markDirty(marker.section)
marker.section.markers.remove(marker)
}
}
_scheduleForRemoval(postNode: Exclude<PostNode, Post>) {
if (postNode.renderNode) {
postNode.renderNode.scheduleForRemoval()
this.scheduleRerender()
this.scheduleDidUpdate()
}
let removedAdjacentToList =
(postNode.prev && isListSection(postNode.prev as Section)) ||
(postNode.next && isListSection(postNode.next as Section))
if (removedAdjacentToList) {
this.addCallback(CALLBACK_QUEUES.BEFORE_COMPLETE, () => this._joinContiguousListSections())
}
}
_joinContiguousListSections() {
let { post } = this.editor
let range = this._range
let prev: Section
let groups: ListSection[][] = []
let currentGroup!: Option<ListSection[]>
// FIXME do we need to force a re-render of the range if changed sections
// are contained within the range?
let updatedHead: Option<Position> = null
forEach(post.sections, section => {
if (prev && isListSection(prev) && isListSection(section) && prev.tagName === section.tagName) {
currentGroup = currentGroup || [prev]
currentGroup.push(section)
} else {
if (currentGroup) {
groups.push(currentGroup)
}
currentGroup = null
}
prev = section
})
if (currentGroup) {
groups.push(currentGroup)
}
forEach(groups, group => {
let list = group[0]
forEach(group, listSection => {
if (listSection === list) {
return
}
let currentHead = range.head
let prevPosition: Maybe<Position>
// FIXME is there a currentHead if there is no range?
// is the current head a list item in the section
if (!range.isBlank && isListItem(currentHead.section!) && currentHead.section.parent === listSection) {
prevPosition = list.tailPosition()
}
this._joinListSections(list, listSection)
if (prevPosition) {
updatedHead = prevPosition.move(FORWARD)
}
})
})
if (updatedHead) {
this.setRange(updatedHead)
}
}
_joinListSections(baseList: ListSection, nextList: ListSection) {
baseList.join(nextList)
this._markDirty(baseList)
this.removeSection(nextList)
}
_markDirty(postNode: PostNode) {
if (postNode.renderNode) {
postNode.renderNode.markDirty()
this.scheduleRerender()
this.scheduleDidUpdate()
}
if ('section' in postNode && postNode.section) {
this._markDirty(postNode.section)
}
if (isMarkerable(postNode as Section)) {
this.addCallback(CALLBACK_QUEUES.BEFORE_COMPLETE, () => this._coalesceMarkers(postNode as Markerable))
}
}
/**
* @param {Position} position object with {section, offset} the marker and offset to delete from
* @param {Number} direction The direction to delete in (default is BACKWARD)
* @return {Position} for positioning the cursor
* @public
* @deprecated after v0.10.3
*/
deleteFrom(position: Position, direction: Direction = Direction.BACKWARD): Position {
deprecate(
"`postEditor#deleteFrom is deprecated. Use `deleteAtPosition(position, direction=BACKWARD, {unit}={unit: 'char'})` instead"
)
return this.deleteAtPosition(position, direction, { unit: TextUnit.CHAR })
}
/**
* Delete 1 `unit` (can be 'char' or 'word') in the given `direction` at the given
* `position`. In almost all cases this will be equivalent to deleting the range formed
* by expanding the position 1 unit in the given direction. The exception is when deleting
* backward from the beginning of a list item, which reverts the list item into a markup section
* instead of joining it with its previous list item (if any).
*
* Usage:
*
* let position = section.tailPosition();
* // Section has text of "Howdy!"
* editor.run((postEditor) => {
* postEditor.deleteAtPosition(position);
* });
* // section has text of "Howdy"
*
* @param {Position} position The position to delete at
* @param {Direction} [direction=DIRECTION.BACKWARD] direction The direction to delete in
* @param {Object} [options]
* @param {String} [options.unit="char"] The unit of deletion ("word" or "char")
* @return {Position}
*/
deleteAtPosition(
position: Position,
direction: Direction = Direction.BACKWARD,
{ unit }: { unit: TextUnit } = { unit: TextUnit.CHAR }
): Position {
if (direction === Direction.BACKWARD) {
return this._deleteAtPositionBackward(position, unit)
} else {
return this._deleteAtPositionForward(position, unit)
}
}
_deleteAtPositionBackward(position: Position, unit: TextUnit) {
if (position.isHead() && isListItem(position.section!)) {
this.toggleSection('p', position)
return this._range.head
} else {
let prevPosition = unit === 'word' ? position.moveWord(BACKWARD) : position.move(BACKWARD)
let range = prevPosition.toRange(position)
return this.deleteRange(range)
}
}
_deleteAtPositionForward(position: Position, unit: TextUnit) {
let nextPosition = unit === 'word' ? position.moveWord(FORWARD) : position.move(FORWARD)
let range = position.toRange(nextPosition)
return this.deleteRange(range)
}
/**
* Split markers at two positions, once at the head, and if necessary once
* at the tail.
*
* Usage:
* ```
* let range = editor.range;
* editor.run((postEditor) => {
* postEditor.splitMarkers(range);
* });
* ```
* The return value will be marker object completely inside the offsets
* provided. Markers outside of the split may also have been modified.
*
* @param {Range} markerRange
* @return {Array} of markers that are inside the split
* @private
*/
splitMarkers(range: Range): Markuperable[] {
const { post } = this.editor
const { head, tail } = range
this.splitSectionMarkerAtOffset(head.section!, head.offset)
this.splitSectionMarkerAtOffset(tail.section!, tail.offset)
return post.markersContainedByRange(range)
}
splitSectionMarkerAtOffset(section: Section, offset: number) {
const edit = section.splitMarkerAtOffset(offset)
edit.removed.forEach(m => this.removeMarker(m))
}
/**
* Split the section at the position.
*
* Usage:
* ```
* let position = editor.cursor.offsets.head;
* editor.run((postEditor) => {
* postEditor.splitSection(position);
* });
* // Will result in the creation of two new sections
* // replacing the old one at the cursor position
* ```
* The return value will be the two new sections. One or both of these
* sections can be blank (contain only a blank marker), for example if the
* headMarkerOffset is 0.
*
* @param {Position} position
* @return {Array} new sections, one for the first half and one for the second (either one can be null)
* @public
*/
splitSection(position: Position): [Option<Section>, Option<Section>] {
const section = position.section!
if (isCardSection(section)) {
return this._splitCardSection(section, position)
} else if (isListItem(section)) {
let isLastAndBlank = section.isBlank && !section.next
if (isLastAndBlank) {
// if is last, replace the item with a blank markup section
let parent = section.parent
let collection = this.editor.post.sections
let blank = this.builder.createMarkupSection()
this.removeSection(section)
this.insertSectionBefore(collection, blank, parent.next)
return [null, blank]
} else {
let [pre, post] = this._splitListItem(section, position)
return [pre, post]
}
} else {
let splitSections = (section as Markerable).splitAtPosition(position)
splitSections.forEach(s => this._coalesceMarkers(s))
this._replaceSection(section, splitSections)
return splitSections
}
}
/**
* @param {Section} cardSection
* @param {Position} position to split at
* @return {Section[]} 2-item array of pre and post-split sections
* @private
*/
_splitCardSection(cardSection: Card, position: Position): [Section, Section] {
let { offset } = position
assert('Cards section must be split at offset 0 or 1', offset === 0 || offset === 1)
let newSection = this.builder.createMarkupSection()
let nextSection: Section
let surroundingSections: [Section, Section]
if (offset === 0) {
nextSection = cardSection
surroundingSections = [newSection, cardSection]
} else {
nextSection = cardSection.next!
surroundingSections = [cardSection, newSection]
}
let collection = this.editor.post.sections
this.insertSectionBefore(collection, newSection, nextSection)
return surroundingSections
}
/**
* @param {Section} section
* @param {Section} newSection
* @public
*/
replaceSection(section: Section, newSection: Section) {
if (!section) {
// FIXME should a falsy section be a valid argument?
this.insertSectionBefore(this.editor.post.sections, newSection, null)
} else {
this._replaceSection(section, [newSection])
}
}
moveSectionBefore(
collection: LinkedList<Cloneable<Section>>,
renderedSection: Cloneable<Section>,
beforeSection: Section
) {
const newSection = renderedSection.clone()
this.removeSection(renderedSection)
this.insertSectionBefore(collection, newSection, beforeSection)
return newSection
}
/**
* @param {Section} section A section that is already in DOM
* @public
*/
moveSectionUp(renderedSection: Cloneable<Section>) {
const isFirst = !renderedSection.prev
if (isFirst) {
return renderedSection
}
const collection = renderedSection.parent.sections
const beforeSection = renderedSection.prev!
return this.moveSectionBefore(collection, renderedSection, beforeSection)
}
/**
* @param {Section} section A section that is already in DOM
* @public
*/
moveSectionDown(renderedSection: Cloneable<Section>) {
const isLast = !renderedSection.next
if (isLast) {
return renderedSection
}
const beforeSection = renderedSection.next!.next!
const collection = renderedSection.parent.sections
return this.moveSectionBefore(collection, renderedSection, beforeSection)
}
/**
* Insert an array of markers at the given position. If the position is in
* a non-markerable section (like a card section), this method throws an error.
*
* @param {Position} position
* @param {Marker[]} markers
* @return {Position} The position that represents the end of the inserted markers.
* @public
*/
insertMarkers(position: Position, markers: Markuperable[]): Position {
const section = position.section! as Markerable
let offset = position.offset
assert('Cannot insert markers at non-markerable position', section!.isMarkerable)
this.editActionTaken = EditAction.INSERT_TEXT
let edit = section.splitMarkerAtOffset(offset)
edit.removed.forEach(marker => this._scheduleForRemoval(marker))
let prevMarker = section.markerBeforeOffset(offset)
markers.forEach(marker => {
section.markers.insertAfter(marker, prevMarker!)
offset += marker.length
prevMarker = marker
})
this._coalesceMarkers(section)
this._markDirty(section)
let nextPosition = section.toPosition(offset)
this.setRange(nextPosition)
return nextPosition
}
/**
* Inserts text with the given markups, ignoring the existing markups at
* the position, if any.
*
* @param {Position} position
* @param {String} text
* @param {Markup[]} markups
* @return {Position} position at the end of the inserted text
*/
insertTextWithMarkup(position: Position, text: string, markups: Markup[] = []): Maybe<Position> {
let { section } = position
if (!section!.isMarkerable) {
return
}
let marker = this.builder.createMarker(text, markups)
return this.insertMarkers(position, [marker])
}
/**
* Insert the text at the given position
* Inherits the markups already at that position, if any.
*
* @param {Position} position
* @param {String} text
* @return {Position} position at the end of the inserted text.
*/
insertText(position: Position, text: string): Maybe<Position> {
let { section } = position
if (!section!.isMarkerable) {
return
}
let markups = position.marker && position.marker.markups
markups = markups || []
return this.insertTextWithMarkup(position, text, markups)
}
_replaceSection(section: Section, newSections: Section[]) {
let nextSection = section.next
let collection = ((section.parent as unknown) as HasChildSections).sections
let nextNewSection = newSections[0]
if (isMarkupSection(nextNewSection) && isListItem(section)) {
// put the new section after the ListSection (section.parent)
// instead of after the ListItem
collection = ((section.parent.parent as unknown) as HasChildSections).sections
nextSection = section.parent.next
}
newSections.forEach(s => this.insertSectionBefore(collection, s, nextSection))
this.removeSection(section)
}
/**
* Given a markerRange (for example `editor.range`) mark all markers
* inside it as a given markup. The markup must be provided as a post
* abstract node.
*
* Usage:
*
* let range = editor.range;
* let strongMarkup = editor.builder.createMarkup('strong');
* editor.run((postEditor) => {
* postEditor.addMarkupToRange(range, strongMarkup);
* });
* // Will result some markers possibly being split, and the markup
* // being applied to all markers between the split.
*
* @param {Range} range
* @param {Markup} markup A markup post abstract node
* @public
*/
addMarkupToRange(range: Range, markup: Markup) {
if (range.isCollapsed) {
return
}
let markers = this.splitMarkers(range)
if (markers.length) {
// We insert the new markup at a consistent index across the range.
// If we just push on the end of the list, it can end up in different positions
// of the markup stack. This results in unnecessary closing and re-opening of
// the markup each time it changes position.
// If we just push it at the beginning of the list, this causes unnecessary closing
// and re-opening of surrounding tags.
// So, we look for any tags open across the whole range, and push into the stack
// at the end of those.
// Prompted by https://github.com/bustle/mobiledoc-kit/issues/360
let markupsOpenAcrossRange = reduce(
markers,
function (soFar, marker) {
return commonItems(soFar, marker.markups)
},
markers[0].markups
)
let indexToInsert = markupsOpenAcrossRange.length
markers.forEach(marker => {
marker.addMarkupAtIndex(markup, indexToInsert)
this._markDirty(marker)
})
}
}
/**
* Given a markerRange (for example `editor.range`) remove the given
* markup from all contained markers.
*
* Usage:
* ```
* let { range } = editor;
* let markup = markerRange.headMarker.markups[0];
* editor.run(postEditor => {
* postEditor.removeMarkupFromRange(range, markup);
* });
* // Will result in some markers possibly being split, and the markup
* // being removed from all markers between the split.
* ```
* @param {Range} range Object with offsets
* @param {Markup|Function} markupOrCallback A markup post abstract node or
* a function that returns true when passed a markup that should be removed
* @private
*/
removeMarkupFromRange(range: Range, markupOrMarkupCallback: ((markup: Markup) => boolean) | Markup) {
if (range.isCollapsed) {
return
}
this.splitMarkers(range).forEach(marker => {
marker.removeMarkup(markupOrMarkupCallback)
this._markDirty(marker)
})
}
/**
* Toggle the given markup in the given range (or at the position given). If the range/position
* has the markup, the markup will be removed. If nothing in the range/position
* has the markup, the markup will be added to everything in the range/position.
*
* Usage:
* ```
* // Remove any 'strong' markup if it exists in the selection, otherwise
* // make it all 'strong'
* editor.run(postEditor => postEditor.toggleMarkup('strong'));
*
* // add/remove a link to 'bustle.com' to the selection
* editor.run(postEditor => {
* const linkMarkup = postEditor.builder.createMarkup('a', {href: 'http://bustle.com'});
* postEditor.toggleMarkup(linkMarkup);
* });
* ```
* @param {Markup|String} markupOrString Either a markup object created using
* the builder (useful when adding a markup with attributes, like an 'a' markup),
* or, if a string, the tag name of the markup (e.g. 'strong', 'em') to toggle.
* @param {Range|Position} range in which to toggle. Defaults to current editor range.
* @public
*/
toggleMarkup(markupOrMarkupString: Markup | string, range: Range | Position = this._range) {
range = toRange(range)
const markup =
typeof markupOrMarkupString === 'string' ? this.builder.createMarkup(markupOrMarkupString) : markupOrMarkupString
const hasMarkup = this.editor.detectMarkupInRange(range, markup.tagName)
// FIXME: This implies only a single markup in a range. This may not be
// true for links (which are not the same object instance like multiple
// strong tags would be).
if (hasMarkup) {
this.removeMarkupFromRange(range, hasMarkup)
} else {
this.addMarkupToRange(range, markup)
}
this.setRange(range)
}
/**
* Toggles the tagName of the active section or sections in the given range/position.
* If every section has the tag name, they will all be reset to default sections.
* Otherwise, every section will be changed to the requested type
*
* @param {String} sectionTagName A valid markup section or
* list section tag name (e.g. 'blockquote', 'h2', 'ul')
* @param {Range|Position} range The range over which to toggle.
* Defaults to the current editor range.
* @public
*/
toggleSection(sectionTagName: string, range: Range | Position = this._range) {
range = shrinkRange(toRange(range))
sectionTagName = normalizeTagName(sectionTagName)
let { post } = this.editor
let everySectionHasTagName = true
post.walkMarkerableSections(range, section => {
if (!this._isSameSectionType(section, sectionTagName)) {
everySectionHasTagName = false
}
})
let tagName = everySectionHasTagName ? 'p' : sectionTagName
let sectionTransformations: SectionTransformation[] = []
post.walkMarkerableSections(range, section => {
let changedSection = this.changeSectionTagName(section, tagName)
sectionTransformations.push({
from: section,
to: changedSection,
})
})
let nextRange = this._determineNextRangeAfterToggleSection(range, sectionTransformations)
this.setRange(nextRange)
}
_determineNextRangeAfterToggleSection(range: Range, sectionTransformations: SectionTransformation[]) {
if (sectionTransformations.length) {
let changedHeadSection = detect(sectionTransformations, ({ from }) => {
return from === range.headSection
})!.to
let changedTailSection = detect(sectionTransformations, ({ from }) => {
return from === range.tailSection
})!.to
if (changedHeadSection.isListSection || changedTailSection.isListSection) {
// We don't know to which ListItem's the original sections point at, so
// we don't have enough information to reconstruct the range when
// dealing with lists.
return sectionTransformations[0].to.headPosition().toRange()
} else {
return Range.create(
changedHeadSection as Markerable,
range.headSectionOffset,
changedTailSection as Markerable,
range.tailSectionOffset,
range.direction
)
}
} else {
return range
}
}
setAttribute(key: string, value: string, range: Range = this._range) {
this._mutateAttribute(key, range, (section, attribute) => {
if (section.getAttribute(attribute) !== value) {
section.setAttribute(attribute, value)
return true
}
})
}
removeAttribute(key: string, range: Range = this._range) {
this._mutateAttribute(key, range, (section, attribute) => {
if (section.hasAttribute(attribute)) {
section.removeAttribute(attribute)
return true
}
})
}
_mutateAttribute(key: string, range: Range, cb: (section: Attributable, attribute: string) => boolean | void) {
range = toRange(range)
let { post } = this.editor
let attribute = `data-md-${key}`
post.walkMarkerableSections(range, section => {
const cbSection: Attributable = isListItem(section) ? section.parent : ((section as unknown) as Attributable)
if (cb(cbSection, attribute) === true) {
this._markDirty(section)
}
})
this.setRange(range)
}
_isSameSectionType(section: Section & TagNameable, sectionTagName: string) {
return isListItem(section) ? section.parent.tagName === sectionTagName : section.tagName === sectionTagName
}
/**
* @param {Markerable} section
* @private
*/
changeSectionTagName(section: Markerable & TagNameable, newTagName: string) {
assert('Cannot pass non-markerable section to `changeSectionTagName`', section.isMarkerable)
if (isListSectionTagName(newTagName)) {
return this._changeSectionToListItem(section, newTagName)
} else if (isListItem(section)) {
return this._changeSectionFromListItem(section, newTagName)
} else {
section.tagName = newTagName
this._markDirty(section)
return section
}
}
/**
* Splits the item at the position given.
* If the position is at the start or end of the item, the pre- or post-item
* will contain a single empty ("") marker.
* @param {ListItem} item
* @param {Position} position
* @return {Array} the pre-item and post-item on either side of the split
* @private
*/
_splitListItem(item: ListItem, position: Position): [ListItem, ListItem] {
let { section, offset } = position
assert('Cannot split list item at position that does not include item', item === section)
item.splitMarkerAtOffset(offset)
let prevMarker = item.markerBeforeOffset(offset)
let preItem = this.builder.createListItem(),
postItem = this.builder.createListItem()
let currentItem = preItem
item.markers.forEach(marker => {
currentItem.markers.append(marker.clone())
if (marker === prevMarker) {
currentItem = postItem
}
})
this._replaceSection(item, [preItem, postItem])
return [preItem, postItem]
}
/**
* Splits the list at the position given.
* @return {Array} pre-split list and post-split list, either of which could
* be blank (0-item list) if the position is at the start or end of the list.
*
* Note: Contiguous list sections will be joined in the before_complete queue
* of the postEditor.
*
* @private
*/
_splitListAtPosition(list: ListSection, position: Position): [ListSection, ListSection] {
assert('Cannot split list at position not in list', position.section!.parent === list)
let positionIsMiddle = !position.isHead() && !position.isTail()
if (positionIsMiddle) {
let item = position.section! as ListItem
let [pre] = this._splitListItem(item, position)
position = pre.tailPosition()
}
let preList = this.builder.createListSection(list.tagName)
let postList = this.builder.createListSection(list.tagName)
let preItem = position.section
let currentList = preList
list.items.forEach(item => {
// If this item matches the start item and the position is at its start,
// it should be appended to the postList instead of the preList
if (item === preItem && position.isEqual(item.headPosition())) {
currentList = postList
}
currentList.items.append(item.clone())
// If we just appended the preItem, append the remaining items to the postList
if (item === preItem) {
currentList = postList
}
})
this._replaceSection(list, [preList, postList])
return [preList, postList]
}
/**
* @return Array of [prev, mid, next] lists. `prev` and `next` can
* be blank, depending on the position of `item`. `mid` will always
* be a 1-item list containing `item`. `prev` and `next` will be
* removed in the before_complete queue if they are blank
* (and still attached).
*
* @private
*/
_splitListAtItem(list: ListSection, item: ListItem) {
let next = list
let prev = this.builder.createListSection(next.tagName, [], next.attributes)
let mid = this.builder.createListSection(next.tagName)
let addToPrev = true
// must turn the LinkedList into an array so that we can remove items
// as we iterate through it
let items = next.items.toArray()
items.forEach(i => {
let listToAppend: ListSection
if (i === item) {
addToPrev = false
listToAppend = mid
} else if (addToPrev) {
listToAppend = prev
} else {
return // break after iterating prev and mid parts of the list
}
listToAppend.join(i)
this.removeSection(i)
})
let found = !addToPrev
assert('Cannot split list at item that is not present in the list', found)
let collection = this.editor.post.sections
this.insertSectionBefore(collection, mid, next)
this.insertSectionBefore(collection, prev, mid)
// Remove possibly blank prev/next lists
this.addCallback(CALLBACK_QUEUES.BEFORE_COMPLETE, () => {
;[prev, next].forEach(_list => {
let isAttached = !!_list._parent
if (_list.isBlank && isAttached) {
this.removeSection(_list)
}
})
})
return [prev, mid, next]
}
_changeSectionFromListItem(section: Section, newTagName: string) {
assertType<ListItem>('Must pass list item to `_changeSectionFromListItem`', section, isListItem(section))
let listSection = section.parent as ListSection
let markupSection = this.builder.createMarkupSection(newTagName)
markupSection.join(section)
let [, mid] = this._splitListAtItem(listSection, section)
this.replaceSection(mid, markupSection)
return markupSection
}
_changeSectionToListItem(section: ListSection | Markerable, newTagName: string) {
let isAlreadyCorrectListItem =
section.isListItem && ((section.parent as unknown) as TagNameable).tagName === newTagName
if (isAlreadyCorrectListItem) {
return section
}
let listSection = this.builder.createListSection(newTagName)
listSection.join(section)
let sectionToReplace: Section
if (isListItem(section)) {
let [, mid] = this._splitListAtItem(section.parent, section)
sectionToReplace = mid
} else {
sectionToReplace = section
}
this.replaceSection(sectionToReplace, listSection)
return listSection
}
/**
* Insert a given section before another one, updating the post abstract
* and the rendered UI.
*
* Usage:
* ```
* let markerRange = editor.range;
* let sectionWithCursor = markerRange.headMarker.section;
* let section = editor.builder.createCardSection('my-image');
* let collection = sectionWithCursor.parent.sections;
* editor.run((postEditor) => {
* postEditor.insertSectionBefore(collection, section, sectionWithCursor);
* });
* ```
* @param {LinkedList} collection The list of sections to insert into
* @param {Object} section The new section
* @param {Object} beforeSection Optional The section "before" is relative to,
* if falsy the new section will be appended to the collection
* @public
*/
insertSectionBefore(
collection: LinkedList<Section> | LinkedList<Cloneable<Section>>,
section: Section,
beforeSection?: Option<Section>
) {
;(collection as LinkedList<Section>).insertBefore(section, beforeSection)
this._markDirty(section.parent)
}
/**
* Insert the given section after the current active section, or, if no
* section is active, at the end of the document.
* @param {Section} section
* @public
*/
insertSection(section: Section) {
const activeSection = this.editor.activeSection
const nextSection = activeSection && activeSection.next
const collection = (this.editor.post.sections as unknown) as LinkedList<Section>
this.insertSectionBefore(collection, section, nextSection)
}
/**
* Insert the given section at the end of the document.
* @param {Section} section
* @public
*/
insertSectionAtEnd(section: Section) {
this.insertSectionBefore(this.editor.post.sections, section, null)
}
/**
* Insert the `post` at the given position in the editor's post.
* @param {Position} position
* @param {Post} post
* @private
*/
insertPost(position: Position, newPost: Post) {
let post = this.editor.post
let inserter = new PostInserter(this, post)
let nextPosition = inserter.insert(position, newPost)
return nextPosition
}
/**
* Remove a given section from the post abstract and the rendered UI.
*
* Usage:
* ```
* let { range } = editor;
* let sectionWithCursor = range.head.section;
* editor.run((postEditor) => {
* postEditor.removeSection(sectionWithCursor);
* });
* ```
* @param {Object} section The section to remove
* @public
*/
removeSection(section: Section) {
let parent = section.parent
assertType<HasChildSections>('expected section to have child sections', parent, hasChildSections(parent))
this._scheduleForRemoval(section)
parent.sections.remove(section)
if (isListSection(parent)) {
this._scheduleListRemovalIfEmpty(parent)
}
}
removeAllSections() {
this.editor.post.sections.toArray().forEach(section => {
this.removeSection(section)
})
}
migrateSectionsFromPost(post: Post) {
post.sections.toArray().forEach(section => {
post.sections.remove(section)
this.insertSectionBefore(this.editor.post.sections, section, null)
})
}
_scheduleListRemovalIfEmpty(listSection: ListSection) {
this.addCallback(CALLBACK_QUEUES.BEFORE_COMPLETE, () => {
// if the list is attached and blank after we do other rendering stuff,
// remove it
let isAttached = !!listSection._parent
if (isAttached && listSection.isBlank) {
this.removeSection(listSection)
}
})
}
/**
* A method for adding work the deferred queue
*
* @param {Function} callback to run during completion
* @param {Boolean} [once=false] Whether to only schedule the callback once.
* @public
*/
schedule(callback: LifecycleCallback, once: boolean = false) {
assert('Work can only be scheduled before a post edit has completed', !this._didComplete)
if (once) {
this.addCallbackOnce(CALLBACK_QUEUES.COMPLETE, callback)
} else {
this.addCallback(CALLBACK_QUEUES.COMPLETE, callback)
}
}
/**
* A method for adding work the deferred queue. The callback will only
* be added to the queue once, even if `scheduleOnce` is called multiple times.
* The function cannot be an anonymous function.
*
* @param {Function} callback to run during completion
* @public
*/
scheduleOnce(callback: LifecycleCallback) {
this.schedule(callback, true)
}
/**
* Add a rerender job to the queue
*
* @public
*/
scheduleRerender() {
this.scheduleOnce(this._rerender)
}
/**
* Schedule a notification that the post has been changed.
* The notification will result in the editor firing its `postDidChange`
* hook after the postEditor completes its work (at the end of {@link Editor#run}).
*
* @public
*/
scheduleDidUpdate() {
this.scheduleOnce(this._postDidChange)
}
scheduleAfterRender(callback: LifecycleCallback, once = false) {
if (once) {
this.addCallbackOnce(CALLBACK_QUEUES.AFTER_COMPLETE, callback)
} else {
this.addCallback(CALLBACK_QUEUES.AFTER_COMPLETE, callback)
}
}
/**
* Flush any work on the queue. {@link Editor#run} calls this method; it
* should not be called directly.
*
* @private
*/
complete() {
assert('Post editing can only be completed once', !this._didComplete)
this.runCallbacks(CALLBACK_QUEUES.BEFORE_COMPLETE)
this._didComplete = true
this.runCallbacks(CALLBACK_QUEUES.COMPLETE)
this.runCallbacks(CALLBACK_QUEUES.AFTER_COMPLETE)
}
undoLastChange() {
this.editor._editHistory.stepBackward(this)
}
redoLastChange() {
this.editor._editHistory.stepForward(this)
}
cancelSnapshot() {
this._shouldCancelSnapshot = true
}
} | the_stack |
import { expect } from "chai";
import * as sinon from "sinon";
import { StandardTypeNames } from "@itwin/appui-abstract";
import { FilterOperator } from "../../../components-react/table/columnfiltering/ColumnFiltering";
import { TableColumnFilterDescriptor } from "../../../components-react/table/columnfiltering/TableColumnFilterDescriptor";
import { ReactDataGridColumn, TableColumn } from "../../../components-react/table/component/TableColumn";
import { SimpleTableDataProvider } from "../../../components-react/table/SimpleTableDataProvider";
import { ColumnDescription, RowItem } from "../../../components-react/table/TableDataProvider";
import { TestFilterableTable, TestUtils } from "../../TestUtils";
const columns: ColumnDescription[] = [
{
key: "lorem",
label: "Lorem",
},
{
key: "index",
label: "Index",
showDistinctValueFilters: false,
showFieldFilters: false,
filterCaseSensitive: true,
},
];
// cSpell:ignore lorem
// cSpell:disable
const loremIpsum = [
"Lorem",
"ipsum",
"dolor",
"sit",
"amet,",
"consectetur",
"adipiscing",
"elit,",
"sed",
"do",
];
// cSpell:enable
const createRow = (i: number) => {
const row: RowItem = { key: i.toString(), cells: [] };
const loremIndex = i % 10;
row.cells.push({
key: columns[0].key,
record: TestUtils.createPropertyRecord(loremIpsum[loremIndex], columns[0], StandardTypeNames.Text),
});
row.cells.push({
key: columns[1].key,
record: TestUtils.createPropertyRecord(i + 1, columns[1], StandardTypeNames.Number),
});
return row;
};
const numTestRows = 100;
describe("FilterableColumn", () => {
let rows: RowItem[];
let dataProvider: SimpleTableDataProvider;
let testTable: TestFilterableTable;
let columnDescriptions: ColumnDescription[];
let filterableColumn0: TableColumn;
let filterableColumn1: TableColumn;
let columnDescription0: ColumnDescription;
let columnDescription1: ColumnDescription;
const onApplyFilterSpy = sinon.spy();
const applyFilter = async (): Promise<void> => {
if (dataProvider.applyFilterDescriptors) {
await dataProvider.applyFilterDescriptors(testTable.filterDescriptors);
onApplyFilterSpy();
}
};
before(async () => {
rows = new Array<RowItem>();
for (let i = 0; i < numTestRows; i++) {
const row = createRow(i);
rows.push(row);
}
testTable = new TestFilterableTable(columns);
dataProvider = new SimpleTableDataProvider(columns);
dataProvider.setItems(rows);
columnDescriptions = await dataProvider.getColumns();
});
beforeEach(async () => {
testTable.filterDescriptors.clear();
await applyFilter();
onApplyFilterSpy.resetHistory();
columnDescription0 = columnDescriptions[0];
const reactDataGridColumn0: ReactDataGridColumn = {
key: columnDescription0.key,
name: columnDescription0.label,
};
filterableColumn0 = new TableColumn(testTable, columnDescription0, reactDataGridColumn0);
columnDescription1 = columnDescriptions[1];
const reactDataGridColumn1: ReactDataGridColumn = {
key: columnDescription0.key,
name: columnDescription0.label,
};
filterableColumn1 = new TableColumn(testTable, columnDescription1, reactDataGridColumn1);
});
describe("properties", () => {
it("filterableTable should get table", () => {
expect(filterableColumn0.filterableTable).to.eq(testTable);
});
it("columnFilterDescriptor should get filter description", () => {
expect(filterableColumn0.isFilterActive).to.be.false;
expect(filterableColumn0.columnFilterDescriptor).to.not.be.undefined;
expect(filterableColumn0.isFilterActive).to.be.false;
});
it("filterMemberType should get member type", () => {
expect(filterableColumn0.filterMemberType).to.eq(StandardTypeNames.Text);
});
it("showDistinctValueFilters should get proper value", () => {
expect(filterableColumn0.showDistinctValueFilters).to.be.true;
expect(filterableColumn1.showDistinctValueFilters).to.be.false;
});
it("showFieldFilters should get proper value", () => {
expect(filterableColumn0.showFieldFilters).to.be.true;
expect(filterableColumn1.showFieldFilters).to.be.false;
});
});
describe("ColumnFilterDescriptor", () => {
beforeEach(() => {
filterableColumn0.columnFilterDescriptor.distinctFilter.addDistinctValue("lorem");
filterableColumn0.columnFilterDescriptor.fieldFilter.addFieldValue("ipsum", FilterOperator.IsEqualTo);
});
it("column property should return the FilterableColumn", () => {
const columnFilterDescriptor = filterableColumn0.columnFilterDescriptor as TableColumnFilterDescriptor;
expect(columnFilterDescriptor).to.not.be.undefined;
expect(columnFilterDescriptor.column).to.eq(filterableColumn0);
});
it("memberKey property should return the column key", () => {
const columnFilterDescriptor = filterableColumn0.columnFilterDescriptor as TableColumnFilterDescriptor;
expect(columnFilterDescriptor.memberKey).to.eq(filterableColumn0.columnDescription.key);
});
it("memberType property should return the column type", () => {
const columnFilterDescriptor = filterableColumn0.columnFilterDescriptor as TableColumnFilterDescriptor;
expect(columnFilterDescriptor.memberType).to.eq(StandardTypeNames.Text);
});
it("memberKey setter should set the key", () => {
const columnFilterDescriptor = filterableColumn0.columnFilterDescriptor as TableColumnFilterDescriptor;
columnFilterDescriptor.memberKey = "lorem";
expect(columnFilterDescriptor.memberKey).to.eq("lorem");
columnFilterDescriptor.memberKey = "abc";
expect(columnFilterDescriptor.memberKey).to.eq("abc");
columnFilterDescriptor.memberKey = "lorem";
});
it("memberType setter should set the type", () => {
const columnFilterDescriptor = filterableColumn0.columnFilterDescriptor as TableColumnFilterDescriptor;
columnFilterDescriptor.memberType = StandardTypeNames.Text;
expect(columnFilterDescriptor.memberType).to.eq(StandardTypeNames.Text);
columnFilterDescriptor.memberType = StandardTypeNames.Boolean;
expect(columnFilterDescriptor.memberType).to.eq(StandardTypeNames.Boolean);
columnFilterDescriptor.memberType = StandardTypeNames.Text;
});
it("getFilterExpression should return ECExpression for the descriptor", () => {
const columnFilterDescriptor = filterableColumn0.columnFilterDescriptor as TableColumnFilterDescriptor;
const expression = columnFilterDescriptor.getFilterExpression();
expect(expression).to.eq(`((lorem = "lorem")) And ((lorem = "ipsum"))`);
});
});
describe("DistinctValuesFilterDescriptor", () => {
beforeEach(() => {
filterableColumn0.columnFilterDescriptor.distinctFilter.addDistinctValue("Lorem");
filterableColumn0.columnFilterDescriptor.distinctFilter.addDistinctValue("ipsum");
});
it("distinctValues should return values", () => {
const columnFilterDescriptor = filterableColumn0.columnFilterDescriptor;
const distinctFilter = columnFilterDescriptor.distinctFilter;
const distinctValues = distinctFilter.distinctValues;
expect(distinctValues.values.length).to.eq(2);
expect(distinctValues.values[0]).to.eq("Lorem");
expect(distinctValues.values[1]).to.eq("ipsum");
});
it("isFilterForColumn should return proper value", () => {
const columnFilterDescriptor = filterableColumn0.columnFilterDescriptor;
const distinctFilter = columnFilterDescriptor.distinctFilter;
expect(distinctFilter.isFilterForColumn("lorem")).to.be.true;
expect(distinctFilter.isFilterForColumn("index")).to.be.false;
});
it("trying to add a duplicate should not allow", () => {
const columnFilterDescriptor = filterableColumn0.columnFilterDescriptor;
const distinctFilter = columnFilterDescriptor.distinctFilter;
expect(distinctFilter.distinctValues.values.length).to.eq(2);
distinctFilter.addDistinctValue("Lorem");
expect(distinctFilter.distinctValues.values.length).to.eq(2);
});
it("remove should take out correctly", () => {
const columnFilterDescriptor = filterableColumn0.columnFilterDescriptor;
const distinctFilter = columnFilterDescriptor.distinctFilter;
expect(distinctFilter.distinctValues.values.length).to.eq(2);
distinctFilter.removeDistinctValue("Lorem");
expect(distinctFilter.distinctValues.values.length).to.eq(1);
});
it("trying to remove a missing value should be handled", () => {
const columnFilterDescriptor = filterableColumn0.columnFilterDescriptor;
const distinctFilter = columnFilterDescriptor.distinctFilter;
expect(distinctFilter.distinctValues.values.length).to.eq(2);
distinctFilter.removeDistinctValue(1);
expect(distinctFilter.distinctValues.values.length).to.eq(2);
});
it("distinctValuesComparisonOperator should get and set", () => {
const columnFilterDescriptor = filterableColumn0.columnFilterDescriptor;
const distinctFilter = columnFilterDescriptor.distinctFilter;
expect(distinctFilter.distinctValuesComparisonOperator).to.eq(FilterOperator.IsEqualTo);
distinctFilter.distinctValuesComparisonOperator = FilterOperator.IsNotEqualTo;
expect(distinctFilter.distinctValuesComparisonOperator).to.eq(FilterOperator.IsNotEqualTo);
distinctFilter.distinctValuesComparisonOperator = FilterOperator.IsEqualTo;
});
it("getFilterExpression should return ECExpression for the descriptor", () => {
const columnFilterDescriptor = filterableColumn0.columnFilterDescriptor;
const distinctFilter = columnFilterDescriptor.distinctFilter;
const expression = distinctFilter.getFilterExpression();
expect(expression).to.eq(`(lorem = "Lorem") Or (lorem = "ipsum")`);
});
});
describe("FieldFilterDescriptor", () => {
beforeEach(() => {
filterableColumn1.columnFilterDescriptor.fieldFilter.addFieldValue(10, FilterOperator.IsLessThan);
filterableColumn1.columnFilterDescriptor.fieldFilter.addFieldValue(15, FilterOperator.IsEqualTo);
filterableColumn1.columnFilterDescriptor.fieldFilter.addFieldValue(90, FilterOperator.IsGreaterThanOrEqualTo);
});
it("isFilterForColumn should return proper value", () => {
const columnFilterDescriptor = filterableColumn1.columnFilterDescriptor;
const fieldFilter = columnFilterDescriptor.fieldFilter;
expect(fieldFilter.isFilterForColumn("index")).to.be.true;
expect(fieldFilter.isFilterForColumn("lorem")).to.be.false;
});
it("trying to add a duplicate should not allow", () => {
const columnFilterDescriptor = filterableColumn1.columnFilterDescriptor;
const fieldFilter = columnFilterDescriptor.fieldFilter;
expect(fieldFilter.filterDescriptorCollection.count).to.eq(3);
fieldFilter.addFieldValue(10, FilterOperator.IsLessThan);
expect(fieldFilter.filterDescriptorCollection.count).to.eq(3);
});
it("remove should take out correctly", () => {
const columnFilterDescriptor = filterableColumn1.columnFilterDescriptor;
const fieldFilter = columnFilterDescriptor.fieldFilter;
expect(fieldFilter.filterDescriptorCollection.count).to.eq(3);
fieldFilter.removeFieldValue(10, FilterOperator.IsLessThan);
expect(fieldFilter.filterDescriptorCollection.count).to.eq(2);
});
it("trying to remove a missing value should be handled", () => {
const columnFilterDescriptor = filterableColumn1.columnFilterDescriptor;
const fieldFilter = columnFilterDescriptor.fieldFilter;
expect(fieldFilter.filterDescriptorCollection.count).to.eq(3);
fieldFilter.removeFieldValue(150, FilterOperator.IsEqualTo);
expect(fieldFilter.filterDescriptorCollection.count).to.eq(3);
});
it("getFilterExpression should return ECExpression for the descriptor", () => {
const columnFilterDescriptor = filterableColumn1.columnFilterDescriptor;
const fieldFilter = columnFilterDescriptor.fieldFilter;
const expression = fieldFilter.getFilterExpression();
expect(expression).to.eq(`(index < "10") Or (index = "15") Or (index >= "90")`);
});
});
}); | the_stack |
import { getColIdxFromClientX, getClientY, getClientX, selectAutoFillRange, setPosition, completeAction, showAggregate, dialog, locale, fillRange, hideAutoFillOptions, performUndoRedo, hideAutoFillElement } from '../../spreadsheet/index';
import { Spreadsheet, contentLoaded, positionAutoFillElement, getCellPosition, getRowIdxFromClientY } from '../../spreadsheet/index';
import { performAutoFill, isLockedCells } from '../../spreadsheet/index';
import { ICellRenderer, editAlert, AutoFillEventArgs } from '../common/index';
import { updateSelectedRange, isHiddenRow, setAutoFill, AutoFillType, AutoFillDirection, refreshCell, getFillInfo, getautofillDDB } from '../../workbook/index';
import { getRangeIndexes, getSwapRange, Workbook, getRowsHeight, getColumnsWidth, isInRange } from '../../workbook/index';
import { getCell, CellModel, SheetModel, getRangeAddress, isHiddenCol, beginAction } from '../../workbook/index';
import { addClass, isNullOrUndefined, L10n, removeClass } from '@syncfusion/ej2-base';
import { Dialog } from '../services';
import { ItemModel, MenuEventArgs } from '@syncfusion/ej2-navigations';
import { DropDownButton } from '@syncfusion/ej2-splitbuttons';
/**
* AutoFill module allows to perform auto fill functionalities.
*/
export class AutoFill {
private parent: Spreadsheet;
private autoFillElement: HTMLElement;
private autoFillElementPosition: { left: number, top: number };
private autoFillCell: { rowIndex: number, colIndex: number };
public autoFillDropDown: DropDownButton;
private isVerticalFill: boolean;
private fillOptionIndex: number = 0;
constructor(parent: Spreadsheet) {
this.parent = parent;
this.addEventListener();
}
private getfillItems(): ItemModel[] {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
return [
{ text: l10n.getConstant('CopyCells') },
{ text: l10n.getConstant('FillSeries') },
{ text: l10n.getConstant('FillFormattingOnly') },
{ text: l10n.getConstant('FillWithoutFormatting') }];
}
private init(): void {
this.createAutoFillElement();
}
private createAutoFillElement(): void {
const element: HTMLElement = this.parent.getMainContent();
const ele: HTMLElement = this.parent.createElement('div', { className: 'e-autofill' });
element.appendChild(ele);
this.autoFillElement = ele;
this.getautofillDDB({ id: this.parent.element.id + '_autofilloptionbtn', appendElem: element });
}
private getautofillDDB(args: { id: string, appendElem: HTMLElement }): DropDownButton {
const splitBtnElem: HTMLElement = this.parent.createElement('button', { id: args.id, className: 'e-filloption' });
splitBtnElem.appendChild(this.parent.createElement('span', { className: 'e-tbar-btn-text' }));
this.autoFillDropDown = new DropDownButton({
cssClass: 'e-dragfill-ddb',
iconCss: 'e-icons e-dragfill-icon',
items: this.getfillItems(),
createPopupOnClick: true,
select: (args: MenuEventArgs): void => {
this.autoFillOptionClick({ type: this.getFillType(args.item.text) });
},
beforeOpen: (): void => this.autoFillClick()
});
this.autoFillDropDown.createElement = this.parent.createElement;
this.autoFillDropDown.appendTo(splitBtnElem);
args.appendElem.appendChild(splitBtnElem);
return this.autoFillDropDown;
}
private getFillType(text: string): AutoFillType {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
let type: AutoFillType;
if (text === l10n.getConstant('CopyCells')) { type = 'CopyCells'; }
else if (text === l10n.getConstant('FillSeries')) { type = 'FillSeries'; }
else if (text === l10n.getConstant('FillFormattingOnly')) { type = 'FillFormattingOnly'; }
else { type = 'FillWithoutFormatting'; }
return type;
}
private autoFillClick(): void {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const fillInfo: { fillType: AutoFillType, disableItems: string[] } = { fillType: 'FillSeries', disableItems: [''] };
this.parent.notify(getFillInfo, fillInfo);
this.autoFillDropDown.setProperties({ 'items': this.getfillItems() }, true);
this.autoFillDropDown.removeItems(fillInfo.disableItems);
this.refreshAutoFillOption(l10n.getConstant(fillInfo.fillType));
}
private getFillRange(pStartCell: { rowIndex: number, colIndex: number }, pEndCell: { rowIndex: number, colIndex: number },
pFillCell: { rowIndex: number, colIndex: number }, direction: AutoFillDirection): number[] {
switch (direction) {
case 'Up':
return [pFillCell.rowIndex, pStartCell.colIndex, pStartCell.rowIndex - 1, pEndCell.colIndex];
case 'Right':
return [pStartCell.rowIndex, pEndCell.colIndex + 1, pEndCell.rowIndex, pFillCell.colIndex];
case 'Down':
return [pEndCell.rowIndex + 1, pStartCell.colIndex, pFillCell.rowIndex, pEndCell.colIndex];
case 'Left':
return [pStartCell.rowIndex, pFillCell.colIndex, pEndCell.rowIndex, pStartCell.colIndex - 1];
}
}
private autoFillOptionClick(args: { type: AutoFillType }): void {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const sheet: SheetModel = this.parent.getActiveSheet();
const range: number[] = getSwapRange(getRangeIndexes(this.parent.selectionModule.dAutoFillCell));
const currcell: number[] = getRangeIndexes(sheet.selectedRange);
const minr: number = range[0]; const minc: number = range[1]; const maxr: number = range[2]; const maxc: number = range[3];
const dir: AutoFillDirection = this.getDirection({ rowIndex: maxr, colIndex: maxc }, { rowIndex: currcell[2],
colIndex: currcell[3] });
const dataRange: number[] = [minr, minc, maxr, maxc];
const fillRange: number[] = this.getFillRange({ rowIndex: minr, colIndex: minc }, { rowIndex: maxr, colIndex: maxc },
{ rowIndex: currcell[2], colIndex: currcell[3] }, dir);
this.refreshAutoFillOption(l10n.getConstant(args.type));
this.parent.notify(performUndoRedo, { isUndo: true, isPublic: true, preventEvt: args.type === 'FillWithoutFormatting', preventReSelect: true });
const eventArgs: { dataRange: string, fillRange: string, direction: AutoFillDirection, fillType: AutoFillType,
isFillOptClick: boolean } = { dataRange: sheet.name + '!' + getRangeAddress(dataRange), fillRange:
sheet.name + '!' + getRangeAddress(fillRange), direction: dir, fillType: args.type, isFillOptClick: true };
this.isVerticalFill = eventArgs.direction === 'Down' || eventArgs.direction === 'Up';
this.parent.notify(setAutoFill, eventArgs);
this.positionAutoFillElement({ isautofill: true });
const autoFillArgs: {
dataRange: string,
fillRange: string,
direction: AutoFillDirection,
fillType: AutoFillType,
selectedRange: string
} = { dataRange: eventArgs.dataRange, fillRange: eventArgs.fillRange, fillType: eventArgs.fillType, direction: eventArgs.direction, selectedRange: sheet.name + '!' + getRangeAddress(currcell) };
this.parent.notify(completeAction, { eventArgs: autoFillArgs, action: 'autofill' });
this.parent.notify(showAggregate, {});
this.autoFillClick();
}
private refreshAutoFillOption(type: string): void {
for (let i: number = 0; i < this.autoFillDropDown.items.length; i++) {
this.autoFillDropDown.items[i].iconCss = '';
}
for (let i: number = 0; i < this.autoFillDropDown.items.length; i++) {
if (this.autoFillDropDown.items[i].text === type) {
this.autoFillDropDown.items[i].iconCss = 'e-icons e-selected-icon';
}
}
if (['Copy Cells', 'Fill Series', 'Fill Formatting Only', 'Fill Without Formatting'].indexOf(type) < 0) {
this.autoFillDropDown.items[this.fillOptionIndex].iconCss = '';
}
this.autoFillDropDown.dataBind();
}
private positionAutoFillElement(args?: { isautofill?: boolean, preventAnimation?: boolean }): void {
let top: number = 0; let left: number = 0;
const sheet: SheetModel = this.parent.getActiveSheet();
const indexes: number[] = getSwapRange(getRangeIndexes(sheet.selectedRange));
let tdiff: number = -5;
let ldiff: number = -5;
let otdiff: number = 6;
let oldiff: number = 6;
const isRowSelected: boolean = (indexes[1] === 0 && indexes[3] === sheet.colCount - 1);
const isColSelected: boolean = (indexes[0] === 0 && indexes[2] === sheet.rowCount - 1);
let rowIdx: number = indexes[2];
let colIdx: number = indexes[3];
let height: number; let width: number;
let pos: { top: number, left: number };
const cell: HTMLElement = this.parent.getCell(rowIdx, colIdx);
if (isHiddenCol(sheet, indexes[3]) || isHiddenRow(sheet, indexes[2]) ||
(cell && cell.classList.contains('e-formularef-selection')) || (sheet.isProtected && sheet.protectSettings.selectUnLockedCells
&& isLockedCells(this.parent, indexes))) {
this.hideAutoFillElement();
return;
}
if ((sheet.isProtected && (sheet.protectSettings.selectCells || sheet.protectSettings.selectUnLockedCells)) || !sheet.isProtected) {
if (isRowSelected) {
tdiff = -5;
ldiff = -1;
otdiff = 6;
oldiff = 2;
rowIdx = indexes[2];
colIdx = indexes[1];
}
else if (isColSelected) {
ldiff = -5;
tdiff = 0;
otdiff = 1;
oldiff = 6;
rowIdx = indexes[0];
colIdx = indexes[3];
}
if (sheet.frozenColumns || sheet.frozenRows) {
if (isColSelected || isRowSelected) {
setPosition(this.parent, this.autoFillElement, indexes, 'e-autofill', args && args.preventAnimation);
if (this.parent.autoFillSettings.showFillOptions && args && args.isautofill) {
setPosition(this.parent, this.autoFillDropDown.element, indexes, 'e-filloption');
}
}
else {
setPosition(
this.parent, this.autoFillElement, [rowIdx, colIdx, rowIdx, colIdx], 'e-autofill', args && args.preventAnimation);
if (this.parent.autoFillSettings.showFillOptions && args && args.isautofill) {
setPosition(this.parent, this.autoFillDropDown.element, [rowIdx, colIdx, rowIdx, colIdx], 'e-filloption');
}
}
if (this.autoFillElement) {
this.autoFillCell = { rowIndex: rowIdx, colIndex: colIdx };
const element: Element = this.parent.element.querySelectorAll('.e-autofill')[0];
if (element) {
const clientRect: ClientRect = element.getBoundingClientRect();
this.autoFillElementPosition = {
left: clientRect.left, top: clientRect.top
};
}
}
}
else {
pos = getCellPosition(
sheet, [rowIdx, colIdx, rowIdx, colIdx], this.parent.frozenRowCount(sheet), this.parent.frozenColCount(sheet),
this.parent.viewport.beforeFreezeHeight, this.parent.viewport.beforeFreezeWidth, this.parent.sheetModule.colGroupWidth);
height = getRowsHeight(sheet, rowIdx, rowIdx, true);
width = getColumnsWidth(sheet, colIdx, colIdx, true);
if (!isColSelected) { top += height; }
if (!isRowSelected) { left += width; }
top += Math.round(pos.top) + tdiff;
left += Math.round(pos.left) + ldiff;
if (this.autoFillElement) {
removeClass([this.autoFillElement], 'e-hide');
this.autoFillElement.style.top = top + 'px'; this.autoFillElement.style.left = left + 'px';
this.autoFillCell = { rowIndex: rowIdx, colIndex: colIdx };
const clientRect: ClientRect = this.autoFillElement.getBoundingClientRect();
this.autoFillElementPosition = {
left: clientRect.left, top: clientRect.top
};
if (this.parent.autoFillSettings.showFillOptions && args && args.isautofill) {
removeClass([this.autoFillDropDown.element], 'e-hide');
this.autoFillDropDown.element.style.top = top + otdiff + 'px'; this.autoFillDropDown.element.style.left = left + oldiff + 'px';
}
}
}
}
}
private hideAutoFillElement(): void {
const elem: Element = this.parent.element;
elem.querySelectorAll('.e-autofill').forEach((optElem: Element) => {
if (elem) {
addClass([optElem], 'e-hide');
}
});
}
private hideAutoFillOptions(): void {
const elem: Element = this.parent.element;
elem.querySelectorAll('.e-filloption').forEach((optElem: Element) => {
if (elem) {
addClass([optElem], 'e-hide');
}
});
}
private selectAutoFillRange(args: { e: MouseEvent & TouchEvent, indexes?: number[] }): number[] {
const rowObj: { clientY: number; target: Element; } = { clientY: getClientY(args.e), target: args.e.target as Element };
const colObj: { clientX: number; target: Element; } = { clientX: getClientX(args.e), target: args.e.target as Element };
const sheet: SheetModel = this.parent.getActiveSheet();
this.parent.notify(getRowIdxFromClientY, rowObj);
this.parent.notify(getColIdxFromClientX, colObj);
let rangeIndexes: number[];
const autofillRange: fillRangeInfo
= this.getAutoFillRange({ rowIndex: rowObj.clientY, colIndex: colObj.clientX });
if (autofillRange && autofillRange.fillRange) {
rangeIndexes = [autofillRange.startCell.rowIndex, autofillRange.startCell.colIndex, autofillRange.endCell.rowIndex,
autofillRange.endCell.colIndex];
} else {
rangeIndexes = getRangeIndexes(sheet.selectedRange);
}
args.indexes = rangeIndexes;
return rangeIndexes;
}
private getAutoFillRange(idx: { colIndex: number, rowIndex: number }): fillRangeInfo {
const sheet: SheetModel = this.parent.getActiveSheet();
const aCell: { rowIndex: number; colIndex: number; } = this.autoFillCell;
const range: number[] = getSwapRange(getRangeIndexes(sheet.selectedRange));
const minr: number = range[0];
const minc: number = range[1];
const maxr: number = range[2];
const maxc: number = range[3];
const inRange: boolean = isInRange(range, [idx.rowIndex, idx.colIndex, idx.rowIndex, idx.colIndex], true);
const minIdx: { colIndex: number, rowIndex: number } = { rowIndex: minr, colIndex: minc };
const scell: { colIndex: number, rowIndex: number } = { rowIndex: range[0], colIndex: range[1] };
const ecell: { colIndex: number, rowIndex: number } = { rowIndex: range[2], colIndex: range[3] };
const maxIdx: { colIndex: number, rowIndex: number } = { rowIndex: maxr, colIndex: maxc };
const modifiedIdx: { colIndex: number, rowIndex: number } = this.modifyRangeForMerge(idx.rowIndex,
idx.colIndex, aCell.rowIndex, aCell.colIndex, range);
if (idx.rowIndex < aCell.rowIndex) {// up
if ((minr - idx.rowIndex > idx.colIndex - maxc) && (minr - idx.rowIndex > minc - idx.colIndex))
{
return inRange ? { startCell: minIdx, endCell: { rowIndex: idx.rowIndex, colIndex: maxc } } : { startCell: maxIdx, endCell:
{ rowIndex: modifiedIdx.rowIndex, colIndex: minc }, fillRange: [modifiedIdx.rowIndex, minc, minr - 1, maxc], direction: 'Up' };
}
else if (idx.colIndex > aCell.colIndex) {
return { startCell: minIdx, endCell: { rowIndex: maxr, colIndex: idx.colIndex },
fillRange: [minr, maxc + 1, maxr, idx.colIndex], direction: 'Right' };
}
else if (idx.colIndex < aCell.colIndex) {
return inRange ? { startCell: minIdx, endCell: maxIdx } : { startCell: maxIdx, endCell:
{ rowIndex: minr, colIndex: idx.colIndex }, fillRange: [minr, idx.colIndex, maxr, minc - 1], direction: 'Left' };
}
else { return { startCell: scell, endCell: ecell }; }
}
else if (idx.colIndex > aCell.colIndex) {// right
if ((idx.rowIndex - maxr > idx.colIndex - maxc)) {
return { startCell: minIdx, endCell: { rowIndex: idx.rowIndex, colIndex: maxc },
fillRange: [maxr + 1, minc, idx.rowIndex, maxc], direction: 'Down' };
}
else {
return { startCell: minIdx, endCell: { rowIndex: maxr, colIndex: modifiedIdx.colIndex },
fillRange: [minr, maxc + 1, maxr, modifiedIdx.colIndex], direction: 'Right' };
}
}
else if (idx.colIndex < aCell.colIndex) { // left
if ((idx.rowIndex - maxr > maxc - idx.colIndex) || ((idx.rowIndex - minr > maxc - idx.colIndex) && idx.rowIndex !== maxr)) {
return { startCell: minIdx, endCell: { rowIndex: idx.rowIndex, colIndex: maxc },
fillRange: [maxr + 1, minc, idx.rowIndex, maxc], direction: 'Down' };
}
else {
return inRange ? { startCell: minIdx, endCell: maxIdx } : { startCell: maxIdx, endCell:
{ rowIndex: minr, colIndex: modifiedIdx.colIndex }, fillRange: [minr, modifiedIdx.colIndex, maxr, minc - 1], direction: 'Left' };
}
}
else if (idx.rowIndex > aCell.rowIndex) {// down
return { startCell: minIdx, endCell: { rowIndex: modifiedIdx.rowIndex, colIndex: maxc },
fillRange: [maxr + 1, minc, modifiedIdx.rowIndex, maxc], direction: 'Down' };
}
else if (idx.rowIndex === aCell.rowIndex && idx.colIndex === aCell.colIndex) {
return { startCell: scell, endCell: ecell };
}
else {
return { startCell: scell, endCell: ecell };
}
}
private modifyRangeForMerge(rowIdx: number, colIdx: number, autoFillRowIdx: number, autoFillColIdx:
number, selRange: number[]): { colIndex: number, rowIndex: number } {
const modifiedIdx: { colIndex: number, rowIndex: number } = { rowIndex: rowIdx, colIndex: colIdx };
if (this.isMergedRange(selRange)) {
const selRowCount: number = selRange[2] - selRange[0] + 1;
const selColCount: number = selRange[3] - selRange[1] + 1;
let remainder: number;
if (rowIdx < autoFillRowIdx) { // up
remainder = (selRange[2] - rowIdx + 1) % selRowCount;
if (remainder && rowIdx - (selRowCount - remainder) >= 0) {
modifiedIdx.rowIndex = rowIdx - (selRowCount - remainder);
}
}
else if (colIdx > autoFillColIdx) { // right
remainder = (colIdx - selRange[1] + 1) % selColCount;
if (remainder) {
modifiedIdx.colIndex = colIdx + (selColCount - remainder);
}
}
else if (colIdx < autoFillColIdx) { // left
remainder = (selRange[3] - colIdx + 1) % selColCount;
if (remainder && colIdx - (selColCount - remainder) >= 0) {
modifiedIdx.colIndex = colIdx - (selColCount - remainder);
}
}
else if (rowIdx > autoFillRowIdx) { // down
remainder = (rowIdx - selRange[0] + 1) % selRowCount;
if (remainder) {
modifiedIdx.rowIndex = rowIdx + (selRowCount - remainder);
}
}
}
return modifiedIdx;
}
private performAutoFill(args: { event: MouseEvent & TouchEvent, dAutoFillCell: string }): void {
if (!(args.event.clientX > this.autoFillElementPosition.left && args.event.clientX < this.autoFillElementPosition.left + 10) ||
!(args.event.clientY > this.autoFillElementPosition.top && args.event.clientY < this.autoFillElementPosition.top + 10)) {
const rowObj: { clientY: number; target: Element; } = { clientY: getClientY(args.event), target: args.event.target as Element };
const colObj: { clientX: number; target: Element; } = { clientX: getClientX(args.event), target: args.event.target as Element };
const sheet: SheetModel = this.parent.getActiveSheet();
this.parent.notify(getRowIdxFromClientY, rowObj);
this.parent.notify(getColIdxFromClientX, colObj);
const autofillRange: fillRangeInfo = this.getAutoFillRange({ rowIndex: rowObj.clientY, colIndex: colObj.clientX });
if (autofillRange && autofillRange.fillRange) {
const eventArgs: AutoFillEventArgs = {
dataRange: sheet.name + '!' + args.dAutoFillCell,
fillRange: sheet.name + '!' + getRangeAddress(autofillRange.fillRange), direction: autofillRange.direction,
fillType: this.parent.autoFillSettings.fillType, cancel: false
};
this.parent.notify(beginAction, { eventArgs: eventArgs, action: 'autofill' });
if (eventArgs.cancel) {
return;
}
const isLockedCell: boolean = isLockedCells(this.parent, autofillRange.fillRange);
if (sheet.isProtected && isLockedCell) {
this.parent.notify(editAlert, null);
return;
}
this.performAutoFillAction(eventArgs, autofillRange, isLockedCell);
if (this.isMergedRange(getRangeIndexes(eventArgs.dataRange))) {
this.parent.renderModule.refreshSheet();
}
this.positionAutoFillElement({ isautofill: !this.isMergedRange(getRangeIndexes(eventArgs.fillRange)) });
}
} else {
this.positionAutoFillElement({ isautofill: false });
}
}
private refreshCell(options: { rowIndex: number, colIndex: number }): void {
this.parent.serviceLocator.getService<ICellRenderer>('cell').refreshRange([options.rowIndex, options.colIndex, options.rowIndex, options.colIndex]);
}
private isRange(range: number[]): boolean {
return range && (range[0] !== range[2] || range[1] !== range[3]);
}
private fillRange(options: { verticalFill: boolean }): void {
const args: {
dataRange: string,
fillRange: string,
direction: AutoFillDirection,
fillType: AutoFillType
} = {
dataRange: '',
fillRange: '',
direction: 'Down',
fillType: 'CopyCells'
};
const sheet: SheetModel = this.parent.getActiveSheet();
const range: number[] = getSwapRange(getRangeIndexes(sheet.selectedRange));
const minr: number = range[0]; const minc: number = range[1]; const maxr: number = range[2]; const maxc: number = range[3];
const dirc: AutoFillDirection = this.getDirection({ rowIndex: minr, colIndex: minc }, { rowIndex: maxr, colIndex: maxc },
options.verticalFill);
const isProperKey: boolean = options.verticalFill ? dirc === 'Down' : dirc === 'Right';
if (this.isRange(range) && isProperKey) {
if (options.verticalFill) {
args.dataRange = sheet.name + '!' + getRangeAddress([minr, minc, minr, maxc]);
args.fillRange = sheet.name + '!' + getRangeAddress([minr + 1, minc, maxr, maxc]);
}
else {
args.dataRange = sheet.name + '!' + getRangeAddress([minr, minc, maxr, minc]);
args.fillRange = sheet.name + '!' + getRangeAddress([minr, minc + 1, maxr, maxc]);
}
}
else {
if (options.verticalFill) {
if (!minr) {
return;
}
args.dataRange = sheet.name + '!' + getRangeAddress([minr - 1, minc, minr - 1, maxc]);
}
else {
if (!minc) {
return;
}
args.dataRange = sheet.name + '!' + getRangeAddress([minr, minc - 1, maxr, minc - 1]);
}
args.fillRange = sheet.name + '!' + getRangeAddress(range);
}
args.direction = options.verticalFill ? 'Down' : 'Right';
args.fillType = 'CopyCells';
if (sheet.isProtected) {
return;
}
this.performAutoFillAction(args);
}
private getDirection(endCell: { rowIndex: number, colIndex: number }, currcell: { rowIndex: number, colIndex: number },
isVerticalFill?: boolean): AutoFillDirection {
isVerticalFill = isNullOrUndefined(isVerticalFill) ? this.isVerticalFill : isVerticalFill;
if (isVerticalFill) {
if (currcell.rowIndex < endCell.rowIndex) { // up
return 'Up';
}
else if (currcell.rowIndex > endCell.rowIndex) {// down
return 'Down';
}
else if (currcell.colIndex > endCell.colIndex) {// right
return 'Right';
}
else if (currcell.colIndex < endCell.colIndex) {// left
return 'Left';
}
}
else {
if (currcell.colIndex > endCell.colIndex) {// right
return 'Right';
}
else if (currcell.colIndex < endCell.colIndex) {// left
return 'Left';
}
else if (currcell.rowIndex < endCell.rowIndex) {// up
return 'Up';
}
else if (currcell.rowIndex > endCell.rowIndex) {// down
return 'Down';
}
}
return null;
}
private performAutoFillAction(args: AutoFillEventArgs, autoFillRange?: fillRangeInfo, isLockedCell?: boolean): void {
const sheet: SheetModel = this.parent.getActiveSheet();
const l10n: L10n = this.parent.serviceLocator.getService(locale);
if (this.isMergedRange(getRangeIndexes(args.fillRange))) {
const dialogInst: Dialog = this.parent.serviceLocator.getService(dialog) as Dialog;
dialogInst.show({
target: this.parent.element, isModal: true, showCloseIcon: true, height: 180, width: 400, content: l10n.getConstant('AutoFillMergeAlertMsg'),
buttons: [{
buttonModel: { content: (this.parent.serviceLocator.getService(locale) as L10n).getConstant('Ok'), isPrimary: true },
click: (): void => { dialogInst.hide(); this.parent.selectRange(args.dataRange); }
}],
close: (): void => { dialogInst.hide(); this.parent.selectRange(args.dataRange); }
}, false);
return;
}
this.isVerticalFill = args.direction === 'Down' || args.direction === 'Up';
this.parent.notify(setAutoFill, {
dataRange: args.dataRange,
fillRange: args.fillRange, direction: args.direction, fillType: args.fillType, isLockedCell: isLockedCell
});
const selRange: string = autoFillRange ? getRangeAddress([autoFillRange.startCell.rowIndex, autoFillRange.startCell.colIndex,
autoFillRange.endCell.rowIndex, autoFillRange.endCell.colIndex]) : sheet.selectedRange;
updateSelectedRange(this.parent as Workbook, selRange, sheet);
const autoFillArgs: {
dataRange: string,
fillRange: string,
direction: AutoFillDirection,
fillType: AutoFillType,
selectedRange: string
} = { dataRange: args.dataRange, fillRange: args.fillRange, fillType: args.fillType, direction: args.direction,
selectedRange: selRange };
this.parent.notify(completeAction, { eventArgs: autoFillArgs, action: 'autofill' });
this.parent.notify(showAggregate, {});
}
private getRangeData(options: { range: number[], sheetIdx: number }): CellModel[] {
const arr: CellModel[] = [];
const sheet: SheetModel = this.parent.getActiveSheet();
let minr: number = options.range[0];
let minc: number = options.range[1];
const maxr: number = options.range[2];
const maxc: number = options.range[3];
const minCol: number = minc;
let cell: CellModel;
while (minr <= maxr) {
if (isHiddenRow(sheet, minr)) { minr++; continue; }
minc = minCol;
while (minc <= maxc) {
if (isHiddenCol(sheet, minc)) { minc++; continue; }
cell = getCell(minr, minc, sheet);
arr.push(cell);
minc++;
}
minr++;
}
return arr;
}
private isMergedRange(range: number[]): boolean {
let i: number = 0;
const data: CellModel[] = this.getRangeData({ range: range, sheetIdx: this.parent.activeSheetIndex });
for (i = 0; i < data.length; i++) {
if (data[i] && (data[i].rowSpan || data[i].colSpan)) {
return true;
}
}
return false;
}
private addEventListener(): void {
this.parent.on(contentLoaded, this.init, this);
this.parent.on(positionAutoFillElement, this.positionAutoFillElement, this);
this.parent.on(hideAutoFillOptions, this.hideAutoFillOptions, this);
this.parent.on(hideAutoFillElement, this.hideAutoFillElement, this);
this.parent.on(performAutoFill, this.performAutoFill, this);
this.parent.on(fillRange, this.fillRange, this);
this.parent.on(selectAutoFillRange, this.selectAutoFillRange, this);
this.parent.on(refreshCell, this.refreshCell, this);
this.parent.on(getautofillDDB, this.getautofillDDB, this);
}
private removeEventListener(): void {
if (!this.parent.isDestroyed) {
this.parent.off(contentLoaded, this.init);
this.parent.off(positionAutoFillElement, this.positionAutoFillElement);
this.parent.off(hideAutoFillOptions, this.hideAutoFillOptions);
this.parent.off(hideAutoFillElement, this.hideAutoFillElement);
this.parent.off(performAutoFill, this.performAutoFill);
this.parent.off(fillRange, this.fillRange);
this.parent.off(selectAutoFillRange, this.selectAutoFillRange);
this.parent.off(refreshCell, this.refreshCell);
this.parent.off(getautofillDDB, this.getautofillDDB);
}
}
/**
* Destroy AutoFill module.
*
* @returns {void} - Destroy auto fill module.
*/
public destroy(): void {
this.removeEventListener();
this.parent = null;
}
/**
* Get the AutoFill module name.
*
* @returns {string} - Get the auto fill module name.
*/
public getModuleName(): string {
return 'autofill';
}
}
interface fillRangeInfo {
startCell?: { colIndex: number, rowIndex: number },
endCell?: { colIndex: number, rowIndex: number },
fillRange?: number[],
direction?: AutoFillDirection
} | the_stack |
import { projectRoot} from '../webpack/helpers';
const commander = require('commander');
const fs = require('fs');
const JSON5 = require('json5');
const _cliProgress = require('cli-progress');
const _ = require('lodash');
const program = new commander.Command();
program.version('1.0.0', '-v, --version');
const NEW_MESSAGE_TODO = '// TODO New key - Add a translation';
const MESSAGE_CHANGED_TODO = '// TODO Source message changed - Revise the translation';
const COMMENTS_CHANGED_TODO = '// TODO Source comments changed - Revise the translation';
const DEFAULT_SOURCE_FILE_LOCATION = 'src/assets/i18n/en.json5';
const LANGUAGE_FILES_LOCATION = 'src/assets/i18n';
parseCliInput();
/**
* Parses the CLI input given by the user
* If no parameters are set (standard usage) -> source file is default (set to DEFAULT_SOURCE_FILE_LOCATION) and all
* other language files in the LANGUAGE_FILES_LOCATION are synced with this one in-place
* (replaced with newly synced file)
* If only target-file -t is set -> either -i in-place or -o output-file must be set
* Source file can be set with -s if it should be something else than DEFAULT_SOURCE_FILE_LOCATION
*
* If any of the paths to files/dirs given by user are not valid, an error message is printed and script gets aborted
*/
function parseCliInput() {
program
.option('-d, --output-dir <output-dir>', 'output dir when running script on all language files; mutually exclusive with -o')
.option('-t, --target-file <target>', 'target file we compare with and where completed output ends up if -o is not configured and -i is')
.option('-i, --edit-in-place', 'edit-in-place; store output straight in target file; mutually exclusive with -o')
.option('-s, --source-file <source>', 'source file to be parsed for translation', projectRoot(DEFAULT_SOURCE_FILE_LOCATION))
.option('-o, --output-file <output>', 'where output of script ends up; mutually exclusive with -i')
.usage('([-d <output-dir>] [-s <source-file>]) || (-t <target-file> (-i | -o <output>) [-s <source-file>])')
.parse(process.argv);
if (!program.targetFile) {
fs.readdirSync(projectRoot(LANGUAGE_FILES_LOCATION)).forEach(file => {
if (!program.sourceFile.toString().endsWith(file)) {
const targetFileLocation = projectRoot(LANGUAGE_FILES_LOCATION + "/" + file);
console.log('Syncing file at: ' + targetFileLocation + ' with source file at: ' + program.sourceFile);
if (program.outputDir) {
if (!fs.existsSync(program.outputDir)) {
fs.mkdirSync(program.outputDir);
}
const outputFileLocation = program.outputDir + "/" + file;
console.log('Output location: ' + outputFileLocation);
syncFileWithSource(targetFileLocation, outputFileLocation);
} else {
console.log('Replacing in target location');
syncFileWithSource(targetFileLocation, targetFileLocation);
}
}
});
} else {
if (program.targetFile && !checkIfPathToFileIsValid(program.targetFile)) {
console.error('Directory path of target file is not valid.');
console.log(program.outputHelp());
process.exit(1);
}
if (program.targetFile && checkIfFileExists(program.targetFile) && !(program.editInPlace || program.outputFile)) {
console.error('This target file already exists, if you want to overwrite this add option -i, or add an -o output location');
console.log(program.outputHelp());
process.exit(1);
}
if (!checkIfFileExists(program.sourceFile)) {
console.error('Path of source file is not valid.');
console.log(program.outputHelp());
process.exit(1);
}
if (program.outputFile && !checkIfPathToFileIsValid(program.outputFile)) {
console.error('Directory path of output file is not valid.');
console.log(program.outputHelp());
process.exit(1);
}
syncFileWithSource(program.targetFile, getOutputFileLocationIfExistsElseTargetFileLocation(program.targetFile));
}
}
/**
* Creates chunk lists for both the source and the target files (for example en.json5 and nl.json5 respectively)
* > Creates output chunks by comparing the source chunk with corresponding target chunk (based on key of translation)
* > Writes the output chunks to a new valid lang.json5 file, either replacing the target file (-i in-place)
* or sending it to an output file specified by the user
* @param pathToTargetFile Valid path to target file to generate target chunks from
* @param pathToOutputFile Valid path to output file to write output chunks to
*/
function syncFileWithSource(pathToTargetFile, pathToOutputFile) {
const progressBar = new _cliProgress.SingleBar({}, _cliProgress.Presets.shades_classic);
progressBar.start(100, 0);
const sourceLines = [];
const targetLines = [];
const existingTargetFile = readFileIfExists(pathToTargetFile);
existingTargetFile.toString().split("\n").forEach((function (line) {
targetLines.push(line.trim());
}));
progressBar.update(10);
const sourceFile = readFileIfExists(program.sourceFile);
sourceFile.toString().split("\n").forEach((function (line) {
sourceLines.push(line.trim());
}));
progressBar.update(20);
const sourceChunks = createChunks(sourceLines, progressBar, false);
const targetChunks = createChunks(targetLines, progressBar, true);
const outputChunks = compareChunksAndCreateOutput(sourceChunks, targetChunks, progressBar);
const file = fs.createWriteStream(pathToOutputFile);
file.on('error', function (err) {
console.error('Something went wrong writing to output file at: ' + pathToOutputFile + err)
});
file.on('open', function() {
file.write("{\n");
outputChunks.forEach(function (chunk) {
progressBar.increment();
chunk.split("\n").forEach(function (line) {
file.write(" " + line + "\n");
});
});
file.write("\n}");
file.end();
});
file.on('finish', function() {
const osName = process.platform;
if (osName.startsWith("win")) {
replaceLineEndingsToCRLF(pathToOutputFile);
}
});
progressBar.update(100);
progressBar.stop();
}
/**
* For each of the source chunks:
* - Determine if it's a new key-value => Add it to output, with source comments, source key-value commented, a message indicating it's new and the source-key value uncommented
* - If it's not new, compare it with the corresponding target chunk and log the differences, see createNewChunkComparingSourceAndTarget
* @param sourceChunks All the source chunks, split per key-value pair group
* @param targetChunks All the target chunks, split per key-value pair group
* @param progressBar The progressbar for the CLI
* @return {Array} All the output chunks, split per key-value pair group
*/
function compareChunksAndCreateOutput(sourceChunks, targetChunks, progressBar) {
const outputChunks = [];
sourceChunks.map((sourceChunk) => {
progressBar.increment();
if (sourceChunk.trim().length !== 0) {
let newChunk = [];
const sourceList = sourceChunk.split("\n");
const keyValueSource = sourceList[sourceList.length - 1];
const keySource = getSubStringBeforeLastString(keyValueSource, ":");
const commentSource = getSubStringBeforeLastString(sourceChunk, keyValueSource);
const correspondingTargetChunk = targetChunks.find((targetChunk) => {
return targetChunk.includes(keySource);
});
// Create new chunk with: the source comments, the commented source key-value, the todos and either the old target key-value pair or if it's a new pair, the source key-value pair
newChunk.push(removeWhiteLines(commentSource));
newChunk.push("// " + keyValueSource);
if (correspondingTargetChunk === undefined) {
newChunk.push(NEW_MESSAGE_TODO);
newChunk.push(keyValueSource);
} else {
createNewChunkComparingSourceAndTarget(correspondingTargetChunk, sourceChunk, commentSource, keyValueSource, newChunk);
}
outputChunks.push(newChunk.filter(Boolean).join("\n"));
} else {
outputChunks.push(sourceChunk);
}
});
return outputChunks;
}
/**
* If a corresponding target chunk is found:
* - If old key value is not found in comments > Assumed it is new key
* - If the target comments do not contain the source comments (because they have changed since last time) => Add comments changed message
* - If the key-value in the target comments is not the same as the source key-value (because it changes since last time) => Add message changed message
* - Add the old todos if they haven't been added already
* - End with the original target key-value
*/
function createNewChunkComparingSourceAndTarget(correspondingTargetChunk, sourceChunk, commentSource, keyValueSource, newChunk) {
let commentsOfSourceHaveChanged = false;
let messageOfSourceHasChanged = false;
const targetList = correspondingTargetChunk.split("\n");
const oldKeyValueInTargetComments = getSubStringWithRegex(correspondingTargetChunk, "\\s*\\/\\/\\s*\".*");
const keyValueTarget = targetList[targetList.length - 1];
if (oldKeyValueInTargetComments != null) {
const oldKeyValueUncommented = getSubStringWithRegex(oldKeyValueInTargetComments[0], "\".*")[0];
if (!(_.isEmpty(correspondingTargetChunk) && _.isEmpty(commentSource)) && !removeWhiteLines(correspondingTargetChunk).includes(removeWhiteLines(commentSource.trim()))) {
commentsOfSourceHaveChanged = true;
newChunk.push(COMMENTS_CHANGED_TODO);
}
const parsedOldKey = JSON5.stringify("{" + oldKeyValueUncommented + "}");
const parsedSourceKey = JSON5.stringify("{" + keyValueSource + "}");
if (!_.isEqual(parsedOldKey, parsedSourceKey)) {
messageOfSourceHasChanged = true;
newChunk.push(MESSAGE_CHANGED_TODO);
}
addOldTodosIfNeeded(targetList, newChunk, commentsOfSourceHaveChanged, messageOfSourceHasChanged);
}
newChunk.push(keyValueTarget);
}
// Adds old todos found in target comments if they've not been added already
function addOldTodosIfNeeded(targetList, newChunk, commentsOfSourceHaveChanged, messageOfSourceHasChanged) {
targetList.map((targetLine) => {
const foundTODO = getSubStringWithRegex(targetLine, "\\s*//\\s*TODO.*");
if (foundTODO != null) {
const todo = foundTODO[0];
if (!((todo.includes(COMMENTS_CHANGED_TODO) && commentsOfSourceHaveChanged)
|| (todo.includes(MESSAGE_CHANGED_TODO) && messageOfSourceHasChanged))) {
newChunk.push(todo);
}
}
});
}
/**
* Creates chunks from an array of lines, each chunk contains either an empty line or a grouping of comments with their corresponding key-value pair
* @param lines Array of lines, to be grouped into chunks
* @param progressBar Progressbar of the CLI
* @return {Array} Array of chunks, grouped by key-value and their corresponding comments or an empty line
*/
function createChunks(lines, progressBar, creatingTarget) {
const chunks = [];
let nextChunk = [];
let onMultiLineComment = false;
lines.map((line) => {
progressBar.increment();
if (line.length === 0) {
chunks.push(line);
}
if (isOneLineCommentLine(line)) {
nextChunk.push(line);
}
if (onMultiLineComment) {
nextChunk.push(line);
if (isEndOfMultiLineComment(line)) {
onMultiLineComment = false;
}
}
if (isStartOfMultiLineComment(line)) {
nextChunk.push(line);
onMultiLineComment = true;
}
if (isKeyValuePair(line)) {
nextChunk.push(line);
const newMessageLineIfExists = nextChunk.find((lineInChunk) => lineInChunk.trim().startsWith(NEW_MESSAGE_TODO));
if (newMessageLineIfExists === undefined || !creatingTarget) {
chunks.push(nextChunk.join("\n"));
}
nextChunk = [];
}
});
return chunks;
}
function readFileIfExists(pathToFile) {
if (checkIfFileExists(pathToFile)) {
try {
return fs.readFileSync(pathToFile, 'utf8');
} catch (e) {
console.error('Error:', e.stack);
}
}
return null;
}
function isOneLineCommentLine(line) {
return (line.startsWith("//"));
}
function isStartOfMultiLineComment(line) {
return (line.startsWith("/*"));
}
function isEndOfMultiLineComment(line) {
return (line.endsWith("*/"));
}
function isKeyValuePair(line) {
return (line.startsWith("\""));
}
function getSubStringWithRegex(string, regex) {
return string.match(regex);
}
function getSubStringBeforeLastString(string, char) {
const lastCharIndex = string.lastIndexOf(char);
return string.substr(0, lastCharIndex);
}
function getOutputFileLocationIfExistsElseTargetFileLocation(targetLocation) {
if (program.outputFile) {
return program.outputFile;
}
return targetLocation;
}
function checkIfPathToFileIsValid(pathToCheck) {
if (!pathToCheck.includes("/")) {
return true;
}
return checkIfFileExists(getPathOfDirectory(pathToCheck));
}
function checkIfFileExists(pathToCheck) {
return fs.existsSync(pathToCheck);
}
function getPathOfDirectory(pathToCheck) {
return getSubStringBeforeLastString(pathToCheck, "/");
}
function removeWhiteLines(string) {
return string.replace(/^(?=\n)$|^\s*|\s*$|\n\n+/gm, "")
}
/**
* Replaces UNIX \n LF line endings to windows \r\n CRLF line endings.
* @param filePath Path to file whose line endings are being converted
*/
function replaceLineEndingsToCRLF(filePath) {
const data = readFileIfExists(filePath);
const result = data.replace(/\n/g,"\r\n");
fs.writeFileSync(filePath, result, 'utf8');
} | the_stack |
import * as Mock from '../MockEnvironment';
import { AuthenticationProvider } from '../../src/ui/AuthenticationProvider/AuthenticationProvider';
import { ModalBox } from '../../src/ExternalModulesShim';
import { IAuthenticationProviderOptions } from '../../src/ui/AuthenticationProvider/AuthenticationProvider';
import { IBuildingCallOptionsEventArgs } from '../../src/events/QueryEvents';
import { QueryEvents } from '../../src/events/QueryEvents';
import { ISettingsPopulateMenuArgs } from '../../src/ui/Settings/Settings';
import { SettingsEvents } from '../../src/events/SettingsEvents';
import { l } from '../../src/strings/Strings';
import { $$ } from '../../src/utils/Dom';
import { MissingAuthenticationError } from '../../src/rest/MissingAuthenticationError';
import _ = require('underscore');
import { SearchEndpoint } from '../../src/BaseModules';
import { InitializationEvents } from '../../src/EventsModules';
import { IInitializationEventArgs } from '../../src/events/InitializationEvents';
import { QUERY_STATE_ATTRIBUTES } from '../../src/models/QueryStateModel';
import { Utils } from '../../src/UtilsModules';
export function AuthenticationProviderTest() {
describe('AuthenticationProvider', function () {
const organizationId = 'testorganization';
const accessTokenStorageKey = `coveo-auth-provider-access-token-${organizationId}`;
let initializationArgs: IInitializationEventArgs;
let options: IAuthenticationProviderOptions;
let test: Mock.IBasicComponentSetup<AuthenticationProvider>;
function initAuthenticationProvider() {
test = Mock.optionsComponentSetup<AuthenticationProvider, IAuthenticationProviderOptions>(AuthenticationProvider, options);
}
function setDataTab(el: HTMLElement, tab: string) {
$$(el).setAttribute('data-tab', tab);
}
function triggerAfterComponentsInitialization() {
$$(test.env.root).trigger(InitializationEvents.afterComponentsInitialization, initializationArgs);
}
function setupEndpoint() {
const endpoint = new SearchEndpoint({
restUri: 'https://platform.cloud.coveo.com/rest/search',
queryStringArguments: { organizationId }
});
test.env.queryController.getEndpoint = () => endpoint;
}
beforeEach(function () {
window.location.hash = '';
localStorage.clear();
initializationArgs = {
defer: []
};
options = {
name: 'foo',
caption: 'foobar',
useIFrame: true
};
spyOn(ModalBox, 'open').and.callFake(() => {});
spyOn(ModalBox, 'close').and.callFake(() => {});
initAuthenticationProvider();
});
afterEach(function () {
test = null;
});
it(`local storage contains an access token,
when components have initialized, it updates the endpoint to use the access token`, () => {
const accessToken = 'access-token';
localStorage.setItem(accessTokenStorageKey, accessToken);
initAuthenticationProvider();
setupEndpoint();
const spy = spyOn(test.cmp.queryController.getEndpoint().accessToken, 'updateToken');
triggerAfterComponentsInitialization();
expect(spy).toHaveBeenCalledWith(accessToken);
});
it(`local storage contains an access token,
auth provider has a data-tab configured,
when components have initialized,
it updates the endpoint to use the access token`, () => {
const accessToken = 'access-token';
localStorage.setItem(accessTokenStorageKey, accessToken);
initAuthenticationProvider();
setDataTab(test.cmp.element, 'a');
setupEndpoint();
const spy = spyOn(test.cmp.queryController.getEndpoint().accessToken, 'updateToken');
triggerAfterComponentsInitialization();
expect(spy).toHaveBeenCalledWith(accessToken);
});
describe(`url hash contains a handshake token, when components have initialized`, () => {
const handshakeToken = '04212242-fd27-4825-be27-53844ed83ac9';
const accessToken = 'access-token';
let exchangeTokenSpy: jasmine.Spy;
beforeEach(() => {
window.location.hash = `handshake_token=${handshakeToken}`;
AuthenticationProvider.handshakeInProgress = false;
initAuthenticationProvider();
setupEndpoint();
exchangeTokenSpy = spyOn(test.cmp.queryController.getEndpoint(), 'exchangeHandshakeToken');
exchangeTokenSpy.and.returnValue(Promise.resolve(accessToken));
});
it('sets the handshake-in-progress flag to true', () => {
triggerAfterComponentsInitialization();
expect(AuthenticationProvider.handshakeInProgress).toBe(true);
});
it('exchanges the token', () => {
triggerAfterComponentsInitialization();
expect(exchangeTokenSpy).toHaveBeenCalledWith({ handshakeToken });
});
it(`when an accessToken is found in localstorage,
it sends both the accessToken and handshake token`, () => {
const accessToken = 'access-token';
localStorage.setItem(accessTokenStorageKey, accessToken);
triggerAfterComponentsInitialization();
expect(exchangeTokenSpy).toHaveBeenCalledWith({ handshakeToken, accessToken });
});
it(`url hash starts with / followed by #handshake_token param,
it exchanges the token`, () => {
// Angular by default adds a / between the hash and the hash parameters.
window.location.hash = `/handshake_token=${handshakeToken}`;
triggerAfterComponentsInitialization();
expect(exchangeTokenSpy).toHaveBeenCalledWith({ handshakeToken });
});
it(`url hash contains multiple params including an #handshake_token param,
it exchanges the token`, () => {
window.location.hash = `a=b&handshake_token=${handshakeToken}`;
triggerAfterComponentsInitialization();
expect(exchangeTokenSpy).toHaveBeenCalledWith({ handshakeToken });
});
describe(`url hash contains an active tab and a handshake token param,
auth provider data-tab does not match the active tab`, () => {
beforeEach(() => {
window.location.hash = `${QUERY_STATE_ATTRIBUTES.T}=a&handshake_token=${handshakeToken}`;
setDataTab(test.cmp.element, 'b');
});
it(`does not exchange the handshake token`, () => {
triggerAfterComponentsInitialization();
expect(exchangeTokenSpy).not.toHaveBeenCalled();
});
it('does not load an existing access token', () => {
// Ensures that the AuthenticationProvider that is performing the exchange is using the
// initially configured API key, not an access token loaded by a different instance.
localStorage.setItem(accessTokenStorageKey, 'access-token');
const spy = spyOn(test.cmp.queryController.getEndpoint().accessToken, 'updateToken');
triggerAfterComponentsInitialization();
expect(spy).not.toHaveBeenCalled();
});
});
it(`url hash contains an active tab and a handshake token param,
auth provider data-tab does not match the active tab,
it does not exchange the token`, () => {
window.location.hash = `${QUERY_STATE_ATTRIBUTES.T}=a&handshake_token=${handshakeToken}`;
setDataTab(test.cmp.element, 'b');
triggerAfterComponentsInitialization();
expect(exchangeTokenSpy).not.toHaveBeenCalled();
});
it(`url hash contains an active tab and a handshake token param,
auth provider data-tab matches the active tab,
it exchanges the token`, () => {
window.location.hash = `${QUERY_STATE_ATTRIBUTES.T}=a&handshake_token=${handshakeToken}`;
setDataTab(test.cmp.element, 'a');
$$(test.cmp.element).setAttribute('data-tab', 'a');
triggerAfterComponentsInitialization();
expect(exchangeTokenSpy).toHaveBeenCalledWith({ handshakeToken });
});
it(`url hash contains an #handshake_token with encoded characters,
it decodes the token before exchanging it`, () => {
const token = 'test%3Etoken';
window.location.hash = `handshake_token=${token}`;
triggerAfterComponentsInitialization();
expect(exchangeTokenSpy).toHaveBeenCalledWith({ handshakeToken: 'test>token' });
});
it('adds an entry to the initialization args #defer array', () => {
triggerAfterComponentsInitialization();
expect(initializationArgs.defer.length).toBe(1);
});
it('adds the access token to local storage', async done => {
triggerAfterComponentsInitialization();
await Utils.resolveAfter(0);
const token = localStorage.getItem(accessTokenStorageKey);
expect(token).toBe(accessToken);
done();
});
it('sets the handshake-in-progress flag to false', async done => {
triggerAfterComponentsInitialization();
await Utils.resolveAfter(0);
expect(AuthenticationProvider.handshakeInProgress).toBe(false);
done();
});
it('it removes the handshake token from the url', async done => {
window.location.hash = `a=b&handshake_token=${handshakeToken}`;
triggerAfterComponentsInitialization();
await Utils.resolveAfter(0);
expect(window.location.hash).toBe(`#a=b`);
done();
});
it('when the hash starts with a /, it removes the handshake token from the url but keeps the slash', async done => {
window.location.hash = `/handshake_token=${handshakeToken}`;
triggerAfterComponentsInitialization();
await Utils.resolveAfter(0);
expect(window.location.hash).toBe(`#/`);
done();
});
it('when the handshake token is between two parameters, it removes the handshake token correctly', async done => {
window.location.hash = `/a=b&handshake_token=${handshakeToken}&c=d`;
triggerAfterComponentsInitialization();
await Utils.resolveAfter(0);
expect(window.location.hash).toBe(`#/a=b&c=d`);
done();
});
it('when the hash starts with a /, it removes the handshake token from the url but keeps the slash', async done => {
window.location.hash = `/a=b&handshake_token=${handshakeToken}`;
triggerAfterComponentsInitialization();
await Utils.resolveAfter(0);
expect(window.location.hash).toBe(`#/a=b`);
done();
});
it('updates the endpoint to use the access token', async done => {
const spy = spyOn(test.cmp.queryController.getEndpoint().accessToken, 'updateToken');
triggerAfterComponentsInitialization();
await Utils.resolveAfter(0);
expect(spy).toHaveBeenCalledWith(accessToken);
done();
});
});
describe('url hash contains a handshake token, when the exchange throws an error', () => {
const errorMessage = 'unable to exchange token';
let exchangeTokenSpy: jasmine.Spy;
beforeEach(() => {
window.location.hash = `handshake_token=token`;
initAuthenticationProvider();
setupEndpoint();
exchangeTokenSpy = spyOn(test.cmp.queryController.getEndpoint(), 'exchangeHandshakeToken');
exchangeTokenSpy.and.returnValue(Promise.reject(errorMessage));
});
it(`it logs an error`, async done => {
const logggerSpy = spyOn(test.cmp.logger, 'error');
triggerAfterComponentsInitialization();
await Utils.resolveAfter(0);
expect(logggerSpy).toHaveBeenCalledWith(errorMessage);
done();
});
it('sets the handshake-in-progress flag to false', async done => {
triggerAfterComponentsInitialization();
await Utils.resolveAfter(0);
expect(AuthenticationProvider.handshakeInProgress).toBe(false);
done();
});
});
describe(`a handshake is in progress`, () => {
const accessToken = 'access-token';
beforeEach(() => {
AuthenticationProvider.handshakeInProgress = true;
initAuthenticationProvider();
setupEndpoint();
});
it('when the handshake completes, it loads the access token', async done => {
jasmine.clock().install();
const spy = spyOn(test.cmp.queryController.getEndpoint().accessToken, 'updateToken');
triggerAfterComponentsInitialization();
jasmine.clock().tick(500);
localStorage.setItem(accessTokenStorageKey, accessToken);
AuthenticationProvider.handshakeInProgress = false;
jasmine.clock().tick(100);
jasmine.clock().uninstall();
await Utils.resolveAfter(0);
expect(spy).toHaveBeenCalledWith(accessToken);
done();
});
it('adds an entry to the initialization args #defer array', () => {
triggerAfterComponentsInitialization();
expect(initializationArgs.defer.length).toBe(1);
});
});
describe('when encountering an invalid token error', () => {
let fakeWindow: Window;
function triggerInvalidTokenError() {
const error = { name: 'InvalidTokenException' };
$$(test.env.root).trigger(QueryEvents.queryError, { error });
}
function triggerExpiredTokenError() {
const error = { name: 'ExpiredTokenException' };
$$(test.env.root).trigger(QueryEvents.queryError, { error });
}
function triggerInvalidAuthenticationProviderError() {
const error = { name: 'InvalidAuthenticationProviderException' };
$$(test.env.root).trigger(QueryEvents.queryError, { error });
}
beforeEach(() => {
fakeWindow = Mock.mockWindow();
test.cmp._window = fakeWindow;
setupEndpoint();
});
describe('if there is an invalid access token in storage', () => {
beforeEach(() => {
localStorage.setItem(accessTokenStorageKey, 'invalid token');
triggerInvalidTokenError();
});
it('clears the access token from localstorage', () => {
expect(localStorage.getItem(accessTokenStorageKey)).toBe(null);
});
it('reloads the page', () => {
expect(fakeWindow.location.reload).toHaveBeenCalledTimes(1);
});
});
it('if there is no access token in storage, it does not reload the page', () => {
triggerInvalidTokenError();
expect(fakeWindow.location.reload).not.toHaveBeenCalled();
});
it('if there is an expired access token is in storage, it clears the token', () => {
localStorage.setItem(accessTokenStorageKey, 'expired token');
triggerExpiredTokenError();
expect(localStorage.getItem(accessTokenStorageKey)).toBe(null);
});
it('if there is a token with an invalid authentication provider in storage, it clears the token', () => {
localStorage.setItem(accessTokenStorageKey, 'token with invalid auth provider');
triggerInvalidAuthenticationProviderError();
expect(localStorage.getItem(accessTokenStorageKey)).toBe(null);
});
});
describe('exposes options', function () {
it('name should push name in buildingCallOptions', function () {
options = { name: 'testpatate' };
initAuthenticationProvider();
let eventArgs: IBuildingCallOptionsEventArgs = {
options: {
authentication: []
}
};
$$(test.cmp.root).trigger(QueryEvents.buildingCallOptions, eventArgs);
expect(eventArgs.options.authentication).toEqual(jasmine.arrayContaining(['testpatate']));
});
describe('caption', function () {
it('should set itself in the menu', function () {
let populateMenuArgs: ISettingsPopulateMenuArgs = {
settings: null,
menuData: []
};
$$(test.cmp.root).trigger(SettingsEvents.settingsPopulateMenu, populateMenuArgs);
expect(populateMenuArgs.menuData).toEqual(
jasmine.arrayContaining([
jasmine.objectContaining({
text: l('Reauthenticate', 'foobar'),
className: 'coveo-authentication-provider',
onOpen: jasmine.any(Function)
})
])
);
});
it('should be the title of the modal box when iFrame is enabled', function () {
$$(test.cmp.root).trigger(QueryEvents.queryError, { error: new MissingAuthenticationError('foo') });
expect(ModalBox.open).toHaveBeenCalledWith(
jasmine.anything(),
jasmine.objectContaining({
title: l('Authenticating', 'foobar')
})
);
});
});
it('useIFrame set to false should redirect to auth provider URL', function () {
options = {
name: 'foo',
caption: 'foobar',
useIFrame: false
};
initAuthenticationProvider();
let fakeWindow = Mock.mockWindow();
test.cmp._window = fakeWindow;
test.env.searchEndpoint.getAuthenticationProviderUri = () => 'coveo.com';
$$(test.env.root).trigger(QueryEvents.queryError, { error: new MissingAuthenticationError('foo') });
expect(fakeWindow.location.href).toBe('coveo.com');
});
it('useIFrame and showIFrame set to true should display a ModalBox containing iframe', function () {
options = {
name: 'foo',
caption: 'foobar',
useIFrame: true,
showIFrame: true
};
initAuthenticationProvider();
test.env.searchEndpoint.getAuthenticationProviderUri = () => 'http://coveo.com/';
$$(test.env.root).trigger(QueryEvents.queryError, { error: new MissingAuthenticationError('foo') });
expect(ModalBox.open['calls'].mostRecent().args[0].children[0].src).toBe('http://coveo.com/');
});
it('showIFrame set to false should show a waiting popup not containing the iframe', function () {
options = {
name: 'foo',
caption: 'foobar',
useIFrame: true,
showIFrame: false
};
initAuthenticationProvider();
$$(test.env.root).trigger(QueryEvents.queryError, { error: new MissingAuthenticationError('foo') });
expect(ModalBox.open).toHaveBeenCalledWith(
jasmine.objectContaining({
className: 'coveo-waiting-for-authentication-popup'
}),
jasmine.anything()
);
});
});
it('should stop a redirect loop after 3 redirects', function () {
spyOn(test.cmp.logger, 'error').and.returnValue(null);
_.times(3, () => $$(test.env.root).trigger(QueryEvents.queryError, { error: { provider: 'foo' } }));
$$(test.env.root).trigger(QueryEvents.queryError, { error: new MissingAuthenticationError('foo') });
expect(test.cmp.logger.error).toHaveBeenCalledWith(
'The AuthenticationProvider is in a redirect loop. This may be due to a back-end configuration problem.'
);
});
});
} | the_stack |
import '../fixtures/window';
import { Editor, globalContext } from '@alilc/lowcode-editor-core';
import { Designer } from '../../src/designer/designer';
import formSchema from '../fixtures/schema/form';
import '../../src/designer/builtin-hotkey';
import { fireEvent } from '@testing-library/react';
const editor = new Editor();
let designer: Designer;
beforeAll(() => {
globalContext.register(editor, Editor);
});
beforeEach(() => {
designer = new Designer({ editor });
editor.set('designer', designer);
designer.project.open(formSchema);
});
afterEach(() => {
designer = null;
});
// keyCode 对应表:https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
// hotkey 模块底层用的 keyCode,所以还不能用 key / code 测试
describe('快捷键测试', () => {
it('right', () => {
const firstCardNode = designer.currentDocument?.getNode('node_k1ow3cbj')!;
firstCardNode.select();
fireEvent.keyDown(document, { keyCode: 39 });
expect(designer.currentSelection?.selected.includes('node_k1ow3cbl')).toBeTruthy();
});
it('left', () => {
const firstCardNode = designer.currentDocument?.getNode('node_k1ow3cbl')!;
firstCardNode.select();
fireEvent.keyDown(document, { keyCode: 37 });
expect(designer.currentSelection?.selected.includes('node_k1ow3cbj')).toBeTruthy();
});
it('down', () => {
const firstCardNode = designer.currentDocument?.getNode('node_k1ow3cbl')!;
firstCardNode.select();
fireEvent.keyDown(document, { keyCode: 40 });
expect(designer.currentSelection?.selected.includes('node_k1ow3cbo')).toBeTruthy();
});
it('up', () => {
const secondCardNode = designer.currentDocument?.getNode('node_k1ow3cbm')!;
secondCardNode.select();
fireEvent.keyDown(document, { keyCode: 38 });
expect(designer.currentSelection?.selected.includes('node_k1ow3cbl')).toBeTruthy();
});
// 跟右侧节点调换位置
it('option + right', () => {
const firstButtonNode = designer.currentDocument?.getNode('node_k1ow3cbn')!;
firstButtonNode.select();
fireEvent.keyDown(document, { keyCode: 39, altKey: true });
expect(firstButtonNode.prevSibling?.getId()).toBe('node_k1ow3cbp');
});
// 跟左侧节点调换位置
it('option + left', () => {
const secondButtonNode = designer.currentDocument?.getNode('node_k1ow3cbp')!;
secondButtonNode.select();
fireEvent.keyDown(document, { keyCode: 37, altKey: true });
expect(secondButtonNode.nextSibling?.getId()).toBe('node_k1ow3cbn');
});
// 向父级移动该节点
it('option + up', () => {
const firstCardNode = designer.currentDocument?.getNode('node_k1ow3cbp')!;
firstCardNode.select();
fireEvent.keyDown(document, { keyCode: 38, altKey: true });
});
// 将节点移入到兄弟节点中
it('option + up', () => {
const firstCardNode = designer.currentDocument?.getNode('node_k1ow3cbp')!;
firstCardNode.select();
fireEvent.keyDown(document, { keyCode: 40, altKey: true });
});
// 撤销
it('command + z', async () => {
const firstButtonNode = designer.currentDocument?.getNode('node_k1ow3cbn')!;
let secondButtonNode = designer.currentDocument?.getNode('node_k1ow3cbp')!;
// 等待第一个 session 结束
await new Promise(resolve => setTimeout(resolve, 1000));
firstButtonNode.remove();
expect(secondButtonNode.getParent()?.children.size).toBe(1);
await new Promise(resolve => setTimeout(resolve, 1000));
fireEvent.keyDown(document, { keyCode: 90, metaKey: true });
// 重新获取一次节点,因为 documentModel.import 是全画布刷新
secondButtonNode = designer.currentDocument?.getNode('node_k1ow3cbp')!;
expect(secondButtonNode.getParent()?.children.size).toBe(2);
});
// 重做
it('command + y', async () => {
const firstButtonNode = designer.currentDocument?.getNode('node_k1ow3cbn')!;
let secondButtonNode = designer.currentDocument?.getNode('node_k1ow3cbp')!;
// 等待第一个 session 结束
await new Promise(resolve => setTimeout(resolve, 1000));
firstButtonNode.remove();
expect(secondButtonNode.getParent()?.children.size).toBe(1);
await new Promise(resolve => setTimeout(resolve, 1000));
fireEvent.keyDown(document, { keyCode: 90, metaKey: true });
// 重新获取一次节点,因为 documentModel.import 是全画布刷新
secondButtonNode = designer.currentDocument?.getNode('node_k1ow3cbp')!;
expect(secondButtonNode.getParent()?.children.size).toBe(2);
await new Promise(resolve => setTimeout(resolve, 1000));
fireEvent.keyDown(document, { keyCode: 89, metaKey: true });
// 重新获取一次节点,因为 documentModel.import 是全画布刷新
secondButtonNode = designer.currentDocument?.getNode('node_k1ow3cbp')!;
expect(secondButtonNode.getParent()?.children.size).toBe(1);
});
it('command + c', () => {
const firstCardNode = designer.currentDocument?.getNode('node_k1ow3cbp')!;
firstCardNode.select();
fireEvent.keyDown(document, { keyCode: 67, metaKey: true });
});
it('command + v', async () => {
const secondButtonNode = designer.currentDocument?.getNode('node_k1ow3cbp')!;
secondButtonNode.select();
fireEvent.keyDown(document, { keyCode: 67, metaKey: true });
fireEvent.keyDown(document, { keyCode: 86, metaKey: true });
await new Promise(resolve => setTimeout(resolve, 1000));
// clipboard 异步,先注释
// expect(secondButtonNode.getParent()?.children.size).toBe(3);
});
// 撤销所有选中
it('escape', () => {
const firstCardNode = designer.currentDocument?.getNode('node_k1ow3cbp')!;
firstCardNode.select();
expect(designer.currentSelection!.selected.includes('node_k1ow3cbp')).toBeTruthy();
fireEvent.keyDown(document, { keyCode: 27 });
expect(designer.currentSelection!.selected.length).toBe(0);
});
// 删除节点
it('delete', () => {
const firstButtonNode = designer.currentDocument?.getNode('node_k1ow3cbn')!;
const secondButtonNode = designer.currentDocument?.getNode('node_k1ow3cbp')!;
firstButtonNode.select();
expect(secondButtonNode.prevSibling.id).toBe('node_k1ow3cbn');
fireEvent.keyDown(document, { keyCode: 46 });
expect(secondButtonNode.prevSibling).toBeNull();
});
describe('非正常分支', () => {
it('liveEditing mode', () => {
designer.project.mountSimulator({
liveEditing: {
editing: {},
},
});
editor.set('designer', designer);
designer.currentDocument?.selection.select('page');
// nothing happened
fireEvent.keyDown(document, { keyCode: 39 });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(document, { keyCode: 37 });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(document, { keyCode: 40 });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(document, { keyCode: 38 });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(document, { keyCode: 39, altKey: true });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(document, { keyCode: 37, altKey: true });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(document, { keyCode: 40, altKey: true });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(document, { keyCode: 38, altKey: true });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(document, { keyCode: 90, metaKey: true });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(document, { keyCode: 89, metaKey: true });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(document, { keyCode: 67, metaKey: true });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(document, { keyCode: 86, metaKey: true });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(document, { keyCode: 27 });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(document, { keyCode: 46 });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
});
it('isFormEvent: true', () => {
const inputDOMNode = document.createElement('INPUT');
designer.currentDocument?.selection.select('page');
// nothing happened
fireEvent.keyDown(inputDOMNode, { keyCode: 39 });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(inputDOMNode, { keyCode: 37 });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(inputDOMNode, { keyCode: 40 });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(inputDOMNode, { keyCode: 38 });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(inputDOMNode, { keyCode: 39, altKey: true });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(inputDOMNode, { keyCode: 37, altKey: true });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(inputDOMNode, { keyCode: 40, altKey: true });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(inputDOMNode, { keyCode: 38, altKey: true });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(inputDOMNode, { keyCode: 90, metaKey: true });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(inputDOMNode, { keyCode: 89, metaKey: true });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(inputDOMNode, { keyCode: 67, metaKey: true });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(inputDOMNode, { keyCode: 86, metaKey: true });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(inputDOMNode, { keyCode: 27 });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
fireEvent.keyDown(inputDOMNode, { keyCode: 46 });
expect(designer.currentDocument?.selection.selected[0]).toBe('page');
});
});
}); | the_stack |
/// <reference path="../../../elements.d.ts" />
import { NodeEditBehaviorStylesheetInstance } from "../../node-edit-behavior/node-edit-behavior";
import { Polymer } from '../../../../../tools/definitions/polymer';
import { MetaBlock } from "../monaco-editor/monaco-editor";
import { I18NKeys } from "../../../../_locales/i18n-keys";
import { I18NClass } from "../../../../js/shared";
declare const browserAPI: browserAPI;
namespace StylesheetEditElement {
export const stylesheetEditProperties: {
item: CRM.StylesheetNode;
} = {
item: {
type: Object,
value: {},
notify: true
}
} as any;
export class STE implements I18NClass {
static is: any = 'stylesheet-edit';
static behaviors: any = [window.Polymer.NodeEditBehavior, window.Polymer.CodeEditBehavior];
static properties = stylesheetEditProperties;
static editorPlaceHolderAnimation: Animation;
private static _getExportData(this: NodeEditBehaviorStylesheetInstance): CRM.StylesheetNode {
const settings = {};
this.save(null, settings);
this.$.dropdownMenu.selected = 0;
return settings as CRM.StylesheetNode;
};
static exportStylesheetAsCRM(this: NodeEditBehaviorStylesheetInstance) {
window.app.editCRM.exportSingleNode(this._getExportData(), 'CRM');
};
static exportStylesheetAsUserscript(this: NodeEditBehaviorStylesheetInstance) {
window.app.editCRM.exportSingleNode(this._getExportData(), 'Userscript');
};
static exportStylesheetAsUserstyle(this: NodeEditBehaviorStylesheetInstance) {
window.app.editCRM.exportSingleNode(this._getExportData(), 'Userstyle');
};
static cancelChanges(this: NodeEditBehaviorStylesheetInstance) {
if (this.fullscreen) {
this.exitFullScreen();
}
window.setTimeout(() => {
this.finishEditing();
window.externalEditor.cancelOpenFiles();
this.fullscreenEditorManager &&
this.fullscreenEditorManager.destroy();
this.active = false;
}, this.fullscreen ? 500 : 0);
};
static saveChanges(this: NodeEditBehaviorStylesheetInstance, resultStorage: Partial<CRM.StylesheetNode>) {
resultStorage.value.stylesheet = (this.editorManager &&
this.editorManager.editor &&
this.editorManager.getValue()) || this.item.value.stylesheet;
resultStorage.value.launchMode = this.$.dropdownMenu.selected;
resultStorage.value.toggle = this.$.isTogglableButton.checked;
resultStorage.value.defaultOn = this.$.isDefaultOnButton.checked;
this.finishEditing();
window.externalEditor.cancelOpenFiles();
this.editorManager.destroy();
this.fullscreenEditorManager &&
this.fullscreenEditorManager.destroy();
this.active = false;
};
/**
* Reloads the editor completely (to apply new settings)
*/
static reloadEditor(this: NodeEditBehaviorStylesheetInstance) {
if (this.editorManager) {
if (this.editorMode === 'main') {
this.newSettings.value.stylesheet = this.editorManager.getValue();
} else {
try {
this.newSettings.value.options = JSON.parse(this.editorManager.getValue());
} catch(e) {
this.newSettings.value.options = this.editorManager.getValue();
}
}
}
let value: string;
if (this.editorMode === 'main') {
value = this.newSettings.value.stylesheet;
} else {
if (typeof this.newSettings.value.options === 'string') {
value = this.newSettings.value.options;
} else {
value = JSON.stringify(this.newSettings.value.options);
}
}
if (this.fullscreen) {
this.fullscreenEditorManager.reset();
const editor = this.fullscreenEditorManager.editor;
if (!this.fullscreenEditorManager.isDiff(editor)) {
editor.setValue(value);
}
} else {
this.editorManager.reset();
const editor = this.editorManager.editor;
if (!this.editorManager.isDiff(editor)) {
editor.setValue(value);
}
}
};
/**
* Triggered when the monaco editor has been loaded, fills it with the options and fullscreen element
*/
static editorLoaded(this: NodeEditBehaviorStylesheetInstance) {
const editorManager = this.editorManager;
(editorManager.getTypeHandler() as any)[0].listen('metaChange', ({content: oldTags}: MetaBlock, {content: newTags}: MetaBlock) => {
if (this.editorMode === 'main') {
const oldPreprocessor = oldTags['preprocessor'] && oldTags['preprocessor'][0];
const newPreprocessor = newTags['preprocessor'] && newTags['preprocessor'][0];
if (oldPreprocessor !== newPreprocessor &&
((oldPreprocessor === 'less' || oldPreprocessor === 'stylus') &&
newPreprocessor !== 'less' && newPreprocessor !== 'stylus') ||
((newPreprocessor === 'less' || newPreprocessor === 'stylus') &&
oldPreprocessor !== 'less' && oldPreprocessor !== 'stylus')) {
this.editorManager.setLess(
newPreprocessor === 'less' || newPreprocessor === 'stylus');
}
this.$.editorStylusInfo.classList[
newPreprocessor === 'stylus' ? 'remove' : 'add'
]('hidden');
}
});
editorManager.editor.getDomNode().classList.remove('stylesheet-edit-codeMirror');
editorManager.editor.getDomNode().classList.add('script-edit-codeMirror');
editorManager.editor.getDomNode().classList.add('small');
if (this.fullscreen) {
this.$.editorFullScreen.children[0].innerHTML = '<path d="M10 32h6v6h4V28H10v4zm6-16h-6v4h10V10h-4v6zm12 22h4v-6h6v-4H28v10zm4-22v-6h-4v10h10v-4h-6z"/>';
}
};
private static _getPreprocessor(this: NodeEditBehaviorStylesheetInstance, stylesheet: string) {
const tags = window.app.editCRM.getMetaTags(stylesheet);
return (tags['preprocessor'] && tags['preprocessor'][0]) || 'default';
}
/**
* Loads the monaco editor
*/
private static async _loadEditor(this: NodeEditBehaviorStylesheetInstance, content: string = this.item.value.stylesheet) {
const placeHolder = $(this.$.editor);
this.editorHeight = placeHolder.height();
this.editorWidth = placeHolder.width();
!window.app.settings.editor && (window.app.settings.editor = {
theme: 'dark',
zoom: '100',
keyBindings: {
goToDef: 'Ctrl-F12',
rename: 'Ctrl-F2'
},
cssUnderlineDisabled: false,
disabledMetaDataHighlight: false
});
const preprocessor = this._getPreprocessor(content) as string;
const editorType = (preprocessor === 'stylus' || preprocessor === 'less') ?
this.$.editor.EditorMode.LESS_META : this.$.editor.EditorMode.CSS_META;
this.$.editorStylusInfo.classList[
preprocessor === 'stylus' ? 'remove' : 'add']('hidden');
this.editorManager = await this.$.editor.create(editorType, {
value: content,
language: 'css',
theme: window.app.settings.editor.theme === 'dark' ? 'vs-dark' : 'vs',
wordWrap: 'off',
fontSize: (~~window.app.settings.editor.zoom / 100) * 14,
folding: true
});
this.editorLoaded();
};
static async onLangChanged(this: NodeEditBehaviorStylesheetInstance) {
this.$.exportMenu.$.dropdownSelected.innerText = await this.__async(
I18NKeys.options.editPages.code.exportAs);
}
static async init(this: NodeEditBehaviorStylesheetInstance) {
this._init();
this._CEBIinit();
this.$.dropdownMenu.init();
this.$.exportMenu.init();
await this.onLangChanged();
this.initDropdown();
this.selectorStateChange(0, this.newSettings.value.launchMode);
window.app.$.editorToolsRibbonContainer.classList.remove('editingScript');
window.app.$.editorToolsRibbonContainer.classList.add('editingStylesheet');
window.stylesheetEdit = this;
window.externalEditor.init();
if (window.app.storageLocal.recoverUnsavedData) {
browserAPI.storage.local.set({
editing: {
val: this.item.value.stylesheet,
id: this.item.id,
crmType: window.app.crmTypes
}
});
this.savingInterval = window.setInterval(() => {
if (this.active && this.editorManager) {
//Save
let val;
try {
val = this.editorManager.getValue();
browserAPI.storage.local.set({
editing: {
val: val,
id: this.item.id,
crmType: window.app.crmTypes
}
});
} catch (e) { }
} else {
//Stop this interval
browserAPI.storage.local.set({
editing: false
});
window.clearInterval(this.savingInterval);
}
}, 5000);
}
this.active = true;
setTimeout(() => {
this._loadEditor();
}, 750);
}
private static _showMainTab(this: NodeEditBehaviorStylesheetInstance) {
this.editorManager.switchToModel('default',
this.newSettings.value.stylesheet, this.editorManager.EditorMode.CSS_META);
}
private static _parseVar(this: NodeEditBehaviorStylesheetInstance, value: string) {
const [type, name, ...rest] = value.replace(/\n/g, '').split(' ');
const joined = rest.join(' ').trim();
let label: string;
let lastLabelChar: number;
if (joined.indexOf('"') === 0 || joined.indexOf("'") === 0) {
const strChar = joined[0];
//Find end of string
label = joined.slice(1, 1 + joined.slice(1).indexOf(strChar));
} else {
label = rest[0];
}
lastLabelChar = type.length + 1 + name.length + 1 +
label.length + 2;
const defaultValue = value.replace(/\n/g, '').slice(lastLabelChar).trim();
return {
type,
name,
label,
defaultValue
}
}
private static _metaTagVarTypeToCodeOptionType(type: string) {
switch (type) {
case 'text':
return 'string';
case 'color':
return 'color';
case 'checkbox':
return 'boolean';
case 'select':
return 'choice';
}
return '?';
}
private static _codeOptionTypeToMetaTagVarType(type: CRM.OptionsValue['type']) {
switch (type) {
case 'number':
case 'string':
return 'text';
case 'boolean':
return 'checkbox';
case 'choice':
return 'select';
}
return null;
}
private static _metaTagVarsToCodeOptions(this: NodeEditBehaviorStylesheetInstance,
stylesheet: string, options: CRM.Options|string) {
if (typeof options === 'string') {
return options;
}
const metaTags = window.app.editCRM.getMetaTags(stylesheet);
const vars = [...(metaTags['var'] || []), ...(metaTags['advanced'] || [])];
if (vars.length === 0) {
return null;
} else {
const obj: CRM.Options = {};
let option;
vars.forEach((value: string) => {
const { type, name, label, defaultValue } = this._parseVar(value);
const descriptor = window.app.templates.mergeObjects(options[name] || {}, {
type: this._metaTagVarTypeToCodeOptionType(type),
descr: label
} as Partial<CRM.OptionsValue>);
switch (type) {
case 'text':
case 'color':
case 'checkbox':
option = options[name] as CRM.OptionString|CRM.OptionColorPicker|
CRM.OptionCheckbox;
if (option && option.value === null) {
(descriptor as CRM.OptionString|CRM.OptionColorPicker|CRM.OptionCheckbox)
.value =defaultValue;
}
break;
case 'select':
try {
const parsed = JSON.parse(defaultValue);
if (Array.isArray(defaultValue)) {
obj[name] = window.app.templates.mergeObjects(descriptor, {
values: defaultValue.map((value) => {
if (value.indexOf(':') > -1) {
return value.split(':')[0];
} else {
return value;
}
}),
selected: 0
}) as CRM.OptionChoice;
} else {
obj[name] = window.app.templates.mergeObjects(descriptor, {
values: Object.getOwnPropertyNames(parsed).map((name) => {
return parsed[name];
}),
selected: 0
}) as CRM.OptionChoice;
}
} catch(e) {
obj[name] = window.app.templates.mergeObjects(descriptor, {
values: [],
selected: 0
}) as CRM.OptionChoice;
break;
}
}
obj[name] = descriptor as CRM.OptionsValue;
});
return obj;
}
}
private static _codeOptionsToMetaTagVars(this: NodeEditBehaviorStylesheetInstance,
options: CRM.Options|string) {
if (typeof options === 'string') {
return [];
}
return Object.getOwnPropertyNames(options).map((key) => {
const option = options[key];
let defaultValue: string;
const type = this._codeOptionTypeToMetaTagVarType(option.type);
if (!type) {
return null;
}
switch (option.type) {
case 'number':
defaultValue = option.defaultValue !== undefined ?
(option.defaultValue + '') : (option.value + '');
break;
case 'color':
case 'string':
defaultValue = option.defaultValue !== undefined ?
option.defaultValue : option.value;
break;
case 'boolean':
defaultValue = defaultValue = option.defaultValue !== undefined ?
(~~option.defaultValue + '') : (~~option.value + '');
break;
case 'choice':
defaultValue = JSON.stringify(option.values);
break;
}
return `${type} ${key} '${option.descr}' ${defaultValue}`;
}).filter(val => !!val);
}
static changeTabEvent(this: NodeEditBehaviorStylesheetInstance, e: Polymer.ClickEvent) {
const element = window.app.util.findElementWithClassName(e, 'editorTab');
const mainClicked = element.classList.contains('mainEditorTab');
if (mainClicked && this.editorMode !== 'main') {
this.$.editorStylusInfo.classList[
this._getPreprocessor(this.newSettings.value.stylesheet) === 'stylus' ?
'remove' : 'add']('hidden');
try {
this.newSettings.value.options = JSON.parse(this.editorManager.getValue());
} catch(e) {
this.newSettings.value.options = this.editorManager.getValue();
}
this.hideCodeOptions();
const stylesheet = this.newSettings.value.stylesheet;
if (window.app.editCRM.getMetaLines(stylesheet).length > 0) {
const metaIndexes = window.app.editCRM.getMetaIndexes(stylesheet);
const lastIndex = metaIndexes.slice(-1)[0];
//Remove all @var tags
const metaLines = [...window.app.editCRM.getMetaLinesForIndex(
stylesheet, lastIndex).filter((line) => {
return line.indexOf('@var') === -1 &&
line.indexOf('@advanced') === -1;
}), ...this._codeOptionsToMetaTagVars(
this.newSettings.value.options)];
const splitLines = stylesheet.split('\n');
splitLines.splice(lastIndex.start, lastIndex.end - lastIndex.start,
...metaLines);
this.newSettings.value.stylesheet = splitLines.join('\n');
}
this._showMainTab();
this.editorMode = 'main';
} else if (!mainClicked && this.editorMode === 'main') {
this.$.editorStylusInfo.classList.add('hidden');
this.newSettings.value.stylesheet = this.editorManager.getValue();
this.showCodeOptions();
const stylesheet = this.newSettings.value.stylesheet;
if (window.app.editCRM.getMetaLines(stylesheet).length > 0) {
this.newSettings.value.options = this._metaTagVarsToCodeOptions(
this.newSettings.value.stylesheet,
this.newSettings.value.options);
}
this.editorMode = 'options';
}
Array.prototype.slice.apply(window.stylesheetEdit.shadowRoot.querySelectorAll('.editorTab')).forEach(
function(tab: HTMLElement) {
tab.classList.remove('active');
});
element.classList.add('active');
}
}
if (window.objectify) {
window.register(STE);
} else {
window.addEventListener('RegisterReady', () => {
window.register(STE);
});
}
}
export type StylesheetEdit = Polymer.El<'stylesheet-edit', typeof StylesheetEditElement.STE &
typeof StylesheetEditElement.stylesheetEditProperties>;; | the_stack |
import { Assert, AITestClass } from "@microsoft/ai-test-framework";
import {
PageViewPerformance,
PageView,
TelemetryItemCreator,
IPageViewTelemetry,
IEventTelemetry,
Event as EventTelemetry,
Trace,
ITraceTelemetry,
Metric,
IMetricTelemetry,
RemoteDependencyData,
IDependencyTelemetry,
} from '@microsoft/applicationinsights-common';
import { ApplicationInsights } from '../../../src/JavaScriptSDK/ApplicationInsights'
import {
IAppInsightsCore, AppInsightsCore,
ITelemetryItem,
IConfiguration, IPlugin
} from '@microsoft/applicationinsights-core-js';
export class TelemetryItemCreatorTests extends AITestClass {
private _core: IAppInsightsCore;
private _appInsights: ApplicationInsights;
public testInitialize() {
const plugin: IPlugin = new ChannelPlugin();
this._core = new AppInsightsCore();
this._core.initialize(
{instrumentationKey: "key"},
[plugin]
);
this._appInsights = new ApplicationInsights();
this._appInsights.initialize({ "instrumentationKey": "ikey" }, this._core, []);
}
public registerTests() {
this.testCase({
name: "TelemetryItemCreatorTests: create a valid ITelemetryItem for a page view performance item",
test: () => {
// setup
const name = "testName";
const uri = "testUri";
const pageViewPerformance = new PageViewPerformance(this._core.logger, name, uri, null);
const properties = {
"propKey1": "PropVal1",
"propKey2": "PropVal2"
};
// act
const telemetryItem = TelemetryItemCreator.create<PageViewPerformance>(
pageViewPerformance,
PageViewPerformance.dataType,
PageViewPerformance.envelopeType,
this._core.logger,
properties);
// assert
Assert.ok(telemetryItem);
Assert.equal("Microsoft.ApplicationInsights.{0}.PageviewPerformance", telemetryItem.name, "telemtryItem.name");
Assert.equal("Microsoft.ApplicationInsights.{0}.PageviewPerformance", telemetryItem.name, "telemtryItem.name");
Assert.equal("", telemetryItem.iKey, "telemetryItem.iKey");
Assert.deepEqual({"propKey1":"PropVal1","propKey2":"PropVal2"},telemetryItem.data, "telemetryItem.data");
}
});
this.testCase({
name: "TelemetryItemCreatorTests: create a valid ITelemetryItem for a page view item",
test: () => {
// setup
const name = "testName";
const uri = "testUri";
const pageView: IPageViewTelemetry = {
name,
uri
};
const properties = {
"propKey1": "PropVal1",
"propKey2": "PropVal2"
};
// act
const telemetryItem = TelemetryItemCreator.create<IPageViewTelemetry>(
pageView,
PageView.dataType,
PageView.envelopeType,
this._core.logger,
properties);
// assert
Assert.ok(telemetryItem);
Assert.equal("Microsoft.ApplicationInsights.{0}.Pageview", telemetryItem.name, "telemtryItem.name");
Assert.equal("PageviewData", telemetryItem.baseType, "telemetryItem.baseType");
Assert.equal("",telemetryItem.iKey,"telemetryItem.iKey");
Assert.deepEqual({"propKey1":"PropVal1","propKey2":"PropVal2"},telemetryItem.data, "telemetryItem.data");
}
});
this.testCase({
name: "TelemetryItemCreatorTests: create a valid TelemetryItem for trackEvent with iKey",
test: () => {
// setup
const event: IEventTelemetry = {
name: "trackEventNewtTest",
iKey: "newTestIkey",
properties: { "prop1": "value1" },
measurements: { "measurement1": 200 }
}
const customProperties = {"propKey1":"PropVal1"};
// act
const telemetryItem = TelemetryItemCreator.create<ITelemetryItem>(
event,
EventTelemetry.dataType,
EventTelemetry.envelopeType,
this._appInsights.diagLog(),
customProperties);
// assert
Assert.equal("Microsoft.ApplicationInsights.{0}.Event", telemetryItem.name, "telemtryItem.name");
Assert.equal("EventData", telemetryItem.baseType, "telemetryItem.baseType");
Assert.equal("newTestIkey", telemetryItem.iKey, "telemtryItem.iKey");
Assert.deepEqual({"propKey1":"PropVal1"},telemetryItem.data, "telemetryItem.data");
Assert.deepEqual( "trackEventNewtTest",telemetryItem.baseData.name, "telemetryItem.baseData.name");
Assert.deepEqual({ "prop1": "value1" },telemetryItem.baseData.properties, "telemetryItem.baseData.properties");
Assert.deepEqual({ "measurement1": 200 },telemetryItem.baseData.measurements, "telemetryItem.baseData.measurements");
}
});
this.testCase({
name: "TelemetryItemCreatorTests: create a valid ITelemetryItem for a page view item with iKey",
test: () => {
// setup
const name = "testName";
const uri = "testUri";
const pageView: IPageViewTelemetry = {
name: name,
uri: uri,
iKey: "newIkey"
};
const properties = {
"propKey1": "PropVal1"
};
// act
const telemetryItem = TelemetryItemCreator.create<IPageViewTelemetry>(
pageView,
PageView.dataType,
PageView.envelopeType,
this._core.logger,
properties);
// assert
Assert.ok(telemetryItem);
Assert.equal("Microsoft.ApplicationInsights.{0}.Pageview", telemetryItem.name, "telemtryItem.name");
Assert.equal("newIkey", telemetryItem.iKey, "telemtryItem.iKey");
Assert.equal("PageviewData", telemetryItem.baseType, "telemetryItem.baseType");
Assert.equal("testUri", telemetryItem.baseData.uri, "telemetryItem.baseData.uri");
Assert.equal("testName", telemetryItem.baseData.name, "telemetryItem.baseData.name");
Assert.deepEqual({"propKey1":"PropVal1"},telemetryItem.data, "telemetryItem.data");
}
});
this.testCase({
name: "TelemetryItemCreatorTests: create a valid ITelemetryItem for a trace item with iKey",
test: () => {
// setup
const trace: ITraceTelemetry = {
message:"traceMessage",
iKey: "newIkey"
};
const customProperties = {
"propKey1": "PropVal1"
};
// act
const telemetryItem = TelemetryItemCreator.create<ITraceTelemetry>(
trace,
Trace.dataType,
Trace.envelopeType,
this._core.logger,
customProperties);
// assert
Assert.ok(telemetryItem);
Assert.equal("Microsoft.ApplicationInsights.{0}.Message", telemetryItem.name, "telemtryItem.name");
Assert.equal("newIkey", telemetryItem.iKey, "telemtryItem.iKey");
Assert.equal("MessageData", telemetryItem.baseType, "telemetryItem.baseType");
Assert.equal("traceMessage", telemetryItem.baseData.message, "telemetryItem.baseData.message");
Assert.deepEqual({"propKey1":"PropVal1"},telemetryItem.data, "telemetryItem.data");
}
});
this.testCase({
name: "TelemetryItemCreatorTests: create a valid ITelemetryItem for a metric item with iKey",
test: () => {
// setup
const metric: IMetricTelemetry = {
name:"metricName",
average: 5,
iKey: "newIkey"
};
// act
const telemetryItem = TelemetryItemCreator.create<IMetricTelemetry>(
metric,
Metric.dataType,
Metric.envelopeType,
this._core.logger,
);
// assert
Assert.ok(telemetryItem);
Assert.equal("Microsoft.ApplicationInsights.{0}.Metric", telemetryItem.name, "telemtryItem.name");
Assert.equal("newIkey", telemetryItem.iKey, "telemtryItem.iKey");
Assert.equal("MetricData", telemetryItem.baseType, "telemetryItem.baseType");
Assert.equal("metricName",telemetryItem.baseData.name, "telemetryItem.baseData.name");
Assert.equal(5,telemetryItem.baseData.average, "telemetryItem.baseData.average");
}
});
this.testCase({
name: "TelemetryItemCreatorTests: create a valid ITelemetryItem for a dependency item with iKey",
test: () => {
// setup
const dependency: IDependencyTelemetry = {
name:"dependencyName",
id:"id",
responseCode: 200,
iKey: "newIkey"
};
// act
const telemetryItem = TelemetryItemCreator.create<IDependencyTelemetry>(
dependency,
RemoteDependencyData.dataType,
RemoteDependencyData.envelopeType,
this._core.logger,
);
// assert
Assert.ok(telemetryItem);
Assert.equal("Microsoft.ApplicationInsights.{0}.RemoteDependency", telemetryItem.name, "telemtryItem.name");
Assert.equal("newIkey", telemetryItem.iKey, "telemtryItem.iKey");
Assert.equal("RemoteDependencyData", telemetryItem.baseType, "telemetryItem.baseType");
Assert.equal("dependencyName",telemetryItem.baseData.name, "telemetryItem.baseData.name");
Assert.equal(200,telemetryItem.baseData.responseCode, "telemetryItem.baseData.responseCode");
Assert.equal("id",telemetryItem.baseData.id, "telemetryItem.baseData.id");
}
});
}
}
class ChannelPlugin implements IPlugin {
public isFlushInvoked = false;
public isTearDownInvoked = false;
public isResumeInvoked = false;
public isPauseInvoked = false;
public processTelemetry;
public identifier = "Sender";
public priority: number = 1001;
constructor() {
this.processTelemetry = this._processTelemetry.bind(this);
}
public pause(): void {
this.isPauseInvoked = true;
}
public resume(): void {
this.isResumeInvoked = true;
}
public teardown(): void {
this.isTearDownInvoked = true;
}
flush(async?: boolean, callBack?: () => void): void {
this.isFlushInvoked = true;
if (callBack) {
callBack();
}
}
setNextPlugin(next: any) {
// no next setup
}
public initialize = (config: IConfiguration) => {
}
private _processTelemetry(env: ITelemetryItem) {
}
} | the_stack |
declare module 'babylonjs-materials' {
export = BABYLON;
}
declare module BABYLON {
class ShadowOnlyMaterial extends PushMaterial {
private _renderId;
private _activeLight;
constructor(name: string, scene: Scene);
needAlphaBlending(): boolean;
needAlphaTesting(): boolean;
getAlphaTestTexture(): Nullable<BaseTexture>;
activeLight: IShadowLight;
isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean;
bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void;
clone(name: string): ShadowOnlyMaterial;
serialize(): any;
getClassName(): string;
static Parse(source: any, scene: Scene, rootUrl: string): ShadowOnlyMaterial;
}
}
declare module BABYLON {
class GradientMaterial extends PushMaterial {
private _maxSimultaneousLights;
maxSimultaneousLights: number;
topColor: Color3;
topColorAlpha: number;
bottomColor: Color3;
bottomColorAlpha: number;
offset: number;
smoothness: number;
disableLighting: boolean;
private _scaledDiffuse;
private _renderId;
constructor(name: string, scene: Scene);
needAlphaBlending(): boolean;
needAlphaTesting(): boolean;
getAlphaTestTexture(): Nullable<BaseTexture>;
isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean;
bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void;
getAnimatables(): IAnimatable[];
dispose(forceDisposeEffect?: boolean): void;
clone(name: string): GradientMaterial;
serialize(): any;
getClassName(): string;
static Parse(source: any, scene: Scene, rootUrl: string): GradientMaterial;
}
}
declare module BABYLON {
class NormalMaterial extends PushMaterial {
private _diffuseTexture;
diffuseTexture: BaseTexture;
diffuseColor: Color3;
private _disableLighting;
disableLighting: boolean;
private _maxSimultaneousLights;
maxSimultaneousLights: number;
private _renderId;
constructor(name: string, scene: Scene);
needAlphaBlending(): boolean;
needAlphaTesting(): boolean;
getAlphaTestTexture(): Nullable<BaseTexture>;
isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean;
bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void;
getAnimatables(): IAnimatable[];
getActiveTextures(): BaseTexture[];
hasTexture(texture: BaseTexture): boolean;
dispose(forceDisposeEffect?: boolean): void;
clone(name: string): NormalMaterial;
serialize(): any;
getClassName(): string;
static Parse(source: any, scene: Scene, rootUrl: string): NormalMaterial;
}
}
declare module BABYLON {
class LavaMaterial extends PushMaterial {
private _diffuseTexture;
diffuseTexture: BaseTexture;
noiseTexture: BaseTexture;
fogColor: Color3;
speed: number;
movingSpeed: number;
lowFrequencySpeed: number;
fogDensity: number;
private _lastTime;
diffuseColor: Color3;
private _disableLighting;
disableLighting: boolean;
private _maxSimultaneousLights;
maxSimultaneousLights: number;
private _scaledDiffuse;
private _renderId;
constructor(name: string, scene: Scene);
needAlphaBlending(): boolean;
needAlphaTesting(): boolean;
getAlphaTestTexture(): Nullable<BaseTexture>;
isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean;
bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void;
getAnimatables(): IAnimatable[];
getActiveTextures(): BaseTexture[];
hasTexture(texture: BaseTexture): boolean;
dispose(forceDisposeEffect?: boolean): void;
clone(name: string): LavaMaterial;
serialize(): any;
getClassName(): string;
static Parse(source: any, scene: Scene, rootUrl: string): LavaMaterial;
}
}
declare module BABYLON {
class SimpleMaterial extends PushMaterial {
private _diffuseTexture;
diffuseTexture: BaseTexture;
diffuseColor: Color3;
private _disableLighting;
disableLighting: boolean;
private _maxSimultaneousLights;
maxSimultaneousLights: number;
private _renderId;
constructor(name: string, scene: Scene);
needAlphaBlending(): boolean;
needAlphaTesting(): boolean;
getAlphaTestTexture(): Nullable<BaseTexture>;
isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean;
bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void;
getAnimatables(): IAnimatable[];
getActiveTextures(): BaseTexture[];
hasTexture(texture: BaseTexture): boolean;
dispose(forceDisposeEffect?: boolean): void;
clone(name: string): SimpleMaterial;
serialize(): any;
getClassName(): string;
static Parse(source: any, scene: Scene, rootUrl: string): SimpleMaterial;
}
}
declare module BABYLON {
class WaterMaterial extends PushMaterial {
renderTargetSize: Vector2;
private _bumpTexture;
bumpTexture: BaseTexture;
diffuseColor: Color3;
specularColor: Color3;
specularPower: number;
private _disableLighting;
disableLighting: boolean;
private _maxSimultaneousLights;
maxSimultaneousLights: number;
/**
* @param {number}: Represents the wind force
*/
windForce: number;
/**
* @param {Vector2}: The direction of the wind in the plane (X, Z)
*/
windDirection: Vector2;
/**
* @param {number}: Wave height, represents the height of the waves
*/
waveHeight: number;
/**
* @param {number}: Bump height, represents the bump height related to the bump map
*/
bumpHeight: number;
/**
* @param {boolean}: Add a smaller moving bump to less steady waves.
*/
private _bumpSuperimpose;
bumpSuperimpose: boolean;
/**
* @param {boolean}: Color refraction and reflection differently with .waterColor2 and .colorBlendFactor2. Non-linear (physically correct) fresnel.
*/
private _fresnelSeparate;
fresnelSeparate: boolean;
/**
* @param {boolean}: bump Waves modify the reflection.
*/
private _bumpAffectsReflection;
bumpAffectsReflection: boolean;
/**
* @param {number}: The water color blended with the refraction (near)
*/
waterColor: Color3;
/**
* @param {number}: The blend factor related to the water color
*/
colorBlendFactor: number;
/**
* @param {number}: The water color blended with the reflection (far)
*/
waterColor2: Color3;
/**
* @param {number}: The blend factor related to the water color (reflection, far)
*/
colorBlendFactor2: number;
/**
* @param {number}: Represents the maximum length of a wave
*/
waveLength: number;
/**
* @param {number}: Defines the waves speed
*/
waveSpeed: number;
protected _renderTargets: SmartArray<RenderTargetTexture>;
private _mesh;
private _refractionRTT;
private _reflectionRTT;
private _reflectionTransform;
private _lastTime;
private _lastDeltaTime;
private _renderId;
private _useLogarithmicDepth;
private _waitingRenderList;
/**
* Constructor
*/
constructor(name: string, scene: Scene, renderTargetSize?: Vector2);
useLogarithmicDepth: boolean;
readonly refractionTexture: Nullable<RenderTargetTexture>;
readonly reflectionTexture: Nullable<RenderTargetTexture>;
addToRenderList(node: any): void;
enableRenderTargets(enable: boolean): void;
getRenderList(): Nullable<AbstractMesh[]>;
readonly renderTargetsEnabled: boolean;
needAlphaBlending(): boolean;
needAlphaTesting(): boolean;
getAlphaTestTexture(): Nullable<BaseTexture>;
isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean;
bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void;
private _createRenderTargets(scene, renderTargetSize);
getAnimatables(): IAnimatable[];
getActiveTextures(): BaseTexture[];
hasTexture(texture: BaseTexture): boolean;
dispose(forceDisposeEffect?: boolean): void;
clone(name: string): WaterMaterial;
serialize(): any;
getClassName(): string;
static Parse(source: any, scene: Scene, rootUrl: string): WaterMaterial;
static CreateDefaultMesh(name: string, scene: Scene): Mesh;
}
}
declare module BABYLON {
class FireMaterial extends PushMaterial {
private _diffuseTexture;
diffuseTexture: Nullable<BaseTexture>;
private _distortionTexture;
distortionTexture: Nullable<BaseTexture>;
private _opacityTexture;
opacityTexture: Nullable<BaseTexture>;
diffuseColor: Color3;
speed: number;
private _scaledDiffuse;
private _renderId;
private _lastTime;
constructor(name: string, scene: Scene);
needAlphaBlending(): boolean;
needAlphaTesting(): boolean;
getAlphaTestTexture(): Nullable<BaseTexture>;
isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean;
bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void;
getAnimatables(): IAnimatable[];
getActiveTextures(): BaseTexture[];
hasTexture(texture: BaseTexture): boolean;
getClassName(): string;
dispose(forceDisposeEffect?: boolean): void;
clone(name: string): FireMaterial;
serialize(): any;
static Parse(source: any, scene: Scene, rootUrl: string): FireMaterial;
}
}
declare module BABYLON {
class FurMaterial extends PushMaterial {
private _diffuseTexture;
diffuseTexture: BaseTexture;
private _heightTexture;
heightTexture: BaseTexture;
diffuseColor: Color3;
furLength: number;
furAngle: number;
furColor: Color3;
furOffset: number;
furSpacing: number;
furGravity: Vector3;
furSpeed: number;
furDensity: number;
furTexture: DynamicTexture;
private _disableLighting;
disableLighting: boolean;
private _maxSimultaneousLights;
maxSimultaneousLights: number;
highLevelFur: boolean;
_meshes: AbstractMesh[];
private _renderId;
private _furTime;
constructor(name: string, scene: Scene);
furTime: number;
needAlphaBlending(): boolean;
needAlphaTesting(): boolean;
getAlphaTestTexture(): Nullable<BaseTexture>;
updateFur(): void;
isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean;
bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void;
getAnimatables(): IAnimatable[];
getActiveTextures(): BaseTexture[];
hasTexture(texture: BaseTexture): boolean;
dispose(forceDisposeEffect?: boolean): void;
clone(name: string): FurMaterial;
serialize(): any;
getClassName(): string;
static Parse(source: any, scene: Scene, rootUrl: string): FurMaterial;
static GenerateTexture(name: string, scene: Scene): DynamicTexture;
static FurifyMesh(sourceMesh: Mesh, quality: number): Mesh[];
}
}
declare module BABYLON {
class TerrainMaterial extends PushMaterial {
private _mixTexture;
mixTexture: BaseTexture;
private _diffuseTexture1;
diffuseTexture1: Texture;
private _diffuseTexture2;
diffuseTexture2: Texture;
private _diffuseTexture3;
diffuseTexture3: Texture;
private _bumpTexture1;
bumpTexture1: Texture;
private _bumpTexture2;
bumpTexture2: Texture;
private _bumpTexture3;
bumpTexture3: Texture;
diffuseColor: Color3;
specularColor: Color3;
specularPower: number;
private _disableLighting;
disableLighting: boolean;
private _maxSimultaneousLights;
maxSimultaneousLights: number;
private _renderId;
constructor(name: string, scene: Scene);
needAlphaBlending(): boolean;
needAlphaTesting(): boolean;
getAlphaTestTexture(): Nullable<BaseTexture>;
isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean;
bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void;
getAnimatables(): IAnimatable[];
getActiveTextures(): BaseTexture[];
hasTexture(texture: BaseTexture): boolean;
dispose(forceDisposeEffect?: boolean): void;
clone(name: string): TerrainMaterial;
serialize(): any;
getClassName(): string;
static Parse(source: any, scene: Scene, rootUrl: string): TerrainMaterial;
}
}
declare module BABYLON {
class TriPlanarMaterial extends PushMaterial {
mixTexture: BaseTexture;
private _diffuseTextureX;
diffuseTextureX: BaseTexture;
private _diffuseTextureY;
diffuseTextureY: BaseTexture;
private _diffuseTextureZ;
diffuseTextureZ: BaseTexture;
private _normalTextureX;
normalTextureX: BaseTexture;
private _normalTextureY;
normalTextureY: BaseTexture;
private _normalTextureZ;
normalTextureZ: BaseTexture;
tileSize: number;
diffuseColor: Color3;
specularColor: Color3;
specularPower: number;
private _disableLighting;
disableLighting: boolean;
private _maxSimultaneousLights;
maxSimultaneousLights: number;
private _renderId;
constructor(name: string, scene: Scene);
needAlphaBlending(): boolean;
needAlphaTesting(): boolean;
getAlphaTestTexture(): Nullable<BaseTexture>;
isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean;
bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void;
getAnimatables(): IAnimatable[];
getActiveTextures(): BaseTexture[];
hasTexture(texture: BaseTexture): boolean;
dispose(forceDisposeEffect?: boolean): void;
clone(name: string): TriPlanarMaterial;
serialize(): any;
getClassName(): string;
static Parse(source: any, scene: Scene, rootUrl: string): TriPlanarMaterial;
}
}
declare module BABYLON {
class SkyMaterial extends PushMaterial {
luminance: number;
turbidity: number;
rayleigh: number;
mieCoefficient: number;
mieDirectionalG: number;
distance: number;
inclination: number;
azimuth: number;
sunPosition: Vector3;
useSunPosition: boolean;
private _cameraPosition;
private _renderId;
constructor(name: string, scene: Scene);
needAlphaBlending(): boolean;
needAlphaTesting(): boolean;
getAlphaTestTexture(): Nullable<BaseTexture>;
isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean;
bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void;
getAnimatables(): IAnimatable[];
dispose(forceDisposeEffect?: boolean): void;
clone(name: string): SkyMaterial;
serialize(): any;
getClassName(): string;
static Parse(source: any, scene: Scene, rootUrl: string): SkyMaterial;
}
}
declare module BABYLON {
/**
* The grid materials allows you to wrap any shape with a grid.
* Colors are customizable.
*/
class GridMaterial extends BABYLON.PushMaterial {
/**
* Main color of the grid (e.g. between lines)
*/
mainColor: Color3;
/**
* Color of the grid lines.
*/
lineColor: Color3;
/**
* The scale of the grid compared to unit.
*/
gridRatio: number;
/**
* Allows setting an offset for the grid lines.
*/
gridOffset: Vector3;
/**
* The frequency of thicker lines.
*/
majorUnitFrequency: number;
/**
* The visibility of minor units in the grid.
*/
minorUnitVisibility: number;
/**
* The grid opacity outside of the lines.
*/
opacity: number;
/**
* Determine RBG output is premultiplied by alpha value.
*/
preMultiplyAlpha: boolean;
private _gridControl;
private _renderId;
/**
* constructor
* @param name The name given to the material in order to identify it afterwards.
* @param scene The scene the material is used in.
*/
constructor(name: string, scene: Scene);
/**
* Returns wehter or not the grid requires alpha blending.
*/
needAlphaBlending(): boolean;
needAlphaBlendingForMesh(mesh: AbstractMesh): boolean;
isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean;
bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void;
dispose(forceDisposeEffect?: boolean): void;
clone(name: string): GridMaterial;
serialize(): any;
getClassName(): string;
static Parse(source: any, scene: Scene, rootUrl: string): GridMaterial;
}
}
declare module BABYLON {
class StandardMaterialDefines_OldVer extends MaterialDefines implements IImageProcessingConfigurationDefines {
DIFFUSE: boolean;
AMBIENT: boolean;
OPACITY: boolean;
OPACITYRGB: boolean;
REFLECTION: boolean;
EMISSIVE: boolean;
SPECULAR: boolean;
BUMP: boolean;
PARALLAX: boolean;
PARALLAXOCCLUSION: boolean;
SPECULAROVERALPHA: boolean;
CLIPPLANE: boolean;
ALPHATEST: boolean;
ALPHAFROMDIFFUSE: boolean;
POINTSIZE: boolean;
FOG: boolean;
SPECULARTERM: boolean;
DIFFUSEFRESNEL: boolean;
OPACITYFRESNEL: boolean;
REFLECTIONFRESNEL: boolean;
REFRACTIONFRESNEL: boolean;
EMISSIVEFRESNEL: boolean;
FRESNEL: boolean;
NORMAL: boolean;
UV1: boolean;
UV2: boolean;
VERTEXCOLOR: boolean;
VERTEXALPHA: boolean;
NUM_BONE_INFLUENCERS: number;
BonesPerMesh: number;
INSTANCES: boolean;
GLOSSINESS: boolean;
ROUGHNESS: boolean;
EMISSIVEASILLUMINATION: boolean;
LINKEMISSIVEWITHDIFFUSE: boolean;
REFLECTIONFRESNELFROMSPECULAR: boolean;
LIGHTMAP: boolean;
USELIGHTMAPASSHADOWMAP: boolean;
REFLECTIONMAP_3D: boolean;
REFLECTIONMAP_SPHERICAL: boolean;
REFLECTIONMAP_PLANAR: boolean;
REFLECTIONMAP_CUBIC: boolean;
REFLECTIONMAP_PROJECTION: boolean;
REFLECTIONMAP_SKYBOX: boolean;
REFLECTIONMAP_EXPLICIT: boolean;
REFLECTIONMAP_EQUIRECTANGULAR: boolean;
REFLECTIONMAP_EQUIRECTANGULAR_FIXED: boolean;
REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED: boolean;
INVERTCUBICMAP: boolean;
LOGARITHMICDEPTH: boolean;
REFRACTION: boolean;
REFRACTIONMAP_3D: boolean;
REFLECTIONOVERALPHA: boolean;
TWOSIDEDLIGHTING: boolean;
SHADOWFLOAT: boolean;
MORPHTARGETS: boolean;
MORPHTARGETS_NORMAL: boolean;
MORPHTARGETS_TANGENT: boolean;
NUM_MORPH_INFLUENCERS: number;
IMAGEPROCESSING: boolean;
VIGNETTE: boolean;
VIGNETTEBLENDMODEMULTIPLY: boolean;
VIGNETTEBLENDMODEOPAQUE: boolean;
TONEMAPPING: boolean;
CONTRAST: boolean;
COLORCURVES: boolean;
COLORGRADING: boolean;
COLORGRADING3D: boolean;
SAMPLER3DGREENDEPTH: boolean;
SAMPLER3DBGRMAP: boolean;
IMAGEPROCESSINGPOSTPROCESS: boolean;
EXPOSURE: boolean;
constructor();
setReflectionMode(modeToEnable: string): void;
}
class StandardMaterial_OldVer extends PushMaterial {
private _diffuseTexture;
diffuseTexture: BaseTexture;
private _ambientTexture;
ambientTexture: BaseTexture;
private _opacityTexture;
opacityTexture: BaseTexture;
private _reflectionTexture;
reflectionTexture: BaseTexture;
private _emissiveTexture;
emissiveTexture: BaseTexture;
private _specularTexture;
specularTexture: BaseTexture;
private _bumpTexture;
bumpTexture: BaseTexture;
private _lightmapTexture;
lightmapTexture: BaseTexture;
private _refractionTexture;
refractionTexture: BaseTexture;
ambientColor: Color3;
diffuseColor: Color3;
specularColor: Color3;
emissiveColor: Color3;
specularPower: number;
private _useAlphaFromDiffuseTexture;
useAlphaFromDiffuseTexture: boolean;
private _useEmissiveAsIllumination;
useEmissiveAsIllumination: boolean;
private _linkEmissiveWithDiffuse;
linkEmissiveWithDiffuse: boolean;
private _useSpecularOverAlpha;
useSpecularOverAlpha: boolean;
private _useReflectionOverAlpha;
useReflectionOverAlpha: boolean;
private _disableLighting;
disableLighting: boolean;
private _useParallax;
useParallax: boolean;
private _useParallaxOcclusion;
useParallaxOcclusion: boolean;
parallaxScaleBias: number;
private _roughness;
roughness: number;
indexOfRefraction: number;
invertRefractionY: boolean;
private _useLightmapAsShadowmap;
useLightmapAsShadowmap: boolean;
private _diffuseFresnelParameters;
diffuseFresnelParameters: FresnelParameters;
private _opacityFresnelParameters;
opacityFresnelParameters: FresnelParameters;
private _reflectionFresnelParameters;
reflectionFresnelParameters: FresnelParameters;
private _refractionFresnelParameters;
refractionFresnelParameters: FresnelParameters;
private _emissiveFresnelParameters;
emissiveFresnelParameters: FresnelParameters;
private _useReflectionFresnelFromSpecular;
useReflectionFresnelFromSpecular: boolean;
private _useGlossinessFromSpecularMapAlpha;
useGlossinessFromSpecularMapAlpha: boolean;
private _maxSimultaneousLights;
maxSimultaneousLights: number;
/**
* If sets to true, x component of normal map value will invert (x = 1.0 - x).
*/
private _invertNormalMapX;
invertNormalMapX: boolean;
/**
* If sets to true, y component of normal map value will invert (y = 1.0 - y).
*/
private _invertNormalMapY;
invertNormalMapY: boolean;
/**
* If sets to true and backfaceCulling is false, normals will be flipped on the backside.
*/
private _twoSidedLighting;
twoSidedLighting: boolean;
/**
* Default configuration related to image processing available in the standard Material.
*/
protected _imageProcessingConfiguration: ImageProcessingConfiguration;
/**
* Gets the image processing configuration used either in this material.
*/
/**
* Sets the Default image processing configuration used either in the this material.
*
* If sets to null, the scene one is in use.
*/
imageProcessingConfiguration: ImageProcessingConfiguration;
/**
* Keep track of the image processing observer to allow dispose and replace.
*/
private _imageProcessingObserver;
/**
* Attaches a new image processing configuration to the Standard Material.
* @param configuration
*/
protected _attachImageProcessingConfiguration(configuration: Nullable<ImageProcessingConfiguration>): void;
/**
* Gets wether the color curves effect is enabled.
*/
/**
* Sets wether the color curves effect is enabled.
*/
cameraColorCurvesEnabled: boolean;
/**
* Gets wether the color grading effect is enabled.
*/
/**
* Gets wether the color grading effect is enabled.
*/
cameraColorGradingEnabled: boolean;
/**
* Gets wether tonemapping is enabled or not.
*/
/**
* Sets wether tonemapping is enabled or not
*/
cameraToneMappingEnabled: boolean;
/**
* The camera exposure used on this material.
* This property is here and not in the camera to allow controlling exposure without full screen post process.
* This corresponds to a photographic exposure.
*/
/**
* The camera exposure used on this material.
* This property is here and not in the camera to allow controlling exposure without full screen post process.
* This corresponds to a photographic exposure.
*/
cameraExposure: number;
/**
* Gets The camera contrast used on this material.
*/
/**
* Sets The camera contrast used on this material.
*/
cameraContrast: number;
/**
* Gets the Color Grading 2D Lookup Texture.
*/
/**
* Sets the Color Grading 2D Lookup Texture.
*/
cameraColorGradingTexture: Nullable<BaseTexture>;
customShaderNameResolve: (shaderName: string, uniforms: string[], uniformBuffers: string[], samplers: string[], defines: StandardMaterialDefines_OldVer) => string;
protected _renderTargets: SmartArray<RenderTargetTexture>;
protected _worldViewProjectionMatrix: Matrix;
protected _globalAmbientColor: Color3;
protected _useLogarithmicDepth: boolean;
constructor(name: string, scene: Scene);
getClassName(): string;
useLogarithmicDepth: boolean;
needAlphaBlending(): boolean;
needAlphaTesting(): boolean;
protected _shouldUseAlphaFromDiffuseTexture(): boolean;
getAlphaTestTexture(): BaseTexture;
/**
* Child classes can use it to update shaders
*/
isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean;
buildUniformLayout(): void;
unbind(): void;
bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void;
getAnimatables(): IAnimatable[];
getActiveTextures(): BaseTexture[];
dispose(forceDisposeEffect?: boolean, forceDisposeTextures?: boolean): void;
clone(name: string): StandardMaterial_OldVer;
serialize(): any;
static Parse(source: any, scene: Scene, rootUrl: string): StandardMaterial_OldVer;
static _DiffuseTextureEnabled: boolean;
static DiffuseTextureEnabled: boolean;
static _AmbientTextureEnabled: boolean;
static AmbientTextureEnabled: boolean;
static _OpacityTextureEnabled: boolean;
static OpacityTextureEnabled: boolean;
static _ReflectionTextureEnabled: boolean;
static ReflectionTextureEnabled: boolean;
static _EmissiveTextureEnabled: boolean;
static EmissiveTextureEnabled: boolean;
static _SpecularTextureEnabled: boolean;
static SpecularTextureEnabled: boolean;
static _BumpTextureEnabled: boolean;
static BumpTextureEnabled: boolean;
static _LightmapTextureEnabled: boolean;
static LightmapTextureEnabled: boolean;
static _RefractionTextureEnabled: boolean;
static RefractionTextureEnabled: boolean;
static _ColorGradingTextureEnabled: boolean;
static ColorGradingTextureEnabled: boolean;
static _FresnelEnabled: boolean;
static FresnelEnabled: boolean;
}
class CustomShaderStructure {
FragmentStore: string;
VertexStore: string;
constructor();
}
class ShaderSpecialParts {
constructor();
Fragment_Begin: string;
Fragment_Definitions: string;
Fragment_MainBegin: string;
Fragment_Custom_Diffuse: string;
Fragment_Custom_Alpha: string;
Fragment_Before_FragColor: string;
Vertex_Begin: string;
Vertex_Definitions: string;
Vertex_MainBegin: string;
Vertex_Before_PositionUpdated: string;
Vertex_Before_NormalUpdated: string;
}
class ShaderForVer3_0 extends CustomShaderStructure {
constructor();
}
class StandardShaderVersions {
static Ver3_0: string;
}
class CustomMaterial extends StandardMaterial_OldVer {
static ShaderIndexer: number;
CustomParts: ShaderSpecialParts;
ShaderVersion: CustomShaderStructure;
_isCreatedShader: boolean;
_createdShaderName: string;
_customUniform: string[];
_newUniforms: string[];
_newUniformInstances: any[];
_newSamplerInstances: Texture[];
AttachAfterBind(mesh: Mesh, effect: Effect): void;
ReviewUniform(name: string, arr: string[]): string[];
Builder(shaderName: string, uniforms: string[], uniformBuffers: string[], samplers: string[], defines: StandardMaterialDefines_OldVer): string;
SelectVersion(ver: string): void;
constructor(name: string, scene: Scene);
AddUniform(name: string, kind: string, param: any): CustomMaterial;
Fragment_Begin(shaderPart: string): CustomMaterial;
Fragment_Definitions(shaderPart: string): CustomMaterial;
Fragment_MainBegin(shaderPart: string): CustomMaterial;
Fragment_Custom_Diffuse(shaderPart: string): CustomMaterial;
Fragment_Custom_Alpha(shaderPart: string): CustomMaterial;
Fragment_Before_FragColor(shaderPart: string): CustomMaterial;
Vertex_Begin(shaderPart: string): CustomMaterial;
Vertex_Definitions(shaderPart: string): CustomMaterial;
Vertex_MainBegin(shaderPart: string): CustomMaterial;
Vertex_Before_PositionUpdated(shaderPart: string): CustomMaterial;
Vertex_Before_NormalUpdated(shaderPart: string): CustomMaterial;
}
}
declare module BABYLON {
class CellMaterial extends PushMaterial {
private _diffuseTexture;
diffuseTexture: BaseTexture;
diffuseColor: Color3;
_computeHighLevel: boolean;
computeHighLevel: boolean;
private _disableLighting;
disableLighting: boolean;
private _maxSimultaneousLights;
maxSimultaneousLights: number;
private _renderId;
constructor(name: string, scene: Scene);
needAlphaBlending(): boolean;
needAlphaTesting(): boolean;
getAlphaTestTexture(): Nullable<BaseTexture>;
isReadyForSubMesh(mesh: AbstractMesh, subMesh: SubMesh, useInstances?: boolean): boolean;
bindForSubMesh(world: Matrix, mesh: Mesh, subMesh: SubMesh): void;
getAnimatables(): IAnimatable[];
getActiveTextures(): BaseTexture[];
hasTexture(texture: BaseTexture): boolean;
dispose(forceDisposeEffect?: boolean): void;
getClassName(): string;
clone(name: string): CellMaterial;
serialize(): any;
static Parse(source: any, scene: Scene, rootUrl: string): CellMaterial;
}
} | the_stack |
import * as monaco from "monaco-editor/esm/vs/editor/editor.api";
import dot from "dot-object";
import * as colors from "@material-ui/core/colors";
import { createGlobalStyle, css } from "styled-components";
// import { SyntaxClass } from "../workers/typescript";
const entries = Object.entries as <T>(
o: T
) => [Extract<keyof T, string>, T[keyof T]][];
const white = "#ffffff";
const black = "#161616";
const variableColor = "#c97c2a";
const syntaxClasses = {
variable: variableColor,
type: colors.teal.A700,
scope: "#db9504",
function: colors.lightBlue.A700,
number: colors.orange[400],
string: colors.lightGreen[800],
comment: colors.blueGrey[600],
constant: variableColor,
directive: colors.grey[900],
control: colors.grey[900],
operator: colors.teal.A700,
modifier: colors.pink[600],
punctuation: colors.grey[900]
};
export const globalEditorCSS = createGlobalStyle`
${entries(syntaxClasses).map(
([name, color]) =>
css`
span.${name} {
color: ${color} !important;
}
`
)}
`;
const editorColors = {
contrastBorder: colors.grey[200],
errorForeground: colors.red[500],
focusBorder: colors.grey[200],
foreground: colors.grey[800],
activityBar: {
background: white,
border: colors.grey[200]
},
activityBarBadge: {
background: colors.red[500]
},
button: {
background: colors.blue[600],
foreground: black,
border: colors.blue[600],
hoverBackground: colors.blue[600]
},
dropdown: {
background: white,
border: colors.grey[300],
foreground: black
},
editor: {
background: white,
foreground: colors.grey[800],
hoverHighlightBackground: colors.grey[300],
inactiveSelectionBackground: colors.grey[300],
lineHighlightBackground: colors.grey[200],
lineHighlightBorder: colors.grey[200],
rangeHighlightBackground: colors.grey[200],
selectionBackground: colors.grey[300],
selectionHighlightBackground: colors.grey[200],
wordHighlightStrongBackground: colors.grey[200],
wordHighlightBackground: colors.grey[200]
},
editorBracketMatch: {
background: colors.grey[200],
border: colors.grey[200]
},
editorCodeLens: {
foreground: colors.grey[800]
},
editorCursor: {
background: white,
foreground: black
},
editorError: {
border: colors.grey[200],
foreground: colors.red[500]
},
editorGroup: {
background: white,
border: colors.grey[200],
dropBackground: white
},
editorGroupHeader: {
tabsBackground: white,
tabsBorder: colors.grey[200]
},
editorGutter: {
background: white,
deletedBackground: colors.red[500],
modifiedBackground: white
},
editorHoverWidget: {
background: white,
border: colors.grey[200]
},
editorIndentGuide: {
background: white
},
editorLink: {
activeForeground: colors.grey[300]
},
editorLineNumber: {
foreground: colors.grey[600],
activeForeground: colors.grey[900]
},
editorRuler: {
foreground: black
},
editorMarkerNavigation: {
background: white
},
editorMarkerNavigationWarning: {
background: colors.grey[200]
},
editorMarkerNavigationError: {
background: white
},
editorOverviewRuler: {
border: colors.grey[200],
commonContentForeground: colors.grey[200],
currentContentForeground: colors.red[500],
incomingContentForeground: colors.green[500]
},
editorSuggestWidget: {
background: white,
border: colors.grey[200],
foreground: colors.grey[800],
selectedBackground: colors.grey[200]
},
editorWarning: {
border: colors.grey[200],
foreground: colors.red[300]
},
editorWhitespace: {
foreground: colors.grey[800]
},
editorWidget: {
background: white,
border: colors.grey[200]
},
extensionButton: {
prominentBackground: colors.grey[200],
prominentForeground: white,
prominentHoverBackground: colors.grey[200]
},
input: {
background: colors.grey[200],
foreground: black,
border: colors.grey[200],
placeholderForeground: colors.grey[400]
},
inputOption: {
activeBorder: colors.lightBlue[500]
},
inputValidation: {
infoBorder: colors.purple[500],
warningBorder: colors.amber[500],
errorBorder: colors.red[500]
},
list: {
dropBackground: white,
highlightForeground: colors.lightBlue[500],
hoverBackground: colors.grey[200],
focusBackground: colors.grey[200],
activeSelectionBackground: colors.grey[200],
activeSelectionForeground: black,
inactiveSelectionBackground: colors.grey[200],
inactiveSelectionForeground: white,
warningForeground: colors.amber[500],
errorForeground: colors.red[500]
},
menu: {
background: white,
selectionBackground: colors.grey[200]
},
peekView: {
border: colors.grey[300]
},
peekViewEditor: {
background: colors.grey[200],
matchHighlightBackground: colors.lightBlue[500]
},
peekViewResult: {
background: colors.grey[200],
fileForeground: white,
lineForeground: white,
matchHighlightBackground: colors.lightBlue[500],
selectionBackground: colors.grey[200],
selectionForeground: white
},
peekViewTitle: {
background: colors.grey[200]
},
peekViewTitleDescription: {
foreground: colors.blue[700]
},
peekViewTitleLabel: {
foreground: black
},
scrollbarSlider: {
activeBackground: white,
border: colors.grey[200]
},
selection: {
background: colors.blue[700]
},
separator: {
background: colors.grey[300],
foreground: black
},
sideBar: {
background: white,
border: colors.grey[200],
foreground: colors.grey[800]
},
sideBarSectionHeader: {
background: white,
foreground: black,
border: colors.grey[200]
},
sideBarTitle: {
foreground: black
},
statusBar: {
background: colors.grey[200],
foreground: black,
debuggingBackground: colors.red[500],
debuggingForeground: colors.grey[200],
noFolderBackground: colors.grey[200],
noFolderForeground: white,
border: colors.grey[200]
},
statusBarItem: {
prominentBackground: colors.red[500],
prominentHoverBackground: colors.amber[500],
remoteForeground: colors.grey[100],
remoteBackground: colors.purple[500]
},
tab: {
activeBackground: white,
activeForeground: white,
border: colors.grey[200],
activeBorder: colors.lightBlue[500],
inactiveBackground: white,
inactiveForeground: colors.grey[400],
unfocusedActiveForeground: white,
unfocusedInactiveForeground: colors.grey[400]
},
titleBar: {
background: white,
activeBackground: white,
activeForeground: white,
border: colors.grey[200],
inactiveBackground: white,
inactiveForeground: colors.grey[300]
}
};
const vscodeTokens = [
{
name: "Delimeter Bracket",
scope: ["backtick.bracket"],
settings: {
foreground: syntaxClasses.modifier
}
},
{
name: "Operator",
scope: ["operator"],
settings: {
foreground: syntaxClasses.operator
}
},
{
name: "Comment",
scope: ["comment"],
settings: {
foreground: colors.blueGrey[600],
fontStyle: "italic"
}
},
{
name: "Keyword",
scope: ["keyword"],
settings: {
foreground: colors.purple.A700
}
},
{
name: "Storage",
scope: ["storage"],
settings: {
foreground: colors.purple.A700
}
},
{
name: "Constant",
scope: ["constant"],
settings: {
foreground: syntaxClasses.constant
}
},
{
name: "Variable",
scope: ["variable"],
settings: {
foreground: syntaxClasses.variable
}
},
{
name: "String",
scope: ["string"],
settings: {
foreground: syntaxClasses.string
}
},
{
name: "String",
scope: ["number"],
settings: {
foreground: colors.deepOrange.A200
}
},
{
name: "None",
scope: ["none"],
settings: {
foreground: colors.blueGrey[300]
}
},
{
name: "Invalid Deprecated",
scope: ["invalid.deprecated"],
settings: {
foreground: colors.brown[800],
background: colors.amber[300]
}
},
{
name: "Invalid Illegal",
scope: ["invalid.illegal"],
settings: {
foreground: black,
background: colors.red[400]
}
},
{
name: "Markup Bold",
scope: ["markup.bold"],
settings: {
foreground: colors.deepOrange.A200,
fontStyle: "bold"
}
},
{
name: "Markup Changed",
scope: ["markup.changed"],
settings: {
foreground: colors.purple.A700
}
},
{
name: "Markup Deleted",
scope: ["markup.deleted"],
settings: {
foreground: colors.pink.A200
}
},
{
name: "Markup Italic",
scope: ["markup.italic"],
settings: {
foreground: colors.purple.A700,
fontStyle: "italic"
}
},
{
name: "Markup Heading",
scope: ["markup.heading"],
settings: {
foreground: colors.pink.A200
}
},
{
name: "Markup Heading Punctuation Definition Heading",
scope: ["markup.heading punctuation.definition.heading"],
settings: {
foreground: colors.lightBlue.A400
}
},
{
name: "Markup Link",
scope: ["markup.link"],
settings: {
foreground: colors.purple.A700
}
},
{
name: "Markup Inserted",
scope: ["markup.inserted"],
settings: {
foreground: colors.green.A200
}
},
{
name: "Markup Quote",
scope: ["markup.quote"],
settings: {
foreground: colors.deepOrange.A200
}
},
{
name: "Markup Raw",
scope: ["markup.raw"],
settings: {
foreground: colors.green.A200
}
},
{
scope: "token.info-token",
settings: {
foreground: colors.lightBlue[600]
}
},
{
scope: "token.warn-token",
settings: {
foreground: colors.lightBlue[700]
}
},
{
scope: "token.error-token",
settings: {
foreground: colors.red[700]
}
},
{
scope: "token.debug-token",
settings: {
foreground: colors.purple[400]
}
}
];
function removeUndefined(
rule: monaco.editor.ITokenThemeRule
): monaco.editor.ITokenThemeRule {
return entries(rule).reduce<monaco.editor.ITokenThemeRule>(
(acc, [key, value]) => {
if (value) {
acc[key] = value;
}
return acc;
},
{ token: rule.token }
);
}
function transformVscodeTokens(): monaco.editor.ITokenThemeRule[] {
const rules: monaco.editor.ITokenThemeRule[] = [];
vscodeTokens.forEach(token => {
if (Array.isArray(token.scope)) {
token.scope.forEach(scope => {
rules.push(
removeUndefined({
token: scope,
foreground: token.settings.foreground,
background: token.settings.background,
fontStyle: token.settings.fontStyle
})
);
});
} else {
rules.push(
removeUndefined({
token: token.scope,
foreground: token.settings.foreground,
background: token.settings.background,
fontStyle: token.settings.fontStyle
})
);
}
});
return rules;
}
const theme: monaco.editor.IStandaloneThemeData = {
inherit: true,
base: "vs",
colors: dot.dot(editorColors),
rules: transformVscodeTokens()
};
export default theme; | the_stack |
import { BindParam } from '../BindParam/BindParam';
import {
Neo4jSingleTypes,
Neo4jSupportedTypes,
} from '../QueryRunner/QueryRunner';
import { neo4jDriver } from '../..';
import { NeogmaConstraintError } from '../../Errors';
/** symbols for Where operations */
const OpIn: unique symbol = Symbol('in');
const OpContains: unique symbol = Symbol('contains');
export const Op = {
in: OpIn,
contains: OpContains,
} as const;
/** the type to be used for "in" */
interface WhereInI {
[Op.in]: Neo4jSingleTypes[];
}
interface WhereContainsI {
[Op.contains]: string;
}
const isWhereIn = (value: WhereValuesI): value is WhereInI => {
return value?.[Op.in];
};
const isWhereContains = (value: WhereValuesI): value is WhereContainsI => {
return value?.[Op.contains];
};
const isNeo4jSupportedTypes = (
value: WhereValuesI,
): value is Neo4jSupportedTypes => {
const isSupportedSingleType = (value: WhereValuesI): boolean => {
return (
typeof value === 'string' ||
typeof value === 'number' ||
typeof value === 'boolean' ||
neo4jDriver.isInt(value) ||
neo4jDriver.isPoint(value) ||
neo4jDriver.isDate(value) ||
neo4jDriver.isTime(value) ||
neo4jDriver.isLocalTime(value) ||
neo4jDriver.isDateTime(value) ||
neo4jDriver.isLocalDateTime(value) ||
neo4jDriver.isDuration(value)
);
};
if (Array.isArray(value)) {
return value.every((element) => isSupportedSingleType(element));
}
return isSupportedSingleType(value);
};
/** the type for the accepted values for an attribute */
export type WhereValuesI = Neo4jSupportedTypes | WhereInI | WhereContainsI;
/**
* an object to be used for a query identifier
* Its keys are the identifier attributes for the where, and the values are the values for that attribute
*/
export interface WhereParamsI {
/** the attribute and values for an identifier */
[attribute: string]: WhereValuesI;
}
/**
* an object with the query identifiers as keys and the attributes+types as value
*/
export interface WhereParamsByIdentifierI {
/** the identifiers to use */
[identifier: string]: WhereParamsI;
}
/** a Where instance or the basic object which can create a Where instance */
export type AnyWhereI = WhereParamsByIdentifierI | Where;
export class Where {
/** where bind params. Ensures that keys of the bind param are unique */
private bindParam: BindParam;
/** all the given options, so we can easily combine them into a new statement */
private rawParams: WhereParamsByIdentifierI[] = [];
/**
* an object with the key being the `identifier.property` and the value being the the bind param name which corresponds to it, and an operator to be used in the statement
* this is needed for the following reasons:
* 1) when generating the statement, those values are used
* 2) the bind param names which are generated from this Where need to be differentiated from the actual keys of the bindParam, since this Where can only remove those
*/
private identifierPropertyData: Array<{
identifier: string;
property: string;
bindParamName: string;
operator: 'equals' | 'in' | 'contains';
}> = [];
constructor(
/** the where parameters to use */
whereParams: Parameters<Where['addParams']>[0],
/** an existing bind param to be used, so the properties can be merged. If empty, a new one will be created and used */
bindParam?: BindParam,
) {
this.bindParam = BindParam.acquire(bindParam);
this.addParams(whereParams);
Object.setPrototypeOf(this, Where.prototype);
}
/** gets the BindParam used in this Where */
public getBindParam(): BindParam {
return this.bindParam;
}
/** gets the raw where parameters used to generate the final result */
public getRawParams(): Where['rawParams'] {
return this.rawParams;
}
/** refreshes the statement and the bindParams by the given where params */
public addParams(
/** the where parameters to use */
whereParams: WhereParamsByIdentifierI,
): Where {
// push the latest whereParams to the end of the array
this.rawParams.push(whereParams);
/* set the identifierPropertyData field by the rawParams */
// merge all rawParams, for each identifier, into a single one. That way, the latest rawOption will dictate its properties if some previous ones have a common key
const params: WhereParamsByIdentifierI = {};
for (const rawParam of this.rawParams) {
for (const [identifier, value] of Object.entries(rawParam)) {
params[identifier] = { ...params[identifier], ...value };
}
}
// remove all used bind param names from the bind param, since we're gonna set them again from scratch
this.bindParam.remove(
this.identifierPropertyData.map(
({ bindParamName }) => bindParamName,
),
);
// reset identifierPropertyData as they've been removed from the bindParam
this.identifierPropertyData = [];
for (const nodeIdentifier in params) {
for (const property in params[nodeIdentifier]) {
const value = params[nodeIdentifier][property];
if (isNeo4jSupportedTypes(value)) {
this.addBindParamDataEntry({
identifier: nodeIdentifier,
property,
value,
operator: 'equals',
});
} else if (isWhereIn(value)) {
this.addBindParamDataEntry({
identifier: nodeIdentifier,
property,
value: value[Op.in],
operator: 'in',
});
} else if (isWhereContains(value)) {
this.addBindParamDataEntry({
identifier: nodeIdentifier,
property,
value: value[Op.contains],
operator: 'contains',
});
}
}
}
return this;
}
/** adds a value to the bind param, while updating the usedBindParamNames field appropriately */
private addBindParamDataEntry = ({
identifier,
property,
operator,
value,
}: {
identifier: string;
property: string;
operator: Where['identifierPropertyData'][0]['operator'];
value: Neo4jSupportedTypes;
}) => {
const bindParamName = this.bindParam.getUniqueNameAndAdd(
property,
value,
);
this.identifierPropertyData.push({
identifier,
property,
bindParamName,
operator,
});
};
/** gets the statement by the params */
public getStatement = (
/**
* text is in the format "a.p1 = $v1 AND a.p2 = $v2"
* object is in the format "{ a.p1 = $v1, a.p2 = $v2 }"
*/
mode: 'object' | 'text',
): string => {
const statementParts: string[] = [];
const operatorForStatement = (
operator: Where['identifierPropertyData'][0]['operator'],
) => {
if (mode === 'object') {
if (operator !== 'equals') {
throw new NeogmaConstraintError(
'The only operator which is supported for object mode is "equals"',
{
actual: {
mode,
operator,
},
},
);
}
// : is the only operator used in object mode
return ':';
}
const textMap: Record<
Where['identifierPropertyData'][0]['operator'],
string
> = {
equals: '=',
in: 'IN',
contains: 'CONTAINS',
};
// else, return the appropriate text-mode operator
return textMap[operator];
};
if (mode === 'text') {
for (const bindParamData of this.identifierPropertyData) {
statementParts.push(
[
`${bindParamData.identifier}.${bindParamData.property}`,
operatorForStatement(bindParamData.operator),
`$${bindParamData.bindParamName}`,
].join(' '),
);
}
return statementParts.join(' AND ');
}
if (mode === 'object') {
for (const bindParamData of this.identifierPropertyData) {
statementParts.push(
[
bindParamData.property,
operatorForStatement(bindParamData.operator),
` $${bindParamData.bindParamName}`,
].join(''),
);
}
return `{ ${statementParts.join(', ')} }`;
}
throw new NeogmaConstraintError(`invalid mode ${mode}`);
};
/** returns a Where object if params is specified, else returns null */
public static acquire(
params?: AnyWhereI | null,
bindParam?: BindParam,
): Where | null {
if (!params) {
return null;
}
if (params instanceof Where) {
return params;
}
return new Where(params, bindParam);
}
/**
* if the value is not an array, it gets returned as is. If it's an array, a "[Op.in]" object is returned for that value
*/
public static ensureIn(value: WhereValuesI): WhereValuesI {
return value instanceof Array
? {
[Op.in]: value,
}
: value;
}
} | the_stack |
import Debug from 'debug';
import {uuid} from '../utils';
import extend from 'extend';
// @ts-ignore
import Layout from 'layout';
import * as _ from 'lodash';
import {slides_v1 as SlidesV1} from 'googleapis';
import {
ImageDefinition,
SlideDefinition,
TableDefinition,
TextDefinition,
VideoDefinition,
} from '../slides';
import {
findLayoutIdByName,
findPlaceholder,
findSpeakerNotesObjectId,
} from './presentation_helpers';
import assert from 'assert';
const debug = Debug('md2gslides');
interface BoundingBox {
height: number;
width: number;
x: number;
y: number;
}
/**
* Performs most of the work of converting a slide into API requests.
*
*/
export default class GenericLayout {
public name: string;
public presentation: SlidesV1.Schema$Presentation;
private slide: SlideDefinition;
public constructor(
name: string,
presentation: SlidesV1.Schema$Presentation,
slide: SlideDefinition
) {
this.name = name;
this.presentation = presentation;
this.slide = slide;
}
public appendCreateSlideRequest(
requests: SlidesV1.Schema$Request[]
): SlidesV1.Schema$Request[] {
const layoutId = findLayoutIdByName(this.presentation, this.name);
if (!layoutId) {
throw new Error(`Unable to find layout ${this.name}`);
}
this.slide.objectId = uuid();
debug('Creating slide %s with layout %s', this.slide.objectId, this.name);
requests.push({
createSlide: {
slideLayoutReference: {
layoutId: layoutId,
},
objectId: this.slide.objectId,
},
});
return requests;
}
public appendContentRequests(
requests: SlidesV1.Schema$Request[]
): SlidesV1.Schema$Request[] {
this.appendFillPlaceholderTextRequest(this.slide.title, 'TITLE', requests);
this.appendFillPlaceholderTextRequest(
this.slide.title,
'CENTERED_TITLE',
requests
);
this.appendFillPlaceholderTextRequest(
this.slide.subtitle,
'SUBTITLE',
requests
);
if (this.slide.backgroundImage) {
this.appendSetBackgroundImageRequest(
this.slide.backgroundImage,
requests
);
}
if (this.slide.tables.length) {
this.appendCreateTableRequests(this.slide.tables, requests);
}
if (this.slide.bodies) {
assert(this.slide.objectId);
const bodyElements = findPlaceholder(
this.presentation,
this.slide.objectId,
'BODY'
);
const bodyCount = Math.min(
bodyElements?.length ?? 0,
this.slide.bodies.length
);
for (let i = 0; i < bodyCount; ++i) {
const placeholder = bodyElements![i];
const body = this.slide.bodies[i];
this.appendFillPlaceholderTextRequest(body.text, placeholder, requests);
if (body.images && body.images.length) {
this.appendCreateImageRequests(body.images, placeholder, requests);
}
if (body.videos && body.videos.length) {
this.appendCreateVideoRequests(body.videos, placeholder, requests);
}
}
}
if (this.slide.notes) {
assert(this.slide.objectId);
const objectId = findSpeakerNotesObjectId(
this.presentation,
this.slide.objectId
);
this.appendInsertTextRequests(
this.slide.notes,
{objectId: objectId},
requests
);
}
return requests;
}
protected appendFillPlaceholderTextRequest(
value: TextDefinition | undefined,
placeholder: string | SlidesV1.Schema$PageElement,
requests: SlidesV1.Schema$Request[]
): void {
if (!value) {
debug('No text for placeholder %s');
return;
}
if (typeof placeholder === 'string') {
assert(this.slide.objectId);
const pageElements = findPlaceholder(
this.presentation,
this.slide.objectId,
placeholder
);
if (!pageElements) {
debug('Skipping undefined placeholder %s', placeholder);
return;
}
placeholder = pageElements[0];
}
this.appendInsertTextRequests(
value,
{objectId: placeholder.objectId},
requests
);
}
protected appendInsertTextRequests(
text: TextDefinition,
locationProps:
| Partial<SlidesV1.Schema$UpdateTextStyleRequest>
| Partial<SlidesV1.Schema$CreateParagraphBulletsRequest>,
requests: SlidesV1.Schema$Request[]
): void {
// Insert the raw text first
const request = {
insertText: extend(
{
text: text.rawText,
},
locationProps
),
};
requests.push(request);
// Apply any text styles present.
// Most of the work for generating the text runs
// is performed when parsing markdown.
for (const textRun of text.textRuns) {
const request: SlidesV1.Schema$Request = {
updateTextStyle: extend(
{
textRange: {
type: 'FIXED_RANGE',
startIndex: textRun.start,
endIndex: textRun.end,
},
style: {
bold: textRun.bold,
italic: textRun.italic,
foregroundColor: textRun.foregroundColor,
backgroundColor: textRun.backgroundColor,
strikethrough: textRun.strikethrough,
underline: textRun.underline,
smallCaps: textRun.smallCaps,
fontFamily: textRun.fontFamily,
fontSize: textRun.fontSize,
link: textRun.link,
baselineOffset: textRun.baselineOffset,
},
},
locationProps
),
};
assert(request.updateTextStyle?.style);
request.updateTextStyle.fields = this.computeShallowFieldMask(
request.updateTextStyle.style
);
if (request.updateTextStyle.fields.length) {
requests.push(request); // Only push if at least one style set
}
}
// Convert paragraphs to lists.
// Note that leading tabs for nested lists in the raw text are removed.
// In this case, we're assuming that lists are supplied in order of
// appearance and they're non-overlapping.
// Processing in the reverse order avoids having to readjust indices.
for (const listMarker of _.reverse(text.listMarkers)) {
const request = {
createParagraphBullets: extend(
{
textRange: {
type: 'FIXED_RANGE',
startIndex: listMarker.start,
endIndex: listMarker.end,
},
bulletPreset:
listMarker.type === 'ordered'
? 'NUMBERED_DIGIT_ALPHA_ROMAN'
: 'BULLET_DISC_CIRCLE_SQUARE',
},
locationProps
),
};
requests.push(request);
}
}
protected appendSetBackgroundImageRequest(
image: ImageDefinition,
requests: SlidesV1.Schema$Request[]
): void {
debug(
'Slide #%d: setting background image to %s',
this.slide.index,
image.url
);
requests.push({
updatePageProperties: {
objectId: this.slide.objectId,
fields: 'pageBackgroundFill.stretchedPictureFill.contentUrl',
pageProperties: {
pageBackgroundFill: {
stretchedPictureFill: {
contentUrl: image.url,
},
},
},
},
});
}
protected appendCreateImageRequests(
images: ImageDefinition[],
placeholder: SlidesV1.Schema$PageElement | undefined,
requests: SlidesV1.Schema$Request[]
): void {
// TODO - Fix weird cast
const layer = (Layout as (s: string) => Layout.PackingSmith)('left-right'); // TODO - Configurable?
for (const image of images) {
debug('Slide #%d: adding inline image %s', this.slide.index, image.url);
layer.addItem({
width: image.width + image.padding * 2,
height: image.height + image.padding * 2,
meta: image,
});
}
const box = this.getBodyBoundingBox(placeholder);
const computedLayout = layer.export();
const scaleRatio = Math.min(
box.width / computedLayout.width,
box.height / computedLayout.height
);
const scaledWidth = computedLayout.width * scaleRatio;
const scaledHeight = computedLayout.height * scaleRatio;
const baseTranslateX = box.x + (box.width - scaledWidth) / 2;
const baseTranslateY = box.y + (box.height - scaledHeight) / 2;
for (const item of computedLayout.items) {
const itemOffsetX = item.meta.offsetX ? item.meta.offsetX : 0;
const itemOffsetY = item.meta.offsetY ? item.meta.offsetY : 0;
const itemPadding = item.meta.padding ? item.meta.padding : 0;
const width = item.meta.width * scaleRatio;
const height = item.meta.height * scaleRatio;
const translateX =
baseTranslateX + (item.x + itemPadding + itemOffsetX) * scaleRatio;
const translateY =
baseTranslateY + (item.y + itemPadding + itemOffsetY) * scaleRatio;
requests.push({
createImage: {
elementProperties: {
pageObjectId: this.slide.objectId,
size: {
height: {
magnitude: height,
unit: 'EMU',
},
width: {
magnitude: width,
unit: 'EMU',
},
},
transform: {
scaleX: 1,
scaleY: 1,
translateX: translateX,
translateY: translateY,
shearX: 0,
shearY: 0,
unit: 'EMU',
},
},
url: item.meta.url,
},
});
}
}
protected appendCreateVideoRequests(
videos: VideoDefinition[],
placeholder: SlidesV1.Schema$PageElement | undefined,
requests: SlidesV1.Schema$Request[]
): void {
if (videos.length > 1) {
throw new Error('Multiple videos per slide are not supported.');
}
const video = videos[0];
debug('Slide #%d: adding video %s', this.slide.index, video.id);
const box = this.getBodyBoundingBox(placeholder);
const scaleRatio = Math.min(
box.width / video.width,
box.height / video.height
);
const scaledWidth = video.width * scaleRatio;
const scaledHeight = video.height * scaleRatio;
const translateX = box.x + (box.width - scaledWidth) / 2;
const translateY = box.y + (box.height - scaledHeight) / 2;
const objectId = uuid();
requests.push({
createVideo: {
source: 'YOUTUBE',
objectId: objectId,
id: video.id,
elementProperties: {
pageObjectId: this.slide.objectId,
size: {
height: {
magnitude: scaledHeight,
unit: 'EMU',
},
width: {
magnitude: scaledWidth,
unit: 'EMU',
},
},
transform: {
scaleX: 1,
scaleY: 1,
translateX: translateX,
translateY: translateY,
shearX: 0,
shearY: 0,
unit: 'EMU',
},
},
},
});
requests.push({
updateVideoProperties: {
objectId: objectId,
fields: 'autoPlay',
videoProperties: {
autoPlay: video.autoPlay,
},
},
});
}
protected appendCreateTableRequests(
tables: TableDefinition[],
requests: SlidesV1.Schema$Request[]
): void {
if (tables.length > 1) {
throw new Error('Multiple tables per slide are not supported.');
}
const table = tables[0];
const tableId = uuid();
requests.push({
createTable: {
objectId: tableId,
elementProperties: {
pageObjectId: this.slide.objectId,
// Use default size/transform for tables
},
rows: table.rows,
columns: table.columns,
},
});
for (const r in table.cells) {
const row = table.cells[r];
for (const c in row) {
this.appendInsertTextRequests(
row[c],
{
objectId: tableId,
cellLocation: {
rowIndex: parseInt(r),
columnIndex: parseInt(c),
},
},
requests
);
}
}
}
protected calculateBoundingBox(
element: SlidesV1.Schema$PageElement
): BoundingBox {
assert(element);
assert(element.size?.height?.magnitude);
assert(element.size?.width?.magnitude);
const height = element.size.height.magnitude;
const width = element.size.width.magnitude;
const scaleX = element.transform?.scaleX ?? 1;
const scaleY = element.transform?.scaleY ?? 1;
const shearX = element.transform?.shearX ?? 0;
const shearY = element.transform?.shearY ?? 0;
return {
width: scaleX * width + shearX * height,
height: scaleY * height + shearY * width,
x: element.transform?.translateX ?? 0,
y: element.transform?.translateY ?? 0,
};
}
protected getBodyBoundingBox(
placeholder: SlidesV1.Schema$PageElement | undefined
): BoundingBox {
if (placeholder) {
return this.calculateBoundingBox(placeholder);
}
assert(this.presentation.pageSize?.width?.magnitude);
assert(this.presentation.pageSize?.height?.magnitude);
return {
width: this.presentation.pageSize.width.magnitude,
height: this.presentation.pageSize.height.magnitude,
x: 0,
y: 0,
};
}
protected computeShallowFieldMask<T>(object: T): string {
const fields = [];
for (const field of Object.keys(object)) {
if (object[field as keyof T] !== undefined) {
fields.push(field);
}
}
return fields.join(',');
}
} | the_stack |
'use strict';
import { ExtensionContext, window, ProgressLocation, workspace, ConfigurationTarget } from 'vscode';
import { instrumentOperationAsVsCodeCommand } from "vscode-extension-telemetry-wrapper";
import * as path from 'path';
import * as os from 'os';
import { utils } from 'pddl-workspace';
import { ValDownloader as ValDownloaderBase, ValVersion, readValManifest, writeValManifest } from 'ai-planning-val';
import { PARSER_EXECUTABLE_OR_SERVICE, CONF_PDDL, VALIDATION_PATH, VALUE_SEQ_PATH, VAL_STEP_PATH, VALIDATOR_VERSION } from '../configuration/configuration';
import { VAL_DOWNLOAD_COMMAND, ValDownloadOptions } from './valCommand';
import { ensureAbsoluteGlobalStoragePath } from '../utils';
export class ValDownloader extends ValDownloaderBase {
/** Directory where VAL binaries are to be downloaded locally. */
static readonly VAL_DIR = "val";
/** File that contains version info of last downloaded VAL binaries. */
private valVersionPath: string;
private readonly binaryStorage: string;
constructor(private context: ExtensionContext) {
super();
this.binaryStorage = this.context.globalStoragePath;
this.valVersionPath = path.join(this.getValPath(), "VAL.version");
}
registerCommands(): ValDownloader {
this.context.subscriptions.push(instrumentOperationAsVsCodeCommand(VAL_DOWNLOAD_COMMAND, async (options: ValDownloadOptions) => {
try {
const userAgreesToDownload = options?.bypassConsent ?? await this.promptForConsent();
if (!userAgreesToDownload) { return; }
await this.downloadConfigureAndCleanUp();
} catch (ex: unknown) {
const error = ex as Error;
window.showErrorMessage(error.message ?? "" + error);
}
}));
return this;
}
protected async downloadDelegate(url: string, zipPath: string, message: string): Promise<void> {
return await window.withProgress({ location: ProgressLocation.Window, title: message }, () => {
return super.downloadDelegate(url, zipPath, message);
});
}
/** Directory where VAL binaries are to be downloaded locally. */
getValPath(): string {
return path.join(this.binaryStorage, ValDownloader.VAL_DIR);
}
private asAbsoluteStoragePath(relativePath: string): string {
return path.join(this.binaryStorage, relativePath);
}
private async promptForConsent(): Promise<boolean> {
const download = "Download";
const message = `Please confirm to download [VAL tools](${ValDownloader.VAL_REPO}) build from ${ValDownloader.VAL_BINARY_PROJECT}?`;
const answer = await window.showInformationMessage(message, { modal: true }, download);
return answer === download;
}
async downloadConfigureAndCleanUp(): Promise<ValVersion> {
const wasValInstalled = await this.isInstalled();
const previousVersion = wasValInstalled ? await this.readVersion() : undefined;
let newVersion: ValVersion | undefined;
try {
newVersion = await this.downloadAndConfigure();
}
finally {
// clean previous version
if (wasValInstalled && previousVersion && newVersion) {
if (previousVersion.buildId !== newVersion.buildId) {
console.log(`The ${previousVersion.version} and the ${newVersion.version} differ, cleaning-up the old version.`);
const filesAbsPaths = previousVersion.files.map(f => this.asAbsoluteStoragePath(path.join(ValDownloader.VAL_DIR, f)));
await ValDownloader.deleteAll(filesAbsPaths);
}
}
}
return newVersion;
}
protected getLatestStableValBuildId(): number {
return workspace.getConfiguration(CONF_PDDL).get<number>(VALIDATOR_VERSION) ?? -1;
}
private async downloadAndConfigure(): Promise<ValVersion> {
const buildId = this.getLatestStableValBuildId();
await utils.afs.mkdirIfDoesNotExist(this.binaryStorage, 0o755);
const newValVersion = await this.download(buildId, this.getValPath());
const wasValInstalled = await this.isInstalled();
const previousVersion = wasValInstalled ? await this.readVersion() : undefined;
await this.writeVersion(newValVersion);
await this.updateConfigurationPaths(newValVersion, previousVersion);
return newValVersion;
}
async isInstalled(): Promise<boolean> {
return await utils.afs.exists(this.valVersionPath);
}
private async readVersion(): Promise<ValVersion> {
return readValManifest(this.valVersionPath);
}
private async writeVersion(valVersion: ValVersion): Promise<void> {
return writeValManifest(this.valVersionPath, valVersion);
}
/**
* Configures the val tool paths
* @param newValVersion val version just downloaded
* @param oldValVersion val version from which we are upgrading
*/
private async updateConfigurationPaths(newValVersion: ValVersion, oldValVersion?: ValVersion): Promise<void> {
const fileToConfig = new Map<string, string>();
fileToConfig.set("Parser", PARSER_EXECUTABLE_OR_SERVICE);
fileToConfig.set("Validate", CONF_PDDL + '.' + VALIDATION_PATH);
fileToConfig.set("ValueSeq", CONF_PDDL + '.' + VALUE_SEQ_PATH);
fileToConfig.set("ValStep", CONF_PDDL + '.' + VAL_STEP_PATH);
for (const toolName of fileToConfig.keys()) {
const oldToolPath = findValToolPath(oldValVersion, toolName);
const newToolPath = findValToolPath(newValVersion, toolName);
if (!newToolPath) {
console.log(`Tool ${toolName} not found in the downloaded archive.`);
return;
}
const oldToolAbsPath = oldToolPath && this.asAbsoluteStoragePath(path.join(ValDownloader.VAL_DIR, oldToolPath));
const newToolAbsPath = this.asAbsoluteStoragePath(path.join(ValDownloader.VAL_DIR, newToolPath));
const configKey = fileToConfig.get(toolName);
if (configKey && newToolPath) {
await this.updateConfigurationPath(toolName, configKey, newToolAbsPath, oldToolAbsPath);
}
}
}
/**
* Updates the configuration path for the configuration key, unless it was explicitly set by the user.
* @param toolName name of the tool being configured
* @param configKey configuration key in the form prefix.postfix
* @param newToolPath the location of the currently downloaded/unzipped tool
* @param prevDownloadToolPath the location of the previously downloaded/unzipped tool (if known)
*/
private async updateConfigurationPath(toolName: string, configKey: string, newToolPath: string, prevDownloadToolPath?: string): Promise<void> {
const configurationInspect = workspace.getConfiguration().inspect<string>(configKey);
if (!configurationInspect) {
console.log("configuration not declared: " + configKey);
return;
}
const normConfiguredGlobalValue =
this.normalizePathIfValid(
// for backward compatibility
ensureAbsoluteGlobalStoragePath(configurationInspect.globalValue, this.context));
const normPrevDownloadToolPath = this.normalizePathIfValid(prevDownloadToolPath);
// was the configuration value empty?
if (normConfiguredGlobalValue === undefined
// or did it match the previous download?
// (i.e.it came from the previous download and the user did not change the configuration)
|| normConfiguredGlobalValue === normPrevDownloadToolPath
// or does the path not exist anyway?
// || prevDownloadToolPath && !await utils.afs.exists(this.asAbsoluteStoragePath(prevDownloadToolPath))
|| await this.shouldOverwrite(toolName, normConfiguredGlobalValue, newToolPath)) {
// Overwrite it!
return await workspace.getConfiguration().update(configKey, newToolPath, ConfigurationTarget.Global);
}
}
protected async shouldOverwrite(toolName: string, yourConfiguredPath: string, newToolPath: string): Promise<boolean> {
const overwrite = "Overwrite";
const message = `VAL tool '${toolName}' was already configured:\n\nYour configuration: ${yourConfiguredPath}\n\nJust downloaded: ${newToolPath}\n\nWish to use the downloaded tool instead?`;
const answer = await window.showInformationMessage(message, {modal: true}, overwrite, "Keep");
return answer === overwrite;
}
private normalizePathIfValid(pathToNormalize?: string): string | undefined {
if (!pathToNormalize) { return pathToNormalize; }
let normalizedPath = path.normalize(pathToNormalize);
if (os.platform() === 'darwin' && normalizedPath.includes(' ')) {
normalizedPath = normalizedPath.replace(' ', '\\ ');
}
return normalizedPath;
}
async isNewValVersionAvailable(): Promise<boolean> {
const isInstalled = await this.isInstalled();
if (!isInstalled) { return false; }
const latestStableValBuildId = this.getLatestStableValBuildId();
const installedVersion = await this.readVersion();
return latestStableValBuildId > installedVersion.buildId;
}
}
/**
* Finds the path of given VAL tool in the given version.
* @param valVersion VAL version manifest (if known)
* @param toolName tool name for which we are looking for its path
* @returns corresponding path, or _undefined_ if the _valVersion_ argument is null or undefined
*/
function findValToolPath(valVersion: ValVersion | undefined, toolName: string): string | undefined {
if (!valVersion) { return undefined; }
const pattern = new RegExp("\\b" + toolName + "(?:\\.exe)?$");
return valVersion.files.find(filePath => pattern.test(filePath));
} | the_stack |
import { SelectionEventsEmitter, SelectionElementEventsEmitter } from './selection-events-emitter';
import { Injectable } from '@angular/core';
export interface SelectionTuple {
index: number;
item: any;
}
/**
* Represents possible operations with selection model.
*/
@Injectable()
export class RTSelectionService {
public eventEmitters: SelectionElementEventsEmitter[] = new Array<SelectionElementEventsEmitter>();
public childSelectionServices: RTSelectionService[] = new Array<RTSelectionService>();
public areaEventsEmitter: SelectionEventsEmitter;
/**
* Index of last selected/deselected element in {@link items} collection.
*/
public lastProcessedIndex: number;
/**
* Optional function which can be used to compare {@link items} elements.
*
* This function can be used by {@link checkSelection}.
*
* Also it's reasonable to use this function for {@link getItemIndex}.
* @param index index of element in {@link items} collection.
* @param actual element from {@link items} collection.
*/
public trackByFn: (index: number, item: any) => any;
/**
* Collection of elements for selection.
*/
public items: any[];
/**
* Collection of {@link SelectionTuple} elements which represents currently selected items in {@link items} collection.
*/
private selectionsList: SelectionTuple[] = new Array<SelectionTuple>();
constructor() {
this.trackByFn = this.trackByIdentity;
}
/**
* Performs application-defined logic for service destroy.
*/
public destroy(): void {
this.areaEventsEmitter = null;
this.eventEmitters.length = 0;
this.selectionsList.length = 0;
this.lastProcessedIndex = null;
this.items = null;
}
/**
* Performs check that every selected element is actually selected.
*
*/
public checkSelection(): void {
if (this.items !== null && typeof this.items !== 'undefined') {
for (let i = this.selectionsList.length - 1; i >= 0; i--) {
const tuple = this.selectionsList[i];
const trackFn = this.trackByFn || this.trackByIdentity;
if (this.isIndexAcceptable(tuple.index) && trackFn(tuple.index, this.items[tuple.index]) === trackFn(tuple.index, tuple.item)) {
tuple.item = this.items[tuple.index];
this.selectItem(tuple, true);
} else {
this.deselectItem(tuple);
}
}
} else {
this.deselectAll();
}
}
/**
* Checks that applied index is valid number and it's value is inside {@link items} boundaries.
* @param index index to check.
* @returns `true` if index is valid.
*/
public isIndexAcceptable(index: number): boolean {
return index !== null && typeof index !== 'undefined' && index >= 0 && this.items && this.items.length > index;
}
/**
* Selects range of elements in {@link items} collection.
* @param fromIndex index of element from which selection range begins.
* @param toIndex index of element on which selection range ends.
*/
public selectRange(fromIndex: number, toIndex: number): void {
if (toIndex < 0 || this.items.length <= toIndex || fromIndex < 0 || this.items.length <= fromIndex) {
return;
}
const startIndex = Math.min(fromIndex, toIndex);
const endIndex = Math.max(fromIndex, toIndex);
if (this.isRangeSelected(startIndex, endIndex)) {
return;
}
this.deselectAll();
const tempData = new Array<SelectionTuple>();
for (let i = startIndex; i <= endIndex; i++) {
const tuple = this.getSelectionTuple(i);
tempData.push(tuple);
this.processSelection(tuple, true);
}
this.selectionsList.splice(0, this.selectionsList.length, ...tempData);
this.lastProcessedIndex = endIndex;
}
/**
* Checks that at least one element selected in {@link items} collection.
* @returns `true` if anything is selected.
*/
public hasSelections(): boolean {
return this.selectionsList.length !== 0;
}
/**
* Checks that all elements inside specified range are selected in {@link items} collection.
* @param fromIndex index of element from which check must be performed.
* @param toIndex index of element to which check must be performed.
* @returns `true` if all elements inside specified range are selected.
*/
public isRangeSelected(from: number, to: number): boolean {
// nothing selected
if (this.selectionsList.length === 0) {
return false;
}
// entire list selected
if (from === 0 && to === this.items.length - 1 && this.selectionsList.length === this.items.length) {
return true;
}
const orderedIndexes = this.selectionsList.map((tuple: SelectionTuple) => tuple.index).sort();
return 1 + to - from === orderedIndexes.length && orderedIndexes[0] === from && orderedIndexes[orderedIndexes.length - 1] === to;
}
/**
* Checks that element at specified index is selected.
* @param index index of element in {@link items} collection to check.
* @returns `true` if element is selected.
*/
public isIndexSelected(index: number): boolean {
if (this.selectionsList.length > 0 && this.isIndexAcceptable(index)) {
return this.selectionsList.findIndex((st: SelectionTuple) => st.index === index) !== -1;
}
return false;
}
/**
* Returns index of specified element in {@link items} collection.
* @param item element to find.
* @returns index of specified element in {@link items} collection. -1 if element not found.
* @see {@link trackByFn}
*/
public getItemIndex(item: any): number {
return this.items.findIndex((value: any) => value === item);
}
/**
* Returns index of first selected element from {@link items} collection.
* @returns index of first selected element. -1 if nothing is selected.
*/
public getMinSelectedIndex(): number {
let minIndex = -1;
this.selectionsList.forEach((item: SelectionTuple) => {
minIndex = minIndex === -1 || item.index < minIndex ? item.index : minIndex;
});
return minIndex;
}
/**
* Returns index of last selected element from {@link items} collection.
* @returns index of last selected element. -1 if nothing is selected.
*/
public getMaxSelectedIndex(): number {
let maxIndex = -1;
this.selectionsList.forEach((item: SelectionTuple) => {
maxIndex = maxIndex === -1 || item.index > maxIndex ? item.index : maxIndex;
});
return maxIndex;
}
/**
* Selects first element in {@link items} collection.
*/
public selectFirst(): void {
if (this.items.length > 0) {
this.selectItem(this.getSelectionTuple(0));
}
}
/**
* Selects last element in {@link items} collection.
*/
public selectLast(): void {
if (this.items.length > 0) {
this.selectItem(this.getSelectionTuple(this.items.length - 1));
}
}
/**
* Selects element at specified index in {@link items} collection.
* @param index index of element in {@link items} collection.
* @param savePrevious `true` if previously selected elements must stay selected after current selection.
*/
public selectIndex(index: number, savePrevious: boolean = false): void {
if (this.isIndexAcceptable(index)) {
this.selectItem(this.getSelectionTuple(index), savePrevious);
}
}
/**
* Deselects element at specified index in {@link items} collection.
* @param index index of element in {@link items} collection.
*/
public deselectIndex(index: number): void {
if (this.isIndexAcceptable(index)) {
this.deselectItem(this.getSelectionTuple(index));
}
}
/**
* Toggles selection of element at the specified index.
* @param index index of element in {@link items} collection.
* @param savePrevious `true` if previously selected elements must stay selected after current selection.
*/
public toggleSelection(index: number, savePrevious: boolean = false): void {
if (!this.isIndexAcceptable(index)) {
return;
}
const tuple = this.getSelectionTuple(index);
if (this.isIndexSelected(index) && (this.selectionsList.length === 1 || (this.selectionsList.length > 1 && savePrevious))) {
this.deselectItem(tuple);
return;
}
this.selectItem(tuple, savePrevious);
}
/**
* Returns all elements from {@link items} collection which are marked as selected.
* @returns collection of selected elements.
*/
public getSelectedElements(): any[] {
return this.selectionsList.map((selectionTuple: SelectionTuple) => selectionTuple.item);
}
/**
* Returns indexes of all elements from {@link items} collection which are marked as selected.
* @returns collection of selected elements indexes in {@link items} collection.
*/
public getSelectedIndexes(): number[] {
return this.selectionsList.map((selectionTuple: SelectionTuple) => selectionTuple.index);
}
/**
* Performs final processing of selection/deselection of element.
*/
public processSelection(tuple: SelectionTuple, selected: boolean): void {
if (Object.prototype.hasOwnProperty.call(tuple.item, 'selected')) {
tuple.item.selected = selected;
}
const initialSelectState = this.eventEmitters[tuple.index] ? this.eventEmitters[tuple.index].selected || null : null;
if (initialSelectState === null || initialSelectState !== selected) {
if (this.eventEmitters.length > tuple.index && this.eventEmitters[tuple.index]) {
this.emitEvents(this.eventEmitters[tuple.index], selected, tuple);
this.eventEmitters[tuple.index].postProcessSelection(selected);
}
if (this.areaEventsEmitter) {
this.emitEvents(this.areaEventsEmitter, selected, tuple);
}
}
}
/**
* Default tracking function that will be used if nothing was specified for {@link trackByFn}.
* Implements comparison by reference equality of objects.
*/
private trackByIdentity: (index: number, item: any) => any = (index: number, item: any) => item;
private deselectItem(selectionTuple: SelectionTuple): void {
const index = this.selectionsList.findIndex((selectedItem: SelectionTuple) => selectedItem.item === selectionTuple.item);
if (index !== -1) {
this.selectionsList.splice(index, 1);
}
this.processSelection(selectionTuple, false);
this.lastProcessedIndex = selectionTuple.index;
}
private selectItem(selectionTuple: SelectionTuple, savePrevious: boolean = false): void {
if (savePrevious) {
const index = this.selectionsList.findIndex((selectedItem: SelectionTuple) => selectedItem.item === selectionTuple.item);
if (index !== -1) {
this.selectionsList.splice(index, 1);
}
this.selectionsList.push(selectionTuple);
this.processSelection(selectionTuple, true);
} else {
const list = this.selectionsList.splice(0, this.selectionsList.length);
list.forEach((selectedItem: SelectionTuple) => {
this.processSelection(selectedItem, false);
});
this.selectionsList.push(selectionTuple);
this.processSelection(selectionTuple, true);
}
this.lastProcessedIndex = selectionTuple.index;
}
private getSelectionTuple(index: number): SelectionTuple {
return {
index,
item: this.items[index]
};
}
/**
* Selects all elements in {@link items} collection.
*/
public selectAll(recursive: boolean = true): void {
this.selectRange(0, this.items.length - 1);
// run this directly after render to give child selectionAreas ability to render
setTimeout(() => {
if (recursive && this.childSelectionServices) {
this.childSelectionServices.forEach(service => {
service.selectAll(recursive);
});
}
}, 0);
}
/**
* Deselects all elements in {@link items} collection.
*/
public deselectAll(recursive: boolean = true): void {
if (recursive && this.childSelectionServices) {
this.childSelectionServices.forEach(service => {
service.deselectAll(recursive);
});
}
const list = this.selectionsList.splice(0, this.selectionsList.length);
for (const item of list) {
this.processSelection(item, false);
}
this.lastProcessedIndex = null;
}
public emitEvents(emitter: SelectionEventsEmitter, selected: boolean, tuple: SelectionTuple): void {
if (selected) {
emitter.itemSelected.emit({ index: tuple.index, item: tuple.item });
} else {
emitter.itemDeselected.emit({ index: tuple.index, item: tuple.item });
}
emitter.selectionChanged.emit({ index: tuple.index, item: tuple.item });
}
} | the_stack |
import type * as es from 'elasticsearch';
import * as ts from '@terascope/utils';
import * as utils from './utils';
import { IndexConfig, MigrateIndexOptions } from './interfaces';
const _loggers = new WeakMap<IndexConfig<any>, ts.Logger>();
/**
* Manage Elasticsearch Indices
*/
export default class IndexManager {
readonly client: es.Client;
readonly esVersion: number;
enableIndexMutations: boolean;
constructor(client: es.Client, enableIndexMutations = ts.isTest) {
if (!utils.isValidClient(client)) {
throw new ts.TSError('IndexManager requires elasticsearch client', {
fatalError: true,
});
}
this.enableIndexMutations = enableIndexMutations;
this.esVersion = utils.getESVersion(client);
this.client = client;
}
/** Verify the index exists */
async exists(index: string): Promise<boolean> {
return this.client.indices.exists({
index,
});
}
/**
* Format the current index name.
*
* @param useWildcard if true a wildcard is added to the end of the end the index name
*/
formatIndexName<T = any>(config: IndexConfig<T>, useWildcard = true): string {
utils.validateIndexConfig(config);
const { name, namespace } = config;
const dataVersion = utils.getDataVersionStr(config);
const schemaVersion = utils.getSchemaVersionStr(config);
const indexName = utils.formatIndexName([namespace, name, dataVersion, schemaVersion]);
if (utils.isTimeSeriesIndex(config.index_schema) && !useWildcard) {
const timeSeriesFormat = utils.getRolloverFrequency(config);
return utils.timeSeriesIndex(indexName, timeSeriesFormat);
}
if (utils.isTemplatedIndex(config.index_schema) && useWildcard) {
return `${indexName}-*`;
}
return indexName;
}
/**
* Format the template name, similar to formatIndexName except it excludes
* template wildcards and the time series parts of the index name.
*/
formatTemplateName<T = any>(config: IndexConfig<T>): string {
utils.validateIndexConfig(config);
const { name, namespace } = config;
const indexName = utils.formatIndexName([
namespace, name, utils.getDataVersionStr(config)
]);
return indexName;
}
/**
* Safely setup a versioned Index, its template and any other required resources
*
* @returns a boolean that indicates whether the index was created or not
*/
async indexSetup<T>(config: IndexConfig<T>): Promise<boolean> {
utils.validateIndexConfig(config);
const indexName = this.formatIndexName(config, false);
const logger = this._logger(config);
const settings = Object.assign({}, config.index_settings);
logger.trace(`Using elasticsearch version ${this.esVersion}`);
const body: any = config.data_type.toESMapping({
typeName: config.name,
version: this.esVersion,
overrides: {
settings,
}
});
const enableMutations = (
this.enableIndexMutations || utils.isTimeSeriesIndex(config.index_schema)
);
if (enableMutations && utils.isTemplatedIndex(config.index_schema)) {
const templateName = this.formatTemplateName(config);
const schemaVersion = utils.getSchemaVersion(config);
body.template = templateName;
await this.upsertTemplate(
{
...body,
index_patterns: [this.formatIndexName(
// only use wildcard for timeseries indices
config, utils.isTimeSeriesIndex(config.index_schema)
)],
version: schemaVersion,
},
logger
);
}
if (await this.exists(indexName)) {
if (!enableMutations) {
logger.trace(`Index for config ${config.name} already exists`);
return false;
}
logger.info(`Index for config ${config.name} already exists, updating the mappings`);
await this.updateMapping(indexName, config.name, body, logger);
return false;
}
if (!enableMutations) {
throw new Error(
`Refusing to create index for config ${config.name} since mutations are disabled`
);
}
logger.info(`Creating index "${indexName}" for config ${config.name}...`);
try {
await this.client.indices.create(
utils.fixMappingRequest(
this.client,
{
index: indexName,
body,
},
false
)
);
} catch (err) {
const errStr = ts.parseError(err, true);
if (!errStr.includes('already_exists_exception')) {
throw err;
}
}
logger.trace(`Checking index availability for "${indexName}"...`);
await this.waitForIndexAvailability(indexName);
const isActive = await this.isIndexActive(indexName);
if (!isActive) {
throw new Error(`Index "${indexName}" is not active`);
}
logger.trace(`Index "${indexName}" is ready for use`);
return true;
}
async isIndexActive(index: string): Promise<boolean> {
const stats = await this.client.indices.recovery({ index });
if (ts.isEmpty(stats)) return false;
const getShardsPath = utils.shardsPath(index);
const shards = getShardsPath(stats);
return utils.verifyIndexShards(shards);
}
/**
* Perform an Index Migration
*
* **IMPORTANT** This is a potentially dangerous operation
* and should only when the cluster is properly shutdown.
*
* @todo add support for timeseries and templated indexes
* @todo add support for complicated re-indexing behaviors
*/
async migrateIndex<T>(options: MigrateIndexOptions<T>): Promise<any> {
const {
timeout, config, previousVersion, previousName, previousNamespace
} = options;
utils.validateIndexConfig(config);
const logger = this._logger(config);
let previousConfig = ts.cloneDeep(config);
if (!config.index_schema || !previousConfig.index_schema) {
logger.warn('Missing index_schema on config, skipping migration');
return false;
}
if (config.index_schema.timeseries || config.index_schema.template) {
logger.warn('Migrating timeseries or template indexes are currently not supported');
return false;
}
const newIndexName = this.formatIndexName(config);
if (previousName) {
previousConfig.name = previousName;
}
if (previousNamespace) {
previousConfig.namespace = previousNamespace;
}
if (previousVersion) {
previousConfig.index_schema.version = previousVersion;
} else {
// try and decrement the to last version
const _previousConfig = ts.cloneDeep(previousConfig);
_previousConfig.index_schema!.version!--;
if (_previousConfig.index_schema!.version! > 0) {
const _indexName = this.formatIndexName(_previousConfig);
const previousExists = await this.exists(_indexName);
const newExists = await this.exists(newIndexName);
if (previousExists && !newExists) {
previousConfig = _previousConfig;
}
}
}
const previousIndexName = this.formatIndexName(previousConfig);
await this.indexSetup(config);
if (newIndexName === previousIndexName) {
logger.warn(
`No changes detected for index ${newIndexName},`,
'if there are mapping changes make sure to bump index_schema.version'
);
return false;
}
logger.warn(`Reindexing the index ${previousIndexName} to ${newIndexName}`);
return this.client.reindex({
timeout,
waitForActiveShards: 'all',
waitForCompletion: true,
body: {
source: {
index: previousIndexName,
},
dest: {
index: newIndexName,
},
},
});
}
async getMapping(index: string): Promise<any> {
const params: any = { index };
if (this.esVersion === 7) {
params.includeTypeName = false;
}
return this.client.indices.getMapping(params);
}
async putMapping(index: string, type: string, properties: Record<string, any>): Promise<any> {
const params: any = {
index,
type,
body: {
properties,
},
};
if (this.esVersion >= 7) {
delete params.type;
params.includeTypeName = false;
}
return this.client.indices.putMapping(params);
}
/**
* Safely update a mapping
*
* **WARNING:** This only updates the mapping if it exists
*/
async updateMapping(
index: string, type: string, mapping: Record<string, any>, logger: ts.Logger
): Promise<void> {
const result = await this.getMapping(index);
const propertiesPath = this.esVersion >= 7 ? [
'mappings', 'properties'
] : ['mappings', type, 'properties'];
const existing = ts.get(result[index], propertiesPath, {});
const current = ts.get(mapping, propertiesPath, {});
let breakingChange = false;
let safeChange = false;
const cFlattened = utils.getFlattenedNamesAndTypes(current);
const eFlattened = utils.getFlattenedNamesAndTypes(existing);
logger.trace({
current: cFlattened,
existing: eFlattened
}, `flattened mapping changes for ${index}`);
const changes: [type: 'changed'|'removed'|'added', field: string][] = [];
for (const [field, [cType, cExtra]] of Object.entries(cFlattened)) {
const eConfig = eFlattened[field];
if (eConfig == null) {
safeChange = true;
changes.push(['added', field]);
} else {
const [eType, eExtra] = eConfig;
if (eType !== cType || eExtra !== cExtra) {
breakingChange = true;
changes.push(['changed', field]);
}
}
}
for (const field of Object.keys(eFlattened)) {
if (cFlattened[field] == null) {
changes.push(['removed', field]);
}
}
const changesList = changes.map(([changeType, field]) => `${changeType} field "${field}"`);
const changesInfo = changesList.length ? ` CHANGES: ${changesList.join(', ')}` : '';
if (breakingChange) {
throw new Error(`Index ${index} (${type}) has breaking change in the mapping, increment the schema version to fix this.${changesInfo}`);
}
if (safeChange) {
logger.info(`Detected mapping changes for ${index} (${type}).${changesInfo}`);
await this.putMapping(index, type, current);
return;
}
if (changesInfo) {
logger.info(`No major changes for ${index} (${type}).${changesInfo}`);
} else {
logger.info(`No changes for ${index} (${type}).${changesInfo}`);
}
}
async getTemplate(name: string, flatSettings: boolean): Promise<Record<string, any>> {
const params: any = { name, flatSettings };
if (this.esVersion === 7) {
params.includeTypeName = false;
}
return this.client.indices.getTemplate(params);
}
/**
* Safely create or update a template
*/
async upsertTemplate(
template: Record<string, any>, logger?: ts.Logger
): Promise<void> {
const { template: name, version } = template;
try {
const templates = await this.getTemplate(name, true);
const latestVersion = templates[name].version;
if (version === latestVersion) return;
} catch (err) {
if (err.statusCode !== 404) {
throw err;
}
}
const params = utils.fixMappingRequest(
this.client,
{
body: template,
name,
},
true
);
if (logger) {
logger.debug(`Upserting template "${name}"...`, params);
}
await this.client.indices.putTemplate(params);
}
protected async waitForIndexAvailability(index: string): Promise<void> {
const query = {
index,
q: '',
size: 0,
terminate_after: '1',
};
await ts.pRetry(() => this.client.search(query), utils.getRetryConfig());
}
private _logger<T>(config: IndexConfig<T>): ts.Logger {
if (config.logger) return config.logger;
const logger = _loggers.get(config);
if (logger) return logger;
const debugLoggerName = `elasticsearch-store:index-manager:${config.name}`;
const newLogger = ts.debugLogger(debugLoggerName);
_loggers.set(config, newLogger);
return newLogger;
}
} | the_stack |
import {
ArrayExt
} from '@lumino/algorithm';
import {
Menu
} from '@lumino/widgets';
import {
IDisposable
} from '@lumino/disposable';
import {
JupyterLab
} from '@jupyterlab/application';
import {
INativeMenu
} from '../../../main/menu';
import {
asyncRemoteRenderer
} from '../../../asyncremote';
import {
IMainMenu, FileMenu, EditMenu, ViewMenu, HelpMenu, KernelMenu, RunMenu, SettingsMenu, TabsMenu
} from '@jupyterlab/mainmenu';
/**
* The main menu class. Interacts with the electron main process
* to setup native menu bar.
*/
export
class NativeMenu implements IMainMenu {
constructor(private app: JupyterLab) {
// Register click event listener
asyncRemoteRenderer.onRemoteEvent(INativeMenu.clickEvent, (opts) => {
if (opts.command === INativeMenu.launchNewEnvironment.id) {
asyncRemoteRenderer.runRemoteMethod(INativeMenu.launchNewEnvironment, opts);
} else if (this.app.commands.hasCommand(opts.command)) {
return this.app.commands.execute(opts.command, opts.args);
} else {
return Promise.reject(new Error(`Command (${opts.command}) not found`));
}
});
let commands = app.commands;
this.editMenu = new NativeEditMenu({ commands });
this.fileMenu = new NativeFileMenu({ commands });
this.helpMenu = new NativeHelpMenu({ commands });
this.kernelMenu = new NativeKernelMenu({ commands });
this.runMenu = new NativeRunMenu({ commands });
this.settingsMenu = new NativeSettingsMenu({ commands });
this.viewMenu = new NativeViewMenu({ commands });
this.tabsMenu = new NativeTabsMenu({ commands });
this.addMenu(this.fileMenu.menu, { rank: 0 });
this.addMenu(this.editMenu.menu, { rank: 1 });
this.addMenu(this.viewMenu.menu, { rank: 2 });
this.addMenu(this.runMenu.menu, { rank: 3 });
this.addMenu(this.kernelMenu.menu, { rank: 4 });
this.addMenu(this.tabsMenu.menu, { rank: 500 });
this.addMenu(this.settingsMenu.menu, { rank: 999 });
this.addMenu(this.helpMenu.menu, { rank: 1000 });
asyncRemoteRenderer.runRemoteMethod(INativeMenu.finalizeMenubar, undefined);
}
/**
* Add PhosphorJS menu to native menu bar.
*
* @param menu PhosphorJS menu to add to menu bar
* @param options Menu options
*/
addMenu(menu: Menu, options: IMainMenu.IAddOptions = {}): Promise<void> {
if (ArrayExt.findFirstIndex(this._items, (item, idx) => item.menu === menu) > -1) {
return;
}
let rank = 'rank' in options ? options.rank : 100;
let rankItem = { menu, rank };
let index = ArrayExt.upperBound(this._items, rankItem, Private.itemCmp);
// Upon disposal, remove the menu and its rank reference.
menu.disposed.connect(this._onMenuDisposed, this);
let menuItem: INativeMenu.IMenuItemOptions = {
rank: rank,
label: menu.title.label,
submenu: buildNativeMenu(menu),
};
ArrayExt.insert(this._items, index, rankItem);
/* Add the menu to the native menu */
return asyncRemoteRenderer.runRemoteMethod(INativeMenu.addMenu, menuItem);
}
/**
* Dispose of the resources held by the menu bar.
*/
dispose(): void {
this.editMenu.dispose();
this.fileMenu.dispose();
this.helpMenu.dispose();
this.kernelMenu.dispose();
this.runMenu.dispose();
this.settingsMenu.dispose();
this.viewMenu.dispose();
this.tabsMenu.dispose();
}
/**
* Handle the disposal of a menu.
*/
private _onMenuDisposed(menu: Menu): void {
let index = ArrayExt.findFirstIndex(this._items, item => item.menu === menu);
if (index !== -1) {
ArrayExt.removeAt(this._items, index);
}
}
private _items: Private.IRankItem[] = [];
/**
* The application "Edit" menu.
*/
readonly editMenu: NativeEditMenu;
/**
* The application "File" menu.
*/
readonly fileMenu: NativeFileMenu;
/**
* The application "Help" menu.
*/
readonly helpMenu: NativeHelpMenu;
/**
* The application "Kernel" menu.
*/
readonly kernelMenu: NativeKernelMenu;
/**
* The application "Run" menu.
*/
readonly runMenu: NativeRunMenu;
/**
* The application "Settings" menu.
*/
readonly settingsMenu: NativeSettingsMenu;
/**
* The application "View" menu.
*/
readonly viewMenu: NativeViewMenu;
/**
* The application "Tabs" menu.
*/
readonly tabsMenu: NativeTabsMenu;
}
class NativeEditMenu extends EditMenu {
constructor(options: Menu.IOptions) {
super(options);
}
addGroup(items: Menu.IItemOptions[], rank?: number): IDisposable {
const added = super.addGroup(items, rank);
let menuItem: INativeMenu.IMenuItemOptions = {
label: this.menu.title.label,
submenu: buildNativeMenu(this.menu)
};
asyncRemoteRenderer.runRemoteMethod(INativeMenu.updateMenu, menuItem);
return added;
}
}
class NativeFileMenu extends FileMenu {
constructor(options: Menu.IOptions) {
super(options);
}
addGroup(items: Menu.IItemOptions[], rank?: number): IDisposable {
const res = super.addGroup(items, rank);
let menuItem: INativeMenu.IMenuItemOptions = {
label: this.menu.title.label,
submenu: buildNativeMenu(this.menu)
};
asyncRemoteRenderer.runRemoteMethod(INativeMenu.updateMenu, menuItem);
return res;
}
}
class NativeHelpMenu extends HelpMenu {
constructor(options: Menu.IOptions) {
super(options);
}
addGroup(items: Menu.IItemOptions[], rank?: number): IDisposable {
const added = super.addGroup(items, rank);
let menuItem: INativeMenu.IMenuItemOptions = {
label: this.menu.title.label,
submenu: buildNativeMenu(this.menu)
};
asyncRemoteRenderer.runRemoteMethod(INativeMenu.updateMenu, menuItem);
return added;
}
}
class NativeKernelMenu extends KernelMenu {
constructor(options: Menu.IOptions) {
super(options);
}
addGroup(items: Menu.IItemOptions[], rank?: number): IDisposable {
const added = super.addGroup(items, rank);
let menuItem: INativeMenu.IMenuItemOptions = {
label: this.menu.title.label,
submenu: buildNativeMenu(this.menu)
};
asyncRemoteRenderer.runRemoteMethod(INativeMenu.updateMenu, menuItem);
return added;
}
}
class NativeRunMenu extends RunMenu {
constructor(options: Menu.IOptions) {
super(options);
}
addGroup(items: Menu.IItemOptions[], rank?: number): IDisposable {
const res = super.addGroup(items, rank);
let menuItem: INativeMenu.IMenuItemOptions = {
label: this.menu.title.label,
submenu: buildNativeMenu(this.menu)
};
asyncRemoteRenderer.runRemoteMethod(INativeMenu.updateMenu, menuItem);
return res;
}
}
class NativeSettingsMenu extends SettingsMenu {
constructor(options: Menu.IOptions) {
super(options);
}
addGroup(items: Menu.IItemOptions[], rank?: number): IDisposable {
const res = super.addGroup(items, rank);
let menuItem: INativeMenu.IMenuItemOptions = {
label: this.menu.title.label,
submenu: buildNativeMenu(this.menu)
};
asyncRemoteRenderer.runRemoteMethod(INativeMenu.updateMenu, menuItem);
return res;
}
}
class NativeViewMenu extends ViewMenu {
constructor(options: Menu.IOptions) {
super(options);
}
addGroup(items: Menu.IItemOptions[], rank?: number): IDisposable {
const res = super.addGroup(items, rank);
let menuItem: INativeMenu.IMenuItemOptions = {
label: this.menu.title.label,
submenu: buildNativeMenu(this.menu)
};
asyncRemoteRenderer.runRemoteMethod(INativeMenu.updateMenu, menuItem);
return res;
}
}
class NativeTabsMenu extends TabsMenu {
constructor(options: Menu.IOptions) {
super(options);
}
addGroup(items: Menu.IItemOptions[], rank?: number): IDisposable {
const res = super.addGroup(items, rank);
let menuItem: INativeMenu.IMenuItemOptions = {
label: this.menu.title.label,
submenu: buildNativeMenu(this.menu)
};
asyncRemoteRenderer.runRemoteMethod(INativeMenu.updateMenu, menuItem);
return res;
}
}
/**
* Convert phosphorJS menu configuration to a native electron
* menu configuration.
*
* @param menu The phosphorJS menu object
*
* @return Array of electron menu items representing menu item
* drop down contents
*/
function buildNativeMenu(menu: Menu): INativeMenu.IMenuItemOptions[] {
let items = menu.items;
let nItems = new Array<INativeMenu.IMenuItemOptions>(items.length);
for (let i = 0; i < items.length; i++) {
nItems[i] = { command: null, type: null, label: null, submenu: null, accelerator: null };
if (items[i].type === 'command') {
nItems[i].type = 'normal';
} else {
nItems[i].type = (items[i].type as 'normal' | 'submenu' | 'separator');
}
nItems[i].label = items[i].label;
nItems[i].command = items[i].command;
nItems[i].args = items[i].args;
// Dynmaic values will need to wait for a better native menu system
// nItems[i].checked = items[i].isToggled;
// nItems[i].enabled = !items[i].isEnabled;
if (items[i].submenu !== null) {
nItems[i].submenu = buildNativeMenu(items[i].submenu);
}
}
return dedupSeparatorsMenu(nItems);
}
function dedupSeparatorsMenu(arr: INativeMenu.IMenuItemOptions[]): INativeMenu.IMenuItemOptions[] {
// Setting to true initially so that leading separators will be removed
let lastWasSeparator = true;
let filterItems = arr.filter((menuItem, idx, arr) => {
if (lastWasSeparator) {
if (menuItem.type === 'separator') {
return false;
} else {
lastWasSeparator = false;
return true;
}
} else {
if (menuItem.type === 'separator') {
lastWasSeparator = true;
}
return true;
}
});
// If the last item was a separator, remove it
if (lastWasSeparator) {
filterItems.pop();
}
return filterItems;
}
/**
* A namespace for private data.
*/
namespace Private {
/**
* An object which holds a menu and its sort rank.
*/
export
interface IRankItem {
/**
* The menu for the item.
*/
menu: Menu;
/**
* The sort rank of the menu.
*/
rank: number;
}
/**
* A comparator function for menu rank items.
*/
export
function itemCmp(first: IRankItem, second: IRankItem): number {
return first.rank - second.rank;
}
} | the_stack |
import React from 'react'
import Base1DView, { Base1DViewModel } from '@jbrowse/core/util/Base1DViewModel'
import { getSession } from '@jbrowse/core/util'
import { makeStyles, useTheme } from '@material-ui/core/styles'
import { alpha } from '@material-ui/core/styles'
import LinearProgress from '@material-ui/core/LinearProgress'
import { ContentBlock } from '@jbrowse/core/util/blockTypes'
import { observer } from 'mobx-react'
import { Instance } from 'mobx-state-tree'
import clsx from 'clsx'
import { Typography } from '@material-ui/core'
import {
LinearGenomeViewStateModel,
HEADER_BAR_HEIGHT,
HEADER_OVERVIEW_HEIGHT,
} from '..'
import { chooseGridPitch } from '../util'
import OverviewRubberBand from './OverviewRubberBand'
const useStyles = makeStyles(theme => {
const scaleBarColor = theme.palette.tertiary
? theme.palette.tertiary.light
: theme.palette.primary.light
return {
scaleBar: {
width: '100%',
height: HEADER_OVERVIEW_HEIGHT,
overflow: 'hidden',
},
scaleBarContig: {
backgroundColor: theme.palette.background.default,
position: 'absolute',
top: 0,
height: HEADER_OVERVIEW_HEIGHT,
border: '1px solid',
borderBottomColor: 'black',
},
scaleBarContigForward: {
backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 15 9'%3E%3Cpath d='M-.1 0L6 4.5L-.1 9' fill='none' stroke='%23ddd'/%3E%3C/svg%3E")`,
backgroundRepeat: 'repeat',
},
scaleBarContigReverse: {
backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 15 9'%3E%3Cpath d='M6 0L0 4.5L6 9' fill='none' stroke='%23ddd'/%3E%3C/svg%3E")`,
backgroundRepeat: 'repeat',
},
scaleBarRegionIncompleteLeft: {
width: 10,
height: 17.5,
background: `linear-gradient(-225deg,black 3px, transparent 1px),
linear-gradient(45deg, black 3px, transparent 1px)`,
backgroundRepeat: 'repeat-y',
backgroundSize: '10px 8px',
borderTopLeftRadius: '2px',
borderBottomLeftRadius: '2px',
float: 'left',
},
scaleBarRegionIncompleteRight: {
width: 10,
height: 17.5,
background: `linear-gradient(225deg, black 3px, transparent 1px),
linear-gradient(-45deg, black 3px, transparent 1px)`,
backgroundRepeat: 'repeat-y',
backgroundSize: '10px 8px',
borderTopRightRadius: '2px',
borderBottomRightRadius: '2px',
float: 'right',
},
scaleBarRefName: {
position: 'absolute',
fontWeight: 'bold',
lineHeight: 'normal',
pointerEvents: 'none',
left: 5,
},
scaleBarLabel: {
height: HEADER_OVERVIEW_HEIGHT,
width: 1,
position: 'absolute',
display: 'flex',
justifyContent: 'center',
pointerEvents: 'none',
},
scaleBarVisibleRegion: {
background: alpha(scaleBarColor, 0.3),
position: 'absolute',
height: HEADER_OVERVIEW_HEIGHT,
pointerEvents: 'none',
top: -1,
zIndex: 100,
borderWidth: 1,
borderStyle: 'solid',
borderColor: alpha(scaleBarColor, 0.8),
boxSizing: 'content-box',
},
overview: {
height: HEADER_BAR_HEIGHT,
position: 'relative',
},
overviewSvg: { position: 'absolute' },
}
})
const wholeSeqSpacer = 2
const Polygon = observer(
({
model,
overview,
}: {
model: LGV
overview: Instance<Base1DViewModel>
}) => {
const theme = useTheme()
const classes = useStyles()
const {
offsetPx,
dynamicBlocks: { contentBlocks, totalWidthPxWithoutBorders },
} = model
const polygonColor = theme.palette.tertiary
? theme.palette.tertiary.light
: theme.palette.primary.light
if (!contentBlocks.length) {
return null
}
const firstBlock = contentBlocks[0]
const lastBlock = contentBlocks[contentBlocks.length - 1]
const topLeft = overview.bpToPx({
refName: firstBlock.refName,
coord: firstBlock.reversed ? firstBlock.end : firstBlock.start,
regionNumber: firstBlock.regionNumber,
})
const topRight = overview.bpToPx({
refName: lastBlock.refName,
coord: lastBlock.reversed ? lastBlock.start : lastBlock.end,
regionNumber: lastBlock.regionNumber,
})
const startPx = Math.max(0, -offsetPx)
const endPx =
startPx +
totalWidthPxWithoutBorders +
(contentBlocks.length * model.interRegionPaddingWidth) / 2
const points = [
[startPx, HEADER_BAR_HEIGHT],
[endPx, HEADER_BAR_HEIGHT],
[topRight, 0],
[topLeft, 0],
]
return (
<svg
height={HEADER_BAR_HEIGHT}
width="100%"
className={classes.overviewSvg}
>
{points && (
<polygon
points={points.toString()}
fill={alpha(polygonColor, 0.3)}
stroke={alpha(polygonColor, 0.8)}
/>
)}
</svg>
)
},
)
type LGV = Instance<LinearGenomeViewStateModel>
const ScaleBar = observer(
({
model,
scale,
overview,
}: {
model: LGV
overview: Base1DViewModel
scale: number
}) => {
const classes = useStyles()
const { dynamicBlocks: visibleRegions } = model
const { assemblyManager } = getSession(model)
const gridPitch = chooseGridPitch(scale, 120, 15)
const { dynamicBlocks: overviewVisibleRegions } = overview
if (!visibleRegions.contentBlocks.length) {
return null
}
const firstBlock = visibleRegions.contentBlocks[0]
const firstOverviewPx =
overview.bpToPx({
refName: firstBlock.refName,
regionNumber: firstBlock.regionNumber,
coord: firstBlock.reversed ? firstBlock.end : firstBlock.start,
}) || 0
const lastBlock =
visibleRegions.contentBlocks[visibleRegions.contentBlocks.length - 1]
const lastOverviewPx =
overview.bpToPx({
refName: lastBlock.refName,
coord: lastBlock.reversed ? lastBlock.start : lastBlock.end,
regionNumber: lastBlock.regionNumber,
}) || 0
return (
<div className={classes.scaleBar}>
<div
className={classes.scaleBarVisibleRegion}
style={{
width: lastOverviewPx - firstOverviewPx,
left: firstOverviewPx,
}}
/>
{/* this is the entire scale bar */}
{overviewVisibleRegions.map((seq, idx) => {
const assembly = assemblyManager.get(seq.assemblyName)
let refNameColor: string | undefined
if (assembly) {
refNameColor = assembly.getRefNameColor(seq.refName)
}
const regionLength = seq.end - seq.start
const tickLabels = []
for (
let index = 0;
index < Math.floor(regionLength / gridPitch.majorPitch);
index++
) {
const offsetLabel = (index + 1) * gridPitch.majorPitch
tickLabels.push(
seq.reversed ? seq.end - offsetLabel : seq.start + offsetLabel,
)
}
return !(seq instanceof ContentBlock) ? (
<div
key={`${JSON.stringify(seq)}-${idx}`}
className={classes.scaleBarContig}
style={{
width: seq.widthPx,
left: seq.offsetPx,
backgroundColor: '#999',
backgroundImage:
'repeating-linear-gradient(90deg, transparent, transparent 1px, rgba(255,255,255,.5) 1px, rgba(255,255,255,.5) 3px)',
}}
/>
) : (
<div
key={`${JSON.stringify(seq)}-${idx}`}
className={clsx(
classes.scaleBarContig,
seq.reversed
? classes.scaleBarContigReverse
: classes.scaleBarContigForward,
)}
style={{
left: seq.offsetPx,
width: seq.widthPx,
borderColor: refNameColor,
}}
>
{/* name of sequence */}
<Typography
style={{
color: refNameColor,
zIndex: 100,
}}
className={classes.scaleBarRefName}
>
{seq.refName}
</Typography>
{/* the number labels drawn in overview scale bar*/}
{tickLabels.map((tickLabel, labelIdx) => (
<Typography
key={`${JSON.stringify(seq)}-${tickLabel}-${labelIdx}`}
className={classes.scaleBarLabel}
variant="body2"
style={{
left: ((labelIdx + 1) * gridPitch.majorPitch) / scale,
pointerEvents: 'none',
color: refNameColor,
}}
>
{tickLabel.toLocaleString('en-US')}
</Typography>
))}
</div>
)
})}
</div>
)
},
)
function OverviewScaleBar({
model,
children,
}: {
model: LGV
children: React.ReactNode
}) {
const classes = useStyles()
const { width, displayedRegions } = model
const overview = Base1DView.create({
displayedRegions: JSON.parse(JSON.stringify(displayedRegions)),
interRegionPaddingWidth: 0,
minimumBlockWidth: model.minimumBlockWidth,
})
overview.setVolatileWidth(width)
overview.showAllRegions()
const scale =
model.totalBp / (width - (displayedRegions.length - 1) * wholeSeqSpacer)
return !displayedRegions.length ? (
<>
<div className={classes.scaleBar}>
<LinearProgress
variant="indeterminate"
style={{ marginTop: 4, width: '100%' }}
/>
</div>
<div>{children}</div>
</>
) : (
<div>
<OverviewRubberBand
model={model}
overview={overview}
ControlComponent={
<ScaleBar model={model} overview={overview} scale={scale} />
}
/>
<div className={classes.overview}>
<Polygon model={model} overview={overview} />
{children}
</div>
</div>
)
}
export default observer(OverviewScaleBar) | the_stack |
// taze: $, JQuery from //third_party/javascript/typings/jquery:jquery_without_externs
// taze: jstree from //third_party/javascript/typings/jstree:jstree
import {Component, ElementRef, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {MatDialog} from '@angular/material/dialog';
import {MatSlideToggleChange} from '@angular/material/slide-toggle';
import {MatSnackBar} from '@angular/material/snack-bar';
// to backend.
import {v4 as uuid} from 'uuid';
import {ReplaySubject} from 'rxjs';
import {filter, take, takeUntil} from 'rxjs/operators';
import {MessageTypes, POPUP_DIALOG_DEFAULT_DIMENSION, SNACKBAR_DURATION_MS} from '../constants/constants';
import {JsTreeAction, JsTreeInternalNode, JsTreeNode, NodeAttribute} from '../constants/jstree';
import {Rect} from '../constants/rect';
import {BackendManagerService} from '../services/backend_manager_service';
import {ControlMessage, ControlMessageService} from '../services/control_message_service';
import {CopyXmlDialog} from './copy_xml_dialog';
const ICON_CLASSES: {[key: string]: string} = {
'hierarchy': 'fa fa-sitemap',
'FrameLayout': 'fa fa-object-group',
'ViewGroup': 'fa fa-users',
'TextView': 'fa fa-file-text',
'LinearLayout': 'fa fa-bars',
'RelativeLayout': 'fa fa-object-ungroup',
'GridLayout': 'fa fa-th',
'View': 'fa fa-window-maximize',
'ImageView': 'fa fa-picture-o',
'default': 'fa fa-folder'
};
interface BoundElement {
id: string;
bound: Rect;
}
declare var $: any;
/**
* Component responsible for drawing and interacting with UI tree XML of device
* screen.
*/
@Component({
selector: 'ui-tree-viewer',
templateUrl: './ui_tree_viewer.ng.html',
styleUrls: ['./ui_tree_viewer.css']
})
export class UiTreeViewer implements OnInit, OnDestroy {
@ViewChild('jsTree', {static: true}) jsTreeEl!: ElementRef;
readonly destroyed = new ReplaySubject<void>(1);
readonly domParser = new DOMParser();
jsTree!: any;
searchStr = '';
rawXML = '';
searchType = 'ALL';
searchTypes = ['ALL'];
searchSuccess = false;
showAttributes = true;
highlightMode = false;
attributes: NodeAttribute[] = [];
nodeBounds: BoundElement[] = [];
constructor(
private readonly dialog: MatDialog,
private readonly snackBar: MatSnackBar,
private readonly backendManagerService: BackendManagerService,
private readonly controlMessageService: ControlMessageService,
) {}
ngOnInit() {
this.setupDataTree();
this.controlMessageService.getControlMessageSubject()
.pipe(
takeUntil(this.destroyed),
filter(
(msg: ControlMessage) =>
msg.messageType === MessageTypes.INSPECT_CLICKED_NODE))
.subscribe((msg: ControlMessage) => {
// `unknown`.
// tslint:disable:no-any no-unnecessary-type-assertion
const coor: Rect = JSON.parse(msg.extra) as any;
// tslint:enable:no-any no-unnecessary-type-assertion
const smallestContainingNode =
this.nodeBounds.filter(el => el.bound.contains(coor))
.reduce((prev, curr) => {
if (prev.bound.area() > curr.bound.area()) {
return curr;
}
return prev;
});
if (smallestContainingNode) {
this.jsTree.jstree('deselect_all');
this.focusNode(smallestContainingNode.id);
}
});
this.fetchXML();
}
setupDataTree() {
const jsTreeObj: any = $(this.jsTreeEl.nativeElement);
this.jsTree = jsTreeObj.jstree({
'core': {
'themes': {
'dots': false,
},
'data': {},
},
'search': {
'case_insensitive': true,
'search_callback': this.jsTreeSearchCB.bind(this),
},
'plugins': ['search', 'wholerow'],
});
this.buildSelectEvent();
this.buildSearchCompleteEvent();
this.buildHoverEvent();
this.buildDehoverEvent();
}
buildHoverEvent() {
this.jsTree.on('hover_node.jstree', (e: unknown, action: JsTreeAction) => {
if (this.highlightMode) {
this.sendDrawMessage(
MessageTypes.NODE_HOVERED, action.node.original.attributes);
}
});
}
sendDrawMessage(messageType: MessageTypes, attributes?: NodeAttribute[]) {
if (attributes) {
const coordinates = attributes.find(el => el.name === 'bounds');
if (coordinates && coordinates.value) {
this.controlMessageService.sendMessage(
{messageType, extra: coordinates.value});
}
}
}
buildDehoverEvent() {
this.jsTree.on(
'dehover_node.jstree', (e: unknown, action: JsTreeAction) => {
if (this.highlightMode) {
this.controlMessageService.sendMessage(
{messageType: MessageTypes.CLEAR_CANVAS, extra: ''});
}
});
}
buildSelectEvent() {
this.jsTree.on('select_node.jstree', (e: unknown, action: JsTreeAction) => {
const attr = action.node.original.attributes;
if (attr != null) {
this.attributes = attr;
if (this.highlightMode) {
this.sendDrawMessage(
MessageTypes.NODE_SELECTED, action.node.original.attributes);
}
}
});
}
buildSearchCompleteEvent() {
this.jsTree.on('search.jstree', () => {
if (!this.searchSuccess) {
this.snackBar.open(
'No matches found', 'OK', {duration: SNACKBAR_DURATION_MS});
}
this.searchSuccess = false;
});
}
getJsTreeInstance(): any {
// jstree(true) returns an existing instance instead of creating a new
// instance.
return this.jsTree.jstree(true);
}
updateDataTree(jsTreeNode: JsTreeNode[]) {
// 'settings' is an internal field that contains some desired jstree
// properties.
this.getJsTreeInstance()['settings'].core.data = jsTreeNode;
this.getJsTreeInstance().refresh(
/* skip_loading */ false, /* forget_state */ true);
}
fetchXML() {
this.controlMessageService.sendMessage(
{messageType: MessageTypes.CLEAR_CANVAS, extra: 'all'});
this.nodeBounds = [];
this.searchTypes = ['ALL'];
this.backendManagerService.fetchXML()
.pipe(take(1), takeUntil(this.destroyed))
.subscribe(data => {
const treeData: JsTreeNode[] = [];
this.rawXML = data.join();
for (const line of data) {
const domObj = this.domParser.parseFromString(line, 'text/xml');
const obj = domObj.getElementsByTagName('hierarchy');
treeData.push(this.convertXMLToJSTreeNode(obj[0]));
}
this.updateDataTree(treeData);
});
}
/*
* Example XML(for reference):
* <hierarchy>
* <node index="0" text="" class="android.widget.FrameLayout"
* package="com.android.systemui" content-desc="" checkable="false"
* checked="false" clickable="false" enabled="true" focusable="false"
* focused="false" scrollable="false" long-clickable="false" password="false"
* selected="false" bounds="[0,0][1080,2028]" resource-id="">
* <node index="0" text="" class="android.view.View"
* package="com.android.systemui" content-desc="" checkable="false"
* checked="false" clickable="false" enabled="true" focusable="false"
* focused="false" scrollable="false" long-clickable="false"
* password="false" selected="false" bounds="[0,0][1080,2028]"
* resource-id="com.android.systemui:id/scrim_behind"/>
* </node>
* </hierarchy>
*/
convertXMLToJSTreeNode(xmlNode: Element): JsTreeNode {
let text = xmlNode.className;
if (text === '') {
text = xmlNode.tagName;
}
text = text.replace(/.+\..+\./, '');
const id = uuid();
const node = new JsTreeNode(text, id);
if (ICON_CLASSES.hasOwnProperty(text)) {
node.icon = ICON_CLASSES[text];
}
node.attributes = [];
for (const attr in xmlNode.attributes) {
if (!isNaN(Number(attr))) {
const name = xmlNode.attributes[attr]['name'];
const value = xmlNode.attributes[attr]['value'];
node.attributes.push({name, value});
if (this.searchTypes.indexOf(name) < 0) {
this.searchTypes.push(name);
}
if (name === 'bounds') {
this.nodeBounds.push(
{id, bound: Rect.createFromCoordinatesStr(value)});
}
}
}
xmlNode.childNodes.forEach(child => {
node.children.push(this.convertXMLToJSTreeNode(child as Element));
});
return node;
}
focusNode(nodeId: string) {
this.jsTree.jstree('select_node', nodeId);
this.getJsTreeInstance()
.get_node(nodeId, true)
.children('jstree-anchor')
.focus();
}
jsTreeSearchCB(text: string, node: JsTreeInternalNode) {
const lowerCaseText = text.toLowerCase();
if (node.original.attributes) {
for (const attr of node.original.attributes) {
if (this.searchType !== 'ALL' && this.searchType !== attr.name) {
continue;
}
if (!attr.value || !attr.value.toLowerCase().includes(lowerCaseText)) {
continue;
}
this.searchSuccess = true;
this.focusNode(node.id);
}
}
}
toggleHighlight(e: MatSlideToggleChange) {
this.highlightMode = e.checked;
if (!this.highlightMode) {
this.controlMessageService.sendMessage(
{messageType: MessageTypes.CLEAR_CANVAS, extra: 'all'});
}
}
toggleInspectDevice(e: MatSlideToggleChange) {
this.controlMessageService.sendMessage({
messageType: MessageTypes.SET_INSPECT_MODE,
extra: e.checked.toString()
});
}
toggleAttributes(e: MatSlideToggleChange) {
this.showAttributes = e.checked;
}
expandAll() {
this.jsTree.jstree('open_all');
}
closeAll() {
this.jsTree.jstree('close_all');
}
showXML() {
this.dialog.open(CopyXmlDialog, {
width: POPUP_DIALOG_DEFAULT_DIMENSION.width,
height: POPUP_DIALOG_DEFAULT_DIMENSION.height,
data: this.rawXML
});
}
searchTree() {
this.jsTree.jstree('deselect_all');
this.jsTree.jstree('search', this.searchStr);
}
ngOnDestroy() {
this.controlMessageService.sendMessage(
{messageType: MessageTypes.CLEAR_CANVAS, extra: 'all'});
this.controlMessageService.sendMessage({
messageType: MessageTypes.SET_INSPECT_MODE,
extra: 'false',
});
this.destroyed.next();
}
} | the_stack |
import {VComponent} from "./VisualComponent";
import * as d3 from 'd3'
import {includes} from "lodash";
import {ZoomTransform} from "d3-zoom";
import * as concaveman from "concaveman"
export type NeighborDetail = {
indexID: number, distance: number, refTransID: number, refWordID: number
}
export type StateDesc = {
id: number,
occ: number[][] | null,
pivot: { trans_ID: number, word_ID: number } | null,
pos: number[]
}
export interface StateProjectorData {
states: StateDesc[],
loc: string,
labels?: string[][],
moreNeighbors?: number[][][]
}
export type StateProjectorClickEvent = {
loc: string,
pointIDs: number[],
neighborIDs: number[],
caller: StateProjector
}
export type StateProjectorHoverEvent = {
loc: string,
transID: number,
wordID: number,
caller: StateProjector,
hovered: boolean
}
export class StateProjector extends VComponent<StateProjectorData> {
css_name = 'stateprojector';
static events = {
clicked: 'state_projector_clicked',
hovered: 'state_projector_hovered'
};
protected options = {
pos: {x: 0, y: 0},
css_class_main: 'state_projector',
keepAspectRatio: false
};
protected _current = {
hidden: false,
xScale: d3.scaleLinear(),
yScale: d3.scaleLinear(),
zoom: null,
noOfLines: 1,
pivots: <StateDesc[][]>[[]],
loc: 'src',
pivotNeighbors: <{ [key: number]: { [key: number]: StateDesc[] } }> {},
project: {w: 500, h: 500},
zoomTransform: d3.zoomIdentity,
hasLabels: false,
moreNeighbors: <number[][][]>null,
hideNN: false
};
data: StateProjectorData;
// readonly getter
get current() {
return this._current
}
get states(): StateDesc[] {
return this.data.states;
}
get loc(): string {
return this.current.loc;
}
get labels(): string[][] {
return this.data.labels;
}
constructor(d3Parent, eventHandler?, options: {} = {}) {
super(d3Parent, eventHandler);
this.superInit(options, true)
}
protected _init() {
const zoom = d3.zoom()
// .filter(() => (<MouseEvent>d3.event).shiftKey)
.scaleExtent([1 / 2, 4])
.on("zoom", () => this._zoomLayers((<d3.D3ZoomEvent<any, any>>d3.event).transform));
this._current.zoom = zoom;
this.layers.bg.append("rect")
.attr('id', 'zoomRect')
.attr("width", 100)
.attr("height", 100)
.style("fill", "none")
.style("pointer-events", "all")
.call(zoom)
.on("dblclick.zoom", () =>
this.base.select('#zoomRect')
.transition().duration(200)
.call(<any>zoom.transform, d3.zoomIdentity));
}
protected _zoomLayers(transform: ZoomTransform) {
this._current.zoomTransform = transform;
// console.log(transform, "--- transform");
this.layers.fg.attr('transform', transform.toString());
this.layers.main.attr('transform', transform.toString());
const f = 1. / Math.sqrt(transform.k);
const plR = 5 * f;
this.layers.fg.selectAll('.plPoint').attr('r', plR);
const w = 2 * f;
this.layers.fg.selectAll('.pl')
.style('stroke-width', w + 'px');
}
protected static neighborDetails(occ: number[][]): NeighborDetail[] {
return occ.map(oc => {
const [indexID, distance, refTransID, refWordID] = oc;
return {indexID, distance, refTransID, refWordID}
})
}
protected _wrangle(data: StateProjectorData) {
const op = this.options;
const cur = this._current;
const nDetails = StateProjector.neighborDetails;
if (data.moreNeighbors) {
cur.moreNeighbors = data.moreNeighbors;
}
/*======================================
determine scales and positions
=======================================*/
const st = data.states;
let [minX, maxX] = d3.extent(st.map(d => d.pos[0]));
let [minY, maxY] = d3.extent(st.map(d => d.pos[1]));
let diffX = maxX - minX;
let diffY = maxY - minY;
if (op.keepAspectRatio) {
if (diffX > diffY) {
// noinspection JSSuspiciousNameCombination
diffY = diffX
} else {
// noinspection JSSuspiciousNameCombination
diffX = diffY
}
}
cur.xScale.domain([minX, minX + diffX]).range([10, cur.project.w - 10]);
cur.yScale.domain([minY, minY + diffY]).range([10, cur.project.h - 10]);
/*======================================
determine neighbor information
=======================================*/
cur.loc = data.loc;
cur.pivotNeighbors = {};
// go through all non-pivot state and make them 'neighbors' to their reference
// translation and word
st.filter(d => !d.pivot).forEach(me =>
nDetails(me.occ).forEach(occ => {
const wordList = cur.pivotNeighbors[occ.refTransID] || {};
const neighbors = wordList[occ.refWordID] || [];
neighbors.push(me);
wordList[occ.refWordID] = neighbors;
cur.pivotNeighbors[occ.refTransID] = wordList;
}));
// create a list of all pivots (anchor for lines)
cur.pivots = [];
cur.noOfLines = st.filter(d => d.pivot && (d.pivot.word_ID == 0)).length;
for (let pT = 0; pT < cur.noOfLines; pT++) {
cur.pivots.push(st.filter(d => d.pivot && (d.pivot.trans_ID == pT))
.sort((a, b) => a.pivot.word_ID - b.pivot.word_ID));
}
cur.hasLabels = data.labels != null;
this.parent.attrs({
'width': cur.project.w,
'height': cur.project.h,
});
this.layers.bg.select('#zoomRect').attrs({
'width': cur.project.w,
'height': cur.project.h,
});
return data;
}
protected _render(renderData: StateProjectorData): void {
// shortcuts:
const states = renderData.states;
const cur = this._current;
const sX = cur.xScale;
const sY = cur.yScale;
const nDetails = StateProjector.neighborDetails;
let pps = this.layers.main.selectAll('.pp').data(states);
pps.exit().remove();
let ppsEnter = pps.enter().append('g').attr('class', 'pp');
ppsEnter.append('circle');
pps = ppsEnter.merge(pps);
pps.attr('transform',
d => `translate(${sX(d.pos[0])},${sY(d.pos[1])})`);
pps.select('circle').attr('r', d => Math.sqrt(2*d.occ.length));
pps.on('mouseenter', d => {
const allL = this.layers.main.selectAll('.hoverLine')
.data(nDetails(d.occ)
.map(oc => cur.pivots[oc.refTransID][oc.refWordID]));
allL.exit().remove();
allL.enter().append('line').attr('class', 'hoverLine')
.styles({
fill: 'none',
stroke: 'red',
'stroke-width': (2 / Math.sqrt(this._current.zoomTransform.k)),
'pointer-events': 'none'
})
.merge(allL)
.attrs({
x1: sX(d.pos[0]),
y1: sY(d.pos[1]),
x2: o => sX(o.pos[0]),
y2: o => sY(o.pos[1])
})
});
pps.on('mouseleave', () => {
this.layers.main.selectAll('.hoverLine').remove()
});
pps.on('click',
d => {
const eventDetails: StateProjectorClickEvent = {
loc: cur.loc,
pointIDs: [d.id],
caller: this,
neighborIDs: [d.id]
};
this.eventHandler
.trigger(StateProjector.events.clicked, eventDetails)
});
// this.layers.fg.selectAll('.label').data(renderData.states[0].)
this.layers.fg.selectAll('.pl').remove();
this.layers.fg.selectAll('.plPoint').remove();
for (let pT = 0; pT < cur.noOfLines; pT++) {
this.lineDraw(cur.pivots[pT], 'pl_' + pT,
cur.hasLabels ? renderData.labels[pT] || [] : []);
}
}
private lineDraw(onlyPivots: StateDesc[], className: string, labels: string[]) {
const cur = this._current;
console.log(onlyPivots, "--- onlyPivots", labels);
const line = d3.line<StateDesc>()
.x(d => cur.xScale(d.pos[0]))
.y(d => cur.yScale(d.pos[1]));
// .curve(d3.curveCardinal)
let pls = this.layers.fg.selectAll('.pl.' + className)
.data([onlyPivots]);
pls = pls.enter().append('path').attr('class', 'pl ' + className)
.merge(pls);
pls
// .transition()
.attr('d', line)
.style('stroke-width', 2. / Math.sqrt(cur.zoomTransform.k) + 'px');
let plPoints = this.layers.fg.selectAll('.plPoint.' + className).data(onlyPivots);
plPoints.exit().remove();
plPoints = plPoints.enter().append('circle').attr('class', 'plPoint ' + className)
.merge(plPoints);
plPoints.attrs({
cx: d => cur.xScale(d.pos[0]),
cy: d => cur.yScale(d.pos[1]),
r: 5 / Math.sqrt(cur.zoomTransform.k)
});
plPoints.classed('startPoint', d => d.pivot.word_ID === 0);
plPoints.classed('endPoint', d => d.pivot.word_ID === onlyPivots.length - 1);
const plLabel = this.layers.fg.selectAll(".plLabel." + className)
.data(labels);
plLabel.exit().remove();
const plLabelEnter = plLabel.enter()
.append('text')
.attr('class', 'plLabel ' + className);
plLabelEnter.merge(plLabel).attrs({
x: (d, i) => cur.xScale(onlyPivots[i].pos[0]),
y: (d, i) => cur.yScale(onlyPivots[i].pos[1]),
}).text(d => d);
plPoints.on('mouseenter', d => {
const detail: StateProjectorHoverEvent = {
hovered: true,
transID: d.pivot.trans_ID,
wordID: d.pivot.word_ID,
loc: cur.loc,
caller: this
};
this.eventHandler.trigger(StateProjector.events.hovered, detail);
});
plPoints.on('mouseleave', d => {
const detail: StateProjectorHoverEvent = {
hovered: false,
transID: d.pivot.trans_ID,
wordID: d.pivot.word_ID,
loc: cur.loc,
caller: this
};
this.eventHandler.trigger(StateProjector.events.hovered, detail);
});
plPoints.on('click',
d => {
const neighborIDs = this.myNeighborIDs(d.pivot.trans_ID, d.pivot.word_ID);
const evDetails: StateProjectorClickEvent = {
loc: cur.loc,
pointIDs: [d.id],
neighborIDs,
caller: this
};
this.eventHandler
.trigger(StateProjector.events.clicked, evDetails)
});
}
myNeighbors = (trans_ID, word_ID): StateDesc[] => {
const trans = this._current.pivotNeighbors[trans_ID];
if (trans) {
return trans[word_ID] || [];
} else {
return []
}
};
myNeighborIDs = (trans_ID, word_ID) => {
if (this.current.moreNeighbors) {
return this.current.moreNeighbors[trans_ID][word_ID];
} else {
return this.myNeighbors(trans_ID, word_ID).map(d => d.id)
}
};
actionSelectPoints(point_IDs: number[]) {
this.layers.main.selectAll('.pp')
.classed('selected',
(d: StateDesc) => includes(point_IDs, d.id));
this.layers.fg.selectAll('.plPoint')
.classed('selected',
(d: StateDesc) => includes(point_IDs, d.id));
}
actionHoverPivot(trans_ID: number, word_ID: number, hovered = true) {
if (hovered) {
const cur = this._current;
const myself = cur.pivots[trans_ID][word_ID];
const myNeighbors = this.myNeighbors(trans_ID, word_ID);
const points = myNeighbors.map(d => [cur.xScale(d.pos[0]), cur.yScale(d.pos[1])])
const polygon = concaveman(points)
const lGen:any = d3.line().curve(d3.curveLinearClosed);
const allPoly = this.layers.main
.selectAll('.hoverLine').data([polygon])
allPoly.exit().remove();
allPoly.enter().append('path').attr('class', 'hoverLine')
.merge(allPoly)
.style('opacity', 1. / (Math.sqrt(myNeighbors.length)))
.attr('d', lGen)
// const allL = this.layers.main.selectAll('.hoverLine')
// .data(myNeighbors);
// allL.exit().remove();
//
// allL.enter().append('line').attr('class', 'hoverLine')
// .merge(allL)
// .style('opacity', 1. / (Math.sqrt(myNeighbors.length)))
// .attrs({
// x1: cur.xScale(myself.pos[0]),
// y1: cur.yScale(myself.pos[1]),
// x2: o => cur.xScale(o.pos[0]),
// y2: o => cur.yScale(o.pos[1])
// })
} else {
this.layers.main.selectAll('.hoverLine').remove();
}
}
actionHoverRegion(regions: { x: number, y: number, w: number, h: number }[], hovered: boolean, pixelCoord = true) {
let hRect = this.layers.fg.selectAll('.highlightRect')
.data(hovered ? regions : []);
hRect.exit().remove();
hRect = hRect.enter().append('rect').attr('class', 'highlightRect')
.merge(hRect);
hRect.attrs({
x: d => d.x,
y: d => d.y,
width: d => d.w,
height: d => d.h,
})
}
} | the_stack |
// tslint:disable-next-line
/// <reference path="./gapi.client.drive.d.ts" />
import { map, filter, toArray } from '@lumino/algorithm';
import { Contents } from '@jupyterlab/services';
import { PathExt } from '@jupyterlab/coreutils';
import { DocumentRegistry } from '@jupyterlab/docregistry';
import {
driveApiRequest,
gapiAuthorized,
gapiInitialized,
makeError
} from './gapi';
/**
* Fields to request for File resources.
*/
const RESOURCE_FIELDS =
'kind,id,name,mimeType,trashed,headRevisionId,' +
'parents,modifiedTime,createdTime,capabilities,' +
'webContentLink,teamDriveId';
/**
* Fields to request for Team Drive resources.
*/
const TEAMDRIVE_FIELDS = 'kind,id,name,capabilities';
/**
* Fields to request for Revision resources.
*/
const REVISION_FIELDS = 'id, modifiedTime, keepForever';
/**
* Fields to request for File listings.
*/
const FILE_LIST_FIELDS = 'nextPageToken';
/**
* Fields to reuest for Team Drive listings.
*/
const TEAMDRIVE_LIST_FIELDS = 'nextPageToken';
/**
* Fields to reuest for Team Drive listings.
*/
const REVISION_LIST_FIELDS = 'nextPageToken';
/**
* Page size for file listing (max allowable).
*/
const FILE_PAGE_SIZE = 1000;
/**
* Page size for team drive listing (max allowable).
*/
const TEAMDRIVE_PAGE_SIZE = 100;
/**
* Page size for revision listing (max allowable).
*/
const REVISION_PAGE_SIZE = 1000;
export const RT_MIMETYPE = 'application/vnd.google-apps.drive-sdk';
export const FOLDER_MIMETYPE = 'application/vnd.google-apps.folder';
export const FILE_MIMETYPE = 'application/vnd.google-apps.file';
const MULTIPART_BOUNDARY = '-------314159265358979323846';
/**
* Type alias for a files resource returned by
* the Google Drive API.
*/
export type FileResource = gapi.client.drive.File;
/**
* Type alias for a Google Drive revision resource.
*/
export type RevisionResource = gapi.client.drive.Revision;
/**
* Type stub for a Team Drive resource.
*/
export type TeamDriveResource = gapi.client.drive.TeamDrive;
/**
* An API response which may be paginated.
*/
type PaginatedResponse =
| gapi.client.drive.FileList
| gapi.client.drive.TeamDriveList
| gapi.client.drive.RevisionList;
/**
* Alias for directory IFileType.
*/
const directoryFileType = DocumentRegistry.defaultDirectoryFileType;
/**
* The name of the dummy "Shared with me" folder.
*/
const SHARED_DIRECTORY = 'Shared with me';
/**
* The path of the dummy pseudo-root folder.
*/
const COLLECTIONS_DIRECTORY = '';
/**
* A dummy files resource for the "Shared with me" folder.
*/
const SHARED_DIRECTORY_RESOURCE: FileResource = {
kind: 'dummy',
name: SHARED_DIRECTORY
};
/**
* A dummy files resource for the pseudo-root folder.
*/
const COLLECTIONS_DIRECTORY_RESOURCE: FileResource = {
kind: 'dummy',
name: ''
};
/* ****** Functions for uploading/downloading files ******** */
/**
* Get a download URL for a file path.
*
* @param path - the path corresponding to the file.
*
* @returns a promise that resolves with the download URL.
*/
export async function urlForFile(path: string): Promise<string> {
const resource = await getResourceForPath(path);
return resource.webContentLink!;
}
/**
* Given a path and `Contents.IModel`, upload the contents to Google Drive.
*
* @param path - the path to which to upload the contents.
*
* @param model - the `Contents.IModel` to upload.
*
* @param fileType - a candidate DocumentRegistry.IFileType for the given file.
*
* @param exisiting - whether the file exists.
*
* @returns a promise fulfulled with the `Contents.IModel` that has been uploaded,
* or throws an Error if it fails.
*/
export async function uploadFile(
path: string,
model: Partial<Contents.IModel>,
fileType: DocumentRegistry.IFileType,
existing: boolean = false,
fileTypeForPath:
| ((path: string) => DocumentRegistry.IFileType)
| undefined = undefined
): Promise<Contents.IModel> {
if (isDummy(PathExt.dirname(path)) && !existing) {
throw makeError(
400,
`Google Drive: "${path}"` + ' is not a valid save directory'
);
}
let resourceReadyPromise: Promise<FileResource>;
if (existing) {
resourceReadyPromise = getResourceForPath(path);
} else {
resourceReadyPromise = new Promise<FileResource>(
async (resolve, reject) => {
let enclosingFolderPath = PathExt.dirname(path);
const resource: FileResource = fileResourceFromContentsModel(
model,
fileType
);
const parentFolderResource = await getResourceForPath(
enclosingFolderPath
);
if (!isDirectory(parentFolderResource)) {
throw new Error('Google Drive: expected a folder: ' + path);
}
if (parentFolderResource.kind === 'drive#teamDrive') {
resource.teamDriveId = parentFolderResource.id;
} else if (parentFolderResource.teamDriveId) {
resource.teamDriveId = parentFolderResource.teamDriveId;
}
resource.parents = [parentFolderResource.id!];
resolve(resource);
}
);
}
const resource = await resourceReadyPromise;
// Construct the HTTP request: first the metadata,
// then the content of the uploaded file.
const delimiter = '\r\n--' + MULTIPART_BOUNDARY + '\r\n';
const closeDelim = '\r\n--' + MULTIPART_BOUNDARY + '--';
// Metatdata part.
let body = delimiter + 'Content-Type: application/json\r\n\r\n';
// Don't update metadata if the file already exists.
if (!existing) {
body += JSON.stringify(resource);
}
body += delimiter;
// Content of the file.
body += 'Content-Type: ' + resource.mimeType + '\r\n';
// It is not well documented, but as can be seen in
// filebrowser/src/model.ts, anything that is not a
// notebook is a base64 encoded string.
if (model.format === 'base64') {
body += 'Content-Transfer-Encoding: base64\r\n';
body += '\r\n' + model.content + closeDelim;
} else if (model.format === 'text') {
// If it is already a text string, just send that.
body += '\r\n' + model.content + closeDelim;
} else {
// Notebook case.
body += '\r\n' + JSON.stringify(model.content) + closeDelim;
}
let apiPath = '/upload/drive/v3/files';
let method = 'POST';
if (existing) {
method = 'PATCH';
apiPath = apiPath + '/' + resource.id;
}
const createRequest = () => {
return gapi.client.request({
path: apiPath,
method: method,
params: {
uploadType: 'multipart',
supportsTeamDrives: !!resource.teamDriveId,
fields: RESOURCE_FIELDS
},
headers: {
'Content-Type':
'multipart/related; boundary="' + MULTIPART_BOUNDARY + '"'
},
body: body
});
};
const result = await driveApiRequest<FileResource>(createRequest);
// Update the cache.
Private.resourceCache.set(path, result);
return contentsModelFromFileResource(
result,
path,
fileType,
true,
fileTypeForPath
);
}
/**
* Given a files resource, construct a Contents.IModel.
*
* @param resource - the files resource.
*
* @param path - the path at which the resource exists in the filesystem.
* This should include the name of the file itself.
*
* @param fileType - a candidate DocumentRegistry.IFileType for the given file.
*
* @param includeContents - whether to download the actual text/json/binary
* content from the server. This takes much more bandwidth, so should only
* be used when required.
*
* @param fileTypeForPath - A function that, given a path argument, returns
* and DocumentRegistry.IFileType that is consistent with the path.
*
* @returns a promise fulfilled with the Contents.IModel for the resource.
*/
export async function contentsModelFromFileResource(
resource: FileResource,
path: string,
fileType: DocumentRegistry.IFileType,
includeContents: boolean,
fileTypeForPath:
| ((path: string) => DocumentRegistry.IFileType)
| undefined = undefined
): Promise<Contents.IModel> {
// Handle the exception of the dummy directories
if (resource.kind === 'dummy') {
return contentsModelFromDummyFileResource(
resource,
path,
includeContents,
fileTypeForPath
);
}
// Handle the case of getting the contents of a directory.
if (isDirectory(resource)) {
// Enter contents metadata.
const contents: Contents.IModel = {
name: resource.name!,
path: path,
type: 'directory',
writable: resource.capabilities!.canEdit || true,
created: resource.createdTime || '',
last_modified: resource.modifiedTime || '',
mimetype: fileType.mimeTypes[0],
content: null,
format: 'json'
};
// Get directory listing if applicable.
if (includeContents) {
if (!fileTypeForPath) {
throw Error(
'Must include fileTypeForPath argument to get directory listing'
);
}
const fileList: FileResource[] = [];
const resources = await searchDirectory(path);
// Update the cache.
Private.clearCacheForDirectory(path);
Private.populateCacheForDirectory(path, resources);
let currentContents = Promise.resolve({});
for (let i = 0; i < resources.length; i++) {
const currentResource = resources[i];
const resourcePath = path
? path + '/' + currentResource.name!
: currentResource.name!;
const resourceFileType = fileTypeForPath(resourcePath);
currentContents = contentsModelFromFileResource(
currentResource,
resourcePath,
resourceFileType,
false
);
fileList.push(await currentContents);
}
return { ...contents, content: fileList };
} else {
return contents;
}
} else {
// Handle the case of getting the contents of a file.
const contents: Contents.IModel = {
name: resource.name!,
path: path,
type: fileType.contentType,
writable: resource.capabilities!.canEdit || true,
created: resource.createdTime || '',
last_modified: resource.modifiedTime || '',
mimetype: fileType.mimeTypes[0],
content: null,
format: fileType.fileFormat
};
// Download the contents from the server if necessary.
if (includeContents) {
const result: any = await downloadResource(
resource,
false,
contents.format
);
let content = result;
return { ...contents, content };
} else {
return contents;
}
}
}
/**
* There are two fake directories that we expose in the file browser
* in order to have access to the "Shared with me" directory. This is
* not a proper directory in the Google Drive system, just a collection
* of files that have a `sharedWithMe` flag, so we have to treat it
* separately. This constructs Contents.IModels from our dummy directories.
*
* @param resource: the dummy files resource.
*
* @param path: the path for the dummy resource.
*
* @param includeContents: whether to include the directory listing
* for the dummy directory.
*
* @param fileTypeForPath - A function that, given a path argument, returns
* and DocumentRegistry.IFileType that is consistent with the path.
*
* @returns a promise fulfilled with the a Contents.IModel for the resource.
*/
async function contentsModelFromDummyFileResource(
resource: FileResource,
path: string,
includeContents: boolean,
fileTypeForPath: ((path: string) => DocumentRegistry.IFileType) | undefined
): Promise<Contents.IModel> {
// Construct the empty Contents.IModel.
const contents: Contents.IModel = {
name: resource.name!,
path: path,
type: 'directory',
writable: false,
created: '',
last_modified: '',
content: null,
mimetype: '',
format: 'json'
};
if (includeContents && !fileTypeForPath) {
throw Error(
'Must include fileTypeForPath argument to get directory listing'
);
}
if (resource.name === SHARED_DIRECTORY && includeContents) {
// If `resource` is the SHARED_DIRECTORY_RESOURCE, and we
// need the file listing for it, then get them.
const fileList: Contents.IModel[] = [];
const resources = await searchSharedFiles();
// Update the cache.
Private.clearCacheForDirectory(path);
Private.populateCacheForDirectory(path, resources);
let currentContents: Promise<any> | undefined;
for (let i = 0; i < resources.length; i++) {
const currentResource = resources[i];
const resourcePath = path
? path + '/' + currentResource.name
: currentResource.name!;
const resourceFileType = fileTypeForPath!(resourcePath);
currentContents = contentsModelFromFileResource(
currentResource,
resourcePath,
resourceFileType,
false,
fileTypeForPath
);
fileList.push(await currentContents);
}
const content = fileList;
return { ...contents, content };
} else if (resource.name === COLLECTIONS_DIRECTORY && includeContents) {
// If `resource` is the pseudo-root directory, construct
// a contents model for it.
const sharedContentsPromise = contentsModelFromFileResource(
SHARED_DIRECTORY_RESOURCE,
SHARED_DIRECTORY,
directoryFileType,
false,
undefined
);
const rootContentsPromise = resourceFromFileId('root').then(
rootResource => {
return contentsModelFromFileResource(
rootResource,
rootResource.name || '',
directoryFileType,
false,
undefined
);
}
);
const teamDrivesContentsPromise = listTeamDrives().then(drives => {
const drivePromises: Promise<Contents.IModel>[] = [];
for (let drive of drives) {
drivePromises.push(
contentsModelFromFileResource(
drive,
drive.name!,
directoryFileType,
false,
undefined
)
);
}
return Promise.all(drivePromises);
});
const c = await Promise.all([
rootContentsPromise,
sharedContentsPromise,
teamDrivesContentsPromise
]);
const rootItems = c[2];
rootItems.unshift(c[1]);
rootItems.unshift(c[0]);
return { ...contents, content: rootItems };
} else {
// Otherwise return the (mostly) empty contents model.
return contents;
}
}
/**
* Given a path, get a `Contents.IModel` corresponding to that file.
*
* @param path - the path of the file.
*
* @param includeContents - whether to include the binary/text/contents of the file.
* If false, just get the metadata.
*
* @param fileTypeForPath - A function that, given a path argument, returns
* and DocumentRegistry.IFileType that is consistent with the path.
*
* @returns a promise fulfilled with the `Contents.IModel` of the appropriate file.
* Otherwise, throws an error.
*/
export async function contentsModelForPath(
path: string,
includeContents: boolean,
fileTypeForPath: (path: string) => DocumentRegistry.IFileType
): Promise<Contents.IModel> {
const fileType = fileTypeForPath(path);
const resource = await getResourceForPath(path);
const contents = await contentsModelFromFileResource(
resource,
path,
fileType,
includeContents,
fileTypeForPath
);
return contents;
}
/* ********* Functions for file creation/deletion ************** */
/**
* Give edit permissions to a Google drive user.
*
* @param resource: the FileResource to share.
*
* @param emailAddresses - the email addresses of the users for which
* to create the permissions.
*
* @returns a promise fulfilled when the permissions are created.
*/
export async function createPermissions(
resource: FileResource,
emailAddresses: string[]
): Promise<void> {
// Do nothing for an empty list.
if (emailAddresses.length === 0) {
return;
}
const createRequest = () => {
// Create a batch request for permissions.
// Note: the typings for gapi.client are missing
// the newBatch() function, which creates an HttpBatchRequest
const batch: any = (gapi as any).client.newBatch();
for (let address of emailAddresses) {
const permissionRequest = {
type: 'user',
role: 'writer',
emailAddress: address
};
const request = gapi.client.drive.permissions.create({
fileId: resource.id!,
emailMessage: `${resource.name} has been shared with you`,
sendNotificationEmail: true,
resource: permissionRequest,
supportsTeamDrives: !!resource.teamDriveId
});
batch.add(request);
}
return batch;
};
// Submit the batch request.
await driveApiRequest<any>(createRequest);
return;
}
/**
* Delete a file from the users Google Drive.
*
* @param path - the path of the file to delete.
*
* @returns a promise fulfilled when the file has been deleted.
*/
export async function deleteFile(path: string): Promise<void> {
const resource = await getResourceForPath(path);
const createRequest = () => {
return gapi.client.drive.files.delete({
fileId: resource.id!,
supportsTeamDrives: !!resource.teamDriveId
});
};
await driveApiRequest<void>(createRequest, 204);
// Update the cache
Private.resourceCache.delete(path);
return;
}
/* ****** Functions for file system querying/manipulation ***** */
/**
* Search a directory.
*
* @param path - the path of the directory on the server.
*
* @param query - a query string, following the format of
* query strings for the Google Drive v3 API, which
* narrows down search results. An empty query string
* corresponds to just listing the contents of the directory.
*
* @returns a promise fulfilled with a list of files resources,
* corresponding to the files that are in the directory and
* match the query string.
*/
export async function searchDirectory(
path: string,
query: string = ''
): Promise<FileResource[]> {
const resource = await getResourceForPath(path);
// Check to make sure this is a folder.
if (!isDirectory(resource)) {
throw new Error('Google Drive: expected a folder: ' + path);
}
// Construct the query.
let fullQuery: string =
`\'${resource.id}\' in parents ` + 'and trashed = false';
if (query) {
fullQuery += ' and ' + query;
}
const getPage = (pageToken?: string) => {
let createRequest: () => gapi.client.HttpRequest<
gapi.client.drive.FileList
>;
if (resource.teamDriveId) {
// Case of a directory in a team drive.
createRequest = () => {
return gapi.client.drive.files.list({
q: fullQuery,
pageSize: FILE_PAGE_SIZE,
pageToken,
fields: `${FILE_LIST_FIELDS}, files(${RESOURCE_FIELDS})`,
corpora: 'teamDrive',
includeTeamDriveItems: true,
supportsTeamDrives: true,
teamDriveId: resource.teamDriveId
});
};
} else if (resource.kind === 'drive#teamDrive') {
// Case of the root of a team drive.
createRequest = () => {
return gapi.client.drive.files.list({
q: fullQuery,
pageSize: FILE_PAGE_SIZE,
pageToken,
fields: `${FILE_LIST_FIELDS}, files(${RESOURCE_FIELDS})`,
corpora: 'teamDrive',
includeTeamDriveItems: true,
supportsTeamDrives: true,
teamDriveId: resource.id!
});
};
} else {
// Case of the user directory.
createRequest = () => {
return gapi.client.drive.files.list({
q: fullQuery,
pageSize: FILE_PAGE_SIZE,
pageToken,
fields: `${FILE_LIST_FIELDS}, files(${RESOURCE_FIELDS})`
});
};
}
return driveApiRequest(createRequest);
};
return depaginate(getPage, 'files');
}
/**
* Search the list of files that have been shared with the user.
*
* @param query - a query string, following the format of
* query strings for the Google Drive v3 API, which
* narrows down search results. An empty query string
* corresponds to just listing the shared files.
*
* @returns a promise fulfilled with the files that have been
* shared with the user.
*
* ### Notes
* This does not search Team Drives.
*/
export async function searchSharedFiles(
query: string = ''
): Promise<FileResource[]> {
await gapiInitialized.promise;
// Construct the query.
let fullQuery = 'sharedWithMe = true';
if (query) {
fullQuery += ' and ' + query;
}
const getPage = (pageToken?: string) => {
const createRequest = () => {
return gapi.client.drive.files.list({
q: fullQuery,
pageSize: FILE_PAGE_SIZE,
pageToken,
fields: `${FILE_LIST_FIELDS}, files(${RESOURCE_FIELDS})`
});
};
return driveApiRequest(createRequest);
};
return depaginate(getPage, 'files');
}
/**
* Move a file in Google Drive. Can also be used to rename the file.
*
* @param oldPath - The initial location of the file (where the path
* includes the filename).
*
* @param newPath - The new location of the file (where the path
* includes the filename).
*
* @param fileTypeForPath - A function that, given a path argument, returns
* and DocumentRegistry.IFileType that is consistent with the path.
*
* @returns a promise fulfilled with the `Contents.IModel` of the moved file.
* Otherwise, throws an error.
*/
export async function moveFile(
oldPath: string,
newPath: string,
fileTypeForPath: (path: string) => DocumentRegistry.IFileType
): Promise<Contents.IModel> {
if (isDummy(PathExt.dirname(newPath))) {
throw makeError(
400,
`Google Drive: "${newPath}" ` + 'is not a valid save directory'
);
}
if (oldPath === newPath) {
return contentsModelForPath(oldPath, true, fileTypeForPath);
} else {
let newFolderPath = PathExt.dirname(newPath);
// Get a promise that resolves with the resource in the current position.
const resourcePromise = getResourceForPath(oldPath);
// Get a promise that resolves with the resource of the new folder.
const newFolderPromise = getResourceForPath(newFolderPath);
// Check the new path to make sure there isn't already a file
// with the same name there.
const newName = PathExt.basename(newPath);
const directorySearchPromise = searchDirectory(
newFolderPath,
"name = '" + newName + "'"
);
// Once we have all the required information,
// update the metadata with the new parent directory
// for the file.
const values = await Promise.all([
resourcePromise,
newFolderPromise,
directorySearchPromise
]);
const resource = values[0];
const newFolder = values[1];
const directorySearch = values[2];
if (directorySearch.length !== 0) {
throw new Error(
'Google Drive: File with the same name ' +
'already exists in the destination directory'
);
} else {
const createRequest = () => {
return gapi.client.drive.files.update({
fileId: resource.id!,
addParents: newFolder.id!,
removeParents: resource.parents ? resource.parents[0] : undefined,
resource: {
name: newName
},
fields: RESOURCE_FIELDS,
supportsTeamDrives: !!(resource.teamDriveId || newFolder.teamDriveId)
});
};
const response = await driveApiRequest<FileResource>(createRequest);
// Update the cache.
Private.resourceCache.delete(oldPath);
Private.resourceCache.set(newPath, response);
return contentsModelForPath(newPath, true, fileTypeForPath);
}
}
}
/**
* Copy a file in Google Drive. It is assumed that the new filename has
* been determined previous to invoking this function, and does not conflict
* with any files in the new directory.
*
* @param oldPath - The initial location of the file (where the path
* includes the filename).
*
* @param newPath - The location of the copy (where the path
* includes the filename). This cannot be the same as `oldPath`.
*
* @param fileTypeForPath - A function that, given a path argument, returns
* and DocumentRegistry.IFileType that is consistent with the path.
*
* @returns a promise fulfilled with the `Contents.IModel` of the copy.
* Otherwise, throws an error.
*/
export async function copyFile(
oldPath: string,
newPath: string,
fileTypeForPath: (path: string) => DocumentRegistry.IFileType
): Promise<Contents.IModel> {
if (isDummy(PathExt.dirname(newPath))) {
throw makeError(
400,
`Google Drive: "${newPath}"` + ' is not a valid save directory'
);
}
if (oldPath === newPath) {
throw makeError(
400,
'Google Drive: cannot copy a file with' +
' the same name to the same directory'
);
} else {
let newFolderPath = PathExt.dirname(newPath);
// Get a promise that resolves with the resource in the current position.
const resourcePromise = getResourceForPath(oldPath);
// Get a promise that resolves with the resource of the new folder.
const newFolderPromise = getResourceForPath(newFolderPath);
// Check the new path to make sure there isn't already a file
// with the same name there.
const newName = PathExt.basename(newPath);
const directorySearchPromise = searchDirectory(
newFolderPath,
"name = '" + newName + "'"
);
// Once we have all the required information,
// perform the copy.
const values = await Promise.all([
resourcePromise,
newFolderPromise,
directorySearchPromise
]);
const resource = values[0];
const newFolder = values[1];
const directorySearch = values[2];
if (directorySearch.length !== 0) {
throw new Error(
'Google Drive: File with the same name ' +
'already exists in the destination directory'
);
} else {
const createRequest = () => {
return gapi.client.drive.files.copy({
fileId: resource.id!,
resource: {
parents: [newFolder.id!],
name: newName
},
fields: RESOURCE_FIELDS,
supportsTeamDrives: !!(newFolder.teamDriveId || resource.teamDriveId)
});
};
const response = await driveApiRequest<FileResource>(createRequest);
// Update the cache.
Private.resourceCache.set(newPath, response);
return contentsModelForPath(newPath, true, fileTypeForPath);
}
}
}
/**
* Invalidate the resource cache.
*
* #### Notes
* The resource cache is mostly private to this module, and
* is essential to not be rate-limited by Google.
*
* This should only be called when the user signs out, and
* the cached information about their directory structure
* is no longer valid.
*/
export function clearCache(): void {
Private.resourceCache.clear();
}
/* ******** Functions for dealing with revisions ******** */
/**
* List the revisions for a file in Google Drive.
*
* @param path - the path of the file.
*
* @returns a promise fulfilled with a list of `Contents.ICheckpointModel`
* that correspond to the file revisions stored on drive.
*/
export async function listRevisions(
path: string
): Promise<Contents.ICheckpointModel[]> {
const resource = await getResourceForPath(path);
const getPage = (pageToken?: string) => {
const createRequest = () => {
return gapi.client.drive.revisions.list({
fileId: resource.id!,
pageSize: REVISION_PAGE_SIZE,
pageToken,
fields: `${REVISION_LIST_FIELDS}, revisions(${REVISION_FIELDS})`
});
};
return driveApiRequest<gapi.client.drive.RevisionList>(createRequest);
};
const listing = await depaginate(getPage, 'revisions');
const revisions = map(
filter(listing || [], (revision: RevisionResource) => {
return revision.keepForever!;
}),
(revision: RevisionResource) => {
return { id: revision.id!, last_modified: revision.modifiedTime! };
}
);
return toArray(revisions);
}
/**
* Tell Google drive to keep the current revision. Without doing
* this the revision would eventually be cleaned up.
*
* @param path - the path of the file to pin.
*
* @returns a promise fulfilled with an `ICheckpointModel` corresponding
* to the newly pinned revision.
*/
export async function pinCurrentRevision(
path: string
): Promise<Contents.ICheckpointModel> {
const resource = await getResourceForPath(path);
const createRequest = () => {
return gapi.client.drive.revisions.update({
fileId: resource.id!,
revisionId: resource.headRevisionId!,
resource: {
keepForever: true
}
});
};
const revision = await driveApiRequest<RevisionResource>(createRequest);
return { id: revision.id!, last_modified: revision.modifiedTime! };
}
/**
* Tell Google drive not to keep the current revision.
* Eventually the revision will then be cleaned up.
*
* @param path - the path of the file to unpin.
*
* @param revisionId - the id of the revision to unpin.
*
* @returns a promise fulfilled when the revision is unpinned.
*/
export async function unpinRevision(
path: string,
revisionId: string
): Promise<void> {
const resource = await getResourceForPath(path);
const createRequest = () => {
return gapi.client.drive.revisions.update({
fileId: resource.id!,
revisionId: revisionId,
resource: {
keepForever: false
}
});
};
await driveApiRequest<RevisionResource>(createRequest);
return;
}
/**
* Revert a file to a particular revision id.
*
* @param path - the path of the file.
*
* @param revisionId - the id of the revision to revert.
*
* @param fileType - a candidate DocumentRegistry.IFileType for the given file.
*
* @returns a promise fulfilled when the file is reverted.
*/
export async function revertToRevision(
path: string,
revisionId: string,
fileType: DocumentRegistry.IFileType
): Promise<void> {
// Get the correct file resource.
const revisionResource = await getResourceForPath(path);
const content = await downloadRevision(
revisionResource,
revisionId,
fileType.fileFormat
);
const contents: Contents.IModel = {
name: revisionResource.name!,
path: path,
type: fileType.contentType,
writable: revisionResource.capabilities!.canEdit || true,
created: String(revisionResource.createdTime),
// TODO What is the appropriate modified time?
last_modified: String(revisionResource.modifiedTime),
mimetype: fileType.mimeTypes[0],
content,
format: fileType.fileFormat
};
// Reupload the reverted file to the head revision.
await uploadFile(path, contents, fileType, true, undefined);
return;
}
/* *********Utility functions ********* */
/**
* Construct a minimal files resource object from a
* contents model.
*
* @param contents - The contents model.
*
* @param fileType - a candidate DocumentRegistry.IFileType for the given file.
*
* @returns a files resource object for the Google Drive API.
*
* #### Notes
* This does not include any of the binary/text/json content of the
* `contents`, just some metadata (`name` and `mimeType`).
*/
function fileResourceFromContentsModel(
contents: Partial<Contents.IModel>,
fileType: DocumentRegistry.IFileType
): FileResource {
let mimeType: string;
switch (contents.type) {
case 'notebook':
// The Contents API does not specify a notebook mimetype,
// but the Google Drive API requires one.
mimeType = 'application/x-ipynb+json';
break;
case 'directory':
mimeType = FOLDER_MIMETYPE;
break;
default:
mimeType = fileType.mimeTypes[0];
break;
}
return {
name: contents.name || PathExt.basename(contents.path || ''),
mimeType
};
}
/**
* Obtains the Google Drive Files resource for a file or folder relative
* to the a given folder. The path should be a file or a subfolder, and
* should not contain multiple levels of folders (hence the name
* pathComponent). It should also not contain any leading or trailing
* slashes.
*
* @param pathComponent - The file/folder to find
*
* @param type - type of resource (file or folder)
*
* @param folderId - The Google Drive folder id
*
* @returns A promise fulfilled by either the files resource for the given
* file/folder, or rejected with an Error object.
*/
async function getResourceForRelativePath(
pathComponent: string,
folderId: string,
teamDriveId: string = ''
): Promise<FileResource> {
await gapiInitialized.promise;
// Construct a search query for the file at hand.
const query =
`name = \'${pathComponent}\' and trashed = false ` +
`and \'${folderId}\' in parents`;
// Construct a request for the files matching the query.
let createRequest: () => gapi.client.HttpRequest<gapi.client.drive.FileList>;
if (teamDriveId) {
createRequest = () => {
return gapi.client.drive.files.list({
q: query,
pageSize: FILE_PAGE_SIZE,
fields: `${FILE_LIST_FIELDS}, files(${RESOURCE_FIELDS})`,
supportsTeamDrives: true,
includeTeamDriveItems: true,
corpora: 'teamDrive',
teamDriveId: teamDriveId
});
};
} else {
createRequest = () => {
return gapi.client.drive.files.list({
q: query,
pageSize: FILE_PAGE_SIZE,
fields: `${FILE_LIST_FIELDS}, files(${RESOURCE_FIELDS})`
});
};
}
// Make the request.
const result = await driveApiRequest<gapi.client.drive.FileList>(
createRequest
);
const files: FileResource[] = result.files || [];
if (!files || files.length === 0) {
throw Error(
'Google Drive: cannot find the specified file/folder: ' + pathComponent
);
} else if (files.length > 1) {
throw Error('Google Drive: multiple files/folders match: ' + pathComponent);
}
return files[0];
}
/**
* Given the unique id string for a file in Google Drive,
* get the files resource metadata associated with it.
*
* @param id - The file ID.
*
* @returns A promise that resolves with the files resource
* corresponding to `id`.
*
* ### Notes
* This does not support Team Drives.
*/
async function resourceFromFileId(id: string): Promise<FileResource> {
await gapiInitialized.promise;
const createRequest = () => {
return gapi.client.drive.files.get({
fileId: id,
fields: RESOURCE_FIELDS
});
};
return driveApiRequest<FileResource>(createRequest);
}
/**
* Given a name, find the user's root drive resource,
* or a Team Drive resource with the same name.
*
* @param name - The Team Drive name.
*/
async function driveForName(
name: string
): Promise<TeamDriveResource | FileResource> {
const rootResource = resourceFromFileId('root');
const teamDriveResources = listTeamDrives();
const result = await Promise.all([rootResource, teamDriveResources]);
const root = result[0];
const teamDrives = result[1];
if (root.name === name) {
return root;
}
for (let drive of teamDrives) {
if (drive.name === name) {
return drive;
}
}
throw Error(`Google Drive: cannot find Team Drive: ${name}`);
}
/**
* List the Team Drives accessible to a user.
*
* @returns a list of team drive resources.
*/
async function listTeamDrives(): Promise<TeamDriveResource[]> {
await gapiAuthorized.promise;
const getPage = (
pageToken: string
): Promise<gapi.client.drive.TeamDriveList> => {
const createRequest = () => {
return gapi.client.drive.teamdrives.list({
fields: `${TEAMDRIVE_LIST_FIELDS}, teamDrives(${TEAMDRIVE_FIELDS})`,
pageSize: TEAMDRIVE_PAGE_SIZE,
pageToken
});
};
return driveApiRequest<gapi.client.drive.TeamDriveList>(createRequest);
};
return depaginate(getPage, 'teamDrives');
}
/**
* Split a path into path components
*/
function splitPath(path: string): string[] {
return path.split('/').filter((s, i, a) => Boolean(s));
}
/**
* Whether a path is a dummy directory.
*/
export function isDummy(path: string): boolean {
return path === COLLECTIONS_DIRECTORY || path === SHARED_DIRECTORY;
}
/**
* Whether a resource is a directory (or Team Drive),
* which may contain items.
*/
export function isDirectory(resource: FileResource): boolean {
return !!(
resource.kind === 'drive#teamDrive' || resource.mimeType === FOLDER_MIMETYPE
);
}
/**
* Depaginate a series of requests into a single array.
*/
async function depaginate<
T extends FileResource | TeamDriveResource,
L extends PaginatedResponse
>(
getPage: (pageToken?: string) => Promise<L>,
listName: keyof L,
pageToken?: string
): Promise<T[]> {
const list = await getPage(pageToken);
const total = (list[listName] as any) as T[];
if (list.nextPageToken) {
return depaginate<T, L>(getPage, listName, list.nextPageToken).then(
next => {
return [...total, ...next];
}
);
} else {
return total;
}
}
/**
* Gets the Google Drive Files resource corresponding to a path. The path
* is always treated as an absolute path, no matter whether it contains
* leading or trailing slashes. In fact, all leading, trailing and
* consecutive slashes are ignored.
*
* @param path - The path of the file.
*
* @param type - The type (file or folder)
*
* @returns A promise fulfilled with the files resource for the given path.
* or an Error object on error.
*/
export async function getResourceForPath(path: string): Promise<FileResource> {
// First check the cache.
if (Private.resourceCache.has(path)) {
return Private.resourceCache.get(path)!;
}
const components = splitPath(path);
if (components.length === 0) {
// Handle the case for the pseudo folders
// (i.e., the view onto the "My Drive" and "Shared
// with me" directories, as well as the pseudo-root).
return COLLECTIONS_DIRECTORY_RESOURCE;
} else if (components.length === 1 && components[0] === SHARED_DIRECTORY) {
return SHARED_DIRECTORY_RESOURCE;
} else {
// Create a Promise of a FileResource to walk the path until
// we find the right file.
let currentResource: FileResource;
// Current path component index.
let idx = 0;
// Team Drive id for the path, or the empty string if
// the path is not in a Team Drive.
let teamDriveId = '';
if (components[0] === SHARED_DIRECTORY) {
// Handle the case of the `Shared With Me` directory.
const shared = await searchSharedFiles("name = '" + components[1] + "'");
if (!shared || shared.length === 0) {
throw Error(
'Google Drive: cannot find the specified file/folder: ' +
components[1]
);
} else if (shared.length > 1) {
throw Error(
'Google Drive: multiple files/folders match: ' + components[1]
);
}
currentResource = shared[0];
idx = 2; // Set the component index to the third component.
} else {
// Handle the case of a `My Drive` or a Team Drive
try {
const drive = await driveForName(components[0]);
if (drive.kind === 'drive#teamDrive') {
teamDriveId = drive.id!;
}
currentResource = drive;
idx = 1;
} catch {
throw Error(`Unexpected file in root directory: ${components[0]}`);
}
}
// Loop over the components, updating the current resource.
// Start the loop at idx to skip the pseudo-root.
for (; idx < components.length; idx++) {
const component = components[idx];
currentResource = await getResourceForRelativePath(
component,
currentResource.id!,
teamDriveId
);
}
// Update the cache.
Private.resourceCache.set(path, currentResource);
// Resolve with the final value of currentResource.
return currentResource;
}
}
/**
* Download the contents of a file from Google Drive.
*
* @param resource - the files resource metadata object.
*
* @param format - the format of the file ('json', 'text', or 'base64')
*
* @returns a promise fulfilled with the contents of the file.
*/
async function downloadResource(
resource: FileResource,
picked: boolean = false,
format: Contents.FileFormat
): Promise<any> {
await gapiInitialized.promise;
if (format !== 'base64') {
const token = gapi.auth.getToken().access_token;
const url = `https://www.googleapis.com/drive/v3/files/${
resource.id
}?alt=media&supportsTeamDrives=${!!resource.teamDriveId}`;
const response = await fetch(url, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`
}
});
const data = await response.text();
return format === 'text' ? data : JSON.parse(data);
} else {
const createRequest = () => {
return gapi.client.drive.files.get({
fileId: resource.id!,
alt: 'media',
supportsTeamDrives: !!resource.teamDriveId
});
};
return driveApiRequest<any>(createRequest).then(result => {
return btoa(result);
});
}
}
/**
* Download a revision of a file from Google Drive.
*
* @param resource - the files resource metadata object.
*
* @param revisionId - the id of the revision to download.
*
* @param format - the format of the file ('json', 'text', or 'base64')
*
* @returns a promise fulfilled with the contents of the file.
*/
async function downloadRevision(
resource: FileResource,
revisionId: string,
format: Contents.FileFormat
): Promise<any> {
await gapiInitialized.promise;
if (format !== 'base64') {
const token = gapi.auth.getToken().access_token;
const url = `https://www.googleapis.com/drive/v3/files/${
resource.id
}/revisions/${revisionId}?alt=media`;
const response = await fetch(url, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`
}
});
const data = await response.text();
return format === 'text' ? data : JSON.parse(data);
} else {
const createRequest = () => {
return gapi.client.drive.revisions.get({
fileId: resource.id!,
revisionId: revisionId,
alt: 'media'
});
};
return driveApiRequest<any>(createRequest).then(result => {
return btoa(result);
});
}
}
namespace Private {
/**
* A Map associating file paths with cached files
* resources. This can significantly cut down on
* API requests.
*/
export const resourceCache = new Map<string, FileResource>();
/**
* When we list the contents of a directory we can
* use that opportunity to refresh the cached values
* for that directory. This function clears all
* the cached resources that are in a given directory.
*/
export function clearCacheForDirectory(path: string): void {
resourceCache.forEach((value, key) => {
let enclosingFolderPath = PathExt.dirname(key);
if (path === enclosingFolderPath) {
resourceCache.delete(key);
}
});
}
/**
* Given a list of resources in a directory, put them in
* the resource cache. This strips any duplicates, since
* the path-based contents manager can't handle those correctly.
*/
export function populateCacheForDirectory(
path: string,
resourceList: FileResource[]
) {
// Identify duplicates in the list: we can't handle those
// correctly, so don't insert them.
const duplicatePaths: string[] = [];
const candidatePaths: string[] = [];
for (let resource of resourceList) {
const filePath = PathExt.join(path, resource.name!);
if (candidatePaths.indexOf(filePath) !== -1) {
duplicatePaths.push(filePath);
} else {
candidatePaths.push(filePath);
}
}
// Insert non-duplicates into the cache.
for (let resource of resourceList) {
const filePath = PathExt.join(path, resource.name!);
if (duplicatePaths.indexOf(filePath) === -1) {
Private.resourceCache.set(filePath, resource);
}
}
}
} | the_stack |
import { cleanup, render, screen, waitFor } from '@testing-library/react';
import React from 'react';
import { LiveModeType, liveState } from '../../types/tracks';
import { videoMockFactory } from '../../utils/tests/factories';
import { wrapInIntlProvider } from '../../utils/tests/intl';
import { wrapInRouter } from '../../utils/tests/router';
import * as mockWindow from '../../utils/window';
import { PLAYER_ROUTE } from '../routes';
import DashboardVideoLiveJitsi from '.';
let events: any = {};
const dispatch = (eventName: string, eventObject: any) => {
events[eventName](eventObject);
};
const mockExecuteCommand = jest.fn();
const mockDispose = jest.fn();
const mockJitsi = jest.fn().mockImplementation(() => ({
dispose: mockDispose,
executeCommand: mockExecuteCommand,
addListener: (eventName: string, callback: (event: any) => void) => {
events[eventName] = callback;
},
}));
jest.mock('../../utils/errors/report', () => ({ report: jest.fn() }));
jest.mock('../../utils/window', () => ({
converse: {
participantLeaves: jest.fn(),
},
}));
let mockDecodedJwtToken = {};
jest.mock('../../data/appData', () => ({
getDecodedJwt: () => mockDecodedJwtToken,
}));
describe('<DashboardVideoLiveJitsi />', () => {
beforeEach(() => {
mockDecodedJwtToken = {
user: {
id: '7f93178b-e578-44a6-8c85-ef267b6bf431',
username: 'jane_doe',
},
};
events = {};
jest.clearAllMocks();
jest.useFakeTimers('modern');
});
afterEach(() => {
jest.runOnlyPendingTimers();
jest.useRealTimers();
});
it('configures jitsi', () => {
const video = videoMockFactory({
live_info: {
medialive: {
input: {
endpoints: [
'rtmp://1.2.3.4:1935/stream-key-primary',
'rtmp://4.3.2.1:1935/stream-key-secondary',
],
},
},
jitsi: {
domain: 'meet.jit.si',
external_api_url: 'https://meet.jit.si/external_api.js',
config_overwrite: {},
interface_config_overwrite: {},
},
},
live_state: liveState.CREATING,
live_type: LiveModeType.JITSI,
});
global.JitsiMeetExternalAPI = mockJitsi;
const { rerender } = render(
wrapInIntlProvider(
<DashboardVideoLiveJitsi
video={video}
setCanStartLive={jest.fn()}
setCanShowStartButton={jest.fn()}
isInstructor={true}
/>,
),
);
const toolbarButtons = [
'microphone',
'camera',
'closedcaptions',
'desktop',
'fullscreen',
'fodeviceselection',
'hangup',
'profile',
'settings',
'raisehand',
'videoquality',
'filmstrip',
'feedback',
'shortcuts',
'tileview',
'select-background',
'help',
'mute-everyone',
'mute-video-everyone',
'security',
];
expect(mockJitsi).toHaveBeenCalledWith('meet.jit.si', {
configOverwrite: {
constraints: {
video: {
height: {
ideal: 720,
max: 720,
min: 240,
},
},
},
conferenceInfo: {
alwaysVisible: ['recording'],
autoHide: [],
},
disablePolls: true,
doNotStoreRoom: true,
hideConferenceSubject: true,
hideConferenceTimer: true,
resolution: 720,
toolbarButtons,
},
interfaceConfigOverwrite: {
HIDE_INVITE_MORE_HEADER: true,
TOOLBAR_BUTTONS: toolbarButtons,
},
parentNode: expect.any(HTMLElement),
roomName: video.id,
userInfo: {
displayName: 'jane_doe',
},
});
expect(mockExecuteCommand).not.toHaveBeenCalledWith(
'startRecording',
expect.any({}),
);
expect(mockExecuteCommand).not.toHaveBeenCalledWith(
'stopRecording',
expect.any(String),
);
expect(events.recordingStatusChanged).toBeDefined();
expect(events.participantRoleChanged).toBeDefined();
expect(events.videoConferenceLeft).toBeDefined();
expect(events.videoConferenceJoined).toBeDefined();
// state switch to running, recording must start
rerender(
wrapInIntlProvider(
<DashboardVideoLiveJitsi
video={{ ...video, live_state: liveState.RUNNING }}
setCanStartLive={jest.fn()}
setCanShowStartButton={jest.fn()}
isInstructor={true}
/>,
),
);
expect(mockExecuteCommand).toHaveBeenCalledWith('startRecording', {
mode: 'stream',
rtmpStreamKey: 'rtmp://1.2.3.4:1935/marsha/stream-key-primary',
});
expect(mockExecuteCommand).not.toHaveBeenCalledWith(
'stopRecording',
expect.any(String),
);
// state switch to stopping, recording must stop
rerender(
wrapInIntlProvider(
<DashboardVideoLiveJitsi
video={{ ...video, live_state: liveState.STOPPING }}
setCanStartLive={jest.fn()}
setCanShowStartButton={jest.fn()}
isInstructor={true}
/>,
),
);
expect(mockExecuteCommand).toHaveBeenCalledWith('stopRecording', 'stream');
expect(mockExecuteCommand).toHaveBeenCalledTimes(2);
});
it('configures jitsi without username', () => {
const decodedTokenWithoutUser = [
{},
{
user: {
id: '7f93178b-e578-44a6-8c85-ef267b6bf431',
},
},
];
decodedTokenWithoutUser.forEach((decodedToken) => {
mockDecodedJwtToken = decodedToken;
const video = videoMockFactory({
live_info: {
medialive: {
input: {
endpoints: [
'rtmp://1.2.3.4:1935/stream-key-primary',
'rtmp://4.3.2.1:1935/stream-key-secondary',
],
},
},
jitsi: {
domain: 'meet.jit.si',
external_api_url: 'https://meet.jit.si/external_api.js',
config_overwrite: {},
interface_config_overwrite: {},
},
},
live_state: liveState.CREATING,
live_type: LiveModeType.JITSI,
});
global.JitsiMeetExternalAPI = mockJitsi;
render(
wrapInIntlProvider(
<DashboardVideoLiveJitsi
video={video}
setCanStartLive={jest.fn()}
setCanShowStartButton={jest.fn()}
isInstructor={true}
/>,
),
);
const toolbarButtons = [
'microphone',
'camera',
'closedcaptions',
'desktop',
'fullscreen',
'fodeviceselection',
'hangup',
'profile',
'settings',
'raisehand',
'videoquality',
'filmstrip',
'feedback',
'shortcuts',
'tileview',
'select-background',
'help',
'mute-everyone',
'mute-video-everyone',
'security',
];
expect(mockJitsi).toHaveBeenCalledWith('meet.jit.si', {
configOverwrite: {
constraints: {
video: {
height: {
ideal: 720,
max: 720,
min: 240,
},
},
},
conferenceInfo: {
alwaysVisible: ['recording'],
autoHide: [],
},
disablePolls: true,
doNotStoreRoom: true,
hideConferenceSubject: true,
hideConferenceTimer: true,
resolution: 720,
toolbarButtons,
},
interfaceConfigOverwrite: {
HIDE_INVITE_MORE_HEADER: true,
TOOLBAR_BUTTONS: toolbarButtons,
},
parentNode: expect.any(HTMLElement),
roomName: video.id,
userInfo: {
displayName: undefined,
},
});
cleanup();
jest.clearAllMocks();
});
});
it('manages recording interruption', async () => {
const video = videoMockFactory({
live_info: {
medialive: {
input: {
endpoints: [
'rtmp://1.2.3.4:1935/stream-key-primary',
'rtmp://4.3.2.1:1935/stream-key-secondary',
],
},
},
jitsi: {
domain: 'meet.jit.si',
external_api_url: 'https://meet.jit.si/external_api.js',
config_overwrite: {},
interface_config_overwrite: {},
},
},
live_state: liveState.RUNNING,
live_type: LiveModeType.JITSI,
});
global.JitsiMeetExternalAPI = mockJitsi;
render(
wrapInIntlProvider(
<DashboardVideoLiveJitsi
video={video}
setCanStartLive={jest.fn()}
setCanShowStartButton={jest.fn()}
isInstructor={true}
/>,
),
);
expect(events.recordingStatusChanged).toBeDefined();
expect(mockExecuteCommand).toHaveBeenCalledWith('startRecording', {
mode: 'stream',
rtmpStreamKey: 'rtmp://1.2.3.4:1935/marsha/stream-key-primary',
});
expect(mockExecuteCommand).not.toHaveBeenCalledWith(
'stopRecording',
expect.any(String),
);
expect(mockExecuteCommand).toHaveBeenCalledTimes(1);
// simulates recording interruption
dispatch('recordingStatusChanged', {
on: false,
mode: 'stream',
error: 'service unavailable',
});
jest.advanceTimersToNextTimer();
await waitFor(() => {
expect(mockExecuteCommand).toHaveBeenCalledTimes(2);
});
expect(mockExecuteCommand).toHaveBeenCalledWith('startRecording', {
mode: 'stream',
rtmpStreamKey: 'rtmp://1.2.3.4:1935/marsha/stream-key-primary',
});
expect(mockExecuteCommand).not.toHaveBeenCalledWith(
'stopRecording',
expect.any(String),
);
});
it('calls setCanStartLive when role changes', () => {
const video = videoMockFactory({
live_info: {
medialive: {
input: {
endpoints: [
'rtmp://1.2.3.4:1935/stream-key-primary',
'rtmp://4.3.2.1:1935/stream-key-secondary',
],
},
},
jitsi: {
domain: 'meet.jit.si',
external_api_url: 'https://meet.jit.si/external_api.js',
config_overwrite: {},
interface_config_overwrite: {},
},
},
live_state: liveState.RUNNING,
live_type: LiveModeType.JITSI,
});
global.JitsiMeetExternalAPI = mockJitsi;
const mockCanStartLive = jest.fn();
render(
wrapInIntlProvider(
<DashboardVideoLiveJitsi
video={video}
setCanStartLive={mockCanStartLive}
setCanShowStartButton={jest.fn()}
isInstructor={true}
/>,
),
);
expect(mockCanStartLive).not.toHaveBeenCalled();
// simulates moderator role granted
dispatch('participantRoleChanged', {
role: 'moderator',
});
expect(mockCanStartLive).toHaveBeenLastCalledWith(true);
// simulates user is no longer moderator
dispatch('participantRoleChanged', {
role: 'participant',
});
expect(mockCanStartLive).toHaveBeenLastCalledWith(false);
});
it('calls setCanStartLive and setCanShowStartButton when participant leave the conference', () => {
const video = videoMockFactory({
live_info: {
medialive: {
input: {
endpoints: [
'rtmp://1.2.3.4:1935/stream-key-primary',
'rtmp://4.3.2.1:1935/stream-key-secondary',
],
},
},
jitsi: {
domain: 'meet.jit.si',
external_api_url: 'https://meet.jit.si/external_api.js',
config_overwrite: {},
interface_config_overwrite: {},
},
},
live_state: liveState.RUNNING,
live_type: LiveModeType.JITSI,
});
global.JitsiMeetExternalAPI = mockJitsi;
const mockCanStartLive = jest.fn();
const mockCanShowStartButton = jest.fn();
render(
wrapInIntlProvider(
<DashboardVideoLiveJitsi
video={video}
setCanStartLive={mockCanStartLive}
setCanShowStartButton={mockCanShowStartButton}
isInstructor={true}
/>,
),
);
const toolbarButtons = [
'microphone',
'camera',
'closedcaptions',
'desktop',
'fullscreen',
'fodeviceselection',
'hangup',
'profile',
'settings',
'raisehand',
'videoquality',
'filmstrip',
'feedback',
'shortcuts',
'tileview',
'select-background',
'help',
'mute-everyone',
'mute-video-everyone',
'security',
];
expect(mockJitsi).toHaveBeenCalledWith('meet.jit.si', {
configOverwrite: {
constraints: {
video: {
height: {
ideal: 720,
max: 720,
min: 240,
},
},
},
conferenceInfo: {
alwaysVisible: ['recording'],
autoHide: [],
},
disablePolls: true,
doNotStoreRoom: true,
hideConferenceSubject: true,
hideConferenceTimer: true,
resolution: 720,
toolbarButtons,
},
interfaceConfigOverwrite: {
HIDE_INVITE_MORE_HEADER: true,
TOOLBAR_BUTTONS: toolbarButtons,
},
parentNode: expect.any(HTMLElement),
roomName: video.id,
userInfo: {
displayName: 'jane_doe',
},
});
expect(mockCanStartLive).not.toHaveBeenCalled();
expect(mockCanShowStartButton).not.toHaveBeenCalled();
expect(mockJitsi).toHaveBeenCalledTimes(1);
// simulates user leave the conference
dispatch('videoConferenceLeft', {});
expect(mockCanStartLive).toHaveBeenLastCalledWith(false);
expect(mockCanShowStartButton).toHaveBeenLastCalledWith(false);
expect(mockDispose).toHaveBeenCalled();
expect(mockJitsi).toHaveBeenCalledWith('meet.jit.si', {
configOverwrite: {
constraints: {
video: {
height: {
ideal: 720,
max: 720,
min: 240,
},
},
},
conferenceInfo: {
alwaysVisible: ['recording'],
autoHide: [],
},
disablePolls: true,
doNotStoreRoom: true,
hideConferenceSubject: true,
hideConferenceTimer: true,
prejoinPageEnabled: true,
resolution: 720,
toolbarButtons,
},
interfaceConfigOverwrite: {
HIDE_INVITE_MORE_HEADER: true,
TOOLBAR_BUTTONS: toolbarButtons,
},
parentNode: expect.any(HTMLElement),
roomName: video.id,
userInfo: {
displayName: 'jane_doe',
},
});
expect(mockJitsi).toHaveBeenCalledTimes(2);
});
it('calls setCanShowStartButton when participant join the conference', () => {
const video = videoMockFactory({
live_info: {
medialive: {
input: {
endpoints: [
'rtmp://1.2.3.4:1935/stream-key-primary',
'rtmp://4.3.2.1:1935/stream-key-secondary',
],
},
},
jitsi: {
domain: 'meet.jit.si',
external_api_url: 'https://meet.jit.si/external_api.js',
config_overwrite: {},
interface_config_overwrite: {},
},
},
live_state: liveState.RUNNING,
live_type: LiveModeType.JITSI,
});
global.JitsiMeetExternalAPI = mockJitsi;
const mockCanShowStartButton = jest.fn();
render(
wrapInIntlProvider(
<DashboardVideoLiveJitsi
video={video}
setCanStartLive={jest.fn()}
setCanShowStartButton={mockCanShowStartButton}
isInstructor={true}
/>,
),
);
expect(mockCanShowStartButton).not.toHaveBeenCalled();
// simulates user leave the conference
dispatch('videoConferenceJoined', {});
expect(mockCanShowStartButton).toHaveBeenLastCalledWith(true);
});
it('does not start recording when isInstructor is False', () => {
const video = videoMockFactory({
live_info: {
jitsi: {
domain: 'meet.jit.si',
external_api_url: 'https://meet.jit.si/external_api.js',
config_overwrite: {},
interface_config_overwrite: {},
},
},
live_state: liveState.RUNNING,
live_type: LiveModeType.JITSI,
});
global.JitsiMeetExternalAPI = mockJitsi;
render(<DashboardVideoLiveJitsi video={video} isInstructor={false} />);
expect(mockExecuteCommand).not.toHaveBeenCalledWith(
'startRecording',
expect.any({}),
);
expect(mockExecuteCommand).not.toHaveBeenCalledWith(
'stopRecording',
expect.any(String),
);
});
it('redirects to the player when user leaves the conference and is not an instructor', () => {
const video = videoMockFactory({
live_info: {
jitsi: {
domain: 'meet.jit.si',
external_api_url: 'https://meet.jit.si/external_api.js',
config_overwrite: {},
interface_config_overwrite: {},
},
},
live_state: liveState.RUNNING,
live_type: LiveModeType.JITSI,
});
global.JitsiMeetExternalAPI = mockJitsi;
render(
wrapInRouter(
<DashboardVideoLiveJitsi video={video} isInstructor={false} />,
[
{
path: PLAYER_ROUTE(),
render: ({ match }) => {
return <span>{'video player'}</span>;
},
},
],
),
);
// simulates user leave the conference
dispatch('videoConferenceLeft', {});
expect(mockDispose).toHaveBeenCalled();
expect(mockWindow.converse.participantLeaves).toHaveBeenCalled();
screen.getByText('video player');
});
}); | the_stack |
import {OutputGlNode} from '../../../../src/engine/nodes/gl/Output';
import {SceneJsonExporter} from '../../../../src/engine/io/json/export/Scene';
import {SceneJsonImporter} from '../../../../src/engine/io/json/import/Scene';
import {BaseBuilderMatNodeType} from '../../../../src/engine/nodes/mat/_BaseBuilder';
import {GlConnectionPointType} from '../../../../src/engine/nodes/utils/io/connections/Gl';
import {ParamType} from '../../../../src/engine/poly/ParamType';
import {CoreSleep} from '../../../../src/core/Sleep';
import {FloatParam} from '../../../../src/engine/params/Float';
import {Vector3Param} from '../../../../src/engine/params/Vector3';
import {MeshBasicBuilderMatNode} from '../../../../src/engine/nodes/mat/MeshBasicBuilder';
import {ColorParam} from '../../../../src/engine/params/Color';
QUnit.test(
'MAT spare params:spare params are re-created as expected and the uniforms updated on change',
async (assert) => {
const scene = window.scene;
scene.setFrame(1);
const MAT = window.MAT;
await scene.waitForCooksCompleted();
const mesh_basic1 = MAT.createNode('meshBasicBuilder');
mesh_basic1.createNode('output');
mesh_basic1.createNode('globals');
assert.ok(mesh_basic1.assemblerController, 'assembler controller is present');
assert.ok(mesh_basic1.assemblerController?.compileRequired(), 'compiled is required');
await mesh_basic1.compute();
assert.deepEqual(mesh_basic1.params.spare_names.sort(), []);
assert.notOk(mesh_basic1.assemblerController?.compileRequired(), 'compile is not required');
const output1 = mesh_basic1.node('output1')! as OutputGlNode;
const param1 = mesh_basic1.createNode('param');
CoreSleep.sleep(10);
assert.ok(mesh_basic1.assemblerController?.compileRequired(), 'compiled is required');
const param_name = param1.p.name.value;
param1.set_gl_type(GlConnectionPointType.FLOAT);
assert.ok(mesh_basic1.assemblerController?.compileRequired(), 'compiled is required');
CoreSleep.sleep(10);
await mesh_basic1.compute();
assert.notOk(mesh_basic1.assemblerController?.compileRequired(), 'compiled is NOT required');
// param should already exist, and also uniform on mat
assert.deepEqual(mesh_basic1.params.spare_names.sort(), [param_name], 'spare params has param_name');
assert.equal(mesh_basic1.params.get(param_name)!.type(), ParamType.FLOAT);
// changing the param type updates the spare param type
param1.set_gl_type(GlConnectionPointType.INT);
await mesh_basic1.compute();
assert.equal(mesh_basic1.params.get(param_name)!.type(), ParamType.INTEGER);
// we revert back to float for the rest of the test
param1.set_gl_type(GlConnectionPointType.FLOAT);
await mesh_basic1.compute();
assert.equal(mesh_basic1.params.get(param_name)!.type(), ParamType.FLOAT);
// updating the param updates the uniform, without having to cook the material node
output1.setInput('alpha', param1);
assert.ok(mesh_basic1.assemblerController?.compileRequired(), 'compiled is required');
await mesh_basic1.compute();
assert.notOk(mesh_basic1.assemblerController?.compileRequired(), 'compiled is required');
const uniform_name = param1.uniform_name();
assert.equal(mesh_basic1.params.get(param_name)!.value, 0);
assert.equal(mesh_basic1.material.uniforms[uniform_name].value, 0);
mesh_basic1.params.get(param_name)!.set(0.5);
assert.equal(
mesh_basic1.material.uniforms[uniform_name].value,
0.5,
'param updates the uniform when its value changes'
);
// and use an expression on the param as well
mesh_basic1.params.get(param_name)!.set('$F');
assert.equal(scene.frame(), 1);
await CoreSleep.sleep(100);
assert.equal(
mesh_basic1.material.uniforms[uniform_name].value,
1,
'param updates the uniform when its expression becomes dirty'
);
scene.setFrame(2);
await CoreSleep.sleep(100);
assert.equal(
mesh_basic1.material.uniforms[uniform_name].value,
2,
'param updates the uniform when its expression becomes dirty'
);
scene.setFrame(3);
await CoreSleep.sleep(20);
assert.equal(
mesh_basic1.material.uniforms[uniform_name].value,
3,
'param updates the uniform when its expression becomes dirty again'
);
// if I change the type of the param, the raw_input stays
param1.set_gl_type(GlConnectionPointType.INT);
await mesh_basic1.compute();
let spare_param = mesh_basic1.params.get(param_name)!;
assert.equal(spare_param.type(), ParamType.INTEGER);
await CoreSleep.sleep(10);
assert.equal(spare_param.rawInput(), '$F');
assert.notOk(spare_param.isDirty(), 'param not dirty');
scene.setFrame(35);
assert.ok(spare_param.isDirty(), 'param is dirty');
assert.equal(scene.frame(), 35, 'scene frame is 35');
await spare_param.compute();
assert.equal(spare_param.value, 35, 'param is 35');
assert.equal(mesh_basic1.material.uniforms[uniform_name].value, 35, 'uniforrm is 35');
scene.timeController.setMaxFrame(1000);
scene.setFrame(124);
await spare_param.compute();
assert.equal(mesh_basic1.material.uniforms[uniform_name].value, 124, 'frame is 124');
// we revert back to float for the rest of the test
param1.set_gl_type(GlConnectionPointType.FLOAT);
await mesh_basic1.compute();
spare_param = mesh_basic1.params.get(param_name)!;
assert.equal(spare_param.type(), ParamType.FLOAT);
assert.equal(mesh_basic1.params.get(param_name)!.rawInput(), '$F');
const data = new SceneJsonExporter(scene).data();
// the param is not saved in the export data, since it will be re-created
console.log('************ LOAD **************');
const scene2 = await SceneJsonImporter.loadData(data);
await scene2.waitForCooksCompleted();
const new_mesh_basic1 = scene2.node('/MAT/meshBasicBuilder1') as BaseBuilderMatNodeType;
await new_mesh_basic1.compute();
assert.ok(new_mesh_basic1.assemblerController, 'assembler_controller is present');
assert.notOk(new_mesh_basic1.assemblerController?.compileRequired(), 'compile is not required');
assert.deepEqual(new_mesh_basic1.params.spare_names.sort(), [param_name], 'spare params has param_name');
assert.equal(new_mesh_basic1.params.get(param_name)?.rawInput(), '$F', 'param raw input is $F');
await CoreSleep.sleep(100);
assert.equal(new_mesh_basic1.params.get(param_name)?.value, 124, 'param value is 124');
assert.equal(new_mesh_basic1.material.uniforms[uniform_name].value, 124, 'uniform is 124');
// update the param to be sure dependency with frame has been created
scene2.setFrame(2);
await CoreSleep.sleep(100);
assert.equal(
new_mesh_basic1.material.uniforms[uniform_name].value,
2,
'param updates the uniform when its expression becomes dirty'
);
scene2.setFrame(10);
await CoreSleep.sleep(20);
assert.equal(
new_mesh_basic1.material.uniforms[uniform_name].value,
10,
'param updates the uniform when its expression becomes dirty again'
);
}
);
QUnit.test('MAT spare params:creating a spare param as vector, saving and load back', async (assert) => {
const scene = window.scene;
const MAT = window.MAT;
const mesh_basic1 = MAT.createNode('meshBasicBuilder');
mesh_basic1.createNode('output');
mesh_basic1.createNode('globals');
await scene.waitForCooksCompleted();
await mesh_basic1.compute();
assert.deepEqual(mesh_basic1.params.spare_names.sort(), []);
assert.notOk(mesh_basic1.assemblerController?.compileRequired());
// const output1 = mesh_basic1.node('output1')! as OutputGlNode;
assert.notOk(mesh_basic1.assemblerController?.compileRequired(), 'compiled is required');
const param1 = mesh_basic1.createNode('param');
const param_name = param1.p.name.value;
const uniform_name = param1.uniform_name();
// first compute with a float, and only after compute with a vector, to make sure the new val is okay
param1.set_gl_type(GlConnectionPointType.FLOAT);
await CoreSleep.sleep(100);
const float_spare_param = mesh_basic1.params.get(param_name)! as FloatParam;
assert.equal(float_spare_param.type(), ParamType.FLOAT, 'param is float');
assert.equal(mesh_basic1.material.uniforms[uniform_name].value, 0);
float_spare_param.set(0.25);
assert.equal(mesh_basic1.material.uniforms[uniform_name].value, 0.25);
// now change to vec3
param1.set_gl_type(GlConnectionPointType.VEC3);
await CoreSleep.sleep(100);
let vec3_spare_param = mesh_basic1.params.get(param_name)! as Vector3Param;
assert.equal(vec3_spare_param.type(), ParamType.VECTOR3, 'param is vec3');
assert.deepEqual(vec3_spare_param.valueSerialized(), [0.25, 0.25, 0.25], 'value_serialized is 0.25,0.25,0.25');
assert.deepEqual(vec3_spare_param.defaultValueSerialized(), [0, 0, 0], 'default_value_serialized is 0,0,0');
vec3_spare_param.set([0.1, 0.2, 0.3]);
assert.equal(mesh_basic1.material.uniforms[uniform_name].value.x, 0.1);
assert.equal(mesh_basic1.material.uniforms[uniform_name].value.y, 0.2);
assert.equal(mesh_basic1.material.uniforms[uniform_name].value.z, 0.3);
vec3_spare_param.y.set(0.8);
assert.equal(mesh_basic1.material.uniforms[uniform_name].value.x, 0.1);
assert.equal(mesh_basic1.material.uniforms[uniform_name].value.y, 0.8);
assert.equal(mesh_basic1.material.uniforms[uniform_name].value.z, 0.3);
const data = new SceneJsonExporter(scene).data();
// the param is not saved in the export data, since it will be re-created
console.log('************ LOAD **************');
const scene2 = await SceneJsonImporter.loadData(data);
await scene2.waitForCooksCompleted();
await CoreSleep.sleep(10);
const mesh_basic2 = scene2.node(`/MAT/${mesh_basic1.name()}`)! as MeshBasicBuilderMatNode;
const vec3_spare_param2 = mesh_basic2.params.get(param_name)! as Vector3Param;
assert.equal(vec3_spare_param2.type(), ParamType.VECTOR3);
assert.deepEqual(
vec3_spare_param2.valueSerialized(),
[0.1, 0.8, 0.3],
'after load value_serialized is 0.1,0.8,0.3'
);
assert.deepEqual(
vec3_spare_param2.defaultValueSerialized(),
[0, 0, 0],
'after load default_value_serialized is 0,0,0'
);
await CoreSleep.sleep(100);
vec3_spare_param2.set([0.1, 0.2, 0.3]);
await CoreSleep.sleep(100);
assert.equal(vec3_spare_param2.value.x, 0.1);
assert.equal(vec3_spare_param2.value.y, 0.2);
assert.equal(vec3_spare_param2.value.z, 0.3);
assert.equal(mesh_basic2.material.uniforms[uniform_name].value.x, 0.1);
assert.equal(mesh_basic2.material.uniforms[uniform_name].value.y, 0.2);
assert.equal(mesh_basic2.material.uniforms[uniform_name].value.z, 0.3);
return;
vec3_spare_param2.y.set(0.8);
assert.equal(mesh_basic2.material.uniforms[uniform_name].value.x, 0.1);
assert.equal(mesh_basic2.material.uniforms[uniform_name].value.y, 0.8);
assert.equal(mesh_basic2.material.uniforms[uniform_name].value.z, 0.3);
});
QUnit.test('MAT spare params: creating a spare param as color, saving and load back', async (assert) => {
const scene = window.scene;
const MAT = window.MAT;
const mesh_basic1 = MAT.createNode('meshBasicBuilder');
mesh_basic1.createNode('output');
mesh_basic1.createNode('globals');
assert.ok(mesh_basic1.assemblerController?.compileRequired(), 'compile required');
await scene.waitForCooksCompleted();
await mesh_basic1.compute();
assert.deepEqual(mesh_basic1.params.spare_names.sort(), [], 'no spare params');
assert.notOk(mesh_basic1.assemblerController?.compileRequired(), 'compile not required');
// const output1 = mesh_basic1.node('output1')! as OutputGlNode;
// assert.notOk(mesh_basic1.assembler_controller.compileRequired(), 'compile is required');
const param1 = mesh_basic1.createNode('param');
const param_name = param1.p.name.value;
const uniform_name = param1.uniform_name();
// first compute with a float, and only after compute with a vector, to make sure the new val is okay
param1.set_gl_type(GlConnectionPointType.FLOAT);
await mesh_basic1.compute();
const float_spare_param = mesh_basic1.params.get(param_name)! as FloatParam;
assert.equal(float_spare_param.type(), ParamType.FLOAT, 'param is float');
assert.equal(mesh_basic1.material.uniforms[uniform_name].value, 0);
float_spare_param.set(0.25);
assert.equal(mesh_basic1.material.uniforms[uniform_name].value, 0.25);
// now change to vec3
param1.set_gl_type(GlConnectionPointType.VEC3);
param1.p.asColor.set(1);
await mesh_basic1.compute();
let vec3_spare_param = mesh_basic1.params.get(param_name)! as ColorParam;
assert.equal(vec3_spare_param.type(), ParamType.COLOR, 'param is color');
assert.deepEqual(vec3_spare_param.valueSerialized(), [0.25, 0.25, 0.25], 'value_serialized is 0.25,0.25,0.25');
assert.deepEqual(vec3_spare_param.defaultValueSerialized(), [0, 0, 0], 'default_value_serialized is 0,0,0');
vec3_spare_param.set([0.1, 0.2, 0.3]);
assert.equal(mesh_basic1.material.uniforms[uniform_name].value.r, 0.1);
assert.equal(mesh_basic1.material.uniforms[uniform_name].value.g, 0.2);
assert.equal(mesh_basic1.material.uniforms[uniform_name].value.b, 0.3);
vec3_spare_param.g.set(0.8);
assert.equal(mesh_basic1.material.uniforms[uniform_name].value.r, 0.1);
assert.equal(mesh_basic1.material.uniforms[uniform_name].value.g, 0.8);
assert.equal(mesh_basic1.material.uniforms[uniform_name].value.b, 0.3);
console.log('************ EXPORT **************');
const data = new SceneJsonExporter(scene).data();
// the param is not saved in the export data, since it will be re-created
console.log('************ LOAD **************');
const scene2 = await SceneJsonImporter.loadData(data);
await scene2.waitForCooksCompleted();
await CoreSleep.sleep(100);
const mesh_basic2 = scene2.node(`/MAT/${mesh_basic1.name()}`)! as MeshBasicBuilderMatNode;
const vec3_spare_param2 = mesh_basic2.params.get(param_name)! as ColorParam;
assert.equal(vec3_spare_param2.type(), ParamType.COLOR);
assert.deepEqual(
vec3_spare_param2.valueSerialized(),
[0.1, 0.8, 0.3],
'after load value_serialized is 0.1,0.8,0.3'
);
assert.deepEqual(
vec3_spare_param2.defaultValueSerialized(),
[0, 0, 0],
'after load default_value_serialized is 0,0,0'
);
// Note: the uniform should be set to the param value,
// But it currently seems that this is not happening because the param is set
// while the scene is loading, therefore the callback is not executed.
// But this does not seem to be a problem when running the scene
// vec3_spare_param2.options.execute_callback();
// console.log('mesh_basic2', uniform_name, mesh_basic2.material);
// assert.equal(mesh_basic2.material.uniforms[uniform_name].value.r, 0.1);
// assert.equal(mesh_basic2.material.uniforms[uniform_name].value.g, 0.8);
// assert.equal(mesh_basic2.material.uniforms[uniform_name].value.b, 0.3);
vec3_spare_param2.set([0.7, 0.2, 0.15]);
assert.equal(mesh_basic2.material.uniforms[uniform_name].value.r, 0.7);
assert.equal(mesh_basic2.material.uniforms[uniform_name].value.g, 0.2);
assert.equal(mesh_basic2.material.uniforms[uniform_name].value.b, 0.15);
vec3_spare_param2.g.set(0.6);
assert.equal(mesh_basic2.material.uniforms[uniform_name].value.r, 0.7);
assert.equal(mesh_basic2.material.uniforms[uniform_name].value.g, 0.6);
assert.equal(mesh_basic2.material.uniforms[uniform_name].value.b, 0.15);
}); | the_stack |
* Imports
*/
import * as tf from '@tensorflow/tfjs-core';
import * as support from '../core/sketch_support';
/**
* Interface for JSON specification of a `MusicVAE` model.
*
* @property max_seq_len: Model trained on dataset w/ this max sequence length.
* @property mode: Pre-trained models have this parameter for legacy reasons.
* 0 for VAE, 1 for Decoder only. This model is Decoder only (not used).
* @property name: QuickDraw name, like cat, dog, elephant, etc
* @property scale_factor: the factor to convert from neural-network space to
* pixel space. Most pre-trained models have this number between 80-120
* @property version: Pre-trained models have a version between 1-6, for
* the purpose of experimental research log.
*/
export interface SketchRNNInfo {
max_seq_len: number;
mode: number;
name: string;
scale_factor: number;
version: number;
}
/**
* Interface for specification of the Probability Distribution Function
* of a pen stroke.
*
* Please refer to "A Neural Representation of Sketch Drawings"
* https://arxiv.org/abs/1704.03477
*
* In Eq.3 is an explanation of all of these parameters.
*
* Below is a brief description:
*
* @property pi: categorial distribution for mixture of Gaussian
* @property muX: mean for x-axis
* @property muY: mean for y-axis
* @property sigmaX: standard deviation of x-axis
* @property sigmaY: standard deviation of y-axis
* @property corr: correlation parameter between x and y
* @property pen: categorical distribution for the 3 pen states
*/
export interface StrokePDF {
pi: Float32Array;
muX: Float32Array;
muY: Float32Array;
sigmaX: Float32Array;
sigmaY: Float32Array;
corr: Float32Array;
pen: Float32Array;
}
/**
* States of the LSTM Cell
*
* Long-Short Term Memory: ftp://ftp.idsia.ch/pub/juergen/lstm.pdf
*
* @property c: memory "cell" of the LSTM.
* @property h: hidden state (also the output) of the LSTM.
*/
export interface LSTMState {
c: Float32Array;
h: Float32Array;
}
/**
* Main SketchRNN model class.
*
* Implementation of decoder model in https://arxiv.org/abs/1704.03477
*
* TODO(hardmaru): make a "batch" continueSequence-like method
* that runs fully on GPU.
*/
export class SketchRNN {
private checkpointURL: string;
private forgetBias: tf.Scalar;
private initialized: boolean;
public info: SketchRNNInfo;
public numUnits: number;
public pixelFactor: number;
public scaleFactor: number;
// raw weights and dimensions directly from JSON
private weights: Float32Array[];
private weightDims: number[][];
// TensorFlow.js weight matrices
private outputKernel: tf.Tensor2D;
private outputBias: tf.Tensor1D;
private lstmKernel: tf.Tensor2D;
private lstmBias: tf.Tensor1D;
private rawVars: tf.Tensor[];
private NMIXTURE = 20;
/**
* `SketchRNN` constructor.
*
* @param checkpointURL Path to the checkpoint directory.
*/
constructor(checkpointURL: string) {
this.checkpointURL = checkpointURL;
this.initialized = false;
}
/**
* Returns true if model is intialized.
*/
isInitialized() {
return this.initialized;
}
/**
* Instantiates class information inputs from the JSON model.
* TODO(hardmaru): to add support for new tfjs checkpoints.
*/
private instantiateFromJSON(info: SketchRNNInfo,
weightDims: number[][],
weightStrings: string[]) {
this.forgetBias = tf.scalar(1.0);
this.info = info;
this.setPixelFactor(2.0);
this.weightDims = weightDims;
this.numUnits = this.weightDims[0][0]; // size of LSTM
let rawWeights: Float32Array;
const maxWeight = 10.0;
this.weights = [];
for (let i = 0; i < weightStrings.length; i++) {
rawWeights = new Float32Array(support.stringToArray(weightStrings[i]));
const N: number = rawWeights.length;
for (let j = 0; j < N; j++) {
rawWeights[j] = maxWeight * rawWeights[j] / 32767;
}
this.weights.push(rawWeights);
}
this.outputKernel = tf.tensor2d(this.weights[0],
[this.weightDims[0][0], this.weightDims[0][1]]);
this.outputBias = tf.tensor1d(this.weights[1]);
const lstmKernelXH = tf.tensor2d(this.weights[2],
[this.weightDims[2][0], this.weightDims[2][1]]);
const lstmKernelHH = tf.tensor2d(this.weights[3],
[this.weightDims[3][0], this.weightDims[3][1]]);
const axis = 0;
this.lstmKernel = tf.concat2d([lstmKernelXH, lstmKernelHH], axis);
this.lstmBias = tf.tensor1d(this.weights[4]);
this.rawVars = [
this.outputKernel,
this.outputBias,
this.lstmKernel,
this.lstmBias
];
}
/**
* Loads variables from the JSON model
*/
async initialize() {
this.dispose();
const vars = await fetch(this.checkpointURL)
.then((response) => response.json());
this.instantiateFromJSON(vars[0], vars[1], vars[2]);
this.initialized = true;
console.log('Initialized SketchRNN.');
}
dispose() {
if (this.rawVars) {
for (let i = 0; i < this.rawVars.length; i++) {
this.rawVars[i].dispose();
}
this.rawVars = undefined;
}
if (this.forgetBias) {
this.forgetBias.dispose();
this.forgetBias = undefined;
}
this.initialized = false;
}
/**
* Sets the internal EXTRA factor of this model (pixel to model space)
*
* @param scale (the extra scale factor for pixel to model space)
*
* @returns nothing
*/
setPixelFactor(scale: number) {
// for best effect, set to 1.0 for d3 or paper.js, 2.0 for p5.js
this.pixelFactor = scale;
this.scaleFactor = this.info.scale_factor / this.pixelFactor;
}
/**
* Updates the RNN, returns the next state.
*
* @param stroke [dx, dy, penDown, penUp, penEnd].
* @param state previous LSTMState.
*
* @returns next LSTMState.
*/
update(stroke: number[], state: LSTMState) {
const out = tf.tidy(() => {
const numUnits = this.numUnits;
const s = this.scaleFactor;
const normStroke =
[stroke[0]/s, stroke[1]/s, stroke[2], stroke[3], stroke[4]];
const x = tf.tensor2d(normStroke, [1, 5]);
const c = tf.tensor2d(state.c, [1, numUnits]);
const h = tf.tensor2d(state.h, [1, numUnits]);
const newState = tf.basicLSTMCell(
this.forgetBias,
this.lstmKernel,
this.lstmBias,
x,
c,
h);
return tf.concat(newState, 1);
});
const newCH = out.dataSync();
out.dispose();
const newC = newCH.slice(0, this.numUnits);
const newH = newCH.slice(this.numUnits, this.numUnits * 2);
const finalState:LSTMState = {
c: new Float32Array(newC),
h: new Float32Array(newH)
};
return finalState;
}
/**
* Updates the RNN on a series of Strokes, returns the next state.
*
* @param strokes list of [dx, dy, penDown, penUp, penEnd].
* @param state previous LSTMState.
* @param steps (Optional) number of steps of the stroke to update
* (default is length of strokes list)
*
*
* @returns the final LSTMState.
*/
updateStrokes(strokes: number[][], state: LSTMState, steps?: number) {
const out = tf.tidy(() => {
const numUnits = this.numUnits;
const s = this.scaleFactor;
let normStroke:number[];
let x: tf.Tensor2D;
let c: tf.Tensor2D;
let h: tf.Tensor2D;
let newState: tf.Tensor2D[];
let numSteps = strokes.length;
if (steps) {
numSteps = steps;
}
c = tf.tensor2d(state.c, [1, numUnits]);
h = tf.tensor2d(state.h, [1, numUnits]);
for (let i=0;i<numSteps;i++) {
normStroke = [strokes[i][0]/s,
strokes[i][1]/s,
strokes[i][2],
strokes[i][3],
strokes[i][4]];
x = tf.tensor2d(normStroke, [1, 5]);
newState = tf.basicLSTMCell(
this.forgetBias,
this.lstmKernel,
this.lstmBias,
x,
c,
h);
c = newState[0];
h = newState[1];
}
return tf.concat(newState, 1);
});
const newCH = out.dataSync();
out.dispose();
const newC = newCH.slice(0, this.numUnits);
const newH = newCH.slice(this.numUnits, this.numUnits * 2);
const finalState:LSTMState = {
c: new Float32Array(newC),
h: new Float32Array(newH)
};
return finalState;
}
/**
* Given the RNN state, returns the probability distribution function (pdf)
* of the next stroke. Optionally adjust the temperature of the pdf here.
*
* @param state previous LSTMState.
* @param temperature (Optional) for dx and dy (default 0.65)
* @param softmaxTemperature (Optional) for Pi and Pen discrete states
* (default is temperature * 0.5 + 0.5, which is a nice heuristic.)
*
* @returns StrokePDF (pi, muX, muY, sigmaX, sigmaY, corr, pen)
*/
getPDF(state: LSTMState,
temperature=0.65,
softmaxTemperature?: number) {
const temp = temperature;
let discreteTemp: number = 0.5 + temp * 0.5; // good heuristic.
if (softmaxTemperature) {
discreteTemp = softmaxTemperature;
}
const NOUT = this.NMIXTURE;
const out = tf.tidy(() => {
const numUnits = this.numUnits;
const h = tf.tensor2d(state.h, [1, numUnits]);
const sqrttemp = tf.scalar(Math.sqrt(temp));
const softtemp = tf.scalar(discreteTemp);
const z = tf.add(tf.matMul(h, this.outputKernel), this.outputBias)
.squeeze();
const [rawPen, rst] = tf.split(z, [3, NOUT*6]);
const [rawPi, mu1, mu2, rawSigma1, rawSigma2, rawCorr] = tf.split(rst, 6);
const pen = tf.softmax(rawPen.div(softtemp));
const pi = tf.softmax(rawPi.div(softtemp));
const sigma1 = tf.exp(rawSigma1).mul(sqrttemp);
const sigma2 = tf.exp(rawSigma2).mul(sqrttemp);
const corr = tf.tanh(rawCorr);
const result = [pi, mu1, mu2, sigma1, sigma2, corr, pen];
// concat, and then unpack after dataSync
return tf.concat(result);
});
const result = out.dataSync();
out.dispose();
const pdf:StrokePDF = { // note: JS doesn't have a nice "split" method.
pi: new Float32Array(result.slice(0, NOUT)),
muX: new Float32Array(result.slice(1*NOUT, 2*NOUT)),
muY: new Float32Array(result.slice(2*NOUT, 3*NOUT)),
sigmaX: new Float32Array(result.slice(3*NOUT, 4*NOUT)),
sigmaY: new Float32Array(result.slice(4*NOUT, 15*NOUT)),
corr: new Float32Array(result.slice(5*NOUT, 6*NOUT)),
pen: new Float32Array(result.slice(6*NOUT, 6*NOUT+3))
};
return pdf;
}
/**
* Returns the zero/initial state of the model
*
* @returns zero state of the lstm: [c, h], where c and h are zero vectors.
*/
zeroState() {
const result:LSTMState = {
c: new Float32Array(this.numUnits),
h: new Float32Array(this.numUnits)
};
return result;
}
/**
* Returns a new copy of the rnn state
*
* @param rnnState original LSTMState
*
* @returns copy of LSTMState
*/
copyState(rnnState: LSTMState) {
const result:LSTMState = {
c: new Float32Array(rnnState.c),
h: new Float32Array(rnnState.h)
};
return result;
}
/**
* Returns the zero input state of the model
*
* @returns [0, 0, 1, 0, 0].
*/
zeroInput() {
return [0, 0, 1, 0, 0];
}
/**
* Samples the next point of the sketch given pdf parameters
*
* @param pdf result from getPDF() call
*
* @returns [dx, dy, penDown, penUp, penEnd]
*/
sample(pdf: StrokePDF) {
// pdf is a StrokePDF Interface
// returns [x, y, eos]
const idx = support.sampleSoftmax(pdf.pi);
const mu1 = pdf.muX[idx];
const mu2 = pdf.muY[idx];
const sigma1 = pdf.sigmaX[idx];
const sigma2 = pdf.sigmaY[idx];
const corr = pdf.corr[idx];
const penIdx = support.sampleSoftmax(pdf.pen);
const penstate = [0, 0, 0];
penstate[penIdx] = 1;
const delta = support.birandn(mu1, mu2, sigma1, sigma2, corr);
const stroke = [
delta[0] * this.scaleFactor,
delta[1] * this.scaleFactor,
penstate[0],
penstate[1],
penstate[2]
];
return stroke;
}
/**
* Simplifies line using RDP algorithm
*
* @param line list of points [[x0, y0], [x1, y1], ...]
* @param tolerance (Optional) default 2.0
*
* @returns simpified line [[x0', y0'], [x1', y1'], ...]
*/
simplifyLine(line: number[][], tolerance?: number) {
return support.simplifyLine(line, tolerance);
}
/**
* Simplifies lines using RDP algorithm
*
* @param line list of lines (each element is [[x0, y0], [x1, y1], ...])
* @param tolerance (Optional) default 2.0
*
* @returns simpified lines (each elem is [[x0', y0'], [x1', y1'], ...])
*/
simplifyLines(lines: number[][][], tolerance?: number) {
return support.simplifyLines(lines, tolerance);
}
/**
* Convert from polylines to stroke-5 format that sketch-rnn uses
*
* @param lines list of points each elem is ([[x0, y0], [x1, y1], ...])
*
* @returns stroke-5 format of the line, list of [dx, dy, p0, p1, p2]
*/
linesToStroke(lines: number[][][]) {
return support.linesToStrokes(lines);
}
/**
* Convert from a line format to stroke-5
*
* @param line list of points [[x0, y0], [x1, y1], ...]
* @param lastPoint the absolute position of the last point
*
* @returns stroke-5 format of the line, list of [dx, dy, p0, p1, p2]
*/
lineToStroke(line: number[][], lastPoint: number[]) {
return support.lineToStroke(line, lastPoint);
}
} | the_stack |
import {
Provider,
Type,
} from '@angular/core';
import { ComponentFixture } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import {
createComponent as createComponentInner,
typeInElement,
} from '@terminus/ngx-tools/testing';
import * as testComponents from '@terminus/ui/date-range/testing';
// eslint-disable-next-line no-duplicate-imports
import { getRangeInputInstances } from '@terminus/ui/date-range/testing';
import { TsDateRangeModule } from './date-range.module';
/**
* NOTE (B$): The ideal test would be to actually check the DOM to verify that specific dates are disabled etc. I was not having any luck
* querying that deeply into the generated DOM. So, for now, we are simply testing the class as fully as possible.
*/
describe(`TsDateRangeComponent`, function() {
describe(`date constraints`, function() {
test(`should set the END min date according to the start date`, function() {
const fixture = createComponent(testComponents.SeededDates);
fixture.detectChanges();
const endInputInstance = getRangeInputInstances(fixture)[1];
expect(endInputInstance.minDate).toEqual(new Date(2018, 1, 1));
});
test(`should set the START max date according to the end date`, function() {
const fixture = createComponent(testComponents.SeededDates);
fixture.detectChanges();
const startInputInstance = getRangeInputInstances(fixture)[0];
expect(startInputInstance.maxDate).toEqual(new Date(2018, 1, 12));
});
test(`should set the START max date according to the end date on BLUR`, function() {
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
const [startInputInstance, endInputInstance] = getRangeInputInstances(fixture);
const endInputElement = endInputInstance.inputElement.nativeElement;
typeInElement('3-4-2019', endInputElement);
endInputElement.blur();
fixture.detectChanges();
expect(startInputInstance.maxDate).toEqual(new Date('3-4-2019'));
});
});
describe(`control syncing`, function() {
describe(`internal controls`, function() {
test(`should update their VALUE when the external control value changes`, function() {
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
const [startInputInstance, endInputInstance] = getRangeInputInstances(fixture);
expect(startInputInstance.formControl.value).toEqual(null);
expect(endInputInstance.formControl.value).toEqual(null);
const date = new Date(2018, 3, 3);
startInputInstance.formControl.setValue(date);
endInputInstance.formControl.setValue(date);
fixture.detectChanges();
expect(fixture.componentInstance.dateRangeComponent.internalStartControl.value).toEqual(date);
expect(fixture.componentInstance.dateRangeComponent.internalEndControl.value).toEqual(date);
expect.assertions(4);
});
// internal status/error updated by external ctrl
test(`should update their STATUS when the external control changes`, function() {
jest.useFakeTimers();
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
const [startInputInstance, endInputInstance] = getRangeInputInstances(fixture);
expect(startInputInstance.formControl.valid).toEqual(true);
expect(endInputInstance.formControl.valid).toEqual(true);
// Simulate user entering and leaving the input to trigger validation
startInputInstance.inputElement.nativeElement.focus();
endInputInstance.inputElement.nativeElement.focus();
fixture.detectChanges();
startInputInstance.inputElement.nativeElement.blur();
endInputInstance.inputElement.nativeElement.blur();
fixture.detectChanges();
expect(startInputInstance.formControl.errors).toEqual({ required: true });
expect(endInputInstance.formControl.errors).toEqual({ required: true });
jest.runAllTimers();
expect.assertions(4);
});
test(`should do nothing if no controls exist`, function() {
jest.useFakeTimers();
const fixture = createComponent(testComponents.NoControls);
fixture.detectChanges();
const [startInputInstance, endInputInstance] = getRangeInputInstances(fixture);
expect(startInputInstance.formControl.valid).toEqual(true);
expect(endInputInstance.formControl.valid).toEqual(true);
// Simulate user entering and leaving the input to trigger validation
startInputInstance.inputElement.nativeElement.focus();
endInputInstance.inputElement.nativeElement.focus();
fixture.detectChanges();
startInputInstance.inputElement.nativeElement.blur();
endInputInstance.inputElement.nativeElement.blur();
fixture.detectChanges();
expect(startInputInstance.formControl.errors).toEqual(null);
expect(endInputInstance.formControl.errors).toEqual(null);
jest.runAllTimers();
expect.assertions(4);
});
});
describe(`external controls`, function() {
test(`should update their VALUE when the internal control changes`, function() {
const fixture = createComponent(testComponents.Basic);
fixture.detectChanges();
const [startInputInstance, endInputInstance] = getRangeInputInstances(fixture);
expect(startInputInstance.formControl.value).toBeNull();
expect(endInputInstance.formControl.value).toBeNull();
typeInElement('3-4-2019', startInputInstance.inputElement.nativeElement);
startInputInstance.inputElement.nativeElement.blur();
typeInElement('3-8-2019', endInputInstance.inputElement.nativeElement);
endInputInstance.inputElement.nativeElement.blur();
fixture.detectChanges();
expect(fixture.componentInstance.dateRangeComponent.internalStartControl.value).toEqual(new Date('3-4-2019'));
expect(fixture.componentInstance.dateRangeComponent.internalEndControl.value).toEqual(new Date('3-8-2019'));
expect.assertions(4);
});
});
});
describe(`emitters`, function() {
let fixture: ComponentFixture<testComponents.Emitters>;
beforeEach(() => {
fixture = createComponent(testComponents.Emitters);
fixture.componentInstance.dateRangeChange = jest.fn();
fixture.componentInstance.startSelected = jest.fn();
fixture.componentInstance.endSelected = jest.fn();
fixture.detectChanges();
});
test(`should pass correct values when fired`, function() {
const [startInputInstance, endInputInstance] = getRangeInputInstances(fixture);
typeInElement('3-4-2019', startInputInstance.inputElement.nativeElement);
startInputInstance.inputElement.nativeElement.blur();
fixture.detectChanges();
expect(fixture.componentInstance.startSelected).toHaveBeenCalledWith(new Date('3-4-2019'));
expect(fixture.componentInstance.dateRangeChange).toHaveBeenCalledWith({
start: new Date('3-4-2019'),
end: null,
});
typeInElement('3-8-2019', endInputInstance.inputElement.nativeElement);
endInputInstance.inputElement.nativeElement.blur();
fixture.detectChanges();
expect(fixture.componentInstance.endSelected).toHaveBeenCalledWith(new Date('3-8-2019'));
expect(fixture.componentInstance.dateRangeChange).toHaveBeenCalledWith({
start: new Date('3-4-2019'),
end: new Date('3-8-2019'),
});
typeInElement('', startInputInstance.inputElement.nativeElement);
fixture.detectChanges();
startInputInstance.inputElement.nativeElement.blur();
fixture.detectChanges();
const changeMock = fixture.componentInstance.dateRangeChange.mock;
expect(changeMock.calls[changeMock.calls.length - 1][0]).toEqual({
start: null,
end: new Date('3-8-2019'),
});
expect.assertions(5);
});
});
describe(`input component`, function() {
test(`should receive all needed parameters from the date range component`, function() {
const fixture = createComponent(testComponents.Params);
const hostInstance = fixture.componentInstance;
fixture.detectChanges();
const [startInputInstance, endInputInstance] = getRangeInputInstances(fixture);
expect(endInputInstance.maxDate).toEqual(hostInstance.endMax);
expect(endInputInstance.minDate).toEqual(hostInstance.endMin);
expect(startInputInstance.isDisabled).toEqual(true);
expect(endInputInstance.isDisabled).toEqual(true);
expect(startInputInstance.startingView).toEqual(hostInstance.startingView);
expect(endInputInstance.startingView).toEqual(hostInstance.startingView);
expect(startInputInstance.maxDate).toEqual(hostInstance.startMax);
expect(startInputInstance.minDate).toEqual(hostInstance.startMin);
expect(startInputInstance.theme).toEqual(hostInstance.theme);
expect(endInputInstance.theme).toEqual(hostInstance.theme);
expect.assertions(10);
});
});
test(`should work without a form group`, function() {
const fixture = createComponent(testComponents.NoFormGroup);
fixture.componentInstance.startSelected = jest.fn();
fixture.detectChanges();
const startInputInstance = getRangeInputInstances(fixture)[0];
typeInElement('3-4-2019', startInputInstance.inputElement.nativeElement);
startInputInstance.inputElement.nativeElement.blur();
fixture.detectChanges();
expect(fixture.componentInstance.startSelected).toHaveBeenCalled();
});
});
/**
* Create component
*
* @param component
* @param providers
* @param imports
*/
const createComponent =
<T>(component: Type<T>, providers: Provider[] = [], imports: any[] = []): ComponentFixture<T> => createComponentInner<T>(component,
providers,
[
ReactiveFormsModule,
TsDateRangeModule,
...imports,
]); | the_stack |
import {ParseConformance} from './parseConformance';
interface PathStructure {
name?: string;
params?: StatementStructure[];
}
interface StatementStructure {
resourceType?: string;
value?: string;
path?: [string | PathStructure];
left?: StatementStructure;
right?: StatementStructure;
op?: string;
}
export class FhirPath {
private parser: any;
readonly resources: any;
readonly operators = ['=', '!', '&', '<', '>', '~'];
private findClosingParenIndex(string, startIndex) {
let parenLevel = 0;
for (let i = startIndex; i < string.length; i++) {
if (string[i] === '(') {
parenLevel++;
} else if (string[i] === ')') {
if (parenLevel > 0) {
parenLevel--;
} else {
return i;
}
}
}
}
private findClosingQuoteIndex(string, startIndex) {
for (let i = startIndex; i < string.length; i++) {
if (string[i] === '\'') {
if (string[i-1] === '\\') {
continue;
}
return i;
}
}
}
/**
* Constructs a new instance of the FhirPath class with one or mores resources
* @classdesc Handles evaluation of FhirPath against one or more resources. See {@link http://build.fhir.org/fhirpath.html} for more information.
* @param {Resource|Array<Resource>} resources One or more resources that the class should evaluate FhirPath against
* @param {ParseConformance} parser The conformance parser to use when needing to reference definitions of resources
* @class
*/
constructor(resources, parser) {
this.resources = resources instanceof Array ? resources : [resources];
this.parser = parser ? parser : new ParseConformance(true);
}
/**
* Attempts to resolve the resource reference using this resources.
* If no resource is found in the resources provided to the FhirPath class, calls the resolve event.
* @param {string} reference The resource reference string to resolve
* @return {Resource}
* @fires FhirPath#resolve
* @private
*/
private internalResolve(reference) {
const regex = /^([A-z]+)\/(.+?)$/;
const match = reference.trim().match(regex);
function find(resources, resourceType, id) {
for (let i = 0; i < resources.length; i++) {
const resource = resources[i];
if (resource.resourceType === 'Bundle') {
// recursively search through resources in the bundle
const childResources = resource.entry.map(e => e.resource);
const found = find(childResources, resourceType, id);
if (found) {
return found;
}
}
if (resource.resourceType.toLowerCase() !== resourceType.toLowerCase()) {
continue;
}
if (resource.id.toLowerCase() !== id.toLowerCase()) {
continue;
}
return resource;
}
}
if (match) {
const found = find(this.resources, match[1], match[2]);
if (found) {
return found;
}
}
return this.resolve(reference);
}
/**
* A callback which is executed when a reference needs to be resolved to a resource.
* This should be overridden by the caller of the FhirPath class.
* @param {string} reference The reference that needs to be resolved
* @returns Should return a Resource instance
* @event
*/
public resolve(reference) {
return;
}
/**
* Gets a list of all resource type names from the ParseConformance class loaded with the FhirPath class.
* @returns {string[]}
* @private
*/
private getResourceTypes() {
const self = this;
const keys = Object.keys(this.parser.parsedStructureDefinitions);
return keys.filter(key => self.parser.parsedStructureDefinitions[key]._kind === 'resource');
}
/**
* Parses the specified path into a structure
* @param {string} fhirPath
* @returns {Array}
* @private
*/
public parse(fhirPath): StatementStructure[] {
const statements = [];
let ns: StatementStructure = {}; // newStatement
const fhirPathSplit = fhirPath.split('.');
const resourceTypes = this.getResourceTypes();
if (fhirPathSplit.length > 0 && resourceTypes.indexOf(fhirPathSplit[0]) >= 0) {
ns.resourceType = fhirPathSplit[0];
fhirPath = fhirPath.substring(fhirPathSplit[0].length+1);
}
for (let i = 0; i < fhirPath.length; i++) {
const char = fhirPath[i];
if (char === '\'') {
if (i === 0) {
const closingQuoteIndex = this.findClosingQuoteIndex(fhirPath, i+1);
ns.value = fhirPath.substring(i+1, closingQuoteIndex);
i = closingQuoteIndex;
}
} else if (char === '(') {
if (ns.path && ns.path.length > 0) { // Paren is used for function
const fn: PathStructure = {
name: (<string>ns.path.pop()).toLowerCase()
};
ns.path.push(fn);
// set the params for the function
const closingParenIndex = this.findClosingParenIndex(fhirPath, i+1);
const fnParams = fhirPath.substring(i+1, closingParenIndex);
fn.params = this.parse(fnParams);
i = closingParenIndex;
}
// TODO
} else if (char === '\'') {
// TODO?
} else if (char === ' ') {
// TODO?
} else if (this.operators.indexOf(char) >= 0) {
const left = ns;
let rightPath = fhirPath.substring(i+1);
let operator = char;
// Double-operator
if (this.operators.indexOf(rightPath[0]) >= 0) {
operator += rightPath[0];
rightPath = rightPath.substring(1);
}
ns = {
left: left,
right: this.parse(rightPath.trim())[0], // TODO: Should right ever be an array? Don't think so
op: operator
}
if (ns.left.path && ns.left.path.length > 0) {
ns.left.path[ns.left.path.length-1] = (<string>ns.left.path[ns.left.path.length-1]).trim();
}
if (ns.right.path && ns.right.path.length > 0) {
ns.right.path[ns.right.path.length-1] = (<string>ns.right.path[ns.right.path.length-1]).trim();
}
break;
} else if (char === '.') {
ns.path.push('');
} else {
if (!ns.hasOwnProperty('path')) {
ns.path = [''];
}
ns.path[ns.path.length-1] += char;
}
}
statements.push(ns);
return statements;
}
private getValue(current, paths): any {
if (current === undefined || current == null) {
return current;
}
if (!paths || paths.length === 0) {
return current;
}
const nextPath = paths[0];
const nextPaths = paths.slice(1);
if (current instanceof Array) {
if (typeof nextPath === 'string') {
let ret = [];
nextPaths.unshift(nextPath);
for (let i = 0; i < current.length; i++) {
const currentRet = this.getValue(current[i], nextPaths);
if (currentRet instanceof Array) {
ret = ret.concat(currentRet);
} else if (currentRet !== undefined && currentRet !== null) {
ret.push(currentRet);
}
}
return ret;
} else if (nextPath.name === 'first') {
return this.getValue(current[0], nextPaths);
} else if (nextPath.name === 'last') {
return this.getValue(current[current.length - 1], nextPaths);
} else if (nextPath.name === 'where') {
if (!nextPath.params || nextPath.params.length === 0) {
throw new Error('Expected .where() to have a parameter');
}
const filtered = [];
for (let i = 0; i < current.length; i++) {
const paramsClone = JSON.parse(JSON.stringify(nextPath.params));
const results = this.internalEvaluate(current[i], paramsClone);
if (typeof results === 'boolean' && results === true) {
filtered.push(current[i]);
} else if (results instanceof Array && results.length === 1 && results[0]) {
filtered.push(current[i]);
}
}
return this.getValue(filtered, nextPaths);
} else {
throw new Error('Unsupported function for arrays ' + nextPath.name);
}
} else {
if (typeof nextPath === 'string') {
return this.getValue(current[nextPath], nextPaths);
} else if (nextPath.name === 'resolve') {
const reference = typeof current === 'string' ? current : current.reference;
const resource = this.internalResolve(reference);
return this.getValue(resource, nextPaths);
} else if (nextPath.name === 'startswith') {
if (!nextPath.params || nextPath.params.length !== 1) {
throw new Error('Expected a single parameter to startsWith()');
}
if (typeof current !== 'string') {
throw new Error('startsWith() must be used on string types');
}
const paramValue = nextPath.params[0].value || this.getValue(current, nextPath.params[0].path);
if (!paramValue || current.indexOf(paramValue) !== 0) {
return false;
}
return true;
} else {
throw new Error('Unsupported function for objects ' + nextPath.name);
}
}
}
/**
* Evaluates the given statements against the specified single resource.
* @param {Resource} resource
* @param statements
* @returns {*}
* @private
*/
private internalEvaluate(resource, statements) {
let ret = [];
for (let i = 0; i < statements.length; i++) {
const statement = statements[i];
if (statement.path) {
statement.value = this.getValue(resource, statement.path);
}
if (statement.left && statement.left.path) {
statement.left.value = this.getValue(resource, statement.left.path);
}
if (statement.right && statement.right.path) {
statement.right.value = this.getValue(resource, statement.right.path);
}
if (statement.op) {
if (!statement.left || !statement.right) {
return false;
}
switch (statement.op) {
case '=':
case '==':
return statement.left.value === statement.right.value;
case '!=':
return statement.left.value !== statement.right.value;
}
} else {
if (statement.value instanceof Array) {
ret = ret.concat(statement.value);
} else {
ret.push(statement.value);
}
}
}
return ret;
}
/**
* Determines if the statements specified should result in an array being returned
* @param statements
* @returns {boolean}
* @private
*/
private shouldReturnArray(statements) {
// TODO: Make this more intelligent.
// It could instead determine if the last actual path represents
// an array, based on the definitions stored in ParseConformance class.
if (statements.length === 1) {
const statementHasWhereFn = (statements[0].path || []).filter(nextPath => nextPath.name === 'where');
if (statementHasWhereFn.length > 0) {
return true;
}
}
return false;
}
/**
* Evaluates the given fhirPath string against the resources passed in the constructor of the class
* In the event of an operator comparison, returns a boolean
* In the event of a path evaluation, returns the value of the given path (for each of the resources)
* @param {string} fhirPath The FhirPath string to evaluate against the resources provided to the FhirPath class
* @returns {obj|Array} The result of the evaluation. Can be either an object, boolean or array of results
*/
public evaluate(fhirPath) {
if (!fhirPath) {
return;
}
const statements = this.parse(fhirPath);
let ret = [];
for (let r = 0; r < this.resources.length; r++) {
const resource = this.resources[r];
ret = ret.concat(this.internalEvaluate(resource, statements));
}
if (this.resources.length === 1 && ret.length === 1 && !this.shouldReturnArray(statements)) {
return ret[0];
}
return ret;
}
} | the_stack |
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
IWebPartContext,
PropertyPaneDropdown,
PropertyPaneSlider,
PropertyPaneToggle
} from '@microsoft/sp-webpart-base';
import { Version } from '@microsoft/sp-core-library';
import * as strings from 'dockMenuStrings';
import { IDockMenuWebPartProps } from './IDockMenuWebPartProps';
//Imports property pane custom fields
import { PropertyFieldCustomList, CustomListFieldType } from 'sp-client-custom-fields/lib/PropertyFieldCustomList';
import { PropertyFieldFontPicker } from 'sp-client-custom-fields/lib/PropertyFieldFontPicker';
import { PropertyFieldFontSizePicker } from 'sp-client-custom-fields/lib/PropertyFieldFontSizePicker';
import { PropertyFieldColorPickerMini } from 'sp-client-custom-fields/lib/PropertyFieldColorPickerMini';
import { PropertyFieldAlignPicker } from 'sp-client-custom-fields/lib/PropertyFieldAlignPicker';
//Loads external CSS
require('../../css/coverflow/coverflow.scss');
//Loads external JS libs
require('jquery');
require('jqueryui');
import * as $ from 'jquery';
require('coverflow');
require('interpolate');
require('touchSwipe');
//require('jqueryreflection');
export default class DockMenuWebPart extends BaseClientSideWebPart<IDockMenuWebPartProps> {
private guid: string;
/**
* @function
* Web part contructor.
*/
public constructor(context?: IWebPartContext) {
super();
this.guid = this.getGuid();
//Hack: to invoke correctly the onPropertyChange function outside this class
//we need to bind this object on it first
this.onPropertyPaneFieldChanged = this.onPropertyPaneFieldChanged.bind(this);
}
/**
* @function
* Gets WP data version
*/
protected get dataVersion(): Version {
return Version.parse('1.0');
}
/**
* @function
* Renders HTML code
*/
public render(): void {
var html = '<div class="photos" style="position: relative; width: 100%;" id="' + this.guid + '-bigCarousel">';
if (this.properties.items != null) {
this.properties.items.map(item => {
if (item != null && item.Enabled != "false") {
html += '<div><img class="cover" src="' + item.Picture + '" data-name="' + item.Title + '"/>';
if (this.properties.textPanelEnable != false) {
var content = item.Title;
var linkUrl = item['Link Url'];
var linkText = item['Link Text'];
if (linkUrl && linkUrl != '' && linkUrl != 'undefined') {
content += " <a style='color: " + this.properties.textPanelFontColor + "' href='" + linkUrl + "'>";
var dataText = linkText;
if (dataText == null || dataText == '')
dataText = strings.ReadMore;
content += dataText;
content += "</a>";
}
if (this.properties.shadow === false) {
html += '<div style=\'position: absolute; bottom: 0px; min-height: 50px; line-height: 50px; left: 0; width: 100%; color: ' + this.properties.textPanelFontColor + '; background-color: ' + this.properties.textPanelBackgroundColor + '; font-family: ' + this.properties.textPanelFont + '; font-size: ' + this.properties.textPanelFontSize + '; text-align: ' + this.properties.textPanelAlign + ' \'><span style="padding: 8px">' + content + '</span></div>';
}
else {
html += '<div style=\'position: absolute; top: 190px; min-height: 50px; line-height: 50px; left: 0; width: 100%; color: ' + this.properties.textPanelFontColor + '; background-color: ' + this.properties.textPanelBackgroundColor + '; font-family: ' + this.properties.textPanelFont + '; font-size: ' + this.properties.textPanelFontSize + '; text-align: ' + this.properties.textPanelAlign + ' \'><span style="padding: 8px">' + content + '</span></div>';
}
}
html += '</div>';
}
});
}
html += '</div>';
this.domElement.innerHTML = html;
this.renderContents();
}
private renderContents(): void {
if (($ as any)('#' + this.guid + '-bigCarousel') != null) {
if (this.properties.shadow === true && $.fn.reflect) {
($ as any)('#' + this.guid + '-bigCarousel .cover').reflect();
}
($ as any)('#' + this.guid + '-bigCarousel').coverflow(
{
easing: this.properties.easing,
duration: this.properties.duration,
index: 3,
width: 320,
height: 240,
visible: 'density',
density: this.properties.density,
innerOffset: this.properties.innerOffset,
innerScale: this.properties.innerScale,
selectedCss: { opacity: 1 },
outerCss: { opacity: .1 },
confirm: () => {
},
change: (event, cover) => {
}
}
);
}
}
/**
* @function
* Generates a GUID
*/
private getGuid(): string {
return this.s4() + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' +
this.s4() + '-' + this.s4() + this.s4() + this.s4();
}
/**
* @function
* Generates a GUID part
*/
private s4(): string {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
/**
* @function
* PropertyPanel settings definition
*/
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
displayGroupsAsAccordion: true,
groups: [
{
groupName: strings.DataGroupName,
groupFields: [
PropertyFieldCustomList('items', {
label: strings.DataFieldLabel,
value: this.properties.items,
headerText: "Manage Items",
fields: [
{ id: 'Title', title: 'Title', required: true, type: CustomListFieldType.string },
{ id: 'Enabled', title: 'Enabled', required: true, type: CustomListFieldType.boolean },
{ id: 'Picture', title: 'Picture', required: true, type: CustomListFieldType.picture },
//{ title: 'Picture', required: true, type: CustomListFieldType.picture },
{ id: 'Link Url', title: 'Link Url', required: false, type: CustomListFieldType.string, hidden: true },
{ id: 'Link Text', title: 'Link Text', required: false, type: CustomListFieldType.string, hidden: true }
],
onPropertyChange: this.onPropertyPaneFieldChanged,
render: this.render.bind(this),
disableReactivePropertyChanges: this.disableReactivePropertyChanges,
context: this.context,
properties: this.properties,
key: "coverflowListField"
})
]
},
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneToggle('shadow', {
label: strings.Shadow,
}),
PropertyPaneDropdown('duration', {
label: strings.SpeedFieldLabel,
options: [
{key: 'slow', text: 'slow'},
{key: 'normal', text: 'normal'},
{key: 'fast', text: 'fast'}
]
}),
PropertyPaneDropdown('easing', {
label: strings.Easing,
options: [
{key: 'swing', text: 'swing'},
{key: 'linear', text:'linear'},
{key: 'jswing', text:'jswing'},
{key: 'easeInQuad', text:'easeInQuad'},
{key: 'easeInCubic', text:'easeInCubic'},
{key: 'easeInQuart', text:'easeInQuart'},
{key: 'easeInQuint', text:'easeInQuint'},
{key: 'easeInSine', text:'easeInSine'},
{key: 'easeInExpo', text:'easeInExpo'},
{key: 'easeInCirc', text:'easeInCirc'},
{key: 'easeInElastic', text:'easeInElastic'},
{key: 'easeInBack', text:'easeInBack'},
{key: 'easeInBounce', text:'easeInBounce'},
{key: 'easeOutQuad', text:'easeOutQuad'},
{key: 'easeOutCubic', text:'easeOutCubic'},
{key: 'easeOutQuart', text:'easeOutQuart'},
{key: 'easeOutQuint', text:'easeOutQuint'},
{key: 'easeOutSine', text:'easeOutSine'},
{key: 'easeOutExpo', text:'easeOutExpo'},
{key: 'easeOutCirc', text:'easeOutCirc'},
{key: 'easeOutElastic', text:'easeOutElastic'},
{key: 'easeOutBack', text:'easeOutBack'},
{key: 'easeOutBounce', text:'easeOutBounce'},
{key: 'easeInOutQuad', text:'easeInOutQuad'},
{key: 'easeInOutCubic', text:'easeInOutCubic'},
{key: 'easeInOutQuart', text:'easeInOutQuart'},
{key: 'easeInOutQuint', text:'easeInOutQuint'},
{key: 'easeInOutSine', text:'easeInOutSine'},
{key: 'easeInOutExpo', text:'easeInOutExpo'},
{key: 'easeInOutCirc', text:'easeInOutCirc'},
{key: 'easeInOutElastic', text:'easeInOutElastic'},
{key: 'easeInOutBack', text:'easeInOutBack'},
{key: 'easeInOutBounce', text:'easeInOutBounce'}
]
}),
PropertyPaneSlider('density', {
label: strings.Density,
min: 0,
max: 4,
step: 0.1
}),
PropertyPaneSlider('innerOffset', {
label: strings.InnerOffset,
min: 0,
max: 200,
step: 1
}),
PropertyPaneSlider('innerScale', {
label: strings.InnerScale,
min: 0,
max: 1,
step: 0.1
})
]
}
]
},
{
header: {
description: strings.PropertyPageTextPanel
},
groups: [
{
groupName: strings.TextPanelGroupName,
groupFields: [
PropertyPaneToggle('textPanelEnable', {
label: strings.TextPanelEnableFieldLabel
}),
PropertyFieldAlignPicker('textPanelAlign', {
label: strings.TextPanelAlignFieldLabel,
initialValue: this.properties.textPanelAlign,
onPropertyChanged: this.onPropertyPaneFieldChanged,
render: this.render.bind(this),
disableReactivePropertyChanges: this.disableReactivePropertyChanges,
properties: this.properties,
key: "coverflowAlignField"
}),
PropertyFieldFontPicker('textPanelFont', {
label: strings.TextPanelFontFieldLabel,
initialValue: this.properties.textPanelFont,
onPropertyChange: this.onPropertyPaneFieldChanged,
render: this.render.bind(this),
disableReactivePropertyChanges: this.disableReactivePropertyChanges,
properties: this.properties,
key: "coverflowFontField"
}),
PropertyFieldFontSizePicker('textPanelFontSize', {
label: strings.TextPanelFontSizeFieldLabel,
initialValue: this.properties.textPanelFontSize,
usePixels: true,
preview: true,
onPropertyChange: this.onPropertyPaneFieldChanged,
render: this.render.bind(this),
disableReactivePropertyChanges: this.disableReactivePropertyChanges,
properties: this.properties,
key: "coverflowFontSizeField"
}),
PropertyFieldColorPickerMini('textPanelFontColor', {
label: strings.TextPanelFontColorFieldLabel,
initialColor: this.properties.textPanelFontColor,
onPropertyChange: this.onPropertyPaneFieldChanged,
render: this.render.bind(this),
disableReactivePropertyChanges: this.disableReactivePropertyChanges,
properties: this.properties,
key: "coverflowFontColorField"
}),
PropertyFieldColorPickerMini('textPanelBackgroundColor', {
label: strings.TextPanelBackgroundColorFieldLabel,
initialColor: this.properties.textPanelBackgroundColor,
onPropertyChange: this.onPropertyPaneFieldChanged,
render: this.render.bind(this),
disableReactivePropertyChanges: this.disableReactivePropertyChanges,
properties: this.properties,
key: "coverflowBackgroundColorField"
})
]
}
]
}
]
};
}
} | the_stack |
import type { CeramicApi } from '@ceramicnetwork/common'
import type { StreamID } from '@ceramicnetwork/streamid'
import { TileDocument } from '@ceramicnetwork/stream-tile'
import { CIP11_DEFINITION_SCHEMA_URL, CIP11_INDEX_SCHEMA_URL } from '@glazed/constants'
import { DataModel } from '@glazed/datamodel'
import type { Definition, IdentityIndex } from '@glazed/did-datastore-model'
import type { ModelTypeAliases, ModelTypesToAliases } from '@glazed/types'
import { TileProxy } from './proxy'
import type { TileContent, TileDoc } from './proxy'
import { assertDIDstring } from './utils'
export { assertDIDstring, isDIDstring } from './utils'
export type DefinitionContentType<
ModelTypes extends ModelTypeAliases,
Alias extends keyof ModelTypes['definitions']
> = ModelTypes['schemas'][ModelTypes['definitions'][Alias]]
export type DefinitionsContentTypes<
ModelTypes extends ModelTypeAliases,
Fallback = Record<string, unknown>
> = {
[Key: string]: typeof Key extends keyof ModelTypes['definitions']
? DefinitionContentType<ModelTypes, typeof Key>
: Fallback
}
export type DefinitionWithID<Config extends Record<string, unknown> = Record<string, unknown>> =
Definition<Config> & { id: StreamID }
export type Entry = {
key: string
id: string
record: unknown
}
export type CreateOptions = {
pin?: boolean
}
export type DIDDataStoreParams<ModelTypes extends ModelTypeAliases = ModelTypeAliases> = {
autopin?: boolean
ceramic: CeramicApi
model: DataModel<ModelTypes> | ModelTypesToAliases<ModelTypes>
}
/**
* ```sh
* import { DIDDataStore } from '@glazed/did-datastore'
* ```
*/
export class DIDDataStore<
ModelTypes extends ModelTypeAliases = ModelTypeAliases,
Alias extends keyof ModelTypes['definitions'] = keyof ModelTypes['definitions']
> {
#autopin: boolean
#ceramic: CeramicApi
/** @internal */
_indexProxy: TileProxy
#model: DataModel<ModelTypes>
constructor({ autopin, ceramic, model }: DIDDataStoreParams<ModelTypes>) {
this.#autopin = autopin !== false
this.#ceramic = ceramic
this._indexProxy = new TileProxy(this._getOwnIDXDoc.bind(this))
this.#model =
model instanceof DataModel ? model : new DataModel<ModelTypes>({ autopin, ceramic, model })
}
get authenticated(): boolean {
return this.#ceramic.did != null
}
get ceramic(): CeramicApi {
return this.#ceramic
}
get id(): string {
if (this.#ceramic.did == null) {
throw new Error('Ceramic instance is not authenticated')
}
return this.#ceramic.did.id
}
get model(): DataModel<ModelTypes> {
return this.#model
}
// High-level APIs
async has(key: Alias, did?: string): Promise<boolean> {
const definitionID = this.getDefinitionID(key as string)
const ref = await this.getRecordID(definitionID, did)
return ref != null
}
async get<Key extends Alias, ContentType = DefinitionContentType<ModelTypes, Key>>(
key: Key,
did?: string
): Promise<ContentType | null> {
const definitionID = this.getDefinitionID(key as string)
return await this.getRecord<ContentType>(definitionID, did)
}
async set<Key extends Alias, ContentType = DefinitionContentType<ModelTypes, Key>>(
key: Key,
content: ContentType,
options?: CreateOptions
): Promise<StreamID> {
const definitionID = this.getDefinitionID(key as string)
const [created, id] = await this._setRecordOnly(definitionID, content, options)
if (created) {
await this._setReference(definitionID, id)
}
return id
}
async merge<Key extends Alias, ContentType = DefinitionContentType<ModelTypes, Key>>(
key: Key,
content: ContentType,
options?: CreateOptions
): Promise<StreamID> {
const definitionID = this.getDefinitionID(key as string)
const existing = await this.getRecord<ContentType>(definitionID)
const newContent = existing ? { ...existing, ...content } : content
return await this.setRecord(definitionID, newContent, options)
}
async setAll<Contents extends DefinitionsContentTypes<ModelTypes>>(
contents: Contents,
options?: CreateOptions
): Promise<IdentityIndex> {
const updates = Object.entries(contents).map(async ([alias, content]) => {
const definitionID = this.getDefinitionID(alias)
const [created, id] = await this._setRecordOnly(definitionID, content, options)
return [created, definitionID, id]
}) as Array<Promise<[boolean, string, StreamID]>>
const changes = await Promise.all(updates)
const newReferences = changes.reduce((acc, [created, key, id]) => {
if (created) {
acc[key] = id.toUrl()
}
return acc
}, {} as IdentityIndex)
await this._setReferences(newReferences)
return newReferences
}
async setDefaults<Contents extends DefinitionsContentTypes<ModelTypes>>(
contents: Contents,
options?: CreateOptions
): Promise<IdentityIndex> {
const index = (await this.getIndex()) ?? {}
const updates = Object.entries(contents)
.map(([alias, content]): [string, Record<string, unknown>] => [
this.getDefinitionID(alias),
content,
])
.filter((entry) => index[entry[0]] == null)
.map(async ([key, content]) => {
const definition = await this.getDefinition(key)
const id = await this._createRecord(definition, content, options)
return { [key]: id.toUrl() }
}) as Array<Promise<IdentityIndex>>
const changes = await Promise.all(updates)
const newReferences = changes.reduce((acc, keyToID) => {
return Object.assign(acc, keyToID)
}, {} as IdentityIndex)
await this._setReferences(newReferences)
return newReferences
}
async remove(key: Alias): Promise<void> {
await this._indexProxy.changeContent((index) => {
if (index) delete index[this.getDefinitionID(key as string)]
return index
})
}
// Identity Index APIs
async getIndex(did?: string): Promise<IdentityIndex | null> {
const rootDoc =
this.authenticated && (did === this.id || did == null)
? await this._indexProxy.get()
: await this._getIDXDoc(did ?? this.id)
return rootDoc ? (rootDoc.content as IdentityIndex) : null
}
iterator(did?: string): AsyncIterableIterator<Entry> {
let list: Array<[string, string]>
let cursor = 0
return {
[Symbol.asyncIterator]() {
return this
},
next: async (): Promise<IteratorResult<Entry>> => {
if (list == null) {
const index = await this.getIndex(did)
list = Object.entries(index ?? {})
}
if (cursor === list.length) {
return { done: true, value: null }
}
const [key, id] = list[cursor++]
const doc = await this._loadDocument(id)
return { done: false, value: { key, id, record: doc.content } }
},
}
}
/** @internal */
async _createIDXDoc(did: string): Promise<TileDoc> {
assertDIDstring(did)
return await TileDocument.create<TileContent>(
this.#ceramic,
null,
{ deterministic: true, controllers: [did], family: 'IDX' },
{ anchor: false, publish: false }
)
}
/** @internal */
async _getIDXDoc(did: string): Promise<TileDoc | null> {
const doc = await this._createIDXDoc(did)
if (doc.content == null || doc.metadata.schema == null) {
return null
}
if (doc.metadata.schema !== CIP11_INDEX_SCHEMA_URL) {
throw new Error('Invalid document: schema is not IdentityIndex')
}
return doc
}
/** @internal */
async _getOwnIDXDoc(): Promise<TileDoc> {
const doc = await this._createIDXDoc(this.id)
if (doc.content == null || doc.metadata.schema == null) {
// Doc just got created, set to empty object with schema
await doc.update({}, { schema: CIP11_INDEX_SCHEMA_URL })
if (this.#autopin) {
await this.#ceramic.pin.add(doc.id)
}
} else if (doc.metadata.schema !== CIP11_INDEX_SCHEMA_URL) {
throw new Error('Invalid document: schema is not IdentityIndex')
}
return doc
}
// Definition APIs
getDefinitionID(aliasOrID: string): string {
return this.#model.getDefinitionID(aliasOrID) ?? aliasOrID
}
async getDefinition(id: StreamID | string): Promise<DefinitionWithID> {
const doc = await this._loadDocument(id)
if (doc.metadata.schema !== CIP11_DEFINITION_SCHEMA_URL) {
throw new Error('Invalid document: schema is not Definition')
}
return { ...doc.content, id: doc.id } as DefinitionWithID
}
// Record APIs
async getRecordID(definitionID: string, did?: string): Promise<string | null> {
const index = await this.getIndex(did ?? this.id)
return index?.[definitionID] ?? null
}
async getRecordDocument(definitionID: string, did?: string): Promise<TileDoc | null> {
const id = await this.getRecordID(definitionID, did)
return id ? await this._loadDocument(id) : null
}
async getRecord<ContentType = unknown>(
definitionID: string,
did?: string
): Promise<ContentType | null> {
const doc = await this.getRecordDocument(definitionID, did)
return doc ? (doc.content as ContentType) : null
}
async setRecord(
definitionID: string,
content: Record<string, any>,
options?: CreateOptions
): Promise<StreamID> {
const [created, id] = await this._setRecordOnly(definitionID, content, options)
if (created) {
await this._setReference(definitionID, id)
}
return id
}
/** @internal */
async _setRecordOnly(
definitionID: string,
content: Record<string, any>,
{ pin }: CreateOptions = {}
): Promise<[boolean, StreamID]> {
const existing = await this.getRecordID(definitionID, this.id)
if (existing == null) {
const definition = await this.getDefinition(definitionID)
const ref = await this._createRecord(definition, content, { pin })
return [true, ref]
} else {
const doc = await this._loadDocument(existing)
await doc.update(content)
return [false, doc.id]
}
}
/** @internal */
async _loadDocument(id: StreamID | string): Promise<TileDoc> {
return await TileDocument.load(this.#ceramic, id)
}
/** @internal */
async _createRecord(
definition: DefinitionWithID,
content: Record<string, any>,
{ pin }: CreateOptions = {}
): Promise<StreamID> {
// Doc must first be created in a deterministic way
const doc = await TileDocument.create<TileContent>(
this.#ceramic,
null,
{ deterministic: true, controllers: [this.id], family: definition.id.toString() },
{ anchor: false, publish: false }
)
// Then be updated with content and schema
const updated = doc.update(content, { schema: definition.schema })
if (pin ?? this.#autopin) {
await Promise.all([updated, this.#ceramic.pin.add(doc.id)])
} else {
await updated
}
return doc.id
}
// References APIs
/** @internal */
async _setReference(definitionID: string, id: StreamID): Promise<void> {
await this._indexProxy.changeContent((index) => {
return { ...index, [definitionID]: id.toUrl() }
})
}
/** @internal */
async _setReferences(references: IdentityIndex): Promise<void> {
if (Object.keys(references).length !== 0) {
await this._indexProxy.changeContent((index) => {
return { ...index, ...references }
})
}
}
} | the_stack |
import * as util from "../util";
import { TestBuilder } from "../util";
import { JsxEmit } from "typescript";
// language=TypeScript
const reactLib = `
export class Component {
static isClass = true
}
namespace React {
const isLua = typeof Component === "object"
export function createElement(
type: any,
props?: any,
...children: any[]
) {
let typeStr: string
if (isLua) {
typeStr =
typeof type === "function" ? "<< function >>" :
typeof type === "object" ? \`<< class \${type.name} >>\` :
type
} else {
typeStr = typeof type === "function" ? (type.isClass
? \`<< class \${type.name} >>\`
: "<< function >>")
: type
}
return {
type: typeStr,
props,
children
};
}
export class Fragment extends Component {
}
}
export default React;
`;
// language=TypeScript
const jsxTypings = `declare namespace JSX {
interface IntrinsicElements {
a: any
b: any
foo: any
bar: any
div: any
"with-dash": any
}
}
`;
function testJsx(...args: [string] | [TemplateStringsArray, ...any[]]): TestBuilder {
return util
.testFunction(...args)
.setOptions({
jsx: JsxEmit.React,
})
.setMainFileName("main.tsx")
.addExtraFile("react.ts", reactLib)
.addExtraFile("jsx.d.ts", jsxTypings)
.setTsHeader('import React, { Component } from "./react";');
}
describe("jsx", () => {
test("element", () => {
testJsx`
return <foo></foo>
`.expectToMatchJsResult();
});
test("self closing element", () => {
testJsx`
return <foo />
`.expectToMatchJsResult();
});
test("element with dash name", () => {
testJsx`
return <with-dash />
`.expectToMatchJsResult();
});
test("custom element", () => {
testJsx`
function Foo() {}
return <Foo />
`.expectToMatchJsResult();
});
test("fragment", () => {
testJsx`
return <></>
`.expectToMatchJsResult();
});
test("fragment with children", () => {
testJsx`
return <><a foo="bar" /><b bar="foo" /></>
`.expectToMatchJsResult();
});
test("esoteric component names", () => {
testJsx`
class _Foo extends Component {}
return <_Foo />
`.expectToMatchJsResult();
testJsx`
class $ extends Component {}
return <$ />
`.expectToMatchJsResult();
testJsx`
class é extends Component {}
return <é />
`.expectToMatchJsResult();
});
test("nested elements", () => {
testJsx`
return <foo><bar></bar></foo>
`.expectToMatchJsResult();
});
test("many nested elements", () => {
testJsx`
return <foo><a><b><bar></bar></b></a></foo>
`.expectToMatchJsResult();
});
test("interpolated children", () => {
testJsx`
const x = 3
return <foo>{x}</foo>
`.expectToMatchJsResult();
});
test("string prop", () => {
testJsx`
return <a foo="bar" />
`.expectToMatchJsResult();
});
test("value prop", () => {
testJsx`
const x = 5
return <a foo={x} />
`.expectToMatchJsResult();
});
test("quoted prop", () => {
testJsx`
return <a foo-bar={true} />
`.expectToMatchJsResult();
});
test("shorthand prop", () => {
testJsx`
return <a foo />
`.expectToMatchJsResult();
});
test("spaces in jsxText", () => {
testJsx`
return <a>this
<b/> is some<a/>multiline
text <a/> thing.
<b/>
</a>
`.expectToMatchJsResult();
});
test("multiline string jsxText", () => {
testJsx`
return <a>
foo bar
baz
</a>
`.expectToMatchJsResult();
});
test("access tag value", () => {
testJsx`
const a = { b(){} };
return <a.b c='d' />
`.expectToMatchJsResult();
testJsx`
const a = { b: { c: { d(){} } } };
return <a.b.c.d c='d'/>
`.expectToMatchJsResult();
});
test("spread props", () => {
testJsx`
const x = {c: "d", e: "f"}
return <a {...x} />
`.expectToMatchJsResult();
testJsx`
const x = {c: "d", e: "no"}
return <a a="b" {...x} e="f" />
`.expectToMatchJsResult();
});
test("comment children", () => {
testJsx`
return <a>
{/* comment */}
{/* another comment */}
</a>
`.expectToMatchJsResult();
testJsx`
return <a>
<b/>
{/* comment */}
<b/>
</a>
`.expectToMatchJsResult();
});
test("multiline string prop value", () => {
testJsx`
return <div value="This is a
multi-line string."
/>
`.expectToMatchJsResult();
testJsx`
return <div value="
This is a longer
multi-line string.
"
/>
`.expectToMatchJsResult();
});
test("prop strings with entities", () => {
testJsx`
return <div value="a>b" />
`.expectToMatchJsResult();
});
test("jsxText with entities", () => {
testJsx`
return <a> 9+10<21 </a>
`.expectToMatchJsResult();
});
test("Spread children", () => {
// doesn't actually "spread" (typescript's current behavior)
testJsx`
const children = [<a/>, <b/>]
return <foo>{...children}</foo>
`.expectToMatchJsResult();
});
test("complex", () => {
testJsx`
const x = 3
const props = {one: "two", three: 4}
return <div a="b">
<a c="d" r={x}/>
<b baz-bar {...props}> the {x}marks the spot </b>
a
{/** bar */}
and
<> <a>2</a></>
<b/>
</div>
`.expectToMatchJsResult();
});
// language=TypeScript
const customJsxLib = `export namespace MyLib {
export function myCreate(
type: any,
props: any,
...children: any[]
) {
return { type: typeof type, props, children, myThing: true };
}
export function MyFragment() {
}
}
`;
test("custom JSX factory", () => {
testJsx`
return <a><b>c</b></a>
`
.setTsHeader('import { MyLib } from "./myJsx";')
.setOptions({ jsxFactory: "MyLib.myCreate" })
.addExtraFile("myJsx.ts", customJsxLib)
.expectToMatchJsResult();
testJsx`
return <a><b>c</b></a>
`
.setTsHeader('import { MyLib } from "./myJsx";const myCreate2 = MyLib.myCreate;')
.setOptions({ jsxFactory: "myCreate2" })
.addExtraFile("myJsx.ts", customJsxLib)
.expectToMatchJsResult();
});
test("custom fragment factory", () => {
testJsx`
return <><b>c</b></>
`
.setTsHeader('import { MyLib } from "./myJsx";')
.setOptions({ jsxFactory: "MyLib.myCreate", jsxFragmentFactory: "MyLib.MyFragment" })
.addExtraFile("myJsx.ts", customJsxLib)
.expectToMatchJsResult();
testJsx`
return <><b>c</b></>
`
.setTsHeader('import { MyLib } from "./myJsx";function MyFragment2(){};')
.setOptions({ jsxFactory: "MyLib.myCreate", jsxFragmentFactory: "MyFragment2" })
.addExtraFile("myJsx.ts", customJsxLib)
.expectToMatchJsResult();
});
test("custom JSX pragma", () => {
testJsx`
return <a><b>c</b></a>
`
.setTsHeader('/** @jsx MyLib.myCreate */\nimport { MyLib } from "./myJsx";')
.addExtraFile("myJsx.ts", customJsxLib)
.expectToMatchJsResult();
testJsx`
return <a><b>c</b></a>
`
.setTsHeader('/** @jsx myCreate2 */import { MyLib } from "./myJsx";const myCreate2 = MyLib.myCreate;')
.addExtraFile("myJsx.ts", customJsxLib)
.expectToMatchJsResult();
});
test("custom fragment pragma", () => {
testJsx`
return <><b>c</b></>
`
.setTsHeader(
'/** @jsx MyLib.myCreate */\n/** @jsxFrag MyLib.MyFragment */\nimport { MyLib } from "./myJsx";'
)
.addExtraFile("myJsx.ts", customJsxLib)
.expectToMatchJsResult();
testJsx`
return <><b>c</b></>
`
.setTsHeader(
"/** @jsx MyLib.myCreate */\n/** @jsxFrag MyFragment2 */\n" +
'import { MyLib } from "./myJsx";function MyFragment2(){};'
)
.setOptions({ jsxFactory: "MyLib.myCreate", jsxFragmentFactory: "MyFragment" })
.addExtraFile("myJsx.ts", customJsxLib)
.expectToMatchJsResult();
});
test("forward declare components", () => {
testJsx`
const foo = <Foo />
function Foo(){}
return foo
`.expectToMatchJsResult();
});
test("invalid jsx config", () => {
testJsx(`
return <a/>
`)
.setOptions({
jsx: JsxEmit.Preserve,
})
.expectToHaveDiagnostics();
});
}); | the_stack |
import { ClusterTestContext, RavenTestContext } from "../../Utils/TestUtil";
import { DocumentStore } from "../../../src/Documents/DocumentStore";
import { DocumentConventions } from "../../../src/Documents/Conventions/DocumentConventions";
import { ServerNode } from "../../../src/Http/ServerNode";
import { Topology } from "../../../src/Http/Topology";
import { GetDatabaseTopologyCommand } from "../../../src/ServerWide/Commands/GetDatabaseTopologyCommand";
import { delay } from "../../../src/Utility/PromiseUtil";
import { DocumentSession } from "../../../src/Documents/Session/DocumentSession";
import { User } from "../../Assets/Entities";
import { assertThat } from "../../Utils/AssertExtensions";
import { RequestExecutor } from "../../../src/Http/RequestExecutor";
import { GetStatisticsOperation } from "../../../src/Documents/Operations/GetStatisticsOperation";
import { UpdateTopologyParameters } from "../../../src/Http/UpdateTopologyParameters";
(RavenTestContext.isPullRequest ? describe.skip : describe)("ClusterModesForRequestExecutorTest", function () {
let testContext: ClusterTestContext;
beforeEach(async function () {
testContext = new ClusterTestContext();
});
afterEach(async () => testContext.dispose());
it("round_robin_load_balancing_should_work", async () => {
const cluster = await testContext.createRaftCluster(3);
try {
const initialLeader = cluster.getInitialLeader();
const followers = cluster.nodes
.filter(x => !x.leader);
const conventionsForLoadBalancing = new DocumentConventions();
conventionsForLoadBalancing.readBalanceBehavior = "RoundRobin";
const databaseName = testContext.getDatabaseName();
const numberOfNodes = 3;
await cluster.createDatabase({
databaseName
}, numberOfNodes, cluster.getInitialLeader().url);
let leaderStore: DocumentStore;
try {
leaderStore = new DocumentStore(cluster.getInitialLeader().url, databaseName);
leaderStore.conventions = conventionsForLoadBalancing;
let follower1: DocumentStore;
try {
follower1 = new DocumentStore(followers[0].url, databaseName);
follower1.conventions = conventionsForLoadBalancing;
let follower2: DocumentStore;
try {
follower2 = new DocumentStore(followers[1].url, databaseName);
follower2.conventions = conventionsForLoadBalancing;
leaderStore.initialize();
follower1.initialize();
follower2.initialize();
const leaderRequestExecutor = leaderStore.getRequestExecutor();
//make sure we have updated topology --> more deterministic test
const serverNode = new ServerNode({
clusterTag: "A",
database: databaseName,
url: initialLeader.url
});
const updateTopologyParameters = new UpdateTopologyParameters(serverNode);
updateTopologyParameters.timeoutInMs = 5000;
updateTopologyParameters.forceUpdate = true;
await leaderRequestExecutor.updateTopology(updateTopologyParameters);
//wait until all nodes in database cluster are members (and not promotables)
//GetDatabaseTopologyCommand -> does not retrieve promotables
let topology = new Topology();
while (!topology.nodes || topology.nodes.length !== 3) {
const topologyGetCommand = new GetDatabaseTopologyCommand();
await leaderRequestExecutor.execute(topologyGetCommand);
topology = topologyGetCommand.result;
await delay(50);
}
{
const session = leaderStore.openSession();
const user1 = new User();
user1.name = "John Dow";
await session.store(user1);
const user2 = new User();
user2.name = "Jack Dow";
await session.store(user2);
const user3 = new User();
user3.name = "Jane Dow";
await session.store(user3);
const marker = new User();
marker.name = "FooBar";
await session.store(marker, "marker");
await session.saveChanges();
await testContext.waitForDocumentInCluster(User, session as DocumentSession,
"marker", d => true, 10_000);
}
const usedUrls: String[] = [];
for (let i = 0; i < 3; i++) {
const session = leaderStore.openSession();
await session.query(User)
.whereStartsWith("name", "Ja")
.all();
const currentNode = await session.advanced.getCurrentSessionNode();
usedUrls.push(currentNode.url.toLocaleLowerCase());
}
assertThat(usedUrls)
.hasSize(3);
} finally {
follower2.dispose();
}
} finally {
follower1.dispose();
}
} finally {
leaderStore.dispose();
}
} finally {
cluster.dispose();
}
});
it("round_robin_load_balancing_with_failing_node_should_work", async () => {
const cluster = await testContext.createRaftCluster(3);
try {
const initialLeader = cluster.getInitialLeader();
const followers = cluster.nodes
.filter(x => !x.leader);
const conventionsForLoadBalancing = new DocumentConventions();
conventionsForLoadBalancing.readBalanceBehavior = "RoundRobin";
const databaseName = testContext.getDatabaseName();
const numberOfNodes = 3;
await cluster.createDatabase({
databaseName
}, numberOfNodes, cluster.getInitialLeader().url);
let leaderStore: DocumentStore;
try {
leaderStore = new DocumentStore(cluster.getInitialLeader().url, databaseName);
leaderStore.conventions = conventionsForLoadBalancing;
let follower1: DocumentStore;
try {
follower1 = new DocumentStore(followers[0].url, databaseName);
follower1.conventions = conventionsForLoadBalancing;
let follower2: DocumentStore;
try {
follower2 = new DocumentStore(followers[1].url, databaseName);
follower2.conventions = conventionsForLoadBalancing;
leaderStore.initialize();
follower1.initialize();
follower2.initialize();
const leaderRequestExecutor = leaderStore.getRequestExecutor();
//make sure we have updated topology --> more deterministic test
const serverNode = new ServerNode({
clusterTag: "A",
database: databaseName,
url: initialLeader.url
});
const updateTopologyParameters = new UpdateTopologyParameters(serverNode);
updateTopologyParameters.timeoutInMs = 5000;
updateTopologyParameters.forceUpdate = true;
await leaderRequestExecutor.updateTopology(updateTopologyParameters);
//wait until all nodes in database cluster are members (and not promotables)
//GetDatabaseTopologyCommand -> does not retrieve promotables
let topology = new Topology();
while (!topology.nodes || topology.nodes.length !== 3) {
const topologyGetCommand = new GetDatabaseTopologyCommand();
await leaderRequestExecutor.execute(topologyGetCommand);
topology = topologyGetCommand.result;
await delay(50);
}
{
const session = leaderStore.openSession();
const user1 = new User();
user1.name = "John Dow";
await session.store(user1);
const user2 = new User();
user2.name = "Jack Dow";
await session.store(user2);
const user3 = new User();
user3.name = "Jane Dow";
await session.store(user3);
const marker = new User();
marker.name = "FooBar";
await session.store(marker, "marker");
await session.saveChanges();
await testContext.waitForDocumentInCluster(User, session as DocumentSession,
"marker", d => true, 10_000);
}
const requestExecutor = RequestExecutor.create(follower1.urls, databaseName, {
documentConventions: follower1.conventions
});
try {
do {
await delay(100);
} while (!requestExecutor.getTopologyNodes());
await cluster.disposeServer(initialLeader.nodeTag);
const failedRequests: string[] = [];
requestExecutor.on("failedRequest", event => {
failedRequests.push(event.url);
});
for (let sessionId = 0; sessionId < 5; sessionId++) {
requestExecutor.cache.clear(); // make sure we do not use request cache
const command = new GetStatisticsOperation().getCommand(new DocumentConventions());
await requestExecutor.execute(command);
}
} finally {
requestExecutor.dispose();
}
} finally {
follower2.dispose();
}
} finally {
follower1.dispose();
}
} finally {
leaderStore.dispose();
}
} finally {
cluster.dispose();
}
});
it("RavenDB_7992", async () => {
//here we test that when choosing Fastest-Node as the ReadBalanceBehavior,
//we can execute commands that use a context, without it leading to a race condition
const cluster = await testContext.createRaftCluster(3);
try {
const initialLeader = cluster.getInitialLeader();
const conventionsForLoadBalancing = new DocumentConventions();
conventionsForLoadBalancing.readBalanceBehavior = "FastestNode";
const databaseName = testContext.getDatabaseName();
const numberOfNodes = 3;
await cluster.createDatabase({
databaseName
}, numberOfNodes, cluster.getInitialLeader().url);
{
const leaderStore = new DocumentStore(initialLeader.url, databaseName);
try {
leaderStore.conventions = conventionsForLoadBalancing;
leaderStore.initialize();
{
const session = leaderStore.openSession();
const user = new User();
user.name = "Jon Snow";
await session.store(user);
await session.saveChanges();
}
{
const session = leaderStore.openSession();
await session.query(User)
.whereStartsWith("name", "Jo");
}
} finally {
leaderStore.dispose();
}
}
} finally {
cluster.dispose();
}
});
}); | the_stack |
import { auxiliaries, vec2 } from 'webgl-operate';
import {
Camera,
Canvas,
Color,
ColorScale,
Context,
DefaultFramebuffer,
FontFace,
Invalidate,
Label,
LabelRenderPass,
NdcFillingRectangle,
Position2DLabel,
Program,
Renderer,
Shader,
Text,
Texture2D,
Wizard,
} from 'webgl-operate';
import { Example } from './example';
/* spellchecker: enable */
// tslint:disable:max-classes-per-file
class ColorScaleRenderer extends Renderer {
protected _extensions = false;
protected _positions = new Array<vec2>();
protected _presets: Array<[string, string, number, boolean]> = [
['smithwalt', 'viridis', 7, false],
['smithwalt', 'viridis', 64, false],
['smithwalt', 'inferno', 7, false],
['smithwalt', 'inferno', 64, false],
['marcosci', 'cividis', 7, false],
['marcosci', 'cividis', 64, false],
['smithwalt', 'magma', 7, false],
['smithwalt', 'magma', 64, false],
['colorbrewer', 'Greys', 4, true],
['colorbrewer', 'Greys', 7, true],
['smithwalt', 'plasma', 7, false],
['smithwalt', 'plasma', 64, false],
['colorbrewer', 'Spectral', 7, true],
['colorbrewer', 'Spectral', 64, true],
['mikhailov', 'turbo', 16, false],
['mikhailov', 'turbo', 128, false],
['colorbrewer', 'BrBG', 7, true],
['colorbrewer', 'RdBu', 64, true],
['colorbrewer', 'RdYlBu', 7, true],
['colorbrewer', 'PuOr', 7, true],
['colorbrewer', 'OrRd', 4, false],
['colorbrewer', 'OrRd', 7, false],
['colorbrewer', 'RdPu', 4, false],
['colorbrewer', 'RdPu', 7, false],
['colorbrewer', 'Accent', 7, false],
['colorbrewer', 'Paired', 7, false],
['colorbrewer', 'Pastel2', 7, false],
['colorbrewer', 'Dark2', 7, false],
];
protected _labelPass: LabelRenderPass;
protected _labels = new Array<Position2DLabel>();
protected _textures = new Array<Texture2D>();
protected _ndcrect: NdcFillingRectangle;
protected _program: Program;
protected _uExtent: WebGLUniformLocation;
protected _uOffset: WebGLUniformLocation;
protected _camera: Camera;
protected _defaultFBO: DefaultFramebuffer;
protected _fontFace: FontFace | 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 {
const gl = context.gl;
/* Create framebuffers, textures, and render buffers. */
this._defaultFBO = new DefaultFramebuffer(this._context, 'DefaultFBO');
this._defaultFBO.initialize();
this._ndcrect = new NdcFillingRectangle(this._context);
this._ndcrect.initialize();
const vert = new Shader(context, gl.VERTEX_SHADER, 'colorscale.vert');
vert.initialize(require('./data/colorscale.vert'));
const frag = new Shader(context, gl.FRAGMENT_SHADER, 'colorscale.frag');
frag.initialize(require('./data/colorscale.frag'));
this._program = new Program(context, 'ColorScaleProgram');
this._program.initialize([vert, frag], false);
this._program.attribute('a_position', this._ndcrect.vertexLocation);
this._program.link();
this._program.bind();
this._uExtent = this._program.uniform('u_extent');
this._uOffset = this._program.uniform('u_offset');
gl.uniform1i(this._program.uniform('u_texture'), 0);
this._program.unbind();
/* 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 = false;
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));
const createLabeledColorScaleRect = (i: number
, source: string, preset: string, steps: number, invert: boolean): void => {
this._positions[i] = vec2.create();
this._labels[i] = new Position2DLabel(new Text(`${source}: ${preset} #${steps}`), Label.Type.Dynamic);
this._labels[i].lineAnchor = Label.LineAnchor.Top;
this._textures[i] = new Texture2D(context, `Texture${preset}`);
this._textures[i].initialize(steps, 1, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE);
ColorScale.fromPreset(`data/${source}.json`, preset, steps).then((scale: ColorScale) => {
if (invert) {
scale.invert();
}
const data = scale.bitsUI8(Color.Space.RGB, false);
this._textures[i].data(data, true, false);
});
};
this._positions.length = this._labels.length = this._textures.length = this._presets.length;
for (let i = 0; i < this._presets.length; ++i) {
createLabeledColorScaleRect(i,
this._presets[i][0], this._presets[i][1], this._presets[i][2], this._presets[i][3]);
}
this._labelPass.labels = this._labels;
for (const label of this._labelPass.labels) {
label.fontSize = 15.0 * Label.devicePixelRatio();
label.color.fromHex('#fff');
label.fontSizeUnit = Label.Unit.Pixel;
}
return true;
}
/**
* Uninitializes Buffers, Textures, and Program.
*/
protected onUninitialize(): void {
super.uninitialize();
this._defaultFBO.uninitialize();
this._labelPass.uninitialize();
}
protected onDiscarded(): void {
this._altered.alter('canvasSize');
this._altered.alter('clearColor');
this._altered.alter('frameSize');
this._altered.alter('multiFrameNumber');
}
/**
* 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;
for (let i = 0; i < this._presets.length; ++i) {
const [x, y] = [i % 4, Math.floor(i / 4)];
this._positions[i][0] = (x + 1) * 0.05 + x * 0.45 - 1.0;
this._positions[i][1] = (y + 1) * 0.15 + y * 0.10 - 1.0 + 0.05;
}
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, true, false);
this._labelPass.frame();
this._program.bind();
gl.uniform2f(this._uExtent, 0.40, 0.40 / 7.0 * this._camera.aspect);
for (let i = 0; i < this._presets.length; ++i) {
this._textures[i].bind(gl.TEXTURE0);
gl.uniform2fv(this._uOffset, this._positions[i]);
this._ndcrect.draw();
}
this._program.unbind();
}
protected updateLabels(): void {
if (!this._labelPass.initialized) {
return;
}
const s05 = vec2.fromValues(this._canvasSize[0] * 0.5, this._canvasSize[1] * 0.5);
for (let i = 0; i < this._presets.length; ++i) {
this._labels[i].position = vec2.mul(vec2.create(), this._positions[i], s05);
}
}
}
export class ColorScaleExample extends Example {
private _canvas: Canvas;
private _renderer: ColorScaleRenderer;
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 ColorScaleRenderer();
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(): ColorScaleRenderer {
return this._renderer;
}
} | the_stack |
import { GridItem } from "../../src/GridItem";
import { ItemRenderer } from "../../src/ItemRenderer";
import { cleanup, sandbox } from "./utils/utils";
describe("test ItemRenderer", () => {
let itemRenderer: ItemRenderer;
let el: HTMLElement;
beforeEach(() => {
el = sandbox("");
});
afterEach(() => {
cleanup();
});
[false, true].forEach((horizontal) => {
it(`should check changing inline size through setContainerRect (horizontal: ${horizontal})`, () => {
// Given
itemRenderer = new ItemRenderer({
horizontal,
});
// When
itemRenderer.setContainerRect({
width: 100,
height: 200,
});
// Then
if (horizontal) {
expect(itemRenderer.getInlineSize()).to.be.equals(200);
} else {
expect(itemRenderer.getInlineSize()).to.be.equals(100);
}
});
});
it(`should checks whether the item's rect is calculated by calling updateItems`, () => {
// Given
el.style.cssText = "position: absolute; left: 50px; top: 50px; width: 200px; height: 100px;";
itemRenderer = new ItemRenderer({
horizontal: false,
});
const item: GridItem = new GridItem(false, {
element: el,
});
// When
itemRenderer.updateItems([item]);
const rect1 = item.rect!;
el.style.width = "300px";
// 300 x 100
itemRenderer.updateItems([item]);
const rect2 = item.rect!;
// Then
expect(item.orgRect!.width).to.be.equals(200);
expect(item.orgRect!.height).to.be.equals(100);
expect(item.orgRect!.top).to.be.equals(50);
expect(item.orgRect!.left).to.be.equals(50);
expect(rect1.width).to.be.equals(200);
expect(rect1.height).to.be.equals(100);
expect(rect1.top).to.be.equals(50);
expect(rect1.left).to.be.equals(50);
expect(rect2.width).to.be.equals(300);
expect(rect2.height).to.be.equals(100);
expect(rect2.top).to.be.equals(50);
expect(rect2.left).to.be.equals(50);
});
it(`should check if all items are the same size when isEqualSize is true`, () => {
// Given
el.style.cssText = "position: absolute; left: 50px; top: 50px; width: 200px; height: 100px;";
itemRenderer = new ItemRenderer({
horizontal: false,
isEqualSize: true,
});
const item1: GridItem = new GridItem(false, {
element: el,
});
const item2: GridItem = new GridItem(false, {
element: el,
});
// When
itemRenderer.updateItems([item1]);
el.style.width = "300px";
// When isEqualSize is true, the size is recognized as the same.
itemRenderer.updateItems([item2]);
// Then
expect(item1.orgRect!.width).to.be.equals(200);
expect(item1.orgRect!.height).to.be.equals(100);
expect(item1.rect!.width).to.be.equals(200);
expect(item1.rect!.height).to.be.equals(100);
expect(item2.orgRect!.width).to.be.equals(200);
expect(item2.orgRect!.height).to.be.equals(100);
expect(item2.rect!.width).to.be.equals(200);
expect(item2.rect!.height).to.be.equals(100);
});
it(`should Check if the rect can be updated by resize when isEqualSize is true.`, () => {
// Given
el.style.cssText = "position: absolute; left: 50px; top: 50px; width: 200px; height: 100px;";
itemRenderer = new ItemRenderer({
horizontal: false,
isEqualSize: true,
});
const item1: GridItem = new GridItem(false, {
element: el,
});
const item2: GridItem = new GridItem(false, {
element: el,
});
// When
itemRenderer.updateItems([item1]);
itemRenderer.resize();
el.style.width = "300px";
// When isEqualSize is true, the size is recognized as the same.
itemRenderer.updateItems([item2]);
// Then
expect(item1.orgRect!.width).to.be.equals(200);
expect(item1.orgRect!.height).to.be.equals(100);
expect(item1.rect!.width).to.be.equals(200);
expect(item1.rect!.height).to.be.equals(100);
expect(item2.orgRect!.width).to.be.equals(300);
expect(item2.orgRect!.height).to.be.equals(100);
expect(item2.rect!.width).to.be.equals(300);
expect(item2.rect!.height).to.be.equals(100);
});
it(`should check if check if the size is not updated. when isConstantSize is true`, () => {
// Given
el.style.cssText = "position: absolute; left: 50px; top: 50px; width: 200px; height: 100px;";
itemRenderer = new ItemRenderer({
horizontal: false,
isConstantSize: true,
});
const item: GridItem = new GridItem(false, {
element: el,
});
// When
itemRenderer.updateItems([item]);
el.style.width = "300px";
// When isEqualSize is true, the size is recognized as the same.
itemRenderer.updateItems([item]);
// Then
expect(item.orgRect!.width).to.be.equals(200);
expect(item.orgRect!.height).to.be.equals(100);
expect(item.rect!.width).to.be.equals(200);
expect(item.rect!.height).to.be.equals(100);
});
it(`should check if the style is set in the element when the item is rendered`, () => {
// Given
el.style.cssText = "";
itemRenderer = new ItemRenderer({
horizontal: false,
});
itemRenderer.setContainerRect({
width: 100,
height: 200,
});
const item: GridItem = new GridItem(false, {
element: el,
cssRect: {
left: 100,
width: 50,
},
});
// When
itemRenderer.renderItems([item]);
// Then
expect(el.style.left).to.be.equals("100px");
expect(el.style.width).to.be.equals("50px");
expect(el.style.top).to.be.equals("");
expect(el.style.height).to.be.equals("");
});
it(`should check if transform is used instead of left and top when useTransform is true`, () => {
// Given
el.style.cssText = "";
itemRenderer = new ItemRenderer({
horizontal: false,
useTransform: true,
});
itemRenderer.setContainerRect({
width: 100,
height: 200,
});
const item: GridItem = new GridItem(false, {
element: el,
cssRect: {
left: 100,
width: 50,
},
});
// When
itemRenderer.renderItems([item]);
// Then
expect(el.style.top).to.be.equals("");
expect(el.style.left).to.be.equals("");
expect(el.style.transform).to.be.equals("translate(100px, 0px)");
});
it(`should check if the style is set in the element when the item is rendered`, () => {
// Given
el.style.cssText = "display: block;";
itemRenderer = new ItemRenderer({
horizontal: false,
});
itemRenderer.setContainerRect({
width: 100,
height: 200,
});
const item: GridItem = new GridItem(false, {
element: el,
cssRect: {
left: 100,
width: 50,
},
});
// When
itemRenderer.renderItems([item]);
// Then
expect(el.style.left).to.be.equals("100px");
expect(el.style.width).to.be.equals("50px");
expect(el.style.top).to.be.equals("");
expect(el.style.height).to.be.equals("");
expect(el.style.display).to.be.equals("block");
});
[true, false].forEach((horizontal) => {
it(`should check if inline pos and size are % when percentage is true (horizontal: ${horizontal})`, () => {
// Given
el.style.cssText = "";
itemRenderer = new ItemRenderer({
horizontal,
percentage: true,
});
itemRenderer.setContainerRect({
width: 100,
height: 200,
});
const item: GridItem = new GridItem(horizontal, {
element: el,
cssRect: {
left: 100,
top: 50,
width: 50,
height: 50,
},
});
// When
itemRenderer.renderItems([item]);
// Then
if (horizontal) {
// top , height are %
expect(el.style.left).to.be.equals("100px");
expect(el.style.width).to.be.equals("50px");
expect(el.style.top).to.be.equals("25%");
expect(el.style.height).to.be.equals("25%");
} else {
// left , width are %
expect(el.style.left).to.be.equals("100%");
expect(el.style.width).to.be.equals("50%");
expect(el.style.top).to.be.equals("50px");
expect(el.style.height).to.be.equals("50px");
}
});
it(`should check if inline pos is % when percentage is ["position"] (horizontal: ${horizontal})`, () => {
// Given
el.style.cssText = "";
itemRenderer = new ItemRenderer({
horizontal,
percentage: ["position"],
});
itemRenderer.setContainerRect({
width: 100,
height: 200,
});
const item: GridItem = new GridItem(horizontal, {
element: el,
cssRect: {
left: 100,
top: 50,
width: 50,
height: 50,
},
});
// When
itemRenderer.renderItems([item]);
// Then
if (horizontal) {
// top are %
expect(el.style.left).to.be.equals("100px");
expect(el.style.width).to.be.equals("50px");
expect(el.style.top).to.be.equals("25%");
expect(el.style.height).to.be.equals("50px");
} else {
// left are %
expect(el.style.left).to.be.equals("100%");
expect(el.style.width).to.be.equals("50px");
expect(el.style.top).to.be.equals("50px");
expect(el.style.height).to.be.equals("50px");
}
});
it(`should check if inline size is % when percentage is ["size"] (horizontal: ${horizontal})`, () => {
// Given
el.style.cssText = "";
itemRenderer = new ItemRenderer({
horizontal,
percentage: ["size"],
});
itemRenderer.setContainerRect({
width: 100,
height: 200,
});
const item: GridItem = new GridItem(horizontal, {
element: el,
cssRect: {
left: 100,
top: 50,
width: 50,
height: 50,
},
});
// When
itemRenderer.renderItems([item]);
// Then
if (horizontal) {
// height are %
expect(el.style.left).to.be.equals("100px");
expect(el.style.width).to.be.equals("50px");
expect(el.style.top).to.be.equals("50px");
expect(el.style.height).to.be.equals("25%");
} else {
// width are %
expect(el.style.left).to.be.equals("100px");
expect(el.style.width).to.be.equals("50%");
expect(el.style.top).to.be.equals("50px");
expect(el.style.height).to.be.equals("50px");
}
});
});
it(`should check get status and restore status`, () => {
// Given
el.style.cssText = "position: absolute; left: 50px; top: 50px; width: 200px; height: 100px;";
itemRenderer = new ItemRenderer({
horizontal: false,
isEqualSize: true,
});
itemRenderer.setContainerRect({
width: 100,
height: 200,
});
const item: GridItem = new GridItem(false, {
element: el,
});
itemRenderer.updateItems([item]);
// When
// { left: 50, top: 50, width: 200, height: 100 }
const status = itemRenderer.getStatus();
// strange rect
el.style.cssText = "position: absolute; left: 30px; top: 30px; width: 100px; height: 50px;";
// reset renderer
itemRenderer = new ItemRenderer({
horizontal: false,
isEqualSize: true,
});
itemRenderer.setContainerRect({
width: 100,
height: 200,
});
itemRenderer.setStatus(status);
const item2: GridItem = new GridItem(false, {
element: el,
});
itemRenderer.updateItems([item2]);
// Then
expect(item2.rect!.width).to.be.equals(200);
expect(item2.rect!.height).to.be.equals(100);
});
it("should check the data attributes.", () => {
// Given
el.setAttribute("test", "test");
el.setAttribute("data-grid-test", "data-grid-test");
itemRenderer = new ItemRenderer({
horizontal: false,
});
const item: GridItem = new GridItem(false, {
element: el,
});
// When
itemRenderer.updateItems([item]);
// Then
expect(item.attributes).to.be.deep.equals({
"test": "data-grid-test",
});
});
}); | the_stack |
module TDev.RT {
interface SpriteAnimationData {
apply : (rt : Runtime, sprite : Sprite, value : number) => void;
easing : (value : number) => number;
duration : number;
repeat : number;
yoyo:boolean;
reversed: boolean;
init?: (sprite: Sprite) => void;
}
//? A animation to animate sprite properties.
//@ stem("anim") ctx(general)
export class SpriteAnimation
extends RTValue
{
private _tweens : SpriteAnimationData[] = [];
private _onStart : Event_;
private _onStop : Event_;
private _tweenIndex = 0;
private _t : number = -1;
private _timeScale = 1;
public isActive = true;
constructor(public _sprite : Sprite) {
super();
}
private pushTween(
apply : (rt : Runtime, sprite : Sprite, value : number) => void,
easing : (value : number) => number,
duration : number) : SpriteAnimationData {
this.ensureActive();
if (this._tweens.length > 0 && this._tweens[this._tweens.length-1].repeat < 0)
Util.userError(lf("the previous animation repeats forever"));
var tween = { apply : apply,
easing : easing,
duration : Math.max(duration,0),
repeat : 1,
yoyo:false,
reversed:false
};
this._tweens.push(tween);
return tween;
}
private ensureActive() {
if(!this.isActive) Util.userError(lf("trying to chain a tween that has already stopped"));
}
static easing = {
linear : {
in : function(x) { return x; },
out : function(x) { return x; },
inout : function(x) { return x; },
},
quadratic : {
in : function(x) { return x*x; },
out : function(x) { return x*(2-x); },
inout : function(x) { return (x*=2) < 1 ? x*x/2 : (1-(--x)*(x-2))/2; },
},
cubic : {
in : function(x) { return x*x*x; },
out : function(x) { --x; return 1 + x*x*x; },
inout : function(x) { return (x*=2) < 1 ? x*x*x/2 : ((x-=2)*x*x+2)/2; }
},
sine : {
in : function(x) { return 1 - Math.cos(x*Math.PI/2); },
out : function(x) { return Math.sin(x * Math.PI/2); },
inout : function(x) { return (1 - Math.cos(Math.PI*x))/2; },
},
expo : {
in : function(x) { return x==0 ? 0 : Math.pow(1024, x - 1); },
out : function(x) { return x==1 ? 1 : 1-Math.pow(2, -10 * x); },
inout : function(x) { return x==0 ? 0 : x==1 ? 1 : (x*=2) < 1 ? Math.pow(1024, x-1)/2 : 1 - Math.pow(2,-10*(x-1)) / 2; },
},
};
static resolveEasing(name : string, shape : string) {
var e = SpriteAnimation.easing[name.toLowerCase().replace(' ', '')] || SpriteAnimation.easing['cubic'];
return e[shape.toLowerCase().replace(' ', '')] || e['inout'];
}
//? Gets the current time scale factor
//@ readsMutable
public time_scale() : number { return this._timeScale; }
//? Sets the current time scale factor
//@ writesMutable [scale].defl(1)
public set_time_scale(scale : number) {
this._timeScale = scale;
}
//? Moves the sprite to a given location using separate easing for x and y
//@ writesMutable
//@ [duration].defl(1)
//@ [easing].deflStrings('cubic', 'linear', 'quadratic', 'expo', 'sine')
//@ [shape].deflStrings('inout', 'out', 'in')
public move_to(duration : number, easing : string, shape : string, x : number, y : number) {
var oldx = this._sprite.x();
var oldy = this._sprite.y();
var dx = x - oldx;
var dy = y - oldy;
var tw = this.pushTween(
function(rt,sprite,k) {
sprite.set_pos(oldx + k * dx, oldy + k * dy);
},
SpriteAnimation.resolveEasing(easing,shape),
duration);
tw.init = function(sp) {
oldx = sp.x();
oldy = sp.y();
dx = x - oldx;
dy = y - oldy;
}
}
//? Changes the text of the sprite.
//@ [duration].defl(1)
//@ [easing].deflStrings('cubic', 'linear', 'quadratic', 'expo', 'sine')
//@ [shape].deflStrings('inout', 'out', 'in')
public text(duration: number, easing: string, shape: string, value: string) {
var oldtext = this._sprite.text() || "";
var oldnumber = parseInt(oldtext);
var newnumber = parseInt(value);
// interpolating between numbers?
if (!isNaN(newnumber) && (!isNaN(oldnumber) || !oldnumber)) {
if (isNaN(oldnumber)) oldnumber = 0;
var d = newnumber - oldnumber;
this.pushTween(
function (rt, sprite, k) {
sprite.set_text(Math_.round(oldnumber + k * d).toString());
},
SpriteAnimation.resolveEasing(easing, shape),
duration);
}
else {
var n = Math.max(oldtext.length, value.length);
var s = oldtext;
this.pushTween(
function (rt, sprite, k) {
var i = Math.floor(k * n);
var c = value[i] || "";
s = (value.substring(0, i) || "") + + (oldtext.substring(i) || "");
sprite.set_text(s);
},
SpriteAnimation.resolveEasing(easing, shape),
duration);
}
}
//? Changes the color of the sprite
//@ [duration].defl(1)
//@ [easing].deflStrings('cubic', 'linear', 'quadratic', 'expo', 'sine')
//@ [shape].deflStrings('inout', 'out', 'in')
public color(duration : number, easing : string, shape : string, c : Color) {
var old = this._sprite.color();
var tw = this.pushTween(
function(rt,sprite,k) {
var onek = 1 - k;
sprite.set_color(Color.fromArgb(old.a * k + c.a * onek, old.r * k + c.r * onek, old.g * k + c.g * onek, old.b * k + c.b * onek));
},
SpriteAnimation.resolveEasing(easing,shape),
duration);
tw.init = function(sprite) { old = sprite.color(); }
}
//? Creating a beating animation
//@ writesMutable [duration].defl(0.3) [cycle].defl(2) [value].defl(1.1)
public beat(duration : number, cycle : number, value : number) {
this.scale(duration, 'quadratic', 'inout', value);
this.repeat(cycle * 2, true);
}
//? Scales the sprite
//@ writesMutable [duration].defl(0.5) [value].defl(1.2)
//@ [easing].deflStrings('sine', 'linear', 'quadratic', 'cubic', 'expo')
//@ [shape].deflStrings('inout', 'out', 'in')
public scale(duration : number, easing : string, shape : string, value : number) {
var current = 1.0;
this.pushTween(
function(rt, sprite, k) { sprite.set_scale(current * (1-k) + k * value); },
SpriteAnimation.resolveEasing(easing, shape),
duration);
}
//? Modifies the sprite width
//@ writesMutable [duration].defl(0.5) [value].defl(100)
//@ [easing].deflStrings('sine', 'linear', 'quadratic', 'cubic', 'expo')
//@ [shape].deflStrings('inout', 'out', 'in')
public width(duration: number, easing: string, shape: string, value: number) {
var current = this._sprite.width();
this.pushTween(
function (rt, sprite, k) { sprite.set_width(current * (1 - k) + k * value); },
SpriteAnimation.resolveEasing(easing, shape),
duration);
}
//? Modifies the sprite height
//@ writesMutable [duration].defl(0.5) [value].defl(100)
//@ [easing].deflStrings('sine', 'linear', 'quadratic', 'cubic', 'expo')
//@ [shape].deflStrings('inout', 'out', 'in')
public height(duration: number, easing: string, shape: string, value: number) {
var current = this._sprite.height();
this.pushTween(
function (rt, sprite, k) { sprite.set_height(current * (1 - k) + k * value); },
SpriteAnimation.resolveEasing(easing, shape),
duration);
}
//? Starts a new animation and continues with the current animation
//@ writesMutable
public fork() : SpriteAnimation {
var anim = this._sprite.createAnimation();
this.pushTween(
function(rt, sprite, k) { sprite.startAnimation(anim); },
SpriteAnimation.easing['linear']['in'],
0);
return anim;
}
//? Waits till the animation completes. This action will evolve the board if needed.
//@ async
public wait(r: ResumeCtx) {
var board = this._sprite._parent;
var boardTick = board.tick;
if (!board) {
r.resume();
return;
}
App.allow_other_events(r.stackframe);
var step = () => {
r.rt.yield_now();
// call evolved if not called in another loop
if (boardTick != board.tick) {
boardTick = board.tick;
board.evolve();
board.update_on_wall();
}
if (!this.isActive)
r.resume();
else Util.setTimeout(100, step);
};
step();
}
//? Waits for the other animation to complete before proceding.
public wait_for(animation : SpriteAnimation) {
var tween = this.pushTween(
function(rt, sprite, k) {
if(!animation.isActive)
tween.duration = -1;
},
SpriteAnimation.easing['linear']['in'],
1e6);
}
//? Stops this animation
//@ writesMutable
public stop() {
// this will stop the tweening on the next iteration
this._tweenIndex = this._tweens.length;
this._t = 0;
}
//? Repeats the latest animation. Negative ``count`` makes infinite repetition. ``yoyo`` makes the animation repeat back and forth.
//@ writesMutable [count].defl(2)
public repeat(count : number, yoyo : boolean) {
this.ensureActive();
if (this._tweens.length > 0) {
var tween = this._tweens[this._tweens.length - 1];
tween.repeat = count;
tween.yoyo = yoyo;
tween.reversed = false;
}
}
//? Raised when the animation started playing
//@ ignoreReturnValue writesMutable
public on_start(body : Action) : EventBinding{
if (!this._onStart) this._onStart = new Event_();
return this._onStart.addHandler(body);
}
//? Raised when the animation stopped playing
//@ ignoreReturnValue writesMutable
public on_stop(body : Action) : EventBinding{
this.ensureActive();
if (!this._onStop) this._onStop = new Event_();
return this._onStop.addHandler(body);
}
//? Waits for a number of seconds
//@ [duration].defl(1) writesMutable
public sleep(duration : number) {
this.pushTween(
function(rt, sprite, x) {},
SpriteAnimation.easing['linear']['in'],
duration
);
}
//? Fades in to fully opaque
//@ writesMutable [duration].defl(0.5)
//@ [easing].deflStrings('cubic', 'linear', 'quadratic', 'expo', 'sine')
public fade_in(duration : number, easing : string)
{
var old = this._sprite.opacity();
var tw = this.pushTween(
function(rt, sprite, value) {
sprite.set_opacity(old * (1-value) + value);
},
SpriteAnimation.resolveEasing(easing, 'in'),
duration
);
tw.init = function(sprite) { old = sprite.opacity() };
}
//? Fades out to transparent
//@ writesMutable [duration].defl(0.5)
//@ [easing].deflStrings('cubic', 'linear', 'quadratic', 'expo', 'sine')
public fade_out(duration : number, easing : string)
{
var old = this._sprite.opacity();
var tw = this.pushTween(
function(rt, sprite, value) {
sprite.set_opacity(old*(1-value));
},
SpriteAnimation.resolveEasing(easing, 'out'),
duration
);
tw.init = function(sprite) { old = sprite.opacity() };
}
//? Changes the opacity of the sprite
//@ writesMutable [duration].defl(0.5)
//@ [easing].deflStrings('cubic', 'linear', 'quadratic', 'expo', 'sine')
//@ [shape].deflStrings('inout', 'out', 'in')
public fade(duration: number, easing: string, shape: string, opacity : number) {
var old = this._sprite.opacity();
opacity = Math_.normalize(opacity);
var tw = this.pushTween(
function (rt, sprite, value) {
sprite.set_opacity(old * (1 - value) + opacity * value);
},
SpriteAnimation.resolveEasing(easing, shape),
duration
);
tw.init = function(sprite) { old = sprite.opacity() };
}
//? Scales up and fades out an object
//@ writesMutable [duration].defl(0.5) [scale].defl(1.5)
//@ [easing].deflStrings('cubic', 'linear', 'quadratic', 'expo', 'sine')
public puff_out(duration : number, easing : string, scale : number)
{
var oldop = this._sprite.opacity();
var oldscale = this._sprite.scale();
var tw = this.pushTween(
function(rt, sprite, value) {
sprite.set_opacity(oldop*(1-value));
sprite.set_scale(oldscale * (1-value) + value * scale);
},
SpriteAnimation.resolveEasing(easing, 'out'),
duration
);
tw.init = function(sprite) {
oldop = sprite.opacity();
oldscale = sprite.scale();
};
}
//? Hides the sprite
//@ writesMutable
public hide() {
this.pushTween(
function(rt, sprite, value) { sprite.hide(); },
SpriteAnimation.easing['linear']['in'],
0
);
}
//? shows the sprite
//@ writesMutable
public show() {
this.pushTween(
function(rt, sprite, value) { sprite.show(); },
SpriteAnimation.easing['linear']['in'],
0
);
}
//? deletes the sprite
//@ writesMutable
public delete_() {
this.pushTween(
function(rt, sprite, value) { sprite.delete_(); },
SpriteAnimation.easing['linear']['in'],
0
);
}
//? play sound
//@ writesMutable
public play_sound(sound : Sound) {
this.pushTween(
function(rt, sprite, value) { sound.playAsync().done(); },
SpriteAnimation.easing['linear']['in'],
0
);
}
//? Sets a different frame from the sprite sheet
public frame(name : string) {
var sheet = this._sprite.sheet();
if (sheet)
this.pushTween(
function(rt, sprite, value) {
sheet.set_frame(sprite, name);
},
SpriteAnimation.easing['linear']['in'],
0
);
}
//? Starts playing an animation from the sprite sheet, if any
//@ writesMutable
//@ [animation].defl('all')
public play_frames(animation : string) {
var sheet = this._sprite.sheet();
if (sheet) {
var data = sheet.findAnimation(animation);
if (data) {
this.pushTween(
function(rt, sprite, x) {
sheet.set_frame(sprite, data.frames[Math.floor(x * (data.frames.length - 1))]);
},
SpriteAnimation.resolveEasing('linear', 'in'),
data.duration);
this.repeat(data.loopCount, data.yoyo);
}
}
}
//? Rotates the sprite.
//@ writesMutable [duration].defl(1)
//@ [easing].deflStrings('expo', 'linear', 'quadratic', 'cubic', 'sine')
//@ [shape].deflStrings('in', 'out', 'inout')
public turn_to(duration : number, easing : string, shape : string, angle : number) {
var old = this._sprite.angle();
var tw = this.pushTween(
function(rt, sprite, value) { sprite.set_angle(old * value + (1-value) * angle); },
SpriteAnimation.resolveEasing(easing,shape),
duration
);
tw.init = function(sp) { old = sp.angle() };
}
//? Calls a user handler during the animation. ``handler`` receives a number from 0 to 1 during the tweeining.
//@ writesMutable [duration].defl(1)
//@ [easing].deflStrings('expo', 'linear', 'quadratic', 'cubic', 'sine')
//@ [shape].deflStrings('in', 'out', 'inout')
public run(duration : number, easing : string, shape : string, handler : NumberAction) {
var ev = new Event_();
ev.addHandler(handler);
this.pushTween(
(rt, sprite, x) => {
rt.queueLocalEvent(ev, [x], false);
},
SpriteAnimation.resolveEasing(easing, shape),
duration
);
}
private initTween(tween: SpriteAnimationData) {
if (tween && tween.init) {
tween.init(this._sprite);
delete tween.init;
}
}
// returns false if finished
public evolve(rt : Runtime, dT : number) : boolean {
if (!this.isActive) return false;
if (this._t < 0 && this._onStart && this._onStart.handlers) rt.queueLocalEvent(this._onStart, [], false);
var tween = this._tweens[this._tweenIndex];
this._t = this._t < 0 ? 0 : this._t + dT * this._timeScale;
// advance to the next tween if needed
while(tween && this._t > tween.duration) {
// make sure to call tween.apply at least once
this.initTween(tween);
tween.apply(rt, this._sprite, tween.reversed ? 0 : 1);
// increment timer...
this._t = tween.duration < 0 ? 0 : this._t - tween.duration;
if(tween.repeat == 0)
tween = this._tweens[++this._tweenIndex];
else if (tween.repeat > 0 && --tween.repeat == 0)
tween = this._tweens[++this._tweenIndex];
else // repeat
if (tween.yoyo) tween.reversed = !tween.reversed;
}
// are we done?
if (tween) {
// interpolated current tween.
var x = tween.easing(this._t / tween.duration);
this.initTween(tween);
tween.apply(rt,this._sprite, tween.reversed ? 1 - x : x);
return true;
} else {
if (this._onStop && this._onStop.handlers) rt.queueLocalEvent(this._onStop, [], false);
return this.isActive = false;
}
}
//? Gets a value indicating if the animation is still running
public is_active(): boolean {
return this.isActive;
}
public getViewCore(s: IStackFrame, b:BoxBase): HTMLElement {
return div('item', 'tween');
}
//? Describes the animation.
//@ readsMutable
public post_to_wall(s: IStackFrame): void {
super.post_to_wall(s)
}
}
} | the_stack |
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FlatTreeControl} from '@angular/cdk/tree';
import {IFileDescription} from '../i-file-description';
import {BehaviorSubject, EMPTY, merge, Observable, of} from 'rxjs';
import {CollectionViewer, SelectionChange} from '@angular/cdk/collections';
import {expand, last, map, } from 'rxjs/operators';
import {IFileAccessService} from '../i-file-access-service';
import {FileAccessServiceFactoryService} from '../file-access-service-factory.service';
import {isNullOrUndefined} from '../../../common/util';
import {IFileAccessConfiguration} from '../i-file-access-configuration';
import {FormBuilder, FormGroup} from '@angular/forms';
/** Flat node with expandable and level information */
class DynamicFlatNode {
item: string;
maticon?: string;
icon?: string;
constructor(public node: IFileDescription, public level = 1, public expandable = false,
public isLoading = false) {
if (level === 0) {
const configLabel = node.configuration.fullLabel();
this.item = configLabel.label;
this.maticon = configLabel.maticon;
this.icon = configLabel.icon;
} else {
this.item = node.name;
}
}
}
/**
* Database for dynamic file accesss data. When expanding a node in the tree, the data source will need to fetch
* the descendants data from the service.
*/
class FileData {
private rootLevelNodes: IFileDescription[];
constructor(root: IFileDescription, private accessService: IFileAccessService, private onlyDirectories: boolean) {
this.rootLevelNodes = [root];
}
/** Initial data from database */
initialData(): DynamicFlatNode[] {
return this.rootLevelNodes.map(dir => new DynamicFlatNode(dir, 0, true));
}
getChildren(node: IFileDescription): Observable<IFileDescription[] | undefined> {
if (node.type === 'file') {
return of(undefined);
} else {
const children = node.children;
if (isNullOrUndefined(children)) {
return this.accessService.load(node).pipe(
map((result: IFileDescription) => {
return result.children.filter(fd => !this.onlyDirectories || fd.type === 'dir');
})
);
} else {
return of(children.filter(fd => !this.onlyDirectories || fd.type === 'dir'));
}
}
}
isExpandable(node: IFileDescription): boolean {
return node.type === 'dir';
}
}
/**
* File database, it can build a tree structured Json object from string.
* Each node in Json object represents a file or a directory. For a file, it has filename and type.
* For a directory, it has filename and children (a list of files or directories).
* The input will be a json object string, and the output is a list of `FileNode` with nested
* structure.
*/
class DynamicFileDataSource {
dataChange = new BehaviorSubject<DynamicFlatNode[]>([]);
get data(): DynamicFlatNode[] { return this.dataChange.value; }
set data(value: DynamicFlatNode[]) {
this.treeControl.dataNodes = value;
this.dataChange.next(value);
}
constructor(private treeControl: FlatTreeControl<DynamicFlatNode>,
private database: FileData) {}
connect(collectionViewer: CollectionViewer): Observable<DynamicFlatNode[]> {
this.treeControl.expansionModel.changed.subscribe(change => {
if ((change as SelectionChange<DynamicFlatNode>).added ||
(change as SelectionChange<DynamicFlatNode>).removed) {
this.handleTreeControl(change as SelectionChange<DynamicFlatNode>);
}
});
return merge(collectionViewer.viewChange, this.dataChange).pipe(map(() => this.data));
}
/** Handle expand/collapse behaviors */
handleTreeControl(change: SelectionChange<DynamicFlatNode>) {
if (change.added) {
change.added.forEach(node => this.toggleNode(node, true));
}
if (change.removed) {
change.removed.slice().reverse().forEach(node => this.toggleNode(node, false));
}
}
/**
* Toggle the node, remove from display list
*/
toggleNode(node: DynamicFlatNode, expandNode: boolean) {
const children = this.database.getChildren(node.node);
const index = this.data.indexOf(node);
if (index < 0) { // If cannot find the node, no op
return;
}
node.isLoading = true;
children.subscribe(childrenDescr => {
if (expandNode) {
const nodes = childrenDescr.map(filedescr =>
new DynamicFlatNode(filedescr, node.level + 1, this.database.isExpandable(filedescr)));
this.data.splice(index + 1, 0, ...nodes);
} else {
let count = 0;
for (let i = index + 1; i < this.data.length
&& this.data[i].level > node.level; i++, count++) {}
this.data.splice(index + 1, count);
}
// notify the change
this.dataChange.next(this.data);
node.isLoading = false;
}, (error) => {
console.log('error loading children', error); // TODO
node.isLoading = false;
});
}
/**
* Open the tree up to the given node.
* @param node node to be visible
* @param callBack called when node is contained in the tree.
*/
openNode(node: IFileDescription, callBack: (node: DynamicFlatNode) => void) {
const start: {data: DynamicFlatNode[], index: number, path: string, pathIndex: number}
= {data: this.data, index: 0, path: node.path, pathIndex: 0};
of(start).pipe(
expand(current => {
if (current.index < 0 || current.pathIndex < 0) {
return EMPTY;
} else {
return this.openSubdir(current);
}
}),
last()
).subscribe(current => {
this.dataChange.next(current.data);
if (current.index >= 0) {
callBack(current.data[current.index]);
}
});
}
openSubdir(current: {data: DynamicFlatNode[], index: number, path: string, pathIndex: number})
: Observable<{data: DynamicFlatNode[], index: number, path: string, pathIndex: number}> {
if (current.index < 0 || current.pathIndex < 0) {
return of(current);
}
const nodeToExpand = current.data[current.index];
const pathParts = (current.path) ? current.path.split('/') : [];
if (!nodeToExpand || current.pathIndex >= pathParts.length) {
return of({data: current.data, index: current.index, path: current.path, pathIndex: -1});
}
const dirNameToOpen = pathParts[current.pathIndex];
return this.database.getChildren(nodeToExpand.node).pipe(
map((childrenDescr: IFileDescription[]) => {
const nodes = childrenDescr.map(filedescr =>
new DynamicFlatNode(filedescr, nodeToExpand.level + 1, this.database.isExpandable(filedescr)));
const newData = current.data.slice();
newData.splice(current.index + 1, 0, ...nodes);
const indexInNewNodes = nodes.findIndex((node) => node.node.name === dirNameToOpen);
if (indexInNewNodes < 0) {
return {data: current.data, index: -1, path: current.path, pathIndex: current.pathIndex};
} else {
const newIndex = current.index + 1 + indexInNewNodes;
return {
data: newData,
index: newIndex,
path: current.path,
pathIndex: current.pathIndex + 1
};
}
})
);
}
}
@Component({
selector: 'app-file-explorer',
templateUrl: './file-explorer.component.html',
styleUrls: ['./file-explorer.component.scss']
})
export class FileExplorerComponent implements OnInit {
/**
* The selectable configurations.
* If null, there will be no selection.
*/
@Input() configurations?: IFileAccessConfiguration[];
/**
* Root file (a directory) to be shown in the explorer.
*/
@Input() root: IFileDescription;
/**
* Selected file when starting the component.
*/
@Input() file: IFileDescription;
/**
* Determine what sort of entries can be selected.
* 'file': only files.
* 'dir': only directories
* undefined: everything.
*/
@Input() selectableFileType?: 'file'|'dir';
/**
* The selected file node.
*/
@Output() selectedFile: EventEmitter<IFileDescription> = new EventEmitter<IFileDescription>();
form: FormGroup;
_currentRoot: IFileDescription;
treeControl: FlatTreeControl<DynamicFlatNode>;
dataSource: DynamicFileDataSource;
activeNode: DynamicFlatNode;
getLevel = (node: DynamicFlatNode) => node.level;
isExpandable = (node: DynamicFlatNode) => node.expandable;
hasChild = (_: number, _nodeData: DynamicFlatNode) => _nodeData.expandable;
constructor(private formBuilder: FormBuilder, private fileAccessServiceFactoryService: FileAccessServiceFactoryService) {
}
ngOnInit() {
this.currentRoot = this.root.configuration.rootDescription();
this.initForm();
this.form.valueChanges.subscribe((val) => {
this.currentRoot = this.configurations[val.selectedConfigurationIndex].rootDescription();
});
}
initForm() {
if (!this.form) {
const index = (!this.root || !this.configurations) ?
0 :
this.configurations.findIndex(conf => conf.id === this.root.configuration.id);
this.form = this.formBuilder.group(
{
selectedConfigurationIndex: [index]
}
);
}
}
get currentRoot(): IFileDescription {
return this._currentRoot;
}
set currentRoot(newRoot: IFileDescription) {
if (newRoot) {
const accessService = this.fileAccessServiceFactoryService.getFileAccessService(newRoot.configuration.type);
const database = new FileData(newRoot, accessService, (this.selectableFileType === 'dir'));
this.treeControl = new FlatTreeControl<DynamicFlatNode>(this.getLevel, this.isExpandable);
this.dataSource = new DynamicFileDataSource(this.treeControl, database);
this.dataSource.data = database.initialData();
if (this.file && !this._currentRoot) {
this.dataSource.openNode(this.file, (node) => { this.activeNode = node; });
} else {
this.dataSource.openNode(newRoot, (node) => {
this.activeNode = node;
this.selected(this.activeNode);
});
}
if (this.fileTypeMatches(newRoot)) {
this.selectedFile.emit(newRoot);
}
} else {
this.dataSource = null;
}
this._currentRoot = newRoot;
}
selected(node: DynamicFlatNode) {
if (node && this.fileTypeMatches(node.node)) {
this.selectedFile.emit(node.node);
this.activeNode = node;
} else {
this.selectedFile.emit(null);
this.activeNode = null;
}
}
private fileTypeMatches(file: IFileDescription): boolean {
if (isNullOrUndefined(this.selectableFileType)) {
return true;
} else {
return this.selectableFileType === file.type;
}
}
} | the_stack |
import { BrushEndListener, BrushEvent } from '@elastic/charts'
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { Space, Button, Spin, Alert, Tooltip, Drawer, Result } from 'antd'
import { LoadingOutlined, SettingOutlined } from '@ant-design/icons'
import { useTranslation } from 'react-i18next'
import { useMount, useSessionStorage } from 'react-use'
import { useMemoizedFn } from 'ahooks'
import { sortBy } from 'lodash'
import formatSql from '@lib/utils/sqlFormatter'
import client, { TopsqlInstanceItem, TopsqlSummaryItem } from '@lib/client'
import {
Card,
TimeRangeSelector,
toTimeRangeValue,
DEFAULT_TIME_RANGE,
Toolbar,
AutoRefreshButton,
TimeRange,
fromTimeRangeValue,
TimeRangeValue,
} from '@lib/components'
import { useClientRequest } from '@lib/utils/useClientRequest'
import { telemetry } from '../../utils/telemetry'
import { InstanceSelect } from '../../components/Filter'
import styles from './List.module.less'
import { ListTable } from './ListTable'
import { ListChart } from './ListChart'
import { SettingsForm } from './SettingsForm'
import { onLegendItemOver, onLegendItemOut } from './legendAction'
import { InstanceType } from './ListDetail/ListDetailTable'
const TOP_N = 5
const CHART_BAR_WIDTH = 8
export function TopSQLList() {
const { t } = useTranslation()
const { topSQLConfig, isConfigLoading, updateConfig, haveHistoryData } =
useTopSQLConfig()
const [showSettings, setShowSettings] = useState(false)
const [instance, setInstance] = useSessionStorage<TopsqlInstanceItem | null>(
'topsql.instance',
null
)
const [timeRange, setTimeRange] = useSessionStorage(
'topsql.recent_time_range',
DEFAULT_TIME_RANGE
)
const [timeWindowSize, setTimeWindowSize] = useState(0)
const containerRef = useRef<HTMLDivElement>(null)
const computeTimeWindowSize = useMemoizedFn(
([min, max]: TimeRangeValue): number => {
const screenWidth = containerRef.current?.offsetWidth || 0
const windowSize = Math.ceil(
(CHART_BAR_WIDTH * (max - min)) / screenWidth
)
setTimeWindowSize(windowSize)
return windowSize
}
)
const {
topSQLData,
isLoading: isDataLoading,
updateTopSQLData,
} = useTopSQLData(instance, timeRange, computeTimeWindowSize)
const isLoading = isConfigLoading || isDataLoading
const {
instances,
isLoading: isInstancesLoading,
fetchInstances,
} = useInstances(timeRange)
const handleBrushEnd: BrushEndListener = useCallback(
(v: BrushEvent) => {
if (!v.x) {
return
}
let value: [number, number]
const tr = v.x.map((d) => d / 1000)
const delta = tr[1] - tr[0]
if (delta < 60) {
const offset = Math.floor(delta / 2)
value = [
Math.ceil(tr[0] + offset - 30),
Math.floor(tr[1] - offset + 30),
]
} else {
value = [Math.ceil(tr[0]), Math.floor(tr[1])]
}
setTimeRange(fromTimeRangeValue(value))
telemetry.dndZoomIn(value)
},
[setTimeRange]
)
const fetchInstancesAndSelectInstance = useMemoizedFn(async () => {
const [firstInstance] = await fetchInstances(timeRange)
// Select the first instance if there not instance selected
if (!!instance) {
return
}
setInstance(firstInstance)
})
useMount(() => {
fetchInstancesAndSelectInstance()
})
const chartRef = useRef<any>(null)
return (
<>
<div className={styles.container} ref={containerRef}>
{/* Show "not enabled" Alert when there are historical data */}
{!isConfigLoading && !topSQLConfig?.enable && haveHistoryData && (
<Card noMarginBottom>
<Alert
message={t(`topsql.alert_header.title`)}
description={
<>
{t(`topsql.alert_header.body`)}
<a
onClick={() => {
setShowSettings(true)
telemetry.clickSettings('bannerTips')
}}
>
{` ${t('topsql.alert_header.settings')}`}
</a>
</>
}
type="info"
showIcon
/>
</Card>
)}
<Card noMarginBottom>
<Toolbar>
<Space>
<InstanceSelect
value={instance}
onChange={(inst) => {
setInstance(inst)
if (inst) {
telemetry.finishSelectInstance(inst?.instance_type!)
}
}}
instances={instances}
disabled={isLoading || isInstancesLoading}
onDropdownVisibleChange={(open) =>
open && telemetry.openSelectInstance()
}
/>
<TimeRangeSelector.WithZoomOut
value={timeRange}
onChange={(v) => {
setTimeRange(v)
telemetry.selectTimeRange(v)
}}
disabled={isLoading}
/>
<AutoRefreshButton
disabled={isLoading}
onRefresh={async () => {
await fetchInstancesAndSelectInstance()
updateTopSQLData(instance, timeRange)
}}
/>
{isLoading && (
<Spin
indicator={<LoadingOutlined style={{ fontSize: 24 }} spin />}
/>
)}
</Space>
<Space>
<Tooltip title={t('topsql.settings.title')} placement="bottom">
<SettingOutlined
onClick={() => {
setShowSettings(true)
telemetry.clickSettings('settingIcon')
}}
/>
</Tooltip>
</Space>
</Toolbar>
</Card>
{/* Show "not enabled" Result when there are no historical data */}
{!isConfigLoading && !topSQLConfig?.enable && !haveHistoryData ? (
<Result
title={t('topsql.settings.disabled_result.title')}
subTitle={t('topsql.settings.disabled_result.sub_title')}
extra={
<Button
type="primary"
onClick={() => {
setShowSettings(true)
telemetry.clickSettings('firstTimeTips')
}}
>
{t('conprof.settings.open_settings')}
</Button>
}
/>
) : (
<>
<div className={styles.chart_container}>
<ListChart
onBrushEnd={handleBrushEnd}
data={topSQLData}
timeRangeTimestamp={toTimeRangeValue(timeRange)}
timeWindowSize={timeWindowSize}
ref={chartRef}
/>
</div>
{!!topSQLData?.length && (
<ListTable
onRowOver={(key: string) =>
onLegendItemOver(chartRef.current, key)
}
onRowLeave={() => onLegendItemOut(chartRef.current)}
topN={TOP_N}
instanceType={instance?.instance_type as InstanceType}
data={topSQLData}
/>
)}
</>
)}
</div>
<Drawer
title={t('statement.settings.title')}
width={300}
closable={true}
visible={showSettings}
onClose={() => setShowSettings(false)}
destroyOnClose={true}
>
<SettingsForm
onClose={() => setShowSettings(false)}
onConfigUpdated={updateConfig}
/>
</Drawer>
</>
)
}
const useTopSQLData = (
instance: TopsqlInstanceItem | null,
timeRange: TimeRange,
computeTimeWindowSize: (ts: TimeRangeValue) => number
) => {
const [topSQLData, setTopSQLData] = useState<TopsqlSummaryItem[]>([])
const [isLoading, setIsLoading] = useState(false)
const updateTopSQLData = useMemoizedFn(
async (_instance: TopsqlInstanceItem | null, _timeRange: TimeRange) => {
if (!_instance) {
return
}
let data: TopsqlSummaryItem[]
const ts = toTimeRangeValue(_timeRange)
const timeWindowSize = computeTimeWindowSize(ts)
const [start, end] = ts
try {
setIsLoading(true)
const resp = await client
.getInstance()
.topsqlSummaryGet(
String(end),
_instance.instance,
_instance.instance_type,
String(start),
String(TOP_N),
`${timeWindowSize}s`
)
data = resp.data.data ?? []
} finally {
setIsLoading(false)
}
// Sort data by digest
// If this digest occurs continuously on the timeline, we can easily see the sequential overhead
data.sort((a, b) => a.sql_digest?.localeCompare(b.sql_digest!) || 0)
data.forEach((d) => {
d.sql_text = formatSql(d.sql_text)
d.plans?.forEach((item) => {
// Filter empty cpu time data
item.timestamp_sec = item.timestamp_sec?.filter(
(_, index) => !!item.cpu_time_ms?.[index]
)
item.cpu_time_ms = item.cpu_time_ms?.filter((c) => !!c)
item.timestamp_sec = item.timestamp_sec?.map((t) => t * 1000)
})
})
setTopSQLData(data)
}
)
useEffect(() => {
updateTopSQLData(instance, timeRange)
}, [instance, timeRange, updateTopSQLData])
return { topSQLData, isLoading, updateTopSQLData }
}
const useTopSQLConfig = () => {
// Use the instance interface to query if historical data is available
const {
data: topSQLConfig,
isLoading: isConfigLoading,
sendRequest: updateConfig,
} = useClientRequest((reqConfig) =>
client.getInstance().topsqlConfigGet(reqConfig)
)
const [haveHistoryData, setHaveHistoryData] = useState(true)
const [loadingHistory, setLoadingHistory] = useState(true)
useEffect(() => {
if (!topSQLConfig) {
return
}
if (!!topSQLConfig.enable) {
setLoadingHistory(false)
return
}
;(async function () {
const now = Date.now() / 1000
const sevenDaysAgo = now - 7 * 24 * 60 * 60
setLoadingHistory(true)
try {
const res = await client
.getInstance()
.topsqlInstancesGet(String(now), String(sevenDaysAgo))
const data = res.data.data
if (!!data?.length) {
setHaveHistoryData(true)
} else {
setHaveHistoryData(false)
}
} finally {
setLoadingHistory(false)
}
})()
}, [topSQLConfig])
return {
topSQLConfig,
isConfigLoading: isConfigLoading || loadingHistory,
updateConfig,
haveHistoryData,
}
}
const useInstances = (timeRange: TimeRange) => {
const [instances, setInstances] = useState<TopsqlInstanceItem[]>([])
const [isLoading, setLoading] = useState(false)
const fetchInstances = async (
_timeRange: TimeRange | null
): Promise<TopsqlInstanceItem[]> => {
if (!_timeRange) {
return []
}
const [start, end] = toTimeRangeValue(_timeRange)
const resp = await client
.getInstance()
.topsqlInstancesGet(String(end), String(start))
const data = sortBy(resp.data.data || [], ['instance_type', 'instance'])
setInstances(data)
return data
}
useEffect(() => {
setLoading(true)
fetchInstances(timeRange).finally(() => {
setLoading(false)
})
}, [timeRange])
return {
instances,
fetchInstances,
isLoading,
}
} | the_stack |
import { faTrashAlt } from '@fortawesome/free-solid-svg-icons/faTrashAlt';
import { faUndo } from '@fortawesome/free-solid-svg-icons/faUndo';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import * as React from 'react';
import styled from 'styled-components';
import { stopKeyDownEvent, withPreventDefault } from '../../utils';
import { AddTagForm } from './AddTagForm';
import {
ResourceTagInfo,
ResourceTagInfoState,
ResourceTagSubmitInfo,
SubmitInfo,
TaggedResource,
} from './models';
import map from 'lodash/map';
import sortBy from 'lodash/sortBy';
import toString from 'lodash/toString';
import { faPencilAlt } from '@fortawesome/free-solid-svg-icons/faPencilAlt';
import { Heading } from '../Heading';
import { Modal } from '../Modal';
import { Flex } from '../Flex';
import { Input } from '../Input';
import { Button } from '../Button';
import { CollectionSummary } from './CollectionSummary/CollectionSummary';
import { useTranslation } from '../../hooks/useTranslation';
import {
getResourceTagSubmitInfo,
groupResourcesByTags,
} from './tag-management-service';
import partition from 'lodash/partition';
const NBSP = '\u00a0';
const iconStyles = (props: any) => `
font-size: 14px;
color: ${props.theme.colors.text.main};
`;
const FaPencil = (props: any) => (
<FontAwesomeIcon icon={faPencilAlt} {...props} />
);
const EditButtonIcon = styled(FaPencil)`
${iconStyles} margin-left: 10px;
`;
const FaTrashAlt = (props: any) => (
<FontAwesomeIcon icon={faTrashAlt} {...props} />
);
const DeleteButtonIcon = styled(FaTrashAlt)`
${iconStyles};
`;
export const UndoButtonMinWidth = 100;
const UndoButton = styled(Button)`
width: ${UndoButtonMinWidth}px;
text-align: left;
`;
const InputPadder = styled.div`
padding-left: 17px;
padding-right: 17px;
`;
const TdThHorizontalPadding = 10;
const TagTable = styled.table`
width: 100%;
max-width: 100%;
border: none;
border-collapse: collapse;
font-size: 14px;
& > thead > tr > th,
& > thead > tr > td {
padding: 11px ${TdThHorizontalPadding}px;
}
& > thead > tr > th {
height: 42px;
font-size: 16px;
font-weight: bold;
background-color: #f2f2f2;
}
& > tbody > tr > td {
padding: 8px ${TdThHorizontalPadding}px;
height: 50px;
}
& > tbody > tr:nth-of-type(even) {
background-color: #f8f8f8;
}
& > thead > tr > th,
& > tbody > tr > td {
border: none;
vertical-align: middle;
}
`;
const TagTr = styled.tr`
&:hover {
${DeleteButtonIcon}, ${EditButtonIcon} {
opacity: 0.7;
}
}
${DeleteButtonIcon}, ${EditButtonIcon} {
opacity: 0;
cursor: pointer;
&:hover {
opacity: 1;
}
}
`;
const TagDeleteTh = styled.th`
width: 36px;
`;
const TagDeleteTd = styled(TagDeleteTh.withComponent('td'))`
table > tbody > tr > & {
padding-left: 11px;
padding-right: 11px;
}
`;
const TagPropertyTh = styled.th`
width: 30%;
max-width: 300px;
text-align: left;
`;
const TagPropertyTd = TagPropertyTh.withComponent('td');
const TagKeyTd = styled(TagPropertyTd)<{ state?: ResourceTagInfoState }>`
font-weight: bold;
color: ${(props) =>
props.state === 'added' ? props.theme.colors.warning.main : 'inherit'};
`;
const TagValueTd = styled(TagPropertyTd)``;
const TagProperty = styled.div<{ state?: ResourceTagInfoState }>`
display: flex;
max-width: 100%;
color: ${(props) =>
props.state === 'added'
? props.theme.colors.warning.main
: props.state === 'updated'
? props.theme.colors.warning.main
: props.state === 'deleted'
? props.theme.colors.gray.main
: 'inherit'};
& > ${InputPadder} {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
`;
const EdittableTagValue = styled(TagProperty)`
display: flex;
cursor: pointer;
& > ${InputPadder} {
display: inline-flex;
align-items: center;
justify-content: flex-start;
max-width: 100%;
}
`;
const EdittableTagValueText = styled.div`
flex: 1;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
`;
const PreviousTagProperty = styled(TagProperty)`
display: inline-flex;
width: 100%;
margin-bottom: ${(props) => (props.state === 'deleted' ? 0 : 6)}px;
position: relative;
&:after {
content: '';
position: absolute;
left: 0;
right: 0;
display: block;
background: ${(props) => props.theme.colors.warning.main};
height: 2px;
top: 50%;
}
${TagKeyTd} > &, ${TagValueTd} > & {
color: ${(props) => props.theme.colors.gray.main};
}
${TagKeyTd} > &:after {
right: ${-TdThHorizontalPadding}px;
}
${TagValueTd} > & {
width: auto;
&:after {
left: ${-TdThHorizontalPadding}px;
}
}
`;
const TagUndoChangedTh = styled.th`
min-width: ${UndoButtonMinWidth}px;
`;
const TagUndoChangedTd = styled(TagUndoChangedTh.withComponent('td'))`
text-align: right;
`;
export interface TagManagementModalProps<T> {
/** Selected items to tag */
items: T[];
/** Selected items type */
itemType: string;
/** Tag field title */
titleField: keyof T | ((item: T) => string);
/** Tags property in the selected item */
tagField: keyof T;
/** On cancel press event */
cancel: () => void;
/** On done press event */
done: (
tagSubmitInfo: SubmitInfo<ResourceTagSubmitInfo, ResourceTagSubmitInfo>,
) => void;
}
/**
* Displays a Modal to manage Tags.
*
* [View story source](https://github.com/balena-io-modules/rendition/blob/master/src/components/TagManagementModal/TagManagementModal.stories.tsx)
*
*
*
* Modal Strings:
*
* | `Name |` Description |
* |------|-------------|
* | `labels.tags` | Tags |
* | `labels.shared` | Shared |
* | `labels.tag_name` | Tag name |
* | `labels.value` | Value |
* | `labels.tag_value` | Tag value |
* | `actions.ok` | OK |
* | `actions.add_tag` | Add tag |
* | `actions.continue` | Continue |
* | `actions.undo_add` | Undo add |
* | `actions.undo_edit` | Undo edit |
* | `actions.undo_delete` | Undo delete |
* | `actions.apply_item_type_count` | Apply |
* | `actions.apply_item_type_count_plural` | Apply to {{count}} {{itemType}} |
* | `actions_messages.confirmation` | Are you sure? |
* | `actions_confirmations.confirm_to_proceed` | Do you want to proceed? |
* | `no_data.no_name_set` | No name set |
* | `warnings.this_would_overwrite_tags` | Adding this would overwrite tags on {{itemType}} |
* | `warnings.tag_name_group_exists_and_will_be_overwritten` | A tag name group exists on {{count}} other {{itemType}} and will be overwritten. |
* | `warnings.tag_name_group_exists_and_will_be_overwritten_plural` | A tag name group exists on {{count}} other {{itemType}}s and will be overwritten. |
* | `errors.no_tags_for_selected_itemtype` | The selected {{itemType}} has no tags |
* | `errors.no_tags_for_selected_itemtype_plural` | The selected {{itemType}}s have no tags in common |
* | `fields_errors.tag_name_cannot_be_empty` | The tag name can't be empty. |
* | `fields_errors.tag_names_cannot_contain_whitespace` | Tag names cannot contain whitespace |
* | `fields_errors.some_tag_keys_are_reserved` | Tag names beginning with {{namespace}} are reserved |
* | `fields_errors.tag_with_same_name_exists` | A tag with the same name already exists |
*/
export const TagManagementModal = <T extends TaggedResource>({
items,
itemType,
titleField,
tagField,
cancel,
done,
}: TagManagementModalProps<T>) => {
const { t } = useTranslation();
const [editingTag, setEditingTag] = React.useState<
ResourceTagInfo<T> | undefined
>(undefined);
const [tags, setTags] = React.useState<Array<ResourceTagInfo<T>>>();
const [partialTags, setPartialTags] =
React.useState<Array<ResourceTagInfo<T>>>();
const tagDiffs = React.useMemo(
() => getResourceTagSubmitInfo(tags || []),
[tags],
);
React.useEffect(() => {
const allTags = groupResourcesByTags(items, tagField);
const [commonTags, $partialTags] = partition(
allTags,
(t) => t.items.length === items.length,
);
setTags(commonTags);
setPartialTags($partialTags);
// TODO: This snapshots the item at the moment the modal is open.
// Consider using a separate state for editing tags.
}, [items.length > 0]);
if (!tags || !partialTags) {
return null;
}
const addTag = (tag: ResourceTagInfo<T>) => {
let slicedTags = tags.slice();
const existingDeletedTag = slicedTags.find(
(existingTag) =>
existingTag.state === 'deleted' && existingTag.tag_key === tag.tag_key,
);
if (existingDeletedTag) {
existingDeletedTag.initialValue = existingDeletedTag.value;
existingDeletedTag.value = tag.value;
existingDeletedTag.state = 'updated';
} else {
const newTag: ResourceTagInfo<T> = {
tag_key: tag.tag_key,
value: tag.value,
items: items.slice(),
state: 'added',
};
slicedTags.push(newTag);
slicedTags = sortBy(slicedTags, 'tag_key');
}
setEditingTag(undefined);
setTags(slicedTags);
};
const undoTagChanges = (tag: ResourceTagInfo<T>) => {
if (tag.state === 'added') {
setTags(tags.filter((t) => t !== tag));
return;
}
if (tag.state === 'updated') {
tag.value = tag.initialValue || '';
tag.state = undefined;
}
if (tag.state === 'deleted') {
tag.state = undefined;
}
setTags(tags.slice());
};
const startTagEdit = (tag: ResourceTagInfo<T>) => {
if (tag && tag.initialValue === undefined) {
tag.initialValue = tag.value || '';
}
setEditingTag(tag);
};
const endTagEdit = () => {
if (editingTag) {
const tagKey = editingTag.tag_key;
const newTags = tags.map((tag) =>
tag.tag_key === tagKey ? editingTag : tag,
);
setTags(newTags);
}
setEditingTag(undefined);
};
const setEditingTagValue = (value: string) => {
if (!editingTag) {
return;
}
const newTag = { ...editingTag };
newTag.value = value;
if (!newTag.state && newTag.initialValue !== value) {
newTag.state = 'updated';
}
setEditingTag(newTag);
};
const deleteTag = (tag: ResourceTagInfo<T>) => {
if (tag.state === 'added') {
setTags(tags.filter((t) => t !== tag));
return;
}
tag.state = 'deleted';
setTags(tags.slice());
};
const getItemTitle = (item: T) => {
const title =
typeof titleField === 'function'
? titleField(item)
: toString(item[titleField]);
return title || `(${t('no_data.no_name_set')})`;
};
return (
<Modal
width={1000}
titleElement={
<div>
<Heading.h3 mt={0} mb={10}>
{items.length > 1 && <span>{t('labels.shared')} </span>}
{t('labels.tags')}
</Heading.h3>
<CollectionSummary
items={items.map(getItemTitle).sort()}
itemsType={t('resource.' + itemType, { count: items.length })}
maxVisibleItemCount={10}
/>
</div>
}
cancel={cancel}
done={withPreventDefault(() => done(tagDiffs))}
action={t(`actions.apply_item_type_count`, {
count: items.length,
itemType: t('labels.' + itemType, {
count: items.length,
}).toLowerCase(),
})}
primaryButtonProps={{
disabled:
Object.values(tagDiffs).filter(
(changedTags) => changedTags.length > 0,
).length === 0
? true
: false,
}}
>
<Flex>
<TagTable>
<AddTagForm<T>
itemType={itemType}
existingTags={tags}
overwritableTags={partialTags}
addTag={addTag}
t={t}
/>
<thead>
<tr>
<TagDeleteTh />
<TagPropertyTh>
<InputPadder>{t('labels.tag_name')}</InputPadder>
</TagPropertyTh>
<TagPropertyTh>
<InputPadder>{t('labels.value')}</InputPadder>
</TagPropertyTh>
<TagUndoChangedTh />
</tr>
</thead>
<tbody>
{!tags.length ? (
<tr>
<td />
<td colSpan={3}>
<InputPadder>
{t(`errors.no_tags_for_selected_itemtype`, {
count: items.length,
itemType,
})}
</InputPadder>
</td>
</tr>
) : (
map(tags, (tag) => {
const showPreviousTagProperties =
editingTag?.tag_key !== tag.tag_key &&
(tag.state === 'deleted' || tag.state === 'updated');
return (
<TagTr key={tag.tag_key} {...tag}>
<TagDeleteTd>
{tag.state !== 'deleted' && (
<Flex alignItems="center">
<DeleteButtonIcon onClick={() => deleteTag(tag)} />
</Flex>
)}
</TagDeleteTd>
<TagKeyTd state={tag.state}>
{showPreviousTagProperties && (
<PreviousTagProperty state={tag.state}>
<InputPadder>{tag.tag_key}</InputPadder>
</PreviousTagProperty>
)}
{tag.state !== 'deleted' && (
<TagProperty state={tag.state}>
<InputPadder>{tag.tag_key}</InputPadder>
</TagProperty>
)}
</TagKeyTd>
<TagValueTd>
{showPreviousTagProperties && (
<PreviousTagProperty state={tag.state}>
<InputPadder>{tag.value || NBSP}</InputPadder>
</PreviousTagProperty>
)}
{editingTag?.tag_key !== tag.tag_key &&
tag.state !== 'deleted' && (
<EdittableTagValue
state={tag.state}
onClick={() => startTagEdit(tag)}
>
<InputPadder>
<EdittableTagValueText>
{tag.value || NBSP}
</EdittableTagValueText>
<EditButtonIcon />
</InputPadder>
</EdittableTagValue>
)}
{editingTag?.tag_key === tag.tag_key && (
<Input
width="100%"
autoFocus
onKeyDown={(e) => stopKeyDownEvent(e, 13, endTagEdit)}
onFocus={(e) => {
// move the cursor to the end
const target = e.target as HTMLInputElement;
const len = (target.value || '').length;
if (len) {
target.setSelectionRange(len, len);
}
}}
onChange={(e) => setEditingTagValue(e.target.value)}
onBlur={() => endTagEdit()}
value={editingTag.value}
placeholder={t('labels.tag_value')}
/>
)}
</TagValueTd>
<TagUndoChangedTd>
{tag.state && (
<Flex alignItems="center" justifyContent="flex-end">
<UndoButton
plain
primary
icon={<FontAwesomeIcon icon={faUndo} />}
onClick={() => undoTagChanges(tag)}
>
<span>
{tag.state === 'added'
? t('actions.undo_add')
: tag.state === 'updated'
? t('actions.undo_edit')
: t('actions.undo_delete')}
</span>
</UndoButton>
</Flex>
)}
</TagUndoChangedTd>
</TagTr>
);
})
)}
</tbody>
</TagTable>
</Flex>
</Modal>
);
}; | the_stack |
export const delimiter: string;
export const sep: string;
export function basename(...args: any[]): void;
export function dirname(...args: any[]): void;
export function extname(...args: any[]): void;
export function format(p0: any): any;
export function isAbsolute(...args: any[]): void;
export function join(...args: any[]): void;
export function normalize(...args: any[]): void;
export function parse(...args: any[]): void;
export function relative(...args: any[]): void;
export function resolve(...args: any[]): void;
export function toNamespacedPath(...args: any[]): void;
export namespace posix {
const delimiter: string;
const sep: string;
function basename(...args: any[]): void;
function dirname(...args: any[]): void;
function extname(...args: any[]): void;
function format(p0: any): any;
function isAbsolute(...args: any[]): void;
function join(...args: any[]): void;
function normalize(...args: any[]): void;
function parse(...args: any[]): void;
function relative(...args: any[]): void;
function resolve(...args: any[]): void;
function toNamespacedPath(...args: any[]): void;
namespace posix {
const delimiter: string;
const sep: string;
function basename(...args: any[]): void;
function dirname(...args: any[]): void;
function extname(...args: any[]): void;
function format(p0: any): any;
function isAbsolute(...args: any[]): void;
function join(...args: any[]): void;
function normalize(...args: any[]): void;
function parse(...args: any[]): void;
function relative(...args: any[]): void;
function resolve(...args: any[]): void;
function toNamespacedPath(...args: any[]): void;
namespace posix {
const delimiter: string;
const sep: string;
function basename(...args: any[]): void;
function dirname(...args: any[]): void;
function extname(...args: any[]): void;
function format(p0: any): any;
function isAbsolute(...args: any[]): void;
function join(...args: any[]): void;
function normalize(...args: any[]): void;
function parse(...args: any[]): void;
function relative(...args: any[]): void;
function resolve(...args: any[]): void;
function toNamespacedPath(...args: any[]): void;
namespace posix {
// Too-deep object hierarchy from path.posix.posix.posix.posix
const basename: any;
// Too-deep object hierarchy from path.posix.posix.posix.posix
const delimiter: any;
// Too-deep object hierarchy from path.posix.posix.posix.posix
const dirname: any;
// Too-deep object hierarchy from path.posix.posix.posix.posix
const extname: any;
// Too-deep object hierarchy from path.posix.posix.posix.posix
const format: any;
// Too-deep object hierarchy from path.posix.posix.posix.posix
const isAbsolute: any;
// Too-deep object hierarchy from path.posix.posix.posix.posix
const join: any;
// Too-deep object hierarchy from path.posix.posix.posix.posix
const normalize: any;
// Too-deep object hierarchy from path.posix.posix.posix.posix
const parse: any;
// Too-deep object hierarchy from path.posix.posix.posix.posix
const posix: any;
// Too-deep object hierarchy from path.posix.posix.posix.posix
const relative: any;
// Too-deep object hierarchy from path.posix.posix.posix.posix
const resolve: any;
// Too-deep object hierarchy from path.posix.posix.posix.posix
const sep: any;
// Too-deep object hierarchy from path.posix.posix.posix.posix
const toNamespacedPath: any;
// Too-deep object hierarchy from path.posix.posix.posix.posix
const win32: any;
}
namespace win32 {
// Too-deep object hierarchy from path.posix.posix.posix.win32
const basename: any;
// Too-deep object hierarchy from path.posix.posix.posix.win32
const delimiter: any;
// Too-deep object hierarchy from path.posix.posix.posix.win32
const dirname: any;
// Too-deep object hierarchy from path.posix.posix.posix.win32
const extname: any;
// Too-deep object hierarchy from path.posix.posix.posix.win32
const format: any;
// Too-deep object hierarchy from path.posix.posix.posix.win32
const isAbsolute: any;
// Too-deep object hierarchy from path.posix.posix.posix.win32
const join: any;
// Too-deep object hierarchy from path.posix.posix.posix.win32
const normalize: any;
// Too-deep object hierarchy from path.posix.posix.posix.win32
const parse: any;
// Too-deep object hierarchy from path.posix.posix.posix.win32
const posix: any;
// Too-deep object hierarchy from path.posix.posix.posix.win32
const relative: any;
// Too-deep object hierarchy from path.posix.posix.posix.win32
const resolve: any;
// Too-deep object hierarchy from path.posix.posix.posix.win32
const sep: any;
// Too-deep object hierarchy from path.posix.posix.posix.win32
const toNamespacedPath: any;
// Too-deep object hierarchy from path.posix.posix.posix.win32
const win32: any;
}
}
namespace win32 {
const delimiter: string;
const sep: string;
function basename(...args: any[]): void;
function dirname(...args: any[]): void;
function extname(...args: any[]): void;
function format(p0: any): any;
function isAbsolute(...args: any[]): void;
function join(...args: any[]): void;
function normalize(...args: any[]): void;
function parse(...args: any[]): void;
function relative(...args: any[]): void;
function resolve(...args: any[]): void;
function toNamespacedPath(...args: any[]): void;
namespace posix {
// Too-deep object hierarchy from path.posix.posix.win32.posix
const basename: any;
// Too-deep object hierarchy from path.posix.posix.win32.posix
const delimiter: any;
// Too-deep object hierarchy from path.posix.posix.win32.posix
const dirname: any;
// Too-deep object hierarchy from path.posix.posix.win32.posix
const extname: any;
// Too-deep object hierarchy from path.posix.posix.win32.posix
const format: any;
// Too-deep object hierarchy from path.posix.posix.win32.posix
const isAbsolute: any;
// Too-deep object hierarchy from path.posix.posix.win32.posix
const join: any;
// Too-deep object hierarchy from path.posix.posix.win32.posix
const normalize: any;
// Too-deep object hierarchy from path.posix.posix.win32.posix
const parse: any;
// Too-deep object hierarchy from path.posix.posix.win32.posix
const posix: any;
// Too-deep object hierarchy from path.posix.posix.win32.posix
const relative: any;
// Too-deep object hierarchy from path.posix.posix.win32.posix
const resolve: any;
// Too-deep object hierarchy from path.posix.posix.win32.posix
const sep: any;
// Too-deep object hierarchy from path.posix.posix.win32.posix
const toNamespacedPath: any;
// Too-deep object hierarchy from path.posix.posix.win32.posix
const win32: any;
}
namespace win32 {
// Too-deep object hierarchy from path.posix.posix.win32.win32
const basename: any;
// Too-deep object hierarchy from path.posix.posix.win32.win32
const delimiter: any;
// Too-deep object hierarchy from path.posix.posix.win32.win32
const dirname: any;
// Too-deep object hierarchy from path.posix.posix.win32.win32
const extname: any;
// Too-deep object hierarchy from path.posix.posix.win32.win32
const format: any;
// Too-deep object hierarchy from path.posix.posix.win32.win32
const isAbsolute: any;
// Too-deep object hierarchy from path.posix.posix.win32.win32
const join: any;
// Too-deep object hierarchy from path.posix.posix.win32.win32
const normalize: any;
// Too-deep object hierarchy from path.posix.posix.win32.win32
const parse: any;
// Too-deep object hierarchy from path.posix.posix.win32.win32
const posix: any;
// Too-deep object hierarchy from path.posix.posix.win32.win32
const relative: any;
// Too-deep object hierarchy from path.posix.posix.win32.win32
const resolve: any;
// Too-deep object hierarchy from path.posix.posix.win32.win32
const sep: any;
// Too-deep object hierarchy from path.posix.posix.win32.win32
const toNamespacedPath: any;
// Too-deep object hierarchy from path.posix.posix.win32.win32
const win32: any;
}
}
}
namespace win32 {
const delimiter: string;
const sep: string;
function basename(...args: any[]): void;
function dirname(...args: any[]): void;
function extname(...args: any[]): void;
function format(p0: any): any;
function isAbsolute(...args: any[]): void;
function join(...args: any[]): void;
function normalize(...args: any[]): void;
function parse(...args: any[]): void;
function relative(...args: any[]): void;
function resolve(...args: any[]): void;
function toNamespacedPath(...args: any[]): void;
namespace posix {
const delimiter: string;
const sep: string;
function basename(...args: any[]): void;
function dirname(...args: any[]): void;
function extname(...args: any[]): void;
function format(p0: any): any;
function isAbsolute(...args: any[]): void;
function join(...args: any[]): void;
function normalize(...args: any[]): void;
function parse(...args: any[]): void;
function relative(...args: any[]): void;
function resolve(...args: any[]): void;
function toNamespacedPath(...args: any[]): void;
namespace posix {
// Too-deep object hierarchy from path.posix.win32.posix.posix
const basename: any;
// Too-deep object hierarchy from path.posix.win32.posix.posix
const delimiter: any;
// Too-deep object hierarchy from path.posix.win32.posix.posix
const dirname: any;
// Too-deep object hierarchy from path.posix.win32.posix.posix
const extname: any;
// Too-deep object hierarchy from path.posix.win32.posix.posix
const format: any;
// Too-deep object hierarchy from path.posix.win32.posix.posix
const isAbsolute: any;
// Too-deep object hierarchy from path.posix.win32.posix.posix
const join: any;
// Too-deep object hierarchy from path.posix.win32.posix.posix
const normalize: any;
// Too-deep object hierarchy from path.posix.win32.posix.posix
const parse: any;
// Too-deep object hierarchy from path.posix.win32.posix.posix
const posix: any;
// Too-deep object hierarchy from path.posix.win32.posix.posix
const relative: any;
// Too-deep object hierarchy from path.posix.win32.posix.posix
const resolve: any;
// Too-deep object hierarchy from path.posix.win32.posix.posix
const sep: any;
// Too-deep object hierarchy from path.posix.win32.posix.posix
const toNamespacedPath: any;
// Too-deep object hierarchy from path.posix.win32.posix.posix
const win32: any;
}
namespace win32 {
// Too-deep object hierarchy from path.posix.win32.posix.win32
const basename: any;
// Too-deep object hierarchy from path.posix.win32.posix.win32
const delimiter: any;
// Too-deep object hierarchy from path.posix.win32.posix.win32
const dirname: any;
// Too-deep object hierarchy from path.posix.win32.posix.win32
const extname: any;
// Too-deep object hierarchy from path.posix.win32.posix.win32
const format: any;
// Too-deep object hierarchy from path.posix.win32.posix.win32
const isAbsolute: any;
// Too-deep object hierarchy from path.posix.win32.posix.win32
const join: any;
// Too-deep object hierarchy from path.posix.win32.posix.win32
const normalize: any;
// Too-deep object hierarchy from path.posix.win32.posix.win32
const parse: any;
// Too-deep object hierarchy from path.posix.win32.posix.win32
const posix: any;
// Too-deep object hierarchy from path.posix.win32.posix.win32
const relative: any;
// Too-deep object hierarchy from path.posix.win32.posix.win32
const resolve: any;
// Too-deep object hierarchy from path.posix.win32.posix.win32
const sep: any;
// Too-deep object hierarchy from path.posix.win32.posix.win32
const toNamespacedPath: any;
// Too-deep object hierarchy from path.posix.win32.posix.win32
const win32: any;
}
}
namespace win32 {
const delimiter: string;
const sep: string;
function basename(...args: any[]): void;
function dirname(...args: any[]): void;
function extname(...args: any[]): void;
function format(p0: any): any;
function isAbsolute(...args: any[]): void;
function join(...args: any[]): void;
function normalize(...args: any[]): void;
function parse(...args: any[]): void;
function relative(...args: any[]): void;
function resolve(...args: any[]): void;
function toNamespacedPath(...args: any[]): void;
namespace posix {
// Too-deep object hierarchy from path.posix.win32.win32.posix
const basename: any;
// Too-deep object hierarchy from path.posix.win32.win32.posix
const delimiter: any;
// Too-deep object hierarchy from path.posix.win32.win32.posix
const dirname: any;
// Too-deep object hierarchy from path.posix.win32.win32.posix
const extname: any;
// Too-deep object hierarchy from path.posix.win32.win32.posix
const format: any;
// Too-deep object hierarchy from path.posix.win32.win32.posix
const isAbsolute: any;
// Too-deep object hierarchy from path.posix.win32.win32.posix
const join: any;
// Too-deep object hierarchy from path.posix.win32.win32.posix
const normalize: any;
// Too-deep object hierarchy from path.posix.win32.win32.posix
const parse: any;
// Too-deep object hierarchy from path.posix.win32.win32.posix
const posix: any;
// Too-deep object hierarchy from path.posix.win32.win32.posix
const relative: any;
// Too-deep object hierarchy from path.posix.win32.win32.posix
const resolve: any;
// Too-deep object hierarchy from path.posix.win32.win32.posix
const sep: any;
// Too-deep object hierarchy from path.posix.win32.win32.posix
const toNamespacedPath: any;
// Too-deep object hierarchy from path.posix.win32.win32.posix
const win32: any;
}
namespace win32 {
// Too-deep object hierarchy from path.posix.win32.win32.win32
const basename: any;
// Too-deep object hierarchy from path.posix.win32.win32.win32
const delimiter: any;
// Too-deep object hierarchy from path.posix.win32.win32.win32
const dirname: any;
// Too-deep object hierarchy from path.posix.win32.win32.win32
const extname: any;
// Too-deep object hierarchy from path.posix.win32.win32.win32
const format: any;
// Too-deep object hierarchy from path.posix.win32.win32.win32
const isAbsolute: any;
// Too-deep object hierarchy from path.posix.win32.win32.win32
const join: any;
// Too-deep object hierarchy from path.posix.win32.win32.win32
const normalize: any;
// Too-deep object hierarchy from path.posix.win32.win32.win32
const parse: any;
// Too-deep object hierarchy from path.posix.win32.win32.win32
const posix: any;
// Too-deep object hierarchy from path.posix.win32.win32.win32
const relative: any;
// Too-deep object hierarchy from path.posix.win32.win32.win32
const resolve: any;
// Too-deep object hierarchy from path.posix.win32.win32.win32
const sep: any;
// Too-deep object hierarchy from path.posix.win32.win32.win32
const toNamespacedPath: any;
// Too-deep object hierarchy from path.posix.win32.win32.win32
const win32: any;
}
}
}
}
export namespace win32 {
const delimiter: string;
const sep: string;
function basename(...args: any[]): void;
function dirname(...args: any[]): void;
function extname(...args: any[]): void;
function format(p0: any): any;
function isAbsolute(...args: any[]): void;
function join(...args: any[]): void;
function normalize(...args: any[]): void;
function parse(...args: any[]): void;
function relative(...args: any[]): void;
function resolve(...args: any[]): void;
function toNamespacedPath(...args: any[]): void;
namespace posix {
const delimiter: string;
const sep: string;
function basename(...args: any[]): void;
function dirname(...args: any[]): void;
function extname(...args: any[]): void;
function format(p0: any): any;
function isAbsolute(...args: any[]): void;
function join(...args: any[]): void;
function normalize(...args: any[]): void;
function parse(...args: any[]): void;
function relative(...args: any[]): void;
function resolve(...args: any[]): void;
function toNamespacedPath(...args: any[]): void;
namespace posix {
const delimiter: string;
const sep: string;
function basename(...args: any[]): void;
function dirname(...args: any[]): void;
function extname(...args: any[]): void;
function format(p0: any): any;
function isAbsolute(...args: any[]): void;
function join(...args: any[]): void;
function normalize(...args: any[]): void;
function parse(...args: any[]): void;
function relative(...args: any[]): void;
function resolve(...args: any[]): void;
function toNamespacedPath(...args: any[]): void;
namespace posix {
// Too-deep object hierarchy from path.win32.posix.posix.posix
const basename: any;
// Too-deep object hierarchy from path.win32.posix.posix.posix
const delimiter: any;
// Too-deep object hierarchy from path.win32.posix.posix.posix
const dirname: any;
// Too-deep object hierarchy from path.win32.posix.posix.posix
const extname: any;
// Too-deep object hierarchy from path.win32.posix.posix.posix
const format: any;
// Too-deep object hierarchy from path.win32.posix.posix.posix
const isAbsolute: any;
// Too-deep object hierarchy from path.win32.posix.posix.posix
const join: any;
// Too-deep object hierarchy from path.win32.posix.posix.posix
const normalize: any;
// Too-deep object hierarchy from path.win32.posix.posix.posix
const parse: any;
// Too-deep object hierarchy from path.win32.posix.posix.posix
const posix: any;
// Too-deep object hierarchy from path.win32.posix.posix.posix
const relative: any;
// Too-deep object hierarchy from path.win32.posix.posix.posix
const resolve: any;
// Too-deep object hierarchy from path.win32.posix.posix.posix
const sep: any;
// Too-deep object hierarchy from path.win32.posix.posix.posix
const toNamespacedPath: any;
// Too-deep object hierarchy from path.win32.posix.posix.posix
const win32: any;
}
namespace win32 {
// Too-deep object hierarchy from path.win32.posix.posix.win32
const basename: any;
// Too-deep object hierarchy from path.win32.posix.posix.win32
const delimiter: any;
// Too-deep object hierarchy from path.win32.posix.posix.win32
const dirname: any;
// Too-deep object hierarchy from path.win32.posix.posix.win32
const extname: any;
// Too-deep object hierarchy from path.win32.posix.posix.win32
const format: any;
// Too-deep object hierarchy from path.win32.posix.posix.win32
const isAbsolute: any;
// Too-deep object hierarchy from path.win32.posix.posix.win32
const join: any;
// Too-deep object hierarchy from path.win32.posix.posix.win32
const normalize: any;
// Too-deep object hierarchy from path.win32.posix.posix.win32
const parse: any;
// Too-deep object hierarchy from path.win32.posix.posix.win32
const posix: any;
// Too-deep object hierarchy from path.win32.posix.posix.win32
const relative: any;
// Too-deep object hierarchy from path.win32.posix.posix.win32
const resolve: any;
// Too-deep object hierarchy from path.win32.posix.posix.win32
const sep: any;
// Too-deep object hierarchy from path.win32.posix.posix.win32
const toNamespacedPath: any;
// Too-deep object hierarchy from path.win32.posix.posix.win32
const win32: any;
}
}
namespace win32 {
const delimiter: string;
const sep: string;
function basename(...args: any[]): void;
function dirname(...args: any[]): void;
function extname(...args: any[]): void;
function format(p0: any): any;
function isAbsolute(...args: any[]): void;
function join(...args: any[]): void;
function normalize(...args: any[]): void;
function parse(...args: any[]): void;
function relative(...args: any[]): void;
function resolve(...args: any[]): void;
function toNamespacedPath(...args: any[]): void;
namespace posix {
// Too-deep object hierarchy from path.win32.posix.win32.posix
const basename: any;
// Too-deep object hierarchy from path.win32.posix.win32.posix
const delimiter: any;
// Too-deep object hierarchy from path.win32.posix.win32.posix
const dirname: any;
// Too-deep object hierarchy from path.win32.posix.win32.posix
const extname: any;
// Too-deep object hierarchy from path.win32.posix.win32.posix
const format: any;
// Too-deep object hierarchy from path.win32.posix.win32.posix
const isAbsolute: any;
// Too-deep object hierarchy from path.win32.posix.win32.posix
const join: any;
// Too-deep object hierarchy from path.win32.posix.win32.posix
const normalize: any;
// Too-deep object hierarchy from path.win32.posix.win32.posix
const parse: any;
// Too-deep object hierarchy from path.win32.posix.win32.posix
const posix: any;
// Too-deep object hierarchy from path.win32.posix.win32.posix
const relative: any;
// Too-deep object hierarchy from path.win32.posix.win32.posix
const resolve: any;
// Too-deep object hierarchy from path.win32.posix.win32.posix
const sep: any;
// Too-deep object hierarchy from path.win32.posix.win32.posix
const toNamespacedPath: any;
// Too-deep object hierarchy from path.win32.posix.win32.posix
const win32: any;
}
namespace win32 {
// Too-deep object hierarchy from path.win32.posix.win32.win32
const basename: any;
// Too-deep object hierarchy from path.win32.posix.win32.win32
const delimiter: any;
// Too-deep object hierarchy from path.win32.posix.win32.win32
const dirname: any;
// Too-deep object hierarchy from path.win32.posix.win32.win32
const extname: any;
// Too-deep object hierarchy from path.win32.posix.win32.win32
const format: any;
// Too-deep object hierarchy from path.win32.posix.win32.win32
const isAbsolute: any;
// Too-deep object hierarchy from path.win32.posix.win32.win32
const join: any;
// Too-deep object hierarchy from path.win32.posix.win32.win32
const normalize: any;
// Too-deep object hierarchy from path.win32.posix.win32.win32
const parse: any;
// Too-deep object hierarchy from path.win32.posix.win32.win32
const posix: any;
// Too-deep object hierarchy from path.win32.posix.win32.win32
const relative: any;
// Too-deep object hierarchy from path.win32.posix.win32.win32
const resolve: any;
// Too-deep object hierarchy from path.win32.posix.win32.win32
const sep: any;
// Too-deep object hierarchy from path.win32.posix.win32.win32
const toNamespacedPath: any;
// Too-deep object hierarchy from path.win32.posix.win32.win32
const win32: any;
}
}
}
namespace win32 {
const delimiter: string;
const sep: string;
function basename(...args: any[]): void;
function dirname(...args: any[]): void;
function extname(...args: any[]): void;
function format(p0: any): any;
function isAbsolute(...args: any[]): void;
function join(...args: any[]): void;
function normalize(...args: any[]): void;
function parse(...args: any[]): void;
function relative(...args: any[]): void;
function resolve(...args: any[]): void;
function toNamespacedPath(...args: any[]): void;
namespace posix {
const delimiter: string;
const sep: string;
function basename(...args: any[]): void;
function dirname(...args: any[]): void;
function extname(...args: any[]): void;
function format(p0: any): any;
function isAbsolute(...args: any[]): void;
function join(...args: any[]): void;
function normalize(...args: any[]): void;
function parse(...args: any[]): void;
function relative(...args: any[]): void;
function resolve(...args: any[]): void;
function toNamespacedPath(...args: any[]): void;
namespace posix {
// Too-deep object hierarchy from path.win32.win32.posix.posix
const basename: any;
// Too-deep object hierarchy from path.win32.win32.posix.posix
const delimiter: any;
// Too-deep object hierarchy from path.win32.win32.posix.posix
const dirname: any;
// Too-deep object hierarchy from path.win32.win32.posix.posix
const extname: any;
// Too-deep object hierarchy from path.win32.win32.posix.posix
const format: any;
// Too-deep object hierarchy from path.win32.win32.posix.posix
const isAbsolute: any;
// Too-deep object hierarchy from path.win32.win32.posix.posix
const join: any;
// Too-deep object hierarchy from path.win32.win32.posix.posix
const normalize: any;
// Too-deep object hierarchy from path.win32.win32.posix.posix
const parse: any;
// Too-deep object hierarchy from path.win32.win32.posix.posix
const posix: any;
// Too-deep object hierarchy from path.win32.win32.posix.posix
const relative: any;
// Too-deep object hierarchy from path.win32.win32.posix.posix
const resolve: any;
// Too-deep object hierarchy from path.win32.win32.posix.posix
const sep: any;
// Too-deep object hierarchy from path.win32.win32.posix.posix
const toNamespacedPath: any;
// Too-deep object hierarchy from path.win32.win32.posix.posix
const win32: any;
}
namespace win32 {
// Too-deep object hierarchy from path.win32.win32.posix.win32
const basename: any;
// Too-deep object hierarchy from path.win32.win32.posix.win32
const delimiter: any;
// Too-deep object hierarchy from path.win32.win32.posix.win32
const dirname: any;
// Too-deep object hierarchy from path.win32.win32.posix.win32
const extname: any;
// Too-deep object hierarchy from path.win32.win32.posix.win32
const format: any;
// Too-deep object hierarchy from path.win32.win32.posix.win32
const isAbsolute: any;
// Too-deep object hierarchy from path.win32.win32.posix.win32
const join: any;
// Too-deep object hierarchy from path.win32.win32.posix.win32
const normalize: any;
// Too-deep object hierarchy from path.win32.win32.posix.win32
const parse: any;
// Too-deep object hierarchy from path.win32.win32.posix.win32
const posix: any;
// Too-deep object hierarchy from path.win32.win32.posix.win32
const relative: any;
// Too-deep object hierarchy from path.win32.win32.posix.win32
const resolve: any;
// Too-deep object hierarchy from path.win32.win32.posix.win32
const sep: any;
// Too-deep object hierarchy from path.win32.win32.posix.win32
const toNamespacedPath: any;
// Too-deep object hierarchy from path.win32.win32.posix.win32
const win32: any;
}
}
namespace win32 {
const delimiter: string;
const sep: string;
function basename(...args: any[]): void;
function dirname(...args: any[]): void;
function extname(...args: any[]): void;
function format(p0: any): any;
function isAbsolute(...args: any[]): void;
function join(...args: any[]): void;
function normalize(...args: any[]): void;
function parse(...args: any[]): void;
function relative(...args: any[]): void;
function resolve(...args: any[]): void;
function toNamespacedPath(...args: any[]): void;
namespace posix {
// Too-deep object hierarchy from path.win32.win32.win32.posix
const basename: any;
// Too-deep object hierarchy from path.win32.win32.win32.posix
const delimiter: any;
// Too-deep object hierarchy from path.win32.win32.win32.posix
const dirname: any;
// Too-deep object hierarchy from path.win32.win32.win32.posix
const extname: any;
// Too-deep object hierarchy from path.win32.win32.win32.posix
const format: any;
// Too-deep object hierarchy from path.win32.win32.win32.posix
const isAbsolute: any;
// Too-deep object hierarchy from path.win32.win32.win32.posix
const join: any;
// Too-deep object hierarchy from path.win32.win32.win32.posix
const normalize: any;
// Too-deep object hierarchy from path.win32.win32.win32.posix
const parse: any;
// Too-deep object hierarchy from path.win32.win32.win32.posix
const posix: any;
// Too-deep object hierarchy from path.win32.win32.win32.posix
const relative: any;
// Too-deep object hierarchy from path.win32.win32.win32.posix
const resolve: any;
// Too-deep object hierarchy from path.win32.win32.win32.posix
const sep: any;
// Too-deep object hierarchy from path.win32.win32.win32.posix
const toNamespacedPath: any;
// Too-deep object hierarchy from path.win32.win32.win32.posix
const win32: any;
}
namespace win32 {
// Too-deep object hierarchy from path.win32.win32.win32.win32
const basename: any;
// Too-deep object hierarchy from path.win32.win32.win32.win32
const delimiter: any;
// Too-deep object hierarchy from path.win32.win32.win32.win32
const dirname: any;
// Too-deep object hierarchy from path.win32.win32.win32.win32
const extname: any;
// Too-deep object hierarchy from path.win32.win32.win32.win32
const format: any;
// Too-deep object hierarchy from path.win32.win32.win32.win32
const isAbsolute: any;
// Too-deep object hierarchy from path.win32.win32.win32.win32
const join: any;
// Too-deep object hierarchy from path.win32.win32.win32.win32
const normalize: any;
// Too-deep object hierarchy from path.win32.win32.win32.win32
const parse: any;
// Too-deep object hierarchy from path.win32.win32.win32.win32
const posix: any;
// Too-deep object hierarchy from path.win32.win32.win32.win32
const relative: any;
// Too-deep object hierarchy from path.win32.win32.win32.win32
const resolve: any;
// Too-deep object hierarchy from path.win32.win32.win32.win32
const sep: any;
// Too-deep object hierarchy from path.win32.win32.win32.win32
const toNamespacedPath: any;
// Too-deep object hierarchy from path.win32.win32.win32.win32
const win32: any;
}
}
}
} | the_stack |
export interface HmsPushResultCodeInterface {
// Success
SUCCESS: '0';
// Error
ERROR: '-1';
// Bundle is null; exception
NULL_BUNDLE: '333';
// You do not have a token. Apply for a token.
ERROR_NO_TOKEN: '907122030';
// The current network is unavailable. Check the network connection.
ERROR_NO_NETWORK: '907122031';
// The token has expired. Delete the token and apply for a new one.
ERROR_TOKEN_INVALID: '907122032';
// If the Push service is unavailable; contact Huawei technical support.
ERROR_SERVICE_NOT_AVAILABLE: '907122046';
// If the Push server returns an error; contact Huawei technical support.
ERROR_PUSH_SERVER: '907122047';
// Unknown error. Contact Huawei technical support.
ERROR_UNKNOWN: '907122045';
// The number of subscribed topics exceeds 2000.
ERROR_TOPIC_EXCEED: '907122034';
// Failed to send the subscription topic. Contact Huawei technical support.
ERROR_TOPIC_SEND: '907122035';
// Push rights are not enabled. Enable the service and set push service parameters at AppGallery Connect.
ERROR_NO_RIGHT: '907122036';
// Failed to apply for the token. Contact Huawei technical support.
ERROR_GET_TOKEN_ERR: '907122037';
// No storage location is selected for the application or the storage location is invalid.
ERROR_STORAGE_LOCATION_EMPTY: '907122038';
// Failed to apply for a token. Cross-region token application is not allowed.
ERROR_NOT_ALLOW_CROSS_APPLY: '907122053';
// The message body size exceeds the maximum.
ERROR_SIZE: '907122041';
// The message contains invalid parameters.
ERROR_INVALID_PARAMETERS: '907122042';
// The number of sent messages reaches the upper limit. The messages will be discarded.
ERROR_TOO_MANY_MESSAGES: '907122043';
// The message lifetime expires before the message is successfully sent to the APP server.
ERROR_TTL_EXCEEDED: '907122044';
// Huawei Mobile Services (APK) can't connect Huawei Push Kit.
ERROR_HMS_CLIENT_API: '907122048';
// The current EMUI version is too early to use the capability.
ERROR_OPERATION_NOT_SUPPORTED: '907122049';
// The operation cannot be performed in the main thread.
ERROR_MAIN_THREAD: '907122050';
// The device certificate authentication fails.
ERROR_HMS_DEVICE_AUTH_FAILED_SELF_MAPPING: '907122051';
// Failed to bind the service.
ERROR_BIND_SERVICE_SELF_MAPPING: '907122052';
// The SDK is being automatically initialized. Try again later.
ERROR_AUTO_INITIALIZING: '907122054';
/*The input parameter is incorrect. Check whether the related configuration information is correct.
* Example =app_id in the agconnect - services.json file;
* Check whether the build.gradle file is configured with the certificate signature.
*/
ERROR_ARGUMENTS_INVALID: '907135000';
// Internal Push error. Contact Huawei technical support engineers.
ERROR_INTERNAL_ERROR: '907135001';
// The service does not exist. The invoked interface does not exist.
ERROR_NAMING_INVALID: '907135002';
// The ApiClient object is invalid.
ERROR_CLIENT_API_INVALID: '907135003';
// Invoking AIDL times out. Contact Huawei technical support.
ERROR_EXECUTE_TIMEOUT: '907135004';
// The current area does not support this service.
ERROR_NOT_IN_SERVICE: '907135005';
// If the AIDL connection session is invalid; contact Huawei technical support.
ERROR_SESSION_INVALID: '907135006';
// An error occurred when invoking an unspecified API.
ERROR_API_NOT_SPECIFIED: '1002';
/* Failed to invoke the gateway to query the application scope.
* Check whether the current app has been created and enabled in AppGallery Connect.
* If yes; contact Huawei technical support.
*/
ERROR_GET_SCOPE_ERROR: '907135700';
/* Scope is not configured on the AppGallery Connect.
* Check whether the current app has been created and enabled in AppGallery Connect.
* If yes; contact Huawei technical support.
*/
ERROR_SCOPE_LIST_EMPTY: '907135701';
/* The certificate fingerprint is not configured on the AppGallery Connect.
* 1. Check whether your phone can access the Internet.
* 2. Check whether the correct certificate fingerprint is configured in AppGallery Connect. For details; see AppGallery Connect configuration in Development Preparations.
* 3. If the check result is correct; contact Huawei technical support.
*/
ERROR_CERT_FINGERPRINT_EMPTY: '907135702';
// Permission is not configured on the AppGallery Connect.
ERROR_PERMISSION_LIST_EMPTY: '907135703';
// The authentication information of the application does not exist.
ERROR_AUTH_INFO_NOT_EXIST: '6002';
// An error occurred during certificate fingerprint verification.
// Check whether the correct certificate fingerprint is configured in AppGallery Connect. For details; see AppGallery Connect configuration in Development Preparations.
ERROR_CERT_FINGERPRINT_ERROR: '6003';
// Interface authentication =The permission does not exist and is not applied for in AppGallery Connect.
ERROR_PERMISSION_NOT_EXIST: '6004';
// Interface authentication =unauthorized.
ERROR_PERMISSION_NOT_AUTHORIZED: '6005';
// Interface authentication =The authorization expires.
ERROR_PERMISSION_EXPIRED: '6006';
}
export enum HmsPushResultCodeEnum {
// Success
SUCCESS = '0',
// Error
ERROR = '-1',
// Bundle is null, exception
NULL_BUNDLE = '333',
// You do not have a token. Apply for a token.
ERROR_NO_TOKEN = '907122030',
// The current network is unavailable. Check the network connection.
ERROR_NO_NETWORK = '907122031',
// The token has expired. Delete the token and apply for a new one.
ERROR_TOKEN_INVALID = '907122032',
// If the Push service is unavailable, contact Huawei technical support.
ERROR_SERVICE_NOT_AVAILABLE = '907122046',
// If the Push server returns an error, contact Huawei technical support.
ERROR_PUSH_SERVER = '907122047',
// Unknown error. Contact Huawei technical support.
ERROR_UNKNOWN = '907122045',
// The number of subscribed topics exceeds 2000.
ERROR_TOPIC_EXCEED = '907122034',
// Failed to send the subscription topic. Contact Huawei technical support.
ERROR_TOPIC_SEND = '907122035',
// Push rights are not enabled. Enable the service and set push service parameters at AppGallery Connect.
ERROR_NO_RIGHT = '907122036',
// Failed to apply for the token. Contact Huawei technical support.
ERROR_GET_TOKEN_ERR = '907122037',
// No storage location is selected for the application or the storage location is invalid.
ERROR_STORAGE_LOCATION_EMPTY = '907122038',
// Failed to apply for a token. Cross-region token application is not allowed.
ERROR_NOT_ALLOW_CROSS_APPLY = '907122053',
// The message body size exceeds the maximum.
ERROR_SIZE = '907122041',
// The message contains invalid parameters.
ERROR_INVALID_PARAMETERS = '907122042',
// The number of sent messages reaches the upper limit. The messages will be discarded.
ERROR_TOO_MANY_MESSAGES = '907122043',
// The message lifetime expires before the message is successfully sent to the APP server.
ERROR_TTL_EXCEEDED = '907122044',
// Huawei Mobile Services (APK) can't connect Huawei Push Kit.
ERROR_HMS_CLIENT_API = '907122048',
// The current EMUI version is too early to use the capability.
ERROR_OPERATION_NOT_SUPPORTED = '907122049',
// The operation cannot be performed in the main thread.
ERROR_MAIN_THREAD = '907122050',
// The device certificate authentication fails.
ERROR_HMS_DEVICE_AUTH_FAILED_SELF_MAPPING = '907122051',
// Failed to bind the service.
ERROR_BIND_SERVICE_SELF_MAPPING = '907122052',
// The SDK is being automatically initialized. Try again later.
ERROR_AUTO_INITIALIZING = '907122054',
/*The input parameter is incorrect. Check whether the related configuration information is correct.
* Example =app_id in the agconnect - services.json file,
* Check whether the build.gradle file is configured with the certificate signature.
*/
ERROR_ARGUMENTS_INVALID = '907135000',
// Internal Push error. Contact Huawei technical support engineers.
ERROR_INTERNAL_ERROR = '907135001',
// The service does not exist. The invoked interface does not exist.
ERROR_NAMING_INVALID = '907135002',
// The ApiClient object is invalid.
ERROR_CLIENT_API_INVALID = '907135003',
// Invoking AIDL times out. Contact Huawei technical support.
ERROR_EXECUTE_TIMEOUT = '907135004',
// The current area does not support this service.
ERROR_NOT_IN_SERVICE = '907135005',
// If the AIDL connection session is invalid, contact Huawei technical support.
ERROR_SESSION_INVALID = '907135006',
// An error occurred when invoking an unspecified API.
ERROR_API_NOT_SPECIFIED = '1002',
/* Failed to invoke the gateway to query the application scope.
* Check whether the current app has been created and enabled in AppGallery Connect.
* If yes, contact Huawei technical support.
*/
ERROR_GET_SCOPE_ERROR = '907135700',
/* Scope is not configured on the AppGallery Connect.
* Check whether the current app has been created and enabled in AppGallery Connect.
* If yes, contact Huawei technical support.
*/
ERROR_SCOPE_LIST_EMPTY = '907135701',
/* The certificate fingerprint is not configured on the AppGallery Connect.
* 1. Check whether your phone can access the Internet.
* 2. Check whether the correct certificate fingerprint is configured in AppGallery Connect. For details, see AppGallery Connect configuration in Development Preparations.
* 3. If the check result is correct, contact Huawei technical support.
*/
ERROR_CERT_FINGERPRINT_EMPTY = '907135702',
// Permission is not configured on the AppGallery Connect.
ERROR_PERMISSION_LIST_EMPTY = '907135703',
// The authentication information of the application does not exist.
ERROR_AUTH_INFO_NOT_EXIST = '6002',
// An error occurred during certificate fingerprint verification.
// Check whether the correct certificate fingerprint is configured in AppGallery Connect. For details, see AppGallery Connect configuration in Development Preparations.
ERROR_CERT_FINGERPRINT_ERROR = '6003',
// Interface authentication =The permission does not exist and is not applied for in AppGallery Connect.
ERROR_PERMISSION_NOT_EXIST = '6004',
// Interface authentication =unauthorized.
ERROR_PERMISSION_NOT_AUTHORIZED = '6005',
// Interface authentication =The authorization expires.
ERROR_PERMISSION_EXPIRED = '6006',
} | the_stack |
import type {
CellAddress,
CellRange,
MaybeCall,
MaybePromise,
} from "../ts-types";
const isNode =
typeof window === "undefined" || typeof window.window === "undefined";
type ArrayElementPredicate<E> = (t: E, i: number, arr: E[]) => boolean;
// type ObjectElementPredicate<T, K extends keyof T> = (
// t: T[K],
// key?: K,
// obj?: T
// ) => boolean;
type ArrayElementFunction<E> = (t: E, i: number, arr: E[]) => void;
type ObjectElementFunction<T, K extends keyof T> = (
t: T[K],
key: K,
obj: T
) => void;
let arrayFind: <T>(
arr: T[],
predicate: ArrayElementPredicate<T>
) => T | undefined;
let arrayFindIndex: <T>(
arr: T[],
predicate: ArrayElementPredicate<T>
) => number;
const array = {
get find(): typeof arrayFind {
if (arrayFind) {
return arrayFind;
}
if (Array.prototype.find) {
arrayFind = <T>(
arr: T[],
predicate: ArrayElementPredicate<T>
): T | undefined => Array.prototype.find.call(arr, predicate);
} else {
arrayFind = <T>(
arr: T[],
predicate: ArrayElementPredicate<T>
): T | undefined => {
const index = array.findIndex(arr, predicate);
return index >= 0 ? arr[index] : undefined;
};
}
return arrayFind;
},
get findIndex(): typeof arrayFindIndex {
if (arrayFindIndex) {
return arrayFindIndex;
}
if (Array.prototype.findIndex) {
arrayFindIndex = <T>(
arr: T[],
predicate: ArrayElementPredicate<T>
): number => Array.prototype.findIndex.call(arr, predicate);
} else {
arrayFindIndex = <T>(
arr: T[],
predicate: ArrayElementPredicate<T>
): number => {
const { length } = arr;
for (let i = 0; i < length; i++) {
const value = arr[i];
if (predicate(value, i, arr)) {
return i;
}
}
return -1;
};
}
return arrayFindIndex;
},
};
function analyzeUserAgent(): {
IE: boolean;
Edge: boolean;
Chrome: boolean;
Firefox: boolean;
Safari: boolean;
} {
if (isNode) {
return {
IE: false,
Edge: false,
Chrome: false,
Firefox: false,
Safari: false,
};
} else {
const ua = window.navigator.userAgent.toLowerCase();
return {
IE: !!/(msie|trident)/.exec(ua),
Edge: ua.indexOf("edge") > -1,
Chrome: ua.indexOf("chrome") > -1 && ua.indexOf("edge") === -1,
Firefox: ua.indexOf("firefox") > -1,
Safari: ua.indexOf("safari") > -1 && ua.indexOf("edge") === -1,
};
}
}
const { IE, Chrome, Firefox, Edge, Safari } = analyzeUserAgent();
function setReadonly<T, K extends keyof T>(obj: T, name: K, value: T[K]): void {
Object.defineProperty(obj, name, {
enumerable: false,
configurable: true,
value,
});
}
export function each<E>(obj: E[], fn: ArrayElementFunction<E>): void;
export function each<T, K extends keyof T>(
obj: T,
fn: ObjectElementFunction<T, K>
): void;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function each(obj: any, fn: any): void {
for (const key in obj) {
fn(obj[key], key, obj);
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function isObject(obj: any): obj is Record<string, any> {
return obj === Object(obj);
}
export function omit<T, K extends keyof T>(source: T, omits: K[]): Omit<T, K> {
const result = {} as Omit<T, K>;
for (const key in source) {
if (omits.indexOf(key as never) >= 0) {
continue;
}
Object.defineProperty(result, key, {
get() {
return source[key];
},
set(val) {
source[key] = val;
},
configurable: true,
enumerable: true,
});
}
return result;
}
export function defaults<T>(source: T, defs: Partial<T>): T {
const keys: string[] = [];
const result = {} as T;
for (const key in source) {
keys.push(key);
Object.defineProperty(result, key, {
get() {
const val = source[key];
return val === undefined ? defs[key] : val;
},
set(val) {
source[key] = val;
},
configurable: true,
enumerable: true,
});
}
for (const key in defs) {
if (keys.indexOf(key) >= 0) {
continue;
}
Object.defineProperty(result, key, {
get() {
const val = source[key];
return val === undefined ? defs[key] : val;
},
set(val) {
source[key] = val;
},
configurable: true,
enumerable: true,
});
}
return result;
}
export function extend<T, U>(t: T, u: U): T & U;
export function extend<T, U, V>(t: T, u: U, v: V): T & U & V;
export function extend<T>(...args: T[]): T;
export function extend<T>(...args: T[]): T {
const result = {} as T;
args.forEach((source) => {
for (const key in source) {
Object.defineProperty(result, key, {
get() {
return source[key];
},
set(val) {
source[key] = val;
},
configurable: true,
enumerable: true,
});
}
});
return result;
}
function isDescendantElement(root: HTMLElement, target: HTMLElement): boolean {
while (target.parentElement) {
const p = target.parentElement;
if (root === p) {
return true;
}
target = p;
}
return false;
}
/* eslint-disable @typescript-eslint/no-explicit-any */
function applyChainSafe(
obj: any,
fn: (value: any, name: string) => any,
...names: string[]
): any {
let value = obj;
for (let i = 0; i < names.length && value != null; i++) {
value = fn(value, names[i]);
}
return value;
}
function getChainSafe(obj: any, ...names: string[]): any {
return applyChainSafe(obj, (val, name) => val[name], ...names);
}
function getOrApply<_T, A extends any[]>(
value: undefined,
...args: A
): undefined;
function getOrApply<_T, A extends any[]>(value: null, ...args: A): null;
function getOrApply<T, A extends any[]>(value: MaybeCall<T, A>, ...args: A): T;
function getOrApply<T, A extends any[]>(value: MaybeCall<T, A>, ...args: A): T {
if (typeof value === "function") {
return (value as any)(...args);
} else {
return value;
}
}
/* eslint-enable @typescript-eslint/no-explicit-any */
function endsWith(
str: string,
searchString: string,
position?: number
): boolean {
const subjectString = str.toString();
if (
typeof position !== "number" ||
!isFinite(position) ||
Math.floor(position) !== position ||
position > subjectString.length
) {
position = subjectString.length;
}
position -= searchString.length;
const lastIndex = subjectString.lastIndexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
}
function genChars(s: string): { next(): string | null } {
// Surrogate Code Point
// [\uD800-\uDBFF]
// Variation Selectors
// FVS [\u180B-\u180D]
// VS1~VS16 [\uFE00-\uFE0F]
// VS17~VS256 \uDB40[\uDD00-\uDDEF]
const re =
/([\uD800-\uDBFF][\uDC00-\uDFFF]|\r\n|[^\uD800-\uDFFF])([\u180B-\u180D]|[\uFE00-\uFE0F]|\uDB40[\uDD00-\uDDEF])?/g;
return {
next(): string | null {
const res = re.exec(s);
return res !== null ? res[0] : null;
},
};
}
export type GenWordsResult = {
next(): string | null;
};
function genWords(s: string): GenWordsResult {
const re = /[!-~]+|[^!-~\s]+|\s+/g;
return {
next(): string | null {
const res = re.exec(s);
return res !== null ? res[0] : null;
},
};
}
export function isPromise<T>(
data: T | Promise<T> | undefined
): data is Promise<T> {
return Boolean(data && typeof (data as Promise<T>).then === "function");
}
function then<T, R>(
result: MaybePromise<T>,
callback: (arg: T) => MaybePromise<R>
): MaybePromise<R>;
function then<T, R>(
result: MaybePromise<T>,
callback: (arg: T) => R
): MaybePromise<R>;
function then<T, R>(
result: MaybePromise<T>,
callback: (arg: T) => R
): MaybePromise<R> {
return isPromise(result) ? result.then((r) => callback(r)) : callback(result);
}
function getMouseButtons(e: MouseEvent): number {
if (e.buttons != null) {
return e.buttons;
}
/*for legacy*/
if (e.which != null) {
if (e.which === 3) {
//right?
return 4;
}
if (e.which === 2) {
//middle?
return 4;
}
return e.which; //left or no
}
if (e.button === 0 || e.button === 1) {
return 1; //candidate left
}
if (e.button === 2) {
return 2; // right
}
return 0; //no or middle?
}
function getKeyCode(e: KeyboardEvent): number {
return e.keyCode || e.which;
}
function isTouchEvent(e: TouchEvent | MouseEvent): e is TouchEvent {
return !!(e as TouchEvent).changedTouches;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function getIgnoreCase(obj: any, name: string): any {
if (obj[name]) {
return obj[name];
}
const l = name.toLowerCase();
if (obj[l]) {
return obj[l];
}
const u = name.toLowerCase();
if (obj[u]) {
return obj[u];
}
for (const k in obj) {
if (k.toLowerCase() === l) {
return obj[k];
}
}
return undefined;
}
function cancel(e: Event): void {
e.preventDefault();
e.stopPropagation();
}
function toBoxArray<T>(obj: T | T[]): [T, T, T, T] {
if (!Array.isArray(obj)) {
return [obj /*top*/, obj /*right*/, obj /*bottom*/, obj /*left*/];
}
if (obj.length === 3) {
return [
obj[0] /*top*/,
obj[1] /*right*/,
obj[2] /*bottom*/,
obj[1] /*left*/,
];
}
if (obj.length === 2) {
return [
obj[0] /*top*/,
obj[1] /*right*/,
obj[0] /*bottom*/,
obj[1] /*left*/,
];
}
if (obj.length === 1) {
return [
obj[0] /*top*/,
obj[0] /*right*/,
obj[0] /*bottom*/,
obj[0] /*left*/,
];
}
return obj as [T, T, T, T];
}
export {
isNode,
isDescendantElement,
getChainSafe,
applyChainSafe,
getOrApply,
getIgnoreCase,
then,
array,
};
export function cellEquals(a: CellAddress, b: CellAddress): boolean {
return a.col === b.col && a.row === b.row;
}
export function cellInRange(
range: CellRange,
col: number,
row: number
): boolean {
return (
range.start.col <= col &&
col <= range.end.col &&
range.start.row <= row &&
row <= range.end.row
);
}
export const browser = {
IE,
Edge,
Chrome,
Firefox,
Safari,
// Chrome 33554431
// FireFox 17895588
// IE 10737433
heightLimit: Chrome ? 33554431 : Firefox ? 17895588 : 10737433, // default IE limit
};
export const obj = {
setReadonly,
isObject,
};
export const str = {
endsWith,
genChars,
genWords,
};
export const event = {
getMouseButtons,
getKeyCode,
isTouchEvent,
cancel,
};
export const style = {
toBoxArray,
};
export const emptyFn = Function.prototype; | the_stack |
import { makeExecutableSchema } from 'graphql-tools';
import { Pool } from 'pg';
import dotenv from 'dotenv';
dotenv.config();
const PG_URI = process.env.PG_URI
const pool = new Pool({
connectionString: PG_URI,
});
interface dbType {
query: (text: any, params?: any, callback?: any) => any | void;
}
const db: dbType = {
query: (text, params, callback) => {
console.log('executed query:', text);
return pool.query(text, params, callback);
}
};
// SCHEMA FOR GRAPHIQL SANDBOX
const typeDefs = `
type Film {
_id: ID!
director: String!
episode_id: Int!
opening_crawl: String!
producer: String!
release_date: String!
title: String!
people: [Person]
planets: [Planet]
species: [Species]
vessels: [Vessel]
}
type Person {
_id: ID!
birth_year: String
eye_color: String
gender: String
hair_color: String
height: Int
planets: [Planet]
mass: String
name: String!
skin_color: String
species: [Species]
films: [Film]
vessels: [Vessel]
}
type Planet {
_id: ID!
climate: String
diameter: Int
gravity: String
name: String
orbital_period: Int
population: Float
rotation_period: Int
surface_water: String
terrain: String
people: [Person]
species: [Species]
films: [Film]
}
type Species {
_id: ID!
average_height: String
average_lifespan: String
classification: String
eye_colors: String
hair_colors: String
planets: [Planet]
language: String
name: String!
skin_colors: String
people: [Person]
films: [Film]
}
type StarshipSpec {
MGLT: String
_id: ID!
hyperdrive_rating: String
vessels: [Vessel]
}
type Vessel {
_id: ID!
cargo_capacity: String
consumables: String
cost_in_credits: Float
crew: Int
length: String
manufacturer: String
max_atmosphering_speed: String
model: String
name: String!
passengers: Int
vessel_class: String!
vessel_type: String!
starshipSpecs: [StarshipSpec]
people: [Person]
films: [Film]
}
type Query {
films: [Film]
film(_id: ID!): Film
people: [Person]
person(_id: ID!): Person
planets: [Planet]
planet(_id: ID!): Planet
species: [Species]
speciesById(_id: ID!): Species
starshipSpecs: [StarshipSpec]
starshipSpec(_id: ID!): StarshipSpec
vessels: [Vessel]
vessel(_id: ID!): Vessel
}
type Mutation {
addFilm(
director: String!,
episode_id: Int!,
opening_crawl: String!,
producer: String!,
release_date: String!,
title: String!,
): Film!
updateFilm(
_id: ID,
director: String,
episode_id: Int,
opening_crawl: String,
producer: String,
release_date: String,
title: String,
): Film!
deleteFilm(
_id: ID!,
): Film!
addPerson(
birth_year: String,
eye_color: String,
gender: String,
hair_color: String,
height: Int,
homeworld_id: Int,
mass: String,
name: String!,
skin_color: String,
species_id: Int,
): Person!
updatePerson(
_id: ID,
birth_year: String,
eye_color: String,
gender: String,
hair_color: String,
height: Int,
homeworld_id: Int,
mass: String,
name: String,
skin_color: String,
species_id: Int,
): Person!
deletePerson(
_id: ID!,
): Person!
addPlanet(
climate: String,
diameter: Int,
gravity: String,
name: String,
orbital_period: Int,
population: Float,
rotation_period: Int,
surface_water: String,
terrain: String,
): Planet!
updatePlanet(
_id: ID,
climate: String,
diameter: Int,
gravity: String,
name: String,
orbital_period: Int,
population: Float,
rotation_period: Int,
surface_water: String,
terrain: String,
): Planet!
deletePlanet(
_id: ID!,
): Planet!
addSpecies(
average_height: String,
average_lifespan: String,
classification: String,
eye_colors: String,
hair_colors: String,
homeworld_id: Int,
language: String,
name: String!,
skin_colors: String,
): Species!
updateSpecies(
_id: ID,
average_height: String,
average_lifespan: String,
classification: String,
eye_colors: String,
hair_colors: String,
homeworld_id: Int,
language: String,
name: String,
skin_colors: String,
): Species!
deleteSpecies(
_id: ID!,
): Species!
addStarshipSpec(
MGLT: String,
hyperdrive_rating: String,
vessel_id: Int!,
): StarshipSpec!
updateStarshipSpec(
MGLT: String,
_id: ID,
hyperdrive_rating: String,
vessel_id: Int,
): StarshipSpec!
deleteStarshipSpec(
_id: ID!,
): StarshipSpec!
addVessel(
cargo_capacity: String,
consumables: String,
cost_in_credits: Float,
crew: Int,
length: String,
manufacturer: String,
max_atmosphering_speed: String,
model: String,
name: String!,
passengers: Int,
vessel_class: String!,
vessel_type: String!,
): Vessel!
updateVessel(
_id: ID,
cargo_capacity: String,
consumables: String,
cost_in_credits: Float,
crew: Int,
length: String,
manufacturer: String,
max_atmosphering_speed: String,
model: String,
name: String,
passengers: Int,
vessel_class: String,
vessel_type: String,
): Vessel!
deleteVessel(
_id: ID!,
): Vessel!
}
`;
// RESOLVER FOR GRAPHIQL SANDBOX
const resolvers = {
Query: {
films: async () => {
try {
const query = 'SELECT * FROM films';
const data = await db.query(query);
console.log('sql query results data.rows', data.rows);
return data.rows;
} catch (err: any) {
console.log('error in query', err);
}
},
film: async (parent, args, context, info) => {
try {
const query = 'SELECT * FROM films WHERE _id = $1';
const values = [args._id];
const data = await db.query(query, values);
console.log('sql query result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
people: async () => {
try {
const query = 'SELECT * FROM people';
const data = await db.query(query);
console.log('sql query results data.rows', data.rows);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
person: async (parent, args, context, info) => {
try {
const query = 'SELECT * FROM people WHERE _id = $1';
const values = [args._id];
const data = await db.query(query, values);
console.log('sql query result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
planets: async () => {
try {
const query = 'SELECT * FROM planets';
const data = await db.query(query);
console.log('sql query results data.rows', data.rows);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
planet: async (parent, args, context, info) => {
try {
const query = 'SELECT * FROM planets WHERE _id = $1';
const values = [args._id];
const data = await db.query(query, values);
console.log('sql query result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
species: async () => {
try {
const query = 'SELECT * FROM species';
const data = await db.query(query);
console.log('sql query results data.rows', data.rows);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
speciesById: async (parent, args, context, info) => {
try {
const query = 'SELECT * FROM species WHERE _id = $1';
const values = [args._id];
const data = await db.query(query, values);
console.log('sql query result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
starshipSpecs: async () => {
try {
const query = 'SELECT * FROM starship_specs';
const data = await db.query(query);
console.log('sql query results data.rows', data.rows);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
starshipSpec: async (parent, args, context, info) => {
try {
const query = 'SELECT * FROM starship_specs WHERE _id = $1';
const values = [args._id];
const data = await db.query(query, values);
console.log('sql query result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
vessels: async () => {
try {
const query = 'SELECT * FROM vessels';
const data = await db.query(query);
console.log('sql query results data.rows', data.rows);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
vessel: async (parent, args, context, info) => {
try {
const query = 'SELECT * FROM vessels WHERE _id = $1';
const values = [args._id];
const data = await db.query(query, values);
console.log('sql query result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
},
Mutation: {
addFilm: async (parent, args, context, info) => {
try {
const query = `INSERT INTO films (director, episode_id,
opening_crawl, producer, release_date,
title)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING *`;
const values = [args.director, args.episode_id,
args.opening_crawl, args.producer, args.release_date,
args.title];
const data = await db.query(query, values);
console.log('insert sql result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
updateFilm: async (parent, args, context, info) => {
try {
// sanitizing data for sql insert
const argsArr = Object.keys(args).filter((el) => (el !== '_id'));
const setStr = argsArr
.map((el, i) => el + ' = $' + (i + 1))
.join(', ');
argsArr.push('_id');
const pKey = '$' + argsArr.length;
const valuesArr = argsArr.map((el) => args[el]);
// insert query
const query = 'UPDATE films SET ' + setStr + ' WHERE _id = ' + pKey + ' RETURNING *';
const values = valuesArr;
const data = await db.query(query, values);
console.log('insert sql result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
deleteFilm: async (parent, args, context, info) => {
try {
const query = `DELETE FROM films
WHERE _id = $1 RETURNING *`;
const values = [args._id];
const data = await db.query(query, values);
console.log('delete sql result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
addPerson: async (parent, args, context, info) => {
try {
const query = `INSERT INTO people (birth_year, eye_color,
gender, hair_color, height,
homeworld_id, mass, name,
skin_color, species_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
RETURNING *`;
const values = [args.birth_year, args.eye_color,
args.gender, args.hair_color, args.height,
args.homeworld_id, args.mass, args.name,
args.skin_color, args.species_id];
const data = await db.query(query, values);
console.log('insert sql result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
updatePerson: async (parent, args, context, info) => {
try {
// sanitizing data for sql insert
const argsArr = Object.keys(args).filter((el) => (el !== '_id'));
const setStr = argsArr
.map((el, i) => el + ' = $' + (i + 1))
.join(', ');
argsArr.push('_id');
const pKey = '$' + argsArr.length;
const valuesArr = argsArr.map((el) => args[el]);
// insert query
const query = 'UPDATE people SET ' + setStr + ' WHERE _id = ' + pKey + ' RETURNING *';
const values = valuesArr;
const data = await db.query(query, values);
console.log('insert sql result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
deletePerson: async (parent, args, context, info) => {
try {
const query = `DELETE FROM people
WHERE _id = $1 RETURNING *`;
const values = [args._id];
const data = await db.query(query, values);
console.log('delete sql result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
addPlanet: async (parent, args, context, info) => {
try {
const query = `INSERT INTO planets (climate, diameter,
gravity, name, orbital_period,
population, rotation_period, surface_water,
terrain)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
RETURNING *`;
const values = [args.climate, args.diameter,
args.gravity, args.name, args.orbital_period,
args.population, args.rotation_period, args.surface_water,
args.terrain];
const data = await db.query(query, values);
console.log('insert sql result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
updatePlanet: async (parent, args, context, info) => {
try {
// sanitizing data for sql insert
const argsArr = Object.keys(args).filter((el) => (el !== '_id'));
const setStr = argsArr
.map((el, i) => el + ' = $' + (i + 1))
.join(', ');
argsArr.push('_id');
const pKey = '$' + argsArr.length;
const valuesArr = argsArr.map((el) => args[el]);
// insert query
const query = 'UPDATE planets SET ' + setStr + ' WHERE _id = ' + pKey + ' RETURNING *';
const values = valuesArr;
const data = await db.query(query, values);
console.log('insert sql result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
deletePlanet: async (parent, args, context, info) => {
try {
const query = `DELETE FROM planets
WHERE _id = $1 RETURNING *`;
const values = [args._id];
const data = await db.query(query, values);
console.log('delete sql result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
addSpecies: async (parent, args, context, info) => {
try {
const query = `INSERT INTO species (average_height, average_lifespan,
classification, eye_colors, hair_colors,
homeworld_id, language, name,
skin_colors)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
RETURNING *`;
const values = [args.average_height, args.average_lifespan,
args.classification, args.eye_colors, args.hair_colors,
args.homeworld_id, args.language, args.name,
args.skin_colors];
const data = await db.query(query, values);
console.log('insert sql result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
updateSpecies: async (parent, args, context, info) => {
try {
// sanitizing data for sql insert
const argsArr = Object.keys(args).filter((el) => (el !== '_id'));
const setStr = argsArr
.map((el, i) => el + ' = $' + (i + 1))
.join(', ');
argsArr.push('_id');
const pKey = '$' + argsArr.length;
const valuesArr = argsArr.map((el) => args[el]);
// insert query
const query = 'UPDATE species SET ' + setStr + ' WHERE _id = ' + pKey + ' RETURNING *';
const values = valuesArr;
const data = await db.query(query, values);
console.log('insert sql result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
deleteSpecies: async (parent, args, context, info) => {
try {
const query = `DELETE FROM species
WHERE _id = $1 RETURNING *`;
const values = [args._id];
const data = await db.query(query, values);
console.log('delete sql result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
addStarshipSpec: async (parent, args, context, info) => {
try {
const query = `INSERT INTO starship_specs (MGLT, hyperdrive_rating,
vessel_id)
VALUES ($1, $2, $3)
RETURNING *`;
const values = [args.MGLT, args.hyperdrive_rating,
args.vessel_id];
const data = await db.query(query, values);
console.log('insert sql result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
updateStarshipSpec: async (parent, args, context, info) => {
try {
// sanitizing data for sql insert
const argsArr = Object.keys(args).filter((el) => (el !== '_id'));
const setStr = argsArr
.map((el, i) => el + ' = $' + (i + 1))
.join(', ');
argsArr.push('_id');
const pKey = '$' + argsArr.length;
const valuesArr = argsArr.map((el) => args[el]);
// insert query
const query = 'UPDATE starship_specs SET ' + setStr + ' WHERE _id = ' + pKey + ' RETURNING *';
const values = valuesArr;
const data = await db.query(query, values);
console.log('insert sql result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
deleteStarshipSpec: async (parent, args, context, info) => {
try {
const query = `DELETE FROM starship_specs
WHERE _id = $1 RETURNING *`;
const values = [args._id];
const data = await db.query(query, values);
console.log('delete sql result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
addVessel: async (parent, args, context, info) => {
try {
const query = `INSERT INTO vessels (cargo_capacity, consumables,
cost_in_credits, crew, length,
manufacturer, max_atmosphering_speed, model,
name, passengers, vessel_class,
vessel_type)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
RETURNING *`;
const values = [args.cargo_capacity, args.consumables,
args.cost_in_credits, args.crew, args.length,
args.manufacturer, args.max_atmosphering_speed, args.model,
args.name, args.passengers, args.vessel_class,
args.vessel_type];
const data = await db.query(query, values);
console.log('insert sql result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
updateVessel: async (parent, args, context, info) => {
try {
// sanitizing data for sql insert
const argsArr = Object.keys(args).filter((el) => (el !== '_id'));
const setStr = argsArr
.map((el, i) => el + ' = $' + (i + 1))
.join(', ');
argsArr.push('_id');
const pKey = '$' + argsArr.length;
const valuesArr = argsArr.map((el) => args[el]);
// insert query
const query = 'UPDATE vessels SET ' + setStr + ' WHERE _id = ' + pKey + ' RETURNING *';
const values = valuesArr;
const data = await db.query(query, values);
console.log('insert sql result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
deleteVessel: async (parent, args, context, info) => {
try {
const query = `DELETE FROM vessels
WHERE _id = $1 RETURNING *`;
const values = [args._id];
const data = await db.query(query, values);
console.log('delete sql result data.rows[0]', data.rows[0]);
return data.rows[0];
} catch (err: any) {
throw new Error(err);
}
},
},
Film: {
people: async (films) => {
try {
const query = `SELECT * FROM people
LEFT OUTER JOIN people_in_films
ON people._id = people_in_films.person_id
WHERE people_in_films.film_id = $1`;
const values = [films._id];
const data = await db.query(query, values);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
planets: async (films) => {
try {
const query = `SELECT * FROM planets
LEFT OUTER JOIN planets_in_films
ON planets._id = planets_in_films.planet_id
WHERE planets_in_films.film_id = $1`;
const values = [films._id];
const data = await db.query(query, values);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
species: async (films) => {
try {
const query = `SELECT * FROM species
LEFT OUTER JOIN species_in_films
ON species._id = species_in_films.species_id
WHERE species_in_films.film_id = $1`;
const values = [films._id];
const data = await db.query(query, values);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
vessels: async (films) => {
try {
const query = `SELECT * FROM vessels
LEFT OUTER JOIN vessels_in_films
ON vessels._id = vessels_in_films.vessel_id
WHERE vessels_in_films.film_id = $1`;
const values = [films._id];
const data = await db.query(query, values);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
},
Person: {
planets: async (people) => {
try {
const query = `SELECT planets.* FROM planets
LEFT OUTER JOIN people
ON planets._id = people.homeworld_id
WHERE people._id = $1`;
const values = [people._id];
const data = await db.query(query, values);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
species: async (people) => {
try {
const query = `SELECT species.* FROM species
LEFT OUTER JOIN people
ON species._id = people.species_id
WHERE people._id = $1`;
const values = [people._id];
const data = await db.query(query, values);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
films: async (people) => {
try {
const query = `SELECT * FROM films
LEFT OUTER JOIN people_in_films
ON films._id = people_in_films.film_id
WHERE people_in_films.person_id = $1`;
const values = [people._id];
const data = await db.query(query, values);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
vessels: async (people) => {
try {
const query = `SELECT * FROM vessels
LEFT OUTER JOIN pilots
ON vessels._id = pilots.vessel_id
WHERE pilots.person_id = $1`;
const values = [people._id];
const data = await db.query(query, values);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
},
Planet: {
people: async (planets) => {
try {
const query = `SELECT * FROM people
WHERE homeworld_id = $1`;
const values = [planets._id];
const data = await db.query(query, values);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
species: async (planets) => {
try {
const query = `SELECT * FROM species
WHERE homeworld_id = $1`;
const values = [planets._id];
const data = await db.query(query, values);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
films: async (planets) => {
try {
const query = `SELECT * FROM films
LEFT OUTER JOIN planets_in_films
ON films._id = planets_in_films.film_id
WHERE planets_in_films.planet_id = $1`;
const values = [planets._id];
const data = await db.query(query, values);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
},
Species: {
planets: async (species) => {
try {
const query = `SELECT planets.* FROM planets
LEFT OUTER JOIN species
ON planets._id = species.homeworld_id
WHERE species._id = $1`;
const values = [species._id];
const data = await db.query(query, values);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
people: async (species) => {
try {
const query = `SELECT * FROM people
WHERE species_id = $1`;
const values = [species._id];
const data = await db.query(query, values);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
films: async (species) => {
try {
const query = `SELECT * FROM films
LEFT OUTER JOIN species_in_films
ON films._id = species_in_films.film_id
WHERE species_in_films.species_id = $1`;
const values = [species._id];
const data = await db.query(query, values);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
},
StarshipSpec: {
vessels: async (starship_specs) => {
try {
const query = `SELECT vessels.* FROM vessels
LEFT OUTER JOIN starship_specs
ON vessels._id = starship_specs.vessel_id
WHERE starship_specs._id = $1`;
const values = [starship_specs._id];
const data = await db.query(query, values);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
},
Vessel: {
starshipSpecs: async (vessels) => {
try {
const query = `SELECT * FROM starship_specs
WHERE vessel_id = $1`;
const values = [vessels._id];
const data = await db.query(query, values);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
people: async (vessels) => {
try {
const query = `SELECT * FROM people
LEFT OUTER JOIN pilots
ON people._id = pilots.person_id
WHERE pilots.vessel_id = $1`;
const values = [vessels._id];
const data = await db.query(query, values);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
films: async (vessels) => {
try {
const query = `SELECT * FROM films
LEFT OUTER JOIN vessels_in_films
ON films._id = vessels_in_films.film_id
WHERE vessels_in_films.vessel_id = $1`;
const values = [vessels._id];
const data = await db.query(query, values);
return data.rows;
} catch (err: any) {
throw new Error(err);
}
},
},
};
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
export default schema; | the_stack |
import React, {useEffect, useState} from 'react';
import {enableScreens} from 'react-native-screens';
import {Platform, StatusBar, Image, AppState} from 'react-native';
import {
getStateFromPath,
LinkingOptions,
NavigationContainer,
NavigationContainerRef
} from '@react-navigation/native';
import {
createStackNavigator,
CardStyleInterpolators
} from '@react-navigation/stack';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import {SafeAreaProvider} from 'react-native-safe-area-context';
import PushNotification, {
PushNotification as PN
} from 'react-native-push-notification';
import PushNotificationIOS from '@react-native-community/push-notification-ios';
import Spinner from 'react-native-loading-spinner-overlay';
// import NetInfo from '@react-native-community/netinfo';
import {useTranslation} from 'react-i18next';
import {
ExposureProvider,
TraceConfiguration,
KeyServerType,
useExposure,
StatusState,
getConfigData
} from 'react-native-exposure-notification-service';
import {Asset} from 'expo-asset';
import * as Font from 'expo-font';
import * as SecureStore from 'expo-secure-store';
import './services/i18n';
import {useRtl} from './hooks/i18n';
import {ApplicationProvider, useApplication} from './providers/context';
import {
SettingsProvider,
SettingsContext,
useSettings
} from './providers/settings';
import {VaccineCertConfigProvider} from './providers/vaccine-cert-config';
import {urls} from './constants/urls';
import {Base} from './components/templates/base';
import {NavBar} from './components/atoms/navbar';
import {TabBarBottom} from './components/organisms/tab-bar-bottom';
import {Over16} from './components/views/over-16';
import {Under16} from './components/views/under-16';
import {GetStarted} from './components/views/get-started';
import {YourData} from './components/views/your-data';
import {AppUsage} from './components/views/app-usage';
import {ContactTracingInformation} from './components/views/contact-tracing-information';
import {FollowUpCall} from './components/views/follow-up-call';
import {Sorry} from './components/views/sorry';
import {
DataProtectionPolicy,
TermsAndConditions
} from './components/views/data-protection-policy';
import {Dashboard} from './components/views/dashboard';
import {SymptomChecker} from './components/views/symptom-checker';
import {SymptomsHistory} from './components/views/symptoms-history';
import {ContactTracing} from './components/views/contact-tracing';
import {CountyBreakdown} from './components/views/county-breakdown';
import {CountyChart} from './components/views/chart-by-county';
import {CloseContactInfo} from './components/views/close-contact-info';
import {CloseContactAlert} from './components/views/close-contact-alert';
import {UploadKeys} from './components/views/upload-keys';
import {Reminder} from './components/views/reminder';
import {VaccineStats} from './components/views/vaccine-stats';
import {VaccineByCounty} from './components/views/vaccine-by-county';
import {Register, Scan, ViewCert} from './components/views/vaccine-cert';
import {Settings} from './components/views/settings';
import {ContactTracingSettings} from './components/views/settings/contact-tracing';
import {CheckInSettings} from './components/views/settings/check-in';
import {CheckInReminder} from './components/views/settings/check-in-reminder';
import {Metrics} from './components/views/settings/metrics';
import {Language} from './components/views/settings/language';
import {Leave} from './components/views/settings/leave';
import {Debug} from './components/views/settings/debug';
import {isMountedRef, navigationRef} from './navigation';
import {colors} from './constants/colors';
import {Loading} from './components/views/loading';
import {RemindersProvider} from './providers/reminders';
import {notificationHooks} from './services/notifications';
import {Pause} from './components/views/pause';
import {
DEEP_LINK_DOMAIN,
DEEP_LINK_PREFIX_IOS,
DEEP_LINK_PREFIX_ANDROID
} from '@env';
const DEEP_LINK_PREFIX =
Platform.OS === 'ios' ? DEEP_LINK_PREFIX_IOS : DEEP_LINK_PREFIX_ANDROID;
/*
import {
VenueCodeScanner,
CameraPermission,
ScanResultSuccess,
ScanResultError,
VenueHistory,
RiskyVenueContact
} from './venue-check-in';
*/
enableScreens();
/*try {
NetInfo.fetch().then((state) => console.log(state));
} catch (err) {
console.log(err);
}*/
function cacheImages(images: (string | number)[]) {
return images.map((image) => {
if (typeof image === 'string') {
return Image.prefetch(image);
} else {
return Asset.fromModule(image).downloadAsync();
}
});
}
const Stack = createStackNavigator();
const Tab = createBottomTabNavigator();
const SymptomsStack = () => {
const app = useApplication();
const {t} = useTranslation();
const initialRouteName = app.checks.length
? 'symptoms.history'
: 'symptoms.checker';
return (
<Stack.Navigator
screenOptions={{
animationEnabled: true
// header: props => <NavBar hideSettings={!app.user || !app.user.id} {...props} />
}}
initialRouteName={initialRouteName}
headerMode="none">
<Stack.Screen
name="symptoms.history"
component={SymptomsHistory}
options={{title: t('viewNames:symptomchecker')}}
/>
<Stack.Screen
name="symptoms.checker"
component={SymptomChecker}
options={{title: t('viewNames:symptomchecker')}}
/>
</Stack.Navigator>
);
};
const MainStack = () => {
const {t} = useTranslation();
useRtl();
return (
<Tab.Navigator
initialRouteName="dashboard"
tabBar={(props: any) => <TabBarBottom {...props} />}>
<Tab.Screen
name="dashboard"
component={Dashboard}
options={{title: t('viewNames:updates')}}
/>
<Tab.Screen
name="vaccineStats"
component={VaccineStats}
options={{title: t('viewNames:vaccineStats')}}
/>
<Tab.Screen
name="symptoms"
component={SymptomsStack}
options={{title: t('viewNames:symptomchecker')}}
/>
<Tab.Screen
name="tracing"
component={ContactTracing}
options={{title: t('viewNames:contactTracing')}}
/>
</Tab.Navigator>
);
};
const RootStack = createStackNavigator();
/*
const VenueCheckInStack = createStackNavigator();
const VenueStack = () => {
const {t} = useTranslation();
return (
<VenueCheckInStack.Navigator
screenOptions={{
cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
cardStyle: {backgroundColor: colors.black},
gestureEnabled: false,
gestureDirection: 'horizontal',
animationEnabled: true,
header: () => null
}}
initialRouteName={'venueCheckIn.scanner'}
mode="modal"
headerMode="none">
<VenueCheckInStack.Screen
name="venueCheckIn.scanner"
component={VenueCodeScanner}
options={{
title: t('viewNames:venueCheckIn')
}}
/>
<VenueCheckInStack.Screen
name="venueCheckIn.scanSuccess"
component={ScanResultSuccess}
options={{title: t('viewNames:venueCheckIn')}}
initialParams={{isLastCheckinValid: true}}
/>
<VenueCheckInStack.Screen
name="venueCheckIn.scanError"
component={ScanResultError}
options={{title: t('viewNames:venueCheckIn')}}
/>
<VenueCheckInStack.Screen
name="venueCheckIn.permission"
component={CameraPermission}
options={{title: t('viewNames:venueCheckIn')}}
/>
</VenueCheckInStack.Navigator>
);
};
*/
const AppStack: React.FC<any> = ({route}) => {
const {t} = useTranslation();
const {initialScreen} = route.params;
return (
<Stack.Navigator
screenOptions={{
cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
cardStyle: {backgroundColor: 'transparent'},
gestureEnabled: true,
gestureDirection: 'horizontal',
animationEnabled: true,
header: (props) => <NavBar {...props} />
}}
initialRouteName={initialScreen}
headerMode="float">
<Stack.Screen
name="over16"
component={Over16}
options={{
title: t('viewNames:age'),
header: () => null,
cardStyle: {backgroundColor: colors.yellow}
}}
/>
<Stack.Screen name="under16" component={Under16} />
<Stack.Screen
name="getStarted"
component={GetStarted}
options={{
title: t('viewNames:getStarted'),
header: () => null,
cardStyle: {backgroundColor: colors.yellow}
}}
/>
<Stack.Screen
name="yourData"
component={YourData}
options={{title: t('yourData:title')}}
/>
<Stack.Screen
name="appUsage"
component={AppUsage}
options={{title: t('appUsage:title')}}
/>
<Stack.Screen
name="contactTracingInformation"
component={ContactTracingInformation}
options={{title: t('tabBar:contactTracing')}}
/>
<Stack.Screen
name="followUpCall"
component={FollowUpCall}
options={{title: t('followUpCall:contactTracing')}}
/>
<Stack.Screen
name="main"
component={MainStack}
// @ts-ignore
options={{showSettings: true}}
/>
<Stack.Screen
name="casesByCounty"
component={CountyBreakdown}
options={{title: t('viewNames:casesByCounty')}}
/>
<Stack.Screen name="chartByCounty" component={CountyChart} />
<Stack.Screen
name="vaccineByCounty"
component={VaccineByCounty}
options={{title: t('viewNames:vaccineByCounty')}}
/>
<Stack.Screen
name="closeContactInfo"
component={CloseContactInfo}
options={{title: t('closeContactInfo:title')}}
/>
<Stack.Screen
name="closeContactAlert"
component={CloseContactAlert}
options={{title: t('closeContactAlert:title')}}
/>
<Stack.Screen name="reminder" component={Reminder} />
<Stack.Screen
name="uploadKeys"
component={UploadKeys}
options={{title: t('viewNames:uploadKeys')}}
/>
<Stack.Screen
name="pause"
component={Pause}
options={{title: t('pause:title')}}
/>
<Stack.Screen
name="settings"
component={Settings}
options={{title: t('viewNames:settings')}}
/>
<Stack.Screen
name="settings.contactTracing"
component={ContactTracingSettings}
options={{title: t('viewNames:settingsContactTracing')}}
/>
<Stack.Screen
name="settings.checkIn"
component={CheckInSettings}
options={{title: t('viewNames:settingsCheckin')}}
/>
<Stack.Screen
name="settings.checkInReminder"
component={CheckInReminder}
options={{title: t('viewNames:settingsCheckinReminder')}}
/>
<Stack.Screen
name="settings.privacy"
component={DataProtectionPolicy}
options={{title: t('viewNames:dataPolicy')}}
/>
<Stack.Screen
name="settings.terms"
component={TermsAndConditions}
options={{title: t('viewNames:terms')}}
/>
<Stack.Screen
name="settings.metrics"
component={Metrics}
options={{title: t('viewNames:metrics')}}
/>
<Stack.Screen
name="settings.language"
component={Language}
options={{title: t('languageSettings:title')}}
/>
<Stack.Screen
name="settings.leave"
component={Leave}
options={{title: t('viewNames:leave')}}
/>
<Stack.Screen name="settings.debug" component={Debug} />
<Stack.Screen name="sorry" component={Sorry} />
<Stack.Screen
name="privacy"
component={DataProtectionPolicy}
options={{title: t('viewNames:dataPolicy')}}
/>
<Stack.Screen
name="terms"
component={TermsAndConditions}
options={{title: t('viewNames:terms')}}
/>
{/*
<Stack.Screen
name="settings.venueHistory"
component={VenueHistory}
options={{title: t('viewNames:venueHistory')}}
/>
<Stack.Screen
name="riskyVenueContact"
component={RiskyVenueContact}
options={{title: t('viewNames:riskyVenueContact')}}
/>*/}
<Stack.Screen
name="vaccineCert.register"
component={Register}
options={{title: t('viewNames:vaccineCert')}}
/>
<Stack.Screen
name="vaccineCert.scan"
component={Scan}
options={{title: t('viewNames:vaccineCert')}}
/>
<Stack.Screen
name="vaccineCert.view"
component={ViewCert}
options={{title: t('viewNames:vaccineCert')}}
/>
</Stack.Navigator>
);
};
const linking: LinkingOptions = {
prefixes: [DEEP_LINK_PREFIX, DEEP_LINK_DOMAIN],
config: {
screens: {
app: {
screens: {
uploadKeys: {
path: '/v' // query string params are passed direct to the route as params
}
}
}
}
},
getStateFromPath: (path: string, config: any) => {
const state = getStateFromPath(path, config);
// Look for 'uploadKeys' in the inner stack nested inside rootstack
const innerRoutes = state?.routes?.length
? state.routes[0].state?.routes
: null;
const uploadKeysRoute = innerRoutes?.find(
(route) => route.name === 'uploadKeys'
);
if (uploadKeysRoute) {
return {
...state,
routes: [
{
name: 'app', // main is nested inside rootstack
state: {
routes: [
{name: 'main', params: {screen: 'tracing'}},
uploadKeysRoute
]
}
}
]
};
}
return state;
}
};
function Navigation({
notification,
exposureNotificationClicked,
setAppState
}: {
traceConfiguration: TraceConfiguration;
notification: PN | null;
exposureNotificationClicked: Boolean | null;
setAppState: (value: React.SetStateAction<State>) => void;
}) {
const app = useApplication();
const {checkExposure, initialised, enabled, status} = useExposure();
const initialScreen = app.user ? 'main' : 'over16';
const {initializing} = app;
useEffect(() => {
if (
!initializing &&
initialised &&
status.state === StatusState.active &&
enabled
) {
checkExposure(false);
}
}, [initializing, initialised]);
useEffect(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
};
}, []);
useEffect(() => {
if (Platform.OS !== 'ios') {
return;
}
if (navigationRef.current && notification) {
navigationRef.current.navigate('closeContactAlert');
setAppState((s) => ({...s, notification: null}));
}
}, [app, notification]);
useEffect(() => {
if (Platform.OS !== 'android') {
return;
}
if (navigationRef.current && exposureNotificationClicked) {
console.log('exposureNotificationClicked', exposureNotificationClicked);
navigationRef.current.navigate('closeContactAlert');
setAppState((s) => ({...s, exposureNotificationClicked: null}));
}
}, [app, exposureNotificationClicked]);
return (
<NavigationContainer
linking={linking}
ref={(e) => {
navigationRef.current = e;
notificationHooks.navigation = e as NavigationContainerRef;
}}>
<Spinner animation="fade" visible={!!app.loading} />
<RootStack.Navigator
screenOptions={{
cardStyleInterpolator: CardStyleInterpolators.forHorizontalIOS,
cardStyle: {backgroundColor: 'transparent'},
gestureEnabled: true,
gestureDirection: 'horizontal'
}}
headerMode="none"
mode="modal"
initialRouteName={'app'}>
<RootStack.Screen
name="app"
component={AppStack}
initialParams={{initialScreen}}
/>
{/*
<RootStack.Screen name="venueCheckIn" component={VenueStack} />
*/}
</RootStack.Navigator>
</NavigationContainer>
);
}
const ExposureApp: React.FC = ({children}) => {
const {t} = useTranslation();
const [authToken, setAuthToken] = useState<string>('');
const [refreshToken, setRefreshToken] = useState<string>('');
const settings = useSettings();
const app = useApplication();
useEffect(() => {
async function getTokens() {
try {
const storedAuthToken = (await SecureStore.getItemAsync('token')) || '';
const storedRefreshToken =
(await SecureStore.getItemAsync('refreshToken')) || '';
if (storedAuthToken !== authToken) {
setAuthToken(storedAuthToken);
}
if (storedRefreshToken !== refreshToken) {
setRefreshToken(storedRefreshToken);
}
} catch (err) {
console.log('error getting tokens', err);
}
//patch to fix completedExposureOnboarding
const config = await getConfigData();
if (config.lastExposureIndex > 0 && !app.completedExposureOnboarding) {
await app.setContext({completedExposureOnboarding: true});
}
}
getTokens();
}, [app.user]);
const mobile =
(app.callBackData && app.callBackData.mobile) ||
(app.callBackData &&
`${app.callBackData.code}${app.callBackData.number.replace(
/^0+/,
''
)}`) ||
'';
return (
<ExposureProvider
isReady={Boolean(
app.user?.valid &&
app.completedExposureOnboarding &&
authToken &&
refreshToken &&
!app.initializing
)}
traceConfiguration={settings.traceConfiguration}
serverUrl={urls.api}
keyServerUrl={urls.api}
keyServerType={KeyServerType.nearform}
authToken={authToken}
refreshToken={refreshToken}
notificationTitle={t('closeContactNotification:title')}
notificationDescription={t('closeContactNotification:description')}
analyticsOptin={app.analyticsConsent}
callbackNumber={mobile}>
{children}
</ExposureProvider>
);
};
interface State {
loading: boolean;
token?: {os: string; token: string};
notification: PN | null;
exposureNotificationClicked: Boolean | null;
}
export default function App(props: {
exposureNotificationClicked: Boolean | null;
}) {
const [appState, setAppState] = React.useState<State>({
loading: false,
notification: null,
exposureNotificationClicked: props.exposureNotificationClicked
});
useEffect(() => {
async function loadResourcesAndDataAsync() {
try {
const imageAssets = cacheImages([
require('./assets/images/onboard1/image.png'),
require('./assets/images/onboard2/image.png'),
require('./assets/images/onboard3/image.png'),
require('./assets/images/permissions/bluetooth.png'),
require('./assets/images/permissions/notifications.png'),
require('./assets/images/logo/logo.png'),
require('./assets/images/symptoma/image.png'),
require('./assets/images/symptomb/image.png'),
require('./assets/images/symptomc/image.png'),
require('./assets/images/symptomd/image.png')
]);
const fonts = await Font.loadAsync({
'lato-black': require('./assets/fonts/lato/Lato-Black.ttf'),
'lato-bold': require('./assets/fonts/lato/Lato-Bold.ttf'),
lato: require('./assets/fonts/lato/Lato-Regular.ttf'),
'lato-thin': require('./assets/fonts/lato/Lato-Thin.ttf')
});
await Promise.all([...imageAssets, fonts]);
} catch (e) {
console.warn(e);
} finally {
setAppState((s) => ({...s, loading: false}));
}
}
loadResourcesAndDataAsync();
notificationHooks.handleNotification = async function (notification) {
let requiresHandling = false;
if (Platform.OS === 'ios') {
if (
(notification && notification.userInteraction) ||
(AppState.currentState === 'active' && notification)
) {
PushNotification.setApplicationIconBadgeNumber(0);
requiresHandling = true;
setTimeout(() => {
notification.finish(
Platform.OS === 'ios'
? PushNotificationIOS.FetchResult.NoData
: ''
);
}, 3000);
}
}
if (requiresHandling) {
setTimeout(() => setAppState((s) => ({...s, notification})), 500);
}
};
}, []);
return (
<SafeAreaProvider>
<Base>
<SettingsProvider>
<SettingsContext.Consumer>
{(settingsValue) => {
if (!settingsValue.loaded) {
return <Loading />;
}
return (
<ApplicationProvider
appConfig={settingsValue.appConfig}
user={settingsValue.user}
consent={settingsValue.consent}
analyticsConsent={settingsValue.analyticsConsent}
completedExposureOnboarding={
settingsValue.completedExposureOnboarding
}
dpinDate={settingsValue.dpinDate}
tandcDate={settingsValue.tandcDate}>
<ExposureApp>
<RemindersProvider>
<VaccineCertConfigProvider>
<StatusBar barStyle="default" />
<Navigation
traceConfiguration={settingsValue.traceConfiguration}
notification={appState.notification}
exposureNotificationClicked={
appState.exposureNotificationClicked
}
setAppState={setAppState}
/>
</VaccineCertConfigProvider>
</RemindersProvider>
</ExposureApp>
</ApplicationProvider>
);
}}
</SettingsContext.Consumer>
</SettingsProvider>
</Base>
</SafeAreaProvider>
);
} | the_stack |
import * as assert from "assert";
import {BufferUtil} from "../../lib/core/buffer-util";
import {HTTPChunk, HTTPBuffer} from "../../lib/core/http-buffer";
describe("HTTPBuffer", function() {
describe("HTTPResponse tests", function() {
it("Basic chunked payload", function (done) {
let data = BufferUtil.fromString("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\n\r\na\r\n1234567890\r\n0\r\n\r\n");
let httpBuffer = new HTTPBuffer();
httpBuffer.append(data);
assert(httpBuffer.complete());
assert(httpBuffer.hasHeader("Content-Type"));
assert.equal(httpBuffer.body(), "1234567890");
assert.equal(httpBuffer.statusCode(), 200);
done();
});
it("Basic chunked payload as json", function (done) {
let data = BufferUtil.fromString("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\n\r\ne\r\n{\"test\": true}\r\n0\r\n\r\n");
let httpBuffer = new HTTPBuffer();
httpBuffer.append(data);
assert(httpBuffer.complete());
assert(httpBuffer.hasHeader("Content-Type"));
assert(httpBuffer.bodyAsJSON().test);
done();
});
it("Basic chunked payload split up", function (done) {
let data1 = BufferUtil.fromString("HTTP/1.1 200 OK\r\nContent-Type: ");
let data2 = BufferUtil.fromString("application/json\r\nTransfer-Encoding: chunked\r\n\r\na\r\n1234567890\r\n0\r\n\r\n");
let httpBuffer = new HTTPBuffer();
httpBuffer.append(data1);
// Everything should be undefined
assert(!httpBuffer.complete());
assert.equal(httpBuffer.body(), undefined);
assert.equal(httpBuffer.statusCode(), undefined);
// Now we add the second portion and it should be complete
httpBuffer.append(data2);
assert.equal(httpBuffer.body(), "1234567890");
done();
});
it("Chunked payload, headers and body split", function (done) {
// I would not expect this test to be necessary, but this happened
// A payload came in two parts, exactly split between header and body
// In this case, the header is defined, but no body yet, and that ends up in an undefined error!
let headers = BufferUtil.fromString("POST /test?this=1 HTTP/1.1\r\nContent-Type: application/json; charset=utf-8\r\nTransfer-Encoding: chunked\r\n\r\n");
let body = BufferUtil.fromString("a\r\n1234567890\r\n0\r\n\r\n");
let httpBuffer = new HTTPBuffer();
httpBuffer.append(headers);
httpBuffer.complete();
httpBuffer.append(body);
assert(httpBuffer.complete());
assert(httpBuffer.hasHeader("Content-Type"));
assert.equal(httpBuffer.body(), "1234567890");
assert.equal(httpBuffer.statusCode(), undefined);
assert.equal(httpBuffer.method(), "POST");
assert.equal(httpBuffer.uri(), "/test?this=1");
done();
});
it("Advanced chunked payload", function (done) {
// Got this directly from actual sniffing of payloads
// {"version":"1.0","response":{"shouldEndSession":true,"card":{"type":"Simple","title":"Playing Episode 140","content":"Playing Episode 140"},"directives":[{"type":"AudioPlayer.Play","playBehavior":"REPLACE_ALL","audioItem":{"stream":{"url":"https://feeds.soundcloud.com/stream/275202399-amazon-web-services-306355661-amazon-web-services.mp3","token":"0","expectedPreviousToken":null,"offsetInMilliseconds":0}}}]},"sessionAttributes":{"playOrder":[0,1,2,3,4,5],"index":0,"offsetInMilliseconds":0,"loop":true,"shuffle":false,"playbackIndexChanged":false,"enqueuedToken":null,"STATE":"_PLAY_MODE"}}
let data = BufferUtil.fromString("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nDate: Fri, 02 Sep 2016 18:09:26 GMT\r\nConnection: keep-alive\r\nTransfer-Encoding: chunked\r\n\r\n252\r\n{\"version\":\"1.0\",\"response\":{\"shouldEndSession\":true,\"card\":{\"type\":\"Simple\",\"title\":\"Playing Episode 140\",\"content\":\"Playing Episode 140\"},\"directives\":[{\"type\":\"AudioPlayer.Play\",\"playBehavior\":\"REPLACE_ALL\",\"audioItem\":{\"stream\":{\"url\":\"https://feeds.soundcloud.com/stream/275202399-amazon-web-services-306355661-amazon-web-services.mp3\",\"token\":\"0\",\"expectedPreviousToken\":null,\"offsetInMilliseconds\":0}}}]},\"sessionAttributes\":{\"playOrder\":[0,1,2,3,4,5],\"index\":0,\"offsetInMilliseconds\":0,\"loop\":true,\"shuffle\":false,\"playbackIndexChanged\":false,\"enqueuedToken\":null,\"STATE\":\"_PLAY_MODE\"}}\r\n0\r\n\r\n");
let httpBuffer = new HTTPBuffer();
httpBuffer.append(data);
assert(httpBuffer.complete());
assert.equal(httpBuffer.statusCode(), 200);
let json = httpBuffer.bodyAsJSON();
assert.equal(json.response.shouldEndSession, true);
assert.equal(json.response.card.type, "Simple");
done();
});
it("Advanced broken up chunked payload", function (done) {
// Got this directly from actual sniffing of payloads
// {"version":"1.0","response":{"shouldEndSession":true,"card":{"type":"Simple","title":"Playing Episode 140","content":"Playing Episode 140"},"directives":[{"type":"AudioPlayer.Play","playBehavior":"REPLACE_ALL","audioItem":{"stream":{"url":"https://feeds.soundcloud.com/stream/275202399-amazon-web-services-306355661-amazon-web-services.mp3","token":"0","expectedPreviousToken":null,"offsetInMilliseconds":0}}}]},"sessionAttributes":{"playOrder":[0,1,2,3,4,5],"index":0,"offsetInMilliseconds":0,"loop":true,"shuffle":false,"playbackIndexChanged":false,"enqueuedToken":null,"STATE":"_PLAY_MODE"}}
let data1 = BufferUtil.fromString("HTTP/1.1 200 OK\r\nContent-Type: application/");
let data2 = BufferUtil.fromString("json\r\nDate: Fri, 02 Sep 2016 18:09:26 GMT\r\nConnection: keep-alive\r\nTransfer-Encoding: chunked\r\n\r\n252\r\n");
let data3 = BufferUtil.fromString("{\"version\":\"1.0\",\"response\":{\"shouldEndSession\":true,\"card\":{\"type\":\"Simple\",\"title\":\"Playing Episode 140\",\"content\":\"Playing Episode 140\"},\"directives\":[{\"type\":\"AudioPlayer.Play\",\"playBehavior\":\"REPLACE_ALL\",\"audioItem\":{\"stream\":{\"url\":\"https://feeds.soundcloud.com/stream/275202399-amazon-web-services-306355661-amazon-web-services.mp3\",\"token\":\"0\",\"expectedPreviousToken\":null,\"offsetInMilliseconds\":0}}}]},\"sessionAttributes\":{\"playOrder\":[0,1,2,3,4,5],\"index\":0,\"offsetInMilliseconds\":0,\"loop\":true,\"shuffle\":false,\"playbackIndexChanged\":false,\"enqueuedToken\":null,\"STATE\":\"_PLAY_MODE\"}}\r\n0\r\n\r\n");
let httpBuffer = new HTTPBuffer();
httpBuffer.append(data1);
// Everything should be undefined
assert(!httpBuffer.complete());
assert.equal(httpBuffer.body(), undefined);
assert.equal(httpBuffer.statusCode(), undefined);
httpBuffer.append(data2);
assert.equal(httpBuffer.header("Content-Type"), "application/json");
assert.equal(httpBuffer.body(), undefined);
assert(!httpBuffer.complete());
httpBuffer.append(data3);
assert(httpBuffer.complete());
done();
});
});
describe("HTTPRequest tests", function() {
it("Basic request payload", function (done) {
let data = BufferUtil.fromString("POST /test?this=1 HTTP/1.1\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: 10\r\n\r\n1234567890");
let httpBuffer = new HTTPBuffer();
httpBuffer.append(data);
assert(httpBuffer.complete());
assert(httpBuffer.hasHeader("Content-Type"));
assert.equal(httpBuffer.body(), "1234567890");
assert.equal(httpBuffer.statusCode(), undefined);
assert.equal(httpBuffer.method(), "POST");
assert.equal(httpBuffer.uri(), "/test?this=1");
done();
});
it("Basic request payload, no content-length", function (done) {
let data = BufferUtil.fromString("POST /test?this=1 HTTP/1.1\r\nContent-Type: application/json; charset=utf-8\r\n\r\n1234567890");
let httpBuffer = new HTTPBuffer();
httpBuffer.append(data);
assert(httpBuffer.complete());
assert(httpBuffer.hasHeader("Content-Type"));
assert.equal(httpBuffer.body(), "1234567890");
assert.equal(httpBuffer.statusCode(), undefined);
assert.equal(httpBuffer.method(), "POST");
assert.equal(httpBuffer.uri(), "/test?this=1");
done();
});
it("Basic request payload, headers and body split", function (done) {
// I would not expect this test to be necessary, but this happened
// A payload came in two parts, exactly split between header and body
// In this case, the header is defined, but no body yet, and that ends up in an undefined error!
let headers = BufferUtil.fromString("POST /test?this=1 HTTP/1.1\r\nContent-Type: application/json; charset=utf-8\r\n\r\n");
let body = BufferUtil.fromString("1234567890");
let httpBuffer = new HTTPBuffer();
httpBuffer.append(headers);
httpBuffer.complete();
httpBuffer.append(body);
assert(httpBuffer.complete());
assert(httpBuffer.hasHeader("Content-Type"));
assert.equal(httpBuffer.body(), "1234567890");
assert.equal(httpBuffer.statusCode(), undefined);
assert.equal(httpBuffer.method(), "POST");
assert.equal(httpBuffer.uri(), "/test?this=1");
done();
});
it("Error response payload", function (done) {
// I would not expect this test to be necessary, but this happened
// A payload came in two parts, exactly split between header and body
// In this case, the header is defined, but no body yet, and that ends up in an undefined error!
let message = "This is an error that occurred";
let buffer = HTTPBuffer.errorResponse("This is an error that occurred");
assert.equal(buffer.raw().toString(), "HTTP/1.1 500 Error\r\nContent-Type: text/plain" +
"\r\nContent-Length: " + message.length + "\r\n\r\n" +
"This is an error that occurred");
done();
});
});
});
describe("HTTPChunk", function() {
describe("#parse()", function() {
it("Finds chunk", function (done) {
let chunk = HTTPChunk.parse(BufferUtil.fromString("a\r\n1234567890ABC"));
assert.equal(chunk.length(), 10);
assert.equal(chunk.headerLength(), 3);
assert.equal(chunk.body.toString(), "1234567890");
done();
});
it("Finds another chunk", function (done) {
let chunk = HTTPChunk.parse(BufferUtil.fromString("14\r\n12345678901234567890"));
assert.equal(chunk.length(), 20);
assert.equal(chunk.headerLength(), 4);
assert.equal(chunk.body.toString(), "12345678901234567890");
done();
});
it("Finds incomplete chunk", function (done) {
let chunk = HTTPChunk.parse(BufferUtil.fromString("14\r\n1234567890"));
assert(chunk === null);
done();
});
it("Finds incomplete chunk header", function (done) {
let chunk = HTTPChunk.parse(BufferUtil.fromString("14\r"));
assert(chunk === null);
done();
});
});
describe("#parseLength()", function() {
it("Finds chunk length", function (done) {
let length = HTTPChunk.parseLength(BufferUtil.fromString("1\r\n"));
assert.equal(length, "1");
length = HTTPChunk.parseLength(BufferUtil.fromString("a\r\n"));
assert.equal(length, "a");
length = HTTPChunk.parseLength(BufferUtil.fromString("E\r\n"));
assert.equal(length, "E");
length = HTTPChunk.parseLength(BufferUtil.fromString("10000\r\n"));
assert.equal(length, "10000");
done();
});
it("Finds bad chunk", function (done) {
try {
HTTPChunk.parseLength(BufferUtil.fromString("45G\r\n"));
assert(false, "This should never be reached");
} catch (e) {
assert(e.message.indexOf("Invalid character") !== -1);
}
done();
});
it("Finds no chunk", function (done) {
let length = HTTPChunk.parseLength(BufferUtil.fromString("45a"));
assert.equal(length, null);
done();
});
});
}); | the_stack |
export interface Translation {
home: Home
header: Header
footer: Footer
gdpr: GDPR
myCars: MyCars
confirm: Confirm
handover: Handover
completed: Completed
processes: Processes
deregisterOverview: DeregisterOverview
companyInfo: CompanyInfo
companyInfoForm: CompanyInfoFormPage
deregisterSidenav: DeregisterSidenav
deregisterVehicle: DeregisterVehicle
recyclingFundOverview: RecyclingFundOverview
recyclingFundSidenav: RecyclingFundSidenav
recyclingCompanies: RecyclingCompanies
notFound: NotFound
errorBoundary: ErrorBoundary
routes: Routes
}
export interface Home {
title: string
}
export interface Header {
logoutText: string
}
export interface Footer {
topLinksInfo: FooterLinks[]
topLinksContact: FooterLinks[]
bottomLinks: FooterLinks[]
bottomLinksTitle: string
}
export interface FooterLinks {
title: string
href: string
}
export interface GDPR {
title: string
subTitles: DataSubtitles
info: string
buttons: DataButtons
checkbox: string
error: Errors
}
export interface MyCars {
title: string
subTitles: MyCarsSubtitles
info: MyCarsInfo
actions: CarActions
status: CarStatus
buttons: CarsButtons
tooltip: ToolTip
error: Errors
}
export interface Confirm {
title: string
subTitles: ConfirmSubTitles
info: string
buttons: ProcessButtons
checkbox: CheckBox
}
export interface Handover {
titles: ProcessTitles
subTitles: HandoverSubTitles
info: string
subInfo: string
buttons: HandoverButtons
error: Errors
cancelModal: CancelModal
}
export interface Completed {
title: string
subTitles: CompletedSubTitles
info: CompletedInfo
confirmedBy: CompletedConfirmation
error: Errors
buttons: CompletedButtons
}
export interface Processes {
step: string
outOf: string
citizen: ProcessSections
company: ProcessSections
}
export interface ProcessSections {
title: string
sections: string[]
completed: string
}
export interface CancelModal {
titles: CancelModalTitles
info: string
buttons: ProcessButtons
error: Errors
}
export interface CancelModalTitles {
info: string
error: string
}
export interface DataSubtitles {
info: string
}
export interface DataButtons {
continue: string
}
export interface MyCarsSubtitles {
pending: string
active: string
done: string
}
export interface MyCarsInfo {
noCarsAvailable: string
}
export interface CarActions {
valid: string
invalid: string
}
export interface CarStatus {
coOwned: string
recycle: string
done: string
}
export interface CarsButtons {
openProcess: string
seeDetails: string
reload: string
}
export interface ToolTip {
text: string
link: string
}
export interface ConfirmSubTitles {
confirm: string
}
export interface ProcessButtons {
cancel: string
continue: string
}
export interface CheckBox {
label: string
linkLabel: string
}
export interface ProcessTitles {
success: string
error: string
loading: string
notfound: string
}
export interface HandoverSubTitles {
nextStep: string
companies: string
}
export interface HandoverButtons extends ProcessButtons {
close: string
}
export interface CompletedSubTitles {
summary: string
payment: string
}
export interface CompletedInfo {
oldDeregistration: string
payment: string
paymentLinkText: string
}
export interface CompletedConfirmation {
user: string
company: string
authority: string
fund: string
}
export interface CompletedButtons extends ProcessButtons {
close: string
}
export interface Errors {
title: string
message: string
primaryButton: string
secondaryButton: string
}
export interface DeregisterOverview {
title: string
info: string
subtitles: DeregisterOverviewSubTitles
buttons: DeregisterOverviewButtons
search: InputField
table: string[]
success: string
}
export interface CompanyInfo {
title: string
info: string
empty: string
subtitles: CompanyInfoSubTitles
buttons: CompanyInfoButtons
}
export interface CompanyInfoFormPage {
addTitle: string
editTitle: string
form: CompanyInfoForm
buttons: CompanyInfoFormButtons
success: string
}
export interface CompanyInfoForm {
title: string
company: InputField
visitingAddress: InputField
postNumber: InputField
city: InputField
website: InputField
phoneNumber: InputField
}
export interface deregisterSidenav {
deregister: string
companyInfo: string
}
export interface DeregisterVehicle {
select: DeregisterSelect
deregister: Deregister
}
export interface RecyclingFundOverview {
title: string
subtitles: ReyclingFundOverviewSubTitles
info: string
buttons: ReyclingFundOverviewButtons
search: InputField
table: string[]
}
export interface RecyclingCompanies {
title: string
info: string
empty: string
subtitles: RecyclingCompaniesSubTitles
status: CompanyStatus
buttons: CompanyInfoButtons
}
export interface CompanyStatus {
active: string
inactive: string
}
export interface NotFound {
title: string
content: string
button: string
}
export interface ErrorBoundary {
title: string
contents: string[]
}
export interface DeregisterSelect {
title: string
info: string
input: InputField
buttons: DeregisterSelectButtons
}
export interface Deregister {
titles: ProcessTitles
info: ProcessTitles
buttons: DeregisterButtons
success: string
error: Errors
}
export interface DeregisterOverviewSubTitles {
history: string
}
export interface DeregisterOverviewButtons {
deregister: string
}
export interface ReyclingFundOverviewSubTitles {
deregistered: string
}
export interface ReyclingFundOverviewButtons {
export: string
}
export interface CompanyInfoSubTitles {
location: string
}
export interface RecyclingCompaniesSubTitles {
companies: string
}
export interface DeregisterOverviewButtons {
add: string
delete: string
edit: string
}
export interface DeregisterSelectButtons {
cancel: string
continue: string
}
export interface DeregisterButtons {
back: string
confirm: string
}
export interface DeregisterSidenav {
deregister: string
companyInfo: string
}
export interface RecyclingFundSidenav {
title: string
recycled: string
companies: string
}
export interface InputField {
label: string
placeholder: string
errors: InputErrors
}
export interface Routes {
home: HomeRoutes
myCars: string
recycleVehicle: RecycleVehicleRoutes
deregisterVehicle: DeregisterVehicleRoutes
recycledVehicles: string
recyclingCompanies: RecyclingCompaniesRoutes
companyInfo: CompanyInfoRoutes
}
export interface HomeRoutes {
citizen: string
recyclingCompany: string
recyclingFund: string
developer: string
}
export interface RecycleVehicleRoutes {
baseRoute: string
confirm: string
handover: string
completed: string
}
export interface DeregisterVehicleRoutes {
baseRoute: string
select: string
deregister: string
}
export interface CompanyInfoRoutes {
baseRoute: string
add: string
edit: string
}
export interface RecyclingCompaniesRoutes {
baseRoute: string
add: string
edit: string
}
// Converts JSON strings to/from your types
// and asserts the results of JSON.parse at runtime
export class Convert {
public static toTranslation(json: string): Translation {
return cast(JSON.parse(json), r('Translation'))
}
public static translationToJson(value: Translation): string {
return JSON.stringify(uncast(value, r('Translation')), null, 2)
}
}
function invalidValue(typ: any, val: any): never {
throw Error(
`Invalid value ${JSON.stringify(val)} for type ${JSON.stringify(typ)}`,
)
}
function jsonToJSProps(typ: any): any {
if (typ.jsonToJS === undefined) {
const map: any = {}
typ.props.forEach((p: any) => (map[p.json] = { key: p.js, typ: p.typ }))
typ.jsonToJS = map
}
return typ.jsonToJS
}
function jsToJSONProps(typ: any): any {
if (typ.jsToJSON === undefined) {
const map: any = {}
typ.props.forEach((p: any) => (map[p.js] = { key: p.json, typ: p.typ }))
typ.jsToJSON = map
}
return typ.jsToJSON
}
function transform(val: any, typ: any, getProps: any): any {
function transformPrimitive(typ: string, val: any): any {
if (typeof typ === typeof val) return val
return invalidValue(typ, val)
}
function transformUnion(typs: any[], val: any): any {
// val must validate against one typ in typs
const l = typs.length
for (let i = 0; i < l; i++) {
const typ = typs[i]
try {
return transform(val, typ, getProps)
} catch (_) {}
}
return invalidValue(typs, val)
}
function transformEnum(cases: string[], val: any): any {
if (cases.indexOf(val) !== -1) return val
return invalidValue(cases, val)
}
function transformArray(typ: any, val: any): any {
// val must be an array with no invalid elements
if (!Array.isArray(val)) return invalidValue('array', val)
return val.map((el) => transform(el, typ, getProps))
}
function transformDate(val: any): any {
if (val === null) {
return null
}
const d = new Date(val)
if (isNaN(d.valueOf())) {
return invalidValue('Date', val)
}
return d
}
function transformObject(
props: { [k: string]: any },
additional: any,
val: any,
): any {
if (val === null || typeof val !== 'object' || Array.isArray(val)) {
return invalidValue('object', val)
}
const result: any = {}
Object.getOwnPropertyNames(props).forEach((key) => {
const prop = props[key]
const v = Object.prototype.hasOwnProperty.call(val, key)
? val[key]
: undefined
result[prop.key] = transform(v, prop.typ, getProps)
})
Object.getOwnPropertyNames(val).forEach((key) => {
if (!Object.prototype.hasOwnProperty.call(props, key)) {
result[key] = transform(val[key], additional, getProps)
}
})
return result
}
if (typ === 'any') return val
if (typ === null) {
if (val === null) return val
return invalidValue(typ, val)
}
if (typ === false) return invalidValue(typ, val)
while (typeof typ === 'object' && typ.ref !== undefined) {
typ = typeMap[typ.ref]
}
if (Array.isArray(typ)) return transformEnum(typ, val)
if (typeof typ === 'object') {
return typ.hasOwnProperty('unionMembers')
? transformUnion(typ.unionMembers, val)
: typ.hasOwnProperty('arrayItems')
? transformArray(typ.arrayItems, val)
: typ.hasOwnProperty('props')
? transformObject(getProps(typ), typ.additional, val)
: invalidValue(typ, val)
}
// Numbers can be parsed by Date but shouldn't be.
if (typ === Date && typeof val !== 'number') return transformDate(val)
return transformPrimitive(typ, val)
}
function cast<T>(val: any, typ: any): T {
return transform(val, typ, jsonToJSProps)
}
function uncast<T>(val: T, typ: any): any {
return transform(val, typ, jsToJSONProps)
}
function a(typ: any) {
return { arrayItems: typ }
}
function u(...typs: any[]) {
return { unionMembers: typs }
}
function o(props: any[], additional: any) {
return { props, additional }
}
function m(additional: any) {
return { props: [], additional }
}
function r(name: string) {
return { ref: name }
} | the_stack |
import GraphQLJSON from 'graphql-type-json';
import moment from 'moment';
import * as _ from 'underscore';
import SimpleSchema from 'simpl-schema';
import { schemaDefaultValue } from '../../collectionUtils';
import { makeEditable } from '../../editor/make_editable';
import { forumTypeSetting } from '../../instanceSettings';
import { getWithLoader } from '../../loaders';
import { accessFilterMultiple, accessFilterSingle, addFieldsDict, arrayOfForeignKeysField, denormalizedCountOfReferences, denormalizedField, foreignKeyField, googleLocationToMongoLocation, resolverOnlyField } from '../../utils/schemaUtils';
import { Utils } from '../../vulcan-lib';
import { localGroupTypeFormOptions } from '../localgroups/groupTypes';
import { userOwns } from '../../vulcan-users/permissions';
import { userCanCommentLock, userCanModeratePost, userIsSharedOn } from '../users/helpers';
import { Posts } from './collection';
import { sequenceGetNextPostID, sequenceGetPrevPostID, sequenceContainsPost } from '../sequences/helpers';
import { postCanEditHideCommentKarma } from './helpers';
import { captureException } from '@sentry/core';
import { formGroups } from './formGroups';
import { userOverNKarmaFunc } from "../../vulcan-users";
const MINIMUM_COAUTHOR_KARMA = 10;
export const EVENT_TYPES = [
{value: 'presentation', label: 'Presentation'},
{value: 'discussion', label: 'Discussion'},
{value: 'workshop', label: 'Workshop'},
{value: 'social', label: 'Social'},
{value: 'coworking', label: 'Coworking'},
{value: 'course', label: 'Course'},
{value: 'conference', label: 'Conference'},
]
const isEAForum = forumTypeSetting.get() === 'EAForum'
function eaFrontpageDate (document: Partial<DbPost>) {
if (document.isEvent || !document.submitToFrontpage) {
return undefined
}
return new Date()
}
const frontpageDefault = isEAForum ?
eaFrontpageDate :
undefined
const userHasModerationGuidelines = (currentUser: DbUser|null): boolean => {
return !!(currentUser && ((currentUser.moderationGuidelines && currentUser.moderationGuidelines.html) || currentUser.moderationStyle))
}
addFieldsDict(Posts, {
// Legacy: Boolean used to indicate that post was imported from old LW database
legacy: {
type: Boolean,
optional: true,
hidden: false,
defaultValue: false,
viewableBy: ['guests'],
editableBy: ['admins'],
insertableBy: ['admins'],
control: "checkbox",
order: 12,
group: formGroups.adminOptions,
},
// Legacy ID: ID used in the original LessWrong database
legacyId: {
type: String,
optional: true,
hidden: true,
viewableBy: ['guests'],
editableBy: ['members'],
insertableBy: ['members'],
},
// Legacy Spam: True if the original post in the legacy LW database had this post
// marked as spam
legacySpam: {
type: Boolean,
optional: true,
defaultValue: false,
hidden: true,
viewableBy: ['guests'],
editableBy: ['members'],
insertableBy: ['members'],
},
// Feed Id: If this post was automatically generated by an integrated RSS feed
// then this field will have the ID of the relevant feed
feedId: {
...foreignKeyField({
idFieldName: "feedId",
resolverName: "feed",
collectionName: "RSSFeeds",
type: "RSSFeed",
nullable: true,
}),
optional: true,
viewableBy: ['guests'],
editableBy: ['admins'],
insertableBy: ['admins'],
group: formGroups.adminOptions,
},
// Feed Link: If this post was automatically generated by an integrated RSS feed
// then this field will have the link to the original blogpost it was posted from
feedLink: {
type: String,
optional: true,
viewableBy: ['guests'],
editableBy: ['admins'],
insertableBy: ['admins'],
group: formGroups.adminOptions
},
// lastVisitedAt: If the user is logged in and has viewed this post, the date
// they last viewed it. Otherwise, null.
lastVisitedAt: resolverOnlyField({
type: Date,
viewableBy: ['guests'],
resolver: async (post: DbPost, args: void, context: ResolverContext) => {
const { ReadStatuses, currentUser } = context;
if (!currentUser) return null;
const readStatus = await getWithLoader(context, ReadStatuses,
`readStatuses`,
{ userId: currentUser._id },
'postId', post._id
);
if (!readStatus.length) return null;
return readStatus[0].lastUpdated;
}
}),
isRead: resolverOnlyField({
type: Boolean,
viewableBy: ['guests'],
resolver: async (post: DbPost, args: void, context: ResolverContext) => {
const { ReadStatuses, currentUser } = context;
if (!currentUser) return false;
const readStatus = await getWithLoader(context, ReadStatuses,
`readStatuses`,
{ userId: currentUser._id },
'postId', post._id
);
if (!readStatus.length) return false;
return readStatus[0].isRead;
}
}),
// curatedDate: Date at which the post was promoted to curated (null or false
// if it never has been promoted to curated)
curatedDate: {
type: Date,
control: 'datetime',
optional: true,
viewableBy: ['guests'],
insertableBy: ['sunshineRegiment', 'admins'],
editableBy: ['sunshineRegiment', 'admins'],
group: formGroups.adminOptions,
},
// metaDate: Date at which the post was marked as meta (null or false if it
// never has been marked as meta)
metaDate: {
type: Date,
control: 'datetime',
optional: true,
viewableBy: ['guests'],
insertableBy: ['sunshineRegiment', 'admins'],
editableBy: ['sunshineRegiment', 'admins'],
group: formGroups.adminOptions,
},
suggestForCuratedUserIds: {
type: Array,
viewableBy: ['members'],
insertableBy: ['sunshineRegiment', 'admins'],
editableBy: ['sunshineRegiment', 'admins'],
optional: true,
label: "Suggested for Curated by",
control: "UsersListEditor",
group: formGroups.adminOptions,
resolveAs: {
fieldName: 'suggestForCuratedUsernames',
type: 'String',
resolver: async (post: DbPost, args: void, context: ResolverContext): Promise<string|null> => {
// TODO - Turn this into a proper resolve field.
// Ran into weird issue trying to get this to be a proper "users"
// resolve field. Wasn't sure it actually needed to be anyway,
// did a hacky thing.
const users = await Promise.all(_.map(post.suggestForCuratedUserIds,
async userId => {
const user = await context.loaders.Users.load(userId)
return user.displayName;
}
))
if (users.length) {
return users.join(", ")
} else {
return null
}
},
addOriginalField: true,
}
},
'suggestForCuratedUserIds.$': {
type: String,
foreignKey: 'Users',
optional: true,
},
// frontpageDate: Date at which the post was promoted to frontpage (null or
// false if it never has been promoted to frontpage)
frontpageDate: {
type: Date,
control: 'datetime',
viewableBy: ['guests'],
editableBy: ['members'],
insertableBy: ['members'],
onInsert: frontpageDefault,
optional: true,
hidden: true,
},
collectionTitle: {
type: String,
optional: true,
viewableBy: ['guests'],
editableBy: ['admins', 'sunshineRegiment'],
insertableBy: ['admins', 'sunshineRegiment'],
group: formGroups.canonicalSequence,
},
coauthorStatuses: {
type: Array,
resolveAs: {
fieldName: 'coauthors',
type: '[User!]!',
resolver: async (post: DbPost, args: void, context: ResolverContext) => {
const loader = context.loaders['Users'];
const resolvedDocs = await loader.loadMany(
post.coauthorStatuses?.filter(({ confirmed }) => confirmed).map(({ userId }) => userId) || []
);
return await accessFilterMultiple(context.currentUser, context['Users'], resolvedDocs, context);
},
addOriginalField: true,
},
viewableBy: ['guests'],
editableBy: ['sunshineRegiment', 'admins', userOverNKarmaFunc(MINIMUM_COAUTHOR_KARMA)],
insertableBy: ['sunshineRegiment', 'admins', userOverNKarmaFunc(MINIMUM_COAUTHOR_KARMA)],
optional: true,
label: "Co-Authors",
control: "CoauthorsListEditor",
group: formGroups.advancedOptions,
},
'coauthorStatuses.$': {
type: new SimpleSchema({
userId: String,
confirmed: Boolean,
requested: Boolean,
}),
optional: true,
},
hasCoauthorPermission: {
type: Boolean,
viewableBy: ['guests'],
editableBy: ['members'],
insertableBy: ['members'],
optional: true,
hidden: true,
...schemaDefaultValue(false),
},
// Cloudinary image id for an image that will be used as the OpenGraph image
socialPreviewImageId: {
type: String,
optional: true,
label: "Social Preview Image",
viewableBy: ['guests'],
editableBy: ['sunshineRegiment', 'admins'],
insertableBy: ['sunshineRegiment', 'admins'],
control: "ImageUpload",
group: formGroups.advancedOptions,
},
// Autoset OpenGraph image, derived from the first post image in a callback
socialPreviewImageAutoUrl: {
type: String,
optional: true,
hidden: true,
label: "Social Preview Image Auto-generated URL",
viewableBy: ['guests'],
editableBy: ['members'],
insertableBy: ['members'],
},
canonicalSequenceId: {
...foreignKeyField({
idFieldName: "canonicalSequenceId",
resolverName: "canonicalSequence",
collectionName: "Sequences",
type: "Sequence",
nullable: true,
}),
optional: true,
viewableBy: ['guests'],
editableBy: ['admins', 'sunshineRegiment'],
insertableBy: ['admins', 'sunshineRegiment'],
group: formGroups.canonicalSequence,
hidden: false,
control: "text",
},
canonicalCollectionSlug: {
type: String,
foreignKey: {
collection: 'Collections',
field: 'slug'
},
optional: true,
viewableBy: ['guests'],
editableBy: ['admins', 'sunshineRegiment'],
insertableBy: ['admins', 'sunshineRegiment'],
hidden: false,
control: "text",
group: formGroups.canonicalSequence,
resolveAs: {
fieldName: 'canonicalCollection',
addOriginalField: true,
type: "Collection",
// TODO: Make sure we run proper access checks on this. Using slugs means it doesn't
// work out of the box with the id-resolver generators
resolver: async (post: DbPost, args: void, context: ResolverContext): Promise<DbCollection|null> => {
if (!post.canonicalCollectionSlug) return null;
const collection = await context.Collections.findOne({slug: post.canonicalCollectionSlug})
return await accessFilterSingle(context.currentUser, context.Collections, collection, context);
}
},
},
canonicalBookId: {
...foreignKeyField({
idFieldName: "canonicalBookId",
resolverName: "canonicalBook",
collectionName: "Books",
type: "Book",
nullable: true,
}),
optional: true,
viewableBy: ['guests'],
editableBy: ['admins', 'sunshineRegiment'],
insertableBy: ['admins', 'sunshineRegiment'],
group: formGroups.canonicalSequence,
hidden: false,
control: "text",
},
canonicalNextPostSlug: {
type: String,
foreignKey: {
collection: "Posts",
field: 'slug',
},
optional: true,
viewableBy: ['guests'],
editableBy: ['admins', 'sunshineRegiment'],
insertableBy: ['admins', 'sunshineRegiment'],
group: formGroups.canonicalSequence,
hidden: false,
control: "text"
},
canonicalPrevPostSlug: {
type: String,
foreignKey: {
collection: "Posts",
field: 'slug',
},
optional: true,
viewableBy: ['guests'],
editableBy: ['admins', 'sunshineRegiment'],
insertableBy: ['admins', 'sunshineRegiment'],
group: formGroups.canonicalSequence,
hidden: false,
control: "text"
},
// The next post. If a sequenceId is provided, that sequence must contain this
// post, and this returns the next post after this one in that sequence. If
// no sequenceId is provided, uses this post's canonical sequence.
nextPost: resolverOnlyField({
type: "Post",
graphQLtype: "Post",
viewableBy: ['guests'],
graphqlArguments: 'sequenceId: String',
resolver: async (post: DbPost, args: {sequenceId: string}, context: ResolverContext) => {
const { sequenceId } = args;
const { currentUser, Posts } = context;
if (sequenceId) {
const nextPostID = await sequenceGetNextPostID(sequenceId, post._id, context);
if (nextPostID) {
const nextPost = await context.loaders.Posts.load(nextPostID);
const nextPostFiltered = await accessFilterSingle(currentUser, Posts, nextPost, context);
if (nextPostFiltered)
return nextPostFiltered;
}
}
if(post.canonicalSequenceId) {
const nextPostID = await sequenceGetNextPostID(post.canonicalSequenceId, post._id, context);
if (nextPostID) {
const nextPost = await context.loaders.Posts.load(nextPostID);
const nextPostFiltered = await accessFilterSingle(currentUser, Posts, nextPost, context);
if (nextPostFiltered)
return nextPostFiltered;
}
}
if (post.canonicalNextPostSlug) {
const nextPost = await Posts.findOne({ slug: post.canonicalNextPostSlug });
const nextPostFiltered = await accessFilterSingle(currentUser, Posts, nextPost, context);
if (nextPostFiltered)
return nextPostFiltered;
}
return null;
}
}),
// The previous post. If a sequenceId is provided, that sequence must contain
// this post, and this returns the post before this one in that sequence.
// If no sequenceId is provided, uses this post's canonical sequence.
prevPost: resolverOnlyField({
type: "Post",
graphQLtype: "Post",
viewableBy: ['guests'],
graphqlArguments: 'sequenceId: String',
resolver: async (post: DbPost, args: {sequenceId: string}, context: ResolverContext) => {
const { sequenceId } = args;
const { currentUser, Posts } = context;
if (sequenceId) {
const prevPostID = await sequenceGetPrevPostID(sequenceId, post._id, context);
if (prevPostID) {
const prevPost = await context.loaders.Posts.load(prevPostID);
const prevPostFiltered = await accessFilterSingle(currentUser, Posts, prevPost, context);
if (prevPostFiltered) {
return prevPostFiltered;
}
}
}
if(post.canonicalSequenceId) {
const prevPostID = await sequenceGetPrevPostID(post.canonicalSequenceId, post._id, context);
if (prevPostID) {
const prevPost = await context.loaders.Posts.load(prevPostID);
const prevPostFiltered = await accessFilterSingle(currentUser, Posts, prevPost, context);
if (prevPostFiltered) {
return prevPostFiltered;
}
}
}
if (post.canonicalPrevPostSlug) {
const prevPost = await Posts.findOne({ slug: post.canonicalPrevPostSlug });
const prevPostFiltered = await accessFilterSingle(currentUser, Posts, prevPost, context);
if (prevPostFiltered) {
return prevPostFiltered;
}
}
return null;
}
}),
// A sequence this post is part of. Takes an optional sequenceId; if the
// sequenceId is given and it contains this post, returns that sequence.
// Otherwise, if this post has a canonical sequence, return that. If no
// sequence ID is given and there is no canonical sequence for this post,
// returns null.
sequence: resolverOnlyField({
type: "Sequence",
graphQLtype: "Sequence",
viewableBy: ['guests'],
graphqlArguments: 'sequenceId: String',
resolver: async (post: DbPost, args: {sequenceId: string}, context: ResolverContext) => {
const { sequenceId } = args;
const { currentUser } = context;
let sequence: DbSequence|null = null;
if (sequenceId && await sequenceContainsPost(sequenceId, post._id, context)) {
sequence = await context.loaders.Sequences.load(sequenceId);
} else if (post.canonicalSequenceId) {
sequence = await context.loaders.Sequences.load(post.canonicalSequenceId);
}
return await accessFilterSingle(currentUser, context.Sequences, sequence, context);
}
}),
// unlisted: If true, the post is not featured on the frontpage and is not
// featured on the user page. Only accessible via it's ID
unlisted: {
type: Boolean,
optional: true,
viewableBy: ['guests'],
editableBy: ['admins', 'sunshineRegiment'],
insertableBy: ['admins', 'sunshineRegiment'],
label: "Make only accessible via link",
control: "checkbox",
order: 11,
group: formGroups.adminOptions,
...schemaDefaultValue(false),
},
// disableRecommendation: If true, this post will never appear as a
// recommended post (but will still appear in all other places, ie on its
// author's profile, in archives, etc).
// Use for things that lose their relevance with age, like announcements, or
// for things that aged poorly, like results that didn't replicate.
disableRecommendation: {
type: Boolean,
optional: true,
viewableBy: ['guests'],
editableBy: ['admins', 'sunshineRegiment'],
insertableBy: ['admins', 'sunshineRegiment'],
label: "Exclude from Recommendations",
control: "checkbox",
order: 12,
group: formGroups.adminOptions,
...schemaDefaultValue(false),
},
// defaultRecommendation: If true, always include this post in the recommendations
defaultRecommendation: {
type: Boolean,
optional: true,
viewableBy: ['guests'],
editableBy: ['admins', 'sunshineRegiment'],
insertableBy: ['admins', 'sunshineRegiment'],
label: "Include in default recommendations",
control: "checkbox",
order: 13,
group: formGroups.adminOptions,
...schemaDefaultValue(false),
},
// Drafts
draft: {
label: 'Save to Drafts',
type: Boolean,
optional: true,
...schemaDefaultValue(false),
viewableBy: ['members'],
insertableBy: ['members'],
editableBy: ['members', 'sunshineRegiment', 'admins'],
hidden: true,
},
// meta: The post is published to the meta section of the page
meta: {
type: Boolean,
optional: true,
viewableBy: ['guests'],
editableBy: ['members', 'sunshineRegiment', 'admins'],
insertableBy: ['members'],
hidden: true,
label: "Publish to meta",
control: "checkbox",
...schemaDefaultValue(false)
},
hideFrontpageComments: {
type: Boolean,
optional: true,
viewableBy: ['guests'],
editableBy: ['admins'],
insertableBy: ['admins'],
control: 'checkbox',
group: formGroups.moderationGroup,
...schemaDefaultValue(false),
},
// maxBaseScore: Highest baseScore this post ever had, used for RSS feed generation
maxBaseScore: {
type: Number,
optional: true,
viewableBy: ['guests'],
hidden: true,
onInsert: (document) => document.baseScore || 0,
},
// The timestamp when the post's maxBaseScore first exceeded 2
scoreExceeded2Date: {
type: Date,
optional: true,
viewableBy: ['guests'],
onInsert: document => document.baseScore >= 2 ? new Date() : null
},
// The timestamp when the post's maxBaseScore first exceeded 30
scoreExceeded30Date: {
type: Date,
optional: true,
viewableBy: ['guests'],
onInsert: document => document.baseScore >= 30 ? new Date() : null
},
// The timestamp when the post's maxBaseScore first exceeded 45
scoreExceeded45Date: {
type: Date,
optional: true,
viewableBy: ['guests'],
onInsert: document => document.baseScore >= 45 ? new Date() : null
},
// The timestamp when the post's maxBaseScore first exceeded 75
scoreExceeded75Date: {
type: Date,
optional: true,
viewableBy: ['guests'],
onInsert: document => document.baseScore >= 75 ? new Date() : null
},
// The timestamp when the post's maxBaseScore first exceeded 125
scoreExceeded125Date: {
type: Date,
optional: true,
viewableBy: ['guests'],
onInsert: document => document.baseScore >= 125 ? new Date() : null
},
// The timestamp when the post's maxBaseScore first exceeded 200
scoreExceeded200Date: {
type: Date,
optional: true,
viewableBy: ['guests'],
onInsert: document => document.baseScore >= 200 ? new Date() : null
},
bannedUserIds: {
type: Array,
viewableBy: ['guests'],
group: formGroups.moderationGroup,
insertableBy: [userCanModeratePost],
editableBy: ['sunshineRegiment', 'admins'],
hidden: true,
optional: true,
// label: "Users banned from commenting on this post",
// control: "UsersListEditor",
},
'bannedUserIds.$': {
type: String,
foreignKey: "Users",
optional: true
},
commentsLocked: {
type: Boolean,
viewableBy: ['guests'],
group: formGroups.moderationGroup,
insertableBy: (currentUser: DbUser|null) => userCanCommentLock(currentUser, null),
editableBy: (currentUser: DbUser|null, document: DbPost) => userCanCommentLock(currentUser, document),
optional: true,
control: "checkbox",
},
// Event specific fields:
/////////////////////////////////////////////////////////////////////////////
organizerIds: {
...arrayOfForeignKeysField({
idFieldName: "organizerIds",
resolverName: "organizers",
collectionName: "Users",
type: "User"
}),
viewableBy: ['guests'],
insertableBy: ['members'],
editableBy: ['members', 'sunshineRegiment', 'admins'],
optional: true,
hidden: true,
control: "UsersListEditor",
group: formGroups.event,
},
'organizerIds.$': {
type: String,
foreignKey: "Users",
optional: true,
},
groupId: {
...foreignKeyField({
idFieldName: "groupId",
resolverName: "group",
collectionName: "Localgroups",
type: "Localgroup",
nullable: true,
}),
viewableBy: ['guests'],
editableBy: ['members', 'sunshineRegiment', 'admins'],
insertableBy: ['members'],
optional: true,
order: 1,
control: 'SelectLocalgroup',
label: 'Group',
group: formGroups.event,
hidden: (props) => !props.eventForm,
},
eventType: {
type: String,
viewableBy: ['guests'],
insertableBy: ['members'],
editableBy: ['members'],
hidden: (props) => !props.eventForm,
control: 'select',
group: formGroups.event,
optional: true,
order: 2,
label: 'Event Format',
form: {
options: EVENT_TYPES
},
},
isEvent: {
type: Boolean,
hidden: true,
group: formGroups.event,
viewableBy: ['guests'],
editableBy: ['admins', 'sunshineRegiment'],
insertableBy: ['members'],
optional: true,
...schemaDefaultValue(false),
onCreate: ({newDocument}: {newDocument: DbInsertion<DbPost>}) => {
// HACK: This replaces the `onCreate` that normally comes with
// `schemaDefaultValue`. In addition to enforcing that the field must
// be present (not undefined), it also enforces that it cannot be null.
// There is a bug where GreaterWrong somehow submits posts with isEvent
// set to null (instead of false), which causes some post-views to filter
// it out (because they filter for non-events using isEvent:false which
// does not match null).
if (newDocument.isEvent===undefined || newDocument.isEvent===null)
return false;
else
return undefined;
}
},
reviewedByUserId: {
...foreignKeyField({
idFieldName: "reviewedByUserId",
resolverName: "reviewedByUser",
collectionName: "Users",
type: "User",
nullable: true,
}),
optional: true,
viewableBy: ['guests'],
editableBy: ['sunshineRegiment', 'admins'],
insertableBy: ['sunshineRegiment', 'admins'],
hidden: true,
},
reviewForCuratedUserId: {
type: String,
foreignKey: "Users",
optional: true,
viewableBy: ['guests'],
editableBy: ['sunshineRegiment', 'admins'],
insertableBy: ['sunshineRegiment', 'admins'],
group: formGroups.adminOptions,
label: "Curated Review UserId"
},
startTime: {
type: Date,
hidden: (props) => !props.eventForm,
viewableBy: ['guests'],
editableBy: ['members', 'sunshineRegiment', 'admins'],
insertableBy: ['members'],
control: 'datetime',
label: "Start Time",
group: formGroups.event,
optional: true,
nullable: true,
tooltip: 'For courses/programs, this is the application deadline.'
},
localStartTime: {
type: Date,
viewableBy: ['guests'],
},
endTime: {
type: Date,
hidden: (props) => !props.eventForm || props.document.eventType === 'course',
viewableBy: ['guests'],
editableBy: ['members', 'sunshineRegiment', 'admins'],
insertableBy: ['members'],
control: 'datetime',
label: "End Time",
group: formGroups.event,
optional: true,
nullable: true,
},
localEndTime: {
type: Date,
viewableBy: ['guests'],
},
eventRegistrationLink: {
type: String,
hidden: (props) => !props.eventForm,
viewableBy: ['guests'],
insertableBy: ['members'],
editableBy: ['members'],
label: "Event Registration Link",
control: "MuiTextField",
optional: true,
group: formGroups.event,
regEx: SimpleSchema.RegEx.Url,
tooltip: 'https://...'
},
joinEventLink: {
type: String,
hidden: (props) => !props.eventForm,
viewableBy: ['guests'],
insertableBy: ['members'],
editableBy: ['members'],
label: "Join Online Event Link",
control: "MuiTextField",
optional: true,
group: formGroups.event,
regEx: SimpleSchema.RegEx.Url,
tooltip: 'https://...'
},
onlineEvent: {
type: Boolean,
hidden: (props) => !props.eventForm,
viewableBy: ['guests'],
editableBy: ['members', 'sunshineRegiment', 'admins'],
insertableBy: ['members'],
optional: true,
group: formGroups.event,
order: 0,
...schemaDefaultValue(false),
},
globalEvent: {
type: Boolean,
hidden: (props) => !props.eventForm,
viewableBy: ['guests'],
editableBy: ['members', 'sunshineRegiment', 'admins'],
insertableBy: ['members'],
optional: true,
group: formGroups.event,
label: "This event is intended for a global audience",
tooltip: 'By default, events are only advertised to people who are located nearby (for both in-person and online events). Check this to advertise it people located anywhere.',
...schemaDefaultValue(false),
},
mongoLocation: {
type: Object,
viewableBy: ['guests'],
hidden: true,
blackbox: true,
optional: true,
...denormalizedField({
needsUpdate: data => ('googleLocation' in data),
getValue: async (post) => {
if (post.googleLocation) return googleLocationToMongoLocation(post.googleLocation)
return null
}
}),
},
googleLocation: {
type: Object,
form: {
stringVersionFieldName: "location",
},
hidden: (props) => !props.eventForm,
viewableBy: ['guests'],
insertableBy: ['members'],
editableBy: ['members', 'sunshineRegiment', 'admins'],
label: "Event Location",
control: 'LocationFormComponent',
blackbox: true,
group: formGroups.event,
optional: true
},
location: {
type: String,
viewableBy: ['guests'],
editableBy: ['members', 'sunshineRegiment', 'admins'],
insertableBy: ['members'],
hidden: true,
optional: true
},
contactInfo: {
type: String,
hidden: (props) => !props.eventForm,
viewableBy: ['guests'],
insertableBy: ['members'],
editableBy: ['members'],
label: "Contact Info",
control: "MuiTextField",
optional: true,
group: formGroups.event,
},
facebookLink: {
type: String,
hidden: (props) => !props.eventForm,
viewableBy: ['guests'],
insertableBy: ['members'],
editableBy: ['members', 'sunshineRegiment', 'admins'],
label: "Facebook Event",
control: "MuiTextField",
optional: true,
group: formGroups.event,
regEx: SimpleSchema.RegEx.Url,
tooltip: 'https://www.facebook.com/events/...'
},
meetupLink: {
type: String,
hidden: (props) => !props.eventForm,
viewableBy: ['guests'],
insertableBy: ['members'],
editableBy: ['members', 'sunshineRegiment', 'admins'],
label: "Meetup.com Event",
control: "MuiTextField",
optional: true,
group: formGroups.event,
regEx: SimpleSchema.RegEx.Url,
tooltip: 'https://www.meetup.com/...'
},
website: {
type: String,
hidden: (props) => !props.eventForm,
viewableBy: ['guests'],
insertableBy: ['members'],
editableBy: ['members', 'sunshineRegiment', 'admins'],
control: "MuiTextField",
optional: true,
group: formGroups.event,
regEx: SimpleSchema.RegEx.Url,
tooltip: 'https://...'
},
eventImageId: {
type: String,
optional: true,
hidden: (props) => !props.eventForm || !isEAForum,
label: "Event Image",
viewableBy: ['guests'],
insertableBy: ['members'],
editableBy: ['members'],
control: "ImageUpload",
group: formGroups.event,
tooltip: "Recommend 1920x1080 px, 16:9 aspect ratio (same as Facebook)"
},
types: {
type: Array,
viewableBy: ['guests'],
insertableBy: ['members'],
editableBy: ['members', 'sunshineRegiment', 'admins'],
hidden: (props) => isEAForum || !props.eventForm,
control: 'MultiSelectButtons',
label: "Group Type:",
group: formGroups.event,
optional: true,
form: {
options: localGroupTypeFormOptions
},
},
'types.$': {
type: String,
optional: true,
},
metaSticky: {
order:10,
type: Boolean,
optional: true,
label: "Sticky (Meta)",
...schemaDefaultValue(false),
group: formGroups.adminOptions,
viewableBy: ['guests'],
editableBy: ['admins'],
insertableBy: ['admins'],
control: 'checkbox',
onInsert: (post) => {
if(!post.metaSticky) {
return false;
}
},
onEdit: (modifier, post) => {
if (!modifier.$set.metaSticky) {
return false;
}
}
},
sharingSettings: {
type: Object,
order: 16,
viewableBy: [userOwns, userIsSharedOn, 'admins'],
editableBy: [userOwns, 'admins'],
insertableBy: ['members'],
optional: true,
label: "Sharing Settings",
group: formGroups.title,
blackbox: true,
hidden: true,
},
shareWithUsers: {
type: Array,
order: 15,
viewableBy: ['guests'],
insertableBy: ['members'],
editableBy: ['members', 'sunshineRegiment', 'admins'],
optional: true,
control: "UsersListEditor",
label: "Share draft with users",
group: formGroups.options
},
'shareWithUsers.$': {
type: String,
foreignKey: "Users",
optional: true
},
commentSortOrder: {
type: String,
viewableBy: ['guests'],
insertableBy: ['admins'],
editableBy: ['admins'],
optional: true,
group: formGroups.adminOptions,
},
// hideAuthor: Post stays online, but doesn't show on your user profile anymore, and doesn't
// link back to your account
hideAuthor: {
type: Boolean,
viewableBy: ['guests'],
insertableBy: ['admins'],
editableBy: ['admins'],
optional: true,
group: formGroups.adminOptions,
...schemaDefaultValue(false),
},
tableOfContents: resolverOnlyField({
type: Object,
viewableBy: ['guests'],
graphQLtype: GraphQLJSON,
resolver: async (document: DbPost, args: void, context: ResolverContext) => {
try {
return await Utils.getToCforPost({document, version: null, context});
} catch(e) {
captureException(e);
return null;
}
},
}),
tableOfContentsRevision: resolverOnlyField({
type: Object,
viewableBy: ['guests'],
graphQLtype: GraphQLJSON,
graphqlArguments: 'version: String',
resolver: async (document: DbPost, args: {version:string}, context: ResolverContext) => {
const { version=null } = args;
try {
return await Utils.getToCforPost({document, version, context});
} catch(e) {
captureException(e);
return null;
}
},
}),
// GraphQL only field that resolves based on whether the current user has closed
// this posts author's moderation guidelines in the past
showModerationGuidelines: {
type: Boolean,
optional: true,
canRead: ['guests'],
resolveAs: {
type: 'Boolean',
resolver: async (post: DbPost, args: void, context: ResolverContext): Promise<boolean> => {
const { LWEvents, currentUser } = context;
if(currentUser){
const query = {
name:'toggled-user-moderation-guidelines',
documentId: post.userId,
userId: currentUser._id
}
const sort = {sort:{createdAt:-1}}
const event = await LWEvents.findOne(query, sort);
const author = await context.Users.findOne({_id: post.userId});
if (event) {
return !!(event.properties && event.properties.targetState)
} else {
return !!(author?.collapseModerationGuidelines ? false : ((post.moderationGuidelines && post.moderationGuidelines.html) || post.moderationStyle))
}
} else {
return false
}
},
addOriginalField: false
}
},
moderationStyle: {
type: String,
optional: true,
control: "select",
group: formGroups.moderationGroup,
label: "Style",
viewableBy: ['guests'],
editableBy: ['members', 'sunshineRegiment', 'admins'],
insertableBy: ['members', 'sunshineRegiment', 'admins'],
blackbox: true,
order: 55,
form: {
options: function () { // options for the select form control
return [
{value: "", label: "No Moderation"},
{value: "easy-going", label: "Easy Going - I just delete obvious spam and trolling."},
{value: "norm-enforcing", label: "Norm Enforcing - I try to enforce particular rules (see below)"},
{value: "reign-of-terror", label: "Reign of Terror - I delete anything I judge to be annoying or counterproductive"},
];
}
},
},
// On a post, do not show comment karma
hideCommentKarma: {
type: Boolean,
optional: true,
group: formGroups.moderationGroup,
viewableBy: ['guests'],
insertableBy: ['admins', postCanEditHideCommentKarma],
editableBy: ['admins', postCanEditHideCommentKarma],
hidden: !isEAForum,
denormalized: true,
...schemaDefaultValue(false),
},
commentCount: {
type: Number,
optional: true,
defaultValue: 0,
...denormalizedCountOfReferences({
fieldName: "commentCount",
collectionName: "Posts",
foreignCollectionName: "Comments",
foreignTypeName: "comment",
foreignFieldName: "postId",
filterFn: comment => !comment.deleted
}),
canRead: ['guests'],
},
recentComments: resolverOnlyField({
type: Array,
graphQLtype: "[Comment]",
viewableBy: ['guests'],
graphqlArguments: 'commentsLimit: Int, maxAgeHours: Int, af: Boolean',
resolver: async (post: DbPost, args: {commentsLimit?: number, maxAgeHours?: number, af?: boolean}, context: ResolverContext) => {
const { commentsLimit=5, maxAgeHours=18, af=false } = args;
const { currentUser, Comments } = context;
const timeCutoff = moment(post.lastCommentedAt).subtract(maxAgeHours, 'hours').toDate();
const comments = await Comments.find({
...Comments.defaultView({}).selector,
postId: post._id,
score: {$gt:0},
deletedPublic: false,
postedAt: {$gt: timeCutoff},
...(af ? {af:true} : {}),
}, {
limit: commentsLimit,
sort: {postedAt:-1}
}).fetch();
return await accessFilterMultiple(currentUser, Comments, comments, context);
}
}),
'recentComments.$': {
type: Object,
foreignKey: 'Comments',
},
});
makeEditable({
collection: Posts,
options: {
formGroup: formGroups.content,
order: 25,
pingbacks: true,
permissions: {
viewableBy: ['guests'],
editableBy: ['members', 'sunshineRegiment', 'admins'],
insertableBy: ['members']
},
}
})
makeEditable({
collection: Posts,
options: {
// Determines whether to use the comment editor configuration (e.g. Toolbars)
commentEditor: true,
// Determines whether to use the comment editor styles (e.g. Fonts)
commentStyles: true,
formGroup: formGroups.moderationGroup,
order: 50,
fieldName: "moderationGuidelines",
permissions: {
viewableBy: ['guests'],
editableBy: ['members', 'sunshineRegiment', 'admins'],
insertableBy: [userHasModerationGuidelines]
},
}
})
makeEditable({
collection: Posts,
options: {
formGroup: formGroups.highlight,
fieldName: "customHighlight",
permissions: {
viewableBy: ['guests'],
editableBy: ['sunshineRegiment', 'admins'],
insertableBy: ['sunshineRegiment', 'admins'],
},
}
}) | the_stack |
import { ScriptMockField } from "./scriptMockField";
import { ScriptMappingItem } from "./scriptMappingItem";
import { Type } from "class-transformer";
import { OPERATION, CONSTANTS, DATA_MEDIA_TYPE, SOURCE_TYPE } from "../components/statics";
import { NonSerializable, AppUtils, NonSerializableIfDefault, SerializableGetter } from "../components/appUtils";
import { UserDataWrapper } from "./userDataWrapper";
import { Config } from "./config";
import { SObjectDescribe } from "./sobjectDescribe";
import { Org } from "./org";
import { IAppModel, IPolymorphicField } from "../components/helper_interfaces";
import { FieldItem } from "./fieldItem";
import { SFieldDescribe } from "./sfieldDescribe";
import { ScriptObjectField } from "./ScriptObjectField";
import { RESOURCES } from "../components/resources";
import {
Query as SOQLQuery,
Field as SOQLField,
getComposedField,
parseQuery,
} from 'soql-parser-js';
import { SelectItem } from "../components/helper_classes";
/**
* Parsed object
* from the script file
*/
export class ScriptObject implements IAppModel {
// ------------- JSON --------------
// Mandatories ---
@SerializableGetter([CONSTANTS.EXPORT_JSON_TAG, CONSTANTS.EXPORT_JSON_FULL_TAG])
get query(): string {
return this.getQueryTemplate().format(this.fields.map(field => field.name).join(', '));
}
operation: string = OPERATION[OPERATION.Upsert].toString();
externalId: string = CONSTANTS.DEFAULT_EXTERNAL_ID_FIELD_NAME;
// Optionals --
@NonSerializableIfDefault([], [CONSTANTS.EXPORT_JSON_TAG])
@Type(() => ScriptMockField)
mockFields: ScriptMockField[] = new Array<ScriptMockField>();
@NonSerializableIfDefault([], [CONSTANTS.EXPORT_JSON_TAG])
@Type(() => ScriptMappingItem)
fieldMapping: ScriptMappingItem[] = new Array<ScriptMappingItem>();
@SerializableGetter([CONSTANTS.EXPORT_JSON_TAG, CONSTANTS.EXPORT_JSON_FULL_TAG])
get deleteQuery(): string {
if (this.deleteOldData || this.enumOperation == OPERATION.Delete) {
if (this.deleteWhere)
return `SELECT Id FROM ${this.name} WHERE ${this.deleteWhere}`;
else if (this.deleteAllData)
return `SELECT Id FROM ${this.name}`;
else
return undefined;
}
else
return undefined;
}
@NonSerializableIfDefault(false, [CONSTANTS.EXPORT_JSON_TAG])
deleteOldData: boolean = false;
@NonSerializableIfDefault(false, [CONSTANTS.EXPORT_JSON_TAG])
updateWithMockData: boolean = false;
@NonSerializableIfDefault(false, [CONSTANTS.EXPORT_JSON_TAG])
mockCSVData: boolean = false;
@NonSerializableIfDefault("", [CONSTANTS.EXPORT_JSON_TAG])
targetRecordsFilter: string = "";
@NonSerializableIfDefault(false, [CONSTANTS.EXPORT_JSON_TAG])
excluded: boolean = false;
@NonSerializableIfDefault(false, [CONSTANTS.EXPORT_JSON_TAG])
useCSVValuesMapping: boolean = false;
@NonSerializableIfDefault(false, [CONSTANTS.EXPORT_JSON_TAG])
useFieldMapping: boolean = false;
@NonSerializableIfDefault(false, [CONSTANTS.EXPORT_JSON_TAG])
useValuesMapping: boolean = false;
@NonSerializableIfDefault(true, [CONSTANTS.EXPORT_JSON_TAG])
master: boolean = true;
@NonSerializable()
allRecords: boolean;
@NonSerializableIfDefault([], [CONSTANTS.EXPORT_JSON_TAG])
excludedFields: Array<string> = new Array<string>();
// Other members ----------------------------
@NonSerializable([CONSTANTS.EXPORT_JSON_TAG, CONSTANTS.EXPORT_JSON_FULL_TAG])
deleteAllData: boolean = false;
@NonSerializable([CONSTANTS.EXPORT_JSON_TAG, CONSTANTS.EXPORT_JSON_FULL_TAG])
@Type(() => ScriptObjectField)
fields: Array<ScriptObjectField> = new Array<ScriptObjectField>();
@NonSerializable([CONSTANTS.EXPORT_JSON_TAG, CONSTANTS.EXPORT_JSON_FULL_TAG])
where: string;
@NonSerializable([CONSTANTS.EXPORT_JSON_TAG, CONSTANTS.EXPORT_JSON_FULL_TAG])
deleteWhere: string;
@NonSerializable([CONSTANTS.EXPORT_JSON_TAG, CONSTANTS.EXPORT_JSON_FULL_TAG])
limit: number;
@NonSerializable([CONSTANTS.EXPORT_JSON_TAG, CONSTANTS.EXPORT_JSON_FULL_TAG])
orderBy: string;
// ------------ Constructor -----------------------//
constructor(init?: Partial<ScriptObject>) {
if (init) {
this.initialize(init);
}
}
// ------------ Other -----------------------//
@NonSerializable()
config: Config;
@NonSerializable([CONSTANTS.EXPORT_JSON_TAG, CONSTANTS.EXPORT_JSON_FULL_TAG])
name: string;
@NonSerializable()
errorMessage: string;
@NonSerializable()
fieldItems: FieldItem[] = new Array<FieldItem>();
@NonSerializable()
fullQueryFields: string[] = new Array<string>();
@NonSerializable()
availableFieldItemsForFieldMapping: Array<FieldItem> = new Array<FieldItem>();
@NonSerializable()
availableFieldItemsForMocking: Array<FieldItem> = new Array<FieldItem>();
@NonSerializable()
availableTargetSObjectNamesForFieldMapping: Array<FieldItem> = new Array<FieldItem>();
@NonSerializable()
availableTargetSFieldsNamesForFieldMapping: Array<FieldItem> = new Array<FieldItem>();
@NonSerializable()
mockPatterns: SelectItem[] = new Array<SelectItem>();
@NonSerializable()
private _polymorphicFields: IPolymorphicField[] = new Array<IPolymorphicField>();
get isComplexExternalId(): boolean {
return (this.externalId || "").indexOf(CONSTANTS.COMPLEX_FIELDS_SEPARATOR) >= 0;
}
get selectedFieldItems(): FieldItem[] {
return this.fieldItems.filter(fieldItem => fieldItem.selected);
}
get label() {
return this.sObjectDescribe.name || this.name;
}
get enumOperation(): OPERATION {
return AppUtils.getOperation(this.operation);
}
get userData(): UserDataWrapper {
return this.config && this.config.userData || new UserDataWrapper();
}
get sourceOrg(): Org {
return this.userData.orgs && this.userData.orgs.filter(org => org.sourceType == SOURCE_TYPE.Source)[0];
}
get targetOrg(): Org {
return this.userData.orgs && this.userData.orgs.filter(org => org.sourceType == SOURCE_TYPE.Target)[0];
}
get org(): Org {
let sourceOrg = this.sourceOrg;
let targetOrg = this.targetOrg;
if (!sourceOrg && !targetOrg) {
return new Org({
media: DATA_MEDIA_TYPE.Unknown
});
}
let org = new Org(sourceOrg.isOrg() ? sourceOrg : targetOrg);
sourceOrg.isOrg() && sourceOrg.objectsMap.forEach((describe, name) => {
if (!org.objectsMap.has(name)) {
org.objectsMap.set(name, describe);
}
});
targetOrg.isOrg() && targetOrg.objectsMap.forEach((describe, name) => {
if (!org.objectsMap.has(name)) {
org.objectsMap.set(name, describe);
}
});
return org;
}
get sourceSObjectDescribe(): SObjectDescribe {
if (this.sourceOrg.isOrg())
return this.sourceOrg.objectsMap.get(this.name) || new SObjectDescribe();
return this.targetSObjectDescribe;
}
get targetSObjectDescribe(): SObjectDescribe {
if (this.targetOrg.isOrg())
return this.targetOrg.objectsMap.get(this.name) || new SObjectDescribe();
return this.sourceSObjectDescribe;
}
get sObjectDescribe(): SObjectDescribe {
return this.org.objectsMap.get(this.name) || new SObjectDescribe();
}
get defaultExternalId(): string {
if (this.name == CONSTANTS.RECORD_TYPE_SOBJECT_NAME) {
return CONSTANTS.DEFAULT_RECORD_TYPE_ID_EXTERNAL_ID_FIELD_NAME;
}
if (!this.isOrgDescribed) {
return "Id";
}
return ([].concat(
[...this.sObjectDescribe.fieldsMap.values()].filter(field => field.nameField),
[...this.sObjectDescribe.fieldsMap.values()].filter(field => field.autoNumber),
[...this.sObjectDescribe.fieldsMap.values()].filter(field => field.unique))[0]
|| { name: "Id" })["name"];
}
get isOrgDescribed(): boolean {
return this.sObjectDescribe.isValid();
}
get specialQueryFields(): SFieldDescribe[] {
let multiFields: SFieldDescribe[] = new Array<SFieldDescribe>();
// Multiselect fields //////////////
let multiselectFields = this.fields.filter(field => CONSTANTS.MULTISELECT_SOQL_KEYWORDS.some(name => field.name == name));
if (multiselectFields.length > 0) {
let pattern: any = multiselectFields.reduce((acc, field) => {
let name = field.name == "all" ? "all_true" : field.name;
let parts = name.split('_');
acc[parts[0]] = parts[1] == "true";
return acc;
}, {});
multiFields = multiFields.concat([...this.sObjectDescribe.fieldsMap.values()].filter(fieldDescribe => {
if ((___compare(pattern.all != "undefined", pattern.all == true)
|| !Object.keys(pattern).some(prop => ___compare(fieldDescribe[prop], pattern[prop], true)))) {
if (!(fieldDescribe.lookup && CONSTANTS.OBJECTS_NOT_TO_USE_IN_QUERY_MULTISELECT.indexOf(fieldDescribe.referencedObjectType) >= 0)) {
return fieldDescribe;
}
}
}).filter(x => !!x));
}
// Compound fields //////////////
if (this.name == "Account") {
let compoundFields = this.fields.filter(field => [...CONSTANTS.COMPOUND_FIELDS.keys()].some(name => field.name == name));
compoundFields.forEach(compoundField => {
let queryFields = CONSTANTS.COMPOUND_FIELDS.get(compoundField.name);
let describes = [...this.sObjectDescribe.fieldsMap.values()].filter(describe => {
return queryFields.some(queryField => queryField == describe.name);
});
multiFields = multiFields.concat(describes);
});
}
return multiFields;
// ------------- Local functions ---------------------//
function ___compare(fieldDescribeProperty: any, patternProperty: any, negative: boolean = false): boolean {
if (!negative)
return fieldDescribeProperty == patternProperty || typeof patternProperty == "undefined";
else
return fieldDescribeProperty != patternProperty && typeof fieldDescribeProperty != "undefined";
}
}
get polymorphicFields(): IPolymorphicField[] {
return this._polymorphicFields;
}
get hasPolymorphicFields(): boolean {
return this.polymorphicFields.length > 0;
}
get unresolvedPolymorphicFields(): IPolymorphicField[] {
return this.polymorphicFields.filter(field => field.name.indexOf(CONSTANTS.REFERENCE_FIELD_OBJECT_SEPARATOR) < 0);
}
get hasUnresolvedPolymorphicFields(): boolean {
return this.unresolvedPolymorphicFields.length > 0;
}
get hasInvalidFields(): boolean {
return this.fieldItems.some(item => !item.isValid());
}
get excludedFieldsItems(): Array<FieldItem> {
return this.fullQueryFields.filter(field => field != "Id" && field != this.externalId).map(name => new FieldItem({
name,
selected: this.excludedFields.some(f => f == name),
isExcludedItem: true
}));
}
get externalIdFieldItems(): FieldItem[] {
return this.fieldItems.filter(field => field.sFieldDescribe && field.sFieldDescribe.canBeExternalId);
}
get included(): boolean {
return !this.excluded;
}
set included(value: boolean) {
this.excluded = !value;
}
get targetSobjectNameForFieldMapping(): string {
let item = this.fieldMapping.filter(item => !!item.targetObject)[0];
return item && item.targetObject;
}
get hasNonBreakingIssues(): boolean {
return this.hasInvalidFieldMappings;
}
get hasInvalidFieldMappings(): boolean {
return this.fieldMapping.some(field => !field.isValid());
}
// ------ Methods ------------- //
initialize(init?: Partial<ScriptObject>) {
if (init) {
AppUtils.objectAssignSafe(this, init);
}
}
isValid(): boolean {
let errors = [];
if (this.sourceOrg.isDescribed() && !this.sourceSObjectDescribe.isDescribed()) {
errors.push(RESOURCES.ValidationError_MissingSObjectInSourceOrg);
}
if (this.targetOrg.isDescribed() && !this.targetSObjectDescribe.isDescribed()) {
errors.push(RESOURCES.ValidationError_MissingSObjectInTargetOrg);
}
if (this.sourceSObjectDescribe.isValid() && this.targetSObjectDescribe.isValid()) {
if (this.hasInvalidFields) {
errors.push(RESOURCES.ValidationError_FieldMetadataErrors);
}
}
this.errorMessage = errors.join(RESOURCES.ValidationError_Separator);
return errors.length == 0 || this.excluded;
}
isInitialized(): boolean {
return !!this.name;
}
isMissingInBothOrgs(): boolean {
return !this.sObjectDescribe.isValid();
}
getSelectedFieldItems(): FieldItem[] {
return this.fields.map(field => {
return new FieldItem({
name: field.name,
selected: true,
sFieldDescribe: this.sObjectDescribe.fieldsMap.get(field.cleanName) || new SFieldDescribe()
});
});
}
getFieldItems(): FieldItem[] {
if (!this.isInitialized()) return new Array<FieldItem>();
// --------- All object fields -------------------//
let items = this.getSelectedFieldItems();
this._polymorphicFields = this.getPolymorphicFields();
let compoundFields = this.name == "Account" ? [...CONSTANTS.COMPOUND_FIELDS.keys()] : new Array<string>();
items = items.concat
(
// --------- All SObject metadata fields -------------------//
[...this.sObjectDescribe.fieldsMap.keys()]
.filter(field => !this.sObjectDescribe.fieldsMap.get(field).readonly)
.map(field => {
return new FieldItem({
name: field,
selected: false
});
}),
// --------- Multiselect keywords + Compound fields + Other fields -------------------//
[].concat(CONSTANTS.MULTISELECT_SOQL_KEYWORDS, compoundFields, "Id").map(field => {
return new FieldItem({
name: field,
selected: false
});
})
);
let unresolvedPolymorphicFields = this.unresolvedPolymorphicFields;
items.forEach(item => {
item.sFieldDescribe = this.sObjectDescribe.fieldsMap.get(item.cleanName) || new SFieldDescribe();
item.isMultiselect = [].concat(CONSTANTS.MULTISELECT_SOQL_KEYWORDS, compoundFields).some(keyword => item.name == keyword);
let sourceDescribe = this.sourceSObjectDescribe.fieldsMap.get(item.cleanName) || new SFieldDescribe();
let targetDescribe = this.targetSObjectDescribe.fieldsMap.get(item.cleanName) || new SFieldDescribe();
if (!item.isMultiselect) {
let errors = [];
if (!sourceDescribe.isValid() && this.sourceOrg.isOrg()) {
errors.push(RESOURCES.ValidationError_MissingFieldInSourceOrg);
}
if (!targetDescribe.isValid() && this.targetOrg.isOrg()) {
errors.push(RESOURCES.ValidationError_MissingFieldInTargetOrg);
}
if (unresolvedPolymorphicFields.some(fieldItem => fieldItem.name == item.name)) {
errors.push(RESOURCES.ValidationError_UnresolvedPolymorphicField);
}
item.errorMessage = errors.join(RESOURCES.ValidationError_Separator);
}
});
items = AppUtils.distinctArray(items, "cleanName");
// Field Mapping errors
this.fieldMapping.forEach(field => {
let errors = [];
if (field.targetObject && this.org.isDescribed && !this.org.objectsMap.has(field.targetObject)) {
errors.push(RESOURCES.ValidationError_FieldMappingTargetSObjectIsNotExist);
}
if (field.sourceField && this.sObjectDescribe.isDescribed()
&& this.sObjectDescribe.fieldsMap.size > 0
&& !this.sObjectDescribe.fieldsMap.has(field.sourceField)) {
errors.push(RESOURCES.ValidationError_FieldMappingSourceFieldDoesNotExist);
}
if (field.targetField
&& this.org.isDescribed
&& this.org.objectsMap.has(this.targetSobjectNameForFieldMapping)
&& this.org.objectsMap.get(this.targetSobjectNameForFieldMapping).fieldsMap.size > 0
&& !this.org.objectsMap.get(this.targetSobjectNameForFieldMapping).fieldsMap.has(field.targetField)) {
errors.push(RESOURCES.ValidationError_FieldMappingTargetFieldDoesNotExist);
}
field.errorMessage = errors.join('; ');
});
return AppUtils.sortArray(items, "category", "cleanName");
}
getFullQueryFields(): string[] {
let fields: Array<string> = [].concat(
this.specialQueryFields.map(field => field.name),
this.fields.map(x => x.cleanName),
!this.isComplexExternalId ? this.externalId : undefined
).filter(field => !!field);
fields = AppUtils.exclude(fields, CONSTANTS.MULTISELECT_SOQL_KEYWORDS);
fields = AppUtils.exclude(fields, [...CONSTANTS.COMPOUND_FIELDS.keys()]);
fields = AppUtils.uniqueArray(fields);
return fields;
}
getFullQueryFieldsDescriptions(): SFieldDescribe[] {
return this.getFullQueryFields().map(field => {
return this.sObjectDescribe.fieldsMap.get(field) || new SFieldDescribe();
});
}
getQueryTemplate(limit?: number): string {
return `SELECT {0} FROM ${this.name}${this.where ? ' WHERE ' + this.where : ''}${this.orderBy ? " ORDER BY " + this.orderBy : ""}${limit || this.limit ? " LIMIT " + (limit || this.limit) : ""}`;
}
getFullQuery(limit?: number): string {
return this.getQueryTemplate(limit).format(this.fullQueryFields.join(', '));
}
getTestQuery(limit?: number): string {
let testQueryFields = AppUtils.exclude(this.fullQueryFields, this.excludedFields);
return this.getQueryTemplate(limit).format(testQueryFields.join(', '));
}
getPolymorphicFields(): IPolymorphicField[] {
if (!this.org.isValid()) return [];
let sobjects = [...this.org.objectsMap.values()];
let polymorphic = this.getSelectedFieldItems().filter(field => field.sFieldDescribe && field.sFieldDescribe.isPolymorphic);
return polymorphic
.filter(field => field.sFieldDescribe && field.sFieldDescribe.isPolymorphic)
.map(field => <IPolymorphicField>{
name: field.name,
referencedToSObjects: sobjects.filter(object => field.sFieldDescribe.referenceTo.indexOf(object.name) >= 0),
referencedTo: field.sFieldDescribe.referenceTo,
fieldItem: field,
parentSObject: field.referencedObjectType
});
}
getAvailableFieldItemsForFieldMapping(): FieldItem[] {
return this.getFullQueryFieldsDescriptions().filter(fieldDescr => {
return fieldDescr.name != "Id"
&& !fieldDescr.lookup
&& fieldDescr.isValid()
&& CONSTANTS.FIELDS_NOT_TO_USE_IN_FIELD_MAPPING.indexOf(fieldDescr.name) < 0
}).map(fieldItem => {
let item = this.fieldItems.filter(item => item.name == fieldItem.name)[0];
if (item) {
return item;
}
return new FieldItem({
name: fieldItem.name,
sFieldDescribe: fieldItem,
});
});
}
getAvailableFieldItemsForMocking(): FieldItem[] {
return this.getFullQueryFieldsDescriptions().filter(fieldDescr => {
return fieldDescr.name != "Id"
&& !fieldDescr.lookup
&& !fieldDescr.readonly
// Can't anonymize external id fields
&& this.externalId
&& this.externalId.indexOf(fieldDescr.name) < 0
&& fieldDescr.isValid()
&& !this.mockFields.some(field => field.name == fieldDescr.name)
&& CONSTANTS.FIELDS_NOT_TO_USE_IN_FIELD_MOCKING.indexOf(fieldDescr.name) < 0
}).map(fieldItem => {
let item = this.fieldItems.filter(item => item.name == fieldItem.name)[0];
if (item) {
return item;
}
return new FieldItem({
name: fieldItem.name,
sFieldDescribe: fieldItem,
});
});
}
parseQueryString(query: string): SOQLQuery {
if (!this.org.isValid()) return <SOQLQuery>{};
let parsedQuery = parseQuery(query);
let invalidFields = parsedQuery.fields
.filter(field => (<SOQLField>field).type != "Field")
.map(field => ((<SOQLField>field).rawValue || (<SOQLField>field).field));
if (invalidFields.length > 0) {
throw new Error(RESOURCES.Config_ReferencedFieldsNotAllowedToUse.format(invalidFields.filter(x => !!x).join(', ')));
}
let objectFields = this.sObjectDescribe.fields.map(field => field.name);
let queryFields = new Array<string>("Id");
parsedQuery.fields.forEach(field => {
let f = <SOQLField>field;
let normalizedField = AppUtils.searchClosest(f.rawValue || f.field, objectFields);
queryFields.push(normalizedField);
});
queryFields = AppUtils.uniqueArray(queryFields);
parsedQuery.fields = queryFields.map(field => getComposedField(field));
parsedQuery.sObject = this.name;
return parsedQuery;
}
getMockPatterns(): SelectItem[] {
return [
{
text: "Country",
value: "country",
},
{
text: "City",
value: "city",
},
{
text: "Zip",
value: "zip()",
},
{
text: "Street",
value: "street",
},
{
text: "Address",
value: "address",
},
{
text: "Address1",
value: "address1",
},
{
text: "Address2",
value: "address2",
},
{
text: "State",
value: "state",
},
{
text: "State abbr",
value: "state_abbr",
},
{
text: "Latitude",
value: "latitude",
},
{
text: "Longitude",
value: "longitude",
},
{
text: "Building number",
value: "building_number",
},
{
text: "Sentence",
value: "sentence",
},
{
text: "Title",
value: "title",
},
{
text: "Text",
value: "text",
},
{
text: "Short text",
value: "string",
},
{
text: "Description",
value: "description",
},
{
text: "Short description",
value: "short_description",
},
{
text: "Word",
value: "word",
},
{
text: "Letter",
value: "letter",
},
{
text: "IP Address",
value: "ip",
},
{
text: "Domain",
value: "domain",
},
{
text: "Url",
value: "url",
},
{
text: "Email",
value: "email",
},
{
text: "Browser user agent",
value: "user_agent",
},
{
text: "Name",
value: "name",
},
{
text: "Usernaconfigme",
value: "username",
},
{
text: "Fist name",
value: "first_name",
},
{
text: "Last name",
value: "last_name",
},
{
text: "Full name",
value: "full_name",
},
{
text: "Password",
value: "full_name",
},
{
text: "Name prefix",
value: "name_prefix",
},
{
text: "Name suffix",
value: "name_suffix",
},
{
text: "Company name",
value: "company_name",
},
{
text: "Company suffix",
value: "company_suffix",
},
{
text: "Catch phrase",
value: "catch_phrase",
},
{
text: "Phone",
value: "phone",
},
{
text: "From 0 to 1",
value: "random",
},
{
text: "Integer",
value: "integer()",
},
{
text: "Double",
value: "double()",
},
{
text: "Date",
value: "date()",
},
{
text: "Time",
value: "time()",
},
{
text: "Century",
value: "century",
},
{
text: "AM/PM",
value: "am_pm",
},
{
text: "Day of year",
value: "day_of_year",
},
{
text: "Day of month",
value: "day_of_month",
},
{
text: "Day of week",
value: "day_of_week",
},
{
text: "Month number",
value: "month_number",
},
{
text: "Year",
value: "year",
},
{
text: "Timezone",
value: "timezone",
},
{
text: "Credit card number",
value: "card_number('Visa')",
},
{
text: "Credit card type",
value: "card_type",
},
{
text: "Credit card exp",
value: "card_exp",
},
{
text: "Country code",
value: "country_code",
},
{
text: "Language code",
value: "language_code",
},
{
text: "Locale",
value: "locale",
},
{
text: "Currency code",
value: "currency_code",
},
{
text: "Currency symbol",
value: "currency_symbol",
},
{
text: "Currency name",
value: "currency_name",
},
{
text: "Mime type",
value: "mime_type",
},
{
text: "File extension",
value: "file_extension",
},
{
text: "Boolean",
value: "boolean",
},
{
text: "UUID",
value: "uuid",
},
{
text: "Color name",
value: "color_name",
},
{
text: "RGB HEX Color name",
value: "rgb_hex",
},
{
text: "Incremented days",
value: `c_seq_date('2018-01-01','d')`
},
{
text: "Autonumber",
value: `c_seq_number('${this.name.replace("__c", "")}_',1,1)`
},
{
text: "Record Id",
value: `ids`
}
].sort((a, b) => (a.text > b.text) ? 1 : -1);
}
/**
* This method is intended to update the properties only once
* to avoid circular digests of angualar framework.
* So we could not use getters.
*/
updateFieldItems() {
this.fieldItems = this.getFieldItems();
this.fullQueryFields = this.getFullQueryFields();
this.availableFieldItemsForFieldMapping = this.getAvailableFieldItemsForFieldMapping();
this.availableFieldItemsForMocking = this.getAvailableFieldItemsForMocking();
this.mockPatterns = this.getMockPatterns();
}
} | the_stack |
import { generateEase, rotatePoint, SimpleEase } from './ParticleUtils';
import { Particle } from './Particle';
import { EmitterConfigV3 } from './EmitterConfig';
import { Container } from '@pixi/display';
import { settings } from '@pixi/settings';
import { Point } from '@pixi/math';
import { Ticker } from '@pixi/ticker';
import { BehaviorOrder, IEmitterBehavior, IEmitterBehaviorClass } from './behaviors/Behaviors';
// get the shared ticker, only supports V5 and V6 with individual packages
/**
* @hidden
*/
const ticker = Ticker.shared;
/**
* Key used in sorted order to determine when to set particle position from the emitter position
* and rotation.
*/
const PositionParticle = Symbol('Position particle per emitter position');
/**
* A particle emitter.
*/
export class Emitter
{
private static knownBehaviors: {[key: string]: IEmitterBehaviorClass} = {};
/**
* Registers a new behavior, so that it will be recognized when initializing emitters.
* Behaviors registered later with duplicate types will override older ones, although there is no limit on
* the allowed types.
* @param constructor The behavior class to register.
*/
public static registerBehavior(constructor: IEmitterBehaviorClass): void
{
Emitter.knownBehaviors[constructor.type] = constructor;
}
/**
* Active initialization behaviors for this emitter.
*/
protected initBehaviors: (IEmitterBehavior | typeof PositionParticle)[];
/**
* Active update behaviors for this emitter.
*/
protected updateBehaviors: IEmitterBehavior[];
/**
* Active recycle behaviors for this emitter.
*/
protected recycleBehaviors: IEmitterBehavior[];
// properties for individual particles
/**
* The minimum lifetime for a particle, in seconds.
*/
public minLifetime: number;
/**
* The maximum lifetime for a particle, in seconds.
*/
public maxLifetime: number;
/**
* An easing function for nonlinear interpolation of values. Accepts a single
* parameter of time as a value from 0-1, inclusive. Expected outputs are values
* from 0-1, inclusive.
*/
public customEase: SimpleEase;
// properties for spawning particles
/**
* Time between particle spawns in seconds.
*/
protected _frequency: number;
/**
* Chance that a particle will be spawned on each opportunity to spawn one.
* 0 is 0%, 1 is 100%.
*/
public spawnChance: number;
/**
* Maximum number of particles to keep alive at a time. If this limit
* is reached, no more particles will spawn until some have died.
*/
public maxParticles: number;
/**
* The amount of time in seconds to emit for before setting emit to false.
* A value of -1 is an unlimited amount of time.
*/
public emitterLifetime: number;
/**
* Position at which to spawn particles, relative to the emitter's owner's origin.
* For example, the flames of a rocket travelling right might have a spawnPos
* of {x:-50, y:0}.
* to spawn at the rear of the rocket.
* To change this, use updateSpawnPos().
*/
public spawnPos: Point;
/**
* Number of particles to spawn time that the frequency allows for particles to spawn.
*/
public particlesPerWave: number;
/**
* Rotation of the emitter or emitter's owner in degrees. This is added to
* the calculated spawn angle.
* To change this, use rotate().
*/
protected rotation: number;
/**
* The world position of the emitter's owner, to add spawnPos to when
* spawning particles. To change this, use updateOwnerPos().
*/
protected ownerPos: Point;
/**
* The origin + spawnPos in the previous update, so that the spawn position
* can be interpolated to space out particles better.
*/
protected _prevEmitterPos: Point;
/**
* If _prevEmitterPos is valid, to prevent interpolation on the first update
*/
protected _prevPosIsValid: boolean;
/**
* If either ownerPos or spawnPos has changed since the previous update.
*/
protected _posChanged: boolean;
/**
* The container to add particles to.
*/
protected _parent: Container;
/**
* If particles should be added at the back of the display list instead of the front.
*/
public addAtBack: boolean;
/**
* The current number of active particles.
*/
public particleCount: number;
/**
* If particles should be emitted during update() calls. Setting this to false
* stops new particles from being created, but allows existing ones to die out.
*/
protected _emit: boolean;
/**
* The timer for when to spawn particles in seconds, where numbers less
* than 0 mean that particles should be spawned.
*/
protected _spawnTimer: number;
/**
* The life of the emitter in seconds.
*/
protected _emitterLife: number;
/**
* The particles that are active and on the display list. This is the first particle in a
* linked list.
*/
protected _activeParticlesFirst: Particle;
/**
* The particles that are active and on the display list. This is the last particle in a
* linked list.
*/
protected _activeParticlesLast: Particle;
/**
* The particles that are not currently being used. This is the first particle in a
* linked list.
*/
protected _poolFirst: Particle;
/**
* The original config object that this emitter was initialized with.
*/
protected _origConfig: any;
/**
* If the update function is called automatically from the shared ticker.
* Setting this to false requires calling the update function manually.
*/
protected _autoUpdate: boolean;
/**
* If the emitter should destroy itself when all particles have died out. This is set by
* playOnceAndDestroy();
*/
protected _destroyWhenComplete: boolean;
/**
* A callback for when all particles have died out. This is set by
* playOnceAndDestroy() or playOnce();
*/
protected _completeCallback: () => void;
/**
* @param particleParent The container to add the particles to.
* @param particleImages A texture or array of textures to use
* for the particles. Strings will be turned
* into textures via Texture.from().
* @param config A configuration object containing settings for the emitter.
* @param config.emit If config.emit is explicitly passed as false, the
* Emitter will start disabled.
* @param config.autoUpdate If config.autoUpdate is explicitly passed as
* true, the Emitter will automatically call
* update via the PIXI shared ticker.
*/
constructor(particleParent: Container, config: EmitterConfigV3)
{
this.initBehaviors = [];
this.updateBehaviors = [];
this.recycleBehaviors = [];
// properties for individual particles
this.minLifetime = 0;
this.maxLifetime = 0;
this.customEase = null;
// properties for spawning particles
this._frequency = 1;
this.spawnChance = 1;
this.maxParticles = 1000;
this.emitterLifetime = -1;
this.spawnPos = new Point();
this.particlesPerWave = 1;
// emitter properties
this.rotation = 0;
this.ownerPos = new Point();
this._prevEmitterPos = new Point();
this._prevPosIsValid = false;
this._posChanged = false;
this._parent = null;
this.addAtBack = false;
this.particleCount = 0;
this._emit = false;
this._spawnTimer = 0;
this._emitterLife = -1;
this._activeParticlesFirst = null;
this._activeParticlesLast = null;
this._poolFirst = null;
this._origConfig = null;
this._autoUpdate = false;
this._destroyWhenComplete = false;
this._completeCallback = null;
// set the initial parent
this.parent = particleParent;
if (config)
{
this.init(config);
}
// save often used functions on the instance instead of the prototype for better speed
this.recycle = this.recycle;
this.update = this.update;
this.rotate = this.rotate;
this.updateSpawnPos = this.updateSpawnPos;
this.updateOwnerPos = this.updateOwnerPos;
}
/**
* Time between particle spawns in seconds. If this value is not a number greater than 0,
* it will be set to 1 (particle per second) to prevent infinite loops.
*/
public get frequency(): number { return this._frequency; }
public set frequency(value: number)
{
// do some error checking to prevent infinite loops
if (typeof value === 'number' && value > 0)
{
this._frequency = value;
}
else
{
this._frequency = 1;
}
}
/**
* The container to add particles to. Settings this will dump any active particles.
*/
public get parent(): Container { return this._parent; }
public set parent(value: Container)
{
this.cleanup();
this._parent = value;
}
/**
* Sets up the emitter based on the config settings.
* @param config A configuration object containing settings for the emitter.
*/
public init(config: EmitterConfigV3): void
{
if (!config)
{
return;
}
// clean up any existing particles
this.cleanup();
// store the original config and particle images, in case we need to re-initialize
// when the particle constructor is changed
this._origConfig = config;
// /////////////////////////
// Particle Properties //
// /////////////////////////
// set up the lifetime
this.minLifetime = config.lifetime.min;
this.maxLifetime = config.lifetime.max;
// use the custom ease if provided
if (config.ease)
{
this.customEase = typeof config.ease === 'function'
? config.ease : generateEase(config.ease);
}
else
{
this.customEase = null;
}
// ////////////////////////
// Emitter Properties //
// ////////////////////////
// reset spawn type specific settings
this.particlesPerWave = 1;
if (config.particlesPerWave && config.particlesPerWave > 1)
{
this.particlesPerWave = config.particlesPerWave;
}
// set the spawning frequency
this.frequency = config.frequency;
this.spawnChance = (typeof config.spawnChance === 'number' && config.spawnChance > 0) ? config.spawnChance : 1;
// set the emitter lifetime
this.emitterLifetime = config.emitterLifetime || -1;
// set the max particles
this.maxParticles = config.maxParticles > 0 ? config.maxParticles : 1000;
// determine if we should add the particle at the back of the list or not
this.addAtBack = !!config.addAtBack;
// reset the emitter position and rotation variables
this.rotation = 0;
this.ownerPos.set(0);
if (config.pos)
{
this.spawnPos.copyFrom(config.pos);
}
else
{
this.spawnPos.set(0);
}
this._prevEmitterPos.copyFrom(this.spawnPos);
// previous emitter position is invalid and should not be used for interpolation
this._prevPosIsValid = false;
// start emitting
this._spawnTimer = 0;
this.emit = config.emit === undefined ? true : !!config.emit;
this.autoUpdate = !!config.autoUpdate;
// ////////////////////////
// Behaviors //
// ////////////////////////
const behaviors: (IEmitterBehavior | typeof PositionParticle)[] = config.behaviors.map((data) =>
{
const constructor = Emitter.knownBehaviors[data.type];
if (!constructor)
{
console.error(`Unknown behavior: ${data.type}`);
return null;
}
return new constructor(data.config);
})
.filter((b) => !!b);
behaviors.push(PositionParticle);
behaviors.sort((a, b) =>
{
if (a === PositionParticle)
{
return (b as IEmitterBehavior).order === BehaviorOrder.Spawn ? 1 : -1;
}
else if (b === PositionParticle)
{
return (a as IEmitterBehavior).order === BehaviorOrder.Spawn ? -1 : 1;
}
return (a as IEmitterBehavior).order - (b as IEmitterBehavior).order;
});
this.initBehaviors = behaviors.slice();
this.updateBehaviors = behaviors.filter((b) => b !== PositionParticle && b.updateParticle) as IEmitterBehavior[];
this.recycleBehaviors = behaviors.filter((b) => b !== PositionParticle && b.recycleParticle) as IEmitterBehavior[];
}
/**
* Gets the instantiated behavior of the specified type, if it is present on this emitter.
* @param type The behavior type to find.
*/
public getBehavior(type: string): IEmitterBehavior|null
{
// bail if we don't know about such an emitter
if (!Emitter.knownBehaviors[type]) return null;
// find one that is an instance of the specified type
return this.initBehaviors.find((b) => b instanceof Emitter.knownBehaviors[type]) as IEmitterBehavior || null;
}
/**
* Fills the pool with the specified number of particles, so that they don't have to be instantiated later.
* @param count The number of particles to create.
*/
public fillPool(count: number): void
{
for (; count > 0; --count)
{
const p = new Particle(this);
p.next = this._poolFirst;
this._poolFirst = p;
}
}
/**
* Recycles an individual particle. For internal use only.
* @param particle The particle to recycle.
* @param fromCleanup If this is being called to manually clean up all particles.
* @internal
*/
public recycle(particle: Particle, fromCleanup = false): void
{
for (let i = 0; i < this.recycleBehaviors.length; ++i)
{
this.recycleBehaviors[i].recycleParticle(particle, !fromCleanup);
}
if (particle.next)
{
particle.next.prev = particle.prev;
}
if (particle.prev)
{
particle.prev.next = particle.next;
}
if (particle === this._activeParticlesLast)
{
this._activeParticlesLast = particle.prev;
}
if (particle === this._activeParticlesFirst)
{
this._activeParticlesFirst = particle.next;
}
// add to pool
particle.prev = null;
particle.next = this._poolFirst;
this._poolFirst = particle;
// remove child from display, or make it invisible if it is in a ParticleContainer
if (particle.parent)
{
particle.parent.removeChild(particle);
}
// decrease count
--this.particleCount;
}
/**
* Sets the rotation of the emitter to a new value. This rotates the spawn position in addition
* to particle direction.
* @param newRot The new rotation, in degrees.
*/
public rotate(newRot: number): void
{
if (this.rotation === newRot) return;
// caclulate the difference in rotation for rotating spawnPos
const diff = newRot - this.rotation;
this.rotation = newRot;
// rotate spawnPos
rotatePoint(diff, this.spawnPos);
// mark the position as having changed
this._posChanged = true;
}
/**
* Changes the spawn position of the emitter.
* @param x The new x value of the spawn position for the emitter.
* @param y The new y value of the spawn position for the emitter.
*/
public updateSpawnPos(x: number, y: number): void
{
this._posChanged = true;
this.spawnPos.x = x;
this.spawnPos.y = y;
}
/**
* Changes the position of the emitter's owner. You should call this if you are adding
* particles to the world container that your emitter's owner is moving around in.
* @param x The new x value of the emitter's owner.
* @param y The new y value of the emitter's owner.
*/
public updateOwnerPos(x: number, y: number): void
{
this._posChanged = true;
this.ownerPos.x = x;
this.ownerPos.y = y;
}
/**
* Prevents emitter position interpolation in the next update.
* This should be used if you made a major position change of your emitter's owner
* that was not normal movement.
*/
public resetPositionTracking(): void
{
this._prevPosIsValid = false;
}
/**
* If particles should be emitted during update() calls. Setting this to false
* stops new particles from being created, but allows existing ones to die out.
*/
public get emit(): boolean { return this._emit; }
public set emit(value: boolean)
{
this._emit = !!value;
this._emitterLife = this.emitterLifetime;
}
/**
* If the update function is called automatically from the shared ticker.
* Setting this to false requires calling the update function manually.
*/
public get autoUpdate(): boolean { return this._autoUpdate; }
public set autoUpdate(value: boolean)
{
if (this._autoUpdate && !value)
{
ticker.remove(this.update, this);
}
else if (!this._autoUpdate && value)
{
ticker.add(this.update, this);
}
this._autoUpdate = !!value;
}
/**
* Starts emitting particles, sets autoUpdate to true, and sets up the Emitter to destroy itself
* when particle emission is complete.
* @param callback Callback for when emission is complete (all particles have died off)
*/
public playOnceAndDestroy(callback?: () => void): void
{
this.autoUpdate = true;
this.emit = true;
this._destroyWhenComplete = true;
this._completeCallback = callback;
}
/**
* Starts emitting particles and optionally calls a callback when particle emission is complete.
* @param callback Callback for when emission is complete (all particles have died off)
*/
public playOnce(callback?: () => void): void
{
this.emit = true;
this._completeCallback = callback;
}
/**
* Updates all particles spawned by this emitter and emits new ones.
* @param delta Time elapsed since the previous frame, in __seconds__.
*/
public update(delta: number): void
{
if (this._autoUpdate)
{
delta = delta / settings.TARGET_FPMS / 1000;
}
// if we don't have a parent to add particles to, then don't do anything.
// this also works as a isDestroyed check
if (!this._parent) return;
// == update existing particles ==
// update all particle lifetimes before turning them over to behaviors
for (let particle = this._activeParticlesFirst, next; particle; particle = next)
{
// save next particle in case we recycle this one
next = particle.next;
// increase age
particle.age += delta;
// recycle particle if it is too old
if (particle.age > particle.maxLife || particle.age < 0)
{
this.recycle(particle);
}
else
{
// determine our interpolation value
let lerp = particle.age * particle.oneOverLife;// lifetime / maxLife;
// global ease affects all interpolation calculations
if (this.customEase)
{
if (this.customEase.length === 4)
{
// the t, b, c, d parameters that some tween libraries use
// (time, initial value, end value, duration)
lerp = (this.customEase as any)(lerp, 0, 1, 1);
}
else
{
// the simplified version that we like that takes
// one parameter, time from 0-1. TweenJS eases provide this usage.
lerp = this.customEase(lerp);
}
}
// set age percent for all interpolation calculations
particle.agePercent = lerp;
// let each behavior run wild on the active particles
for (let i = 0; i < this.updateBehaviors.length; ++i)
{
if (this.updateBehaviors[i].updateParticle(particle, delta))
{
this.recycle(particle);
break;
}
}
}
}
let prevX: number;
let prevY: number;
// if the previous position is valid, store these for later interpolation
if (this._prevPosIsValid)
{
prevX = this._prevEmitterPos.x;
prevY = this._prevEmitterPos.y;
}
// store current position of the emitter as local variables
const curX = this.ownerPos.x + this.spawnPos.x;
const curY = this.ownerPos.y + this.spawnPos.y;
// spawn new particles
if (this._emit)
{
// decrease spawn timer
this._spawnTimer -= delta < 0 ? 0 : delta;
// while _spawnTimer < 0, we have particles to spawn
while (this._spawnTimer <= 0)
{
// determine if the emitter should stop spawning
if (this._emitterLife >= 0)
{
this._emitterLife -= this._frequency;
if (this._emitterLife <= 0)
{
this._spawnTimer = 0;
this._emitterLife = 0;
this.emit = false;
break;
}
}
// determine if we have hit the particle limit
if (this.particleCount >= this.maxParticles)
{
this._spawnTimer += this._frequency;
continue;
}
let emitPosX: number;
let emitPosY: number;
// If the position has changed and this isn't the first spawn,
// interpolate the spawn position
if (this._prevPosIsValid && this._posChanged)
{
// 1 - _spawnTimer / delta, but _spawnTimer is negative
const lerp = 1 + (this._spawnTimer / delta);
emitPosX = ((curX - prevX) * lerp) + prevX;
emitPosY = ((curY - prevY) * lerp) + prevY;
}
// otherwise just set to the spawn position
else
{
emitPosX = curX;
emitPosY = curY;
}
let waveFirst: Particle = null;
let waveLast: Particle = null;
// create enough particles to fill the wave
for (let len = Math.min(this.particlesPerWave, this.maxParticles - this.particleCount), i = 0; i < len; ++i)
{
// see if we actually spawn one
if (this.spawnChance < 1 && Math.random() >= this.spawnChance)
{
continue;
}
// determine the particle lifetime
let lifetime;
if (this.minLifetime === this.maxLifetime)
{
lifetime = this.minLifetime;
}
else
{
lifetime = (Math.random() * (this.maxLifetime - this.minLifetime)) + this.minLifetime;
}
// only make the particle if it wouldn't immediately destroy itself
if (-this._spawnTimer >= lifetime)
{
continue;
}
// create particle
let p: Particle;
if (this._poolFirst)
{
p = this._poolFirst;
this._poolFirst = this._poolFirst.next;
p.next = null;
}
else
{
p = new Particle(this);
}
// initialize particle
p.init(lifetime);
// add the particle to the display list
if (this.addAtBack)
{
this._parent.addChildAt(p, 0);
}
else
{
this._parent.addChild(p);
}
// add particles to list of ones in this wave
if (waveFirst)
{
waveLast.next = p;
p.prev = waveLast;
waveLast = p;
}
else
{
waveLast = waveFirst = p;
}
// increase our particle count
++this.particleCount;
}
if (waveFirst)
{
// add particle to list of active particles
if (this._activeParticlesLast)
{
this._activeParticlesLast.next = waveFirst;
waveFirst.prev = this._activeParticlesLast;
this._activeParticlesLast = waveLast;
}
else
{
this._activeParticlesFirst = waveFirst;
this._activeParticlesLast = waveLast;
}
// run behavior init on particles
for (let i = 0; i < this.initBehaviors.length; ++i)
{
const behavior = this.initBehaviors[i];
// if we hit our special key, interrupt behaviors to apply
// emitter position/rotation
if (behavior === PositionParticle)
{
for (let particle = waveFirst, next; particle; particle = next)
{
// save next particle in case we recycle this one
next = particle.next;
// rotate the particle's position by the emitter's rotation
if (this.rotation !== 0)
{
rotatePoint(this.rotation, particle.position);
particle.rotation += this.rotation;
}
// offset by the emitter's position
particle.position.x += emitPosX;
particle.position.y += emitPosY;
// also, just update the particle's age properties while we are looping through
particle.age += delta;
// determine our interpolation value
let lerp = particle.age * particle.oneOverLife;// lifetime / maxLife;
// global ease affects all interpolation calculations
if (this.customEase)
{
if (this.customEase.length === 4)
{
// the t, b, c, d parameters that some tween libraries use
// (time, initial value, end value, duration)
lerp = (this.customEase as any)(lerp, 0, 1, 1);
}
else
{
// the simplified version that we like that takes
// one parameter, time from 0-1. TweenJS eases provide this usage.
lerp = this.customEase(lerp);
}
}
// set age percent for all interpolation calculations
particle.agePercent = lerp;
}
}
else
{
behavior.initParticles(waveFirst);
}
}
for (let particle = waveFirst, next; particle; particle = next)
{
// save next particle in case we recycle this one
next = particle.next;
// now update the particles by the time passed, so the particles are spread out properly
for (let i = 0; i < this.updateBehaviors.length; ++i)
{
// we want a positive delta, because a negative delta messes things up
if (this.updateBehaviors[i].updateParticle(particle, -this._spawnTimer))
{
// bail if the particle got reycled
this.recycle(particle);
break;
}
}
}
}
// increase timer and continue on to any other particles that need to be created
this._spawnTimer += this._frequency;
}
}
// if the position changed before this update, then keep track of that
if (this._posChanged)
{
this._prevEmitterPos.x = curX;
this._prevEmitterPos.y = curY;
this._prevPosIsValid = true;
this._posChanged = false;
}
// if we are all done and should destroy ourselves, take care of that
if (!this._emit && !this._activeParticlesFirst)
{
if (this._completeCallback)
{
const cb = this._completeCallback;
this._completeCallback = null;
cb();
}
if (this._destroyWhenComplete)
{
this.destroy();
}
}
}
/**
* Emits a single wave of particles, using standard spawnChance & particlesPerWave settings. Does not affect
* regular spawning through the frequency, and ignores the emit property. The max particle count is respected, however,
* so if there are already too many particles then nothing will happen.
*/
public emitNow(): void
{
const emitPosX = this.ownerPos.x + this.spawnPos.x;
const emitPosY = this.ownerPos.y + this.spawnPos.y;
let waveFirst: Particle = null;
let waveLast: Particle = null;
// create enough particles to fill the wave
for (let len = Math.min(this.particlesPerWave, this.maxParticles - this.particleCount), i = 0; i < len; ++i)
{
// see if we actually spawn one
if (this.spawnChance < 1 && Math.random() >= this.spawnChance)
{
continue;
}
// create particle
let p: Particle;
if (this._poolFirst)
{
p = this._poolFirst;
this._poolFirst = this._poolFirst.next;
p.next = null;
}
else
{
p = new Particle(this);
}
let lifetime: number;
if (this.minLifetime === this.maxLifetime)
{
lifetime = this.minLifetime;
}
else
{
lifetime = (Math.random() * (this.maxLifetime - this.minLifetime)) + this.minLifetime;
}
// initialize particle
p.init(lifetime);
// add the particle to the display list
if (this.addAtBack)
{
this._parent.addChildAt(p, 0);
}
else
{
this._parent.addChild(p);
}
// add particles to list of ones in this wave
if (waveFirst)
{
waveLast.next = p;
p.prev = waveLast;
waveLast = p;
}
else
{
waveLast = waveFirst = p;
}
// increase our particle count
++this.particleCount;
}
if (waveFirst)
{
// add particle to list of active particles
if (this._activeParticlesLast)
{
this._activeParticlesLast.next = waveFirst;
waveFirst.prev = this._activeParticlesLast;
this._activeParticlesLast = waveLast;
}
else
{
this._activeParticlesFirst = waveFirst;
this._activeParticlesLast = waveLast;
}
// run behavior init on particles
for (let i = 0; i < this.initBehaviors.length; ++i)
{
const behavior = this.initBehaviors[i];
// if we hit our special key, interrupt behaviors to apply
// emitter position/rotation
if (behavior === PositionParticle)
{
for (let particle = waveFirst, next; particle; particle = next)
{
// save next particle in case we recycle this one
next = particle.next;
// rotate the particle's position by the emitter's rotation
if (this.rotation !== 0)
{
rotatePoint(this.rotation, particle.position);
particle.rotation += this.rotation;
}
// offset by the emitter's position
particle.position.x += emitPosX;
particle.position.y += emitPosY;
}
}
else
{
behavior.initParticles(waveFirst);
}
}
}
}
/**
* Kills all active particles immediately.
*/
public cleanup(): void
{
let particle;
let next;
for (particle = this._activeParticlesFirst; particle; particle = next)
{
next = particle.next;
this.recycle(particle, true);
}
this._activeParticlesFirst = this._activeParticlesLast = null;
this.particleCount = 0;
}
/**
* If this emitter has been destroyed. Note that a destroyed emitter can still be reused, after
* having a new parent set and being reinitialized.
*/
public get destroyed(): boolean
{
return !(this._parent && this.initBehaviors.length);
}
/**
* Destroys the emitter and all of its particles.
*/
public destroy(): void
{
// make sure we aren't still listening to any tickers
this.autoUpdate = false;
// puts all active particles in the pool, and removes them from the particle parent
this.cleanup();
// wipe the pool clean
let next;
for (let particle = this._poolFirst; particle; particle = next)
{
// store next value so we don't lose it in our destroy call
next = particle.next;
particle.destroy();
}
this._poolFirst = this._parent = this.spawnPos = this.ownerPos
= this.customEase = this._completeCallback = null;
this.initBehaviors.length = this.updateBehaviors.length = this.recycleBehaviors.length = 0;
}
} | the_stack |
import InternalEvent from '../view/event/InternalEvent';
import Point from '../view/geometry/Point';
import MaxPopupMenu from './MaxPopupMenu';
import EventSource from '../view/event/EventSource';
import EventObject from '../view/event/EventObject';
import Client from '../Client';
import { br, write, writeln } from '../util/domUtils';
import Cell from '../view/cell/Cell';
import { KeyboardEventListener, MouseEventListener, PopupMenuItem } from '../types';
interface HTMLSelectOptionWithFunct extends HTMLOptionElement {
funct?: (evt: any) => void;
};
interface HTMLImageElementWithProps extends HTMLImageElement {
initialClassName?: any;
altIcon?: any;
};
/**
* Creates a toolbar inside a given DOM node. The toolbar may contain icons,
* buttons and combo boxes.
*
* ### Event: mxEvent.SELECT
*
* Fires when an item was selected in the toolbar. The <code>function</code>
* property contains the function that was selected in <selectMode>.
*
* @class MaxToolbar
* @extends {EventSource}
*/
class MaxToolbar extends EventSource {
constructor(container: HTMLElement) {
super();
this.container = container;
}
menu: MaxPopupMenu | null = null;
currentImg: HTMLImageElementWithProps | HTMLButtonElement | null = null;
selectedMode: HTMLImageElementWithProps | null = null;
defaultMode: HTMLImageElementWithProps | HTMLButtonElement | null = null;
defaultFunction: Function | null = null;
/**
* Reference to the DOM nodes that contains the toolbar.
*/
container: HTMLElement;
/**
* Specifies if events are handled. Default is true.
*/
enabled: boolean = true;
/**
* Specifies if <resetMode> requires a forced flag of true for resetting
* the current mode in the toolbar. Default is false. This is set to true
* if the toolbar item is double clicked to avoid a reset after a single
* use of the item.
*/
noReset: boolean = false;
/**
* Boolean indicating if the default mode should be the last selected
* switch mode or the first inserted switch mode. Default is true, that
* is the last selected switch mode is the default mode. The default mode
* is the mode to be selected after a reset of the toolbar. If this is
* false, then the default mode is the first inserted mode item regardless
* of what was last selected. Otherwise, the selected item after a reset is
* the previously selected item.
*/
updateDefaultMode: boolean = true;
/**
* Adds the given function as an image with the specified title and icon
* and returns the new image node.
*
* @param title Optional string that is used as the tooltip.
* @param icon Optional URL of the image to be used. If no URL is given, then a
* button is created.
* @param funct Function to execute on a mouse click.
* @param pressedIcon Optional URL of the pressed image. Default is a gray
* background.
* @param style Optional style classname. Default is mxToolbarItem.
* @param factoryMethod Optional factory method for popup menu, eg.
* (menu, evt, cell)=> { menu.addItem('Hello, World!'); }
*/
addItem(
title: string | null=null,
icon: string | null=null,
funct: MouseEventListener | KeyboardEventListener | null=null,
pressedIcon: string | null=null,
style: string | null=null,
factoryMethod: ((handler: PopupMenuItem, cell: Cell | null, me: MouseEvent) => void) | null=null)
{
const img = document.createElement(icon != null ? 'img' : 'button');
const initialClassName =
style || (factoryMethod != null ? 'mxToolbarMode' : 'mxToolbarItem');
img.className = initialClassName;
if (icon) {
img.setAttribute('src', icon);
}
if (title != null) {
if (icon != null) {
img.setAttribute('title', title);
} else {
write(img, title);
}
}
this.container.appendChild(img);
// Invokes the function on a click on the toolbar item
if (funct != null) {
InternalEvent.addListener(img, 'click', funct);
if (Client.IS_TOUCH) {
InternalEvent.addListener(img, 'touchend', funct);
}
}
const mouseHandler = (evt: MouseEvent) => {
if (pressedIcon != null) {
img.setAttribute('src', <string>icon);
} else {
img.style.backgroundColor = '';
}
};
// Highlights the toolbar item with a gray background
// while it is being clicked with the mouse
InternalEvent.addGestureListeners(
img,
(evt) => {
if (pressedIcon != null) {
img.setAttribute('src', pressedIcon);
} else {
img.style.backgroundColor = 'gray';
}
// Popup Menu
if (factoryMethod != null) {
if (this.menu == null) {
this.menu = new MaxPopupMenu();
//this.menu.init();
}
const last = this.currentImg;
if (this.menu.isMenuShowing()) {
this.menu.hideMenu();
}
if (last != img) {
// Redirects factory method to local factory method
this.currentImg = img;
this.menu.factoryMethod = factoryMethod;
const point = new Point(img.offsetLeft, img.offsetTop + img.offsetHeight);
this.menu.popup(point.x, point.y, null, evt);
// Sets and overrides to restore classname
if (this.menu.isMenuShowing()) {
img.className = `${initialClassName}Selected`;
const hideMenu = this.menu.hideMenu;
this.menu.hideMenu = () => {
hideMenu.apply(this);
img.className = initialClassName;
this.currentImg = null;
};
}
}
}
},
null,
mouseHandler
);
InternalEvent.addListener(img, 'mouseout', mouseHandler);
return img;
}
/**
* Adds and returns a new SELECT element using the given style. The element
* is placed inside a DIV with the mxToolbarComboContainer style classname.
*
* @param style - Optional style classname. Default is mxToolbarCombo.
*/
addCombo(style?: string): HTMLSelectElement {
const div = document.createElement('div');
div.style.display = 'inline';
div.className = 'mxToolbarComboContainer';
const select = document.createElement('select');
select.className = style || 'mxToolbarCombo';
div.appendChild(select);
this.container.appendChild(div);
return select;
}
/**
* Adds and returns a new SELECT element using the given title as the
* default element. The selection is reset to this element after each
* change.
*
* @param title - String that specifies the title of the default element.
* @param style - Optional style classname. Default is mxToolbarCombo.
*/
addActionCombo(title: string, style?: string): HTMLSelectElement {
const select = document.createElement('select');
select.className = style || 'mxToolbarCombo';
this.addOption(select, title, null);
InternalEvent.addListener(select, 'change', (evt: InternalEvent) => {
const value = <HTMLSelectOptionWithFunct>select.options[select.selectedIndex];
select.selectedIndex = 0;
if (value.funct != null) {
value.funct(evt);
}
});
this.container.appendChild(select);
return select;
}
/**
* Adds and returns a new OPTION element inside the given SELECT element.
* If the given value is a function then it is stored in the option's funct
* field.
*
* @param combo - SELECT element that will contain the new entry.
* @param title - String that specifies the title of the option.
* @param value - Specifies the value associated with this option.
*/
addOption(combo: HTMLSelectElement, title: string, value: string | ((evt: any) => void) | null = null): HTMLOptionElement {
const option = <HTMLSelectOptionWithFunct>document.createElement('option');
writeln(option, title);
if (typeof value === 'function') {
option.funct = value;
} else {
option.setAttribute('value', <string>value);
}
combo.appendChild(option);
return option;
}
/**
* Adds a new selectable item to the toolbar. Only one switch mode item may
* be selected at a time. The currently selected item is the default item
* after a reset of the toolbar.
*/
addSwitchMode(
title: string,
icon: string, funct: () => void,
pressedIcon: string | null=null,
style: string='mxToolbarMode'
) {
const img = <HTMLImageElementWithProps>document.createElement('img');
img.initialClassName = style;
img.className = img.initialClassName;
img.setAttribute('src', icon);
img.altIcon = pressedIcon;
if (title != null) {
img.setAttribute('title', title);
}
InternalEvent.addListener(img, 'click', (evt: MouseEvent) => {
const selectedModeImg = <HTMLImageElementWithProps>this.selectedMode;
let tmp = selectedModeImg.altIcon;
if (tmp != null) {
selectedModeImg.altIcon = selectedModeImg.getAttribute('src');
selectedModeImg.setAttribute('src', tmp);
} else {
selectedModeImg.className = selectedModeImg.initialClassName;
}
if (this.updateDefaultMode) {
this.defaultMode = img;
}
this.selectedMode = img;
tmp = img.altIcon;
if (tmp != null) {
img.altIcon = img.getAttribute('src');
img.setAttribute('src', tmp);
} else {
img.className = `${img.initialClassName}Selected`;
}
this.fireEvent(new EventObject(InternalEvent.SELECT));
funct();
});
this.container.appendChild(img);
if (this.defaultMode == null) {
this.defaultMode = img;
// Function should fire only once so
// do not pass it with the select event
this.selectMode(img);
funct();
}
return img;
}
/**
* Adds a new item to the toolbar. The selection is typically reset after
* the item has been consumed, for example by adding a new vertex to the
* graph. The reset is not carried out if the item is double clicked.
*
* The function argument uses the following signature: funct(evt, cell) where
* evt is the native mouse event and cell is the cell under the mouse.
*/
addMode(
title: string | null=null,
icon: string | null=null,
funct: Function,
pressedIcon: string,
style: string | null=null,
toggle: boolean=false
) {
toggle = toggle != null ? toggle : true;
const img = <HTMLImageElementWithProps>document.createElement(icon != null ? 'img' : 'button');
img.initialClassName = style || 'mxToolbarMode';
img.className = img.initialClassName;
if (icon) {
img.setAttribute('src', icon);
}
img.altIcon = pressedIcon;
if (title != null) {
img.setAttribute('title', title);
}
if (this.enabled && toggle) {
InternalEvent.addListener(img, 'click', (evt: MouseEvent) => {
this.selectMode(img, funct);
this.noReset = false;
});
InternalEvent.addListener(img, 'dblclick', (evt: MouseEvent) => {
this.selectMode(img, funct);
this.noReset = true;
});
if (this.defaultMode == null) {
this.defaultMode = img;
this.defaultFunction = funct;
this.selectMode(img, funct);
}
}
this.container.appendChild(img);
return img;
}
/**
* Resets the state of the previously selected mode and displays the given
* DOM node as selected. This function fires a select event with the given
* function as a parameter.
*/
selectMode(domNode: HTMLImageElement, funct: Function | null=null): void {
if (this.selectedMode != domNode) {
if (this.selectedMode != null) {
const tmp = this.selectedMode.altIcon;
if (tmp != null) {
this.selectedMode.altIcon = this.selectedMode.getAttribute('src');
this.selectedMode.setAttribute('src', tmp);
} else {
this.selectedMode.className = this.selectedMode.initialClassName;
}
}
this.selectedMode = domNode;
const tmp = this.selectedMode.altIcon;
if (tmp != null) {
this.selectedMode.altIcon = this.selectedMode.getAttribute('src');
this.selectedMode.setAttribute('src', tmp);
} else {
this.selectedMode.className = `${this.selectedMode.initialClassName}Selected`;
}
this.fireEvent(new EventObject(InternalEvent.SELECT, { function: funct }));
}
}
/**
* Selects the default mode and resets the state of the previously selected
* mode.
*/
resetMode(forced: boolean=false): void {
if ((forced || !this.noReset) && this.selectedMode != this.defaultMode) {
// The last selected switch mode will be activated
// so the function was already executed and is
// no longer required here
this.selectMode(<HTMLImageElement>this.defaultMode, this.defaultFunction);
}
}
/**
* Adds the specifies image as a separator.
*
* @param icon - URL of the separator icon.
*/
addSeparator(icon: string): HTMLImageElement | HTMLButtonElement {
return this.addItem(null, icon, null);
}
/**
* Adds a break to the container.
*/
addBreak(): void {
br(this.container);
}
/**
* Adds a horizontal line to the container.
*/
addLine(): void {
const hr = document.createElement('hr');
hr.style.marginRight = '6px';
hr.setAttribute('size', '1');
this.container.appendChild(hr);
}
/**
* Removes the toolbar and all its associated resources.
*/
destroy(): void {
InternalEvent.release(this.container);
// @ts-ignore
this.container = null;
this.defaultMode = null;
this.defaultFunction = null;
this.selectedMode = null;
if (this.menu != null) {
this.menu.destroy();
}
}
}
export default MaxToolbar; | the_stack |
import TimeLog from './time_log';
/**
* A BLeak configuration file.
*/
export interface IBLeakConfig {
/** REQUIRED **/
// URL to web page to check for memory leaks.
url: string;
// Runs your program in a loop. Each step has a "check" function, and a "next" function
// to transition to the next step in the loop.
loop: Step[];
/** OPTIONAL **/
// Number of iterations to do
iterations: number;
// Number of iterations to perform during a ranking evaluation.
rankingEvaluationIterations: number;
// Number of runs to perform during a ranking evaluation.
rankingEvaluationRuns: number;
// Leaks to consider "fixed" during run.
fixedLeaks: number[];
// Maps leak roots back to distinct leak fixes, identified by their first heap path. Used to evaluate different ranking metrics.
fixMap: {[leakRoot: string]: number};
login: Step[];
setup: Step[];
// How long (in milliseconds) to wait for a step transition to finish before declaring an error.
// Default: 10 minutes (10 * 60 * 1000)
timeout: number;
rewrite: (url: string, type: string, source: Buffer, fixes: number[]) => Buffer;
// How long (in milliseconds) to wait between a check() returning 'true' and transitioning to the next step or taking a heap snapshot.
// Default: 1000
postCheckSleep: number;
// How long (in milliseconds) to wait between transitioning to the next step and running check() for the first time.
// Default: 0
postNextSleep: number;
// How long (in milliseconds) to wait between submitting login credentials and reloading the page for a run.
// Default: 5000
postLoginSleep: number;
}
export type StepType = "login" | "setup" | "loop";
/**
* A stage in an application loop.
*/
export interface Step {
// Return 'true' if the program has finished loading the current state
check: () => boolean;
// Transitions to the next step.
next: () => null | undefined;
}
/**
* Chrome heap snapshot.
*/
export interface HeapSnapshot {
snapshot: HeapSnapshotContents;
nodes: number[];
edges: number[];
trace_function_info: any[];
trace_tree: any[];
samples: any[];
strings: string[];
}
export interface HeapSnapshotContents {
meta: HeapSnapshotMeta;
node_count: number;
edge_count: number;
trace_function_count: number;
root_index?: number;
}
export interface HeapSnapshotMeta {
node_fields: string[];
node_types: (string | string[])[];
edge_fields: string[];
edge_types: (string | string[])[];
trace_function_info_fields: string[];
trace_node_fields: string[];
sample_fields: string[];
}
/**
* The type of a heap snapshot edge.
* Copied from `v8-profiler.h`.
*/
export const enum SnapshotEdgeType {
ContextVariable = 0, // A variable from a function context.
Element = 1, // An element of an array.
Property = 2, // A named object property.
Internal = 3, // A link that can't be accessed from JS,
// thus, its name isn't a real property name
// (e.g. parts of a ConsString).
Hidden = 4, // A link that is needed for proper sizes
// calculation, but may be hidden from user.
Shortcut = 5, // A link that must not be followed during
// sizes calculation.
Weak = 6 // A weak reference (ignored by the GC).
}
export function SnapshotEdgeTypeToString(se: SnapshotEdgeType): string {
switch (se) {
case SnapshotEdgeType.ContextVariable:
return "ContextVariable";
case SnapshotEdgeType.Element:
return "Element";
case SnapshotEdgeType.Hidden:
return "Hidden";
case SnapshotEdgeType.Internal:
return "Internal";
case SnapshotEdgeType.Property:
return "Property";
case SnapshotEdgeType.Shortcut:
return "Shortcut";
case SnapshotEdgeType.Weak:
return "Weak";
default:
return "(Unknown)";
}
}
/**
* The type of a heap snapshot node.
* Copied from `v8-profiler.h`.
*/
export const enum SnapshotNodeType {
Hidden = 0, // Hidden node, may be filtered when shown to user.
Array = 1, // An array of elements.
String = 2, // A string.
Object = 3, // A JS object (except for arrays and strings).
Code = 4, // Compiled code.
Closure = 5, // Function closure.
RegExp = 6, // RegExp.
HeapNumber = 7, // Number stored in the heap.
Native = 8, // Native object (not from V8 heap).
Synthetic = 9, // Synthetic object, usualy used for grouping
// snapshot items together.
ConsString = 10, // Concatenated string. A pair of pointers to strings.
SlicedString = 11, // Sliced string. A fragment of another string.
Symbol = 12, // A Symbol (ES6).
Unresolved = 15 // (Internal) Not resolved yet.
}
/**
* A summary of a heap snapshot's size
*/
export interface SnapshotSizeSummary {
numNodes: number;
numEdges: number;
totalSize: number;
hiddenSize: number;
arraySize: number;
stringSize: number;
objectSize: number;
codeSize: number;
closureSize: number;
regexpSize: number;
heapNumberSize: number;
nativeSize: number;
syntheticSize: number;
consStringSize: number;
slicedStringSize: number;
symbolSize: number;
unknownSize: number;
}
export function SnapshotNodeTypeToString(sn: SnapshotNodeType): string {
switch (sn) {
case SnapshotNodeType.Array:
return "Array";
case SnapshotNodeType.Closure:
return "Closure";
case SnapshotNodeType.Code:
return "Code";
case SnapshotNodeType.ConsString:
return "ConsString";
case SnapshotNodeType.HeapNumber:
return "HeapNumber";
case SnapshotNodeType.Hidden:
return "Hidden";
case SnapshotNodeType.Native:
return "Native";
case SnapshotNodeType.Object:
return "Object";
case SnapshotNodeType.RegExp:
return "RegExp";
case SnapshotNodeType.SlicedString:
return "SlicedString";
case SnapshotNodeType.String:
return "String";
case SnapshotNodeType.Symbol:
return "Symbol";
case SnapshotNodeType.Synthetic:
return "Synthetic";
case SnapshotNodeType.Unresolved:
return "Unresolved";
default:
return "(Unknown)";
}
}
// rankingEvaluation[rankingName][top n fixed][run] => heap size over time
export interface RankingEvaluation {
transitiveClosureSize: SnapshotSizeSummary[][][];
leakShare: SnapshotSizeSummary[][][];
retainedSize: SnapshotSizeSummary[][][];
}
/**
* The raw output of BLeak, as a JSON object.
*/
export interface IBLeakResults {
// A listing of memory leaks in no particular order.
leaks: ILeakRoot[];
// All unique stack frames.
stackFrames: IStackFrame[];
// The program's original source files.
sourceFiles: ISourceFileRepository;
// Heap statistics, broken down by iteration.
heapStats: SnapshotSizeSummary[];
// Performance of different rankings.
rankingEvaluation: RankingEvaluation;
}
/**
* Represents a single leak root.
*/
export interface ILeakRoot {
// Unique ID for this leak root.
id: number;
// Paths through the heap to this leak.
paths: IPath[];
scores: ILeakScores;
stacks: IStack[];
}
/**
* Represents a heap path.
*/
export type IPath = IPathSegment[];
/**
* Contains various leak scores for a given memory leak.
*/
export interface ILeakScores {
transitiveClosureSize: number;
leakShare: number;
retainedSize: number;
ownedObjects: number;
}
/**
* Contains a collection of source files, indexed by URL.
*/
export interface ISourceFileRepository {
[url: string]: ISourceFile;
}
/**
* Represents a single source file. Must be JavaScript or HTML.
*/
export interface ISourceFile {
mimeType: "text/javascript" | "text/html";
source: string;
}
/**
* Represents a stack frame in a concise JSON format.
* [url, line, column, functionName, source]
*/
export type IStackFrame = [string, number, number, string, string];
/**
* Represents a stack trace. Each number is an offset into the stackFrames array.
*/
export type IStack = number[];
/**
* Logging interface. Specified so that `console` satisfies this interface.
*/
export interface Log {
// A debug println.
debug(data: string): void;
// A regular println.
log(data: string): void;
// Print an error
error(data: string): void;
// Runs the given function f. If time logging is enabled, inserts an
// event into the time log with the given operation type.
timeEvent<T>(operation: OperationType, f: () => T): T;
// Returns the time log.
getTimeLog(): TimeLog | null;
}
/**
* Operations that we measure overhead for.
*/
export const enum OperationType {
LEAK_IDENTIFICATION_AND_RANKING = "LeakIdentificationAndRanking",
LEAK_DIAGNOSES = "LeakDiagnoses",
// Called whenever the proxy code is running. Superset of all of the
// other proxy options.
PROXY_RUNNING = "ProxyRunning",
// The webpage issued an intercepted request via the proxy.
PROXY_REWRITE = "ProxyRewrite",
// The webpage issued an intercepted request via the proxy during diagnosis.
PROXY_DIAGNOSIS_REWRITE = "ProxyDiagnosisRewrite",
// The webpage ran eval().
PROXY_EVAL_REWRITE = "ProxyEvalRewrite",
// The webpage ran eval() during diagnosis.
PROXY_EVAL_DIAGNOSIS_REWRITE = "ProxyEvalDiagnosisRewrite",
// The webpage loaded HTML that the proxy is rewriting.
PROXY_HTML_REWRITE = "ProxyHTMLRewrite",
// BLeak is waiting for the webpage to get to a certain state.
WAIT_FOR_PAGE = "WaitForPage",
// BLeak is parsing a heap snapshot
HEAP_SNAPSHOT_PARSE = "HeapSnapshotParse",
// BLeak is running the PropagateGrowth algorithm
PROPAGATE_GROWTH = "PropagateGrowth",
// BLeak is running the FindLeakPaths algorithm
FIND_LEAK_PATHS = "FindLeakPaths",
// BLeak is running the CalculateLeakShare algorithm, along w/
// retained size and transitive closure size
CALCULATE_METRICS = "CalculateMetrics",
// BLeak is collecting stack traces from the webpage, and using
// source maps to translate them from the transformed code to the
// source code.
GET_GROWTH_STACKS = "GetGrowthStacks",
// BLeak is sleeping.
SLEEP = "Sleep",
// BLeak is navigating to a webpage and waiting for it to load.
NAVIGATE = "Navigate"
}
/**
* Interface for a progress bar.
*/
export interface IProgressBar extends Log {
// Proceed to the next operation.
nextOperation(): void;
// Go to 100% complete, regardless of current completion amount.
finish(): void;
// Abort the progress bar due to a fatal error.
abort(): void;
// Update the current description w/o moving the progress bar.
updateDescription(desc: string): void;
// The total number of operations that need to be performed.
setOperationCount(count: number): void;
}
/**
* Indicates an item's growth status.
* **MUST FIT INTO 2 BITS.** (Value <= 3)
*/
export const enum GrowthStatus {
NEW = 0,
NOT_GROWING = 1,
GROWING = 2
} | the_stack |
namespace display {
class Chart {
// Variables used for data configuration.
private font: image.Font;
private times: number[];
private values: number[];
// grid
private gridRows: number;
private gridCols: number;
private gridWidth: number;
private gridHeight: number;
// chart rendering
private chartWidth: number;
private chartHeight: number;
private scaleXMin: number;
private scaleXMax: number;
private scaleYMin: number;
private scaleYMax: number;
private axisPaddingX: number;
private axisPaddingY: number;
// estimated best number of entries
private maxEntries: number;
public backgroundColor: number;
public axisColor: number;
public lineColor: number;
constructor() {
this.font = image.font5;
this.backgroundColor = 0;
this.axisColor = 1;
this.lineColor = 1;
this.axisPaddingX = 22;
this.axisPaddingY = this.font.charHeight + 4;
this.gridRows = 2;
this.gridCols = 2; // computed on the fly
this.times = [];
this.values = [];
this.chartWidth = screen.width - this.axisPaddingX;
this.chartHeight = screen.height - this.axisPaddingY;
this.maxEntries = (this.chartWidth - 2) / 2;
}
public addPoint(value: number) {
this.times.push(control.millis() / 1000);
this.values.push(value);
if (this.times.length > this.maxEntries * 2) {
this.times = this.times.slice(this.times.length - this.maxEntries - 1, this.times.length - 1);
this.values = this.values.slice(this.values.length - this.maxEntries - 1, this.values.length - 1);
}
}
public render() {
if (this.times.length < 2) return;
this.calculateScale();
screen.fill(this.backgroundColor);
this.drawAxes();
this.drawChartGrid();
this.drawGraphPoints();
}
private calculateScale() {
this.scaleYMax = this.values[0];
this.scaleYMin = this.values[0];
for (let j = 0, len2 = this.values.length; j < len2; j++) {
if (this.scaleYMax < this.values[j]) {
this.scaleYMax = this.values[j];
}
if (this.scaleYMin > this.values[j]) {
this.scaleYMin = this.values[j];
}
}
// avoid empty interval
if (this.scaleXMin === this.scaleXMax)
this.scaleXMax = this.scaleXMin + 1; // TODO
if (this.scaleYMin === this.scaleYMax)
this.scaleYMax = this.scaleYMin + 1; // TODO
// update axis to look better
let rx = generateSteps(0, this.times[this.times.length - 1] - this.times[0], 4);
this.scaleXMin = rx[0];
this.scaleXMax = rx[1];
this.gridCols = rx[2];
let ry = generateSteps(this.scaleYMin, this.scaleYMax, 6);
this.scaleYMin = ry[0];
this.scaleYMax = ry[1];
this.gridRows = ry[2];
// update y-axis width
let xl = 0;
const yRange = this.scaleYMax - this.scaleYMin;
const yUnit = yRange / this.gridRows;
for (let i = 0; i <= this.gridRows; ++i)
xl = Math.max(roundWithPrecision(this.scaleYMax - (i * yUnit), 2).toString().length, xl);
this.axisPaddingX = xl * this.font.charWidth + 4;
this.chartWidth = screen.width - this.axisPaddingX;
this.maxEntries = (this.chartWidth - 2) / 2;
// Calculate the grid for background / scale.
this.gridWidth = this.chartWidth / this.gridCols; // This is the width of the grid cells (background and axes).
this.gridHeight = this.chartHeight / this.gridRows; // This is the height of the grid cells (background axes).
}
private drawChartGrid() {
const c = this.axisColor;
const tipLength = 3;
screen.drawRect(0, 0, this.chartWidth, this.chartHeight, c);
for (let i = 0; i < this.gridCols; i++) {
screen.drawLine(i * this.gridWidth, this.chartHeight, i * this.gridWidth, this.chartHeight - tipLength, c);
screen.drawLine(i * this.gridWidth, 0, i * this.gridWidth, tipLength, c);
}
for (let i = 0; i < this.gridRows; i++) {
screen.drawLine(0, i * this.gridHeight, tipLength, i * this.gridHeight, c);
screen.drawLine(this.chartWidth, i * this.gridHeight, this.chartWidth - tipLength, i * this.gridHeight, c);
}
}
private drawAxes() {
const c = this.axisColor;
const xRange = this.scaleXMax - this.scaleXMin;
const yRange = this.scaleYMax - this.scaleYMin;
const xUnit = xRange / this.gridCols;
const yUnit = yRange / this.gridRows;
// Draw the y-axes labels.
let text = '';
for (let i = 0; i <= this.gridRows; i++) {
text = roundWithPrecision(this.scaleYMax - (i * yUnit), 2).toString();
let y = i * this.gridHeight - this.font.charHeight / 2;
if (i == this.gridRows)
y -= this.font.charHeight / 2;
else if (i == 0)
y += this.font.charHeight / 2;
screen.print(text, this.chartWidth + 5, y, c, this.font);
}
// Draw the x-axis labels
for (let i = 0; i <= this.gridCols; i++) {
text = roundWithPrecision((i * xUnit), 2).toString();
let x = i * this.gridWidth;
if (i > 0)
x -= this.font.charWidth / 2; // move one char to the left
screen.print(text, x, this.chartHeight + (this.axisPaddingY - 2 - this.font.charHeight), c, this.font);
}
}
private drawGraphPoints() {
const c = this.lineColor;
// Determine the scaling factor based on the min / max ranges.
const xRange = this.scaleXMax - this.scaleXMin;
const yRange = this.scaleYMax - this.scaleYMin;
const xFactor = this.chartWidth / xRange;
let yFactor = this.chartHeight / yRange;
let nextX = 0;
let nextY = (this.values[0] - this.scaleYMin) * yFactor;
const startX = nextX;
const startY = nextY;
for (let i = 1; i < this.values.length; i++) {
let prevX = nextX;
let prevY = nextY;
nextX = (this.times[i] - this.times[0]) * xFactor;
nextY = (this.values[i] - this.scaleYMin) * yFactor;
screen.drawLine(prevX, prevY, nextX, nextY, c);
}
}
}
// helpers
function log10(x: number): number {
return Math.log(x) / Math.log(10);
}
function roundWithPrecision(x: number, digits: number): number {
if (digits <= 0) return Math.round(x);
let d = Math.pow(10, digits);
return Math.round(x * d) / d;
}
function generateSteps(start: number, end: number, numberOfTicks: number): number[] {
let bases = [1, 5, 2, 3]; // Tick bases selection
let currentBase: number;
let n: number;
let intervalSize: number, upperBound: number, lowerBound: number;
let nIntervals: number, nMaxIntervals: number;
let the_intervalsize = 0.1;
let exponentYmax =
Math.floor(Math.max(log10(Math.abs(start)), log10(Math.abs(end))));
let mantissaYmax = end / Math.pow(10.0, exponentYmax);
// now check if numbers can be cleaned...
// make it pretty
let significative_numbers = Math.min(3, Math.abs(exponentYmax) + 1);
let expo = Math.pow(10.0, significative_numbers);
let start_norm = Math.abs(start) * expo;
let end_norm = Math.abs(end) * expo;
let mant_norm = Math.abs(mantissaYmax) * expo;
// trunc ends
let ip_start = Math.floor(start_norm * Math.sign(start));
let ip_end = Math.ceil(end_norm * Math.sign(end));
start = ip_start;
end = ip_end;
mantissaYmax = Math.ceil(mant_norm);
nMaxIntervals = 0;
for (let k = 0; k < bases.length; ++k) {
// Loop initialisation
currentBase = bases[k];
n = 4; // This value only allows results smaller than about 1000 = 10^n
do // Tick vector length reduction
{
--n;
intervalSize = currentBase * Math.pow(10.0, exponentYmax - n);
upperBound =
Math.ceil(mantissaYmax * Math.pow(10.0, n) / currentBase)
* intervalSize;
nIntervals =
Math.ceil((upperBound - start) / intervalSize);
lowerBound = upperBound - nIntervals * intervalSize;
}
while (nIntervals > numberOfTicks);
if (nIntervals > nMaxIntervals) {
nMaxIntervals = nIntervals;
ip_start = ip_start = lowerBound;
ip_end = upperBound;
the_intervalsize = intervalSize;
}
}
// trunc ends
if (start < 0)
start = Math.floor(ip_start) / expo;
else
start = Math.ceil(ip_start) / expo;
if (end < 0)
end = Math.floor(ip_end) / expo;
else
end = Math.ceil(ip_end) / expo;
return [start, end, nMaxIntervals];
}
let chart: Chart;
/**
* Adds a new point to the trend chart and renders it to the screen.
*/
//% group="Charts"
//% blockId=graphadd block="graph %value"
//% blockGap=8
export function graph(value: number) {
if (!chart)
chart = new Chart();
chart.addPoint(value);
chart.render();
}
/**
* Clears the trend chart and the screen
*/
//% group="Charts"
//% blockid=graphclear block="graph clear"
export function graphClear() {
chart = undefined;
screen.fill(0);
}
} | the_stack |
import { Transaction, EditorState } from "prosemirror-state";
import {
newHoverIdReceived,
requestMatchesForDocument,
selectMatch,
setConfigValue,
requestMatchesSuccess,
requestError,
requestMatchesForDirtyRanges,
requestMatchesComplete,
removeMatch,
removeAllMatches,
newHighlightIdReceived,
setFilterState
} from "./state/actions";
import {
selectMatchByMatchId,
selectAllAutoFixableMatches
} from "./state/selectors";
import {
PROSEMIRROR_TYPERIGHTER_ACTION,
IPluginState,
IPluginConfig
} from "./state/reducer";
import {
IMatcherResponse,
TMatchRequestErrorWithDefault
} from "./interfaces/IMatch";
import { EditorView } from "prosemirror-view";
import { compact } from "./utils/array";
import {
getPatchesFromReplacementText,
applyPatchToTransaction
} from "./utils/prosemirror";
type Command = (
state: EditorState,
dispatch?: (tr: Transaction) => void
) => boolean;
type GetState<TPluginState extends IPluginState = IPluginState> = (
state: EditorState
) => TPluginState;
/**
* Requests matches for an entire document.
*/
export const requestMatchesForDocumentCommand = (
requestId: string,
categoryIds: string[]
): Command => (state, dispatch) => {
if (dispatch) {
dispatch(
state.tr.setMeta(
PROSEMIRROR_TYPERIGHTER_ACTION,
requestMatchesForDocument(requestId, categoryIds)
)
);
}
return true;
};
/**
* Request matches for the current set of dirty ranges.
*/
export const requestMatchesForDirtyRangesCommand = (
requestId: string,
categoryIds: string[]
): Command => (state, dispatch) => {
if (dispatch) {
dispatch(
state.tr.setMeta(
PROSEMIRROR_TYPERIGHTER_ACTION,
requestMatchesForDirtyRanges(requestId, categoryIds)
)
);
}
return true;
};
/**
* Indicate the user is hovering over a match.
*/
export const startHoverCommand = (matchId: string, rectIndex: number | undefined): Command => (
state,
dispatch
) => {
if (dispatch) {
dispatch(
state.tr.setMeta(
PROSEMIRROR_TYPERIGHTER_ACTION,
newHoverIdReceived(matchId, rectIndex)
)
);
}
return true;
};
/**
* Indicate that the user is no longer hovering over a match.
*/
export const stopHoverCommand = (): Command => (state, dispatch) => {
if (dispatch) {
dispatch(
state.tr.setMeta(
PROSEMIRROR_TYPERIGHTER_ACTION,
newHoverIdReceived(undefined, undefined)
)
);
}
return true;
};
/**
* Indicate the user is highlighting a match decoration.
*
* The highlight state indicates that we'd like to draw the user's
* attention to this match, without additional UI elements, e.g. tooltips.
*/
export const startHighlightCommand = (matchId: string): Command => (
state,
dispatch
) => {
if (dispatch) {
dispatch(
state.tr.setMeta(
PROSEMIRROR_TYPERIGHTER_ACTION,
newHighlightIdReceived(matchId)
)
);
}
return true;
};
/**
* Indicate that the user is no longer highlighting a match decoration.
*/
export const stopHighlightCommand = (): Command => (state, dispatch) => {
if (dispatch) {
dispatch(
state.tr.setMeta(
PROSEMIRROR_TYPERIGHTER_ACTION,
newHighlightIdReceived(undefined)
)
);
}
return true;
};
/**
* Mark a given match as active.
*/
export const selectMatchCommand = <TPluginState extends IPluginState>(
matchId: string,
getState: GetState<TPluginState>
): Command => (state, dispatch) => {
const pluginState = getState(state);
const output = selectMatchByMatchId(pluginState, matchId);
if (!output) {
return false;
}
if (dispatch) {
dispatch(
state.tr.setMeta(PROSEMIRROR_TYPERIGHTER_ACTION, selectMatch(matchId))
);
}
return true;
};
/**
* Set a configuration value.
*/
export const setConfigValueCommand = <
ConfigKey extends keyof IPluginConfig,
ConfigValue extends IPluginConfig[ConfigKey]
>(
key: ConfigKey,
value: ConfigValue
): Command => (state, dispatch) => {
if (dispatch) {
dispatch(
state.tr.setMeta(
PROSEMIRROR_TYPERIGHTER_ACTION,
setConfigValue(key, value)
)
);
}
return true;
};
/**
* Set the current filter state.
*/
export const setFilterStateCommand = <TPluginState extends IPluginState>(
filterState: TPluginState["filterState"]
): Command => (state, dispatch) => {
if (dispatch) {
dispatch(
state.tr.setMeta(
PROSEMIRROR_TYPERIGHTER_ACTION,
setFilterState(filterState)
)
);
}
return true;
};
/**
* Apply a successful matcher response to the document.
*/
export const applyMatcherResponseCommand = (
matcherResponse: IMatcherResponse
): Command => (state, dispatch) => {
if (dispatch) {
dispatch(
state.tr.setMeta(
PROSEMIRROR_TYPERIGHTER_ACTION,
requestMatchesSuccess(matcherResponse)
)
);
}
return true;
};
/**
* Apply an error to the document. Important to ensure
* that failed matcher requests are reapplied as dirtied ranges
* to be resent on the next request.
*/
export const applyRequestErrorCommand = (
matchRequestError: TMatchRequestErrorWithDefault
): Command => (state, dispatch) => {
if (dispatch) {
dispatch(
state.tr.setMeta(
PROSEMIRROR_TYPERIGHTER_ACTION,
requestError({
...matchRequestError,
type: matchRequestError.type || "GENERAL_ERROR"
})
)
);
}
return true;
};
/**
* Mark the
*/
export const applyRequestCompleteCommand = (requestId: string): Command => (
state,
dispatch
) => {
if (dispatch) {
dispatch(
state.tr.setMeta(
PROSEMIRROR_TYPERIGHTER_ACTION,
requestMatchesComplete(requestId)
)
);
}
return true;
};
export type ApplySuggestionOptions = Array<{
matchId: string;
text: string;
}>;
/**
* Applies a suggestion from a match to the document.
*/
export const applySuggestionsCommand = (
suggestionOptions: ApplySuggestionOptions,
getState: GetState
): Command => (state, dispatch) => {
const pluginState = getState(state);
const suggestionsToApply = suggestionOptions
.map(opt => {
const maybeMatch = selectMatchByMatchId(pluginState, opt.matchId);
return maybeMatch
? {
from: maybeMatch.from,
to: maybeMatch.to,
text: opt.text
}
: undefined;
})
.filter(compact);
return maybeApplySuggestions(suggestionsToApply, state, dispatch);
};
/**
* Applies the first suggestion for each rule marked as auto-fixable.
*/
export const applyAutoFixableSuggestionsCommand = (
getState: GetState
): Command => (state, dispatch) => {
const pluginState = getState(state);
const suggestionsToApply = selectAllAutoFixableMatches(pluginState).map(
output => ({
from: output.from,
to: output.to,
text:
output.suggestions && output.suggestions.length
? output.suggestions[0].text
: undefined
})
);
return maybeApplySuggestions(suggestionsToApply, state, dispatch);
};
/**
* Ignore a match, removing it from the plugin state.
* Returns true if the match was found, false if not.
*/
export const ignoreMatchCommand = (id: string) => (getState: GetState) => (
state: EditorState,
dispatch?: (tr: Transaction<any>) => void
): boolean => {
const match = selectMatchByMatchId(getState(state), id);
if (match && dispatch) {
dispatch(state.tr.setMeta(PROSEMIRROR_TYPERIGHTER_ACTION, removeMatch(id)));
}
return !!match;
};
export const clearMatchesCommand = () => <TPluginState extends IPluginState>(
_: GetState<TPluginState>
) => (
state: EditorState,
dispatch?: (tr: Transaction<any>) => void
): boolean => {
if (dispatch) {
dispatch(state.tr.setMeta(PROSEMIRROR_TYPERIGHTER_ACTION, removeAllMatches()));
}
return true;
};
const maybeApplySuggestions = (
suggestionsToApply: Array<{
from: number;
to: number;
text: string | undefined;
}>,
state: EditorState,
dispatch?: (tr: Transaction<any>) => void
) => {
if (!suggestionsToApply.length) {
return false;
}
if (!dispatch) {
return true;
}
const tr = state.tr;
suggestionsToApply.forEach(({ from, to, text }) => {
if (!text) {
return;
}
const mappedFrom = tr.mapping.map(from);
const mappedTo = tr.mapping.map(to);
const replacementFrags = getPatchesFromReplacementText(
tr,
mappedFrom,
mappedTo,
text
);
replacementFrags.forEach(frag =>
applyPatchToTransaction(tr, state.schema, frag)
);
});
dispatch(tr);
return true;
};
/**
* Create a palette of prosemirror-typerighter commands bound to the given EditorView.
*/
export const createBoundCommands = <TPluginState extends IPluginState>(
view: EditorView,
getState: GetState<TPluginState>
) => {
const bindCommand = <CommandArgs extends any[]>(
action: (...args: CommandArgs) => Command
) => (...args: CommandArgs) => action(...args)(view.state, view.dispatch);
return {
ignoreMatch: (id: string) =>
ignoreMatchCommand(id)(getState)(view.state, view.dispatch),
clearMatches: () => clearMatchesCommand()(getState)(view.state, view.dispatch),
applySuggestions: (suggestionOpts: ApplySuggestionOptions) =>
applySuggestionsCommand(suggestionOpts, getState)(
view.state,
view.dispatch
),
selectMatch: (blockId: string) =>
selectMatchCommand(blockId, getState)(view.state, view.dispatch),
applyAutoFixableSuggestions: () =>
applyAutoFixableSuggestionsCommand(getState)(view.state, view.dispatch),
requestMatchesForDocument: bindCommand(requestMatchesForDocumentCommand),
requestMatchesForDirtyRanges: bindCommand(
requestMatchesForDirtyRangesCommand
),
indicateHover: bindCommand(startHoverCommand),
stopHover: bindCommand(stopHoverCommand),
indicateHighlight: bindCommand(startHighlightCommand),
stopHighlight: bindCommand(stopHighlightCommand),
setConfigValue: bindCommand(setConfigValueCommand),
applyMatcherResponse: bindCommand(applyMatcherResponseCommand),
applyRequestError: bindCommand(applyRequestErrorCommand),
applyRequestComplete: bindCommand(applyRequestCompleteCommand),
setFilterState: bindCommand(setFilterStateCommand)
};
};
export type Commands = ReturnType<typeof createBoundCommands>; | the_stack |
import * as net from 'net';
import {YouTube, Twitch} from '../chat-plugins/youtube';
import {Net, Utils} from '../../lib';
import {RoomSections} from './room-settings';
const ONLINE_SYMBOL = ` \u25C9 `;
const OFFLINE_SYMBOL = ` \u25CC `;
export function getCommonBattles(
userID1: ID, user1: User | null, userID2: ID, user2: User | null, connection: Connection
) {
const battles = [];
for (const curRoom of Rooms.rooms.values()) {
if (!curRoom.battle) continue;
if (
(user1?.inRooms.has(curRoom.roomid) || curRoom.auth.get(userID1) === Users.PLAYER_SYMBOL) &&
(user2?.inRooms.has(curRoom.roomid) || curRoom.auth.get(userID2) === Users.PLAYER_SYMBOL)
) {
if (connection) {
void curRoom.uploadReplay(connection.user, connection, "forpunishment");
}
battles.push(curRoom.roomid);
}
}
return battles;
}
export function findFormats(targetId: string, isOMSearch = false) {
const exactFormat = Dex.formats.get(targetId);
const formatList = exactFormat.exists ? [exactFormat] : Dex.formats.all();
// Filter formats and group by section
const sections: {[k: string]: {name: string, formats: ID[]}} = {};
let totalMatches = 0;
for (const format of formatList) {
const sectionId = toID(format.section);
// Skip generation prefix if it wasn't provided
const formatId = /^gen\d+/.test(targetId) ? format.id : format.id.slice(4);
if (
!targetId || format[targetId + 'Show' as 'searchShow'] || sectionId === targetId ||
formatId.startsWith(targetId) || exactFormat.exists
) {
if (isOMSearch) {
const officialFormats = [
'ou', 'uu', 'ru', 'nu', 'pu', 'ubers', 'lc', 'monotype', 'customgame', 'doublescustomgame', 'gbusingles', 'gbudoubles',
];
if (format.id.startsWith('gen') && officialFormats.includes(format.id.slice(4))) {
continue;
}
}
totalMatches++;
if (!sections[sectionId]) sections[sectionId] = {name: format.section!, formats: []};
sections[sectionId].formats.push(format.id);
}
}
return {totalMatches, sections};
}
export const commands: Chat.ChatCommands = {
ip: 'whois',
rooms: 'whois',
alt: 'whois',
alts: 'whois',
whoare: 'whois',
altsnorecurse: 'whois',
profile: 'whois',
whois(target, room, user, connection, cmd) {
if (room?.roomid === 'staff' && !this.runBroadcast()) return;
const targetUser = this.getUserOrSelf(target, {exactName: user.tempGroup === ' '});
const showAll = (cmd === 'ip' || cmd === 'whoare' || cmd === 'alt' || cmd === 'alts' || cmd === 'altsnorecurse');
const showRecursiveAlts = showAll && (cmd !== 'altsnorecurse');
if (!targetUser) {
if (showAll) return this.parse('/offlinewhois ' + target);
return this.errorReply(`User ${target} not found.`);
}
if (showAll && !user.trusted && targetUser !== user) {
return this.errorReply(`/${cmd} - Access denied.`);
}
let buf = Utils.html`<strong class="username"><small style="display:none">${targetUser.tempGroup}</small>${targetUser.name}</strong> `;
const ac = targetUser.autoconfirmed;
if (ac && showAll) {
buf += ` <small style="color:gray">(ac${targetUser.id === ac ? `` : `: <span class="username">${ac}</span>`})</small>`;
}
const trusted = targetUser.trusted;
if (trusted && showAll) {
buf += ` <small style="color:gray">(trusted${targetUser.id === trusted ? `` : `: <span class="username">${trusted}</span>`})</small>`;
}
if (!targetUser.connected) buf += ` <em style="color:gray">(offline)</em>`;
const roomauth = room?.auth.getDirect(targetUser.id);
if (roomauth && Config.groups[roomauth]?.name) {
buf += Utils.html`<br />${Config.groups[roomauth].name} (${roomauth})`;
}
if (Config.groups[targetUser.tempGroup]?.name) {
buf += Utils.html`<br />Global ${Config.groups[targetUser.tempGroup].name} (${targetUser.tempGroup})`;
}
if (Users.globalAuth.sectionLeaders.has(targetUser.id)) {
buf += Utils.html`<br />Section Leader (${RoomSections.sectionNames[Users.globalAuth.sectionLeaders.get(targetUser.id)!]})`;
}
if (targetUser.isSysop) {
buf += `<br />(Pokémon Showdown System Operator)`;
}
if (!targetUser.registered) {
buf += `<br />(Unregistered)`;
}
let publicrooms = ``;
let hiddenrooms = ``;
let privaterooms = ``;
for (const roomid of targetUser.inRooms) {
const targetRoom = Rooms.get(roomid)!;
const authSymbol = targetRoom.auth.getDirect(targetUser.id).trim();
const battleTitle = (targetRoom.battle ? ` title="${targetRoom.title}"` : '');
const output = `${authSymbol}<a href="/${roomid}"${battleTitle}>${roomid}</a>`;
if (targetRoom.settings.isPrivate === true) {
if (targetRoom.settings.modjoin === '~') continue;
if (privaterooms) privaterooms += ` | `;
privaterooms += output;
} else if (targetRoom.settings.isPrivate) {
if (hiddenrooms) hiddenrooms += ` | `;
hiddenrooms += output;
} else {
if (publicrooms) publicrooms += ` | `;
publicrooms += output;
}
}
buf += `<br />Rooms: ${publicrooms || `<em>(no public rooms)</em>`}`;
if (!showAll) {
return this.sendReplyBox(buf);
}
const canViewAlts = (user === targetUser ? user.can('altsself') : user.can('alts', targetUser));
const canViewPunishments = canViewAlts ||
(room && room.settings.isPrivate !== true && user.can('mute', targetUser, room) && targetUser.id in room.users);
const canViewSecretRooms = user === targetUser || (canViewAlts && targetUser.locked) || user.can('makeroom');
buf += `<br />`;
if (canViewAlts) {
let prevNames = targetUser.previousIDs.map(userid => {
const punishments = Punishments.userids.get(userid);
if (!punishments || !user.can('alts')) return userid;
return punishments.map(
punishment => (
`${userid}${punishment ? ` (${Punishments.punishmentTypes.get(punishment.type)?.desc || `punished`}` +
`${punishment.id !== targetUser.id ? ` as ${punishment.id}` : ``})` : ``}`
)
).join(' | ');
}).join(", ");
if (prevNames) buf += Utils.html`<br />Previous names: ${prevNames}`;
for (const targetAlt of targetUser.getAltUsers(true)) {
if (!targetAlt.named && !targetAlt.connected) continue;
if (targetAlt.tempGroup === '~' && user.tempGroup !== '~') continue;
const punishments = Punishments.userids.get(targetAlt.id) || [];
const punishMsg = !user.can('alts') ? '' : punishments.map(punishment => (
` (${Punishments.punishmentTypes.get(punishment.type)?.desc || 'punished'}` +
`${punishment.id !== targetAlt.id ? ` as ${punishment.id}` : ''})`
)).join(' | ');
buf += Utils.html`<br />Alt: <span class="username">${targetAlt.name}</span>${punishMsg}`;
if (!targetAlt.connected) buf += ` <em style="color:gray">(offline)</em>`;
prevNames = targetAlt.previousIDs.map(userid => {
const p = Punishments.userids.get(userid);
if (!p || !user.can('alts')) return userid;
return p.map(
cur => `${userid} (${Punishments.punishmentTypes.get(cur.type)?.desc || 'punished'}` + `${cur.id !== targetAlt.id ? ` as ${cur.id}` : ``})`
).join(' | ');
}).join(", ");
if (prevNames) buf += `<br />Previous names: ${prevNames}`;
}
}
if (canViewPunishments) {
if (targetUser.namelocked) {
buf += `<br />NAMELOCKED: ${targetUser.namelocked}`;
const punishment = Punishments.userids.getByType(targetUser.locked!, 'NAMELOCK');
if (punishment) {
const expiresIn = Punishments.checkLockExpiration(targetUser.locked);
if (expiresIn) buf += expiresIn;
if (punishment.reason) buf += Utils.html` (reason: ${punishment.reason})`;
}
} else if (targetUser.locked) {
buf += `<br />LOCKED: ${targetUser.locked}`;
switch (targetUser.locked) {
case '#rangelock':
buf += ` - IP or host is in a temporary range-lock`;
break;
case '#hostfilter':
buf += ` - host is permanently locked for being a proxy`;
break;
}
const punishment = Punishments.userids.getByType(targetUser.locked, 'LOCK');
if (punishment) {
const expiresIn = Punishments.checkLockExpiration(targetUser.locked);
if (expiresIn) buf += expiresIn;
if (punishment.reason) buf += Utils.html` (reason: ${punishment.reason})`;
}
}
if (user.can('lock')) {
const battlebanned = Punishments.isBattleBanned(targetUser);
if (battlebanned) {
buf += `<br />BATTLEBANNED: ${battlebanned.id}`;
buf += ` ${Punishments.checkPunishmentExpiration(battlebanned)}`;
if (battlebanned.reason) buf += Utils.html` (reason: ${battlebanned.reason})`;
}
const groupchatbanned = Punishments.isGroupchatBanned(targetUser);
if (groupchatbanned) {
buf += `<br />Banned from using groupchats${groupchatbanned.id !== targetUser.id ? `: ${groupchatbanned.id}` : ``}`;
buf += ` ${Punishments.checkPunishmentExpiration(groupchatbanned)}`;
if (groupchatbanned.reason) buf += Utils.html` (reason: ${groupchatbanned.reason})`;
}
const ticketbanned = Punishments.isTicketBanned(targetUser.id);
if (ticketbanned) {
buf += `<br />Banned from creating help tickets${ticketbanned.id !== targetUser.id ? `: ${ticketbanned.id}` : ``}`;
buf += ` ${Punishments.checkPunishmentExpiration(ticketbanned)}`;
if (ticketbanned.reason) buf += Utils.html` (reason: ${ticketbanned.reason})`;
}
}
if (targetUser.semilocked) {
buf += `<br />Semilocked: ${user.can('lock') ? targetUser.semilocked : "(reason hidden)"}`;
}
}
if (user === targetUser ? user.can('ipself') : user.can('ip', targetUser)) {
const ips = targetUser.ips.map(ip => {
const status = [];
const punishments = Punishments.ips.get(ip);
if (user.can('alts') && punishments) {
for (const punishment of punishments) {
const {type, id} = punishment;
let punishMsg = Punishments.punishmentTypes.get(type)?.desc || type;
if (id !== targetUser.id) punishMsg += ` as ${id}`;
status.push(punishMsg);
}
}
if (Punishments.isSharedIp(ip)) {
let sharedStr = 'shared';
if (Punishments.sharedIps.get(ip)) {
sharedStr += `: ${Punishments.sharedIps.get(ip)}`;
}
status.push(sharedStr);
}
return `<a href="https://whatismyipaddress.com/ip/${ip}" target="_blank">${ip}</a>` + (status.length ? ` (${status.join('; ')})` : '');
});
buf += `<br /> IP${Chat.plural(ips)}: ${ips.join(", ")}`;
if (user.tempGroup !== ' ' && targetUser.latestHost) {
buf += Utils.html`<br />Host: ${targetUser.latestHost} [${targetUser.latestHostType}]`;
}
} else if (user === targetUser) {
buf += `<br /> IP: <a href="https://whatismyipaddress.com/ip/${connection.ip}" target="_blank">${connection.ip}</a>`;
}
if (canViewAlts && hiddenrooms) {
buf += `<br />Hidden rooms: ${hiddenrooms}`;
}
if (canViewSecretRooms && privaterooms) {
buf += `<br />Secret rooms: ${privaterooms}`;
}
const gameRooms = [];
for (const curRoom of Rooms.rooms.values()) {
if (!curRoom.game) continue;
const inPlayerTable = targetUser.id in curRoom.game.playerTable && !targetUser.inRooms.has(curRoom.roomid);
const hasPlayerSymbol = curRoom.auth.getDirect(targetUser.id) === Users.PLAYER_SYMBOL;
const canSeeRoom = canViewAlts || user === targetUser || !curRoom.settings.isPrivate;
if ((inPlayerTable || hasPlayerSymbol) && canSeeRoom) {
gameRooms.push(curRoom.roomid);
}
}
if (gameRooms.length) {
buf += `<br />Recent games: ${gameRooms.map(id => {
const shortId = id.startsWith('battle-') ? id.slice(7) : id;
return Utils.html`<a href="/${id}">${shortId}</a>`;
}).join(' | ')}`;
}
if (canViewPunishments) {
const punishments = Punishments.getRoomPunishments(targetUser, {checkIps: true});
if (punishments.length) {
buf += `<br />Room punishments: `;
buf += punishments.map(([curRoom, curPunishment]) => {
const {type: punishType, id: punishUserid, expireTime, reason} = curPunishment;
let punishDesc = Punishments.roomPunishmentTypes.get(punishType)?.desc || punishType;
if (punishUserid !== targetUser.id) punishDesc += ` as ${punishUserid}`;
const expiresIn = new Date(expireTime).getTime() - Date.now();
const expireString = Chat.toDurationString(expiresIn, {precision: 1});
punishDesc += ` for ${expireString}`;
if (reason) punishDesc += `: ${reason}`;
return `<a href="/${curRoom}">${curRoom}</a> (${punishDesc})`;
}).join(', ');
}
}
this.sendReplyBox(buf);
if (showRecursiveAlts && canViewAlts) {
const targetId = toID(target);
for (const alt of Users.users.values()) {
if (alt !== targetUser && alt.previousIDs.includes(targetId)) {
void this.parse(`/altsnorecurse ${alt.name}`);
}
}
}
},
whoishelp: [
`/whois - Get details on yourself: alts, group, IP address, and rooms.`,
`/whois [username] - Get details on a username: alts (Requires: % @ &), group, IP address (Requires: @ &), and rooms.`,
],
'chp': 'offlinewhois',
checkpunishment: 'offlinewhois',
offlinewhois(target, room, user) {
if (!user.trusted) {
return this.errorReply("/offlinewhois - Access denied.");
}
const userid = toID(target);
if (!userid) return this.errorReply("Please enter a valid username.");
const targetUser = Users.get(userid);
let buf = Utils.html`<strong class="username">${target}</strong>`;
if (!targetUser?.connected) buf += ` <em style="color:gray">(offline)</em>`;
const roomauth = room?.auth.getDirect(userid);
if (roomauth && Config.groups[roomauth]?.name) {
buf += `<br />${Config.groups[roomauth].name} (${roomauth})`;
}
const group = Users.globalAuth.get(userid);
if (Config.groups[group]?.name) {
buf += `<br />Global ${Config.groups[group].name} (${group})`;
}
if (Users.globalAuth.sectionLeaders.has(userid)) {
buf += `<br />Section Leader (${RoomSections.sectionNames[Users.globalAuth.sectionLeaders.get(userid)!]})`;
}
buf += `<br /><br />`;
let atLeastOne = false;
const idPunishments = Punishments.userids.get(userid);
if (idPunishments) {
for (const p of idPunishments) {
const {type: punishType, id: punishUserid, reason} = p;
if (!user.can('alts') && !['LOCK', 'BAN'].includes(punishType)) continue;
const punishDesc = (Punishments.punishmentTypes.get(punishType)?.desc || punishType);
buf += `${punishDesc}: ${punishUserid}`;
const expiresIn = Punishments.checkLockExpiration(userid);
if (expiresIn) buf += expiresIn;
if (reason) buf += Utils.html` (reason: ${reason})`;
buf += '<br />';
atLeastOne = true;
}
}
if (!user.can('alts') && !atLeastOne) {
const hasJurisdiction = room && user.can('mute', null, room) && Punishments.roomUserids.nestedHas(room.roomid, userid);
if (!hasJurisdiction) {
return this.errorReply("/checkpunishment - User not found.");
}
}
const punishments = Punishments.getRoomPunishments(targetUser || {id: userid} as User);
if (punishments?.length) {
buf += `<br />Room punishments: `;
buf += punishments.map(([curRoom, curPunishment]) => {
const {type: punishType, id: punishUserid, expireTime, reason} = curPunishment;
let punishDesc = Punishments.roomPunishmentTypes.get(punishType)?.desc || punishType;
if (punishUserid !== userid) punishDesc += ` as ${punishUserid}`;
const expiresIn = new Date(expireTime).getTime() - Date.now();
const expireString = Chat.toDurationString(expiresIn, {precision: 1});
punishDesc += ` for ${expireString}`;
if (reason) punishDesc += `: ${reason}`;
return `<a href="/${curRoom}">${curRoom}</a> (${punishDesc})`;
}).join(', ');
atLeastOne = true;
}
if (!atLeastOne) {
buf += `This username has no punishments associated with it.`;
}
this.sendReplyBox(buf);
},
offlinewhoishelp: [
`/offlinewhois [username] - Get details on a username without requiring them to be online.`,
`Requires: trusted user. `,
],
sbtl: 'sharedbattles',
sharedbattles(target, room) {
this.checkCan('lock');
const [targetUsername1, targetUsername2] = target.split(',');
if (!targetUsername1 || !targetUsername2) return this.parse(`/help sharedbattles`);
const user1 = Users.get(targetUsername1);
const user2 = Users.get(targetUsername2);
const userID1 = toID(targetUsername1);
const userID2 = toID(targetUsername2);
const battles = getCommonBattles(userID1, user1, userID2, user2, this.connection);
if (!battles.length) return this.sendReply(`${targetUsername1} and ${targetUsername2} have no common battles.`);
this.sendReplyBox(Utils.html`Common battles between ${targetUsername1} and ${targetUsername2}:<br />` + battles.map(id => {
const shortId = id.startsWith('battle-') ? id.slice(7) : id;
return Utils.html`<a href="/${id}">${shortId}</a>`;
}).join(' | '));
},
sharedbattleshelp: [`/sharedbattles [user1], [user2] - Finds recent battles common to [user1] and [user2]. Requires % @ &`],
sp: 'showpunishments',
showpunishments(target, room, user) {
room = this.requireRoom();
if (!room.persist) {
return this.errorReply("This command is unavailable in temporary rooms.");
}
return this.parse(`/join view-punishments-${room}`);
},
showpunishmentshelp: [`/showpunishments - Shows the current punishments in the room. Requires: % @ # &`],
sgp: 'showglobalpunishments',
showglobalpunishments(target, room, user) {
this.checkCan('lock');
return this.parse(`/join view-globalpunishments`);
},
showglobalpunishmentshelp: [`/showpunishments - Shows the current global punishments. Requires: % @ # &`],
async host(target, room, user, connection, cmd) {
if (!target) return this.parse('/help host');
this.checkCan('alts');
target = target.trim();
if (!net.isIPv4(target)) return this.errorReply('You must pass a valid IPv4 IP to /host.');
const {dnsbl, host, hostType} = await IPTools.lookup(target);
const dnsblMessage = dnsbl ? ` [${dnsbl}]` : ``;
this.sendReply(`IP ${target}: ${host || "ERROR"} [${hostType}]${dnsblMessage}`);
},
hosthelp: [`/host [ip] - Gets the host for a given IP. Requires: % @ &`],
searchip: 'ipsearch',
ipsearchall: 'ipsearch',
hostsearch: 'ipsearch',
ipsearch(target, room, user, connection, cmd) {
if (!target.trim()) return this.parse(`/help ipsearch`);
this.checkCan('rangeban');
const [ipOrHost, roomid] = this.splitOne(target);
const targetRoom = roomid ? Rooms.get(roomid) : null;
if (typeof targetRoom === 'undefined') {
return this.errorReply(`The room "${roomid}" does not exist.`);
}
const results: string[] = [];
const isAll = (cmd === 'ipsearchall');
if (/[a-z]/.test(ipOrHost)) {
// host
this.sendReply(`Users with host ${ipOrHost}${targetRoom ? ` in the room ${targetRoom.title}` : ``}:`);
for (const curUser of Users.users.values()) {
if (results.length > 100 && !isAll) break;
if (!curUser.latestHost?.endsWith(ipOrHost)) continue;
if (targetRoom && !curUser.inRooms.has(targetRoom.roomid)) continue;
results.push(`${curUser.connected ? ONLINE_SYMBOL : OFFLINE_SYMBOL} ${curUser.name}`);
}
} else if (IPTools.ipRegex.test(ipOrHost)) {
// ip
this.sendReply(`Users with IP ${ipOrHost}${targetRoom ? ` in the room ${targetRoom.title}` : ``}:`);
for (const curUser of Users.users.values()) {
if (!curUser.ips.some(ip => ip === ipOrHost)) continue;
if (targetRoom && !curUser.inRooms.has(targetRoom.roomid)) continue;
results.push(`${curUser.connected ? ONLINE_SYMBOL : OFFLINE_SYMBOL} ${curUser.name}`);
}
} else if (IPTools.isValidRange(ipOrHost)) {
// range
this.sendReply(`Users in IP range ${ipOrHost}${targetRoom ? ` in the room ${targetRoom.title}` : ``}:`);
const checker = IPTools.checker(ipOrHost);
for (const curUser of Users.users.values()) {
if (results.length > 100 && !isAll) continue;
if (!curUser.ips.some(ip => checker(ip))) continue;
if (targetRoom && !curUser.inRooms.has(targetRoom.roomid)) continue;
results.push(`${curUser.connected ? ONLINE_SYMBOL : OFFLINE_SYMBOL} ${curUser.name}`);
}
} else {
return this.errorReply(`${ipOrHost} is not a valid IP, IP range, or host.`);
}
if (!results.length) {
return this.sendReply(`No users found.`);
}
this.sendReply(results.slice(0, 100).join('; '));
if (results.length > 100 && !isAll) {
this.sendReply(`More than 100 users found. Use /ipsearchall for the full list.`);
}
},
ipsearchhelp: [`/ipsearch [ip|range|host], (room) - Find all users with specified IP, IP range, or host. If a room is provided only users in the room will be shown. Requires: &`],
checkchallenges(target, room, user) {
room = this.requireRoom();
if (!user.can('addhtml', null, room)) this.checkCan('ban', null, room);
if (!this.runBroadcast(true)) return;
if (!this.broadcasting) {
this.errorReply(`This command must be broadcast:`);
return this.parse(`/help checkchallenges`);
}
if (!target || !target.includes(',')) return this.parse(`/help checkchallenges`);
const {targetUser: user1, rest} = this.requireUser(target);
const {targetUser: user2, rest: rest2} = this.requireUser(rest);
if (user1 === user2 || rest2) return this.parse(`/help checkchallenges`);
if (!(user1.id in room.users) || !(user2.id in room.users)) {
return this.errorReply(`Both users must be in this room.`);
}
const chall = Ladders.challenges.search(user1.id, user2.id);
if (!chall) {
return this.sendReplyBox(Utils.html`${user1.name} and ${user2.name} are not challenging each other.`);
}
const [from, to] = user1.id === chall.from ? [user1, user2] : [user2, user1];
this.sendReplyBox(Utils.html`${from.name} is challenging ${to.name} in ${Dex.formats.get(chall.format).name}.`);
},
checkchallengeshelp: [`!checkchallenges [user1], [user2] - Check if the specified users are challenging each other. Requires: * @ # &`],
/*********************************************************
* Client fallback
*********************************************************/
unignore: 'ignore',
ignore(target, room, user) {
if (!room) {
this.errorReply(`In PMs, this command can only be used by itself to ignore the person you're talking to: "/${this.cmd}", not "/${this.cmd} ${target}"`);
}
this.errorReply(`You're using a custom client that doesn't support the ignore command.`);
},
ignorehelp: [`/ignore [user] - Ignore the given [user].`],
/*********************************************************
* Data Search Dex
*********************************************************/
pstats: 'data',
stats: 'data',
dex: 'data',
pokedex: 'data',
data(target, room, user, connection, cmd) {
if (!this.runBroadcast()) return;
const gen = parseInt(cmd.substr(-1));
if (gen) target += `, gen${gen}`;
const {dex, format, targets} = this.splitFormat(target, true);
let buffer = '';
target = targets.join(',');
const targetId = toID(target);
if (!targetId) return this.parse('/help data');
const targetNum = parseInt(target);
if (!isNaN(targetNum) && `${targetNum}` === target) {
for (const pokemon of Dex.species.all()) {
if (pokemon.num === targetNum) {
target = pokemon.baseSpecies;
break;
}
}
}
const newTargets = dex.dataSearch(target);
const showDetails = (cmd.startsWith('dt') || cmd === 'details');
if (!newTargets || !newTargets.length) {
return this.errorReply(`No Pok\u00e9mon, item, move, ability or nature named '${target}' was found${Dex.gen > dex.gen ? ` in Gen ${dex.gen}` : ""}. (Check your spelling?)`);
}
for (const [i, newTarget] of newTargets.entries()) {
if (newTarget.isInexact && !i) {
buffer = `No Pok\u00e9mon, item, move, ability or nature named '${target}' was found${Dex.gen > dex.gen ? ` in Gen ${dex.gen}` : ""}. Showing the data of '${newTargets[0].name}' instead.\n`;
}
let details: {[k: string]: string} = {};
switch (newTarget.searchType) {
case 'nature':
const nature = Dex.natures.get(newTarget.name);
buffer += `${nature.name} nature: `;
if (nature.plus) {
buffer += `+10% ${Dex.stats.names[nature.plus]}, -10% ${Dex.stats.names[nature.minus!]}.`;
} else {
buffer += `No effect.`;
}
return this.sendReply(buffer);
case 'pokemon':
let pokemon = dex.species.get(newTarget.name);
if (format?.onModifySpecies) {
pokemon = format.onModifySpecies.call({dex, clampIntRange: Utils.clampIntRange, toID} as Battle, pokemon) || pokemon;
}
let tierDisplay = room?.settings.dataCommandTierDisplay;
if (!tierDisplay && room?.battle) {
if (room.battle.format.includes('doubles') || room.battle.format.includes('vgc')) {
tierDisplay = 'doubles tiers';
} else if (room.battle.format.includes('nationaldex')) {
tierDisplay = 'numbers';
}
}
if (!tierDisplay) tierDisplay = 'tiers';
const displayedTier = tierDisplay === 'tiers' ? pokemon.tier :
tierDisplay === 'doubles tiers' ? pokemon.doublesTier :
pokemon.num >= 0 ? String(pokemon.num) : pokemon.tier;
buffer += `|raw|${Chat.getDataPokemonHTML(pokemon, dex.gen, displayedTier)}\n`;
if (showDetails) {
let weighthit = 20;
if (pokemon.weighthg >= 2000) {
weighthit = 120;
} else if (pokemon.weighthg >= 1000) {
weighthit = 100;
} else if (pokemon.weighthg >= 500) {
weighthit = 80;
} else if (pokemon.weighthg >= 250) {
weighthit = 60;
} else if (pokemon.weighthg >= 100) {
weighthit = 40;
}
details = {
"Dex#": String(pokemon.num),
Gen: String(pokemon.gen) || 'CAP',
Height: `${pokemon.heightm} m`,
};
details["Weight"] = `${pokemon.weighthg / 10} kg <em>(${weighthit} BP)</em>`;
const gmaxMove = pokemon.canGigantamax || dex.species.get(pokemon.changesFrom).canGigantamax;
if (gmaxMove && dex.gen >= 8) details["G-Max Move"] = gmaxMove;
if (pokemon.color && dex.gen >= 5) details["Dex Colour"] = pokemon.color;
if (pokemon.eggGroups && dex.gen >= 2) details["Egg Group(s)"] = pokemon.eggGroups.join(", ");
const evos: string[] = [];
for (const evoName of pokemon.evos) {
const evo = dex.species.get(evoName);
if (evo.gen <= dex.gen) {
const condition = evo.evoCondition ? ` ${evo.evoCondition}` : ``;
switch (evo.evoType) {
case 'levelExtra':
evos.push(`${evo.name} (level-up${condition})`);
break;
case 'levelFriendship':
evos.push(`${evo.name} (level-up with high Friendship${condition})`);
break;
case 'levelHold':
evos.push(`${evo.name} (level-up holding ${evo.evoItem}${condition})`);
break;
case 'useItem':
evos.push(`${evo.name} (${evo.evoItem})`);
break;
case 'levelMove':
evos.push(`${evo.name} (level-up with ${evo.evoMove}${condition})`);
break;
case 'other':
evos.push(`${evo.name} (${evo.evoCondition})`);
break;
case 'trade':
evos.push(`${evo.name} (trade${evo.evoItem ? ` holding ${evo.evoItem}` : condition})`);
break;
default:
evos.push(`${evo.name} (${evo.evoLevel}${condition})`);
}
}
}
if (!evos.length) {
details[`<font color="#686868">Does Not Evolve</font>`] = "";
} else {
details["Evolution"] = evos.join(", ");
}
}
break;
case 'item':
const item = dex.items.get(newTarget.name);
buffer += `|raw|${Chat.getDataItemHTML(item)}\n`;
if (showDetails) {
details = {
Gen: String(item.gen),
};
if (dex.gen >= 4) {
if (item.fling) {
details["Fling Base Power"] = String(item.fling.basePower);
if (item.fling.status) details["Fling Effect"] = item.fling.status;
if (item.fling.volatileStatus) details["Fling Effect"] = item.fling.volatileStatus;
if (item.isBerry) details["Fling Effect"] = "Activates the Berry's effect on the target.";
if (item.id === 'whiteherb') details["Fling Effect"] = "Restores the target's negative stat stages to 0.";
if (item.id === 'mentalherb') {
const flingEffect = "Removes the effects of Attract, Disable, Encore, Heal Block, Taunt, and Torment from the target.";
details["Fling Effect"] = flingEffect;
}
} else {
details["Fling"] = "This item cannot be used with Fling.";
}
}
if (item.naturalGift && dex.gen >= 3) {
details["Natural Gift Type"] = item.naturalGift.type;
details["Natural Gift Base Power"] = String(item.naturalGift.basePower);
}
if (item.isNonstandard) {
details[`Unobtainable in Gen ${dex.gen}`] = "";
}
}
break;
case 'move':
const move = dex.moves.get(newTarget.name);
buffer += `|raw|${Chat.getDataMoveHTML(move)}\n`;
if (showDetails) {
details = {
Priority: String(move.priority),
Gen: String(move.gen) || 'CAP',
};
if (move.isNonstandard === "Past" && dex.gen >= 8) details["✗ Past Gens Only"] = "";
if (move.secondary || move.secondaries) details["✓ Secondary effect"] = "";
if (move.flags['contact']) details["✓ Contact"] = "";
if (move.flags['sound']) details["✓ Sound"] = "";
if (move.flags['bullet']) details["✓ Bullet"] = "";
if (move.flags['pulse']) details["✓ Pulse"] = "";
if (!move.flags['protect'] && move.target !== 'self') details["✓ Bypasses Protect"] = "";
if (move.flags['bypasssub']) details["✓ Bypasses Substitutes"] = "";
if (move.flags['defrost']) details["✓ Thaws user"] = "";
if (move.flags['bite']) details["✓ Bite"] = "";
if (move.flags['punch']) details["✓ Punch"] = "";
if (move.flags['powder']) details["✓ Powder"] = "";
if (move.flags['reflectable']) details["✓ Bounceable"] = "";
if (move.flags['charge']) details["✓ Two-turn move"] = "";
if (move.flags['recharge']) details["✓ Has recharge turn"] = "";
if (move.flags['gravity'] && dex.gen >= 4) details["✗ Suppressed by Gravity"] = "";
if (move.flags['dance'] && dex.gen >= 7) details["✓ Dance move"] = "";
if (dex.gen >= 7) {
if (move.gen >= 8 && move.isMax) {
// Don't display Z-Power for Max/G-Max moves
} else if (move.zMove?.basePower) {
details["Z-Power"] = String(move.zMove.basePower);
} else if (move.zMove?.effect) {
const zEffects: {[k: string]: string} = {
clearnegativeboost: "Restores negative stat stages to 0",
crit2: "Crit ratio +2",
heal: "Restores HP 100%",
curse: "Restores HP 100% if user is Ghost type, otherwise Attack +1",
redirect: "Redirects opposing attacks to user",
healreplacement: "Restores replacement's HP 100%",
};
details["Z-Effect"] = zEffects[move.zMove.effect];
} else if (move.zMove?.boost) {
details["Z-Effect"] = "";
const boost = move.zMove.boost;
const stats: {[k in BoostID]: string} = {
atk: 'Attack', def: 'Defense', spa: 'Sp. Atk', spd: 'Sp. Def', spe: 'Speed', accuracy: 'Accuracy', evasion: 'Evasiveness',
};
let h: BoostID;
for (h in boost) {
details["Z-Effect"] += ` ${stats[h]} +${boost[h]}`;
}
} else if (move.isZ && typeof move.isZ === 'string') {
details["✓ Z-Move"] = "";
const zCrystal = dex.items.get(move.isZ);
details["Z-Crystal"] = zCrystal.name;
if (zCrystal.itemUser) {
details["User"] = zCrystal.itemUser.join(", ");
details["Required Move"] = dex.items.get(move.isZ).zMoveFrom!;
}
} else {
details["Z-Effect"] = "None";
}
}
if (dex.gen >= 8) {
if (move.isMax) {
details["✓ Max Move"] = "";
if (typeof move.isMax === "string") details["User"] = `${move.isMax}`;
} else if (move.maxMove?.basePower) {
details["Dynamax Power"] = String(move.maxMove.basePower);
}
}
const targetTypes: {[k: string]: string} = {
normal: "One Adjacent Pok\u00e9mon",
self: "User",
adjacentAlly: "One Ally",
adjacentAllyOrSelf: "User or Ally",
adjacentFoe: "One Adjacent Opposing Pok\u00e9mon",
allAdjacentFoes: "All Adjacent Opponents",
foeSide: "Opposing Side",
allySide: "User's Side",
allyTeam: "User's Side",
allAdjacent: "All Adjacent Pok\u00e9mon",
any: "Any Pok\u00e9mon",
all: "All Pok\u00e9mon",
scripted: "Chosen Automatically",
randomNormal: "Random Adjacent Opposing Pok\u00e9mon",
allies: "User and Allies",
};
details["Target"] = targetTypes[move.target] || "Unknown";
if (move.id === 'snatch' && dex.gen >= 3) {
details[`<a href="https://${Config.routes.dex}/tags/nonsnatchable">Non-Snatchable Moves</a>`] = '';
}
if (move.id === 'mirrormove') {
details[`<a href="https://${Config.routes.dex}/tags/nonmirror">Non-Mirrorable Moves</a>`] = '';
}
if (move.isNonstandard === 'Unobtainable') {
details[`Unobtainable in Gen ${dex.gen}`] = "";
}
}
break;
case 'ability':
const ability = dex.abilities.get(newTarget.name);
buffer += `|raw|${Chat.getDataAbilityHTML(ability)}\n`;
if (showDetails) {
details = {
Gen: String(ability.gen) || 'CAP',
};
if (ability.isPermanent) details["✓ Not affected by Gastro Acid"] = "";
if (ability.isBreakable) details["✓ Ignored by Mold Breaker"] = "";
}
break;
default:
throw new Error(`Unrecognized searchType`);
}
if (showDetails) {
buffer += `|raw|<font size="1">${Object.entries(details).map(([detail, value]) => (
value === '' ? detail : `<font color="#686868">${detail}:</font> ${value}`
)).join(" |  ")}</font>\n`;
}
}
this.sendReply(buffer);
},
datahelp: [
`/data [pokemon/item/move/ability/nature] - Get details on this pokemon/item/move/ability/nature.`,
`/data [pokemon/item/move/ability/nature], Gen [generation number/format name] - Get details on this pokemon/item/move/ability/nature for that generation/format.`,
`!data [pokemon/item/move/ability/nature] - Show everyone these details. Requires: + % @ # &`,
],
dt: 'details',
dt1: 'details',
dt2: 'details',
dt3: 'details',
dt4: 'details',
dt5: 'details',
dt6: 'details',
dt7: 'details',
dt8: 'details',
details(target) {
if (!target) return this.parse('/help details');
this.run('data');
},
detailshelp() {
this.sendReplyBox(
`<code>/details [Pok\u00e9mon/item/move/ability/nature]</code>: get additional details on this Pok\u00e9mon/item/move/ability/nature.<br />` +
`<code>/details [Pok\u00e9mon/item/move/ability/nature], Gen [generation number]</code>: get details on this Pok\u00e9mon/item/move/ability/nature in that generation.<br />` +
`You can also append the generation number to <code>/dt</code>; for example, <code>/dt1 Mewtwo</code> gets details on Mewtwo in Gen 1.<br />` +
`<code>/details [Pok\u00e9mon/item/move/ability/nature], [format]</code>: get details on this Pok\u00e9mon/item/move/ability/nature in that format.<br />` +
`<code>!details [Pok\u00e9mon/item/move/ability/nature]</code>: show everyone these details. Requires: + % @ # &`
);
},
weaknesses: 'weakness',
weak: 'weakness',
resist: 'weakness',
weakness(target, room, user) {
if (!target) return this.parse('/help weakness');
if (!this.runBroadcast()) return;
const {dex, targets} = this.splitFormat(target.split(/[,/]/).map(toID));
let isInverse = false;
if (targets[targets.length - 1] === 'inverse') {
isInverse = true;
targets.pop();
}
let species: {types: string[], [k: string]: any} = dex.species.get(targets[0]);
const type1 = dex.types.get(targets[0]);
const type2 = dex.types.get(targets[1]);
const type3 = dex.types.get(targets[2]);
if (species.exists) {
target = species.name;
} else {
const types = [];
if (type1.exists) {
types.push(type1.name);
if (type2.exists && type2 !== type1) {
types.push(type2.name);
}
if (type3.exists && type3 !== type1 && type3 !== type2) {
types.push(type3.name);
}
}
if (types.length === 0) {
return this.sendReplyBox(Utils.html`${target} isn't a recognized type or Pokemon${Dex.gen > dex.gen ? ` in Gen ${dex.gen}` : ""}.`);
}
species = {types: types};
target = types.join("/");
}
const weaknesses = [];
const resistances = [];
const immunities = [];
for (const type of dex.types.names()) {
const notImmune = dex.getImmunity(type, species);
if (notImmune || isInverse) {
let typeMod = !notImmune && isInverse ? 1 : 0;
typeMod += (isInverse ? -1 : 1) * dex.getEffectiveness(type, species);
switch (typeMod) {
case 1:
weaknesses.push(type);
break;
case 2:
weaknesses.push(`<b>${type}</b>`);
break;
case 3:
weaknesses.push(`<b><i>${type}</i></b>`);
break;
case -1:
resistances.push(type);
break;
case -2:
resistances.push(`<b>${type}</b>`);
break;
case -3:
resistances.push(`<b><i>${type}</i></b>`);
break;
}
} else {
immunities.push(type);
}
}
const statuses: {[k: string]: string} = {
brn: "Burn",
frz: "Frozen",
hail: "Hail damage",
par: "Paralysis",
powder: "Powder moves",
prankster: "Prankster",
sandstorm: "Sandstorm damage",
tox: "Toxic",
trapped: "Trapping",
};
for (const status in statuses) {
if (!dex.getImmunity(status, species)) {
immunities.push(statuses[status]);
}
}
const buffer = [];
buffer.push(`${species.exists ? `${species.name} (ignoring abilities):` : `${target}:`}`);
buffer.push(`<span class="message-effect-weak">Weaknesses</span>: ${weaknesses.join(', ') || '<font color=#999999>None</font>'}`);
buffer.push(`<span class="message-effect-resist">Resistances</span>: ${resistances.join(', ') || '<font color=#999999>None</font>'}`);
buffer.push(`<span class="message-effect-immune">Immunities</span>: ${immunities.join(', ') || '<font color=#999999>None</font>'}`);
this.sendReplyBox(buffer.join('<br />'));
},
weaknesshelp: [
`/weakness [pokemon] - Provides a Pok\u00e9mon's resistances, weaknesses, and immunities, ignoring abilities.`,
`/weakness [type 1]/[type 2] - Provides a type or type combination's resistances, weaknesses, and immunities, ignoring abilities.`,
`!weakness [pokemon] - Shows everyone a Pok\u00e9mon's resistances, weaknesses, and immunities, ignoring abilities. Requires: + % @ # &`,
`!weakness [type 1]/[type 2] - Shows everyone a type or type combination's resistances, weaknesses, and immunities, ignoring abilities. Requires: + % @ # &`,
],
eff: 'effectiveness',
type: 'effectiveness',
matchup: 'effectiveness',
effectiveness(target, room, user) {
const {dex, targets} = this.splitFormat(target.split(/[,/]/));
if (targets.length !== 2) return this.errorReply("Attacker and defender must be separated with a comma.");
let searchMethods = ['types', 'moves', 'species'];
const sourceMethods = ['types', 'moves'];
const targetMethods = ['types', 'species'];
let source;
let defender;
let foundData;
let atkName;
let defName;
for (let i = 0; i < 2; ++i) {
let method!: string;
for (const m of searchMethods) {
foundData = (dex as any)[m].get(targets[i]);
if (foundData.exists) {
method = m;
break;
}
}
if (!foundData.exists) return this.parse('/help effectiveness');
if (!source && sourceMethods.includes(method)) {
if (foundData.type) {
source = foundData;
atkName = foundData.name;
} else {
source = foundData.name;
atkName = foundData.name;
}
searchMethods = targetMethods;
} else if (!defender && targetMethods.includes(method)) {
if (foundData.types) {
defender = foundData;
defName = `${foundData.name} (not counting abilities)`;
} else {
defender = {types: [foundData.name]};
defName = foundData.name;
}
searchMethods = sourceMethods;
}
}
if (!this.runBroadcast()) return;
let factor = 0;
if (dex.getImmunity(source, defender) ||
source.ignoreImmunity && (source.ignoreImmunity === true || source.ignoreImmunity[source.type])) {
let totalTypeMod = 0;
if (source.effectType !== 'Move' || source.category !== 'Status' && (source.basePower || source.basePowerCallback)) {
for (const type of defender.types) {
const baseMod = dex.getEffectiveness(source, type);
const moveMod = source.onEffectiveness?.call({dex: Dex} as Battle, baseMod, null, type, source);
totalTypeMod += typeof moveMod === 'number' ? moveMod : baseMod;
}
}
factor = Math.pow(2, totalTypeMod);
}
const hasThousandArrows = source.id === 'thousandarrows' && defender.types.includes('Flying');
const additionalInfo = hasThousandArrows ? "<br />However, Thousand Arrows will be 1x effective on the first hit." : "";
this.sendReplyBox(`${atkName} is ${factor}x effective against ${defName}.${additionalInfo}`);
},
effectivenesshelp: [
`/effectiveness [attack], [defender] - Provides the effectiveness of a move or type on another type or a Pok\u00e9mon.`,
`!effectiveness [attack], [defender] - Shows everyone the effectiveness of a move or type on another type or a Pok\u00e9mon.`,
],
cover: 'coverage',
coverage(target, room, user) {
if (!this.runBroadcast()) return;
if (!target) return this.parse("/help coverage");
const {dex, targets} = this.splitFormat(target.split(/[,+/]/));
const sources: (string | Move)[] = [];
let dispTable = false;
const bestCoverage: {[k: string]: number} = {};
let hasThousandArrows = false;
for (const type of dex.types.names()) {
// This command uses -5 to designate immunity
bestCoverage[type] = -5;
}
for (let arg of targets) {
arg = toID(arg);
// arg is the gen?
if (arg === dex.currentMod) continue;
// arg is 'table' or 'all'?
if (arg === 'table' || arg === 'all') {
if (this.broadcasting) return this.sendReplyBox("The full table cannot be broadcast.");
dispTable = true;
continue;
}
// arg is a type?
const argType = arg.charAt(0).toUpperCase() + arg.slice(1);
let eff;
if (dex.types.isName(argType)) {
sources.push(argType);
for (const type in bestCoverage) {
if (!dex.getImmunity(argType, type)) continue;
eff = dex.getEffectiveness(argType, type);
if (eff > bestCoverage[type]) bestCoverage[type] = eff;
}
continue;
}
// arg is a move?
const move = dex.moves.get(arg);
if (!move.exists) {
return this.errorReply(`Type or move '${arg}' not found.`);
} else if (move.gen > dex.gen) {
return this.errorReply(`Move '${arg}' is not available in Gen ${dex.gen}.`);
}
if (!move.basePower && !move.basePowerCallback) continue;
if (move.id === 'thousandarrows') hasThousandArrows = true;
sources.push(move);
for (const type in bestCoverage) {
if (move.id === "struggle") {
eff = 0;
} else {
if (!dex.getImmunity(move.type, type) && !move.ignoreImmunity) continue;
const baseMod = dex.getEffectiveness(move, type);
const moveMod = move.onEffectiveness?.call({dex} as Battle, baseMod, null, type, move as ActiveMove);
eff = typeof moveMod === 'number' ? moveMod : baseMod;
}
if (eff > bestCoverage[type]) bestCoverage[type] = eff;
}
}
if (sources.length === 0) return this.errorReply("No moves using a type table for determining damage were specified.");
if (sources.length > 4) return this.errorReply("Specify a maximum of 4 moves or types.");
// converts to fractional effectiveness, 0 for immune
for (const type in bestCoverage) {
if (bestCoverage[type] === -5) {
bestCoverage[type] = 0;
continue;
}
bestCoverage[type] = Math.pow(2, bestCoverage[type]);
}
if (!dispTable) {
const buffer: string[] = [];
const superEff: string[] = [];
const neutral: string[] = [];
const resists: string[] = [];
const immune: string[] = [];
for (const type in bestCoverage) {
switch (bestCoverage[type]) {
case 0:
immune.push(type);
break;
case 0.25:
case 0.5:
resists.push(type);
break;
case 1:
neutral.push(type);
break;
case 2:
case 4:
superEff.push(type);
break;
default:
throw new Error(`/coverage effectiveness of ${bestCoverage[type]} from parameters: ${target}`);
}
}
buffer.push(`Coverage for ${sources.join(' + ')}:`);
buffer.push(`<b><font color=#559955>Super Effective</font></b>: ${superEff.join(', ') || '<font color=#999999>None</font>'}`);
buffer.push(`<span class="message-effect-resist">Neutral</span>: ${neutral.join(', ') || '<font color=#999999>None</font>'}`);
buffer.push(`<span class="message-effect-weak">Resists</span>: ${resists.join(', ') || '<font color=#999999>None</font>'}`);
buffer.push(`<span class="message-effect-immune">Immunities</span>: ${immune.join(', ') || '<font color=#999999>None</font>'}`);
return this.sendReplyBox(buffer.join('<br />'));
} else {
let buffer = '<div class="scrollable"><table cellpadding="1" width="100%"><tr><th></th>';
const icon: {[k: string]: string} = {};
for (const type of dex.types.names()) {
icon[type] = `<img src="https://${Config.routes.client}/sprites/types/${type}.png" width="32" height="14">`;
// row of icons at top
buffer += `<th>${icon[type]}</th>`;
}
buffer += '</tr>';
for (const type1 of dex.types.names()) {
// assembles the rest of the rows
buffer += `<tr><th>${icon[type1]}</th>`;
for (const type2 of dex.types.names()) {
let typing: string;
let cell = '<th ';
let bestEff = -5;
if (type1 === type2) {
// when types are the same it's considered pure type
typing = type1;
bestEff = bestCoverage[type1];
} else {
typing = `${type1}/${type2}`;
for (const move of sources) {
let curEff = 0;
if (typeof move === 'string') {
if (!dex.getImmunity(move, type1) || !dex.getImmunity(move, type2)) {
continue;
}
let baseMod = dex.getEffectiveness(move, type1);
curEff += baseMod;
baseMod = dex.getEffectiveness(move, type2);
curEff += baseMod;
} else {
if ((!dex.getImmunity(move.type, type1) || !dex.getImmunity(move.type, type2)) && !move.ignoreImmunity) {
continue;
}
let baseMod = dex.getEffectiveness(move.type, type1);
let moveMod = move.onEffectiveness?.call({dex} as Battle, baseMod, null, type1, move as ActiveMove);
curEff += typeof moveMod === 'number' ? moveMod : baseMod;
baseMod = dex.getEffectiveness(move.type, type2);
moveMod = move.onEffectiveness?.call({dex} as Battle, baseMod, null, type2, move as ActiveMove);
curEff += typeof moveMod === 'number' ? moveMod : baseMod;
}
if (curEff > bestEff) bestEff = curEff;
}
if (bestEff === -5) {
bestEff = 0;
} else {
bestEff = Math.pow(2, bestEff);
}
}
switch (bestEff) {
case 0:
cell += `bgcolor=#666666 title="${typing}"><font color=#000000>${bestEff}</font>`;
break;
case 0.25:
case 0.5:
cell += `bgcolor=#AA5544 title="${typing}"><font color=#660000>${bestEff}</font>`;
break;
case 1:
cell += `bgcolor=#6688AA title="${typing}"><font color=#000066>${bestEff}</font>`;
break;
case 2:
case 4:
cell += `bgcolor=#559955 title="${typing}"><font color=#003300>${bestEff}</font>`;
break;
default:
throw new Error(`/coverage effectiveness of ${bestEff} from parameters: ${target}`);
}
cell += '</th>';
buffer += cell;
}
}
buffer += '</table></div>';
if (hasThousandArrows) {
buffer += "<br /><b>Thousand Arrows has neutral type effectiveness on Flying-type Pok\u00e9mon if not already smacked down.";
}
this.sendReplyBox(`Coverage for ${sources.join(' + ')}:<br />${buffer}`);
}
},
coveragehelp: [
`/coverage [move 1], [move 2] ... - Provides the best effectiveness match-up against all defending types for given moves or attacking types`,
`!coverage [move 1], [move 2] ... - Shows this information to everyone.`,
`Adding the parameter 'all' or 'table' will display the information with a table of all type combinations.`,
],
statcalc(target, room, user) {
if (!target) return this.parse("/help statcalc");
if (!this.runBroadcast()) return;
const targets = target.split(' ');
let lvlSet = false;
let natureSet = false;
let ivSet = false;
let evSet = false;
let baseSet = false;
let modSet = false;
let realSet = false;
let pokemon: StatsTable | undefined;
let useStat: StatID | '' = '';
let level = 100;
let calcHP = false;
let nature = 1.0;
let iv = 31;
let ev = 252;
let baseStat = -1;
let modifier = 0;
let positiveMod = true;
let realStat = 0;
for (const arg of targets) {
const lowercase = arg.toLowerCase();
if (!lvlSet) {
if (lowercase === 'lc') {
level = 5;
lvlSet = true;
continue;
} else if (lowercase === 'vgc') {
level = 50;
lvlSet = true;
continue;
} else if (lowercase.startsWith('lv') || lowercase.startsWith('level')) {
level = parseInt(arg.replace(/\D/g, ''));
lvlSet = true;
if (level < 1 || level > 9999) {
return this.sendReplyBox('Invalid value for level: ' + level);
}
continue;
}
}
if (!useStat) {
switch (lowercase) {
case 'hp':
case 'hitpoints':
calcHP = true;
useStat = 'hp';
continue;
case 'atk':
case 'attack':
useStat = 'atk';
continue;
case 'def':
case 'defense':
useStat = 'def';
continue;
case 'spa':
useStat = 'spa';
continue;
case 'spd':
case 'sdef':
useStat = 'spd';
continue;
case 'spe':
case 'speed':
useStat = 'spe';
continue;
}
}
if (!natureSet) {
if (lowercase === 'boosting' || lowercase === 'positive') {
nature = 1.1;
natureSet = true;
continue;
} else if (lowercase === 'negative' || lowercase === 'inhibiting') {
nature = 0.9;
natureSet = true;
continue;
} else if (lowercase === 'neutral') {
continue;
}
}
if (!ivSet) {
if (lowercase.endsWith('iv') || lowercase.endsWith('ivs')) {
iv = parseInt(arg);
ivSet = true;
if (isNaN(iv)) {
return this.sendReplyBox('Invalid value for IVs: ' + Utils.escapeHTML(arg));
}
continue;
}
}
if (!evSet) {
if (lowercase === 'invested' || lowercase === 'max') {
evSet = true;
if (lowercase === 'max' && !natureSet) {
nature = 1.1;
natureSet = true;
}
} else if (lowercase === 'uninvested') {
ev = 0;
evSet = true;
} else if (lowercase.endsWith('ev') || lowercase.endsWith('evs') ||
lowercase.endsWith('+') || lowercase.endsWith('-')) {
ev = parseInt(arg);
evSet = true;
if (isNaN(ev)) {
return this.sendReplyBox('Invalid value for EVs: ' + Utils.escapeHTML(arg));
}
if (ev > 255 || ev < 0) {
return this.sendReplyBox('The amount of EVs should be between 0 and 255.');
}
if (!natureSet) {
if (arg.includes('+')) {
nature = 1.1;
natureSet = true;
} else if (arg.includes('-')) {
nature = 0.9;
natureSet = true;
}
}
continue;
}
}
if (!modSet) {
if (['band', 'scarf', 'specs'].includes(arg)) {
modifier = 1;
modSet = true;
} else if (arg.startsWith('+')) {
modifier = parseInt(arg.charAt(1));
modSet = true;
} else if (arg.startsWith('-')) {
positiveMod = false;
modifier = parseInt(arg.charAt(1));
modSet = true;
}
if (isNaN(modifier)) {
return this.sendReplyBox('Invalid value for modifier: ' + Utils.escapeHTML(String(modifier)));
}
if (modifier > 6) {
return this.sendReplyBox('Modifier should be a number between -6 and +6');
}
if (modSet) continue;
}
if (!pokemon) {
const testPoke = Dex.species.get(arg);
if (testPoke.exists) {
pokemon = testPoke.baseStats;
baseSet = true;
continue;
}
}
const tempStat = parseInt(arg);
if (!realSet) {
if (lowercase.endsWith('real')) {
realStat = tempStat;
realSet = true;
if (isNaN(realStat)) {
return this.sendReplyBox('Invalid value for target real stat: ' + Utils.escapeHTML(arg));
}
if (realStat < 0) {
return this.sendReplyBox('The target real stat must be greater than 0.');
}
continue;
}
}
if (!isNaN(tempStat) && !baseSet && tempStat > 0 && tempStat < 256) {
baseStat = tempStat;
baseSet = true;
}
}
if (pokemon) {
if (useStat) {
baseStat = pokemon[useStat];
} else {
return this.sendReplyBox('No stat found.');
}
}
if (realSet) {
if (!baseSet) {
if (calcHP) {
baseStat = Math.ceil((100 * realStat - 10 - level * (Math.floor(ev / 4) + iv + 100)) / (2 * level));
} else {
if (!positiveMod) {
realStat *= (2 + modifier) / 2;
} else {
realStat *= 2 / (2 + modifier);
}
baseStat = Math.ceil(
(100 * Math.ceil(realStat) - nature * (level * (Math.floor(ev / 4) + iv) + 500)) /
(2 * level * nature)
);
}
if (baseStat < 0) {
return this.sendReplyBox('No valid value for base stat possible with given parameters.');
}
} else if (!evSet) {
if (calcHP) {
ev = Math.ceil(100 * (realStat - 10) / level - 2 * (baseStat + 50));
} else {
if (!positiveMod) {
realStat *= (2 + modifier) / 2;
} else {
realStat *= 2 / (2 + modifier);
}
ev = Math.ceil(-1 * (2 * (nature * (baseStat * level + 250) - 50 * Math.ceil(realStat))) / (level * nature));
}
ev -= 31;
if (ev < 0) iv += ev;
ev *= 4;
if (iv < 0 || ev > 255) {
return this.sendReplyBox('No valid EV/IV combination possible with given parameters. Maybe try a different nature?' + ev);
}
} else {
return this.sendReplyBox('Too many parameters given; nothing to calculate.');
}
} else if (baseStat < 0) {
return this.sendReplyBox('No valid value for base stat found.');
}
let output: number;
if (calcHP) {
output = (((iv + (2 * baseStat) + Math.floor(ev / 4) + 100) * level) / 100) + 10;
} else {
output = Math.floor(nature * Math.floor((((iv + (2 * baseStat) + Math.floor(ev / 4)) * level) / 100) + 5));
if (positiveMod) {
output *= (2 + modifier) / 2;
} else {
output *= 2 / (2 + modifier);
}
}
return this.sendReplyBox(`Base ${baseStat} ${calcHP ? ' HP ' : ' '}at level ${level} with ${iv} IVs, ${ev}${nature === 1.1 ? '+' : nature === 0.9 ? '-' : ''} EVs${modifier > 0 && !calcHP ? ` at ${positiveMod ? '+' : '-'}${modifier}` : ''}: <b>${Math.floor(output)}</b>.`);
},
statcalchelp: [
`/statcalc [level] [base stat] [IVs] [nature] [EVs] [modifier] (only base stat is required) - Calculates what the actual stat of a Pokémon is with the given parameters. For example, '/statcalc lv50 100 30iv positive 252ev scarf' calculates the speed of a base 100 scarfer with HP Ice in Battle Spot, and '/statcalc uninvested 90 neutral' calculates the attack of an uninvested Crobat.`,
`!statcalc [level] [base stat] [IVs] [nature] [EVs] [modifier] (only base stat is required) - Shows this information to everyone.`,
`Inputing 'hp' as an argument makes it use the formula for HP. Instead of giving nature, '+' and '-' can be appended to the EV amount (e.g. 252+ev) to signify a boosting or inhibiting nature.`,
`An actual stat can be given in place of a base stat or EVs. In this case, the minumum base stat or EVs necessary to have that real stat with the given parameters will be determined. For example, '/statcalc 502real 252+ +1' calculates the minimum base speed necessary for a positive natured fully invested scarfer to outspeed`,
],
/*********************************************************
* Informational commands
*********************************************************/
uptime(target, room, user) {
if (!this.runBroadcast()) return;
const uptime = process.uptime();
let uptimeText;
if (uptime > 24 * 60 * 60) {
const uptimeDays = Math.floor(uptime / (24 * 60 * 60));
uptimeText = uptimeDays + " " + (uptimeDays === 1 ? "day" : "days");
const uptimeHours = Math.floor(uptime / (60 * 60)) - uptimeDays * 24;
if (uptimeHours) uptimeText += ", " + uptimeHours + " " + (uptimeHours === 1 ? "hour" : "hours");
} else {
uptimeText = Chat.toDurationString(uptime * 1000);
}
this.sendReplyBox("Uptime: <b>" + uptimeText + "</b>");
},
uptimehelp: [`/uptime - Shows how long the server has been online for.`],
st: 'servertime',
servertime(target, room, user) {
if (!this.runBroadcast()) return;
const servertime = new Date();
this.sendReplyBox(`Server time: <b>${servertime.toLocaleString()}</b>`);
},
servertimehelp: [`/servertime - Shows the current time where the server is.`],
groups(target, room, user) {
if (!this.runBroadcast()) return;
target = toID(target);
const showRoom = (target !== 'global');
const showGlobal = (target !== 'room' && target !== 'rooms');
const roomRanks = [
`<strong>Room ranks</strong>`,
`^ <strong>Prize Winner</strong> - They don't have any powers beyond a symbol.`,
`+ <strong>Voice</strong> - They can use ! commands like !groups`,
`% <strong>Driver</strong> - The above, and they can mute and warn`,
`@ <strong>Moderator</strong> - The above, and they can room ban users`,
`* <strong>Bot</strong> - Like Moderator, but makes it clear that this user is a bot`,
`# <strong>Room Owner</strong> - They are leaders of the room and can almost totally control it`,
];
const globalRanks = [
`<strong>Global ranks</strong>`,
`+ <strong>Global Voice</strong> - They can use ! commands like !groups`,
`§ <strong>Section Leader</strong> - They oversee rooms in a particular section`,
`% <strong>Global Driver</strong> - Like Voice, and they can lock users and check for alts`,
`@ <strong>Global Moderator</strong> - The above, and they can globally ban users`,
`* <strong>Global Bot</strong> - Like Moderator, but makes it clear that this user is a bot`,
`& <strong>Global Administrator</strong> - They can do anything, like change what this message says and promote users globally`,
];
this.sendReplyBox(
(showRoom ? roomRanks.map(str => this.tr(str)).join('<br />') : ``) +
(showRoom && showGlobal ? `<br /><br />` : ``) +
(showGlobal ? globalRanks.map(str => this.tr(str)).join('<br />') : ``)
);
},
groupshelp: [
`/groups - Explains what the symbols (like % and @) before people's names mean.`,
`/groups [global|room] - Explains only global or room symbols.`,
`!groups - Shows everyone that information. Requires: + % @ # &`,
],
punishments(target, room, user) {
if (!this.runBroadcast()) return;
target = toID(target);
const showRoom = (target !== 'global');
const showGlobal = (target !== 'room' && target !== 'rooms');
const roomPunishments = [
`<strong>Room punishments</strong>:`,
`<strong>warn</strong> - Displays a popup with the rules.`,
`<strong>mute</strong> - Mutes a user (makes them unable to talk) for 7 minutes.`,
`<strong>hourmute</strong> - Mutes a user for 60 minutes.`,
`<strong>ban</strong> - Bans a user (makes them unable to join the room) for 2 days.`,
`<strong>weekban</strong> - Bans a user from the room for a week.`,
`<strong>blacklist</strong> - Bans a user for a year.`,
];
const globalPunishments = [
`<strong>Global punishments</strong>:`,
`<strong>lock</strong> - Locks a user (makes them unable to talk in any rooms or PM non-staff) for 2 days.`,
`<strong>weeklock</strong> - Locks a user for a week.`,
`<strong>namelock</strong> - Locks a user and prevents them from having a username for 2 days.`,
`<strong>globalban</strong> - Globally bans (makes them unable to connect and play games) for a week.`,
];
this.sendReplyBox(
(showRoom ? roomPunishments.map(str => this.tr(str)).join('<br />') : ``) +
(showRoom && showGlobal ? `<br /><br />` : ``) +
(showGlobal ? globalPunishments.map(str => this.tr(str)).join('<br />') : ``)
);
},
punishmentshelp: [
`/punishments - Explains punishments.`,
`!punishments - Show everyone that information. Requires: + % @ # &`,
],
repo: 'opensource',
repository: 'opensource',
git: 'opensource',
opensource(target, room, user) {
if (!this.runBroadcast()) return;
this.sendReplyBox(
`Pokémon Showdown is open source:<br />` +
`- Language: mostly TypeScript, a little PHP<br />` +
`- <a href="https://github.com/smogon/pokemon-showdown/commits/master">What's new?</a><br />` +
`- <a href="https://github.com/smogon/pokemon-showdown">Server source code</a><br />` +
`- <a href="https://github.com/smogon/pokemon-showdown-client">Client source code</a><br />` +
`- <a href="https://github.com/Zarel/Pokemon-Showdown-Dex">Dex source code</a>`
);
},
opensourcehelp: [
`/opensource - Links to PS's source code repository.`,
`!opensource - Show everyone that information. Requires: + % @ # &`,
],
staff(target, room, user) {
if (!this.runBroadcast()) return;
this.sendReplyBox(`<a href="https://www.smogon.com/sim/staff_list">Pokémon Showdown Staff List</a>`);
},
staffhelp: [`/staff - View the staff list.`],
forums(target, room, user) {
if (!this.runBroadcast()) return;
this.sendReplyBox(`<a href="https://www.smogon.com/forums/forums/209/">Pokémon Showdown Forums</a>`);
},
forumshelp: [`/forums - Links to the PS forums.`],
privacypolicy(target, room, user) {
if (!this.runBroadcast()) return;
this.sendReplyBox([
this.tr`- We log PMs so you can report them - staff can't look at them without permission unless there's a law enforcement reason.`,
this.tr`- We log IPs to enforce bans and mutes.`,
this.tr`- We use cookies to save your login info and teams, and for Google Analytics and AdSense.`,
this.tr`- For more information, you can read our <a href="https://${Config.routes.root}/privacy">full privacy policy.</a>`,
].join(`<br />`));
},
privacypolicyhelp: [`/privacypolicy - Displays PS's privacy policy.`],
suggest: 'suggestions',
suggestion: 'suggestions',
suggestions(target, room, user) {
if (!this.runBroadcast()) return;
this.sendReplyBox(`<a href="https://www.smogon.com/forums/forums/517/">Make a suggestion for Pokémon Showdown</a>`);
},
suggestionshelp: [`/suggestions - Links to the place to make suggestions for Pokemon Showdown.`],
bugreport: 'bugs',
bugreports: 'bugs',
bugs(target, room, user) {
if (!this.runBroadcast()) return;
if (room?.battle) {
this.sendReplyBox(`<center><button name="saveReplay"><i class="fa fa-upload"></i> Save Replay</button> — <a href="https://www.smogon.com/forums/threads/3520646/">Questions</a> — <a href="https://www.smogon.com/forums/threads/3663703/">Bug Reports</a></center>`);
} else {
this.sendReplyBox(
`Have a replay showcasing a bug on Pokémon Showdown?<br />` +
`- <a href="https://www.smogon.com/forums/threads/3520646/">Questions</a><br />` +
`- <a href="https://www.smogon.com/forums/threads/3663703/">Bug Reports</a> (ask in <a href="/help">Help</a> before posting in the thread if you're unsure)`
);
}
},
bugshelp: [`/bugs - Links to the various bug reporting services.`],
optionbutton: 'optionsbutton',
optionsbutton(target, room, user) {
if (!this.runBroadcast()) return;
this.sendReplyBox(`<button name="openOptions" class="button"><i style="font-size: 16px; vertical-align: -1px" class="fa fa-cog"></i> Options</button> (The Sound and Options buttons are at the top right, next to your username)`);
},
optionsbuttonhelp: [`/optionsbutton - Provides a button to the Options menu.`],
soundsbutton: 'soundbutton',
volumebutton: 'soundbutton',
soundbutton(target, room, user) {
if (!this.runBroadcast()) return;
this.sendReplyBox(`<button name="openSounds" class="button"><i style="font-size: 16px; vertical-align: -1px" class="fa fa-volume-up"></i> Sound</button> (The Sound and Options buttons are at the top right, next to your username)`);
},
soundbuttonhelp: [`/soundbutton - Provides a button to the Sounds menu.`],
introduction: 'intro',
intro(target, room, user) {
if (!this.runBroadcast()) return;
this.sendReplyBox(
`New to competitive Pokémon?<br />` +
`- <a href="https://www.smogon.com/forums/threads/3676132/">Beginner's Guide to Pokémon Showdown</a><br />` +
`- <a href="https://www.smogon.com/dp/articles/intro_comp_pokemon">An introduction to competitive Pokémon</a><br />` +
`- <a href="https://www.smogon.com/sm/articles/sm_tiers">What do 'OU', 'UU', etc mean?</a><br />` +
`- <a href="https://www.smogon.com/dex/ss/formats/">What are the rules for each format?</a><br />` +
`- <a href="https://www.smogon.com/ss/articles/clauses">What is 'Sleep Clause' and other clauses?</a><br />` +
`- <a href="https://www.smogon.com/articles/getting-started">Next Steps for Competitive Battling</a>`
);
},
introhelp: [
`/intro - Provides an introduction to competitive Pok\u00e9mon.`,
`!intro - Show everyone that information. Requires: + % @ # &`,
],
mentoring: 'smogintro',
smogonintro: 'smogintro',
smogintro(target, room, user) {
if (!this.runBroadcast()) return;
this.sendReplyBox(
`Welcome to Smogon's official simulator! The <a href="https://www.smogon.com/forums/forums/264">Smogon Info / Intro Hub</a> can help you get integrated into the community.<br />` +
`- <a href="https://www.smogon.com/forums/threads/3526346">Useful Smogon Info</a><br />` +
`- <a href="https://www.smogon.com/forums/threads/3498332">Tiering FAQ</a><br />`
);
},
smogintrohelp: [`/smogintro - Provides an introduction to Smogon.`],
bsscalc: 'calc',
calculator: 'calc',
cantsaycalc: 'calc',
damagecalculator: 'calc',
damagecalc: 'calc',
honkalculator: 'calc',
honkocalc: 'calc',
randomscalc: 'calc',
randbatscalc: 'calc',
rcalc: 'calc',
calc(target, room, user, connection, cmd) {
if (cmd === 'calc' && target) return this.parse(`/math ${target}`);
if (!this.runBroadcast()) return;
const DEFAULT_CALC_COMMANDS = ['honkalculator', 'honkocalc'];
const RANDOMS_CALC_COMMANDS = ['randomscalc', 'randbatscalc', 'rcalc'];
const BATTLESPOT_CALC_COMMANDS = ['bsscalc', 'cantsaycalc'];
const SUPPORTED_RANDOM_FORMATS = [
'gen8randombattle', 'gen8unratedrandombattle', 'gen7randombattle', 'gen6randombattle', 'gen5randombattle', 'gen4randombattle', 'gen3randombattle', 'gen2randombattle', 'gen1randombattle',
];
const SUPPORTED_BATTLESPOT_FORMATS = [
'gen5gbusingles', 'gen5gbudoubles', 'gen6battlespotsingles', 'gen6battlespotdoubles', 'gen6battlespottriples', 'gen7battlespotsingles', 'gen7battlespotdoubles', 'gen7bssfactory',
];
const isRandomBattle = (room?.battle && SUPPORTED_RANDOM_FORMATS.includes(room.battle.format));
const isBattleSpotBattle = (room?.battle && (SUPPORTED_BATTLESPOT_FORMATS.includes(room.battle.format) ||
room.battle.format.includes("battlespotspecial")));
if (RANDOMS_CALC_COMMANDS.includes(cmd) ||
(isRandomBattle && !DEFAULT_CALC_COMMANDS.includes(cmd) && !BATTLESPOT_CALC_COMMANDS.includes(cmd))) {
return this.sendReplyBox(
`Random Battles damage calculator. (Courtesy of Austin)<br />` +
`- <a href="https://calc.pokemonshowdown.com/randoms.html">Random Battles Damage Calculator</a>`
);
}
if (BATTLESPOT_CALC_COMMANDS.includes(cmd) || (isBattleSpotBattle && !DEFAULT_CALC_COMMANDS.includes(cmd))) {
return this.sendReplyBox(
`Battle Spot damage calculator. (Courtesy of cant say & LegoFigure11)<br />` +
`- <a href="https://cantsay.github.io/">Battle Spot Damage Calculator</a>`
);
}
this.sendReplyBox(
`Pokémon Showdown! damage calculator. (Courtesy of Honko, Austin, & Kris)<br />` +
`- <a href="https://calc.pokemonshowdown.com/index.html">Damage Calculator</a>`
);
},
calchelp: [
`/calc - Provides a link to a damage calculator`,
`/rcalc - Provides a link to the random battles damage calculator`,
`/bsscalc - Provides a link to the Battle Spot damage calculator`,
`!calc - Shows everyone a link to a damage calculator. Requires: + % @ # &`,
],
capintro: 'cap',
cap(target, room, user) {
if (!this.runBroadcast()) return;
this.sendReplyBox(
`An introduction to the Create-A-Pokémon project:<br />` +
`- <a href="https://www.smogon.com/cap/">CAP project website and description</a><br />` +
`- <a href="https://www.smogon.com/forums/forums/66/">CAP project discussion forum</a><br />` +
`- <a href="https://www.smogon.com/forums/threads/48782/">What Pokémon have been made?</a><br />` +
`- <a href="https://www.smogon.com/forums/forums/477">Talk about the metagame here</a><br />` +
`- <a href="https://www.smogon.com/forums/threads/3671157/">Sample SS CAP teams</a>`
);
},
caphelp: [
`/cap - Provides an introduction to the Create-A-Pok\u00e9mon project.`,
`!cap - Show everyone that information. Requires: + % @ # &`,
],
gennext(target, room, user) {
if (!this.runBroadcast()) return;
this.sendReplyBox(
"NEXT (also called Gen-NEXT) is a mod that makes changes to the game:<br />" +
`- <a href="https://github.com/smogon/pokemon-showdown/blob/master/data/mods/gennext/README.md">README: overview of NEXT</a><br />` +
"Example replays:<br />" +
`- <a href="https://replay.pokemonshowdown.com/gennextou-120689854">Zergo vs Mr Weegle Snarf</a><br />` +
`- <a href="https://replay.pokemonshowdown.com/gennextou-130756055">NickMP vs Khalogie</a>`
);
},
gennexthelp: [`/gennext - Provides information on the Gen-NEXT mod.`],
battlerules(target, room, user) {
return this.parse(`/join view-battlerules`);
},
battleruleshelp: [
`/battlerules - Provides information on the rules that can be added to tournament and challenge battles.`,
],
banlists: 'formathelp',
tier: 'formathelp',
tiers: 'formathelp',
formats: 'formathelp',
tiershelp: 'formathelp',
formatshelp: 'formathelp',
viewbanlist: 'formathelp',
formathelp(target, room, user, connection, cmd) {
if (!target && this.runBroadcast()) {
return this.sendReplyBox(
`- <a href="https://www.smogon.com/tiers/">Smogon Tiers</a><br />` +
`- <a href="https://www.smogon.com/forums/threads/3498332/">Tiering FAQ</a><br />` +
`- <a href="https://www.smogon.com/xyhub/tiers">The banlists for each tier</a><br />` +
"<br /><em>Type /formatshelp <strong>[format|section]</strong> to get details about an available format or group of formats.</em>"
);
}
const isOMSearch = (cmd === 'om' || cmd === 'othermetas');
let targetId = toID(target);
if (targetId === 'ladder') targetId = 'search' as ID;
if (targetId === 'all') targetId = '';
const {totalMatches, sections} = findFormats(targetId, isOMSearch);
if (!totalMatches) return this.errorReply("No matched formats found.");
const format = totalMatches === 1 ? Dex.formats.get(Object.values(sections)[0].formats[0]) : null;
if (!this.runBroadcast(`!formathelp ${format ? format.id : target}`)) return;
if (format) {
const rules: string[] = [];
let rulesetHtml = '';
if (['Format', 'Rule', 'ValidatorRule'].includes(format.effectType)) {
if (format.ruleset?.length) {
rules.push(`<b>Ruleset</b> - ${Utils.escapeHTML(format.ruleset.join(", "))}`);
}
if (format.banlist?.length) {
rules.push(`<b>Bans</b> - ${Utils.escapeHTML(format.banlist.join(", "))}`);
}
if (format.unbanlist?.length) {
rules.push(`<b>Unbans</b> - ${Utils.escapeHTML(format.unbanlist.join(", "))}`);
}
if (format.restricted?.length) {
rules.push(`<b>Restricted</b> - ${Utils.escapeHTML(format.restricted.join(", "))}`);
}
if (rules.length > 0) {
rulesetHtml = `<details><summary>Banlist/Ruleset</summary>${rules.join("<br />")}</details>`;
} else {
rulesetHtml = `No ruleset found for ${format.name}`;
}
}
let formatType: string = (format.gameType || "singles");
formatType = formatType.charAt(0).toUpperCase() + formatType.slice(1).toLowerCase();
if (!format.desc && !format.threads) {
if (format.effectType === 'Format') {
return this.sendReplyBox(`No description found for this ${formatType} ${format.section} format.<br />${rulesetHtml}`);
} else {
return this.sendReplyBox(`No description found for this rule.<br />${rulesetHtml}`);
}
}
const descHtml = [...(format.desc ? [format.desc] : []), ...(format.threads || [])];
return this.sendReplyBox(`${descHtml.join("<br />")}<br />${rulesetHtml}`);
}
let tableStyle = `border:1px solid gray; border-collapse:collapse`;
if (this.broadcasting) {
tableStyle += `; display:inline-block; max-height:240px;" class="scrollable`;
}
// Build tables
const buf = [`<table style="${tableStyle}" cellspacing="0" cellpadding="5">`];
for (const sectionId in sections) {
buf.push(Utils.html`<th style="border:1px solid gray" colspan="2">${sections[sectionId].name}</th>`);
for (const section of sections[sectionId].formats) {
const subformat = Dex.formats.get(section);
const nameHTML = Utils.escapeHTML(subformat.name);
const desc = [...(subformat.desc ? [subformat.desc] : []), ...(subformat.threads || [])];
const descHTML = desc.length ? desc.join("<br />") : "—";
buf.push(`<tr><td style="border:1px solid gray">${nameHTML}</td><td style="border: 1px solid gray; margin-left:10px">${descHTML}</td></tr>`);
}
}
buf.push(`</table>`);
return this.sendReply(`|raw|${buf.join("")}`);
},
formathelphelp: [
`/formathelp [format] - Provides information on the given [format].`,
`If no format is given, provides information on how tiers work.`,
],
roomhelp(target, room, user) {
room = this.requireRoom();
this.checkBroadcast(false, '!htmlbox');
if (this.broadcastMessage) this.checkCan('declare', null, room);
if (!this.runBroadcast(false, '!htmlbox')) return;
const strings = [
[
`<strong>Room drivers (%)</strong> can use:`,
`- /warn OR /k <em>username</em>: warn a user and show the Pokémon Showdown rules`,
`- /mute OR /m <em>username</em>: 7 minute mute`,
`- /hourmute OR /hm <em>username</em>: 60 minute mute`,
`- /unmute <em>username</em>: unmute`,
`- /hidetext <em>username</em>: hide a user's messages from the room`,
`- /announce OR /wall <em>message</em>: make an announcement`,
`- /modlog <em>username</em>: search the moderator log of the room`,
`- /modnote <em>note</em>: add a moderator note that can be read through modlog`,
`- !show [image or youtube link]: display given media in chat.`,
],
[
`<strong>Room moderators (@)</strong> can also use:`,
`- /roomban OR /rb <em>username</em>: ban user from the room`,
`- /roomunban <em>username</em>: unban user from the room`,
`- /roomvoice <em>username</em>: appoint a room voice`,
`- /roomdevoice <em>username</em>: remove a room voice`,
`- /staffintro <em>intro</em>: set the staff introduction that will be displayed for all staff joining the room`,
`- /roomsettings: change a variety of room settings, namely modchat`,
],
[
`<strong>Room owners (#)</strong> can also use:`,
`- /roomintro <em>intro</em>: set the room introduction that will be displayed for all users joining the room`,
`- /rules <em>rules link</em>: set the room rules link seen when using /rules`,
`- /roommod, /roomdriver <em>username</em>: appoint a room moderator/driver`,
`- /roomdemod, /roomdedriver <em>username</em>: remove a room moderator/driver`,
`- /roomdeauth <em>username</em>: remove all room auth from a user`,
`- /declare <em>message</em>: make a large blue declaration to the room`,
`- !htmlbox <em>HTML code</em>: broadcast a box of HTML code to the room`,
`- /roomsettings: change a variety of room settings, including modchat, capsfilter, etc`,
],
[
`More detailed help can be found in the <a href="https://www.smogon.com/forums/posts/6774654/">roomauth guide</a>`,
],
[
`Tournament Help:`,
`- /tour create <em>format</em>, elimination: create a new single elimination tournament in the current room.`,
`- /tour create <em>format</em>, roundrobin: create a new round robin tournament in the current room.`,
`- /tour end: forcibly end the tournament in the current room`,
`- /tour start: start the tournament in the current room`,
`- /tour banlist [pokemon], [talent], [...]: ban moves, abilities, Pokémon or items from being used in a tournament (it must be created first)`,
],
[
`More detailed help can be found in the <a href="https://www.smogon.com/forums/posts/6777489/">tournaments guide</a>`,
],
];
this.sendReplyBox(
strings.map(par => par.map(string => this.tr(string)).join('<br />')).join('<br /><br />')
);
},
restarthelp(target, room, user) {
if (!Rooms.global.lockdown) this.checkCan('lockdown');
if (!this.runBroadcast()) return;
this.sendReplyBox(
`The server is restarting. Things to know:<br />` +
`- We wait a few minutes before restarting so people can finish up their battles<br />` +
`- The restart itself will take around 0.6 seconds<br />` +
`- Your ladder ranking and teams will not change<br />` +
`- We are restarting to update Pokémon Showdown to a newer version`
);
},
rule: 'rules',
roomrules: "rules",
rules(target, room, user, connection, cmd) {
if (!target) {
if (!this.runBroadcast()) return;
this.sendReplyBox(
`${room ? this.tr`Please follow the rules:` + '<br />' : ``}` +
`${room?.settings.rulesLink ? Utils.html`- <a href="${room.settings.rulesLink}">${this.tr`${room.title} room rules`}</a><br />` : ``}` +
`- <a href="https://${Config.routes.root}${this.tr`/rules`}">${this.tr`Global Rules`}</a>`
);
return;
}
if (!room) {
return this.errorReply(`This is not a room you can set the rules of.`);
}
const possibleRoom = Rooms.search(toID(target));
const {totalMatches: formatMatches} = findFormats(toID(target));
if (formatMatches && possibleRoom && cmd !== 'roomrules') {
this.errorReply(`'${target}' is both a room and a tier. `);
this.errorReply(`If you were looking for rules of that room, use /roomrules [room].`);
this.errorReply(`Otherwise, use /tier [tiername].`);
return;
}
if (possibleRoom) {
const rulesLink = possibleRoom.settings.rulesLink;
return this.sendReplyBox(
`${possibleRoom.title}'s rules:<br />` +
`${rulesLink ? Utils.html`- <a href="${rulesLink}">${this.tr`${possibleRoom.title} room rules`}</a><br />` : `None set.`}`
);
}
if (formatMatches > 0 && cmd !== 'roomrules') {
return this.parse(`/tier ${target}`);
}
this.checkCan('editroom', null, room);
if (target.length > 150) {
return this.errorReply(`Error: Room rules link is too long (must be under 150 characters). You can use a URL shortener to shorten the link.`);
}
target = target.trim();
if (target === 'delete' || target === 'remove') {
if (!room.settings.rulesLink) return this.errorReply(`This room does not have rules set to remove.`);
delete room.settings.rulesLink;
this.privateModAction(`${user.name} has removed the room rules link.`);
this.modlog('RULES', null, `removed room rules link`);
} else {
room.settings.rulesLink = target;
this.privateModAction(`${user.name} changed the room rules link to: ${target}`);
this.modlog('RULES', null, `changed link to: ${target}`);
}
room.saveSettings();
},
ruleshelp: [
`/rules - Show links to room rules and global rules.`,
`!rules - Show everyone links to room rules and global rules. Requires: + % @ # &`,
`/rules [url] - Change the room rules URL. Requires: # &`,
`/rules remove - Removes a room rules URL. Requires: # &`,
],
faq(target, room, user) {
if (!this.runBroadcast()) return;
target = toID(target);
const showAll = target === 'all';
if (showAll && this.broadcasting) {
return this.sendReplyBox(this.tr`You cannot broadcast all FAQs at once.`);
}
const buffer = [];
if (showAll || target === 'staff') {
buffer.push(`<a href="https://pokemonshowdown.com/${this.tr`pages/staff`}">${this.tr`Staff FAQ`}</a>`);
}
if (showAll || target === 'autoconfirmed' || target === 'ac') {
buffer.push(this.tr`A user is autoconfirmed when they have won at least one rated battle and have been registered for one week or longer. In order to prevent spamming and trolling, most chatrooms only allow autoconfirmed users to chat. If you are not autoconfirmed, you can politely PM a staff member (staff have %, @, or # in front of their username) in the room you would like to chat and ask them to disable modchat. However, staff are not obligated to disable modchat.`);
if (!this.broadcasting) void this.parse(`/regtime`);
}
if (showAll || target === 'ladder' || target === 'ladderhelp' || target === 'decay') {
buffer.push(`<a href="https://${Config.routes.root}/${this.tr`pages/ladderhelp`}">${this.tr`How the ladder works`}</a>`);
}
if (showAll || target === 'tiering' || target === 'tiers' || target === 'tier') {
buffer.push(`<a href="https://www.smogon.com/ingame/battle/tiering-faq">${this.tr`Tiering FAQ`}</a>`);
}
if (showAll || target === 'badge' || target === 'badges') {
buffer.push(`<a href="https://www.smogon.com/badge_faq">${this.tr`Badge FAQ`}</a>`);
}
if (showAll || target === 'rng') {
buffer.push(`<a href="https://${Config.routes.root}/${this.tr`pages/rng`}">${this.tr`Common misconceptions about our RNG`}</a>`);
}
if (showAll || ['tournaments', 'tournament', 'tours', 'tour'].includes(target)) {
buffer.push(this.tr`To join a room tournament, click the <strong>Join!</strong> button or type the command <code>/tour join</code> in the room's chat. You can check if your team is legal for the tournament by clicking the <strong>Validate</strong> button once you've joined and selected a team. To battle your opponent in the tournament, click the <strong>Ready!</strong> button when it appears. There are two different types of room tournaments: elimination (if a user loses more than a certain number of times, they are eliminated) and round robin (all users play against each other, and the user with the most wins is the winner).`);
}
if (showAll || ['vpn', 'proxy'].includes(target)) {
buffer.push(`<a href="https://pokemonshowdown.com/${this.tr`pages/proxyhelp`}">${this.tr`Proxy lock help`}</a>`);
}
if (!buffer.length && target) {
this.errorReply(`'${target}' is an invalid FAQ.`);
return this.parse(`/help faq`);
}
if (!target || showAll) {
buffer.unshift(`<a href="https://pokemonshowdown.com/${this.tr`pages/faq`}">${this.tr`Frequently Asked Questions`}</a>`);
}
this.sendReplyBox(buffer.join(`<br />`));
},
faqhelp: [
`/faq [theme] - Provides a link to the FAQ. Add autoconfirmed, badges, proxy, ladder, staff, or tiers for a link to these questions. Add all for all of them.`,
`!faq [theme] - Shows everyone a link to the FAQ. Add autoconfirmed, badges, proxy, ladder, staff, or tiers for a link to these questions. Add all for all of them. Requires: + % @ # &`,
],
analysis: 'smogdex',
strategy: 'smogdex',
smogdex(target, room, user) {
if (!target) return this.parse('/help smogdex');
if (!this.runBroadcast()) return;
const targets = target.split(',');
let pokemon = Dex.species.get(targets[0]);
const item = Dex.items.get(targets[0]);
const move = Dex.moves.get(targets[0]);
const ability = Dex.abilities.get(targets[0]);
const format = Dex.formats.get(targets[0]);
let atLeastOne = false;
let generation = (targets[1] || 'ss').trim().toLowerCase();
let genNumber = 8;
const extraFormat = Dex.formats.get(targets[2]);
if (['8', 'gen8', 'eight', 'ss', 'swsh'].includes(generation)) {
generation = 'ss';
} else if (['7', 'gen7', 'seven', 'sm', 'sumo', 'usm', 'usum'].includes(generation)) {
generation = 'sm';
genNumber = 7;
} else if (['6', 'gen6', 'oras', 'six', 'xy'].includes(generation)) {
generation = 'xy';
genNumber = 6;
} else if (['5', 'b2w2', 'bw', 'bw2', 'five', 'gen5'].includes(generation)) {
generation = 'bw';
genNumber = 5;
} else if (['4', 'dp', 'dpp', 'four', 'gen4', 'hgss'].includes(generation)) {
generation = 'dp';
genNumber = 4;
} else if (['3', 'adv', 'frlg', 'gen3', 'rs', 'rse', 'three'].includes(generation)) {
generation = 'rs';
genNumber = 3;
} else if (['2', 'gen2', 'gs', 'gsc', 'two'].includes(generation)) {
generation = 'gs';
genNumber = 2;
} else if (['1', 'gen1', 'one', 'rb', 'rby', 'rgy'].includes(generation)) {
generation = 'rb';
genNumber = 1;
} else {
generation = 'ss';
}
// Pokemon
if (pokemon.exists) {
atLeastOne = true;
if (genNumber < pokemon.gen) {
return this.sendReplyBox(`${pokemon.name} did not exist in ${generation.toUpperCase()}!`);
}
if ((pokemon.battleOnly && pokemon.baseSpecies !== 'Greninja') ||
['Keldeo', 'Genesect'].includes(pokemon.baseSpecies)) {
pokemon = Dex.species.get(pokemon.changesFrom || pokemon.baseSpecies);
}
let formatName = extraFormat.name;
let formatId: string = extraFormat.id;
if (formatName.startsWith('[Gen ') && formatName.slice(6, 8) === '] ') {
formatName = formatName.slice(8);
formatId = toID(formatName);
}
if (formatId === 'battlespotdoubles') {
formatId = 'battle_spot_doubles';
} else if (formatId === 'battlespottriples') {
formatId = 'battle_spot_triples';
if (genNumber > 6) {
return this.sendReplyBox(`Triples formats are not an available format in Pokémon generation ${generation.toUpperCase()}.`);
}
} else if (formatId === 'doublesou') {
formatId = 'doubles';
} else if (formatId === 'balancedhackmons') {
formatId = 'bh';
} else if (formatId === 'battlespotsingles') {
formatId = 'battle_spot_singles';
} else if (formatId === 'ubers') {
formatId = 'uber';
} else if (formatId.includes('vgc')) {
formatId = 'vgc' + formatId.slice(-2);
formatName = 'VGC20' + formatId.slice(-2);
} else if (extraFormat.effectType !== 'Format') {
formatName = formatId = '';
}
const supportedLanguages: {[k: string]: string} = {
spanish: 'es',
french: 'fr',
italian: 'it',
german: 'de',
portuguese: 'pt',
};
let id = pokemon.id;
// Special case for Meowstic-M
if (id === 'meowstic') id = 'meowsticm' as ID;
if (['ou', 'uu'].includes(formatId) && generation === 'sm' &&
room?.settings.language && room.settings.language in supportedLanguages) {
// Limited support for translated analysis
// Translated analysis do not support automatic redirects from a id to the proper page
this.sendReplyBox(
Utils.html`<a href="https://www.smogon.com/dex/${generation}/pokemon/${id}/${formatId}/?lang=${supportedLanguages[room.settings.language]}">${generation.toUpperCase()} ${formatName} ${pokemon.name} analysis</a>, brought to you by <a href="https://www.smogon.com">Smogon University</a>`
);
} else if (['ou', 'uu'].includes(formatId) && generation === 'sm') {
this.sendReplyBox(
Utils.html`<a href="https://www.smogon.com/dex/${generation}/pokemon/${id}/${formatId}">${generation.toUpperCase()} ${formatName} ${pokemon.name} analysis</a>, brought to you by <a href="https://www.smogon.com">Smogon University</a><br />` +
`Other languages: <a href="https://www.smogon.com/dex/${generation}/pokemon/${id}/${formatId}/?lang=es">Español</a>, <a href="https://www.smogon.com/dex/${generation}/pokemon/${id}/${formatId}/?lang=fr">Français</a>, <a href="https://www.smogon.com/dex/${generation}/pokemon/${id}/${formatId}/?lang=it">Italiano</a>, ` +
`<a href="https://www.smogon.com/dex/${generation}/pokemon/${id}/${formatId}/?lang=de">Deutsch</a>, <a href="https://www.smogon.com/dex/${generation}/pokemon/${id}/${formatId}/?lang=pt">Português</a>`
);
} else {
this.sendReplyBox(Utils.html`<a href="https://www.smogon.com/dex/${generation}/pokemon/${id}${(formatId ? '/' + formatId : '')}">${generation.toUpperCase()} ${formatName} ${pokemon.name} analysis</a>, brought to you by <a href="https://www.smogon.com">Smogon University</a>`);
}
}
// Item
if (item.exists && genNumber > 1 && item.gen <= genNumber) {
atLeastOne = true;
this.sendReplyBox(`<a href="https://www.smogon.com/dex/${generation}/items/${item.id}">${generation.toUpperCase()} ${item.name} item analysis</a>, brought to you by <a href="https://www.smogon.com">Smogon University</a>`);
}
// Ability
if (ability.exists && genNumber > 2 && ability.gen <= genNumber) {
atLeastOne = true;
this.sendReplyBox(`<a href="https://www.smogon.com/dex/${generation}/abilities/${ability.id}">${generation.toUpperCase()} ${ability.name} ability analysis</a>, brought to you by <a href="https://www.smogon.com">Smogon University</a>`);
}
// Move
if (move.exists && move.gen <= genNumber) {
atLeastOne = true;
this.sendReplyBox(`<a href="https://www.smogon.com/dex/${generation}/moves/${toID(move.name)}">${generation.toUpperCase()} ${move.name} move analysis</a>, brought to you by <a href="https://www.smogon.com">Smogon University</a>`);
}
// Format
if (format.id) {
let formatName = format.name;
let formatId: string = format.id;
if (formatId === 'battlespotdoubles') {
formatId = 'battle_spot_doubles';
} else if (formatId === 'battlespottriples') {
formatId = 'battle_spot_triples';
if (genNumber > 6) {
return this.sendReplyBox(`Triples formats are not an available format in Pokémon generation ${generation.toUpperCase()}.`);
}
} else if (formatId === 'doublesou') {
formatId = 'doubles';
} else if (formatId === 'balancedhackmons') {
formatId = 'bh';
} else if (formatId === 'battlespotsingles') {
formatId = 'battle_spot_singles';
} else if (formatId === 'ubers') {
formatId = 'uber';
} else if (formatId.includes('vgc')) {
formatId = `vgc${formatId.slice(-2)}`;
formatName = `VGC20${formatId.slice(-2)}`;
} else if (format.effectType !== 'Format') {
formatName = formatId = '';
}
if (formatName) {
atLeastOne = true;
this.sendReplyBox(Utils.html`<a href="https://www.smogon.com/dex/${generation}/formats/${formatId}">${generation.toUpperCase()} ${formatName} format analysis</a>, brought to you by <a href="https://www.smogon.com">Smogon University</a>`);
}
}
if (!atLeastOne) {
return this.sendReplyBox(`Pokémon, item, move, ability, or format not found for generation ${generation.toUpperCase()}.`);
}
},
smogdexhelp: [
`/analysis [pokemon], [generation], [format] - Links to the Smogon University analysis for this Pok\u00e9mon in the given generation.`,
`!analysis [pokemon], [generation], [format] - Shows everyone this link. Requires: + % @ # &`,
],
veekun(target, broadcast, user) {
if (!target) return this.parse('/help veekun');
if (!this.runBroadcast()) return;
const baseLink = 'http://veekun.com/dex/';
const pokemon = Dex.species.get(target);
const item = Dex.items.get(target);
const move = Dex.moves.get(target);
const ability = Dex.abilities.get(target);
const nature = Dex.natures.get(target);
let atLeastOne = false;
// Pokemon
if (pokemon.exists) {
atLeastOne = true;
if (pokemon.isNonstandard && pokemon.isNonstandard !== 'Past') {
return this.errorReply(`${pokemon.name} is not a real Pok\u00e9mon.`);
}
const baseSpecies = pokemon.baseSpecies || pokemon.name;
let forme = pokemon.forme;
// Showdown and Veekun have different names for various formes
if (baseSpecies === 'Meowstic' && forme === 'F') forme = 'Female';
if (baseSpecies === 'Zygarde' && forme === '10%') forme = '10';
if (baseSpecies === 'Necrozma' && !Dex.species.get(baseSpecies + forme).battleOnly) forme = forme.substr(0, 4);
if (baseSpecies === 'Pikachu' && Dex.species.get(baseSpecies + forme).gen === 7) forme += '-Cap';
if (forme.endsWith('Totem')) {
if (baseSpecies === 'Raticate') forme = 'Totem-Alola';
if (baseSpecies === 'Marowak') forme = 'Totem';
if (baseSpecies === 'Mimikyu') forme += forme === 'Busted-Totem' ? '-Busted' : '-Disguised';
}
let link = `${baseLink}pokemon/${baseSpecies.toLowerCase()}`;
if (forme) {
if (baseSpecies === 'Arceus' || baseSpecies === 'Silvally') link += '/flavor';
link += `?form=${forme.toLowerCase()}`;
}
this.sendReplyBox(`<a href="${link}">${pokemon.name} description</a> by Veekun`);
}
// Item
if (item.exists) {
atLeastOne = true;
if (item.isNonstandard && item.isNonstandard !== 'Past') {
return this.errorReply(`${item.name} is not a real item.`);
}
const link = `${baseLink}items/${item.name.toLowerCase()}`;
this.sendReplyBox(`<a href="${link}">${item.name} item description</a> by Veekun`);
}
// Ability
if (ability.exists) {
atLeastOne = true;
if (ability.isNonstandard && ability.isNonstandard !== 'Past') {
return this.errorReply(`${ability.name} is not a real ability.`);
}
const link = `${baseLink}abilities/${ability.name.toLowerCase()}`;
this.sendReplyBox(`<a href="${link}">${ability.name} ability description</a> by Veekun`);
}
// Move
if (move.exists) {
atLeastOne = true;
if (move.isNonstandard && move.isNonstandard !== 'Past') {
return this.errorReply(`${move.name} is not a real move.`);
}
const link = `${baseLink}moves/${move.name.toLowerCase()}`;
this.sendReplyBox(`<a href="${link}">${move.name} move description</a> by Veekun`);
}
// Nature
if (nature.exists) {
atLeastOne = true;
const link = `${baseLink}natures/${nature.name.toLowerCase()}`;
this.sendReplyBox(`<a href="${link}">${nature.name} nature description</a> by Veekun`);
}
if (!atLeastOne) {
return this.sendReplyBox(`Pokémon, item, move, ability, or nature not found.`);
}
},
veekunhelp: [
`/veekun [pokemon] - Links to Veekun website for this pokemon/item/move/ability/nature.`,
`!veekun [pokemon] - Shows everyone this link. Requires: + % @ # &`,
],
register() {
if (!this.runBroadcast()) return;
this.sendReplyBox(`You will be prompted to register upon winning a rated battle. Alternatively, there is a register button in the <button name="openOptions"><i class="fa fa-cog"></i> Options</button> menu in the upper right.`);
},
registerhelp: [`/register - Provides information on how to register.`],
/*********************************************************
* Miscellaneous commands
*********************************************************/
roll: 'dice',
dice(target, room, user) {
if (!target || /[^\d\sdHL+-]/i.test(target)) return this.parse('/help dice');
if (!this.runBroadcast(true)) return;
// ~30 is widely regarded as the sample size required for sum to be a Gaussian distribution.
// This also sets a computation time constraint for safety.
const maxDice = 40;
let diceQuantity = 1;
const diceDataStart = target.indexOf('d');
if (diceDataStart >= 0) {
if (diceDataStart) diceQuantity = Number(target.slice(0, diceDataStart));
target = target.slice(diceDataStart + 1);
if (!Number.isInteger(diceQuantity) || diceQuantity <= 0 || diceQuantity > maxDice) {
return this.sendReply(`The amount of dice rolled should be a natural number up to ${maxDice}.`);
}
}
let offset = 0;
let removeOutlier = 0;
const modifierData = /[+-]/.exec(target);
if (modifierData) {
switch (target.slice(modifierData.index).trim().toLowerCase()) {
case '-l':
removeOutlier = -1;
break;
case '-h':
removeOutlier = +1;
break;
default:
offset = Number(target.slice(modifierData.index));
if (isNaN(offset)) return this.parse('/help dice');
if (!Number.isSafeInteger(offset)) {
return this.errorReply(`The specified offset must be an integer up to ${Number.MAX_SAFE_INTEGER}.`);
}
}
if (removeOutlier && diceQuantity <= 1) {
return this.errorReply(`More than one dice should be rolled before removing outliers.`);
}
target = target.slice(0, modifierData.index);
}
let diceFaces = 6;
if (target.length) {
diceFaces = Number(target);
if (!Number.isSafeInteger(diceFaces) || diceFaces <= 0) {
return this.errorReply(`Rolled dice must have a natural amount of faces up to ${Number.MAX_SAFE_INTEGER}.`);
}
}
if (diceQuantity > 1) {
// Make sure that we can deal with high rolls
if (!Number.isSafeInteger(offset < 0 ? diceQuantity * diceFaces : diceQuantity * diceFaces + offset)) {
return this.errorReply(`The maximum sum of rolled dice must be lower or equal than ${Number.MAX_SAFE_INTEGER}.`);
}
}
let maxRoll = 0;
let minRoll = Number.MAX_SAFE_INTEGER;
const trackRolls = diceQuantity * (('' + diceFaces).length + 1) <= 60;
const rolls = [];
let rollSum = 0;
for (let i = 0; i < diceQuantity; ++i) {
const curRoll = Math.floor(Math.random() * diceFaces) + 1;
rollSum += curRoll;
if (curRoll > maxRoll) maxRoll = curRoll;
if (curRoll < minRoll) minRoll = curRoll;
if (trackRolls) rolls.push(curRoll);
}
// Apply modifiers
if (removeOutlier > 0) {
rollSum -= maxRoll;
} else if (removeOutlier < 0) {
rollSum -= minRoll;
}
if (offset) rollSum += offset;
// Reply with relevant information
let offsetFragment = "";
if (offset) offsetFragment += `${offset > 0 ? ` + ${offset}` : offset}`;
if (diceQuantity === 1) return this.sendReplyBox(`Rolling (1 to ${diceFaces})${offsetFragment}: ${rollSum}`);
const outlierFragment = removeOutlier ? ` except ${removeOutlier > 0 ? "highest" : "lowest"}` : ``;
const rollsFragment = trackRolls ? ": " + rolls.join(", ") : "";
return this.sendReplyBox(
`${diceQuantity} rolls (1 to ${diceFaces})${rollsFragment}<br />` +
`Sum${offsetFragment}${outlierFragment}: ${rollSum}`
);
},
dicehelp: [
`/dice [max number] - Randomly picks a number between 1 and the number you choose.`,
`/dice [number of dice]d[number of sides] - Simulates rolling a number of dice, e.g., /dice 2d4 simulates rolling two 4-sided dice.`,
`/dice [number of dice]d[number of sides][+/-][offset] - Simulates rolling a number of dice and adding an offset to the sum, e.g., /dice 2d6+10: two standard dice are rolled; the result lies between 12 and 22.`,
`/dice [number of dice]d[number of sides]-[H/L] - Simulates rolling a number of dice with removal of extreme values, e.g., /dice 3d8-L: rolls three 8-sided dice; the result ignores the lowest value.`,
],
pr: 'pickrandom',
pick: 'pickrandom',
pickrandom(target, room, user) {
if (!target) return false;
if (!target.includes(',')) return this.parse('/help pick');
if (!this.runBroadcast(true)) return false;
if (this.broadcasting) {
[, target] = Utils.splitFirst(this.message, ' ');
}
const options = target.split(',');
const pickedOption = options[Math.floor(Math.random() * options.length)].trim();
return this.sendReplyBox(Utils.html`<em>We randomly picked:</em> ${pickedOption}`);
},
pickrandomhelp: [`/pick [option], [option], ... - Randomly selects an item from a list containing 2 or more elements.`],
shuffle(target, room, user) {
if (!target?.includes(',')) return this.parse('/help shuffle');
const args = target.split(',');
if (!this.runBroadcast(true)) return false;
const results = Utils.shuffle(args.map(arg => arg.trim()));
return this.sendReplyBox(Utils.html`<em>Shuffled:</em><br> ${results.join(', ')}`);
},
shufflehelp: [
`/shuffle [option], [option], [option], ... - Randomly shuffles a list of 2 or more elements.`,
],
showimage(target, room, user) {
return this.errorReply(`/showimage has been deprecated - use /show instead.`);
},
async requestshow(target, room, user) {
room = this.requireRoom();
this.checkChat();
if (!room.settings.requestShowEnabled) {
return this.errorReply(`Media approvals are disabled in this room.`);
}
if (user.can('showmedia', null, room, '/show')) return this.errorReply(`Use !show instead.`);
if (room.pendingApprovals?.has(user.id)) return this.errorReply('You have a request pending already.');
if (!toID(target)) return this.parse(`/help requestshow`);
let [link, comment] = target.split(',');
if (!/^https?:\/\//.test(link)) link = `https://${link}`;
link = encodeURI(link);
let dimensions;
if (!/^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.be)(\/|$)/i.test(link)) {
if (link.includes('data:image/png;base64')) {
throw new Chat.ErrorMessage('Please provide an actual link (you probably copied the URL wrong?).');
}
try {
dimensions = await Chat.fitImage(link);
} catch {
throw new Chat.ErrorMessage('Invalid link.');
}
}
if (!room.pendingApprovals) room.pendingApprovals = new Map();
room.pendingApprovals.set(user.id, {
name: user.name,
link: link,
comment: comment,
dimensions: dimensions,
});
this.sendReply(`You have requested to show the link: ${link}${comment ? ` (with the comment ${comment})` : ''}.`);
const message = `|tempnotify|pendingapprovals|Pending media request!` +
`|${user.name} has requested to show media in ${room.title}.|new media request`;
room.sendRankedUsers(message, '%');
room.sendMods(
Utils.html`|uhtml|request-${user.id}|<div class="infobox">${user.name} wants to show <a href="${link}">${link}</a><br>` +
`<button class="button" name="send" value="/approveshow ${user.id}">Approve</button><br>` +
`<button class="button" name="send" value="/denyshow ${user.id}">Deny</button></div>`
);
},
requestshowhelp: [`/requestshow [link], [comment] - Requests permission to show media in the room.`],
async approveshow(target, room, user) {
room = this.requireRoom();
this.checkCan('mute', null, room);
if (!room.settings.requestShowEnabled) {
return this.errorReply(`Media approvals are disabled in this room.`);
}
const userid = toID(target);
if (!userid) return this.parse(`/help approveshow`);
const request = room.pendingApprovals?.get(userid);
if (!request) return this.errorReply(`${userid} has no pending request.`);
if (userid === user.id) {
return this.errorReply(`You can't approve your own /show request.`);
}
room.pendingApprovals!.delete(userid);
room.sendMods(`|uhtmlchange|request-${target}|`);
room.sendRankedUsers(`|tempnotifyoff|pendingapprovals`, '%');
let buf;
if (request.dimensions) { // image
const [width, height, resized] = request.dimensions;
buf = Utils.html`<img src="${request.link}" width="${width}" height="${height}" />`;
if (resized) buf += Utils.html`<br /><a href="${request.link}" target="_blank">full-size image</a>`;
} else {
buf = await YouTube.generateVideoDisplay(request.link);
if (!buf) return this.errorReply('Could not get YouTube video');
}
buf += Utils.html`<br /><div class="infobox"><small>(Requested by ${request.name})</small>`;
if (request.comment) {
buf += Utils.html`<br />${request.comment}</small></div>`;
} else {
buf += `</small></div>`;
}
room.add(`|c| ${request.name}|/raw ${buf}`);
this.privateModAction(`${user.name} approved showing media from ${request.name}.`);
},
approveshowhelp: [`/approveshow [user] - Approves the media display request of [user]. Requires: % @ # &`],
denyshow(target, room, user) {
room = this.requireRoom();
this.checkCan('mute', null, room);
if (!room.settings.requestShowEnabled) {
return this.errorReply(`Media approvals are disabled in this room.`);
}
target = toID(target);
if (!target) return this.parse(`/help denyshow`);
const entry = room.pendingApprovals?.get(target);
if (!entry) return this.errorReply(`${target} has no pending request.`);
room.pendingApprovals!.delete(target);
room.sendMods(`|uhtmlchange|request-${target}|`);
room.sendRankedUsers(`|tempnotifyoff|pendingapprovals`, '%');
this.privateModAction(`${user.name} denied ${target}'s request to display ${entry.link}.`);
},
denyshowhelp: [`/denyshow [user] - Denies the media display request of [user]. Requires: % @ # &`],
approvallog(target, room, user) {
room = this.requireRoom();
return this.parse(`/sl approved showing media from, ${room.roomid}`);
},
approvalloghelp: [`/approvallog - View a log of past media approvals in the current room. Requires: % @ # &`],
viewapprovals(target, room, user) {
room = this.requireRoom();
return this.parse(`/join view-approvals-${room.roomid}`);
},
viewapprovalshelp: [
`/viewapprovals - View a list of users who have requested to show media in the current room.`,
`Requires: % @ # &`,
],
async show(target, room, user, connection) {
if (!room?.persist && !this.pmTarget) return this.errorReply(`/show cannot be used in temporary rooms.`);
if (!toID(target).trim()) return this.parse(`/help show`);
if (Monitor.countNetRequests(connection.ip)) {
return this.errorReply(`You are using this command too quickly. Wait a bit and try again.`);
}
const [link, comment] = Utils.splitFirst(target, ',');
let buf;
if (YouTube.linkRegex.test(link)) {
buf = await YouTube.generateVideoDisplay(link);
this.message = this.message.replace(/&ab_channel=(.*)(&|)/ig, '').replace(/https:\/\/www\./ig, '');
} else if (Twitch.linkRegex.test(link)) {
const channelId = Twitch.linkRegex.exec(link)?.[2]?.trim();
if (!channelId) return this.errorReply(`Specify a Twitch channel.`);
const info = await Twitch.getChannel(channelId);
if (!info) return this.errorReply(`Channel ${channelId} not found.`);
buf = `Watching <b><a class="subtle" href="https://twitch.tv/${info.url}">${info.display_name}</a></b>...<br />`;
buf += `<twitch src="${link}" />`;
} else {
if (link.includes('data:image/png;base64')) {
throw new Chat.ErrorMessage('Please provide an actual link (you probably copied it wrong?).');
}
try {
const [width, height, resized] = await Chat.fitImage(link);
buf = Utils.html`<img src="${link}" width="${width}" height="${height}" />`;
if (resized) buf += Utils.html`<br /><a href="${link}" target="_blank">full-size image</a>`;
} catch {
return this.errorReply('Invalid image');
}
}
if (comment) buf += Utils.html`<br />(${comment.trim()})</div>`;
this.checkBroadcast();
if (this.broadcastMessage) {
if (room) {
this.checkCan('show', null, room);
} else {
this.checkCan('altsself');
}
}
this.runBroadcast();
this.sendReplyBox(buf);
},
showhelp: [
`/show [url] - Shows you an image or YouTube video.`,
`!show [url] - Shows an image or YouTube to everyone in a chatroom. Requires: whitelist % @ # &`,
],
rebroadcast(target, room, user, connection) {
if (!target || !target.startsWith('!') || !this.shouldBroadcast()) {
return this.parse('/help rebroadcast');
}
room = this.requireRoom();
room.lastBroadcast = '';
this.parse(target, {broadcastPrefix: "!rebroadcast "});
},
rebroadcasthelp: [
`!rebroadcast ![command] - Bypasses the broadcast cooldown to broadcast a command.`,
],
regdate: 'registertime',
regtime: 'registertime',
async registertime(target, room, user, connection) {
this.runBroadcast();
if (Monitor.countNetRequests(connection.ip)) {
return this.errorReply(`You are using this command too quickly. Wait a bit and try again.`);
}
if (!user.autoconfirmed) return this.errorReply(`Only autoconfirmed users can use this command.`);
target = toID(target);
if (!target) target = user.id;
let rawResult;
try {
rawResult = await Net(`https://${Config.routes.root}/users/${target}.json`).get();
} catch (e: any) {
if (e.message.includes('Not found')) throw new Chat.ErrorMessage(`User '${target}' is unregistered.`);
throw new Chat.ErrorMessage(e.message);
}
// not in a try-catch block because if this doesn't work, this is a problem that should be known
const result = JSON.parse(rawResult);
const date = new Date(result.registertime * 1000);
const duration = Date.now() - date.getTime();
// hardcode, since the loginserver doesn't store exact times, and
// so this can look quite inaccurate if it was within the last day
const regTimeAgo = duration > 24 * 60 * 60 * 1000 ?
Chat.toDurationString(duration, {precision: 1}) :
'less than a day';
this.sendReplyBox(Utils.html`The user '${target}' registered ${regTimeAgo} ago, on the date ${date.toDateString()}.`);
},
registertimehelp: [`/registertime OR /regtime [user] - Find out when [user] registered.`],
pi(target, room, user) {
if (!this.runBroadcast()) return false;
return this.sendReplyBox(
'Did you mean: 1. 3.1415926535897932384626... (Decimal)<br />' +
'2. 3.184809493B91866... (Duodecimal)<br />' +
'3. 3.243F6A8885A308D... (Hexadecimal)<br /><br />' +
'How many digits of pi do YOU know? Test it out <a href="http://guangcongluo.com/mempi/">here</a>!'
);
},
pihelp: [`/pi - Displays the first several digits of pi in several notation types.`],
code(target, room, user, connection) {
// target is trimmed by Chat#splitMessage, but leading spaces can be
// important to code block indentation.
target = this.message.substr(this.cmdToken.length + this.cmd.length + +this.message.includes(' ')).trimRight();
if (!target) return this.parse('/help code');
if (target.length >= 8192) return this.errorReply("Your code must be under 8192 characters long!");
if (target.length < 80 && !target.includes('\n') && !target.includes('```') && this.shouldBroadcast()) {
return this.checkChat(`\`\`\`${target}\`\`\``);
}
this.checkBroadcast(true, '!code');
this.runBroadcast(true);
const isPMOrPersonalRoom = this.room?.settings.isPersonal !== false;
if (this.broadcasting) {
if (isPMOrPersonalRoom) {
target = this.filter(target)!;
if (!target) return this.errorReply(`Invalid code.`);
}
return `/raw <div class="infobox">${Chat.getReadmoreCodeBlock(target)}</div>`;
} else {
this.sendReplyBox(Chat.getReadmoreCodeBlock(target));
}
},
codehelp: [
`!code [code] - Broadcasts code to a room. Accepts multi-line arguments. Requires: + % @ & #`,
`/code [code] - Shows you code. Accepts multi-line arguments.`,
],
};
export const pages: Chat.PageTable = {
battlerules(query, user) {
const rules = Object.values(Dex.data.Rulesets).filter(rule => rule.effectType !== "Format");
const tourHelp = `https://www.smogon.com/forums/threads/pok%C3%A9mon-showdown-forum-rules-resources-read-here-first.3570628/#post-6777489`;
this.title = "Custom Rules";
let rulesHTML = `<div class="pad"><h1>Custom Rules in challenges and tournaments</h1>`;
const basics = [
`<p>Pokémon Showdown! supports custom rules in three ways:</p>`,
`<ul><li>Challenging another user, using the command <code>/challenge USERNAME, FORMAT @@@ RULES</code></li>`,
`<li>Tournaments, using the command <code>/tour rules RULES</code> (see the <a href="${tourHelp}">Tournament command help)</a></li>`,
`<li>Custom rules on your own server</li></ul>`,
`<h2><u>Bans</u></h2>`,
`<p>Bans are just a <code>-</code> followed by the thing you want to ban.</p>`,
`<h3>Individual bans</h3>`,
`<ul><li><code>- Arceus</code>: Ban a Pokémon (including all formes)</li>`,
`<li><code>- Arceus-Flying</code> or <code>- Giratina-Altered</code>: Ban a Pokémon forme</li>`,
`<li><code>- Baton Pass</code>: Ban a move/item/ability/etc</li></ul>`,
`<h3>Group bans</h3>`,
`<ul><li><code>- OU</code> or <code>- DUU</code>: Ban a tier</li>`,
`<li><code>- Mega</code> or <code>- CAP</code>: Ban a Pokémon category</li></ul>`,
`<h3>Complex bans</h3>`,
`<ul><li><code>- Blaziken + Speed Boost</code>: Ban a combination of things in a single Pokemon (you can have a Blaziken, and you can have Speed Boost on the same team, but the Blaziken can't have Speed Boost)</li>`,
`<li><code>- Drizzle ++ Swift Swim</code>: Ban a combination of things in a team (if any Pokémon on your team have Drizzle, no Pokémon can have Swift Swim)</li></ul>`,
`<h2><u>Unbans</u></h2>`,
`<p>Using a <code>+</code> instead of a <code>-</code> unbans that category.</p>`,
`<ul><li><code>+ Blaziken</code>: Unban/unrestrict a Pokémon.</li></ul>`,
`<p><a class="button" href="https://github.com/smogon/pokemon-showdown/blob/master/config/CUSTOM-RULES.md">More details</a></p>`,
];
const rulesets = [
`<h2><u>Rules, mods, and clauses</u></h2>`,
`<p>The following rules can be added to challenges/tournaments to modify the style of play. Alternatively, already present rules can be removed from formats by preceding the rule name with <code>!</code></p>`,
`<p>However, some rules, like <code>Obtainable</code>, are made of subrules, that can be individually turned on and off.</p>`,
`<div class="ladder"><table><tr><th>Rule Name</th><th>Description</th></tr>`,
];
for (const rule of rules) {
if (rule.hasValue) continue;
const desc = rule.desc ? rule.desc : "No description.";
rulesets.push(`<tr><td>${rule.name}</td><td>${desc}</td></tr>`);
}
rulesets.push(
`</table></div>`,
`<h3>Value rules</h3>`,
`<ul><li>Value rules are formatted like [Name] = [value], e.g. "Force Monotype = Water" or "Min Team Size = 4"</li>`,
`<li>To remove a value rule, use <code>![rule name]</code>.</li>`,
`<li>To override another value rule, use <code>!! [Name] = [new value]</code>. For example, overriding the Min Source Gen on [Gen 8] VGC 2021 Series 10 from 8 to 3 would look like <code>!! Min Source Gen = 3</code>.</li></ul>`,
`<div class="ladder"><table><tr><th>Rule Name</th><th>Description</th></tr>`
);
for (const rule of rules) {
if (!rule.hasValue) continue;
const desc = rule.desc ? rule.desc : "No description.";
rulesets.push(`<tr><td>${rule.name}</td><td>${desc}</td></tr>`);
}
rulesets.push(`</table></div>`);
rulesHTML += `${basics.concat(rulesets).join('')}</div>`;
return rulesHTML;
},
punishments(query, user) {
this.title = 'Punishments';
const room = this.requireRoom();
let buf = "";
if (!user.named) return Rooms.RETRY_AFTER_LOGIN;
if (!room.persist) return;
this.checkCan('mute', null, room);
// Ascending order
const sortedPunishments = Utils.sortBy([...Punishments.getPunishments(room.roomid)], ([id, entry]) => (
entry.expireTime
));
const sP = new Map();
for (const [id, entry] of sortedPunishments) {
sP.set(id, entry);
}
buf += Punishments.visualizePunishments(sP, user);
return buf;
},
globalpunishments(query, user) {
this.title = 'Global Punishments';
let buf = "";
if (!user.named) return Rooms.RETRY_AFTER_LOGIN;
this.checkCan('lock');
// Ascending order
const sortedPunishments = Utils.sortBy([...Punishments.getPunishments()], ([id, entry]) => (
entry.expireTime
));
const sP = new Map();
for (const punishment of sortedPunishments) {
sP.set(punishment[0], punishment[1]);
}
buf += Punishments.visualizePunishments(sP, user);
return buf;
},
approvals(args) {
const room = Rooms.get(args[0]) as ChatRoom | GameRoom;
this.checkCan('mute', null, room);
if (!room.pendingApprovals) room.pendingApprovals = new Map();
if (room.pendingApprovals.size < 1) return `<h2>No pending approvals on ${room.title}</h2>`;
let buf = `<div class="pad"><strong>Pending media requests on ${room.title}</strong><hr />`;
for (const [userid, entry] of room.pendingApprovals) {
buf += `<strong>${entry.name}</strong><div class="infobox">`;
buf += `<strong>Requester ID:</strong> ${userid}<br />`;
buf += `<strong>Link:</strong> <a href="${entry.link}">${entry.link}</a><br />`;
buf += `<strong>Comment:</strong> ${entry.comment}`;
buf += `</div><hr />`;
}
return buf;
},
};
process.nextTick(() => {
Dex.includeData();
Chat.multiLinePattern.register(
'/htmlbox', '/quote', '/addquote', '!htmlbox', '/addhtmlbox', '/addrankhtmlbox', '/adduhtml',
'/changeuhtml', '/addrankuhtmlbox', '/changerankuhtmlbox', '/addrankuhtml', '/addhtmlfaq',
'/sendhtmlpage',
);
}); | the_stack |
import type { languages } from '../fillers/monaco-editor-core';
export const conf: languages.LanguageConfiguration = {
comments: {
lineComment: '#'
},
brackets: [
['{', '}'],
['[', ']'],
['(', ')']
],
surroundingPairs: [
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '(', close: ')' },
{ open: "'", close: "'" },
{ open: '"', close: '"' }
],
autoClosingPairs: [
{ open: "'", close: "'", notIn: ['string', 'comment'] },
{ open: '"', close: '"', notIn: ['comment'] },
{ open: '"""', close: '"""' },
{ open: '`', close: '`', notIn: ['string', 'comment'] },
{ open: '(', close: ')' },
{ open: '{', close: '}' },
{ open: '[', close: ']' },
{ open: '<<', close: '>>' }
],
indentationRules: {
increaseIndentPattern: /^\s*(after|else|catch|rescue|fn|[^#]*(do|<\-|\->|\{|\[|\=))\s*$/,
decreaseIndentPattern: /^\s*((\}|\])\s*$|(after|else|catch|rescue|end)\b)/
}
};
/**
* A Monarch lexer for the Elixir language.
*
* References:
*
* * Monarch documentation - https://microsoft.github.io/monaco-editor/monarch.html
* * Elixir lexer - https://github.com/elixir-makeup/makeup_elixir/blob/master/lib/makeup/lexers/elixir_lexer.ex
* * TextMate lexer (elixir-tmbundle) - https://github.com/elixir-editors/elixir-tmbundle/blob/master/Syntaxes/Elixir.tmLanguage
* * TextMate lexer (vscode-elixir-ls) - https://github.com/elixir-lsp/vscode-elixir-ls/blob/master/syntaxes/elixir.json
*/
export const language = <languages.IMonarchLanguage>{
defaultToken: 'source',
tokenPostfix: '.elixir',
brackets: [
{ open: '[', close: ']', token: 'delimiter.square' },
{ open: '(', close: ')', token: 'delimiter.parenthesis' },
{ open: '{', close: '}', token: 'delimiter.curly' },
{ open: '<<', close: '>>', token: 'delimiter.angle.special' }
],
// Below are lists/regexps to which we reference later.
declarationKeywords: [
'def',
'defp',
'defn',
'defnp',
'defguard',
'defguardp',
'defmacro',
'defmacrop',
'defdelegate',
'defcallback',
'defmacrocallback',
'defmodule',
'defprotocol',
'defexception',
'defimpl',
'defstruct'
],
operatorKeywords: ['and', 'in', 'not', 'or', 'when'],
namespaceKeywords: ['alias', 'import', 'require', 'use'],
otherKeywords: [
'after',
'case',
'catch',
'cond',
'do',
'else',
'end',
'fn',
'for',
'if',
'quote',
'raise',
'receive',
'rescue',
'super',
'throw',
'try',
'unless',
'unquote_splicing',
'unquote',
'with'
],
constants: ['true', 'false', 'nil'],
nameBuiltin: ['__MODULE__', '__DIR__', '__ENV__', '__CALLER__', '__STACKTRACE__'],
// Matches any of the operator names:
// <<< >>> ||| &&& ^^^ ~~~ === !== ~>> <~> |~> <|> == != <= >= && || \\ <> ++ -- |> =~ -> <- ~> <~ :: .. = < > + - * / | . ^ & !
operator:
/-[->]?|!={0,2}|\*|\/|\\\\|&{1,3}|\.\.?|\^(?:\^\^)?|\+\+?|<(?:-|<<|=|>|\|>|~>?)?|=~|={1,3}|>(?:=|>>)?|\|~>|\|>|\|{1,3}|~>>?|~~~|::/,
// See https://hexdocs.pm/elixir/syntax-reference.html#variables
variableName: /[a-z_][a-zA-Z0-9_]*[?!]?/,
// See https://hexdocs.pm/elixir/syntax-reference.html#atoms
atomName: /[a-zA-Z_][a-zA-Z0-9_@]*[?!]?|@specialAtomName|@operator/,
specialAtomName: /\.\.\.|<<>>|%\{\}|%|\{\}/,
aliasPart: /[A-Z][a-zA-Z0-9_]*/,
moduleName: /@aliasPart(?:\.@aliasPart)*/,
// Sigil pairs are: """ """, ''' ''', " ", ' ', / /, | |, < >, { }, [ ], ( )
sigilSymmetricDelimiter: /"""|'''|"|'|\/|\|/,
sigilStartDelimiter: /@sigilSymmetricDelimiter|<|\{|\[|\(/,
sigilEndDelimiter: /@sigilSymmetricDelimiter|>|\}|\]|\)/,
decimal: /\d(?:_?\d)*/,
hex: /[0-9a-fA-F](_?[0-9a-fA-F])*/,
octal: /[0-7](_?[0-7])*/,
binary: /[01](_?[01])*/,
// See https://hexdocs.pm/elixir/master/String.html#module-escape-characters
escape: /\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}|\\./,
// The keys below correspond to tokenizer states.
// We start from the root state and match against its rules
// until we explicitly transition into another state.
// The `include` simply brings in all operations from the given state
// and is useful for improving readability.
tokenizer: {
root: [
{ include: '@whitespace' },
{ include: '@comments' },
// Keywords start as either an identifier or a string,
// but end with a : so it's important to match this first.
{ include: '@keywordsShorthand' },
{ include: '@numbers' },
{ include: '@identifiers' },
{ include: '@strings' },
{ include: '@atoms' },
{ include: '@sigils' },
{ include: '@attributes' },
{ include: '@symbols' }
],
// Whitespace
whitespace: [[/\s+/, 'white']],
// Comments
comments: [[/(#)(.*)/, ['comment.punctuation', 'comment']]],
// Keyword list shorthand
keywordsShorthand: [
[/(@atomName)(:)/, ['constant', 'constant.punctuation']],
// Use positive look-ahead to ensure the string is followed by :
// and should be considered a keyword.
[
/"(?=([^"]|#\{.*?\}|\\")*":)/,
{ token: 'constant.delimiter', next: '@doubleQuotedStringKeyword' }
],
[
/'(?=([^']|#\{.*?\}|\\')*':)/,
{ token: 'constant.delimiter', next: '@singleQuotedStringKeyword' }
]
],
doubleQuotedStringKeyword: [
[/":/, { token: 'constant.delimiter', next: '@pop' }],
{ include: '@stringConstantContentInterpol' }
],
singleQuotedStringKeyword: [
[/':/, { token: 'constant.delimiter', next: '@pop' }],
{ include: '@stringConstantContentInterpol' }
],
// Numbers
numbers: [
[/0b@binary/, 'number.binary'],
[/0o@octal/, 'number.octal'],
[/0x@hex/, 'number.hex'],
[/@decimal\.@decimal([eE]-?@decimal)?/, 'number.float'],
[/@decimal/, 'number']
],
// Identifiers
identifiers: [
// Tokenize identifier name in function-like definitions.
// Note: given `def a + b, do: nil`, `a` is not a function name,
// so we use negative look-ahead to ensure there's no operator.
[
/\b(defp?|defnp?|defmacrop?|defguardp?|defdelegate)(\s+)(@variableName)(?!\s+@operator)/,
[
'keyword.declaration',
'white',
{
cases: {
unquote: 'keyword',
'@default': 'function'
}
}
]
],
// Tokenize function calls
[
// In-scope call - an identifier followed by ( or .(
/(@variableName)(?=\s*\.?\s*\()/,
{
cases: {
// Tokenize as keyword in cases like `if(..., do: ..., else: ...)`
'@declarationKeywords': 'keyword.declaration',
'@namespaceKeywords': 'keyword',
'@otherKeywords': 'keyword',
'@default': 'function.call'
}
}
],
[
// Referencing function in a module
/(@moduleName)(\s*)(\.)(\s*)(@variableName)/,
['type.identifier', 'white', 'operator', 'white', 'function.call']
],
[
// Referencing function in an Erlang module
/(:)(@atomName)(\s*)(\.)(\s*)(@variableName)/,
['constant.punctuation', 'constant', 'white', 'operator', 'white', 'function.call']
],
[
// Piping into a function (tokenized separately as it may not have parentheses)
/(\|>)(\s*)(@variableName)/,
[
'operator',
'white',
{
cases: {
'@otherKeywords': 'keyword',
'@default': 'function.call'
}
}
]
],
[
// Function reference passed to another function
/(&)(\s*)(@variableName)/,
['operator', 'white', 'function.call']
],
// Language keywords, builtins, constants and variables
[
/@variableName/,
{
cases: {
'@declarationKeywords': 'keyword.declaration',
'@operatorKeywords': 'keyword.operator',
'@namespaceKeywords': 'keyword',
'@otherKeywords': 'keyword',
'@constants': 'constant.language',
'@nameBuiltin': 'variable.language',
'_.*': 'comment.unused',
'@default': 'identifier'
}
}
],
// Module names
[/@moduleName/, 'type.identifier']
],
// Strings
strings: [
[/"""/, { token: 'string.delimiter', next: '@doubleQuotedHeredoc' }],
[/'''/, { token: 'string.delimiter', next: '@singleQuotedHeredoc' }],
[/"/, { token: 'string.delimiter', next: '@doubleQuotedString' }],
[/'/, { token: 'string.delimiter', next: '@singleQuotedString' }]
],
doubleQuotedHeredoc: [
[/"""/, { token: 'string.delimiter', next: '@pop' }],
{ include: '@stringContentInterpol' }
],
singleQuotedHeredoc: [
[/'''/, { token: 'string.delimiter', next: '@pop' }],
{ include: '@stringContentInterpol' }
],
doubleQuotedString: [
[/"/, { token: 'string.delimiter', next: '@pop' }],
{ include: '@stringContentInterpol' }
],
singleQuotedString: [
[/'/, { token: 'string.delimiter', next: '@pop' }],
{ include: '@stringContentInterpol' }
],
// Atoms
atoms: [
[/(:)(@atomName)/, ['constant.punctuation', 'constant']],
[/:"/, { token: 'constant.delimiter', next: '@doubleQuotedStringAtom' }],
[/:'/, { token: 'constant.delimiter', next: '@singleQuotedStringAtom' }]
],
doubleQuotedStringAtom: [
[/"/, { token: 'constant.delimiter', next: '@pop' }],
{ include: '@stringConstantContentInterpol' }
],
singleQuotedStringAtom: [
[/'/, { token: 'constant.delimiter', next: '@pop' }],
{ include: '@stringConstantContentInterpol' }
],
// Sigils
// See https://elixir-lang.org/getting-started/sigils.html
// Sigils allow for typing values using their textual representation.
// All sigils start with ~ followed by a letter indicating sigil type
// and then a delimiter pair enclosing the textual representation.
// Optional modifiers are allowed after the closing delimiter.
// For instance a regular expressions can be written as:
// ~r/foo|bar/ ~r{foo|bar} ~r/foo|bar/g
//
// In general lowercase sigils allow for interpolation
// and escaped characters, whereas uppercase sigils don't
//
// During tokenization we want to distinguish some
// specific sigil types, namely string and regexp,
// so that they cen be themed separately.
//
// To reasonably handle all those combinations we leverage
// dot-separated states, so if we transition to @sigilStart.interpol.s.{.}
// then "sigilStart.interpol.s" state will match and also all
// the individual dot-separated parameters can be accessed.
sigils: [
[/~[a-z]@sigilStartDelimiter/, { token: '@rematch', next: '@sigil.interpol' }],
[/~[A-Z]@sigilStartDelimiter/, { token: '@rematch', next: '@sigil.noInterpol' }]
],
sigil: [
[/~([a-zA-Z])\{/, { token: '@rematch', switchTo: '@sigilStart.$S2.$1.{.}' }],
[/~([a-zA-Z])\[/, { token: '@rematch', switchTo: '@sigilStart.$S2.$1.[.]' }],
[/~([a-zA-Z])\(/, { token: '@rematch', switchTo: '@sigilStart.$S2.$1.(.)' }],
[/~([a-zA-Z])\</, { token: '@rematch', switchTo: '@sigilStart.$S2.$1.<.>' }],
[
/~([a-zA-Z])(@sigilSymmetricDelimiter)/,
{ token: '@rematch', switchTo: '@sigilStart.$S2.$1.$2.$2' }
]
],
// The definitions below expect states to be of the form:
//
// sigilStart.<interpol-or-noInterpol>.<sigil-letter>.<start-delimiter>.<end-delimiter>
// sigilContinue.<interpol-or-noInterpol>.<sigil-letter>.<start-delimiter>.<end-delimiter>
//
// The sigilStart state is used only to properly classify the token (as string/regex/sigil)
// and immediately switches to the sigilContinue sate, which handles the actual content
// and waits for the corresponding end delimiter.
'sigilStart.interpol.s': [
[
/~s@sigilStartDelimiter/,
{
token: 'string.delimiter',
switchTo: '@sigilContinue.$S2.$S3.$S4.$S5'
}
]
],
'sigilContinue.interpol.s': [
[
/(@sigilEndDelimiter)[a-zA-Z]*/,
{
cases: {
'$1==$S5': { token: 'string.delimiter', next: '@pop' },
'@default': 'string'
}
}
],
{ include: '@stringContentInterpol' }
],
'sigilStart.noInterpol.S': [
[
/~S@sigilStartDelimiter/,
{
token: 'string.delimiter',
switchTo: '@sigilContinue.$S2.$S3.$S4.$S5'
}
]
],
'sigilContinue.noInterpol.S': [
// Ignore escaped sigil end
[/(^|[^\\])\\@sigilEndDelimiter/, 'string'],
[
/(@sigilEndDelimiter)[a-zA-Z]*/,
{
cases: {
'$1==$S5': { token: 'string.delimiter', next: '@pop' },
'@default': 'string'
}
}
],
{ include: '@stringContent' }
],
'sigilStart.interpol.r': [
[
/~r@sigilStartDelimiter/,
{
token: 'regexp.delimiter',
switchTo: '@sigilContinue.$S2.$S3.$S4.$S5'
}
]
],
'sigilContinue.interpol.r': [
[
/(@sigilEndDelimiter)[a-zA-Z]*/,
{
cases: {
'$1==$S5': { token: 'regexp.delimiter', next: '@pop' },
'@default': 'regexp'
}
}
],
{ include: '@regexpContentInterpol' }
],
'sigilStart.noInterpol.R': [
[
/~R@sigilStartDelimiter/,
{
token: 'regexp.delimiter',
switchTo: '@sigilContinue.$S2.$S3.$S4.$S5'
}
]
],
'sigilContinue.noInterpol.R': [
// Ignore escaped sigil end
[/(^|[^\\])\\@sigilEndDelimiter/, 'regexp'],
[
/(@sigilEndDelimiter)[a-zA-Z]*/,
{
cases: {
'$1==$S5': { token: 'regexp.delimiter', next: '@pop' },
'@default': 'regexp'
}
}
],
{ include: '@regexpContent' }
],
// Fallback to the generic sigil by default
'sigilStart.interpol': [
[
/~([a-zA-Z])@sigilStartDelimiter/,
{
token: 'sigil.delimiter',
switchTo: '@sigilContinue.$S2.$S3.$S4.$S5'
}
]
],
'sigilContinue.interpol': [
[
/(@sigilEndDelimiter)[a-zA-Z]*/,
{
cases: {
'$1==$S5': { token: 'sigil.delimiter', next: '@pop' },
'@default': 'sigil'
}
}
],
{ include: '@sigilContentInterpol' }
],
'sigilStart.noInterpol': [
[
/~([a-zA-Z])@sigilStartDelimiter/,
{
token: 'sigil.delimiter',
switchTo: '@sigilContinue.$S2.$S3.$S4.$S5'
}
]
],
'sigilContinue.noInterpol': [
// Ignore escaped sigil end
[/(^|[^\\])\\@sigilEndDelimiter/, 'sigil'],
[
/(@sigilEndDelimiter)[a-zA-Z]*/,
{
cases: {
'$1==$S5': { token: 'sigil.delimiter', next: '@pop' },
'@default': 'sigil'
}
}
],
{ include: '@sigilContent' }
],
// Attributes
attributes: [
// Module @doc* attributes - tokenized as comments
[
/\@(module|type)?doc (~[sS])?"""/,
{
token: 'comment.block.documentation',
next: '@doubleQuotedHeredocDocstring'
}
],
[
/\@(module|type)?doc (~[sS])?"/,
{
token: 'comment.block.documentation',
next: '@doubleQuotedStringDocstring'
}
],
[/\@(module|type)?doc false/, 'comment.block.documentation'],
// Module attributes
[/\@(@variableName)/, 'variable']
],
doubleQuotedHeredocDocstring: [
[/"""/, { token: 'comment.block.documentation', next: '@pop' }],
{ include: '@docstringContent' }
],
doubleQuotedStringDocstring: [
[/"/, { token: 'comment.block.documentation', next: '@pop' }],
{ include: '@docstringContent' }
],
// Operators, punctuation, brackets
symbols: [
// Code point operator (either with regular character ?a or an escaped one ?\n)
[/\?(\\.|[^\\\s])/, 'number.constant'],
// Anonymous function arguments
[/&\d+/, 'operator'],
// Bitshift operators (must go before delimiters, so that << >> don't match first)
[/<<<|>>>/, 'operator'],
// Delimiter pairs
[/[()\[\]\{\}]|<<|>>/, '@brackets'],
// Triple dot is a valid name (must go before operators, so that .. doesn't match instead)
[/\.\.\./, 'identifier'],
// Punctuation => (must go before operators, so it's not tokenized as = then >)
[/=>/, 'punctuation'],
// Operators
[/@operator/, 'operator'],
// Punctuation
[/[:;,.%]/, 'punctuation']
],
// Generic helpers
stringContentInterpol: [
{ include: '@interpolation' },
{ include: '@escapeChar' },
{ include: '@stringContent' }
],
stringContent: [[/./, 'string']],
stringConstantContentInterpol: [
{ include: '@interpolation' },
{ include: '@escapeChar' },
{ include: '@stringConstantContent' }
],
stringConstantContent: [[/./, 'constant']],
regexpContentInterpol: [
{ include: '@interpolation' },
{ include: '@escapeChar' },
{ include: '@regexpContent' }
],
regexpContent: [
// # may be a regular regexp char, so we use a heuristic
// assuming a # surrounded by whitespace is actually a comment.
[/(\s)(#)(\s.*)$/, ['white', 'comment.punctuation', 'comment']],
[/./, 'regexp']
],
sigilContentInterpol: [
{ include: '@interpolation' },
{ include: '@escapeChar' },
{ include: '@sigilContent' }
],
sigilContent: [[/./, 'sigil']],
docstringContent: [[/./, 'comment.block.documentation']],
escapeChar: [[/@escape/, 'constant.character.escape']],
interpolation: [
[/#{/, { token: 'delimiter.bracket.embed', next: '@interpolationContinue' }]
],
interpolationContinue: [
[/}/, { token: 'delimiter.bracket.embed', next: '@pop' }],
// Interpolation brackets may contain arbitrary code,
// so we simply match against all the root rules,
// until we reach interpolation end (the above matches).
{ include: '@root' }
]
}
}; | the_stack |
* @module TileTreeSupplier
*/
import { BeTimePoint, compareStringsOrUndefined, Id64String } from "@itwin/core-bentley";
import {
BatchType, Cartographic, ColorDef, Feature, FeatureTable, Frustum, FrustumPlanes, GeoCoordStatus, OrbitGtBlobProps, PackedFeatureTable, QParams3d,
Quantization, RealityDataFormat, RealityDataProvider, RealityDataSourceKey, ViewFlagOverrides,
} from "@itwin/core-common";
import { Point3d, Range3d, Transform, Vector3d } from "@itwin/core-geometry";
import {
ALong, CRSManager, Downloader, DownloaderXhr, OnlineEngine, OPCReader, OrbitGtAList, OrbitGtBlockIndex, OrbitGtBounds, OrbitGtCoordinate,
OrbitGtDataManager, OrbitGtFrameData, OrbitGtIProjectToViewForSort, OrbitGtIViewRequest, OrbitGtLevel, OrbitGtTileIndex, OrbitGtTileLoadSorter,
OrbitGtTransform, PageCachedFile, PointDataRaw, UrlFS,
} from "@itwin/core-orbitgt";
import { calculateEcefToDbTransformAtLocation } from "../BackgroundMapGeometry";
import { HitDetail } from "../HitDetail";
import { IModelApp } from "../IModelApp";
import { IModelConnection } from "../IModelConnection";
import { RealityDataSource } from "../RealityDataSource";
import { Mesh } from "../render/primitives/mesh/MeshPrimitives";
import { PointCloudArgs } from "../render/primitives/PointCloudPrimitive";
import { RenderGraphic } from "../render/RenderGraphic";
import { RenderMemory } from "../render/RenderMemory";
import { RenderSystem } from "../render/RenderSystem";
import { ViewingSpace } from "../ViewingSpace";
import { Viewport } from "../Viewport";
import {
RealityModelTileTree, Tile, TileContent, TileDrawArgs, TileLoadPriority, TileParams, TileRequest, TileTree, TileTreeOwner,
TileTreeParams, TileTreeSupplier, TileUsageMarker,
} from "./internal";
const scratchRange = Range3d.create();
const scratchWorldFrustum = new Frustum();
interface OrbitGtTreeId {
rdSourceKey: RealityDataSourceKey;
modelId: Id64String;
}
class OrbitGtTreeSupplier implements TileTreeSupplier {
public getOwner(treeId: OrbitGtTreeId, iModel: IModelConnection): TileTreeOwner {
return iModel.tiles.getTileTreeOwner(treeId, this);
}
public async createTileTree(treeId: OrbitGtTreeId, iModel: IModelConnection): Promise<TileTree | undefined> {
return OrbitGtTileTree.createOrbitGtTileTree(treeId.rdSourceKey, iModel, treeId.modelId);
}
public compareTileTreeIds(lhs: OrbitGtTreeId, rhs: OrbitGtTreeId): number {
let cmp = compareStringsOrUndefined(lhs.rdSourceKey.id, rhs.rdSourceKey.id);
if (0 === cmp)
cmp = compareStringsOrUndefined(lhs.rdSourceKey.format, rhs.rdSourceKey.format);
if (0 === cmp)
cmp = compareStringsOrUndefined(lhs.rdSourceKey.iTwinId, rhs.rdSourceKey.iTwinId);
if (0 === cmp)
cmp = compareStringsOrUndefined(lhs.modelId, rhs.modelId);
return cmp;
}
}
const orbitGtTreeSupplier = new OrbitGtTreeSupplier();
function transformFromOrbitGt(ogtTransform: OrbitGtTransform, result?: Transform): Transform {
if (undefined === result)
result = Transform.createIdentity();
result.matrix.setRowValues(
ogtTransform.getElement(0, 0), ogtTransform.getElement(0, 1), ogtTransform.getElement(0, 2),
ogtTransform.getElement(1, 0), ogtTransform.getElement(1, 1), ogtTransform.getElement(1, 2),
ogtTransform.getElement(2, 0), ogtTransform.getElement(2, 1), ogtTransform.getElement(2, 2));
result.origin.x = ogtTransform.getElement(0, 3);
result.origin.y = ogtTransform.getElement(1, 3);
result.origin.z = ogtTransform.getElement(2, 3);
return result;
}
function pointFromOrbitGt(ogtCoordinate: OrbitGtCoordinate, result?: Point3d): Point3d {
if (undefined === result)
result = Point3d.create();
result.x = ogtCoordinate.x;
result.y = ogtCoordinate.y;
result.z = ogtCoordinate.z;
return result;
}
function rangeFromOrbitGt(ogtBounds: OrbitGtBounds, result?: Range3d) {
if (undefined === result)
result = Range3d.create();
pointFromOrbitGt(ogtBounds.min, result.low);
pointFromOrbitGt(ogtBounds.max, result.high);
return result;
}
/** @internal */
export function createOrbitGtTileTreeReference(props: OrbitGtTileTree.ReferenceProps): RealityModelTileTree.Reference {
return new OrbitGtTreeReference(props);
}
class OrbitGtTileTreeParams implements TileTreeParams {
public id: string;
public modelId: string;
public iModel: IModelConnection;
public get priority(): TileLoadPriority { return TileLoadPriority.Context; }
public constructor(rdSourceKey: RealityDataSourceKey, iModel: IModelConnection, modelId: Id64String, public location: Transform) {
const key = rdSourceKey;
this.id = `${key.provider}:${key.format}:${key.id}:${key.iTwinId}`;
this.modelId = modelId;
this.iModel = iModel;
}
}
class OrbitGtRootTile extends Tile {
protected _loadChildren(_resolve: (children: Tile[] | undefined) => void, _reject: (error: Error) => void): void { }
public async requestContent(_isCanceled: () => boolean): Promise<TileRequest.Response> { return undefined; }
public get channel() { return IModelApp.tileAdmin.channels.getForHttp("itwinjs-orbitgit"); }
public async readContent(_data: TileRequest.ResponseData, _system: RenderSystem, _isCanceled?: () => boolean): Promise<TileContent> { return {}; }
public override freeMemory(): void { }
constructor(params: TileParams, tree: TileTree) { super(params, tree); }
}
class OrbitGtViewRequest extends OrbitGtIViewRequest {
private _tileToIModelTransform: Transform;
constructor(private _tileDrawArgs: TileDrawArgs, private _centerOffset: Vector3d) {
super();
this._tileToIModelTransform = _tileDrawArgs.location.multiplyTransformTransform(Transform.createTranslation(_centerOffset));
}
public isVisibleBox(bounds: OrbitGtBounds): boolean {
const box = Frustum.fromRange(rangeFromOrbitGt(bounds, scratchRange));
const worldBox = box.transformBy(this._tileToIModelTransform, scratchWorldFrustum);
return FrustumPlanes.Containment.Outside !== this._tileDrawArgs.frustumPlanes.computeFrustumContainment(worldBox, undefined);
}
public getFrameTime(): number {
return this._tileDrawArgs.now.milliseconds;
}
public shouldSplit(level: OrbitGtLevel, tile: OrbitGtTileIndex) {
// get the world size of the tile voxels
const tileCenter: OrbitGtCoordinate = level.getTileGrid().getCellCenter(tile.gridIndex);
tileCenter.x += this._centerOffset.x;
tileCenter.y += this._centerOffset.y;
tileCenter.z += this._centerOffset.z;
const worldCenter: Point3d = this._tileDrawArgs.location.multiplyXYZ(tileCenter.x, tileCenter.y, tileCenter.z);
const worldCenter2: Point3d = this._tileDrawArgs.location.multiplyXYZ(tileCenter.x, tileCenter.y, tileCenter.z + level.getTileGrid().size.z);
const voxelSize: number = worldCenter2.distance(worldCenter) / 64;
// get the world size of a screen pixel at the tile center
const viewPt: Point3d = this._tileDrawArgs.worldToViewMap.transform0.multiplyPoint3dQuietNormalize(worldCenter);
const viewPt2: Point3d = new Point3d(viewPt.x + 1.0, viewPt.y, viewPt.z);
const pixelSizeAtCenter: number = this._tileDrawArgs.worldToViewMap.transform1.multiplyPoint3dQuietNormalize(viewPt).distance(this._tileDrawArgs.worldToViewMap.transform1.multiplyPoint3dQuietNormalize(viewPt2));
// stop splitting if the voxel size of the children becomes too small to improve quality
const split: boolean = (0.5 * voxelSize > 2.0 * pixelSizeAtCenter);
return split;
}
}
class TileSortProjector implements OrbitGtIProjectToViewForSort {
private _sortTransform: Transform;
constructor(iModelTransform: Transform, viewingSpace: ViewingSpace, centerOffset: Vector3d) {
const rotation = viewingSpace.rotation;
let origin: Vector3d;
if (undefined === viewingSpace.eyePoint) {
origin = Vector3d.createFrom(viewingSpace.viewOrigin);
const viewDelta = viewingSpace.viewDelta;
const eyeDelta = Vector3d.createFrom({ x: viewDelta.x / 2, y: viewDelta.y / 2, z: viewDelta.z * 10 });
rotation.multiplyVector(eyeDelta, eyeDelta);
origin.addInPlace(eyeDelta);
} else {
origin = Vector3d.createFrom(viewingSpace.eyePoint);
}
rotation.multiplyVector(origin);
origin.scaleInPlace(-1);
const toViewTransform = Transform.createOriginAndMatrix(origin, rotation);
const tileToIModelTransform = iModelTransform.multiplyTransformTransform(Transform.createTranslation(centerOffset));
this._sortTransform = toViewTransform.multiplyTransformTransform(tileToIModelTransform);
}
public projectToViewForSort(coordinate: OrbitGtCoordinate) {
const point = pointFromOrbitGt(coordinate);
this._sortTransform.multiplyPoint3d(point, point);
coordinate.x = point.x;
coordinate.y = point.y;
coordinate.z = point.z;
}
}
class OrbitGtTileGraphic extends TileUsageMarker {
public readonly graphic: RenderGraphic;
public constructor(graphic: RenderGraphic, viewport: Viewport, time: BeTimePoint) {
super();
this.graphic = graphic;
this.mark(viewport, time);
}
public dispose(): void {
this.graphic.dispose();
}
}
/** @internal */
export class OrbitGtTileTree extends TileTree {
private _tileParams: TileParams;
public rootTile: OrbitGtRootTile;
public viewFlagOverrides: ViewFlagOverrides = {};
private _tileGraphics = new Map<string, OrbitGtTileGraphic>();
public constructor(treeParams: TileTreeParams, private _dataManager: OrbitGtDataManager, cloudRange: Range3d, private _centerOffset: Vector3d, private _ecefTransform: Transform) {
super(treeParams);
const worldContentRange = this.iModelTransform.multiplyRange(cloudRange);
this.iModel.expandDisplayedExtents(worldContentRange);
this._tileParams = { contentId: "0", range: cloudRange, maximumSize: 256 };
this.rootTile = new OrbitGtRootTile(this._tileParams, this);
}
public override async getEcefTransform(): Promise<Transform | undefined> {
return this._ecefTransform;
}
public override dispose(): void {
if (this.isDisposed)
return;
for (const graphic of this._tileGraphics.values())
graphic.dispose();
this._tileGraphics.clear();
super.dispose();
}
protected _selectTiles(_args: TileDrawArgs): Tile[] { return []; }
public get is3d(): boolean { return true; }
public override get isContentUnbounded(): boolean { return false; }
public get maxDepth(): number | undefined { return undefined; }
private _doPrune(olderThan: BeTimePoint) {
for (const [key, graphic] of this._tileGraphics)
if (graphic.isExpired(olderThan)) {
graphic.dispose();
this._tileGraphics.delete(key);
}
}
public prune() {
const olderThan = BeTimePoint.now().minus(this.expirationTime);
this._doPrune(olderThan);
}
public override collectStatistics(stats: RenderMemory.Statistics): void {
for (const tileGraphic of this._tileGraphics)
tileGraphic[1].graphic.collectStatistics(stats);
}
public draw(args: TileDrawArgs) {
const debugControl = args.context.target.debugControl;
const debugBuilder = (debugControl && debugControl.displayRealityTileRanges) ? args.context.createSceneGraphicBuilder() : undefined;
const doLogging = (debugControl && debugControl.logRealityTiles);
const viewRequest = new OrbitGtViewRequest(args, this._centerOffset);
const levelsInView = new OrbitGtAList<OrbitGtLevel>();
const blocksInView = new OrbitGtAList<OrbitGtBlockIndex>();
const tilesInView = new OrbitGtAList<OrbitGtTileIndex>();
const frameData = new OrbitGtFrameData();
this._dataManager.getViewTree().renderView3D(viewRequest, levelsInView, blocksInView, tilesInView, frameData.tilesToRender);
this._dataManager.filterLoadList(levelsInView, blocksInView, tilesInView, frameData.levelsToLoad, frameData.blocksToLoad, frameData.tilesToLoad);
tilesInView.sort(new OrbitGtTileLoadSorter(this._dataManager.getViewTree(), new TileSortProjector(this.iModelTransform, args.context.viewingSpace, this._centerOffset)));
let totalPointCount = 0;
const tileCount = frameData.tilesToRender.size();
// Inform TileAdmin about tiles we are handling ourselves...
IModelApp.tileAdmin.addExternalTilesForUser(args.context.viewport, { requested: frameData.tilesToLoad.size(), selected: tileCount, ready: tileCount });
if (debugBuilder)
debugBuilder.setSymbology(ColorDef.red, ColorDef.red, 1);
let minLevel = 100, maxLevel = -100;
for (let t: number = 0; t < tileCount; t++) {
const tile: PointDataRaw = frameData.tilesToRender.get(t) as PointDataRaw;
minLevel = Math.min(minLevel, tile.tileIndex.level);
maxLevel = Math.max(maxLevel, tile.tileIndex.level);
totalPointCount += tile.tileIndex.pointCount;
const key = tile.tileIndex.key;
const cachedGraphic = this._tileGraphics.get(key);
if (undefined !== cachedGraphic) {
cachedGraphic.mark(args.context.viewport, args.now);
args.graphics.add(cachedGraphic.graphic);
} else {
const range = rangeFromOrbitGt(tile.bounds);
range.low.addInPlace(this._centerOffset);
range.high.addInPlace(this._centerOffset);
const qParams = QParams3d.fromRange(range, undefined, (tile.points8 != null) ? Quantization.rangeScale8 : Quantization.rangeScale16);
const featureTable = new FeatureTable(1, this.modelId, BatchType.Primary);
const features = new Mesh.Features(featureTable);
const system = IModelApp.renderSystem;
const voxelSize = (range.high.x - range.low.x) / 64;
features.add(new Feature(this.modelId), 1);
const tilePoints = (tile.points8 != null) ? tile.points8.toNativeBuffer() : tile.points16.toNativeBuffer();
let renderGraphic = system.createPointCloud(new PointCloudArgs(tilePoints, qParams, tile.colors.toNativeBuffer(), features, voxelSize, true), this.iModel);
renderGraphic = system.createBatch(renderGraphic!, PackedFeatureTable.pack(featureTable), range);
args.graphics.add(renderGraphic);
this._tileGraphics.set(key, new OrbitGtTileGraphic(renderGraphic, args.context.viewport, args.now));
}
if (debugBuilder)
debugBuilder.addRangeBox(rangeFromOrbitGt(tile.bounds));
}
if (debugBuilder)
args.graphics.add(debugBuilder.finish());
if (doLogging) {
// eslint-disable-next-line no-console
console.log(`Total OrbitGtTiles: ${tileCount} MinLevel: ${minLevel} MaxLevel: ${maxLevel} Total Points: ${totalPointCount}`);
}
args.drawGraphics();
if (frameData.hasMissingData()) {
this._dataManager.loadData(frameData).then(() => IModelApp.tileAdmin.onTileLoad.raiseEvent(this.rootTile)).catch((_err: any) => undefined);
}
}
}
/** @internal */
// eslint-disable-next-line no-redeclare
export namespace OrbitGtTileTree {
export interface ReferenceProps extends RealityModelTileTree.ReferenceBaseProps {
orbitGtBlob?: OrbitGtBlobProps;
modelId?: Id64String;
}
function isValidSASToken(downloadUrl: string): boolean {
// Create fake URL for and parameter parsing and SAS token URI parsing
if(!downloadUrl.startsWith("http"))
downloadUrl = `http://x.com/x?${downloadUrl}`;
const sasUrl = new URL(downloadUrl);
const se = sasUrl.searchParams.get("se");
if (se) {
const expiryUTC = new Date(se);
const now = new Date();
const currentUTC = new Date(now?.toUTCString());
return expiryUTC >= currentUTC;
}
return false;
}
function isValidOrbitGtBlobProps(props: OrbitGtBlobProps): boolean {
// Check main OrbitGtBlobProps fields are defined
if(!props.accountName || !props.containerName || !props.blobFileName || !props.sasToken)
return false;
// Check SAS token is valid
return isValidSASToken(props.sasToken);
}
export async function createOrbitGtTileTree(rdSourceKey: RealityDataSourceKey, iModel: IModelConnection, modelId: Id64String): Promise<TileTree | undefined> {
const rdSource = await RealityDataSource.fromKey(rdSourceKey, iModel.iTwinId);
const isContextShare = rdSourceKey.provider === RealityDataProvider.ContextShare;
const isTilestUrl = rdSourceKey.provider === RealityDataProvider.TilesetUrl;
let blobStringUrl: string;
if (isContextShare) {
const realityData = rdSource ? rdSource.realityData : undefined;
if (rdSource === undefined || realityData === undefined )
return undefined;
const docRootName = realityData.rootDocument;
if (!docRootName)
return undefined;
const token = await IModelApp.getAccessToken();
const blobUrl = await realityData.getBlobUrl(token, docRootName);
blobStringUrl = blobUrl.toString();
} else if (isTilestUrl) {
blobStringUrl = rdSourceKey.id;
} else {
const orbitGtBlobProps = RealityDataSource.createOrbitGtBlobPropsFromKey(rdSourceKey);
if (orbitGtBlobProps === undefined)
return undefined;
if(!isValidOrbitGtBlobProps(orbitGtBlobProps))
return undefined;
const { accountName, containerName, blobFileName, sasToken } = orbitGtBlobProps;
blobStringUrl = blobFileName;
if (accountName.length > 0)
blobStringUrl = UrlFS.getAzureBlobSasUrl(accountName, containerName, blobFileName, sasToken);
}
if (Downloader.INSTANCE == null) Downloader.INSTANCE = new DownloaderXhr();
if (CRSManager.ENGINE == null) CRSManager.ENGINE = await OnlineEngine.create();
// wrap a caching layer (16 MB) around the blob file
const urlFS: UrlFS = new UrlFS();
const blobFileSize: ALong = await urlFS.getFileLength(blobStringUrl);
const cacheKilobytes = 128;
const cachedBlobFile = new PageCachedFile(urlFS, blobStringUrl, blobFileSize, cacheKilobytes * 1024 /* pageSize*/, 128/* maxPageCount*/);
const pointCloudReader = await OPCReader.openFile(cachedBlobFile, blobStringUrl, true/* lazyLoading*/);
let pointCloudCRS = pointCloudReader.getFileCRS();
if (pointCloudCRS == null)
pointCloudCRS = "";
const dataManager = new OrbitGtDataManager(pointCloudReader, pointCloudCRS, PointDataRaw.TYPE);
const pointCloudBounds = dataManager.getPointCloudBounds();
const pointCloudRange = rangeFromOrbitGt(pointCloudBounds);
const pointCloudCenter = pointCloudRange.localXYZToWorld(.5, .5, .5)!;
const addCloudCenter = Transform.createTranslation(pointCloudCenter);
const ecefTransform = Transform.createIdentity();
let pointCloudCenterToDb = addCloudCenter;
if (pointCloudCRS.length > 0) {
await CRSManager.ENGINE.prepareForArea(pointCloudCRS, pointCloudBounds);
const wgs84CRS = "4978";
await CRSManager.ENGINE.prepareForArea(wgs84CRS, new OrbitGtBounds());
const pointCloudToEcef = transformFromOrbitGt(CRSManager.createTransform(pointCloudCRS, new OrbitGtCoordinate(pointCloudCenter.x, pointCloudCenter.y, pointCloudCenter.z), wgs84CRS));
const pointCloudCenterToEcef = pointCloudToEcef.multiplyTransformTransform(addCloudCenter);
ecefTransform.setFrom(pointCloudCenterToEcef);
let ecefToDb = iModel.getMapEcefToDb(0);
// In initial publishing version the iModel ecef Transform was used to locate the reality model.
// This would work well only for tilesets published from that iModel but for iModels the ecef transform is calculated
// at the center of the project extents and the reality model location may differ greatly, and the curvature of the earth
// could introduce significant errors.
// The publishing was modified to calculate the ecef transform at the reality model range center and at the same time the "iModelPublishVersion"
// member was added to the root object.
const ecefOrigin = pointCloudCenterToEcef.getOrigin();
const dbOrigin = ecefToDb.multiplyPoint3d(ecefOrigin);
const realityOriginToProjectDistance = iModel.projectExtents.distanceToPoint(dbOrigin);
const maxProjectDistance = 1E5; // Only use the project GCS projection if within 100KM of the project. Don't attempt to use GCS if global reality model or in another locale - Results will be unreliable.
if (realityOriginToProjectDistance < maxProjectDistance) {
const cartographicOrigin = Cartographic.fromEcef(ecefOrigin);
const geoConverter = iModel.noGcsDefined ? undefined : iModel.geoServices.getConverter("WGS84");
if (cartographicOrigin !== undefined && geoConverter !== undefined) {
const geoOrigin = Point3d.create(cartographicOrigin.longitudeDegrees, cartographicOrigin.latitudeDegrees, cartographicOrigin.height);
const response = await geoConverter.getIModelCoordinatesFromGeoCoordinates([geoOrigin]);
if (response.iModelCoords[0].s === GeoCoordStatus.Success) {
const ecefToDbOrigin = await calculateEcefToDbTransformAtLocation(Point3d.fromJSON(response.iModelCoords[0].p), iModel);
if (ecefToDbOrigin)
ecefToDb = ecefToDbOrigin;
}
}
}
pointCloudCenterToDb = ecefToDb.multiplyTransformTransform(pointCloudCenterToEcef);
}
const params = new OrbitGtTileTreeParams(rdSourceKey, iModel, modelId, pointCloudCenterToDb);
// We use a RTC transform to avoid jitter from large cloud coordinates.
const centerOffset = Vector3d.create(-pointCloudCenter.x, -pointCloudCenter.y, -pointCloudCenter.z);
pointCloudRange.low.addInPlace(centerOffset);
pointCloudRange.high.addInPlace(centerOffset);
return new OrbitGtTileTree(params, dataManager, pointCloudRange, centerOffset, ecefTransform);
}
}
/** Supplies a reality data [[TileTree]] from a URL. May be associated with a persistent [[GeometricModelState]], or attached at run-time via a [[ContextOrbitGtState]].
* @internal
*/
class OrbitGtTreeReference extends RealityModelTileTree.Reference {
public readonly treeOwner: TileTreeOwner;
protected _rdSourceKey: RealityDataSourceKey;
public override get castsShadows() { return false; }
public constructor(props: OrbitGtTileTree.ReferenceProps) {
super(props);
// Create rdSourceKey if not provided
if (props.rdSourceKey) {
this._rdSourceKey = props.rdSourceKey;
} else if (props.orbitGtBlob) {
this._rdSourceKey = RealityDataSource.createKeyFromOrbitGtBlobProps(props.orbitGtBlob);
} else {
// TODO: Maybe we should throw an exception
this._rdSourceKey = RealityDataSource.createKeyFromBlobUrl("", RealityDataProvider.OrbitGtBlob, RealityDataFormat.OPC);
}
const ogtTreeId: OrbitGtTreeId = { rdSourceKey: this._rdSourceKey, modelId: this.modelId };
this.treeOwner = orbitGtTreeSupplier.getOwner(ogtTreeId, props.iModel);
}
public override async getToolTip(hit: HitDetail): Promise<HTMLElement | string | undefined> {
const tree = this.treeOwner.tileTree;
if (undefined === tree || hit.iModel !== tree.iModel)
return undefined;
const strings = [];
strings.push(IModelApp.localization.getLocalizedString("iModelJs:RealityModelTypes.OrbitGTPointCloud"));
if (this._name)
strings.push(`${IModelApp.localization.getLocalizedString("iModelJs:TooltipInfo.Name")} ${this._name}`);
const div = document.createElement("div");
div.innerHTML = strings.join("<br>");
return div;
}
} | the_stack |
import {
CARD_EDITABLE_KEY,
CARD_ELEMENT_KEY,
CARD_KEY,
CARD_LEFT_SELECTOR,
CARD_LOADING_KEY,
CARD_RIGHT_SELECTOR,
CARD_TYPE_KEY,
CARD_VALUE_KEY,
} from '../constants/card';
import {
CardOptions,
CardInterface,
MaximizeInterface,
CardToolbarItemOptions,
CardEntry as CardEntryType,
CardToolbarInterface,
ResizeInterface,
CardValue,
} from '../types/card';
import { EditorInterface } from '../types/editor';
import { NodeInterface } from '../types/node';
import { RangeInterface } from '../types/range';
import { ToolbarItemOptions } from '../types/toolbar';
import { TinyCanvasInterface } from '../types/tiny-canvas';
import { decodeCardValue, encodeCardValue, isEngine, random } from '../utils';
import Maximize from './maximize';
import Resize from './resize';
import Toolbar from './toolbar';
import { $ } from '../node';
import { CardType, SelectStyleType } from './enum';
import { DATA_ELEMENT, UI } from '../constants';
abstract class CardEntry<T extends CardValue = CardValue>
implements CardInterface<T>
{
protected readonly editor: EditorInterface;
readonly root: NodeInterface;
toolbarModel?: CardToolbarInterface;
resizeModel?: ResizeInterface;
activatedByOther: string | false = false;
selectedByOther: string | false = false;
/**
* 可编辑的节点
*/
readonly contenteditable: Array<string> = [];
static readonly cardName: string;
static readonly cardType: CardType;
static readonly autoActivate: boolean;
static readonly autoSelected: boolean = true;
static readonly singleSelectable: boolean;
static readonly collab: boolean = true;
static readonly focus: boolean;
static readonly selectStyleType: SelectStyleType = SelectStyleType.BORDER;
static readonly lazyRender: boolean = false;
private defaultMaximize: MaximizeInterface;
isMaximize: boolean = false;
get isEditable() {
return this.contenteditable.length > 0;
}
get activated() {
return this.root.hasClass('card-activated');
}
private setActivated(activated: boolean) {
activated
? this.root.addClass('card-activated')
: this.root.removeClass('card-activated');
}
get selected() {
return this.root.hasClass('card-selected');
}
private setSelected(selected: boolean) {
selected
? this.root.addClass('card-selected')
: this.root.removeClass('card-selected');
}
get id() {
const value = this.getValue();
return typeof value === 'object' ? value?.id || '' : '';
}
get name() {
return this.root.attributes(CARD_KEY);
}
get type() {
return (
this.getValue()?.type ||
(this.root.attributes(CARD_TYPE_KEY) as CardType)
);
}
set type(type: CardType) {
if (!this.name || type === this.type) return;
// 替换后重新渲染
const { card } = this.editor;
const component = card.replace(this, this.name, {
...this.getValue(),
type,
});
card.render(component.root);
component.activate(false);
card.activate(component.root);
}
get loading() {
return !!this.root.attributes(CARD_LOADING_KEY);
}
constructor({ editor, value, root }: CardOptions<T>) {
this.editor = editor;
const type =
value?.type || (this.constructor as CardEntryType).cardType;
const tagName = type === 'inline' ? 'span' : 'div';
this.root = root ? root : $('<'.concat(tagName, ' />'));
if (typeof value === 'string') value = decodeCardValue(value);
value = value || ({} as T);
value.id = this.getId(value.id);
value.type = type;
this.setValue(value);
this.defaultMaximize = new Maximize(this.editor, this);
}
init() {
this.root.attributes(
CARD_EDITABLE_KEY,
this.isEditable ? 'true' : 'false',
);
this.toolbarModel?.hide();
this.toolbarModel?.destroy();
if (this.toolbar) {
this.toolbarModel = new Toolbar(this.editor, this);
}
if (this.resize) {
this.resizeModel = new Resize(this.editor, this);
}
}
private getId(curId?: string) {
const idCache: Array<string> = [];
this.editor.card.each((card) => {
idCache.push(card.id);
});
if (curId && idCache.indexOf(curId) < 0) return curId;
let id = random();
while (idCache.indexOf(id) >= 0) id = random();
return id;
}
// 设置 DOM 属性里的数据
setValue(value: Partial<T>) {
if (value == null) {
return;
}
const currentValue = this.getValue();
if (!!currentValue?.id) delete value['id'];
value = { ...currentValue, ...value } as T;
if (value.type && currentValue?.type !== value.type) {
this.type = value.type;
}
this.root.attributes(CARD_VALUE_KEY, encodeCardValue(value));
}
// 获取 DOM 属性里的数据
getValue() {
const value = this.root.attributes(CARD_VALUE_KEY);
if (!value) return {} as T;
return decodeCardValue<T>(value);
}
/**
* 获取Card内的 DOM 节点
* @param selector
*/
find(selector: string) {
return this.root.find(selector);
}
findByKey(key: string) {
const body = this.root.first() || $([]);
if (key === 'body' || body.length === 0) return body;
const children = body.children();
const index = ['left', 'center', 'right'].indexOf(key);
if (index > -1) {
const child = children.eq(index);
if (child?.attributes(CARD_ELEMENT_KEY) === key) return child;
}
const tag = this.type === CardType.BLOCK ? 'div' : 'span';
return this.find(`${tag}[${CARD_ELEMENT_KEY}=${key}]`);
}
activate(activated: boolean) {
if (activated) {
if (!this.activated) {
this.setActivated(activated);
this.onActivate(activated);
}
} else if (this.activated) {
this.setActivated(activated);
this.onActivate(false);
}
}
select(selected: boolean) {
if (!isEngine(this.editor) || this.activatedByOther) {
return;
}
if (selected) {
if (!this.selected && !this.isMaximize) {
this.setSelected(selected);
this.onSelect(selected);
}
} else if (this.selected) {
this.setSelected(selected);
this.onSelect(false);
}
}
getCenter() {
return this.findByKey('center');
}
isCenter(node: NodeInterface) {
const center = node.closest(
this.type === CardType.BLOCK
? `div[${CARD_ELEMENT_KEY}=center]`
: `span[${CARD_ELEMENT_KEY}=center]`,
);
return center.length > 0 && center.equal(this.findByKey('center'));
}
isCursor(node: NodeInterface) {
return this.isLeftCursor(node) || this.isRightCursor(node);
}
isLeftCursor(node: NodeInterface) {
if (node.isElement() && node.attributes(CARD_ELEMENT_KEY) !== 'left')
return false;
const cursor = node.closest(CARD_LEFT_SELECTOR);
return cursor.length > 0 && cursor.equal(this.findByKey('left'));
}
isRightCursor(node: NodeInterface) {
if (node.isElement() && node.attributes(CARD_ELEMENT_KEY) !== 'right')
return false;
const cursor = node.closest(CARD_RIGHT_SELECTOR);
return cursor.length > 0 && cursor.equal(this.findByKey('right'));
}
focus(range: RangeInterface, toStart?: boolean) {
const cardLeft = this.findByKey('left');
const cardRight = this.findByKey('right');
if (cardLeft.length === 0 || cardRight.length === 0) {
return;
}
range.select(toStart ? cardLeft : cardRight, true);
range.collapse(false);
if (this.onFocus) this.onFocus();
}
/**
* 当卡片聚焦时触发
*/
onFocus?(): void;
maximize() {
this.isMaximize = true;
this.defaultMaximize.maximize();
this.toolbarModel?.show();
}
minimize() {
this.isMaximize = false;
this.defaultMaximize.restore();
this.toolbarModel?.show();
}
/**
* 工具栏配置项
*/
toolbar?(): Array<CardToolbarItemOptions | ToolbarItemOptions>;
/**
* 是否可改变卡片大小,或者传入渲染节点
*/
resize?: boolean | (() => NodeInterface | void);
onSelect(selected: boolean): void {
const selectStyleType = (this.constructor as CardEntryType)
.selectStyleType;
if (selectStyleType === SelectStyleType.NONE) return;
const selectedClass = `data-card-${selectStyleType}-selected`;
const center = this.getCenter();
if (selected) {
center.addClass(selectedClass);
} else {
center.removeClass(selectedClass);
}
}
onSelectByOther(
selected: boolean,
value?: {
color: string;
rgb: string;
},
): NodeInterface | void {
const center = this.getCenter();
const selectStyleType = (this.constructor as CardEntryType)
.selectStyleType;
if (selectStyleType === SelectStyleType.BACKGROUND) {
center.css('background-color', selected ? value!.rgb : '');
} else {
center.css('outline', selected ? '2px solid ' + value!.color : '');
}
const className = 'card-selected-other';
if (selected) this.root.addClass(className);
else this.root.removeClass(className);
return center;
}
onSelectLeft?(event: KeyboardEvent): boolean | void;
onSelectRight?(event: KeyboardEvent): boolean | void;
onSelectUp?(event: KeyboardEvent): boolean | void;
onSelectDown?(event: KeyboardEvent): boolean | void;
onActivate(activated: boolean) {
if (!this.resize) return;
if (activated) this.resizeModel?.show();
else this.resizeModel?.hide();
}
onActivateByOther(
activated: boolean,
value?: {
color: string;
rgb: string;
},
): NodeInterface | void {
return this.onSelectByOther(activated, value);
}
onChange?(trigger: 'remote' | 'local', node: NodeInterface): void;
destroy() {
this.toolbarModel?.hide();
this.toolbarModel?.destroy();
this.resizeModel?.hide();
this.resizeModel?.destroy();
}
didInsert?(): void;
didUpdate?(): void;
beforeRender() {
const center = this.getCenter();
const loadingElement = $(
`<${
this.type === CardType.BLOCK ? 'div' : 'span'
} class="${CARD_LOADING_KEY}" ${DATA_ELEMENT}="${UI}" />`,
);
loadingElement.append(
'<svg viewBox="0 0 1024 1024" class="data-card-spin" data-icon="loading" width="1em" height="1em" fill="currentColor" aria-hidden="true"> <path d="M988 548c-19.9 0-36-16.1-36-36 0-59.4-11.6-117-34.6-171.3a440.45 440.45 0 0 0-94.3-139.9 437.71 437.71 0 0 0-139.9-94.3C629 83.6 571.4 72 512 72c-19.9 0-36-16.1-36-36s16.1-36 36-36c69.1 0 136.2 13.5 199.3 40.3C772.3 66 827 103 874 150c47 47 83.9 101.8 109.7 162.7 26.7 63.1 40.2 130.2 40.2 199.3.1 19.9-16 36-35.9 36z"></path></svg>',
);
center.empty().append(loadingElement);
}
didRender() {
if (this.loading) this.find(`.${CARD_LOADING_KEY}`).remove();
if (this.resize) {
const container =
typeof this.resize === 'function'
? this.resize()
: this.findByKey('body');
if (container && container.length > 0) {
this.resizeModel?.render(container);
}
}
this.toolbarModel?.hide();
this.toolbarModel?.destroy();
if (this.toolbar) {
this.toolbarModel = new Toolbar(this.editor, this);
}
if (this.isEditable) {
this.editor.nodeId.generateAll(this.getCenter().get<Element>()!);
}
}
abstract render(): NodeInterface | string | void;
updateBackgroundSelection?(range: RangeInterface): void;
drawBackground?(
node: NodeInterface,
range: RangeInterface,
targetCanvas: TinyCanvasInterface,
): DOMRect | RangeInterface[] | void | false;
/**
* 获取卡片区域选中的所有节点
*/
getSelectionNodes?(): Array<NodeInterface>;
executeMark?(mark: NodeInterface): void;
queryMarks?(): NodeInterface[];
}
export default CardEntry; | the_stack |
namespace gdjs {
export namespace fileSystem {
// The Node.js path module, or null if it can't be loaded.
export let _path: any = null;
// The Node.js fs module, or null if it can't be loaded.
export let _fs: any = null;
/** Get the Node.js path module, or null if it can't be loaded */
export const _getPath = function () {
if (!gdjs.fileSystem._path) {
// @ts-ignore
gdjs.fileSystem._path =
typeof require !== 'undefined' ? require('path') : null;
}
return gdjs.fileSystem._path;
};
/** Get the Node.js fs module, or null if it can't be loaded */
export const _getFs = function () {
if (!gdjs.fileSystem._fs) {
// @ts-ignore
gdjs.fileSystem._fs =
typeof require !== 'undefined' ? require('fs') : null;
}
return gdjs.fileSystem._fs;
};
export const getDirectoryName = function (fileOrFolderPath: string) {
const path = gdjs.fileSystem._getPath();
if (!path) {
return '';
}
return path.dirname(fileOrFolderPath);
};
export const getFileName = function (filePath: string) {
const path = gdjs.fileSystem._getPath();
if (!path) {
return '';
}
return path.basename(filePath);
};
export const getExtensionName = function (filePath: string) {
const path = gdjs.fileSystem._getPath();
if (!path) {
return '';
}
return path.extname(filePath);
};
/**
* Get the path to 'Desktop' folder.
* @param runtimeScene The current scene
* @return The path to the desktop folder
*/
export const getDesktopPath = function (
runtimeScene: gdjs.RuntimeScene
): string {
const electron = runtimeScene.getGame().getRenderer().getElectron();
if (electron) {
return electron.remote.app.getPath('desktop') || '';
} else {
return '';
}
};
/**
* Get the path to 'Documents' folder.
* @param runtimeScene The current scene
* @return The path to the documents folder
*/
export const getDocumentsPath = function (
runtimeScene: gdjs.RuntimeScene
): string {
const electron = runtimeScene.getGame().getRenderer().getElectron();
if (electron) {
return electron.remote.app.getPath('documents') || '';
} else {
return '';
}
};
/**
* Get the path to 'Pictures' folder.
* @param runtimeScene The current scene
* @return The path to the pictures folder
*/
export const getPicturesPath = function (
runtimeScene: gdjs.RuntimeScene
): string {
const electron = runtimeScene.getGame().getRenderer().getElectron();
if (electron) {
return electron.remote.app.getPath('pictures') || '';
} else {
return '';
}
};
/**
* Get the path to this application 'Executable' file.
* @param runtimeScene The current scene
* @return The path to this applications executable file
*/
export const getExecutablePath = function (
runtimeScene: gdjs.RuntimeScene
): string {
const electron = runtimeScene.getGame().getRenderer().getElectron();
if (electron) {
return electron.remote.app.getPath('exe') || '';
} else {
return '';
}
};
/**
* Get the path to this application 'Executable' folder.
* @param runtimeScene The current scene
* @return The path to this applications executable folder
*/
export const getExecutableFolderPath = function (
runtimeScene: gdjs.RuntimeScene
): string {
const path = gdjs.fileSystem._getPath();
const executablePath = gdjs.fileSystem.getExecutablePath(runtimeScene);
if (!path) {
return '';
}
return path.dirname(executablePath);
};
/**
* Get the path to 'UserData' folder.
* @param runtimeScene The current scene
* @return The path to userdata folder
*/
export const getUserdataPath = function (
runtimeScene: gdjs.RuntimeScene
): string {
const electron = runtimeScene.getGame().getRenderer().getElectron();
if (electron) {
return electron.remote.app.getPath('userData') || '';
} else {
return '';
}
};
/**
* Get the path to the user's home folder (on Windows `C:\Users\<USERNAME>\` for example).
* @return The path to user's "home" folder
*/
export const getUserHomePath = function (runtimeScene): string {
const electron = runtimeScene.getGame().getRenderer().getElectron();
if (electron) {
return electron.remote.app.getPath('home') || '';
} else {
return '';
}
};
/**
* Get the path to 'Temp' folder.
* @param runtimeScene The current scene
* @return The path to temp folder
*/
export const getTempPath = function (
runtimeScene: gdjs.RuntimeScene
): string {
const electron = runtimeScene.getGame().getRenderer().getElectron();
if (electron) {
return electron.remote.app.getPath('temp') || '';
} else {
return '';
}
};
/**
* Get the path delimiter specific to the operating system.
* @return The path delimiter
*/
export const getPathDelimiter = function (): string {
const path = gdjs.fileSystem._getPath();
if (path) {
return path.sep || '/';
} else {
return '/';
}
};
/**
* Create a new directory at the given path.
* @param directory The path to create a new directory
* @param resultVar The variable where to store the result of the operation
*/
export const makeDirectory = function (
directory: string,
resultVar: gdjs.Variable
) {
const fileSystem = gdjs.fileSystem._getFs();
let result = 'error';
if (fileSystem) {
try {
fileSystem.mkdirSync(directory);
result = 'ok';
} catch (err) {
console.error(
"Unable to create directory at: '" + directory + "': ",
err
);
}
}
resultVar.setString(result);
};
/**
* Save a string into a file, asynchronously.
* @param text The string to be saved
* @param savePath Path to the file
* @param resultVar The variable where to store the result of the operation
*/
export const saveStringToFileAsync = function (
text: string,
savePath: string,
resultVar: gdjs.Variable
) {
const fileSystem = gdjs.fileSystem._getFs();
if (fileSystem) {
fileSystem.writeFile(savePath, text, 'utf8', (err) => {
resultVar.setString('ok');
if (err) {
console.error(
"Unable to save the text to path: '" + savePath + "': ",
err
);
resultVar.setString('error');
}
});
}
};
/**
* Save a string into a file.
* @param text The string to be saved
* @param savePath Path to the file
* @param resultVar The variable where to store the result of the operation
*/
export const saveStringToFile = function (
text: string,
savePath: string,
resultVar: gdjs.Variable
) {
const fileSystem = gdjs.fileSystem._getFs();
let result = 'error';
if (fileSystem) {
try {
fileSystem.writeFileSync(savePath, text, 'utf8');
result = 'ok';
} catch (err) {
console.error(
"Unable to save the text to path: '" + savePath + "': ",
err
);
}
}
resultVar.setString(result);
};
/**
* Save a variable into a file in JSON format.
* @param variable The variable to be saved
* @param savePath Path to the file
* @param resultVar The variable where to store the result of the operation
*/
export const saveVariableToJSONFile = function (
variable: gdjs.Variable,
savePath: string,
resultVar: gdjs.Variable
) {
const fileSystem = gdjs.fileSystem._getFs();
let result = 'error';
if (fileSystem) {
try {
fileSystem.writeFileSync(
savePath,
JSON.stringify(variable.toJSObject()),
'utf8'
);
result = 'ok';
} catch (err) {
console.error(
"Unable to save the variable to path: '" + savePath + "': ",
err
);
}
}
resultVar.setString(result);
};
/**
* Save a variable into a file in JSON format, asynchronously.
* @param variable The variable to be saved
* @param savePath Path to the file
* @param resultVar The variable where to store the result of the operation
*/
export const saveVariableToJSONFileAsync = function (
variable: gdjs.Variable,
savePath: string,
resultVar: gdjs.Variable
) {
const fileSystem = gdjs.fileSystem._getFs();
if (fileSystem) {
fileSystem.writeFile(
savePath,
JSON.stringify(variable.toJSObject()),
'utf8',
(err) => {
resultVar.setString('ok');
if (err) {
console.error(
"Unable to save the variable to path: '" + savePath + "': ",
err
);
resultVar.setString('error');
}
}
);
}
};
/**
* Load a string from a file into a scene variable.
* @param stringVar Variable where to store the content
* @param loadPath Path to the file
* @param resultVar The variable where to store the result of the operation
*/
export const loadStringFromFile = function (
stringVar: gdjs.Variable,
loadPath: string,
resultVar: gdjs.Variable
) {
const fileSystem = gdjs.fileSystem._getFs();
let result = 'error';
if (fileSystem) {
try {
const data = fileSystem.readFileSync(loadPath, 'utf8');
if (data) {
stringVar.setString(data);
result = 'ok';
}
} catch (err) {
console.error(
"Unable to load the file at path: '" + loadPath + "': ",
err
);
}
}
resultVar.setString(result);
};
/**
* Load a JSON file and convert it into a variable.
* @param variable Variable to store the variable
* @param loadPath Path to the file
* @param resultVar The variable where to store the result of the operation
*/
export const loadVariableFromJSONFile = function (
variable: gdjs.Variable,
loadPath: string,
resultVar: gdjs.Variable
) {
const fileSystem = gdjs.fileSystem._getFs();
let result = 'error';
if (fileSystem) {
try {
const data = fileSystem.readFileSync(loadPath, 'utf8');
if (data) {
variable.fromJSON(data);
result = 'ok';
}
} catch (err) {
console.error(
"Unable to load variable from the file at path: '" +
loadPath +
"': ",
err
);
}
}
resultVar.setString(result);
};
/**
* Load a JSON file and convert it into a variable, asynchronously.
* @param variable Variable to store the variable
* @param loadPath Path to the file
* @param resultVar The variable where to store the result of the operation
*/
export const loadVariableFromJSONFileAsync = function (
variable: gdjs.Variable,
loadPath: string,
resultVar: gdjs.Variable
) {
const fileSystem = gdjs.fileSystem._getFs();
if (fileSystem) {
fileSystem.readFile(loadPath, 'utf8', (err, data) => {
if (data) {
variable.fromJSON(data);
resultVar.setString('ok');
}
if (err) {
console.error(
"Unable to load variable from the file at path: '" +
loadPath +
"': ",
err
);
resultVar.setString('error');
}
});
}
};
/**
* Load a string from a file into a scene variable, asynchronously.
* @param stringVar Variable where to store the content
* @param loadPath Path to the file
* @param resultVar The variable where to store the result of the operation
*/
export const loadStringFromFileAsync = function (
stringVar: gdjs.Variable,
loadPath: string,
resultVar: gdjs.Variable
) {
const fileSystem = gdjs.fileSystem._getFs();
if (fileSystem) {
fileSystem.readFile(loadPath, 'utf8', (err, data) => {
if (data) {
stringVar.setString(data);
resultVar.setString('ok');
}
if (err) {
console.error(
"Unable to load the file at path: '" + loadPath + "': ",
err
);
resultVar.setString('error');
}
});
}
};
/**
* Delete a file from the filesystem.
* @param filePath Path to the file
* @param resultVar The variable where to store the result of the operation
*/
export const deleteFile = function (
filePath: string,
resultVar: gdjs.Variable
) {
const fileSystem = gdjs.fileSystem._getFs();
let result = 'error';
if (fileSystem) {
try {
fileSystem.unlinkSync(filePath);
result = 'ok';
} catch (err) {
console.error("Unable to delete the file: '" + filePath + "': ", err);
result = 'error';
}
}
resultVar.setString(result);
};
/**
* Delete a file from the filesystem, asynchronously.
* @param filePath Path to the file
* @param resultVar The variable where to store the result of the operation
*/
export const deleteFileAsync = function (
filePath: string,
resultVar: gdjs.Variable
) {
const fileSystem = gdjs.fileSystem._getFs();
if (fileSystem) {
fileSystem.unlink(filePath, (err) => {
resultVar.setString('ok');
if (err) {
console.error(
"Unable to delete the file: '" + filePath + "': ",
err
);
resultVar.setString('error');
}
});
}
};
/**
* Check if the file or directory exists.
* @param filePath The path to the file or directory
* @return true if fhe file or directory exists
*/
export const pathExists = function (filePath: string): boolean {
const fileSystem = gdjs.fileSystem._getFs();
if (fileSystem) {
return fileSystem.existsSync(filePath);
} else {
return false;
}
};
}
} | the_stack |
import { Browser, EventHandler, createElement, EmitType } from '@syncfusion/ej2-base';
import { ILoadedEventArgs, ILoadEventArgs } from '../../src/linear-gauge/model/interface';
import { LinearGauge } from '../../src/linear-gauge/linear-gauge';
import {profile , inMB, getMemoryProfile} from '../common.spec';
import { MouseEvents } from '../base/events.spec';
import { Gradient } from '../../src/linear-gauge/axes/gradient';
LinearGauge.Inject( Gradient );
describe('Linear gauge control', () => {
describe('linear gauge direct properties', () => {
let gauge: LinearGauge;
let element: HTMLElement;
let svg: HTMLElement;
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
beforeAll((): void => {
element = createElement('div', { id: 'container' });
document.body.appendChild(element);
gauge = new LinearGauge();
gauge.appendTo('#container');
});
afterAll((): void => {
element.remove();
});
it('checking with ranges in vertical orientation', (): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_AxisIndex_0_Range_0');
expect(svg != null).toBe(true);
svg = document.getElementById('container_AxisIndex_0_Range_1');
expect(svg != null).toBe(true);
};
gauge.orientation = 'Vertical';
gauge.axes[0].opposedPosition = false;
gauge.axes[0].ranges = [
{
start: 0,
end: 50,
startWidth: 10,
endWidth: 20,
color: 'red',
position: 'Inside'
},
{
start: 50,
end: 100,
startWidth: 10,
endWidth: 20,
color: 'red',
position: 'Outside'
}
];
gauge.refresh();
});
it('checking with ranges in opposed position', (): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_AxisIndex_0_Range_0');
expect(svg != null).toBe(true);
svg = document.getElementById('container_AxisIndex_0_Range_1');
expect(svg != null).toBe(true);
};
gauge.orientation = 'Vertical';
gauge.axes[0].opposedPosition = true;
gauge.axes[0].ranges = [
{
start: 0,
end: 50,
startWidth: 10,
endWidth: 20,
color: 'red',
position: 'Inside'
},
{
start: 50,
end: 100,
startWidth: 10,
endWidth: 20,
color: 'red',
position: 'Outside'
}
];
gauge.refresh();
});
it('checking with ranges start and end with databind', (): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_AxisIndex_0_Range_0');
expect(svg != null).toBe(true);
svg = document.getElementById('container_AxisIndex_0_Range_1');
expect(svg != null).toBe(true);
};
gauge.axes[0].ranges = [
{
start: 10,
end: 40,
startWidth: 10,
endWidth: 20,
color: 'red',
position: 'Inside'
},
{
start: 50,
end: 100,
startWidth: 10,
endWidth: 20,
color: 'red',
position: 'Outside'
}
];
gauge.dataBind();
});
it('checking with ranges in horizontal orientation', (): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
// svg = document.getElementById('container_AxisIndex_0_Range_0');
// expect(svg != null).toBe(true);
// svg = document.getElementById('container_AxisIndex_0_Range_1');
// expect(svg != null).toBe(true);
};
gauge.orientation = 'Horizontal';
gauge.axes[0].opposedPosition = false;
gauge.axes[0].ranges = [
{
start: 0,
end: 50,
startWidth: 10,
endWidth: 20,
color: 'red',
position: 'Inside'
},
{
start: 50,
end: 100,
startWidth: 10,
endWidth: 20,
color: 'red',
position: 'Outside'
}
];
gauge.refresh();
});
it('checking with ranges in axis opposed position', (): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_AxisIndex_0_Range_0');
expect(svg != null).toBe(true);
svg = document.getElementById('container_AxisIndex_0_Range_1');
expect(svg != null).toBe(true);
};
gauge.orientation = 'Horizontal';
gauge.axes[0].opposedPosition = true;
gauge.axes[0].ranges = [
{
start: 0,
end: 50,
startWidth: 10,
endWidth: 20,
color: 'red',
position: 'Inside'
},
{
start: 50,
end: 100,
startWidth: 10,
endWidth: 20,
color: 'red',
position: 'Outside'
}
];
gauge.refresh();
});
it('checking with ranges in position as cross', (): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_AxisIndex_0_Range_0');
expect(svg != null).toBe(true);
svg = document.getElementById('container_AxisIndex_0_Range_1');
expect(svg != null).toBe(true);
};
gauge.orientation = 'Horizontal';
gauge.axes[0].opposedPosition = false;
gauge.axes[0].ranges[0].position = 'Cross';
gauge.axes[0].ranges[1].position = 'Cross';
gauge.refresh();
});
it('checking with ranges in position as cross with vertical orinetation', (): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_AxisIndex_0_Range_0');
expect(svg != null).toBe(true);
svg = document.getElementById('container_AxisIndex_0_Range_1');
expect(svg != null).toBe(true);
};
gauge.orientation = 'Vertical';
gauge.refresh();
});
it('checking with ranges start value greater than end value in vertical', (): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_AxisIndex_0_Range_0');
expect(svg != null).toBe(true);
};
gauge.orientation = 'Vertical';
gauge.axes[0].ranges[0].start = 30;
gauge.axes[0].ranges[0].end = 10;
gauge.refresh();
});
it('checking with ranges start value greater than end value in horizontal', (): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_AxisIndex_0_Range_0');
expect(svg != null).toBe(true);
};
gauge.orientation = 'Horizontal';
gauge.axes[0].ranges[0].start = 30;
gauge.axes[0].ranges[0].end = 10;
gauge.refresh();
});
it('checking stroke-width for same range start and end values', (): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_AxisIndex_0_Range_0');
expect(svg.getAttribute('stroke-width') == '0').toBe(true);
};
gauge.orientation = 'Horizontal';
gauge.axes[0].ranges[0].start = 30;
gauge.axes[0].ranges[0].end = 30;
gauge.axes[0].ranges[0].border.width = 5;
gauge.refresh();
});
it('checking stroke-width for different range start and end values', (): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_AxisIndex_0_Range_0');
expect(svg.getAttribute('stroke-width') == '5').toBe(true);
};
gauge.orientation = 'Horizontal';
gauge.axes[0].ranges[0].start = 30;
gauge.axes[0].ranges[0].end = 40;
gauge.axes[0].ranges[0].border.width = 5;
gauge.refresh();
});
});
describe('Checking the properties with pointers and gradients', () => {
let gauge: LinearGauge;
let element: HTMLElement;
let svg: HTMLElement;
let trigger: MouseEvents = new MouseEvents();
beforeAll((): void => {
element = createElement('div', { id: 'container' });
document.body.appendChild(element);
gauge = new LinearGauge({
orientation: 'Horizontal',
axes: [{
line: {
color: '#9E9E9E'
},
pointers: [{
value: 10,
height: 15,
width: 15,
placement: 'Near',
offset: -50,
markerType: 'Triangle',
linearGradient:{
startValue:"0%",
endValue:"100%",
colorStop:[{color:"red", offset:"0",style:"border: 10px solid powderblue;padding: 30px;"},
{color:"blue", offset:"15",style:" border: 15px solid powderblue;margin: 50px;"},
],
},
},
{
value: 10,
height: 45,
width: 45,
placement: 'Near',
markerType: 'Circle',
offset: -50,
radialGradient:{
radius: "50",
outerPosition: {x:"50%", y:"50%"},
innerPosition: {x: "50%", y: "50%"},
colorStop:[{color:"pink", offset:"0", opacity:1},
{color:"yellow", offset:"100", opacity:1}],
}
},
{
value: 60,
height: 45,
width: 45,
placement: 'Near',
type:"Bar",
offset: -50,
radialGradient:{
radius: "50",
outerPosition: {x:"50", y:"50"},
innerPosition: {x: "50", y: "50"},
colorStop:[{color:"grey", offset:"0", opacity:1},
{color:"blue", offset:"100", opacity:1}],
}
},
],
ranges: [{
start: 0,
end: 30,
startWidth: 50,
endWidth: 50,
linearGradient:{
startValue:"0",
endValue:"100",
colorStop:[{color:"orange", offset:"0%", opacity:1,style:"vergo"},
{color:"pink", offset:"50%", opacity:1,style:"vergo"},
{color:"green", offset:"100%", opacity:0.8},
],
}
},
{
start: 35,
end: 70,
startWidth: 50,
endWidth: 50,
radialGradient:{
radius: "50",
outerPosition: {x:"50", y:"50"},
innerPosition: {x: "50", y: "50"},
colorStop:[{color:"white", offset:"0%", opacity:1,style:"vergo"},
{color:"blue", offset:"50%", opacity:1,style:"vergo"},
{color:"yellow", offset:"100%", opacity:1}
],
}
},
],
majorTicks: {
color: '#9E9E9E',
interval: 10
},
minorTicks: {
color: '#9E9E9E',
interval: 2
},
labelStyle: {
font: {
color: '#424242'
},
offset: 48
}
}],
annotations: [{
content: '<div id="pointer" style="width:70px"><h1 style="font-size:14px;color:#424242">10 MPH</h1></div>',
axisIndex: 0,
axisValue: 10,
x: 10, zIndex: '1',
y: -70
}]
});
gauge.appendTo('#container');
});
afterAll((): void => {
element.remove();
});
it('checking the stroke property of the range', (): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_AxisIndex_0_Range_0');
expect(svg.getAttribute('stroke')).toBe("#000000");
};
gauge.refresh();
});
it('checking the opacity of the range element', (): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_AxisIndex_0_Range_0');
expect(svg.getAttribute('opacity')).toBe("1");
};
gauge.refresh();
});
it('checking the stroke width of the range element', (): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_AxisIndex_0_Range_0');
expect(svg.getAttribute('stroke-width')).toBe("0");
};
gauge.refresh();
});
it('checking the radial gradient properties of def element', (): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById("_container_svg_1_radialGradient");
expect(svg.getAttribute('cx')).toBe("50%");
expect(svg.getAttribute('cy')).toBe("50%");
expect(svg.getAttribute('fx')).toBe("50%");
expect(svg.getAttribute('fx')).toBe("50%");
expect(svg.getAttribute('r')).toBe("50%");
};
gauge.refresh();
});
it('checking the linear gradient properties of def element', (): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById("_container_svg_0_linearGradient");
expect(svg.getAttribute('x1')).toBe("0%");
expect(svg.getAttribute('y1')).toBe("0%");
expect(svg.getAttribute('x2')).toBe("100%");
expect(svg.getAttribute('y2')).toBe("0%");
};
gauge.refresh();
});
it('checking the stroke dasharray of the range element', (): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_AxisIndex_0_Range_0');
expect(svg.getAttribute('stroke-dasharray')).toBe("");
};
gauge.refresh();
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
});
}); | the_stack |
import { Component, ContentChild, Input, OnDestroy, OnInit, TemplateRef } from '@angular/core';
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { ProgrammingExercise } from 'app/entities/programming-exercise.model';
import { ProgrammingExerciseService } from './services/programming-exercise.service';
import { ActivatedRoute, Router } from '@angular/router';
import { ExerciseComponent } from 'app/exercises/shared/exercise/exercise.component';
import { TranslateService } from '@ngx-translate/core';
import { ActionType } from 'app/shared/delete-dialog/delete-dialog.model';
import { onError } from 'app/shared/util/global.utils';
import { AccountService } from 'app/core/auth/account.service';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ProgrammingExerciseImportComponent } from 'app/exercises/programming/manage/programming-exercise-import.component';
import { FeatureToggle } from 'app/shared/feature-toggle/feature-toggle.service';
import { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';
import { CourseManagementService } from 'app/course/manage/course-management.service';
import { ProgrammingExerciseSimulationUtils } from 'app/exercises/programming/shared/utils/programming-exercise-simulation.utils';
import { SortService } from 'app/shared/service/sort.service';
import { ProgrammingExerciseEditSelectedComponent } from 'app/exercises/programming/manage/programming-exercise-edit-selected.component';
import { ProgrammingAssessmentRepoExportDialogComponent } from 'app/exercises/programming/assess/repo-export/programming-assessment-repo-export-dialog.component';
import { ProgrammingExerciseParticipationType } from 'app/entities/programming-exercise-participation.model';
import { AlertService } from 'app/core/util/alert.service';
import { EventManager } from 'app/core/util/event-manager.service';
import { createBuildPlanUrl } from 'app/exercises/programming/shared/utils/programming-exercise.utils';
import { ProfileService } from 'app/shared/layouts/profiles/profile.service';
import { ConsistencyCheckComponent } from 'app/shared/consistency-check/consistency-check.component';
import { faBook, faCheckDouble, faDownload, faFileSignature, faListAlt, faPencilAlt, faPlus, faSort, faTable, faTimes, faUsers, faWrench } from '@fortawesome/free-solid-svg-icons';
import { CourseExerciseService } from 'app/exercises/shared/course-exercises/course-exercise.service';
@Component({
selector: 'jhi-programming-exercise',
templateUrl: './programming-exercise.component.html',
})
export class ProgrammingExerciseComponent extends ExerciseComponent implements OnInit, OnDestroy {
@Input() programmingExercises: ProgrammingExercise[];
filteredProgrammingExercises: ProgrammingExercise[];
selectedProgrammingExercises: ProgrammingExercise[];
readonly ActionType = ActionType;
FeatureToggle = FeatureToggle;
solutionParticipationType = ProgrammingExerciseParticipationType.SOLUTION;
templateParticipationType = ProgrammingExerciseParticipationType.TEMPLATE;
allChecked = false;
// extension points, see shared/extension-point
@ContentChild('overrideGenerateAndImportButton') overrideGenerateAndImportButton: TemplateRef<any>;
@ContentChild('overrideRepositoryAndBuildPlan') overrideRepositoryAndBuildPlan: TemplateRef<any>;
@ContentChild('overrideButtons') overrideButtons: TemplateRef<any>;
private buildPlanLinkTemplate: string;
// Icons
faSort = faSort;
faPlus = faPlus;
faDownload = faDownload;
faTimes = faTimes;
faBook = faBook;
faWrench = faWrench;
faCheckDouble = faCheckDouble;
faUsers = faUsers;
faTable = faTable;
faListAlt = faListAlt;
faPencilAlt = faPencilAlt;
faFileSignature = faFileSignature;
constructor(
private programmingExerciseService: ProgrammingExerciseService,
private courseExerciseService: CourseExerciseService,
public exerciseService: ExerciseService,
private accountService: AccountService,
private alertService: AlertService,
private modalService: NgbModal,
private router: Router,
private programmingExerciseSimulationUtils: ProgrammingExerciseSimulationUtils,
private sortService: SortService,
private profileService: ProfileService,
courseService: CourseManagementService,
translateService: TranslateService,
eventManager: EventManager,
route: ActivatedRoute,
) {
super(courseService, translateService, route, eventManager);
this.programmingExercises = [];
this.selectedProgrammingExercises = [];
}
ngOnInit(): void {
super.ngOnInit();
}
protected loadExercises(): void {
this.courseExerciseService.findAllProgrammingExercisesForCourse(this.courseId).subscribe({
next: (res: HttpResponse<ProgrammingExercise[]>) => {
this.programmingExercises = res.body!;
this.profileService.getProfileInfo().subscribe((profileInfo) => {
this.buildPlanLinkTemplate = profileInfo.buildPlanURLTemplate;
});
// reconnect exercise with course
this.programmingExercises.forEach((exercise) => {
exercise.course = this.course;
this.accountService.setAccessRightsForExercise(exercise);
if (exercise.projectKey) {
if (exercise.solutionParticipation!.buildPlanId) {
exercise.solutionParticipation!.buildPlanUrl = createBuildPlanUrl(
this.buildPlanLinkTemplate,
exercise.projectKey,
exercise.solutionParticipation!.buildPlanId,
);
}
if (exercise.templateParticipation!.buildPlanId) {
exercise.templateParticipation!.buildPlanUrl = createBuildPlanUrl(
this.buildPlanLinkTemplate,
exercise.projectKey,
exercise.templateParticipation!.buildPlanId,
);
}
}
this.selectedProgrammingExercises = [];
});
this.applyFilter();
this.emitExerciseCount(this.programmingExercises.length);
},
error: (res: HttpErrorResponse) => onError(this.alertService, res),
});
}
protected applyFilter(): void {
this.filteredProgrammingExercises = this.programmingExercises.filter((exercise) => this.filter.matchesExercise(exercise));
this.emitFilteredExerciseCount(this.filteredProgrammingExercises.length);
}
trackId(index: number, item: ProgrammingExercise) {
return item.id;
}
/**
* Deletes programming exercise
* @param programmingExerciseId the id of the programming exercise that we want to delete
* @param event contains additional checks for deleting exercise
*/
deleteProgrammingExercise(programmingExerciseId: number, event: { [key: string]: boolean }) {
return this.programmingExerciseService.delete(programmingExerciseId, event.deleteStudentReposBuildPlans, event.deleteBaseReposBuildPlans).subscribe({
next: () => {
this.eventManager.broadcast({
name: 'programmingExerciseListModification',
content: 'Deleted an programmingExercise',
});
this.dialogErrorSource.next('');
},
error: (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message),
});
}
/**
* Resets programming exercise
* @param programmingExerciseId the id of the programming exercise that we want to delete
*/
resetProgrammingExercise(programmingExerciseId: number) {
this.exerciseService.reset(programmingExerciseId).subscribe({
next: () => this.dialogErrorSource.next(''),
error: (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message),
});
}
protected getChangeEventName(): string {
return 'programmingExerciseListModification';
}
sortRows() {
this.sortService.sortByProperty(this.programmingExercises, this.predicate, this.reverse);
this.applyFilter();
}
openImportModal() {
const modalRef = this.modalService.open(ProgrammingExerciseImportComponent, { size: 'lg', backdrop: 'static' });
modalRef.result.then(
(result: ProgrammingExercise) => {
this.router.navigate(['course-management', this.courseId, 'programming-exercises', 'import', result.id]);
},
() => {},
);
}
toggleProgrammingExercise(programmingExercise: ProgrammingExercise) {
const programmingExerciseIndex = this.selectedProgrammingExercises.indexOf(programmingExercise);
if (programmingExerciseIndex !== -1) {
this.selectedProgrammingExercises.splice(programmingExerciseIndex, 1);
} else {
this.selectedProgrammingExercises.push(programmingExercise);
}
}
toggleAllProgrammingExercises() {
this.selectedProgrammingExercises = [];
if (!this.allChecked) {
this.selectedProgrammingExercises = this.selectedProgrammingExercises.concat(this.programmingExercises);
}
this.allChecked = !this.allChecked;
}
isExerciseSelected(programmingExercise: ProgrammingExercise) {
return this.selectedProgrammingExercises.includes(programmingExercise);
}
openEditSelectedModal() {
const modalRef = this.modalService.open(ProgrammingExerciseEditSelectedComponent, {
size: 'xl',
backdrop: 'static',
});
modalRef.componentInstance.selectedProgrammingExercises = this.selectedProgrammingExercises;
modalRef.closed.subscribe(() => {
location.reload();
});
}
openRepoExportModal() {
const modalRef = this.modalService.open(ProgrammingAssessmentRepoExportDialogComponent, {
size: 'lg',
backdrop: 'static',
});
modalRef.componentInstance.selectedProgrammingExercises = this.selectedProgrammingExercises;
}
/**
* Opens modal and executes a consistency check for the selected exercises
*/
checkConsistencies() {
const modalRef = this.modalService.open(ConsistencyCheckComponent, { keyboard: true, size: 'lg' });
modalRef.componentInstance.exercisesToCheck = this.selectedProgrammingExercises;
}
// ################## ONLY FOR LOCAL TESTING PURPOSE -- START ##################
/**
* Checks if the url includes the string "nolocalsetup', which is an indication
* that the particular programming exercise has no local setup
* This functionality is only for testing purposes (noVersionControlAndContinuousIntegrationAvailable)
* @param urlToCheck the url which will be checked if it contains the substring
*/
noVersionControlAndContinuousIntegrationAvailableCheck(urlToCheck: string): boolean {
return this.programmingExerciseSimulationUtils.noVersionControlAndContinuousIntegrationAvailableCheck(urlToCheck);
}
// ################## ONLY FOR LOCAL TESTING PURPOSE -- END ##################
} | the_stack |
import {assert} from 'chrome://resources/js/assert.m.js';
import {Action} from 'chrome://resources/js/cr/ui/store.js';
import {ChangeFolderOpenAction, CreateBookmarkAction, EditBookmarkAction, FinishSearchAction, MoveBookmarkAction, RefreshNodesAction, RemoveBookmarkAction, ReorderChildrenAction, SelectFolderAction, SelectItemsAction, SetPrefAction, StartSearchAction, UpdateAnchorAction} from './actions.js';
import {BookmarkNode, BookmarksPageState, FolderOpenState, NodeMap, PreferencesState, SearchState, SelectionState} from './types.js';
import {removeIdsFromMap, removeIdsFromObject, removeIdsFromSet} from './util.js';
function selectItems(
selectionState: SelectionState, action: SelectItemsAction): SelectionState {
let newItems = new Set();
if (!action.clear) {
newItems = new Set(selectionState.items);
}
action.items.forEach(function(id) {
let add = true;
if (action.toggle) {
add = !newItems.has(id);
}
if (add) {
newItems.add(id);
} else {
newItems.delete(id);
}
});
return (Object.assign({}, selectionState, {
items: newItems,
anchor: action.anchor,
}) as SelectionState);
}
function deselectAll(selectionState: SelectionState): SelectionState {
return {
items: new Set(),
anchor: null,
};
}
function deselectItems(
selectionState: SelectionState, deleted: Set<string>): SelectionState {
return /** @type {SelectionState} */ (Object.assign({}, selectionState, {
items: removeIdsFromSet(selectionState.items, deleted),
anchor: !selectionState.anchor || deleted.has(selectionState.anchor) ?
null :
selectionState.anchor,
}));
}
function updateAnchor(
selectionState: SelectionState,
action: UpdateAnchorAction): SelectionState {
return (Object.assign({}, selectionState, {
anchor: action.anchor,
}) as SelectionState);
}
// Exported for tests.
export function updateSelection(
selection: SelectionState, action: Action): SelectionState {
switch (action.name) {
case 'clear-search':
case 'finish-search':
case 'select-folder':
case 'deselect-items':
return deselectAll(selection);
case 'select-items':
return selectItems(selection, action as SelectItemsAction);
case 'remove-bookmark':
return deselectItems(
selection, (action as RemoveBookmarkAction).descendants);
case 'move-bookmark':
// Deselect items when they are moved to another folder, since they will
// no longer be visible on screen (for simplicity, ignores items visible
// in search results).
const moveAction = action as MoveBookmarkAction;
if (moveAction.parentId !== moveAction.oldParentId &&
selection.items.has(moveAction.id)) {
return deselectItems(selection, new Set([moveAction.id]));
}
return selection;
case 'update-anchor':
return updateAnchor(selection, action as UpdateAnchorAction);
default:
return selection;
}
}
function startSearch(
search: SearchState, action: StartSearchAction): SearchState {
return {
term: action.term,
inProgress: true,
results: search.results,
};
}
function finishSearch(
search: SearchState, action: FinishSearchAction): SearchState {
return /** @type {SearchState} */ (Object.assign({}, search, {
inProgress: false,
results: action.results,
}));
}
function clearSearch(): SearchState {
return {
term: '',
inProgress: false,
results: null,
};
}
function removeDeletedResults(
search: SearchState, deletedIds: Set<string>): SearchState {
if (!search.results) {
return search;
}
const newResults: string[] = [];
search.results.forEach(function(id) {
if (!deletedIds.has(id)) {
newResults.push(id);
}
});
return (Object.assign({}, search, {
results: newResults,
}) as SearchState);
}
function updateSearch(search: SearchState, action: Action): SearchState {
switch (action.name) {
case 'start-search':
return startSearch(search, action as StartSearchAction);
case 'select-folder':
case 'clear-search':
return clearSearch();
case 'finish-search':
return finishSearch(search, action as FinishSearchAction);
case 'remove-bookmark':
return removeDeletedResults(
search, (action as RemoveBookmarkAction).descendants);
default:
return search;
}
}
function modifyNode(
nodes: NodeMap, id: string,
callback: (p1: BookmarkNode) => BookmarkNode): NodeMap {
const nodeModification: NodeMap = {};
nodeModification[id] = callback(nodes[id]!);
return Object.assign({}, nodes, nodeModification);
}
function createBookmark(nodes: NodeMap, action: CreateBookmarkAction): NodeMap {
const nodeModifications: NodeMap = {};
nodeModifications[action.id] = action.node;
const parentNode = nodes[action.parentId]!;
const newChildren = parentNode.children!.slice();
newChildren.splice(action.parentIndex, 0, action.id);
nodeModifications[action.parentId] = Object.assign({}, parentNode, {
children: newChildren,
});
return Object.assign({}, nodes, nodeModifications);
}
function editBookmark(nodes: NodeMap, action: EditBookmarkAction): NodeMap {
// Do not allow folders to change URL (making them no longer folders).
if (!nodes[action.id]!.url && action.changeInfo.url) {
delete action.changeInfo.url;
}
return modifyNode(nodes, action.id, function(node) {
return Object.assign({}, node, action.changeInfo);
});
}
function moveBookmark(nodes: NodeMap, action: MoveBookmarkAction): NodeMap {
const nodeModifications: NodeMap = {};
const id = action.id;
// Change node's parent.
nodeModifications[id] =
Object.assign({}, nodes[id], {parentId: action.parentId});
// Remove from old parent.
const oldParentId = action.oldParentId;
const oldParentChildren = nodes[oldParentId]!.children!.slice();
oldParentChildren.splice(action.oldIndex, 1);
nodeModifications[oldParentId] =
Object.assign({}, nodes[oldParentId], {children: oldParentChildren});
// Add to new parent.
const parentId = action.parentId;
const parentChildren = oldParentId === parentId ?
oldParentChildren :
nodes[parentId]!.children!.slice();
parentChildren.splice(action.index, 0, action.id);
nodeModifications[parentId] =
Object.assign({}, nodes[parentId], {children: parentChildren});
return Object.assign({}, nodes, nodeModifications);
}
function removeBookmark(nodes: NodeMap, action: RemoveBookmarkAction): NodeMap {
const newState = modifyNode(nodes, action.parentId, function(node) {
const newChildren = node.children!.slice();
newChildren.splice(action.index, 1);
return /** @type {BookmarkNode} */ (
Object.assign({}, node, {children: newChildren}));
});
return removeIdsFromObject(newState, action.descendants);
}
function reorderChildren(
nodes: NodeMap, action: ReorderChildrenAction): NodeMap {
return modifyNode(nodes, action.id, function(node) {
return /** @type {BookmarkNode} */ (
Object.assign({}, node, {children: action.children}));
});
}
export function updateNodes(nodes: NodeMap, action: Action): NodeMap {
switch (action.name) {
case 'create-bookmark':
return createBookmark(nodes, action as CreateBookmarkAction);
case 'edit-bookmark':
return editBookmark(nodes, action as EditBookmarkAction);
case 'move-bookmark':
return moveBookmark(nodes, action as MoveBookmarkAction);
case 'remove-bookmark':
return removeBookmark(nodes, action as RemoveBookmarkAction);
case 'reorder-children':
return reorderChildren(nodes, action as ReorderChildrenAction);
case 'refresh-nodes':
return (action as RefreshNodesAction).nodes;
default:
return nodes;
}
}
function isAncestorOf(
nodes: NodeMap, ancestorId: string, childId: string): boolean {
let currentId: string|undefined = childId;
// Work upwards through the tree from child.
while (currentId) {
if (currentId === ancestorId) {
return true;
}
currentId = nodes[currentId!]!.parentId;
}
return false;
}
// Exported for tests.
export function updateSelectedFolder(
selectedFolder: string, action: Action, nodes: NodeMap): string {
switch (action.name) {
case 'select-folder':
return (action as SelectFolderAction).id;
case 'change-folder-open':
// When hiding the selected folder by closing its ancestor, select
// that ancestor instead.
const changeFolderAction = action as ChangeFolderOpenAction;
if (!changeFolderAction.open && selectedFolder &&
isAncestorOf(nodes, changeFolderAction.id, selectedFolder)) {
return changeFolderAction.id;
}
return selectedFolder;
case 'remove-bookmark':
// When deleting the selected folder (or its ancestor), select the
// parent of the deleted node.
const id = (action as RemoveBookmarkAction).id;
if (selectedFolder && isAncestorOf(nodes, id, selectedFolder)) {
return assert(nodes[id]!.parentId!);
}
return selectedFolder;
default:
return selectedFolder;
}
}
function openFolderAndAncestors(
folderOpenState: FolderOpenState, id: string, nodes: NodeMap):
FolderOpenState {
const newFolderOpenState = (new Map(folderOpenState) as FolderOpenState);
for (let currentId = id; currentId; currentId = nodes[currentId]!.parentId!) {
newFolderOpenState.set(currentId, true);
}
return newFolderOpenState;
}
function changeFolderOpen(
folderOpenState: FolderOpenState,
action: ChangeFolderOpenAction): FolderOpenState {
const newFolderOpenState = new Map(folderOpenState) as FolderOpenState;
newFolderOpenState.set(action.id, action.open);
return newFolderOpenState;
}
export function updateFolderOpenState(
folderOpenState: FolderOpenState, action: Action,
nodes: NodeMap): FolderOpenState {
switch (action.name) {
case 'change-folder-open':
return changeFolderOpen(
folderOpenState, action as ChangeFolderOpenAction);
case 'select-folder':
return openFolderAndAncestors(
folderOpenState, nodes[(action as SelectFolderAction).id]!.parentId!,
nodes);
case 'move-bookmark':
if (!nodes[(action as MoveBookmarkAction).id]!.children) {
return folderOpenState;
}
return openFolderAndAncestors(
folderOpenState, (action as MoveBookmarkAction).parentId, nodes);
case 'remove-bookmark':
return removeIdsFromMap(
folderOpenState, (action as RemoveBookmarkAction).descendants);
default:
return folderOpenState;
}
}
function updatePrefs(
prefs: PreferencesState, action: Action): PreferencesState {
const prefAction = action as SetPrefAction;
switch (prefAction.name) {
case 'set-incognito-availability':
return /** @type {PreferencesState} */ (Object.assign({}, prefs, {
incognitoAvailability: prefAction.value,
}));
case 'set-can-edit':
return /** @type {PreferencesState} */ (Object.assign({}, prefs, {
canEdit: prefAction.value,
}));
default:
return prefs;
}
}
export function reduceAction(
state: BookmarksPageState, action: Action): BookmarksPageState {
return {
nodes: updateNodes(state.nodes, action),
selectedFolder:
updateSelectedFolder(state.selectedFolder, action, state.nodes),
folderOpenState:
updateFolderOpenState(state.folderOpenState, action, state.nodes),
prefs: updatePrefs(state.prefs, action),
search: updateSearch(state.search, action),
selection: updateSelection(state.selection, action),
};
} | the_stack |
import React, {
useState,
useEffect,
useContext,
createContext,
ReactNode,
Component,
ComponentType,
memo,
forwardRef,
PureComponent,
Ref,
} from 'react';
import {createPortal} from 'react-dom';
import {mount, createMount} from '../mount';
describe('@shopify/react-testing', () => {
it('does not time out with large trees', () => {
function RecurseMyself({times}: {times: number}) {
if (times <= 0) {
return <div>finished</div>;
}
return <RecurseMyself times={times - 1} />;
}
expect(() => {
mount(<RecurseMyself times={900} />);
}).not.toThrow();
});
it('can output structured debug strings', () => {
const wrapper = mount(
// eslint-disable-next-line @shopify/jsx-prefer-fragment-wrappers
<div>
<span>hi</span>
</div>,
);
expect(wrapper.debug()).toBe(
`<div>
<span />
</div>`,
);
});
it('can find dom components', () => {
const wrapper = mount(
// eslint-disable-next-line @shopify/jsx-prefer-fragment-wrappers
<div>
<span>hi</span>
</div>,
);
expect(wrapper.find('span')!.text()).toBe('hi');
});
it('can compare text when there are nulls in the vdom', () => {
const wrapper = mount(
// eslint-disable-next-line @shopify/jsx-prefer-fragment-wrappers
<div>
{null}
{/* eslint-disable-next-line @shopify/jsx-prefer-fragment-wrappers */}
<span>{null}hi</span>
</div>,
);
expect(wrapper.find('span')!.text()).toBe('hi');
});
it('can findAll dom components', () => {
const wrapper = mount(
// eslint-disable-next-line @shopify/jsx-prefer-fragment-wrappers
<div>
<span>hi</span>
<span>howdy</span>
</div>,
);
expect(
wrapper.findAll('span').map((component) => component.text()),
).toStrictEqual(['hi', 'howdy']);
});
it('can find functional components', () => {
function Message({children}: {children?: ReactNode}) {
return <span>{children}</span>;
}
const wrapper = mount(
// eslint-disable-next-line @shopify/jsx-prefer-fragment-wrappers
<div>
<Message>hi</Message>
</div>,
);
expect(wrapper.find(Message)!.text()).toBe('hi');
});
it('can findAll functional components', () => {
function Message({children}: {children?: ReactNode}) {
return <span>{children}</span>;
}
const wrapper = mount(
// eslint-disable-next-line @shopify/jsx-prefer-fragment-wrappers
<div>
<Message>hi</Message>
<Message>howdy</Message>
</div>,
);
expect(
wrapper.findAll(Message).map((component) => component.text()),
).toStrictEqual(['hi', 'howdy']);
});
it('can find class components', () => {
// eslint-disable-next-line react/prefer-stateless-function
class Message extends Component<{children?: ReactNode}> {
render() {
return <span>{this.props.children}</span>;
}
}
const wrapper = mount(
// eslint-disable-next-line @shopify/jsx-prefer-fragment-wrappers
<div>
<Message>hi</Message>
</div>,
);
expect(wrapper.find(Message)!.text()).toBe('hi');
});
it('can find context providers', () => {
const Context = createContext({hello: 'world'});
const value = {hello: 'goodbye'};
function MyComponent() {
return (
<Context.Provider value={value}>
<div />
</Context.Provider>
);
}
const myComponent = mount(<MyComponent />);
expect(myComponent.find(Context.Provider)).not.toBeNull();
});
it('throws an error when the component is already mounted', () => {
const wrapper = mount(<div>Hello world</div>);
expect(() => wrapper.mount()).toThrow(
/Attempted to mount a node that was already mounted/,
);
});
describe('rerendering', () => {
function Message({children}: {children?: ReactNode}) {
return <span>{children}</span>;
}
function Counter({children}: {children?: ReactNode}) {
const [counter, setCounter] = useState(0);
return (
// eslint-disable-next-line @shopify/jsx-prefer-fragment-wrappers
<div>
<Message>{counter}</Message>
<button
type="button"
onClick={() => setCounter((count) => count + 1)}
>
increase
</button>
{children}
</div>
);
}
it('updates element tree when state is changed', () => {
const wrapper = mount(<Counter />);
wrapper.find('button')!.trigger('onClick');
expect(wrapper.find(Message)!.html()).toBe('<span>1</span>');
});
it('updates element tree when state is changed by an effect', () => {
function EffectChangeComponent({children}: {children?: ReactNode}) {
const [counter, setCounter] = useState(0);
useEffect(() => setCounter(100), []);
return (
// eslint-disable-next-line @shopify/jsx-prefer-fragment-wrappers
<div>
<Message>{counter}</Message>
{children}
</div>
);
}
const wrapper = mount(<EffectChangeComponent />);
expect(wrapper.find(Message)!.html()).toBe('<span>100</span>');
});
it('updates element tree when state is changed by an effect after changing props', () => {
function PropBasedEffectChangeComponent({
value,
children,
}: {
children?: ReactNode;
value: number;
}) {
const [counter, setCounter] = useState(value);
useEffect(() => setCounter(value), [value]);
return (
// eslint-disable-next-line @shopify/jsx-prefer-fragment-wrappers
<div>
<Message>{counter}</Message>
{children}
</div>
);
}
const wrapper = mount(<PropBasedEffectChangeComponent value={0} />);
expect(wrapper.find(Message)!.html()).toBe('<span>0</span>');
wrapper.setProps({value: 100});
expect(wrapper.find(Message)!.html()).toBe('<span>100</span>');
});
it('updates element tree when props are changed', () => {
const wrapper = mount(<Counter />);
expect(wrapper.find('div')!.html()).not.toMatch('hi hello');
wrapper.setProps({children: <div>hi hello</div>});
expect(wrapper.find('div')!.html()).toMatch('hi hello');
});
it('can test the result of triggering props', () => {
function Clickable({onClick}: {onClick(): void}) {
return (
<button type="button" onClick={onClick}>
Click me
</button>
);
}
function MyComponent() {
const [clicked, setClicked] = useState(false);
/* eslint-disable jest/no-if */
return clicked ? (
<div>Clicked!</div>
) : (
<Clickable onClick={setClicked.bind(null, true)} />
);
/* eslint-enable jest/no-if */
}
const myComponent = mount(<MyComponent />);
(myComponent.find(Clickable as ComponentType<any>) as any)!.trigger(
'onClick',
);
expect(myComponent.text()).toContain('Clicked!');
});
});
describe('traversal', () => {
it('can traverse through portals', () => {
function MyComponent() {
return <div>Hello world!</div>;
}
const portal = document.createElement('div');
const vdom = createPortal(<MyComponent />, portal);
const wrapper = mount(vdom);
expect(wrapper.find(MyComponent)).not.toBeNull();
});
it('can traverse through context providers and consumers', () => {
const MessageContext = createContext<string>('');
function Message({children}: {children?: ReactNode}) {
return <div>{children}</div>;
}
function MyComponent() {
return (
<MessageContext.Consumer>
{(message) => <Message>{message}</Message>}
</MessageContext.Consumer>
);
}
const message = 'Hello world';
const myComponent = mount(
<MessageContext.Provider value={message}>
<MyComponent />
</MessageContext.Provider>,
);
expect(myComponent.find(Message)!.text()).toBe(message);
});
it('can traverse through function memo components', () => {
function Message({children}: {children?: ReactNode}) {
return <div>{children}</div>;
}
const vdom = <Message>Hello world</Message>;
const MyComponent = memo(() => vdom);
const wrapper = mount(<MyComponent />);
expect(wrapper.text()).toBe('Hello world');
expect(wrapper.text()).toBe(wrapper.find(Message)!.text());
});
it('can traverse through class memo components', () => {
function Message({children}: {children?: ReactNode}) {
return <div>{children}</div>;
}
const MyComponent = memo(
// eslint-disable-next-line react/prefer-stateless-function
class MyComponent extends Component {
render() {
return <Message>Hello world</Message>;
}
} as any,
);
const myComponent = mount(<MyComponent />);
expect(myComponent.find(Message)!.text()).toBe('Hello world');
expect(myComponent.text()).toBe(myComponent.find(Message)!.text());
});
it('can traverse through pure components', () => {
function Message({children}: {children?: ReactNode}) {
return <div>{children}</div>;
}
class MyComponent extends PureComponent {
render() {
return <Message>Hello world</Message>;
}
}
const myComponent = mount(<MyComponent />);
expect(myComponent.find(Message)!.text()).toBe('Hello world');
expect(myComponent.text()).toBe(myComponent.find(Message)!.text());
});
it('can find text directly inside a Fragment', () => {
function FragMessage({children}: {children?: ReactNode}) {
return <>{children}</>;
}
const vdom = <FragMessage>oh hi</FragMessage>;
const myComponent = mount(vdom);
expect(myComponent.text()).toBe('oh hi');
});
it('can traverse through s', () => {
function Message({children}: {children?: ReactNode}) {
return <div>{children}</div>;
}
function MyComponent() {
return (
<>
<div>Message is:</div>
<Message>Hello world</Message>
</>
);
}
const myComponent = mount(<MyComponent />);
expect(myComponent.find(Message)!.text()).toBe('Hello world');
expect(myComponent.text()).toContain(myComponent.find(Message)!.text());
});
it('can traverse through forwardRefs', () => {
function Message({children}: {children?: ReactNode}) {
return <div>{children}</div>;
}
const MyComponent = forwardRef<HTMLDivElement, {}>(function MyComponent(
_props: {},
ref: Ref<HTMLDivElement>,
) {
return (
<>
<div ref={ref}>Message is:</div>
<Message>Hello world</Message>
</>
);
});
const myComponent = mount(<MyComponent />);
expect(myComponent.find(Message)!.text()).toBe('Hello world');
expect(myComponent.text()).toContain(myComponent.find(Message)!.text());
});
});
describe('customized mount', () => {
it('treats the rendered component as the root despite any rendered wrapper', () => {
const customMount = createMount({
render: (vdom) => <div>{vdom}</div>,
});
function Message({children}: {children?: ReactNode}) {
return <div>{children}</div>;
}
expect(customMount(<Message>hi</Message>).html()).toBe('<div>hi</div>');
});
it('provides context as a property on the root wrapper', () => {
const AppContext = createContext('not the right message');
const mountWithContext = createMount<
{message: string},
{message: string}
>({
context: ({message}) => ({message}),
render: (vdom, context) => {
return (
<AppContext.Provider value={context.message}>
{vdom}
</AppContext.Provider>
);
},
});
function ContextMessage() {
const message = useContext(AppContext);
return <div>{message}</div>;
}
const wrapper = mountWithContext(<ContextMessage />, {
message: 'the right message',
});
expect(wrapper.context.message).toBe('the right message');
expect(wrapper.html()).toBe(`<div>${wrapper.context.message}</div>`);
});
it('waits on an async afterMount', async () => {
const AppContext = createContext('not the right message');
const mountWithContext = createMount<
{message: string},
{message: string}
>({
context: ({message}) => ({message}),
render: (vdom, context) => {
return (
<AppContext.Provider value={context.message}>
{vdom}
</AppContext.Provider>
);
},
afterMount: async (root) => {
return new Promise((resolve) => {
setTimeout(() => {
root.context.message = 'a different message';
root.forceUpdate();
resolve();
}, 10);
});
},
});
function ContextMessage() {
const message = useContext(AppContext);
return <div>{message}</div>;
}
const wrapperPromise = mountWithContext(<ContextMessage />, {
message: 'an unused message',
});
const wrapper = await wrapperPromise;
expect(wrapper.context.message).toBe('a different message');
expect(wrapper.html()).toBe(`<div>${wrapper.context.message}</div>`);
});
});
}); | the_stack |
import PlayerComponent from '../interfaces/component';
import EventsList from '../interfaces/events-list';
import Player from '../player';
import { EVENT_OPTIONS, IS_ANDROID, IS_IOS } from '../utils/constants';
import { addEvent } from '../utils/events';
import { isAudio, removeElement } from '../utils/general';
/**
* Volume controller element.
*
* @description This class controls the media's volume level using `semantic markup`,
* such as input range and progress elements.
* @see https://codepen.io/mi-lee/post/an-overview-of-html5-semantics
* @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/volume
* @see https://developer.mozilla.org/en-US/Apps/Fundamentals/Audio_and_video_delivery/cross_browser_video_player#Volume
* @class Volume
* @implements PlayerComponent
*/
class Volume implements PlayerComponent {
/**
* Instance of OpenPlayer.
*
* @private
* @type Player
* @memberof Settings
*/
#player: Player;
/**
* Mute button.
*
* @private
* @type HTMLButtonElement
* @memberof Volume
*/
#button: HTMLButtonElement;
/**
* Container for volume elements (display and slider input).
*
* @private
* @type HTMLDivElement
* @memberof Volume
*/
#container: HTMLDivElement;
/**
* Element that displays the media's current volume level.
*
* @private
* @type HTMLProgressElement
* @memberof Volume
*/
#display: HTMLProgressElement;
/**
* Element that allows changing media's current volume.
*
* @private
* @type HTMLInputElement
* @memberof Volume
*/
#slider: HTMLInputElement;
/**
* Events that will be triggered in Volume element:
* - button (to toggle mute in media).
* - media (to alter volume level and modify mute's icon depending of the volume level).
* - slider (events to be triggered when clicking or sliding volume rail to modify volume level).
*
* @private
* @type EventsList
* @memberof Volume
*/
#events: EventsList = {
button: {},
media: {},
slider: {},
};
/**
* Storage of volume value to restore it when toggling mute.
*
* @private
* @type number
* @memberof Volume
*/
#volume: number;
/**
* Default labels from player's config
*
* @private
* @type object
* @memberof Volume
*/
#labels: any;
/**
* Position of the button to be indicated as part of its class name
*
* @private
* @type {string}
* @memberof Volume
*/
#position: string;
/**
* Layer where the control item will be placed
*
* @private
* @type {string}
* @memberof Captions
*/
#layer: string;
/**
* Create an instance of Volume.
*
* @param {Player} player
* @returns {Volume}
*/
constructor(player: Player, position: string, layer: string) {
this.#player = player;
this.#labels = player.getOptions().labels;
this.#volume = this.#player.getMedia().volume;
this.#position = position;
this.#layer = layer;
this._keydownEvent = this._keydownEvent.bind(this);
return this;
}
/**
*
* @inheritDoc
* @memberof Volume
*/
public create(): void {
this.#container = document.createElement('div');
this.#container.className = `op-controls__volume op-control__${this.#position}`;
this.#container.tabIndex = 0;
this.#container.setAttribute('aria-valuemin', '0');
this.#container.setAttribute('aria-valuemax', '100');
this.#container.setAttribute('aria-valuenow', `${this.#volume}`);
this.#container.setAttribute('aria-valuetext', `${this.#labels.volume}: ${this.#volume}`);
this.#container.setAttribute('aria-orientation', 'vertical');
this.#container.setAttribute('aria-label', this.#labels.volumeSlider);
this.#slider = document.createElement('input');
this.#slider.type = 'range';
this.#slider.className = 'op-controls__volume--input';
this.#slider.tabIndex = -1;
this.#slider.value = this.#player.getMedia().volume.toString();
this.#slider.setAttribute('min', '0');
this.#slider.setAttribute('max', '1');
this.#slider.setAttribute('step', '0.1');
this.#slider.setAttribute('aria-label', this.#labels.volumeControl);
this.#display = document.createElement('progress');
this.#display.className = 'op-controls__volume--display';
this.#display.setAttribute('max', '10');
this.#display.setAttribute('role', 'presentation');
this.#display.value = this.#player.getMedia().volume * 10;
this.#container.appendChild(this.#slider);
this.#container.appendChild(this.#display);
// Use as backup when mute is clicked
this.#button = document.createElement('button');
this.#button.type = 'button';
this.#button.className = `op-controls__mute op-control__${this.#position}`;
this.#button.tabIndex = 0;
this.#button.title = this.#labels.mute;
this.#button.setAttribute('aria-controls', this.#player.id);
this.#button.setAttribute('aria-pressed', 'false');
this.#button.setAttribute('aria-label', this.#labels.mute);
this.#button.innerHTML = `<span class="op-sr">${this.#labels.mute}</span>`;
/**
* @private
* @param {*} element
*/
const updateSlider = (element: any) => {
const mediaVolume = element.volume * 1;
const vol = Math.floor(mediaVolume * 100);
this.#slider.value = `${element.volume}`;
this.#display.value = (mediaVolume * 10);
this.#container.setAttribute('aria-valuenow', `${vol}`);
this.#container.setAttribute('aria-valuetext', `${this.#labels.volume}: ${vol}`);
};
/**
* @private
* @param {*} element
*/
const updateButton = (element: any) => {
const vol = element.volume;
if (vol <= 0.5 && vol > 0) {
this.#button.classList.remove('op-controls__mute--muted');
this.#button.classList.add('op-controls__mute--half');
} else if (vol === 0) {
this.#button.classList.add('op-controls__mute--muted');
this.#button.classList.remove('op-controls__mute--half');
} else {
this.#button.classList.remove('op-controls__mute--muted');
this.#button.classList.remove('op-controls__mute--half');
}
};
/**
* @private
* @param {Event} event
*/
const updateVolume = (event: Event) => {
const el = this.#player.activeElement();
const value = parseFloat((event.target as HTMLInputElement).value);
el.volume = value;
el.muted = (el.volume === 0);
this.#volume = value;
const unmuteEl = this.#player.getContainer().querySelector('.op-player__unmute');
if (!el.muted && unmuteEl) {
removeElement(unmuteEl);
}
const e = addEvent('volumechange');
this.#player.getElement().dispatchEvent(e);
};
this.#events.media.volumechange = () => {
const el = this.#player.activeElement();
updateSlider(el);
updateButton(el);
};
this.#events.media.timeupdate = () => {
if (isAudio(this.#player.getElement()) && (this.#player.activeElement().duration === Infinity
|| this.#player.getElement().getAttribute('op-live__enabled'))) {
}
};
this.#events.media.loadedmetadata = () => {
const el = this.#player.activeElement();
if (el.muted) {
el.volume = 0;
}
const e = addEvent('volumechange');
this.#player.getElement().dispatchEvent(e);
};
this.#events.slider.input = updateVolume.bind(this);
this.#events.slider.change = updateVolume.bind(this);
this.#events.button.click = () => {
this.#button.setAttribute('aria-pressed', 'true');
const el = this.#player.activeElement();
el.muted = !el.muted;
if (el.muted) {
el.volume = 0;
this.#button.title = this.#labels.unmute;
this.#button.setAttribute('aria-label', this.#labels.unmute);
} else {
el.volume = this.#volume;
this.#button.title = this.#labels.mute;
this.#button.setAttribute('aria-label', this.#labels.mute);
}
const event = addEvent('volumechange');
this.#player.getElement().dispatchEvent(event);
};
this.#button.addEventListener('click', this.#events.button.click, EVENT_OPTIONS);
Object.keys(this.#events.media).forEach(event => {
this.#player.getElement().addEventListener(event, this.#events.media[event], EVENT_OPTIONS);
});
Object.keys(this.#events.slider).forEach(event => {
this.#slider.addEventListener(event, this.#events.slider[event], EVENT_OPTIONS);
});
this.#player.getContainer().addEventListener('keydown', this._keydownEvent, EVENT_OPTIONS);
if (!IS_ANDROID && !IS_IOS) {
const controls = this.#player.getControls().getLayer(this.#layer);
controls.appendChild(this.#button);
controls.appendChild(this.#container);
}
}
/**
*
* @inheritDoc
* @memberof Volume
*/
public destroy(): void {
this.#button.removeEventListener('click', this.#events.button.click);
Object.keys(this.#events.media).forEach(event => {
this.#player.getElement().removeEventListener(event, this.#events.media[event]);
});
Object.keys(this.#events.slider).forEach(event => {
this.#slider.removeEventListener(event, this.#events.slider[event]);
});
this.#player.getContainer().removeEventListener('keydown', this._keydownEvent);
removeElement(this.#slider);
removeElement(this.#display);
removeElement(this.#container);
}
/**
* Use the `Enter` and space bar keys to manipulate volume.
*
* @private
* @param {KeyboardEvent} e
* @memberof Volume
*/
private _keydownEvent(e: KeyboardEvent) {
const key = e.which || e.keyCode || 0;
const el = this.#player.activeElement();
const playBtnFocused = document?.activeElement?.classList.contains('op-controls__mute');
if (playBtnFocused && (key === 13 || key === 32)) {
el.muted = !el.muted;
el.volume = el.muted ? 0 : this.#volume;
this.#events.button.click();
e.preventDefault();
e.stopPropagation();
}
}
}
export default Volume; | the_stack |
import {
defer,
mapTo,
merge,
NEVER,
of,
startWith,
timer,
} from "rxjs";
import Prioritizer, {
ITaskEvent,
} from "../prioritizer";
/* eslint-disable @typescript-eslint/no-floating-promises */
/* eslint-disable @typescript-eslint/strict-boolean-expressions */
/* eslint-disable no-restricted-properties */
function assert(condition: boolean, msg?: string): asserts condition {
if (!condition) {
throw new Error(msg ?? "The asserted condition turned out to be false.");
}
}
describe("SegmentFetchers Prioritizer", () => {
// beforeEach(() => {
// jest.resetModules();
// });
it("should not throw if updating the priority of a non-existent observable", () => {
const never$ = NEVER;
const prioritizer = new Prioritizer({ prioritySteps: { high: 5, low: 20 } });
expect(() => { prioritizer.updatePriority(never$, 1); }).not.toThrow();
});
it("should run Observable right away", () => {
const a1$ = of(1);
const prioritizer = new Prioritizer({ prioritySteps: { high: 5, low: 20 } });
let emitted = 0;
let completed = 0;
prioritizer.create(a1$, 99).subscribe({
next: (evt) => {
if (emitted === 0) {
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(1);
} else if (emitted === 1) {
expect(evt.type).toEqual("ended");
} else {
throw new Error("Should not have emitted an other event");
}
emitted++;
},
error: () => { throw new Error("Should not have thrown"); },
complete: () => { completed++; },
});
expect(emitted).toEqual(2);
expect(completed).toEqual(1);
});
/* eslint-disable max-len */
it("should throw if the given high priority is a higher (or equal) number than the given low priority", () => {
expect(() => new Prioritizer({ prioritySteps: { high: 7, low: 6 } })).toThrow();
expect(() => new Prioritizer({ prioritySteps: { high: 7, low: 7 } })).toThrow();
expect(() => new Prioritizer({ prioritySteps: { high: 7, low: 8 } })).not.toThrow();
});
it("should run multiple synchronous Observables right away", () => {
const a1$ = of(1);
const a2$ = of(2);
const a3$ = of(3);
const prioritizer = new Prioritizer({ prioritySteps: { high: 5, low: 20 } });
let emitted = 0;
let completed = 0;
function onNext(expectedData : number) {
let item = 0;
return (evt : ITaskEvent<unknown>) => {
if (item === 0) {
expect(evt.type).toEqual("data");
assert(evt.type === "data"); // for TypeScript
expect(evt.value).toEqual(expectedData);
} else if (item === 1) {
expect(evt.type).toEqual("ended");
} else {
throw new Error("Should not have emitted an other event: " + evt.type);
}
item++;
emitted++;
};
}
prioritizer.create(a1$, 99).subscribe({
next: onNext(1),
error: () => { throw new Error("Should not have thrown"); },
complete: () => { completed++; },
});
expect(emitted).toEqual(2);
expect(completed).toEqual(1);
prioritizer.create(a2$, 0).subscribe({
next: onNext(2),
error: () => { throw new Error("Should not have thrown"); },
complete: () => { completed++; },
});
expect(emitted).toEqual(4);
expect(completed).toEqual(2);
prioritizer.create(a3$, 3).subscribe({
next: onNext(3),
error: () => { throw new Error("Should not have thrown"); },
complete: () => { completed++; },
});
expect(emitted).toEqual(6);
expect(completed).toEqual(3);
});
it("should not wait when all Observables have the same priority", (done) => {
let obs1Started = false;
let obs2Started = false;
let obs3Started = false;
let obs4Started = false;
const obs1$ = defer(() => { obs1Started = true; return timer(1).pipe(mapTo(1)); });
const obs2$ = defer(() => { obs2Started = true; return timer(1).pipe(mapTo(2)); });
const obs3$ = defer(() => { obs3Started = true; return timer(1).pipe(mapTo(3)); });
const obs4$ = defer(() => { obs4Started = true; return timer(1).pipe(mapTo(4)); });
const prioritizer = new Prioritizer({ prioritySteps: { high: 5, low: 20 } });
let emitted = 0;
const pObs1 = prioritizer.create(obs1$, 1);
const pObs2 = prioritizer.create(obs2$, 1);
const pObs3 = prioritizer.create(obs3$, 1);
const pObs4 = prioritizer.create(obs4$, 1);
function expectData(
evt : ITaskEvent<unknown>,
expectedData : number,
shouldHaveStartedObs : boolean
) : void {
expect(obs1Started).toEqual(shouldHaveStartedObs);
expect(obs2Started).toEqual(shouldHaveStartedObs);
expect(obs3Started).toEqual(shouldHaveStartedObs);
expect(obs4Started).toEqual(shouldHaveStartedObs);
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(expectedData);
}
const checkEvents = [ (e : ITaskEvent<unknown>) => expectData(e, 0, false),
(e : ITaskEvent<unknown>) => expectData(e, 1, true),
(e : ITaskEvent<unknown>) => expect(e.type).toEqual("ended"),
(e : ITaskEvent<unknown>) => expectData(e, 2, true),
(e : ITaskEvent<unknown>) => expect(e.type).toEqual("ended"),
(e : ITaskEvent<unknown>) => expectData(e, 3, true),
(e : ITaskEvent<unknown>) => expect(e.type).toEqual("ended"),
(e : ITaskEvent<unknown>) => expectData(e, 4, true),
(e : ITaskEvent<unknown>) => expect(e.type).toEqual("ended") ];
merge(pObs1, pObs2, pObs3, pObs4)
.pipe(startWith({ type: "data" as const, value: 0 }))
.subscribe({
next: (evt) => {
const checker = checkEvents[emitted];
if (checker === undefined) {
throw new Error("Unexpected event");
}
checker(evt);
emitted++;
},
error: () => { throw new Error("Should not have thrown"); },
complete: () => {
expect(emitted).toEqual(9);
done();
},
});
});
it("should not wait when Observables are run from lowest priority to highest", (done) => {
let obs1Started = false;
let obs2Started = false;
let obs3Started = false;
let obs4Started = false;
const obs1$ = defer(() => { obs1Started = true; return timer(1).pipe(mapTo(1)); });
const obs2$ = defer(() => { obs2Started = true; return timer(1).pipe(mapTo(2)); });
const obs3$ = defer(() => { obs3Started = true; return timer(1).pipe(mapTo(3)); });
const obs4$ = defer(() => { obs4Started = true; return timer(1).pipe(mapTo(4)); });
const prioritizer = new Prioritizer({ prioritySteps: { high: 5, low: 20 } });
let emitted = 0;
const pObs1 = prioritizer.create(obs1$, 5 + 4);
const pObs2 = prioritizer.create(obs2$, 5 + 3);
const pObs3 = prioritizer.create(obs3$, 5 + 2);
const pObs4 = prioritizer.create(obs4$, 5 + 1);
function expectData(
evt : ITaskEvent<unknown>,
expectedData : number,
shouldHaveStartedObs : boolean
) : void {
expect(obs1Started).toEqual(shouldHaveStartedObs);
expect(obs2Started).toEqual(shouldHaveStartedObs);
expect(obs3Started).toEqual(shouldHaveStartedObs);
expect(obs4Started).toEqual(shouldHaveStartedObs);
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(expectedData);
}
const checkEvents = [ (e : ITaskEvent<unknown>) => expectData(e, 0, false),
(e : ITaskEvent<unknown>) => expectData(e, 1, true),
(e : ITaskEvent<unknown>) => expect(e.type).toEqual("ended"),
(e : ITaskEvent<unknown>) => expectData(e, 2, true),
(e : ITaskEvent<unknown>) => expect(e.type).toEqual("ended"),
(e : ITaskEvent<unknown>) => expectData(e, 3, true),
(e : ITaskEvent<unknown>) => expect(e.type).toEqual("ended"),
(e : ITaskEvent<unknown>) => expectData(e, 4, true),
(e : ITaskEvent<unknown>) => expect(e.type).toEqual("ended") ];
merge(pObs1, pObs2, pObs3, pObs4)
.pipe(startWith({ type: "data" as const, value: 0 }))
.subscribe({
next: (evt) => {
const checker = checkEvents[emitted];
if (checker === undefined) {
throw new Error("Unexpected event");
}
checker(evt);
emitted++;
},
error: () => { throw new Error("Should not have thrown"); },
complete: () => {
expect(emitted).toEqual(9);
done();
},
});
});
it("should wait for higher-priority Observables", (done) => {
let obs1Started = false;
let obs2Started = false;
let obs3Started = false;
let obs4Started = false;
const obs1$ = defer(() => { obs1Started = true; return timer(1).pipe(mapTo(1)); });
const obs2$ = defer(() => { obs2Started = true; return timer(1).pipe(mapTo(2)); });
const obs3$ = defer(() => { obs3Started = true; return timer(1).pipe(mapTo(3)); });
const obs4$ = defer(() => { obs4Started = true; return timer(1).pipe(mapTo(4)); });
const prioritizer = new Prioritizer({ prioritySteps: { high: 5, low: 20 } });
let emitted = 0;
const pObs1 = prioritizer.create(obs1$, 1);
const pObs2 = prioritizer.create(obs2$, 2);
const pObs3 = prioritizer.create(obs3$, 3);
const pObs4 = prioritizer.create(obs4$, 4);
merge(pObs1, pObs2, pObs3, pObs4)
.pipe(startWith({ type: "data", value: 0 }))
.subscribe({
next: (evt) => {
switch (emitted) {
case 0:
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(0);
break;
case 1:
expect(obs1Started).toEqual(true);
expect(obs2Started).toEqual(false);
expect(obs3Started).toEqual(false);
expect(obs4Started).toEqual(false);
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(1);
break;
case 2:
expect(evt.type).toEqual("ended");
break;
case 3:
expect(obs1Started).toEqual(true);
expect(obs2Started).toEqual(true);
expect(obs3Started).toEqual(false);
expect(obs4Started).toEqual(false);
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(2);
break;
case 4:
expect(evt.type).toEqual("ended");
break;
case 5:
expect(obs1Started).toEqual(true);
expect(obs2Started).toEqual(true);
expect(obs3Started).toEqual(true);
expect(obs4Started).toEqual(false);
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(3);
break;
case 6:
expect(evt.type).toEqual("ended");
break;
case 7:
expect(obs1Started).toEqual(true);
expect(obs2Started).toEqual(true);
expect(obs3Started).toEqual(true);
expect(obs4Started).toEqual(true);
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(4);
break;
case 8:
expect(evt.type).toEqual("ended");
break;
default:
throw new Error("Unexpected event");
}
emitted++;
},
error: () => { throw new Error("Should not have thrown"); },
complete: () => {
expect(emitted).toEqual(9);
done();
},
});
});
it("should interrupt low-priority Observables when a high priority one is created", (done) => {
let obs1Started = 0;
let obs2Started = 0;
let obs3Started = 0;
let obs4Started = 0;
const obs1$ = defer(() => { obs1Started++; return timer(1).pipe(mapTo(1)); });
const obs2$ = defer(() => { obs2Started++; return timer(1).pipe(mapTo(2)); });
const obs3$ = defer(() => { obs3Started++; return timer(1).pipe(mapTo(3)); });
const obs4$ = defer(() => { obs4Started++; return timer(1).pipe(mapTo(4)); });
const prioritizer = new Prioritizer({ prioritySteps: { high: 5, low: 20 } });
let emitted = 0;
const pObs1 = prioritizer.create(obs1$, 20);
const pObs2 = prioritizer.create(obs2$, 20 - 1);
const pObs3 = prioritizer.create(obs3$, 5);
const pObs4 = prioritizer.create(obs4$, 0);
merge(pObs1, pObs2, pObs3, pObs4)
.subscribe({
next: (evt) => {
switch (emitted) {
case 0:
expect(evt.type).toEqual("interrupted");
expect(obs1Started).toEqual(1);
expect(obs2Started).toEqual(1);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(0);
break;
case 1:
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(2);
expect(obs1Started).toEqual(1);
expect(obs2Started).toEqual(1);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(1);
break;
case 2:
expect(evt.type).toEqual("ended");
break;
case 3:
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(3);
expect(obs1Started).toEqual(1);
expect(obs2Started).toEqual(1);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(1);
break;
case 4:
expect(evt.type).toEqual("ended");
break;
case 5:
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(4);
expect(obs1Started).toEqual(1);
expect(obs2Started).toEqual(1);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(1);
break;
case 6:
expect(evt.type).toEqual("ended");
break;
case 7:
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(1);
expect(obs1Started).toEqual(2);
expect(obs2Started).toEqual(1);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(1);
break;
case 8:
expect(evt.type).toEqual("ended");
break;
default:
throw new Error("Unexpected event");
}
emitted++;
},
error: () => { throw new Error("Should not have thrown"); },
complete: () => {
expect(obs1Started).toEqual(2);
expect(obs2Started).toEqual(1);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(1);
expect(emitted).toEqual(9);
done();
},
});
});
it("should be able to update a priority", (done) => {
let obs1Started = false;
let obs2Started = false;
let obs3Started = false;
let obs4Started = false;
const obs1$ = defer(() => { obs1Started = true; return timer(1).pipe(mapTo(1)); });
const obs2$ = defer(() => { obs2Started = true; return timer(1).pipe(mapTo(2)); });
const obs3$ = defer(() => { obs3Started = true; return timer(1).pipe(mapTo(3)); });
const obs4$ = defer(() => { obs4Started = true; return timer(1).pipe(mapTo(4)); });
const prioritizer = new Prioritizer({ prioritySteps: { high: 5, low: 20 } });
let emitted = 0;
const pObs1 = prioritizer.create(obs1$, 5 + 1);
const pObs2 = prioritizer.create(obs2$, 5 + 2);
const pObs3 = prioritizer.create(obs3$, 5 + 3);
const pObs4 = prioritizer.create(obs4$, 5 + 4);
merge(pObs1, pObs2, pObs3, pObs4)
.subscribe({
next: (evt) => {
switch (emitted) {
case 0:
prioritizer.updatePriority(pObs4, 5 + 1);
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(1);
expect(obs1Started).toEqual(true);
expect(obs2Started).toEqual(false);
expect(obs3Started).toEqual(false);
expect(obs4Started).toEqual(true);
break;
case 1:
expect(evt.type).toEqual("ended");
break;
case 2:
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(4);
expect(obs1Started).toEqual(true);
expect(obs2Started).toEqual(false);
expect(obs3Started).toEqual(false);
expect(obs4Started).toEqual(true);
break;
case 3:
expect(evt.type).toEqual("ended");
break;
case 4:
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(2);
expect(obs1Started).toEqual(true);
expect(obs2Started).toEqual(true);
expect(obs3Started).toEqual(false);
expect(obs4Started).toEqual(true);
break;
case 5:
expect(evt.type).toEqual("ended");
break;
case 6:
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(3);
expect(obs1Started).toEqual(true);
expect(obs2Started).toEqual(true);
expect(obs3Started).toEqual(true);
expect(obs4Started).toEqual(true);
break;
case 7:
expect(evt.type).toEqual("ended");
break;
default:
throw new Error("Unexpected event");
}
emitted++;
},
error: () => { throw new Error("Should not have thrown"); },
complete: () => {
expect(emitted).toEqual(8);
done();
},
});
});
it("should restart interrupted observables if given the right priority", (done) => {
let obs1Started = 0;
let obs2Started = 0;
let obs3Started = 0;
let obs4Started = 0;
const obs1$ = defer(() => { obs1Started++; return timer(1).pipe(mapTo(1)); });
const obs2$ = defer(() => { obs2Started++; return timer(1).pipe(mapTo(2)); });
const obs3$ = defer(() => { obs3Started++; return timer(1).pipe(mapTo(3)); });
const obs4$ = defer(() => { obs4Started++; return timer(1).pipe(mapTo(4)); });
const prioritizer = new Prioritizer({ prioritySteps: { high: 5, low: 20 } });
let emitted = 0;
const pObs1 = prioritizer.create(obs1$, 20);
const pObs2 = prioritizer.create(obs2$, 20 - 1);
const pObs3 = prioritizer.create(obs3$, 5);
const pObs4 = prioritizer.create(obs4$, 0);
merge(pObs1, pObs2, pObs3, pObs4)
.subscribe({
next: (evt) => {
switch (emitted) {
case 0:
expect(evt.type).toEqual("interrupted");
expect(obs1Started).toEqual(1);
expect(obs2Started).toEqual(1);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(0);
// pObs1 has just been cancelled by pObs3.
// Immediately set it the highest priority.
prioritizer.updatePriority(pObs1, 0);
break;
case 1:
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(2);
expect(obs1Started).toEqual(2);
expect(obs2Started).toEqual(1);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(1);
break;
case 2:
expect(evt.type).toEqual("ended");
break;
case 3:
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(3);
expect(obs1Started).toEqual(2);
expect(obs2Started).toEqual(1);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(1);
break;
case 4:
expect(evt.type).toEqual("ended");
break;
case 5:
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(1);
expect(obs1Started).toEqual(2);
expect(obs2Started).toEqual(1);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(1);
break;
case 6:
expect(evt.type).toEqual("ended");
break;
case 7:
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(4);
expect(obs1Started).toEqual(2);
expect(obs2Started).toEqual(1);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(1);
break;
case 8:
expect(evt.type).toEqual("ended");
break;
default:
throw new Error("Unexpected event");
}
emitted++;
},
error: () => { throw new Error("Should not have thrown"); },
complete: () => {
expect(obs1Started).toEqual(2);
expect(obs2Started).toEqual(1);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(1);
expect(emitted).toEqual(9);
done();
},
});
});
it("should be able to update the priority of pending tasks", (done) => {
let obs1Started = 0;
let obs2Started = 0;
let obs3Started = 0;
let obs4Started = 0;
const obs1$ = defer(() => { obs1Started++; return timer(1).pipe(mapTo(1)); });
const obs2$ = defer(() => { obs2Started++; return timer(1).pipe(mapTo(2)); });
const obs3$ = defer(() => { obs3Started++; return timer(1).pipe(mapTo(3)); });
const obs4$ = defer(() => { obs4Started++; return timer(1).pipe(mapTo(4)); });
const prioritizer = new Prioritizer({ prioritySteps: { high: 5, low: 20 } });
let emitted = 0;
const pObs1 = prioritizer.create(obs1$, 20);
const pObs2 = prioritizer.create(obs2$, 20 - 1);
const pObs3 = prioritizer.create(obs3$, 5);
const pObs4 = prioritizer.create(obs4$, 20 + 10);
merge(pObs1, pObs2, pObs3, pObs4)
.subscribe({
next: (evt) => {
switch (emitted) {
case 0: // interrupting pObs1 now that pObs3 is created
expect(evt.type).toEqual("interrupted");
expect(obs1Started).toEqual(1);
expect(obs2Started).toEqual(1);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(0);
prioritizer.updatePriority(pObs2, 20 + 12);
break;
case 1: // interrupting pObs2 now that it has been updated
expect(evt.type).toEqual("interrupted");
expect(obs1Started).toEqual(1);
expect(obs2Started).toEqual(1);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(0);
break;
case 2: // pObs3 emits
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(3);
expect(obs1Started).toEqual(1);
expect(obs2Started).toEqual(1);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(0);
break;
case 3: // pObs3 ends
expect(evt.type).toEqual("ended");
break;
case 4: // pObs1 emits
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(1);
expect(obs1Started).toEqual(2);
expect(obs2Started).toEqual(1);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(0);
break;
case 5: // pObs1 ends
expect(evt.type).toEqual("ended");
break;
case 6: // pObs4 emits
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(4);
expect(obs1Started).toEqual(2);
expect(obs2Started).toEqual(1);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(1);
break;
case 7: // pObs4 ends
expect(evt.type).toEqual("ended");
break;
case 8: // pObs2 emits
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(2);
expect(obs1Started).toEqual(2);
expect(obs2Started).toEqual(2);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(1);
break;
case 9: // pObs2 ends
expect(evt.type).toEqual("ended");
break;
default:
throw new Error("Unexpected event");
}
emitted++;
},
error: () => { throw new Error("Should not have thrown"); },
complete: () => {
expect(obs1Started).toEqual(2);
expect(obs2Started).toEqual(2);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(1);
expect(emitted).toEqual(10);
done();
},
});
});
it("should be able to interrupt observables after a priority update on a pending task", (done) => {
let obs1Started = 0;
let obs2Started = 0;
let obs3Started = 0;
let obs4Started = 0;
const obs1$ = defer(() => { obs1Started++; return timer(1).pipe(mapTo(1)); });
const obs2$ = defer(() => { obs2Started++; return timer(1).pipe(mapTo(2)); });
const obs3$ = defer(() => { obs3Started++; return timer(1).pipe(mapTo(3)); });
const obs4$ = defer(() => { obs4Started++; return timer(1).pipe(mapTo(4)); });
const prioritizer = new Prioritizer({ prioritySteps: { high: 5, low: 20 } });
let emitted = 0;
const pObs1 = prioritizer.create(obs1$, 20);
const pObs2 = prioritizer.create(obs2$, 20);
const pObs3 = prioritizer.create(obs3$, 20);
const pObs4 = prioritizer.create(obs4$, 20);
// Put in microtask
Promise.resolve().then(() => {
prioritizer.updatePriority(pObs4, 5);
});
merge(pObs1, pObs2, pObs3, pObs4)
.subscribe({
next: (evt) => {
switch (emitted) {
case 0:
expect(evt.type).toEqual("interrupted");
expect(obs1Started).toEqual(1);
expect(obs2Started).toEqual(1);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(1);
break;
case 1:
expect(evt.type).toEqual("interrupted");
break;
case 2:
expect(evt.type).toEqual("interrupted");
break;
case 3:
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(4);
break;
case 4:
expect(evt.type).toEqual("ended");
expect(obs1Started).toEqual(1);
expect(obs2Started).toEqual(1);
expect(obs3Started).toEqual(1);
expect(obs4Started).toEqual(1);
break;
case 5:
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(1);
expect(obs1Started).toEqual(2);
expect(obs2Started).toEqual(2);
expect(obs3Started).toEqual(2);
expect(obs4Started).toEqual(1);
break;
case 6:
expect(evt.type).toEqual("ended");
break;
case 7:
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(2);
break;
case 8:
expect(evt.type).toEqual("ended");
break;
case 9:
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(3);
break;
case 10:
expect(evt.type).toEqual("ended");
break;
default:
throw new Error("Unexpected event");
}
emitted++;
},
error: () => { throw new Error("Should not have thrown"); },
complete: () => {
expect(obs1Started).toEqual(2);
expect(obs2Started).toEqual(2);
expect(obs3Started).toEqual(2);
expect(obs4Started).toEqual(1);
expect(emitted).toEqual(11);
done();
},
});
});
it("should not start right away an updated observable which has still not the priority", (done) => {
let obs1Started = false;
let obs2Started = false;
let obs3Started = false;
let obs4Started = false;
const obs1$ = defer(() => { obs1Started = true; return timer(1).pipe(mapTo(1)); });
const obs2$ = defer(() => { obs2Started = true; return timer(1).pipe(mapTo(2)); });
const obs3$ = defer(() => { obs3Started = true; return timer(1).pipe(mapTo(3)); });
const obs4$ = defer(() => { obs4Started = true; return timer(1).pipe(mapTo(4)); });
const prioritizer = new Prioritizer({ prioritySteps: { high: 5, low: 20 } });
let emitted = 0;
const pObs1 = prioritizer.create(obs1$, 5);
const pObs2 = prioritizer.create(obs2$, 5 + 1);
const pObs3 = prioritizer.create(obs3$, 5 + 2);
const pObs4 = prioritizer.create(obs4$, 5 + 3);
function expectData(
evt : ITaskEvent<unknown>,
expectedData : number,
shouldArray : [boolean, boolean, boolean, boolean]
) : void {
expect(obs1Started).toEqual(shouldArray[0]);
expect(obs2Started).toEqual(shouldArray[1]);
expect(obs3Started).toEqual(shouldArray[2]);
expect(obs4Started).toEqual(shouldArray[3]);
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(expectedData);
}
const checkEvents = [ (e : ITaskEvent<unknown>) => expectData(e, 1, [true, false, false, false]),
(e : ITaskEvent<unknown>) => expect(e.type).toEqual("ended"),
(e : ITaskEvent<unknown>) => expectData(e, 2, [true, true, false, false]),
(e : ITaskEvent<unknown>) => expect(e.type).toEqual("ended"),
(e : ITaskEvent<unknown>) => expectData(e, 3, [true, true, true, true]),
(e : ITaskEvent<unknown>) => expect(e.type).toEqual("ended"),
(e : ITaskEvent<unknown>) => expectData(e, 4, [true, true, true, true]),
(e : ITaskEvent<unknown>) => expect(e.type).toEqual("ended") ];
// Put in microtask
Promise.resolve().then(() => {
prioritizer.updatePriority(pObs4, 5 + 2);
});
merge(pObs1, pObs2, pObs3, pObs4)
.subscribe({
next: (evt) => {
const checker = checkEvents[emitted];
if (checker === undefined) {
throw new Error("Unexpected event");
}
checker(evt);
emitted++;
},
error: () => { throw new Error("Should not have thrown"); },
complete: () => {
expect(emitted).toEqual(checkEvents.length);
done();
},
});
});
it("should not do anything special when updating a pending task with the same priority", (done) => {
let obs1Started = 0;
let obs2Started = 0;
let obs3Started = 0;
let obs4Started = 0;
const obs1$ = defer(() => { obs1Started++; return timer(1).pipe(mapTo(1)); });
const obs2$ = defer(() => { obs2Started++; return timer(1).pipe(mapTo(2)); });
const obs3$ = defer(() => { obs3Started++; return timer(1).pipe(mapTo(3)); });
const obs4$ = defer(() => { obs4Started++; return timer(1).pipe(mapTo(4)); });
const prioritizer = new Prioritizer({ prioritySteps: { high: 5, low: 20 } });
let emitted = 0;
const pObs1 = prioritizer.create(obs1$, 20 + 1);
const pObs2 = prioritizer.create(obs2$, 5);
const pObs3 = prioritizer.create(obs3$, 20 + 2);
const pObs4 = prioritizer.create(obs4$, 20 + 3);
function expectInterrupted(
evt : ITaskEvent<unknown>,
shouldArray : [number, number, number, number]
) : void {
expect(evt.type).toEqual("interrupted");
expect(obs1Started).toEqual(shouldArray[0]);
expect(obs2Started).toEqual(shouldArray[1]);
expect(obs3Started).toEqual(shouldArray[2]);
expect(obs4Started).toEqual(shouldArray[3]);
}
function expectData(
evt : ITaskEvent<unknown>,
expectedData : number,
shouldArray : [number, number, number, number]
) : void {
expect(obs1Started).toEqual(shouldArray[0]);
expect(obs2Started).toEqual(shouldArray[1]);
expect(obs3Started).toEqual(shouldArray[2]);
expect(obs4Started).toEqual(shouldArray[3]);
assert(evt.type === "data",
`evt.type should be equal to "data" but was equal to "${evt.type}"`);
expect(evt.value).toEqual(expectedData);
}
const checkEvents = [ (e : ITaskEvent<unknown>) => expectInterrupted(e, [1, 1, 0, 0]),
(e : ITaskEvent<unknown>) => expectData(e, 2, [1, 1, 0, 0]),
(e : ITaskEvent<unknown>) => expect(e.type).toEqual("ended"),
(e : ITaskEvent<unknown>) => expectData(e, 1, [2, 1, 0, 0]),
(e : ITaskEvent<unknown>) => expect(e.type).toEqual("ended"),
(e : ITaskEvent<unknown>) => expectData(e, 3, [2, 1, 1, 0]),
(e : ITaskEvent<unknown>) => expect(e.type).toEqual("ended"),
(e : ITaskEvent<unknown>) => expectData(e, 4, [2, 1, 1, 1]),
(e : ITaskEvent<unknown>) => expect(e.type).toEqual("ended") ];
// Put in microtask
Promise.resolve().then(() => {
prioritizer.updatePriority(pObs2, 5);
});
merge(pObs1, pObs2, pObs3, pObs4)
.subscribe({
next: (evt) => {
const checker = checkEvents[emitted];
if (checker === undefined) {
throw new Error("Unexpected event");
}
checker(evt);
emitted++;
},
error: () => { throw new Error("Should not have thrown"); },
complete: () => {
expect(emitted).toEqual(checkEvents.length);
done();
},
});
});
}); | the_stack |
* @fileoverview Implements the SVGmenclose wrapper for the MmlMenclose object
*
* @author dpvc@mathjax.org (Davide Cervone)
*/
import {SVGWrapper, SVGConstructor} from '../Wrapper.js';
import {CommonMencloseMixin} from '../../common/Wrappers/menclose.js';
import {SVGmsqrt} from './msqrt.js';
import * as Notation from '../Notation.js';
import {MmlMenclose} from '../../../core/MmlTree/MmlNodes/menclose.js';
import {OptionList} from '../../../util/Options.js';
/*****************************************************************/
/**
* The SVGmenclose wrapper for the MmlMenclose object
*
* @template N The HTMLElement node class
* @template T The Text node class
* @template D The Document class
*/
// @ts-ignore
export class SVGmenclose<N, T, D> extends CommonMencloseMixin<
SVGWrapper<any, any, any>,
SVGmsqrt<any, any, any>,
any,
SVGConstructor<any, any, any>
>(SVGWrapper) {
/**
* The menclose wrapper
*/
public static kind = MmlMenclose.prototype.kind;
/**
* The definitions of the various notations
*/
public static notations: Notation.DefList<SVGmenclose<any, any, any>, any> = new Map([
Notation.Border('top'),
Notation.Border('right'),
Notation.Border('bottom'),
Notation.Border('left'),
Notation.Border2('actuarial', 'top', 'right'),
Notation.Border2('madruwb', 'bottom', 'right'),
Notation.DiagonalStrike('up'),
Notation.DiagonalStrike('down'),
['horizontalstrike', {
renderer: Notation.RenderLine('horizontal', 'Y'),
bbox: (node) => [0, node.padding, 0, node.padding]
}],
['verticalstrike', {
renderer: Notation.RenderLine('vertical', 'X'),
bbox: (node) => [node.padding, 0, node.padding, 0]
}],
['box', {
renderer: (node, _child) => {
const {w, h, d} = node.getBBox();
node.adaptor.append(node.element, node.box(w, h, d));
},
bbox: Notation.fullBBox,
border: Notation.fullBorder,
remove: 'left right top bottom'
}],
['roundedbox', {
renderer: (node, _child) => {
const {w, h, d} = node.getBBox();
const r = node.thickness + node.padding;
node.adaptor.append(node.element, node.box(w, h, d, r));
},
bbox: Notation.fullBBox
}],
['circle', {
renderer: (node, _child) => {
const {w, h, d} = node.getBBox();
node.adaptor.append(node.element, node.ellipse(w, h, d));
},
bbox: Notation.fullBBox
}],
['phasorangle', {
//
// Use a bottom border and an upward strike properly angled
//
renderer: (node, _child) => {
const {w, h, d} = node.getBBox();
const a = node.getArgMod(1.75 * node.padding, h + d)[0];
const t = node.thickness / 2;
const HD = h + d;
const cos = Math.cos(a);
node.adaptor.append(
node.element,
node.path('mitre', 'M', w, t - d, 'L', t + cos * t, t - d, 'L' , cos * HD + t, HD - d - t)
);
},
bbox: (node) => {
const p = node.padding / 2;
const t = node.thickness;
return [2 * p, p, p + t, 3 * p + t];
},
border: (node) => [0, 0, node.thickness, 0],
remove: 'bottom'
}],
Notation.Arrow('up'),
Notation.Arrow('down'),
Notation.Arrow('left'),
Notation.Arrow('right'),
Notation.Arrow('updown'),
Notation.Arrow('leftright'),
Notation.DiagonalArrow('updiagonal'), // backward compatibility
Notation.DiagonalArrow('northeast'),
Notation.DiagonalArrow('southeast'),
Notation.DiagonalArrow('northwest'),
Notation.DiagonalArrow('southwest'),
Notation.DiagonalArrow('northeastsouthwest'),
Notation.DiagonalArrow('northwestsoutheast'),
['longdiv', {
//
// Use a line along the top followed by a half ellipse at the left
//
renderer: (node, _child) => {
const {w, h, d} = node.getBBox();
const t = node.thickness / 2;
const p = node.padding;
node.adaptor.append(
node.element,
node.path('round',
'M', t, t - d,
'a', p - t / 2, (h + d) / 2 - 4 * t, 0, '0,1', 0, h + d - 2 * t,
'L', w - t, h - t
)
);
},
bbox: (node) => {
const p = node.padding;
const t = node.thickness;
return [p + t, p, p, 2 * p + t / 2];
}
}],
['radical', {
//
// Use the msqrt rendering, but remove the extra space due to the radical
// (it is added in at the end, so other notations overlap the root)
//
renderer: (node, child) => {
node.msqrt.toSVG(child);
const left = node.sqrtTRBL()[3];
node.place(-left, 0, child);
},
//
// Create the needed msqrt wrapper
//
init: (node) => {
node.msqrt = node.createMsqrt(node.childNodes[0]);
},
//
// Add back in the padding for the square root
//
bbox: (node) => node.sqrtTRBL(),
//
// This notation replaces the child
//
renderChild: true
}]
] as Notation.DefPair<SVGmenclose<any, any, any>, any>[]);
/********************************************************/
/**
* @override
*/
public toSVG(parent: N) {
const svg = this.standardSVGnode(parent);
//
// Create a box at the correct position and add the children
//
const left = this.getBBoxExtenders()[3];
const def: OptionList = {};
if (left > 0) {
def.transform = 'translate(' + this.fixed(left) + ', 0)';
}
const block = this.adaptor.append(svg, this.svg('g', def));
if (this.renderChild) {
this.renderChild(this, block);
} else {
this.childNodes[0].toSVG(block);
}
//
// Render all the notations for this menclose element
//
for (const name of Object.keys(this.notations)) {
const notation = this.notations[name];
!notation.renderChild && notation.renderer(this, svg);
}
}
/********************************************************/
/**
* Create an arrow using SVG elements
*
* @param {number} W The length of the arrow
* @param {number} a The angle for the arrow
* @param {boolean} double True if this is a double-headed arrow
* @param {string} offset 'X' for vertical arrow, 'Y' for horizontal
* @param {number} dist Distance to translate in the offset direction
* @return {N} The newly created arrow
*/
public arrow(W: number, a: number, double: boolean, offset: string = '', dist: number = 0): N {
const {w, h, d} = this.getBBox();
const dw = (W - w) / 2;
const m = (h - d) / 2;
const t = this.thickness;
const t2 = t / 2;
const [x, y, dx] = [t * this.arrowhead.x, t * this.arrowhead.y, t * this.arrowhead.dx];
const arrow =
(double ?
this.fill(
'M', w + dw, m, // point of arrow
'l', -(x + dx), y, 'l', dx, t2 - y, // upper right head
'L', x - dw, m + t2, // upper side of shaft
'l', dx, y - t2, 'l', -(x + dx), - y, // left point
'l', x + dx, -y, 'l', -dx, y - t2, // lower left head
'L', w + dw - x, m - t2, // lower side of shaft
'l', -dx, t2 - y, 'Z' // lower head
) :
this.fill(
'M', w + dw, m, // point of arrow
'l', -(x + dx), y, 'l', dx, t2 - y, // upper head
'L', -dw, m + t2, 'l', 0, -t, // upper side of shaft
'L', w + dw - x, m - t2, // lower side of shaft
'l', -dx, t2 - y, 'Z' // lower head
));
const transform = [];
if (dist) {
transform.push(offset === 'X' ? `translate(${this.fixed(-dist)} 0)` : `translate(0 ${this.fixed(dist)})`);
}
if (a) {
const A = this.jax.fixed(-a * 180 / Math.PI);
transform.push(`rotate(${A} ${this.fixed(w / 2)} ${this.fixed(m)})`);
}
if (transform.length) {
this.adaptor.setAttribute(arrow, 'transform', transform.join(' '));
}
return arrow as N;
}
/********************************************************/
/**
* Create a line element
*
* @param {number[]} pq The coordinates of the endpoints, [x1, y1, x2, y2]
* @return {N} The newly created line element
*/
public line(pq: [number, number, number, number]): N {
const [x1, y1, x2, y2] = pq;
return this.svg('line', {
x1: this.fixed(x1), y1: this.fixed(y1),
x2: this.fixed(x2), y2: this.fixed(y2),
'stroke-width': this.fixed(this.thickness)
});
}
/**
* Create a rectangle element
*
* @param {number} w The width of the rectangle
* @param {number} h The height of the rectangle
* @param {number} d The depth of the rectangle
* @param {number=} r The corner radius for a rounded rectangle
* @return {N} The newly created line element
*/
public box(w: number, h: number, d: number, r: number = 0): N {
const t = this.thickness;
const def: OptionList = {
x: this.fixed(t / 2), y: this.fixed(t / 2 - d),
width: this.fixed(w - t), height: this.fixed(h + d - t),
fill: 'none', 'stroke-width': this.fixed(t)
};
if (r) {
def.rx = this.fixed(r);
}
return this.svg('rect', def);
}
/**
* Create an ellipse element
*
* @param {number} w The width of the ellipse
* @param {number} h The height of the ellipse
* @param {number} d The depth of the ellipse
* @return {N} The newly created ellipse node
*/
public ellipse(w: number, h: number, d: number): N {
const t = this.thickness;
return this.svg('ellipse', {
rx: this.fixed((w - t) / 2), ry: this.fixed((h + d - t) / 2),
cx: this.fixed(w / 2), cy: this.fixed((h - d) / 2),
'fill': 'none', 'stroke-width': this.fixed(t)
});
}
/**
* Create a path element from the commands that specify it
*
* @param {string} join The join style for the path
* @param {(string|number)[]} P The list of commands and coordinates for the path
* @return {N} The newly created path
*/
public path(join: string, ...P: (string | number)[]): N {
return this.svg('path', {
d: P.map(x => (typeof x === 'string' ? x : this.fixed(x))).join(' '),
style: {'stroke-width': this.fixed(this.thickness)},
'stroke-linecap': 'round', 'stroke-linejoin': join,
fill: 'none'
});
}
/**
* Create a filled path element from the commands the specify it
* (same as path above, but no thickness adjustments)
*
* @param {(string|number)[]} P The list of commands and coordinates for the path
* @return {N} The newly created path
*/
public fill(...P: (string | number)[]): N {
return this.svg('path', {
d: P.map(x => (typeof x === 'string' ? x : this.fixed(x))).join(' ')
});
}
} | the_stack |
* @packageDocumentation
* @hidden
*/
// Some helper methods for compile instantiation code
import { TEST } from 'internal:constants';
import * as js from '../utils/js';
import { CCClass } from './class';
import { CCObject } from './object';
import * as Attr from './utils/attribute';
import { flattenCodeArray } from './utils/compiler';
import { legacyCC } from '../global-exports';
const Destroyed = CCObject.Flags.Destroyed;
const PersistentMask = CCObject.Flags.PersistentMask;
const DEFAULT = `${Attr.DELIMETER}default`;
const IDENTIFIER_RE = CCClass.IDENTIFIER_RE;
const VAR = 'var ';
const LOCAL_OBJ = 'o';
const LOCAL_TEMP_OBJ = 't';
const LOCAL_ARRAY = 'a';
const LINE_INDEX_OF_NEW_OBJ = 0;
const DEFAULT_MODULE_CACHE = {
'cc.ClickEvent': false,
'cc.PrefabInfo': false,
};
const escapeForJS = CCClass.escapeForJS;
// HELPER CLASSES
// ('foo', 'bar')
// -> 'var foo = bar;'
class Declaration {
public varName: any;
public expression: any;
constructor (varName, expression) {
this.varName = varName;
this.expression = expression;
}
public toString () {
return `${VAR + this.varName}=${this.expression};`;
}
}
// ('a =', 'var b = x')
// -> 'var b = a = x';
// ('a =', 'x')
// -> 'a = x';
function mergeDeclaration (statement, expression) {
if (expression instanceof Declaration) {
return new Declaration(expression.varName, statement + expression.expression);
} else {
return statement + expression;
}
}
// ('a', ['var b = x', 'b.foo = bar'])
// -> 'var b = a = x;'
// -> 'b.foo = bar;'
// ('a', 'var b = x')
// -> 'var b = a = x;'
// ('a', 'x')
// -> 'a = x;'
function writeAssignment (codeArray, statement, expression) {
if (Array.isArray(expression)) {
expression[0] = mergeDeclaration(statement, expression[0]);
codeArray.push(expression);
} else {
codeArray.push(`${mergeDeclaration(statement, expression)};`);
}
}
// ('foo', 'bar')
// -> 'targetExpression.foo = bar'
// ('foo1', 'bar1')
// ('foo2', 'bar2')
// -> 't = targetExpression;'
// -> 't.foo1 = bar1;'
// -> 't.foo2 = bar2;'
class Assignments {
public static pool: js.Pool<{}>;
private _exps: any[];
private _targetExp: any;
constructor (targetExpression?) {
this._exps = [];
this._targetExp = targetExpression;
}
public append (key, expression) {
this._exps.push([key, expression]);
}
public writeCode (codeArray) {
let targetVar;
if (this._exps.length > 1) {
codeArray.push(`${LOCAL_TEMP_OBJ}=${this._targetExp};`);
targetVar = LOCAL_TEMP_OBJ;
} else if (this._exps.length === 1) {
targetVar = this._targetExp;
} else {
return;
}
for (let i = 0; i < this._exps.length; i++) {
const pair = this._exps[i];
writeAssignment(codeArray, `${targetVar + getPropAccessor(pair[0])}=`, pair[1]);
}
}
}
Assignments.pool = new js.Pool((obj: any) => {
obj._exps.length = 0;
obj._targetExp = null;
}, 1);
// @ts-expect-error
Assignments.pool.get = function (targetExpression) {
const cache: any = this._get() || new Assignments();
cache._targetExp = targetExpression;
return cache;
};
// HELPER FUNCTIONS
function getPropAccessor (key) {
return IDENTIFIER_RE.test(key) ? (`.${key}`) : (`[${escapeForJS(key)}]`);
}
//
/*
* Variables:
* {Object[]} O - objs list
* {Function[]} F - constructor list
* {Node} [R] - specify an instantiated prefabRoot that all references to prefabRoot in prefab will redirect to
* {Object} o - current creating object
*/
class Parser {
public parent: any;
public objsToClear_iN$t: any[];
public codeArray: any[];
public objs: any[];
public funcs: any[];
public funcModuleCache: any;
public globalVariables: any[];
public globalVariableId: number;
public localVariableId: number;
public result: any;
/*
* @method constructor
* @param {Object} obj - the object to parse
* @param {Node} [parent]
*/
constructor (obj, parent) {
this.parent = parent;
this.objsToClear_iN$t = []; // used to reset _iN$t variable
this.codeArray = [];
// datas for generated code
this.objs = [];
this.funcs = [];
this.funcModuleCache = js.createMap();
js.mixin(this.funcModuleCache, DEFAULT_MODULE_CACHE);
// {String[]} - variable names for circular references,
// not really global, just local variables shared between sub functions
this.globalVariables = [];
// incremental id for new global variables
this.globalVariableId = 0;
// incremental id for new local variables
this.localVariableId = 0;
// generate codeArray
// if (Array.isArray(obj)) {
// this.codeArray.push(this.instantiateArray(obj));
// }
// else {
this.codeArray.push(`${VAR + LOCAL_OBJ},${LOCAL_TEMP_OBJ};`,
'if(R){',
`${LOCAL_OBJ}=R;`,
'}else{',
`${LOCAL_OBJ}=R=new ${this.getFuncModule(obj.constructor, true)}();`,
'}');
obj._iN$t = { globalVar: 'R' };
this.objsToClear_iN$t.push(obj);
this.enumerateObject(this.codeArray, obj);
// }
// generate code
let globalVariablesDeclaration;
if (this.globalVariables.length > 0) {
globalVariablesDeclaration = `${VAR + this.globalVariables.join(',')};`;
}
const code = flattenCodeArray(['return (function(R){',
globalVariablesDeclaration || [],
this.codeArray,
'return o;',
'})']);
// generate method and bind with objs
this.result = Function('O', 'F', code)(this.objs, this.funcs);
// if (TEST && !isPhantomJS) {
// console.log(code);
// }
// cleanup
for (let i = 0, len = this.objsToClear_iN$t.length; i < len; ++i) {
this.objsToClear_iN$t[i]._iN$t = null;
}
this.objsToClear_iN$t.length = 0;
}
public getFuncModule (func, usedInNew?) {
const clsName = js.getClassName(func);
if (clsName) {
const cache = this.funcModuleCache[clsName];
if (cache) {
return cache;
} else if (cache === undefined) {
let clsNameIsModule = clsName.indexOf('.') !== -1;
if (clsNameIsModule) {
try {
// ensure is module
clsNameIsModule = (func === Function(`return ${clsName}`)());
if (clsNameIsModule) {
this.funcModuleCache[clsName] = clsName;
return clsName;
}
} catch (e) {}
}
}
}
let index = this.funcs.indexOf(func);
if (index < 0) {
index = this.funcs.length;
this.funcs.push(func);
}
let res = `F[${index}]`;
if (usedInNew) {
res = `(${res})`;
}
this.funcModuleCache[clsName] = res;
return res;
}
public getObjRef (obj) {
let index = this.objs.indexOf(obj);
if (index < 0) {
index = this.objs.length;
this.objs.push(obj);
}
return `O[${index}]`;
}
public setValueType (codeArray, defaultValue, srcValue, targetExpression) {
// @ts-expect-error
const assignments: any = Assignments.pool.get(targetExpression);
let fastDefinedProps = defaultValue.constructor.__props__;
if (!fastDefinedProps) {
fastDefinedProps = Object.keys(defaultValue);
}
for (let i = 0; i < fastDefinedProps.length; i++) {
const propName = fastDefinedProps[i];
const prop = srcValue[propName];
if (defaultValue[propName] === prop) {
continue;
}
const expression = this.enumerateField(srcValue, propName, prop);
assignments.append(propName, expression);
}
assignments.writeCode(codeArray);
Assignments.pool.put(assignments);
}
public enumerateCCClass (codeArray, obj, klass) {
const props = klass.__values__;
const attrs = Attr.getClassAttrs(klass);
for (let p = 0; p < props.length; p++) {
const key = props[p];
const val = obj[key];
let defaultValue = attrs[key + DEFAULT];
if (equalsToDefault(defaultValue, val)) {
continue;
}
if (typeof val === 'object' && val instanceof legacyCC.ValueType) {
defaultValue = CCClass.getDefault(defaultValue);
if (defaultValue && defaultValue.constructor === val.constructor) {
// fast case
const targetExpression = LOCAL_OBJ + getPropAccessor(key);
this.setValueType(codeArray, defaultValue, val, targetExpression);
continue;
}
}
this.setObjProp(codeArray, obj, key, val);
}
}
public instantiateArray (value) {
if (value.length === 0) {
return '[]';
}
const arrayVar = LOCAL_ARRAY + (++this.localVariableId);
const declaration = new Declaration(arrayVar, `new Array(${value.length})`);
const codeArray = [declaration];
// assign a _iN$t flag to indicate that this object has been parsed.
value._iN$t = {
globalVar: '', // the name of declared global variable used to access this object
source: codeArray, // the source code array for this object
};
this.objsToClear_iN$t.push(value);
for (let i = 0; i < value.length; ++i) {
const statement = `${arrayVar}[${i}]=`;
const expression = this.enumerateField(value, i, value[i]);
writeAssignment(codeArray, statement, expression);
}
return codeArray;
}
public instantiateTypedArray (value) {
const type = value.constructor.name;
if (value.length === 0) {
return `new ${type}`;
}
const arrayVar = LOCAL_ARRAY + (++this.localVariableId);
const declaration = new Declaration(arrayVar, `new ${type}(${value.length})`);
const codeArray = [declaration];
// assign a _iN$t flag to indicate that this object has been parsed.
value._iN$t = {
globalVar: '', // the name of declared global variable used to access this object
source: codeArray, // the source code array for this object
};
this.objsToClear_iN$t.push(value);
for (let i = 0; i < value.length; ++i) {
if (value[i] !== 0) {
const statement = `${arrayVar}[${i}]=`;
writeAssignment(codeArray, statement, value[i]);
}
}
return codeArray;
}
public enumerateField (obj, key, value) {
if (typeof value === 'object' && value) {
const _iN$t = value._iN$t;
if (_iN$t) {
// parsed
let globalVar = _iN$t.globalVar;
if (!globalVar) {
// declare a global var
globalVar = _iN$t.globalVar = `v${++this.globalVariableId}`;
this.globalVariables.push(globalVar);
// insert assignment statement to assign to global var
const line = _iN$t.source[LINE_INDEX_OF_NEW_OBJ];
_iN$t.source[LINE_INDEX_OF_NEW_OBJ] = mergeDeclaration(`${globalVar}=`, line);
// if (typeof line ==='string' && line.startsWith(VAR)) {
// // var o=xxx -> var o=global=xxx
// var LEN_OF_VAR_O = 5;
// _iN$t.source[LINE_INDEX_OF_NEW_OBJ] = line.slice(0, LEN_OF_VAR_O) + '=' + globalVar + line.slice(LEN_OF_VAR_O);
// }
}
return globalVar;
} else if (ArrayBuffer.isView(value)) {
return this.instantiateTypedArray(value);
} else if (Array.isArray(value)) {
return this.instantiateArray(value);
} else {
return this.instantiateObj(value);
}
} else if (typeof value === 'function') {
return this.getFuncModule(value);
} else if (typeof value === 'string') {
return escapeForJS(value);
} else {
if (key === '_objFlags' && (obj instanceof CCObject)) {
value &= PersistentMask;
}
return value;
}
}
public setObjProp (codeArray, obj, key, value) {
const statement = `${LOCAL_OBJ + getPropAccessor(key)}=`;
const expression = this.enumerateField(obj, key, value);
writeAssignment(codeArray, statement, expression);
}
// codeArray - the source code array for this object
public enumerateObject (codeArray, obj) {
const klass = obj.constructor;
if (legacyCC.Class._isCCClass(klass)) {
this.enumerateCCClass(codeArray, obj, klass);
} else {
// primitive javascript object
for (const key in obj) {
if (!obj.hasOwnProperty(key)
|| (key.charCodeAt(0) === 95 && key.charCodeAt(1) === 95 // starts with "__"
&& key !== '__type__')
) {
continue;
}
const value = obj[key];
if (typeof value === 'object' && value && value === obj._iN$t) {
continue;
}
this.setObjProp(codeArray, obj, key, value);
}
}
}
public instantiateObj (obj) {
if (obj instanceof legacyCC.ValueType) {
return CCClass.getNewValueTypeCode(obj);
}
if (obj instanceof legacyCC.Asset) {
// register to asset list and just return the reference.
return this.getObjRef(obj);
}
if (obj._objFlags & Destroyed) {
// the same as cc.isValid(obj)
return null;
}
let createCode;
const ctor = obj.constructor;
if (legacyCC.Class._isCCClass(ctor)) {
if (this.parent) {
if (this.parent instanceof legacyCC.Component) {
if (obj instanceof legacyCC._BaseNode || obj instanceof legacyCC.Component) {
return this.getObjRef(obj);
}
} else if (this.parent instanceof legacyCC._BaseNode) {
if (obj instanceof legacyCC._BaseNode) {
if (!obj.isChildOf(this.parent)) {
// should not clone other nodes if not descendant
return this.getObjRef(obj);
}
} else if (obj instanceof legacyCC.Component) {
if (!obj.node.isChildOf(this.parent)) {
// should not clone other component if not descendant
return this.getObjRef(obj);
}
}
}
}
createCode = new Declaration(LOCAL_OBJ, `new ${this.getFuncModule(ctor, true)}()`);
} else if (ctor === Object) {
createCode = new Declaration(LOCAL_OBJ, '{}');
} else if (!ctor) {
createCode = new Declaration(LOCAL_OBJ, 'Object.create(null)');
} else {
// do not clone unknown type
return this.getObjRef(obj);
}
const codeArray = [createCode];
// assign a _iN$t flag to indicate that this object has been parsed.
obj._iN$t = {
globalVar: '', // the name of declared global variable used to access this object
source: codeArray, // the source code array for this object
// propName: '', // the propName this object defined in its source code,
// // if defined, use LOCAL_OBJ.propName to access the obj, else just use o
};
this.objsToClear_iN$t.push(obj);
this.enumerateObject(codeArray, obj);
return ['(function(){',
codeArray,
'return o;})();'];
}
}
export function equalsToDefault (def: any, value: any) {
if (typeof def === 'function') {
try {
def = def();
} catch (e) {
return false;
}
}
if (def === value) {
return true;
}
if (def && value
&& typeof def === 'object' && typeof value === 'object'
&& def.constructor === value.constructor
) {
if (def instanceof legacyCC.ValueType) {
if (def.equals(value)) {
return true;
}
} else if (Array.isArray(def)) {
return def.length === 0 && value.length === 0;
} else if (def.constructor === Object) {
return js.isEmptyObject(def) && js.isEmptyObject(value);
}
}
return false;
}
export function compile (node) {
const root = (node instanceof legacyCC._BaseNode) && node;
const parser = new Parser(node, root);
return parser.result;
}
if (TEST) {
legacyCC._Test.IntantiateJit = {
equalsToDefault,
compile,
};
} | the_stack |
import { loadConfig } from '../utils/config'
import * as ByteBuffer from 'bytebuffer'
import * as crypto from 'crypto'
import { LND_KEYSEND_KEY } from './lightning'
import * as long from 'long'
const config = loadConfig()
const IS_LND = config.lightning_provider === 'LND'
const IS_GREENLIGHT = config.lightning_provider === 'GREENLIGHT'
/* GET INFO */
interface Feature {
name: string
is_required: boolean
is_known: string
}
interface Chain {
chain: string
network: string
}
export interface GetInfoResponse {
version: string
commit_hash: string
identity_pubkey: string
alias: string
color: string
num_pending_channels: number
num_active_channels: number
num_inactive_channels: number
num_peers: number
block_height: number
block_hash: string
best_header_timestamp: number
synced_to_chain: boolean
synced_to_graph: boolean
uris: string[]
chains: Chain[]
features: { [k: number]: Feature }
testnet: boolean
}
interface GreenlightAddress {
type: number
addr: string
port: number
}
interface GreenlightGetInfoResponse {
node_id: Buffer
alias: string
color: string
num_peers: number
addresses: GreenlightAddress[]
version: string
blockheight: number
network: string
}
export function getInfoResponse(
res: GetInfoResponse | GreenlightGetInfoResponse
): GetInfoResponse {
if (IS_LND) {
// LND
return res as GetInfoResponse
}
if (IS_GREENLIGHT) {
// greenlight
const r = res as GreenlightGetInfoResponse
return <GetInfoResponse>{
identity_pubkey: Buffer.from(r.node_id).toString('hex'),
version: r.version,
alias: r.alias,
color: r.color,
num_peers: r.num_peers,
// FAKE VALUES
num_active_channels: 0,
num_pending_channels: 0,
synced_to_chain: true,
synced_to_graph: true,
best_header_timestamp: 0,
testnet: false,
}
}
return <GetInfoResponse>{}
}
/* ADD INVOICE */
interface HopHint {
node_id: string
chan_id: string
fee_base_msat?: number
fee_proportional_millionths?: number
cltv_expiry_delta?: number
}
interface RouteHint {
hop_hints: HopHint[]
}
export interface AddInvoiceRequest {
value: number
memo?: string
route_hints?: RouteHint[]
expiry?: number
}
type GreenlightAmountUnit = 'millisatoshi' | 'satoshi' | 'bitcoin'
interface GreenlightAmount {
unit: GreenlightAmountUnit
millisatoshi?: string
satoshi?: string
bitcoin?: string
}
interface GreenlightAddInvoiceRequest {
amount: GreenlightAmount
label: string
description: string
}
function makeLabel() {
return crypto.randomBytes(16).toString('hex').toUpperCase()
}
export function addInvoiceRequest(
req: AddInvoiceRequest
): AddInvoiceRequest | GreenlightAddInvoiceRequest {
if (IS_LND) return req
if (IS_GREENLIGHT) {
return <GreenlightAddInvoiceRequest>{
amount: { unit: 'satoshi', satoshi: req.value + '' },
label: makeLabel(),
description: req.memo,
}
}
return <AddInvoiceRequest>{}
}
export interface AddInvoiceResponse {
r_hash: Buffer
payment_request: string
add_index: number
}
enum GreenlightInvoiceStatus {
UNPAID = 0,
PAID = 1,
EXPIRED = 2,
}
interface GreenlightInvoice {
label: string
description: string
millisatoshi?: number
satoshi?: number
bitcoin?: number
status: GreenlightInvoiceStatus
payment_time: number
expiry_time: number
bolt11: string
payment_hash: Buffer
payment_preimage: Buffer
}
export function addInvoiceCommand(): string {
if (IS_LND) return 'addInvoice'
if (IS_GREENLIGHT) return 'createInvoice'
return 'addInvoice'
}
export function addInvoiceResponse(
res: AddInvoiceResponse | GreenlightInvoice
): AddInvoiceResponse {
if (IS_LND) return res as AddInvoiceResponse
if (IS_GREENLIGHT) {
const r = res as GreenlightInvoice
return <AddInvoiceResponse>{
payment_request: r.bolt11,
r_hash: r.payment_hash,
add_index: 0,
}
}
return <AddInvoiceResponse>{}
}
/* LIST CHANNELS */
interface ChannelConstraints {
csv_delay: number
chan_reserve_sat: number
dust_limit_sat: number
max_pending_amt_msat: number
min_htlc_msat: number
max_accepted_htlcs: number
}
interface HTLC {
// ...
}
interface Channel {
active: boolean
remote_pubkey: string
channel_point: string
chan_id: string
capacity: string
local_balance: string
remote_balance: string
commit_fee: string
commit_weight: string
fee_per_kw: string
unsettled_balance: number
total_satoshis_sent: number
total_satoshis_received: number
num_updates: number
pending_htlcs: HTLC[]
csv_delay: number
private: boolean
initiator: boolean
chan_status_flags: string
local_chan_reserve_sat: string
remote_chan_reserve_sat: string
lifetime: number
uptime: number
close_address: string
push_amount_sat: number
thaw_height: number
local_constraints: ChannelConstraints
remote_constraints: ChannelConstraints
}
export interface ListChannelsResponse {
channels: Channel[]
}
interface GreenlightHTLC {
direction: string
id: number
amount: string
expiry: number
payment_hash: string
state: string
local_trimmed: boolean
}
interface GreenlightChannel {
state: string
owner: string
short_channel_id: string
direction: number
channel_id: string
funding_txid: string
close_to_addr: string
close_to: string
private: boolean
total: string
dust_limit: string
spendable: string
receivable: string
their_to_self_delay: number
our_to_self_delay: number
status: string[]
htlcs: GreenlightHTLC[]
}
interface GreenlightPeer {
id: Buffer
connected: boolean
addresses: GreenlightAddress[]
features: string
channels: GreenlightChannel[]
}
interface GreenlightListPeersResponse {
peers: GreenlightPeer[]
}
export function listChannelsResponse(
res: ListChannelsResponse | GreenlightListPeersResponse
): ListChannelsResponse {
if (IS_LND) return res as ListChannelsResponse
if (IS_GREENLIGHT) {
const chans: Channel[] = []
;(res as GreenlightListPeersResponse).peers.forEach((p: GreenlightPeer) => {
p.channels.forEach((ch: GreenlightChannel, i: number) => {
chans.push(<Channel>{
active: ch.state === GreenlightChannelState.CHANNELD_NORMAL,
remote_pubkey: Buffer.from(p.id).toString('hex'),
channel_point: ch.funding_txid + ':' + i,
chan_id: shortChanIDtoInt64(ch.channel_id),
capacity: greelightNumber(ch.total) + '',
local_balance: greelightNumber(ch.spendable) + '',
remote_balance: greelightNumber(ch.receivable) + '',
})
})
})
return <ListChannelsResponse>{
channels: chans,
}
}
return <ListChannelsResponse>{}
}
export function listChannelsCommand(): string {
if (IS_LND) return 'listChannels'
if (IS_GREENLIGHT) return 'listPeers'
return 'listChannels'
}
export interface ListChannelsArgs {
active_only?: boolean
inactive_only?: boolean
peer?: string // HEX!
}
export function listChannelsRequest(args?: ListChannelsArgs): {
[k: string]: any
} {
const opts: { [k: string]: any } = args || {}
if (args && args.peer) {
if (IS_LND) opts.peer = ByteBuffer.fromHex(args.peer)
if (IS_GREENLIGHT) opts.node_id = args.peer
}
return opts
}
export interface ListPeersArgs {
node_id?: string
}
export function listPeersRequest(args?: ListPeersArgs): {
[k: string]: any
} {
const opts: { [k: string]: any } = args || {}
if (IS_GREENLIGHT && args && args.node_id) {
opts.node_id = ByteBuffer.fromHex(args.node_id)
}
return opts
}
interface Peer {
pub_key: string
address: string // eg `127.0.0.1:10011`
}
export interface ListPeersResponse {
peers: Peer[]
}
export function listPeersResponse(
res: ListPeersResponse | GreenlightListPeersResponse
): ListPeersResponse {
if (IS_LND) return res as ListPeersResponse
if (IS_GREENLIGHT) {
return <ListPeersResponse>{
peers: (res as GreenlightListPeersResponse).peers.map(
(p: GreenlightPeer) => {
const addy = p.addresses[0]
const peer: Peer = {
pub_key: Buffer.from(p.id).toString('hex'),
address: addy
? addy.port
? `${addy.addr}:${addy.port}`
: addy.addr
: '',
}
return peer
}
),
}
}
return <ListPeersResponse>{}
}
export type Buf = Buffer | ByteBuffer | ArrayBuffer
type DestCustomRecords = { [key: string]: Buf }
export interface KeysendRequest {
amt: number
final_cltv_delta: number
dest: Buf
dest_custom_records: DestCustomRecords
payment_hash: Buf
dest_features: number[]
route_hints?: RouteHint[]
fee_limit?: { [k: string]: number }
fee_limit_sat?: number
timeout_seconds?: number
}
interface GreenlightHop {
node_id: Buf
short_channel_id: string
fee_base?: string
fee_prop?: number
cltv_expiry_delta?: number
}
type GreenlightRoutehint = GreenlightHop[]
interface GreenlightTLV {
type: string
value: Buf
}
interface GreenlightKeysendRequest {
node_id: Buf
amount: GreenlightAmount
label: string
routehints?: GreenlightRoutehint[]
extratlvs?: GreenlightTLV[]
}
export function keysendRequest(
req: KeysendRequest
): KeysendRequest | GreenlightKeysendRequest {
if (IS_LND) return req
if (IS_GREENLIGHT) {
const r = <GreenlightKeysendRequest>{
node_id: req.dest,
amount: { unit: 'satoshi', satoshi: req.amt + '' },
label: makeLabel(),
}
if (req.route_hints) {
r.routehints = req.route_hints.map((rh) => {
const hops: GreenlightHop[] = rh.hop_hints.map((hh) => {
return <GreenlightHop>{
node_id: ByteBuffer.fromHex(hh.node_id),
short_channel_id: shortChanIDfromInt64(hh.chan_id),
fee_base: '1000',
fee_prop: 1,
cltv_expiry_delta: 40,
}
})
return hops
})
}
if (req.dest_custom_records) {
const dest_recs: GreenlightTLV[] = []
Object.entries(req.dest_custom_records).forEach(([type, value]) => {
if (type === `${LND_KEYSEND_KEY}`) return
dest_recs.push({ type, value })
})
r.extratlvs = dest_recs
}
return r
}
return <KeysendRequest>{}
}
interface Hop {
chan_id: string
chan_capacity: string
amt_to_forward: string
fee: string
expiry: number
amt_to_forward_msat: string
fee_msat: string
pub_key: string
custom_records: DestCustomRecords
}
export interface Route {
total_time_lock: number
total_fees: string // deprecated
total_amt: string // deprecated
hops: Hop[]
total_fees_msat: string
total_amt_msat: string
}
export interface SendPaymentResponse {
payment_error: string
payment_preimage: Buf
payment_route: Route
payment_hash: Buf
}
enum GreenlightPaymentStatus {
PENDING = 0,
COMPLETE = 1,
FAILED = 2,
}
export interface GreenlightPayment {
destination: Buf
payment_hash: Buf
payment_preimage: Buf
status: GreenlightPaymentStatus
amount: GreenlightAmount
amount_sent: GreenlightAmount
}
export function keysendResponse(
res: SendPaymentResponse | GreenlightPayment
): SendPaymentResponse {
if (IS_LND) return res as SendPaymentResponse
if (IS_GREENLIGHT) {
const r = res as GreenlightPayment
const route = <Route>{}
const { satoshi, millisatoshi } = greenlightAmoutToAmounts(r.amount)
route.total_amt = satoshi
route.total_amt_msat = millisatoshi
return <SendPaymentResponse>{
payment_error:
r.status === GreenlightPaymentStatus.FAILED ? 'payment failed' : '',
payment_preimage: r.payment_preimage,
payment_hash: r.payment_hash,
payment_route: route,
}
}
return <SendPaymentResponse>{}
}
export function subscribeCommand(): string {
if (IS_LND) return 'subscribeInvoices'
if (IS_GREENLIGHT) return 'streamIncoming'
return 'subscribeInvoices'
}
export enum InvoiceState {
OPEN = 'OPEN',
SETTLED = 'SETTLED',
CANCELED = 'CANCELED',
ACCEPTED = 'ACCEPTED',
}
enum InvoiceHTLCState {
ACCEPTED = 0,
SETTLED = 1,
CANCELED = 2,
}
interface InvoiceHTLC {
chan_id: string
htlc_index: number
amt_msat: string
accept_height: number
accept_time: string
resolve_time: string
expiry_height: number
state: InvoiceHTLCState
custom_records: DestCustomRecords
}
export interface Invoice {
memo: string
r_preimage: Buf
r_hash: Buf
value: string
value_msat: string
settled: boolean
creation_date: string
settle_date: string
payment_request: string
description_hash: Buf
expiry: string
fallback_addr: string
cltv_expiry: string
route_hints: RouteHint[]
private: boolean
add_index: string
settle_index: string
amt_paid: string
amt_paid_sat: string
amt_paid_msat: string
state: InvoiceState
htlcs: InvoiceHTLC[]
features: { [k: string]: any }
is_keysend: boolean
}
interface GreenlightOffchainPayment {
label: string
preimage: Buf
amount: GreenlightAmount
extratlvs: GreenlightTLV[]
payment_hash: Buf
bolt11: string
}
interface GreenlightIncomingPayment {
offchain: GreenlightOffchainPayment
}
export function subscribeResponse(
res: Invoice | GreenlightIncomingPayment
): Invoice {
if (IS_LND) return res as Invoice
if (IS_GREENLIGHT) {
const r1 = res as GreenlightIncomingPayment
if (!r1.offchain) return <Invoice>{}
const r = r1.offchain
const custom_records = <DestCustomRecords>{}
let is_keysend = false
if (r.extratlvs) {
r.extratlvs.forEach((tlv) => {
// console.log("TLV TYPE", tlv.type, typeof tlv.type, `${LND_KEYSEND_KEY}`)
// if(tlv.type===`${LND_KEYSEND_KEY}`) is_keysend=true
custom_records[tlv.type] = tlv.value
})
}
if (r.label.startsWith('keysend')) is_keysend = true
const i = <Invoice>{
memo: r.label,
r_preimage: r.preimage,
is_keysend,
htlcs: [<InvoiceHTLC>{ custom_records }],
state: InvoiceState.SETTLED,
r_hash: r.payment_hash,
payment_request: r.bolt11,
}
const { satoshi, millisatoshi } = greenlightAmoutToAmounts(r.amount)
i.value = satoshi
i.value_msat = millisatoshi
i.amt_paid_sat = satoshi
i.amt_paid_msat = millisatoshi
return i
}
return <Invoice>{}
}
export interface Addr {
pubkey: string
host: string
}
export interface ConnectPeerArgs {
addr: Addr
}
interface GreenlightConnectPeerArgs {
node_id: string
addr: string
}
export function connectPeerRequest(
req: ConnectPeerArgs
): ConnectPeerArgs | GreenlightConnectPeerArgs {
if (IS_LND) return req
if (IS_GREENLIGHT) {
return <GreenlightConnectPeerArgs>{
node_id: req.addr.pubkey,
addr: req.addr.host,
}
}
return <ConnectPeerArgs>{}
}
interface ConnectPeerResponse {}
interface GreenlightConnectPeerResponse {
node_id: string
features: string
}
export function connectPeerResponse(
res: ConnectPeerResponse | GreenlightConnectPeerResponse
): ConnectPeerResponse {
if (IS_LND) return res as ConnectPeerResponse
if (IS_GREENLIGHT) {
return <GreenlightConnectPeerResponse>{}
}
return <ConnectPeerResponse>{}
}
interface AmountsRes {
satoshi: string
millisatoshi: string
}
function greenlightAmoutToAmounts(a: GreenlightAmount): AmountsRes {
let satoshi = ''
let millisatoshi = ''
if (a.unit === 'satoshi') {
satoshi = a.satoshi || '0'
millisatoshi = parseInt(a.satoshi || '0') * 1000 + ''
} else if (a.unit === 'millisatoshi') {
satoshi = Math.floor(parseInt(a.millisatoshi || '0') / 1000) + ''
millisatoshi = a.millisatoshi + ''
}
return { satoshi, millisatoshi }
}
function greelightNumber(s: string): number {
if (s.endsWith('msat')) {
const s1 = s.substr(0, s.length - 4)
return Math.floor(parseInt(s1) / 1000)
}
if (s.endsWith('sat')) {
const s1 = s.substr(0, s.length - 3)
return parseInt(s1)
}
return 0
}
export function greenlightSignMessagePayload(msg: Buffer): string {
const type = 23
const length = msg.length
const typebuf = Buffer.allocUnsafe(2)
typebuf.writeUInt16BE(type, 0)
const lengthbuf = Buffer.allocUnsafe(2)
lengthbuf.writeUInt16BE(length, 0)
const buf = Buffer.concat([typebuf, lengthbuf, msg], 4 + length)
return buf.toString('hex')
}
enum GreenlightChannelState {
CHANNELD_AWAITING_LOCKIN = 'CHANNELD_AWAITING_LOCKIN',
/* Normal operating state. */
CHANNELD_NORMAL = 'CHANNELD_NORMAL',
/* We are closing, pending HTLC resolution. */
CHANNELD_SHUTTING_DOWN = 'CHANNELD_SHUTTING_DOWN',
/* Exchanging signatures on closing tx. */
CLOSINGD_SIGEXCHANGE = 'CLOSINGD_SIGEXCHANGE',
/* Waiting for onchain event. */
CLOSINGD_COMPLETE = 'CLOSINGD_COMPLETE',
/* Waiting for unilateral close to hit blockchain. */
AWAITING_UNILATERAL = 'AWAITING_UNILATERAL',
/* We've seen the funding spent, we're waiting for onchaind. */
FUNDING_SPEND_SEEN = 'FUNDING_SPEND_SEEN',
/* On chain */
ONCHAIN = 'ONCHAIN',
/* Final state after we have fully settled on-chain */
CLOSED = 'CLOSED',
/* For dual-funded channels, we start at a different state.
* We transition to 'awaiting lockin' after sigs have
* been exchanged */
DUALOPEND_OPEN_INIT = 'DUALOPEND_OPEN_INIT',
/* Dual-funded channel, waiting for lock-in */
DUALOPEND_AWAITING_LOCKIN = 'DUALOPEND_AWAITING_LOCKIN',
}
function shortChanIDfromInt64(int: string): string {
if (typeof int !== 'string') return ''
const l = long.fromString(int, true)
const blockHeight = l.shiftRight(40)
const txIndex = l.shiftRight(16).and(0xffffff)
const txPosition = l.and(0xffff)
if (IS_GREENLIGHT) {
return `${blockHeight.toString()}x${txIndex.toString()}x${txPosition.toString()}`
}
return `${blockHeight.toString()}:${txIndex.toString()}:${txPosition.toString()}`
}
function shortChanIDtoInt64(cid: string): string {
if (typeof cid !== 'string') return ''
if (!(cid.includes(':') || cid.includes('x'))) return ''
let a: string[] = []
const seps = [':', 'x']
for (const sep of seps) {
if (cid.includes(sep)) a = cid.split(sep)
}
if (!a) return ''
if (!Array.isArray(a)) return ''
if (!(a.length === 3)) return ''
const blockHeight = long.fromString(a[0], true).shiftLeft(40)
const txIndex = long.fromString(a[1], true).shiftLeft(16)
const txPosition = long.fromString(a[2], true)
return blockHeight.or(txIndex).or(txPosition).toString()
} | the_stack |
import "./types/fstream";
import {
readFile as readFileWithEncoding,
readFileSync as readFileWithEncodingSync,
stat,
writeFile as writeFileWithEncoding,
writeJson as writeJsonRaw,
createWriteStream
} from "fs-extra";
import { FStreamEntry, Reader } from "fstream";
import { Pack } from "tar";
import tarStream from "tar-stream";
import https, { Agent, request } from "https";
import zlib from "zlib";
import { request as httpRequest } from "http";
import { Readable as ReadableStream } from "stream";
import { StringDecoder } from "string_decoder";
import { parseJson, withoutStart, sleep, tryParseJson, isObject } from "./miscellany";
import { FS, Dir, InMemoryFS } from "./fs";
import { assertDefined } from "./assertions";
import { LoggerWithErrors } from "./logging";
export async function readFile(path: string): Promise<string> {
const res = await readFileWithEncoding(path, { encoding: "utf8" });
if (res.includes("�")) {
throw new Error(`Bad character in ${path}`);
}
return res;
}
export function readFileSync(path: string): string {
const res = readFileWithEncodingSync(path, { encoding: "utf8" });
if (res.includes("�")) {
throw new Error(`Bad character in ${path}`);
}
return res;
}
/** If a file doesn't exist, warn and tell the step it should have been generated by. */
export async function readFileAndWarn(generatedBy: string, filePath: string): Promise<object> {
try {
return await readJson(filePath, isObject);
} catch (e) {
console.error(`Run ${generatedBy} first!`);
throw e;
}
}
export function readJsonSync(path: string): unknown;
export function readJsonSync<T>(path: string, predicate: (parsed: unknown) => parsed is T): T;
export function readJsonSync<T>(path: string, predicate?: (parsed: unknown) => parsed is T) {
return parseJson(readFileSync(path), predicate);
}
export async function readJson(path: string): Promise<unknown>;
export async function readJson<T>(path: string, predicate: (parsed: unknown) => parsed is T): Promise<T>;
export async function readJson<T>(path: string, predicate?: (parsed: unknown) => parsed is T) {
return parseJson(await readFile(path), predicate);
}
export async function tryReadJson(path: string): Promise<unknown>;
export async function tryReadJson<T>(path: string, predicate: (parsed: unknown) => parsed is T): Promise<T | undefined>;
export async function tryReadJson<T>(path: string, predicate?: (parsed: unknown) => parsed is T) {
return tryParseJson(await readFile(path), predicate!);
}
export function writeFile(path: string, content: string): Promise<void> {
return writeFileWithEncoding(path, content, { encoding: "utf8" });
}
export function writeJson(path: string, content: unknown, formatted = true): Promise<void> {
return writeJsonRaw(path, content, { spaces: formatted ? 4 : 0 });
}
export function streamOfString(text: string): NodeJS.ReadableStream {
const s = new ReadableStream();
s.push(text);
s.push(null); // tslint:disable-line no-null-keyword
return s;
}
export function stringOfStream(stream: NodeJS.ReadableStream, description: string): Promise<string> {
const decoder = new StringDecoder("utf8");
let body = "";
stream.on("data", (data: Buffer) => {
body += decoder.write(data);
});
return new Promise<string>((resolve, reject) => {
stream.on("error", reject);
stream.on("end", () => {
body += decoder.end();
if (body.includes("�")) {
reject(`Bad character decode in ${description}`);
} else {
resolve(body);
}
});
});
}
export function streamDone(stream: NodeJS.WritableStream): Promise<void> {
return new Promise<void>((resolve, reject) => {
stream.on("error", reject).on("finish", resolve);
});
}
type FetchOptions = https.RequestOptions & {
readonly retries?: boolean | number;
readonly body?: string;
};
export class Fetcher {
private readonly agent = new Agent({ keepAlive: true });
async fetchJson(options: FetchOptions): Promise<unknown> {
const text = await this.fetch(options);
try {
return JSON.parse(text) as unknown;
} catch (e) {
throw new Error(`Bad response from server:\noptions: ${JSON.stringify(options)}\n\n${text}`);
}
}
async fetch(options: FetchOptions): Promise<string> {
const maxRetries =
options.retries === false || options.retries === undefined ? 0 : options.retries === true ? 10 : options.retries;
for (let retries = maxRetries; retries > 1; retries--) {
try {
return await doRequest(options, request, this.agent);
} catch (err) {
if (!/EAI_AGAIN|ETIMEDOUT|ECONNRESET/.test((err as Error).message)) {
throw err;
}
}
await sleep(1);
}
return doRequest(options, request, this.agent);
}
}
/** Only used for testing. */
export function makeHttpRequest(options: FetchOptions): Promise<string> {
return doRequest(options, httpRequest);
}
function doRequest(options: FetchOptions, makeRequest: typeof request, agent?: Agent): Promise<string> {
return new Promise((resolve, reject) => {
const req = makeRequest(
{
hostname: options.hostname,
port: options.port,
path: `/${options.path}`,
agent,
method: options.method || "GET",
headers: options.headers,
timeout: options.timeout ?? downloadTimeout
},
res => {
let text = "";
res.on("data", (d: string) => {
text += d;
});
res.on("error", reject);
res.on("end", () => {
resolve(text);
});
}
);
if (options.body !== undefined) {
req.write(options.body);
}
req.end();
});
}
export async function isDirectory(path: string): Promise<boolean> {
return (await stat(path)).isDirectory();
}
export const npmInstallFlags =
"--ignore-scripts --no-shrinkwrap --no-package-lock --no-bin-links --no-save --no-audit --no-fund";
const downloadTimeout = 1_000_000; // ms
const connectionTimeout = 800_000; // ms
export function downloadAndExtractFile(url: string, log: LoggerWithErrors): Promise<FS> {
return new Promise<FS>((resolve, reject) => {
const timeout = setTimeout(reject, downloadTimeout);
function rejectAndClearTimeout(reason?: any) {
clearTimeout(timeout);
return reject(reason);
}
const root = new Dir(undefined);
function insertFile(path: string, content: string): void {
const components = path.split("/");
const baseName = assertDefined(components.pop());
let dir = root;
for (const component of components) {
dir = dir.subdir(component);
}
dir.set(baseName, content);
}
log.info("Requesting " + url);
https
.get(url, { timeout: connectionTimeout }, response => {
if (response.statusCode !== 200) {
return rejectAndClearTimeout(
new Error(`DefinitelyTyped download failed with status code ${response.statusCode}`)
);
}
log.info("Getting " + url);
const extract = tarStream.extract();
interface Header {
readonly name: string;
readonly type: "file" | "directory";
}
extract.on("entry", (header: Header, stream: NodeJS.ReadableStream, next: () => void) => {
const name = assertDefined(withoutStart(header.name, "DefinitelyTyped-master/"));
switch (header.type) {
case "file":
stringOfStream(stream, name)
.then(s => {
insertFile(name, s);
next();
})
.catch(rejectAndClearTimeout);
break;
case "directory":
next();
break;
default:
throw new Error(`Unexpected file system entry kind ${header.type}`);
}
});
extract.on("error", rejectAndClearTimeout);
extract.on("finish", () => {
log.info("Done receiving " + url);
clearTimeout(timeout);
resolve(new InMemoryFS(root.finish(), ""));
});
response.pipe(zlib.createGunzip()).pipe(extract);
})
.on("error", rejectAndClearTimeout);
});
}
export function gzip(input: NodeJS.ReadableStream): NodeJS.ReadableStream {
return input.pipe(zlib.createGzip());
}
export function unGzip(input: NodeJS.ReadableStream): NodeJS.ReadableStream {
const output = zlib.createGunzip();
input.pipe(output);
return output;
}
export function writeTgz(inputDirectory: string, outFileName: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
resolve(streamDone(createTgz(inputDirectory, reject).pipe(createWriteStream(outFileName))));
});
}
// To output this for testing:
// `require("./dist/io").createTgz("./src", err => { throw err }).pipe(fs.createWriteStream("foo.tgz"))`
export function createTgz(dir: string, onError: (error: Error) => void): NodeJS.ReadableStream {
return gzip(createTar(dir, onError));
}
function createTar(dir: string, onError: (error: Error) => void): NodeJS.ReadableStream {
const packer = Pack({ noProprietary: true, path: dir }).on("error", onError);
return Reader({ path: dir, type: "Directory", filter: addDirectoryExecutablePermission })
.on("error", onError)
.pipe(packer);
}
/**
* Work around a bug where directories bundled on Windows do not have executable permission when extracted on Linux.
* https://github.com/npm/node-tar/issues/7#issuecomment-17572926
*/
function addDirectoryExecutablePermission(entry: FStreamEntry): boolean {
if (entry.props.type === "Directory") {
entry.props.mode = addExecutePermissionsFromReadPermissions(entry.props.mode);
}
return true;
}
function addExecutePermissionsFromReadPermissions(mode: number): number {
// Constant that gives execute permissions to owner, group, and others. "+x"
const allExecutePermissions = 0o111;
// Moves the bits for read permissions into the place for execute permissions.
// In other words, a component will have execute permissions if it has read permissions.
const readPermissionsAsExecutePermissions = (mode >>> 2) & allExecutePermissions; // tslint:disable-line no-bitwise
// Add these additional execute permissions to the mode.
return mode | readPermissionsAsExecutePermissions; // tslint:disable-line no-bitwise
} | the_stack |
import * as path from "path";
import * as vscode from "vscode";
import { IConfig, retryDownloadConfig } from "../remoteConfigHelper";
import { TelemetryHelper } from "../../../common/telemetryHelper";
import { Telemetry } from "../../../common/telemetry";
import { ExtensionConfigManager } from "../../extensionConfigManager";
import { findFileInFolderHierarchy } from "../../../common/extensionHelper";
import { SettingsHelper } from "../../settingsHelper";
import { OutputChannelLogger } from "../../log/OutputChannelLogger";
import { areSameDates, getRandomIntInclusive } from "../../../common/utils";
import tipsStorage from "./tipsStorage";
enum TipNotificationAction {
GET_MORE_INFO = "tipsMoreInfo",
DO_NOT_SHOW_AGAIN = "tipsDoNotShow",
SHOWN = "tipShown",
}
export interface TipNotificationConfig extends IConfig {
firstTimeMinDaysToRemind: number;
firstTimeMaxDaysToRemind: number;
minDaysToRemind: number;
maxDaysToRemind: number;
daysAfterLastUsage: number;
}
export interface TipInfo {
knownDate?: Date;
shownDate?: Date;
}
export interface Tips {
[tipId: string]: TipInfo;
}
export interface AllTips {
generalTips: Tips;
specificTips: Tips;
}
export interface TipsConfig extends TipNotificationConfig {
daysLeftBeforeGeneralTip: number;
lastExtensionUsageDate?: Date;
allTipsShownFirstly: boolean;
tips: AllTips;
}
export interface GeneratedTipResponse {
selection: string | undefined;
tipKey: string;
}
export class TipNotificationService implements vscode.Disposable {
private static instance: TipNotificationService;
private readonly TIPS_NOTIFICATIONS_LOG_CHANNEL_NAME: string;
private readonly TIPS_CONFIG_NAME: string;
private readonly endpointURL: string;
private readonly downloadConfigRequest: Promise<TipNotificationConfig>;
private readonly getMoreInfoButtonText: string;
private readonly doNotShowTipsAgainButtonText: string;
private cancellationTokenSource: vscode.CancellationTokenSource;
private _tipsConfig: TipsConfig | null;
private logger: OutputChannelLogger;
private showTips: boolean;
public static getInstance(): TipNotificationService {
if (!TipNotificationService.instance) {
TipNotificationService.instance = new TipNotificationService();
}
return TipNotificationService.instance;
}
public dispose(): void {
this.cancellationTokenSource.cancel();
this.cancellationTokenSource.dispose();
}
private constructor() {
this.endpointURL =
"https://microsoft.github.io/vscode-react-native/tipsNotifications/tipsNotificationsConfig.json";
this.TIPS_NOTIFICATIONS_LOG_CHANNEL_NAME = "Tips Notifications";
this.TIPS_CONFIG_NAME = "tipsConfig";
this.getMoreInfoButtonText = "Get more info";
this.doNotShowTipsAgainButtonText = "Don't show tips again";
this.cancellationTokenSource = new vscode.CancellationTokenSource();
this._tipsConfig = null;
this.downloadConfigRequest = retryDownloadConfig<TipNotificationConfig>(
this.endpointURL,
this.cancellationTokenSource,
);
this.showTips = SettingsHelper.getShowTips();
this.logger = OutputChannelLogger.getChannel(
this.TIPS_NOTIFICATIONS_LOG_CHANNEL_NAME,
true,
);
}
public async showTipNotification(
isGeneralTip: boolean = true,
specificTipKey?: string,
): Promise<void> {
if (!isGeneralTip && !specificTipKey) {
this.logger.debug("The specific tip key parameter isn't passed for a specific tip");
return;
}
await this.initializeTipsConfig();
if (!this.showTips) {
return;
}
const curDate: Date = new Date();
let tipResponse: GeneratedTipResponse | undefined;
if (isGeneralTip) {
this.deleteOutdatedKnownDate();
if (this.tipsConfig.daysLeftBeforeGeneralTip === 0) {
tipResponse = await this.showRandomGeneralTipNotification();
} else if (
this.tipsConfig.lastExtensionUsageDate &&
!areSameDates(curDate, this.tipsConfig.lastExtensionUsageDate)
) {
this.tipsConfig.daysLeftBeforeGeneralTip--;
}
} else {
tipResponse = await this.showSpecificTipNotification(<string>specificTipKey);
}
if (tipResponse) {
await this.handleUserActionOnTip(tipResponse, isGeneralTip);
}
this.tipsConfig.lastExtensionUsageDate = curDate;
ExtensionConfigManager.config.set(this.TIPS_CONFIG_NAME, this.tipsConfig);
}
public async setKnownDateForFeatureById(
key: string,
isGeneralTip: boolean = true,
): Promise<void> {
await this.initializeTipsConfig();
if (isGeneralTip) {
this.tipsConfig.tips.generalTips[key].knownDate = new Date();
} else {
this.tipsConfig.tips.specificTips[key].knownDate = new Date();
}
ExtensionConfigManager.config.set(this.TIPS_CONFIG_NAME, this.tipsConfig);
}
public updateTipsConfig(): void {
if (!ExtensionConfigManager.config.has(this.TIPS_CONFIG_NAME)) {
return;
}
const tipsConfig = this.tipsConfig;
tipsConfig.tips.generalTips = this.updateConfigTipsFromStorage(
tipsStorage.generalTips,
tipsConfig.tips.generalTips,
);
tipsConfig.tips.specificTips = this.updateConfigTipsFromStorage(
tipsStorage.specificTips,
tipsConfig.tips.specificTips,
);
this._tipsConfig = tipsConfig;
ExtensionConfigManager.config.set(this.TIPS_CONFIG_NAME, tipsConfig);
}
private updateConfigTipsFromStorage(
storageTips: Record<string, unknown>,
configTips: Tips,
): Tips {
// eslint-disable-next-line no-restricted-syntax
for (const key in configTips) {
if (!(key in storageTips)) {
delete configTips[key];
}
}
// eslint-disable-next-line no-restricted-syntax
for (const key in storageTips) {
if (!(key in configTips)) {
configTips[key] = {};
}
}
return configTips;
}
private get tipsConfig(): TipsConfig {
if (!this._tipsConfig) {
if (!ExtensionConfigManager.config.has(this.TIPS_CONFIG_NAME)) {
throw new Error("Could not find Tips config in the config store.");
} else {
this._tipsConfig = this.parseDatesInRawConfig(
ExtensionConfigManager.config.get(this.TIPS_CONFIG_NAME),
);
}
}
return this._tipsConfig;
}
private async handleUserActionOnTip(
tipResponse: GeneratedTipResponse,
isGeneralTip: boolean,
): Promise<void> {
const { selection, tipKey } = tipResponse;
if (selection === this.getMoreInfoButtonText) {
this.sendTipNotificationActionTelemetry(tipKey, TipNotificationAction.GET_MORE_INFO);
const readmeFile: string | null = findFileInFolderHierarchy(__dirname, "README.md");
if (readmeFile) {
const anchorLink: string = isGeneralTip
? this.getGeneralTipNotificationAnchorLinkByKey(tipKey)
: this.getSpecificTipNotificationAnchorLinkByKey(tipKey);
const uriFile = vscode.Uri.parse(
path.normalize(`file://${readmeFile}${anchorLink}`),
);
void vscode.commands.executeCommand("markdown.showPreview", uriFile);
}
}
if (selection === this.doNotShowTipsAgainButtonText) {
this.sendTipNotificationActionTelemetry(
tipKey,
TipNotificationAction.DO_NOT_SHOW_AGAIN,
);
this.showTips = false;
await SettingsHelper.setShowTips(this.showTips);
}
}
private async initializeTipsConfig(): Promise<void> {
this.showTips = SettingsHelper.getShowTips();
if (this._tipsConfig) {
return;
}
let tipsConfig: TipsConfig;
if (!ExtensionConfigManager.config.has(this.TIPS_CONFIG_NAME)) {
tipsConfig = {
daysLeftBeforeGeneralTip: 0,
firstTimeMinDaysToRemind: 3,
firstTimeMaxDaysToRemind: 6,
minDaysToRemind: 6,
maxDaysToRemind: 10,
daysAfterLastUsage: 30,
allTipsShownFirstly: false,
tips: {
generalTips: {},
specificTips: {},
},
};
tipsConfig = await this.mergeRemoteConfigToLocal(tipsConfig);
Object.keys(tipsStorage.generalTips).forEach(key => {
tipsConfig.tips.generalTips[key] = {};
});
Object.keys(tipsStorage.specificTips).forEach(key => {
tipsConfig.tips.specificTips[key] = {};
});
ExtensionConfigManager.config.set(this.TIPS_CONFIG_NAME, tipsConfig);
} else {
tipsConfig = this.parseDatesInRawConfig(
ExtensionConfigManager.config.get(this.TIPS_CONFIG_NAME),
);
}
this._tipsConfig = tipsConfig;
}
private async showRandomGeneralTipNotification(): Promise<GeneratedTipResponse> {
let generalTipsForRandom: Array<string>;
const generalTips: Tips = this.tipsConfig.tips.generalTips;
const generalTipsKeys: Array<string> = Object.keys(this.tipsConfig.tips.generalTips);
if (!this.tipsConfig.allTipsShownFirstly) {
generalTipsForRandom = generalTipsKeys.filter(
tipId => !generalTips[tipId].knownDate && !generalTips[tipId].shownDate,
);
if (generalTipsForRandom.length === 1) {
this.tipsConfig.allTipsShownFirstly = true;
}
} else {
generalTipsForRandom = generalTipsKeys.sort(
(tipId1, tipId2) =>
// According to ECMAScript standard: The exact moment of midnight at the beginning of
// 01 January, 1970 UTC is represented by the value +0.
(generalTips[tipId2].shownDate ?? new Date(+0)).getTime() -
(generalTips[tipId1].shownDate ?? new Date(+0)).getTime(),
);
}
let leftIndex: number;
switch (generalTipsForRandom.length) {
case 0:
return {
selection: undefined,
tipKey: "",
};
case 1:
leftIndex = 0;
break;
case 2:
leftIndex = 1;
break;
default:
leftIndex = 2;
}
const randIndex: number = getRandomIntInclusive(leftIndex, generalTipsForRandom.length - 1);
const selectedGeneralTipKey: string = generalTipsForRandom[randIndex];
const tipNotificationText = this.getGeneralTipNotificationTextByKey(selectedGeneralTipKey);
this.tipsConfig.tips.generalTips[selectedGeneralTipKey].shownDate = new Date();
this._tipsConfig = await this.mergeRemoteConfigToLocal(this.tipsConfig);
const daysBeforeNextTip: number = this.tipsConfig.allTipsShownFirstly
? getRandomIntInclusive(
this.tipsConfig.minDaysToRemind,
this.tipsConfig.maxDaysToRemind,
)
: getRandomIntInclusive(
this.tipsConfig.firstTimeMinDaysToRemind,
this.tipsConfig.firstTimeMaxDaysToRemind,
);
this.tipsConfig.daysLeftBeforeGeneralTip = daysBeforeNextTip;
ExtensionConfigManager.config.set(this.TIPS_CONFIG_NAME, this.tipsConfig);
this.sendShowTipNotificationTelemetry(selectedGeneralTipKey);
return {
selection: await vscode.window.showInformationMessage(
tipNotificationText,
...[this.getMoreInfoButtonText, this.doNotShowTipsAgainButtonText],
),
tipKey: selectedGeneralTipKey,
};
}
private async showSpecificTipNotification(
tipKey: string,
): Promise<GeneratedTipResponse | undefined> {
if (this.tipsConfig.tips.specificTips[tipKey].shownDate) {
return;
}
const tipNotificationText = this.getSpecificTipNotificationTextByKey(tipKey);
this.tipsConfig.tips.specificTips[tipKey].shownDate = new Date();
ExtensionConfigManager.config.set(this.TIPS_CONFIG_NAME, this.tipsConfig);
this.sendShowTipNotificationTelemetry(tipKey);
return {
selection: await vscode.window.showInformationMessage(
tipNotificationText,
...[this.getMoreInfoButtonText, this.doNotShowTipsAgainButtonText],
),
tipKey,
};
}
private async mergeRemoteConfigToLocal(tipsConfig: TipsConfig): Promise<TipsConfig> {
const remoteConfig = await this.downloadConfigRequest;
tipsConfig.firstTimeMinDaysToRemind = remoteConfig.firstTimeMinDaysToRemind;
tipsConfig.firstTimeMaxDaysToRemind = remoteConfig.firstTimeMaxDaysToRemind;
tipsConfig.minDaysToRemind = remoteConfig.minDaysToRemind;
tipsConfig.maxDaysToRemind = remoteConfig.maxDaysToRemind;
tipsConfig.daysAfterLastUsage = remoteConfig.daysAfterLastUsage;
return tipsConfig;
}
private getGeneralTipNotificationTextByKey(key: string): string {
return tipsStorage.generalTips[key].text;
}
private getSpecificTipNotificationTextByKey(key: string): string {
return tipsStorage.specificTips[key].text;
}
private getGeneralTipNotificationAnchorLinkByKey(key: string): string {
return tipsStorage.generalTips[key].anchorLink;
}
private getSpecificTipNotificationAnchorLinkByKey(key: string): string {
return tipsStorage.specificTips[key].anchorLink;
}
private deleteOutdatedKnownDate(): void {
const dateNow: Date = new Date();
const generalTips: Tips = this.tipsConfig.tips.generalTips;
const generalTipsKeys: Array<string> = Object.keys(this.tipsConfig.tips.generalTips);
generalTipsKeys
.filter(tipKey => {
const knownDate = generalTips[tipKey].knownDate ?? new Date();
return (
generalTips[tipKey].knownDate &&
this.getDifferenceInDays(knownDate, dateNow) >
this.tipsConfig.daysAfterLastUsage
);
})
.forEach(tipKey => {
delete generalTips[tipKey].knownDate;
});
}
private getDifferenceInDays(date1: Date, date2: Date): number {
const diffInMs = Math.abs(date2.getTime() - date1.getTime());
return diffInMs / (1000 * 60 * 60 * 24);
}
private parseDatesInRawConfig(rawTipsConfig: TipsConfig): TipsConfig {
if (rawTipsConfig.lastExtensionUsageDate) {
rawTipsConfig.lastExtensionUsageDate = new Date(rawTipsConfig.lastExtensionUsageDate);
}
const parseDatesInTips = (tipsKeys: string[], tipsType: "generalTips" | "specificTips") => {
tipsKeys.forEach(tipKey => {
const tip = rawTipsConfig.tips[tipsType][tipKey];
if (tip.knownDate) {
rawTipsConfig.tips[tipsType][tipKey].knownDate = new Date(tip.knownDate);
}
if (tip.shownDate) {
if (tip.shownDate) {
rawTipsConfig.tips[tipsType][tipKey].shownDate = new Date(tip.shownDate);
}
}
});
};
parseDatesInTips(Object.keys(rawTipsConfig.tips.specificTips), "specificTips");
parseDatesInTips(Object.keys(rawTipsConfig.tips.generalTips), "generalTips");
return rawTipsConfig;
}
private sendShowTipNotificationTelemetry(tipKey: string): void {
const showTipNotificationEvent = TelemetryHelper.createTelemetryEvent(
"showTipNotification",
{
tipKey,
},
);
Telemetry.send(showTipNotificationEvent);
}
private sendTipNotificationActionTelemetry(
tipKey: string,
tipNotificationAction: TipNotificationAction,
): void {
const tipNotificationActionEvent = TelemetryHelper.createTelemetryEvent(
"tipNotificationAction",
{
tipKey,
tipNotificationAction,
},
);
Telemetry.send(tipNotificationActionEvent);
}
} | the_stack |
import * as React from 'react';
import { Color } from '../../mol-util/color';
import { Icon, ArrowRightSvg, ArrowDropDownSvg, RemoveSvg, AddSvg } from './icons';
export type ColorAccent = 'cyan' | 'red' | 'gray' | 'green' | 'purple' | 'blue' | 'orange'
export class ControlGroup extends React.Component<{
header: string,
title?: string,
initialExpanded?: boolean,
hideExpander?: boolean,
hideOffset?: boolean,
topRightIcon?: React.FC,
headerLeftMargin?: string,
onHeaderClick?: () => void,
noTopMargin?: boolean,
childrenClassName?: string,
maxHeight?: string
}, { isExpanded: boolean }> {
state = { isExpanded: !!this.props.initialExpanded }
headerClicked = () => {
if (this.props.onHeaderClick) {
this.props.onHeaderClick();
} else {
this.setState({ isExpanded: !this.state.isExpanded });
}
}
render() {
let groupClassName = this.props.hideOffset ? 'msp-control-group-children' : 'msp-control-group-children msp-control-offset';
if (this.props.childrenClassName) groupClassName += ' ' + this.props.childrenClassName;
// TODO: customize header style (bg color, togle button etc)
return <div className='msp-control-group-wrapper' style={{ position: 'relative', marginTop: this.props.noTopMargin ? 0 : void 0 }}>
<div className='msp-control-group-header' style={{ marginLeft: this.props.headerLeftMargin }} title={this.props.title}>
<Button onClick={this.headerClicked}>
{!this.props.hideExpander && <Icon svg={this.state.isExpanded ? ArrowRightSvg : ArrowDropDownSvg} />}
{this.props.topRightIcon && <Icon svg={this.props.topRightIcon} style={{ position: 'absolute', right: '2px', top: 0 }} />}
<b>{this.props.header}</b>
</Button>
</div>
{this.state.isExpanded && <div className={groupClassName} style={{ display: this.state.isExpanded ? 'block' : 'none', maxHeight: this.props.maxHeight, overflow: 'hidden', overflowY: 'auto' }}>
{this.props.children}
</div>}
</div>;
}
}
export interface TextInputProps<T> {
className?: string,
style?: React.CSSProperties,
value: T,
fromValue?(v: T): string,
toValue?(s: string): T,
// TODO: add error/help messages here?
isValid?(s: string): boolean,
onChange(value: T): void,
onEnter?(): void,
onBlur?(): void,
delayMs?: number,
blurOnEnter?: boolean,
blurOnEscape?: boolean,
isDisabled?: boolean,
placeholder?: string,
numeric?: boolean
}
interface TextInputState {
originalValue: string,
value: string
}
function _id(x: any) { return x; }
export class TextInput<T = string> extends React.PureComponent<TextInputProps<T>, TextInputState> {
private input = React.createRef<HTMLInputElement>();
private delayHandle: any = void 0;
private pendingValue: T | undefined = void 0;
state = { originalValue: '', value: '' }
onBlur = () => {
this.setState({ value: '' + this.state.originalValue });
if (this.props.onBlur) this.props.onBlur();
}
get isPending() { return typeof this.delayHandle !== 'undefined'; }
clearTimeout() {
if (this.isPending) {
clearTimeout(this.delayHandle);
this.delayHandle = void 0;
}
}
raiseOnChange = () => {
if (this.pendingValue === void 0) return;
this.props.onChange(this.pendingValue!);
this.pendingValue = void 0;
}
triggerChanged(formatted: string, converted: T) {
this.clearTimeout();
if (formatted === this.state.originalValue) return;
if (this.props.delayMs) {
this.pendingValue = converted;
this.delayHandle = setTimeout(this.raiseOnChange, this.props.delayMs);
} else {
this.props.onChange(converted);
}
}
onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
const isInvalid = (this.props.isValid && !this.props.isValid(value)) || (this.props.numeric && Number.isNaN(+value));
if (isInvalid) {
this.clearTimeout();
this.setState({ value });
return;
}
if (this.props.numeric) {
this.setState({ value }, () => this.triggerChanged(value, +value as any));
} else {
const converted = (this.props.toValue || _id)(value);
const formatted = (this.props.fromValue || _id)(converted);
this.setState({ value: formatted }, () => this.triggerChanged(formatted, converted));
}
}
onKeyUp = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.charCode === 27 || e.keyCode === 27 || e.key === 'Escape') {
if (this.props.blurOnEscape && this.input.current) {
this.input.current.blur();
}
}
}
onKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.keyCode === 13 || e.charCode === 13 || e.key === 'Enter') {
if (this.isPending) {
this.clearTimeout();
this.raiseOnChange();
}
if (this.props.blurOnEnter && this.input.current) {
this.input.current.blur();
}
if (this.props.onEnter) this.props.onEnter();
}
e.stopPropagation();
}
static getDerivedStateFromProps(props: TextInputProps<any>, state: TextInputState) {
const value = props.fromValue ? props.fromValue(props.value) : props.value;
if (value === state.originalValue) return null;
return { originalValue: value, value };
}
render() {
return <input type='text'
className={this.props.className}
style={this.props.style}
ref={this.input}
onBlur={this.onBlur}
value={this.state.value}
placeholder={this.props.placeholder}
onChange={this.onChange}
onKeyPress={this.props.onEnter || this.props.blurOnEnter || this.props.blurOnEscape ? this.onKeyPress : void 0}
onKeyDown={this.props.blurOnEscape ? this.onKeyUp : void 0}
disabled={!!this.props.isDisabled}
/>;
}
}
export class ExpandableControlRow extends React.Component<{
label: string,
colorStripe?: Color,
pivot: JSX.Element,
controls: JSX.Element
}, { isExpanded: boolean }> {
state = { isExpanded: false };
toggleExpanded = () => this.setState({ isExpanded: !this.state.isExpanded });
render() {
const { label, pivot, controls } = this.props;
// TODO: fix the inline CSS
return <>
<ControlRow label={<>
{label}
<button className='msp-btn-link msp-btn-icon msp-control-group-expander' onClick={this.toggleExpanded} title={`${this.state.isExpanded ? 'Less' : 'More'} options`}
style={{ background: 'transparent', textAlign: 'left', padding: '0' }}>
<Icon svg={this.state.isExpanded ? RemoveSvg : AddSvg} style={{ display: 'inline-block' }} />
</button>
</>} control={pivot}>
{this.props.colorStripe && <div className='msp-expandable-group-color-stripe' style={{ backgroundColor: Color.toStyle(this.props.colorStripe) }} />}
</ControlRow>
{this.state.isExpanded && <div className='msp-control-offset'>
{controls}
</div>}
</>;
}
}
export function SectionHeader(props: { icon?: React.FC, title: string | JSX.Element, desc?: string, accent?: ColorAccent }) {
return <div className={`msp-section-header${props.accent ? ' msp-transform-header-brand-' + props.accent : ''}` }>
{props.icon && <Icon svg={props.icon} />}
{props.title} <small>{props.desc}</small>
</div>;
}
export type ButtonProps = {
style?: React.CSSProperties,
className?: string,
disabled?: boolean,
title?: string,
icon?: React.FC,
commit?: boolean | 'on' | 'off'
children?: React.ReactNode,
onClick?: (e: React.MouseEvent<HTMLButtonElement>) => void,
onContextMenu?: (e: React.MouseEvent<HTMLButtonElement>) => void,
onMouseEnter?: (e: React.MouseEvent<HTMLButtonElement>) => void,
onMouseLeave?: (e: React.MouseEvent<HTMLButtonElement>) => void,
inline?: boolean,
'data-id'?: string,
'data-color'?: Color,
flex?: boolean | string | number,
noOverflow?: boolean
}
export function Button(props: ButtonProps) {
let className = 'msp-btn';
if (!props.inline) className += ' msp-btn-block';
if (props.noOverflow) className += ' msp-no-overflow';
if (props.flex) className += ' msp-flex-item';
if (props.commit === 'on' || props.commit) className += ' msp-btn-commit msp-btn-commit-on';
if (props.commit === 'off') className += ' msp-btn-commit msp-btn-commit-off';
if (!props.children) className += ' msp-btn-childless';
if (props.className) className += ' ' + props.className;
let style: React.CSSProperties | undefined = void 0;
if (props.flex) {
if (typeof props.flex === 'number') style = { flex: `0 0 ${props.flex}px`, padding: 0, maxWidth: `${props.flex}px` };
else if (typeof props.flex === 'string') style = { flex: `0 0 ${props.flex}`, padding: 0, maxWidth: props.flex };
}
if (props.style) {
if (style) Object.assign(style, props.style);
else style = props.style;
}
return <button onClick={props.onClick} title={props.title} disabled={props.disabled} style={style} className={className} data-id={props['data-id']} data-color={props['data-color']}
onContextMenu={props.onContextMenu} onMouseEnter={props.onMouseEnter} onMouseLeave={props.onMouseLeave}>
{props.icon && <Icon svg={props.icon} />}
{props.children}
</button>;
}
export function IconButton(props: {
svg?: React.FC,
small?: boolean,
onClick: (e: React.MouseEvent<HTMLButtonElement>) => void,
title?: string,
toggleState?: boolean,
disabled?: boolean,
className?: string,
style?: React.CSSProperties,
'data-id'?: string,
extraContent?: JSX.Element,
flex?: boolean | string | number,
transparent?: boolean
}) {
let className = `msp-btn msp-btn-icon${props.small ? '-small' : ''}${props.className ? ' ' + props.className : ''}`;
if (typeof props.toggleState !== 'undefined') {
className += ` msp-btn-link-toggle-${props.toggleState ? 'on' : 'off'}`;
}
if (props.transparent) {
className += ' msp-transparent-bg';
}
let style: React.CSSProperties | undefined = void 0;
if (props.flex) {
if (typeof props.flex === 'boolean') style = { flex: '0 0 32px', padding: 0 };
else if (typeof props.flex === 'number') style = { flex: `0 0 ${props.flex}px`, padding: 0, maxWidth: `${props.flex}px` };
else style = { flex: `0 0 ${props.flex}`, padding: 0, maxWidth: props.flex };
}
if (props.style) {
if (style) Object.assign(style, props.style);
else style = props.style;
}
return <button className={className} onClick={props.onClick} title={props.title} disabled={props.disabled} data-id={props['data-id']} style={style}>
{props.svg && <Icon svg={props.svg} />}
{props.extraContent}
</button>;
}
export type ToggleButtonProps = {
style?: React.CSSProperties,
inline?: boolean,
className?: string,
disabled?: boolean,
label?: string | JSX.Element,
title?: string,
icon?: React.FC,
isSelected?: boolean,
toggle: () => void
}
export class ToggleButton extends React.PureComponent<ToggleButtonProps> {
onClick = (e: React.MouseEvent<HTMLButtonElement>) => {
e.currentTarget.blur();
this.props.toggle();
}
render() {
const props = this.props;
const label = props.label;
const className = props.isSelected ? `${props.className || ''} msp-control-current` : props.className;
return <Button icon={this.props.icon} onClick={this.onClick} title={this.props.title} inline={this.props.inline}
disabled={props.disabled} style={props.style} className={className}>
{label && this.props.isSelected ? <b>{label}</b> : label}
</Button>;
}
}
export class ExpandGroup extends React.PureComponent<{ header: string, headerStyle?: React.CSSProperties, initiallyExpanded?: boolean, accent?: boolean, noOffset?: boolean, marginTop?: 0 | string, headerLeftMargin?: string }, { isExpanded: boolean }> {
state = { isExpanded: !!this.props.initiallyExpanded };
toggleExpanded = () => this.setState({ isExpanded: !this.state.isExpanded });
render() {
return <>
<div className='msp-control-group-header' style={{ marginTop: this.props.marginTop !== void 0 ? this.props.marginTop : '1px', marginLeft: this.props.headerLeftMargin }}>
<button className='msp-btn msp-form-control msp-btn-block' onClick={this.toggleExpanded} style={this.props.headerStyle}>
<Icon svg={this.state.isExpanded ? ArrowDropDownSvg : ArrowRightSvg} />
{this.props.header}
</button>
</div>
{this.state.isExpanded &&
(this.props.noOffset
? this.props.children
: <div className={this.props.accent ? 'msp-accent-offset' : 'msp-control-offset'}>
{this.props.children}
</div>)}
</>;
}
}
export type ControlRowProps = {
title?: string,
label?: React.ReactNode,
control?: React.ReactNode,
className?: string,
children?: React.ReactNode
}
export function ControlRow(props: ControlRowProps) {
let className = 'msp-control-row';
if (props.className) className += ' ' + props.className;
return <div className={className}>
<span className='msp-control-row-label' title={props.title}>{props.label}</span>
<div className='msp-control-row-ctrl'>{props.control}</div>
{props.children}
</div>;
} | the_stack |
class DicomTags {
/// <summary>
/// <para>(0000,0002) Affected SOP Class UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static AffectedSopClassUid: number = 2;
/// <summary>
/// <para>(0000,0003) Requested SOP Class UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static RequestedSopClassUid: number = 3;
/// <summary>
/// <para>(0000,0100) Command Field</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static CommandField: number = 256;
/// <summary>
/// <para>(0000,0110) Message ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static MessageId: number = 272;
/// <summary>
/// <para>(0000,0120) Message ID Being Responded To</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static MessageIdBeingRespondedTo: number = 288;
/// <summary>
/// <para>(0000,0600) Move Destination</para>
/// <para> VR: AE VM:1</para>
/// </summary>
public static MoveDestination: number = 1536;
/// <summary>
/// <para>(0000,0700) Priority</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static Priority: number = 1792;
/// <summary>
/// <para>(0000,0800) Data Set Type</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static DataSetType: number = 2048;
/// <summary>
/// <para>(0000,0900) Status</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static Status: number = 2304;
/// <summary>
/// <para>(0000,0901) Offending Element</para>
/// <para> VR: AT VM:1-n</para>
/// </summary>
public static OffendingElement: number = 2305;
/// <summary>
/// <para>(0000,0902) Error Comment</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ErrorComment: number = 2306;
/// <summary>
/// <para>(0000,0903) Error ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ErrorId: number = 2307;
/// <summary>
/// <para>(0000,1000) Affected SOP Instance UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static AffectedSopInstanceUid: number = 4096;
/// <summary>
/// <para>(0000,1001) Requested SOP Instance UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static RequestedSopInstanceUid: number = 4097;
/// <summary>
/// <para>(0000,1002) Event Type ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static EventTypeId: number = 4098;
/// <summary>
/// <para>(0000,1005) Attribute Identifier List</para>
/// <para> VR: AT VM:1-n</para>
/// </summary>
public static AttributeIdentifierList: number = 4101;
/// <summary>
/// <para>(0000,1008) Action Type ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ActionTypeId: number = 4104;
/// <summary>
/// <para>(0000,1020) Number of Remaining Sub-operations</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfRemainingSubOperations: number = 4128;
/// <summary>
/// <para>(0000,1021) Number of Completed Sub-operations</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfCompletedSubOperations: number = 4129;
/// <summary>
/// <para>(0000,1022) Number of Failed Sub-operations</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfFailedSubOperations: number = 4130;
/// <summary>
/// <para>(0000,1023) Number of Warning Sub-operations</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfWarningSubOperations: number = 4131;
/// <summary>
/// <para>(0000,1030) Move Originator Application Entity Title</para>
/// <para> VR: AE VM:1</para>
/// </summary>
public static MoveOriginatorApplicationEntityTitle: number = 4144;
/// <summary>
/// <para>(0000,1031) Move Originator Message ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static MoveOriginatorMessageId: number = 4145;
/// <summary>
/// <para>(0002,0000) File Meta Information Group Length</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static FileMetaInformationGroupLength: number = 131072;
/// <summary>
/// <para>(0002,0001) File Meta Information Version</para>
/// <para> VR: OB VM:1</para>
/// </summary>
public static FileMetaInformationVersion: number = 131073;
/// <summary>
/// <para>(0002,0002) Media Storage SOP Class UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static MediaStorageSopClassUid: number = 131074;
/// <summary>
/// <para>(0002,0003) Media Storage SOP Instance UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static MediaStorageSopInstanceUid: number = 131075;
/// <summary>
/// <para>(0002,0010) Transfer Syntax UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static TransferSyntaxUid: number = 131088;
/// <summary>
/// <para>(0002,0012) Implementation Class UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static ImplementationClassUid: number = 131090;
/// <summary>
/// <para>(0002,0013) Implementation Version Name</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static ImplementationVersionName: number = 131091;
/// <summary>
/// <para>(0002,0016) Source Application Entity Title</para>
/// <para> VR: AE VM:1</para>
/// </summary>
public static SourceApplicationEntityTitle: number = 131094;
/// <summary>
/// <para>(0002,0100) Private Information Creator UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static PrivateInformationCreatorUid: number = 131328;
/// <summary>
/// <para>(0002,0102) Private Information</para>
/// <para> VR: OB VM:1</para>
/// </summary>
public static PrivateInformation: number = 131330;
/// <summary>
/// <para>(0004,1130) File-set ID</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FileSetId: number = 266544;
/// <summary>
/// <para>(0004,1141) File-set Descriptor File ID</para>
/// <para> VR: CS VM:1-8</para>
/// </summary>
public static FileSetDescriptorFileId: number = 266561;
/// <summary>
/// <para>(0004,1142) Specific Character Set of File-set Descriptor File</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SpecificCharacterSetOfFileSetDescriptorFile: number = 266562;
/// <summary>
/// <para>(0004,1200) Offset of the First Directory Record of the Root Directory Entity</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static OffsetOfTheFirstDirectoryRecordOfTheRootDirectoryEntity: number = 266752;
/// <summary>
/// <para>(0004,1202) Offset of the Last Directory Record of the Root Directory Entity</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static OffsetOfTheLastDirectoryRecordOfTheRootDirectoryEntity: number = 266754;
/// <summary>
/// <para>(0004,1212) File-set Consistency Flag</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static FileSetConsistencyFlag: number = 266770;
/// <summary>
/// <para>(0004,1220) Directory Record Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DirectoryRecordSequence: number = 266784;
/// <summary>
/// <para>(0004,1400) Offset of the Next Directory Record</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static OffsetOfTheNextDirectoryRecord: number = 267264;
/// <summary>
/// <para>(0004,1410) Record In-use Flag</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static RecordInUseFlag: number = 267280;
/// <summary>
/// <para>(0004,1420) Offset of Referenced Lower-Level Directory Entity</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static OffsetOfReferencedLowerLevelDirectoryEntity: number = 267296;
/// <summary>
/// <para>(0004,1430) Directory Record Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DirectoryRecordType: number = 267312;
/// <summary>
/// <para>(0004,1432) Private Record UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static PrivateRecordUid: number = 267314;
/// <summary>
/// <para>(0004,1500) Referenced File ID</para>
/// <para> VR: CS VM:1-8</para>
/// </summary>
public static ReferencedFileId: number = 267520;
/// <summary>
/// <para>(0004,1504) MRDR Directory Record Offset</para>
/// <para> VR: UL VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static MrdrDirectoryRecordOffsetRetired: number = 267524;
/// <summary>
/// <para>(0004,1510) Referenced SOP Class UID in File</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static ReferencedSopClassUidInFile: number = 267536;
/// <summary>
/// <para>(0004,1511) Referenced SOP Instance UID in File</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static ReferencedSopInstanceUidInFile: number = 267537;
/// <summary>
/// <para>(0004,1512) Referenced Transfer Syntax UID in File</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static ReferencedTransferSyntaxUidInFile: number = 267538;
/// <summary>
/// <para>(0004,151A) Referenced Related General SOP Class UID in File</para>
/// <para> VR: UI VM:1-n</para>
/// </summary>
public static ReferencedRelatedGeneralSopClassUidInFile: number = 267546;
/// <summary>
/// <para>(0004,1600) Number of References</para>
/// <para> VR: UL VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static NumberOfReferencesRetired: number = 267776;
/// <summary>
/// <para>(0008,0001) Length to End</para>
/// <para> VR: UL VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static LengthToEndRetired: number = 524289;
/// <summary>
/// <para>(0008,0005) Specific Character Set</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static SpecificCharacterSet: number = 524293;
/// <summary>
/// <para>(0008,0006) Language Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static LanguageCodeSequence: number = 524294;
/// <summary>
/// <para>(0008,0008) Image Type</para>
/// <para> VR: CS VM:2-n</para>
/// </summary>
public static ImageType: number = 524296;
/// <summary>
/// <para>(0008,0010) Recognition Code</para>
/// <para> VR: SH VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static RecognitionCodeRetired: number = 524304;
/// <summary>
/// <para>(0008,0012) Instance Creation Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static InstanceCreationDate: number = 524306;
/// <summary>
/// <para>(0008,0013) Instance Creation Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static InstanceCreationTime: number = 524307;
/// <summary>
/// <para>(0008,0014) Instance Creator UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static InstanceCreatorUid: number = 524308;
/// <summary>
/// <para>(0008,0016) SOP Class UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static SopClassUid: number = 524310;
/// <summary>
/// <para>(0008,0018) SOP Instance UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static SopInstanceUid: number = 524312;
/// <summary>
/// <para>(0008,001A) Related General SOP Class UID</para>
/// <para> VR: UI VM:1-n</para>
/// </summary>
public static RelatedGeneralSopClassUid: number = 524314;
/// <summary>
/// <para>(0008,001B) Original Specialized SOP Class UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static OriginalSpecializedSopClassUid: number = 524315;
/// <summary>
/// <para>(0008,0020) Study Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static StudyDate: number = 524320;
/// <summary>
/// <para>(0008,0021) Series Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static SeriesDate: number = 524321;
/// <summary>
/// <para>(0008,0022) Acquisition Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static AcquisitionDate: number = 524322;
/// <summary>
/// <para>(0008,0023) Content Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static ContentDate: number = 524323;
/// <summary>
/// <para>(0008,0024) Overlay Date</para>
/// <para> VR: DA VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayDateRetired: number = 524324;
/// <summary>
/// <para>(0008,0025) Curve Date</para>
/// <para> VR: DA VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CurveDateRetired: number = 524325;
/// <summary>
/// <para>(0008,002A) Acquisition DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static AcquisitionDatetime: number = 524330;
/// <summary>
/// <para>(0008,0030) Study Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static StudyTime: number = 524336;
/// <summary>
/// <para>(0008,0031) Series Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static SeriesTime: number = 524337;
/// <summary>
/// <para>(0008,0032) Acquisition Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static AcquisitionTime: number = 524338;
/// <summary>
/// <para>(0008,0033) Content Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static ContentTime: number = 524339;
/// <summary>
/// <para>(0008,0034) Overlay Time</para>
/// <para> VR: TM VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayTimeRetired: number = 524340;
/// <summary>
/// <para>(0008,0035) Curve Time</para>
/// <para> VR: TM VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CurveTimeRetired: number = 524341;
/// <summary>
/// <para>(0008,0040) Data Set Type</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DataSetTypeRetired: number = 524352;
/// <summary>
/// <para>(0008,0041) Data Set Subtype</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DataSetSubtypeRetired: number = 524353;
/// <summary>
/// <para>(0008,0042) Nuclear Medicine Series Type</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static NuclearMedicineSeriesTypeRetired: number = 524354;
/// <summary>
/// <para>(0008,0050) Accession Number</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static AccessionNumber: number = 524368;
/// <summary>
/// <para>(0008,0051) Issuer of Accession Number Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IssuerOfAccessionNumberSequence: number = 524369;
/// <summary>
/// <para>(0008,0052) Query/Retrieve Level</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static QueryRetrieveLevel: number = 524370;
/// <summary>
/// <para>(0008,0054) Retrieve AE Title</para>
/// <para> VR: AE VM:1-n</para>
/// </summary>
public static RetrieveAeTitle: number = 524372;
/// <summary>
/// <para>(0008,0056) Instance Availability</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static InstanceAvailability: number = 524374;
/// <summary>
/// <para>(0008,0058) Failed SOP Instance UID List</para>
/// <para> VR: UI VM:1-n</para>
/// </summary>
public static FailedSopInstanceUidList: number = 524376;
/// <summary>
/// <para>(0008,0060) Modality</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static Modality: number = 524384;
/// <summary>
/// <para>(0008,0061) Modalities in Study</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static ModalitiesInStudy: number = 524385;
/// <summary>
/// <para>(0008,0062) SOP Classes in Study</para>
/// <para> VR: UI VM:1-n</para>
/// </summary>
public static SopClassesInStudy: number = 524386;
/// <summary>
/// <para>(0008,0064) Conversion Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ConversionType: number = 524388;
/// <summary>
/// <para>(0008,0068) Presentation Intent Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PresentationIntentType: number = 524392;
/// <summary>
/// <para>(0008,0070) Manufacturer</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static Manufacturer: number = 524400;
/// <summary>
/// <para>(0008,0080) Institution Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static InstitutionName: number = 524416;
/// <summary>
/// <para>(0008,0081) Institution Address</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static InstitutionAddress: number = 524417;
/// <summary>
/// <para>(0008,0082) Institution Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static InstitutionCodeSequence: number = 524418;
/// <summary>
/// <para>(0008,0090) Referring Physician's Name</para>
/// <para> VR: PN VM:1</para>
/// </summary>
public static ReferringPhysiciansName: number = 524432;
/// <summary>
/// <para>(0008,0092) Referring Physician's Address</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static ReferringPhysiciansAddress: number = 524434;
/// <summary>
/// <para>(0008,0094) Referring Physician's Telephone Numbers</para>
/// <para> VR: SH VM:1-n</para>
/// </summary>
public static ReferringPhysiciansTelephoneNumbers: number = 524436;
/// <summary>
/// <para>(0008,0096) Referring Physician Identification Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferringPhysicianIdentificationSequence: number = 524438;
/// <summary>
/// <para>(0008,0100) Code Value</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static CodeValue: number = 524544;
/// <summary>
/// <para>(0008,0102) Coding Scheme Designator</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static CodingSchemeDesignator: number = 524546;
/// <summary>
/// <para>(0008,0103) Coding Scheme Version</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static CodingSchemeVersion: number = 524547;
/// <summary>
/// <para>(0008,0104) Code Meaning</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static CodeMeaning: number = 524548;
/// <summary>
/// <para>(0008,0105) Mapping Resource</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static MappingResource: number = 524549;
/// <summary>
/// <para>(0008,0106) Context Group Version</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static ContextGroupVersion: number = 524550;
/// <summary>
/// <para>(0008,0107) Context Group Local Version</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static ContextGroupLocalVersion: number = 524551;
/// <summary>
/// <para>(0008,010B) Context Group Extension Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ContextGroupExtensionFlag: number = 524555;
/// <summary>
/// <para>(0008,010C) Coding Scheme UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static CodingSchemeUid: number = 524556;
/// <summary>
/// <para>(0008,010D) Context Group Extension Creator UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static ContextGroupExtensionCreatorUid: number = 524557;
/// <summary>
/// <para>(0008,010F) Context Identifier</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ContextIdentifier: number = 524559;
/// <summary>
/// <para>(0008,0110) Coding Scheme Identification Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CodingSchemeIdentificationSequence: number = 524560;
/// <summary>
/// <para>(0008,0112) Coding Scheme Registry</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static CodingSchemeRegistry: number = 524562;
/// <summary>
/// <para>(0008,0114) Coding Scheme External ID</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static CodingSchemeExternalId: number = 524564;
/// <summary>
/// <para>(0008,0115) Coding Scheme Name</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static CodingSchemeName: number = 524565;
/// <summary>
/// <para>(0008,0116) Coding Scheme Responsible Organization</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static CodingSchemeResponsibleOrganization: number = 524566;
/// <summary>
/// <para>(0008,0117) Context UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static ContextUid: number = 524567;
/// <summary>
/// <para>(0008,0201) Timezone Offset From UTC</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static TimezoneOffsetFromUtc: number = 524801;
/// <summary>
/// <para>(0008,1000) Network ID</para>
/// <para> VR: AE VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static NetworkIdRetired: number = 528384;
/// <summary>
/// <para>(0008,1010) Station Name</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static StationName: number = 528400;
/// <summary>
/// <para>(0008,1030) Study Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static StudyDescription: number = 528432;
/// <summary>
/// <para>(0008,1032) Procedure Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ProcedureCodeSequence: number = 528434;
/// <summary>
/// <para>(0008,103E) Series Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SeriesDescription: number = 528446;
/// <summary>
/// <para>(0008,103F) Series Description Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SeriesDescriptionCodeSequence: number = 528447;
/// <summary>
/// <para>(0008,1040) Institutional Department Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static InstitutionalDepartmentName: number = 528448;
/// <summary>
/// <para>(0008,1048) Physician(s) of Record</para>
/// <para> VR: PN VM:1-n</para>
/// </summary>
public static PhysiciansOfRecord: number = 528456;
/// <summary>
/// <para>(0008,1049) Physician(s) of Record Identification Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PhysiciansOfRecordIdentificationSequence: number = 528457;
/// <summary>
/// <para>(0008,1050) Performing Physician's Name</para>
/// <para> VR: PN VM:1-n</para>
/// </summary>
public static PerformingPhysiciansName: number = 528464;
/// <summary>
/// <para>(0008,1052) Performing Physician Identification Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PerformingPhysicianIdentificationSequence: number = 528466;
/// <summary>
/// <para>(0008,1060) Name of Physician(s) Reading Study</para>
/// <para> VR: PN VM:1-n</para>
/// </summary>
public static NameOfPhysiciansReadingStudy: number = 528480;
/// <summary>
/// <para>(0008,1062) Physician(s) Reading Study Identification Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PhysiciansReadingStudyIdentificationSequence: number = 528482;
/// <summary>
/// <para>(0008,1070) Operators' Name</para>
/// <para> VR: PN VM:1-n</para>
/// </summary>
public static OperatorsName: number = 528496;
/// <summary>
/// <para>(0008,1072) Operator Identification Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OperatorIdentificationSequence: number = 528498;
/// <summary>
/// <para>(0008,1080) Admitting Diagnoses Description</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static AdmittingDiagnosesDescription: number = 528512;
/// <summary>
/// <para>(0008,1084) Admitting Diagnoses Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AdmittingDiagnosesCodeSequence: number = 528516;
/// <summary>
/// <para>(0008,1090) Manufacturer's Model Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ManufacturersModelName: number = 528528;
/// <summary>
/// <para>(0008,1100) Referenced Results Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferencedResultsSequenceRetired: number = 528640;
/// <summary>
/// <para>(0008,1110) Referenced Study Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedStudySequence: number = 528656;
/// <summary>
/// <para>(0008,1111) Referenced Performed Procedure Step Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedPerformedProcedureStepSequence: number = 528657;
/// <summary>
/// <para>(0008,1115) Referenced Series Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedSeriesSequence: number = 528661;
/// <summary>
/// <para>(0008,1120) Referenced Patient Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedPatientSequence: number = 528672;
/// <summary>
/// <para>(0008,1125) Referenced Visit Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedVisitSequence: number = 528677;
/// <summary>
/// <para>(0008,1130) Referenced Overlay Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferencedOverlaySequenceRetired: number = 528688;
/// <summary>
/// <para>(0008,1134) Referenced Stereometric Instance Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedStereometricInstanceSequence: number = 528692;
/// <summary>
/// <para>(0008,113A) Referenced Waveform Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedWaveformSequence: number = 528698;
/// <summary>
/// <para>(0008,1140) Referenced Image Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedImageSequence: number = 528704;
/// <summary>
/// <para>(0008,1145) Referenced Curve Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferencedCurveSequenceRetired: number = 528709;
/// <summary>
/// <para>(0008,114A) Referenced Instance Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedInstanceSequence: number = 528714;
/// <summary>
/// <para>(0008,114B) Referenced Real World Value Mapping Instance Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedRealWorldValueMappingInstanceSequence: number = 528715;
/// <summary>
/// <para>(0008,1150) Referenced SOP Class UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static ReferencedSopClassUid: number = 528720;
/// <summary>
/// <para>(0008,1155) Referenced SOP Instance UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static ReferencedSopInstanceUid: number = 528725;
/// <summary>
/// <para>(0008,115A) SOP Classes Supported</para>
/// <para> VR: UI VM:1-n</para>
/// </summary>
public static SopClassesSupported: number = 528730;
/// <summary>
/// <para>(0008,1160) Referenced Frame Number</para>
/// <para> VR: IS VM:1-n</para>
/// </summary>
public static ReferencedFrameNumber: number = 528736;
/// <summary>
/// <para>(0008,1161) Simple Frame List</para>
/// <para> VR: UL VM:1-n</para>
/// </summary>
public static SimpleFrameList: number = 528737;
/// <summary>
/// <para>(0008,1162) Calculated Frame List</para>
/// <para> VR: UL VM:3-3n</para>
/// </summary>
public static CalculatedFrameList: number = 528738;
/// <summary>
/// <para>(0008,1163) Time Range</para>
/// <para> VR: FD VM:2</para>
/// </summary>
public static TimeRange: number = 528739;
/// <summary>
/// <para>(0008,1164) Frame Extraction Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FrameExtractionSequence: number = 528740;
/// <summary>
/// <para>(0008,1167) Multi-Frame Source SOP Instance UID </para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static MultiFrameSourceSopInstanceUid: number = 528743;
/// <summary>
/// <para>(0008,1195) Transaction UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static TransactionUid: number = 528789;
/// <summary>
/// <para>(0008,1197) Failure Reason</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static FailureReason: number = 528791;
/// <summary>
/// <para>(0008,1198) Failed SOP Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FailedSopSequence: number = 528792;
/// <summary>
/// <para>(0008,1199) Referenced SOP Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedSopSequence: number = 528793;
/// <summary>
/// <para>(0008,1200) Studies Containing Other Referenced Instances Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static StudiesContainingOtherReferencedInstancesSequence: number = 528896;
/// <summary>
/// <para>(0008,1250) Related Series Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RelatedSeriesSequence: number = 528976;
/// <summary>
/// <para>(0008,2110) Lossy Image Compression (Retired)</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static LossyImageCompressionRetired: number = 532752;
/// <summary>
/// <para>(0008,2111) Derivation Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static DerivationDescription: number = 532753;
/// <summary>
/// <para>(0008,2112) Source Image Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SourceImageSequence: number = 532754;
/// <summary>
/// <para>(0008,2120) Stage Name</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static StageName: number = 532768;
/// <summary>
/// <para>(0008,2122) Stage Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static StageNumber: number = 532770;
/// <summary>
/// <para>(0008,2124) Number of Stages</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfStages: number = 532772;
/// <summary>
/// <para>(0008,2127) View Name</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static ViewName: number = 532775;
/// <summary>
/// <para>(0008,2128) View Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ViewNumber: number = 532776;
/// <summary>
/// <para>(0008,2129) Number of Event Timers</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfEventTimers: number = 532777;
/// <summary>
/// <para>(0008,212A) Number of Views in Stage</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfViewsInStage: number = 532778;
/// <summary>
/// <para>(0008,2130) Event Elapsed Time(s)</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static EventElapsedTimes: number = 532784;
/// <summary>
/// <para>(0008,2132) Event Timer Name(s)</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static EventTimerNames: number = 532786;
/// <summary>
/// <para>(0008,2133) Event Timer Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static EventTimerSequence: number = 532787;
/// <summary>
/// <para>(0008,2134) Event Time Offset</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static EventTimeOffset: number = 532788;
/// <summary>
/// <para>(0008,2135) Event Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static EventCodeSequence: number = 532789;
/// <summary>
/// <para>(0008,2142) Start Trim</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static StartTrim: number = 532802;
/// <summary>
/// <para>(0008,2143) Stop Trim</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static StopTrim: number = 532803;
/// <summary>
/// <para>(0008,2144) Recommended Display Frame Rate</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static RecommendedDisplayFrameRate: number = 532804;
/// <summary>
/// <para>(0008,2200) Transducer Position</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TransducerPositionRetired: number = 532992;
/// <summary>
/// <para>(0008,2204) Transducer Orientation</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TransducerOrientationRetired: number = 532996;
/// <summary>
/// <para>(0008,2208) Anatomic Structure</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AnatomicStructureRetired: number = 533000;
/// <summary>
/// <para>(0008,2218) Anatomic Region Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AnatomicRegionSequence: number = 533016;
/// <summary>
/// <para>(0008,2220) Anatomic Region Modifier Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AnatomicRegionModifierSequence: number = 533024;
/// <summary>
/// <para>(0008,2228) Primary Anatomic Structure Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PrimaryAnatomicStructureSequence: number = 533032;
/// <summary>
/// <para>(0008,2229) Anatomic Structure, Space or Region Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AnatomicStructureSpaceOrRegionSequence: number = 533033;
/// <summary>
/// <para>(0008,2230) Primary Anatomic Structure Modifier Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PrimaryAnatomicStructureModifierSequence: number = 533040;
/// <summary>
/// <para>(0008,2240) Transducer Position Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TransducerPositionSequenceRetired: number = 533056;
/// <summary>
/// <para>(0008,2242) Transducer Position Modifier Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TransducerPositionModifierSequenceRetired: number = 533058;
/// <summary>
/// <para>(0008,2244) Transducer Orientation Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TransducerOrientationSequenceRetired: number = 533060;
/// <summary>
/// <para>(0008,2246) Transducer Orientation Modifier Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TransducerOrientationModifierSequenceRetired: number = 533062;
/// <summary>
/// <para>(0008,2251) Anatomic Structure Space Or Region Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AnatomicStructureSpaceOrRegionCodeSequenceTrialRetired: number = 533073;
/// <summary>
/// <para>(0008,2253) Anatomic Portal Of Entrance Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AnatomicPortalOfEntranceCodeSequenceTrialRetired: number = 533075;
/// <summary>
/// <para>(0008,2255) Anatomic Approach Direction Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AnatomicApproachDirectionCodeSequenceTrialRetired: number = 533077;
/// <summary>
/// <para>(0008,2256) Anatomic Perspective Description (Trial)</para>
/// <para> VR: ST VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AnatomicPerspectiveDescriptionTrialRetired: number = 533078;
/// <summary>
/// <para>(0008,2257) Anatomic Perspective Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AnatomicPerspectiveCodeSequenceTrialRetired: number = 533079;
/// <summary>
/// <para>(0008,2258) Anatomic Location Of Examining Instrument Description (Trial)</para>
/// <para> VR: ST VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AnatomicLocationOfExaminingInstrumentDescriptionTrialRetired: number = 533080;
/// <summary>
/// <para>(0008,2259) Anatomic Location Of Examining Instrument Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AnatomicLocationOfExaminingInstrumentCodeSequenceTrialRetired: number = 533081;
/// <summary>
/// <para>(0008,225A) Anatomic Structure Space Or Region Modifier Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AnatomicStructureSpaceOrRegionModifierCodeSequenceTrialRetired: number = 533082;
/// <summary>
/// <para>(0008,225C) OnAxis Background Anatomic Structure Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OnaxisBackgroundAnatomicStructureCodeSequenceTrialRetired: number = 533084;
/// <summary>
/// <para>(0008,3001) Alternate Representation Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AlternateRepresentationSequence: number = 536577;
/// <summary>
/// <para>(0008,3010) Irradiation Event UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static IrradiationEventUid: number = 536592;
/// <summary>
/// <para>(0008,4000) Identifying Comments</para>
/// <para> VR: LT VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static IdentifyingCommentsRetired: number = 540672;
/// <summary>
/// <para>(0008,9007) Frame Type</para>
/// <para> VR: CS VM:4</para>
/// </summary>
public static FrameType: number = 561159;
/// <summary>
/// <para>(0008,9092) Referenced Image Evidence Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedImageEvidenceSequence: number = 561298;
/// <summary>
/// <para>(0008,9121) Referenced Raw Data Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedRawDataSequence: number = 561441;
/// <summary>
/// <para>(0008,9123) Creator-Version UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static CreatorVersionUid: number = 561443;
/// <summary>
/// <para>(0008,9124) Derivation Image Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DerivationImageSequence: number = 561444;
/// <summary>
/// <para>(0008,9154) Source Image Evidence Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SourceImageEvidenceSequence: number = 561492;
/// <summary>
/// <para>(0008,9205) Pixel Presentation</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PixelPresentation: number = 561669;
/// <summary>
/// <para>(0008,9206) Volumetric Properties</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static VolumetricProperties: number = 561670;
/// <summary>
/// <para>(0008,9207) Volume Based Calculation Technique</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static VolumeBasedCalculationTechnique: number = 561671;
/// <summary>
/// <para>(0008,9208) Complex Image Component</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ComplexImageComponent: number = 561672;
/// <summary>
/// <para>(0008,9209) Acquisition Contrast</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AcquisitionContrast: number = 561673;
/// <summary>
/// <para>(0008,9215) Derivation Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DerivationCodeSequence: number = 561685;
/// <summary>
/// <para>(0008,9237) Referenced Presentation State Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedPresentationStateSequence: number = 561719;
/// <summary>
/// <para>(0008,9410) Referenced Other Plane Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedOtherPlaneSequence: number = 562192;
/// <summary>
/// <para>(0008,9458) Frame Display Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FrameDisplaySequence: number = 562264;
/// <summary>
/// <para>(0008,9459) Recommended Display Frame Rate in Float</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static RecommendedDisplayFrameRateInFloat: number = 562265;
/// <summary>
/// <para>(0008,9460) Skip Frame Range Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SkipFrameRangeFlag: number = 562272;
/// <summary>
/// <para>(0010,0010) Patient's Name</para>
/// <para> VR: PN VM:1</para>
/// </summary>
public static PatientsName: number = 1048592;
/// <summary>
/// <para>(0010,0020) Patient ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PatientId: number = 1048608;
/// <summary>
/// <para>(0010,0021) Issuer of Patient ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static IssuerOfPatientId: number = 1048609;
/// <summary>
/// <para>(0010,0022) Type of Patient ID</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TypeOfPatientId: number = 1048610;
/// <summary>
/// <para>(0010,0024) Issuer of Patient ID Qualifiers Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IssuerOfPatientIdQualifiersSequence: number = 1048612;
/// <summary>
/// <para>(0010,0030) Patient's Birth Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static PatientsBirthDate: number = 1048624;
/// <summary>
/// <para>(0010,0032) Patient's Birth Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static PatientsBirthTime: number = 1048626;
/// <summary>
/// <para>(0010,0040) Patient's Sex</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PatientsSex: number = 1048640;
/// <summary>
/// <para>(0010,0050) Patient's Insurance Plan Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PatientsInsurancePlanCodeSequence: number = 1048656;
/// <summary>
/// <para>(0010,0101) Patient's Primary Language Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PatientsPrimaryLanguageCodeSequence: number = 1048833;
/// <summary>
/// <para>(0010,0102) Patient's Primary Language Modifier Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PatientsPrimaryLanguageModifierCodeSequence: number = 1048834;
/// <summary>
/// <para>(0010,1000) Other Patient IDs</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static OtherPatientIds: number = 1052672;
/// <summary>
/// <para>(0010,1001) Other Patient Names</para>
/// <para> VR: PN VM:1-n</para>
/// </summary>
public static OtherPatientNames: number = 1052673;
/// <summary>
/// <para>(0010,1002) Other Patient IDs Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OtherPatientIdsSequence: number = 1052674;
/// <summary>
/// <para>(0010,1005) Patient's Birth Name</para>
/// <para> VR: PN VM:1</para>
/// </summary>
public static PatientsBirthName: number = 1052677;
/// <summary>
/// <para>(0010,1010) Patient's Age</para>
/// <para> VR: AS VM:1</para>
/// </summary>
public static PatientsAge: number = 1052688;
/// <summary>
/// <para>(0010,1020) Patient's Size</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static PatientsSize: number = 1052704;
/// <summary>
/// <para>(0010,1021) Patient's Size Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PatientsSizeCodeSequence: number = 1052705;
/// <summary>
/// <para>(0010,1030) Patient's Weight</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static PatientsWeight: number = 1052720;
/// <summary>
/// <para>(0010,1040) Patient's Address</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PatientsAddress: number = 1052736;
/// <summary>
/// <para>(0010,1050) Insurance Plan Identification</para>
/// <para> VR: LO VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static InsurancePlanIdentificationRetired: number = 1052752;
/// <summary>
/// <para>(0010,1060) Patient's Mother's Birth Name</para>
/// <para> VR: PN VM:1</para>
/// </summary>
public static PatientsMothersBirthName: number = 1052768;
/// <summary>
/// <para>(0010,1080) Military Rank</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static MilitaryRank: number = 1052800;
/// <summary>
/// <para>(0010,1081) Branch of Service</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static BranchOfService: number = 1052801;
/// <summary>
/// <para>(0010,1090) Medical Record Locator</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static MedicalRecordLocator: number = 1052816;
/// <summary>
/// <para>(0010,2000) Medical Alerts</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static MedicalAlerts: number = 1056768;
/// <summary>
/// <para>(0010,2110) Allergies</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static Allergies: number = 1057040;
/// <summary>
/// <para>(0010,2150) Country of Residence</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static CountryOfResidence: number = 1057104;
/// <summary>
/// <para>(0010,2152) Region of Residence</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static RegionOfResidence: number = 1057106;
/// <summary>
/// <para>(0010,2154) Patient's Telephone Numbers</para>
/// <para> VR: SH VM:1-n</para>
/// </summary>
public static PatientsTelephoneNumbers: number = 1057108;
/// <summary>
/// <para>(0010,2160) Ethnic Group</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static EthnicGroup: number = 1057120;
/// <summary>
/// <para>(0010,2180) Occupation</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static Occupation: number = 1057152;
/// <summary>
/// <para>(0010,21A0) Smoking Status</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SmokingStatus: number = 1057184;
/// <summary>
/// <para>(0010,21B0) Additional Patient History</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static AdditionalPatientHistory: number = 1057200;
/// <summary>
/// <para>(0010,21C0) Pregnancy Status</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static PregnancyStatus: number = 1057216;
/// <summary>
/// <para>(0010,21D0) Last Menstrual Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static LastMenstrualDate: number = 1057232;
/// <summary>
/// <para>(0010,21F0) Patient's Religious Preference</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PatientsReligiousPreference: number = 1057264;
/// <summary>
/// <para>(0010,2201) Patient Species Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PatientSpeciesDescription: number = 1057281;
/// <summary>
/// <para>(0010,2202) Patient Species Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PatientSpeciesCodeSequence: number = 1057282;
/// <summary>
/// <para>(0010,2203) Patient's Sex Neutered</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PatientsSexNeutered: number = 1057283;
/// <summary>
/// <para>(0010,2210) Anatomical Orientation Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AnatomicalOrientationType: number = 1057296;
/// <summary>
/// <para>(0010,2292) Patient Breed Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PatientBreedDescription: number = 1057426;
/// <summary>
/// <para>(0010,2293) Patient Breed Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PatientBreedCodeSequence: number = 1057427;
/// <summary>
/// <para>(0010,2294) Breed Registration Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BreedRegistrationSequence: number = 1057428;
/// <summary>
/// <para>(0010,2295) Breed Registration Number</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static BreedRegistrationNumber: number = 1057429;
/// <summary>
/// <para>(0010,2296) Breed Registry Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BreedRegistryCodeSequence: number = 1057430;
/// <summary>
/// <para>(0010,2297) Responsible Person</para>
/// <para> VR: PN VM:1</para>
/// </summary>
public static ResponsiblePerson: number = 1057431;
/// <summary>
/// <para>(0010,2298) Responsible Person Role</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ResponsiblePersonRole: number = 1057432;
/// <summary>
/// <para>(0010,2299) Responsible Organization</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ResponsibleOrganization: number = 1057433;
/// <summary>
/// <para>(0010,4000) Patient Comments</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static PatientComments: number = 1064960;
/// <summary>
/// <para>(0010,9431) Examined Body Thickness</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static ExaminedBodyThickness: number = 1086513;
/// <summary>
/// <para>(0012,0010) Clinical Trial Sponsor Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ClinicalTrialSponsorName: number = 1179664;
/// <summary>
/// <para>(0012,0020) Clinical Trial Protocol ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ClinicalTrialProtocolId: number = 1179680;
/// <summary>
/// <para>(0012,0021) Clinical Trial Protocol Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ClinicalTrialProtocolName: number = 1179681;
/// <summary>
/// <para>(0012,0030) Clinical Trial Site ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ClinicalTrialSiteId: number = 1179696;
/// <summary>
/// <para>(0012,0031) Clinical Trial Site Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ClinicalTrialSiteName: number = 1179697;
/// <summary>
/// <para>(0012,0040) Clinical Trial Subject ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ClinicalTrialSubjectId: number = 1179712;
/// <summary>
/// <para>(0012,0042) Clinical Trial Subject Reading ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ClinicalTrialSubjectReadingId: number = 1179714;
/// <summary>
/// <para>(0012,0050) Clinical Trial Time Point ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ClinicalTrialTimePointId: number = 1179728;
/// <summary>
/// <para>(0012,0051) Clinical Trial Time Point Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static ClinicalTrialTimePointDescription: number = 1179729;
/// <summary>
/// <para>(0012,0060) Clinical Trial Coordinating Center Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ClinicalTrialCoordinatingCenterName: number = 1179744;
/// <summary>
/// <para>(0012,0062) Patient Identity Removed</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PatientIdentityRemoved: number = 1179746;
/// <summary>
/// <para>(0012,0063) De-identification Method</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static DeIdentificationMethod: number = 1179747;
/// <summary>
/// <para>(0012,0064) De-identification Method Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DeIdentificationMethodCodeSequence: number = 1179748;
/// <summary>
/// <para>(0012,0071) Clinical Trial Series ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ClinicalTrialSeriesId: number = 1179761;
/// <summary>
/// <para>(0012,0072) Clinical Trial Series Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ClinicalTrialSeriesDescription: number = 1179762;
/// <summary>
/// <para>(0012,0081) Clinical Trial Protocol Ethics Committee Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ClinicalTrialProtocolEthicsCommitteeName: number = 1179777;
/// <summary>
/// <para>(0012,0082) Clinical Trial Protocol Ethics Committee Approval Number</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ClinicalTrialProtocolEthicsCommitteeApprovalNumber: number = 1179778;
/// <summary>
/// <para>(0012,0083) Consent for Clinical Trial Use Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ConsentForClinicalTrialUseSequence: number = 1179779;
/// <summary>
/// <para>(0012,0084) Distribution Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DistributionType: number = 1179780;
/// <summary>
/// <para>(0012,0085) Consent for Distribution Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ConsentForDistributionFlag: number = 1179781;
/// <summary>
/// <para>(0014,0023) CAD File Format</para>
/// <para> VR: ST VM:1-n</para>
/// </summary>
public static CadFileFormat: number = 1310755;
/// <summary>
/// <para>(0014,0024) Component Reference System</para>
/// <para> VR: ST VM:1-n</para>
/// </summary>
public static ComponentReferenceSystem: number = 1310756;
/// <summary>
/// <para>(0014,0025) Component Manufacturing Procedure</para>
/// <para> VR: ST VM:1-n</para>
/// </summary>
public static ComponentManufacturingProcedure: number = 1310757;
/// <summary>
/// <para>(0014,0028) Component Manufacturer</para>
/// <para> VR: ST VM:1-n</para>
/// </summary>
public static ComponentManufacturer: number = 1310760;
/// <summary>
/// <para>(0014,0030) Material Thickness</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static MaterialThickness: number = 1310768;
/// <summary>
/// <para>(0014,0032) Material Pipe Diameter</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static MaterialPipeDiameter: number = 1310770;
/// <summary>
/// <para>(0014,0034) Material Isolation Diameter</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static MaterialIsolationDiameter: number = 1310772;
/// <summary>
/// <para>(0014,0042) Material Grade</para>
/// <para> VR: ST VM:1-n</para>
/// </summary>
public static MaterialGrade: number = 1310786;
/// <summary>
/// <para>(0014,0044) Material Properties File ID</para>
/// <para> VR: ST VM:1-n</para>
/// </summary>
public static MaterialPropertiesFileId: number = 1310788;
/// <summary>
/// <para>(0014,0045) Material Properties File Format</para>
/// <para> VR: ST VM:1-n</para>
/// </summary>
public static MaterialPropertiesFileFormat: number = 1310789;
/// <summary>
/// <para>(0014,0046) Material Notes</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static MaterialNotes: number = 1310790;
/// <summary>
/// <para>(0014,0050) Component Shape</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ComponentShape: number = 1310800;
/// <summary>
/// <para>(0014,0052) Curvature Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CurvatureType: number = 1310802;
/// <summary>
/// <para>(0014,0054) Outer Diameter</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static OuterDiameter: number = 1310804;
/// <summary>
/// <para>(0014,0056) Inner Diameter</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static InnerDiameter: number = 1310806;
/// <summary>
/// <para>(0014,1010) Actual Environmental Conditions</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static ActualEnvironmentalConditions: number = 1314832;
/// <summary>
/// <para>(0014,1020) Expiry Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static ExpiryDate: number = 1314848;
/// <summary>
/// <para>(0014,1040) Environmental Conditions</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static EnvironmentalConditions: number = 1314880;
/// <summary>
/// <para>(0014,2002) Evaluator Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static EvaluatorSequence: number = 1318914;
/// <summary>
/// <para>(0014,2004) Evaluator Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static EvaluatorNumber: number = 1318916;
/// <summary>
/// <para>(0014,2006) Evaluator Name</para>
/// <para> VR: PN VM:1</para>
/// </summary>
public static EvaluatorName: number = 1318918;
/// <summary>
/// <para>(0014,2008) Evaluation Attempt</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static EvaluationAttempt: number = 1318920;
/// <summary>
/// <para>(0014,2012) Indication Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IndicationSequence: number = 1318930;
/// <summary>
/// <para>(0014,2014) Indication Number </para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static IndicationNumber: number = 1318932;
/// <summary>
/// <para>(0014,2016) Indication Label</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static IndicationLabel: number = 1318934;
/// <summary>
/// <para>(0014,2018) Indication Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static IndicationDescription: number = 1318936;
/// <summary>
/// <para>(0014,201A) Indication Type</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static IndicationType: number = 1318938;
/// <summary>
/// <para>(0014,201C) Indication Disposition</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static IndicationDisposition: number = 1318940;
/// <summary>
/// <para>(0014,201E) Indication ROI Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IndicationRoiSequence: number = 1318942;
/// <summary>
/// <para>(0014,2030) Indication Physical Property Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IndicationPhysicalPropertySequence: number = 1318960;
/// <summary>
/// <para>(0014,2032) Property Label</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static PropertyLabel: number = 1318962;
/// <summary>
/// <para>(0014,2202) Coordinate System Number of Axes </para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static CoordinateSystemNumberOfAxes: number = 1319426;
/// <summary>
/// <para>(0014,2204) Coordinate System Axes Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CoordinateSystemAxesSequence: number = 1319428;
/// <summary>
/// <para>(0014,2206) Coordinate System Axis Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static CoordinateSystemAxisDescription: number = 1319430;
/// <summary>
/// <para>(0014,2208) Coordinate System Data Set Mapping</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CoordinateSystemDataSetMapping: number = 1319432;
/// <summary>
/// <para>(0014,220A) Coordinate System Axis Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static CoordinateSystemAxisNumber: number = 1319434;
/// <summary>
/// <para>(0014,220C) Coordinate System Axis Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CoordinateSystemAxisType: number = 1319436;
/// <summary>
/// <para>(0014,220E) Coordinate System Axis Units</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CoordinateSystemAxisUnits: number = 1319438;
/// <summary>
/// <para>(0014,2210) Coordinate System Axis Values</para>
/// <para> VR: OB VM:1</para>
/// </summary>
public static CoordinateSystemAxisValues: number = 1319440;
/// <summary>
/// <para>(0014,2220) Coordinate System Transform Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CoordinateSystemTransformSequence: number = 1319456;
/// <summary>
/// <para>(0014,2222) Transform Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static TransformDescription: number = 1319458;
/// <summary>
/// <para>(0014,2224) Transform Number of Axes</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static TransformNumberOfAxes: number = 1319460;
/// <summary>
/// <para>(0014,2226) Transform Order of Axes</para>
/// <para> VR: IS VM:1-n</para>
/// </summary>
public static TransformOrderOfAxes: number = 1319462;
/// <summary>
/// <para>(0014,2228) Transformed Axis Units</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TransformedAxisUnits: number = 1319464;
/// <summary>
/// <para>(0014,222A) Coordinate System Transform Rotation and Scale Matrix</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static CoordinateSystemTransformRotationAndScaleMatrix: number = 1319466;
/// <summary>
/// <para>(0014,222C) Coordinate System Transform Translation Matrix</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static CoordinateSystemTransformTranslationMatrix: number = 1319468;
/// <summary>
/// <para>(0014,3011) Internal Detector Frame Time</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static InternalDetectorFrameTime: number = 1323025;
/// <summary>
/// <para>(0014,3012) Number of Frames Integrated</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static NumberOfFramesIntegrated: number = 1323026;
/// <summary>
/// <para>(0014,3020) Detector Temperature Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DetectorTemperatureSequence: number = 1323040;
/// <summary>
/// <para>(0014,3022) Sensor Name</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SensorName: number = 1323042;
/// <summary>
/// <para>(0014,3024) Horizontal Offset of Sensor</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static HorizontalOffsetOfSensor: number = 1323044;
/// <summary>
/// <para>(0014,3026) Vertical Offset of Sensor</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static VerticalOffsetOfSensor: number = 1323046;
/// <summary>
/// <para>(0014,3028) Sensor Temperature</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SensorTemperature: number = 1323048;
/// <summary>
/// <para>(0014,3040) Dark Current Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DarkCurrentSequence: number = 1323072;
/// <summary>
/// <para>(0014,3050) Dark Current Counts</para>
/// <para> VR: OB or OW VM:1</para>
/// </summary>
public static DarkCurrentCounts: number = 1323088;
/// <summary>
/// <para>(0014,3060) Gain Correction Reference Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static GainCorrectionReferenceSequence: number = 1323104;
/// <summary>
/// <para>(0014,3070) Air Counts</para>
/// <para> VR: OB or OW VM:1</para>
/// </summary>
public static AirCounts: number = 1323120;
/// <summary>
/// <para>(0014,3071) KV Used in Gain Calibration</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static KvUsedInGainCalibration: number = 1323121;
/// <summary>
/// <para>(0014,3072) MA Used in Gain Calibration</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static MaUsedInGainCalibration: number = 1323122;
/// <summary>
/// <para>(0014,3073) Number of Frames Used for Integration</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static NumberOfFramesUsedForIntegration: number = 1323123;
/// <summary>
/// <para>(0014,3074) Filter Material Used in Gain Calibration</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static FilterMaterialUsedInGainCalibration: number = 1323124;
/// <summary>
/// <para>(0014,3075) Filter Thickness Used in Gain Calibration</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static FilterThicknessUsedInGainCalibration: number = 1323125;
/// <summary>
/// <para>(0014,3076) Date of Gain Calibration</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static DateOfGainCalibration: number = 1323126;
/// <summary>
/// <para>(0014,3077) Time of Gain Calibration</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static TimeOfGainCalibration: number = 1323127;
/// <summary>
/// <para>(0014,3080) Bad Pixel Image</para>
/// <para> VR: OB VM:1</para>
/// </summary>
public static BadPixelImage: number = 1323136;
/// <summary>
/// <para>(0014,3099) Calibration Notes</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static CalibrationNotes: number = 1323161;
/// <summary>
/// <para>(0014,4002) Pulser Equipment Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PulserEquipmentSequence: number = 1327106;
/// <summary>
/// <para>(0014,4004) Pulser Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PulserType: number = 1327108;
/// <summary>
/// <para>(0014,4006) Pulser Notes</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static PulserNotes: number = 1327110;
/// <summary>
/// <para>(0014,4008) Receiver Equipment Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReceiverEquipmentSequence: number = 1327112;
/// <summary>
/// <para>(0014,400A) Amplifier Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AmplifierType: number = 1327114;
/// <summary>
/// <para>(0014,400C) Receiver Notes</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static ReceiverNotes: number = 1327116;
/// <summary>
/// <para>(0014,400E) Pre-Amplifier Equipment Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PreAmplifierEquipmentSequence: number = 1327118;
/// <summary>
/// <para>(0014,400F) Pre-Amplifier Notes</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static PreAmplifierNotes: number = 1327119;
/// <summary>
/// <para>(0014,4010) Transmit Transducer Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TransmitTransducerSequence: number = 1327120;
/// <summary>
/// <para>(0014,4011) Receive Transducer Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReceiveTransducerSequence: number = 1327121;
/// <summary>
/// <para>(0014,4012) Number of Elements</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfElements: number = 1327122;
/// <summary>
/// <para>(0014,4013) Element Shape</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ElementShape: number = 1327123;
/// <summary>
/// <para>(0014,4014) Element Dimension A</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ElementDimensionA: number = 1327124;
/// <summary>
/// <para>(0014,4015) Element Dimension B</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ElementDimensionB: number = 1327125;
/// <summary>
/// <para>(0014,4016) Element Pitch</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ElementPitch: number = 1327126;
/// <summary>
/// <para>(0014,4017) Measured Beam Dimension A</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static MeasuredBeamDimensionA: number = 1327127;
/// <summary>
/// <para>(0014,4018) Measured Beam Dimension B</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static MeasuredBeamDimensionB: number = 1327128;
/// <summary>
/// <para>(0014,4019) Location of Measured Beam Diameter</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static LocationOfMeasuredBeamDiameter: number = 1327129;
/// <summary>
/// <para>(0014,401A) Nominal Frequency</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static NominalFrequency: number = 1327130;
/// <summary>
/// <para>(0014,401B) Measured Center Frequency</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static MeasuredCenterFrequency: number = 1327131;
/// <summary>
/// <para>(0014,401C) Measured Bandwidth</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static MeasuredBandwidth: number = 1327132;
/// <summary>
/// <para>(0014,4020) Pulser Settings Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PulserSettingsSequence: number = 1327136;
/// <summary>
/// <para>(0014,4022) Pulse Width</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static PulseWidth: number = 1327138;
/// <summary>
/// <para>(0014,4024) Excitation Frequency</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ExcitationFrequency: number = 1327140;
/// <summary>
/// <para>(0014,4026) Modulation Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ModulationType: number = 1327142;
/// <summary>
/// <para>(0014,4028) Damping</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static Damping: number = 1327144;
/// <summary>
/// <para>(0014,4030) Receiver Settings Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReceiverSettingsSequence: number = 1327152;
/// <summary>
/// <para>(0014,4031) Acquired Soundpath Length</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static AcquiredSoundpathLength: number = 1327153;
/// <summary>
/// <para>(0014,4032) Acquisition Compression Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AcquisitionCompressionType: number = 1327154;
/// <summary>
/// <para>(0014,4033) Acquisition Sample Size</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static AcquisitionSampleSize: number = 1327155;
/// <summary>
/// <para>(0014,4034) Rectifier Smoothing</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static RectifierSmoothing: number = 1327156;
/// <summary>
/// <para>(0014,4035) DAC Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DacSequence: number = 1327157;
/// <summary>
/// <para>(0014,4036) DAC Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DacType: number = 1327158;
/// <summary>
/// <para>(0014,4038) DAC Gain Points</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static DacGainPoints: number = 1327160;
/// <summary>
/// <para>(0014,403A) DAC Time Points</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static DacTimePoints: number = 1327162;
/// <summary>
/// <para>(0014,403C) DAC Amplitude</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static DacAmplitude: number = 1327164;
/// <summary>
/// <para>(0014,4040) Pre-Amplifier Settings Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PreAmplifierSettingsSequence: number = 1327168;
/// <summary>
/// <para>(0014,4050) Transmit Transducer Settings Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TransmitTransducerSettingsSequence: number = 1327184;
/// <summary>
/// <para>(0014,4051) Receive Transducer Settings Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReceiveTransducerSettingsSequence: number = 1327185;
/// <summary>
/// <para>(0014,4052) Incident Angle</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static IncidentAngle: number = 1327186;
/// <summary>
/// <para>(0014,4054) Coupling Technique</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static CouplingTechnique: number = 1327188;
/// <summary>
/// <para>(0014,4056) Coupling Medium</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static CouplingMedium: number = 1327190;
/// <summary>
/// <para>(0014,4057) Coupling Velocity</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static CouplingVelocity: number = 1327191;
/// <summary>
/// <para>(0014,4058) Crystal Center Location X</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static CrystalCenterLocationX: number = 1327192;
/// <summary>
/// <para>(0014,4059) Crystal Center Location Z</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static CrystalCenterLocationZ: number = 1327193;
/// <summary>
/// <para>(0014,405A) Sound Path Length</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SoundPathLength: number = 1327194;
/// <summary>
/// <para>(0014,405C) Delay Law Identifier</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static DelayLawIdentifier: number = 1327196;
/// <summary>
/// <para>(0014,4060) Gate Settings Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static GateSettingsSequence: number = 1327200;
/// <summary>
/// <para>(0014,4062) Gate Threshold</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static GateThreshold: number = 1327202;
/// <summary>
/// <para>(0014,4064) Velocity of Sound</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static VelocityOfSound: number = 1327204;
/// <summary>
/// <para>(0014,4070) Calibration Settings Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CalibrationSettingsSequence: number = 1327216;
/// <summary>
/// <para>(0014,4072) Calibration Procedure</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static CalibrationProcedure: number = 1327218;
/// <summary>
/// <para>(0014,4074) Procedure Version</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static ProcedureVersion: number = 1327220;
/// <summary>
/// <para>(0014,4076) Procedure Creation Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static ProcedureCreationDate: number = 1327222;
/// <summary>
/// <para>(0014,4078) Procedure Expiration Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static ProcedureExpirationDate: number = 1327224;
/// <summary>
/// <para>(0014,407A) Procedure Last Modified Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static ProcedureLastModifiedDate: number = 1327226;
/// <summary>
/// <para>(0014,407C) Calibration Time</para>
/// <para> VR: TM VM:1-n</para>
/// </summary>
public static CalibrationTime: number = 1327228;
/// <summary>
/// <para>(0014,407E) Calibration Date</para>
/// <para> VR: DA VM:1-n</para>
/// </summary>
public static CalibrationDate: number = 1327230;
/// <summary>
/// <para>(0014,5002) LINAC Energy</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static LinacEnergy: number = 1331202;
/// <summary>
/// <para>(0014,5004) LINAC Output</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static LinacOutput: number = 1331204;
/// <summary>
/// <para>(0018,0010) Contrast/Bolus Agent</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ContrastBolusAgent: number = 1572880;
/// <summary>
/// <para>(0018,0012) Contrast/Bolus Agent Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ContrastBolusAgentSequence: number = 1572882;
/// <summary>
/// <para>(0018,0014) Contrast/Bolus Administration Route Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ContrastBolusAdministrationRouteSequence: number = 1572884;
/// <summary>
/// <para>(0018,0015) Body Part Examined</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BodyPartExamined: number = 1572885;
/// <summary>
/// <para>(0018,0020) Scanning Sequence</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static ScanningSequence: number = 1572896;
/// <summary>
/// <para>(0018,0021) Sequence Variant</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static SequenceVariant: number = 1572897;
/// <summary>
/// <para>(0018,0022) Scan Options</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static ScanOptions: number = 1572898;
/// <summary>
/// <para>(0018,0023) MR Acquisition Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static MrAcquisitionType: number = 1572899;
/// <summary>
/// <para>(0018,0024) Sequence Name</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static SequenceName: number = 1572900;
/// <summary>
/// <para>(0018,0025) Angio Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AngioFlag: number = 1572901;
/// <summary>
/// <para>(0018,0026) Intervention Drug Information Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static InterventionDrugInformationSequence: number = 1572902;
/// <summary>
/// <para>(0018,0027) Intervention Drug Stop Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static InterventionDrugStopTime: number = 1572903;
/// <summary>
/// <para>(0018,0028) Intervention Drug Dose</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static InterventionDrugDose: number = 1572904;
/// <summary>
/// <para>(0018,0029) Intervention Drug Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static InterventionDrugCodeSequence: number = 1572905;
/// <summary>
/// <para>(0018,002A) Additional Drug Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AdditionalDrugSequence: number = 1572906;
/// <summary>
/// <para>(0018,0030) Radionuclide</para>
/// <para> VR: LO VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static RadionuclideRetired: number = 1572912;
/// <summary>
/// <para>(0018,0031) Radiopharmaceutical</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static Radiopharmaceutical: number = 1572913;
/// <summary>
/// <para>(0018,0032) Energy Window Centerline</para>
/// <para> VR: DS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static EnergyWindowCenterlineRetired: number = 1572914;
/// <summary>
/// <para>(0018,0033) Energy Window Total Width</para>
/// <para> VR: DS VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static EnergyWindowTotalWidthRetired: number = 1572915;
/// <summary>
/// <para>(0018,0034) Intervention Drug Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static InterventionDrugName: number = 1572916;
/// <summary>
/// <para>(0018,0035) Intervention Drug Start Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static InterventionDrugStartTime: number = 1572917;
/// <summary>
/// <para>(0018,0036) Intervention Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static InterventionSequence: number = 1572918;
/// <summary>
/// <para>(0018,0037) Therapy Type</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TherapyTypeRetired: number = 1572919;
/// <summary>
/// <para>(0018,0038) Intervention Status</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static InterventionStatus: number = 1572920;
/// <summary>
/// <para>(0018,0039) Therapy Description</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TherapyDescriptionRetired: number = 1572921;
/// <summary>
/// <para>(0018,003A) Intervention Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static InterventionDescription: number = 1572922;
/// <summary>
/// <para>(0018,0040) Cine Rate </para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static CineRate: number = 1572928;
/// <summary>
/// <para>(0018,0042) Initial Cine Run State</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static InitialCineRunState: number = 1572930;
/// <summary>
/// <para>(0018,0050) Slice Thickness</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SliceThickness: number = 1572944;
/// <summary>
/// <para>(0018,0060) KVP</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static Kvp: number = 1572960;
/// <summary>
/// <para>(0018,0070) Counts Accumulated</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static CountsAccumulated: number = 1572976;
/// <summary>
/// <para>(0018,0071) Acquisition Termination Condition</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AcquisitionTerminationCondition: number = 1572977;
/// <summary>
/// <para>(0018,0072) Effective Duration</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static EffectiveDuration: number = 1572978;
/// <summary>
/// <para>(0018,0073) Acquisition Start Condition</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AcquisitionStartCondition: number = 1572979;
/// <summary>
/// <para>(0018,0074) Acquisition Start Condition Data</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static AcquisitionStartConditionData: number = 1572980;
/// <summary>
/// <para>(0018,0075) Acquisition Termination Condition Data</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static AcquisitionTerminationConditionData: number = 1572981;
/// <summary>
/// <para>(0018,0080) Repetition Time</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static RepetitionTime: number = 1572992;
/// <summary>
/// <para>(0018,0081) Echo Time</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static EchoTime: number = 1572993;
/// <summary>
/// <para>(0018,0082) Inversion Time</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static InversionTime: number = 1572994;
/// <summary>
/// <para>(0018,0083) Number of Averages</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static NumberOfAverages: number = 1572995;
/// <summary>
/// <para>(0018,0084) Imaging Frequency</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ImagingFrequency: number = 1572996;
/// <summary>
/// <para>(0018,0085) Imaged Nucleus</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static ImagedNucleus: number = 1572997;
/// <summary>
/// <para>(0018,0086) Echo Number(s)</para>
/// <para> VR: IS VM:1-n</para>
/// </summary>
public static EchoNumbers: number = 1572998;
/// <summary>
/// <para>(0018,0087) Magnetic Field Strength</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static MagneticFieldStrength: number = 1572999;
/// <summary>
/// <para>(0018,0088) Spacing Between Slices</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SpacingBetweenSlices: number = 1573000;
/// <summary>
/// <para>(0018,0089) Number of Phase Encoding Steps</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfPhaseEncodingSteps: number = 1573001;
/// <summary>
/// <para>(0018,0090) Data Collection Diameter</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DataCollectionDiameter: number = 1573008;
/// <summary>
/// <para>(0018,0091) Echo Train Length</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static EchoTrainLength: number = 1573009;
/// <summary>
/// <para>(0018,0093) Percent Sampling</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static PercentSampling: number = 1573011;
/// <summary>
/// <para>(0018,0094) Percent Phase Field of View</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static PercentPhaseFieldOfView: number = 1573012;
/// <summary>
/// <para>(0018,0095) Pixel Bandwidth</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static PixelBandwidth: number = 1573013;
/// <summary>
/// <para>(0018,1000) Device Serial Number</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static DeviceSerialNumber: number = 1576960;
/// <summary>
/// <para>(0018,1002) Device UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static DeviceUid: number = 1576962;
/// <summary>
/// <para>(0018,1003) Device ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static DeviceId: number = 1576963;
/// <summary>
/// <para>(0018,1004) Plate ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PlateId: number = 1576964;
/// <summary>
/// <para>(0018,1005) Generator ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static GeneratorId: number = 1576965;
/// <summary>
/// <para>(0018,1006) Grid ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static GridId: number = 1576966;
/// <summary>
/// <para>(0018,1007) Cassette ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static CassetteId: number = 1576967;
/// <summary>
/// <para>(0018,1008) Gantry ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static GantryId: number = 1576968;
/// <summary>
/// <para>(0018,1010) Secondary Capture Device ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SecondaryCaptureDeviceId: number = 1576976;
/// <summary>
/// <para>(0018,1011) Hardcopy Creation Device ID</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static HardcopyCreationDeviceIdRetired: number = 1576977;
/// <summary>
/// <para>(0018,1012) Date of Secondary Capture</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static DateOfSecondaryCapture: number = 1576978;
/// <summary>
/// <para>(0018,1014) Time of Secondary Capture</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static TimeOfSecondaryCapture: number = 1576980;
/// <summary>
/// <para>(0018,1016) Secondary Capture Device Manufacturer</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SecondaryCaptureDeviceManufacturer: number = 1576982;
/// <summary>
/// <para>(0018,1017) Hardcopy Device Manufacturer</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static HardcopyDeviceManufacturerRetired: number = 1576983;
/// <summary>
/// <para>(0018,1018) Secondary Capture Device Manufacturer's Model Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SecondaryCaptureDeviceManufacturersModelName: number = 1576984;
/// <summary>
/// <para>(0018,1019) Secondary Capture Device Software Versions</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static SecondaryCaptureDeviceSoftwareVersions: number = 1576985;
/// <summary>
/// <para>(0018,101A) Hardcopy Device Software Version</para>
/// <para> VR: LO VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static HardcopyDeviceSoftwareVersionRetired: number = 1576986;
/// <summary>
/// <para>(0018,101B) Hardcopy Device Manufacturer's Model Name</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static HardcopyDeviceManufacturersModelNameRetired: number = 1576987;
/// <summary>
/// <para>(0018,1020) Software Version(s)</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static SoftwareVersions: number = 1576992;
/// <summary>
/// <para>(0018,1022) Video Image Format Acquired</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static VideoImageFormatAcquired: number = 1576994;
/// <summary>
/// <para>(0018,1023) Digital Image Format Acquired</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static DigitalImageFormatAcquired: number = 1576995;
/// <summary>
/// <para>(0018,1030) Protocol Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ProtocolName: number = 1577008;
/// <summary>
/// <para>(0018,1040) Contrast/Bolus Route</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ContrastBolusRoute: number = 1577024;
/// <summary>
/// <para>(0018,1041) Contrast/Bolus Volume</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ContrastBolusVolume: number = 1577025;
/// <summary>
/// <para>(0018,1042) Contrast/Bolus Start Time </para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static ContrastBolusStartTime: number = 1577026;
/// <summary>
/// <para>(0018,1043) Contrast/Bolus Stop Time </para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static ContrastBolusStopTime: number = 1577027;
/// <summary>
/// <para>(0018,1044) Contrast/Bolus Total Dose</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ContrastBolusTotalDose: number = 1577028;
/// <summary>
/// <para>(0018,1045) Syringe Counts</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static SyringeCounts: number = 1577029;
/// <summary>
/// <para>(0018,1046) Contrast Flow Rate</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static ContrastFlowRate: number = 1577030;
/// <summary>
/// <para>(0018,1047) Contrast Flow Duration</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static ContrastFlowDuration: number = 1577031;
/// <summary>
/// <para>(0018,1048) Contrast/Bolus Ingredient</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ContrastBolusIngredient: number = 1577032;
/// <summary>
/// <para>(0018,1049) Contrast/Bolus Ingredient Concentration</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ContrastBolusIngredientConcentration: number = 1577033;
/// <summary>
/// <para>(0018,1050) Spatial Resolution</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SpatialResolution: number = 1577040;
/// <summary>
/// <para>(0018,1060) Trigger Time</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TriggerTime: number = 1577056;
/// <summary>
/// <para>(0018,1061) Trigger Source or Type</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static TriggerSourceOrType: number = 1577057;
/// <summary>
/// <para>(0018,1062) Nominal Interval</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NominalInterval: number = 1577058;
/// <summary>
/// <para>(0018,1063) Frame Time</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static FrameTime: number = 1577059;
/// <summary>
/// <para>(0018,1064) Cardiac Framing Type</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static CardiacFramingType: number = 1577060;
/// <summary>
/// <para>(0018,1065) Frame Time Vector</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static FrameTimeVector: number = 1577061;
/// <summary>
/// <para>(0018,1066) Frame Delay</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static FrameDelay: number = 1577062;
/// <summary>
/// <para>(0018,1067) Image Trigger Delay</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ImageTriggerDelay: number = 1577063;
/// <summary>
/// <para>(0018,1068) Multiplex Group Time Offset</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static MultiplexGroupTimeOffset: number = 1577064;
/// <summary>
/// <para>(0018,1069) Trigger Time Offset</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TriggerTimeOffset: number = 1577065;
/// <summary>
/// <para>(0018,106A) Synchronization Trigger</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SynchronizationTrigger: number = 1577066;
/// <summary>
/// <para>(0018,106C) Synchronization Channel</para>
/// <para> VR: US VM:2</para>
/// </summary>
public static SynchronizationChannel: number = 1577068;
/// <summary>
/// <para>(0018,106E) Trigger Sample Position</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static TriggerSamplePosition: number = 1577070;
/// <summary>
/// <para>(0018,1070) Radiopharmaceutical Route</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static RadiopharmaceuticalRoute: number = 1577072;
/// <summary>
/// <para>(0018,1071) Radiopharmaceutical Volume</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static RadiopharmaceuticalVolume: number = 1577073;
/// <summary>
/// <para>(0018,1072) Radiopharmaceutical Start Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static RadiopharmaceuticalStartTime: number = 1577074;
/// <summary>
/// <para>(0018,1073) Radiopharmaceutical Stop Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static RadiopharmaceuticalStopTime: number = 1577075;
/// <summary>
/// <para>(0018,1074) Radionuclide Total Dose</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static RadionuclideTotalDose: number = 1577076;
/// <summary>
/// <para>(0018,1075) Radionuclide Half Life</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static RadionuclideHalfLife: number = 1577077;
/// <summary>
/// <para>(0018,1076) Radionuclide Positron Fraction</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static RadionuclidePositronFraction: number = 1577078;
/// <summary>
/// <para>(0018,1077) Radiopharmaceutical Specific Activity</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static RadiopharmaceuticalSpecificActivity: number = 1577079;
/// <summary>
/// <para>(0018,1078) Radiopharmaceutical Start DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static RadiopharmaceuticalStartDatetime: number = 1577080;
/// <summary>
/// <para>(0018,1079) Radiopharmaceutical Stop DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static RadiopharmaceuticalStopDatetime: number = 1577081;
/// <summary>
/// <para>(0018,1080) Beat Rejection Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BeatRejectionFlag: number = 1577088;
/// <summary>
/// <para>(0018,1081) Low R-R Value</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static LowRRValue: number = 1577089;
/// <summary>
/// <para>(0018,1082) High R-R Value</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static HighRRValue: number = 1577090;
/// <summary>
/// <para>(0018,1083) Intervals Acquired</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static IntervalsAcquired: number = 1577091;
/// <summary>
/// <para>(0018,1084) Intervals Rejected</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static IntervalsRejected: number = 1577092;
/// <summary>
/// <para>(0018,1085) PVC Rejection</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PvcRejection: number = 1577093;
/// <summary>
/// <para>(0018,1086) Skip Beats</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static SkipBeats: number = 1577094;
/// <summary>
/// <para>(0018,1088) Heart Rate</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static HeartRate: number = 1577096;
/// <summary>
/// <para>(0018,1090) Cardiac Number of Images</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static CardiacNumberOfImages: number = 1577104;
/// <summary>
/// <para>(0018,1094) Trigger Window</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static TriggerWindow: number = 1577108;
/// <summary>
/// <para>(0018,1100) Reconstruction Diameter</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ReconstructionDiameter: number = 1577216;
/// <summary>
/// <para>(0018,1110) Distance Source to Detector</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DistanceSourceToDetector: number = 1577232;
/// <summary>
/// <para>(0018,1111) Distance Source to Patient</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DistanceSourceToPatient: number = 1577233;
/// <summary>
/// <para>(0018,1114) Estimated Radiographic Magnification Factor</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static EstimatedRadiographicMagnificationFactor: number = 1577236;
/// <summary>
/// <para>(0018,1120) Gantry/Detector Tilt</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static GantryDetectorTilt: number = 1577248;
/// <summary>
/// <para>(0018,1121) Gantry/Detector Slew</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static GantryDetectorSlew: number = 1577249;
/// <summary>
/// <para>(0018,1130) Table Height</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TableHeight: number = 1577264;
/// <summary>
/// <para>(0018,1131) Table Traverse</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TableTraverse: number = 1577265;
/// <summary>
/// <para>(0018,1134) Table Motion</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TableMotion: number = 1577268;
/// <summary>
/// <para>(0018,1135) Table Vertical Increment</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static TableVerticalIncrement: number = 1577269;
/// <summary>
/// <para>(0018,1136) Table Lateral Increment</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static TableLateralIncrement: number = 1577270;
/// <summary>
/// <para>(0018,1137) Table Longitudinal Increment</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static TableLongitudinalIncrement: number = 1577271;
/// <summary>
/// <para>(0018,1138) Table Angle</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TableAngle: number = 1577272;
/// <summary>
/// <para>(0018,113A) Table Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TableType: number = 1577274;
/// <summary>
/// <para>(0018,1140) Rotation Direction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RotationDirection: number = 1577280;
/// <summary>
/// <para>(0018,1141) Angular Position</para>
/// <para> VR: DS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AngularPositionRetired: number = 1577281;
/// <summary>
/// <para>(0018,1142) Radial Position</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static RadialPosition: number = 1577282;
/// <summary>
/// <para>(0018,1143) Scan Arc</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ScanArc: number = 1577283;
/// <summary>
/// <para>(0018,1144) Angular Step</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static AngularStep: number = 1577284;
/// <summary>
/// <para>(0018,1145) Center of Rotation Offset</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static CenterOfRotationOffset: number = 1577285;
/// <summary>
/// <para>(0018,1146) Rotation Offset</para>
/// <para> VR: DS VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static RotationOffsetRetired: number = 1577286;
/// <summary>
/// <para>(0018,1147) Field of View Shape</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FieldOfViewShape: number = 1577287;
/// <summary>
/// <para>(0018,1149) Field of View Dimension(s)</para>
/// <para> VR: IS VM:1-2</para>
/// </summary>
public static FieldOfViewDimensions: number = 1577289;
/// <summary>
/// <para>(0018,1150) Exposure Time</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ExposureTime: number = 1577296;
/// <summary>
/// <para>(0018,1151) X-Ray Tube Current</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static XRayTubeCurrent: number = 1577297;
/// <summary>
/// <para>(0018,1152) Exposure </para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static Exposure: number = 1577298;
/// <summary>
/// <para>(0018,1153) Exposure in µAs</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ExposureInUas: number = 1577299;
/// <summary>
/// <para>(0018,1154) Average Pulse Width</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static AveragePulseWidth: number = 1577300;
/// <summary>
/// <para>(0018,1155) Radiation Setting</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RadiationSetting: number = 1577301;
/// <summary>
/// <para>(0018,1156) Rectification Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RectificationType: number = 1577302;
/// <summary>
/// <para>(0018,115A) Radiation Mode</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RadiationMode: number = 1577306;
/// <summary>
/// <para>(0018,115E) Image and Fluoroscopy Area Dose Product</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ImageAndFluoroscopyAreaDoseProduct: number = 1577310;
/// <summary>
/// <para>(0018,1160) Filter Type</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static FilterType: number = 1577312;
/// <summary>
/// <para>(0018,1161) Type of Filters</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static TypeOfFilters: number = 1577313;
/// <summary>
/// <para>(0018,1162) Intensifier Size</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static IntensifierSize: number = 1577314;
/// <summary>
/// <para>(0018,1164) Imager Pixel Spacing</para>
/// <para> VR: DS VM:2</para>
/// </summary>
public static ImagerPixelSpacing: number = 1577316;
/// <summary>
/// <para>(0018,1166) Grid</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static Grid: number = 1577318;
/// <summary>
/// <para>(0018,1170) Generator Power</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static GeneratorPower: number = 1577328;
/// <summary>
/// <para>(0018,1180) Collimator/grid Name </para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static CollimatorGridName: number = 1577344;
/// <summary>
/// <para>(0018,1181) Collimator Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CollimatorType: number = 1577345;
/// <summary>
/// <para>(0018,1182) Focal Distance</para>
/// <para> VR: IS VM:1-2</para>
/// </summary>
public static FocalDistance: number = 1577346;
/// <summary>
/// <para>(0018,1183) X Focus Center</para>
/// <para> VR: DS VM:1-2</para>
/// </summary>
public static XFocusCenter: number = 1577347;
/// <summary>
/// <para>(0018,1184) Y Focus Center</para>
/// <para> VR: DS VM:1-2</para>
/// </summary>
public static YFocusCenter: number = 1577348;
/// <summary>
/// <para>(0018,1190) Focal Spot(s)</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static FocalSpots: number = 1577360;
/// <summary>
/// <para>(0018,1191) Anode Target Material</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AnodeTargetMaterial: number = 1577361;
/// <summary>
/// <para>(0018,11A0) Body Part Thickness</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static BodyPartThickness: number = 1577376;
/// <summary>
/// <para>(0018,11A2) Compression Force</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static CompressionForce: number = 1577378;
/// <summary>
/// <para>(0018,1200) Date of Last Calibration</para>
/// <para> VR: DA VM:1-n</para>
/// </summary>
public static DateOfLastCalibration: number = 1577472;
/// <summary>
/// <para>(0018,1201) Time of Last Calibration</para>
/// <para> VR: TM VM:1-n</para>
/// </summary>
public static TimeOfLastCalibration: number = 1577473;
/// <summary>
/// <para>(0018,1210) Convolution Kernel</para>
/// <para> VR: SH VM:1-n</para>
/// </summary>
public static ConvolutionKernel: number = 1577488;
/// <summary>
/// <para>(0018,1240) Upper/Lower Pixel Values</para>
/// <para> VR: IS VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static UpperLowerPixelValuesRetired: number = 1577536;
/// <summary>
/// <para>(0018,1242) Actual Frame Duration</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ActualFrameDuration: number = 1577538;
/// <summary>
/// <para>(0018,1243) Count Rate</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static CountRate: number = 1577539;
/// <summary>
/// <para>(0018,1244) Preferred Playback Sequencing</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static PreferredPlaybackSequencing: number = 1577540;
/// <summary>
/// <para>(0018,1250) Receive Coil Name</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static ReceiveCoilName: number = 1577552;
/// <summary>
/// <para>(0018,1251) Transmit Coil Name</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static TransmitCoilName: number = 1577553;
/// <summary>
/// <para>(0018,1260) Plate Type</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static PlateType: number = 1577568;
/// <summary>
/// <para>(0018,1261) Phosphor Type</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PhosphorType: number = 1577569;
/// <summary>
/// <para>(0018,1300) Scan Velocity</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ScanVelocity: number = 1577728;
/// <summary>
/// <para>(0018,1301) Whole Body Technique</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static WholeBodyTechnique: number = 1577729;
/// <summary>
/// <para>(0018,1302) Scan Length</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ScanLength: number = 1577730;
/// <summary>
/// <para>(0018,1310) Acquisition Matrix</para>
/// <para> VR: US VM:4</para>
/// </summary>
public static AcquisitionMatrix: number = 1577744;
/// <summary>
/// <para>(0018,1312) In-plane Phase Encoding Direction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static InPlanePhaseEncodingDirection: number = 1577746;
/// <summary>
/// <para>(0018,1314) Flip Angle</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static FlipAngle: number = 1577748;
/// <summary>
/// <para>(0018,1315) Variable Flip Angle Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static VariableFlipAngleFlag: number = 1577749;
/// <summary>
/// <para>(0018,1316) SAR</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static Sar: number = 1577750;
/// <summary>
/// <para>(0018,1318) dB/dt</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DbDt: number = 1577752;
/// <summary>
/// <para>(0018,1400) Acquisition Device Processing Description </para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static AcquisitionDeviceProcessingDescription: number = 1577984;
/// <summary>
/// <para>(0018,1401) Acquisition Device Processing Code</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static AcquisitionDeviceProcessingCode: number = 1577985;
/// <summary>
/// <para>(0018,1402) Cassette Orientation</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CassetteOrientation: number = 1577986;
/// <summary>
/// <para>(0018,1403) Cassette Size</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CassetteSize: number = 1577987;
/// <summary>
/// <para>(0018,1404) Exposures on Plate</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ExposuresOnPlate: number = 1577988;
/// <summary>
/// <para>(0018,1405) Relative X-Ray Exposure</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static RelativeXRayExposure: number = 1577989;
/// <summary>
/// <para>(0018,1411) Exposure Index</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ExposureIndex: number = 1578001;
/// <summary>
/// <para>(0018,1412) Target Exposure Index</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TargetExposureIndex: number = 1578002;
/// <summary>
/// <para>(0018,1413) Deviation Index</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DeviationIndex: number = 1578003;
/// <summary>
/// <para>(0018,1450) Column Angulation</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ColumnAngulation: number = 1578064;
/// <summary>
/// <para>(0018,1460) Tomo Layer Height</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TomoLayerHeight: number = 1578080;
/// <summary>
/// <para>(0018,1470) Tomo Angle</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TomoAngle: number = 1578096;
/// <summary>
/// <para>(0018,1480) Tomo Time</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TomoTime: number = 1578112;
/// <summary>
/// <para>(0018,1490) Tomo Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TomoType: number = 1578128;
/// <summary>
/// <para>(0018,1491) Tomo Class</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TomoClass: number = 1578129;
/// <summary>
/// <para>(0018,1495) Number of Tomosynthesis Source Images</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfTomosynthesisSourceImages: number = 1578133;
/// <summary>
/// <para>(0018,1500) Positioner Motion</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PositionerMotion: number = 1578240;
/// <summary>
/// <para>(0018,1508) Positioner Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PositionerType: number = 1578248;
/// <summary>
/// <para>(0018,1510) Positioner Primary Angle</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static PositionerPrimaryAngle: number = 1578256;
/// <summary>
/// <para>(0018,1511) Positioner Secondary Angle</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static PositionerSecondaryAngle: number = 1578257;
/// <summary>
/// <para>(0018,1520) Positioner Primary Angle Increment</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static PositionerPrimaryAngleIncrement: number = 1578272;
/// <summary>
/// <para>(0018,1521) Positioner Secondary Angle Increment</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static PositionerSecondaryAngleIncrement: number = 1578273;
/// <summary>
/// <para>(0018,1530) Detector Primary Angle</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DetectorPrimaryAngle: number = 1578288;
/// <summary>
/// <para>(0018,1531) Detector Secondary Angle</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DetectorSecondaryAngle: number = 1578289;
/// <summary>
/// <para>(0018,1600) Shutter Shape</para>
/// <para> VR: CS VM:1-3</para>
/// </summary>
public static ShutterShape: number = 1578496;
/// <summary>
/// <para>(0018,1602) Shutter Left Vertical Edge</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ShutterLeftVerticalEdge: number = 1578498;
/// <summary>
/// <para>(0018,1604) Shutter Right Vertical Edge</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ShutterRightVerticalEdge: number = 1578500;
/// <summary>
/// <para>(0018,1606) Shutter Upper Horizontal Edge</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ShutterUpperHorizontalEdge: number = 1578502;
/// <summary>
/// <para>(0018,1608) Shutter Lower Horizontal Edge</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ShutterLowerHorizontalEdge: number = 1578504;
/// <summary>
/// <para>(0018,1610) Center of Circular Shutter</para>
/// <para> VR: IS VM:2</para>
/// </summary>
public static CenterOfCircularShutter: number = 1578512;
/// <summary>
/// <para>(0018,1612) Radius of Circular Shutter</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static RadiusOfCircularShutter: number = 1578514;
/// <summary>
/// <para>(0018,1620) Vertices of the Polygonal Shutter</para>
/// <para> VR: IS VM:2-2n</para>
/// </summary>
public static VerticesOfThePolygonalShutter: number = 1578528;
/// <summary>
/// <para>(0018,1622) Shutter Presentation Value</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ShutterPresentationValue: number = 1578530;
/// <summary>
/// <para>(0018,1623) Shutter Overlay Group</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ShutterOverlayGroup: number = 1578531;
/// <summary>
/// <para>(0018,1624) Shutter Presentation Color CIELab Value</para>
/// <para> VR: US VM:3</para>
/// </summary>
public static ShutterPresentationColorCielabValue: number = 1578532;
/// <summary>
/// <para>(0018,1700) Collimator Shape</para>
/// <para> VR: CS VM:1-3</para>
/// </summary>
public static CollimatorShape: number = 1578752;
/// <summary>
/// <para>(0018,1702) Collimator Left Vertical Edge</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static CollimatorLeftVerticalEdge: number = 1578754;
/// <summary>
/// <para>(0018,1704) Collimator Right Vertical Edge</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static CollimatorRightVerticalEdge: number = 1578756;
/// <summary>
/// <para>(0018,1706) Collimator Upper Horizontal Edge</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static CollimatorUpperHorizontalEdge: number = 1578758;
/// <summary>
/// <para>(0018,1708) Collimator Lower Horizontal Edge</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static CollimatorLowerHorizontalEdge: number = 1578760;
/// <summary>
/// <para>(0018,1710) Center of Circular Collimator</para>
/// <para> VR: IS VM:2</para>
/// </summary>
public static CenterOfCircularCollimator: number = 1578768;
/// <summary>
/// <para>(0018,1712) Radius of Circular Collimator</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static RadiusOfCircularCollimator: number = 1578770;
/// <summary>
/// <para>(0018,1720) Vertices of the Polygonal Collimator</para>
/// <para> VR: IS VM:2-2n</para>
/// </summary>
public static VerticesOfThePolygonalCollimator: number = 1578784;
/// <summary>
/// <para>(0018,1800) Acquisition Time Synchronized</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AcquisitionTimeSynchronized: number = 1579008;
/// <summary>
/// <para>(0018,1801) Time Source</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static TimeSource: number = 1579009;
/// <summary>
/// <para>(0018,1802) Time Distribution Protocol</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TimeDistributionProtocol: number = 1579010;
/// <summary>
/// <para>(0018,1803) NTP Source Address</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static NtpSourceAddress: number = 1579011;
/// <summary>
/// <para>(0018,2001) Page Number Vector</para>
/// <para> VR: IS VM:1-n</para>
/// </summary>
public static PageNumberVector: number = 1581057;
/// <summary>
/// <para>(0018,2002) Frame Label Vector</para>
/// <para> VR: SH VM:1-n</para>
/// </summary>
public static FrameLabelVector: number = 1581058;
/// <summary>
/// <para>(0018,2003) Frame Primary Angle Vector</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static FramePrimaryAngleVector: number = 1581059;
/// <summary>
/// <para>(0018,2004) Frame Secondary Angle Vector</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static FrameSecondaryAngleVector: number = 1581060;
/// <summary>
/// <para>(0018,2005) Slice Location Vector</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static SliceLocationVector: number = 1581061;
/// <summary>
/// <para>(0018,2006) Display Window Label Vector</para>
/// <para> VR: SH VM:1-n</para>
/// </summary>
public static DisplayWindowLabelVector: number = 1581062;
/// <summary>
/// <para>(0018,2010) Nominal Scanned Pixel Spacing</para>
/// <para> VR: DS VM:2</para>
/// </summary>
public static NominalScannedPixelSpacing: number = 1581072;
/// <summary>
/// <para>(0018,2020) Digitizing Device Transport Direction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DigitizingDeviceTransportDirection: number = 1581088;
/// <summary>
/// <para>(0018,2030) Rotation of Scanned Film</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static RotationOfScannedFilm: number = 1581104;
/// <summary>
/// <para>(0018,3100) IVUS Acquisition</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static IvusAcquisition: number = 1585408;
/// <summary>
/// <para>(0018,3101) IVUS Pullback Rate</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static IvusPullbackRate: number = 1585409;
/// <summary>
/// <para>(0018,3102) IVUS Gated Rate</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static IvusGatedRate: number = 1585410;
/// <summary>
/// <para>(0018,3103) IVUS Pullback Start Frame Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static IvusPullbackStartFrameNumber: number = 1585411;
/// <summary>
/// <para>(0018,3104) IVUS Pullback Stop Frame Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static IvusPullbackStopFrameNumber: number = 1585412;
/// <summary>
/// <para>(0018,3105) Lesion Number </para>
/// <para> VR: IS VM:1-n</para>
/// </summary>
public static LesionNumber: number = 1585413;
/// <summary>
/// <para>(0018,4000) Acquisition Comments</para>
/// <para> VR: LT VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AcquisitionCommentsRetired: number = 1589248;
/// <summary>
/// <para>(0018,5000) Output Power</para>
/// <para> VR: SH VM:1-n</para>
/// </summary>
public static OutputPower: number = 1593344;
/// <summary>
/// <para>(0018,5010) Transducer Data</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static TransducerData: number = 1593360;
/// <summary>
/// <para>(0018,5012) Focus Depth</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static FocusDepth: number = 1593362;
/// <summary>
/// <para>(0018,5020) Processing Function</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ProcessingFunction: number = 1593376;
/// <summary>
/// <para>(0018,5021) Postprocessing Function</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PostprocessingFunctionRetired: number = 1593377;
/// <summary>
/// <para>(0018,5022) Mechanical Index</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static MechanicalIndex: number = 1593378;
/// <summary>
/// <para>(0018,5024) Bone Thermal Index</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static BoneThermalIndex: number = 1593380;
/// <summary>
/// <para>(0018,5026) Cranial Thermal Index</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static CranialThermalIndex: number = 1593382;
/// <summary>
/// <para>(0018,5027) Soft Tissue Thermal Index</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SoftTissueThermalIndex: number = 1593383;
/// <summary>
/// <para>(0018,5028) Soft Tissue-focus Thermal Index</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SoftTissueFocusThermalIndex: number = 1593384;
/// <summary>
/// <para>(0018,5029) Soft Tissue-surface Thermal Index</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SoftTissueSurfaceThermalIndex: number = 1593385;
/// <summary>
/// <para>(0018,5030) Dynamic Range</para>
/// <para> VR: DS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DynamicRangeRetired: number = 1593392;
/// <summary>
/// <para>(0018,5040) Total Gain</para>
/// <para> VR: DS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TotalGainRetired: number = 1593408;
/// <summary>
/// <para>(0018,5050) Depth of Scan Field</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static DepthOfScanField: number = 1593424;
/// <summary>
/// <para>(0018,5100) Patient Position</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PatientPosition: number = 1593600;
/// <summary>
/// <para>(0018,5101) View Position</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ViewPosition: number = 1593601;
/// <summary>
/// <para>(0018,5104) Projection Eponymous Name Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ProjectionEponymousNameCodeSequence: number = 1593604;
/// <summary>
/// <para>(0018,5210) Image Transformation Matrix</para>
/// <para> VR: DS VM:6</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ImageTransformationMatrixRetired: number = 1593872;
/// <summary>
/// <para>(0018,5212) Image Translation Vector</para>
/// <para> VR: DS VM:3</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ImageTranslationVectorRetired: number = 1593874;
/// <summary>
/// <para>(0018,6000) Sensitivity</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static Sensitivity: number = 1597440;
/// <summary>
/// <para>(0018,6011) Sequence of Ultrasound Regions</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SequenceOfUltrasoundRegions: number = 1597457;
/// <summary>
/// <para>(0018,6012) Region Spatial Format</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static RegionSpatialFormat: number = 1597458;
/// <summary>
/// <para>(0018,6014) Region Data Type</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static RegionDataType: number = 1597460;
/// <summary>
/// <para>(0018,6016) Region Flags</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static RegionFlags: number = 1597462;
/// <summary>
/// <para>(0018,6018) Region Location Min X0</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static RegionLocationMinX0: number = 1597464;
/// <summary>
/// <para>(0018,601A) Region Location Min Y0</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static RegionLocationMinY0: number = 1597466;
/// <summary>
/// <para>(0018,601C) Region Location Max X1</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static RegionLocationMaxX1: number = 1597468;
/// <summary>
/// <para>(0018,601E) Region Location Max Y1</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static RegionLocationMaxY1: number = 1597470;
/// <summary>
/// <para>(0018,6020) Reference Pixel X0</para>
/// <para> VR: SL VM:1</para>
/// </summary>
public static ReferencePixelX0: number = 1597472;
/// <summary>
/// <para>(0018,6022) Reference Pixel Y0</para>
/// <para> VR: SL VM:1</para>
/// </summary>
public static ReferencePixelY0: number = 1597474;
/// <summary>
/// <para>(0018,6024) Physical Units X Direction</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static PhysicalUnitsXDirection: number = 1597476;
/// <summary>
/// <para>(0018,6026) Physical Units Y Direction</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static PhysicalUnitsYDirection: number = 1597478;
/// <summary>
/// <para>(0018,6028) Reference Pixel Physical Value X</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ReferencePixelPhysicalValueX: number = 1597480;
/// <summary>
/// <para>(0018,602A) Reference Pixel Physical Value Y</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ReferencePixelPhysicalValueY: number = 1597482;
/// <summary>
/// <para>(0018,602C) Physical Delta X</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static PhysicalDeltaX: number = 1597484;
/// <summary>
/// <para>(0018,602E) Physical Delta Y</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static PhysicalDeltaY: number = 1597486;
/// <summary>
/// <para>(0018,6030) Transducer Frequency</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static TransducerFrequency: number = 1597488;
/// <summary>
/// <para>(0018,6031) Transducer Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TransducerType: number = 1597489;
/// <summary>
/// <para>(0018,6032) Pulse Repetition Frequency</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static PulseRepetitionFrequency: number = 1597490;
/// <summary>
/// <para>(0018,6034) Doppler Correction Angle</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static DopplerCorrectionAngle: number = 1597492;
/// <summary>
/// <para>(0018,6036) Steering Angle</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static SteeringAngle: number = 1597494;
/// <summary>
/// <para>(0018,6038) Doppler Sample Volume X Position (Retired)</para>
/// <para> VR: UL VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DopplerSampleVolumeXPositionRetired: number = 1597496;
/// <summary>
/// <para>(0018,6039) Doppler Sample Volume X Position</para>
/// <para> VR: SL VM:1</para>
/// </summary>
public static DopplerSampleVolumeXPosition: number = 1597497;
/// <summary>
/// <para>(0018,603A) Doppler Sample Volume Y Position (Retired)</para>
/// <para> VR: UL VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DopplerSampleVolumeYPositionRetired: number = 1597498;
/// <summary>
/// <para>(0018,603B) Doppler Sample Volume Y Position</para>
/// <para> VR: SL VM:1</para>
/// </summary>
public static DopplerSampleVolumeYPosition: number = 1597499;
/// <summary>
/// <para>(0018,603C) TM-Line Position X0 (Retired)</para>
/// <para> VR: UL VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TmLinePositionX0Retired: number = 1597500;
/// <summary>
/// <para>(0018,603D) TM-Line Position X0</para>
/// <para> VR: SL VM:1</para>
/// </summary>
public static TmLinePositionX0: number = 1597501;
/// <summary>
/// <para>(0018,603E) TM-Line Position Y0 (Retired)</para>
/// <para> VR: UL VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TmLinePositionY0Retired: number = 1597502;
/// <summary>
/// <para>(0018,603F) TM-Line Position Y0</para>
/// <para> VR: SL VM:1</para>
/// </summary>
public static TmLinePositionY0: number = 1597503;
/// <summary>
/// <para>(0018,6040) TM-Line Position X1 (Retired)</para>
/// <para> VR: UL VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TmLinePositionX1Retired: number = 1597504;
/// <summary>
/// <para>(0018,6041) TM-Line Position X1</para>
/// <para> VR: SL VM:1</para>
/// </summary>
public static TmLinePositionX1: number = 1597505;
/// <summary>
/// <para>(0018,6042) TM-Line Position Y1 (Retired)</para>
/// <para> VR: UL VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TmLinePositionY1Retired: number = 1597506;
/// <summary>
/// <para>(0018,6043) TM-Line Position Y1</para>
/// <para> VR: SL VM:1</para>
/// </summary>
public static TmLinePositionY1: number = 1597507;
/// <summary>
/// <para>(0018,6044) Pixel Component Organization</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static PixelComponentOrganization: number = 1597508;
/// <summary>
/// <para>(0018,6046) Pixel Component Mask</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static PixelComponentMask: number = 1597510;
/// <summary>
/// <para>(0018,6048) Pixel Component Range Start</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static PixelComponentRangeStart: number = 1597512;
/// <summary>
/// <para>(0018,604A) Pixel Component Range Stop</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static PixelComponentRangeStop: number = 1597514;
/// <summary>
/// <para>(0018,604C) Pixel Component Physical Units</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static PixelComponentPhysicalUnits: number = 1597516;
/// <summary>
/// <para>(0018,604E) Pixel Component Data Type</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static PixelComponentDataType: number = 1597518;
/// <summary>
/// <para>(0018,6050) Number of Table Break Points</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static NumberOfTableBreakPoints: number = 1597520;
/// <summary>
/// <para>(0018,6052) Table of X Break Points</para>
/// <para> VR: UL VM:1-n</para>
/// </summary>
public static TableOfXBreakPoints: number = 1597522;
/// <summary>
/// <para>(0018,6054) Table of Y Break Points</para>
/// <para> VR: FD VM:1-n</para>
/// </summary>
public static TableOfYBreakPoints: number = 1597524;
/// <summary>
/// <para>(0018,6056) Number of Table Entries</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static NumberOfTableEntries: number = 1597526;
/// <summary>
/// <para>(0018,6058) Table of Pixel Values</para>
/// <para> VR: UL VM:1-n</para>
/// </summary>
public static TableOfPixelValues: number = 1597528;
/// <summary>
/// <para>(0018,605A) Table of Parameter Values</para>
/// <para> VR: FL VM:1-n</para>
/// </summary>
public static TableOfParameterValues: number = 1597530;
/// <summary>
/// <para>(0018,6060) R Wave Time Vector</para>
/// <para> VR: FL VM:1-n</para>
/// </summary>
public static RWaveTimeVector: number = 1597536;
/// <summary>
/// <para>(0018,7000) Detector Conditions Nominal Flag </para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DetectorConditionsNominalFlag: number = 1601536;
/// <summary>
/// <para>(0018,7001) Detector Temperature</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DetectorTemperature: number = 1601537;
/// <summary>
/// <para>(0018,7004) Detector Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DetectorType: number = 1601540;
/// <summary>
/// <para>(0018,7005) Detector Configuration</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DetectorConfiguration: number = 1601541;
/// <summary>
/// <para>(0018,7006) Detector Description</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static DetectorDescription: number = 1601542;
/// <summary>
/// <para>(0018,7008) Detector Mode</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static DetectorMode: number = 1601544;
/// <summary>
/// <para>(0018,700A) Detector ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static DetectorId: number = 1601546;
/// <summary>
/// <para>(0018,700C) Date of Last Detector Calibration </para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static DateOfLastDetectorCalibration: number = 1601548;
/// <summary>
/// <para>(0018,700E) Time of Last Detector Calibration</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static TimeOfLastDetectorCalibration: number = 1601550;
/// <summary>
/// <para>(0018,7010) Exposures on Detector Since Last Calibration </para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ExposuresOnDetectorSinceLastCalibration: number = 1601552;
/// <summary>
/// <para>(0018,7011) Exposures on Detector Since Manufactured </para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ExposuresOnDetectorSinceManufactured: number = 1601553;
/// <summary>
/// <para>(0018,7012) Detector Time Since Last Exposure </para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DetectorTimeSinceLastExposure: number = 1601554;
/// <summary>
/// <para>(0018,7014) Detector Active Time </para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DetectorActiveTime: number = 1601556;
/// <summary>
/// <para>(0018,7016) Detector Activation Offset From Exposure</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DetectorActivationOffsetFromExposure: number = 1601558;
/// <summary>
/// <para>(0018,701A) Detector Binning </para>
/// <para> VR: DS VM:2</para>
/// </summary>
public static DetectorBinning: number = 1601562;
/// <summary>
/// <para>(0018,7020) Detector Element Physical Size</para>
/// <para> VR: DS VM:2</para>
/// </summary>
public static DetectorElementPhysicalSize: number = 1601568;
/// <summary>
/// <para>(0018,7022) Detector Element Spacing</para>
/// <para> VR: DS VM:2</para>
/// </summary>
public static DetectorElementSpacing: number = 1601570;
/// <summary>
/// <para>(0018,7024) Detector Active Shape</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DetectorActiveShape: number = 1601572;
/// <summary>
/// <para>(0018,7026) Detector Active Dimension(s)</para>
/// <para> VR: DS VM:1-2</para>
/// </summary>
public static DetectorActiveDimensions: number = 1601574;
/// <summary>
/// <para>(0018,7028) Detector Active Origin</para>
/// <para> VR: DS VM:2</para>
/// </summary>
public static DetectorActiveOrigin: number = 1601576;
/// <summary>
/// <para>(0018,702A) Detector Manufacturer Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static DetectorManufacturerName: number = 1601578;
/// <summary>
/// <para>(0018,702B) Detector Manufacturer's Model Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static DetectorManufacturersModelName: number = 1601579;
/// <summary>
/// <para>(0018,7030) Field of View Origin</para>
/// <para> VR: DS VM:2</para>
/// </summary>
public static FieldOfViewOrigin: number = 1601584;
/// <summary>
/// <para>(0018,7032) Field of View Rotation</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static FieldOfViewRotation: number = 1601586;
/// <summary>
/// <para>(0018,7034) Field of View Horizontal Flip</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FieldOfViewHorizontalFlip: number = 1601588;
/// <summary>
/// <para>(0018,7036) Pixel Data Area Origin Relative To FOV</para>
/// <para> VR: FL VM:2</para>
/// </summary>
public static PixelDataAreaOriginRelativeToFov: number = 1601590;
/// <summary>
/// <para>(0018,7038) Pixel Data Area Rotation Angle Relative To FOV</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static PixelDataAreaRotationAngleRelativeToFov: number = 1601592;
/// <summary>
/// <para>(0018,7040) Grid Absorbing Material</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static GridAbsorbingMaterial: number = 1601600;
/// <summary>
/// <para>(0018,7041) Grid Spacing Material</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static GridSpacingMaterial: number = 1601601;
/// <summary>
/// <para>(0018,7042) Grid Thickness</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static GridThickness: number = 1601602;
/// <summary>
/// <para>(0018,7044) Grid Pitch</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static GridPitch: number = 1601604;
/// <summary>
/// <para>(0018,7046) Grid Aspect Ratio</para>
/// <para> VR: IS VM:2</para>
/// </summary>
public static GridAspectRatio: number = 1601606;
/// <summary>
/// <para>(0018,7048) Grid Period</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static GridPeriod: number = 1601608;
/// <summary>
/// <para>(0018,704C) Grid Focal Distance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static GridFocalDistance: number = 1601612;
/// <summary>
/// <para>(0018,7050) Filter Material</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static FilterMaterial: number = 1601616;
/// <summary>
/// <para>(0018,7052) Filter Thickness Minimum</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static FilterThicknessMinimum: number = 1601618;
/// <summary>
/// <para>(0018,7054) Filter Thickness Maximum</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static FilterThicknessMaximum: number = 1601620;
/// <summary>
/// <para>(0018,7056) Filter Beam Path Length Minimum</para>
/// <para> VR: FL VM:1-n</para>
/// </summary>
public static FilterBeamPathLengthMinimum: number = 1601622;
/// <summary>
/// <para>(0018,7058) Filter Beam Path Length Maximum</para>
/// <para> VR: FL VM:1-n</para>
/// </summary>
public static FilterBeamPathLengthMaximum: number = 1601624;
/// <summary>
/// <para>(0018,7060) Exposure Control Mode</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ExposureControlMode: number = 1601632;
/// <summary>
/// <para>(0018,7062) Exposure Control Mode Description</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static ExposureControlModeDescription: number = 1601634;
/// <summary>
/// <para>(0018,7064) Exposure Status</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ExposureStatus: number = 1601636;
/// <summary>
/// <para>(0018,7065) Phototimer Setting</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static PhototimerSetting: number = 1601637;
/// <summary>
/// <para>(0018,8150) Exposure Time in µS</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ExposureTimeInUs: number = 1605968;
/// <summary>
/// <para>(0018,8151) X-Ray Tube Current in µA</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static XRayTubeCurrentInUa: number = 1605969;
/// <summary>
/// <para>(0018,9004) Content Qualification</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ContentQualification: number = 1609732;
/// <summary>
/// <para>(0018,9005) Pulse Sequence Name</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static PulseSequenceName: number = 1609733;
/// <summary>
/// <para>(0018,9006) MR Imaging Modifier Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MrImagingModifierSequence: number = 1609734;
/// <summary>
/// <para>(0018,9008) Echo Pulse Sequence</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static EchoPulseSequence: number = 1609736;
/// <summary>
/// <para>(0018,9009) Inversion Recovery</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static InversionRecovery: number = 1609737;
/// <summary>
/// <para>(0018,9010) Flow Compensation</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FlowCompensation: number = 1609744;
/// <summary>
/// <para>(0018,9011) Multiple Spin Echo</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static MultipleSpinEcho: number = 1609745;
/// <summary>
/// <para>(0018,9012) Multi-planar Excitation</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static MultiPlanarExcitation: number = 1609746;
/// <summary>
/// <para>(0018,9014) Phase Contrast</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PhaseContrast: number = 1609748;
/// <summary>
/// <para>(0018,9015) Time of Flight Contrast</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TimeOfFlightContrast: number = 1609749;
/// <summary>
/// <para>(0018,9016) Spoiling</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static Spoiling: number = 1609750;
/// <summary>
/// <para>(0018,9017) Steady State Pulse Sequence</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SteadyStatePulseSequence: number = 1609751;
/// <summary>
/// <para>(0018,9018) Echo Planar Pulse Sequence</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static EchoPlanarPulseSequence: number = 1609752;
/// <summary>
/// <para>(0018,9019) Tag Angle First Axis</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TagAngleFirstAxis: number = 1609753;
/// <summary>
/// <para>(0018,9020) Magnetization Transfer</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static MagnetizationTransfer: number = 1609760;
/// <summary>
/// <para>(0018,9021) T2 Preparation</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static T2Preparation: number = 1609761;
/// <summary>
/// <para>(0018,9022) Blood Signal Nulling</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BloodSignalNulling: number = 1609762;
/// <summary>
/// <para>(0018,9024) Saturation Recovery</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SaturationRecovery: number = 1609764;
/// <summary>
/// <para>(0018,9025) Spectrally Selected Suppression</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SpectrallySelectedSuppression: number = 1609765;
/// <summary>
/// <para>(0018,9026) Spectrally Selected Excitation</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SpectrallySelectedExcitation: number = 1609766;
/// <summary>
/// <para>(0018,9027) Spatial Pre-saturation</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SpatialPreSaturation: number = 1609767;
/// <summary>
/// <para>(0018,9028) Tagging</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static Tagging: number = 1609768;
/// <summary>
/// <para>(0018,9029) Oversampling Phase</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static OversamplingPhase: number = 1609769;
/// <summary>
/// <para>(0018,9030) Tag Spacing First Dimension</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TagSpacingFirstDimension: number = 1609776;
/// <summary>
/// <para>(0018,9032) Geometry of k-Space Traversal</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static GeometryOfKSpaceTraversal: number = 1609778;
/// <summary>
/// <para>(0018,9033) Segmented k-Space Traversal</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SegmentedKSpaceTraversal: number = 1609779;
/// <summary>
/// <para>(0018,9034) Rectilinear Phase Encode Reordering</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RectilinearPhaseEncodeReordering: number = 1609780;
/// <summary>
/// <para>(0018,9035) Tag Thickness</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TagThickness: number = 1609781;
/// <summary>
/// <para>(0018,9036) Partial Fourier Direction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PartialFourierDirection: number = 1609782;
/// <summary>
/// <para>(0018,9037) Cardiac Synchronization Technique</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CardiacSynchronizationTechnique: number = 1609783;
/// <summary>
/// <para>(0018,9041) Receive Coil Manufacturer Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ReceiveCoilManufacturerName: number = 1609793;
/// <summary>
/// <para>(0018,9042) MR Receive Coil Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MrReceiveCoilSequence: number = 1609794;
/// <summary>
/// <para>(0018,9043) Receive Coil Type </para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ReceiveCoilType: number = 1609795;
/// <summary>
/// <para>(0018,9044) Quadrature Receive Coil </para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static QuadratureReceiveCoil: number = 1609796;
/// <summary>
/// <para>(0018,9045) Multi-Coil Definition Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MultiCoilDefinitionSequence: number = 1609797;
/// <summary>
/// <para>(0018,9046) Multi-Coil Configuration </para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static MultiCoilConfiguration: number = 1609798;
/// <summary>
/// <para>(0018,9047) Multi-Coil Element Name</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static MultiCoilElementName: number = 1609799;
/// <summary>
/// <para>(0018,9048) Multi-Coil Element Used</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static MultiCoilElementUsed: number = 1609800;
/// <summary>
/// <para>(0018,9049) MR Transmit Coil Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MrTransmitCoilSequence: number = 1609801;
/// <summary>
/// <para>(0018,9050) Transmit Coil Manufacturer Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static TransmitCoilManufacturerName: number = 1609808;
/// <summary>
/// <para>(0018,9051) Transmit Coil Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TransmitCoilType: number = 1609809;
/// <summary>
/// <para>(0018,9052) Spectral Width</para>
/// <para> VR: FD VM:1-2</para>
/// </summary>
public static SpectralWidth: number = 1609810;
/// <summary>
/// <para>(0018,9053) Chemical Shift Reference</para>
/// <para> VR: FD VM:1-2</para>
/// </summary>
public static ChemicalShiftReference: number = 1609811;
/// <summary>
/// <para>(0018,9054) Volume Localization Technique</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static VolumeLocalizationTechnique: number = 1609812;
/// <summary>
/// <para>(0018,9058) MR Acquisition Frequency Encoding Steps</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static MrAcquisitionFrequencyEncodingSteps: number = 1609816;
/// <summary>
/// <para>(0018,9059) De-coupling</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DeCoupling: number = 1609817;
/// <summary>
/// <para>(0018,9060) De-coupled Nucleus</para>
/// <para> VR: CS VM:1-2</para>
/// </summary>
public static DeCoupledNucleus: number = 1609824;
/// <summary>
/// <para>(0018,9061) De-coupling Frequency</para>
/// <para> VR: FD VM:1-2</para>
/// </summary>
public static DeCouplingFrequency: number = 1609825;
/// <summary>
/// <para>(0018,9062) De-coupling Method</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DeCouplingMethod: number = 1609826;
/// <summary>
/// <para>(0018,9063) De-coupling Chemical Shift Reference</para>
/// <para> VR: FD VM:1-2</para>
/// </summary>
public static DeCouplingChemicalShiftReference: number = 1609827;
/// <summary>
/// <para>(0018,9064) k-space Filtering</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static KSpaceFiltering: number = 1609828;
/// <summary>
/// <para>(0018,9065) Time Domain Filtering</para>
/// <para> VR: CS VM:1-2</para>
/// </summary>
public static TimeDomainFiltering: number = 1609829;
/// <summary>
/// <para>(0018,9066) Number of Zero Fills</para>
/// <para> VR: US VM:1-2</para>
/// </summary>
public static NumberOfZeroFills: number = 1609830;
/// <summary>
/// <para>(0018,9067) Baseline Correction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BaselineCorrection: number = 1609831;
/// <summary>
/// <para>(0018,9069) Parallel Reduction Factor In-plane</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ParallelReductionFactorInPlane: number = 1609833;
/// <summary>
/// <para>(0018,9070) Cardiac R-R Interval Specified</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static CardiacRRIntervalSpecified: number = 1609840;
/// <summary>
/// <para>(0018,9073) Acquisition Duration</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static AcquisitionDuration: number = 1609843;
/// <summary>
/// <para>(0018,9074) Frame Acquisition DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static FrameAcquisitionDatetime: number = 1609844;
/// <summary>
/// <para>(0018,9075) Diffusion Directionality</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DiffusionDirectionality: number = 1609845;
/// <summary>
/// <para>(0018,9076) Diffusion Gradient Direction Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DiffusionGradientDirectionSequence: number = 1609846;
/// <summary>
/// <para>(0018,9077) Parallel Acquisition</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ParallelAcquisition: number = 1609847;
/// <summary>
/// <para>(0018,9078) Parallel Acquisition Technique</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ParallelAcquisitionTechnique: number = 1609848;
/// <summary>
/// <para>(0018,9079) Inversion Times</para>
/// <para> VR: FD VM:1-n</para>
/// </summary>
public static InversionTimes: number = 1609849;
/// <summary>
/// <para>(0018,9080) Metabolite Map Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static MetaboliteMapDescription: number = 1609856;
/// <summary>
/// <para>(0018,9081) Partial Fourier</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PartialFourier: number = 1609857;
/// <summary>
/// <para>(0018,9082) Effective Echo Time</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static EffectiveEchoTime: number = 1609858;
/// <summary>
/// <para>(0018,9083) Metabolite Map Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MetaboliteMapCodeSequence: number = 1609859;
/// <summary>
/// <para>(0018,9084) Chemical Shift Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ChemicalShiftSequence: number = 1609860;
/// <summary>
/// <para>(0018,9085) Cardiac Signal Source</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CardiacSignalSource: number = 1609861;
/// <summary>
/// <para>(0018,9087) Diffusion b-value</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static DiffusionBValue: number = 1609863;
/// <summary>
/// <para>(0018,9089) Diffusion Gradient Orientation</para>
/// <para> VR: FD VM:3</para>
/// </summary>
public static DiffusionGradientOrientation: number = 1609865;
/// <summary>
/// <para>(0018,9090) Velocity Encoding Direction</para>
/// <para> VR: FD VM:3</para>
/// </summary>
public static VelocityEncodingDirection: number = 1609872;
/// <summary>
/// <para>(0018,9091) Velocity Encoding Minimum Value</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static VelocityEncodingMinimumValue: number = 1609873;
/// <summary>
/// <para>(0018,9092) Velocity Encoding Acquisition Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static VelocityEncodingAcquisitionSequence: number = 1609874;
/// <summary>
/// <para>(0018,9093) Number of k-Space Trajectories</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfKSpaceTrajectories: number = 1609875;
/// <summary>
/// <para>(0018,9094) Coverage of k-Space</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CoverageOfKSpace: number = 1609876;
/// <summary>
/// <para>(0018,9095) Spectroscopy Acquisition Phase Rows</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static SpectroscopyAcquisitionPhaseRows: number = 1609877;
/// <summary>
/// <para>(0018,9096) Parallel Reduction Factor In-plane (Retired)</para>
/// <para> VR: FD VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ParallelReductionFactorInPlaneRetired: number = 1609878;
/// <summary>
/// <para>(0018,9098) Transmitter Frequency</para>
/// <para> VR: FD VM:1-2</para>
/// </summary>
public static TransmitterFrequency: number = 1609880;
/// <summary>
/// <para>(0018,9100) Resonant Nucleus</para>
/// <para> VR: CS VM:1-2</para>
/// </summary>
public static ResonantNucleus: number = 1609984;
/// <summary>
/// <para>(0018,9101) Frequency Correction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FrequencyCorrection: number = 1609985;
/// <summary>
/// <para>(0018,9103) MR Spectroscopy FOV/Geometry Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MrSpectroscopyFovGeometrySequence: number = 1609987;
/// <summary>
/// <para>(0018,9104) Slab Thickness</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static SlabThickness: number = 1609988;
/// <summary>
/// <para>(0018,9105) Slab Orientation</para>
/// <para> VR: FD VM:3</para>
/// </summary>
public static SlabOrientation: number = 1609989;
/// <summary>
/// <para>(0018,9106) Mid Slab Position</para>
/// <para> VR: FD VM:3</para>
/// </summary>
public static MidSlabPosition: number = 1609990;
/// <summary>
/// <para>(0018,9107) MR Spatial Saturation Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MrSpatialSaturationSequence: number = 1609991;
/// <summary>
/// <para>(0018,9112) MR Timing and Related Parameters Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MrTimingAndRelatedParametersSequence: number = 1610002;
/// <summary>
/// <para>(0018,9114) MR Echo Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MrEchoSequence: number = 1610004;
/// <summary>
/// <para>(0018,9115) MR Modifier Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MrModifierSequence: number = 1610005;
/// <summary>
/// <para>(0018,9117) MR Diffusion Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MrDiffusionSequence: number = 1610007;
/// <summary>
/// <para>(0018,9118) Cardiac Synchronization Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CardiacSynchronizationSequence: number = 1610008;
/// <summary>
/// <para>(0018,9119) MR Averages Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MrAveragesSequence: number = 1610009;
/// <summary>
/// <para>(0018,9125) MR FOV/Geometry Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MrFovGeometrySequence: number = 1610021;
/// <summary>
/// <para>(0018,9126) Volume Localization Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static VolumeLocalizationSequence: number = 1610022;
/// <summary>
/// <para>(0018,9127) Spectroscopy Acquisition Data Columns</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static SpectroscopyAcquisitionDataColumns: number = 1610023;
/// <summary>
/// <para>(0018,9147) Diffusion Anisotropy Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DiffusionAnisotropyType: number = 1610055;
/// <summary>
/// <para>(0018,9151) Frame Reference DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static FrameReferenceDatetime: number = 1610065;
/// <summary>
/// <para>(0018,9152) MR Metabolite Map Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MrMetaboliteMapSequence: number = 1610066;
/// <summary>
/// <para>(0018,9155) Parallel Reduction Factor out-of-plane</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ParallelReductionFactorOutOfPlane: number = 1610069;
/// <summary>
/// <para>(0018,9159) Spectroscopy Acquisition Out-of-plane Phase Steps</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static SpectroscopyAcquisitionOutOfPlanePhaseSteps: number = 1610073;
/// <summary>
/// <para>(0018,9166) Bulk Motion Status</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static BulkMotionStatusRetired: number = 1610086;
/// <summary>
/// <para>(0018,9168) Parallel Reduction Factor Second In-plane</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ParallelReductionFactorSecondInPlane: number = 1610088;
/// <summary>
/// <para>(0018,9169) Cardiac Beat Rejection Technique</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CardiacBeatRejectionTechnique: number = 1610089;
/// <summary>
/// <para>(0018,9170) Respiratory Motion Compensation Technique</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RespiratoryMotionCompensationTechnique: number = 1610096;
/// <summary>
/// <para>(0018,9171) Respiratory Signal Source</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RespiratorySignalSource: number = 1610097;
/// <summary>
/// <para>(0018,9172) Bulk Motion Compensation Technique</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BulkMotionCompensationTechnique: number = 1610098;
/// <summary>
/// <para>(0018,9173) Bulk Motion Signal Source</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BulkMotionSignalSource: number = 1610099;
/// <summary>
/// <para>(0018,9174) Applicable Safety Standard Agency</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ApplicableSafetyStandardAgency: number = 1610100;
/// <summary>
/// <para>(0018,9175) Applicable Safety Standard Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ApplicableSafetyStandardDescription: number = 1610101;
/// <summary>
/// <para>(0018,9176) Operating Mode Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OperatingModeSequence: number = 1610102;
/// <summary>
/// <para>(0018,9177) Operating Mode Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static OperatingModeType: number = 1610103;
/// <summary>
/// <para>(0018,9178) Operating Mode</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static OperatingMode: number = 1610104;
/// <summary>
/// <para>(0018,9179) Specific Absorption Rate Definition</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SpecificAbsorptionRateDefinition: number = 1610105;
/// <summary>
/// <para>(0018,9180) Gradient Output Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static GradientOutputType: number = 1610112;
/// <summary>
/// <para>(0018,9181) Specific Absorption Rate Value</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static SpecificAbsorptionRateValue: number = 1610113;
/// <summary>
/// <para>(0018,9182) Gradient Output</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static GradientOutput: number = 1610114;
/// <summary>
/// <para>(0018,9183) Flow Compensation Direction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FlowCompensationDirection: number = 1610115;
/// <summary>
/// <para>(0018,9184) Tagging Delay</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TaggingDelay: number = 1610116;
/// <summary>
/// <para>(0018,9185) Respiratory Motion Compensation Technique Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static RespiratoryMotionCompensationTechniqueDescription: number = 1610117;
/// <summary>
/// <para>(0018,9186) Respiratory Signal Source ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static RespiratorySignalSourceId: number = 1610118;
/// <summary>
/// <para>(0018,9195) Chemical Shift Minimum Integration Limit in Hz</para>
/// <para> VR: FD VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ChemicalShiftMinimumIntegrationLimitInHzRetired: number = 1610133;
/// <summary>
/// <para>(0018,9196) Chemical Shift Maximum Integration Limit in Hz</para>
/// <para> VR: FD VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ChemicalShiftMaximumIntegrationLimitInHzRetired: number = 1610134;
/// <summary>
/// <para>(0018,9197) MR Velocity Encoding Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MrVelocityEncodingSequence: number = 1610135;
/// <summary>
/// <para>(0018,9198) First Order Phase Correction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FirstOrderPhaseCorrection: number = 1610136;
/// <summary>
/// <para>(0018,9199) Water Referenced Phase Correction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static WaterReferencedPhaseCorrection: number = 1610137;
/// <summary>
/// <para>(0018,9200) MR Spectroscopy Acquisition Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static MrSpectroscopyAcquisitionType: number = 1610240;
/// <summary>
/// <para>(0018,9214) Respiratory Cycle Position</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RespiratoryCyclePosition: number = 1610260;
/// <summary>
/// <para>(0018,9217) Velocity Encoding Maximum Value</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static VelocityEncodingMaximumValue: number = 1610263;
/// <summary>
/// <para>(0018,9218) Tag Spacing Second Dimension</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TagSpacingSecondDimension: number = 1610264;
/// <summary>
/// <para>(0018,9219) Tag Angle Second Axis</para>
/// <para> VR: SS VM:1</para>
/// </summary>
public static TagAngleSecondAxis: number = 1610265;
/// <summary>
/// <para>(0018,9220) Frame Acquisition Duration</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static FrameAcquisitionDuration: number = 1610272;
/// <summary>
/// <para>(0018,9226) MR Image Frame Type Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MrImageFrameTypeSequence: number = 1610278;
/// <summary>
/// <para>(0018,9227) MR Spectroscopy Frame Type Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MrSpectroscopyFrameTypeSequence: number = 1610279;
/// <summary>
/// <para>(0018,9231) MR Acquisition Phase Encoding Steps in-plane</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static MrAcquisitionPhaseEncodingStepsInPlane: number = 1610289;
/// <summary>
/// <para>(0018,9232) MR Acquisition Phase Encoding Steps out-of-plane</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static MrAcquisitionPhaseEncodingStepsOutOfPlane: number = 1610290;
/// <summary>
/// <para>(0018,9234) Spectroscopy Acquisition Phase Columns</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static SpectroscopyAcquisitionPhaseColumns: number = 1610292;
/// <summary>
/// <para>(0018,9236) Cardiac Cycle Position</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CardiacCyclePosition: number = 1610294;
/// <summary>
/// <para>(0018,9239) Specific Absorption Rate Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SpecificAbsorptionRateSequence: number = 1610297;
/// <summary>
/// <para>(0018,9240) RF Echo Train Length</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static RfEchoTrainLength: number = 1610304;
/// <summary>
/// <para>(0018,9241) Gradient Echo Train Length</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static GradientEchoTrainLength: number = 1610305;
/// <summary>
/// <para>(0018,9250) Arterial Spin Labeling Contrast</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ArterialSpinLabelingContrast: number = 1610320;
/// <summary>
/// <para>(0018,9251) MR Arterial Spin Labeling Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MrArterialSpinLabelingSequence: number = 1610321;
/// <summary>
/// <para>(0018,9252) ASL Technique Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static AslTechniqueDescription: number = 1610322;
/// <summary>
/// <para>(0018,9253) ASL Slab Number</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static AslSlabNumber: number = 1610323;
/// <summary>
/// <para>(0018,9254) ASL Slab Thickness</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static AslSlabThickness: number = 1610324;
/// <summary>
/// <para>(0018,9255) ASL Slab Orientation</para>
/// <para> VR: FD VM:3</para>
/// </summary>
public static AslSlabOrientation: number = 1610325;
/// <summary>
/// <para>(0018,9256) ASL Mid Slab Position</para>
/// <para> VR: FD VM:3</para>
/// </summary>
public static AslMidSlabPosition: number = 1610326;
/// <summary>
/// <para>(0018,9257) ASL Context</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AslContext: number = 1610327;
/// <summary>
/// <para>(0018,9258) ASL Pulse Train Duration</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static AslPulseTrainDuration: number = 1610328;
/// <summary>
/// <para>(0018,9259) ASL Crusher Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AslCrusherFlag: number = 1610329;
/// <summary>
/// <para>(0018,925A) ASL Crusher Flow</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static AslCrusherFlow: number = 1610330;
/// <summary>
/// <para>(0018,925B) ASL Crusher Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static AslCrusherDescription: number = 1610331;
/// <summary>
/// <para>(0018,925C) ASL Bolus Cut-off Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AslBolusCutOffFlag: number = 1610332;
/// <summary>
/// <para>(0018,925D) ASL Bolus Cut-off Timing Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AslBolusCutOffTimingSequence: number = 1610333;
/// <summary>
/// <para>(0018,925E) ASL Bolus Cut-off Technique</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static AslBolusCutOffTechnique: number = 1610334;
/// <summary>
/// <para>(0018,925F) ASL Bolus Cut-off Delay Time</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static AslBolusCutOffDelayTime: number = 1610335;
/// <summary>
/// <para>(0018,9260) ASL Slab Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AslSlabSequence: number = 1610336;
/// <summary>
/// <para>(0018,9295) Chemical Shift Minimum Integration Limit in ppm</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ChemicalShiftMinimumIntegrationLimitInPpm: number = 1610389;
/// <summary>
/// <para>(0018,9296) Chemical Shift Maximum Integration Limit in ppm</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ChemicalShiftMaximumIntegrationLimitInPpm: number = 1610390;
/// <summary>
/// <para>(0018,9301) CT Acquisition Type Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CtAcquisitionTypeSequence: number = 1610497;
/// <summary>
/// <para>(0018,9302) Acquisition Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AcquisitionType: number = 1610498;
/// <summary>
/// <para>(0018,9303) Tube Angle</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TubeAngle: number = 1610499;
/// <summary>
/// <para>(0018,9304) CT Acquisition Details Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CtAcquisitionDetailsSequence: number = 1610500;
/// <summary>
/// <para>(0018,9305) Revolution Time</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static RevolutionTime: number = 1610501;
/// <summary>
/// <para>(0018,9306) Single Collimation Width</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static SingleCollimationWidth: number = 1610502;
/// <summary>
/// <para>(0018,9307) Total Collimation Width</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TotalCollimationWidth: number = 1610503;
/// <summary>
/// <para>(0018,9308) CT Table Dynamics Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CtTableDynamicsSequence: number = 1610504;
/// <summary>
/// <para>(0018,9309) Table Speed</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TableSpeed: number = 1610505;
/// <summary>
/// <para>(0018,9310) Table Feed per Rotation</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TableFeedPerRotation: number = 1610512;
/// <summary>
/// <para>(0018,9311) Spiral Pitch Factor</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static SpiralPitchFactor: number = 1610513;
/// <summary>
/// <para>(0018,9312) CT Geometry Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CtGeometrySequence: number = 1610514;
/// <summary>
/// <para>(0018,9313) Data Collection Center (Patient)</para>
/// <para> VR: FD VM:3</para>
/// </summary>
public static DataCollectionCenterPatient: number = 1610515;
/// <summary>
/// <para>(0018,9314) CT Reconstruction Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CtReconstructionSequence: number = 1610516;
/// <summary>
/// <para>(0018,9315) Reconstruction Algorithm</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ReconstructionAlgorithm: number = 1610517;
/// <summary>
/// <para>(0018,9316) Convolution Kernel Group</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ConvolutionKernelGroup: number = 1610518;
/// <summary>
/// <para>(0018,9317) Reconstruction Field of View</para>
/// <para> VR: FD VM:2</para>
/// </summary>
public static ReconstructionFieldOfView: number = 1610519;
/// <summary>
/// <para>(0018,9318) Reconstruction Target Center (Patient)</para>
/// <para> VR: FD VM:3</para>
/// </summary>
public static ReconstructionTargetCenterPatient: number = 1610520;
/// <summary>
/// <para>(0018,9319) Reconstruction Angle</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ReconstructionAngle: number = 1610521;
/// <summary>
/// <para>(0018,9320) Image Filter</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static ImageFilter: number = 1610528;
/// <summary>
/// <para>(0018,9321) CT Exposure Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CtExposureSequence: number = 1610529;
/// <summary>
/// <para>(0018,9322) Reconstruction Pixel Spacing </para>
/// <para> VR: FD VM:2</para>
/// </summary>
public static ReconstructionPixelSpacing: number = 1610530;
/// <summary>
/// <para>(0018,9323) Exposure Modulation Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ExposureModulationType: number = 1610531;
/// <summary>
/// <para>(0018,9324) Estimated Dose Saving</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static EstimatedDoseSaving: number = 1610532;
/// <summary>
/// <para>(0018,9325) CT X-Ray Details Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CtXRayDetailsSequence: number = 1610533;
/// <summary>
/// <para>(0018,9326) CT Position Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CtPositionSequence: number = 1610534;
/// <summary>
/// <para>(0018,9327) Table Position</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TablePosition: number = 1610535;
/// <summary>
/// <para>(0018,9328) Exposure Time in ms</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ExposureTimeInMs: number = 1610536;
/// <summary>
/// <para>(0018,9329) CT Image Frame Type Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CtImageFrameTypeSequence: number = 1610537;
/// <summary>
/// <para>(0018,9330) X-Ray Tube Current in mA</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static XRayTubeCurrentInMa: number = 1610544;
/// <summary>
/// <para>(0018,9332) Exposure in mAs</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ExposureInMas: number = 1610546;
/// <summary>
/// <para>(0018,9333) Constant Volume Flag </para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ConstantVolumeFlag: number = 1610547;
/// <summary>
/// <para>(0018,9334) Fluoroscopy Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FluoroscopyFlag: number = 1610548;
/// <summary>
/// <para>(0018,9335) Distance Source to Data Collection Center</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static DistanceSourceToDataCollectionCenter: number = 1610549;
/// <summary>
/// <para>(0018,9337) Contrast/Bolus Agent Number</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ContrastBolusAgentNumber: number = 1610551;
/// <summary>
/// <para>(0018,9338) Contrast/Bolus Ingredient Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ContrastBolusIngredientCodeSequence: number = 1610552;
/// <summary>
/// <para>(0018,9340) Contrast Administration Profile Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ContrastAdministrationProfileSequence: number = 1610560;
/// <summary>
/// <para>(0018,9341) Contrast/Bolus Usage Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ContrastBolusUsageSequence: number = 1610561;
/// <summary>
/// <para>(0018,9342) Contrast/Bolus Agent Administered</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ContrastBolusAgentAdministered: number = 1610562;
/// <summary>
/// <para>(0018,9343) Contrast/Bolus Agent Detected</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ContrastBolusAgentDetected: number = 1610563;
/// <summary>
/// <para>(0018,9344) Contrast/Bolus Agent Phase</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ContrastBolusAgentPhase: number = 1610564;
/// <summary>
/// <para>(0018,9345) CTDIvol</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static Ctdivol: number = 1610565;
/// <summary>
/// <para>(0018,9346) CTDI Phantom Type Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CtdiPhantomTypeCodeSequence: number = 1610566;
/// <summary>
/// <para>(0018,9351) Calcium Scoring Mass Factor Patient</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static CalciumScoringMassFactorPatient: number = 1610577;
/// <summary>
/// <para>(0018,9352) Calcium Scoring Mass Factor Device</para>
/// <para> VR: FL VM:3</para>
/// </summary>
public static CalciumScoringMassFactorDevice: number = 1610578;
/// <summary>
/// <para>(0018,9353) Energy Weighting Factor</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static EnergyWeightingFactor: number = 1610579;
/// <summary>
/// <para>(0018,9360) CT Additional X-Ray Source Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CtAdditionalXRaySourceSequence: number = 1610592;
/// <summary>
/// <para>(0018,9401) Projection Pixel Calibration Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ProjectionPixelCalibrationSequence: number = 1610753;
/// <summary>
/// <para>(0018,9402) Distance Source to Isocenter</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static DistanceSourceToIsocenter: number = 1610754;
/// <summary>
/// <para>(0018,9403) Distance Object to Table Top</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static DistanceObjectToTableTop: number = 1610755;
/// <summary>
/// <para>(0018,9404) Object Pixel Spacing in Center of Beam</para>
/// <para> VR: FL VM:2</para>
/// </summary>
public static ObjectPixelSpacingInCenterOfBeam: number = 1610756;
/// <summary>
/// <para>(0018,9405) Positioner Position Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PositionerPositionSequence: number = 1610757;
/// <summary>
/// <para>(0018,9406) Table Position Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TablePositionSequence: number = 1610758;
/// <summary>
/// <para>(0018,9407) Collimator Shape Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CollimatorShapeSequence: number = 1610759;
/// <summary>
/// <para>(0018,9410) Planes in Acquisition</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PlanesInAcquisition: number = 1610768;
/// <summary>
/// <para>(0018,9412) XA/XRF Frame Characteristics Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static XaXrfFrameCharacteristicsSequence: number = 1610770;
/// <summary>
/// <para>(0018,9417) Frame Acquisition Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FrameAcquisitionSequence: number = 1610775;
/// <summary>
/// <para>(0018,9420) X-Ray Receptor Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static XRayReceptorType: number = 1610784;
/// <summary>
/// <para>(0018,9423) Acquisition Protocol Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static AcquisitionProtocolName: number = 1610787;
/// <summary>
/// <para>(0018,9424) Acquisition Protocol Description</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static AcquisitionProtocolDescription: number = 1610788;
/// <summary>
/// <para>(0018,9425) Contrast/Bolus Ingredient Opaque</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ContrastBolusIngredientOpaque: number = 1610789;
/// <summary>
/// <para>(0018,9426) Distance Receptor Plane to Detector Housing</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static DistanceReceptorPlaneToDetectorHousing: number = 1610790;
/// <summary>
/// <para>(0018,9427) Intensifier Active Shape</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static IntensifierActiveShape: number = 1610791;
/// <summary>
/// <para>(0018,9428) Intensifier Active Dimension(s)</para>
/// <para> VR: FL VM:1-2</para>
/// </summary>
public static IntensifierActiveDimensions: number = 1610792;
/// <summary>
/// <para>(0018,9429) Physical Detector Size</para>
/// <para> VR: FL VM:2</para>
/// </summary>
public static PhysicalDetectorSize: number = 1610793;
/// <summary>
/// <para>(0018,9430) Position of Isocenter Projection</para>
/// <para> VR: FL VM:2</para>
/// </summary>
public static PositionOfIsocenterProjection: number = 1610800;
/// <summary>
/// <para>(0018,9432) Field of View Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FieldOfViewSequence: number = 1610802;
/// <summary>
/// <para>(0018,9433) Field of View Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static FieldOfViewDescription: number = 1610803;
/// <summary>
/// <para>(0018,9434) Exposure Control Sensing Regions Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ExposureControlSensingRegionsSequence: number = 1610804;
/// <summary>
/// <para>(0018,9435) Exposure Control Sensing Region Shape</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ExposureControlSensingRegionShape: number = 1610805;
/// <summary>
/// <para>(0018,9436) Exposure Control Sensing Region Left Vertical Edge</para>
/// <para> VR: SS VM:1</para>
/// </summary>
public static ExposureControlSensingRegionLeftVerticalEdge: number = 1610806;
/// <summary>
/// <para>(0018,9437) Exposure Control Sensing Region Right Vertical Edge</para>
/// <para> VR: SS VM:1</para>
/// </summary>
public static ExposureControlSensingRegionRightVerticalEdge: number = 1610807;
/// <summary>
/// <para>(0018,9438) Exposure Control Sensing Region Upper Horizontal Edge</para>
/// <para> VR: SS VM:1</para>
/// </summary>
public static ExposureControlSensingRegionUpperHorizontalEdge: number = 1610808;
/// <summary>
/// <para>(0018,9439) Exposure Control Sensing Region Lower Horizontal Edge</para>
/// <para> VR: SS VM:1</para>
/// </summary>
public static ExposureControlSensingRegionLowerHorizontalEdge: number = 1610809;
/// <summary>
/// <para>(0018,9440) Center of Circular Exposure Control Sensing Region</para>
/// <para> VR: SS VM:2</para>
/// </summary>
public static CenterOfCircularExposureControlSensingRegion: number = 1610816;
/// <summary>
/// <para>(0018,9441) Radius of Circular Exposure Control Sensing Region</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static RadiusOfCircularExposureControlSensingRegion: number = 1610817;
/// <summary>
/// <para>(0018,9442) Vertices of the Polygonal Exposure Control Sensing Region</para>
/// <para> VR: SS VM:2-n</para>
/// </summary>
public static VerticesOfThePolygonalExposureControlSensingRegion: number = 1610818;
/// <summary>
/// <para>(0018,9447) Column Angulation (Patient)</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static ColumnAngulationPatient: number = 1610823;
/// <summary>
/// <para>(0018,9449) Beam Angle</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static BeamAngle: number = 1610825;
/// <summary>
/// <para>(0018,9451) Frame Detector Parameters Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FrameDetectorParametersSequence: number = 1610833;
/// <summary>
/// <para>(0018,9452) Calculated Anatomy Thickness</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static CalculatedAnatomyThickness: number = 1610834;
/// <summary>
/// <para>(0018,9455) Calibration Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CalibrationSequence: number = 1610837;
/// <summary>
/// <para>(0018,9456) Object Thickness Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ObjectThicknessSequence: number = 1610838;
/// <summary>
/// <para>(0018,9457) Plane Identification</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PlaneIdentification: number = 1610839;
/// <summary>
/// <para>(0018,9461) Field of View Dimension(s) in Float</para>
/// <para> VR: FL VM:1-2</para>
/// </summary>
public static FieldOfViewDimensionsInFloat: number = 1610849;
/// <summary>
/// <para>(0018,9462) Isocenter Reference System Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IsocenterReferenceSystemSequence: number = 1610850;
/// <summary>
/// <para>(0018,9463) Positioner Isocenter Primary Angle</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static PositionerIsocenterPrimaryAngle: number = 1610851;
/// <summary>
/// <para>(0018,9464) Positioner Isocenter Secondary Angle</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static PositionerIsocenterSecondaryAngle: number = 1610852;
/// <summary>
/// <para>(0018,9465) Positioner Isocenter Detector Rotation Angle</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static PositionerIsocenterDetectorRotationAngle: number = 1610853;
/// <summary>
/// <para>(0018,9466) Table X Position to Isocenter</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static TableXPositionToIsocenter: number = 1610854;
/// <summary>
/// <para>(0018,9467) Table Y Position to Isocenter</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static TableYPositionToIsocenter: number = 1610855;
/// <summary>
/// <para>(0018,9468) Table Z Position to Isocenter</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static TableZPositionToIsocenter: number = 1610856;
/// <summary>
/// <para>(0018,9469) Table Horizontal Rotation Angle</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static TableHorizontalRotationAngle: number = 1610857;
/// <summary>
/// <para>(0018,9470) Table Head Tilt Angle</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static TableHeadTiltAngle: number = 1610864;
/// <summary>
/// <para>(0018,9471) Table Cradle Tilt Angle</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static TableCradleTiltAngle: number = 1610865;
/// <summary>
/// <para>(0018,9472) Frame Display Shutter Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FrameDisplayShutterSequence: number = 1610866;
/// <summary>
/// <para>(0018,9473) Acquired Image Area Dose Product</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static AcquiredImageAreaDoseProduct: number = 1610867;
/// <summary>
/// <para>(0018,9474) C-arm Positioner Tabletop Relationship</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CArmPositionerTabletopRelationship: number = 1610868;
/// <summary>
/// <para>(0018,9476) X-Ray Geometry Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static XRayGeometrySequence: number = 1610870;
/// <summary>
/// <para>(0018,9477) Irradiation Event Identification Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IrradiationEventIdentificationSequence: number = 1610871;
/// <summary>
/// <para>(0018,9504) X-Ray 3D Frame Type Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static XRay3dFrameTypeSequence: number = 1611012;
/// <summary>
/// <para>(0018,9506) Contributing Sources Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ContributingSourcesSequence: number = 1611014;
/// <summary>
/// <para>(0018,9507) X-Ray 3D Acquisition Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static XRay3dAcquisitionSequence: number = 1611015;
/// <summary>
/// <para>(0018,9508) Primary Positioner Scan Arc</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static PrimaryPositionerScanArc: number = 1611016;
/// <summary>
/// <para>(0018,9509) Secondary Positioner Scan Arc</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static SecondaryPositionerScanArc: number = 1611017;
/// <summary>
/// <para>(0018,9510) Primary Positioner Scan Start Angle</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static PrimaryPositionerScanStartAngle: number = 1611024;
/// <summary>
/// <para>(0018,9511) Secondary Positioner Scan Start Angle</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static SecondaryPositionerScanStartAngle: number = 1611025;
/// <summary>
/// <para>(0018,9514) Primary Positioner Increment</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static PrimaryPositionerIncrement: number = 1611028;
/// <summary>
/// <para>(0018,9515) Secondary Positioner Increment</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static SecondaryPositionerIncrement: number = 1611029;
/// <summary>
/// <para>(0018,9516) Start Acquisition DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static StartAcquisitionDatetime: number = 1611030;
/// <summary>
/// <para>(0018,9517) End Acquisition DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static EndAcquisitionDatetime: number = 1611031;
/// <summary>
/// <para>(0018,9524) Application Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ApplicationName: number = 1611044;
/// <summary>
/// <para>(0018,9525) Application Version</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ApplicationVersion: number = 1611045;
/// <summary>
/// <para>(0018,9526) Application Manufacturer</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ApplicationManufacturer: number = 1611046;
/// <summary>
/// <para>(0018,9527) Algorithm Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AlgorithmType: number = 1611047;
/// <summary>
/// <para>(0018,9528) Algorithm Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static AlgorithmDescription: number = 1611048;
/// <summary>
/// <para>(0018,9530) X-Ray 3D Reconstruction Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static XRay3dReconstructionSequence: number = 1611056;
/// <summary>
/// <para>(0018,9531) Reconstruction Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ReconstructionDescription: number = 1611057;
/// <summary>
/// <para>(0018,9538) Per Projection Acquisition Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PerProjectionAcquisitionSequence: number = 1611064;
/// <summary>
/// <para>(0018,9601) Diffusion b-matrix Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DiffusionBMatrixSequence: number = 1611265;
/// <summary>
/// <para>(0018,9602) Diffusion b-value XX</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static DiffusionBValueXx: number = 1611266;
/// <summary>
/// <para>(0018,9603) Diffusion b-value XY</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static DiffusionBValueXy: number = 1611267;
/// <summary>
/// <para>(0018,9604) Diffusion b-value XZ</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static DiffusionBValueXz: number = 1611268;
/// <summary>
/// <para>(0018,9605) Diffusion b-value YY</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static DiffusionBValueYy: number = 1611269;
/// <summary>
/// <para>(0018,9606) Diffusion b-value YZ</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static DiffusionBValueYz: number = 1611270;
/// <summary>
/// <para>(0018,9607) Diffusion b-value ZZ</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static DiffusionBValueZz: number = 1611271;
/// <summary>
/// <para>(0018,9701) Decay Correction DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static DecayCorrectionDatetime: number = 1611521;
/// <summary>
/// <para>(0018,9715) Start Density Threshold</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static StartDensityThreshold: number = 1611541;
/// <summary>
/// <para>(0018,9716) Start Relative Density Difference Threshold</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static StartRelativeDensityDifferenceThreshold: number = 1611542;
/// <summary>
/// <para>(0018,9717) Start Cardiac Trigger Count Threshold</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static StartCardiacTriggerCountThreshold: number = 1611543;
/// <summary>
/// <para>(0018,9718) Start Respiratory Trigger Count Threshold</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static StartRespiratoryTriggerCountThreshold: number = 1611544;
/// <summary>
/// <para>(0018,9719) Termination Counts Threshold</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TerminationCountsThreshold: number = 1611545;
/// <summary>
/// <para>(0018,9720) Termination Density Threshold</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TerminationDensityThreshold: number = 1611552;
/// <summary>
/// <para>(0018,9721) Termination Relative Density Threshold</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TerminationRelativeDensityThreshold: number = 1611553;
/// <summary>
/// <para>(0018,9722) Termination Time Threshold</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TerminationTimeThreshold: number = 1611554;
/// <summary>
/// <para>(0018,9723) Termination Cardiac Trigger Count Threshold</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TerminationCardiacTriggerCountThreshold: number = 1611555;
/// <summary>
/// <para>(0018,9724) Termination Respiratory Trigger Count Threshold</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TerminationRespiratoryTriggerCountThreshold: number = 1611556;
/// <summary>
/// <para>(0018,9725) Detector Geometry</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DetectorGeometry: number = 1611557;
/// <summary>
/// <para>(0018,9726) Transverse Detector Separation</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TransverseDetectorSeparation: number = 1611558;
/// <summary>
/// <para>(0018,9727) Axial Detector Dimension</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static AxialDetectorDimension: number = 1611559;
/// <summary>
/// <para>(0018,9729) Radiopharmaceutical Agent Number</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static RadiopharmaceuticalAgentNumber: number = 1611561;
/// <summary>
/// <para>(0018,9732) PET Frame Acquisition Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PetFrameAcquisitionSequence: number = 1611570;
/// <summary>
/// <para>(0018,9733) PET Detector Motion Details Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PetDetectorMotionDetailsSequence: number = 1611571;
/// <summary>
/// <para>(0018,9734) PET Table Dynamics Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PetTableDynamicsSequence: number = 1611572;
/// <summary>
/// <para>(0018,9735) PET Position Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PetPositionSequence: number = 1611573;
/// <summary>
/// <para>(0018,9736) PET Frame Correction Factors Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PetFrameCorrectionFactorsSequence: number = 1611574;
/// <summary>
/// <para>(0018,9737) Radiopharmaceutical Usage Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RadiopharmaceuticalUsageSequence: number = 1611575;
/// <summary>
/// <para>(0018,9738) Attenuation Correction Source</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AttenuationCorrectionSource: number = 1611576;
/// <summary>
/// <para>(0018,9739) Number of Iterations</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfIterations: number = 1611577;
/// <summary>
/// <para>(0018,9740) Number of Subsets</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfSubsets: number = 1611584;
/// <summary>
/// <para>(0018,9749) PET Reconstruction Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PetReconstructionSequence: number = 1611593;
/// <summary>
/// <para>(0018,9751) PET Frame Type Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PetFrameTypeSequence: number = 1611601;
/// <summary>
/// <para>(0018,9755) Time of Flight Information Used</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TimeOfFlightInformationUsed: number = 1611605;
/// <summary>
/// <para>(0018,9756) Reconstruction Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ReconstructionType: number = 1611606;
/// <summary>
/// <para>(0018,9758) Decay Corrected </para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DecayCorrected: number = 1611608;
/// <summary>
/// <para>(0018,9759) Attenuation Corrected </para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AttenuationCorrected: number = 1611609;
/// <summary>
/// <para>(0018,9760) Scatter Corrected </para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ScatterCorrected: number = 1611616;
/// <summary>
/// <para>(0018,9761) Dead Time Corrected </para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DeadTimeCorrected: number = 1611617;
/// <summary>
/// <para>(0018,9762) Gantry Motion Corrected </para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static GantryMotionCorrected: number = 1611618;
/// <summary>
/// <para>(0018,9763) Patient Motion Corrected </para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PatientMotionCorrected: number = 1611619;
/// <summary>
/// <para>(0018,9764) Count Loss Normalization Corrected</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CountLossNormalizationCorrected: number = 1611620;
/// <summary>
/// <para>(0018,9765) Randoms Corrected</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RandomsCorrected: number = 1611621;
/// <summary>
/// <para>(0018,9766) Non-uniform Radial Sampling Corrected</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static NonUniformRadialSamplingCorrected: number = 1611622;
/// <summary>
/// <para>(0018,9767) Sensitivity Calibrated</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SensitivityCalibrated: number = 1611623;
/// <summary>
/// <para>(0018,9768) Detector Normalization Correction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DetectorNormalizationCorrection: number = 1611624;
/// <summary>
/// <para>(0018,9769) Iterative Reconstruction Method </para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static IterativeReconstructionMethod: number = 1611625;
/// <summary>
/// <para>(0018,9770) Attenuation Correction Temporal Relationship</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AttenuationCorrectionTemporalRelationship: number = 1611632;
/// <summary>
/// <para>(0018,9771) Patient Physiological State Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PatientPhysiologicalStateSequence: number = 1611633;
/// <summary>
/// <para>(0018,9772) Patient Physiological State Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PatientPhysiologicalStateCodeSequence: number = 1611634;
/// <summary>
/// <para>(0018,9801) Depth(s) of Focus</para>
/// <para> VR: FD VM:1-n</para>
/// </summary>
public static DepthsOfFocus: number = 1611777;
/// <summary>
/// <para>(0018,9803) Excluded Intervals Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ExcludedIntervalsSequence: number = 1611779;
/// <summary>
/// <para>(0018,9804) Exclusion Start Datetime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static ExclusionStartDatetime: number = 1611780;
/// <summary>
/// <para>(0018,9805) Exclusion Duration</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ExclusionDuration: number = 1611781;
/// <summary>
/// <para>(0018,9806) US Image Description Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static UsImageDescriptionSequence: number = 1611782;
/// <summary>
/// <para>(0018,9807) Image Data Type Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ImageDataTypeSequence: number = 1611783;
/// <summary>
/// <para>(0018,9808) Data Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DataType: number = 1611784;
/// <summary>
/// <para>(0018,9809) Transducer Scan Pattern Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TransducerScanPatternCodeSequence: number = 1611785;
/// <summary>
/// <para>(0018,980B) Aliased Data Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AliasedDataType: number = 1611787;
/// <summary>
/// <para>(0018,980C) Position Measuring Device Used</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PositionMeasuringDeviceUsed: number = 1611788;
/// <summary>
/// <para>(0018,980D) Transducer Geometry Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TransducerGeometryCodeSequence: number = 1611789;
/// <summary>
/// <para>(0018,980E) Transducer Beam Steering Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TransducerBeamSteeringCodeSequence: number = 1611790;
/// <summary>
/// <para>(0018,980F) Transducer Application Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TransducerApplicationCodeSequence: number = 1611791;
/// <summary>
/// <para>(0018,A001) Contributing Equipment Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ContributingEquipmentSequence: number = 1613825;
/// <summary>
/// <para>(0018,A002) Contribution Date Time</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static ContributionDateTime: number = 1613826;
/// <summary>
/// <para>(0018,A003) Contribution Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static ContributionDescription: number = 1613827;
/// <summary>
/// <para>(0020,000D) Study Instance UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static StudyInstanceUid: number = 2097165;
/// <summary>
/// <para>(0020,000E) Series Instance UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static SeriesInstanceUid: number = 2097166;
/// <summary>
/// <para>(0020,0010) Study ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static StudyId: number = 2097168;
/// <summary>
/// <para>(0020,0011) Series Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static SeriesNumber: number = 2097169;
/// <summary>
/// <para>(0020,0012) Acquisition Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static AcquisitionNumber: number = 2097170;
/// <summary>
/// <para>(0020,0013) Instance Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static InstanceNumber: number = 2097171;
/// <summary>
/// <para>(0020,0014) Isotope Number</para>
/// <para> VR: IS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static IsotopeNumberRetired: number = 2097172;
/// <summary>
/// <para>(0020,0015) Phase Number</para>
/// <para> VR: IS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PhaseNumberRetired: number = 2097173;
/// <summary>
/// <para>(0020,0016) Interval Number</para>
/// <para> VR: IS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static IntervalNumberRetired: number = 2097174;
/// <summary>
/// <para>(0020,0017) Time Slot Number</para>
/// <para> VR: IS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TimeSlotNumberRetired: number = 2097175;
/// <summary>
/// <para>(0020,0018) Angle Number</para>
/// <para> VR: IS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AngleNumberRetired: number = 2097176;
/// <summary>
/// <para>(0020,0019) Item Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ItemNumber: number = 2097177;
/// <summary>
/// <para>(0020,0020) Patient Orientation</para>
/// <para> VR: CS VM:2</para>
/// </summary>
public static PatientOrientation: number = 2097184;
/// <summary>
/// <para>(0020,0022) Overlay Number</para>
/// <para> VR: IS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayNumberRetired: number = 2097186;
/// <summary>
/// <para>(0020,0024) Curve Number</para>
/// <para> VR: IS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CurveNumberRetired: number = 2097188;
/// <summary>
/// <para>(0020,0026) LUT Number</para>
/// <para> VR: IS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static LutNumberRetired: number = 2097190;
/// <summary>
/// <para>(0020,0030) Image Position</para>
/// <para> VR: DS VM:3</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ImagePositionRetired: number = 2097200;
/// <summary>
/// <para>(0020,0032) Image Position (Patient)</para>
/// <para> VR: DS VM:3</para>
/// </summary>
public static ImagePositionPatient: number = 2097202;
/// <summary>
/// <para>(0020,0035) Image Orientation</para>
/// <para> VR: DS VM:6</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ImageOrientationRetired: number = 2097205;
/// <summary>
/// <para>(0020,0037) Image Orientation (Patient)</para>
/// <para> VR: DS VM:6</para>
/// </summary>
public static ImageOrientationPatient: number = 2097207;
/// <summary>
/// <para>(0020,0050) Location</para>
/// <para> VR: DS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static LocationRetired: number = 2097232;
/// <summary>
/// <para>(0020,0052) Frame of Reference UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static FrameOfReferenceUid: number = 2097234;
/// <summary>
/// <para>(0020,0060) Laterality</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static Laterality: number = 2097248;
/// <summary>
/// <para>(0020,0062) Image Laterality</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ImageLaterality: number = 2097250;
/// <summary>
/// <para>(0020,0070) Image Geometry Type</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ImageGeometryTypeRetired: number = 2097264;
/// <summary>
/// <para>(0020,0080) Masking Image</para>
/// <para> VR: CS VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static MaskingImageRetired: number = 2097280;
/// <summary>
/// <para>(0020,00AA) Report Number</para>
/// <para> VR: IS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReportNumberRetired: number = 2097322;
/// <summary>
/// <para>(0020,0100) Temporal Position Identifier</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static TemporalPositionIdentifier: number = 2097408;
/// <summary>
/// <para>(0020,0105) Number of Temporal Positions</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfTemporalPositions: number = 2097413;
/// <summary>
/// <para>(0020,0110) Temporal Resolution</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TemporalResolution: number = 2097424;
/// <summary>
/// <para>(0020,0200) Synchronization Frame of Reference UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static SynchronizationFrameOfReferenceUid: number = 2097664;
/// <summary>
/// <para>(0020,0242) SOP Instance UID of Concatenation Source</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static SopInstanceUidOfConcatenationSource: number = 2097730;
/// <summary>
/// <para>(0020,1000) Series in Study</para>
/// <para> VR: IS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static SeriesInStudyRetired: number = 2101248;
/// <summary>
/// <para>(0020,1001) Acquisitions in Series</para>
/// <para> VR: IS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AcquisitionsInSeriesRetired: number = 2101249;
/// <summary>
/// <para>(0020,1002) Images in Acquisition</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ImagesInAcquisition: number = 2101250;
/// <summary>
/// <para>(0020,1003) Images in Series</para>
/// <para> VR: IS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ImagesInSeriesRetired: number = 2101251;
/// <summary>
/// <para>(0020,1004) Acquisitions in Study</para>
/// <para> VR: IS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AcquisitionsInStudyRetired: number = 2101252;
/// <summary>
/// <para>(0020,1005) Images in Study</para>
/// <para> VR: IS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ImagesInStudyRetired: number = 2101253;
/// <summary>
/// <para>(0020,1020) Reference</para>
/// <para> VR: LO VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferenceRetired: number = 2101280;
/// <summary>
/// <para>(0020,1040) Position Reference Indicator</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PositionReferenceIndicator: number = 2101312;
/// <summary>
/// <para>(0020,1041) Slice Location</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SliceLocation: number = 2101313;
/// <summary>
/// <para>(0020,1070) Other Study Numbers</para>
/// <para> VR: IS VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OtherStudyNumbersRetired: number = 2101360;
/// <summary>
/// <para>(0020,1200) Number of Patient Related Studies</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfPatientRelatedStudies: number = 2101760;
/// <summary>
/// <para>(0020,1202) Number of Patient Related Series</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfPatientRelatedSeries: number = 2101762;
/// <summary>
/// <para>(0020,1204) Number of Patient Related Instances</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfPatientRelatedInstances: number = 2101764;
/// <summary>
/// <para>(0020,1206) Number of Study Related Series</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfStudyRelatedSeries: number = 2101766;
/// <summary>
/// <para>(0020,1208) Number of Study Related Instances</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfStudyRelatedInstances: number = 2101768;
/// <summary>
/// <para>(0020,1209) Number of Series Related Instances</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfSeriesRelatedInstances: number = 2101769;
/// <summary>
/// <para>(0020,3100 to 31FF) Source Image IDs</para>
/// <para> VR: CS VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static SourceImageIdsRetired: number = 2109696;
/// <summary>
/// <para>(0020,3401) Modifying Device ID</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ModifyingDeviceIdRetired: number = 2110465;
/// <summary>
/// <para>(0020,3402) Modified Image ID</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ModifiedImageIdRetired: number = 2110466;
/// <summary>
/// <para>(0020,3403) Modified Image Date</para>
/// <para> VR: DA VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ModifiedImageDateRetired: number = 2110467;
/// <summary>
/// <para>(0020,3404) Modifying Device Manufacturer</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ModifyingDeviceManufacturerRetired: number = 2110468;
/// <summary>
/// <para>(0020,3405) Modified Image Time</para>
/// <para> VR: TM VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ModifiedImageTimeRetired: number = 2110469;
/// <summary>
/// <para>(0020,3406) Modified Image Description</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ModifiedImageDescriptionRetired: number = 2110470;
/// <summary>
/// <para>(0020,4000) Image Comments</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static ImageComments: number = 2113536;
/// <summary>
/// <para>(0020,5000) Original Image Identification</para>
/// <para> VR: AT VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OriginalImageIdentificationRetired: number = 2117632;
/// <summary>
/// <para>(0020,5002) Original Image Identification Nomenclature</para>
/// <para> VR: LO VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OriginalImageIdentificationNomenclatureRetired: number = 2117634;
/// <summary>
/// <para>(0020,9056) Stack ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static StackId: number = 2134102;
/// <summary>
/// <para>(0020,9057) In-Stack Position Number</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static InStackPositionNumber: number = 2134103;
/// <summary>
/// <para>(0020,9071) Frame Anatomy Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FrameAnatomySequence: number = 2134129;
/// <summary>
/// <para>(0020,9072) Frame Laterality</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FrameLaterality: number = 2134130;
/// <summary>
/// <para>(0020,9111) Frame Content Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FrameContentSequence: number = 2134289;
/// <summary>
/// <para>(0020,9113) Plane Position Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PlanePositionSequence: number = 2134291;
/// <summary>
/// <para>(0020,9116) Plane Orientation Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PlaneOrientationSequence: number = 2134294;
/// <summary>
/// <para>(0020,9128) Temporal Position Index</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static TemporalPositionIndex: number = 2134312;
/// <summary>
/// <para>(0020,9153) Nominal Cardiac Trigger Delay Time</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static NominalCardiacTriggerDelayTime: number = 2134355;
/// <summary>
/// <para>(0020,9154) Nominal Cardiac Trigger Time Prior To R-Peak</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static NominalCardiacTriggerTimePriorToRPeak: number = 2134356;
/// <summary>
/// <para>(0020,9155) Actual Cardiac Trigger Time Prior To R-Peak</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static ActualCardiacTriggerTimePriorToRPeak: number = 2134357;
/// <summary>
/// <para>(0020,9156) Frame Acquisition Number</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static FrameAcquisitionNumber: number = 2134358;
/// <summary>
/// <para>(0020,9157) Dimension Index Values</para>
/// <para> VR: UL VM:1-n</para>
/// </summary>
public static DimensionIndexValues: number = 2134359;
/// <summary>
/// <para>(0020,9158) Frame Comments</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static FrameComments: number = 2134360;
/// <summary>
/// <para>(0020,9161) Concatenation UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static ConcatenationUid: number = 2134369;
/// <summary>
/// <para>(0020,9162) In-concatenation Number</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static InConcatenationNumber: number = 2134370;
/// <summary>
/// <para>(0020,9163) In-concatenation Total Number</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static InConcatenationTotalNumber: number = 2134371;
/// <summary>
/// <para>(0020,9164) Dimension Organization UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static DimensionOrganizationUid: number = 2134372;
/// <summary>
/// <para>(0020,9165) Dimension Index Pointer</para>
/// <para> VR: AT VM:1</para>
/// </summary>
public static DimensionIndexPointer: number = 2134373;
/// <summary>
/// <para>(0020,9167) Functional Group Pointer</para>
/// <para> VR: AT VM:1</para>
/// </summary>
public static FunctionalGroupPointer: number = 2134375;
/// <summary>
/// <para>(0020,9213) Dimension Index Private Creator</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static DimensionIndexPrivateCreator: number = 2134547;
/// <summary>
/// <para>(0020,9221) Dimension Organization Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DimensionOrganizationSequence: number = 2134561;
/// <summary>
/// <para>(0020,9222) Dimension Index Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DimensionIndexSequence: number = 2134562;
/// <summary>
/// <para>(0020,9228) Concatenation Frame Offset Number</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static ConcatenationFrameOffsetNumber: number = 2134568;
/// <summary>
/// <para>(0020,9238) Functional Group Private Creator</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static FunctionalGroupPrivateCreator: number = 2134584;
/// <summary>
/// <para>(0020,9241) Nominal Percentage of Cardiac Phase</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static NominalPercentageOfCardiacPhase: number = 2134593;
/// <summary>
/// <para>(0020,9245) Nominal Percentage of Respiratory Phase</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static NominalPercentageOfRespiratoryPhase: number = 2134597;
/// <summary>
/// <para>(0020,9246) Starting Respiratory Amplitude</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static StartingRespiratoryAmplitude: number = 2134598;
/// <summary>
/// <para>(0020,9247) Starting Respiratory Phase</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static StartingRespiratoryPhase: number = 2134599;
/// <summary>
/// <para>(0020,9248) Ending Respiratory Amplitude</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static EndingRespiratoryAmplitude: number = 2134600;
/// <summary>
/// <para>(0020,9249) Ending Respiratory Phase</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static EndingRespiratoryPhase: number = 2134601;
/// <summary>
/// <para>(0020,9250) Respiratory Trigger Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RespiratoryTriggerType: number = 2134608;
/// <summary>
/// <para>(0020,9251) R-R Interval Time Nominal</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static RRIntervalTimeNominal: number = 2134609;
/// <summary>
/// <para>(0020,9252) Actual Cardiac Trigger Delay Time</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ActualCardiacTriggerDelayTime: number = 2134610;
/// <summary>
/// <para>(0020,9253) Respiratory Synchronization Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RespiratorySynchronizationSequence: number = 2134611;
/// <summary>
/// <para>(0020,9254) Respiratory Interval Time</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static RespiratoryIntervalTime: number = 2134612;
/// <summary>
/// <para>(0020,9255) Nominal Respiratory Trigger Delay Time</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static NominalRespiratoryTriggerDelayTime: number = 2134613;
/// <summary>
/// <para>(0020,9256) Respiratory Trigger Delay Threshold</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static RespiratoryTriggerDelayThreshold: number = 2134614;
/// <summary>
/// <para>(0020,9257) Actual Respiratory Trigger Delay Time</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ActualRespiratoryTriggerDelayTime: number = 2134615;
/// <summary>
/// <para>(0020,9301) Image Position (Volume)</para>
/// <para> VR: FD VM:3</para>
/// </summary>
public static ImagePositionVolume: number = 2134785;
/// <summary>
/// <para>(0020,9302) Image Orientation (Volume)</para>
/// <para> VR: FD VM:6</para>
/// </summary>
public static ImageOrientationVolume: number = 2134786;
/// <summary>
/// <para>(0020,9307) Ultrasound Acquisition Geometry</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static UltrasoundAcquisitionGeometry: number = 2134791;
/// <summary>
/// <para>(0020,9308) Apex Position</para>
/// <para> VR: FD VM:3</para>
/// </summary>
public static ApexPosition: number = 2134792;
/// <summary>
/// <para>(0020,9309) Volume to Transducer Mapping Matrix</para>
/// <para> VR: FD VM:16</para>
/// </summary>
public static VolumeToTransducerMappingMatrix: number = 2134793;
/// <summary>
/// <para>(0020,930A) Volume to Table Mapping Matrix</para>
/// <para> VR: FD VM:16</para>
/// </summary>
public static VolumeToTableMappingMatrix: number = 2134794;
/// <summary>
/// <para>(0020,930C) Patient Frame of Reference Source</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PatientFrameOfReferenceSource: number = 2134796;
/// <summary>
/// <para>(0020,930D) Temporal Position Time Offset</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TemporalPositionTimeOffset: number = 2134797;
/// <summary>
/// <para>(0020,930E) Plane Position (Volume) Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PlanePositionVolumeSequence: number = 2134798;
/// <summary>
/// <para>(0020,930F) Plane Orientation (Volume) Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PlaneOrientationVolumeSequence: number = 2134799;
/// <summary>
/// <para>(0020,9310) Temporal Position Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TemporalPositionSequence: number = 2134800;
/// <summary>
/// <para>(0020,9311) Dimension Organization Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DimensionOrganizationType: number = 2134801;
/// <summary>
/// <para>(0020,9312) Volume Frame of Reference UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static VolumeFrameOfReferenceUid: number = 2134802;
/// <summary>
/// <para>(0020,9313) Table Frame of Reference UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static TableFrameOfReferenceUid: number = 2134803;
/// <summary>
/// <para>(0020,9421) Dimension Description Label</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static DimensionDescriptionLabel: number = 2135073;
/// <summary>
/// <para>(0020,9450) Patient Orientation in Frame Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PatientOrientationInFrameSequence: number = 2135120;
/// <summary>
/// <para>(0020,9453) Frame Label</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static FrameLabel: number = 2135123;
/// <summary>
/// <para>(0020,9518) Acquisition Index</para>
/// <para> VR: US VM:1-n</para>
/// </summary>
public static AcquisitionIndex: number = 2135320;
/// <summary>
/// <para>(0020,9529) Contributing SOP Instances Reference Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ContributingSopInstancesReferenceSequence: number = 2135337;
/// <summary>
/// <para>(0020,9536) Reconstruction Index</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ReconstructionIndex: number = 2135350;
/// <summary>
/// <para>(0022,0001) Light Path Filter Pass-Through Wavelength</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static LightPathFilterPassThroughWavelength: number = 2228225;
/// <summary>
/// <para>(0022,0002) Light Path Filter Pass Band</para>
/// <para> VR: US VM:2</para>
/// </summary>
public static LightPathFilterPassBand: number = 2228226;
/// <summary>
/// <para>(0022,0003) Image Path Filter Pass-Through Wavelength</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ImagePathFilterPassThroughWavelength: number = 2228227;
/// <summary>
/// <para>(0022,0004) Image Path Filter Pass Band</para>
/// <para> VR: US VM:2</para>
/// </summary>
public static ImagePathFilterPassBand: number = 2228228;
/// <summary>
/// <para>(0022,0005) Patient Eye Movement Commanded</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PatientEyeMovementCommanded: number = 2228229;
/// <summary>
/// <para>(0022,0006) Patient Eye Movement Command Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PatientEyeMovementCommandCodeSequence: number = 2228230;
/// <summary>
/// <para>(0022,0007) Spherical Lens Power</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static SphericalLensPower: number = 2228231;
/// <summary>
/// <para>(0022,0008) Cylinder Lens Power</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static CylinderLensPower: number = 2228232;
/// <summary>
/// <para>(0022,0009) Cylinder Axis</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static CylinderAxis: number = 2228233;
/// <summary>
/// <para>(0022,000A) Emmetropic Magnification</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static EmmetropicMagnification: number = 2228234;
/// <summary>
/// <para>(0022,000B) Intra Ocular Pressure</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static IntraOcularPressure: number = 2228235;
/// <summary>
/// <para>(0022,000C) Horizontal Field of View</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static HorizontalFieldOfView: number = 2228236;
/// <summary>
/// <para>(0022,000D) Pupil Dilated</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PupilDilated: number = 2228237;
/// <summary>
/// <para>(0022,000E) Degree of Dilation</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static DegreeOfDilation: number = 2228238;
/// <summary>
/// <para>(0022,0010) Stereo Baseline Angle</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static StereoBaselineAngle: number = 2228240;
/// <summary>
/// <para>(0022,0011) Stereo Baseline Displacement</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static StereoBaselineDisplacement: number = 2228241;
/// <summary>
/// <para>(0022,0012) Stereo Horizontal Pixel Offset</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static StereoHorizontalPixelOffset: number = 2228242;
/// <summary>
/// <para>(0022,0013) Stereo Vertical Pixel Offset</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static StereoVerticalPixelOffset: number = 2228243;
/// <summary>
/// <para>(0022,0014) Stereo Rotation</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static StereoRotation: number = 2228244;
/// <summary>
/// <para>(0022,0015) Acquisition Device Type Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AcquisitionDeviceTypeCodeSequence: number = 2228245;
/// <summary>
/// <para>(0022,0016) Illumination Type Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IlluminationTypeCodeSequence: number = 2228246;
/// <summary>
/// <para>(0022,0017) Light Path Filter Type Stack Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static LightPathFilterTypeStackCodeSequence: number = 2228247;
/// <summary>
/// <para>(0022,0018) Image Path Filter Type Stack Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ImagePathFilterTypeStackCodeSequence: number = 2228248;
/// <summary>
/// <para>(0022,0019) Lenses Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static LensesCodeSequence: number = 2228249;
/// <summary>
/// <para>(0022,001A) Channel Description Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ChannelDescriptionCodeSequence: number = 2228250;
/// <summary>
/// <para>(0022,001B) Refractive State Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RefractiveStateSequence: number = 2228251;
/// <summary>
/// <para>(0022,001C) Mydriatic Agent Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MydriaticAgentCodeSequence: number = 2228252;
/// <summary>
/// <para>(0022,001D) Relative Image Position Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RelativeImagePositionCodeSequence: number = 2228253;
/// <summary>
/// <para>(0022,001E) Camera Angle of View</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static CameraAngleOfView: number = 2228254;
/// <summary>
/// <para>(0022,0020) Stereo Pairs Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static StereoPairsSequence: number = 2228256;
/// <summary>
/// <para>(0022,0021) Left Image Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static LeftImageSequence: number = 2228257;
/// <summary>
/// <para>(0022,0022) Right Image Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RightImageSequence: number = 2228258;
/// <summary>
/// <para>(0022,0030) Axial Length of the Eye</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static AxialLengthOfTheEye: number = 2228272;
/// <summary>
/// <para>(0022,0031) Ophthalmic Frame Location Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OphthalmicFrameLocationSequence: number = 2228273;
/// <summary>
/// <para>(0022,0032) Reference Coordinates</para>
/// <para> VR: FL VM:2-2n</para>
/// </summary>
public static ReferenceCoordinates: number = 2228274;
/// <summary>
/// <para>(0022,0035) Depth Spatial Resolution</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static DepthSpatialResolution: number = 2228277;
/// <summary>
/// <para>(0022,0036) Maximum Depth Distortion</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static MaximumDepthDistortion: number = 2228278;
/// <summary>
/// <para>(0022,0037) Along-scan Spatial Resolution</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static AlongScanSpatialResolution: number = 2228279;
/// <summary>
/// <para>(0022,0038) Maximum Along-scan Distortion</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static MaximumAlongScanDistortion: number = 2228280;
/// <summary>
/// <para>(0022,0039) Ophthalmic Image Orientation</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static OphthalmicImageOrientation: number = 2228281;
/// <summary>
/// <para>(0022,0041) Depth of Transverse Image</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static DepthOfTransverseImage: number = 2228289;
/// <summary>
/// <para>(0022,0042) Mydriatic Agent Concentration Units Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MydriaticAgentConcentrationUnitsSequence: number = 2228290;
/// <summary>
/// <para>(0022,0048) Across-scan Spatial Resolution</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static AcrossScanSpatialResolution: number = 2228296;
/// <summary>
/// <para>(0022,0049) Maximum Across-scan Distortion</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static MaximumAcrossScanDistortion: number = 2228297;
/// <summary>
/// <para>(0022,004E) Mydriatic Agent Concentration</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static MydriaticAgentConcentration: number = 2228302;
/// <summary>
/// <para>(0022,0055) Illumination Wave Length</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static IlluminationWaveLength: number = 2228309;
/// <summary>
/// <para>(0022,0056) Illumination Power</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static IlluminationPower: number = 2228310;
/// <summary>
/// <para>(0022,0057) Illumination Bandwidth</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static IlluminationBandwidth: number = 2228311;
/// <summary>
/// <para>(0022,0058) Mydriatic Agent Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MydriaticAgentSequence: number = 2228312;
/// <summary>
/// <para>(0022,1007) Ophthalmic Axial Measurements Right Eye Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OphthalmicAxialMeasurementsRightEyeSequence: number = 2232327;
/// <summary>
/// <para>(0022,1008) Ophthalmic Axial Measurements Left Eye Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OphthalmicAxialMeasurementsLeftEyeSequence: number = 2232328;
/// <summary>
/// <para>(0022,1010) Ophthalmic Axial Length Measurements Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static OphthalmicAxialLengthMeasurementsType: number = 2232336;
/// <summary>
/// <para>(0022,1019) Ophthalmic Axial Length </para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static OphthalmicAxialLength: number = 2232345;
/// <summary>
/// <para>(0022,1024) Lens Status Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static LensStatusCodeSequence: number = 2232356;
/// <summary>
/// <para>(0022,1025) Vitreous Status Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static VitreousStatusCodeSequence: number = 2232357;
/// <summary>
/// <para>(0022,1028) IOL Formula Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IolFormulaCodeSequence: number = 2232360;
/// <summary>
/// <para>(0022,1029) IOL Formula Detail</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static IolFormulaDetail: number = 2232361;
/// <summary>
/// <para>(0022,1033) Keratometer Index</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static KeratometerIndex: number = 2232371;
/// <summary>
/// <para>(0022,1035) Source of Ophthalmic Axial Length Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SourceOfOphthalmicAxialLengthCodeSequence: number = 2232373;
/// <summary>
/// <para>(0022,1037) Target Refraction </para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static TargetRefraction: number = 2232375;
/// <summary>
/// <para>(0022,1039) Refractive Procedure Occurred</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RefractiveProcedureOccurred: number = 2232377;
/// <summary>
/// <para>(0022,1040) Refractive Surgery Type Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RefractiveSurgeryTypeCodeSequence: number = 2232384;
/// <summary>
/// <para>(0022,1044) Ophthalmic Ultrasound Axial Measurements Type Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OphthalmicUltrasoundAxialMeasurementsTypeCodeSequence: number = 2232388;
/// <summary>
/// <para>(0022,1050) Ophthalmic Axial Length Measurements Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OphthalmicAxialLengthMeasurementsSequence: number = 2232400;
/// <summary>
/// <para>(0022,1053) IOL Power</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static IolPower: number = 2232403;
/// <summary>
/// <para>(0022,1054) Predicted Refractive Error</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static PredictedRefractiveError: number = 2232404;
/// <summary>
/// <para>(0022,1059) Ophthalmic Axial Length Velocity</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static OphthalmicAxialLengthVelocity: number = 2232409;
/// <summary>
/// <para>(0022,1065) Lens Status Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static LensStatusDescription: number = 2232421;
/// <summary>
/// <para>(0022,1066) Vitreous Status Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static VitreousStatusDescription: number = 2232422;
/// <summary>
/// <para>(0022,1090) IOL Power Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IolPowerSequence: number = 2232464;
/// <summary>
/// <para>(0022,1092) Lens Constant Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static LensConstantSequence: number = 2232466;
/// <summary>
/// <para>(0022,1093) IOL Manufacturer</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static IolManufacturer: number = 2232467;
/// <summary>
/// <para>(0022,1094) Lens Constant Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static LensConstantDescription: number = 2232468;
/// <summary>
/// <para>(0022,1096) Keratometry Measurement Type Code Sequence </para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static KeratometryMeasurementTypeCodeSequence: number = 2232470;
/// <summary>
/// <para>(0022,1100) Referenced Ophthalmic Axial Measurements Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedOphthalmicAxialMeasurementsSequence: number = 2232576;
/// <summary>
/// <para>(0022,1101) Ophthalmic Axial Length Measurements Segment Name Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OphthalmicAxialLengthMeasurementsSegmentNameCodeSequence: number = 2232577;
/// <summary>
/// <para>(0022,1103) Refractive Error Before Refractive Surgery Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RefractiveErrorBeforeRefractiveSurgeryCodeSequence: number = 2232579;
/// <summary>
/// <para>(0022,1121) IOL Power For Exact Emmetropia</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static IolPowerForExactEmmetropia: number = 2232609;
/// <summary>
/// <para>(0022,1122) IOL Power For Exact Target Refraction</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static IolPowerForExactTargetRefraction: number = 2232610;
/// <summary>
/// <para>(0022,1125) Anterior Chamber Depth Definition Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AnteriorChamberDepthDefinitionCodeSequence: number = 2232613;
/// <summary>
/// <para>(0022,1130) Lens Thickness</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static LensThickness: number = 2232624;
/// <summary>
/// <para>(0022,1131) Anterior Chamber Depth</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static AnteriorChamberDepth: number = 2232625;
/// <summary>
/// <para>(0022,1132) Source of Lens Thickness Data Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SourceOfLensThicknessDataCodeSequence: number = 2232626;
/// <summary>
/// <para>(0022,1133) Source of Anterior Chamber Depth Data Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SourceOfAnteriorChamberDepthDataCodeSequence: number = 2232627;
/// <summary>
/// <para>(0022,1135) Source of Refractive Error Data Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SourceOfRefractiveErrorDataCodeSequence: number = 2232629;
/// <summary>
/// <para>(0022,1140) Ophthalmic Axial Length Measurement Modified</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static OphthalmicAxialLengthMeasurementModified: number = 2232640;
/// <summary>
/// <para>(0022,1150) Ophthalmic Axial Length Data Source Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OphthalmicAxialLengthDataSourceCodeSequence: number = 2232656;
/// <summary>
/// <para>(0022,1153) Ophthalmic Axial Length Acquisition Method Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OphthalmicAxialLengthAcquisitionMethodCodeSequence: number = 2232659;
/// <summary>
/// <para>(0022,1155) Signal to Noise Ratio</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static SignalToNoiseRatio: number = 2232661;
/// <summary>
/// <para>(0022,1159) Ophthalmic Axial Length Data Source Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static OphthalmicAxialLengthDataSourceDescription: number = 2232665;
/// <summary>
/// <para>(0022,1210) Ophthalmic Axial Length Measurements Total Length Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OphthalmicAxialLengthMeasurementsTotalLengthSequence: number = 2232848;
/// <summary>
/// <para>(0022,1211) Ophthalmic Axial Length Measurements Segmental Length Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OphthalmicAxialLengthMeasurementsSegmentalLengthSequence: number = 2232849;
/// <summary>
/// <para>(0022,1212) Ophthalmic Axial Length Measurements Length Summation Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OphthalmicAxialLengthMeasurementsLengthSummationSequence: number = 2232850;
/// <summary>
/// <para>(0022,1220) Ultrasound Ophthalmic Axial Length Measurements Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static UltrasoundOphthalmicAxialLengthMeasurementsSequence: number = 2232864;
/// <summary>
/// <para>(0022,1225) Optical Ophthalmic Axial Length Measurements Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OpticalOphthalmicAxialLengthMeasurementsSequence: number = 2232869;
/// <summary>
/// <para>(0022,1230) Ultrasound Selected Ophthalmic Axial Length Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static UltrasoundSelectedOphthalmicAxialLengthSequence: number = 2232880;
/// <summary>
/// <para>(0022,1250) Ophthalmic Axial Length Selection Method Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OphthalmicAxialLengthSelectionMethodCodeSequence: number = 2232912;
/// <summary>
/// <para>(0022,1255) Optical Selected Ophthalmic Axial Length Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OpticalSelectedOphthalmicAxialLengthSequence: number = 2232917;
/// <summary>
/// <para>(0022,1257) Selected Segmental Ophthalmic Axial Length Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SelectedSegmentalOphthalmicAxialLengthSequence: number = 2232919;
/// <summary>
/// <para>(0022,1260) Selected Total Ophthalmic Axial Length Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SelectedTotalOphthalmicAxialLengthSequence: number = 2232928;
/// <summary>
/// <para>(0022,1262) Ophthalmic Axial Length Quality Metric Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OphthalmicAxialLengthQualityMetricSequence: number = 2232930;
/// <summary>
/// <para>(0022,1273) Ophthalmic Axial Length Quality Metric Type Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static OphthalmicAxialLengthQualityMetricTypeDescription: number = 2232947;
/// <summary>
/// <para>(0022,1300) Intraocular Lens Calculations Right Eye Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IntraocularLensCalculationsRightEyeSequence: number = 2233088;
/// <summary>
/// <para>(0022,1310) Intraocular Lens Calculations Left Eye Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IntraocularLensCalculationsLeftEyeSequence: number = 2233104;
/// <summary>
/// <para>(0022,1330) Referenced Ophthalmic Axial Length Measurement QC Image Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedOphthalmicAxialLengthMeasurementQcImageSequence: number = 2233136;
/// <summary>
/// <para>(0024,0010) Visual Field Horizontal Extent </para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static VisualFieldHorizontalExtent: number = 2359312;
/// <summary>
/// <para>(0024,0011) Visual Field Vertical Extent</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static VisualFieldVerticalExtent: number = 2359313;
/// <summary>
/// <para>(0024,0012) Visual Field Shape</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static VisualFieldShape: number = 2359314;
/// <summary>
/// <para>(0024,0016) Screening Test Mode Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ScreeningTestModeCodeSequence: number = 2359318;
/// <summary>
/// <para>(0024,0018) Maximum Stimulus Luminance</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static MaximumStimulusLuminance: number = 2359320;
/// <summary>
/// <para>(0024,0020) Background Luminance </para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static BackgroundLuminance: number = 2359328;
/// <summary>
/// <para>(0024,0021) Stimulus Color Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static StimulusColorCodeSequence: number = 2359329;
/// <summary>
/// <para>(0024,0024) Background Illumination Color Code Sequence </para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BackgroundIlluminationColorCodeSequence: number = 2359332;
/// <summary>
/// <para>(0024,0025) Stimulus Area</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static StimulusArea: number = 2359333;
/// <summary>
/// <para>(0024,0028) Stimulus Presentation Time</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static StimulusPresentationTime: number = 2359336;
/// <summary>
/// <para>(0024,0032) Fixation Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FixationSequence: number = 2359346;
/// <summary>
/// <para>(0024,0033) Fixation Monitoring Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FixationMonitoringCodeSequence: number = 2359347;
/// <summary>
/// <para>(0024,0034) Visual Field Catch Trial Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static VisualFieldCatchTrialSequence: number = 2359348;
/// <summary>
/// <para>(0024,0035) Fixation Checked Quantity</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static FixationCheckedQuantity: number = 2359349;
/// <summary>
/// <para>(0024,0036) Patient Not Properly Fixated Quantity</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static PatientNotProperlyFixatedQuantity: number = 2359350;
/// <summary>
/// <para>(0024,0037) Presented Visual Stimuli Data Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PresentedVisualStimuliDataFlag: number = 2359351;
/// <summary>
/// <para>(0024,0038) Number of Visual Stimuli</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfVisualStimuli: number = 2359352;
/// <summary>
/// <para>(0024,0039) Excessive Fixation Losses Data Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ExcessiveFixationLossesDataFlag: number = 2359353;
/// <summary>
/// <para>(0024,0040) Excessive Fixation Losses</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ExcessiveFixationLosses: number = 2359360;
/// <summary>
/// <para>(0024,0042) Stimuli Retesting Quantity</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static StimuliRetestingQuantity: number = 2359362;
/// <summary>
/// <para>(0024,0044) Comments on Patient's Performance of Visual Field</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static CommentsOnPatientsPerformanceOfVisualField: number = 2359364;
/// <summary>
/// <para>(0024,0045) False Negatives Estimate Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FalseNegativesEstimateFlag: number = 2359365;
/// <summary>
/// <para>(0024,0046) False Negatives Estimate</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static FalseNegativesEstimate: number = 2359366;
/// <summary>
/// <para>(0024,0048) Negative Catch Trials Quantity</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NegativeCatchTrialsQuantity: number = 2359368;
/// <summary>
/// <para>(0024,0050) False Negatives Quantity</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static FalseNegativesQuantity: number = 2359376;
/// <summary>
/// <para>(0024,0051) Excessive False Negatives Data Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ExcessiveFalseNegativesDataFlag: number = 2359377;
/// <summary>
/// <para>(0024,0052) Excessive False Negatives</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ExcessiveFalseNegatives: number = 2359378;
/// <summary>
/// <para>(0024,0053) False Positives Estimate Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FalsePositivesEstimateFlag: number = 2359379;
/// <summary>
/// <para>(0024,0054) False Positives Estimate</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static FalsePositivesEstimate: number = 2359380;
/// <summary>
/// <para>(0024,0055) Catch Trials Data Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CatchTrialsDataFlag: number = 2359381;
/// <summary>
/// <para>(0024,0056) Positive Catch Trials Quantity</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static PositiveCatchTrialsQuantity: number = 2359382;
/// <summary>
/// <para>(0024,0057) Test Point Normals Data Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TestPointNormalsDataFlag: number = 2359383;
/// <summary>
/// <para>(0024,0058) Test Point Normals Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TestPointNormalsSequence: number = 2359384;
/// <summary>
/// <para>(0024,0059) Global Deviation Probability Normals Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static GlobalDeviationProbabilityNormalsFlag: number = 2359385;
/// <summary>
/// <para>(0024,0060) False Positives Quantity</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static FalsePositivesQuantity: number = 2359392;
/// <summary>
/// <para>(0024,0061) Excessive False Positives Data Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ExcessiveFalsePositivesDataFlag: number = 2359393;
/// <summary>
/// <para>(0024,0062) Excessive False Positives</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ExcessiveFalsePositives: number = 2359394;
/// <summary>
/// <para>(0024,0063) Visual Field Test Normals Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static VisualFieldTestNormalsFlag: number = 2359395;
/// <summary>
/// <para>(0024,0064) Results Normals Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ResultsNormalsSequence: number = 2359396;
/// <summary>
/// <para>(0024,0065) Age Corrected Sensitivity Deviation Algorithm Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AgeCorrectedSensitivityDeviationAlgorithmSequence: number = 2359397;
/// <summary>
/// <para>(0024,0066) Global Deviation From Normal</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static GlobalDeviationFromNormal: number = 2359398;
/// <summary>
/// <para>(0024,0067) Generalized Defect Sensitivity Deviation Algorithm Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static GeneralizedDefectSensitivityDeviationAlgorithmSequence: number = 2359399;
/// <summary>
/// <para>(0024,0068) Localized Deviation from Normal</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static LocalizedDeviationFromNormal: number = 2359400;
/// <summary>
/// <para>(0024,0069) Patient Reliability Indicator </para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PatientReliabilityIndicator: number = 2359401;
/// <summary>
/// <para>(0024,0070) Visual Field Mean Sensitivity</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static VisualFieldMeanSensitivity: number = 2359408;
/// <summary>
/// <para>(0024,0071) Global Deviation Probability</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static GlobalDeviationProbability: number = 2359409;
/// <summary>
/// <para>(0024,0072) Local Deviation Probability Normals Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static LocalDeviationProbabilityNormalsFlag: number = 2359410;
/// <summary>
/// <para>(0024,0073) Localized Deviation Probability</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static LocalizedDeviationProbability: number = 2359411;
/// <summary>
/// <para>(0024,0074) Short Term Fluctuation Calculated</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ShortTermFluctuationCalculated: number = 2359412;
/// <summary>
/// <para>(0024,0075) Short Term Fluctuation</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static ShortTermFluctuation: number = 2359413;
/// <summary>
/// <para>(0024,0076) Short Term Fluctuation Probability Calculated</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ShortTermFluctuationProbabilityCalculated: number = 2359414;
/// <summary>
/// <para>(0024,0077) Short Term Fluctuation Probability</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static ShortTermFluctuationProbability: number = 2359415;
/// <summary>
/// <para>(0024,0078) Corrected Localized Deviation From Normal Calculated</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CorrectedLocalizedDeviationFromNormalCalculated: number = 2359416;
/// <summary>
/// <para>(0024,0079) Corrected Localized Deviation From Normal</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static CorrectedLocalizedDeviationFromNormal: number = 2359417;
/// <summary>
/// <para>(0024,0080) Corrected Localized Deviation From Normal Probability Calculated</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CorrectedLocalizedDeviationFromNormalProbabilityCalculated: number = 2359424;
/// <summary>
/// <para>(0024,0081) Corrected Localized Deviation From Normal Probability</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static CorrectedLocalizedDeviationFromNormalProbability: number = 2359425;
/// <summary>
/// <para>(0024,0083) Global Deviation Probability Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static GlobalDeviationProbabilitySequence: number = 2359427;
/// <summary>
/// <para>(0024,0085) Localized Deviation Probability Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static LocalizedDeviationProbabilitySequence: number = 2359429;
/// <summary>
/// <para>(0024,0086) Foveal Sensitivity Measured</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FovealSensitivityMeasured: number = 2359430;
/// <summary>
/// <para>(0024,0087) Foveal Sensitivity</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static FovealSensitivity: number = 2359431;
/// <summary>
/// <para>(0024,0088) Visual Field Test Duration</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static VisualFieldTestDuration: number = 2359432;
/// <summary>
/// <para>(0024,0089) Visual Field Test Point Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static VisualFieldTestPointSequence: number = 2359433;
/// <summary>
/// <para>(0024,0090) Visual Field Test Point X-Coordinate</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static VisualFieldTestPointXCoordinate: number = 2359440;
/// <summary>
/// <para>(0024,0091) Visual Field Test Point Y-Coordinate</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static VisualFieldTestPointYCoordinate: number = 2359441;
/// <summary>
/// <para>(0024,0092) Age Corrected Sensitivity Deviation Value</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static AgeCorrectedSensitivityDeviationValue: number = 2359442;
/// <summary>
/// <para>(0024,0093) Stimulus Results</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static StimulusResults: number = 2359443;
/// <summary>
/// <para>(0024,0094) Sensitivity Value</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static SensitivityValue: number = 2359444;
/// <summary>
/// <para>(0024,0095) Retest Stimulus Seen</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RetestStimulusSeen: number = 2359445;
/// <summary>
/// <para>(0024,0096) Retest Sensitivity Value</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static RetestSensitivityValue: number = 2359446;
/// <summary>
/// <para>(0024,0097) Visual Field Test Point Normals Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static VisualFieldTestPointNormalsSequence: number = 2359447;
/// <summary>
/// <para>(0024,0098) Quantified Defect</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static QuantifiedDefect: number = 2359448;
/// <summary>
/// <para>(0024,0100) Age Corrected Sensitivity Deviation Probability Value</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static AgeCorrectedSensitivityDeviationProbabilityValue: number = 2359552;
/// <summary>
/// <para>(0024,0102) Generalized Defect Corrected Sensitivity Deviation Flag </para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static GeneralizedDefectCorrectedSensitivityDeviationFlag: number = 2359554;
/// <summary>
/// <para>(0024,0103) Generalized Defect Corrected Sensitivity Deviation Value </para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static GeneralizedDefectCorrectedSensitivityDeviationValue: number = 2359555;
/// <summary>
/// <para>(0024,0104) Generalized Defect Corrected Sensitivity Deviation Probability Value </para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static GeneralizedDefectCorrectedSensitivityDeviationProbabilityValue: number = 2359556;
/// <summary>
/// <para>(0024,0105) Minimum Sensitivity Value</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static MinimumSensitivityValue: number = 2359557;
/// <summary>
/// <para>(0024,0106) Blind Spot Localized</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BlindSpotLocalized: number = 2359558;
/// <summary>
/// <para>(0024,0107) Blind Spot X-Coordinate</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static BlindSpotXCoordinate: number = 2359559;
/// <summary>
/// <para>(0024,0108) Blind Spot Y-Coordinate </para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static BlindSpotYCoordinate: number = 2359560;
/// <summary>
/// <para>(0024,0110) Visual Acuity Measurement Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static VisualAcuityMeasurementSequence: number = 2359568;
/// <summary>
/// <para>(0024,0112) Refractive Parameters Used on Patient Sequence </para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RefractiveParametersUsedOnPatientSequence: number = 2359570;
/// <summary>
/// <para>(0024,0113) Measurement Laterality</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static MeasurementLaterality: number = 2359571;
/// <summary>
/// <para>(0024,0114) Ophthalmic Patient Clinical Information Left Eye Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OphthalmicPatientClinicalInformationLeftEyeSequence: number = 2359572;
/// <summary>
/// <para>(0024,0115) Ophthalmic Patient Clinical Information Right Eye Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OphthalmicPatientClinicalInformationRightEyeSequence: number = 2359573;
/// <summary>
/// <para>(0024,0117) Foveal Point Normative Data Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FovealPointNormativeDataFlag: number = 2359575;
/// <summary>
/// <para>(0024,0118) Foveal Point Probability Value</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static FovealPointProbabilityValue: number = 2359576;
/// <summary>
/// <para>(0024,0120) Screening Baseline Measured</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ScreeningBaselineMeasured: number = 2359584;
/// <summary>
/// <para>(0024,0122) Screening Baseline Measured Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ScreeningBaselineMeasuredSequence: number = 2359586;
/// <summary>
/// <para>(0024,0124) Screening Baseline Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ScreeningBaselineType: number = 2359588;
/// <summary>
/// <para>(0024,0126) Screening Baseline Value</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static ScreeningBaselineValue: number = 2359590;
/// <summary>
/// <para>(0024,0202) Algorithm Source</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static AlgorithmSource: number = 2359810;
/// <summary>
/// <para>(0024,0306) Data Set Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static DataSetName: number = 2360070;
/// <summary>
/// <para>(0024,0307) Data Set Version</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static DataSetVersion: number = 2360071;
/// <summary>
/// <para>(0024,0308) Data Set Source</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static DataSetSource: number = 2360072;
/// <summary>
/// <para>(0024,0309) Data Set Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static DataSetDescription: number = 2360073;
/// <summary>
/// <para>(0024,0317) Visual Field Test Reliability Global Index Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static VisualFieldTestReliabilityGlobalIndexSequence: number = 2360087;
/// <summary>
/// <para>(0024,0320) Visual Field Global Results Index Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static VisualFieldGlobalResultsIndexSequence: number = 2360096;
/// <summary>
/// <para>(0024,0325) Data Observation Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DataObservationSequence: number = 2360101;
/// <summary>
/// <para>(0024,0338) Index Normals Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static IndexNormalsFlag: number = 2360120;
/// <summary>
/// <para>(0024,0341) Index Probability</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static IndexProbability: number = 2360129;
/// <summary>
/// <para>(0024,0344) Index Probability Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IndexProbabilitySequence: number = 2360132;
/// <summary>
/// <para>(0028,0002) Samples per Pixel</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static SamplesPerPixel: number = 2621442;
/// <summary>
/// <para>(0028,0003) Samples per Pixel Used</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static SamplesPerPixelUsed: number = 2621443;
/// <summary>
/// <para>(0028,0004) Photometric Interpretation</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PhotometricInterpretation: number = 2621444;
/// <summary>
/// <para>(0028,0005) Image Dimensions</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ImageDimensionsRetired: number = 2621445;
/// <summary>
/// <para>(0028,0006) Planar Configuration</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static PlanarConfiguration: number = 2621446;
/// <summary>
/// <para>(0028,0008) Number of Frames</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfFrames: number = 2621448;
/// <summary>
/// <para>(0028,0009) Frame Increment Pointer</para>
/// <para> VR: AT VM:1-n</para>
/// </summary>
public static FrameIncrementPointer: number = 2621449;
/// <summary>
/// <para>(0028,000A) Frame Dimension Pointer</para>
/// <para> VR: AT VM:1-n</para>
/// </summary>
public static FrameDimensionPointer: number = 2621450;
/// <summary>
/// <para>(0028,0010) Rows</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static Rows: number = 2621456;
/// <summary>
/// <para>(0028,0011) Columns</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static Columns: number = 2621457;
/// <summary>
/// <para>(0028,0012) Planes</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PlanesRetired: number = 2621458;
/// <summary>
/// <para>(0028,0014) Ultrasound Color Data Present</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static UltrasoundColorDataPresent: number = 2621460;
/// <summary>
/// <para>(0028,0030) Pixel Spacing</para>
/// <para> VR: DS VM:2</para>
/// </summary>
public static PixelSpacing: number = 2621488;
/// <summary>
/// <para>(0028,0031) Zoom Factor</para>
/// <para> VR: DS VM:2</para>
/// </summary>
public static ZoomFactor: number = 2621489;
/// <summary>
/// <para>(0028,0032) Zoom Center</para>
/// <para> VR: DS VM:2</para>
/// </summary>
public static ZoomCenter: number = 2621490;
/// <summary>
/// <para>(0028,0034) Pixel Aspect Ratio</para>
/// <para> VR: IS VM:2</para>
/// </summary>
public static PixelAspectRatio: number = 2621492;
/// <summary>
/// <para>(0028,0040) Image Format</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ImageFormatRetired: number = 2621504;
/// <summary>
/// <para>(0028,0050) Manipulated Image</para>
/// <para> VR: LO VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ManipulatedImageRetired: number = 2621520;
/// <summary>
/// <para>(0028,0051) Corrected Image</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static CorrectedImage: number = 2621521;
/// <summary>
/// <para>(0028,005F) Compression Recognition Code</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CompressionRecognitionCodeRetired: number = 2621535;
/// <summary>
/// <para>(0028,0060) Compression Code</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CompressionCodeRetired: number = 2621536;
/// <summary>
/// <para>(0028,0061) Compression Originator</para>
/// <para> VR: SH VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CompressionOriginatorRetired: number = 2621537;
/// <summary>
/// <para>(0028,0062) Compression Label</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CompressionLabelRetired: number = 2621538;
/// <summary>
/// <para>(0028,0063) Compression Description</para>
/// <para> VR: SH VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CompressionDescriptionRetired: number = 2621539;
/// <summary>
/// <para>(0028,0065) Compression Sequence</para>
/// <para> VR: CS VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CompressionSequenceRetired: number = 2621541;
/// <summary>
/// <para>(0028,0066) Compression Step Pointers</para>
/// <para> VR: AT VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CompressionStepPointersRetired: number = 2621542;
/// <summary>
/// <para>(0028,0068) Repeat Interval</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static RepeatIntervalRetired: number = 2621544;
/// <summary>
/// <para>(0028,0069) Bits Grouped</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static BitsGroupedRetired: number = 2621545;
/// <summary>
/// <para>(0028,0070) Perimeter Table</para>
/// <para> VR: US VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PerimeterTableRetired: number = 2621552;
/// <summary>
/// <para>(0028,0071) Perimeter Value</para>
/// <para> VR: US or SS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PerimeterValueRetired: number = 2621553;
/// <summary>
/// <para>(0028,0080) Predictor Rows</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PredictorRowsRetired: number = 2621568;
/// <summary>
/// <para>(0028,0081) Predictor Columns</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PredictorColumnsRetired: number = 2621569;
/// <summary>
/// <para>(0028,0082) Predictor Constants</para>
/// <para> VR: US VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PredictorConstantsRetired: number = 2621570;
/// <summary>
/// <para>(0028,0090) Blocked Pixels</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static BlockedPixelsRetired: number = 2621584;
/// <summary>
/// <para>(0028,0091) Block Rows</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static BlockRowsRetired: number = 2621585;
/// <summary>
/// <para>(0028,0092) Block Columns</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static BlockColumnsRetired: number = 2621586;
/// <summary>
/// <para>(0028,0093) Row Overlap</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static RowOverlapRetired: number = 2621587;
/// <summary>
/// <para>(0028,0094) Column Overlap</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ColumnOverlapRetired: number = 2621588;
/// <summary>
/// <para>(0028,0100) Bits Allocated</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static BitsAllocated: number = 2621696;
/// <summary>
/// <para>(0028,0101) Bits Stored</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static BitsStored: number = 2621697;
/// <summary>
/// <para>(0028,0102) High Bit</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static HighBit: number = 2621698;
/// <summary>
/// <para>(0028,0103) Pixel Representation</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static PixelRepresentation: number = 2621699;
/// <summary>
/// <para>(0028,0104) Smallest Valid Pixel Value</para>
/// <para> VR: US or SS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static SmallestValidPixelValueRetired: number = 2621700;
/// <summary>
/// <para>(0028,0105) Largest Valid Pixel Value</para>
/// <para> VR: US or SS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static LargestValidPixelValueRetired: number = 2621701;
/// <summary>
/// <para>(0028,0106) Smallest Image Pixel Value</para>
/// <para> VR: US or SS VM:1</para>
/// </summary>
public static SmallestImagePixelValue: number = 2621702;
/// <summary>
/// <para>(0028,0107) Largest Image Pixel Value</para>
/// <para> VR: US or SS VM:1</para>
/// </summary>
public static LargestImagePixelValue: number = 2621703;
/// <summary>
/// <para>(0028,0108) Smallest Pixel Value in Series</para>
/// <para> VR: US or SS VM:1</para>
/// </summary>
public static SmallestPixelValueInSeries: number = 2621704;
/// <summary>
/// <para>(0028,0109) Largest Pixel Value in Series</para>
/// <para> VR: US or SS VM:1</para>
/// </summary>
public static LargestPixelValueInSeries: number = 2621705;
/// <summary>
/// <para>(0028,0110) Smallest Image Pixel Value in Plane</para>
/// <para> VR: US or SS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static SmallestImagePixelValueInPlaneRetired: number = 2621712;
/// <summary>
/// <para>(0028,0111) Largest Image Pixel Value in Plane</para>
/// <para> VR: US or SS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static LargestImagePixelValueInPlaneRetired: number = 2621713;
/// <summary>
/// <para>(0028,0120) Pixel Padding Value</para>
/// <para> VR: US or SS VM:1</para>
/// </summary>
public static PixelPaddingValue: number = 2621728;
/// <summary>
/// <para>(0028,0121) Pixel Padding Range Limit</para>
/// <para> VR: US or SS VM:1</para>
/// </summary>
public static PixelPaddingRangeLimit: number = 2621729;
/// <summary>
/// <para>(0028,0200) Image Location</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ImageLocationRetired: number = 2621952;
/// <summary>
/// <para>(0028,0300) Quality Control Image</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static QualityControlImage: number = 2622208;
/// <summary>
/// <para>(0028,0301) Burned In Annotation</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BurnedInAnnotation: number = 2622209;
/// <summary>
/// <para>(0028,0302) Recognizable Visual Features</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RecognizableVisualFeatures: number = 2622210;
/// <summary>
/// <para>(0028,0303) Longitudinal Temporal Information Modified</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static LongitudinalTemporalInformationModified: number = 2622211;
/// <summary>
/// <para>(0028,0400) Transform Label</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TransformLabelRetired: number = 2622464;
/// <summary>
/// <para>(0028,0401) Transform Version Number</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TransformVersionNumberRetired: number = 2622465;
/// <summary>
/// <para>(0028,0402) Number of Transform Steps</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static NumberOfTransformStepsRetired: number = 2622466;
/// <summary>
/// <para>(0028,0403) Sequence of Compressed Data</para>
/// <para> VR: LO VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static SequenceOfCompressedDataRetired: number = 2622467;
/// <summary>
/// <para>(0028,0404) Details of Coefficients</para>
/// <para> VR: AT VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DetailsOfCoefficientsRetired: number = 2622468;
/// <summary>
/// <para>(0028,0700) DCT Label</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DctLabelRetired: number = 2623232;
/// <summary>
/// <para>(0028,0701) Data Block Description</para>
/// <para> VR: CS VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DataBlockDescriptionRetired: number = 2623233;
/// <summary>
/// <para>(0028,0702) Data Block</para>
/// <para> VR: AT VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DataBlockRetired: number = 2623234;
/// <summary>
/// <para>(0028,0710) Normalization Factor Format</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static NormalizationFactorFormatRetired: number = 2623248;
/// <summary>
/// <para>(0028,0720) Zonal Map Number Format</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ZonalMapNumberFormatRetired: number = 2623264;
/// <summary>
/// <para>(0028,0721) Zonal Map Location</para>
/// <para> VR: AT VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ZonalMapLocationRetired: number = 2623265;
/// <summary>
/// <para>(0028,0722) Zonal Map Format</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ZonalMapFormatRetired: number = 2623266;
/// <summary>
/// <para>(0028,0730) Adaptive Map Format</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AdaptiveMapFormatRetired: number = 2623280;
/// <summary>
/// <para>(0028,0740) Code Number Format</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CodeNumberFormatRetired: number = 2623296;
/// <summary>
/// <para>(0028,0A02) Pixel Spacing Calibration Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PixelSpacingCalibrationType: number = 2624002;
/// <summary>
/// <para>(0028,0A04) Pixel Spacing Calibration Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PixelSpacingCalibrationDescription: number = 2624004;
/// <summary>
/// <para>(0028,1040) Pixel Intensity Relationship</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PixelIntensityRelationship: number = 2625600;
/// <summary>
/// <para>(0028,1041) Pixel Intensity Relationship Sign</para>
/// <para> VR: SS VM:1</para>
/// </summary>
public static PixelIntensityRelationshipSign: number = 2625601;
/// <summary>
/// <para>(0028,1050) Window Center</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static WindowCenter: number = 2625616;
/// <summary>
/// <para>(0028,1051) Window Width</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static WindowWidth: number = 2625617;
/// <summary>
/// <para>(0028,1052) Rescale Intercept</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static RescaleIntercept: number = 2625618;
/// <summary>
/// <para>(0028,1053) Rescale Slope</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static RescaleSlope: number = 2625619;
/// <summary>
/// <para>(0028,1054) Rescale Type</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static RescaleType: number = 2625620;
/// <summary>
/// <para>(0028,1055) Window Center & Width Explanation</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static WindowCenterWidthExplanation: number = 2625621;
/// <summary>
/// <para>(0028,1056) VOI LUT Function</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static VoiLutFunction: number = 2625622;
/// <summary>
/// <para>(0028,1080) Gray Scale</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static GrayScaleRetired: number = 2625664;
/// <summary>
/// <para>(0028,1090) Recommended Viewing Mode</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RecommendedViewingMode: number = 2625680;
/// <summary>
/// <para>(0028,1100) Gray Lookup Table Descriptor</para>
/// <para> VR: US or SS VM:3</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static GrayLookupTableDescriptorRetired: number = 2625792;
/// <summary>
/// <para>(0028,1101) Red Palette Color Lookup Table Descriptor</para>
/// <para> VR: US or SS VM:3</para>
/// </summary>
public static RedPaletteColorLookupTableDescriptor: number = 2625793;
/// <summary>
/// <para>(0028,1102) Green Palette Color Lookup Table Descriptor</para>
/// <para> VR: US or SS VM:3</para>
/// </summary>
public static GreenPaletteColorLookupTableDescriptor: number = 2625794;
/// <summary>
/// <para>(0028,1103) Blue Palette Color Lookup Table Descriptor</para>
/// <para> VR: US or SS VM:3</para>
/// </summary>
public static BluePaletteColorLookupTableDescriptor: number = 2625795;
/// <summary>
/// <para>(0028,1104) Alpha Palette Color Lookup Table Descriptor</para>
/// <para> VR: US VM:3</para>
/// </summary>
public static AlphaPaletteColorLookupTableDescriptor: number = 2625796;
/// <summary>
/// <para>(0028,1111) Large Red Palette Color Lookup Table Descriptor</para>
/// <para> VR: US or SS VM:4</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static LargeRedPaletteColorLookupTableDescriptorRetired: number = 2625809;
/// <summary>
/// <para>(0028,1112) Large Green Palette Color Lookup Table Descriptor</para>
/// <para> VR: US or SS VM:4</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static LargeGreenPaletteColorLookupTableDescriptorRetired: number = 2625810;
/// <summary>
/// <para>(0028,1113) Large Blue Palette Color Lookup Table Descriptor</para>
/// <para> VR: US or SS VM:4</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static LargeBluePaletteColorLookupTableDescriptorRetired: number = 2625811;
/// <summary>
/// <para>(0028,1199) Palette Color Lookup Table UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static PaletteColorLookupTableUid: number = 2625945;
/// <summary>
/// <para>(0028,1200) Gray Lookup Table Data</para>
/// <para> VR: US or SSor OW VM:1-n1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static GrayLookupTableDataRetired: number = 2626048;
/// <summary>
/// <para>(0028,1201) Red Palette Color Lookup Table Data</para>
/// <para> VR: OW VM:1</para>
/// </summary>
public static RedPaletteColorLookupTableData: number = 2626049;
/// <summary>
/// <para>(0028,1202) Green Palette Color Lookup Table Data</para>
/// <para> VR: OW VM:1</para>
/// </summary>
public static GreenPaletteColorLookupTableData: number = 2626050;
/// <summary>
/// <para>(0028,1203) Blue Palette Color Lookup Table Data</para>
/// <para> VR: OW VM:1</para>
/// </summary>
public static BluePaletteColorLookupTableData: number = 2626051;
/// <summary>
/// <para>(0028,1204) Alpha Palette Color Lookup Table Data</para>
/// <para> VR: OW VM:1</para>
/// </summary>
public static AlphaPaletteColorLookupTableData: number = 2626052;
/// <summary>
/// <para>(0028,1211) Large Red Palette Color Lookup Table Data</para>
/// <para> VR: OW VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static LargeRedPaletteColorLookupTableDataRetired: number = 2626065;
/// <summary>
/// <para>(0028,1212) Large Green Palette Color Lookup Table Data</para>
/// <para> VR: OW VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static LargeGreenPaletteColorLookupTableDataRetired: number = 2626066;
/// <summary>
/// <para>(0028,1213) Large Blue Palette Color Lookup Table Data</para>
/// <para> VR: OW VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static LargeBluePaletteColorLookupTableDataRetired: number = 2626067;
/// <summary>
/// <para>(0028,1214) Large Palette Color Lookup Table UID</para>
/// <para> VR: UI VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static LargePaletteColorLookupTableUidRetired: number = 2626068;
/// <summary>
/// <para>(0028,1221) Segmented Red Palette Color Lookup Table Data</para>
/// <para> VR: OW VM:1</para>
/// </summary>
public static SegmentedRedPaletteColorLookupTableData: number = 2626081;
/// <summary>
/// <para>(0028,1222) Segmented Green Palette Color Lookup Table Data</para>
/// <para> VR: OW VM:1</para>
/// </summary>
public static SegmentedGreenPaletteColorLookupTableData: number = 2626082;
/// <summary>
/// <para>(0028,1223) Segmented Blue Palette Color Lookup Table Data</para>
/// <para> VR: OW VM:1</para>
/// </summary>
public static SegmentedBluePaletteColorLookupTableData: number = 2626083;
/// <summary>
/// <para>(0028,1300) Breast Implant Present</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BreastImplantPresent: number = 2626304;
/// <summary>
/// <para>(0028,1350) Partial View</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PartialView: number = 2626384;
/// <summary>
/// <para>(0028,1351) Partial View Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static PartialViewDescription: number = 2626385;
/// <summary>
/// <para>(0028,1352) Partial View Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PartialViewCodeSequence: number = 2626386;
/// <summary>
/// <para>(0028,135A) Spatial Locations Preserved</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SpatialLocationsPreserved: number = 2626394;
/// <summary>
/// <para>(0028,1401) Data Frame Assignment Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DataFrameAssignmentSequence: number = 2626561;
/// <summary>
/// <para>(0028,1402) Data Path Assignment</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DataPathAssignment: number = 2626562;
/// <summary>
/// <para>(0028,1403) Bits Mapped to Color Lookup Table</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static BitsMappedToColorLookupTable: number = 2626563;
/// <summary>
/// <para>(0028,1404) Blending LUT 1 Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BlendingLut1Sequence: number = 2626564;
/// <summary>
/// <para>(0028,1405) Blending LUT 1 Transfer Function</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BlendingLut1TransferFunction: number = 2626565;
/// <summary>
/// <para>(0028,1406) Blending Weight Constant</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static BlendingWeightConstant: number = 2626566;
/// <summary>
/// <para>(0028,1407) Blending Lookup Table Descriptor</para>
/// <para> VR: US VM:3</para>
/// </summary>
public static BlendingLookupTableDescriptor: number = 2626567;
/// <summary>
/// <para>(0028,1408) Blending Lookup Table Data</para>
/// <para> VR: OW VM:1</para>
/// </summary>
public static BlendingLookupTableData: number = 2626568;
/// <summary>
/// <para>(0028,140B) Enhanced Palette Color Lookup Table Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static EnhancedPaletteColorLookupTableSequence: number = 2626571;
/// <summary>
/// <para>(0028,140C) Blending LUT 2 Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BlendingLut2Sequence: number = 2626572;
/// <summary>
/// <para>(0028,140D) Blending LUT 2 Transfer Function</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BlendingLut2TransferFunction: number = 2626573;
/// <summary>
/// <para>(0028,140E) Data Path ID</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DataPathId: number = 2626574;
/// <summary>
/// <para>(0028,140F) RGB LUT Transfer Function</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RgbLutTransferFunction: number = 2626575;
/// <summary>
/// <para>(0028,1410) Alpha LUT Transfer Function</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AlphaLutTransferFunction: number = 2626576;
/// <summary>
/// <para>(0028,2000) ICC Profile</para>
/// <para> VR: OB VM:1</para>
/// </summary>
public static IccProfile: number = 2629632;
/// <summary>
/// <para>(0028,2110) Lossy Image Compression</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static LossyImageCompression: number = 2629904;
/// <summary>
/// <para>(0028,2112) Lossy Image Compression Ratio</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static LossyImageCompressionRatio: number = 2629906;
/// <summary>
/// <para>(0028,2114) Lossy Image Compression Method</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static LossyImageCompressionMethod: number = 2629908;
/// <summary>
/// <para>(0028,3000) Modality LUT Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ModalityLutSequence: number = 2633728;
/// <summary>
/// <para>(0028,3002) LUT Descriptor</para>
/// <para> VR: US or SS VM:3</para>
/// </summary>
public static LutDescriptor: number = 2633730;
/// <summary>
/// <para>(0028,3003) LUT Explanation</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static LutExplanation: number = 2633731;
/// <summary>
/// <para>(0028,3004) Modality LUT Type</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ModalityLutType: number = 2633732;
/// <summary>
/// <para>(0028,3006) LUT Data</para>
/// <para> VR: US or OW VM:1-n1</para>
/// </summary>
public static LutData: number = 2633734;
/// <summary>
/// <para>(0028,3010) VOI LUT Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static VoiLutSequence: number = 2633744;
/// <summary>
/// <para>(0028,3110) Softcopy VOI LUT Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SoftcopyVoiLutSequence: number = 2634000;
/// <summary>
/// <para>(0028,4000) Image Presentation Comments</para>
/// <para> VR: LT VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ImagePresentationCommentsRetired: number = 2637824;
/// <summary>
/// <para>(0028,5000) Bi-Plane Acquisition Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static BiPlaneAcquisitionSequenceRetired: number = 2641920;
/// <summary>
/// <para>(0028,6010) Representative Frame Number</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static RepresentativeFrameNumber: number = 2646032;
/// <summary>
/// <para>(0028,6020) Frame Numbers of Interest (FOI) </para>
/// <para> VR: US VM:1-n</para>
/// </summary>
public static FrameNumbersOfInterestFoi: number = 2646048;
/// <summary>
/// <para>(0028,6022) Frame of Interest Description</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static FrameOfInterestDescription: number = 2646050;
/// <summary>
/// <para>(0028,6023) Frame of Interest Type</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static FrameOfInterestType: number = 2646051;
/// <summary>
/// <para>(0028,6030) Mask Pointer(s)</para>
/// <para> VR: US VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static MaskPointersRetired: number = 2646064;
/// <summary>
/// <para>(0028,6040) R Wave Pointer</para>
/// <para> VR: US VM:1-n</para>
/// </summary>
public static RWavePointer: number = 2646080;
/// <summary>
/// <para>(0028,6100) Mask Subtraction Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MaskSubtractionSequence: number = 2646272;
/// <summary>
/// <para>(0028,6101) Mask Operation</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static MaskOperation: number = 2646273;
/// <summary>
/// <para>(0028,6102) Applicable Frame Range</para>
/// <para> VR: US VM:2-2n</para>
/// </summary>
public static ApplicableFrameRange: number = 2646274;
/// <summary>
/// <para>(0028,6110) Mask Frame Numbers</para>
/// <para> VR: US VM:1-n</para>
/// </summary>
public static MaskFrameNumbers: number = 2646288;
/// <summary>
/// <para>(0028,6112) Contrast Frame Averaging</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ContrastFrameAveraging: number = 2646290;
/// <summary>
/// <para>(0028,6114) Mask Sub-pixel Shift</para>
/// <para> VR: FL VM:2</para>
/// </summary>
public static MaskSubPixelShift: number = 2646292;
/// <summary>
/// <para>(0028,6120) TID Offset</para>
/// <para> VR: SS VM:1</para>
/// </summary>
public static TidOffset: number = 2646304;
/// <summary>
/// <para>(0028,6190) Mask Operation Explanation</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static MaskOperationExplanation: number = 2646416;
/// <summary>
/// <para>(0028,7FE0) Pixel Data Provider URL</para>
/// <para> VR: UT VM:1</para>
/// </summary>
public static PixelDataProviderUrl: number = 2654176;
/// <summary>
/// <para>(0028,9001) Data Point Rows</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static DataPointRows: number = 2658305;
/// <summary>
/// <para>(0028,9002) Data Point Columns</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static DataPointColumns: number = 2658306;
/// <summary>
/// <para>(0028,9003) Signal Domain Columns</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SignalDomainColumns: number = 2658307;
/// <summary>
/// <para>(0028,9099) Largest Monochrome Pixel Value</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static LargestMonochromePixelValueRetired: number = 2658457;
/// <summary>
/// <para>(0028,9108) Data Representation</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DataRepresentation: number = 2658568;
/// <summary>
/// <para>(0028,9110) Pixel Measures Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PixelMeasuresSequence: number = 2658576;
/// <summary>
/// <para>(0028,9132) Frame VOI LUT Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FrameVoiLutSequence: number = 2658610;
/// <summary>
/// <para>(0028,9145) Pixel Value Transformation Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PixelValueTransformationSequence: number = 2658629;
/// <summary>
/// <para>(0028,9235) Signal Domain Rows</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SignalDomainRows: number = 2658869;
/// <summary>
/// <para>(0028,9411) Display Filter Percentage</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static DisplayFilterPercentage: number = 2659345;
/// <summary>
/// <para>(0028,9415) Frame Pixel Shift Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FramePixelShiftSequence: number = 2659349;
/// <summary>
/// <para>(0028,9416) Subtraction Item ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static SubtractionItemId: number = 2659350;
/// <summary>
/// <para>(0028,9422) Pixel Intensity Relationship LUT Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PixelIntensityRelationshipLutSequence: number = 2659362;
/// <summary>
/// <para>(0028,9443) Frame Pixel Data Properties Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FramePixelDataPropertiesSequence: number = 2659395;
/// <summary>
/// <para>(0028,9444) Geometrical Properties</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static GeometricalProperties: number = 2659396;
/// <summary>
/// <para>(0028,9445) Geometric Maximum Distortion</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static GeometricMaximumDistortion: number = 2659397;
/// <summary>
/// <para>(0028,9446) Image Processing Applied</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static ImageProcessingApplied: number = 2659398;
/// <summary>
/// <para>(0028,9454) Mask Selection Mode</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static MaskSelectionMode: number = 2659412;
/// <summary>
/// <para>(0028,9474) LUT Function</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static LutFunction: number = 2659444;
/// <summary>
/// <para>(0028,9478) Mask Visibility Percentage</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static MaskVisibilityPercentage: number = 2659448;
/// <summary>
/// <para>(0028,9501) Pixel Shift Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PixelShiftSequence: number = 2659585;
/// <summary>
/// <para>(0028,9502) Region Pixel Shift Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RegionPixelShiftSequence: number = 2659586;
/// <summary>
/// <para>(0028,9503) Vertices of the Region</para>
/// <para> VR: SS VM:2-2n</para>
/// </summary>
public static VerticesOfTheRegion: number = 2659587;
/// <summary>
/// <para>(0028,9505) Multi-frame Presentation Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MultiFramePresentationSequence: number = 2659589;
/// <summary>
/// <para>(0028,9506) Pixel Shift Frame Range</para>
/// <para> VR: US VM:2-2n</para>
/// </summary>
public static PixelShiftFrameRange: number = 2659590;
/// <summary>
/// <para>(0028,9507) LUT Frame Range</para>
/// <para> VR: US VM:2-2n</para>
/// </summary>
public static LutFrameRange: number = 2659591;
/// <summary>
/// <para>(0028,9520) Image to Equipment Mapping Matrix</para>
/// <para> VR: DS VM:16</para>
/// </summary>
public static ImageToEquipmentMappingMatrix: number = 2659616;
/// <summary>
/// <para>(0028,9537) Equipment Coordinate System Identification</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static EquipmentCoordinateSystemIdentification: number = 2659639;
/// <summary>
/// <para>(0032,000A) Study Status ID</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static StudyStatusIdRetired: number = 3276810;
/// <summary>
/// <para>(0032,000C) Study Priority ID</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static StudyPriorityIdRetired: number = 3276812;
/// <summary>
/// <para>(0032,0012) Study ID Issuer</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static StudyIdIssuerRetired: number = 3276818;
/// <summary>
/// <para>(0032,0032) Study Verified Date</para>
/// <para> VR: DA VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static StudyVerifiedDateRetired: number = 3276850;
/// <summary>
/// <para>(0032,0033) Study Verified Time</para>
/// <para> VR: TM VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static StudyVerifiedTimeRetired: number = 3276851;
/// <summary>
/// <para>(0032,0034) Study Read Date</para>
/// <para> VR: DA VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static StudyReadDateRetired: number = 3276852;
/// <summary>
/// <para>(0032,0035) Study Read Time</para>
/// <para> VR: TM VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static StudyReadTimeRetired: number = 3276853;
/// <summary>
/// <para>(0032,1000) Scheduled Study Start Date</para>
/// <para> VR: DA VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ScheduledStudyStartDateRetired: number = 3280896;
/// <summary>
/// <para>(0032,1001) Scheduled Study Start Time</para>
/// <para> VR: TM VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ScheduledStudyStartTimeRetired: number = 3280897;
/// <summary>
/// <para>(0032,1010) Scheduled Study Stop Date</para>
/// <para> VR: DA VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ScheduledStudyStopDateRetired: number = 3280912;
/// <summary>
/// <para>(0032,1011) Scheduled Study Stop Time</para>
/// <para> VR: TM VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ScheduledStudyStopTimeRetired: number = 3280913;
/// <summary>
/// <para>(0032,1020) Scheduled Study Location</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ScheduledStudyLocationRetired: number = 3280928;
/// <summary>
/// <para>(0032,1021) Scheduled Study Location AE Title</para>
/// <para> VR: AE VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ScheduledStudyLocationAeTitleRetired: number = 3280929;
/// <summary>
/// <para>(0032,1030) Reason for Study</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReasonForStudyRetired: number = 3280944;
/// <summary>
/// <para>(0032,1031) Requesting Physician Identification Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RequestingPhysicianIdentificationSequence: number = 3280945;
/// <summary>
/// <para>(0032,1032) Requesting Physician</para>
/// <para> VR: PN VM:1</para>
/// </summary>
public static RequestingPhysician: number = 3280946;
/// <summary>
/// <para>(0032,1033) Requesting Service</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static RequestingService: number = 3280947;
/// <summary>
/// <para>(0032,1034) Requesting Service Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RequestingServiceCodeSequence: number = 3280948;
/// <summary>
/// <para>(0032,1040) Study Arrival Date</para>
/// <para> VR: DA VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static StudyArrivalDateRetired: number = 3280960;
/// <summary>
/// <para>(0032,1041) Study Arrival Time</para>
/// <para> VR: TM VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static StudyArrivalTimeRetired: number = 3280961;
/// <summary>
/// <para>(0032,1050) Study Completion Date</para>
/// <para> VR: DA VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static StudyCompletionDateRetired: number = 3280976;
/// <summary>
/// <para>(0032,1051) Study Completion Time</para>
/// <para> VR: TM VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static StudyCompletionTimeRetired: number = 3280977;
/// <summary>
/// <para>(0032,1055) Study Component Status ID</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static StudyComponentStatusIdRetired: number = 3280981;
/// <summary>
/// <para>(0032,1060) Requested Procedure Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static RequestedProcedureDescription: number = 3280992;
/// <summary>
/// <para>(0032,1064) Requested Procedure Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RequestedProcedureCodeSequence: number = 3280996;
/// <summary>
/// <para>(0032,1070) Requested Contrast Agent</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static RequestedContrastAgent: number = 3281008;
/// <summary>
/// <para>(0032,4000) Study Comments</para>
/// <para> VR: LT VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static StudyCommentsRetired: number = 3293184;
/// <summary>
/// <para>(0038,0004) Referenced Patient Alias Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedPatientAliasSequence: number = 3670020;
/// <summary>
/// <para>(0038,0008) Visit Status ID</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static VisitStatusId: number = 3670024;
/// <summary>
/// <para>(0038,0010) Admission ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static AdmissionId: number = 3670032;
/// <summary>
/// <para>(0038,0011) Issuer of Admission ID</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static IssuerOfAdmissionIdRetired: number = 3670033;
/// <summary>
/// <para>(0038,0014) Issuer of Admission ID Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IssuerOfAdmissionIdSequence: number = 3670036;
/// <summary>
/// <para>(0038,0016) Route of Admissions</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static RouteOfAdmissions: number = 3670038;
/// <summary>
/// <para>(0038,001A) Scheduled Admission Date</para>
/// <para> VR: DA VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ScheduledAdmissionDateRetired: number = 3670042;
/// <summary>
/// <para>(0038,001B) Scheduled Admission Time</para>
/// <para> VR: TM VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ScheduledAdmissionTimeRetired: number = 3670043;
/// <summary>
/// <para>(0038,001C) Scheduled Discharge Date</para>
/// <para> VR: DA VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ScheduledDischargeDateRetired: number = 3670044;
/// <summary>
/// <para>(0038,001D) Scheduled Discharge Time</para>
/// <para> VR: TM VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ScheduledDischargeTimeRetired: number = 3670045;
/// <summary>
/// <para>(0038,001E) Scheduled Patient Institution Residence</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ScheduledPatientInstitutionResidenceRetired: number = 3670046;
/// <summary>
/// <para>(0038,0020) Admitting Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static AdmittingDate: number = 3670048;
/// <summary>
/// <para>(0038,0021) Admitting Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static AdmittingTime: number = 3670049;
/// <summary>
/// <para>(0038,0030) Discharge Date</para>
/// <para> VR: DA VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DischargeDateRetired: number = 3670064;
/// <summary>
/// <para>(0038,0032) Discharge Time</para>
/// <para> VR: TM VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DischargeTimeRetired: number = 3670066;
/// <summary>
/// <para>(0038,0040) Discharge Diagnosis Description</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DischargeDiagnosisDescriptionRetired: number = 3670080;
/// <summary>
/// <para>(0038,0044) Discharge Diagnosis Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DischargeDiagnosisCodeSequenceRetired: number = 3670084;
/// <summary>
/// <para>(0038,0050) Special Needs</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SpecialNeeds: number = 3670096;
/// <summary>
/// <para>(0038,0060) Service Episode ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ServiceEpisodeId: number = 3670112;
/// <summary>
/// <para>(0038,0061) Issuer of Service Episode ID</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static IssuerOfServiceEpisodeIdRetired: number = 3670113;
/// <summary>
/// <para>(0038,0062) Service Episode Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ServiceEpisodeDescription: number = 3670114;
/// <summary>
/// <para>(0038,0064) Issuer of Service Episode ID Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IssuerOfServiceEpisodeIdSequence: number = 3670116;
/// <summary>
/// <para>(0038,0100) Pertinent Documents Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PertinentDocumentsSequence: number = 3670272;
/// <summary>
/// <para>(0038,0300) Current Patient Location</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static CurrentPatientLocation: number = 3670784;
/// <summary>
/// <para>(0038,0400) Patient's Institution Residence</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PatientsInstitutionResidence: number = 3671040;
/// <summary>
/// <para>(0038,0500) Patient State</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PatientState: number = 3671296;
/// <summary>
/// <para>(0038,0502) Patient Clinical Trial Participation Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PatientClinicalTrialParticipationSequence: number = 3671298;
/// <summary>
/// <para>(0038,4000) Visit Comments</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static VisitComments: number = 3686400;
/// <summary>
/// <para>(003A,0004) Waveform Originality</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static WaveformOriginality: number = 3801092;
/// <summary>
/// <para>(003A,0005) Number of Waveform Channels </para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfWaveformChannels: number = 3801093;
/// <summary>
/// <para>(003A,0010) Number of Waveform Samples </para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static NumberOfWaveformSamples: number = 3801104;
/// <summary>
/// <para>(003A,001A) Sampling Frequency </para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SamplingFrequency: number = 3801114;
/// <summary>
/// <para>(003A,0020) Multiplex Group Label </para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static MultiplexGroupLabel: number = 3801120;
/// <summary>
/// <para>(003A,0200) Channel Definition Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ChannelDefinitionSequence: number = 3801600;
/// <summary>
/// <para>(003A,0202) Waveform Channel Number </para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static WaveformChannelNumber: number = 3801602;
/// <summary>
/// <para>(003A,0203) Channel Label</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static ChannelLabel: number = 3801603;
/// <summary>
/// <para>(003A,0205) Channel Status</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static ChannelStatus: number = 3801605;
/// <summary>
/// <para>(003A,0208) Channel Source Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ChannelSourceSequence: number = 3801608;
/// <summary>
/// <para>(003A,0209) Channel Source Modifiers Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ChannelSourceModifiersSequence: number = 3801609;
/// <summary>
/// <para>(003A,020A) Source Waveform Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SourceWaveformSequence: number = 3801610;
/// <summary>
/// <para>(003A,020C) Channel Derivation Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ChannelDerivationDescription: number = 3801612;
/// <summary>
/// <para>(003A,0210) Channel Sensitivity </para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ChannelSensitivity: number = 3801616;
/// <summary>
/// <para>(003A,0211) Channel Sensitivity Units Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ChannelSensitivityUnitsSequence: number = 3801617;
/// <summary>
/// <para>(003A,0212) Channel Sensitivity Correction Factor</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ChannelSensitivityCorrectionFactor: number = 3801618;
/// <summary>
/// <para>(003A,0213) Channel Baseline </para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ChannelBaseline: number = 3801619;
/// <summary>
/// <para>(003A,0214) Channel Time Skew</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ChannelTimeSkew: number = 3801620;
/// <summary>
/// <para>(003A,0215) Channel Sample Skew</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ChannelSampleSkew: number = 3801621;
/// <summary>
/// <para>(003A,0218) Channel Offset</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ChannelOffset: number = 3801624;
/// <summary>
/// <para>(003A,021A) Waveform Bits Stored</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static WaveformBitsStored: number = 3801626;
/// <summary>
/// <para>(003A,0220) Filter Low Frequency</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static FilterLowFrequency: number = 3801632;
/// <summary>
/// <para>(003A,0221) Filter High Frequency</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static FilterHighFrequency: number = 3801633;
/// <summary>
/// <para>(003A,0222) Notch Filter Frequency</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static NotchFilterFrequency: number = 3801634;
/// <summary>
/// <para>(003A,0223) Notch Filter Bandwidth</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static NotchFilterBandwidth: number = 3801635;
/// <summary>
/// <para>(003A,0230) Waveform Data Display Scale</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static WaveformDataDisplayScale: number = 3801648;
/// <summary>
/// <para>(003A,0231) Waveform Display Background CIELab Value</para>
/// <para> VR: US VM:3</para>
/// </summary>
public static WaveformDisplayBackgroundCielabValue: number = 3801649;
/// <summary>
/// <para>(003A,0240) Waveform Presentation Group Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static WaveformPresentationGroupSequence: number = 3801664;
/// <summary>
/// <para>(003A,0241) Presentation Group Number</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static PresentationGroupNumber: number = 3801665;
/// <summary>
/// <para>(003A,0242) Channel Display Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ChannelDisplaySequence: number = 3801666;
/// <summary>
/// <para>(003A,0244) Channel Recommended Display CIELab Value</para>
/// <para> VR: US VM:3</para>
/// </summary>
public static ChannelRecommendedDisplayCielabValue: number = 3801668;
/// <summary>
/// <para>(003A,0245) Channel Position</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static ChannelPosition: number = 3801669;
/// <summary>
/// <para>(003A,0246) Display Shading Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DisplayShadingFlag: number = 3801670;
/// <summary>
/// <para>(003A,0247) Fractional Channel Display Scale</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static FractionalChannelDisplayScale: number = 3801671;
/// <summary>
/// <para>(003A,0248) Absolute Channel Display Scale</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static AbsoluteChannelDisplayScale: number = 3801672;
/// <summary>
/// <para>(003A,0300) Multiplexed Audio Channels Description Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MultiplexedAudioChannelsDescriptionCodeSequence: number = 3801856;
/// <summary>
/// <para>(003A,0301) Channel Identification Code</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ChannelIdentificationCode: number = 3801857;
/// <summary>
/// <para>(003A,0302) Channel Mode</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ChannelMode: number = 3801858;
/// <summary>
/// <para>(0040,0001) Scheduled Station AE Title</para>
/// <para> VR: AE VM:1-n</para>
/// </summary>
public static ScheduledStationAeTitle: number = 4194305;
/// <summary>
/// <para>(0040,0002) Scheduled Procedure Step Start Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static ScheduledProcedureStepStartDate: number = 4194306;
/// <summary>
/// <para>(0040,0003) Scheduled Procedure Step Start Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static ScheduledProcedureStepStartTime: number = 4194307;
/// <summary>
/// <para>(0040,0004) Scheduled Procedure Step End Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static ScheduledProcedureStepEndDate: number = 4194308;
/// <summary>
/// <para>(0040,0005) Scheduled Procedure Step End Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static ScheduledProcedureStepEndTime: number = 4194309;
/// <summary>
/// <para>(0040,0006) Scheduled Performing Physician's Name</para>
/// <para> VR: PN VM:1</para>
/// </summary>
public static ScheduledPerformingPhysiciansName: number = 4194310;
/// <summary>
/// <para>(0040,0007) Scheduled Procedure Step Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ScheduledProcedureStepDescription: number = 4194311;
/// <summary>
/// <para>(0040,0008) Scheduled Protocol Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ScheduledProtocolCodeSequence: number = 4194312;
/// <summary>
/// <para>(0040,0009) Scheduled Procedure Step ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static ScheduledProcedureStepId: number = 4194313;
/// <summary>
/// <para>(0040,000A) Stage Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static StageCodeSequence: number = 4194314;
/// <summary>
/// <para>(0040,000B) Scheduled Performing Physician Identification Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ScheduledPerformingPhysicianIdentificationSequence: number = 4194315;
/// <summary>
/// <para>(0040,0010) Scheduled Station Name</para>
/// <para> VR: SH VM:1-n</para>
/// </summary>
public static ScheduledStationName: number = 4194320;
/// <summary>
/// <para>(0040,0011) Scheduled Procedure Step Location</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static ScheduledProcedureStepLocation: number = 4194321;
/// <summary>
/// <para>(0040,0012) Pre-Medication</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PreMedication: number = 4194322;
/// <summary>
/// <para>(0040,0020) Scheduled Procedure Step Status</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ScheduledProcedureStepStatus: number = 4194336;
/// <summary>
/// <para>(0040,0026) Order Placer Identifier Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OrderPlacerIdentifierSequence: number = 4194342;
/// <summary>
/// <para>(0040,0027) Order Filler Identifier Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OrderFillerIdentifierSequence: number = 4194343;
/// <summary>
/// <para>(0040,0031) Local Namespace Entity ID</para>
/// <para> VR: UT VM:1</para>
/// </summary>
public static LocalNamespaceEntityId: number = 4194353;
/// <summary>
/// <para>(0040,0032) Universal Entity ID</para>
/// <para> VR: UT VM:1</para>
/// </summary>
public static UniversalEntityId: number = 4194354;
/// <summary>
/// <para>(0040,0033) Universal Entity ID Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static UniversalEntityIdType: number = 4194355;
/// <summary>
/// <para>(0040,0035) Identifier Type Code</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static IdentifierTypeCode: number = 4194357;
/// <summary>
/// <para>(0040,0036) Assigning Facility Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AssigningFacilitySequence: number = 4194358;
/// <summary>
/// <para>(0040,0039) Assigning Jurisdiction Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AssigningJurisdictionCodeSequence: number = 4194361;
/// <summary>
/// <para>(0040,003A) Assigning Agency or Department Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AssigningAgencyOrDepartmentCodeSequence: number = 4194362;
/// <summary>
/// <para>(0040,0100) Scheduled Procedure Step Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ScheduledProcedureStepSequence: number = 4194560;
/// <summary>
/// <para>(0040,0220) Referenced Non-Image Composite SOP Instance Sequence </para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedNonImageCompositeSopInstanceSequence: number = 4194848;
/// <summary>
/// <para>(0040,0241) Performed Station AE Title</para>
/// <para> VR: AE VM:1</para>
/// </summary>
public static PerformedStationAeTitle: number = 4194881;
/// <summary>
/// <para>(0040,0242) Performed Station Name</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static PerformedStationName: number = 4194882;
/// <summary>
/// <para>(0040,0243) Performed Location</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static PerformedLocation: number = 4194883;
/// <summary>
/// <para>(0040,0244) Performed Procedure Step Start Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static PerformedProcedureStepStartDate: number = 4194884;
/// <summary>
/// <para>(0040,0245) Performed Procedure Step Start Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static PerformedProcedureStepStartTime: number = 4194885;
/// <summary>
/// <para>(0040,0250) Performed Procedure Step End Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static PerformedProcedureStepEndDate: number = 4194896;
/// <summary>
/// <para>(0040,0251) Performed Procedure Step End Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static PerformedProcedureStepEndTime: number = 4194897;
/// <summary>
/// <para>(0040,0252) Performed Procedure Step Status</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PerformedProcedureStepStatus: number = 4194898;
/// <summary>
/// <para>(0040,0253) Performed Procedure Step ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static PerformedProcedureStepId: number = 4194899;
/// <summary>
/// <para>(0040,0254) Performed Procedure Step Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PerformedProcedureStepDescription: number = 4194900;
/// <summary>
/// <para>(0040,0255) Performed Procedure Type Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PerformedProcedureTypeDescription: number = 4194901;
/// <summary>
/// <para>(0040,0260) Performed Protocol Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PerformedProtocolCodeSequence: number = 4194912;
/// <summary>
/// <para>(0040,0261) Performed Protocol Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PerformedProtocolType: number = 4194913;
/// <summary>
/// <para>(0040,0270) Scheduled Step Attributes Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ScheduledStepAttributesSequence: number = 4194928;
/// <summary>
/// <para>(0040,0275) Request Attributes Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RequestAttributesSequence: number = 4194933;
/// <summary>
/// <para>(0040,0280) Comments on the Performed Procedure Step</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static CommentsOnThePerformedProcedureStep: number = 4194944;
/// <summary>
/// <para>(0040,0281) Performed Procedure Step Discontinuation Reason Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PerformedProcedureStepDiscontinuationReasonCodeSequence: number = 4194945;
/// <summary>
/// <para>(0040,0293) Quantity Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static QuantitySequence: number = 4194963;
/// <summary>
/// <para>(0040,0294) Quantity</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static Quantity: number = 4194964;
/// <summary>
/// <para>(0040,0295) Measuring Units Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MeasuringUnitsSequence: number = 4194965;
/// <summary>
/// <para>(0040,0296) Billing Item Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BillingItemSequence: number = 4194966;
/// <summary>
/// <para>(0040,0300) Total Time of Fluoroscopy</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static TotalTimeOfFluoroscopy: number = 4195072;
/// <summary>
/// <para>(0040,0301) Total Number of Exposures</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static TotalNumberOfExposures: number = 4195073;
/// <summary>
/// <para>(0040,0302) Entrance Dose</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static EntranceDose: number = 4195074;
/// <summary>
/// <para>(0040,0303) Exposed Area</para>
/// <para> VR: US VM:1-2</para>
/// </summary>
public static ExposedArea: number = 4195075;
/// <summary>
/// <para>(0040,0306) Distance Source to Entrance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DistanceSourceToEntrance: number = 4195078;
/// <summary>
/// <para>(0040,0307) Distance Source to Support</para>
/// <para> VR: DS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DistanceSourceToSupportRetired: number = 4195079;
/// <summary>
/// <para>(0040,030E) Exposure Dose Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ExposureDoseSequence: number = 4195086;
/// <summary>
/// <para>(0040,0310) Comments on Radiation Dose</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static CommentsOnRadiationDose: number = 4195088;
/// <summary>
/// <para>(0040,0312) X-Ray Output</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static XRayOutput: number = 4195090;
/// <summary>
/// <para>(0040,0314) Half Value Layer</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static HalfValueLayer: number = 4195092;
/// <summary>
/// <para>(0040,0316) Organ Dose</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static OrganDose: number = 4195094;
/// <summary>
/// <para>(0040,0318) Organ Exposed</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static OrganExposed: number = 4195096;
/// <summary>
/// <para>(0040,0320) Billing Procedure Step Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BillingProcedureStepSequence: number = 4195104;
/// <summary>
/// <para>(0040,0321) Film Consumption Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FilmConsumptionSequence: number = 4195105;
/// <summary>
/// <para>(0040,0324) Billing Supplies and Devices Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BillingSuppliesAndDevicesSequence: number = 4195108;
/// <summary>
/// <para>(0040,0330) Referenced Procedure Step Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferencedProcedureStepSequenceRetired: number = 4195120;
/// <summary>
/// <para>(0040,0340) Performed Series Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PerformedSeriesSequence: number = 4195136;
/// <summary>
/// <para>(0040,0400) Comments on the Scheduled Procedure Step</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static CommentsOnTheScheduledProcedureStep: number = 4195328;
/// <summary>
/// <para>(0040,0440) Protocol Context Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ProtocolContextSequence: number = 4195392;
/// <summary>
/// <para>(0040,0441) Content Item Modifier Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ContentItemModifierSequence: number = 4195393;
/// <summary>
/// <para>(0040,0500) Scheduled Specimen Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ScheduledSpecimenSequence: number = 4195584;
/// <summary>
/// <para>(0040,050A) Specimen Accession Number</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static SpecimenAccessionNumberRetired: number = 4195594;
/// <summary>
/// <para>(0040,0512) Container Identifier</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ContainerIdentifier: number = 4195602;
/// <summary>
/// <para>(0040,0513) Issuer of the Container Identifier Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IssuerOfTheContainerIdentifierSequence: number = 4195603;
/// <summary>
/// <para>(0040,0515) Alternate Container Identifier Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AlternateContainerIdentifierSequence: number = 4195605;
/// <summary>
/// <para>(0040,0518) Container Type Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ContainerTypeCodeSequence: number = 4195608;
/// <summary>
/// <para>(0040,051A) Container Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ContainerDescription: number = 4195610;
/// <summary>
/// <para>(0040,0520) Container Component Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ContainerComponentSequence: number = 4195616;
/// <summary>
/// <para>(0040,0550) Specimen Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static SpecimenSequenceRetired: number = 4195664;
/// <summary>
/// <para>(0040,0551) Specimen Identifier</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SpecimenIdentifier: number = 4195665;
/// <summary>
/// <para>(0040,0552) Specimen Description Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static SpecimenDescriptionSequenceTrialRetired: number = 4195666;
/// <summary>
/// <para>(0040,0553) Specimen Description (Trial)</para>
/// <para> VR: ST VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static SpecimenDescriptionTrialRetired: number = 4195667;
/// <summary>
/// <para>(0040,0554) Specimen UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static SpecimenUid: number = 4195668;
/// <summary>
/// <para>(0040,0555) Acquisition Context Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AcquisitionContextSequence: number = 4195669;
/// <summary>
/// <para>(0040,0556) Acquisition Context Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static AcquisitionContextDescription: number = 4195670;
/// <summary>
/// <para>(0040,0560) Specimen Description Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SpecimenDescriptionSequence: number = 4195680;
/// <summary>
/// <para>(0040,0562) Issuer of the Specimen Identifier Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IssuerOfTheSpecimenIdentifierSequence: number = 4195682;
/// <summary>
/// <para>(0040,059A) Specimen Type Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SpecimenTypeCodeSequence: number = 4195738;
/// <summary>
/// <para>(0040,0600) Specimen Short Description </para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SpecimenShortDescription: number = 4195840;
/// <summary>
/// <para>(0040,0602) Specimen Detailed Description </para>
/// <para> VR: UT VM:1</para>
/// </summary>
public static SpecimenDetailedDescription: number = 4195842;
/// <summary>
/// <para>(0040,0610) Specimen Preparation Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SpecimenPreparationSequence: number = 4195856;
/// <summary>
/// <para>(0040,0612) Specimen Preparation Step Content Item Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SpecimenPreparationStepContentItemSequence: number = 4195858;
/// <summary>
/// <para>(0040,0620) Specimen Localization Content Item Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SpecimenLocalizationContentItemSequence: number = 4195872;
/// <summary>
/// <para>(0040,06FA) Slide Identifier</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static SlideIdentifierRetired: number = 4196090;
/// <summary>
/// <para>(0040,071A) Image Center Point Coordinates Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ImageCenterPointCoordinatesSequence: number = 4196122;
/// <summary>
/// <para>(0040,072A) X Offset in Slide Coordinate System</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static XOffsetInSlideCoordinateSystem: number = 4196138;
/// <summary>
/// <para>(0040,073A) Y Offset in Slide Coordinate System</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static YOffsetInSlideCoordinateSystem: number = 4196154;
/// <summary>
/// <para>(0040,074A) Z Offset in Slide Coordinate System</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ZOffsetInSlideCoordinateSystem: number = 4196170;
/// <summary>
/// <para>(0040,08D8) Pixel Spacing Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PixelSpacingSequenceRetired: number = 4196568;
/// <summary>
/// <para>(0040,08DA) Coordinate System Axis Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CoordinateSystemAxisCodeSequenceRetired: number = 4196570;
/// <summary>
/// <para>(0040,08EA) Measurement Units Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MeasurementUnitsCodeSequence: number = 4196586;
/// <summary>
/// <para>(0040,09F8) Vital Stain Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static VitalStainCodeSequenceTrialRetired: number = 4196856;
/// <summary>
/// <para>(0040,1001) Requested Procedure ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static RequestedProcedureId: number = 4198401;
/// <summary>
/// <para>(0040,1002) Reason for the Requested Procedure</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ReasonForTheRequestedProcedure: number = 4198402;
/// <summary>
/// <para>(0040,1003) Requested Procedure Priority </para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static RequestedProcedurePriority: number = 4198403;
/// <summary>
/// <para>(0040,1004) Patient Transport Arrangements</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PatientTransportArrangements: number = 4198404;
/// <summary>
/// <para>(0040,1005) Requested Procedure Location</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static RequestedProcedureLocation: number = 4198405;
/// <summary>
/// <para>(0040,1006) Placer Order Number / Procedure</para>
/// <para> VR: SH VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PlacerOrderNumberProcedureRetired: number = 4198406;
/// <summary>
/// <para>(0040,1007) Filler Order Number / Procedure</para>
/// <para> VR: SH VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static FillerOrderNumberProcedureRetired: number = 4198407;
/// <summary>
/// <para>(0040,1008) Confidentiality Code</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ConfidentialityCode: number = 4198408;
/// <summary>
/// <para>(0040,1009) Reporting Priority</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static ReportingPriority: number = 4198409;
/// <summary>
/// <para>(0040,100A) Reason for Requested Procedure Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReasonForRequestedProcedureCodeSequence: number = 4198410;
/// <summary>
/// <para>(0040,1010) Names of Intended Recipients of Results</para>
/// <para> VR: PN VM:1-n</para>
/// </summary>
public static NamesOfIntendedRecipientsOfResults: number = 4198416;
/// <summary>
/// <para>(0040,1011) Intended Recipients of Results Identification Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IntendedRecipientsOfResultsIdentificationSequence: number = 4198417;
/// <summary>
/// <para>(0040,1012) Reason For Performed Procedure Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReasonForPerformedProcedureCodeSequence: number = 4198418;
/// <summary>
/// <para>(0040,1060) Requested Procedure Description (Trial)</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static RequestedProcedureDescriptionTrialRetired: number = 4198496;
/// <summary>
/// <para>(0040,1101) Person Identification Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PersonIdentificationCodeSequence: number = 4198657;
/// <summary>
/// <para>(0040,1102) Person's Address</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static PersonsAddress: number = 4198658;
/// <summary>
/// <para>(0040,1103) Person's Telephone Numbers</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static PersonsTelephoneNumbers: number = 4198659;
/// <summary>
/// <para>(0040,1400) Requested Procedure Comments</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static RequestedProcedureComments: number = 4199424;
/// <summary>
/// <para>(0040,2001) Reason for the Imaging Service Request</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReasonForTheImagingServiceRequestRetired: number = 4202497;
/// <summary>
/// <para>(0040,2004) Issue Date of Imaging Service Request</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static IssueDateOfImagingServiceRequest: number = 4202500;
/// <summary>
/// <para>(0040,2005) Issue Time of Imaging Service Request</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static IssueTimeOfImagingServiceRequest: number = 4202501;
/// <summary>
/// <para>(0040,2006) Placer Order Number / Imaging Service Request (Retired)</para>
/// <para> VR: SH VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PlacerOrderNumberImagingServiceRequestRetired: number = 4202502;
/// <summary>
/// <para>(0040,2007) Filler Order Number / Imaging Service Request (Retired)</para>
/// <para> VR: SH VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static FillerOrderNumberImagingServiceRequestRetired: number = 4202503;
/// <summary>
/// <para>(0040,2008) Order Entered By</para>
/// <para> VR: PN VM:1</para>
/// </summary>
public static OrderEnteredBy: number = 4202504;
/// <summary>
/// <para>(0040,2009) Order Enterer's Location</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static OrderEnterersLocation: number = 4202505;
/// <summary>
/// <para>(0040,2010) Order Callback Phone Number</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static OrderCallbackPhoneNumber: number = 4202512;
/// <summary>
/// <para>(0040,2016) Placer Order Number / Imaging Service Request</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PlacerOrderNumberImagingServiceRequest: number = 4202518;
/// <summary>
/// <para>(0040,2017) Filler Order Number / Imaging Service Request</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static FillerOrderNumberImagingServiceRequest: number = 4202519;
/// <summary>
/// <para>(0040,2400) Imaging Service Request Comments</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static ImagingServiceRequestComments: number = 4203520;
/// <summary>
/// <para>(0040,3001) Confidentiality Constraint on Patient Data Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ConfidentialityConstraintOnPatientDataDescription: number = 4206593;
/// <summary>
/// <para>(0040,4001) General Purpose Scheduled Procedure Step Status</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static GeneralPurposeScheduledProcedureStepStatus: number = 4210689;
/// <summary>
/// <para>(0040,4002) General Purpose Performed Procedure Step Status</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static GeneralPurposePerformedProcedureStepStatus: number = 4210690;
/// <summary>
/// <para>(0040,4003) General Purpose Scheduled Procedure Step Priority</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static GeneralPurposeScheduledProcedureStepPriority: number = 4210691;
/// <summary>
/// <para>(0040,4004) Scheduled Processing Applications Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ScheduledProcessingApplicationsCodeSequence: number = 4210692;
/// <summary>
/// <para>(0040,4005) Scheduled Procedure Step Start DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static ScheduledProcedureStepStartDatetime: number = 4210693;
/// <summary>
/// <para>(0040,4006) Multiple Copies Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static MultipleCopiesFlag: number = 4210694;
/// <summary>
/// <para>(0040,4007) Performed Processing Applications Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PerformedProcessingApplicationsCodeSequence: number = 4210695;
/// <summary>
/// <para>(0040,4009) Human Performer Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static HumanPerformerCodeSequence: number = 4210697;
/// <summary>
/// <para>(0040,4010) Scheduled Procedure Step Modification Date Time</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static ScheduledProcedureStepModificationDateTime: number = 4210704;
/// <summary>
/// <para>(0040,4011) Expected Completion Date Time</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static ExpectedCompletionDateTime: number = 4210705;
/// <summary>
/// <para>(0040,4015) Resulting General Purpose Performed Procedure Steps Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ResultingGeneralPurposePerformedProcedureStepsSequence: number = 4210709;
/// <summary>
/// <para>(0040,4016) Referenced General Purpose Scheduled Procedure Step Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedGeneralPurposeScheduledProcedureStepSequence: number = 4210710;
/// <summary>
/// <para>(0040,4018) Scheduled Workitem Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ScheduledWorkitemCodeSequence: number = 4210712;
/// <summary>
/// <para>(0040,4019) Performed Workitem Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PerformedWorkitemCodeSequence: number = 4210713;
/// <summary>
/// <para>(0040,4020) Input Availability Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static InputAvailabilityFlag: number = 4210720;
/// <summary>
/// <para>(0040,4021) Input Information Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static InputInformationSequence: number = 4210721;
/// <summary>
/// <para>(0040,4022) Relevant Information Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RelevantInformationSequence: number = 4210722;
/// <summary>
/// <para>(0040,4023) Referenced General Purpose Scheduled Procedure Step Transaction UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static ReferencedGeneralPurposeScheduledProcedureStepTransactionUid: number = 4210723;
/// <summary>
/// <para>(0040,4025) Scheduled Station Name Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ScheduledStationNameCodeSequence: number = 4210725;
/// <summary>
/// <para>(0040,4026) Scheduled Station Class Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ScheduledStationClassCodeSequence: number = 4210726;
/// <summary>
/// <para>(0040,4027) Scheduled Station Geographic Location Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ScheduledStationGeographicLocationCodeSequence: number = 4210727;
/// <summary>
/// <para>(0040,4028) Performed Station Name Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PerformedStationNameCodeSequence: number = 4210728;
/// <summary>
/// <para>(0040,4029) Performed Station Class Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PerformedStationClassCodeSequence: number = 4210729;
/// <summary>
/// <para>(0040,4030) Performed Station Geographic Location Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PerformedStationGeographicLocationCodeSequence: number = 4210736;
/// <summary>
/// <para>(0040,4031) Requested Subsequent Workitem Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RequestedSubsequentWorkitemCodeSequence: number = 4210737;
/// <summary>
/// <para>(0040,4032) Non-DICOM Output Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static NonDicomOutputCodeSequence: number = 4210738;
/// <summary>
/// <para>(0040,4033) Output Information Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OutputInformationSequence: number = 4210739;
/// <summary>
/// <para>(0040,4034) Scheduled Human Performers Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ScheduledHumanPerformersSequence: number = 4210740;
/// <summary>
/// <para>(0040,4035) Actual Human Performers Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ActualHumanPerformersSequence: number = 4210741;
/// <summary>
/// <para>(0040,4036) Human Performer's Organization</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static HumanPerformersOrganization: number = 4210742;
/// <summary>
/// <para>(0040,4037) Human Performer's Name</para>
/// <para> VR: PN VM:1</para>
/// </summary>
public static HumanPerformersName: number = 4210743;
/// <summary>
/// <para>(0040,4040) Raw Data Handling</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RawDataHandling: number = 4210752;
/// <summary>
/// <para>(0040,4041) Input Readiness State</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static InputReadinessState: number = 4210753;
/// <summary>
/// <para>(0040,4050) Performed Procedure Step Start DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static PerformedProcedureStepStartDatetime: number = 4210768;
/// <summary>
/// <para>(0040,4051) Performed Procedure Step End DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static PerformedProcedureStepEndDatetime: number = 4210769;
/// <summary>
/// <para>(0040,4052) Procedure Step Cancellation DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static ProcedureStepCancellationDatetime: number = 4210770;
/// <summary>
/// <para>(0040,8302) Entrance Dose in mGy</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static EntranceDoseInMgy: number = 4227842;
/// <summary>
/// <para>(0040,9094) Referenced Image Real World Value Mapping Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedImageRealWorldValueMappingSequence: number = 4231316;
/// <summary>
/// <para>(0040,9096) Real World Value Mapping Sequence </para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RealWorldValueMappingSequence: number = 4231318;
/// <summary>
/// <para>(0040,9098) Pixel Value Mapping Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PixelValueMappingCodeSequence: number = 4231320;
/// <summary>
/// <para>(0040,9210) LUT Label</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static LutLabel: number = 4231696;
/// <summary>
/// <para>(0040,9211) Real World Value Last Value Mapped</para>
/// <para> VR: US or SS VM:1</para>
/// </summary>
public static RealWorldValueLastValueMapped: number = 4231697;
/// <summary>
/// <para>(0040,9212) Real World Value LUT Data</para>
/// <para> VR: FD VM:1-n</para>
/// </summary>
public static RealWorldValueLutData: number = 4231698;
/// <summary>
/// <para>(0040,9216) Real World Value First Value Mapped</para>
/// <para> VR: US or SS VM:1</para>
/// </summary>
public static RealWorldValueFirstValueMapped: number = 4231702;
/// <summary>
/// <para>(0040,9224) Real World Value Intercept</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static RealWorldValueIntercept: number = 4231716;
/// <summary>
/// <para>(0040,9225) Real World Value Slope</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static RealWorldValueSlope: number = 4231717;
/// <summary>
/// <para>(0040,A007) Findings Flag (Trial)</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static FindingsFlagTrialRetired: number = 4235271;
/// <summary>
/// <para>(0040,A010) Relationship Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RelationshipType: number = 4235280;
/// <summary>
/// <para>(0040,A020) Findings Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static FindingsSequenceTrialRetired: number = 4235296;
/// <summary>
/// <para>(0040,A021) Findings Group UID (Trial)</para>
/// <para> VR: UI VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static FindingsGroupUidTrialRetired: number = 4235297;
/// <summary>
/// <para>(0040,A022) Referenced Findings Group UID (Trial)</para>
/// <para> VR: UI VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferencedFindingsGroupUidTrialRetired: number = 4235298;
/// <summary>
/// <para>(0040,A023) Findings Group Recording Date (Trial)</para>
/// <para> VR: DA VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static FindingsGroupRecordingDateTrialRetired: number = 4235299;
/// <summary>
/// <para>(0040,A024) Findings Group Recording Time (Trial)</para>
/// <para> VR: TM VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static FindingsGroupRecordingTimeTrialRetired: number = 4235300;
/// <summary>
/// <para>(0040,A026) Findings Source Category Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static FindingsSourceCategoryCodeSequenceTrialRetired: number = 4235302;
/// <summary>
/// <para>(0040,A027) Verifying Organization</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static VerifyingOrganization: number = 4235303;
/// <summary>
/// <para>(0040,A028) Documenting Organization Identifier Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DocumentingOrganizationIdentifierCodeSequenceTrialRetired: number = 4235304;
/// <summary>
/// <para>(0040,A030) Verification Date Time</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static VerificationDateTime: number = 4235312;
/// <summary>
/// <para>(0040,A032) Observation Date Time</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static ObservationDateTime: number = 4235314;
/// <summary>
/// <para>(0040,A040) Value Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ValueType: number = 4235328;
/// <summary>
/// <para>(0040,A043) Concept Name Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ConceptNameCodeSequence: number = 4235331;
/// <summary>
/// <para>(0040,A047) Measurement Precision Description (Trial)</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static MeasurementPrecisionDescriptionTrialRetired: number = 4235335;
/// <summary>
/// <para>(0040,A050) Continuity Of Content</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ContinuityOfContent: number = 4235344;
/// <summary>
/// <para>(0040,A057) Urgency or Priority Alerts (Trial)</para>
/// <para> VR: CS VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static UrgencyOrPriorityAlertsTrialRetired: number = 4235351;
/// <summary>
/// <para>(0040,A060) Sequencing Indicator (Trial)</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static SequencingIndicatorTrialRetired: number = 4235360;
/// <summary>
/// <para>(0040,A066) Document Identifier Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DocumentIdentifierCodeSequenceTrialRetired: number = 4235366;
/// <summary>
/// <para>(0040,A067) Document Author (Trial)</para>
/// <para> VR: PN VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DocumentAuthorTrialRetired: number = 4235367;
/// <summary>
/// <para>(0040,A068) Document Author Identifier Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DocumentAuthorIdentifierCodeSequenceTrialRetired: number = 4235368;
/// <summary>
/// <para>(0040,A070) Identifier Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static IdentifierCodeSequenceTrialRetired: number = 4235376;
/// <summary>
/// <para>(0040,A073) Verifying Observer Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static VerifyingObserverSequence: number = 4235379;
/// <summary>
/// <para>(0040,A074) Object Binary Identifier (Trial)</para>
/// <para> VR: OB VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ObjectBinaryIdentifierTrialRetired: number = 4235380;
/// <summary>
/// <para>(0040,A075) Verifying Observer Name</para>
/// <para> VR: PN VM:1</para>
/// </summary>
public static VerifyingObserverName: number = 4235381;
/// <summary>
/// <para>(0040,A076) Documenting Observer Identifier Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DocumentingObserverIdentifierCodeSequenceTrialRetired: number = 4235382;
/// <summary>
/// <para>(0040,A078) Author Observer Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AuthorObserverSequence: number = 4235384;
/// <summary>
/// <para>(0040,A07A) Participant Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ParticipantSequence: number = 4235386;
/// <summary>
/// <para>(0040,A07C) Custodial Organization Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CustodialOrganizationSequence: number = 4235388;
/// <summary>
/// <para>(0040,A080) Participation Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ParticipationType: number = 4235392;
/// <summary>
/// <para>(0040,A082) Participation DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static ParticipationDatetime: number = 4235394;
/// <summary>
/// <para>(0040,A084) Observer Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ObserverType: number = 4235396;
/// <summary>
/// <para>(0040,A085) Procedure Identifier Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ProcedureIdentifierCodeSequenceTrialRetired: number = 4235397;
/// <summary>
/// <para>(0040,A088) Verifying Observer Identification Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static VerifyingObserverIdentificationCodeSequence: number = 4235400;
/// <summary>
/// <para>(0040,A089) Object Directory Binary Identifier (Trial)</para>
/// <para> VR: OB VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ObjectDirectoryBinaryIdentifierTrialRetired: number = 4235401;
/// <summary>
/// <para>(0040,A090) Equivalent CDA Document Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static EquivalentCdaDocumentSequenceRetired: number = 4235408;
/// <summary>
/// <para>(0040,A0B0) Referenced Waveform Channels</para>
/// <para> VR: US VM:2-2n</para>
/// </summary>
public static ReferencedWaveformChannels: number = 4235440;
/// <summary>
/// <para>(0040,A110) Date of Document or Verbal Transaction (Trial)</para>
/// <para> VR: DA VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DateOfDocumentOrVerbalTransactionTrialRetired: number = 4235536;
/// <summary>
/// <para>(0040,A112) Time of Document Creation or Verbal Transaction (Trial)</para>
/// <para> VR: TM VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TimeOfDocumentCreationOrVerbalTransactionTrialRetired: number = 4235538;
/// <summary>
/// <para>(0040,A120) DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static Datetime: number = 4235552;
/// <summary>
/// <para>(0040,A121) Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static Date: number = 4235553;
/// <summary>
/// <para>(0040,A122) Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static Time: number = 4235554;
/// <summary>
/// <para>(0040,A123) Person Name</para>
/// <para> VR: PN VM:1</para>
/// </summary>
public static PersonName: number = 4235555;
/// <summary>
/// <para>(0040,A124) UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static Uid: number = 4235556;
/// <summary>
/// <para>(0040,A125) Report Status ID (Trial)</para>
/// <para> VR: CS VM:2</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReportStatusIdTrialRetired: number = 4235557;
/// <summary>
/// <para>(0040,A130) Temporal Range Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TemporalRangeType: number = 4235568;
/// <summary>
/// <para>(0040,A132) Referenced Sample Positions</para>
/// <para> VR: UL VM:1-n</para>
/// </summary>
public static ReferencedSamplePositions: number = 4235570;
/// <summary>
/// <para>(0040,A136) Referenced Frame Numbers</para>
/// <para> VR: US VM:1-n</para>
/// </summary>
public static ReferencedFrameNumbers: number = 4235574;
/// <summary>
/// <para>(0040,A138) Referenced Time Offsets</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static ReferencedTimeOffsets: number = 4235576;
/// <summary>
/// <para>(0040,A13A) Referenced DateTime </para>
/// <para> VR: DT VM:1-n</para>
/// </summary>
public static ReferencedDatetime: number = 4235578;
/// <summary>
/// <para>(0040,A160) Text Value</para>
/// <para> VR: UT VM:1</para>
/// </summary>
public static TextValue: number = 4235616;
/// <summary>
/// <para>(0040,A167) Observation Category Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ObservationCategoryCodeSequenceTrialRetired: number = 4235623;
/// <summary>
/// <para>(0040,A168) Concept Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ConceptCodeSequence: number = 4235624;
/// <summary>
/// <para>(0040,A16A) Bibliographic Citation (Trial)</para>
/// <para> VR: ST VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static BibliographicCitationTrialRetired: number = 4235626;
/// <summary>
/// <para>(0040,A170) Purpose of Reference Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PurposeOfReferenceCodeSequence: number = 4235632;
/// <summary>
/// <para>(0040,A171) Observation UID (Trial)</para>
/// <para> VR: UI VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ObservationUidTrialRetired: number = 4235633;
/// <summary>
/// <para>(0040,A172) Referenced Observation UID (Trial)</para>
/// <para> VR: UI VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferencedObservationUidTrialRetired: number = 4235634;
/// <summary>
/// <para>(0040,A173) Referenced Observation Class (Trial)</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferencedObservationClassTrialRetired: number = 4235635;
/// <summary>
/// <para>(0040,A174) Referenced Object Observation Class (Trial)</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferencedObjectObservationClassTrialRetired: number = 4235636;
/// <summary>
/// <para>(0040,A180) Annotation Group Number</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static AnnotationGroupNumber: number = 4235648;
/// <summary>
/// <para>(0040,A192) Observation Date (Trial)</para>
/// <para> VR: DA VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ObservationDateTrialRetired: number = 4235666;
/// <summary>
/// <para>(0040,A193) Observation Time (Trial)</para>
/// <para> VR: TM VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ObservationTimeTrialRetired: number = 4235667;
/// <summary>
/// <para>(0040,A194) Measurement Automation (Trial)</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static MeasurementAutomationTrialRetired: number = 4235668;
/// <summary>
/// <para>(0040,A195) Modifier Code Sequence </para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ModifierCodeSequence: number = 4235669;
/// <summary>
/// <para>(0040,A224) Identification Description (Trial)</para>
/// <para> VR: ST VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static IdentificationDescriptionTrialRetired: number = 4235812;
/// <summary>
/// <para>(0040,A290) Coordinates Set Geometric Type (Trial)</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CoordinatesSetGeometricTypeTrialRetired: number = 4235920;
/// <summary>
/// <para>(0040,A296) Algorithm Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AlgorithmCodeSequenceTrialRetired: number = 4235926;
/// <summary>
/// <para>(0040,A297) Algorithm Description (Trial)</para>
/// <para> VR: ST VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AlgorithmDescriptionTrialRetired: number = 4235927;
/// <summary>
/// <para>(0040,A29A) Pixel Coordinates Set (Trial)</para>
/// <para> VR: SL VM:2-2n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PixelCoordinatesSetTrialRetired: number = 4235930;
/// <summary>
/// <para>(0040,A300) Measured Value Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MeasuredValueSequence: number = 4236032;
/// <summary>
/// <para>(0040,A301) Numeric Value Qualifier Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static NumericValueQualifierCodeSequence: number = 4236033;
/// <summary>
/// <para>(0040,A307) Current Observer (Trial)</para>
/// <para> VR: PN VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CurrentObserverTrialRetired: number = 4236039;
/// <summary>
/// <para>(0040,A30A) Numeric Value</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static NumericValue: number = 4236042;
/// <summary>
/// <para>(0040,A313) Referenced Accession Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferencedAccessionSequenceTrialRetired: number = 4236051;
/// <summary>
/// <para>(0040,A33A) Report Status Comment (Trial)</para>
/// <para> VR: ST VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReportStatusCommentTrialRetired: number = 4236090;
/// <summary>
/// <para>(0040,A340) Procedure Context Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ProcedureContextSequenceTrialRetired: number = 4236096;
/// <summary>
/// <para>(0040,A352) Verbal Source (Trial)</para>
/// <para> VR: PN VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static VerbalSourceTrialRetired: number = 4236114;
/// <summary>
/// <para>(0040,A353) Address (Trial)</para>
/// <para> VR: ST VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AddressTrialRetired: number = 4236115;
/// <summary>
/// <para>(0040,A354) Telephone Number (Trial)</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TelephoneNumberTrialRetired: number = 4236116;
/// <summary>
/// <para>(0040,A358) Verbal Source Identifier Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static VerbalSourceIdentifierCodeSequenceTrialRetired: number = 4236120;
/// <summary>
/// <para>(0040,A360) Predecessor Documents Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PredecessorDocumentsSequence: number = 4236128;
/// <summary>
/// <para>(0040,A370) Referenced Request Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedRequestSequence: number = 4236144;
/// <summary>
/// <para>(0040,A372) Performed Procedure Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PerformedProcedureCodeSequence: number = 4236146;
/// <summary>
/// <para>(0040,A375) Current Requested Procedure Evidence Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CurrentRequestedProcedureEvidenceSequence: number = 4236149;
/// <summary>
/// <para>(0040,A380) Report Detail Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReportDetailSequenceTrialRetired: number = 4236160;
/// <summary>
/// <para>(0040,A385) Pertinent Other Evidence Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PertinentOtherEvidenceSequence: number = 4236165;
/// <summary>
/// <para>(0040,A390) HL7 Structured Document Reference Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static Hl7StructuredDocumentReferenceSequence: number = 4236176;
/// <summary>
/// <para>(0040,A402) Observation Subject UID (Trial)</para>
/// <para> VR: UI VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ObservationSubjectUidTrialRetired: number = 4236290;
/// <summary>
/// <para>(0040,A403) Observation Subject Class (Trial)</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ObservationSubjectClassTrialRetired: number = 4236291;
/// <summary>
/// <para>(0040,A404) Observation Subject Type Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ObservationSubjectTypeCodeSequenceTrialRetired: number = 4236292;
/// <summary>
/// <para>(0040,A491) Completion Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CompletionFlag: number = 4236433;
/// <summary>
/// <para>(0040,A492) Completion Flag Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static CompletionFlagDescription: number = 4236434;
/// <summary>
/// <para>(0040,A493) Verification Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static VerificationFlag: number = 4236435;
/// <summary>
/// <para>(0040,A494) Archive Requested</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ArchiveRequested: number = 4236436;
/// <summary>
/// <para>(0040,A496) Preliminary Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PreliminaryFlag: number = 4236438;
/// <summary>
/// <para>(0040,A504) Content Template Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ContentTemplateSequence: number = 4236548;
/// <summary>
/// <para>(0040,A525) Identical Documents Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IdenticalDocumentsSequence: number = 4236581;
/// <summary>
/// <para>(0040,A600) Observation Subject Context Flag (Trial)</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ObservationSubjectContextFlagTrialRetired: number = 4236800;
/// <summary>
/// <para>(0040,A601) Observer Context Flag (Trial)</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ObserverContextFlagTrialRetired: number = 4236801;
/// <summary>
/// <para>(0040,A603) Procedure Context Flag (Trial)</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ProcedureContextFlagTrialRetired: number = 4236803;
/// <summary>
/// <para>(0040,A730) Content Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ContentSequence: number = 4237104;
/// <summary>
/// <para>(0040,A731) Relationship Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static RelationshipSequenceTrialRetired: number = 4237105;
/// <summary>
/// <para>(0040,A732) Relationship Type Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static RelationshipTypeCodeSequenceTrialRetired: number = 4237106;
/// <summary>
/// <para>(0040,A744) Language Code Sequence (Trial)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static LanguageCodeSequenceTrialRetired: number = 4237124;
/// <summary>
/// <para>(0040,A992) Uniform Resource Locator (Trial)</para>
/// <para> VR: ST VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static UniformResourceLocatorTrialRetired: number = 4237714;
/// <summary>
/// <para>(0040,B020) Waveform Annotation Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static WaveformAnnotationSequence: number = 4239392;
/// <summary>
/// <para>(0040,DB00) Template Identifier</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TemplateIdentifier: number = 4250368;
/// <summary>
/// <para>(0040,DB06) Template Version</para>
/// <para> VR: DT VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TemplateVersionRetired: number = 4250374;
/// <summary>
/// <para>(0040,DB07) Template Local Version</para>
/// <para> VR: DT VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TemplateLocalVersionRetired: number = 4250375;
/// <summary>
/// <para>(0040,DB0B) Template Extension Flag</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TemplateExtensionFlagRetired: number = 4250379;
/// <summary>
/// <para>(0040,DB0C) Template Extension Organization UID</para>
/// <para> VR: UI VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TemplateExtensionOrganizationUidRetired: number = 4250380;
/// <summary>
/// <para>(0040,DB0D) Template Extension Creator UID</para>
/// <para> VR: UI VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TemplateExtensionCreatorUidRetired: number = 4250381;
/// <summary>
/// <para>(0040,DB73) Referenced Content Item Identifier</para>
/// <para> VR: UL VM:1-n</para>
/// </summary>
public static ReferencedContentItemIdentifier: number = 4250483;
/// <summary>
/// <para>(0040,E001) HL7 Instance Identifier </para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static Hl7InstanceIdentifier: number = 4251649;
/// <summary>
/// <para>(0040,E004) HL7 Document Effective Time</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static Hl7DocumentEffectiveTime: number = 4251652;
/// <summary>
/// <para>(0040,E006) HL7 Document Type Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static Hl7DocumentTypeCodeSequence: number = 4251654;
/// <summary>
/// <para>(0040,E008) Document Class Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DocumentClassCodeSequence: number = 4251656;
/// <summary>
/// <para>(0040,E010) Retrieve URI </para>
/// <para> VR: UT VM:1</para>
/// </summary>
public static RetrieveUri: number = 4251664;
/// <summary>
/// <para>(0040,E011) Retrieve Location UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static RetrieveLocationUid: number = 4251665;
/// <summary>
/// <para>(0040,E020) Type of Instances</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TypeOfInstances: number = 4251680;
/// <summary>
/// <para>(0040,E021) DICOM Retrieval Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DicomRetrievalSequence: number = 4251681;
/// <summary>
/// <para>(0040,E022) DICOM Media Retrieval Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DicomMediaRetrievalSequence: number = 4251682;
/// <summary>
/// <para>(0040,E023) WADO Retrieval Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static WadoRetrievalSequence: number = 4251683;
/// <summary>
/// <para>(0040,E024) XDS Retrieval Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static XdsRetrievalSequence: number = 4251684;
/// <summary>
/// <para>(0040,E030) Repository Unique ID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static RepositoryUniqueId: number = 4251696;
/// <summary>
/// <para>(0040,E031) Home Community ID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static HomeCommunityId: number = 4251697;
/// <summary>
/// <para>(0042,0010) Document Title</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static DocumentTitle: number = 4325392;
/// <summary>
/// <para>(0042,0011) Encapsulated Document</para>
/// <para> VR: OB VM:1</para>
/// </summary>
public static EncapsulatedDocument: number = 4325393;
/// <summary>
/// <para>(0042,0012) MIME Type of Encapsulated Document</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static MimeTypeOfEncapsulatedDocument: number = 4325394;
/// <summary>
/// <para>(0042,0013) Source Instance Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SourceInstanceSequence: number = 4325395;
/// <summary>
/// <para>(0042,0014) List of MIME Types</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static ListOfMimeTypes: number = 4325396;
/// <summary>
/// <para>(0044,0001) Product Package Identifier</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static ProductPackageIdentifier: number = 4456449;
/// <summary>
/// <para>(0044,0002) Substance Administration Approval</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SubstanceAdministrationApproval: number = 4456450;
/// <summary>
/// <para>(0044,0003) Approval Status Further Description</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static ApprovalStatusFurtherDescription: number = 4456451;
/// <summary>
/// <para>(0044,0004) Approval Status DateTime </para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static ApprovalStatusDatetime: number = 4456452;
/// <summary>
/// <para>(0044,0007) Product Type Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ProductTypeCodeSequence: number = 4456455;
/// <summary>
/// <para>(0044,0008) Product Name</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static ProductName: number = 4456456;
/// <summary>
/// <para>(0044,0009) Product Description</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static ProductDescription: number = 4456457;
/// <summary>
/// <para>(0044,000A) Product Lot Identifier</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ProductLotIdentifier: number = 4456458;
/// <summary>
/// <para>(0044,000B) Product Expiration DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static ProductExpirationDatetime: number = 4456459;
/// <summary>
/// <para>(0044,0010) Substance Administration DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static SubstanceAdministrationDatetime: number = 4456464;
/// <summary>
/// <para>(0044,0011) Substance Administration Notes</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SubstanceAdministrationNotes: number = 4456465;
/// <summary>
/// <para>(0044,0012) Substance Administration Device ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SubstanceAdministrationDeviceId: number = 4456466;
/// <summary>
/// <para>(0044,0013) Product Parameter Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ProductParameterSequence: number = 4456467;
/// <summary>
/// <para>(0044,0019) Substance Administration Parameter Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SubstanceAdministrationParameterSequence: number = 4456473;
/// <summary>
/// <para>(0046,0012) Lens Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static LensDescription: number = 4587538;
/// <summary>
/// <para>(0046,0014) Right Lens Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RightLensSequence: number = 4587540;
/// <summary>
/// <para>(0046,0015) Left Lens Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static LeftLensSequence: number = 4587541;
/// <summary>
/// <para>(0046,0016) Unspecified Laterality Lens Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static UnspecifiedLateralityLensSequence: number = 4587542;
/// <summary>
/// <para>(0046,0018) Cylinder Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CylinderSequence: number = 4587544;
/// <summary>
/// <para>(0046,0028) Prism Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PrismSequence: number = 4587560;
/// <summary>
/// <para>(0046,0030) Horizontal Prism Power</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static HorizontalPrismPower: number = 4587568;
/// <summary>
/// <para>(0046,0032) Horizontal Prism Base</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static HorizontalPrismBase: number = 4587570;
/// <summary>
/// <para>(0046,0034) Vertical Prism Power</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static VerticalPrismPower: number = 4587572;
/// <summary>
/// <para>(0046,0036) Vertical Prism Base</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static VerticalPrismBase: number = 4587574;
/// <summary>
/// <para>(0046,0038) Lens Segment Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static LensSegmentType: number = 4587576;
/// <summary>
/// <para>(0046,0040) Optical Transmittance</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static OpticalTransmittance: number = 4587584;
/// <summary>
/// <para>(0046,0042) Channel Width</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ChannelWidth: number = 4587586;
/// <summary>
/// <para>(0046,0044) Pupil Size</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static PupilSize: number = 4587588;
/// <summary>
/// <para>(0046,0046) Corneal Size</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static CornealSize: number = 4587590;
/// <summary>
/// <para>(0046,0050) Autorefraction Right Eye Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AutorefractionRightEyeSequence: number = 4587600;
/// <summary>
/// <para>(0046,0052) Autorefraction Left Eye Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AutorefractionLeftEyeSequence: number = 4587602;
/// <summary>
/// <para>(0046,0060) Distance Pupillary Distance</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static DistancePupillaryDistance: number = 4587616;
/// <summary>
/// <para>(0046,0062) Near Pupillary Distance</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static NearPupillaryDistance: number = 4587618;
/// <summary>
/// <para>(0046,0063) Intermediate Pupillary Distance</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static IntermediatePupillaryDistance: number = 4587619;
/// <summary>
/// <para>(0046,0064) Other Pupillary Distance</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static OtherPupillaryDistance: number = 4587620;
/// <summary>
/// <para>(0046,0070) Keratometry Right Eye Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static KeratometryRightEyeSequence: number = 4587632;
/// <summary>
/// <para>(0046,0071) Keratometry Left Eye Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static KeratometryLeftEyeSequence: number = 4587633;
/// <summary>
/// <para>(0046,0074) Steep Keratometric Axis Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SteepKeratometricAxisSequence: number = 4587636;
/// <summary>
/// <para>(0046,0075) Radius of Curvature</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static RadiusOfCurvature: number = 4587637;
/// <summary>
/// <para>(0046,0076) Keratometric Power</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static KeratometricPower: number = 4587638;
/// <summary>
/// <para>(0046,0077) Keratometric Axis</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static KeratometricAxis: number = 4587639;
/// <summary>
/// <para>(0046,0080) Flat Keratometric Axis Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FlatKeratometricAxisSequence: number = 4587648;
/// <summary>
/// <para>(0046,0092) Background Color</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BackgroundColor: number = 4587666;
/// <summary>
/// <para>(0046,0094) Optotype</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static Optotype: number = 4587668;
/// <summary>
/// <para>(0046,0095) Optotype Presentation</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static OptotypePresentation: number = 4587669;
/// <summary>
/// <para>(0046,0097) Subjective Refraction Right Eye Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SubjectiveRefractionRightEyeSequence: number = 4587671;
/// <summary>
/// <para>(0046,0098) Subjective Refraction Left Eye Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SubjectiveRefractionLeftEyeSequence: number = 4587672;
/// <summary>
/// <para>(0046,0100) Add Near Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AddNearSequence: number = 4587776;
/// <summary>
/// <para>(0046,0101) Add Intermediate Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AddIntermediateSequence: number = 4587777;
/// <summary>
/// <para>(0046,0102) Add Other Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AddOtherSequence: number = 4587778;
/// <summary>
/// <para>(0046,0104) Add Power</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static AddPower: number = 4587780;
/// <summary>
/// <para>(0046,0106) Viewing Distance</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ViewingDistance: number = 4587782;
/// <summary>
/// <para>(0046,0121) Visual Acuity Type Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static VisualAcuityTypeCodeSequence: number = 4587809;
/// <summary>
/// <para>(0046,0122) Visual Acuity Right Eye Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static VisualAcuityRightEyeSequence: number = 4587810;
/// <summary>
/// <para>(0046,0123) Visual Acuity Left Eye Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static VisualAcuityLeftEyeSequence: number = 4587811;
/// <summary>
/// <para>(0046,0124) Visual Acuity Both Eyes Open Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static VisualAcuityBothEyesOpenSequence: number = 4587812;
/// <summary>
/// <para>(0046,0125) Viewing Distance Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ViewingDistanceType: number = 4587813;
/// <summary>
/// <para>(0046,0135) Visual Acuity Modifiers</para>
/// <para> VR: SS VM:2</para>
/// </summary>
public static VisualAcuityModifiers: number = 4587829;
/// <summary>
/// <para>(0046,0137) Decimal Visual Acuity</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static DecimalVisualAcuity: number = 4587831;
/// <summary>
/// <para>(0046,0139) Optotype Detailed Definition</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static OptotypeDetailedDefinition: number = 4587833;
/// <summary>
/// <para>(0046,0145) Referenced Refractive Measurements Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedRefractiveMeasurementsSequence: number = 4587845;
/// <summary>
/// <para>(0046,0146) Sphere Power</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static SpherePower: number = 4587846;
/// <summary>
/// <para>(0046,0147) Cylinder Power</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static CylinderPower: number = 4587847;
/// <summary>
/// <para>(0048,0001) Imaged Volume Width</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static ImagedVolumeWidth: number = 4718593;
/// <summary>
/// <para>(0048,0002) Imaged Volume Height</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static ImagedVolumeHeight: number = 4718594;
/// <summary>
/// <para>(0048,0003) Imaged Volume Depth</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static ImagedVolumeDepth: number = 4718595;
/// <summary>
/// <para>(0048,0006) Total Pixel Matrix Columns</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static TotalPixelMatrixColumns: number = 4718598;
/// <summary>
/// <para>(0048,0007) Total Pixel Matrix Rows</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static TotalPixelMatrixRows: number = 4718599;
/// <summary>
/// <para>(0048,0008) Total Pixel Matrix Origin Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TotalPixelMatrixOriginSequence: number = 4718600;
/// <summary>
/// <para>(0048,0010) Specimen Label in Image</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SpecimenLabelInImage: number = 4718608;
/// <summary>
/// <para>(0048,0011) Focus Method</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FocusMethod: number = 4718609;
/// <summary>
/// <para>(0048,0012) Extended Depth of Field</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ExtendedDepthOfField: number = 4718610;
/// <summary>
/// <para>(0048,0013) Number of Focal Planes</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfFocalPlanes: number = 4718611;
/// <summary>
/// <para>(0048,0014) Distance Between Focal Planes</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static DistanceBetweenFocalPlanes: number = 4718612;
/// <summary>
/// <para>(0048,0015) Recommended Absent Pixel CIELab Value</para>
/// <para> VR: US VM:3</para>
/// </summary>
public static RecommendedAbsentPixelCielabValue: number = 4718613;
/// <summary>
/// <para>(0048,0100) Illuminator Type Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IlluminatorTypeCodeSequence: number = 4718848;
/// <summary>
/// <para>(0048,0102) Image Orientation (Slide)</para>
/// <para> VR: DS VM:6</para>
/// </summary>
public static ImageOrientationSlide: number = 4718850;
/// <summary>
/// <para>(0048,0105) Optical Path Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OpticalPathSequence: number = 4718853;
/// <summary>
/// <para>(0048,0106) Optical Path Identifier</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static OpticalPathIdentifier: number = 4718854;
/// <summary>
/// <para>(0048,0107) Optical Path Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static OpticalPathDescription: number = 4718855;
/// <summary>
/// <para>(0048,0108) Illumination Color Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IlluminationColorCodeSequence: number = 4718856;
/// <summary>
/// <para>(0048,0110) Specimen Reference Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SpecimenReferenceSequence: number = 4718864;
/// <summary>
/// <para>(0048,0111) Condenser Lens Power</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static CondenserLensPower: number = 4718865;
/// <summary>
/// <para>(0048,0112) Objective Lens Power</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ObjectiveLensPower: number = 4718866;
/// <summary>
/// <para>(0048,0113) Objective Lens Numerical Aperture</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ObjectiveLensNumericalAperture: number = 4718867;
/// <summary>
/// <para>(0048,0120) Palette Color Lookup Table Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PaletteColorLookupTableSequence: number = 4718880;
/// <summary>
/// <para>(0048,0200) Referenced Image Navigation Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedImageNavigationSequence: number = 4719104;
/// <summary>
/// <para>(0048,0201) Top Left Hand Corner of Localizer Area</para>
/// <para> VR: US VM:2</para>
/// </summary>
public static TopLeftHandCornerOfLocalizerArea: number = 4719105;
/// <summary>
/// <para>(0048,0202) Bottom Right Hand Corner of Localizer Area</para>
/// <para> VR: US VM:2</para>
/// </summary>
public static BottomRightHandCornerOfLocalizerArea: number = 4719106;
/// <summary>
/// <para>(0048,0207) Optical Path Identification Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OpticalPathIdentificationSequence: number = 4719111;
/// <summary>
/// <para>(0048,021A) Plane Position (Slide) Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PlanePositionSlideSequence: number = 4719130;
/// <summary>
/// <para>(0048,021E) Row Position In Total Image Pixel Matrix</para>
/// <para> VR: SL VM:1</para>
/// </summary>
public static RowPositionInTotalImagePixelMatrix: number = 4719134;
/// <summary>
/// <para>(0048,021F) Column Position In Total Image Pixel Matrix</para>
/// <para> VR: SL VM:1</para>
/// </summary>
public static ColumnPositionInTotalImagePixelMatrix: number = 4719135;
/// <summary>
/// <para>(0048,0301) Pixel Origin Interpretation</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PixelOriginInterpretation: number = 4719361;
/// <summary>
/// <para>(0050,0004) Calibration Image</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CalibrationImage: number = 5242884;
/// <summary>
/// <para>(0050,0010) Device Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DeviceSequence: number = 5242896;
/// <summary>
/// <para>(0050,0012) Container Component Type Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ContainerComponentTypeCodeSequence: number = 5242898;
/// <summary>
/// <para>(0050,0013) Container Component Thickness</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ContainerComponentThickness: number = 5242899;
/// <summary>
/// <para>(0050,0014) Device Length</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DeviceLength: number = 5242900;
/// <summary>
/// <para>(0050,0015) Container Component Width</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ContainerComponentWidth: number = 5242901;
/// <summary>
/// <para>(0050,0016) Device Diameter</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DeviceDiameter: number = 5242902;
/// <summary>
/// <para>(0050,0017) Device Diameter Units</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DeviceDiameterUnits: number = 5242903;
/// <summary>
/// <para>(0050,0018) Device Volume</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DeviceVolume: number = 5242904;
/// <summary>
/// <para>(0050,0019) Inter-Marker Distance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static InterMarkerDistance: number = 5242905;
/// <summary>
/// <para>(0050,001A) Container Component Material</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ContainerComponentMaterial: number = 5242906;
/// <summary>
/// <para>(0050,001B) Container Component ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ContainerComponentId: number = 5242907;
/// <summary>
/// <para>(0050,001C) Container Component Length</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ContainerComponentLength: number = 5242908;
/// <summary>
/// <para>(0050,001D) Container Component Diameter</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ContainerComponentDiameter: number = 5242909;
/// <summary>
/// <para>(0050,001E) Container Component Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ContainerComponentDescription: number = 5242910;
/// <summary>
/// <para>(0050,0020) Device Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static DeviceDescription: number = 5242912;
/// <summary>
/// <para>(0052,0001) Contrast/Bolus Ingredient Percent by Volume </para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static ContrastBolusIngredientPercentByVolume: number = 5373953;
/// <summary>
/// <para>(0052,0002) OCT Focal Distance</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static OctFocalDistance: number = 5373954;
/// <summary>
/// <para>(0052,0003) Beam Spot Size</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static BeamSpotSize: number = 5373955;
/// <summary>
/// <para>(0052,0004) Effective Refractive Index</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static EffectiveRefractiveIndex: number = 5373956;
/// <summary>
/// <para>(0052,0006) OCT Acquisition Domain</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static OctAcquisitionDomain: number = 5373958;
/// <summary>
/// <para>(0052,0007) OCT Optical Center Wavelength</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static OctOpticalCenterWavelength: number = 5373959;
/// <summary>
/// <para>(0052,0008) Axial Resolution</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static AxialResolution: number = 5373960;
/// <summary>
/// <para>(0052,0009) Ranging Depth</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static RangingDepth: number = 5373961;
/// <summary>
/// <para>(0052,0011) Aline Rate</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static AlineRate: number = 5373969;
/// <summary>
/// <para>(0052,0012) Alines Per Frame</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static AlinesPerFrame: number = 5373970;
/// <summary>
/// <para>(0052,0013) Catheter Rotational Rate</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static CatheterRotationalRate: number = 5373971;
/// <summary>
/// <para>(0052,0014) Aline Pixel Spacing</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static AlinePixelSpacing: number = 5373972;
/// <summary>
/// <para>(0052,0016) Mode of Percutaneous Access Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ModeOfPercutaneousAccessSequence: number = 5373974;
/// <summary>
/// <para>(0052,0025) Intravascular OCT Frame Type Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IntravascularOctFrameTypeSequence: number = 5373989;
/// <summary>
/// <para>(0052,0026) OCT Z Offset Applied</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static OctZOffsetApplied: number = 5373990;
/// <summary>
/// <para>(0052,0027) Intravascular Frame Content Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IntravascularFrameContentSequence: number = 5373991;
/// <summary>
/// <para>(0052,0028) Intravascular Longitudinal Distance</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static IntravascularLongitudinalDistance: number = 5373992;
/// <summary>
/// <para>(0052,0029) Intravascular OCT Frame Content Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IntravascularOctFrameContentSequence: number = 5373993;
/// <summary>
/// <para>(0052,0030) OCT Z Offset Correction</para>
/// <para> VR: SS VM:1</para>
/// </summary>
public static OctZOffsetCorrection: number = 5374000;
/// <summary>
/// <para>(0052,0031) Catheter Direction of Rotation</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CatheterDirectionOfRotation: number = 5374001;
/// <summary>
/// <para>(0052,0033) Seam Line Location</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static SeamLineLocation: number = 5374003;
/// <summary>
/// <para>(0052,0034) First Aline Location</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static FirstAlineLocation: number = 5374004;
/// <summary>
/// <para>(0052,0036) Seam Line Index</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static SeamLineIndex: number = 5374006;
/// <summary>
/// <para>(0052,0038) Number of Padded Alines</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfPaddedAlines: number = 5374008;
/// <summary>
/// <para>(0052,0039) Interpolation Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static InterpolationType: number = 5374009;
/// <summary>
/// <para>(0052,003A) Refractive Index Applied</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RefractiveIndexApplied: number = 5374010;
/// <summary>
/// <para> (0054,0010) Energy Window Vector</para>
/// <para> VR: US VM:1-n</para>
/// </summary>
public static EnergyWindowVector: number = 5505040;
/// <summary>
/// <para>(0054,0011) Number of Energy Windows</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfEnergyWindows: number = 5505041;
/// <summary>
/// <para>(0054,0012) Energy Window Information Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static EnergyWindowInformationSequence: number = 5505042;
/// <summary>
/// <para>(0054,0013) Energy Window Range Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static EnergyWindowRangeSequence: number = 5505043;
/// <summary>
/// <para>(0054,0014) Energy Window Lower Limit</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static EnergyWindowLowerLimit: number = 5505044;
/// <summary>
/// <para>(0054,0015) Energy Window Upper Limit</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static EnergyWindowUpperLimit: number = 5505045;
/// <summary>
/// <para>(0054,0016) Radiopharmaceutical Information Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RadiopharmaceuticalInformationSequence: number = 5505046;
/// <summary>
/// <para>(0054,0017) Residual Syringe Counts</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ResidualSyringeCounts: number = 5505047;
/// <summary>
/// <para>(0054,0018) Energy Window Name</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static EnergyWindowName: number = 5505048;
/// <summary>
/// <para>(0054,0020) Detector Vector</para>
/// <para> VR: US VM:1-n</para>
/// </summary>
public static DetectorVector: number = 5505056;
/// <summary>
/// <para>(0054,0021) Number of Detectors</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfDetectors: number = 5505057;
/// <summary>
/// <para>(0054,0022) Detector Information Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DetectorInformationSequence: number = 5505058;
/// <summary>
/// <para>(0054,0030) Phase Vector</para>
/// <para> VR: US VM:1-n</para>
/// </summary>
public static PhaseVector: number = 5505072;
/// <summary>
/// <para>(0054,0031) Number of Phases</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfPhases: number = 5505073;
/// <summary>
/// <para>(0054,0032) Phase Information Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PhaseInformationSequence: number = 5505074;
/// <summary>
/// <para>(0054,0033) Number of Frames in Phase</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfFramesInPhase: number = 5505075;
/// <summary>
/// <para>(0054,0036) Phase Delay</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static PhaseDelay: number = 5505078;
/// <summary>
/// <para>(0054,0038) Pause Between Frames</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static PauseBetweenFrames: number = 5505080;
/// <summary>
/// <para>(0054,0039) Phase Description</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PhaseDescription: number = 5505081;
/// <summary>
/// <para>(0054,0050) Rotation Vector</para>
/// <para> VR: US VM:1-n</para>
/// </summary>
public static RotationVector: number = 5505104;
/// <summary>
/// <para>(0054,0051) Number of Rotations</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfRotations: number = 5505105;
/// <summary>
/// <para>(0054,0052) Rotation Information Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RotationInformationSequence: number = 5505106;
/// <summary>
/// <para>(0054,0053) Number of Frames in Rotation</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfFramesInRotation: number = 5505107;
/// <summary>
/// <para>(0054,0060) R-R Interval Vector</para>
/// <para> VR: US VM:1-n</para>
/// </summary>
public static RRIntervalVector: number = 5505120;
/// <summary>
/// <para>(0054,0061) Number of R-R Intervals</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfRRIntervals: number = 5505121;
/// <summary>
/// <para>(0054,0062) Gated Information Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static GatedInformationSequence: number = 5505122;
/// <summary>
/// <para>(0054,0063) Data Information Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DataInformationSequence: number = 5505123;
/// <summary>
/// <para>(0054,0070) Time Slot Vector</para>
/// <para> VR: US VM:1-n</para>
/// </summary>
public static TimeSlotVector: number = 5505136;
/// <summary>
/// <para>(0054,0071) Number of Time Slots</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfTimeSlots: number = 5505137;
/// <summary>
/// <para>(0054,0072) Time Slot Information Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TimeSlotInformationSequence: number = 5505138;
/// <summary>
/// <para>(0054,0073) Time Slot Time</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TimeSlotTime: number = 5505139;
/// <summary>
/// <para>(0054,0080) Slice Vector</para>
/// <para> VR: US VM:1-n</para>
/// </summary>
public static SliceVector: number = 5505152;
/// <summary>
/// <para>(0054,0081) Number of Slices</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfSlices: number = 5505153;
/// <summary>
/// <para>(0054,0090) Angular View Vector</para>
/// <para> VR: US VM:1-n</para>
/// </summary>
public static AngularViewVector: number = 5505168;
/// <summary>
/// <para>(0054,0100) Time Slice Vector</para>
/// <para> VR: US VM:1-n</para>
/// </summary>
public static TimeSliceVector: number = 5505280;
/// <summary>
/// <para>(0054,0101) Number of Time Slices</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfTimeSlices: number = 5505281;
/// <summary>
/// <para>(0054,0200) Start Angle</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static StartAngle: number = 5505536;
/// <summary>
/// <para>(0054,0202) Type of Detector Motion</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TypeOfDetectorMotion: number = 5505538;
/// <summary>
/// <para>(0054,0210) Trigger Vector</para>
/// <para> VR: IS VM:1-n</para>
/// </summary>
public static TriggerVector: number = 5505552;
/// <summary>
/// <para>(0054,0211) Number of Triggers in Phase</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfTriggersInPhase: number = 5505553;
/// <summary>
/// <para>(0054,0220) View Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ViewCodeSequence: number = 5505568;
/// <summary>
/// <para>(0054,0222) View Modifier Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ViewModifierCodeSequence: number = 5505570;
/// <summary>
/// <para>(0054,0300) Radionuclide Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RadionuclideCodeSequence: number = 5505792;
/// <summary>
/// <para>(0054,0302) Administration Route Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AdministrationRouteCodeSequence: number = 5505794;
/// <summary>
/// <para>(0054,0304) Radiopharmaceutical Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RadiopharmaceuticalCodeSequence: number = 5505796;
/// <summary>
/// <para>(0054,0306) Calibration Data Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CalibrationDataSequence: number = 5505798;
/// <summary>
/// <para>(0054,0308) Energy Window Number</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static EnergyWindowNumber: number = 5505800;
/// <summary>
/// <para>(0054,0400) Image ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static ImageId: number = 5506048;
/// <summary>
/// <para>(0054,0410) Patient Orientation Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PatientOrientationCodeSequence: number = 5506064;
/// <summary>
/// <para>(0054,0412) Patient Orientation Modifier Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PatientOrientationModifierCodeSequence: number = 5506066;
/// <summary>
/// <para>(0054,0414) Patient Gantry Relationship Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PatientGantryRelationshipCodeSequence: number = 5506068;
/// <summary>
/// <para>(0054,0500) Slice Progression Direction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SliceProgressionDirection: number = 5506304;
/// <summary>
/// <para>(0054,1000) Series Type</para>
/// <para> VR: CS VM:2</para>
/// </summary>
public static SeriesType: number = 5509120;
/// <summary>
/// <para>(0054,1001) Units</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static Units: number = 5509121;
/// <summary>
/// <para>(0054,1002) Counts Source</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CountsSource: number = 5509122;
/// <summary>
/// <para>(0054,1004) Reprojection Method</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ReprojectionMethod: number = 5509124;
/// <summary>
/// <para>(0054,1006) SUV Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SuvType: number = 5509126;
/// <summary>
/// <para>(0054,1100) Randoms Correction Method</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RandomsCorrectionMethod: number = 5509376;
/// <summary>
/// <para>(0054,1101) Attenuation Correction Method</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static AttenuationCorrectionMethod: number = 5509377;
/// <summary>
/// <para>(0054,1102) Decay Correction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DecayCorrection: number = 5509378;
/// <summary>
/// <para>(0054,1103) Reconstruction Method</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ReconstructionMethod: number = 5509379;
/// <summary>
/// <para>(0054,1104) Detector Lines of Response Used</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static DetectorLinesOfResponseUsed: number = 5509380;
/// <summary>
/// <para>(0054,1105) Scatter Correction Method</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ScatterCorrectionMethod: number = 5509381;
/// <summary>
/// <para>(0054,1200) Axial Acceptance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static AxialAcceptance: number = 5509632;
/// <summary>
/// <para>(0054,1201) Axial Mash</para>
/// <para> VR: IS VM:2</para>
/// </summary>
public static AxialMash: number = 5509633;
/// <summary>
/// <para>(0054,1202) Transverse Mash</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static TransverseMash: number = 5509634;
/// <summary>
/// <para>(0054,1203) Detector Element Size</para>
/// <para> VR: DS VM:2</para>
/// </summary>
public static DetectorElementSize: number = 5509635;
/// <summary>
/// <para>(0054,1210) Coincidence Window Width</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static CoincidenceWindowWidth: number = 5509648;
/// <summary>
/// <para>(0054,1220) Secondary Counts Type</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static SecondaryCountsType: number = 5509664;
/// <summary>
/// <para>(0054,1300) Frame Reference Time</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static FrameReferenceTime: number = 5509888;
/// <summary>
/// <para>(0054,1310) Primary (Prompts) Counts Accumulated</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static PrimaryPromptsCountsAccumulated: number = 5509904;
/// <summary>
/// <para>(0054,1311) Secondary Counts Accumulated</para>
/// <para> VR: IS VM:1-n</para>
/// </summary>
public static SecondaryCountsAccumulated: number = 5509905;
/// <summary>
/// <para>(0054,1320) Slice Sensitivity Factor</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SliceSensitivityFactor: number = 5509920;
/// <summary>
/// <para>(0054,1321) Decay Factor</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DecayFactor: number = 5509921;
/// <summary>
/// <para>(0054,1322) Dose Calibration Factor</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DoseCalibrationFactor: number = 5509922;
/// <summary>
/// <para>(0054,1323) Scatter Fraction Factor</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ScatterFractionFactor: number = 5509923;
/// <summary>
/// <para>(0054,1324) Dead Time Factor</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DeadTimeFactor: number = 5509924;
/// <summary>
/// <para>(0054,1330) Image Index</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ImageIndex: number = 5509936;
/// <summary>
/// <para>(0054,1400) Counts Included</para>
/// <para> VR: CS VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CountsIncludedRetired: number = 5510144;
/// <summary>
/// <para>(0054,1401) Dead Time Correction Flag</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DeadTimeCorrectionFlagRetired: number = 5510145;
/// <summary>
/// <para>(0060,3000) Histogram Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static HistogramSequence: number = 6303744;
/// <summary>
/// <para>(0060,3002) Histogram Number of Bins</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static HistogramNumberOfBins: number = 6303746;
/// <summary>
/// <para>(0060,3004) Histogram First Bin Value</para>
/// <para> VR: US or SS VM:1</para>
/// </summary>
public static HistogramFirstBinValue: number = 6303748;
/// <summary>
/// <para>(0060,3006) Histogram Last Bin Value</para>
/// <para> VR: US or SS VM:1</para>
/// </summary>
public static HistogramLastBinValue: number = 6303750;
/// <summary>
/// <para>(0060,3008) Histogram Bin Width</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static HistogramBinWidth: number = 6303752;
/// <summary>
/// <para>(0060,3010) Histogram Explanation</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static HistogramExplanation: number = 6303760;
/// <summary>
/// <para>(0060,3020) Histogram Data</para>
/// <para> VR: UL VM:1-n</para>
/// </summary>
public static HistogramData: number = 6303776;
/// <summary>
/// <para>(0062,0001) Segmentation Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SegmentationType: number = 6422529;
/// <summary>
/// <para>(0062,0002) Segment Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SegmentSequence: number = 6422530;
/// <summary>
/// <para>(0062,0003) Segmented Property Category Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SegmentedPropertyCategoryCodeSequence: number = 6422531;
/// <summary>
/// <para>(0062,0004) Segment Number</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static SegmentNumber: number = 6422532;
/// <summary>
/// <para>(0062,0005) Segment Label</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SegmentLabel: number = 6422533;
/// <summary>
/// <para>(0062,0006) Segment Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static SegmentDescription: number = 6422534;
/// <summary>
/// <para>(0062,0008) Segment Algorithm Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SegmentAlgorithmType: number = 6422536;
/// <summary>
/// <para>(0062,0009) Segment Algorithm Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SegmentAlgorithmName: number = 6422537;
/// <summary>
/// <para>(0062,000A) Segment Identification Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SegmentIdentificationSequence: number = 6422538;
/// <summary>
/// <para>(0062,000B) Referenced Segment Number</para>
/// <para> VR: US VM:1-n</para>
/// </summary>
public static ReferencedSegmentNumber: number = 6422539;
/// <summary>
/// <para>(0062,000C) Recommended Display Grayscale Value</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static RecommendedDisplayGrayscaleValue: number = 6422540;
/// <summary>
/// <para>(0062,000D) Recommended Display CIELab Value</para>
/// <para> VR: US VM:3</para>
/// </summary>
public static RecommendedDisplayCielabValue: number = 6422541;
/// <summary>
/// <para>(0062,000E) Maximum Fractional Value</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static MaximumFractionalValue: number = 6422542;
/// <summary>
/// <para>(0062,000F) Segmented Property Type Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SegmentedPropertyTypeCodeSequence: number = 6422543;
/// <summary>
/// <para>(0062,0010) Segmentation Fractional Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SegmentationFractionalType: number = 6422544;
/// <summary>
/// <para>(0064,0002) Deformable Registration Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DeformableRegistrationSequence: number = 6553602;
/// <summary>
/// <para>(0064,0003) Source Frame of Reference UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static SourceFrameOfReferenceUid: number = 6553603;
/// <summary>
/// <para>(0064,0005) Deformable Registration Grid Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DeformableRegistrationGridSequence: number = 6553605;
/// <summary>
/// <para>(0064,0007) Grid Dimensions</para>
/// <para> VR: UL VM:3</para>
/// </summary>
public static GridDimensions: number = 6553607;
/// <summary>
/// <para>(0064,0008) Grid Resolution</para>
/// <para> VR: FD VM:3</para>
/// </summary>
public static GridResolution: number = 6553608;
/// <summary>
/// <para>(0064,0009) Vector Grid Data</para>
/// <para> VR: OF VM:1</para>
/// </summary>
public static VectorGridData: number = 6553609;
/// <summary>
/// <para>(0064,000F) Pre Deformation Matrix Registration Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PreDeformationMatrixRegistrationSequence: number = 6553615;
/// <summary>
/// <para>(0064,0010) Post Deformation Matrix Registration Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PostDeformationMatrixRegistrationSequence: number = 6553616;
/// <summary>
/// <para>(0066,0001) Number of Surfaces</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static NumberOfSurfaces: number = 6684673;
/// <summary>
/// <para>(0066,0002) Surface Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SurfaceSequence: number = 6684674;
/// <summary>
/// <para>(0066,0003) Surface Number</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static SurfaceNumber: number = 6684675;
/// <summary>
/// <para>(0066,0004) Surface Comments</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static SurfaceComments: number = 6684676;
/// <summary>
/// <para>(0066,0009) Surface Processing</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SurfaceProcessing: number = 6684681;
/// <summary>
/// <para>(0066,000A) Surface Processing Ratio</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static SurfaceProcessingRatio: number = 6684682;
/// <summary>
/// <para>(0066,000B) Surface Processing Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SurfaceProcessingDescription: number = 6684683;
/// <summary>
/// <para>(0066,000C) Recommended Presentation Opacity</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static RecommendedPresentationOpacity: number = 6684684;
/// <summary>
/// <para>(0066,000D) Recommended Presentation Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RecommendedPresentationType: number = 6684685;
/// <summary>
/// <para>(0066,000E) Finite Volume</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FiniteVolume: number = 6684686;
/// <summary>
/// <para>(0066,0010) Manifold</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static Manifold: number = 6684688;
/// <summary>
/// <para>(0066,0011) Surface Points Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SurfacePointsSequence: number = 6684689;
/// <summary>
/// <para>(0066,0012) Surface Points Normals Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SurfacePointsNormalsSequence: number = 6684690;
/// <summary>
/// <para>(0066,0013) Surface Mesh Primitives Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SurfaceMeshPrimitivesSequence: number = 6684691;
/// <summary>
/// <para>(0066,0015) Number of Surface Points</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static NumberOfSurfacePoints: number = 6684693;
/// <summary>
/// <para>(0066,0016) Point Coordinates Data</para>
/// <para> VR: OF VM:1</para>
/// </summary>
public static PointCoordinatesData: number = 6684694;
/// <summary>
/// <para>(0066,0017) Point Position Accuracy</para>
/// <para> VR: FL VM:3</para>
/// </summary>
public static PointPositionAccuracy: number = 6684695;
/// <summary>
/// <para>(0066,0018) Mean Point Distance</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static MeanPointDistance: number = 6684696;
/// <summary>
/// <para>(0066,0019) Maximum Point Distance</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static MaximumPointDistance: number = 6684697;
/// <summary>
/// <para>(0066,001A) Points Bounding Box Coordinates</para>
/// <para> VR: FL VM:6</para>
/// </summary>
public static PointsBoundingBoxCoordinates: number = 6684698;
/// <summary>
/// <para>(0066,001B) Axis of Rotation</para>
/// <para> VR: FL VM:3</para>
/// </summary>
public static AxisOfRotation: number = 6684699;
/// <summary>
/// <para>(0066,001C) Center of Rotation</para>
/// <para> VR: FL VM:3</para>
/// </summary>
public static CenterOfRotation: number = 6684700;
/// <summary>
/// <para>(0066,001E) Number of Vectors</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static NumberOfVectors: number = 6684702;
/// <summary>
/// <para>(0066,001F) Vector Dimensionality</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static VectorDimensionality: number = 6684703;
/// <summary>
/// <para>(0066,0020) Vector Accuracy</para>
/// <para> VR: FL VM:1-n</para>
/// </summary>
public static VectorAccuracy: number = 6684704;
/// <summary>
/// <para>(0066,0021) Vector Coordinate Data</para>
/// <para> VR: OF VM:1</para>
/// </summary>
public static VectorCoordinateData: number = 6684705;
/// <summary>
/// <para>(0066,0023) Triangle Point Index List</para>
/// <para> VR: OW VM:1</para>
/// </summary>
public static TrianglePointIndexList: number = 6684707;
/// <summary>
/// <para>(0066,0024) Edge Point Index List</para>
/// <para> VR: OW VM:1</para>
/// </summary>
public static EdgePointIndexList: number = 6684708;
/// <summary>
/// <para>(0066,0025) Vertex Point Index List</para>
/// <para> VR: OW VM:1</para>
/// </summary>
public static VertexPointIndexList: number = 6684709;
/// <summary>
/// <para>(0066,0026) Triangle Strip Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TriangleStripSequence: number = 6684710;
/// <summary>
/// <para>(0066,0027) Triangle Fan Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TriangleFanSequence: number = 6684711;
/// <summary>
/// <para>(0066,0028) Line Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static LineSequence: number = 6684712;
/// <summary>
/// <para>(0066,0029) Primitive Point Index List</para>
/// <para> VR: OW VM:1</para>
/// </summary>
public static PrimitivePointIndexList: number = 6684713;
/// <summary>
/// <para>(0066,002A) Surface Count</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static SurfaceCount: number = 6684714;
/// <summary>
/// <para>(0066,002B) Referenced Surface Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedSurfaceSequence: number = 6684715;
/// <summary>
/// <para>(0066,002C) Referenced Surface Number</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static ReferencedSurfaceNumber: number = 6684716;
/// <summary>
/// <para>(0066,002D) Segment Surface Generation Algorithm Identification Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SegmentSurfaceGenerationAlgorithmIdentificationSequence: number = 6684717;
/// <summary>
/// <para>(0066,002E) Segment Surface Source Instance Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SegmentSurfaceSourceInstanceSequence: number = 6684718;
/// <summary>
/// <para>(0066,002F) Algorithm Family Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AlgorithmFamilyCodeSequence: number = 6684719;
/// <summary>
/// <para>(0066,0030) Algorithm Name Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AlgorithmNameCodeSequence: number = 6684720;
/// <summary>
/// <para>(0066,0031) Algorithm Version</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static AlgorithmVersion: number = 6684721;
/// <summary>
/// <para>(0066,0032) Algorithm Parameters</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static AlgorithmParameters: number = 6684722;
/// <summary>
/// <para>(0066,0034) Facet Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FacetSequence: number = 6684724;
/// <summary>
/// <para>(0066,0035) Surface Processing Algorithm Identification Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SurfaceProcessingAlgorithmIdentificationSequence: number = 6684725;
/// <summary>
/// <para>(0066,0036) Algorithm Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static AlgorithmName: number = 6684726;
/// <summary>
/// <para>(0068,6210) Implant Size</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ImplantSize: number = 6840848;
/// <summary>
/// <para>(0068,6221) Implant Template Version</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ImplantTemplateVersion: number = 6840865;
/// <summary>
/// <para>(0068,6222) Replaced Implant Template Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReplacedImplantTemplateSequence: number = 6840866;
/// <summary>
/// <para>(0068,6223) Implant Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ImplantType: number = 6840867;
/// <summary>
/// <para>(0068,6224) Derivation Implant Template Sequence </para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DerivationImplantTemplateSequence: number = 6840868;
/// <summary>
/// <para>(0068,6225) Original Implant Template Sequence </para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OriginalImplantTemplateSequence: number = 6840869;
/// <summary>
/// <para>(0068,6226) Effective DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static EffectiveDatetime: number = 6840870;
/// <summary>
/// <para>(0068,6230) Implant Target Anatomy Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ImplantTargetAnatomySequence: number = 6840880;
/// <summary>
/// <para>(0068,6260) Information From Manufacturer Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static InformationFromManufacturerSequence: number = 6840928;
/// <summary>
/// <para>(0068,6265) Notification From Manufacturer Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static NotificationFromManufacturerSequence: number = 6840933;
/// <summary>
/// <para>(0068,6270) Information Issue DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static InformationIssueDatetime: number = 6840944;
/// <summary>
/// <para>(0068,6280) Information Summary</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static InformationSummary: number = 6840960;
/// <summary>
/// <para>(0068,62A0) Implant Regulatory Disapproval Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ImplantRegulatoryDisapprovalCodeSequence: number = 6840992;
/// <summary>
/// <para>(0068,62A5) Overall Template Spatial Tolerance</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static OverallTemplateSpatialTolerance: number = 6840997;
/// <summary>
/// <para>(0068,62C0) HPGL Document Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static HpglDocumentSequence: number = 6841024;
/// <summary>
/// <para>(0068,62D0) HPGL Document ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static HpglDocumentId: number = 6841040;
/// <summary>
/// <para>(0068,62D5) HPGL Document Label</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static HpglDocumentLabel: number = 6841045;
/// <summary>
/// <para>(0068,62E0) View Orientation Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ViewOrientationCodeSequence: number = 6841056;
/// <summary>
/// <para>(0068,62F0) View Orientation Modifier</para>
/// <para> VR: FD VM:9</para>
/// </summary>
public static ViewOrientationModifier: number = 6841072;
/// <summary>
/// <para>(0068,62F2) HPGL Document Scaling</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static HpglDocumentScaling: number = 6841074;
/// <summary>
/// <para>(0068,6300) HPGL Document</para>
/// <para> VR: OB VM:1</para>
/// </summary>
public static HpglDocument: number = 6841088;
/// <summary>
/// <para>(0068,6310) HPGL Contour Pen Number</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static HpglContourPenNumber: number = 6841104;
/// <summary>
/// <para>(0068,6320) HPGL Pen Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static HpglPenSequence: number = 6841120;
/// <summary>
/// <para>(0068,6330) HPGL Pen Number</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static HpglPenNumber: number = 6841136;
/// <summary>
/// <para>(0068,6340) HPGL Pen Label</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static HpglPenLabel: number = 6841152;
/// <summary>
/// <para>(0068,6345) HPGL Pen Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static HpglPenDescription: number = 6841157;
/// <summary>
/// <para>(0068,6346) Recommended Rotation Point</para>
/// <para> VR: FD VM:2</para>
/// </summary>
public static RecommendedRotationPoint: number = 6841158;
/// <summary>
/// <para>(0068,6347) Bounding Rectangle</para>
/// <para> VR: FD VM:4</para>
/// </summary>
public static BoundingRectangle: number = 6841159;
/// <summary>
/// <para>(0068,6350) Implant Template 3D Model Surface Number</para>
/// <para> VR: US VM:1-n</para>
/// </summary>
public static ImplantTemplate3dModelSurfaceNumber: number = 6841168;
/// <summary>
/// <para>(0068,6360) Surface Model Description Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SurfaceModelDescriptionSequence: number = 6841184;
/// <summary>
/// <para>(0068,6380) Surface Model Label</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SurfaceModelLabel: number = 6841216;
/// <summary>
/// <para>(0068,6390) Surface Model Scaling Factor</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static SurfaceModelScalingFactor: number = 6841232;
/// <summary>
/// <para>(0068,63A0) Materials Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MaterialsCodeSequence: number = 6841248;
/// <summary>
/// <para>(0068,63A4) Coating Materials Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CoatingMaterialsCodeSequence: number = 6841252;
/// <summary>
/// <para>(0068,63A8) Implant Type Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ImplantTypeCodeSequence: number = 6841256;
/// <summary>
/// <para>(0068,63AC) Fixation Method Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FixationMethodCodeSequence: number = 6841260;
/// <summary>
/// <para>(0068,63B0) Mating Feature Sets Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MatingFeatureSetsSequence: number = 6841264;
/// <summary>
/// <para>(0068,63C0) Mating Feature Set ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static MatingFeatureSetId: number = 6841280;
/// <summary>
/// <para>(0068,63D0) Mating Feature Set Label</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static MatingFeatureSetLabel: number = 6841296;
/// <summary>
/// <para>(0068,63E0) Mating Feature Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MatingFeatureSequence: number = 6841312;
/// <summary>
/// <para>(0068,63F0) Mating Feature ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static MatingFeatureId: number = 6841328;
/// <summary>
/// <para>(0068,6400) Mating Feature Degree of Freedom Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MatingFeatureDegreeOfFreedomSequence: number = 6841344;
/// <summary>
/// <para>(0068,6410) Degree of Freedom ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static DegreeOfFreedomId: number = 6841360;
/// <summary>
/// <para>(0068,6420) Degree of Freedom Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DegreeOfFreedomType: number = 6841376;
/// <summary>
/// <para>(0068,6430) 2D Mating Feature Coordinates Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TwoDMatingFeatureCoordinatesSequence: number = 6841392;
/// <summary>
/// <para>(0068,6440) Referenced HPGL Document ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ReferencedHpglDocumentId: number = 6841408;
/// <summary>
/// <para>(0068,6450) 2D Mating Point</para>
/// <para> VR: FD VM:2</para>
/// </summary>
public static TwoDMatingPoint: number = 6841424;
/// <summary>
/// <para>(0068,6460) 2D Mating Axes</para>
/// <para> VR: FD VM:4</para>
/// </summary>
public static TwoDMatingAxes: number = 6841440;
/// <summary>
/// <para>(0068,6470) 2D Degree of Freedom Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TwoDDegreeOfFreedomSequence: number = 6841456;
/// <summary>
/// <para>(0068,6490) 3D Degree of Freedom Axis</para>
/// <para> VR: FD VM:3</para>
/// </summary>
public static ThreeDDegreeOfFreedomAxis: number = 6841488;
/// <summary>
/// <para>(0068,64A0) Range of Freedom</para>
/// <para> VR: FD VM:2</para>
/// </summary>
public static RangeOfFreedom: number = 6841504;
/// <summary>
/// <para>(0068,64C0) 3D Mating Point</para>
/// <para> VR: FD VM:3</para>
/// </summary>
public static ThreeDMatingPoint: number = 6841536;
/// <summary>
/// <para>(0068,64D0) 3D Mating Axes</para>
/// <para> VR: FD VM:9</para>
/// </summary>
public static ThreeDMatingAxes: number = 6841552;
/// <summary>
/// <para>(0068,64F0) 2D Degree of Freedom Axis</para>
/// <para> VR: FD VM:3</para>
/// </summary>
public static TwoDDegreeOfFreedomAxis: number = 6841584;
/// <summary>
/// <para>(0068,6500) Planning Landmark Point Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PlanningLandmarkPointSequence: number = 6841600;
/// <summary>
/// <para>(0068,6510) Planning Landmark Line Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PlanningLandmarkLineSequence: number = 6841616;
/// <summary>
/// <para>(0068,6520) Planning Landmark Plane Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PlanningLandmarkPlaneSequence: number = 6841632;
/// <summary>
/// <para>(0068,6530) Planning Landmark ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static PlanningLandmarkId: number = 6841648;
/// <summary>
/// <para>(0068,6540) Planning Landmark Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PlanningLandmarkDescription: number = 6841664;
/// <summary>
/// <para>(0068,6545) Planning Landmark Identification Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PlanningLandmarkIdentificationCodeSequence: number = 6841669;
/// <summary>
/// <para>(0068,6550) 2D Point Coordinates Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TwoDPointCoordinatesSequence: number = 6841680;
/// <summary>
/// <para>(0068,6560) 2D Point Coordinates</para>
/// <para> VR: FD VM:2</para>
/// </summary>
public static TwoDPointCoordinates: number = 6841696;
/// <summary>
/// <para>(0068,6590) 3D Point Coordinates</para>
/// <para> VR: FD VM:3</para>
/// </summary>
public static ThreeDPointCoordinates: number = 6841744;
/// <summary>
/// <para>(0068,65A0) 2D Line Coordinates Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TwoDLineCoordinatesSequence: number = 6841760;
/// <summary>
/// <para>(0068,65B0) 2D Line Coordinates</para>
/// <para> VR: FD VM:4</para>
/// </summary>
public static TwoDLineCoordinates: number = 6841776;
/// <summary>
/// <para>(0068,65D0) 3D Line Coordinates</para>
/// <para> VR: FD VM:6</para>
/// </summary>
public static ThreeDLineCoordinates: number = 6841808;
/// <summary>
/// <para>(0068,65E0) 2D Plane Coordinates Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TwoDPlaneCoordinatesSequence: number = 6841824;
/// <summary>
/// <para>(0068,65F0) 2D Plane Intersection</para>
/// <para> VR: FD VM:4</para>
/// </summary>
public static TwoDPlaneIntersection: number = 6841840;
/// <summary>
/// <para>(0068,6610) 3D Plane Origin</para>
/// <para> VR: FD VM:3</para>
/// </summary>
public static ThreeDPlaneOrigin: number = 6841872;
/// <summary>
/// <para>(0068,6620) 3D Plane Normal</para>
/// <para> VR: FD VM:3</para>
/// </summary>
public static ThreeDPlaneNormal: number = 6841888;
/// <summary>
/// <para>(0070,0001) Graphic Annotation Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static GraphicAnnotationSequence: number = 7340033;
/// <summary>
/// <para>(0070,0002) Graphic Layer</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static GraphicLayer: number = 7340034;
/// <summary>
/// <para>(0070,0003) Bounding Box Annotation Units</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BoundingBoxAnnotationUnits: number = 7340035;
/// <summary>
/// <para>(0070,0004) Anchor Point Annotation Units</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AnchorPointAnnotationUnits: number = 7340036;
/// <summary>
/// <para>(0070,0005) Graphic Annotation Units</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static GraphicAnnotationUnits: number = 7340037;
/// <summary>
/// <para>(0070,0006) Unformatted Text Value</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static UnformattedTextValue: number = 7340038;
/// <summary>
/// <para>(0070,0008) Text Object Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TextObjectSequence: number = 7340040;
/// <summary>
/// <para>(0070,0009) Graphic Object Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static GraphicObjectSequence: number = 7340041;
/// <summary>
/// <para>(0070,0010) Bounding Box Top Left Hand Corner</para>
/// <para> VR: FL VM:2</para>
/// </summary>
public static BoundingBoxTopLeftHandCorner: number = 7340048;
/// <summary>
/// <para>(0070,0011) Bounding Box Bottom Right Hand Corner</para>
/// <para> VR: FL VM:2</para>
/// </summary>
public static BoundingBoxBottomRightHandCorner: number = 7340049;
/// <summary>
/// <para>(0070,0012) Bounding Box Text Horizontal Justification</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BoundingBoxTextHorizontalJustification: number = 7340050;
/// <summary>
/// <para>(0070,0014) Anchor Point</para>
/// <para> VR: FL VM:2</para>
/// </summary>
public static AnchorPoint: number = 7340052;
/// <summary>
/// <para>(0070,0015) Anchor Point Visibility</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AnchorPointVisibility: number = 7340053;
/// <summary>
/// <para>(0070,0020) Graphic Dimensions </para>
/// <para> VR: US VM:1</para>
/// </summary>
public static GraphicDimensions: number = 7340064;
/// <summary>
/// <para>(0070,0021) Number of Graphic Points</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfGraphicPoints: number = 7340065;
/// <summary>
/// <para>(0070,0022) Graphic Data</para>
/// <para> VR: FL VM:2-n</para>
/// </summary>
public static GraphicData: number = 7340066;
/// <summary>
/// <para>(0070,0023) Graphic Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static GraphicType: number = 7340067;
/// <summary>
/// <para>(0070,0024) Graphic Filled</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static GraphicFilled: number = 7340068;
/// <summary>
/// <para>(0070,0040) Image Rotation (Retired)</para>
/// <para> VR: IS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ImageRotationRetired: number = 7340096;
/// <summary>
/// <para>(0070,0041) Image Horizontal Flip</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ImageHorizontalFlip: number = 7340097;
/// <summary>
/// <para>(0070,0042) Image Rotation </para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ImageRotation: number = 7340098;
/// <summary>
/// <para>(0070,0050) Displayed Area Top Left Hand Corner (Trial)</para>
/// <para> VR: US VM:2</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DisplayedAreaTopLeftHandCornerTrialRetired: number = 7340112;
/// <summary>
/// <para>(0070,0051) Displayed Area Bottom Right Hand Corner (Trial)</para>
/// <para> VR: US VM:2</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DisplayedAreaBottomRightHandCornerTrialRetired: number = 7340113;
/// <summary>
/// <para>(0070,0052) Displayed Area Top Left Hand Corner</para>
/// <para> VR: SL VM:2</para>
/// </summary>
public static DisplayedAreaTopLeftHandCorner: number = 7340114;
/// <summary>
/// <para>(0070,0053) Displayed Area Bottom Right Hand Corner</para>
/// <para> VR: SL VM:2</para>
/// </summary>
public static DisplayedAreaBottomRightHandCorner: number = 7340115;
/// <summary>
/// <para>(0070,005A) Displayed Area Selection Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DisplayedAreaSelectionSequence: number = 7340122;
/// <summary>
/// <para>(0070,0060) Graphic Layer Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static GraphicLayerSequence: number = 7340128;
/// <summary>
/// <para>(0070,0062) Graphic Layer Order</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static GraphicLayerOrder: number = 7340130;
/// <summary>
/// <para>(0070,0066) Graphic Layer Recommended Display Grayscale Value</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static GraphicLayerRecommendedDisplayGrayscaleValue: number = 7340134;
/// <summary>
/// <para>(0070,0067) Graphic Layer Recommended Display RGB Value</para>
/// <para> VR: US VM:3</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static GraphicLayerRecommendedDisplayRgbValueRetired: number = 7340135;
/// <summary>
/// <para>(0070,0068) Graphic Layer Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static GraphicLayerDescription: number = 7340136;
/// <summary>
/// <para>(0070,0080) Content Label</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ContentLabel: number = 7340160;
/// <summary>
/// <para>(0070,0081) Content Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ContentDescription: number = 7340161;
/// <summary>
/// <para>(0070,0082) Presentation Creation Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static PresentationCreationDate: number = 7340162;
/// <summary>
/// <para>(0070,0083) Presentation Creation Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static PresentationCreationTime: number = 7340163;
/// <summary>
/// <para>(0070,0084) Content Creator's Name</para>
/// <para> VR: PN VM:1</para>
/// </summary>
public static ContentCreatorsName: number = 7340164;
/// <summary>
/// <para>(0070,0086) Content Creator's Identification Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ContentCreatorsIdentificationCodeSequence: number = 7340166;
/// <summary>
/// <para>(0070,0087) Alternate Content Description Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AlternateContentDescriptionSequence: number = 7340167;
/// <summary>
/// <para>(0070,0100) Presentation Size Mode</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PresentationSizeMode: number = 7340288;
/// <summary>
/// <para>(0070,0101) Presentation Pixel Spacing</para>
/// <para> VR: DS VM:2</para>
/// </summary>
public static PresentationPixelSpacing: number = 7340289;
/// <summary>
/// <para>(0070,0102) Presentation Pixel Aspect Ratio</para>
/// <para> VR: IS VM:2</para>
/// </summary>
public static PresentationPixelAspectRatio: number = 7340290;
/// <summary>
/// <para>(0070,0103) Presentation Pixel Magnification Ratio</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static PresentationPixelMagnificationRatio: number = 7340291;
/// <summary>
/// <para>(0070,0207) Graphic Group Label</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static GraphicGroupLabel: number = 7340551;
/// <summary>
/// <para>(0070,0208) Graphic Group Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static GraphicGroupDescription: number = 7340552;
/// <summary>
/// <para>(0070,0209) Compound Graphic Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CompoundGraphicSequence: number = 7340553;
/// <summary>
/// <para>(0070,0226) Compound Graphic Instance ID</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static CompoundGraphicInstanceId: number = 7340582;
/// <summary>
/// <para>(0070,0227) Font Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static FontName: number = 7340583;
/// <summary>
/// <para>(0070,0228) Font Name Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FontNameType: number = 7340584;
/// <summary>
/// <para>(0070,0229) CSS Font Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static CssFontName: number = 7340585;
/// <summary>
/// <para>(0070,0230) Rotation Angle</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static RotationAngle: number = 7340592;
/// <summary>
/// <para>(0070,0231) Text Style Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TextStyleSequence: number = 7340593;
/// <summary>
/// <para>(0070,0232) Line Style Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static LineStyleSequence: number = 7340594;
/// <summary>
/// <para>(0070,0233) Fill Style Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FillStyleSequence: number = 7340595;
/// <summary>
/// <para>(0070,0234) Graphic Group Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static GraphicGroupSequence: number = 7340596;
/// <summary>
/// <para>(0070,0241) Text Color CIELab Value</para>
/// <para> VR: US VM:3</para>
/// </summary>
public static TextColorCielabValue: number = 7340609;
/// <summary>
/// <para>(0070,0242) Horizontal Alignment</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static HorizontalAlignment: number = 7340610;
/// <summary>
/// <para>(0070,0243) Vertical Alignment</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static VerticalAlignment: number = 7340611;
/// <summary>
/// <para>(0070,0244) Shadow Style</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ShadowStyle: number = 7340612;
/// <summary>
/// <para>(0070,0245) Shadow Offset X</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static ShadowOffsetX: number = 7340613;
/// <summary>
/// <para>(0070,0246) Shadow Offset Y</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static ShadowOffsetY: number = 7340614;
/// <summary>
/// <para>(0070,0247) Shadow Color CIELab Value</para>
/// <para> VR: US VM:3</para>
/// </summary>
public static ShadowColorCielabValue: number = 7340615;
/// <summary>
/// <para>(0070,0248) Underlined</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static Underlined: number = 7340616;
/// <summary>
/// <para>(0070,0249) Bold</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static Bold: number = 7340617;
/// <summary>
/// <para>(0070,0250) Italic</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static Italic: number = 7340624;
/// <summary>
/// <para>(0070,0251) Pattern On Color CIELab Value</para>
/// <para> VR: US VM:3</para>
/// </summary>
public static PatternOnColorCielabValue: number = 7340625;
/// <summary>
/// <para>(0070,0252) Pattern Off Color CIELab Value</para>
/// <para> VR: US VM:3</para>
/// </summary>
public static PatternOffColorCielabValue: number = 7340626;
/// <summary>
/// <para>(0070,0253) Line Thickness</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static LineThickness: number = 7340627;
/// <summary>
/// <para>(0070,0254) Line Dashing Style</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static LineDashingStyle: number = 7340628;
/// <summary>
/// <para>(0070,0255) Line Pattern</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static LinePattern: number = 7340629;
/// <summary>
/// <para>(0070,0256) Fill Pattern</para>
/// <para> VR: OB VM:1</para>
/// </summary>
public static FillPattern: number = 7340630;
/// <summary>
/// <para>(0070,0257) Fill Mode</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FillMode: number = 7340631;
/// <summary>
/// <para>(0070,0258) Shadow Opacity</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static ShadowOpacity: number = 7340632;
/// <summary>
/// <para>(0070,0261) Gap Length</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static GapLength: number = 7340641;
/// <summary>
/// <para>(0070,0262) Diameter of Visibility</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static DiameterOfVisibility: number = 7340642;
/// <summary>
/// <para>(0070,0273) Rotation Point</para>
/// <para> VR: FL VM:2</para>
/// </summary>
public static RotationPoint: number = 7340659;
/// <summary>
/// <para>(0070,0274) Tick Alignment</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TickAlignment: number = 7340660;
/// <summary>
/// <para>(0070,0278) Show Tick Label</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ShowTickLabel: number = 7340664;
/// <summary>
/// <para>(0070,0279) Tick Label Alignment</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TickLabelAlignment: number = 7340665;
/// <summary>
/// <para>(0070,0282) Compound Graphic Units</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CompoundGraphicUnits: number = 7340674;
/// <summary>
/// <para>(0070,0284) Pattern On Opacity</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static PatternOnOpacity: number = 7340676;
/// <summary>
/// <para>(0070,0285) Pattern Off Opacity</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static PatternOffOpacity: number = 7340677;
/// <summary>
/// <para>(0070,0287) Major Ticks Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MajorTicksSequence: number = 7340679;
/// <summary>
/// <para>(0070,0288) Tick Position</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static TickPosition: number = 7340680;
/// <summary>
/// <para>(0070,0289) Tick Label</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static TickLabel: number = 7340681;
/// <summary>
/// <para>(0070,0294) Compound Graphic Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CompoundGraphicType: number = 7340692;
/// <summary>
/// <para>(0070,0295) Graphic Group ID</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static GraphicGroupId: number = 7340693;
/// <summary>
/// <para>(0070,0306) Shape Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ShapeType: number = 7340806;
/// <summary>
/// <para>(0070,0308) Registration Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RegistrationSequence: number = 7340808;
/// <summary>
/// <para>(0070,0309) Matrix Registration Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MatrixRegistrationSequence: number = 7340809;
/// <summary>
/// <para>(0070,030A) Matrix Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MatrixSequence: number = 7340810;
/// <summary>
/// <para>(0070,030C) Frame of Reference Transformation Matrix Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FrameOfReferenceTransformationMatrixType: number = 7340812;
/// <summary>
/// <para>(0070,030D) Registration Type Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RegistrationTypeCodeSequence: number = 7340813;
/// <summary>
/// <para>(0070,030F) Fiducial Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static FiducialDescription: number = 7340815;
/// <summary>
/// <para>(0070,0310) Fiducial Identifier</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static FiducialIdentifier: number = 7340816;
/// <summary>
/// <para>(0070,0311) Fiducial Identifier Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FiducialIdentifierCodeSequence: number = 7340817;
/// <summary>
/// <para>(0070,0312) Contour Uncertainty Radius</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ContourUncertaintyRadius: number = 7340818;
/// <summary>
/// <para>(0070,0314) Used Fiducials Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static UsedFiducialsSequence: number = 7340820;
/// <summary>
/// <para>(0070,0318) Graphic Coordinates Data Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static GraphicCoordinatesDataSequence: number = 7340824;
/// <summary>
/// <para>(0070,031A) Fiducial UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static FiducialUid: number = 7340826;
/// <summary>
/// <para>(0070,031C) Fiducial Set Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FiducialSetSequence: number = 7340828;
/// <summary>
/// <para>(0070,031E) Fiducial Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FiducialSequence: number = 7340830;
/// <summary>
/// <para>(0070,0401) Graphic Layer Recommended Display CIELab Value</para>
/// <para> VR: US VM:3</para>
/// </summary>
public static GraphicLayerRecommendedDisplayCielabValue: number = 7341057;
/// <summary>
/// <para>(0070,0402) Blending Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BlendingSequence: number = 7341058;
/// <summary>
/// <para>(0070,0403) Relative Opacity</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static RelativeOpacity: number = 7341059;
/// <summary>
/// <para>(0070,0404) Referenced Spatial Registration Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedSpatialRegistrationSequence: number = 7341060;
/// <summary>
/// <para>(0070,0405) Blending Position</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BlendingPosition: number = 7341061;
/// <summary>
/// <para>(0072,0002) Hanging Protocol Name</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static HangingProtocolName: number = 7471106;
/// <summary>
/// <para>(0072,0004) Hanging Protocol Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static HangingProtocolDescription: number = 7471108;
/// <summary>
/// <para>(0072,0006) Hanging Protocol Level</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static HangingProtocolLevel: number = 7471110;
/// <summary>
/// <para>(0072,0008) Hanging Protocol Creator</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static HangingProtocolCreator: number = 7471112;
/// <summary>
/// <para>(0072,000A) Hanging Protocol Creation DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static HangingProtocolCreationDatetime: number = 7471114;
/// <summary>
/// <para>(0072,000C) Hanging Protocol Definition Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static HangingProtocolDefinitionSequence: number = 7471116;
/// <summary>
/// <para>(0072,000E) Hanging Protocol User Identification Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static HangingProtocolUserIdentificationCodeSequence: number = 7471118;
/// <summary>
/// <para>(0072,0010) Hanging Protocol User Group Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static HangingProtocolUserGroupName: number = 7471120;
/// <summary>
/// <para>(0072,0012) Source Hanging Protocol Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SourceHangingProtocolSequence: number = 7471122;
/// <summary>
/// <para>(0072,0014) Number of Priors Referenced</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfPriorsReferenced: number = 7471124;
/// <summary>
/// <para>(0072,0020) Image Sets Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ImageSetsSequence: number = 7471136;
/// <summary>
/// <para>(0072,0022) Image Set Selector Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ImageSetSelectorSequence: number = 7471138;
/// <summary>
/// <para>(0072,0024) Image Set Selector Usage Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ImageSetSelectorUsageFlag: number = 7471140;
/// <summary>
/// <para>(0072,0026) Selector Attribute</para>
/// <para> VR: AT VM:1</para>
/// </summary>
public static SelectorAttribute: number = 7471142;
/// <summary>
/// <para>(0072,0028) Selector Value Number</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static SelectorValueNumber: number = 7471144;
/// <summary>
/// <para>(0072,0030) Time Based Image Sets Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TimeBasedImageSetsSequence: number = 7471152;
/// <summary>
/// <para>(0072,0032) Image Set Number</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ImageSetNumber: number = 7471154;
/// <summary>
/// <para>(0072,0034) Image Set Selector Category</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ImageSetSelectorCategory: number = 7471156;
/// <summary>
/// <para>(0072,0038) Relative Time</para>
/// <para> VR: US VM:2</para>
/// </summary>
public static RelativeTime: number = 7471160;
/// <summary>
/// <para>(0072,003A) Relative Time Units</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RelativeTimeUnits: number = 7471162;
/// <summary>
/// <para>(0072,003C) Abstract Prior Value</para>
/// <para> VR: SS VM:2</para>
/// </summary>
public static AbstractPriorValue: number = 7471164;
/// <summary>
/// <para>(0072,003E) Abstract Prior Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AbstractPriorCodeSequence: number = 7471166;
/// <summary>
/// <para>(0072,0040) Image Set Label</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ImageSetLabel: number = 7471168;
/// <summary>
/// <para>(0072,0050) Selector Attribute VR</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SelectorAttributeVr: number = 7471184;
/// <summary>
/// <para>(0072,0052) Selector Sequence Pointer</para>
/// <para> VR: AT VM:1-n</para>
/// </summary>
public static SelectorSequencePointer: number = 7471186;
/// <summary>
/// <para>(0072,0054) Selector Sequence Pointer Private Creator</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static SelectorSequencePointerPrivateCreator: number = 7471188;
/// <summary>
/// <para>(0072,0056) Selector Attribute Private Creator</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SelectorAttributePrivateCreator: number = 7471190;
/// <summary>
/// <para>(0072,0060) Selector AT Value</para>
/// <para> VR: AT VM:1-n</para>
/// </summary>
public static SelectorAtValue: number = 7471200;
/// <summary>
/// <para>(0072,0062) Selector CS Value</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static SelectorCsValue: number = 7471202;
/// <summary>
/// <para>(0072,0064) Selector IS Value</para>
/// <para> VR: IS VM:1-n</para>
/// </summary>
public static SelectorIsValue: number = 7471204;
/// <summary>
/// <para>(0072,0066) Selector LO Value</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static SelectorLoValue: number = 7471206;
/// <summary>
/// <para>(0072,0068) Selector LT Value</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static SelectorLtValue: number = 7471208;
/// <summary>
/// <para>(0072,006A) Selector PN Value</para>
/// <para> VR: PN VM:1-n</para>
/// </summary>
public static SelectorPnValue: number = 7471210;
/// <summary>
/// <para>(0072,006C) Selector SH Value</para>
/// <para> VR: SH VM:1-n</para>
/// </summary>
public static SelectorShValue: number = 7471212;
/// <summary>
/// <para>(0072,006E) Selector ST Value</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static SelectorStValue: number = 7471214;
/// <summary>
/// <para>(0072,0070) Selector UT Value</para>
/// <para> VR: UT VM:1</para>
/// </summary>
public static SelectorUtValue: number = 7471216;
/// <summary>
/// <para>(0072,0072) Selector DS Value</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static SelectorDsValue: number = 7471218;
/// <summary>
/// <para>(0072,0074) Selector FD Value</para>
/// <para> VR: FD VM:1-n</para>
/// </summary>
public static SelectorFdValue: number = 7471220;
/// <summary>
/// <para>(0072,0076) Selector FL Value</para>
/// <para> VR: FL VM:1-n</para>
/// </summary>
public static SelectorFlValue: number = 7471222;
/// <summary>
/// <para>(0072,0078) Selector UL Value</para>
/// <para> VR: UL VM:1-n</para>
/// </summary>
public static SelectorUlValue: number = 7471224;
/// <summary>
/// <para>(0072,007A) Selector US Value</para>
/// <para> VR: US VM:1-n</para>
/// </summary>
public static SelectorUsValue: number = 7471226;
/// <summary>
/// <para>(0072,007C) Selector SL Value</para>
/// <para> VR: SL VM:1-n</para>
/// </summary>
public static SelectorSlValue: number = 7471228;
/// <summary>
/// <para>(0072,007E) Selector SS Value</para>
/// <para> VR: SS VM:1-n</para>
/// </summary>
public static SelectorSsValue: number = 7471230;
/// <summary>
/// <para>(0072,0080) Selector Code Sequence Value</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SelectorCodeSequenceValue: number = 7471232;
/// <summary>
/// <para>(0072,0100) Number of Screens</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfScreens: number = 7471360;
/// <summary>
/// <para>(0072,0102) Nominal Screen Definition Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static NominalScreenDefinitionSequence: number = 7471362;
/// <summary>
/// <para>(0072,0104) Number of Vertical Pixels</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfVerticalPixels: number = 7471364;
/// <summary>
/// <para>(0072,0106) Number of Horizontal Pixels</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfHorizontalPixels: number = 7471366;
/// <summary>
/// <para>(0072,0108) Display Environment Spatial Position</para>
/// <para> VR: FD VM:4</para>
/// </summary>
public static DisplayEnvironmentSpatialPosition: number = 7471368;
/// <summary>
/// <para>(0072,010A) Screen Minimum Grayscale Bit Depth</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ScreenMinimumGrayscaleBitDepth: number = 7471370;
/// <summary>
/// <para>(0072,010C) Screen Minimum Color Bit Depth</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ScreenMinimumColorBitDepth: number = 7471372;
/// <summary>
/// <para>(0072,010E) Application Maximum Repaint Time</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ApplicationMaximumRepaintTime: number = 7471374;
/// <summary>
/// <para>(0072,0200) Display Sets Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DisplaySetsSequence: number = 7471616;
/// <summary>
/// <para>(0072,0202) Display Set Number</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static DisplaySetNumber: number = 7471618;
/// <summary>
/// <para>(0072,0203) Display Set Label</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static DisplaySetLabel: number = 7471619;
/// <summary>
/// <para>(0072,0204) Display Set Presentation Group</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static DisplaySetPresentationGroup: number = 7471620;
/// <summary>
/// <para>(0072,0206) Display Set Presentation Group Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static DisplaySetPresentationGroupDescription: number = 7471622;
/// <summary>
/// <para>(0072,0208) Partial Data Display Handling</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PartialDataDisplayHandling: number = 7471624;
/// <summary>
/// <para>(0072,0210) Synchronized Scrolling Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SynchronizedScrollingSequence: number = 7471632;
/// <summary>
/// <para>(0072,0212) Display Set Scrolling Group</para>
/// <para> VR: US VM:2-n</para>
/// </summary>
public static DisplaySetScrollingGroup: number = 7471634;
/// <summary>
/// <para>(0072,0214) Navigation Indicator Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static NavigationIndicatorSequence: number = 7471636;
/// <summary>
/// <para>(0072,0216) Navigation Display Set </para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NavigationDisplaySet: number = 7471638;
/// <summary>
/// <para>(0072,0218) Reference Display Sets</para>
/// <para> VR: US VM:1-n</para>
/// </summary>
public static ReferenceDisplaySets: number = 7471640;
/// <summary>
/// <para>(0072,0300) Image Boxes Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ImageBoxesSequence: number = 7471872;
/// <summary>
/// <para>(0072,0302) Image Box Number</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ImageBoxNumber: number = 7471874;
/// <summary>
/// <para>(0072,0304) Image Box Layout Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ImageBoxLayoutType: number = 7471876;
/// <summary>
/// <para>(0072,0306) Image Box Tile Horizontal Dimension</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ImageBoxTileHorizontalDimension: number = 7471878;
/// <summary>
/// <para>(0072,0308) Image Box Tile Vertical Dimension</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ImageBoxTileVerticalDimension: number = 7471880;
/// <summary>
/// <para>(0072,0310) Image Box Scroll Direction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ImageBoxScrollDirection: number = 7471888;
/// <summary>
/// <para>(0072,0312) Image Box Small Scroll Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ImageBoxSmallScrollType: number = 7471890;
/// <summary>
/// <para>(0072,0314) Image Box Small Scroll Amount</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ImageBoxSmallScrollAmount: number = 7471892;
/// <summary>
/// <para>(0072,0316) Image Box Large Scroll Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ImageBoxLargeScrollType: number = 7471894;
/// <summary>
/// <para>(0072,0318) Image Box Large Scroll Amount</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ImageBoxLargeScrollAmount: number = 7471896;
/// <summary>
/// <para>(0072,0320) Image Box Overlap Priority</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ImageBoxOverlapPriority: number = 7471904;
/// <summary>
/// <para>(0072,0330) Cine Relative to Real-Time</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static CineRelativeToRealTime: number = 7471920;
/// <summary>
/// <para>(0072,0400) Filter Operations Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FilterOperationsSequence: number = 7472128;
/// <summary>
/// <para>(0072,0402) Filter-by Category</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FilterByCategory: number = 7472130;
/// <summary>
/// <para>(0072,0404) Filter-by Attribute Presence</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FilterByAttributePresence: number = 7472132;
/// <summary>
/// <para>(0072,0406) Filter-by Operator</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FilterByOperator: number = 7472134;
/// <summary>
/// <para>(0072,0420) Structured Display Background CIELab Value</para>
/// <para> VR: US VM:3</para>
/// </summary>
public static StructuredDisplayBackgroundCielabValue: number = 7472160;
/// <summary>
/// <para>(0072,0421) Empty Image Box CIELab Value</para>
/// <para> VR: US VM:3</para>
/// </summary>
public static EmptyImageBoxCielabValue: number = 7472161;
/// <summary>
/// <para>(0072,0422) Structured Display Image Box Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static StructuredDisplayImageBoxSequence: number = 7472162;
/// <summary>
/// <para>(0072,0424) Structured Display Text Box Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static StructuredDisplayTextBoxSequence: number = 7472164;
/// <summary>
/// <para>(0072,0427) Referenced First Frame Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedFirstFrameSequence: number = 7472167;
/// <summary>
/// <para>(0072,0430) Image Box Synchronization Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ImageBoxSynchronizationSequence: number = 7472176;
/// <summary>
/// <para>(0072,0432) Synchronized Image Box List</para>
/// <para> VR: US VM:2-n</para>
/// </summary>
public static SynchronizedImageBoxList: number = 7472178;
/// <summary>
/// <para>(0072,0434) Type of Synchronization</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TypeOfSynchronization: number = 7472180;
/// <summary>
/// <para>(0072,0500) Blending Operation Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BlendingOperationType: number = 7472384;
/// <summary>
/// <para>(0072,0510) Reformatting Operation Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ReformattingOperationType: number = 7472400;
/// <summary>
/// <para>(0072,0512) Reformatting Thickness</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ReformattingThickness: number = 7472402;
/// <summary>
/// <para>(0072,0514) Reformatting Interval</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ReformattingInterval: number = 7472404;
/// <summary>
/// <para>(0072,0516) Reformatting Operation Initial View Direction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ReformattingOperationInitialViewDirection: number = 7472406;
/// <summary>
/// <para>(0072,0520) 3D Rendering Type</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static ThreeDRenderingType: number = 7472416;
/// <summary>
/// <para>(0072,0600) Sorting Operations Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SortingOperationsSequence: number = 7472640;
/// <summary>
/// <para>(0072,0602) Sort-by Category</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SortByCategory: number = 7472642;
/// <summary>
/// <para>(0072,0604) Sorting Direction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SortingDirection: number = 7472644;
/// <summary>
/// <para>(0072,0700) Display Set Patient Orientation</para>
/// <para> VR: CS VM:2</para>
/// </summary>
public static DisplaySetPatientOrientation: number = 7472896;
/// <summary>
/// <para>(0072,0702) VOI Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static VoiType: number = 7472898;
/// <summary>
/// <para>(0072,0704) Pseudo-Color Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PseudoColorType: number = 7472900;
/// <summary>
/// <para>(0072,0705) Pseudo-Color Palette Instance Reference Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PseudoColorPaletteInstanceReferenceSequence: number = 7472901;
/// <summary>
/// <para>(0072,0706) Show Grayscale Inverted</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ShowGrayscaleInverted: number = 7472902;
/// <summary>
/// <para>(0072,0710) Show Image True Size Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ShowImageTrueSizeFlag: number = 7472912;
/// <summary>
/// <para>(0072,0712) Show Graphic Annotation Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ShowGraphicAnnotationFlag: number = 7472914;
/// <summary>
/// <para>(0072,0714) Show Patient Demographics Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ShowPatientDemographicsFlag: number = 7472916;
/// <summary>
/// <para>(0072,0716) Show Acquisition Techniques Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ShowAcquisitionTechniquesFlag: number = 7472918;
/// <summary>
/// <para>(0072,0717) Display Set Horizontal Justification </para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DisplaySetHorizontalJustification: number = 7472919;
/// <summary>
/// <para>(0072,0718) Display Set Vertical Justification</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DisplaySetVerticalJustification: number = 7472920;
/// <summary>
/// <para>(0074,0120) Continuation Start Meterset</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ContinuationStartMeterset: number = 7602464;
/// <summary>
/// <para>(0074,0121) Continuation End Meterset</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static ContinuationEndMeterset: number = 7602465;
/// <summary>
/// <para>(0074,1000) Procedure Step State</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ProcedureStepState: number = 7606272;
/// <summary>
/// <para>(0074,1002) Procedure Step Progress Information Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ProcedureStepProgressInformationSequence: number = 7606274;
/// <summary>
/// <para>(0074,1004) Procedure Step Progress</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ProcedureStepProgress: number = 7606276;
/// <summary>
/// <para>(0074,1006) Procedure Step Progress Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static ProcedureStepProgressDescription: number = 7606278;
/// <summary>
/// <para>(0074,1008) Procedure Step Communications URI Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ProcedureStepCommunicationsUriSequence: number = 7606280;
/// <summary>
/// <para>(0074,100a) Contact URI</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static ContactUri: number = 7606282;
/// <summary>
/// <para>(0074,100c) Contact Display Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ContactDisplayName: number = 7606284;
/// <summary>
/// <para>(0074,100e) Procedure Step Discontinuation Reason Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ProcedureStepDiscontinuationReasonCodeSequence: number = 7606286;
/// <summary>
/// <para>(0074,1020) Beam Task Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BeamTaskSequence: number = 7606304;
/// <summary>
/// <para>(0074,1022) Beam Task Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BeamTaskType: number = 7606306;
/// <summary>
/// <para>(0074,1024) Beam Order Index (Trial)</para>
/// <para> VR: IS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static BeamOrderIndexTrialRetired: number = 7606308;
/// <summary>
/// <para>(0074,1026) Table Top Vertical Adjusted Position</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TableTopVerticalAdjustedPosition: number = 7606310;
/// <summary>
/// <para>(0074,1027) Table Top Longitudinal Adjusted Position</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TableTopLongitudinalAdjustedPosition: number = 7606311;
/// <summary>
/// <para>(0074,1028) Table Top Lateral Adjusted Position</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TableTopLateralAdjustedPosition: number = 7606312;
/// <summary>
/// <para>(0074,102A) Patient Support Adjusted Angle</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static PatientSupportAdjustedAngle: number = 7606314;
/// <summary>
/// <para>(0074,102B) Table Top Eccentric Adjusted Angle</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TableTopEccentricAdjustedAngle: number = 7606315;
/// <summary>
/// <para>(0074,102C) Table Top Pitch Adjusted Angle</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TableTopPitchAdjustedAngle: number = 7606316;
/// <summary>
/// <para>(0074,102D) Table Top Roll Adjusted Angle</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static TableTopRollAdjustedAngle: number = 7606317;
/// <summary>
/// <para>(0074,1030) Delivery Verification Image Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DeliveryVerificationImageSequence: number = 7606320;
/// <summary>
/// <para>(0074,1032) Verification Image Timing</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static VerificationImageTiming: number = 7606322;
/// <summary>
/// <para>(0074,1034) Double Exposure Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DoubleExposureFlag: number = 7606324;
/// <summary>
/// <para>(0074,1036) Double Exposure Ordering</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DoubleExposureOrdering: number = 7606326;
/// <summary>
/// <para>(0074,1038) Double Exposure Meterset (Trial)</para>
/// <para> VR: DS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DoubleExposureMetersetTrialRetired: number = 7606328;
/// <summary>
/// <para>(0074,103A) Double Exposure Field Delta (Trial)</para>
/// <para> VR: DS VM:4</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DoubleExposureFieldDeltaTrialRetired: number = 7606330;
/// <summary>
/// <para>(0074,1040) Related Reference RT Image Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RelatedReferenceRtImageSequence: number = 7606336;
/// <summary>
/// <para>(0074,1042) General Machine Verification Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static GeneralMachineVerificationSequence: number = 7606338;
/// <summary>
/// <para>(0074,1044) Conventional Machine Verification Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ConventionalMachineVerificationSequence: number = 7606340;
/// <summary>
/// <para>(0074,1046) Ion Machine Verification Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IonMachineVerificationSequence: number = 7606342;
/// <summary>
/// <para>(0074,1048) Failed Attributes Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FailedAttributesSequence: number = 7606344;
/// <summary>
/// <para>(0074,104A) Overridden Attributes Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OverriddenAttributesSequence: number = 7606346;
/// <summary>
/// <para>(0074,104C) Conventional Control Point Verification Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ConventionalControlPointVerificationSequence: number = 7606348;
/// <summary>
/// <para>(0074,104E) Ion Control Point Verification Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IonControlPointVerificationSequence: number = 7606350;
/// <summary>
/// <para>(0074,1050) Attribute Occurrence Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AttributeOccurrenceSequence: number = 7606352;
/// <summary>
/// <para>(0074,1052) Attribute Occurrence Pointer</para>
/// <para> VR: AT VM:1</para>
/// </summary>
public static AttributeOccurrencePointer: number = 7606354;
/// <summary>
/// <para>(0074,1054) Attribute Item Selector</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static AttributeItemSelector: number = 7606356;
/// <summary>
/// <para>(0074,1056) Attribute Occurrence Private Creator</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static AttributeOccurrencePrivateCreator: number = 7606358;
/// <summary>
/// <para>(0074,1057) Selector Sequence Pointer Items</para>
/// <para> VR: IS VM:1-n</para>
/// </summary>
public static SelectorSequencePointerItems: number = 7606359;
/// <summary>
/// <para>(0074,1200) Scheduled Procedure Step Priority</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ScheduledProcedureStepPriority: number = 7606784;
/// <summary>
/// <para>(0074,1202) Worklist Label</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static WorklistLabel: number = 7606786;
/// <summary>
/// <para>(0074,1204) Procedure Step Label</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ProcedureStepLabel: number = 7606788;
/// <summary>
/// <para>(0074,1210) Scheduled Processing Parameters Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ScheduledProcessingParametersSequence: number = 7606800;
/// <summary>
/// <para>(0074,1212) Performed Processing Parameters Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PerformedProcessingParametersSequence: number = 7606802;
/// <summary>
/// <para>(0074,1216) Unified Procedure Step Performed Procedure Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static UnifiedProcedureStepPerformedProcedureSequence: number = 7606806;
/// <summary>
/// <para>(0074,1220) Related Procedure Step Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static RelatedProcedureStepSequenceRetired: number = 7606816;
/// <summary>
/// <para>(0074,1222) Procedure Step Relationship Type</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ProcedureStepRelationshipTypeRetired: number = 7606818;
/// <summary>
/// <para>(0074,1224) Replaced Procedure Step Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReplacedProcedureStepSequence: number = 7606820;
/// <summary>
/// <para>(0074,1230) Deletion Lock</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static DeletionLock: number = 7606832;
/// <summary>
/// <para>(0074,1234) Receiving AE</para>
/// <para> VR: AE VM:1</para>
/// </summary>
public static ReceivingAe: number = 7606836;
/// <summary>
/// <para>(0074,1236) Requesting AE</para>
/// <para> VR: AE VM:1</para>
/// </summary>
public static RequestingAe: number = 7606838;
/// <summary>
/// <para>(0074,1238) Reason for Cancellation</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static ReasonForCancellation: number = 7606840;
/// <summary>
/// <para>(0074,1242) SCP Status</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ScpStatus: number = 7606850;
/// <summary>
/// <para>(0074,1244) Subscription List Status</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SubscriptionListStatus: number = 7606852;
/// <summary>
/// <para>(0074,1246) Unified Procedure Step List Status</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static UnifiedProcedureStepListStatus: number = 7606854;
/// <summary>
/// <para>(0074,1324) Beam Order Index</para>
/// <para> VR: UL VM:1</para>
/// </summary>
public static BeamOrderIndex: number = 7607076;
/// <summary>
/// <para>(0074,1338) Double Exposure Meterset</para>
/// <para> VR: FD VM:1</para>
/// </summary>
public static DoubleExposureMeterset: number = 7607096;
/// <summary>
/// <para>(0074,133A) Double Exposure Field Delta</para>
/// <para> VR: FD VM:4</para>
/// </summary>
public static DoubleExposureFieldDelta: number = 7607098;
/// <summary>
/// <para>(0076,0001) Implant Assembly Template Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ImplantAssemblyTemplateName: number = 7733249;
/// <summary>
/// <para>(0076,0003) Implant Assembly Template Issuer</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ImplantAssemblyTemplateIssuer: number = 7733251;
/// <summary>
/// <para>(0076,0006) Implant Assembly Template Version</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ImplantAssemblyTemplateVersion: number = 7733254;
/// <summary>
/// <para>(0076,0008) Replaced Implant Assembly Template Sequence </para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReplacedImplantAssemblyTemplateSequence: number = 7733256;
/// <summary>
/// <para>(0076,000A) Implant Assembly Template Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ImplantAssemblyTemplateType: number = 7733258;
/// <summary>
/// <para>(0076,000C) Original Implant Assembly Template Sequence </para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OriginalImplantAssemblyTemplateSequence: number = 7733260;
/// <summary>
/// <para>(0076,000E) Derivation Implant Assembly Template Sequence </para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DerivationImplantAssemblyTemplateSequence: number = 7733262;
/// <summary>
/// <para>(0076,0010) Implant Assembly Template Target Anatomy Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ImplantAssemblyTemplateTargetAnatomySequence: number = 7733264;
/// <summary>
/// <para>(0076,0020) Procedure Type Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ProcedureTypeCodeSequence: number = 7733280;
/// <summary>
/// <para>(0076,0030) Surgical Technique </para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SurgicalTechnique: number = 7733296;
/// <summary>
/// <para>(0076,0032) Component Types Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ComponentTypesSequence: number = 7733298;
/// <summary>
/// <para>(0076,0034) Component Type Code Sequence</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ComponentTypeCodeSequence: number = 7733300;
/// <summary>
/// <para>(0076,0036) Exclusive Component Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ExclusiveComponentType: number = 7733302;
/// <summary>
/// <para>(0076,0038) Mandatory Component Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static MandatoryComponentType: number = 7733304;
/// <summary>
/// <para>(0076,0040) Component Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ComponentSequence: number = 7733312;
/// <summary>
/// <para>(0076,0055) Component ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ComponentId: number = 7733333;
/// <summary>
/// <para>(0076,0060) Component Assembly Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ComponentAssemblySequence: number = 7733344;
/// <summary>
/// <para>(0076,0070) Component 1 Referenced ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static Component1ReferencedId: number = 7733360;
/// <summary>
/// <para>(0076,0080) Component 1 Referenced Mating Feature Set ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static Component1ReferencedMatingFeatureSetId: number = 7733376;
/// <summary>
/// <para>(0076,0090) Component 1 Referenced Mating Feature ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static Component1ReferencedMatingFeatureId: number = 7733392;
/// <summary>
/// <para>(0076,00A0) Component 2 Referenced ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static Component2ReferencedId: number = 7733408;
/// <summary>
/// <para>(0076,00B0) Component 2 Referenced Mating Feature Set ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static Component2ReferencedMatingFeatureSetId: number = 7733424;
/// <summary>
/// <para>(0076,00C0) Component 2 Referenced Mating Feature ID </para>
/// <para> VR: US VM:1</para>
/// </summary>
public static Component2ReferencedMatingFeatureId: number = 7733440;
/// <summary>
/// <para>(0078,0001) Implant Template Group Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ImplantTemplateGroupName: number = 7864321;
/// <summary>
/// <para>(0078,0010) Implant Template Group Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static ImplantTemplateGroupDescription: number = 7864336;
/// <summary>
/// <para>(0078,0020) Implant Template Group Issuer</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ImplantTemplateGroupIssuer: number = 7864352;
/// <summary>
/// <para>(0078,0024) Implant Template Group Version</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ImplantTemplateGroupVersion: number = 7864356;
/// <summary>
/// <para>(0078,0026) Replaced Implant Template Group Sequence </para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReplacedImplantTemplateGroupSequence: number = 7864358;
/// <summary>
/// <para>(0078,0028) Implant Template Group Target Anatomy Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ImplantTemplateGroupTargetAnatomySequence: number = 7864360;
/// <summary>
/// <para>(0078,002A) Implant Template Group Members Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ImplantTemplateGroupMembersSequence: number = 7864362;
/// <summary>
/// <para>(0078,002E) Implant Template Group Member ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ImplantTemplateGroupMemberId: number = 7864366;
/// <summary>
/// <para>(0078,0050) 3D Implant Template Group Member Matching Point</para>
/// <para> VR: FD VM:3</para>
/// </summary>
public static ThreeDImplantTemplateGroupMemberMatchingPoint: number = 7864400;
/// <summary>
/// <para>(0078,0060) 3D Implant Template Group Member Matching Axes</para>
/// <para> VR: FD VM:9</para>
/// </summary>
public static ThreeDImplantTemplateGroupMemberMatchingAxes: number = 7864416;
/// <summary>
/// <para>(0078,0070) Implant Template Group Member Matching 2D Coordinates Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ImplantTemplateGroupMemberMatching2dCoordinatesSequence: number = 7864432;
/// <summary>
/// <para>(0078,0090) 2D Implant Template Group Member Matching Point </para>
/// <para> VR: FD VM:2</para>
/// </summary>
public static TwoDImplantTemplateGroupMemberMatchingPoint: number = 7864464;
/// <summary>
/// <para>(0078,00A0) 2D Implant Template Group Member Matching Axes</para>
/// <para> VR: FD VM:4</para>
/// </summary>
public static TwoDImplantTemplateGroupMemberMatchingAxes: number = 7864480;
/// <summary>
/// <para>(0078,00B0) Implant Template Group Variation Dimension Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ImplantTemplateGroupVariationDimensionSequence: number = 7864496;
/// <summary>
/// <para>(0078,00B2) Implant Template Group Variation Dimension Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ImplantTemplateGroupVariationDimensionName: number = 7864498;
/// <summary>
/// <para>(0078,00B4) Implant Template Group Variation Dimension Rank Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ImplantTemplateGroupVariationDimensionRankSequence: number = 7864500;
/// <summary>
/// <para>(0078,00B6) Referenced Implant Template Group Member ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ReferencedImplantTemplateGroupMemberId: number = 7864502;
/// <summary>
/// <para>(0078,00B8) Implant Template Group Variation Dimension Rank</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ImplantTemplateGroupVariationDimensionRank: number = 7864504;
/// <summary>
/// <para>(0088,0130) Storage Media File-set ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static StorageMediaFileSetId: number = 8913200;
/// <summary>
/// <para>(0088,0140) Storage Media File-set UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static StorageMediaFileSetUid: number = 8913216;
/// <summary>
/// <para>(0088,0200) Icon Image Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IconImageSequence: number = 8913408;
/// <summary>
/// <para>(0088,0904) Topic Title</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TopicTitleRetired: number = 8915204;
/// <summary>
/// <para>(0088,0906) Topic Subject</para>
/// <para> VR: ST VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TopicSubjectRetired: number = 8915206;
/// <summary>
/// <para>(0088,0910) Topic Author</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TopicAuthorRetired: number = 8915216;
/// <summary>
/// <para>(0088,0912) Topic Keywords</para>
/// <para> VR: LO VM:1-32</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TopicKeywordsRetired: number = 8915218;
/// <summary>
/// <para>(0100,0410) SOP Instance Status</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SopInstanceStatus: number = 16778256;
/// <summary>
/// <para>(0100,0420) SOP Authorization DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static SopAuthorizationDatetime: number = 16778272;
/// <summary>
/// <para>(0100,0424) SOP Authorization Comment</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static SopAuthorizationComment: number = 16778276;
/// <summary>
/// <para>(0100,0426) Authorization Equipment Certification Number</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static AuthorizationEquipmentCertificationNumber: number = 16778278;
/// <summary>
/// <para>(0400,0005) MAC ID Number</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static MacIdNumber: number = 67108869;
/// <summary>
/// <para>(0400,0010) MAC Calculation Transfer Syntax UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static MacCalculationTransferSyntaxUid: number = 67108880;
/// <summary>
/// <para>(0400,0015) MAC Algorithm</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static MacAlgorithm: number = 67108885;
/// <summary>
/// <para>(0400,0020) Data Elements Signed</para>
/// <para> VR: AT VM:1-n</para>
/// </summary>
public static DataElementsSigned: number = 67108896;
/// <summary>
/// <para>(0400,0100) Digital Signature UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static DigitalSignatureUid: number = 67109120;
/// <summary>
/// <para>(0400,0105) Digital Signature DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static DigitalSignatureDatetime: number = 67109125;
/// <summary>
/// <para>(0400,0110) Certificate Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CertificateType: number = 67109136;
/// <summary>
/// <para>(0400,0115) Certificate of Signer</para>
/// <para> VR: OB VM:1</para>
/// </summary>
public static CertificateOfSigner: number = 67109141;
/// <summary>
/// <para>(0400,0120) Signature</para>
/// <para> VR: OB VM:1</para>
/// </summary>
public static Signature: number = 67109152;
/// <summary>
/// <para>(0400,0305) Certified Timestamp Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CertifiedTimestampType: number = 67109637;
/// <summary>
/// <para>(0400,0310) Certified Timestamp</para>
/// <para> VR: OB VM:1</para>
/// </summary>
public static CertifiedTimestamp: number = 67109648;
/// <summary>
/// <para>(0400,0401) Digital Signature Purpose Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DigitalSignaturePurposeCodeSequence: number = 67109889;
/// <summary>
/// <para>(0400,0402) Referenced Digital Signature Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedDigitalSignatureSequence: number = 67109890;
/// <summary>
/// <para>(0400,0403) Referenced SOP Instance MAC Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedSopInstanceMacSequence: number = 67109891;
/// <summary>
/// <para>(0400,0404) MAC</para>
/// <para> VR: OB VM:1</para>
/// </summary>
public static Mac: number = 67109892;
/// <summary>
/// <para>(0400,0500) Encrypted Attributes Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static EncryptedAttributesSequence: number = 67110144;
/// <summary>
/// <para>(0400,0510) Encrypted Content Transfer Syntax UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static EncryptedContentTransferSyntaxUid: number = 67110160;
/// <summary>
/// <para>(0400,0520) Encrypted Content</para>
/// <para> VR: OB VM:1</para>
/// </summary>
public static EncryptedContent: number = 67110176;
/// <summary>
/// <para>(0400,0550) Modified Attributes Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ModifiedAttributesSequence: number = 67110224;
/// <summary>
/// <para>(0400,0561) Original Attributes Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OriginalAttributesSequence: number = 67110241;
/// <summary>
/// <para>(0400,0562) Attribute Modification DateTime</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static AttributeModificationDatetime: number = 67110242;
/// <summary>
/// <para>(0400,0563) Modifying System</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ModifyingSystem: number = 67110243;
/// <summary>
/// <para>(0400,0564) Source of Previous Values</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SourceOfPreviousValues: number = 67110244;
/// <summary>
/// <para>(0400,0565) Reason for the Attribute Modification</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ReasonForTheAttributeModification: number = 67110245;
/// <summary>
/// <para>(2000,0010) Number of Copies</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfCopies: number = 536870928;
/// <summary>
/// <para>(2000,001E) Printer Configuration Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PrinterConfigurationSequence: number = 536870942;
/// <summary>
/// <para>(2000,0020) Print Priority</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PrintPriority: number = 536870944;
/// <summary>
/// <para>(2000,0030) Medium Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static MediumType: number = 536870960;
/// <summary>
/// <para>(2000,0040) Film Destination</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FilmDestination: number = 536870976;
/// <summary>
/// <para>(2000,0050) Film Session Label</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static FilmSessionLabel: number = 536870992;
/// <summary>
/// <para>(2000,0060) Memory Allocation</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static MemoryAllocation: number = 536871008;
/// <summary>
/// <para>(2000,0061) Maximum Memory Allocation</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static MaximumMemoryAllocation: number = 536871009;
/// <summary>
/// <para>(2000,0062) Color Image Printing Flag</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ColorImagePrintingFlagRetired: number = 536871010;
/// <summary>
/// <para>(2000,0063) Collation Flag</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CollationFlagRetired: number = 536871011;
/// <summary>
/// <para>(2000,0065) Annotation Flag</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AnnotationFlagRetired: number = 536871013;
/// <summary>
/// <para>(2000,0067) Image Overlay Flag</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ImageOverlayFlagRetired: number = 536871015;
/// <summary>
/// <para>(2000,0069) Presentation LUT Flag</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PresentationLutFlagRetired: number = 536871017;
/// <summary>
/// <para>(2000,006A) Image Box Presentation LUT Flag</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ImageBoxPresentationLutFlagRetired: number = 536871018;
/// <summary>
/// <para>(2000,00A0) Memory Bit Depth</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static MemoryBitDepth: number = 536871072;
/// <summary>
/// <para>(2000,00A1) Printing Bit Depth</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static PrintingBitDepth: number = 536871073;
/// <summary>
/// <para>(2000,00A2) Media Installed Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MediaInstalledSequence: number = 536871074;
/// <summary>
/// <para>(2000,00A4) Other Media Available Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OtherMediaAvailableSequence: number = 536871076;
/// <summary>
/// <para>(2000,00A8) Supported Image Display Formats Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SupportedImageDisplayFormatsSequence: number = 536871080;
/// <summary>
/// <para>(2000,0500) Referenced Film Box Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedFilmBoxSequence: number = 536872192;
/// <summary>
/// <para>(2000,0510) Referenced Stored Print Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferencedStoredPrintSequenceRetired: number = 536872208;
/// <summary>
/// <para>(2010,0010) Image Display Format</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static ImageDisplayFormat: number = 537919504;
/// <summary>
/// <para>(2010,0030) Annotation Display Format ID</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AnnotationDisplayFormatId: number = 537919536;
/// <summary>
/// <para>(2010,0040) Film Orientation</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FilmOrientation: number = 537919552;
/// <summary>
/// <para>(2010,0050) Film Size ID</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FilmSizeId: number = 537919568;
/// <summary>
/// <para>(2010,0052) Printer Resolution ID</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PrinterResolutionId: number = 537919570;
/// <summary>
/// <para>(2010,0054) Default Printer Resolution ID</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DefaultPrinterResolutionId: number = 537919572;
/// <summary>
/// <para>(2010,0060) Magnification Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static MagnificationType: number = 537919584;
/// <summary>
/// <para>(2010,0080) Smoothing Type </para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SmoothingType: number = 537919616;
/// <summary>
/// <para>(2010,00A6) Default Magnification Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DefaultMagnificationType: number = 537919654;
/// <summary>
/// <para>(2010,00A7) Other Magnification Types Available</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static OtherMagnificationTypesAvailable: number = 537919655;
/// <summary>
/// <para>(2010,00A8) Default Smoothing Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DefaultSmoothingType: number = 537919656;
/// <summary>
/// <para>(2010,00A9) Other Smoothing Types Available</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static OtherSmoothingTypesAvailable: number = 537919657;
/// <summary>
/// <para>(2010,0100) Border Density</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BorderDensity: number = 537919744;
/// <summary>
/// <para>(2010,0110) Empty Image Density</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static EmptyImageDensity: number = 537919760;
/// <summary>
/// <para>(2010,0120) Min Density</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static MinDensity: number = 537919776;
/// <summary>
/// <para>(2010,0130) Max Density</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static MaxDensity: number = 537919792;
/// <summary>
/// <para>(2010,0140) Trim</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static Trim: number = 537919808;
/// <summary>
/// <para>(2010,0150) Configuration Information</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static ConfigurationInformation: number = 537919824;
/// <summary>
/// <para>(2010,0152) Configuration Information Description</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static ConfigurationInformationDescription: number = 537919826;
/// <summary>
/// <para>(2010,0154) Maximum Collated Films</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static MaximumCollatedFilms: number = 537919828;
/// <summary>
/// <para>(2010,015E) Illumination</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static Illumination: number = 537919838;
/// <summary>
/// <para>(2010,0160) Reflected Ambient Light</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ReflectedAmbientLight: number = 537919840;
/// <summary>
/// <para>(2010,0376) Printer Pixel Spacing</para>
/// <para> VR: DS VM:2</para>
/// </summary>
public static PrinterPixelSpacing: number = 537920374;
/// <summary>
/// <para>(2010,0500) Referenced Film Session Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedFilmSessionSequence: number = 537920768;
/// <summary>
/// <para>(2010,0510) Referenced Image Box Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedImageBoxSequence: number = 537920784;
/// <summary>
/// <para>(2010,0520) Referenced Basic Annotation Box Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedBasicAnnotationBoxSequence: number = 537920800;
/// <summary>
/// <para>(2020,0010) Image Box Position</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ImageBoxPosition: number = 538968080;
/// <summary>
/// <para>(2020,0020) Polarity</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static Polarity: number = 538968096;
/// <summary>
/// <para>(2020,0030) Requested Image Size</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static RequestedImageSize: number = 538968112;
/// <summary>
/// <para>(2020,0040) Requested Decimate/Crop Behavior</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RequestedDecimateCropBehavior: number = 538968128;
/// <summary>
/// <para>(2020,0050) Requested Resolution ID</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RequestedResolutionId: number = 538968144;
/// <summary>
/// <para>(2020,00A0) Requested Image Size Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RequestedImageSizeFlag: number = 538968224;
/// <summary>
/// <para>(2020,00A2) Decimate/Crop Result</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DecimateCropResult: number = 538968226;
/// <summary>
/// <para>(2020,0110) Basic Grayscale Image Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BasicGrayscaleImageSequence: number = 538968336;
/// <summary>
/// <para>(2020,0111) Basic Color Image Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BasicColorImageSequence: number = 538968337;
/// <summary>
/// <para>(2020,0130) Referenced Image Overlay Box Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferencedImageOverlayBoxSequenceRetired: number = 538968368;
/// <summary>
/// <para>(2020,0140) Referenced VOI LUT Box Sequence </para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferencedVoiLutBoxSequenceRetired: number = 538968384;
/// <summary>
/// <para>(2030,0010) Annotation Position</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static AnnotationPosition: number = 540016656;
/// <summary>
/// <para>(2030,0020) Text String</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static TextString: number = 540016672;
/// <summary>
/// <para>(2040,0010) Referenced Overlay Plane Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferencedOverlayPlaneSequenceRetired: number = 541065232;
/// <summary>
/// <para>(2040,0011) Referenced Overlay Plane Groups</para>
/// <para> VR: US VM:1-99</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferencedOverlayPlaneGroupsRetired: number = 541065233;
/// <summary>
/// <para>(2040,0020) Overlay Pixel Data Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayPixelDataSequenceRetired: number = 541065248;
/// <summary>
/// <para>(2040,0060) Overlay Magnification Type</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayMagnificationTypeRetired: number = 541065312;
/// <summary>
/// <para>(2040,0070) Overlay Smoothing Type</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlaySmoothingTypeRetired: number = 541065328;
/// <summary>
/// <para>(2040,0072) Overlay or Image Magnification</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayOrImageMagnificationRetired: number = 541065330;
/// <summary>
/// <para>(2040,0074) Magnify to Number of Columns</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static MagnifyToNumberOfColumnsRetired: number = 541065332;
/// <summary>
/// <para>(2040,0080) Overlay Foreground Density</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayForegroundDensityRetired: number = 541065344;
/// <summary>
/// <para>(2040,0082) Overlay Background Density</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayBackgroundDensityRetired: number = 541065346;
/// <summary>
/// <para>(2040,0090) Overlay Mode</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayModeRetired: number = 541065360;
/// <summary>
/// <para>(2040,0100) Threshold Density</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ThresholdDensityRetired: number = 541065472;
/// <summary>
/// <para>(2040,0500) Referenced Image Box Sequence (Retired)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferencedImageBoxSequenceRetired: number = 541066496;
/// <summary>
/// <para>(2050,0010) Presentation LUT Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PresentationLutSequence: number = 542113808;
/// <summary>
/// <para>(2050,0020) Presentation LUT Shape</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PresentationLutShape: number = 542113824;
/// <summary>
/// <para>(2050,0500) Referenced Presentation LUT Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedPresentationLutSequence: number = 542115072;
/// <summary>
/// <para>(2100,0010) Print Job ID</para>
/// <para> VR: SH VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PrintJobIdRetired: number = 553648144;
/// <summary>
/// <para>(2100,0020) Execution Status</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ExecutionStatus: number = 553648160;
/// <summary>
/// <para>(2100,0030) Execution Status Info</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ExecutionStatusInfo: number = 553648176;
/// <summary>
/// <para>(2100,0040) Creation Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static CreationDate: number = 553648192;
/// <summary>
/// <para>(2100,0050) Creation Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static CreationTime: number = 553648208;
/// <summary>
/// <para>(2100,0070) Originator</para>
/// <para> VR: AE VM:1</para>
/// </summary>
public static Originator: number = 553648240;
/// <summary>
/// <para>(2100,0140) Destination AE</para>
/// <para> VR: AE VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DestinationAeRetired: number = 553648448;
/// <summary>
/// <para>(2100,0160) Owner ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static OwnerId: number = 553648480;
/// <summary>
/// <para>(2100,0170) Number of Films</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfFilms: number = 553648496;
/// <summary>
/// <para>(2100,0500) Referenced Print Job Sequence (Pull Stored Print)</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferencedPrintJobSequencePullStoredPrintRetired: number = 553649408;
/// <summary>
/// <para>(2110,0010) Printer Status</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PrinterStatus: number = 554696720;
/// <summary>
/// <para>(2110,0020) Printer Status Info</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PrinterStatusInfo: number = 554696736;
/// <summary>
/// <para>(2110,0030) Printer Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PrinterName: number = 554696752;
/// <summary>
/// <para>(2110,0099) Print Queue ID</para>
/// <para> VR: SH VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PrintQueueIdRetired: number = 554696857;
/// <summary>
/// <para>(2120,0010) Queue Status</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static QueueStatusRetired: number = 555745296;
/// <summary>
/// <para>(2120,0050) Print Job Description Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PrintJobDescriptionSequenceRetired: number = 555745360;
/// <summary>
/// <para>(2120,0070) Referenced Print Job Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferencedPrintJobSequenceRetired: number = 555745392;
/// <summary>
/// <para>(2130,0010) Print Management Capabilities Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PrintManagementCapabilitiesSequenceRetired: number = 556793872;
/// <summary>
/// <para>(2130,0015) Printer Characteristics Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PrinterCharacteristicsSequenceRetired: number = 556793877;
/// <summary>
/// <para>(2130,0030) Film Box Content Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static FilmBoxContentSequenceRetired: number = 556793904;
/// <summary>
/// <para>(2130,0040) Image Box Content Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ImageBoxContentSequenceRetired: number = 556793920;
/// <summary>
/// <para>(2130,0050) Annotation Content Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AnnotationContentSequenceRetired: number = 556793936;
/// <summary>
/// <para>(2130,0060) Image Overlay Box Content Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ImageOverlayBoxContentSequenceRetired: number = 556793952;
/// <summary>
/// <para>(2130,0080) Presentation LUT Content Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PresentationLutContentSequenceRetired: number = 556793984;
/// <summary>
/// <para>(2130,00A0) Proposed Study Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ProposedStudySequenceRetired: number = 556794016;
/// <summary>
/// <para>(2130,00C0) Original Image Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OriginalImageSequenceRetired: number = 556794048;
/// <summary>
/// <para>(2200,0001) Label Using Information Extracted From Instances</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static LabelUsingInformationExtractedFromInstances: number = 570425345;
/// <summary>
/// <para>(2200,0002) Label Text</para>
/// <para> VR: UT VM:1</para>
/// </summary>
public static LabelText: number = 570425346;
/// <summary>
/// <para>(2200,0003) Label Style Selection</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static LabelStyleSelection: number = 570425347;
/// <summary>
/// <para>(2200,0004) Media Disposition</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static MediaDisposition: number = 570425348;
/// <summary>
/// <para>(2200,0005) Barcode Value</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static BarcodeValue: number = 570425349;
/// <summary>
/// <para>(2200,0006) Barcode Symbology</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BarcodeSymbology: number = 570425350;
/// <summary>
/// <para>(2200,0007) Allow Media Splitting</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AllowMediaSplitting: number = 570425351;
/// <summary>
/// <para>(2200,0008) Include Non-DICOM Objects</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static IncludeNonDicomObjects: number = 570425352;
/// <summary>
/// <para>(2200,0009) Include Display Application</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static IncludeDisplayApplication: number = 570425353;
/// <summary>
/// <para>(2200,000A) Preserve Composite Instances After Media Creation</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PreserveCompositeInstancesAfterMediaCreation: number = 570425354;
/// <summary>
/// <para>(2200,000B) Total Number of Pieces of Media Created</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static TotalNumberOfPiecesOfMediaCreated: number = 570425355;
/// <summary>
/// <para>(2200,000C) Requested Media Application Profile</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static RequestedMediaApplicationProfile: number = 570425356;
/// <summary>
/// <para>(2200,000D) Referenced Storage Media Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedStorageMediaSequence: number = 570425357;
/// <summary>
/// <para>(2200,000E) Failure Attributes</para>
/// <para> VR: AT VM:1-n</para>
/// </summary>
public static FailureAttributes: number = 570425358;
/// <summary>
/// <para>(2200,000F) Allow Lossy Compression</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AllowLossyCompression: number = 570425359;
/// <summary>
/// <para>(2200,0020) Request Priority</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RequestPriority: number = 570425376;
/// <summary>
/// <para>(3002,0002) RT Image Label</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static RtImageLabel: number = 805437442;
/// <summary>
/// <para>(3002,0003) RT Image Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static RtImageName: number = 805437443;
/// <summary>
/// <para>(3002,0004) RT Image Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static RtImageDescription: number = 805437444;
/// <summary>
/// <para>(3002,000A) Reported Values Origin</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ReportedValuesOrigin: number = 805437450;
/// <summary>
/// <para>(3002,000C) RT Image Plane</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RtImagePlane: number = 805437452;
/// <summary>
/// <para>(3002,000D) X-Ray Image Receptor Translation</para>
/// <para> VR: DS VM:3</para>
/// </summary>
public static XRayImageReceptorTranslation: number = 805437453;
/// <summary>
/// <para>(3002,000E) X-Ray Image Receptor Angle</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static XRayImageReceptorAngle: number = 805437454;
/// <summary>
/// <para>(3002,0010) RT Image Orientation</para>
/// <para> VR: DS VM:6</para>
/// </summary>
public static RtImageOrientation: number = 805437456;
/// <summary>
/// <para>(3002,0011) Image Plane Pixel Spacing</para>
/// <para> VR: DS VM:2</para>
/// </summary>
public static ImagePlanePixelSpacing: number = 805437457;
/// <summary>
/// <para>(3002,0012) RT Image Position</para>
/// <para> VR: DS VM:2</para>
/// </summary>
public static RtImagePosition: number = 805437458;
/// <summary>
/// <para>(3002,0020) Radiation Machine Name</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static RadiationMachineName: number = 805437472;
/// <summary>
/// <para>(3002,0022) Radiation Machine SAD</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static RadiationMachineSad: number = 805437474;
/// <summary>
/// <para>(3002,0024) Radiation Machine SSD</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static RadiationMachineSsd: number = 805437476;
/// <summary>
/// <para>(3002,0026) RT Image SID</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static RtImageSid: number = 805437478;
/// <summary>
/// <para>(3002,0028) Source to Reference Object Distance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SourceToReferenceObjectDistance: number = 805437480;
/// <summary>
/// <para>(3002,0029) Fraction Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static FractionNumber: number = 805437481;
/// <summary>
/// <para>(3002,0030) Exposure Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ExposureSequence: number = 805437488;
/// <summary>
/// <para>(3002,0032) Meterset Exposure</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static MetersetExposure: number = 805437490;
/// <summary>
/// <para>(3002,0034) Diaphragm Position</para>
/// <para> VR: DS VM:4</para>
/// </summary>
public static DiaphragmPosition: number = 805437492;
/// <summary>
/// <para>(3002,0040) Fluence Map Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FluenceMapSequence: number = 805437504;
/// <summary>
/// <para>(3002,0041) Fluence Data Source</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FluenceDataSource: number = 805437505;
/// <summary>
/// <para>(3002,0042) Fluence Data Scale</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static FluenceDataScale: number = 805437506;
/// <summary>
/// <para>(3002,0050) Primary Fluence Mode Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PrimaryFluenceModeSequence: number = 805437520;
/// <summary>
/// <para>(3002,0051) Fluence Mode</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FluenceMode: number = 805437521;
/// <summary>
/// <para>(3002,0052) Fluence Mode ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static FluenceModeId: number = 805437522;
/// <summary>
/// <para>(3004,0001) DVH Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DvhType: number = 805568513;
/// <summary>
/// <para>(3004,0002) Dose Units</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DoseUnits: number = 805568514;
/// <summary>
/// <para>(3004,0004) Dose Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DoseType: number = 805568516;
/// <summary>
/// <para>(3004,0006) Dose Comment</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static DoseComment: number = 805568518;
/// <summary>
/// <para>(3004,0008) Normalization Point</para>
/// <para> VR: DS VM:3</para>
/// </summary>
public static NormalizationPoint: number = 805568520;
/// <summary>
/// <para>(3004,000A) Dose Summation Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DoseSummationType: number = 805568522;
/// <summary>
/// <para>(3004,000C) Grid Frame Offset Vector</para>
/// <para> VR: DS VM:2-n</para>
/// </summary>
public static GridFrameOffsetVector: number = 805568524;
/// <summary>
/// <para>(3004,000E) Dose Grid Scaling</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DoseGridScaling: number = 805568526;
/// <summary>
/// <para>(3004,0010) RT Dose ROI Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RtDoseRoiSequence: number = 805568528;
/// <summary>
/// <para>(3004,0012) Dose Value</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DoseValue: number = 805568530;
/// <summary>
/// <para>(3004,0014) Tissue Heterogeneity Correction</para>
/// <para> VR: CS VM:1-3</para>
/// </summary>
public static TissueHeterogeneityCorrection: number = 805568532;
/// <summary>
/// <para>(3004,0040) DVH Normalization Point</para>
/// <para> VR: DS VM:3</para>
/// </summary>
public static DvhNormalizationPoint: number = 805568576;
/// <summary>
/// <para>(3004,0042) DVH Normalization Dose Value</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DvhNormalizationDoseValue: number = 805568578;
/// <summary>
/// <para>(3004,0050) DVH Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DvhSequence: number = 805568592;
/// <summary>
/// <para>(3004,0052) DVH Dose Scaling</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DvhDoseScaling: number = 805568594;
/// <summary>
/// <para>(3004,0054) DVH Volume Units</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DvhVolumeUnits: number = 805568596;
/// <summary>
/// <para>(3004,0056) DVH Number of Bins</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static DvhNumberOfBins: number = 805568598;
/// <summary>
/// <para>(3004,0058) DVH Data</para>
/// <para> VR: DS VM:2-2n</para>
/// </summary>
public static DvhData: number = 805568600;
/// <summary>
/// <para>(3004,0060) DVH Referenced ROI Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DvhReferencedRoiSequence: number = 805568608;
/// <summary>
/// <para>(3004,0062) DVH ROI Contribution Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DvhRoiContributionType: number = 805568610;
/// <summary>
/// <para>(3004,0070) DVH Minimum Dose</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DvhMinimumDose: number = 805568624;
/// <summary>
/// <para>(3004,0072) DVH Maximum Dose</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DvhMaximumDose: number = 805568626;
/// <summary>
/// <para>(3004,0074) DVH Mean Dose</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DvhMeanDose: number = 805568628;
/// <summary>
/// <para>(3006,0002) Structure Set Label</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static StructureSetLabel: number = 805699586;
/// <summary>
/// <para>(3006,0004) Structure Set Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static StructureSetName: number = 805699588;
/// <summary>
/// <para>(3006,0006) Structure Set Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static StructureSetDescription: number = 805699590;
/// <summary>
/// <para>(3006,0008) Structure Set Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static StructureSetDate: number = 805699592;
/// <summary>
/// <para>(3006,0009) Structure Set Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static StructureSetTime: number = 805699593;
/// <summary>
/// <para>(3006,0010) Referenced Frame of Reference Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedFrameOfReferenceSequence: number = 805699600;
/// <summary>
/// <para>(3006,0012) RT Referenced Study Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RtReferencedStudySequence: number = 805699602;
/// <summary>
/// <para>(3006,0014) RT Referenced Series Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RtReferencedSeriesSequence: number = 805699604;
/// <summary>
/// <para>(3006,0016) Contour Image Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ContourImageSequence: number = 805699606;
/// <summary>
/// <para>(3006,0020) Structure Set ROI Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static StructureSetRoiSequence: number = 805699616;
/// <summary>
/// <para>(3006,0022) ROI Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static RoiNumber: number = 805699618;
/// <summary>
/// <para>(3006,0024) Referenced Frame of Reference UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static ReferencedFrameOfReferenceUid: number = 805699620;
/// <summary>
/// <para>(3006,0026) ROI Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static RoiName: number = 805699622;
/// <summary>
/// <para>(3006,0028) ROI Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static RoiDescription: number = 805699624;
/// <summary>
/// <para>(3006,002A) ROI Display Color</para>
/// <para> VR: IS VM:3</para>
/// </summary>
public static RoiDisplayColor: number = 805699626;
/// <summary>
/// <para>(3006,002C) ROI Volume</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static RoiVolume: number = 805699628;
/// <summary>
/// <para>(3006,0030) RT Related ROI Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RtRelatedRoiSequence: number = 805699632;
/// <summary>
/// <para>(3006,0033) RT ROI Relationship</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RtRoiRelationship: number = 805699635;
/// <summary>
/// <para>(3006,0036) ROI Generation Algorithm</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RoiGenerationAlgorithm: number = 805699638;
/// <summary>
/// <para>(3006,0038) ROI Generation Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static RoiGenerationDescription: number = 805699640;
/// <summary>
/// <para>(3006,0039) ROI Contour Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RoiContourSequence: number = 805699641;
/// <summary>
/// <para>(3006,0040) Contour Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ContourSequence: number = 805699648;
/// <summary>
/// <para>(3006,0042) Contour Geometric Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ContourGeometricType: number = 805699650;
/// <summary>
/// <para>(3006,0044) Contour Slab Thickness</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ContourSlabThickness: number = 805699652;
/// <summary>
/// <para>(3006,0045) Contour Offset Vector</para>
/// <para> VR: DS VM:3</para>
/// </summary>
public static ContourOffsetVector: number = 805699653;
/// <summary>
/// <para>(3006,0046) Number of Contour Points</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfContourPoints: number = 805699654;
/// <summary>
/// <para>(3006,0048) Contour Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ContourNumber: number = 805699656;
/// <summary>
/// <para>(3006,0049) Attached Contours</para>
/// <para> VR: IS VM:1-n</para>
/// </summary>
public static AttachedContours: number = 805699657;
/// <summary>
/// <para>(3006,0050) Contour Data</para>
/// <para> VR: DS VM:3-3n</para>
/// </summary>
public static ContourData: number = 805699664;
/// <summary>
/// <para>(3006,0080) RT ROI Observations Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RtRoiObservationsSequence: number = 805699712;
/// <summary>
/// <para>(3006,0082) Observation Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ObservationNumber: number = 805699714;
/// <summary>
/// <para>(3006,0084) Referenced ROI Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedRoiNumber: number = 805699716;
/// <summary>
/// <para>(3006,0085) ROI Observation Label</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static RoiObservationLabel: number = 805699717;
/// <summary>
/// <para>(3006,0086) RT ROI Identification Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RtRoiIdentificationCodeSequence: number = 805699718;
/// <summary>
/// <para>(3006,0088) ROI Observation Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static RoiObservationDescription: number = 805699720;
/// <summary>
/// <para>(3006,00A0) Related RT ROI Observations Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RelatedRtRoiObservationsSequence: number = 805699744;
/// <summary>
/// <para>(3006,00A4) RT ROI Interpreted Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RtRoiInterpretedType: number = 805699748;
/// <summary>
/// <para>(3006,00A6) ROI Interpreter</para>
/// <para> VR: PN VM:1</para>
/// </summary>
public static RoiInterpreter: number = 805699750;
/// <summary>
/// <para>(3006,00B0) ROI Physical Properties Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RoiPhysicalPropertiesSequence: number = 805699760;
/// <summary>
/// <para>(3006,00B2) ROI Physical Property</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RoiPhysicalProperty: number = 805699762;
/// <summary>
/// <para>(3006,00B4) ROI Physical Property Value</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static RoiPhysicalPropertyValue: number = 805699764;
/// <summary>
/// <para>(3006,00B6) ROI Elemental Composition Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RoiElementalCompositionSequence: number = 805699766;
/// <summary>
/// <para>(3006,00B7) ROI Elemental Composition Atomic Number</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static RoiElementalCompositionAtomicNumber: number = 805699767;
/// <summary>
/// <para>(3006,00B8) ROI Elemental Composition Atomic Mass Fraction</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static RoiElementalCompositionAtomicMassFraction: number = 805699768;
/// <summary>
/// <para>(3006,00C0) Frame of Reference Relationship Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FrameOfReferenceRelationshipSequence: number = 805699776;
/// <summary>
/// <para>(3006,00C2) Related Frame of Reference UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static RelatedFrameOfReferenceUid: number = 805699778;
/// <summary>
/// <para>(3006,00C4) Frame of Reference Transformation Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FrameOfReferenceTransformationType: number = 805699780;
/// <summary>
/// <para>(3006,00C6) Frame of Reference Transformation Matrix</para>
/// <para> VR: DS VM:16</para>
/// </summary>
public static FrameOfReferenceTransformationMatrix: number = 805699782;
/// <summary>
/// <para>(3006,00C8) Frame of Reference Transformation Comment</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static FrameOfReferenceTransformationComment: number = 805699784;
/// <summary>
/// <para>(3008,0010) Measured Dose Reference Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MeasuredDoseReferenceSequence: number = 805830672;
/// <summary>
/// <para>(3008,0012) Measured Dose Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static MeasuredDoseDescription: number = 805830674;
/// <summary>
/// <para>(3008,0014) Measured Dose Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static MeasuredDoseType: number = 805830676;
/// <summary>
/// <para>(3008,0016) Measured Dose Value</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static MeasuredDoseValue: number = 805830678;
/// <summary>
/// <para>(3008,0020) Treatment Session Beam Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TreatmentSessionBeamSequence: number = 805830688;
/// <summary>
/// <para>(3008,0021) Treatment Session Ion Beam Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TreatmentSessionIonBeamSequence: number = 805830689;
/// <summary>
/// <para>(3008,0022) Current Fraction Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static CurrentFractionNumber: number = 805830690;
/// <summary>
/// <para>(3008,0024) Treatment Control Point Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static TreatmentControlPointDate: number = 805830692;
/// <summary>
/// <para>(3008,0025) Treatment Control Point Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static TreatmentControlPointTime: number = 805830693;
/// <summary>
/// <para>(3008,002A) Treatment Termination Status</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TreatmentTerminationStatus: number = 805830698;
/// <summary>
/// <para>(3008,002B) Treatment Termination Code</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static TreatmentTerminationCode: number = 805830699;
/// <summary>
/// <para>(3008,002C) Treatment Verification Status</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TreatmentVerificationStatus: number = 805830700;
/// <summary>
/// <para>(3008,0030) Referenced Treatment Record Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedTreatmentRecordSequence: number = 805830704;
/// <summary>
/// <para>(3008,0032) Specified Primary Meterset </para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SpecifiedPrimaryMeterset: number = 805830706;
/// <summary>
/// <para>(3008,0033) Specified Secondary Meterset </para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SpecifiedSecondaryMeterset: number = 805830707;
/// <summary>
/// <para>(3008,0036) Delivered Primary Meterset </para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DeliveredPrimaryMeterset: number = 805830710;
/// <summary>
/// <para>(3008,0037) Delivered Secondary Meterset </para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DeliveredSecondaryMeterset: number = 805830711;
/// <summary>
/// <para>(3008,003A) Specified Treatment Time</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SpecifiedTreatmentTime: number = 805830714;
/// <summary>
/// <para>(3008,003B) Delivered Treatment Time</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DeliveredTreatmentTime: number = 805830715;
/// <summary>
/// <para>(3008,0040) Control Point Delivery Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ControlPointDeliverySequence: number = 805830720;
/// <summary>
/// <para>(3008,0041) Ion Control Point Delivery Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IonControlPointDeliverySequence: number = 805830721;
/// <summary>
/// <para>(3008,0042) Specified Meterset</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SpecifiedMeterset: number = 805830722;
/// <summary>
/// <para>(3008,0044) Delivered Meterset</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DeliveredMeterset: number = 805830724;
/// <summary>
/// <para>(3008,0045) Meterset Rate Set</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static MetersetRateSet: number = 805830725;
/// <summary>
/// <para>(3008,0046) Meterset Rate Delivered</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static MetersetRateDelivered: number = 805830726;
/// <summary>
/// <para>(3008,0047) Scan Spot Metersets Delivered</para>
/// <para> VR: FL VM:1-n</para>
/// </summary>
public static ScanSpotMetersetsDelivered: number = 805830727;
/// <summary>
/// <para>(3008,0048) Dose Rate Delivered</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DoseRateDelivered: number = 805830728;
/// <summary>
/// <para>(3008,0050) Treatment Summary Calculated Dose Reference Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TreatmentSummaryCalculatedDoseReferenceSequence: number = 805830736;
/// <summary>
/// <para>(3008,0052) Cumulative Dose to Dose Reference</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static CumulativeDoseToDoseReference: number = 805830738;
/// <summary>
/// <para>(3008,0054) First Treatment Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static FirstTreatmentDate: number = 805830740;
/// <summary>
/// <para>(3008,0056) Most Recent Treatment Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static MostRecentTreatmentDate: number = 805830742;
/// <summary>
/// <para>(3008,005A) Number of Fractions Delivered</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfFractionsDelivered: number = 805830746;
/// <summary>
/// <para>(3008,0060) Override Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OverrideSequence: number = 805830752;
/// <summary>
/// <para>(3008,0061) Parameter Sequence Pointer</para>
/// <para> VR: AT VM:1</para>
/// </summary>
public static ParameterSequencePointer: number = 805830753;
/// <summary>
/// <para>(3008,0062) Override Parameter Pointer</para>
/// <para> VR: AT VM:1</para>
/// </summary>
public static OverrideParameterPointer: number = 805830754;
/// <summary>
/// <para>(3008,0063) Parameter Item Index</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ParameterItemIndex: number = 805830755;
/// <summary>
/// <para>(3008,0064) Measured Dose Reference Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static MeasuredDoseReferenceNumber: number = 805830756;
/// <summary>
/// <para>(3008,0065) Parameter Pointer</para>
/// <para> VR: AT VM:1</para>
/// </summary>
public static ParameterPointer: number = 805830757;
/// <summary>
/// <para>(3008,0066) Override Reason</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static OverrideReason: number = 805830758;
/// <summary>
/// <para>(3008,0068) Corrected Parameter Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CorrectedParameterSequence: number = 805830760;
/// <summary>
/// <para>(3008,006A) Correction Value</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static CorrectionValue: number = 805830762;
/// <summary>
/// <para>(3008,0070) Calculated Dose Reference Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CalculatedDoseReferenceSequence: number = 805830768;
/// <summary>
/// <para>(3008,0072) Calculated Dose Reference Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static CalculatedDoseReferenceNumber: number = 805830770;
/// <summary>
/// <para>(3008,0074) Calculated Dose Reference Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static CalculatedDoseReferenceDescription: number = 805830772;
/// <summary>
/// <para>(3008,0076) Calculated Dose Reference Dose Value</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static CalculatedDoseReferenceDoseValue: number = 805830774;
/// <summary>
/// <para>(3008,0078) Start Meterset</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static StartMeterset: number = 805830776;
/// <summary>
/// <para>(3008,007A) End Meterset</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static EndMeterset: number = 805830778;
/// <summary>
/// <para>(3008,0080) Referenced Measured Dose Reference Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedMeasuredDoseReferenceSequence: number = 805830784;
/// <summary>
/// <para>(3008,0082) Referenced Measured Dose Reference Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedMeasuredDoseReferenceNumber: number = 805830786;
/// <summary>
/// <para>(3008,0090) Referenced Calculated Dose Reference Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedCalculatedDoseReferenceSequence: number = 805830800;
/// <summary>
/// <para>(3008,0092) Referenced Calculated Dose Reference Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedCalculatedDoseReferenceNumber: number = 805830802;
/// <summary>
/// <para>(3008,00A0) Beam Limiting Device Leaf Pairs Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BeamLimitingDeviceLeafPairsSequence: number = 805830816;
/// <summary>
/// <para>(3008,00B0) Recorded Wedge Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RecordedWedgeSequence: number = 805830832;
/// <summary>
/// <para>(3008,00C0) Recorded Compensator Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RecordedCompensatorSequence: number = 805830848;
/// <summary>
/// <para>(3008,00D0) Recorded Block Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RecordedBlockSequence: number = 805830864;
/// <summary>
/// <para>(3008,00E0) Treatment Summary Measured Dose Reference Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TreatmentSummaryMeasuredDoseReferenceSequence: number = 805830880;
/// <summary>
/// <para>(3008,00F0) Recorded Snout Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RecordedSnoutSequence: number = 805830896;
/// <summary>
/// <para>(3008,00F2) Recorded Range Shifter Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RecordedRangeShifterSequence: number = 805830898;
/// <summary>
/// <para>(3008,00F4) Recorded Lateral Spreading Device Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RecordedLateralSpreadingDeviceSequence: number = 805830900;
/// <summary>
/// <para>(3008,00F6) Recorded Range Modulator Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RecordedRangeModulatorSequence: number = 805830902;
/// <summary>
/// <para>(3008,0100) Recorded Source Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RecordedSourceSequence: number = 805830912;
/// <summary>
/// <para>(3008,0105) Source Serial Number</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SourceSerialNumber: number = 805830917;
/// <summary>
/// <para>(3008,0110) Treatment Session Application Setup Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TreatmentSessionApplicationSetupSequence: number = 805830928;
/// <summary>
/// <para>(3008,0116) Application Setup Check</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ApplicationSetupCheck: number = 805830934;
/// <summary>
/// <para>(3008,0120) Recorded Brachy Accessory Device Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RecordedBrachyAccessoryDeviceSequence: number = 805830944;
/// <summary>
/// <para>(3008,0122) Referenced Brachy Accessory Device Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedBrachyAccessoryDeviceNumber: number = 805830946;
/// <summary>
/// <para>(3008,0130) Recorded Channel Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RecordedChannelSequence: number = 805830960;
/// <summary>
/// <para>(3008,0132) Specified Channel Total Time</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SpecifiedChannelTotalTime: number = 805830962;
/// <summary>
/// <para>(3008,0134) Delivered Channel Total Time</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DeliveredChannelTotalTime: number = 805830964;
/// <summary>
/// <para>(3008,0136) Specified Number of Pulses</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static SpecifiedNumberOfPulses: number = 805830966;
/// <summary>
/// <para>(3008,0138) Delivered Number of Pulses</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static DeliveredNumberOfPulses: number = 805830968;
/// <summary>
/// <para>(3008,013A) Specified Pulse Repetition Interval</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SpecifiedPulseRepetitionInterval: number = 805830970;
/// <summary>
/// <para>(3008,013C) Delivered Pulse Repetition Interval</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DeliveredPulseRepetitionInterval: number = 805830972;
/// <summary>
/// <para>(3008,0140) Recorded Source Applicator Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RecordedSourceApplicatorSequence: number = 805830976;
/// <summary>
/// <para>(3008,0142) Referenced Source Applicator Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedSourceApplicatorNumber: number = 805830978;
/// <summary>
/// <para>(3008,0150) Recorded Channel Shield Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RecordedChannelShieldSequence: number = 805830992;
/// <summary>
/// <para>(3008,0152) Referenced Channel Shield Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedChannelShieldNumber: number = 805830994;
/// <summary>
/// <para>(3008,0160) Brachy Control Point Delivered Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BrachyControlPointDeliveredSequence: number = 805831008;
/// <summary>
/// <para>(3008,0162) Safe Position Exit Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static SafePositionExitDate: number = 805831010;
/// <summary>
/// <para>(3008,0164) Safe Position Exit Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static SafePositionExitTime: number = 805831012;
/// <summary>
/// <para>(3008,0166) Safe Position Return Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static SafePositionReturnDate: number = 805831014;
/// <summary>
/// <para>(3008,0168) Safe Position Return Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static SafePositionReturnTime: number = 805831016;
/// <summary>
/// <para>(3008,0200) Current Treatment Status</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CurrentTreatmentStatus: number = 805831168;
/// <summary>
/// <para>(3008,0202) Treatment Status Comment</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static TreatmentStatusComment: number = 805831170;
/// <summary>
/// <para>(3008,0220) Fraction Group Summary Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FractionGroupSummarySequence: number = 805831200;
/// <summary>
/// <para>(3008,0223) Referenced Fraction Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedFractionNumber: number = 805831203;
/// <summary>
/// <para>(3008,0224) Fraction Group Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FractionGroupType: number = 805831204;
/// <summary>
/// <para>(3008,0230) Beam Stopper Position</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BeamStopperPosition: number = 805831216;
/// <summary>
/// <para>(3008,0240) Fraction Status Summary Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FractionStatusSummarySequence: number = 805831232;
/// <summary>
/// <para>(3008,0250) Treatment Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static TreatmentDate: number = 805831248;
/// <summary>
/// <para>(3008,0251) Treatment Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static TreatmentTime: number = 805831249;
/// <summary>
/// <para>(300A,0002) RT Plan Label</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static RtPlanLabel: number = 805961730;
/// <summary>
/// <para>(300A,0003) RT Plan Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static RtPlanName: number = 805961731;
/// <summary>
/// <para>(300A,0004) RT Plan Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static RtPlanDescription: number = 805961732;
/// <summary>
/// <para>(300A,0006) RT Plan Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static RtPlanDate: number = 805961734;
/// <summary>
/// <para>(300A,0007) RT Plan Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static RtPlanTime: number = 805961735;
/// <summary>
/// <para>(300A,0009) Treatment Protocols</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static TreatmentProtocols: number = 805961737;
/// <summary>
/// <para>(300A,000A) Plan Intent</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PlanIntent: number = 805961738;
/// <summary>
/// <para>(300A,000B) Treatment Sites</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static TreatmentSites: number = 805961739;
/// <summary>
/// <para>(300A,000C) RT Plan Geometry</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RtPlanGeometry: number = 805961740;
/// <summary>
/// <para>(300A,000E) Prescription Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static PrescriptionDescription: number = 805961742;
/// <summary>
/// <para>(300A,0010) Dose Reference Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DoseReferenceSequence: number = 805961744;
/// <summary>
/// <para>(300A,0012) Dose Reference Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static DoseReferenceNumber: number = 805961746;
/// <summary>
/// <para>(300A,0013) Dose Reference UID</para>
/// <para> VR: UI VM:1</para>
/// </summary>
public static DoseReferenceUid: number = 805961747;
/// <summary>
/// <para>(300A,0014) Dose Reference Structure Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DoseReferenceStructureType: number = 805961748;
/// <summary>
/// <para>(300A,0015) Nominal Beam Energy Unit</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static NominalBeamEnergyUnit: number = 805961749;
/// <summary>
/// <para>(300A,0016) Dose Reference Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static DoseReferenceDescription: number = 805961750;
/// <summary>
/// <para>(300A,0018) Dose Reference Point Coordinates</para>
/// <para> VR: DS VM:3</para>
/// </summary>
public static DoseReferencePointCoordinates: number = 805961752;
/// <summary>
/// <para>(300A,001A) Nominal Prior Dose</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static NominalPriorDose: number = 805961754;
/// <summary>
/// <para>(300A,0020) Dose Reference Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DoseReferenceType: number = 805961760;
/// <summary>
/// <para>(300A,0021) Constraint Weight</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ConstraintWeight: number = 805961761;
/// <summary>
/// <para>(300A,0022) Delivery Warning Dose</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DeliveryWarningDose: number = 805961762;
/// <summary>
/// <para>(300A,0023) Delivery Maximum Dose</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DeliveryMaximumDose: number = 805961763;
/// <summary>
/// <para>(300A,0025) Target Minimum Dose</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TargetMinimumDose: number = 805961765;
/// <summary>
/// <para>(300A,0026) Target Prescription Dose</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TargetPrescriptionDose: number = 805961766;
/// <summary>
/// <para>(300A,0027) Target Maximum Dose</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TargetMaximumDose: number = 805961767;
/// <summary>
/// <para>(300A,0028) Target Underdose Volume Fraction</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TargetUnderdoseVolumeFraction: number = 805961768;
/// <summary>
/// <para>(300A,002A) Organ at Risk Full-volume Dose</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static OrganAtRiskFullVolumeDose: number = 805961770;
/// <summary>
/// <para>(300A,002B) Organ at Risk Limit Dose</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static OrganAtRiskLimitDose: number = 805961771;
/// <summary>
/// <para>(300A,002C) Organ at Risk Maximum Dose</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static OrganAtRiskMaximumDose: number = 805961772;
/// <summary>
/// <para>(300A,002D) Organ at Risk Overdose Volume Fraction</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static OrganAtRiskOverdoseVolumeFraction: number = 805961773;
/// <summary>
/// <para>(300A,0040) Tolerance Table Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ToleranceTableSequence: number = 805961792;
/// <summary>
/// <para>(300A,0042) Tolerance Table Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ToleranceTableNumber: number = 805961794;
/// <summary>
/// <para>(300A,0043) Tolerance Table Label</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static ToleranceTableLabel: number = 805961795;
/// <summary>
/// <para>(300A,0044) Gantry Angle Tolerance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static GantryAngleTolerance: number = 805961796;
/// <summary>
/// <para>(300A,0046) Beam Limiting Device Angle Tolerance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static BeamLimitingDeviceAngleTolerance: number = 805961798;
/// <summary>
/// <para>(300A,0048) Beam Limiting Device Tolerance Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BeamLimitingDeviceToleranceSequence: number = 805961800;
/// <summary>
/// <para>(300A,004A) Beam Limiting Device Position Tolerance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static BeamLimitingDevicePositionTolerance: number = 805961802;
/// <summary>
/// <para>(300A,004B) Snout Position Tolerance</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static SnoutPositionTolerance: number = 805961803;
/// <summary>
/// <para>(300A,004C) Patient Support Angle Tolerance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static PatientSupportAngleTolerance: number = 805961804;
/// <summary>
/// <para>(300A,004E) Table Top Eccentric Angle Tolerance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TableTopEccentricAngleTolerance: number = 805961806;
/// <summary>
/// <para>(300A,004F) Table Top Pitch Angle Tolerance</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static TableTopPitchAngleTolerance: number = 805961807;
/// <summary>
/// <para>(300A,0050) Table Top Roll Angle Tolerance</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static TableTopRollAngleTolerance: number = 805961808;
/// <summary>
/// <para>(300A,0051) Table Top Vertical Position Tolerance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TableTopVerticalPositionTolerance: number = 805961809;
/// <summary>
/// <para>(300A,0052) Table Top Longitudinal Position Tolerance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TableTopLongitudinalPositionTolerance: number = 805961810;
/// <summary>
/// <para>(300A,0053) Table Top Lateral Position Tolerance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TableTopLateralPositionTolerance: number = 805961811;
/// <summary>
/// <para>(300A,0055) RT Plan Relationship</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RtPlanRelationship: number = 805961813;
/// <summary>
/// <para>(300A,0070) Fraction Group Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FractionGroupSequence: number = 805961840;
/// <summary>
/// <para>(300A,0071) Fraction Group Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static FractionGroupNumber: number = 805961841;
/// <summary>
/// <para>(300A,0072) Fraction Group Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static FractionGroupDescription: number = 805961842;
/// <summary>
/// <para>(300A,0078) Number of Fractions Planned</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfFractionsPlanned: number = 805961848;
/// <summary>
/// <para>(300A,0079) Number of Fraction Pattern Digits Per Day</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfFractionPatternDigitsPerDay: number = 805961849;
/// <summary>
/// <para>(300A,007A) Repeat Fraction Cycle Length</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static RepeatFractionCycleLength: number = 805961850;
/// <summary>
/// <para>(300A,007B) Fraction Pattern</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static FractionPattern: number = 805961851;
/// <summary>
/// <para>(300A,0080) Number of Beams</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfBeams: number = 805961856;
/// <summary>
/// <para>(300A,0082) Beam Dose Specification Point</para>
/// <para> VR: DS VM:3</para>
/// </summary>
public static BeamDoseSpecificationPoint: number = 805961858;
/// <summary>
/// <para>(300A,0084) Beam Dose</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static BeamDose: number = 805961860;
/// <summary>
/// <para>(300A,0086) Beam Meterset</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static BeamMeterset: number = 805961862;
/// <summary>
/// <para>(300A,0088) Beam Dose Point Depth</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static BeamDosePointDepth: number = 805961864;
/// <summary>
/// <para>(300A,0089) Beam Dose Point Equivalent Depth</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static BeamDosePointEquivalentDepth: number = 805961865;
/// <summary>
/// <para>(300A,008A) Beam Dose Point SSD</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static BeamDosePointSsd: number = 805961866;
/// <summary>
/// <para>(300A,00A0) Number of Brachy Application Setups</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfBrachyApplicationSetups: number = 805961888;
/// <summary>
/// <para>(300A,00A2) Brachy Application Setup Dose Specification Point</para>
/// <para> VR: DS VM:3</para>
/// </summary>
public static BrachyApplicationSetupDoseSpecificationPoint: number = 805961890;
/// <summary>
/// <para>(300A,00A4) Brachy Application Setup Dose</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static BrachyApplicationSetupDose: number = 805961892;
/// <summary>
/// <para>(300A,00B0) Beam Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BeamSequence: number = 805961904;
/// <summary>
/// <para>(300A,00B2) Treatment Machine Name </para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static TreatmentMachineName: number = 805961906;
/// <summary>
/// <para>(300A,00B3) Primary Dosimeter Unit</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PrimaryDosimeterUnit: number = 805961907;
/// <summary>
/// <para>(300A,00B4) Source-Axis Distance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SourceAxisDistance: number = 805961908;
/// <summary>
/// <para>(300A,00B6) Beam Limiting Device Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BeamLimitingDeviceSequence: number = 805961910;
/// <summary>
/// <para>(300A,00B8) RT Beam Limiting Device Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RtBeamLimitingDeviceType: number = 805961912;
/// <summary>
/// <para>(300A,00BA) Source to Beam Limiting Device Distance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SourceToBeamLimitingDeviceDistance: number = 805961914;
/// <summary>
/// <para>(300A,00BB) Isocenter to Beam Limiting Device Distance</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static IsocenterToBeamLimitingDeviceDistance: number = 805961915;
/// <summary>
/// <para>(300A,00BC) Number of Leaf/Jaw Pairs</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfLeafJawPairs: number = 805961916;
/// <summary>
/// <para>(300A,00BE) Leaf Position Boundaries</para>
/// <para> VR: DS VM:3-n</para>
/// </summary>
public static LeafPositionBoundaries: number = 805961918;
/// <summary>
/// <para>(300A,00C0) Beam Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static BeamNumber: number = 805961920;
/// <summary>
/// <para>(300A,00C2) Beam Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static BeamName: number = 805961922;
/// <summary>
/// <para>(300A,00C3) Beam Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static BeamDescription: number = 805961923;
/// <summary>
/// <para>(300A,00C4) Beam Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BeamType: number = 805961924;
/// <summary>
/// <para>(300A,00C6) Radiation Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RadiationType: number = 805961926;
/// <summary>
/// <para>(300A,00C7) High-Dose Technique Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static HighDoseTechniqueType: number = 805961927;
/// <summary>
/// <para>(300A,00C8) Reference Image Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferenceImageNumber: number = 805961928;
/// <summary>
/// <para>(300A,00CA) Planned Verification Image Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PlannedVerificationImageSequence: number = 805961930;
/// <summary>
/// <para>(300A,00CC) Imaging Device-Specific Acquisition Parameters</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static ImagingDeviceSpecificAcquisitionParameters: number = 805961932;
/// <summary>
/// <para>(300A,00CE) Treatment Delivery Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TreatmentDeliveryType: number = 805961934;
/// <summary>
/// <para>(300A,00D0) Number of Wedges</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfWedges: number = 805961936;
/// <summary>
/// <para>(300A,00D1) Wedge Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static WedgeSequence: number = 805961937;
/// <summary>
/// <para>(300A,00D2) Wedge Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static WedgeNumber: number = 805961938;
/// <summary>
/// <para>(300A,00D3) Wedge Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static WedgeType: number = 805961939;
/// <summary>
/// <para>(300A,00D4) Wedge ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static WedgeId: number = 805961940;
/// <summary>
/// <para>(300A,00D5) Wedge Angle</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static WedgeAngle: number = 805961941;
/// <summary>
/// <para>(300A,00D6) Wedge Factor</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static WedgeFactor: number = 805961942;
/// <summary>
/// <para>(300A,00D7) Total Wedge Tray Water-Equivalent Thickness</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static TotalWedgeTrayWaterEquivalentThickness: number = 805961943;
/// <summary>
/// <para>(300A,00D8) Wedge Orientation</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static WedgeOrientation: number = 805961944;
/// <summary>
/// <para>(300A,00D9) Isocenter to Wedge Tray Distance</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static IsocenterToWedgeTrayDistance: number = 805961945;
/// <summary>
/// <para>(300A,00DA) Source to Wedge Tray Distance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SourceToWedgeTrayDistance: number = 805961946;
/// <summary>
/// <para>(300A,00DB) Wedge Thin Edge Position</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static WedgeThinEdgePosition: number = 805961947;
/// <summary>
/// <para>(300A,00DC) Bolus ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static BolusId: number = 805961948;
/// <summary>
/// <para>(300A,00DD) Bolus Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static BolusDescription: number = 805961949;
/// <summary>
/// <para>(300A,00E0) Number of Compensators</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfCompensators: number = 805961952;
/// <summary>
/// <para>(300A,00E1) Material ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static MaterialId: number = 805961953;
/// <summary>
/// <para>(300A,00E2) Total Compensator Tray Factor</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TotalCompensatorTrayFactor: number = 805961954;
/// <summary>
/// <para>(300A,00E3) Compensator Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static CompensatorSequence: number = 805961955;
/// <summary>
/// <para>(300A,00E4) Compensator Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static CompensatorNumber: number = 805961956;
/// <summary>
/// <para>(300A,00E5) Compensator ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static CompensatorId: number = 805961957;
/// <summary>
/// <para>(300A,00E6) Source to Compensator Tray Distance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SourceToCompensatorTrayDistance: number = 805961958;
/// <summary>
/// <para>(300A,00E7) Compensator Rows</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static CompensatorRows: number = 805961959;
/// <summary>
/// <para>(300A,00E8) Compensator Columns</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static CompensatorColumns: number = 805961960;
/// <summary>
/// <para>(300A,00E9) Compensator Pixel Spacing</para>
/// <para> VR: DS VM:2</para>
/// </summary>
public static CompensatorPixelSpacing: number = 805961961;
/// <summary>
/// <para>(300A,00EA) Compensator Position</para>
/// <para> VR: DS VM:2</para>
/// </summary>
public static CompensatorPosition: number = 805961962;
/// <summary>
/// <para>(300A,00EB) Compensator Transmission Data</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static CompensatorTransmissionData: number = 805961963;
/// <summary>
/// <para>(300A,00EC) Compensator Thickness Data</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static CompensatorThicknessData: number = 805961964;
/// <summary>
/// <para>(300A,00ED) Number of Boli</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfBoli: number = 805961965;
/// <summary>
/// <para>(300A,00EE) Compensator Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CompensatorType: number = 805961966;
/// <summary>
/// <para>(300A,00F0) Number of Blocks</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfBlocks: number = 805961968;
/// <summary>
/// <para>(300A,00F2) Total Block Tray Factor</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TotalBlockTrayFactor: number = 805961970;
/// <summary>
/// <para>(300A,00F3) Total Block Tray Water-Equivalent Thickness</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static TotalBlockTrayWaterEquivalentThickness: number = 805961971;
/// <summary>
/// <para>(300A,00F4) Block Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BlockSequence: number = 805961972;
/// <summary>
/// <para>(300A,00F5) Block Tray ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static BlockTrayId: number = 805961973;
/// <summary>
/// <para>(300A,00F6) Source to Block Tray Distance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SourceToBlockTrayDistance: number = 805961974;
/// <summary>
/// <para>(300A,00F7) Isocenter to Block Tray Distance</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static IsocenterToBlockTrayDistance: number = 805961975;
/// <summary>
/// <para>(300A,00F8) Block Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BlockType: number = 805961976;
/// <summary>
/// <para>(300A,00F9) Accessory Code</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static AccessoryCode: number = 805961977;
/// <summary>
/// <para>(300A,00FA) Block Divergence</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BlockDivergence: number = 805961978;
/// <summary>
/// <para>(300A,00FB) Block Mounting Position</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BlockMountingPosition: number = 805961979;
/// <summary>
/// <para>(300A,00FC) Block Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static BlockNumber: number = 805961980;
/// <summary>
/// <para>(300A,00FE) Block Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static BlockName: number = 805961982;
/// <summary>
/// <para>(300A,0100) Block Thickness</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static BlockThickness: number = 805961984;
/// <summary>
/// <para>(300A,0102) Block Transmission</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static BlockTransmission: number = 805961986;
/// <summary>
/// <para>(300A,0104) Block Number of Points</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static BlockNumberOfPoints: number = 805961988;
/// <summary>
/// <para>(300A,0106) Block Data</para>
/// <para> VR: DS VM:2-2n</para>
/// </summary>
public static BlockData: number = 805961990;
/// <summary>
/// <para>(300A,0107) Applicator Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ApplicatorSequence: number = 805961991;
/// <summary>
/// <para>(300A,0108) Applicator ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static ApplicatorId: number = 805961992;
/// <summary>
/// <para>(300A,0109) Applicator Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ApplicatorType: number = 805961993;
/// <summary>
/// <para>(300A,010A) Applicator Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ApplicatorDescription: number = 805961994;
/// <summary>
/// <para>(300A,010C) Cumulative Dose Reference Coefficient</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static CumulativeDoseReferenceCoefficient: number = 805961996;
/// <summary>
/// <para>(300A,010E) Final Cumulative Meterset Weight</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static FinalCumulativeMetersetWeight: number = 805961998;
/// <summary>
/// <para>(300A,0110) Number of Control Points</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfControlPoints: number = 805962000;
/// <summary>
/// <para>(300A,0111) Control Point Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ControlPointSequence: number = 805962001;
/// <summary>
/// <para>(300A,0112) Control Point Index</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ControlPointIndex: number = 805962002;
/// <summary>
/// <para>(300A,0114) Nominal Beam Energy</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static NominalBeamEnergy: number = 805962004;
/// <summary>
/// <para>(300A,0115) Dose Rate Set</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static DoseRateSet: number = 805962005;
/// <summary>
/// <para>(300A,0116) Wedge Position Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static WedgePositionSequence: number = 805962006;
/// <summary>
/// <para>(300A,0118) Wedge Position</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static WedgePosition: number = 805962008;
/// <summary>
/// <para>(300A,011A) Beam Limiting Device Position Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BeamLimitingDevicePositionSequence: number = 805962010;
/// <summary>
/// <para>(300A,011C) Leaf/Jaw Positions</para>
/// <para> VR: DS VM:2-2n</para>
/// </summary>
public static LeafJawPositions: number = 805962012;
/// <summary>
/// <para>(300A,011E) Gantry Angle</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static GantryAngle: number = 805962014;
/// <summary>
/// <para>(300A,011F) Gantry Rotation Direction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static GantryRotationDirection: number = 805962015;
/// <summary>
/// <para>(300A,0120) Beam Limiting Device Angle</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static BeamLimitingDeviceAngle: number = 805962016;
/// <summary>
/// <para>(300A,0121) Beam Limiting Device Rotation Direction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BeamLimitingDeviceRotationDirection: number = 805962017;
/// <summary>
/// <para>(300A,0122) Patient Support Angle</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static PatientSupportAngle: number = 805962018;
/// <summary>
/// <para>(300A,0123) Patient Support Rotation Direction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PatientSupportRotationDirection: number = 805962019;
/// <summary>
/// <para>(300A,0124) Table Top Eccentric Axis Distance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TableTopEccentricAxisDistance: number = 805962020;
/// <summary>
/// <para>(300A,0125) Table Top Eccentric Angle</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TableTopEccentricAngle: number = 805962021;
/// <summary>
/// <para>(300A,0126) Table Top Eccentric Rotation Direction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TableTopEccentricRotationDirection: number = 805962022;
/// <summary>
/// <para>(300A,0128) Table Top Vertical Position</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TableTopVerticalPosition: number = 805962024;
/// <summary>
/// <para>(300A,0129) Table Top Longitudinal Position</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TableTopLongitudinalPosition: number = 805962025;
/// <summary>
/// <para>(300A,012A) Table Top Lateral Position</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TableTopLateralPosition: number = 805962026;
/// <summary>
/// <para>(300A,012C) Isocenter Position</para>
/// <para> VR: DS VM:3</para>
/// </summary>
public static IsocenterPosition: number = 805962028;
/// <summary>
/// <para>(300A,012E) Surface Entry Point</para>
/// <para> VR: DS VM:3</para>
/// </summary>
public static SurfaceEntryPoint: number = 805962030;
/// <summary>
/// <para>(300A,0130) Source to Surface Distance</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SourceToSurfaceDistance: number = 805962032;
/// <summary>
/// <para>(300A,0134) Cumulative Meterset Weight</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static CumulativeMetersetWeight: number = 805962036;
/// <summary>
/// <para>(300A,0140) Table Top Pitch Angle</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static TableTopPitchAngle: number = 805962048;
/// <summary>
/// <para>(300A,0142) Table Top Pitch Rotation Direction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TableTopPitchRotationDirection: number = 805962050;
/// <summary>
/// <para>(300A,0144) Table Top Roll Angle</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static TableTopRollAngle: number = 805962052;
/// <summary>
/// <para>(300A,0146) Table Top Roll Rotation Direction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TableTopRollRotationDirection: number = 805962054;
/// <summary>
/// <para>(300A,0148) Head Fixation Angle</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static HeadFixationAngle: number = 805962056;
/// <summary>
/// <para>(300A,014A) Gantry Pitch Angle</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static GantryPitchAngle: number = 805962058;
/// <summary>
/// <para>(300A,014C) Gantry Pitch Rotation Direction</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static GantryPitchRotationDirection: number = 805962060;
/// <summary>
/// <para>(300A,014E) Gantry Pitch Angle Tolerance</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static GantryPitchAngleTolerance: number = 805962062;
/// <summary>
/// <para>(300A,0180) Patient Setup Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PatientSetupSequence: number = 805962112;
/// <summary>
/// <para>(300A,0182) Patient Setup Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static PatientSetupNumber: number = 805962114;
/// <summary>
/// <para>(300A,0183) Patient Setup Label</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PatientSetupLabel: number = 805962115;
/// <summary>
/// <para>(300A,0184) Patient Additional Position</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PatientAdditionalPosition: number = 805962116;
/// <summary>
/// <para>(300A,0190) Fixation Device Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static FixationDeviceSequence: number = 805962128;
/// <summary>
/// <para>(300A,0192) Fixation Device Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static FixationDeviceType: number = 805962130;
/// <summary>
/// <para>(300A,0194) Fixation Device Label</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static FixationDeviceLabel: number = 805962132;
/// <summary>
/// <para>(300A,0196) Fixation Device Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static FixationDeviceDescription: number = 805962134;
/// <summary>
/// <para>(300A,0198) Fixation Device Position</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static FixationDevicePosition: number = 805962136;
/// <summary>
/// <para>(300A,0199) Fixation Device Pitch Angle</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static FixationDevicePitchAngle: number = 805962137;
/// <summary>
/// <para>(300A,019A) Fixation Device Roll Angle</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static FixationDeviceRollAngle: number = 805962138;
/// <summary>
/// <para>(300A,01A0) Shielding Device Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ShieldingDeviceSequence: number = 805962144;
/// <summary>
/// <para>(300A,01A2) Shielding Device Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ShieldingDeviceType: number = 805962146;
/// <summary>
/// <para>(300A,01A4) Shielding Device Label</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static ShieldingDeviceLabel: number = 805962148;
/// <summary>
/// <para>(300A,01A6) Shielding Device Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static ShieldingDeviceDescription: number = 805962150;
/// <summary>
/// <para>(300A,01A8) Shielding Device Position</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static ShieldingDevicePosition: number = 805962152;
/// <summary>
/// <para>(300A,01B0) Setup Technique</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SetupTechnique: number = 805962160;
/// <summary>
/// <para>(300A,01B2) Setup Technique Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static SetupTechniqueDescription: number = 805962162;
/// <summary>
/// <para>(300A,01B4) Setup Device Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SetupDeviceSequence: number = 805962164;
/// <summary>
/// <para>(300A,01B6) Setup Device Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SetupDeviceType: number = 805962166;
/// <summary>
/// <para>(300A,01B8) Setup Device Label</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static SetupDeviceLabel: number = 805962168;
/// <summary>
/// <para>(300A,01BA) Setup Device Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static SetupDeviceDescription: number = 805962170;
/// <summary>
/// <para>(300A,01BC) Setup Device Parameter</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SetupDeviceParameter: number = 805962172;
/// <summary>
/// <para>(300A,01D0) Setup Reference Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static SetupReferenceDescription: number = 805962192;
/// <summary>
/// <para>(300A,01D2) Table Top Vertical Setup Displacement</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TableTopVerticalSetupDisplacement: number = 805962194;
/// <summary>
/// <para>(300A,01D4) Table Top Longitudinal Setup Displacement</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TableTopLongitudinalSetupDisplacement: number = 805962196;
/// <summary>
/// <para>(300A,01D6) Table Top Lateral Setup Displacement</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TableTopLateralSetupDisplacement: number = 805962198;
/// <summary>
/// <para>(300A,0200) Brachy Treatment Technique</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BrachyTreatmentTechnique: number = 805962240;
/// <summary>
/// <para>(300A,0202) Brachy Treatment Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BrachyTreatmentType: number = 805962242;
/// <summary>
/// <para>(300A,0206) Treatment Machine Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static TreatmentMachineSequence: number = 805962246;
/// <summary>
/// <para>(300A,0210) Source Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SourceSequence: number = 805962256;
/// <summary>
/// <para>(300A,0212) Source Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static SourceNumber: number = 805962258;
/// <summary>
/// <para>(300A,0214) Source Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SourceType: number = 805962260;
/// <summary>
/// <para>(300A,0216) Source Manufacturer</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SourceManufacturer: number = 805962262;
/// <summary>
/// <para>(300A,0218) Active Source Diameter</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ActiveSourceDiameter: number = 805962264;
/// <summary>
/// <para>(300A,021A) Active Source Length</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ActiveSourceLength: number = 805962266;
/// <summary>
/// <para>(300A,0222) Source Encapsulation Nominal Thickness</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SourceEncapsulationNominalThickness: number = 805962274;
/// <summary>
/// <para>(300A,0224) Source Encapsulation Nominal Transmission</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SourceEncapsulationNominalTransmission: number = 805962276;
/// <summary>
/// <para>(300A,0226) Source Isotope Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SourceIsotopeName: number = 805962278;
/// <summary>
/// <para>(300A,0228) Source Isotope Half Life</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SourceIsotopeHalfLife: number = 805962280;
/// <summary>
/// <para>(300A,0229) Source Strength Units</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SourceStrengthUnits: number = 805962281;
/// <summary>
/// <para>(300A,022A) Reference Air Kerma Rate</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ReferenceAirKermaRate: number = 805962282;
/// <summary>
/// <para>(300A,022B) Source Strength</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SourceStrength: number = 805962283;
/// <summary>
/// <para>(300A,022C) Source Strength Reference Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static SourceStrengthReferenceDate: number = 805962284;
/// <summary>
/// <para>(300A,022E) Source Strength Reference Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static SourceStrengthReferenceTime: number = 805962286;
/// <summary>
/// <para>(300A,0230) Application Setup Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ApplicationSetupSequence: number = 805962288;
/// <summary>
/// <para>(300A,0232) Application Setup Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ApplicationSetupType: number = 805962290;
/// <summary>
/// <para>(300A,0234) Application Setup Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ApplicationSetupNumber: number = 805962292;
/// <summary>
/// <para>(300A,0236) Application Setup Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ApplicationSetupName: number = 805962294;
/// <summary>
/// <para>(300A,0238) Application Setup Manufacturer</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ApplicationSetupManufacturer: number = 805962296;
/// <summary>
/// <para>(300A,0240) Template Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static TemplateNumber: number = 805962304;
/// <summary>
/// <para>(300A,0242) Template Type</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static TemplateType: number = 805962306;
/// <summary>
/// <para>(300A,0244) Template Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static TemplateName: number = 805962308;
/// <summary>
/// <para>(300A,0250) Total Reference Air Kerma</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TotalReferenceAirKerma: number = 805962320;
/// <summary>
/// <para>(300A,0260) Brachy Accessory Device Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BrachyAccessoryDeviceSequence: number = 805962336;
/// <summary>
/// <para>(300A,0262) Brachy Accessory Device Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static BrachyAccessoryDeviceNumber: number = 805962338;
/// <summary>
/// <para>(300A,0263) Brachy Accessory Device ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static BrachyAccessoryDeviceId: number = 805962339;
/// <summary>
/// <para>(300A,0264) Brachy Accessory Device Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static BrachyAccessoryDeviceType: number = 805962340;
/// <summary>
/// <para>(300A,0266) Brachy Accessory Device Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static BrachyAccessoryDeviceName: number = 805962342;
/// <summary>
/// <para>(300A,026A) Brachy Accessory Device Nominal Thickness</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static BrachyAccessoryDeviceNominalThickness: number = 805962346;
/// <summary>
/// <para>(300A,026C) Brachy Accessory Device Nominal Transmission</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static BrachyAccessoryDeviceNominalTransmission: number = 805962348;
/// <summary>
/// <para>(300A,0280) Channel Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ChannelSequence: number = 805962368;
/// <summary>
/// <para>(300A,0282) Channel Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ChannelNumber: number = 805962370;
/// <summary>
/// <para>(300A,0284) Channel Length</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ChannelLength: number = 805962372;
/// <summary>
/// <para>(300A,0286) Channel Total Time</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ChannelTotalTime: number = 805962374;
/// <summary>
/// <para>(300A,0288) Source Movement Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SourceMovementType: number = 805962376;
/// <summary>
/// <para>(300A,028A) Number of Pulses</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfPulses: number = 805962378;
/// <summary>
/// <para>(300A,028C) Pulse Repetition Interval</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static PulseRepetitionInterval: number = 805962380;
/// <summary>
/// <para>(300A,0290) Source Applicator Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static SourceApplicatorNumber: number = 805962384;
/// <summary>
/// <para>(300A,0291) Source Applicator ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static SourceApplicatorId: number = 805962385;
/// <summary>
/// <para>(300A,0292) Source Applicator Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static SourceApplicatorType: number = 805962386;
/// <summary>
/// <para>(300A,0294) Source Applicator Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SourceApplicatorName: number = 805962388;
/// <summary>
/// <para>(300A,0296) Source Applicator Length</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SourceApplicatorLength: number = 805962390;
/// <summary>
/// <para>(300A,0298) Source Applicator Manufacturer</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static SourceApplicatorManufacturer: number = 805962392;
/// <summary>
/// <para>(300A,029C) Source Applicator Wall Nominal Thickness</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SourceApplicatorWallNominalThickness: number = 805962396;
/// <summary>
/// <para>(300A,029E) Source Applicator Wall Nominal Transmission</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SourceApplicatorWallNominalTransmission: number = 805962398;
/// <summary>
/// <para>(300A,02A0) Source Applicator Step Size</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static SourceApplicatorStepSize: number = 805962400;
/// <summary>
/// <para>(300A,02A2) Transfer Tube Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static TransferTubeNumber: number = 805962402;
/// <summary>
/// <para>(300A,02A4) Transfer Tube Length</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static TransferTubeLength: number = 805962404;
/// <summary>
/// <para>(300A,02B0) Channel Shield Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ChannelShieldSequence: number = 805962416;
/// <summary>
/// <para>(300A,02B2) Channel Shield Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ChannelShieldNumber: number = 805962418;
/// <summary>
/// <para>(300A,02B3) Channel Shield ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static ChannelShieldId: number = 805962419;
/// <summary>
/// <para>(300A,02B4) Channel Shield Name</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ChannelShieldName: number = 805962420;
/// <summary>
/// <para>(300A,02B8) Channel Shield Nominal Thickness</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ChannelShieldNominalThickness: number = 805962424;
/// <summary>
/// <para>(300A,02BA) Channel Shield Nominal Transmission</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ChannelShieldNominalTransmission: number = 805962426;
/// <summary>
/// <para>(300A,02C8) Final Cumulative Time Weight</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static FinalCumulativeTimeWeight: number = 805962440;
/// <summary>
/// <para>(300A,02D0) Brachy Control Point Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BrachyControlPointSequence: number = 805962448;
/// <summary>
/// <para>(300A,02D2) Control Point Relative Position</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static ControlPointRelativePosition: number = 805962450;
/// <summary>
/// <para>(300A,02D4) Control Point 3D Position</para>
/// <para> VR: DS VM:3</para>
/// </summary>
public static ControlPoint3dPosition: number = 805962452;
/// <summary>
/// <para>(300A,02D6) Cumulative Time Weight</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static CumulativeTimeWeight: number = 805962454;
/// <summary>
/// <para>(300A,02E0) Compensator Divergence</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CompensatorDivergence: number = 805962464;
/// <summary>
/// <para>(300A,02E1) Compensator Mounting Position</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CompensatorMountingPosition: number = 805962465;
/// <summary>
/// <para>(300A,02E2) Source to Compensator Distance</para>
/// <para> VR: DS VM:1-n</para>
/// </summary>
public static SourceToCompensatorDistance: number = 805962466;
/// <summary>
/// <para>(300A,02E3) Total Compensator Tray Water-Equivalent Thickness</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static TotalCompensatorTrayWaterEquivalentThickness: number = 805962467;
/// <summary>
/// <para>(300A,02E4) Isocenter to Compensator Tray Distance</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static IsocenterToCompensatorTrayDistance: number = 805962468;
/// <summary>
/// <para>(300A,02E5) Compensator Column Offset</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static CompensatorColumnOffset: number = 805962469;
/// <summary>
/// <para>(300A,02E6) Isocenter to Compensator Distances</para>
/// <para> VR: FL VM:1-n</para>
/// </summary>
public static IsocenterToCompensatorDistances: number = 805962470;
/// <summary>
/// <para>(300A,02E7) Compensator Relative Stopping Power Ratio</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static CompensatorRelativeStoppingPowerRatio: number = 805962471;
/// <summary>
/// <para>(300A,02E8) Compensator Milling Tool Diameter</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static CompensatorMillingToolDiameter: number = 805962472;
/// <summary>
/// <para>(300A,02EA) Ion Range Compensator Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IonRangeCompensatorSequence: number = 805962474;
/// <summary>
/// <para>(300A,02EB) Compensator Description</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static CompensatorDescription: number = 805962475;
/// <summary>
/// <para>(300A,0302) Radiation Mass Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static RadiationMassNumber: number = 805962498;
/// <summary>
/// <para>(300A,0304) Radiation Atomic Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static RadiationAtomicNumber: number = 805962500;
/// <summary>
/// <para>(300A,0306) Radiation Charge State</para>
/// <para> VR: SS VM:1</para>
/// </summary>
public static RadiationChargeState: number = 805962502;
/// <summary>
/// <para>(300A,0308) Scan Mode</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ScanMode: number = 805962504;
/// <summary>
/// <para>(300A,030A) Virtual Source-Axis Distances</para>
/// <para> VR: FL VM:2</para>
/// </summary>
public static VirtualSourceAxisDistances: number = 805962506;
/// <summary>
/// <para>(300A,030C) Snout Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SnoutSequence: number = 805962508;
/// <summary>
/// <para>(300A,030D) Snout Position</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static SnoutPosition: number = 805962509;
/// <summary>
/// <para>(300A,030F) Snout ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static SnoutId: number = 805962511;
/// <summary>
/// <para>(300A,0312) Number of Range Shifters</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfRangeShifters: number = 805962514;
/// <summary>
/// <para>(300A,0314) Range Shifter Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RangeShifterSequence: number = 805962516;
/// <summary>
/// <para>(300A,0316) Range Shifter Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static RangeShifterNumber: number = 805962518;
/// <summary>
/// <para>(300A,0318) Range Shifter ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static RangeShifterId: number = 805962520;
/// <summary>
/// <para>(300A,0320) Range Shifter Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RangeShifterType: number = 805962528;
/// <summary>
/// <para>(300A,0322) Range Shifter Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static RangeShifterDescription: number = 805962530;
/// <summary>
/// <para>(300A,0330) Number of Lateral Spreading Devices</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfLateralSpreadingDevices: number = 805962544;
/// <summary>
/// <para>(300A,0332) Lateral Spreading Device Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static LateralSpreadingDeviceSequence: number = 805962546;
/// <summary>
/// <para>(300A,0334) Lateral Spreading Device Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static LateralSpreadingDeviceNumber: number = 805962548;
/// <summary>
/// <para>(300A,0336) Lateral Spreading Device ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static LateralSpreadingDeviceId: number = 805962550;
/// <summary>
/// <para>(300A,0338) Lateral Spreading Device Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static LateralSpreadingDeviceType: number = 805962552;
/// <summary>
/// <para>(300A,033A) Lateral Spreading Device Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static LateralSpreadingDeviceDescription: number = 805962554;
/// <summary>
/// <para>(300A,033C) Lateral Spreading Device Water Equivalent Thickness</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static LateralSpreadingDeviceWaterEquivalentThickness: number = 805962556;
/// <summary>
/// <para>(300A,0340) Number of Range Modulators</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfRangeModulators: number = 805962560;
/// <summary>
/// <para>(300A,0342) Range Modulator Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RangeModulatorSequence: number = 805962562;
/// <summary>
/// <para>(300A,0344) Range Modulator Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static RangeModulatorNumber: number = 805962564;
/// <summary>
/// <para>(300A,0346) Range Modulator ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static RangeModulatorId: number = 805962566;
/// <summary>
/// <para>(300A,0348) Range Modulator Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RangeModulatorType: number = 805962568;
/// <summary>
/// <para>(300A,034A) Range Modulator Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static RangeModulatorDescription: number = 805962570;
/// <summary>
/// <para>(300A,034C) Beam Current Modulation ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static BeamCurrentModulationId: number = 805962572;
/// <summary>
/// <para>(300A,0350) Patient Support Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PatientSupportType: number = 805962576;
/// <summary>
/// <para>(300A,0352) Patient Support ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static PatientSupportId: number = 805962578;
/// <summary>
/// <para>(300A,0354) Patient Support Accessory Code</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static PatientSupportAccessoryCode: number = 805962580;
/// <summary>
/// <para>(300A,0356) Fixation Light Azimuthal Angle</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static FixationLightAzimuthalAngle: number = 805962582;
/// <summary>
/// <para>(300A,0358) Fixation Light Polar Angle</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static FixationLightPolarAngle: number = 805962584;
/// <summary>
/// <para>(300A,035A) Meterset Rate</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static MetersetRate: number = 805962586;
/// <summary>
/// <para>(300A,0360) Range Shifter Settings Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RangeShifterSettingsSequence: number = 805962592;
/// <summary>
/// <para>(300A,0362) Range Shifter Setting</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static RangeShifterSetting: number = 805962594;
/// <summary>
/// <para>(300A,0364) Isocenter to Range Shifter Distance</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static IsocenterToRangeShifterDistance: number = 805962596;
/// <summary>
/// <para>(300A,0366) Range Shifter Water Equivalent Thickness</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static RangeShifterWaterEquivalentThickness: number = 805962598;
/// <summary>
/// <para>(300A,0370) Lateral Spreading Device Settings Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static LateralSpreadingDeviceSettingsSequence: number = 805962608;
/// <summary>
/// <para>(300A,0372) Lateral Spreading Device Setting</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static LateralSpreadingDeviceSetting: number = 805962610;
/// <summary>
/// <para>(300A,0374) Isocenter to Lateral Spreading Device Distance</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static IsocenterToLateralSpreadingDeviceDistance: number = 805962612;
/// <summary>
/// <para>(300A,0380) Range Modulator Settings Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RangeModulatorSettingsSequence: number = 805962624;
/// <summary>
/// <para>(300A,0382) Range Modulator Gating Start Value</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static RangeModulatorGatingStartValue: number = 805962626;
/// <summary>
/// <para>(300A,0384) Range Modulator Gating Stop Value</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static RangeModulatorGatingStopValue: number = 805962628;
/// <summary>
/// <para>(300A,0386) Range Modulator Gating Start Water Equivalent Thickness</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static RangeModulatorGatingStartWaterEquivalentThickness: number = 805962630;
/// <summary>
/// <para>(300A,0388) Range Modulator Gating Stop Water Equivalent Thickness</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static RangeModulatorGatingStopWaterEquivalentThickness: number = 805962632;
/// <summary>
/// <para>(300A,038A) Isocenter to Range Modulator Distance</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static IsocenterToRangeModulatorDistance: number = 805962634;
/// <summary>
/// <para>(300A,0390) Scan Spot Tune ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static ScanSpotTuneId: number = 805962640;
/// <summary>
/// <para>(300A,0392) Number of Scan Spot Positions</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfScanSpotPositions: number = 805962642;
/// <summary>
/// <para>(300A,0394) Scan Spot Position Map</para>
/// <para> VR: FL VM:1-n</para>
/// </summary>
public static ScanSpotPositionMap: number = 805962644;
/// <summary>
/// <para>(300A,0396) Scan Spot Meterset Weights</para>
/// <para> VR: FL VM:1-n</para>
/// </summary>
public static ScanSpotMetersetWeights: number = 805962646;
/// <summary>
/// <para>(300A,0398) Scanning Spot Size</para>
/// <para> VR: FL VM:2</para>
/// </summary>
public static ScanningSpotSize: number = 805962648;
/// <summary>
/// <para>(300A,039A) Number of Paintings</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfPaintings: number = 805962650;
/// <summary>
/// <para>(300A,03A0) Ion Tolerance Table Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IonToleranceTableSequence: number = 805962656;
/// <summary>
/// <para>(300A,03A2) Ion Beam Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IonBeamSequence: number = 805962658;
/// <summary>
/// <para>(300A,03A4) Ion Beam Limiting Device Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IonBeamLimitingDeviceSequence: number = 805962660;
/// <summary>
/// <para>(300A,03A6) Ion Block Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IonBlockSequence: number = 805962662;
/// <summary>
/// <para>(300A,03A8) Ion Control Point Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IonControlPointSequence: number = 805962664;
/// <summary>
/// <para>(300A,03AA) Ion Wedge Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IonWedgeSequence: number = 805962666;
/// <summary>
/// <para>(300A,03AC) Ion Wedge Position Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static IonWedgePositionSequence: number = 805962668;
/// <summary>
/// <para>(300A,0401) Referenced Setup Image Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedSetupImageSequence: number = 805962753;
/// <summary>
/// <para>(300A,0402) Setup Image Comment</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static SetupImageComment: number = 805962754;
/// <summary>
/// <para>(300A,0410) Motion Synchronization Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MotionSynchronizationSequence: number = 805962768;
/// <summary>
/// <para>(300A,0412) Control Point Orientation</para>
/// <para> VR: FL VM:3</para>
/// </summary>
public static ControlPointOrientation: number = 805962770;
/// <summary>
/// <para>(300A,0420) General Accessory Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static GeneralAccessorySequence: number = 805962784;
/// <summary>
/// <para>(300A,0421) General Accessory ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static GeneralAccessoryId: number = 805962785;
/// <summary>
/// <para>(300A,0422) General Accessory Description</para>
/// <para> VR: ST VM:1</para>
/// </summary>
public static GeneralAccessoryDescription: number = 805962786;
/// <summary>
/// <para>(300A,0423) General Accessory Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static GeneralAccessoryType: number = 805962787;
/// <summary>
/// <para>(300A,0424) General Accessory Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static GeneralAccessoryNumber: number = 805962788;
/// <summary>
/// <para>(300A,0431) Applicator Geometry Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ApplicatorGeometrySequence: number = 805962801;
/// <summary>
/// <para>(300A,0432) Applicator Aperture Shape</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ApplicatorApertureShape: number = 805962802;
/// <summary>
/// <para>(300A,0433) Applicator Opening</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static ApplicatorOpening: number = 805962803;
/// <summary>
/// <para>(300A,0434) Applicator Opening X</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static ApplicatorOpeningX: number = 805962804;
/// <summary>
/// <para>(300A,0435) Applicator Opening Y</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static ApplicatorOpeningY: number = 805962805;
/// <summary>
/// <para>(300A,0436) Source to Applicator Mounting Position Distance</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static SourceToApplicatorMountingPositionDistance: number = 805962806;
/// <summary>
/// <para>(300C,0002) Referenced RT Plan Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedRtPlanSequence: number = 806092802;
/// <summary>
/// <para>(300C,0004) Referenced Beam Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedBeamSequence: number = 806092804;
/// <summary>
/// <para>(300C,0006) Referenced Beam Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedBeamNumber: number = 806092806;
/// <summary>
/// <para>(300C,0007) Referenced Reference Image Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedReferenceImageNumber: number = 806092807;
/// <summary>
/// <para>(300C,0008) Start Cumulative Meterset Weight</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static StartCumulativeMetersetWeight: number = 806092808;
/// <summary>
/// <para>(300C,0009) End Cumulative Meterset Weight</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static EndCumulativeMetersetWeight: number = 806092809;
/// <summary>
/// <para>(300C,000A) Referenced Brachy Application Setup Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedBrachyApplicationSetupSequence: number = 806092810;
/// <summary>
/// <para>(300C,000C) Referenced Brachy Application Setup Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedBrachyApplicationSetupNumber: number = 806092812;
/// <summary>
/// <para>(300C,000E) Referenced Source Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedSourceNumber: number = 806092814;
/// <summary>
/// <para>(300C,0020) Referenced Fraction Group Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedFractionGroupSequence: number = 806092832;
/// <summary>
/// <para>(300C,0022) Referenced Fraction Group Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedFractionGroupNumber: number = 806092834;
/// <summary>
/// <para>(300C,0040) Referenced Verification Image Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedVerificationImageSequence: number = 806092864;
/// <summary>
/// <para>(300C,0042) Referenced Reference Image Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedReferenceImageSequence: number = 806092866;
/// <summary>
/// <para>(300C,0050) Referenced Dose Reference Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedDoseReferenceSequence: number = 806092880;
/// <summary>
/// <para>(300C,0051) Referenced Dose Reference Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedDoseReferenceNumber: number = 806092881;
/// <summary>
/// <para>(300C,0055) Brachy Referenced Dose Reference Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BrachyReferencedDoseReferenceSequence: number = 806092885;
/// <summary>
/// <para>(300C,0060) Referenced Structure Set Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedStructureSetSequence: number = 806092896;
/// <summary>
/// <para>(300C,006A) Referenced Patient Setup Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedPatientSetupNumber: number = 806092906;
/// <summary>
/// <para>(300C,0080) Referenced Dose Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedDoseSequence: number = 806092928;
/// <summary>
/// <para>(300C,00A0) Referenced Tolerance Table Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedToleranceTableNumber: number = 806092960;
/// <summary>
/// <para>(300C,00B0) Referenced Bolus Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedBolusSequence: number = 806092976;
/// <summary>
/// <para>(300C,00C0) Referenced Wedge Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedWedgeNumber: number = 806092992;
/// <summary>
/// <para>(300C,00D0) Referenced Compensator Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedCompensatorNumber: number = 806093008;
/// <summary>
/// <para>(300C,00E0) Referenced Block Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedBlockNumber: number = 806093024;
/// <summary>
/// <para>(300C,00F0) Referenced Control Point Index</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedControlPointIndex: number = 806093040;
/// <summary>
/// <para>(300C,00F2) Referenced Control Point Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ReferencedControlPointSequence: number = 806093042;
/// <summary>
/// <para>(300C,00F4) Referenced Start Control Point Index</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedStartControlPointIndex: number = 806093044;
/// <summary>
/// <para>(300C,00F6) Referenced Stop Control Point Index</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedStopControlPointIndex: number = 806093046;
/// <summary>
/// <para>(300C,0100) Referenced Range Shifter Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedRangeShifterNumber: number = 806093056;
/// <summary>
/// <para>(300C,0102) Referenced Lateral Spreading Device Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedLateralSpreadingDeviceNumber: number = 806093058;
/// <summary>
/// <para>(300C,0104) Referenced Range Modulator Number</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static ReferencedRangeModulatorNumber: number = 806093060;
/// <summary>
/// <para>(300E,0002) Approval Status</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ApprovalStatus: number = 806223874;
/// <summary>
/// <para>(300E,0004) Review Date</para>
/// <para> VR: DA VM:1</para>
/// </summary>
public static ReviewDate: number = 806223876;
/// <summary>
/// <para>(300E,0005) Review Time</para>
/// <para> VR: TM VM:1</para>
/// </summary>
public static ReviewTime: number = 806223877;
/// <summary>
/// <para>(300E,0008) Reviewer Name</para>
/// <para> VR: PN VM:1</para>
/// </summary>
public static ReviewerName: number = 806223880;
/// <summary>
/// <para>(4000,0010) Arbitrary</para>
/// <para> VR: LT VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ArbitraryRetired: number = 1073741840;
/// <summary>
/// <para>(4000,4000) Text Comments</para>
/// <para> VR: LT VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TextCommentsRetired: number = 1073758208;
/// <summary>
/// <para>(4008,0040) Results ID</para>
/// <para> VR: SH VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ResultsIdRetired: number = 1074266176;
/// <summary>
/// <para>(4008,0042) Results ID Issuer</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ResultsIdIssuerRetired: number = 1074266178;
/// <summary>
/// <para>(4008,0050) Referenced Interpretation Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferencedInterpretationSequenceRetired: number = 1074266192;
/// <summary>
/// <para>(4008,00FF) Report Production Status (Trial)</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReportProductionStatusTrialRetired: number = 1074266367;
/// <summary>
/// <para>(4008,0100) Interpretation Recorded Date</para>
/// <para> VR: DA VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static InterpretationRecordedDateRetired: number = 1074266368;
/// <summary>
/// <para>(4008,0101) Interpretation Recorded Time</para>
/// <para> VR: TM VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static InterpretationRecordedTimeRetired: number = 1074266369;
/// <summary>
/// <para>(4008,0102) Interpretation Recorder</para>
/// <para> VR: PN VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static InterpretationRecorderRetired: number = 1074266370;
/// <summary>
/// <para>(4008,0103) Reference to Recorded Sound</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ReferenceToRecordedSoundRetired: number = 1074266371;
/// <summary>
/// <para>(4008,0108) Interpretation Transcription Date</para>
/// <para> VR: DA VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static InterpretationTranscriptionDateRetired: number = 1074266376;
/// <summary>
/// <para>(4008,0109) Interpretation Transcription Time</para>
/// <para> VR: TM VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static InterpretationTranscriptionTimeRetired: number = 1074266377;
/// <summary>
/// <para>(4008,010A) Interpretation Transcriber</para>
/// <para> VR: PN VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static InterpretationTranscriberRetired: number = 1074266378;
/// <summary>
/// <para>(4008,010B) Interpretation Text</para>
/// <para> VR: ST VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static InterpretationTextRetired: number = 1074266379;
/// <summary>
/// <para>(4008,010C) Interpretation Author</para>
/// <para> VR: PN VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static InterpretationAuthorRetired: number = 1074266380;
/// <summary>
/// <para>(4008,0111) Interpretation Approver Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static InterpretationApproverSequenceRetired: number = 1074266385;
/// <summary>
/// <para>(4008,0112) Interpretation Approval Date</para>
/// <para> VR: DA VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static InterpretationApprovalDateRetired: number = 1074266386;
/// <summary>
/// <para>(4008,0113) Interpretation Approval Time</para>
/// <para> VR: TM VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static InterpretationApprovalTimeRetired: number = 1074266387;
/// <summary>
/// <para>(4008,0114) Physician Approving Interpretation</para>
/// <para> VR: PN VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static PhysicianApprovingInterpretationRetired: number = 1074266388;
/// <summary>
/// <para>(4008,0115) Interpretation Diagnosis Description</para>
/// <para> VR: LT VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static InterpretationDiagnosisDescriptionRetired: number = 1074266389;
/// <summary>
/// <para>(4008,0117) Interpretation Diagnosis Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static InterpretationDiagnosisCodeSequenceRetired: number = 1074266391;
/// <summary>
/// <para>(4008,0118) Results Distribution List Sequence</para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ResultsDistributionListSequenceRetired: number = 1074266392;
/// <summary>
/// <para>(4008,0119) Distribution Name</para>
/// <para> VR: PN VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DistributionNameRetired: number = 1074266393;
/// <summary>
/// <para>(4008,011A) Distribution Address</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DistributionAddressRetired: number = 1074266394;
/// <summary>
/// <para>(4008,0200) Interpretation ID</para>
/// <para> VR: SH VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static InterpretationIdRetired: number = 1074266624;
/// <summary>
/// <para>(4008,0202) Interpretation ID Issuer</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static InterpretationIdIssuerRetired: number = 1074266626;
/// <summary>
/// <para>(4008,0210) Interpretation Type ID</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static InterpretationTypeIdRetired: number = 1074266640;
/// <summary>
/// <para>(4008,0212) Interpretation Status ID</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static InterpretationStatusIdRetired: number = 1074266642;
/// <summary>
/// <para>(4008,0300) Impressions</para>
/// <para> VR: ST VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ImpressionsRetired: number = 1074266880;
/// <summary>
/// <para>(4008,4000) Results Comments</para>
/// <para> VR: ST VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static ResultsCommentsRetired: number = 1074282496;
/// <summary>
/// <para>(4010,0001) Low Energy Detectors</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static LowEnergyDetectors: number = 1074790401;
/// <summary>
/// <para>(4010,0002) High Energy Detectors</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static HighEnergyDetectors: number = 1074790402;
/// <summary>
/// <para>(4010,0004) Detector Geometry Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DetectorGeometrySequence: number = 1074790404;
/// <summary>
/// <para>(4010,1001) Threat ROI Voxel Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ThreatRoiVoxelSequence: number = 1074794497;
/// <summary>
/// <para>(4010,1004) Threat ROI Base</para>
/// <para> VR: FL VM:3</para>
/// </summary>
public static ThreatRoiBase: number = 1074794500;
/// <summary>
/// <para>(4010,1005) Threat ROI Extents </para>
/// <para> VR: FL VM:3</para>
/// </summary>
public static ThreatRoiExtents: number = 1074794501;
/// <summary>
/// <para>(4010,1006) Threat ROI Bitmap</para>
/// <para> VR: OB VM:1</para>
/// </summary>
public static ThreatRoiBitmap: number = 1074794502;
/// <summary>
/// <para>(4010,1007) Route Segment ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static RouteSegmentId: number = 1074794503;
/// <summary>
/// <para>(4010,1008) Gantry Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static GantryType: number = 1074794504;
/// <summary>
/// <para>(4010,1009) OOI Owner Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static OoiOwnerType: number = 1074794505;
/// <summary>
/// <para>(4010,100A) Route Segment Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static RouteSegmentSequence: number = 1074794506;
/// <summary>
/// <para>(4010,1010) Potential Threat Object ID</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static PotentialThreatObjectId: number = 1074794512;
/// <summary>
/// <para>(4010,1011) Threat Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static ThreatSequence: number = 1074794513;
/// <summary>
/// <para>(4010,1012) Threat Category </para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ThreatCategory: number = 1074794514;
/// <summary>
/// <para>(4010,1013) Threat Category Description</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static ThreatCategoryDescription: number = 1074794515;
/// <summary>
/// <para>(4010,1014) ATD Ability Assessment</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AtdAbilityAssessment: number = 1074794516;
/// <summary>
/// <para>(4010,1015) ATD Assessment Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AtdAssessmentFlag: number = 1074794517;
/// <summary>
/// <para>(4010,1016) ATD Assessment Probability</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static AtdAssessmentProbability: number = 1074794518;
/// <summary>
/// <para>(4010,1017) Mass</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static Mass: number = 1074794519;
/// <summary>
/// <para>(4010,1018) Density</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static Density: number = 1074794520;
/// <summary>
/// <para>(4010,1019) Z Effective</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static ZEffective: number = 1074794521;
/// <summary>
/// <para>(4010,101A) Boarding Pass ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static BoardingPassId: number = 1074794522;
/// <summary>
/// <para>(4010,101B) Center of Mass</para>
/// <para> VR: FL VM:3</para>
/// </summary>
public static CenterOfMass: number = 1074794523;
/// <summary>
/// <para>(4010,101C) Center of PTO</para>
/// <para> VR: FL VM:3</para>
/// </summary>
public static CenterOfPto: number = 1074794524;
/// <summary>
/// <para>(4010,101D) Bounding Polygon</para>
/// <para> VR: FL VM:6-n</para>
/// </summary>
public static BoundingPolygon: number = 1074794525;
/// <summary>
/// <para>(4010,101E) Route Segment Start Location ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static RouteSegmentStartLocationId: number = 1074794526;
/// <summary>
/// <para>(4010,101F) Route Segment End Location ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static RouteSegmentEndLocationId: number = 1074794527;
/// <summary>
/// <para>(4010,1020) Route Segment Location ID Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static RouteSegmentLocationIdType: number = 1074794528;
/// <summary>
/// <para>(4010,1021) Abort Reason</para>
/// <para> VR: CS VM:1-n</para>
/// </summary>
public static AbortReason: number = 1074794529;
/// <summary>
/// <para>(4010,1023) Volume of PTO</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static VolumeOfPto: number = 1074794531;
/// <summary>
/// <para>(4010,1024) Abort Flag</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AbortFlag: number = 1074794532;
/// <summary>
/// <para>(4010,1025) Route Segment Start Time</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static RouteSegmentStartTime: number = 1074794533;
/// <summary>
/// <para>(4010,1026) Route Segment End Time</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static RouteSegmentEndTime: number = 1074794534;
/// <summary>
/// <para>(4010,1027) TDR Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TdrType: number = 1074794535;
/// <summary>
/// <para>(4010,1028) International Route Segment</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static InternationalRouteSegment: number = 1074794536;
/// <summary>
/// <para>(4010,1029) Threat Detection Algorithm and Version</para>
/// <para> VR: LO VM:1-n</para>
/// </summary>
public static ThreatDetectionAlgorithmAndVersion: number = 1074794537;
/// <summary>
/// <para>(4010,102A) Assigned Location </para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static AssignedLocation: number = 1074794538;
/// <summary>
/// <para>(4010,102B) Alarm Decision Time</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static AlarmDecisionTime: number = 1074794539;
/// <summary>
/// <para>(4010,1031) Alarm Decision</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AlarmDecision: number = 1074794545;
/// <summary>
/// <para>(4010,1033) Number of Total Objects</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfTotalObjects: number = 1074794547;
/// <summary>
/// <para>(4010,1034) Number of Alarm Objects</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static NumberOfAlarmObjects: number = 1074794548;
/// <summary>
/// <para>(4010,1037) PTO Representation Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PtoRepresentationSequence: number = 1074794551;
/// <summary>
/// <para>(4010,1038) ATD Assessment Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AtdAssessmentSequence: number = 1074794552;
/// <summary>
/// <para>(4010,1039) TIP Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TipType: number = 1074794553;
/// <summary>
/// <para>(4010,103A) DICOS Version</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static DicosVersion: number = 1074794554;
/// <summary>
/// <para>(4010,1041) OOI Owner Creation Time</para>
/// <para> VR: DT VM:1</para>
/// </summary>
public static OoiOwnerCreationTime: number = 1074794561;
/// <summary>
/// <para>(4010,1042) OOI Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static OoiType: number = 1074794562;
/// <summary>
/// <para>(4010,1043) OOI Size</para>
/// <para> VR: FL VM:3</para>
/// </summary>
public static OoiSize: number = 1074794563;
/// <summary>
/// <para>(4010,1044) Acquisition Status</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static AcquisitionStatus: number = 1074794564;
/// <summary>
/// <para>(4010,1045) Basis Materials Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static BasisMaterialsCodeSequence: number = 1074794565;
/// <summary>
/// <para>(4010,1046) Phantom Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static PhantomType: number = 1074794566;
/// <summary>
/// <para>(4010,1047) OOI Owner Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static OoiOwnerSequence: number = 1074794567;
/// <summary>
/// <para>(4010,1048) Scan Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static ScanType: number = 1074794568;
/// <summary>
/// <para>(4010,1051) Itinerary ID</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ItineraryId: number = 1074794577;
/// <summary>
/// <para>(4010,1052) Itinerary ID Type</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static ItineraryIdType: number = 1074794578;
/// <summary>
/// <para>(4010,1053) Itinerary ID Assigning Authority</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static ItineraryIdAssigningAuthority: number = 1074794579;
/// <summary>
/// <para>(4010,1054) Route ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static RouteId: number = 1074794580;
/// <summary>
/// <para>(4010,1055) Route ID Assigning Authority</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static RouteIdAssigningAuthority: number = 1074794581;
/// <summary>
/// <para>(4010,1056) Inbound Arrival Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static InboundArrivalType: number = 1074794582;
/// <summary>
/// <para>(4010,1058) Carrier ID</para>
/// <para> VR: SH VM:1</para>
/// </summary>
public static CarrierId: number = 1074794584;
/// <summary>
/// <para>(4010,1059) Carrier ID Assigning Authority</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static CarrierIdAssigningAuthority: number = 1074794585;
/// <summary>
/// <para>(4010,1060) Source Orientation</para>
/// <para> VR: FL VM:3</para>
/// </summary>
public static SourceOrientation: number = 1074794592;
/// <summary>
/// <para>(4010,1061) Source Position</para>
/// <para> VR: FL VM:3</para>
/// </summary>
public static SourcePosition: number = 1074794593;
/// <summary>
/// <para>(4010,1062) Belt Height</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static BeltHeight: number = 1074794594;
/// <summary>
/// <para>(4010,1064) Algorithm Routing Code Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static AlgorithmRoutingCodeSequence: number = 1074794596;
/// <summary>
/// <para>(4010,1067) Transport Classification</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static TransportClassification: number = 1074794599;
/// <summary>
/// <para>(4010,1068) OOI Type Descriptor</para>
/// <para> VR: LT VM:1</para>
/// </summary>
public static OoiTypeDescriptor: number = 1074794600;
/// <summary>
/// <para>(4010,1069) Total Processing Time</para>
/// <para> VR: FL VM:1</para>
/// </summary>
public static TotalProcessingTime: number = 1074794601;
/// <summary>
/// <para>(4010,106C) Detector Calibration Data</para>
/// <para> VR: OB VM:1</para>
/// </summary>
public static DetectorCalibrationData: number = 1074794604;
/// <summary>
/// <para>(4FFE,0001) MAC Parameters Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static MacParametersSequence: number = 1342046209;
/// <summary>
/// <para>(5000,0005) Curve Dimensions </para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CurveDimensionsRetired: number = 1342177285;
/// <summary>
/// <para>(5000,0010) Number of Points </para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static NumberOfPointsRetired: number = 1342177296;
/// <summary>
/// <para>(5000,0020) Type of Data</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TypeOfDataRetired: number = 1342177312;
/// <summary>
/// <para>(5000,0022) Curve Description</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CurveDescriptionRetired: number = 1342177314;
/// <summary>
/// <para>(5000,0030) Axis Units </para>
/// <para> VR: SH VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AxisUnitsRetired: number = 1342177328;
/// <summary>
/// <para>(5000,0040) Axis Labels </para>
/// <para> VR: SH VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AxisLabelsRetired: number = 1342177344;
/// <summary>
/// <para>(5000,0103) Data Value Representation </para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static DataValueRepresentationRetired: number = 1342177539;
/// <summary>
/// <para>(5000,0104) Minimum Coordinate Value </para>
/// <para> VR: US VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static MinimumCoordinateValueRetired: number = 1342177540;
/// <summary>
/// <para>(5000,0105) Maximum Coordinate Value </para>
/// <para> VR: US VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static MaximumCoordinateValueRetired: number = 1342177541;
/// <summary>
/// <para>(5000,0106) Curve Range</para>
/// <para> VR: SH VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CurveRangeRetired: number = 1342177542;
/// <summary>
/// <para>(5000,0110) Curve Data Descriptor</para>
/// <para> VR: US VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CurveDataDescriptorRetired: number = 1342177552;
/// <summary>
/// <para>(5000,0112) Coordinate Start Value</para>
/// <para> VR: US VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CoordinateStartValueRetired: number = 1342177554;
/// <summary>
/// <para>(5000,0114) Coordinate Step Value</para>
/// <para> VR: US VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CoordinateStepValueRetired: number = 1342177556;
/// <summary>
/// <para>(5000,1001) Curve Activation Layer </para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CurveActivationLayerRetired: number = 1342181377;
/// <summary>
/// <para>(5000,2000) Audio Type</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AudioTypeRetired: number = 1342185472;
/// <summary>
/// <para>(5000,2002) Audio Sample Format</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AudioSampleFormatRetired: number = 1342185474;
/// <summary>
/// <para>(5000,2004) Number of Channels</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static NumberOfChannelsRetired: number = 1342185476;
/// <summary>
/// <para>(5000,2006) Number of Samples</para>
/// <para> VR: UL VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static NumberOfSamplesRetired: number = 1342185478;
/// <summary>
/// <para>(5000,2008) Sample Rate</para>
/// <para> VR: UL VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static SampleRateRetired: number = 1342185480;
/// <summary>
/// <para>(5000,200A) Total Time</para>
/// <para> VR: UL VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static TotalTimeRetired: number = 1342185482;
/// <summary>
/// <para>(5000,200C) Audio Sample Data</para>
/// <para> VR: OW or OB VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AudioSampleDataRetired: number = 1342185484;
/// <summary>
/// <para>(5000,200E) Audio Comments</para>
/// <para> VR: LT VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static AudioCommentsRetired: number = 1342185486;
/// <summary>
/// <para>(5000,2500) Curve Label</para>
/// <para> VR: LO VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CurveLabelRetired: number = 1342186752;
/// <summary>
/// <para>(5000,2600) Curve Referenced Overlay Sequence </para>
/// <para> VR: SQ VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CurveReferencedOverlaySequenceRetired: number = 1342187008;
/// <summary>
/// <para>(5000,2610) Curve Referenced Overlay Group</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CurveReferencedOverlayGroupRetired: number = 1342187024;
/// <summary>
/// <para>(5000,3000) Curve Data</para>
/// <para> VR: OW or OB VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CurveDataRetired: number = 1342189568;
/// <summary>
/// <para>(5200,9229) Shared Functional Groups Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static SharedFunctionalGroupsSequence: number = 1375769129;
/// <summary>
/// <para>(5200,9230) Per-frame Functional Groups Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static PerFrameFunctionalGroupsSequence: number = 1375769136;
/// <summary>
/// <para>(5400,0100) Waveform Sequence </para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static WaveformSequence: number = 1409286400;
/// <summary>
/// <para>(5400,0110) Channel Minimum Value </para>
/// <para> VR: OB or OW VM:1</para>
/// </summary>
public static ChannelMinimumValue: number = 1409286416;
/// <summary>
/// <para>(5400,0112) Channel Maximum Value </para>
/// <para> VR: OB or OW VM:1</para>
/// </summary>
public static ChannelMaximumValue: number = 1409286418;
/// <summary>
/// <para>(5400,1004) Waveform Bits Allocated</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static WaveformBitsAllocated: number = 1409290244;
/// <summary>
/// <para>(5400,1006) Waveform Sample Interpretation</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static WaveformSampleInterpretation: number = 1409290246;
/// <summary>
/// <para>(5400,100A) Waveform Padding Value</para>
/// <para> VR: OB or OW VM:1</para>
/// </summary>
public static WaveformPaddingValue: number = 1409290250;
/// <summary>
/// <para>(5400,1010) Waveform Data </para>
/// <para> VR: OB or OW VM:1</para>
/// </summary>
public static WaveformData: number = 1409290256;
/// <summary>
/// <para>(5600,0010) First Order Phase Correction Angle</para>
/// <para> VR: OF VM:1</para>
/// </summary>
public static FirstOrderPhaseCorrectionAngle: number = 1442840592;
/// <summary>
/// <para>(5600,0020) Spectroscopy Data</para>
/// <para> VR: OF VM:1</para>
/// </summary>
public static SpectroscopyData: number = 1442840608;
/// <summary>
/// <para>(6000,0010) Overlay Rows</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static OverlayRows: number = 1610612752;
/// <summary>
/// <para>(6000,0011) Overlay Columns</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static OverlayColumns: number = 1610612753;
/// <summary>
/// <para>(6000,0012) Overlay Planes</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayPlanesRetired: number = 1610612754;
/// <summary>
/// <para>(6000,0015) Number of Frames in Overlay</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static NumberOfFramesInOverlay: number = 1610612757;
/// <summary>
/// <para>(6000,0022) Overlay Description</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static OverlayDescription: number = 1610612770;
/// <summary>
/// <para>(6000,0040) Overlay Type</para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static OverlayType: number = 1610612800;
/// <summary>
/// <para>(6000,0045) Overlay Subtype</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static OverlaySubtype: number = 1610612805;
/// <summary>
/// <para>(6000,0050) Overlay Origin</para>
/// <para> VR: SS VM:2</para>
/// </summary>
public static OverlayOrigin: number = 1610612816;
/// <summary>
/// <para>(6000,0051) Image Frame Origin</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static ImageFrameOrigin: number = 1610612817;
/// <summary>
/// <para>(6000,0052) Overlay Plane Origin</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayPlaneOriginRetired: number = 1610612818;
/// <summary>
/// <para>(6000,0060) Overlay Compression Code</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayCompressionCodeRetired: number = 1610612832;
/// <summary>
/// <para>(6000,0061) Overlay Compression Originator</para>
/// <para> VR: SH VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayCompressionOriginatorRetired: number = 1610612833;
/// <summary>
/// <para>(6000,0062) Overlay Compression Label</para>
/// <para> VR: SH VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayCompressionLabelRetired: number = 1610612834;
/// <summary>
/// <para>(6000,0063) Overlay Compression Description</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayCompressionDescriptionRetired: number = 1610612835;
/// <summary>
/// <para>(6000,0066) Overlay Compression Step Pointers</para>
/// <para> VR: AT VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayCompressionStepPointersRetired: number = 1610612838;
/// <summary>
/// <para>(6000,0068) Overlay Repeat Interval</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayRepeatIntervalRetired: number = 1610612840;
/// <summary>
/// <para>(6000,0069) Overlay Bits Grouped</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayBitsGroupedRetired: number = 1610612841;
/// <summary>
/// <para>(6000,0100) Overlay Bits Allocated</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static OverlayBitsAllocated: number = 1610612992;
/// <summary>
/// <para>(6000,0102) Overlay Bit Position</para>
/// <para> VR: US VM:1</para>
/// </summary>
public static OverlayBitPosition: number = 1610612994;
/// <summary>
/// <para>(6000,0110) Overlay Format</para>
/// <para> VR: CS VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayFormatRetired: number = 1610613008;
/// <summary>
/// <para>(6000,0200) Overlay Location</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayLocationRetired: number = 1610613248;
/// <summary>
/// <para>(6000,0800) Overlay Code Label</para>
/// <para> VR: CS VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayCodeLabelRetired: number = 1610614784;
/// <summary>
/// <para>(6000,0802) Overlay Number of Tables</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayNumberOfTablesRetired: number = 1610614786;
/// <summary>
/// <para>(6000,0803) Overlay Code Table Location</para>
/// <para> VR: AT VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayCodeTableLocationRetired: number = 1610614787;
/// <summary>
/// <para>(6000,0804) Overlay Bits For Code Word</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayBitsForCodeWordRetired: number = 1610614788;
/// <summary>
/// <para>(6000,1001) Overlay Activation Layer </para>
/// <para> VR: CS VM:1</para>
/// </summary>
public static OverlayActivationLayer: number = 1610616833;
/// <summary>
/// <para>(6000,1100) Overlay Descriptor - Gray</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayDescriptorGrayRetired: number = 1610617088;
/// <summary>
/// <para>(6000,1101) Overlay Descriptor - Red</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayDescriptorRedRetired: number = 1610617089;
/// <summary>
/// <para>(6000,1102) Overlay Descriptor - Green</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayDescriptorGreenRetired: number = 1610617090;
/// <summary>
/// <para>(6000,1103) Overlay Descriptor - Blue</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayDescriptorBlueRetired: number = 1610617091;
/// <summary>
/// <para>(6000,1200) Overlays - Gray</para>
/// <para> VR: US VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlaysGrayRetired: number = 1610617344;
/// <summary>
/// <para>(6000,1201) Overlays - Red</para>
/// <para> VR: US VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlaysRedRetired: number = 1610617345;
/// <summary>
/// <para>(6000,1202) Overlays - Green</para>
/// <para> VR: US VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlaysGreenRetired: number = 1610617346;
/// <summary>
/// <para>(6000,1203) Overlays - Blue</para>
/// <para> VR: US VM:1-n</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlaysBlueRetired: number = 1610617347;
/// <summary>
/// <para>(6000,1301) ROI Area</para>
/// <para> VR: IS VM:1</para>
/// </summary>
public static RoiArea: number = 1610617601;
/// <summary>
/// <para>(6000,1302) ROI Mean</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static RoiMean: number = 1610617602;
/// <summary>
/// <para>(6000,1303) ROI Standard Deviation</para>
/// <para> VR: DS VM:1</para>
/// </summary>
public static RoiStandardDeviation: number = 1610617603;
/// <summary>
/// <para>(6000,1500) Overlay Label</para>
/// <para> VR: LO VM:1</para>
/// </summary>
public static OverlayLabel: number = 1610618112;
/// <summary>
/// <para>(6000,3000) Overlay Data</para>
/// <para> VR: OB or OW VM:1</para>
/// </summary>
public static OverlayData: number = 1610625024;
/// <summary>
/// <para>(6000,4000) Overlay Comments</para>
/// <para> VR: LT VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static OverlayCommentsRetired: number = 1610629120;
/// <summary>
/// <para>(7F00,0010) Variable Pixel Data</para>
/// <para> VR: OW or OB VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static VariablePixelDataRetired: number = 2130706448;
/// <summary>
/// <para>(7F00,0011) Variable Next Data Group</para>
/// <para> VR: US VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static VariableNextDataGroupRetired: number = 2130706449;
/// <summary>
/// <para>(7F00,0020) Variable Coefficients SDVN</para>
/// <para> VR: OW VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static VariableCoefficientsSdvnRetired: number = 2130706464;
/// <summary>
/// <para>(7F00,0030) Variable Coefficients SDHN</para>
/// <para> VR: OW VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static VariableCoefficientsSdhnRetired: number = 2130706480;
/// <summary>
/// <para>(7F00,0040) Variable Coefficients SDDN</para>
/// <para> VR: OW VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static VariableCoefficientsSddnRetired: number = 2130706496;
/// <summary>
/// <para>(7FE0,0010) Pixel Data</para>
/// <para> VR: OW or OB VM:1</para>
/// </summary>
public static PixelData: number = 2145386512;
/// <summary>
/// <para>(7FE0,0020) Coefficients SDVN</para>
/// <para> VR: OW VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CoefficientsSdvnRetired: number = 2145386528;
/// <summary>
/// <para>(7FE0,0030) Coefficients SDHN</para>
/// <para> VR: OW VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CoefficientsSdhnRetired: number = 2145386544;
/// <summary>
/// <para>(7FE0,0040) Coefficients SDDN</para>
/// <para> VR: OW VM:1</para>
/// <para>This tag has been retired.</para>
/// </summary>
public static CoefficientsSddnRetired: number = 2145386560;
/// <summary>
/// <para>(FFFA,FFFA) Digital Signatures Sequence</para>
/// <para> VR: SQ VM:1</para>
/// </summary>
public static DigitalSignaturesSequence: number = 4294639610;
/// <summary>
/// <para>(FFFC,FFFC) Data Set Trailing Padding</para>
/// <para> VR: OB VM:1</para>
/// </summary>
public static DataSetTrailingPadding: number = 4294770684;
} | the_stack |
import * as tslibType from 'tslib';
const tslib: typeof tslibType = require('tslib');
import { Observable } from '../data/observable';
import { trace as profilingTrace, time, uptime, level as profilingLevel } from '../profiling';
type ModuleLoader = (name?: string) => any;
interface Context {
keys(): string[];
(key: string): any;
}
interface ExtensionMap {
[originalFileExtension: string]: string;
}
function registerOnGlobalContext(moduleName: string, exportName: string): void {
Object.defineProperty(global, exportName, {
get: function () {
// We do not need to cache require() call since it is already cached in the runtime.
const m = global.loadModule(moduleName);
// Redefine the property to make sure the above code is executed only once.
const resolvedValue = m[exportName];
Object.defineProperty(global, exportName, {
value: resolvedValue,
configurable: true,
writable: true,
});
return resolvedValue;
},
configurable: true,
});
}
/**
* Manages internal framework global state
*/
export class NativeScriptGlobalState {
events: Observable;
launched = false;
// used by various classes to setup callbacks to wire up global app event handling when the app instance is ready
appEventWiring: Array<any>;
private _appInstanceReady = false;
private _setLaunched: () => void;
constructor() {
// console.log('creating NativeScriptGlobals...')
this.events = new Observable();
this._setLaunched = this._setLaunchedFn.bind(this);
this.events.on('launch', this._setLaunched);
if (profilingLevel() > 0) {
this.events.on('displayed', () => {
const duration = uptime();
const end = time();
const start = end - duration;
profilingTrace(`Displayed in ${duration.toFixed(2)}ms`, start, end);
});
}
}
get appInstanceReady() {
return this._appInstanceReady;
}
set appInstanceReady(value: boolean) {
this._appInstanceReady = value;
// app instance ready, wire up any app events waiting in startup queue
if (this.appEventWiring && this.appEventWiring.length) {
for (const callback of this.appEventWiring) {
callback();
}
// cleanup
this.appEventWiring = null;
}
}
/**
* Ability for classes to initialize app event handling early even before the app instance is ready during boot cycle avoiding boot race conditions
* @param callback wire up any global event handling inside the callback
*/
addEventWiring(callback: () => void) {
if (this._appInstanceReady) {
callback();
} else {
if (!this.appEventWiring) {
this.appEventWiring = [];
}
this.appEventWiring.push(callback);
}
}
private _setLaunchedFn() {
// console.log('NativeScriptGlobals launch fired!');
this.launched = true;
this.events.off('launch', this._setLaunched);
this._setLaunched = null;
}
}
export function installPolyfills(moduleName: string, exportNames: string[]) {
if (global.__snapshot) {
const loadedModule = global.loadModule(moduleName);
exportNames.forEach((exportName) => (global[exportName] = loadedModule[exportName]));
} else {
exportNames.forEach((exportName) => registerOnGlobalContext(moduleName, exportName));
}
}
export function initGlobal() {
if (!global.NativeScriptHasInitGlobal) {
global.NativeScriptHasInitGlobal = true;
// init global state handler
global.NativeScriptGlobals = new NativeScriptGlobalState();
// ts-helpers
// Required by V8 snapshot generator
if (!(<any>global).__extends) {
(<any>global).__extends = function (d, b) {
for (const p in b) {
if (b.hasOwnProperty(p)) {
d[p] = b[p];
}
}
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : ((__.prototype = b.prototype), new __());
};
}
// Bind the tslib helpers to global scope.
// This is needed when we don't use importHelpers, which
// breaks extending native-classes
for (const fnName of Object.keys(tslib)) {
if (typeof tslib[fnName] !== 'function') {
continue;
}
if (fnName in global) {
// Don't override globals that are already defined (ex. __extends)
continue;
}
global[fnName] = tslib[fnName];
}
// module helpers
const modules: Map<string, { moduleId: string; loader: ModuleLoader }> = new Map<string, { moduleId: string; loader: ModuleLoader }>();
const modulesLoadedForUI = new Set<string>();
const defaultExtensionMap: ExtensionMap = {
'.js': '.js',
'.ts': '.js',
'.kt': '.js',
'.css': '.css',
'.scss': '.css',
'.less': '.css',
'.sass': '.css',
'.xml': '.xml',
};
// Cast to <any> because moduleResolvers is read-only in definitions
(<any>global).moduleResolvers = [global.require];
global.registerModule = function (name: string, loader: ModuleLoader): void {
modules.set(name, { loader, moduleId: name });
};
global._unregisterModule = function _unregisterModule(name: string): void {
modules.delete(name);
};
global._isModuleLoadedForUI = function _isModuleLoadedForUI(moduleName: string): boolean {
return modulesLoadedForUI.has(moduleName);
};
global.registerWebpackModules = function registerWebpackModules(context: Context, extensionMap: ExtensionMap = {}) {
context.keys().forEach((moduleId) => {
const extDotIndex = moduleId.lastIndexOf('.');
const base = moduleId.substr(0, extDotIndex);
const originalExt = moduleId.substr(extDotIndex);
const registerExt = extensionMap[originalExt] || defaultExtensionMap[originalExt] || originalExt;
// We prefer source files for webpack scenarios before compilation leftovers,
// e. g. if we get a .js and .ts for the same module, the .js is probably the compiled version of the .ts file,
// so we register the .ts with higher priority, similar is the case with us preferring the .scss to .css
const isSourceFile = originalExt !== registerExt;
const registerName = base + registerExt;
const registerWithName = (nickName: string) => {
modules.set(nickName, {
moduleId,
loader: () => {
return context(moduleId);
},
});
};
if (registerName.startsWith('./') && registerName.endsWith('.js')) {
const jsNickNames = [
// This is extremely short version like "main-page" that was promoted to be used with global.registerModule("module-name", loaderFunc);
registerName.substr(2, registerName.length - 5),
// This is for supporting module names like "./main/main-page"
registerName.substr(0, registerName.length - 3),
// This is for supporting module names like "main/main-page.js"
registerName.substr(2),
];
jsNickNames.forEach((jsNickName) => {
if (isSourceFile || !global.moduleExists(jsNickName)) {
registerWithName(jsNickName);
}
});
} else if (registerName.startsWith('./')) {
const moduleNickNames = [
// This is for supporting module names like "main/main-page.xml"
registerName.substr(2),
];
moduleNickNames.forEach((moduleNickName) => {
if (!global.moduleExists(moduleNickName)) {
registerWithName(moduleNickName);
}
});
}
if (isSourceFile || !global.moduleExists(registerName)) {
registerWithName(registerName);
}
});
};
global.moduleExists = function moduleExists(name: string): boolean {
return modules.has(name);
};
global.loadModule = function loadModule(name: string, isUIModule = false): any {
const moduleInfo = modules.get(name);
if (moduleInfo) {
if (isUIModule) {
modulesLoadedForUI.add(moduleInfo.moduleId);
}
const result = moduleInfo.loader(name);
if (result.enableAutoAccept) {
result.enableAutoAccept();
}
return result;
}
for (const resolver of (<any>global).moduleResolvers) {
const result = resolver(name);
if (result) {
modules.set(name, { moduleId: name, loader: () => result });
return result;
}
}
};
global.getRegisteredModules = function getRegisteredModules(): string[] {
return Array.from(modules.keys());
};
/**
* Polyfills
*/
// This method iterates all the keys in the source exports object and copies them to the destination exports one.
// Note: the method will not check for naming collisions and will override any already existing entries in the destination exports.
global.moduleMerge = function (sourceExports: any, destExports: any) {
for (const key in sourceExports) {
destExports[key] = sourceExports[key];
}
};
global.zonedCallback = function (callback: Function): Function {
if ((<any>global).zone) {
// Zone v0.5.* style callback wrapping
return (<any>global).zone.bind(callback);
}
if ((<any>global).Zone) {
// Zone v0.6.* style callback wrapping
return (<any>global).Zone.current.wrap(callback);
} else {
return callback;
}
};
(<any>global).System = {
import(path) {
return new Promise((resolve, reject) => {
try {
resolve(global.require(path));
} catch (e) {
reject(e);
}
});
},
};
// DOM api polyfills
global.registerModule('timer', () => require('../timer'));
installPolyfills('timer', ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval']);
global.registerModule('animation', () => require('../animation-frame'));
installPolyfills('animation', ['requestAnimationFrame', 'cancelAnimationFrame']);
global.registerModule('ui-dialogs', () => require('../ui/dialogs'));
installPolyfills('ui-dialogs', ['alert', 'confirm', 'prompt', 'login', 'action']);
global.registerModule('text', () => require('../text'));
installPolyfills('text', ['TextDecoder', 'TextEncoder']);
global.registerModule('xhr', () => require('../xhr'));
installPolyfills('xhr', ['XMLHttpRequest', 'FormData', 'Blob', 'File', 'FileReader']);
global.registerModule('fetch', () => require('../fetch'));
installPolyfills('fetch', ['fetch', 'Headers', 'Request', 'Response']);
// global.registerModule('abortcontroller', () => require('../abortcontroller'));
// installPolyfills('abortcontroller', ['AbortController', 'AbortSignal']);
// Custom decorators
global.Deprecated = function (target: Object, key?: string | symbol, descriptor?: any) {
if (descriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`${key.toString()} is deprecated`);
return originalMethod.apply(this, args);
};
return descriptor;
} else {
console.log(`${(target && (<any>target).name) || target} is deprecated`);
return target;
}
};
global.Experimental = function (target: Object, key?: string | symbol, descriptor?: any) {
if (descriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`${key.toString()} is experimental`);
return originalMethod.apply(this, args);
};
return descriptor;
} else {
console.log(`${(target && (<any>target).name) || target} is experimental`);
return target;
}
};
}
}
if (!global.NativeScriptHasInitGlobal) {
initGlobal();
} | the_stack |
import { constants } from "@ts-ast-viewer/shared";
import CircularJson from "circular-json";
import React, { useEffect, useState } from "react";
import {
CommentRange,
CompilerApi,
FlowNode,
getPublicApiInfo,
getStartSafe,
Node,
PublicApiInfo,
ReadonlyMap,
Signature,
SourceFile,
Symbol,
Type,
TypeChecker,
} from "../compiler";
import { BindingTools, CompilerState } from "../types";
import { ArrayUtils, getEnumFlagNames, getSyntaxKindName } from "../utils";
import { LazyTreeView } from "./LazyTreeView";
import { Spinner } from "./Spinner";
import { ToolTippedText } from "./ToolTippedText";
export interface PropertiesViewerProps {
compiler: CompilerState;
sourceFile: SourceFile;
bindingTools: () => BindingTools;
selectedNode: Node;
bindingEnabled: boolean;
showInternals: boolean;
}
export function PropertiesViewer(props: PropertiesViewerProps) {
const [publicApiInfo, setPublicApiInfo] = useState<PublicApiInfo | false | undefined>(undefined);
useEffect(() => {
setPublicApiInfo(undefined);
getPublicApiInfo(props.compiler.packageName).then(publicApiInfo => {
setPublicApiInfo(publicApiInfo);
}).catch(err => {
console.error(err);
setPublicApiInfo(false);
});
}, [props.compiler.packageName]);
const { selectedNode, sourceFile, bindingEnabled, bindingTools } = props;
const context: Context = {
api: props.compiler.api,
publicApiInfo,
showInternals: props.showInternals,
sourceFile,
};
if (publicApiInfo == null) {
return <Spinner backgroundColor="#1e1e1e" />;
}
return (
<div className="propertiesViewer">
<div className="container">
<h2>Node</h2>
<div id={constants.css.properties.node.id}>
{getForSelectedNode(context, selectedNode)}
</div>
{bindingEnabled && getBindingSection(context, selectedNode, bindingTools().typeChecker)}
</div>
</div>
);
}
interface Context {
api: CompilerApi;
publicApiInfo: PublicApiInfo | undefined | false;
showInternals: boolean;
sourceFile: SourceFile;
}
function getBindingSection(context: Context, selectedNode: Node, typeChecker: TypeChecker) {
return (
<>
<h2>Type</h2>
<div id={constants.css.properties.type.id}>
{getForType(context, selectedNode, typeChecker)}
</div>
<h2>Symbol</h2>
<div id={constants.css.properties.symbol.id}>
{getForSymbol(context, selectedNode, typeChecker)}
</div>
<h2>Signature</h2>
<div id={constants.css.properties.signature.id}>
{getForSignature(context, selectedNode, typeChecker)}
</div>
<h2>FlowNode</h2>
<div>
{getForFlowNode(context, selectedNode, typeChecker)}
</div>
</>
);
}
function getForSelectedNode(context: Context, selectedNode: Node) {
return <LazyTreeView nodeLabel={getSyntaxKindName(context.api, selectedNode.kind)} defaultCollapsed={false} getChildren={getChildren} />;
function getChildren() {
const { sourceFile } = context;
return (
<>
{getProperties(context, selectedNode)}
{getMethodElement("getChildCount()", selectedNode.getChildCount(sourceFile))}
{getMethodElement("getFullStart()", selectedNode.getFullStart())}
{getMethodElement("getStart()", selectedNode.getStart(sourceFile))}
{getMethodElement("getStart(sourceFile, true)", getStartSafe(selectedNode, sourceFile))}
{getMethodElement("getFullWidth()", selectedNode.getFullWidth())}
{getMethodElement("getWidth()", selectedNode.getWidth(sourceFile))}
{getMethodElement("getLeadingTriviaWidth()", selectedNode.getLeadingTriviaWidth(sourceFile))}
{getMethodElement("getFullText()", selectedNode.getFullText(sourceFile))}
{/* Need to do this because internally typescript doesn't pass the sourceFile to getStart() in TokenOrIdentifierObject (bug in ts I need to report...) */}
{getMethodElement("getText()", sourceFile.text.substring(selectedNode.getStart(context.sourceFile), selectedNode.getEnd()))}
{/* comments */}
{getForCommentRanges(
`ts.getLeadingCommentRanges(fileFullText, ${selectedNode.getFullStart()})`,
context.api.getLeadingCommentRanges(context.sourceFile.text, selectedNode.getFullStart()),
)}
{getForCommentRanges(
`ts.getTrailingCommentRanges(fileFullText, ${selectedNode.end})`,
context.api.getTrailingCommentRanges(context.sourceFile.text, selectedNode.end),
)}
</>
);
}
function getMethodElement(name: string, result: string | number) {
return getTextDiv(name, typeof result === "string" ? result : JSON.stringify(result));
}
function getForCommentRanges(name: string, commentRanges: CommentRange[] | undefined) {
if (commentRanges == null) {
return getTextDiv(name, "undefined");
} else {
return getArrayDiv(context, name, commentRanges);
}
}
}
function getForType(context: Context, node: Node, typeChecker: TypeChecker) {
if (node.kind === context.api.SyntaxKind.SourceFile) {
return <>[None]</>;
}
const type = getOrReturnError(() => typeChecker.getTypeAtLocation(node));
if (type == null) {
return <>[None]</>;
}
if (typeof type === "string") {
return <>[Error getting type: {type}]</>;
}
return getTreeView(context, type, getTypeToString() || "Type");
function getTypeToString() {
try {
return typeChecker.typeToString(type as Type, node);
} catch (err) {
return `[Problem getting type text: ${err}]`;
}
}
}
function getForSymbol(context: Context, node: Node, typeChecker: TypeChecker) {
const symbol = getOrReturnError(() => ((node as any).symbol as Symbol | undefined) || typeChecker.getSymbolAtLocation(node));
if (symbol == null) {
return <>[None]</>;
}
if (typeof symbol === "string") {
return <>[Error getting symbol: {symbol}]</>;
}
return getTreeView(context, symbol, getSymbolName() || "Symbol");
function getSymbolName() {
try {
return (symbol as Symbol).getName();
} catch (err) {
return `[Problem getting symbol name: ${err}]`;
}
}
}
function getForSignature(context: Context, node: Node, typeChecker: TypeChecker) {
const signature = getOrReturnError(() => typeChecker.getSignatureFromDeclaration(node as any));
if (signature == null || typeof signature === "string") {
return <>[None]</>;
}
return getTreeView(context, signature, "Signature");
}
function getForFlowNode(context: Context, node: Node, typeChecker: TypeChecker) {
const nodeWithFlowNode = node as Node & { flowNode?: FlowNode };
if (nodeWithFlowNode.flowNode == null) {
return <>[None]</>;
}
return getTreeView(context, nodeWithFlowNode.flowNode, "FlowNode");
}
function getOrReturnError<T>(getFunc: () => T): T | string {
try {
return getFunc();
} catch (err) {
return JSON.stringify(err);
}
}
function getTreeView(context: Context, obj: any, label: string) {
return <LazyTreeView nodeLabel={label} defaultCollapsed={false} getChildren={() => getProperties(context, obj)} />;
}
function getProperties(context: Context, obj: any) {
const keyInfo = getObjectKeyInfo(context, obj);
const values = (
<>
{keyInfo.map(info => {
const element = getNodeKeyValue(info.key, info.value, obj);
if (info.permission === "internal") {
return (
<div className="internal" key={info.key} data-name={info.key}>
{element}
</div>
);
}
return element;
})}
</>
);
return values;
function getNodeKeyValue(key: string, value: any, parent: any): JSX.Element {
if (value === null) {
return getTextDiv(key, "null");
} else if (value === undefined) {
return getTextDiv(key, "undefined");
} else if (value instanceof Array) {
return getArrayDiv(context, key, value);
} else if (isTsNode(value)) {
return getNodeDiv(context, key, value);
} else if (isMap(value)) {
return getMapDiv(context, key, value);
} else if (typeof value === "object") {
return getObjectDiv(context, key, value);
} else {
return getCustomValueDiv(context, key, value, parent);
}
}
}
function getArrayDiv(context: Context, key: string, value: unknown[]) {
if (value.length === 0) {
return getTextDiv(key, "[]");
} else {
return (
<div className="array" key={key} data-name={key}>
<div className="key">{key}: [</div>
<div className="value">{value.map((v, i) => getTreeNode(context, v, undefined, i))}</div>
<div className="suffix">]</div>
</div>
);
}
}
function getMapDiv(context: Context, key: string, value: ReadonlyMap<unknown>) {
const entries = ArrayUtils.from(value.entries());
if (entries.length === 0) {
return getTextDiv(key, "{}");
} else {
return (
<div className="array" key={key} data-name={key}>
<div className="key">{key}:{"{"}</div>
<div className="value">{entries.map((v, i) => getTreeNode(context, v[1], v[0], i))}</div>
<div className="suffix">{"}"}</div>
</div>
);
}
}
function getObjectDiv(context: Context, key: string, value: unknown) {
if (getObjectKeyInfo(context, value).length === 0) {
return getTextDiv(key, "{}");
} else {
return (
<div className="object" key={key} data-name={key}>
<div className="key">{key}:</div>
<div className="value">{getTreeNode(context, value)}</div>
</div>
);
}
}
function getCustomValueDiv(context: Context, key: string, value: any, parent: any) {
return (
<div className="text" key={key} data-name={key}>
<div className="key">{key}:</div>
<div className="value">{getCustomValue()}</div>
</div>
);
function getCustomValue() {
if (isTsNode(parent)) {
switch (key) {
case "kind":
return `${value} (SyntaxKind.${getSyntaxKindName(context.api, value)})`;
case "flags":
return getEnumFlagElement(context.api.NodeFlags, value);
}
}
if (isTsType(parent) && key === "objectFlags") {
return getEnumFlagElement(context.api.ObjectFlags, value);
}
if (isTsType(parent) && key === "flags") {
return getEnumFlagElement(context.api.TypeFlags, value);
}
if (isTsSymbol(parent) && key === "flags") {
return getEnumFlagElement(context.api.SymbolFlags, value);
}
if (isFlowNode(parent) && key === "flags") {
return getEnumFlagElement(context.api.FlowFlags, value);
}
return CircularJson.stringify(value);
}
}
function getNodeDiv(context: Context, key: string, value: Node) {
return (
<div className="object" key={key} data-name={key}>
<div className="key">{key}:</div>
<div className="value">{getTreeNode(context, value)}</div>
</div>
);
}
function getTextDiv(key: string | undefined, value: string) {
return (
<div className="text" key={key} data-name={key}>
{key == null ? undefined : <div className="key">{key}:</div>}
<div className="value">{value}</div>
</div>
);
}
function getTreeNode(context: Context, value: any, key?: string, index?: number): JSX.Element {
const labelName = getLabelName(context, value);
key = getKey();
if (typeof value === "string") {
return getTextDiv(key, `"${value}"`);
}
if (typeof value === "number") {
return getTextDiv(key, value.toString());
}
if (typeof value === "boolean") {
return getTextDiv(key, value.toString());
}
return <LazyTreeView nodeLabel={key} key={index} defaultCollapsed={true} getChildren={() => getProperties(context, value)} />;
function getKey() {
if (key == null) {
return labelName;
} else if (labelName != null) {
return `${key}: ${getLabelName(context, value)}`;
}
return key;
}
}
function getLabelName(context: Context, obj: any) {
if (obj == null) {
return undefined;
}
if (isTsNode(obj)) {
return appendName(getSyntaxKindName(context.api, obj.kind));
}
if (isTsSignature(obj)) {
return appendName("Signature");
}
if (isTsType(obj)) {
return appendName("Type");
}
if (isTsSymbol(obj)) {
return appendName("Symbol");
}
const objType = typeof obj;
if (objType === "string" || objType === "number" || objType === "boolean") {
return undefined;
}
return appendName("Object");
function appendName(title: string) {
const name = getName();
return name == null ? title : `${title} (${name})`;
}
function getName() {
try {
if (typeof obj.getName === "function") {
return obj.getName();
}
if (isTsNode(obj) && (obj as any).name != null) {
const name = (obj as any).name as Node;
return name.getText();
}
return undefined;
} catch (err) {
return undefined;
}
}
}
function getObjectKeyInfo(context: Context, obj: any) {
if (obj == null) {
return [];
}
return Object.keys(obj)
.map(key => ({
key,
permission: getKeyPermission(context, obj, key),
value: obj[key],
}))
.filter(kv => {
if (kv.permission === false) {
return false;
}
return context.showInternals || kv.permission !== "internal";
});
}
const nodeDisallowedKeys = new Set(["parent", "_children", "symbol"]);
const typeDisallowedKeys = new Set(["checker", "symbol"]);
function getKeyPermission(context: Context, obj: any, key: string): true | false | "internal" {
const { publicApiInfo } = context;
if (isTsNode(obj)) {
if (nodeDisallowedKeys.has(key)) {
return false;
}
if (!publicApiInfo) {
return true;
}
const kindName = getSyntaxKindName(context.api, obj.kind);
return hasInProperties(publicApiInfo.nodePropertiesBySyntaxKind.get(kindName));
}
if (isTsType(obj)) {
return !typeDisallowedKeys.has(key) && hasInProperties(publicApiInfo && publicApiInfo.typeProperties);
}
if (isTsSignature(obj)) {
return hasInProperties(publicApiInfo && publicApiInfo.signatureProperties);
}
if (isTsSymbol(obj)) {
return hasInProperties(publicApiInfo && publicApiInfo.symbolProperties);
}
return true;
function hasInProperties(publicApiProperties: Set<string> | undefined | false) {
if (!publicApiProperties) {
return true;
}
return publicApiProperties.has(key) ? true : "internal";
}
}
function isMap(value: any): value is ReadonlyMap<unknown> {
return typeof value.keys === "function"
&& typeof value.values === "function";
}
function isTsNode(value: any): value is Node {
return typeof (value as Node).kind === "number";
}
function isTsType(value: any): value is Type {
return (value as Type).getBaseTypes != null;
}
function isTsSymbol(value: any): value is Symbol {
return (value as Symbol).getDeclarations != null;
}
function isTsSignature(value: any): value is Signature {
if (value.declaration == null) {
return false;
}
return isTsNode(value.declaration);
}
function isFlowNode(value: any): value is FlowNode {
// TODO: FlowStart does not have antecedent(s)
return value.antecedents != null || value.antecedent != null;
}
function getEnumFlagElement(enumObj: any, value: number) {
const names = getEnumFlagNames(enumObj, value);
if (names.length === 0) {
return <>{value}</>;
}
return <ToolTippedText text={value.toString()}>{getNames()}</ToolTippedText>;
function getNames() {
return <ul>{names.map((name, i) => <li key={i}>{name}</li>)}</ul>;
}
} | the_stack |
import GL from '@luma.gl/constants';
import Resource, {ResourceProps} from './resource';
import Texture from './texture';
import Framebuffer from './framebuffer';
import {parseUniformName, getUniformSetter} from './uniforms';
import {VertexShader, FragmentShader} from './shader';
import ProgramConfiguration from './program-configuration';
import {copyUniform, checkUniformValues} from './uniforms';
import {isWebGL2, assertWebGL2Context, withParameters, log} from '@luma.gl/gltools';
import {getKey} from '../webgl-utils';
import {getPrimitiveDrawMode} from '../webgl-utils/attribute-utils';
import {uid, assert} from '../utils';
const LOG_PROGRAM_PERF_PRIORITY = 4;
const GL_SEPARATE_ATTRIBS = 0x8c8d;
export type ProgramProps = ResourceProps & {
hash?;
vs?;
fs?;
varyings?;
bufferMode?: number;
}
export type ProgramDrawOptions = {
logPriority?: any;
drawMode?: any;
vertexCount: any;
offset?: number;
start?: any;
end?: any;
isIndexed?: boolean;
indexType?: any;
instanceCount?: number;
isInstanced?: boolean;
vertexArray?: any;
transformFeedback?: any;
framebuffer?: any;
parameters?: {};
uniforms?: any;
samplers?: any;
};
export default class Program extends Resource {
configuration: ProgramConfiguration;
// Experimental flag to avoid deleting Program object while it is cached
_isCached = false;
_textureIndexCounter = 0;
hash: string;; // Used by ProgramManager
vs;
fs;
uniforms: {};
_textureUniforms: {};
varyings: {};
_uniformCount = 0;
_uniformSetters: {};
constructor(gl: WebGLRenderingContext, props: ProgramProps = {}) {
super(gl, props);
this.initialize(props);
Object.seal(this);
this._setId(props.id);
}
initialize(props: ProgramProps = {}) {
const {hash, vs, fs, varyings, bufferMode = GL_SEPARATE_ATTRIBS} = props;
this.hash = hash || ''; // Used by ProgramManager
// Create shaders if needed
this.vs =
typeof vs === 'string' ? new VertexShader(this.gl, {id: `${props.id}-vs`, source: vs}) : vs;
this.fs =
typeof fs === 'string' ? new FragmentShader(this.gl, {id: `${props.id}-fs`, source: fs}) : fs;
assert(this.vs instanceof VertexShader);
assert(this.fs instanceof FragmentShader);
// uniforms
this.uniforms = {};
this._textureUniforms = {};
// Setup varyings if supplied
if (varyings && varyings.length > 0) {
assertWebGL2Context(this.gl);
this.varyings = varyings;
this.gl2.transformFeedbackVaryings(this.handle, varyings, bufferMode);
}
this._compileAndLink();
this._readUniformLocationsFromLinkedProgram();
this.configuration = new ProgramConfiguration(this);
return this.setProps(props);
}
delete(options = {}) {
if (this._isCached) {
// This object is cached, do not delete
return this;
}
return super.delete(options);
}
setProps(props) {
if ('uniforms' in props) {
this.setUniforms(props.uniforms);
}
return this;
}
// A good thing about the WebGL API is that there are so many ways to draw things ;)
// This function unifies those ways into a single call using common parameters with sane defaults
draw(options: ProgramDrawOptions): boolean {
const {
logPriority, // Probe log priority, enables Model to do more integrated logging
drawMode = GL.TRIANGLES,
vertexCount,
offset = 0,
start,
end,
isIndexed = false,
indexType = GL.UNSIGNED_SHORT,
instanceCount = 0,
isInstanced = instanceCount > 0,
vertexArray = null,
transformFeedback,
framebuffer,
// Deprecated
uniforms,
samplers
} = options;
let {parameters = {}} = options;
if (uniforms || samplers) {
// DEPRECATED: v7.0 (deprecated earlier but warning not properly implemented)
log.deprecated('Program.draw({uniforms})', 'Program.setUniforms(uniforms)')();
this.setUniforms(uniforms || {});
}
if (log.priority >= logPriority) {
const fb = framebuffer ? framebuffer.id : 'default';
const message =
`mode=${getKey(this.gl, drawMode)} verts=${vertexCount} ` +
`instances=${instanceCount} indexType=${getKey(this.gl, indexType)} ` +
`isInstanced=${isInstanced} isIndexed=${isIndexed} ` +
`Framebuffer=${fb}`;
log.log(logPriority, message)();
}
// TODO - move vertex array binding and transform feedback binding to withParameters?
assert(vertexArray);
this.gl.useProgram(this.handle);
if (
// Note: async textures set as uniforms might still be loading.
// Now that all uniforms have been updated, check if any texture
// in the uniforms is not yet initialized, then we don't draw
!this._areTexturesRenderable() ||
// Avoid WebGL draw call when not rendering any data
vertexCount === 0 ||
(isInstanced && instanceCount === 0)
) {
return false;
}
vertexArray.bindForDraw(vertexCount, instanceCount, () => {
if (framebuffer !== undefined) {
parameters = Object.assign({}, parameters, {framebuffer});
}
if (transformFeedback) {
const primitiveMode = getPrimitiveDrawMode(drawMode);
transformFeedback.begin(primitiveMode);
}
this._bindTextures();
withParameters(this.gl, parameters, () => {
// TODO - Use polyfilled WebGL2RenderingContext instead of ANGLE extension
if (isIndexed && isInstanced) {
this.gl2.drawElementsInstanced(drawMode, vertexCount, indexType, offset, instanceCount);
} else if (isIndexed && isWebGL2(this.gl) && !isNaN(start) && !isNaN(end)) {
this.gl2.drawRangeElements(drawMode, start, end, vertexCount, indexType, offset);
} else if (isIndexed) {
this.gl.drawElements(drawMode, vertexCount, indexType, offset);
} else if (isInstanced) {
this.gl2.drawArraysInstanced(drawMode, offset, vertexCount, instanceCount);
} else {
this.gl.drawArrays(drawMode, offset, vertexCount);
}
});
if (transformFeedback) {
transformFeedback.end();
}
});
return true;
}
setUniforms(uniforms = {}) {
if (log.priority >= 2) {
checkUniformValues(uniforms, this.id, this._uniformSetters);
}
this.gl.useProgram(this.handle);
for (const uniformName in uniforms) {
const uniform = uniforms[uniformName];
const uniformSetter = this._uniformSetters[uniformName];
if (uniformSetter) {
let value = uniform;
let textureUpdate = false;
if (value instanceof Framebuffer) {
value = value.texture;
}
if (value instanceof Texture) {
textureUpdate = this.uniforms[uniformName] !== uniform;
if (textureUpdate) {
// eslint-disable-next-line max-depth
if (uniformSetter.textureIndex === undefined) {
uniformSetter.textureIndex = this._textureIndexCounter++;
}
// Bind texture to index
const texture = value;
const {textureIndex} = uniformSetter;
texture.bind(textureIndex);
value = textureIndex;
this._textureUniforms[uniformName] = texture;
} else {
value = uniformSetter.textureIndex;
}
} else if (this._textureUniforms[uniformName]) {
delete this._textureUniforms[uniformName];
}
// NOTE(Tarek): uniformSetter returns whether
// value had to be updated or not.
if (uniformSetter(value) || textureUpdate) {
copyUniform(this.uniforms, uniformName, uniform);
}
}
}
return this;
}
// PRIVATE METHODS
// Checks if all texture-values uniforms are renderable (i.e. loaded)
// Update a texture if needed (e.g. from video)
// Note: This is currently done before every draw call
_areTexturesRenderable() {
let texturesRenderable = true;
for (const uniformName in this._textureUniforms) {
const texture = this._textureUniforms[uniformName];
texture.update();
texturesRenderable = texturesRenderable && texture.loaded;
}
return texturesRenderable;
}
// Binds textures
// Note: This is currently done before every draw call
_bindTextures() {
for (const uniformName in this._textureUniforms) {
const textureIndex = this._uniformSetters[uniformName].textureIndex;
this._textureUniforms[uniformName].bind(textureIndex);
}
}
// RESOURCE METHODS
_createHandle() {
return this.gl.createProgram();
}
_deleteHandle() {
this.gl.deleteProgram(this.handle);
}
// Extract opts needed to initialize a `Program` from an independently created WebGLProgram handle
_getOptionsFromHandle(handle) {
const shaderHandles = this.gl.getAttachedShaders(handle);
const opts = {};
for (const shaderHandle of shaderHandles) {
const type = this.gl.getShaderParameter(this.handle, GL.SHADER_TYPE);
switch (type) {
case GL.VERTEX_SHADER:
// @ts-ignore
opts.vs = new VertexShader({handle: shaderHandle});
break;
case GL.FRAGMENT_SHADER:
// @ts-ignore
opts.fs = new FragmentShader({handle: shaderHandle});
break;
default:
}
}
return opts;
}
_getParameter(pname) {
return this.gl.getProgramParameter(this.handle, pname);
}
// If program is not named, name it after shader names
// TODO - this.id will already have been initialized
_setId(id) {
if (!id) {
const programName = this._getName();
this.id = uid(programName);
}
}
// Generate a default name for the program based on names of the shaders
_getName() {
let programName = this.vs.getName() || this.fs.getName();
programName = programName.replace(/shader/i, '');
programName = programName ? `${programName}-program` : 'program';
return programName;
}
_compileAndLink() {
const {gl} = this;
gl.attachShader(this.handle, this.vs.handle);
gl.attachShader(this.handle, this.fs.handle);
log.time(LOG_PROGRAM_PERF_PRIORITY, `linkProgram for ${this._getName()}`)();
gl.linkProgram(this.handle);
log.timeEnd(LOG_PROGRAM_PERF_PRIORITY, `linkProgram for ${this._getName()}`)();
// Avoid checking program linking error in production
// @ts-ignore
if (gl.debug || log.level > 0) {
const linked = gl.getProgramParameter(this.handle, gl.LINK_STATUS);
if (!linked) {
throw new Error(`Error linking: ${gl.getProgramInfoLog(this.handle)}`);
}
gl.validateProgram(this.handle);
const validated = gl.getProgramParameter(this.handle, gl.VALIDATE_STATUS);
if (!validated) {
throw new Error(`Error validating: ${gl.getProgramInfoLog(this.handle)}`);
}
}
}
// query uniform locations and build name to setter map.
// TODO - This overlaps with ProgramConfiguration?
_readUniformLocationsFromLinkedProgram() {
const {gl} = this;
this._uniformSetters = {};
this._uniformCount = this._getParameter(GL.ACTIVE_UNIFORMS);
for (let i = 0; i < this._uniformCount; i++) {
const info = this.gl.getActiveUniform(this.handle, i);
const {name} = parseUniformName(info.name);
let location = gl.getUniformLocation(this.handle, name);
// @ts-expect-error
this._uniformSetters[name] = getUniformSetter(gl, location, info);
if (info.size > 1) {
for (let l = 0; l < info.size; l++) {
location = gl.getUniformLocation(this.handle, `${name}[${l}]`);
// @ts-expect-error
this._uniformSetters[`${name}[${l}]`] = getUniformSetter(gl, location, info);
}
}
}
this._textureIndexCounter = 0;
}
// TO BE REMOVED in v7?
// Rretrieves information about active uniforms identifed by their indices (`uniformIndices`)
// https://
// developer.mozilla.org/en-US/docs/Web/API/WebGL2RenderingContext/getActiveUniforms
getActiveUniforms(uniformIndices, pname) {
return this.gl2.getActiveUniforms(this.handle, uniformIndices, pname);
}
// Retrieves the index of a uniform block
getUniformBlockIndex(blockName) {
return this.gl2.getUniformBlockIndex(this.handle, blockName);
}
// Retrieves information about an active uniform block (`blockIndex`)
// https://
// developer.mozilla.org/en-US/docs/Web/API/WebGL2RenderingContext/getActiveUniformBlockParameter
getActiveUniformBlockParameter(blockIndex, pname) {
return this.gl2.getActiveUniformBlockParameter(this.handle, blockIndex, pname);
}
// Binds a uniform block (`blockIndex`) to a specific binding point (`blockBinding`)
uniformBlockBinding(blockIndex, blockBinding) {
this.gl2.uniformBlockBinding(this.handle, blockIndex, blockBinding);
}
} | the_stack |
import * as path from "path";
import * as fs from "fs";
import * as electronLocalShortcut from "electron-localshortcut";
import {
__DARWIN__,
__WIN32__,
__LINUX__,
__DEV__,
menuIdFromMachineId,
} from "./utils/electron-utils";
import {
BrowserWindow,
app,
Menu,
MenuItemConstructorOptions,
MenuItem,
ipcMain,
IpcMainEvent,
webContents,
dialog,
shell,
} from "electron";
import {
mainProcessStore,
createMainProcessStateAware,
} from "./mainProcessStore";
import {
appGotFocusAction,
appLostFocusAction,
} from "../../src/shared/state/redux-app-focus";
import {
restoreAppWindowAction,
maximizeAppWindowAction,
minimizeAppWindowAction,
} from "../../src/shared/state/redux-window-state";
import {
RequestMessage,
ResponseMessage,
} from "@shared/messaging/message-types";
import {
RENDERER_REQUEST_CHANNEL,
MAIN_RESPONSE_CHANNEL,
MAIN_REQUEST_CHANNEL,
RENDERER_RESPONSE_CHANNEL,
} from "../../src/shared/utils/channel-ids";
import { processMessageFromRenderer } from "./mainMessageProcessor";
import { AppState, IdeConnection } from "@state/AppState";
import {
emulatorSetSavedDataAction,
emulatorRequestTypeAction,
emulatorSetSoundLevelAction,
emulatorMuteAction,
emulatorUnmuteAction,
emulatorShowStatusbarAction,
emulatorHideStatusbarAction,
emulatorShowKeyboardAction,
emulatorHideKeyboardAction,
emulatorSetClockMultiplierAction,
emulatorShowFramesAction,
emulatorHideFramesAction,
emulatorShowToolbarAction,
emulatorHideToolbarAction,
emulatorSetMachineContextAction,
emulatorKeyboardHeightAction,
} from "@state/redux-emulator-state";
import { BinaryWriter } from "@shared/utils/BinaryWriter";
import { TzxHeader, TzxStandardSpeedDataBlock } from "@shared/tape/tzx-file";
import { ideDisconnectsAction } from "@state/redux-ide-connection.state";
import { MachineContextProvider } from "./machine-context";
import {
ZxSpectrum128ContextProvider,
ZxSpectrum48ContextProvider,
} from "./zx-spectrum-context";
import { Cz88ContextProvider } from "./cz-88-context";
import { IAppWindow } from "./IAppWindows";
import {
appConfiguration,
appSettings,
reloadSettings,
saveKliveSettings,
} from "./klive-configuration";
import { KliveSettings } from "@shared/messaging/emu-configurations";
/**
* Stores a reference to the lazily loaded `electron-window-state` package.
*/
let windowStateKeeper: any | null = null;
/**
* Minimum application window dimensions
*/
const MIN_WIDTH = 640;
const MIN_HEIGHT = 128;
// --- Menu IDs
const TOGGLE_KEYBOARD = "toggle_keyboard";
const TOGGLE_TOOLBAR = "toggle_toolbar";
const TOGGLE_STATUSBAR = "toggle_statusbar";
const TOGGLE_FRAMES = "toggle_frames";
const TOGGLE_DEVTOOLS = "toggle_devtools";
const START_VM = "start_vm";
const PAUSE_VM = "pause_vm";
const STOP_VM = "stop_vm";
const RESTART_VM = "restart_vm";
const DEBUG_VM = "debug_vm";
const STEP_INTO_VM = "step_into_vm";
const STEP_OVER_VM = "step_over_vm";
const STEP_OUT_VM = "step_out_vm";
/**
* This class encapsulates the functionality of the application's window
* at the main process side.
*/
export class AppWindow implements IAppWindow {
// --- The associated BrowserWindow instance
private _window: BrowserWindow | null;
// --- Last machine type used
private _lastMachineType: string | null = null;
// --- Menu provider for the machine type
private _machineContextProvider: MachineContextProvider | null = null;
// --- Last sound level used
private _lastSoundLevel: number | null = null;
// --- Last muted value
private _lastMuted: boolean | null = null;
// --- Indicates that the main window watches for IDE notifications
private _watchingIde = false;
/**
* ID of the last message
*/
private _mainMessageSeqNo = 0;
/**
* Message resolvers
*/
private _mainMessageResolvers = new Map<
number,
(msg?: ResponseMessage | PromiseLike<ResponseMessage>) => void
>();
// ==========================================================================
// Static members
/**
* Now, we allow only a singleton instance
*/
static instance: AppWindow;
/**
* Gets the current machine context provider
*/
static getContextProvider(): MachineContextProvider | null {
return AppWindow.instance._machineContextProvider;
}
// ==========================================================================
// Lifecycle methods
/**
* Instantiates the browser window
*/
constructor() {
// --- Store the reference to the singleton instance
AppWindow.instance = this;
// --- Setup the state keeper module
if (!windowStateKeeper) {
windowStateKeeper = require("electron-window-state");
}
// --- Restore the last window state
const savedWindowState = windowStateKeeper({
defaultWidth: MIN_WIDTH,
defaultHeight: MIN_HEIGHT,
});
// --- Prepare the configuration options for the app window
const windowOptions: Electron.BrowserWindowConstructorOptions = {
x: savedWindowState.x,
y: savedWindowState.y,
width: savedWindowState.width,
height: savedWindowState.height,
minWidth: MIN_WIDTH,
minHeight: MIN_HEIGHT,
show: true,
// --- This fixes subpixel aliasing on Windows
// --- See https://github.com/atom/atom/commit/683bef5b9d133cb194b476938c77cc07fd05b972
backgroundColor: "#fff",
webPreferences: {
webSecurity: false,
devTools: process.env.NODE_ENV === "production" ? false : true,
contextIsolation: true,
preload: path.join(__dirname, "preload.bundled.js"),
},
acceptFirstMouse: true,
icon: path.join(__dirname, "icons/spectnet-logo.png"),
};
// --- Additional options depending on the host platform
if (__DARWIN__) {
windowOptions.frame = true;
} else if (__WIN32__) {
windowOptions.frame = true;
} else if (__LINUX__) {
windowOptions.icon = path.join(__dirname, "icons/spectnet-logo.png");
}
this._window = new BrowserWindow(windowOptions);
// --- Set up main window events
this._window.on("focus", () => {
electronLocalShortcut.register(
this._window,
["CommandOrControl+R", "CommandOrControl+Shift+R", "F5"],
() => {}
);
mainProcessStore.dispatch(appGotFocusAction());
});
this._window.on("blur", () => {
electronLocalShortcut.unregisterAll(this._window);
mainProcessStore.dispatch(appLostFocusAction());
});
this.window.on("enter-full-screen", () => {
// TODO: Implement this
});
// So this is a bit of a hack. If we call window.isFullScreen directly after
// receiving the leave-full-screen event it'll return true which isn't what
// we're after. So we'll say that we're transitioning to 'normal' even though
// we might be maximized. This works because electron will emit a 'maximized'
// event after 'leave-full-screen' if the state prior to full-screen was maximized.
this.window.on("leave-full-screen", () => {
mainProcessStore.dispatch(restoreAppWindowAction());
});
this.window.on("maximize", () => {
mainProcessStore.dispatch(maximizeAppWindowAction());
});
this.window.on("minimize", () => {
mainProcessStore.dispatch(minimizeAppWindowAction());
});
this.window.on("unmaximize", () => {
mainProcessStore.dispatch(restoreAppWindowAction());
});
this.window.on("restore", () => {
mainProcessStore.dispatch(restoreAppWindowAction());
});
this.window.on("hide", () => {
// TODO: Implement this
});
this.window.on("show", () => {
mainProcessStore.dispatch(restoreAppWindowAction());
});
this._window.on("closed", () => {
// --- Release resources
this._window = null;
}); // --- Load the main file
// --- Allow the `electron-windows-state` package to follow and save the
// --- app window's state
savedWindowState.manage(this._window);
// --- Set up message processing
ipcMain.on(
RENDERER_REQUEST_CHANNEL,
async (_ev: IpcMainEvent, message: RequestMessage) => {
const response = await processMessageFromRenderer(message);
response.correlationId = message.correlationId;
const allWebContents = webContents.getAllWebContents();
const pageContenst =
webContents.length === 1 ? allWebContents[0] : webContents.fromId(1);
if (!pageContenst) return;
pageContenst.send(MAIN_RESPONSE_CHANNEL, response);
}
);
// --- Process the results coming from the renderer process
ipcMain.on(
RENDERER_RESPONSE_CHANNEL,
(_ev: IpcMainEvent, response: ResponseMessage) => {
// --- Check for UI message
const resolver = this._mainMessageResolvers.get(response.correlationId);
// --- Resolve the message
if (resolver) {
resolver(response);
this._mainMessageResolvers.delete(response.correlationId);
}
}
);
// --- Catch state changes
const emulatorStateAware = createMainProcessStateAware();
emulatorStateAware.stateChanged.on((state) =>
this.processStateChange(state)
);
const ideConnectionStateAware = createMainProcessStateAware(
"ideConnection"
);
ideConnectionStateAware.stateChanged.on((state) => {
const conn = state as IdeConnection;
if (conn.connected) {
this.disableMachineMenu();
} else {
this.enableMachineMenu();
}
});
// --- Set up the default provider
this._machineContextProvider = new ZxSpectrum48ContextProvider(this);
}
/**
* Gets the associated BrowserWindow
*/
get window(): BrowserWindow | null {
return this._window;
}
/**
* Posts a message from the renderer to the main
* @param message Message contents
*/
postMessageToRenderer(message: RequestMessage): void {
if (this._window?.isDestroyed() === false) {
this._window.webContents.send(MAIN_REQUEST_CHANNEL, message);
}
}
/**
* Sends an async message to the main process
* @param message Message to send
*/
sendMessageToRenderer<TMessage extends ResponseMessage>(
message: RequestMessage
): Promise<TMessage> {
message.correlationId = this._mainMessageSeqNo++;
const promise = new Promise<TMessage>((resolve) => {
this._mainMessageResolvers.set(message.correlationId, resolve);
});
this.postMessageToRenderer(message);
return promise;
}
/**
* Loads the contenst of the main window
*/
load(): void {
this._window.loadFile(path.join(__dirname, "index.html"));
}
/**
* Sets up the application menu
*/
setupMenu(): void {
// --- Merge startup configuration and settings
const viewOptions = appSettings?.viewOptions ?? {
showToolbar: true,
showStatusbar: true,
showFrameInfo: true,
};
if (viewOptions.showFrameInfo === undefined) {
viewOptions.showFrameInfo = appConfiguration?.viewOptions.showFrameInfo;
}
if (viewOptions.showToolbar === undefined) {
viewOptions.showToolbar = appConfiguration?.viewOptions?.showToolbar;
}
if (viewOptions.showStatusbar === undefined) {
viewOptions.showStatusbar = appConfiguration?.viewOptions?.showStatusbar;
}
if (viewOptions.showKeyboard === undefined) {
viewOptions.showKeyboard = appConfiguration?.viewOptions?.showStatusbar;
}
const template: (MenuItemConstructorOptions | MenuItem)[] = [];
if (__DARWIN__) {
template.push({
label: app.name,
submenu: [
{ role: "about" },
{ type: "separator" },
{ role: "services" },
{ type: "separator" },
{ role: "hide" },
{ role: "hideOthers" },
{ role: "unhide" },
{ type: "separator" },
{ role: "quit" },
],
});
}
// --- Prepare the File menu
const fileMenu: MenuItemConstructorOptions = {
label: "File",
submenu: [__DARWIN__ ? { role: "close" } : { role: "quit" }],
};
// --- Preapre the view menu
const viewSubMenu: MenuItemConstructorOptions[] = [
{ role: "resetZoom" },
{ role: "zoomIn" },
{ role: "zoomOut" },
{ type: "separator" },
{ role: "togglefullscreen" },
{
id: TOGGLE_DEVTOOLS,
label: "Toggle Developer Tools",
accelerator: "Ctrl+Shift+I",
visible: true, //appConfiguration?.viewOptions?.showDevTools ?? false,
enabled: true, //appConfiguration?.viewOptions?.showDevTools ?? false,
click: () => {
this.window.webContents.toggleDevTools();
},
},
{ type: "separator" },
{
id: TOGGLE_KEYBOARD,
label: "Show keyboard",
type: "checkbox",
checked: false,
click: (mi) => {
if (mi.checked) {
mainProcessStore.dispatch(emulatorShowKeyboardAction());
} else {
mainProcessStore.dispatch(emulatorHideKeyboardAction());
}
},
},
{ type: "separator" },
];
let extraViewItems: MenuItemConstructorOptions[] =
this._machineContextProvider?.provideViewMenuItems() ?? [];
if (extraViewItems.length > 0) {
extraViewItems.push({ type: "separator" });
}
viewSubMenu.push(...extraViewItems);
viewSubMenu.push(
{
id: TOGGLE_TOOLBAR,
label: "Show toolbar",
type: "checkbox",
checked: viewOptions.showToolbar ?? true,
click: (mi) => {
if (mi.checked) {
mainProcessStore.dispatch(emulatorShowToolbarAction());
} else {
mainProcessStore.dispatch(emulatorHideToolbarAction());
}
},
},
{
id: TOGGLE_STATUSBAR,
label: "Show statusbar",
type: "checkbox",
checked: viewOptions.showStatusbar ?? true,
click: (mi) => {
if (mi.checked) {
mainProcessStore.dispatch(emulatorShowStatusbarAction());
} else {
mainProcessStore.dispatch(emulatorHideStatusbarAction());
}
},
},
{
id: TOGGLE_FRAMES,
label: "Show frame information",
type: "checkbox",
checked: viewOptions.showFrameInfo ?? true,
click: (mi) => {
if (mi.checked) {
mainProcessStore.dispatch(emulatorShowFramesAction());
} else {
mainProcessStore.dispatch(emulatorHideFramesAction());
}
},
}
);
// --- Add the file and view menu
template.push(fileMenu, {
label: "View",
submenu: viewSubMenu,
});
// --- Prepare the Run menu
const runMenu: MenuItemConstructorOptions = {
label: "Run",
submenu: [
{
id: START_VM,
label: "Start",
accelerator: "F5",
enabled: true,
click: async () => await this.startVm(),
},
{
id: PAUSE_VM,
label: "Pause",
accelerator: "Shift+F5",
enabled: false,
click: async () => await this.pauseVm(),
},
{
id: STOP_VM,
label: "Stop",
accelerator: "F4",
enabled: false,
click: async () => await this.stopVm(),
},
{
id: RESTART_VM,
label: "Restart",
accelerator: "Shift+F4",
enabled: false,
click: async () => await this.restartVm(),
},
{ type: "separator" },
{
id: DEBUG_VM,
label: "Start with debugging",
accelerator: "Ctrl+F5",
enabled: true,
click: async () => await this.debugVm(),
},
{
id: STEP_INTO_VM,
label: "Step into",
accelerator: "F3",
enabled: false,
click: async () => await this.stepIntoVm(),
},
{
id: STEP_OVER_VM,
label: "Step over",
accelerator: "Shift+F3",
enabled: false,
click: async () => await this.stepOverVm(),
},
{
id: STEP_OUT_VM,
label: "Step out",
accelerator: "Ctrl+F3",
enabled: false,
click: async () => await this.stepOutVm(),
},
],
};
template.push(runMenu);
// --- Prepare the machine menu
const machineSubMenu: MenuItemConstructorOptions[] = [];
for (let i = 0; i < MACHINE_MENU_ITEMS.length; i++) {
machineSubMenu.push({
id: menuIdFromMachineId(MACHINE_MENU_ITEMS[i].id),
label: MACHINE_MENU_ITEMS[i].label,
type: "radio",
checked: i ? false : true,
enabled: MACHINE_MENU_ITEMS[i].enabled,
click: async (mi) => {
try {
this.saveAppSettings();
} catch {
// --- Intentionally ignored
}
const machineType = mi.id.split("_")[1];
this.requestMachineType(machineType);
// --- Wait while the menu is instantiated
await new Promise((r) => setTimeout(r, 200));
this.setMachineTypeMenu(mi.id);
await new Promise((r) => setTimeout(r, 200));
AppWindow.instance.applyStoredSettings(machineType);
},
});
}
machineSubMenu.push(
{ type: "separator" },
{
id: SOUND_MENU_ITEMS[0].id,
label: "Mute sound",
type: "radio",
checked: false,
click: () => this.setSoundLevel(SOUND_MENU_ITEMS[0].level),
},
{
id: SOUND_MENU_ITEMS[1].id,
label: "Sound: Low ",
type: "radio",
checked: false,
click: () => this.setSoundLevel(SOUND_MENU_ITEMS[1].level),
},
{
id: SOUND_MENU_ITEMS[2].id,
label: "Sound: Medium",
type: "radio",
checked: false,
click: () => this.setSoundLevel(SOUND_MENU_ITEMS[2].level),
},
{
id: SOUND_MENU_ITEMS[3].id,
label: "Sound: High",
type: "radio",
checked: true,
click: () => this.setSoundLevel(SOUND_MENU_ITEMS[3].level),
},
{
id: SOUND_MENU_ITEMS[4].id,
label: "Sound: Highest",
type: "radio",
checked: false,
click: () => this.setSoundLevel(SOUND_MENU_ITEMS[4].level),
}
);
const emuState = mainProcessStore.getState().emulatorPanelState;
emuState.internalState;
const cpuClockSubmenu: MenuItemConstructorOptions = {
type: "submenu",
label: "CPU clock multiplier",
submenu: [],
};
const baseClockFrequency =
this._machineContextProvider?.getNormalCpuFrequency() ?? 1_000_000;
for (let i = 1; i <= 24; i++) {
(cpuClockSubmenu.submenu as MenuItemConstructorOptions[]).push({
id: `clockMultiplier_${i}`,
type: "radio",
label:
(i > 1 ? `${i}x` : `Normal`) +
` (${((i * baseClockFrequency) / 1_000_000).toFixed(4)}MHz)`,
click: () => {
mainProcessStore.dispatch(emulatorSetClockMultiplierAction(i)());
},
});
}
machineSubMenu.push({ type: "separator" });
machineSubMenu.push(cpuClockSubmenu);
let extraMachineItems: MenuItemConstructorOptions[] =
this._machineContextProvider?.provideMachineMenuItems() ?? [];
if (extraMachineItems.length > 0) {
machineSubMenu.push({ type: "separator" });
machineSubMenu.push(...extraMachineItems);
}
template.push({
label: "Machine",
submenu: machineSubMenu,
});
if (__DARWIN__) {
template.push({
label: "Window",
submenu: [
{ role: "minimize" },
{ role: "zoom" },
{ type: "separator" },
{ role: "front" },
{ type: "separator" },
{ role: "window" },
],
});
}
const helpSubmenu: MenuItemConstructorOptions[] = [
{
label: "Klive on Github",
click: async () => {
await shell.openExternal("https://github.com/Dotneteer/kliveide");
},
},
{
label: "Getting started with Klive",
click: async () => {
await shell.openExternal(
"https://dotneteer.github.io/kliveide/getting-started/install-kliveide.html"
);
},
},
];
let extraHelpItems: MenuItemConstructorOptions[] =
this._machineContextProvider?.provideHelpMenuItems() ?? [];
if (extraHelpItems.length > 0) {
helpSubmenu.push({ type: "separator" });
helpSubmenu.push(...extraHelpItems);
}
template.push({
role: "help",
submenu: helpSubmenu,
});
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);
if (this._machineContextProvider) {
mainProcessStore.dispatch(
emulatorSetMachineContextAction(
this._machineContextProvider.getMachineContextDescription()
)()
);
}
}
applyStoredSettings(machineType: string): void {
// --- Set view options
const viewOptions = appSettings?.viewOptions ?? {
showToolbar: true,
showStatusbar: true,
showFrameInfo: true,
};
if (viewOptions?.showFrameInfo === undefined) {
viewOptions.showFrameInfo = appConfiguration?.viewOptions?.showFrameInfo;
}
mainProcessStore.dispatch(
viewOptions?.showFrameInfo
? emulatorShowFramesAction()
: emulatorHideFramesAction()
);
if (viewOptions?.showToolbar === undefined) {
viewOptions.showToolbar = appConfiguration?.viewOptions?.showToolbar;
}
mainProcessStore.dispatch(
viewOptions?.showToolbar
? emulatorShowToolbarAction()
: emulatorHideToolbarAction()
);
if (viewOptions?.showStatusbar === undefined) {
viewOptions.showStatusbar = appConfiguration?.viewOptions?.showStatusbar;
}
mainProcessStore.dispatch(
viewOptions?.showStatusbar
? emulatorShowStatusbarAction()
: emulatorHideStatusbarAction()
);
if (viewOptions?.showKeyboard === undefined) {
viewOptions.showKeyboard = appConfiguration?.viewOptions?.showStatusbar;
}
if (viewOptions?.keyboardHeight) {
mainProcessStore.dispatch(
emulatorKeyboardHeightAction(viewOptions.keyboardHeight)()
);
}
mainProcessStore.dispatch(
viewOptions?.showKeyboard
? emulatorShowKeyboardAction()
: emulatorHideKeyboardAction()
);
// --- Machine specific
const machineSpecific = appSettings?.machineSpecific[machineType];
if (machineSpecific && this._machineContextProvider) {
this._machineContextProvider.setMachineSpecificSettings(machineSpecific);
}
if (this._machineContextProvider) {
mainProcessStore.dispatch(
emulatorSetMachineContextAction(
this._machineContextProvider.getMachineContextDescription()
)()
);
}
}
/**
* Requests a machine type according to its menu ID
* @param id Machine type, or menu ID of the machine type
* @param options Machine construction options
*/
requestMachineType(id: string, options?: Record<string, any>): void {
const parts = id.split("_");
const typeId = parts[0];
// --- Prepare the menu provider for the machine
switch (typeId) {
case "48":
this._machineContextProvider = new ZxSpectrum48ContextProvider(this);
break;
case "128":
this._machineContextProvider = new ZxSpectrum128ContextProvider(this);
break;
case "cz88":
this._machineContextProvider = new Cz88ContextProvider(this);
break;
}
// --- Set the new machine type in the state vector
mainProcessStore.dispatch(emulatorRequestTypeAction(id, options)());
// --- Now, create the menu with the current machine type
this.setupMenu();
this.setMachineTypeMenu(menuIdFromMachineId(typeId));
// --- Take care that the menu is updated according to the state
const emuState = mainProcessStore.getState().emulatorPanelState;
if (emuState) {
this._machineContextProvider?.updateMenuStatus(emuState);
}
}
/**
* Verifies if IDE is still connected
*/
async startWatchingIde(): Promise<void> {
this._watchingIde = true;
while (this._watchingIde) {
await new Promise((r) => setTimeout(r, 400));
const state = mainProcessStore.getState();
const lastHeartBeat = state.ideConnection?.lastHeartBeat ?? -1;
if (lastHeartBeat > 0) {
if (Date.now() - lastHeartBeat > 3000) {
// --- IDE seems to be disconnected
mainProcessStore.dispatch(ideDisconnectsAction());
if (!(appConfiguration?.viewOptions?.showDevTools ?? false)) {
this.window.webContents.closeDevTools();
}
}
}
}
}
/**
* Stops watching IDE connection
*/
stopWatchingIde(): void {
this._watchingIde = false;
}
// ==========================================================================
// Menu helpers
/**
* Disables all machine menu items
*/
private disableMachineMenu(): void {
for (const item of MACHINE_MENU_ITEMS) {
const menuItem = Menu.getApplicationMenu().getMenuItemById(item.id);
if (menuItem) {
menuItem.enabled = false;
}
}
}
/**
* Disables all machine menu items
*/
private enableMachineMenu(): void {
for (const item of MACHINE_MENU_ITEMS) {
const menuItem = Menu.getApplicationMenu().getMenuItemById(item.id);
if (menuItem) {
menuItem.enabled = item.enabled;
}
}
}
/**
* Sets the active menu according to the current machine type
*/
setMachineTypeMenu(id: string): void {
const menuItem = Menu.getApplicationMenu().getMenuItemById(`${id}`);
if (menuItem) {
menuItem.checked = true;
}
}
/**
* Sets the sound menu with the specified level
* @param level Sound level
*/
setSoundLevelMenu(muted: boolean, level: number): void {
for (const menuItem of SOUND_MENU_ITEMS) {
const item = Menu.getApplicationMenu().getMenuItemById(menuItem.id);
if (item) {
item.checked = false;
}
}
if (muted) {
const soundItem = Menu.getApplicationMenu().getMenuItemById(
SOUND_MENU_ITEMS[0].id
);
if (soundItem) {
soundItem.checked = true;
}
} else {
for (let i = 0; i < SOUND_MENU_ITEMS.length; i++) {
if (level < SOUND_MENU_ITEMS[i].level + 0.02) {
const soundItem = Menu.getApplicationMenu().getMenuItemById(
SOUND_MENU_ITEMS[i].id
);
if (soundItem) {
soundItem.checked = true;
}
break;
}
}
}
}
/**
* Saves the current application settings
*/
saveAppSettings(): void {
const state = mainProcessStore.getState().emulatorPanelState;
const machineType = state.currentType.split("_")[0];
const kliveSettings: KliveSettings = {
machineType,
viewOptions: {
showToolbar: state.showToolbar,
showFrameInfo: state.showFrames,
showKeyboard: state.keyboardPanel,
showStatusbar: state.statusbar,
keyboardHeight: state.keyboardHeight,
},
};
if (this._machineContextProvider) {
kliveSettings.machineSpecific = appSettings?.machineSpecific;
if (!kliveSettings.machineSpecific) {
kliveSettings.machineSpecific = {};
}
kliveSettings.machineSpecific[
machineType
] = this._machineContextProvider.getMachineSpecificSettings();
}
saveKliveSettings(kliveSettings);
reloadSettings();
}
// ==========================================================================
// Virtual machine helpers
/**
* Starts the virtual machine
*/
private async startVm(): Promise<void> {
await this.sendMessageToRenderer({ type: "startVm" });
}
/**
* Pauses the virtual machine
*/
private async pauseVm(): Promise<void> {
await this.sendMessageToRenderer({ type: "pauseVm" });
}
/**
* Stops the virtual machine
*/
private async stopVm(): Promise<void> {
if (await this.confirmStop("stopping", "stop")) {
await this.sendMessageToRenderer({ type: "stopVm" });
}
}
/**
* Restarts the virtual machine
*/
private async restartVm(): Promise<void> {
if (await this.confirmStop("restarting", "restart")) {
await this.sendMessageToRenderer({ type: "restartVm" });
}
}
/**
* Starts debugging the virtual machine
*/
private async debugVm(): Promise<void> {
await this.sendMessageToRenderer({ type: "debugVm" });
}
/**
* Steps into the virtual machine
*/
private async stepIntoVm(): Promise<void> {
await this.sendMessageToRenderer({ type: "stepIntoVm" });
}
/**
* Steps over the virtual machine
*/
private async stepOverVm(): Promise<void> {
await this.sendMessageToRenderer({ type: "stepOverVm" });
}
/**
* Steps out the virtual machine
*/
private async stepOutVm(): Promise<void> {
await this.sendMessageToRenderer({ type: "stepOutVm" });
}
/**
* Display a confirm message for reset
*/
private async confirmStop(
actionName: string,
actionVerb: string
): Promise<boolean> {
const result = await dialog.showMessageBox(this.window, {
title: `Confirm ${actionName} the machine`,
message: `Are you sure you want to ${actionVerb} the machine?`,
buttons: ["Yes", "No"],
defaultId: 0,
type: "question",
});
return result.response === 0;
}
/**
* Sets the specified sound level
* @param level Sound level (between 0.0 and 1.0)
*/
setSoundLevel(level: number): void {
if (level === 0) {
mainProcessStore.dispatch(emulatorMuteAction());
} else {
mainProcessStore.dispatch(emulatorUnmuteAction());
mainProcessStore.dispatch(emulatorSetSoundLevelAction(level)());
}
}
/**
* Processes emulator data changes
* @param state Emulator state
*/
private processStateChange(fullState: AppState): void {
const menu = Menu.getApplicationMenu();
const emuState = fullState.emulatorPanelState;
if (menu) {
// --- DevTools visibility
// const devToolVisible =
// (fullState?.ideConnection?.connected ?? false) ||
// (appConfiguration?.viewOptions?.showDevTools ?? false);
// const toggleDevTools = menu.getMenuItemById(TOGGLE_DEVTOOLS);
// if (toggleDevTools) {
// toggleDevTools.visible = toggleDevTools.enabled = devToolVisible;
// }
// --- Keyboard panel status
const toggleKeyboard = menu.getMenuItemById(TOGGLE_KEYBOARD);
if (toggleKeyboard) {
toggleKeyboard.checked = !!emuState.keyboardPanel;
}
// --- Clock multiplier status
if (emuState) {
const clockMultiplier = emuState.clockMultiplier ?? 1;
const cmItem = menu.getMenuItemById(
`clockMultiplier_${clockMultiplier}`
);
if (cmItem) {
cmItem.checked = false;
}
}
// --- VM control commands
const executionState = emuState.executionState;
const startVm = menu.getMenuItemById(START_VM);
if (startVm) {
startVm.enabled =
executionState === 0 || executionState === 3 || executionState === 5;
}
const pauseVm = menu.getMenuItemById(PAUSE_VM);
if (pauseVm) {
pauseVm.enabled = executionState === 1;
}
const stopVm = menu.getMenuItemById(STOP_VM);
if (stopVm) {
stopVm.enabled = executionState === 1 || executionState === 3;
}
const restartVm = menu.getMenuItemById(RESTART_VM);
if (restartVm) {
restartVm.enabled = executionState === 1 || executionState === 3;
}
const debugVm = menu.getMenuItemById(DEBUG_VM);
if (debugVm) {
debugVm.enabled =
executionState === 0 || executionState === 3 || executionState === 5;
}
const stepIntoVm = menu.getMenuItemById(STEP_INTO_VM);
if (stepIntoVm) {
stepIntoVm.enabled = executionState === 3;
}
const stepOverVm = menu.getMenuItemById(STEP_OVER_VM);
if (stepOverVm) {
stepOverVm.enabled = executionState === 3;
}
const stepOutVm = menu.getMenuItemById(STEP_OUT_VM);
if (stepOutVm) {
stepOutVm.enabled = executionState === 3;
}
}
// --- Take care that custom machine menus are updated
this._machineContextProvider?.updateMenuStatus(emuState);
if (this._lastMachineType !== emuState.currentType) {
// --- Current machine types has changed
this._lastMachineType = emuState.currentType;
this.requestMachineType(this._lastMachineType);
}
// --- Sound level has changed
this._lastSoundLevel = emuState.soundLevel;
this._lastMuted = emuState.muted;
this.setSoundLevelMenu(this._lastMuted, this._lastSoundLevel);
// --- The engine has just saved a ZX Spectrum file
if (emuState?.savedData && emuState.savedData.length > 0) {
const data = emuState.savedData;
const ideConfig = mainProcessStore.getState().ideConfiguration;
if (!ideConfig) {
return;
}
// --- Create filename
const tapeFilePath = path.join(
ideConfig.projectFolder,
ideConfig.saveFolder
);
const nameBytes = data.slice(2, 12);
let name = "";
for (let i = 0; i < 10; i++) {
name += String.fromCharCode(nameBytes[i]);
}
const tapeFileName = path.join(tapeFilePath, `${name.trimRight()}.tzx`);
// --- We use this writer to save file info into
const writer = new BinaryWriter();
new TzxHeader().writeTo(writer);
// --- The first 19 bytes is the header
new TzxStandardSpeedDataBlock(data.slice(0, 19)).writeTo(writer);
// --- Other bytes are the data block
new TzxStandardSpeedDataBlock(data.slice(19)).writeTo(writer);
// --- Now, save the file
fs.writeFileSync(tapeFileName, writer.buffer);
// --- Sign that the file has been saved
mainProcessStore.dispatch(
emulatorSetSavedDataAction(new Uint8Array(0))()
);
}
}
}
/**
* The list of machine menu items
*/
const MACHINE_MENU_ITEMS: { id: string; label: string; enabled: boolean }[] = [
{ id: "48", label: "ZX Spectrum 48", enabled: true },
{ id: "128", label: "ZX Spectrum 128", enabled: true },
{ id: "p3e", label: "ZX Spectrum +3E (to be done)", enabled: false },
{
id: "next",
label: "ZX Spectrum Next (to be done)",
enabled: false,
},
{ id: "cz88", label: "Cambridge Z88 (in progress)", enabled: true },
];
/**
* The list of sound menu items
*/
const SOUND_MENU_ITEMS: { id: string; level: number }[] = [
{ id: "mute_sound", level: 0.0 },
{ id: "sound_level_low", level: 0.13 },
{ id: "sound_level_medium", level: 0.25 },
{ id: "sound_level_high", level: 0.5 },
{ id: "sound_level_highest", level: 1.0 },
]; | the_stack |
import {GameEvent} from "./game_events/GameEvent";
import {
directions_angles,
get_sqr_distance,
get_tile_position,
mount_collision_polygon,
next_px_step,
range_360,
} from "./utils";
import {ControllableChar} from "./ControllableChar";
import {interaction_patterns} from "./game_events/GameEventManager";
import {Map} from "./Map";
import * as numbers from "./magic_numbers";
import * as _ from "lodash";
export enum npc_movement_types {
IDLE = "idle",
RANDOM = "random",
}
export enum npc_types {
NORMAL = "normal",
INN = "inn",
SHOP = "shop",
SPRITE = "sprite",
HEALER = "healer",
}
/** The NPC class. */
export class NPC extends ControllableChar {
private static readonly NPC_TALK_RANGE = 21;
private static readonly MAX_DIR_GET_TRIES = 7;
private static readonly STOP_MINIMAL_DISTANCE_SQR = 2 * 2;
private movement_type: npc_movement_types;
private _npc_type: npc_types;
private _message: string;
private _thought_message: string;
private _avatar: string;
private _voice_key: string;
private _base_collision_layer: number;
private _talk_range: number;
private _events: GameEvent[];
private _shop_key: string;
private _inn_key: string;
private _healer_key: string;
private no_shadow: boolean;
private _ignore_world_map_scale: boolean;
private anchor_x: number;
private anchor_y: number;
private scale_x: number;
private scale_y: number;
private _interaction_pattern: interaction_patterns;
private _affected_by_reveal: boolean;
private _label: string;
public visible: boolean;
protected storage_keys: {
position?: string;
action?: string;
animation?: string;
base_collision_layer?: string;
affected_by_reveal?: string;
visible?: string;
movement_type?: npc_movement_types;
};
private sprite_misc_db_key: string;
private ignore_physics: boolean;
private _initial_x: number;
private _initial_y: number;
private _angle_direction: number;
private _max_distance: number;
private _step_duration: number;
private _wait_duration: number;
private _step_frame_counter: number;
private _stepping: boolean;
private _base_step: number;
private _step_max_variation: number;
private _step_destination: {x: number; y: number};
constructor(
game,
data,
key_name,
label,
active,
initial_x,
initial_y,
storage_keys,
initial_action,
initial_animation,
enable_footsteps,
walk_speed,
dash_speed,
climb_speed,
npc_type,
movement_type,
message,
thought_message,
avatar,
shop_key,
inn_key,
healer_key,
base_collision_layer,
talk_range,
events_info,
no_shadow,
ignore_world_map_scale,
anchor_x,
anchor_y,
scale_x,
scale_y,
interaction_pattern,
affected_by_reveal,
sprite_misc_db_key,
ignore_physics,
visible,
voice_key,
max_distance,
step_duration,
wait_duration,
base_step,
step_max_variation
) {
super(
game,
data,
key_name,
enable_footsteps,
walk_speed,
dash_speed,
climb_speed,
true,
initial_x,
initial_y,
initial_action,
initial_animation,
storage_keys,
active
);
this._npc_type = npc_type ?? npc_types.NORMAL;
if (this.storage_keys.movement_type !== undefined) {
movement_type = this.data.storage.get(this.storage_keys.movement_type);
}
this.movement_type = movement_type ?? npc_movement_types.IDLE;
this._message = message ?? "";
this._thought_message = thought_message ?? "";
this._avatar = avatar ?? null;
this._voice_key = voice_key ?? "";
this._shop_key = shop_key;
this._inn_key = inn_key;
this._healer_key = healer_key;
if (this.storage_keys.base_collision_layer !== undefined) {
base_collision_layer = this.data.storage.get(this.storage_keys.base_collision_layer);
}
this._base_collision_layer = base_collision_layer ?? 0;
this._talk_range = talk_range ?? NPC.NPC_TALK_RANGE;
this.no_shadow = no_shadow ?? false;
this._ignore_world_map_scale = ignore_world_map_scale ?? false;
this.anchor_x = anchor_x;
this.anchor_y = anchor_y;
this.scale_x = scale_x;
this.scale_y = scale_y;
this._interaction_pattern = interaction_pattern ?? interaction_patterns.NO_INTERACTION;
if (this.storage_keys.affected_by_reveal !== undefined) {
affected_by_reveal = this.data.storage.get(this.storage_keys.affected_by_reveal);
}
this._affected_by_reveal = affected_by_reveal ?? false;
if (this.storage_keys.visible !== undefined) {
visible = this.data.storage.get(this.storage_keys.visible);
}
this.visible = visible ?? true;
this.ignore_physics = ignore_physics ?? false;
this._events = [];
this.set_events(events_info ?? []);
this.sprite_misc_db_key = sprite_misc_db_key;
this._label = label;
this._max_distance = max_distance;
this._step_duration = step_duration;
this._wait_duration = wait_duration ?? this._step_duration;
this._step_frame_counter = 0;
this._stepping = false;
this._base_step = base_step;
this._step_max_variation = step_max_variation;
}
/** The list of GameEvents related to this NPC. */
get events() {
return this._events;
}
/** The default interaction message of this NPC. */
get message() {
return this._message;
}
/** The default interaction message by using Mind Read of this NPC. */
get thought_message() {
return this._thought_message;
}
/** The avatar key of this NPC. */
get avatar() {
return this._avatar;
}
/** The unique label that identifies this NPC. */
get label() {
return this._label;
}
/** The voicec sound key of this NPC. */
get voice_key() {
return this._voice_key;
}
/** The type of interaction that this NPC provides when interacting with the hero. */
get interaction_pattern() {
return this._interaction_pattern;
}
/** The interaction range factor. Determines how far the hero need to be at least to start an interaction. */
get talk_range() {
return this._talk_range;
}
/** The collision layer that this NPC is. */
get base_collision_layer() {
return this._base_collision_layer;
}
/** The collision layer that this NPC is. */
get collision_layer() {
return this.base_collision_layer;
}
/** Whether this NPC is affected by Reveal psynergy or not. */
get affected_by_reveal() {
return this._affected_by_reveal;
}
/** If true, this NPC scale won't change when it's in World Map. */
get ignore_world_map_scale() {
return this._ignore_world_map_scale;
}
/** The type of this NPC. */
get npc_type() {
return this._npc_type;
}
/** If it's a shop NPC, returns the key of the shop that it owns. */
get shop_key() {
return this._shop_key;
}
/** If it's a Inn NPC, returns the key of the inn that it owns. */
get inn_key() {
return this._inn_key;
}
/** If it's a Healer NPC, returns the key of the healer establishment that it owns. */
get healer_key() {
return this._healer_key;
}
/**
* Updates this NPC properties according to current storage values.
*/
check_storage_keys() {
if (this.storage_keys.base_collision_layer !== undefined) {
const storage_value = this.data.storage.get(this.storage_keys.base_collision_layer);
if (this.base_collision_layer !== storage_value) {
this._base_collision_layer = storage_value;
}
}
if (this.storage_keys.affected_by_reveal !== undefined) {
const storage_value = this.data.storage.get(this.storage_keys.affected_by_reveal);
if (this.affected_by_reveal !== storage_value) {
this._affected_by_reveal = storage_value;
}
}
if (this.storage_keys.visible !== undefined) {
const storage_value = this.data.storage.get(this.storage_keys.visible);
if (this.visible !== storage_value) {
this.visible = storage_value;
}
}
if (this.storage_keys.movement_type !== undefined) {
const storage_value = this.data.storage.get(this.storage_keys.movement_type);
if (this.movement_type !== storage_value) {
this.movement_type = storage_value;
}
}
}
/**
* Initialize the Game Events related to this NPC.
* @param events_info the events info json.
*/
private set_events(events_info) {
for (let i = 0; i < events_info.length; ++i) {
const event = this.data.game_event_manager.get_event_instance(events_info[i]);
this.events.push(event);
}
}
/**
* Changes the collision layer of this NPC.
* @param destination_collision_layer the desitination collision layer index.
* @param update_on_map whether you want this modification to propagate to map structure.
*/
change_collision_layer(destination_collision_layer: number, update_on_map: boolean = true) {
this.sprite.body.removeCollisionGroup(this.data.collision.npc_collision_groups[this.base_collision_layer]);
this.sprite.body.setCollisionGroup(this.data.collision.npc_collision_groups[destination_collision_layer]);
if (update_on_map) {
this.data.map.update_body_tile(
this.tile_x_pos,
this.tile_y_pos,
this.tile_x_pos,
this.tile_y_pos,
this.base_collision_layer,
destination_collision_layer,
this
);
}
this._base_collision_layer = destination_collision_layer;
this.sprite.base_collision_layer = destination_collision_layer;
}
/**
* Updates the tile positions.
*/
update_tile_position(update_on_map: boolean = true) {
const new_x_pos = get_tile_position(this.x, this.data.map.tile_width);
const new_y_pos = get_tile_position(this.y, this.data.map.tile_height);
if (update_on_map) {
this.data.map.update_body_tile(
this.tile_x_pos,
this.tile_y_pos,
new_x_pos,
new_y_pos,
this.base_collision_layer,
this.base_collision_layer,
this
);
}
this._tile_x_pos = new_x_pos;
this._tile_y_pos = new_y_pos;
}
/**
* Updates this NPC initial position.
* @param x the x pos in px.
* @param y the y pos in px.
*/
update_initial_position(x: number, y: number) {
this._initial_x = x;
this._initial_y = y;
}
/**
* The main update function of this NPC.
*/
update() {
if (!this.active) {
return;
}
if (this.movement_type === npc_movement_types.IDLE) {
this.stop_char(false);
} else if (this.movement_type === npc_movement_types.RANDOM) {
if (this._stepping && this._step_frame_counter < this._step_duration) {
if (!this.set_speed_factors()) {
this._step_frame_counter = this._step_duration;
} else {
this.choose_direction_by_speed();
this.set_direction();
this.choose_action_based_on_char_state();
this.calculate_speed();
this.apply_speed();
this.play_current_action(true);
if (
get_sqr_distance(this.x, this._step_destination.x, this.y, this._step_destination.y) <
NPC.STOP_MINIMAL_DISTANCE_SQR
) {
this._step_frame_counter = this._step_duration;
}
}
} else if (!this._stepping && this._step_frame_counter < this._wait_duration) {
this.stop_char(true);
} else if (this._step_frame_counter >= (this._stepping ? this._step_duration : this._wait_duration)) {
this._stepping = !this._stepping;
if (this._stepping) {
if (!this.update_random_walk()) {
this._stepping = false;
}
}
this._step_frame_counter = 0;
}
this._step_frame_counter += 1;
}
this.update_shadow();
this.update_tile_position();
}
/**
* Sets the x-y speed values that this NPC is going to be using to move.
* @returns Returns true if the speed values were set. Going towards a collision direction is not acceptable, then returns false.
*/
private set_speed_factors() {
for (let i = 0; i < this.game.physics.p2.world.narrowphase.contactEquations.length; ++i) {
const contact = this.game.physics.p2.world.narrowphase.contactEquations[i];
if (contact.bodyB === this.body.data && contact.bodyA === this.data.hero.body.data) {
const normal = contact.normalA;
const collision_angle = range_360(Math.atan2(normal[1], normal[0]));
if (
this._angle_direction > collision_angle - numbers.degree90 &&
this._angle_direction < collision_angle + numbers.degree90
) {
//going towards the collision direction is not acceptable.
return false;
}
}
}
this.current_speed.x = this.force_diagonal_speed.x;
this.current_speed.y = this.force_diagonal_speed.y;
return true;
}
/**
* Tries to find a direction for this NPC to move in the random walk.
* @param flip_direction If true, this function will try to find directions in the opposite direction.
* @returns Returns true if a direction to move was found.
*/
private update_random_walk(flip_direction: boolean = false) {
if (
flip_direction ||
get_sqr_distance(this.x, this._initial_x, this.y, this._initial_y) <= Math.pow(this._max_distance, 2)
) {
for (let tries = 0; tries < NPC.MAX_DIR_GET_TRIES; ++tries) {
const step_size = this._base_step + _.random(this._step_max_variation);
let desired_direction;
const r1 = (Math.random() * numbers.degree360) / 4;
const r2 = (Math.random() * numbers.degree360) / 4;
if (flip_direction) {
desired_direction = this._angle_direction + Math.PI + r1 - r2;
} else {
desired_direction = this._angle_direction + r1 - r2;
}
const next_pos: {x: number; y: number} = next_px_step(this.x, this.y, step_size, desired_direction);
const wall_avoiding_dist = _.mean([this.data.map.tile_width, this.data.map.tile_height]) / 2;
const surrounding_constraints = [
{direction: desired_direction, step_size: step_size},
{direction: desired_direction, step_size: step_size + wall_avoiding_dist},
...(flip_direction
? []
: [{direction: desired_direction + numbers.degree45, step_size: step_size}]),
...(flip_direction
? []
: [{direction: desired_direction - numbers.degree45, step_size: step_size}]),
];
surrounding_tests: {
for (let i = 0; i < surrounding_constraints.length; ++i) {
const constraint = surrounding_constraints[i];
const test_pos: {x: number; y: number} = next_px_step(
this.x,
this.y,
constraint.step_size,
constraint.direction
);
const test_pos_x_tile = get_tile_position(test_pos.x, this.data.map.tile_width);
const test_pos_y_tile = get_tile_position(test_pos.y, this.data.map.tile_height);
if (this.is_pos_colliding(test_pos_x_tile, test_pos_y_tile)) {
break surrounding_tests;
}
}
if (
get_sqr_distance(next_pos.x, this._initial_x, next_pos.y, this._initial_y) >
Math.pow(this._max_distance, 2)
) {
break surrounding_tests;
}
this._step_destination = next_pos;
this._angle_direction = range_360(desired_direction);
const speed_vector = new Phaser.Point(next_pos.x - this.x, next_pos.y - this.y).normalize();
this.force_diagonal_speed.x = speed_vector.x;
this.force_diagonal_speed.y = speed_vector.y;
return true;
}
}
}
if (!flip_direction) {
const dir_found = this.update_random_walk(true);
if (!dir_found) {
this._angle_direction = range_360(this._angle_direction + Math.PI);
}
return dir_found;
}
return false;
}
/**
* Tests whether this NPC would collide in a given position.
* @param tile_x_pos the tile x position.
* @param tile_y_pos the tile y position.
* @returns returns true if the NPC is going to collide.
*/
is_pos_colliding(tile_x_pos: number, tile_y_pos: number) {
if (this.data.map.is_tile_blocked(tile_x_pos, tile_y_pos, this.base_collision_layer)) {
return true;
}
const instances_in_tile = this.data.map.get_tile_bodies(tile_x_pos, tile_y_pos);
if (instances_in_tile.length && !instances_in_tile.includes(this)) {
return true;
}
return tile_x_pos === this.data.hero.tile_x_pos && tile_y_pos === this.data.hero.tile_y_pos;
}
/**
* Activates or deactivates this NPC.
* @param active true, if you want to activate it.
*/
toggle_active(active: boolean) {
if (active) {
this.sprite.body?.collides(this.data.collision.hero_collision_group);
this.sprite.visible = true;
if (this.shadow) {
this.shadow.visible = true;
}
this._active = true;
} else {
this.sprite.body?.removeCollisionGroup(this.data.collision.hero_collision_group);
this.sprite.visible = false;
if (this.shadow) {
this.shadow.visible = false;
}
this._active = false;
}
}
/**
* Initializes this NPC.
* @param map the map that's being mounted.
*/
init_npc(map: Map) {
const npc_db = this.data.dbs.npc_db[this.key_name];
const npc_sprite_info =
this.sprite_misc_db_key !== undefined
? this.data.info.misc_sprite_base_list[this.sprite_misc_db_key]
: this.data.info.npcs_sprite_base_list[this.key_name];
if (!this.no_shadow) {
this.set_shadow(npc_db.shadow_key, this.data.middlelayer_group, this.base_collision_layer, {
shadow_anchor_x: npc_db.shadow_anchor_x,
shadow_anchor_y: npc_db.shadow_anchor_y,
});
}
this.set_sprite(
this.data.middlelayer_group,
npc_sprite_info,
this.base_collision_layer,
map,
this.anchor_x ?? npc_db.anchor_x,
this.anchor_y ?? npc_db.anchor_y,
this.scale_x ?? npc_db.scale_x,
this.scale_y ?? npc_db.scale_y
);
this._initial_x = this.sprite.x;
this._initial_y = this.sprite.y;
this._angle_direction = directions_angles[this.current_direction];
if (this.ignore_world_map_scale) {
this.sprite.scale.setTo(1, 1);
if (this.shadow) {
this.shadow.scale.setTo(1, 1);
}
}
if (this.affected_by_reveal || !this.visible) {
this.sprite.visible = false;
}
this.sprite.is_npc = true;
this.play(this.current_action, this.current_animation);
}
/**
* Initializes the collision body of this NPC.
*/
config_body() {
if (this.ignore_physics) return;
this.game.physics.p2.enable(this.sprite, false);
//Important to be after the previous command
if (this.data.dbs.npc_db[this.key_name].anchor_x !== undefined) {
this.sprite.anchor.x = this.data.dbs.npc_db[this.key_name].anchor_x;
} else {
this.reset_anchor("x");
}
if (this.data.dbs.npc_db[this.key_name].anchor_y !== undefined) {
this.sprite.anchor.y = this.data.dbs.npc_db[this.key_name].anchor_y;
} else {
this.reset_anchor("y");
}
this.sprite.body.clearShapes();
this._body_radius = this.data.dbs.npc_db[this.key_name].body_radius;
const width = this.body_radius << 1;
const polygon = mount_collision_polygon(
width,
-(width >> 1),
this.data.dbs.npc_db[this.key_name].collision_body_bevel
);
this.sprite.body.addPolygon(
{
optimalDecomp: false,
skipSimpleCheck: true,
removeCollinearPoints: false,
},
polygon
);
if (this.active) {
this.sprite.body.setCollisionGroup(this.data.collision.npc_collision_groups[this.base_collision_layer]);
}
this.sprite.body.damping = 0;
this.sprite.body.angularDamping = 0;
this.sprite.body.inertia = 0;
this.sprite.body.setZeroRotation();
this.sprite.body.fixedRotation = true;
this.sprite.body.mass = 1;
this.sprite.body.static = true;
this.sprite.body.collides(this.data.collision.hero_collision_group);
}
/**
* Unsets this NPC.
*/
unset() {
if (this.sprite) {
this.data.middlelayer_group.removeChild(this.sprite);
this.sprite.destroy();
}
if (this.shadow) {
this.data.middlelayer_group.removeChild(this.shadow);
this.shadow.destroy();
}
if (this.footsteps) {
this.footsteps.destroy();
}
this.unset_push_timer();
this._events.forEach(event => event.destroy());
this.look_target = null;
}
} | the_stack |
import {
isString,
isBoolean,
isPlainObject,
isDate,
isNumber,
isEmptyObject,
assign
} from '@intlify/shared'
import {
handleMissing,
isTranslateFallbackWarn,
NOT_REOSLVED,
MISSING_RESOLVE_VALUE
} from './context'
import { CoreWarnCodes, getWarnMessage } from './warnings'
import { CoreErrorCodes, createCoreError } from './errors'
import { VueDevToolsTimelineEvents } from '@intlify/vue-devtools'
import { Availabilities } from './intl'
import type { Locale, FallbackLocale } from './runtime'
import type {
DateTimeFormat,
DateTimeFormats as DateTimeFormatsType,
DateTimeFormatOptions,
PickupFormatKeys
} from './types/index'
import type { CoreContext, CoreInternalContext } from './context'
/**
* # datetime
*
* ## usages:
* // for example `context.datetimeFormats` below
* 'en-US': {
* short: {
* year: 'numeric', month: '2-digit', day: '2-digit',
* hour: '2-digit', minute: '2-digit'
* }
* },
* 'ja-JP': { ... }
*
* // datetimeable value only
* datetime(context, value)
*
* // key argument
* datetime(context, value, 'short')
*
* // key & locale argument
* datetime(context, value, 'short', 'ja-JP')
*
* // object sytle argument
* datetime(context, value, { key: 'short', locale: 'ja-JP' })
*
* // suppress localize miss warning option, override context.missingWarn
* datetime(context, value, { key: 'short', locale: 'ja-JP', missingWarn: false })
*
* // suppress localize fallback warning option, override context.fallbackWarn
* datetime(context, value, { key: 'short', locale: 'ja-JP', fallbackWarn: false })
*
* // if you specify `part` options, you can get an array of objects containing the formatted datetime in parts
* datetime(context, value, { key: 'short', part: true })
*
* // orverride context.datetimeFormats[locale] options with functino options
* datetime(cnotext, value, 'short', { currency: 'EUR' })
* datetime(cnotext, value, 'short', 'ja-JP', { currency: 'EUR' })
* datetime(context, value, { key: 'short', part: true }, { currency: 'EUR'})
*/
/**
* DateTime options
*
* @remarks
* Options for Datetime formatting API
*
* @VueI18nGeneral
*/
export interface DateTimeOptions<Key = string, Locales = Locale> {
/**
* @remarks
* The target format key
*/
key?: Key
/**
* @remarks
* The locale of localization
*/
locale?: Locales
/**
* @remarks
* Whether suppress warnings outputted when localization fails
*/
missingWarn?: boolean
/**
* @remarks
* Whether do resolve on format keys when your language lacks a formatting for a key
*/
fallbackWarn?: boolean
/**
* @remarks
* Whether to use [Intel.DateTimeFormat#formatToParts](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts)
*/
part?: boolean
}
/**
* `datetime` function overloads
*/
export function datetime<
Context extends CoreContext<Message, {}, Context['datetimeFormats'], {}>,
Message = string
>(
context: Context,
value: number | string | Date
): string | number | Intl.DateTimeFormatPart[]
export function datetime<
Context extends CoreContext<Message, {}, Context['datetimeFormats'], {}>,
Value extends number | string | Date = number,
Key extends string = string,
ResourceKeys extends PickupFormatKeys<
Context['datetimeFormats']
> = PickupFormatKeys<Context['datetimeFormats']>,
Message = string
>(
context: Context,
value: Value,
keyOrOptions:
| Key
| ResourceKeys
| DateTimeOptions<Key | ResourceKeys, Context['locale']>
): string | number | Intl.DateTimeFormatPart[]
export function datetime<
Context extends CoreContext<Message, {}, Context['datetimeFormats'], {}>,
Value extends number | string | Date = number,
Key extends string = string,
ResourceKeys extends PickupFormatKeys<
Context['datetimeFormats']
> = PickupFormatKeys<Context['datetimeFormats']>,
Message = string
>(
context: Context,
value: Value,
keyOrOptions:
| Key
| ResourceKeys
| DateTimeOptions<Key | ResourceKeys, Context['locale']>,
locale: Context['locale']
): string | number | Intl.DateTimeFormatPart[]
export function datetime<
Context extends CoreContext<Message, {}, Context['datetimeFormats'], {}>,
Value extends number | string | Date = number,
Key extends string = string,
ResourceKeys extends PickupFormatKeys<
Context['datetimeFormats']
> = PickupFormatKeys<Context['datetimeFormats']>,
Message = string
>(
context: Context,
value: Value,
keyOrOptions:
| Key
| ResourceKeys
| DateTimeOptions<Key | ResourceKeys, Context['locale']>,
override: Intl.DateTimeFormatOptions
): string | number | Intl.DateTimeFormatPart[]
export function datetime<
Context extends CoreContext<Message, {}, Context['datetimeFormats'], {}>,
Value extends number | string | Date = number,
Key extends string = string,
ResourceKeys extends PickupFormatKeys<
Context['datetimeFormats']
> = PickupFormatKeys<Context['datetimeFormats']>,
Message = string
>(
context: Context,
value: Value,
keyOrOptions:
| Key
| ResourceKeys
| DateTimeOptions<Key | ResourceKeys, Context['locale']>,
locale: Context['locale'],
override: Intl.DateTimeFormatOptions
): string | number | Intl.DateTimeFormatPart[]
// implementation of `datetime` function
export function datetime<
Context extends CoreContext<Message, {}, Context['datetimeFormats'], {}>,
Message = string
>(
context: Context,
...args: unknown[]
): string | number | Intl.DateTimeFormatPart[] {
const {
datetimeFormats,
unresolving,
fallbackLocale,
onWarn,
localeFallbacker
} = context
const { __datetimeFormatters } = context as unknown as CoreInternalContext
if (__DEV__ && !Availabilities.dateTimeFormat) {
onWarn(getWarnMessage(CoreWarnCodes.CANNOT_FORMAT_DATE))
return MISSING_RESOLVE_VALUE
}
const [key, value, options, overrides] = parseDateTimeArgs(...args)
const missingWarn = isBoolean(options.missingWarn)
? options.missingWarn
: context.missingWarn
const fallbackWarn = isBoolean(options.fallbackWarn)
? options.fallbackWarn
: context.fallbackWarn
const part = !!options.part
const locale = isString(options.locale) ? options.locale : context.locale
const locales = localeFallbacker(
context as any, // eslint-disable-line @typescript-eslint/no-explicit-any
fallbackLocale as FallbackLocale,
locale
)
if (!isString(key) || key === '') {
return new Intl.DateTimeFormat(locale).format(value)
}
// resolve format
let datetimeFormat: DateTimeFormat = {}
let targetLocale: Locale | undefined
let format: DateTimeFormatOptions | null = null
let from: Locale = locale
let to: Locale | null = null
const type = 'datetime format'
for (let i = 0; i < locales.length; i++) {
targetLocale = to = locales[i]
if (
__DEV__ &&
locale !== targetLocale &&
isTranslateFallbackWarn(fallbackWarn, key)
) {
onWarn(
getWarnMessage(CoreWarnCodes.FALLBACK_TO_DATE_FORMAT, {
key,
target: targetLocale
})
)
}
// for vue-devtools timeline event
if (!__BRIDGE__ && __DEV__ && locale !== targetLocale) {
const emitter = (context as unknown as CoreInternalContext).__v_emitter
if (emitter) {
emitter.emit(VueDevToolsTimelineEvents.FALBACK, {
type,
key,
from,
to,
groupId: `${type}:${key}`
})
}
}
datetimeFormat =
(datetimeFormats as unknown as DateTimeFormatsType)[targetLocale] || {}
format = datetimeFormat[key]
if (isPlainObject(format)) break
handleMissing(context as any, key, targetLocale, missingWarn, type) // eslint-disable-line @typescript-eslint/no-explicit-any
from = to
}
// checking format and target locale
if (!isPlainObject(format) || !isString(targetLocale)) {
return unresolving ? NOT_REOSLVED : key
}
let id = `${targetLocale}__${key}`
if (!isEmptyObject(overrides)) {
id = `${id}__${JSON.stringify(overrides)}`
}
let formatter = __datetimeFormatters.get(id)
if (!formatter) {
formatter = new Intl.DateTimeFormat(
targetLocale,
assign({}, format, overrides)
)
__datetimeFormatters.set(id, formatter)
}
return !part ? formatter.format(value) : formatter.formatToParts(value)
}
/** @internal */
export function parseDateTimeArgs(
...args: unknown[]
): [string, number | Date, DateTimeOptions, Intl.DateTimeFormatOptions] {
const [arg1, arg2, arg3, arg4] = args
let options = {} as DateTimeOptions
let overrides = {} as Intl.DateTimeFormatOptions
let value: number | Date
if (isString(arg1)) {
// Only allow ISO strings - other date formats are often supported,
// but may cause different results in different browsers.
const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/)
if (!matches) {
throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT)
}
// Some browsers can not parse the iso datetime separated by space,
// this is a compromise solution by replace the 'T'/' ' with 'T'
const dateTime = matches[3]
? matches[3].trim().startsWith('T')
? `${matches[1].trim()}${matches[3].trim()}`
: `${matches[1].trim()}T${matches[3].trim()}`
: matches[1].trim()
value = new Date(dateTime)
try {
// This will fail if the date is not valid
value.toISOString()
} catch (e) {
throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT)
}
} else if (isDate(arg1)) {
if (isNaN(arg1.getTime())) {
throw createCoreError(CoreErrorCodes.INVALID_DATE_ARGUMENT)
}
value = arg1
} else if (isNumber(arg1)) {
value = arg1
} else {
throw createCoreError(CoreErrorCodes.INVALID_ARGUMENT)
}
if (isString(arg2)) {
options.key = arg2
} else if (isPlainObject(arg2)) {
options = arg2
}
if (isString(arg3)) {
options.locale = arg3
} else if (isPlainObject(arg3)) {
overrides = arg3
}
if (isPlainObject(arg4)) {
overrides = arg4
}
return [options.key || '', value, options, overrides]
}
/** @internal */
export function clearDateTimeFormat<DateTimeFormats = {}, Message = string>(
ctx: CoreContext<Message, {}, DateTimeFormats>,
locale: Locale,
format: DateTimeFormat
): void {
const context = ctx as unknown as CoreInternalContext
for (const key in format) {
const id = `${locale}__${key}`
if (!context.__datetimeFormatters.has(id)) {
continue
}
context.__datetimeFormatters.delete(id)
}
} | the_stack |
export const SuggestedModifires: Array<any> = [
{
action: 'superSlow',
copy: 'Slow it all the way down.'
},
{
action: 'superFast',
copy: 'Make it as fast as possible.'
},
{
action: 'slowDown',
copy: 'Slow it down.'
},
{
action: 'speedUp',
copy: 'Speed it up.'
}
];
export const SuggestedSfx: Array<any> = [
{
action: 'sfx',
sfx: 'airhorn',
copy: 'Give me an airhorn.'
},
{
action: 'sfx',
sfx: 'church bell',
copy: 'Give me church bells.'
},
{
action: 'sfx',
sfx: 'horse neigh',
copy: 'Give me a horse neigh.'
},
{
action: 'sfx',
sfx: 'balloon pop',
copy: 'Give me a balloon pop.'
},
{
action: 'sfx',
sfx: 'cannon firing',
copy: 'Give me a cannon firing.'
},
{
action: 'sfx',
sfx: 'frog',
copy: 'Give me a frog.'
},
{
action: 'sfx',
sfx: 'car honking',
copy: 'Give me a car honking.'
},
{
action: 'sfx',
sfx: 'clock ticking',
copy: 'Give me a clock ticking.'
},
{
action: 'sfx',
sfx: 'campfire',
copy: 'Give me a campfire.'
},
{
action: 'sfx',
sfx: 'cat meow',
copy: 'Give me a cat meowing.'
},
{
action: 'sfx',
sfx: 'dog bark',
copy: 'Give me a dog barking.'
},
{
action: 'sfx',
sfx: 'crickets',
copy: 'Give me crickets.'
},
{
action: 'sfx',
sfx: 'helicopter',
copy: 'Give me a helicopter.'
},
{
action: 'sfx',
sfx: 'alarm clock',
copy: 'Give me an alarm clock.'
},
{
action: 'sfx',
sfx: 'chicken clucking',
copy: 'Give me a chicken clucking.'
},
{
action: 'sfx',
sfx: 'boat horn',
copy: 'Give me a boat horn.'
},
{
action: 'sfx',
sfx: 'elephant',
copy: 'Give me an elephant.'
},
{
action: 'sfx',
sfx: 'crow cawing',
copy: 'Give me a crow.'
},
{
action: 'sfx',
sfx: 'dial up sound',
copy: 'Give me a dial up sound.'
},
{
action: 'sfx',
sfx: 'cow moo',
copy: 'Give me a cow moo.'
},
{
action: 'sfx',
sfx: 'crowd cheering',
copy: 'Play a crowd cheering.'
},
{
action: 'sfx',
sfx: 'referee whistling',
copy: 'Give me a referee whistling.'
},
{
action: 'sfx',
sfx: 'doorbell',
copy: 'Play a doorbell.'
},
{
action: 'sfx',
sfx: 'lion roaring',
copy: 'Play a lion roaring.'
},
{
action: 'sfx',
sfx: 'train',
copy: 'Play a train sound.'
},
{
action: 'sfx',
sfx: 'firetruck',
copy: 'Play a firetruck.'
},
{
action: 'sfx',
sfx: 'laser gun',
copy: 'Give me a laser.'
},
{
action: 'sfx',
sfx: 'fireworks',
copy: 'Give me fireworks.'
},
{
action: 'sfx',
sfx: 'wind chimes',
copy: 'Give me wind chimes.'
},
{
action: 'sfx',
sfx: 'glass breaking',
copy: 'Give me glass breaking.'
},
{
action: 'sfx',
sfx: 'owl hoot',
copy: 'Give me an owl hoot.'
},
{
action: 'sfx',
sfx: 'telephone ringing',
copy: 'Give me a telephone ringing.'
},
{
action: 'sfx',
sfx: 'waves',
copy: 'Give me waves.'
},
{
action: 'sfx',
sfx: 'underwater',
copy: 'Play it underwater.'
},
{
action: 'sfx',
sfx: 'thunder',
copy: 'Give me some thunder.'
},
{
action: 'sfx',
sfx: 'gong',
copy: 'Give me a gong.'
},
{
action: 'sfx',
sfx: 'handclaps',
copy: 'Give me handclaps.'
},
{
action: 'sfx',
sfx: 'jaw harp',
copy: 'Give me a jaw harp.'
},
{
action: 'sfx',
sfx: 'monkey',
copy: 'Give me a monkey.'
},
{
action: 'sfx',
sfx: 'singing',
copy: 'Give me some singing.'
},
{
action: 'sfx',
sfx: 'choir',
copy: 'Give me a choir.'
},
{
action: 'sfx',
sfx: 'crowd clapping',
copy: 'Give me a crowd clapping.'
},
{
action: 'sfx',
sfx: 'boing',
copy: 'Give me a boing.'
},
{
action: 'sfx',
sfx: 'finger cymbals',
copy: 'Give me finger cymbals.'
},
{
action: 'sfx',
sfx: 'marching band whistle',
copy: 'Give me a marching band whistle.'
},
{
action: 'sfx',
sfx: 'triangle',
copy: 'Play a triangle.'
},
{
action: 'sfx',
sfx: 'howling ghost',
copy: 'Play a howling ghost.'
},
{
action: 'sfx',
sfx: 'river',
copy: 'Give me a river.'
},
{
action: 'sfx',
sfx: 'waterfall',
copy: 'Give me a waterfall.'
},
{
action: 'sfx',
sfx: 'motorcycle',
copy: 'Give me a motorcycle.'
},
{
action: 'sfx',
sfx: 'car revving',
copy: 'Give me a car revving.'
},
{
action: 'sfx',
sfx: 'woodpecker',
copy: 'Give me a woodpecker.'
},
{
action: 'sfx',
sfx: 'zombie',
copy: 'Give me a zombie.'
},
{
action: 'sfx',
sfx: 'seagull',
copy: 'Give me a seagull.'
},
{
action: 'sfx',
sfx: 'coffee shop',
copy: 'Play it in a coffee shop.'
},
{
action: 'sfx',
sfx: 'forest',
copy: 'Give me a forest.'
},
{
action: 'sfx',
sfx: 'video game sounds',
copy: 'Give me video game sounds.'
},
{
action: 'sfx',
sfx: 'chalk writing',
copy: 'Give me chalk writing.'
},
{
action: 'sfx',
sfx: 'city traffic noises',
copy: 'Give me city traffic noises.'
},
{
action: 'sfx',
sfx: 'wolf howling',
copy: 'Give me a wolf howling.'
},
{
action: 'sfx',
sfx: 'hippo',
copy: 'Give me a hippo.'
},
{
action: 'sfx',
sfx: 'tire squeals',
copy: 'Play tire squeals.'
},
{
action: 'sfx',
sfx: 'ufo',
copy: 'Give me a UFO.'
},
{
action: 'sfx',
sfx: 'tiger growls',
copy: 'Give me a tiger.'
},
{
action: 'sfx',
sfx: 'waves crashing',
copy: 'Give me waves crashing.'
},
{
action: 'sfx',
sfx: 'sonar',
copy: 'Give me sonar.'
},
{
action: 'sfx',
sfx: 'typewriter',
copy: 'Give me a typewriter.'
},
{
action: 'sfx',
sfx: 'drone',
copy: 'Give me drone.'
},
{
action: 'sfx',
sfx: 'refrigerator hum',
copy: 'Give me a refrigerator hum.'
},
{
action: 'sfx',
sfx: 'swamp sounds',
copy: 'Give me swamp sounds.'
},
{
action: 'sfx',
sfx: 'car alarm',
copy: 'Give me a car alarm.'
},
{
action: 'sfx',
sfx: 'airplane takeoff',
copy: 'Give me an airplane takeoff.'
},
{
action: 'sfx',
sfx: 'vinyl crackling',
copy: 'Give me vinyl crackling.'
},
{
action: 'sfx',
sfx: 'printer sounds',
copy: 'Give me printer sounds.'
},
{
action: 'sfx',
sfx: 'bubbles',
copy: 'Give me bubbles.'
},
{
action: 'sfx',
sfx: 'movie projector',
copy: 'Give me a movie projector.'
},
{
action: 'sfx',
sfx: 'bicycle bell',
copy: 'Give me a bicycle bell.'
},
{
action: 'sfx',
sfx: 'white noise',
copy: 'Give me white noise.'
},
{
action: 'sfx',
sfx: 'brown noise',
copy: 'Give me brown noise.'
},
{
action: 'sfx',
sfx: 'rain',
copy: 'Give me rain.'
},
{
action: 'sfx',
sfx: 'vacuum cleaner',
copy: 'Give me a vacuum cleaner.'
},
{
action: 'sfx',
sfx: 'dinosaur',
copy: 'Give me dinosaurs.'
},
{
action: 'sfx',
sfx: 'frying pan',
copy: 'Give me a frying pan.'
},
{
action: 'sfx',
sfx: 'rowing boat',
copy: 'Give me a rowing boat.'
},
{
action: 'sfx',
sfx: 'chain saw',
copy: 'Give me a chainsaw.'
},
{
action: 'sfx',
sfx: 'mouse squeak',
copy: 'Give me a mouse squeak.'
},
{
action: 'sfx',
sfx: 'whispering',
copy: 'Give me whispering.'
},
{
action: 'sfx',
sfx: 'hyenas',
copy: 'Play some hyenas.'
},
{
action: 'sfx',
sfx: 'bear growl',
copy: 'Give me a bear growl.'
},
{
action: 'sfx',
sfx: 'tea kettle',
copy: 'Give me a tea kettle.'
},
{
action: 'sfx',
sfx: 'amen',
copy: 'Give me an amen.'
},
{
action: 'sfx',
sfx: 'basketball buzzer',
copy: 'Give me a basketball buzzer.'
}
];
export const SuggestedInstruments: Array<any> = [
{
instrument: 'classical guitar',
type: 'guitar',
tag: 'baroque',
copy: 'Add a classical guitar.'
},
{
instrument: 'dobro',
type: 'guitar',
tag: 'americana',
copy: 'Add an americana dobro.'
},
{
instrument: 'dobro',
type: 'guitar',
tag: 'southern',
copy: 'Add a southern dobro.'
},
{
instrument: 'bass guitar',
type: 'bass',
tag: 'smooth',
copy: 'Add a smooth bass.'
},
{
instrument: 'bass guitar',
type: 'bass',
tag: 'jazz',
copy: 'Add a jazz bass.'
},
{
instrument: 'bass guitar',
type: 'bass',
tag: 'lounge',
copy: 'Add a lounge bass.'
},
{
instrument: 'bass guitar',
type: 'bass',
tag: 'groovy' ,
copy: 'Add a groovy bass.'
},
{
instrument: 'acoustic guitar',
type: 'guitar',
tag: 'folk',
copy: 'Add a folk guitar.'
},
{
instrument: 'acoustic guitar',
type: 'guitar',
tag: 'relaxing' ,
copy: 'Add a relaxing guitar.'
},
{
instrument: 'flute',
type: 'bonus',
tag: 'whimsical',
copy: 'Add a whimsical flute.'
},
{
instrument: 'sitar',
type: 'guitar',
tag: 'psychedelic',
copy: 'Add a sitar.'
},
{
instrument: 'ukelele',
type: 'guitar',
tag: 'folk',
copy: 'Add a ukelele.'
},
{
instrument: 'ukelele',
type: 'guitar',
tag: 'relaxing' ,
copy: 'Add a relaxing ukelele.'
},
{
instrument: 'dulcimer',
type: 'bonus',
tag: 'celtic' ,
copy: 'Add a celtic dulcimer.'
},
{
instrument: 'fiddle',
type: 'bonus',
tag: 'southern',
copy: 'Add a fiddle.'
},
{
instrument: 'rhodes piano',
type: 'keyboard',
tag: 'jazz',
copy: 'Add a rhodes piano.'
},
{
instrument: 'rhodes piano',
type: 'keyboard',
tag: 'groovy',
copy: 'Add a groovy rhodes piano.'
},
{
instrument: 'saxophone',
type: 'bonus',
tag: 'disco',
copy: 'Add a disco saxophone.'
},
{
instrument: 'saxophone',
type: 'bonus',
tag: 'relaxing',
copy: 'Add a saxophone.'
},
{
instrument: 'mandolin',
type: 'bonus',
tag: 'southern',
copy: 'Add a southern mandolin.'
},
{
instrument: 'mandolin',
type: 'bonus',
tag: 'acoustic',
copy: 'Add a mandolin.'
},
{
instrument: 'mandolin',
type: 'bonus',
tag: 'happy',
copy: 'Add a happy mandolin.'
},
{
instrument: 'hammond organ',
type: 'keyboard',
tag: 'gospel',
copy: 'Add a gospel keyboard.'
},
{
instrument: 'banjo',
type: 'bonus',
tag: 'americana',
copy: 'Add a banjo.'
},
{
instrument: 'banjo',
type: 'bonus',
tag: 'southern',
copy: 'Add a southern banjo.'
},
{
instrument: 'didgeridoo',
type: 'bonus',
tag: 'australian',
copy: 'Add a didgeridoo.'
},
{
instrument: 'horns',
type: 'bonus',
tag: 'stabs',
copy: 'Add horn stabs.'
},
{
instrument: 'horns',
type: 'bonus',
tag: 'mariachi',
copy: 'Add mariachi horns.'
},
{
instrument: 'horns',
type: 'bonus',
tag: 'polka',
copy: 'Add polka horns.'
},
{
instrument: 'horns',
type: 'bonus',
tag: 'happy',
copy: 'Add a happy horns.'
},
{
instrument: 'drum machine',
type: 'drums',
tag: 'dance',
copy: 'Add a drum machine.'
},
{
instrument: 'tuba',
type: 'bonus',
tag: 'funk',
copy: 'Add a funk tuba.'
},
{
instrument: 'tuba',
type: 'bonus',
tag: 'new orleans',
copy: 'Add a New Orleans tuba.'
},
{
instrument: 'tuba',
type: 'bonus',
tag: 'silly',
copy: 'Add a silly tuba.'
},
{
instrument: 'tuba',
type: 'bonus',
tag: 'polka' ,
copy: 'Add a polka tuba.'
},
{
instrument: 'upright bass',
type: 'bass',
tag: 'laid back',
copy: 'Add an upright bass.'
},
{
instrument: 'upright bass',
type: 'bass',
tag: 'soul',
copy: 'Add a soul upright bass.'
},
{
instrument: 'upright bass',
type: 'bass',
tag: 'smooth',
copy: 'Add a smooth upright bass.'
},
{
instrument: 'upright bass',
type: 'bass',
tag: 'jazz',
copy: 'Add a jazz upright bass.'
},
{
instrument: 'upright bass',
type: 'bass',
tag: 'walking',
copy: 'Add a walking upright bass.'
},
{
instrument: 'upright bass',
type: 'bass',
tag: 'bowed',
copy: 'Add a bowed bass.'
},
{
instrument: 'upright bass',
type: 'bass',
tag: 'bluegrass',
copy: 'Add a bluegrass bass.'
},
{
instrument: 'clavinet',
type: 'bonus',
tag: 'smooth',
copy: 'Add a smooth clav.'
},
{
instrument: 'clavinet',
type: 'bonus',
tag: 'jazz',
copy: 'Add a jazz clavinet.'
},
{
instrument: 'clavinet',
type: 'bonus',
tag: 'lounge',
copy: 'Add a lounge clavinet.'
},
{
instrument: 'clavinet',
type: 'bonus',
tag: 'groovy',
copy: 'Add a groovy clavinet.'
},
{
instrument: 'clavinet',
type: 'bonus',
tag: 'funk',
copy: 'Add a funk clavinet.'
},
{
instrument: 'clavinet',
type: 'bonus',
tag: 'reggae',
copy: 'Add a reggae clavinet.'
},
{
instrument: 'harp',
type: 'bonus',
tag: 'arpeggio',
copy: 'Add a harp.'
},
{
instrument: 'harp',
type: 'bonus',
tag: 'hip hop',
copy: 'Add a hip hop harp.'
},
{
instrument: 'harp',
type: 'bonus',
tag: 'whimsical',
copy: 'Add a whimsical harp.'
},
{
instrument: 'drumset',
type: 'drums',
tag: 'retro',
copy: 'Add retro drums.'
},
{
instrument: 'drumset',
type: 'drums',
tag: 'oldies',
copy: 'Add oldies drums.'
},
{
instrument: 'drumset',
type: 'drums',
tag: 'trip hop',
copy: 'Add a trip hop beat.'
},
{
instrument: 'drumset',
type: 'drums',
tag: 'cool beat',
copy: 'Add a cool beat.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'techno',
copy: 'Add a techno beat.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'club',
copy: 'Add a club beat.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'edm',
copy: 'Add an edm beat.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'drum and bass',
copy: 'Add a drum and bass beat.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'soulful',
copy: 'Add soulful drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'motown',
copy: 'Add motown drums.'
},
{
instrument: 'wind',
type: 'bonus',
tag: 'jazz',
copy: 'Add a jazz wind.'
},
{
instrument: 'trumpet',
type: 'bonus',
tag: 'classical',
copy: 'Add a classical trumpet.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'ambient',
copy: 'Add an ambient piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'nostalgic',
copy: 'Add a nostalgic piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'glitch',
copy: 'Add a glitch piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'walking',
copy: 'Add a walking piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'relaxing',
copy: 'Add a relaxing piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'funk',
copy: 'Add a funk piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'motown',
copy: 'Add a motown piano.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'southern',
copy: 'Add a southern guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'silly',
copy: 'Add a silly guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'clean',
copy: 'Add a clean guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'rock and roll',
copy: 'Add rock guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'shoegaze',
copy: 'Add a shoegaze guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'indie rock',
copy: 'Add an indie rock guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'bouncy',
copy: 'Add a bouncy guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'r and b',
copy: 'Add an r&b guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'smooth',
copy: 'Add a smooth guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'jazz',
copy: 'Add a jazz guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'ambient',
copy: 'Add an ambient guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'sweet',
copy: 'Add a sweet guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'reverby',
copy: 'Add a reverby guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'hoedown',
copy: 'Add a hoedown guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'folky',
copy: 'Add a folky guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'celtic',
copy: 'Add a celtic guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'pop',
copy: 'Add a pop guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'relaxing',
copy: 'Add a relaxing guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'psychedelic',
copy: 'Add a psychedelic guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'chorused',
copy: 'Add a chorused guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'lounge',
copy: 'Add a lounge guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'classical',
copy: 'Add a classical guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'reggae',
copy: 'Add a reggae guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'happy',
copy: 'Add a happy guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'heavy metal',
copy: 'Add a heavy metal guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'angry',
copy: 'Add an angry guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'alternative',
copy: 'Add an alt-rock guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'punk',
copy: 'Add a punk guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'surf rock',
copy: 'Add a surf rock guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: '60s',
copy: 'Add a 60s guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'blues',
copy: 'Add a blues guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'distorted',
copy: 'Add a distorted guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'gritty',
copy: 'Add a gritty guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'motown',
copy: 'Give me some motown guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'retro',
copy: 'Give me a retro guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'classic rock',
copy: 'Give me a classic rock guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'dreamy',
copy: 'Give me a dreamy guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'oldies',
copy: 'Add an oldies guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'soul',
copy: 'Add a soul guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'funk',
copy: 'Add a funky guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'heavy',
copy: 'Add a heavy guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'disco',
copy: 'Give me a disco guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: '70s',
copy: 'Add a 70s guitar.'
},
{
instrument: 'strings',
type: 'bonus',
tag: 'southern',
copy: 'Add a fiddle.'
},
{
instrument: 'strings',
type: 'bonus',
tag: 'acoustic',
copy: 'Add a bluegrass fiddle.'
},
{
instrument: 'strings',
type: 'bonus',
tag: 'folk' ,
copy: 'Add folk strings.'
},
{
instrument: 'violin',
type: 'bonus',
tag: 'classical',
copy: 'Add some classical violin.'
},
{
instrument: 'synthesizer',
type: 'keyboard',
tag: 'club',
copy: 'Add a club synthesizer.'
},
{
instrument: 'synthesizer',
type: 'keyboard',
tag: 'edm',
copy: 'Add an edm synthesizer.'
},
{
instrument: 'synthesizer',
type: 'keyboard',
tag: 'electronic',
copy: 'Add a synthesizer.'
},
{
instrument: 'synthesizer',
type: 'keyboard',
tag: 'chiptune',
copy: 'Add a chiptune synthesizer.'
},
{
instrument: 'synthesizer',
type: 'keyboard',
tag: 'electro pop',
copy: 'Add an electro pop synthesizer.'
},
{
instrument: 'synthesizer',
type: 'keyboard',
tag: 'funk',
copy: 'Add a funk synthesizer.'
},
{
instrument: 'synthesizer',
type: 'keyboard',
tag: '70s',
copy: 'Add a 70s synthesizer.'
},
{
instrument: 'synthesizer',
type: 'keyboard',
tag: '80s',
copy: 'Add a 80s synthesizer.'
},
{
instrument: 'synthesizer',
type: 'keyboard',
tag: 'synth pop',
copy: 'Add a synth pop synthesizer.'
},
{
instrument: 'synthesizer',
type: 'keyboard',
tag: 'indie pop',
copy: 'Add an indie pop synthesizer.'
},
{
instrument: 'synthesizer',
type: 'keyboard',
tag: 'retro',
copy: 'Add a retro synthesizer.'
},
{
instrument: 'synthesizer',
type: 'keyboard',
tag: 'hip hop',
copy: 'Add a hip hop synthesizer.'
},
{
instrument: 'synthesizer',
type: 'keyboard',
tag: 'mysterious',
copy: 'Add a mysterious synthesizer.'
},
{
instrument: 'bass synthesizer',
type: 'keyboard',
tag: 'chiptune',
copy: 'Add a chiptune bass.'
},
{
instrument: 'bass synthesizer',
type: 'keyboard',
tag: 'electronic',
copy: 'Add a bass synthesizer.'
},
{
instrument: 'bass synthesizer',
type: 'keyboard',
tag: '80s',
copy: 'Add am 80s bass.'
},
{
instrument: 'bass synthesizer',
type: 'keyboard',
tag: 'synth pop',
copy: 'Add a synth pop bass.'
},
{
instrument: 'electronic organ',
type: 'keyboard',
tag: 'happy',
copy: 'Add a happy organ.'
},
{
instrument: 'electric bass guitar',
type: 'bass',
tag: 'alternative',
copy: 'Add an alternative bass.'
},
{
instrument: 'electric bass guitar',
type: 'bass',
tag: 'rock',
copy: 'Give me a rock bass.'
},
{
instrument: 'electric bass guitar',
type: 'bass',
tag: 'indie rock',
copy: 'Give me an indie rock bass.'
},
{
instrument: 'electric bass guitar',
type: 'bass',
tag: 'alternative rock',
copy: 'Add an alt-rock bass.'
},
{
instrument: 'electric bass guitar',
type: 'bass',
tag: 'distorted',
copy: 'Add a distorted bass.'
},
{
instrument: 'electric bass guitar',
type: 'bass',
tag: 'r and b',
copy: 'Add an R&B bass.'
},
{
instrument: 'electric bass guitar',
type: 'bass',
tag: 'soul',
copy: 'Add a soul bass.'
},
{
instrument: 'electric bass guitar',
type: 'bass',
tag: 'hip hop',
copy: 'Give me a hip hop bass.'
},
{
instrument: 'electric bass guitar',
type: 'bass',
tag: 'smooth',
copy: 'Give me a smooth bass.'
},
{
instrument: 'electric bass guitar',
type: 'bass',
tag: 'funk',
copy: 'Give me a funky bassline.'
},
{
instrument: 'electric bass guitar',
type: 'bass',
tag: 'heavy metal',
copy: 'Give me a metal bass.'
},
];
export const SuggestedGenres: Array<any> = [
{
instrument: 'bass',
type: 'bass',
tag: 'distorted',
copy: 'Make it a distorted bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'chiptune',
copy: 'Make it a chiptune bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'electronic',
copy: 'Make it an electronic bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'classical',
copy: 'Make it a classical bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'bowed',
copy: 'Make it a bowed bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'acoustic',
copy: 'Make it an acoustic bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'r and b',
copy: 'Make it an R&B bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'soul',
copy: 'Make it a soul bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'hip hop',
copy: 'Make it a hip hop bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'smooth',
copy: 'Make it a smooth bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'funk',
copy: 'Make it a funk bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'groovy',
copy: 'Make it a groovy bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'heavy metal',
copy: 'Make it a metal bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'aggressive',
copy: 'Make it an aggressive bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'grunge',
copy: 'Make it a grunge bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'surf rock',
copy: 'Make it a surf rock bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: '60s',
copy: 'Make it a 60s bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'bluegrass',
copy: 'Make it a bluegrass bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'folk',
copy: 'Make it a folk bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'upright',
copy: 'Make it an upright bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'classic rock',
copy: 'Make it a classic rock bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'reggae',
copy: 'Make it a reggae bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'happy',
copy: 'Make it a happy bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: '80s',
copy: 'Make it an 80s bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'synth pop',
copy: 'Make it a synth pop bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'pop',
copy: 'Make it a pop bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'electro',
copy: 'Make it an electro bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'electroclash',
copy: 'Make it an electroclash bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'indie pop',
copy: 'Make it an indie pop bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'chill',
copy: 'Make it a chill bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'retro',
copy: 'Make it a retro bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'dubstep',
copy: 'Make it a dubstep bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'wobble',
copy: 'Make it a wobble bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'edm',
copy: 'Make it an EDM bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'rave',
copy: 'Make it a rave bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'futuristic',
copy: 'Make it a futuristic bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'scifi',
copy: 'Make it a scifi bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'upbeat',
copy: 'Make it an upbeat bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'bouncy',
copy: 'Make it a bouncy bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'blues',
copy: 'Make it a blues bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'motown',
copy: 'Make it a motown bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'oldies',
copy: 'Make it an oldies bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'dirty',
copy: 'Make it a dirty bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'gritty',
copy: 'Make it a gritty bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'walking',
copy: 'Make it a walking bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'swing',
copy: 'Make it a swing bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'jazz',
copy: 'Make it a jazz bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'relaxing',
copy: 'Make it a relaxing bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'lounge',
copy: 'Make it a lounge bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'slap',
copy: 'Make it a slap bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: '808',
copy: 'Make it an 808 bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'heavy',
copy: 'Make it a heavy bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'low',
copy: 'Make it a low bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: '70s',
copy: 'Make it a 70s bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'disco',
copy: 'Make it a disco bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'dance',
copy: 'Make it a dance bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'punk rock',
copy: 'Make it a punk rock bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'pop punk',
copy: 'Make it a pop punk bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'driving',
copy: 'Make it a driving bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'shoegaze',
copy: 'Make it a shoegaze bass.'
},
{
instrument: 'bass',
type: 'bass',
tag: 'chillwave',
copy: 'Make it a chillwave bass.'
},
{
instrument: 'electronic organ',
type: 'keyboard',
tag: 'reggae',
copy: 'Make it a reggae organ.'
},
{
instrument: 'synthesizer',
type: 'keyboard',
tag: 'house',
copy: 'Make it a house synthesizer.'
},
{
instrument: 'synthesizer',
type: 'keyboard',
tag: 'techno',
copy: 'Make it a techno synthesizer.'
},
{
instrument: 'strings',
type: 'bonus',
tag: 'classical',
copy: 'Make it classical strings.'
},
{
instrument: 'strings',
type: 'bonus',
tag: 'relaxing',
copy: 'Make it relaxing strings.'
},
{
instrument: 'strings',
type: 'bonus',
tag: 'dreamy',
copy: 'Make it dreamy strings.'
},
{
instrument: 'strings',
type: 'bonus',
tag: 'bubble bath',
copy: 'Make it bubble bath strings.'
},
{
instrument: 'strings',
type: 'bonus',
tag: 'ethereal',
copy: 'Make it ethereal strings.'
},
{
instrument: 'strings',
type: 'bonus',
tag: 'hip hop',
copy: 'Make it hip hop strings.'
},
{
instrument: 'strings',
type: 'bonus',
tag: 'moody',
copy: 'Make it moody strings.'
},
{
instrument: 'strings',
type: 'bonus',
tag: 'disco',
copy: 'Make it disco strings.'
},
{
instrument: 'strings',
type: 'bonus',
tag: 'pop',
copy: 'Make it pop strings.'
},
{
instrument: 'strings',
type: 'bonus',
tag: 'country',
copy: 'Make it country strings.'
},
{
instrument: 'strings',
type: 'bonus',
tag: 'chamber',
copy: 'Make it chamber strings.'
},
{
instrument: 'strings',
type: 'bonus',
tag: 'bluegrass',
copy: 'Make it bluegrass strings.'
},
{
instrument: 'strings',
type: 'bonus',
tag: 'appalachian',
copy: 'Make it appalachian strings.'
},
{
instrument: 'strings',
type: 'bonus',
tag: 'americana',
copy: 'Make it an americana strings.'
},
{
instrument: 'violin',
type: 'bonus',
tag: 'disco',
copy: 'Make it a disco violin.'
},
{
instrument: 'violin',
type: 'bonus',
tag: 'pop',
copy: 'Make it a pop violin.'
},
{
instrument: 'violin',
type: 'bonus',
tag: 'country',
copy: 'Make it a country violin.'
},
{
instrument: 'violin',
type: 'bonus',
tag: 'chamber' ,
copy: 'Make it a chamber violin.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'reggae',
copy: 'Make it a reggae guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'happy',
copy: 'Make it a happy guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'heavy metal',
copy: 'Make it a heavy metal guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'aggressive',
copy: 'Make it an aggressive guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'alternative',
copy: 'Make it an alternative guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'grunge',
copy: 'Make it a grunge guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'punk',
copy: 'Make it a punk guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'surf rock',
copy: 'Make it a surf rock guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'twang',
copy: 'Make it a twang guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'tremolo',
copy: 'Make it a tremolo guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: '60s',
copy: 'Make it a 60s guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'blues',
copy: 'Make it a blues guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'distorted',
copy: 'Make it a distorted guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'rock',
copy: 'Make it a rock guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'gritty',
copy: 'Make it a gritty guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'motown',
copy: 'Make it a motown guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'upbeat',
copy: 'Make it an upbeat guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'retro',
copy: 'Make it a retro guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'classic rock',
copy: 'Make it a classic rock guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'dreamy',
copy: 'Make it a dreamy guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'oldies',
copy: 'Make it an oldies guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'soul',
copy: 'Make it a soul guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'soulful',
copy: 'Make it a soulful guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'funk',
copy: 'Make it a funk guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'pop punk',
copy: 'Make it a pop punk guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'driving',
copy: 'Make it a driving guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'heavy',
copy: 'Make it a heavy guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'groovy',
copy: 'Make it a groovy guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'disco',
copy: 'Make it a disco guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: '70s',
copy: 'Make it a 70s guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'dance',
copy: 'Make it a dance guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'bluegrass',
copy: 'Make it a bluegrass guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'folk',
copy: 'Make it a folk guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'country',
copy: 'Make it a country guitar.'
},
{
instrument: 'guitar',
type: 'guitar',
tag: 'appalachian',
copy: 'Make it an Appalachian guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'dream pop',
copy: 'Make it a dream pop guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'indie rock',
copy: 'Make it an indie rock guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'bouncy',
copy: 'Make it a bouncy guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'r and b',
copy: 'Make it an R&B guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'smooth',
copy: 'Make it a smooth guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'jazz',
copy: 'Make it a jazz guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'ambient',
copy: 'Make it an ambient guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'sweet',
copy: 'Make it a sweet guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'reverby',
copy: 'Make it a reverby guitar.'
},
{
instrument: 'electric guitar',
type: 'guitar',
tag: 'lounge',
copy: 'Make it a lounge guitar.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'soul',
copy: 'Make it a soul piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: '60s',
copy: 'Make it a 60s piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'upbeat',
copy: 'Make it an upbeat piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'soulful',
copy: 'Make it a soulful piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'lounge',
copy: 'Make it a lounge piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'bouncy',
copy: 'Make it a bouncy piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'retro',
copy: 'Make it a retro piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'inspiring',
copy: 'Make it an inspiring piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'moody',
copy: 'Make it a moody piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'jazz',
copy: 'Make it a jazz piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'sad',
copy: 'Make it a sad piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'ethereal',
copy: 'Make it an ethereal piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'rock',
copy: 'Make it a rock piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'classic rock',
copy: 'Make it a classic rock piano.'
},
{
instrument: 'piano',
type: 'keyboard',
tag: 'oldies' ,
copy: 'Make it an oldies piano.'
},
{
instrument: 'wind',
type: 'bonus',
tag: 'didgeridoo',
copy: 'Make it a didgeridoo.'
},
{
instrument: 'wind',
type: 'bonus',
tag: 'new orleans',
copy: 'Make it New Orleans horns.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'r and b',
copy: 'Make it R&B drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'backbeat',
copy: 'Make it backbeat drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'soul',
copy: 'Make it soul drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'hip hop',
copy: 'Make it a hip hop beat.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'alternative',
copy: 'Make it alt-rock drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'rock',
copy: 'Make it rock drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'indie rock',
copy: 'Make it indie rock drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'classic rock',
copy: 'Make it classic rock drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'funk',
copy: 'Make it funk drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'jazz',
copy: 'Make it jazz drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'jazz fusion',
copy: 'Make it jazz fusion drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: '80s',
copy: 'Make it 80s drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'synth pop',
copy: 'Make it synth pop drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'pop',
copy: 'Make it pop drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'electroclash',
copy: 'Make it electroclash drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'indie pop',
copy: 'Make it indie pop drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'retro',
copy: 'Make it retro drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: '90s',
copy: 'Make it a 90s beat.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'old school',
copy: 'Make it old school drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'surf rock',
copy: 'Make it surf rock drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: '60s',
copy: 'Make it 60s drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'shoegaze',
copy: 'Make it shoegaze drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'dream pop',
copy: 'Make it dream pop drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'gritty',
copy: 'Make it gritty drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'heavy',
copy: 'Make it heavy drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'disco',
copy: 'Make it disco drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: '70s',
copy: 'Make it a 70s drum.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'dance',
copy: 'Make it a dance beat.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'dance rock',
copy: 'Make it dance rock drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'upbeat',
copy: 'Make it upbeat drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'happy',
copy: 'Make it happy drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'punk rock',
copy: 'Make it punk rock drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'pop punk',
copy: 'Make it pop punk drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'driving',
copy: 'Make it a driving beat.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'aggressive',
copy: 'Make it an aggressive beat.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'chiptune',
copy: 'Make it chiptune drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'electronic',
copy: 'Make it electronic drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'rock and roll',
copy: 'Make it rock and roll drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'rap',
copy: 'Make it a rap beat.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'relaxing',
copy: 'Make it a relaxing beat.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'smooth',
copy: 'Make it a smooth beat.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'sexy',
copy: 'Make it a sexy beat.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'lounge',
copy: 'Make it lounge drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'latin jazz',
copy: 'Make it latin jazz drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'festive',
copy: 'Make it festive drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'blues',
copy: 'Make it blues drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'dirty',
copy: 'Make it dirty drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'swing',
copy: 'Make it swing drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'reggae',
copy: 'Make it reggae drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'brushes',
copy: 'Make it a brushes beat.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'spastic',
copy: 'Make it a spastic beat.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'energetic',
copy: 'Make it energetic drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'heavy metal',
copy: 'Make it metal drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'grunge',
copy: 'Make it grunge drums.'
},
{
instrument: 'drums',
type: 'drums',
tag: 'dubstep',
copy: 'Make it a dubstep beat.'
},
{
instrument: 'drumset',
type: 'drums',
tag: 'backbeat',
copy: 'Make it backbeat drums.'
},
{
instrument: 'harp',
type: 'bonus',
tag: 'classical',
copy: 'Make it a classical harp.'
},
{
instrument: 'harp',
type: 'bonus',
tag: 'relaxing',
copy: 'Make it a relaxing harp.'
},
{
instrument: 'harp',
type: 'bonus',
tag: 'dreamy',
copy: 'Make it a dreamy harp.'
},
{
instrument: 'clavinet',
type: 'bonus',
tag: 'soul',
copy: 'Make it a soul clavinet.'
},
{
instrument: 'clavinet',
type: 'bonus',
tag: '70s',
copy: 'Make it a 70s clavinet.'
},
{
instrument: 'clavinet',
type: 'bonus',
tag: 'funk' ,
copy: 'Make it a funk clavinet.'
},
{
instrument: 'upright bass',
type: 'bass',
tag: 'classical',
copy: 'Make it a classical bass.'
},
{
instrument: 'upright bass',
type: 'bass',
tag: 'upright',
copy: 'Make it an upright bass.'
},
{
instrument: 'upright bass',
type: 'bass',
tag: 'r and b',
copy: 'Make it an R&B upright bass.'
},
{
instrument: 'upright bass',
type: 'bass',
tag: 'lounge' ,
copy: 'Make it a lounge upright bass.'
},
{
instrument: 'tuba',
type: 'bonus',
tag: 'mariachi',
copy: 'Make it a mariachi tuba.'
},
{
instrument: 'tuba',
type: 'bonus',
tag: 'polka',
copy: 'Make it a polka tuba.'
},
{
instrument: 'tuba',
type: 'bonus',
tag: 'marching band',
copy: 'Make it a marching band tuba.'
},
{
instrument: 'drum machine',
type: 'drums',
tag: 'synth pop',
copy: 'Make it a synth pop drum machine.'
},
{
instrument: 'drum machine',
type: 'drums',
tag: 'pop',
copy: 'Make it a pop drum machine.'
},
{
instrument: 'drum machine',
type: 'drums',
tag: 'retro',
copy: 'Make it a retro drum machine.'
},
{
instrument: 'drum machine',
type: 'drums',
tag: 'hip hop',
copy: 'Make it a hip hop drum machine.'
},
{
instrument: 'drum machine',
type: 'drums',
tag: '90s',
copy: 'Make it a 90s drum machine.'
},
{
instrument: 'drum machine',
type: 'drums',
tag: 'old school',
copy: 'Make it an old school drum machine.'
},
{
instrument: 'drum machine',
type: 'drums',
tag: 'chiptune',
copy: 'Make it a chiptune drum machine.'
},
{
instrument: 'drum machine',
type: 'drums',
tag: 'electronic',
copy: 'Make it an electronic drum machine.'
},
{
instrument: 'drum machine',
type: 'drums',
tag: 'house',
copy: 'Make it a house drum machine.'
},
{
instrument: 'drum machine',
type: 'drums',
tag: 'techno',
copy: 'Make it a techno drum machine.'
},
{
instrument: 'drum machine',
type: 'drums',
tag: 'edm',
copy: 'Make it an EDM drum machine.'
},
{
instrument: 'drum machine',
type: 'drums',
tag: 'dubstep',
copy: 'Make it a dubstep drum machine.'
},
{
instrument: 'horns',
type: 'bonus',
tag: 'ethereal',
copy: 'Make it ethereal horns.'
},
{
instrument: 'horns',
type: 'bonus',
tag: 'ambient',
copy: 'Make it ambient horns.'
},
{
instrument: 'horns',
type: 'bonus',
tag: 'soul',
copy: 'Make it soul horns.'
},
{
instrument: 'horns',
type: 'bonus',
tag: '60s',
copy: 'Make it 60s horns.'
},
{
instrument: 'horns',
type: 'bonus',
tag: 'upbeat',
copy: 'Make it upbeat horns.'
},
{
instrument: 'horns',
type: 'bonus',
tag: 'soulful',
copy: 'Make it soulful horns.'
},
{
instrument: 'horns',
type: 'bonus',
tag: 'bouncy',
copy: 'Make it bouncy horns.'
},
{
instrument: 'horns',
type: 'bonus',
tag: '70s',
copy: 'Make it 70s horns.'
},
{
instrument: 'horns',
type: 'bonus',
tag: 'smooth',
copy: 'Make it smooth horns.'
},
{
instrument: 'horns',
type: 'bonus',
tag: 'sexy',
copy: 'Make it sexy horns.'
},
{
instrument: 'horns',
type: 'bonus',
tag: 'lounge',
copy: 'Make it lounge horns.'
},
{
instrument: 'horns',
type: 'bonus',
tag: 'funk',
copy: 'Make it funk horns.'
},
{
instrument: 'horns',
type: 'bonus',
tag: 'jazz',
copy: 'Make it jazz horns.'
},
{
instrument: 'horns',
type: 'bonus',
tag: 'funk' ,
copy: 'Make it funk horns.'
},
{
instrument: 'banjo',
type: 'bonus',
tag: 'bluegrass',
copy: 'Make it a bluegrass banjo.'
},
{
instrument: 'banjo',
type: 'bonus',
tag: 'folk',
copy: 'Make it a banjo.'
},
{
instrument: 'banjo',
type: 'bonus',
tag: 'appalachian',
copy: 'Make it an appalachian banjo.'
},
{
instrument: 'mandolin',
type: 'bonus',
tag: 'bluegrass',
copy: 'Make it a bluegrass mandolin.'
},
{
instrument: 'mandolin',
type: 'bonus',
tag: 'folk',
copy: 'Make it a folk mandolin.'
},
{
instrument: 'mandolin',
type: 'bonus',
tag: 'country',
copy: 'Make it a country mandolin.'
},
{
instrument: 'mandolin',
type: 'bonus',
tag: 'upbeat',
copy: 'Make it an upbeat mandolin.'
},
{
instrument: 'saxophone',
type: 'bonus',
tag: 'reggae',
copy: 'Make it a reggae saxophone.'
},
{
instrument: 'saxophone',
type: 'bonus',
tag: 'mellow',
copy: 'Make it a mellow saxophone.'
},
{
instrument: 'rhodes piano',
type: 'keyboard',
tag: 'funk',
copy: 'Make it a funk rhodes piano.'
},
{
instrument: 'rhodes piano',
type: 'keyboard',
tag: 'soul',
copy: 'Make it a soul rhodes piano.'
},
{
instrument: 'rhodes piano',
type: 'keyboard',
tag: 'happy',
copy: 'Make it a happy rhodes piano.'
},
{
instrument: 'rhodes piano',
type: 'keyboard',
tag: 'motown' ,
copy: 'Make it a motown rhodes piano.'
},
{
instrument: 'fiddle',
type: 'bonus',
tag: 'bluegrass',
copy: 'Make it a bluegrass fiddle.'
},
{
instrument: 'fiddle',
type: 'bonus',
tag: 'folk',
copy: 'Make it a folk fiddle.'
},
{
instrument: 'fiddle',
type: 'bonus',
tag: 'country',
copy: 'Make it a country fiddle.'
},
{
instrument: 'dulcimer',
type: 'bonus',
tag: 'folky',
copy: 'Make it a folky dulcimer.'
},
{
instrument: 'ukelele',
type: 'guitar',
tag: 'singer songwriter',
copy: 'Make it a ukelele.'
},
{
instrument: 'ukelele',
type: 'guitar',
tag: 'cute',
copy: 'Make it a cute ukelele.'
},
{
instrument: 'sitar',
type: 'guitar',
tag: 'hindustani classical' ,
copy: 'Make it a classical sitar.'
},
{
instrument: 'flute',
type: 'bonus',
tag: 'ethereal',
copy: 'Make it an ethereal flute.'
},
{
instrument: 'flute',
type: 'bonus',
tag: 'angelic' ,
copy: 'Make it an angelic flute.'
},
{
instrument: 'acoustic guitar',
type: 'guitar',
tag: 'singer songwriter',
copy: 'Make it an acoustic guitar.'
},
{
instrument: 'acoustic guitar',
type: 'guitar',
tag: 'twee',
copy: 'Make it a twee acoustic guitar.'
},
{
instrument: 'dobro',
type: 'guitar',
tag: 'bluegrass',
copy: 'Make it a bluegrass dobro.'
},
{
instrument: 'dobro',
type: 'guitar',
tag: 'folk',
copy: 'Make it a folk dobro.'
},
{
instrument: 'dobro',
type: 'guitar',
tag: 'country',
copy: 'Make it a country dobro.'
},
{
instrument: 'classical guitar',
type: 'guitar',
tag: 'classical',
copy: 'Make it a classical guitar.'
}
]; | the_stack |
import { lift, range, immutable } from '../'
import { update } from '../src/immupdate'
describe('Array', () => {
it('can be unwrapped', () => {
const arr = [1, 2, 3]
const unwrapped = lift(arr)
.pipe(arr => {
expect(arr[0] + arr[1]).toBe(3) // Type assertion
return arr
})
.value()
expect(unwrapped).toBe(arr)
expect(arr instanceof Array).toBe(true)
// The unwrapped Array retained its original mutability.
unwrapped.push
})
it('can be mapped', () => {
const arr = [1, 2, 3]
const arr2 = immutable(arr)
const mapped = lift(arr)
.map(x => x * 2)
.value()
const mapped2 = lift(arr2)
.map(x => x * 2)
.value()
expect(mapped).toEqual([2, 4, 6])
expect(mapped instanceof Array).toBe(true)
expect(mapped).not.toBe(arr)
// The map iterator can also return Wrappers
const mapped3 = lift(arr)
.map(x => lift(x * 2))
.value()
expect(mapped2).toEqual([2, 4, 6])
// Type assertion
const _mapped: Array<number> = mapped
const _mapped2: ReadonlyArray<number> = mapped2
const _mapped3: Array<number> = mapped3
})
it('can collect its items', () => {
const arr = [1, 2, 3]
const arr2 = immutable(arr)
const result = lift(arr)
.collect(item => {
if (item === 2) return
return item.toString()
})
.value()
const result2 = lift(arr2)
.collect(item => {
if (item === 2) return
return item.toString()
})
.value()
// Type assertion
const _result: Array<string> = result
const _resul2: ReadonlyArray<string> = result2
expect(result).toEqual(['1', '3'])
})
it('can collect its items to refine their types', () => {
type A = { type: 'a'; a: number }
type B = { type: 'b'; b: string }
type Union = A | B
const isA = (u: Union): u is A => u.type === 'a'
const arr: Union[] = [
{ type: 'a', a: 10 },
{ type: 'a', a: 20 },
{ type: 'b', b: '30' }
]
const result = lift(arr)
.collect(item => {
if (isA(item)) return undefined
return item
})
.value()
// Type assertion
const _result: Array<B> = result
})
it('can be flatMapped', () => {
const arr = [1, 2, 3]
const arr2 = immutable(arr)
const mapped = lift(arr)
.flatMap(x => [x + 1, x + 2])
.value()
expect(mapped).toEqual([2, 3, 3, 4, 4, 5])
// The flatMap iterator can also return Wrappers
const mapped3 = lift(arr2)
.flatMap(x => lift([x + 1, x + 2]))
.value()
expect(mapped3).toEqual([2, 3, 3, 4, 4, 5])
// Intermediary chaining, test inference
const mapped4 = lift([1, 2, 3, 2, 1])
.flatMap(x => lift([x + 1, x + 2]))
.map(y => y + 1)
.distinct()
.value()
// Type assertion
const _mapped: Array<number> = mapped
const _mapped3: ReadonlyArray<number> = mapped3
const _mapped4: Array<number> = mapped4
expect(mapped4).toEqual([3, 4, 5, 6])
})
it('can be filtered', () => {
const arr = [1, 2, 3, 4, 5, 6]
const arr2 = immutable(arr)
const filtered = lift(arr)
.map(n => n * 2)
.filter(n => n > 6)
.value()
const filtered2 = lift(arr2)
.map(n => n * 2)
.filter(n => n > 6)
.value()
// Type assertion
const _filtered: Array<number> = filtered
const _filtered2: ReadonlyArray<number> = filtered2
expect(filtered).toEqual([8, 10, 12])
expect(filtered instanceof Array).toBe(true)
expect(filtered).not.toBe(arr)
type A = { type: 'a'; a: number }
type B = { type: 'b'; b: string }
type Union = A | B
const isA = (u: Union): u is A => u.type === 'a'
const arr3: Union[] = [
{ type: 'a', a: 10 },
{ type: 'a', a: 20 },
{ type: 'b', b: '30' }
]
const arr4 = immutable(arr3)
// It should now have been refined as an Array of as
const filtered3: A[] = arr3.filter(isA)
const _filtered4: ReadonlyArray<A> = arr4.filter(isA)
expect(filtered3).toEqual([
{ type: 'a', a: 10 },
{ type: 'a', a: 20 }
])
})
it('can append an item', () => {
const arr = [1, 2, 3, 4, 5, 6]
const arr2 = immutable(arr)
const updated = lift(arr).append(7).value()
const updated2 = lift(arr2).append(7).value()
// Type assertion
const _updated: Array<number> = updated
const _updated2: ReadonlyArray<number> = updated2
expect(updated).toEqual([1, 2, 3, 4, 5, 6, 7])
expect(updated).not.toBe(arr)
})
it('can append an Array item', () => {
const arr = [[1], [2], [3], [4], [5], [6]]
const arr2 = immutable(arr)
const updated = lift(arr).append([7]).value()
const updated2 = lift(arr2).append([7]).value()
// Type Assertion
const _updated: Array<number[]> = updated
const _updated2: ReadonlyArray<ReadonlyArray<number>> = updated2
expect(updated).toEqual([[1], [2], [3], [4], [5], [6], [7]])
expect(updated).not.toBe(arr)
})
it('can append an Array of items', () => {
const arr = [1, 2, 3, 4, 5, 6]
const arr2 = immutable(arr)
const updated = lift(arr)
.appendAll([7, 8, 9, 10])
.appendAll(new Set([11, 12]))
.value()
const updated2 = lift(arr2).appendAll([7, 8, 9, 10]).value()
// Type assertion
const _updated: Array<number> = updated
const _updated2: ReadonlyArray<number> = updated2
expect(updated).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
expect(updated).not.toBe(arr)
})
it('can insert an item', () => {
const arr = [1, 2, 3, 4, 5, 6]
const arr2 = immutable(arr)
const updated = lift(arr).insert(2, 300).value()
const updated2 = lift(arr2).insert(2, 300).value()
// Type assertion
const _updated: Array<number> = arr
const _updated2: ReadonlyArray<number> = arr2
expect(updated).toEqual([1, 2, 300, 3, 4, 5, 6])
expect(updated).not.toBe(arr)
})
it('can replace an item at a given index', () => {
const arr = [1, 2, 3, 4, 5, 6]
const arr2 = immutable(arr)
const updated = lift(arr)
.updateAt(-1, n => n * 2)
.updateAt(2, n => lift(n * 1000)) // test that we can return a lifted value as well
.updateAt(5, n => n * 100)
.updateAt(1000, n => n / 10)
.value()
const updated2 = lift(arr2)
.updateAt(-1, n => n * 2)
.updateAt(2, n => lift(n * 1000)) // test that we can return a lifted value as well
.updateAt(5, n => n * 100)
.updateAt(1000, n => n / 10)
.value()
expect(updated).toEqual([1, 2, 3000, 4, 5, 600])
expect(updated).not.toBe(arr)
// Type assertion
const _updated: number[] = updated
const _updated2: ReadonlyArray<number> = updated2
})
it('it can update itself', () => {
const arr: Array<{ id: number; label: string }> = [
{ id: 1, label: 'one' },
{ id: 2, label: 'two' }
]
const arr2 = immutable(arr)
const updated = lift(arr)
.pipe(arr =>
update(arr, draft => {
const item = draft[1]
if (item) item.label = 'TWO'
expect(draft).toEqual([
{ id: 1, label: 'one' },
{ id: 2, label: 'TWO' }
])
})
)
.value()
const updated2 = lift(arr2)
.pipe(arr =>
update(arr, draft => {
const item = draft[1]
if (item) item.label = 'TWO'
})
)
.value()
expect(updated).toEqual([
{ id: 1, label: 'one' },
{ id: 2, label: 'TWO' }
])
// Type assertion
const _updated: typeof arr = updated
const _updated2: typeof arr2 = updated2
})
it("won't replace an item if the given index is out of bounds", () => {
const arr = [
{ id: 1, label: 'one' },
{ id: 2, label: 'two' }
]
const arr2 = immutable(arr)
const updated = lift(arr)
.updateAt(-1, item =>
update(item, draft => {
draft.label = draft.label.toUpperCase()
})
)
.updateAt(1000, item =>
update(item, draft => {
draft.label = draft.label.toUpperCase()
})
)
.value()
const updated2 = lift(arr2)
.updateAt(-1, item =>
update(item, draft => {
draft.label = draft.label.toUpperCase()
})
)
.updateAt(1000, item =>
update(item, draft => {
draft.label = draft.label.toUpperCase()
})
)
.value()
expect(updated).toEqual(arr)
// Type assertion
const _updated: typeof arr = updated
const _updated2: typeof arr2 = updated2
})
it('can remove an item at a given index', () => {
const arr = ['a', 'b', 'c', 'd', 'e', 'f']
const arr2 = immutable(arr)
const updated = lift(arr).removeAt(2).value()
const updated2 = lift(arr2).removeAt(2).value()
// Type assertion
const _updated: Array<string> = updated
const _updated2: ReadonlyArray<string> = updated2
expect(updated).toEqual(['a', 'b', 'd', 'e', 'f'])
expect(updated).not.toBe(arr)
})
it("won't remove an item if the given index is negative", () => {
const arr = ['a', 'b', 'c', 'd', 'e', 'f']
const arr2 = immutable(arr)
const updated = lift(arr).removeAt(-1).value()
const updated2 = lift(arr2).removeAt(-1).value()
expect(updated).toEqual(arr)
// Type assertion
const _updated: Array<string> = updated
const _updated2: ReadonlyArray<string> = updated2
})
it('can remove all falsy values', () => {
const arr = [undefined, 'a', '', 'b', false, 'c', undefined, 'd', 'e', null, null, 'f', 0]
const arr2 = immutable(arr)
const updated = lift(arr).compact().value()
const updated2 = lift(arr2).compact().value()
expect(updated).toEqual(['a', 'b', 'c', 'd', 'e', 'f'])
expect(updated).not.toBe(arr as any)
const updated3 = lift(['', 'hey']).compact().value()
expect(updated3).toEqual(['hey'])
// Type assertion
const _updated: Array<string | true | number> = updated
const _updated2: ReadonlyArray<string | true | number> = updated2
})
it('can be flattened', () => {
const arr = [[1, 2], [3], [], [4, 5, 6]]
const arr2 = immutable(arr)
const result = lift(arr).flatten().value()
const result2 = lift(arr2).flatten().value()
// Type assertion
const _result: number[] = result
const _result2: ReadonlyArray<number> = result2
expect(result).toEqual([1, 2, 3, 4, 5, 6])
})
it('can count items satisfying a predicate', () => {
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3]
const arr2 = immutable(arr)
const count = lift(arr).count(n => n > 3)
const count2 = lift(arr2).count(n => n > 3)
// Type assertion
const _count: number = count
const _count2: number = count2
expect(count).toBe(7)
})
it('can keep only the first ocurrence of any encountered item', () => {
const arr = [{ id: 10 }, { id: 20 }, { id: 10 }, { id: 30 }, { id: 40 }, { id: 40 }]
const arr2 = immutable(arr)
const result = lift(arr)
.distinct(u => u.id)
.value()
const result2 = lift(arr2)
.distinct(u => u.id)
.value()
// Type assertion
const _result: typeof arr = result
const _result2: typeof arr2 = result2
expect(result).toEqual([{ id: 10 }, { id: 20 }, { id: 30 }, { id: 40 }])
expect(result[0]).toBe(arr[0])
expect(result[1]).toBe(arr[1])
expect(result[2]).toBe(arr[3])
expect(result[3]).toBe(arr[4])
const arr3 = ['7', 1, 2, 2, 1, '3', '7', '2', '3']
const result3 = lift(arr3).distinct().value()
expect(result3).toEqual(['7', 1, 2, '3', '2'])
})
it('can be sliced from the left', () => {
const arr = [1, 2, 3, 4, 5, 6]
const arr2 = immutable(arr)
const result = lift(arr).take(3).value()
const result2 = lift(arr2).take(3).value()
// Type assertion
const _result: number[] = result
const _result2: ReadonlyArray<number> = result2
expect(result).toEqual([1, 2, 3])
})
it('can be sliced from the right', () => {
const arr = [1, 2, 3, 4, 5, 6]
const arr2 = immutable(arr)
const result = lift(arr).takeRight(3).value()
const result2 = lift(arr2).takeRight(3).value()
// Type assertion
const _result: number[] = result
const _result2: ReadonlyArray<number> = result2
expect(result).toEqual([4, 5, 6])
})
it('can create a new Array, with grouped sub arrays', () => {
const result = lift([1, 2, 3, 4, 5, 6]).grouped(2).value()
const result2 = lift([1, 2, 3, 4, 5]).grouped(2).value()
const result3 = lift([1, 2, 3, 4, 5]).grouped(3).value()
const result4 = lift([{ name: 'a' }, { name: 'b' }, { name: 'c' }, { name: 'd' }])
.grouped(2)
.value()
// Type assertion
const _result: number[][] = result
const _result2: number[][] = result2
const _result3: number[][] = result3
const _result4: Array<Array<{ name: string }>> = result4
expect(result).toEqual([
[1, 2],
[3, 4],
[5, 6]
])
expect(result2).toEqual([[1, 2], [3, 4], [5]])
expect(result3).toEqual([
[1, 2, 3],
[4, 5]
])
expect(result4).toEqual([
[{ name: 'a' }, { name: 'b' }],
[{ name: 'c' }, { name: 'd' }]
])
})
it('can create a Map, grouping all items by key', () => {
const arr = [
{ age: 10, name: 'jon' },
{ age: 30, name: 'momo' },
{ age: 10, name: 'kiki' },
{ age: 28, name: 'jesus' },
{ age: 29, name: 'frank' },
{ age: 30, name: 'michel' }
]
const arr2 = immutable(arr)
const result = lift(arr)
.groupBy(p => p.age)
.value()
const result2 = lift(arr2)
.groupBy(p => p.age)
.value()
// Type assertion
const _result: Map<number, Array<{ age: number; name: string }>> = result
const _result2: ReadonlyMap<number, ReadonlyArray<{ age: number; name: string }>> = result2
expect([...result.entries()]).toEqual([
[
10,
[
{ age: 10, name: 'jon' },
{ age: 10, name: 'kiki' }
]
],
[
30,
[
{ age: 30, name: 'momo' },
{ age: 30, name: 'michel' }
]
],
[28, [{ age: 28, name: 'jesus' }]],
[29, [{ age: 29, name: 'frank' }]]
])
})
it('can be reversed', () => {
const arr = [1, 2, 3, 4]
const arr2 = immutable(arr)
const result = lift(arr).reverse().value()
const result2 = lift(arr2).reverse().value()
// Type assertion
const _result: Array<number> = result
const _result2: ReadonlyArray<number> = result2
expect(result).toEqual([4, 3, 2, 1])
})
it('allows its first item to be read', () => {
const arr = [1, 2, 3, 4]
const arr2 = immutable(arr)
const one = lift(arr).first()
const one2 = lift(arr2).first()
// Type assertion
const _one: number | undefined = one
const _one2: number | undefined = one2
expect(one).toBe(1)
expect(lift([]).first()).toBe(undefined)
})
it('allows its last item to be read', () => {
const arr = [1, 2, 3, 4]
const arr2 = immutable(arr)
const four = lift(arr).last()
const four2 = lift(arr2).last()
// Type assertion
const _four: number | undefined = four
const _four2: number | undefined = four2
expect(four).toBe(4)
expect(lift([]).last()).toBe(undefined)
})
it('allows an item to be read by index', () => {
const arr = [1, 2, 3, 4]
const arr2 = immutable(arr)
const item = lift(arr).get(2)
const item2 = lift(arr2).get(2)
// Type assertion
const _item: number | undefined = item
const _item2: number | undefined = item2
expect(item).toBe(3)
expect(lift(arr).get(999)).toBe(undefined)
})
it('can be sorted', () => {
// Numbers
const arr = [5, 4, 1, 6, 2, 4, 3]
const arr2 = immutable(arr)
const sorted = lift(arr).sort().value()
const sorted2 = lift(arr2).sort().value()
// Type assertion
const _sorted: number[] = sorted
const _sorted2: ReadonlyArray<number> = sorted2
expect(sorted).not.toBe(arr)
expect(sorted).toEqual([1, 2, 3, 4, 4, 5, 6])
// String sort uses localeCompare
const arr3 = 'ä ba bb bä bz a e è é aa ae b ss sz sa st ß'.split(' ')
const sorted3 = lift(arr3).sort().value()
expect(sorted3.join(' ')).toBe('a ä aa ae b ba bä bb bz e é è sa ss ß st sz')
// String sort + ignoreCase
const arr4 = ['e', 'c', 'ca', 'A', 'F', 'd', 'b']
const sorted4 = lift(arr4)
.sort(item => item.toLowerCase())
.value()
expect(sorted4).toEqual(['A', 'b', 'c', 'ca', 'd', 'e', 'F'])
// null and undefined should be in tail position
const arr6 = ['e', 'c', '', undefined, 'ca', null, 'A', undefined, 'F', null, 'd', 'b']
const sorted6 = lift(arr6)
.sort(item => item && item.toLowerCase())
.value()
expect(sorted6).toEqual(['', 'A', 'b', 'c', 'ca', 'd', 'e', 'F', null, null, undefined, undefined])
// By field
const people = [
{ name: 'Jesse', creationDate: 2 },
{ name: 'Walt', creationDate: 1 },
{ name: 'Mike', creationDate: 4 },
{ name: 'Skyler', creationDate: 3 }
]
const sorted7 = lift(people)
.sort(p => p.creationDate)
.map(p => p.name)
.value()
expect(sorted7).toEqual(['Walt', 'Jesse', 'Skyler', 'Mike'])
// Double-sort
const people2 = [
{ name: 'Jesse', age: 44 },
{ name: 'Walt', age: 18 },
{ name: 'Mike', age: 20 },
{ name: 'Skyler', age: 37 },
{ name: 'Walt', age: 100 },
{ name: 'Tonton', age: 18 },
{ name: 'Jesse', age: 20 }
]
const sorted8 = lift(people2)
.sort(p => p.age)
.sort(p => p.name)
.value()
expect(sorted8).toEqual([
{ name: 'Jesse', age: 20 },
{ name: 'Jesse', age: 44 },
{ name: 'Mike', age: 20 },
{ name: 'Skyler', age: 37 },
{ name: 'Tonton', age: 18 },
{ name: 'Walt', age: 18 },
{ name: 'Walt', age: 100 }
])
const sorted9 = lift(people2)
.sort(
p => p.name,
p => p.age
)
.value()
const sorted10 = lift(immutable(people2))
.sort(
p => p.name,
p => p.age
)
.value()
expect(sorted9).toEqual([
{ name: 'Jesse', age: 20 },
{ name: 'Jesse', age: 44 },
{ name: 'Mike', age: 20 },
{ name: 'Skyler', age: 37 },
{ name: 'Tonton', age: 18 },
{ name: 'Walt', age: 18 },
{ name: 'Walt', age: 100 }
])
// Type assertion
const _sorted9: Array<{ name: string; age: number }> = sorted9
const _sorted10: ReadonlyArray<{ name: string; age: number }> = sorted10
})
it('can reduce its items', () => {
const arr = ['a', 'b', 'c', 'd']
const arr2 = immutable(arr)
const result = lift(arr).reduce('zzz', (acc, value) => acc + value)
const result2 = lift(arr2).reduce('zzz', (acc, value) => acc + value)
expect(result).toBe('zzzabcd')
expect(lift([] as string[]).reduce('zzz', (acc, value) => acc + value)).toBe('zzz')
// Type assertion
const _result: string = result
const _result2: string = result2
const arr3 = [1, 2, 3]
const seed2: number[] = []
const result3 = lift(arr3).reduce(seed2, (acc, value) => acc.concat(value))
expect(result3.value()).toEqual([1, 2, 3])
})
it('can drop some items', () => {
const arr = ['a', 'b', 'c', 'd']
const arr2 = immutable(arr)
const result = lift(arr).drop(2).value()
const result2 = lift(arr2).drop(2).value()
// Type assertion
const _result: Array<string> = result
const _result2: ReadonlyArray<string> = result2
expect(result).toEqual(['c', 'd'])
expect(lift(arr).drop(100).value()).toEqual([])
})
it('can drop some items from its right side', () => {
const arr = ['a', 'b', 'c', 'd']
const arr2 = immutable(arr)
const result = lift(arr).dropRight(2).value()
const result2 = lift(arr2).dropRight(2).value()
// Type assertion
const _result: Array<string> = result
const _result2: ReadonlyArray<string> = result2
expect(result).toEqual(['a', 'b'])
expect(lift(arr).dropRight(100).value()).toEqual([])
})
it('can be converted to a Set-like object', () => {
const arr = ['a', 'b', 'c', 'd']
const arr2 = immutable(arr)
const result = lift(arr).toSet().value()
const result2 = lift(arr2).toSet().value()
expect(result).toEqual(new Set(['a', 'b', 'c', 'd']))
const arr3 = [1, 2, 3, 4]
const result3 = lift(arr3).toSet().value()
expect(result3).toEqual(new Set([1, 2, 3, 4]))
// Type assertion
const _result: Set<string> = result
const _result2: ReadonlySet<string> = result2
})
it('can create a range', () => {
const singleArgRange = range(5).value()
expect(singleArgRange).toEqual([0, 1, 2, 3, 4])
const rangeWithoutStep = range(1, 4).value()
expect(rangeWithoutStep).toEqual([1, 2, 3, 4])
const rangeWithStepOfOne = range(1, 4, 1).value()
expect(rangeWithStepOfOne).toEqual([1, 2, 3, 4])
const rangeWithStepOfFive = range(0, 15, 5).value()
expect(rangeWithStepOfFive).toEqual([0, 5, 10, 15])
const rangeWithNegativeStep = range(2, -4, -1).value()
expect(rangeWithNegativeStep).toEqual([2, 1, 0, -1, -2, -3, -4])
})
it('can be arbitrarily transformed', () => {
const arr = [1, 2, 3]
const result = lift(arr)
.pipe(arr => {
return arr.map(n => n * 2)
})
.value()
expect(result).toEqual([2, 4, 6])
// Array -> Object
const result2 = lift(arr).pipe(_arr => ({ a: 1, b: 2 }))
expect(result2.value()).toEqual({ a: 1, b: 2 })
// Array -> string
const result3 = lift(arr).pipe(_ => 'ohoh')
expect(result3).toBe('ohoh')
// Object -> Array
const result4 = lift({ a: 1, b: 2 }).pipe(obj => lift(obj).keys().sort().value())
expect(result4.value()).toEqual(['a', 'b'])
// Object -> ArrayWrapper
const result5 = lift({ a: 1, b: 2 }).pipe(obj => lift(obj).keys().sort())
expect(result5.value()).toEqual(['a', 'b'])
// Type assertion
const _result: number[] = result
const _result2: { a: number; b: number } = result2.value()
const _result3: string = result3
const _result4: Array<string> = result4.value()
const _result5: Array<string> = result5.value()
})
}) | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.