text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import * as vscode from "vscode"; import type { Argument, InputOr, RegisterOr } from "."; import { insert as apiInsert, Context, deindentLines, edit, indentLines, joinLines, keypress, Positions, replace, Selections, selectionsLines, setSelections, Shift } from "../api"; import type { Register } from "../state/registers"; import { LengthMismatchError } from "../utils/errors"; /** * Perform changes on the text content of the document. * * See https://github.com/mawww/kakoune/blob/master/doc/pages/keys.asciidoc#changes. */ declare module "./edit"; /** * Insert contents of register. * * A `where` argument may be specified to state where the text should be * inserted relative to each selection. If unspecified, each selection will be * replaced by the text. * * Specify `"shift": "select"` to select the inserted selection, * `"shift": "extend"` to extend to the inserted text, and nothing to keep the * current selections. * * `select` is deprecated; use `shift` with `"select"` instead. * * @keys `s-a-r` (normal) * * #### Additional commands * * | Title | Identifier | Keybinding | Commands | * | ---------------------------------- | ----------------------- | ------------------------------ | ----------------------------------------------------------------------------------------------------------- | * | Pick register and replace | `selectRegister-insert` | `c-r` (normal), `c-r` (insert) | `[".selectRegister"], [".edit.insert"]` | * | Paste before | `paste.before` | `s-p` (normal) | `[".edit.insert", { handleNewLine: true, where: "start" }]` | * | Paste after | `paste.after` | `p` (normal) | `[".edit.insert", { handleNewLine: true, where: "end" }]` | * | Paste before and select | `paste.before.select` | `s-a-p` (normal) | `[".edit.insert", { handleNewLine: true, where: "start", shift: "select" }]` | * | Paste after and select | `paste.after.select` | `a-p` (normal) | `[".edit.insert", { handleNewLine: true, where: "end" , shift: "select" }]` | * | Delete | `delete` | `a-d` (normal) | `[".edit.insert", { register: "_" }]` | * | Delete and switch to Insert | `delete-insert` | `a-c` (normal) | `[".modes.set", { input: "insert" }], [".edit.insert", { register: "_" }]` | * | Copy and delete | `yank-delete` | `d` (normal) | `[".selections.saveText"], [".edit.insert", { register: "_" }]` | * | Copy, delete and switch to Insert | `yank-delete-insert` | `c` (normal) | `[".selections.saveText"], [".modes.set", { input: "insert" }], [".edit.insert", { register: "_" }]` | * | Copy and replace | `yank-replace` | `s-r` (normal) | `[".selections.saveText", { register: "tmp" }], [".edit.insert"], [".updateRegister", { copyFrom: "tmp" }]` | */ export async function insert( _: Context, selections: readonly vscode.Selection[], register: RegisterOr<"dquote", Register.Flags.CanRead>, adjust: Argument<boolean> = true, handleNewLine: Argument<boolean> = false, repetitions: number, select: Argument<boolean> = false, shift?: Argument<Shift>, text?: Argument<string>, where?: Argument<"active" | "anchor" | "start" | "end" | undefined>, ) { let contents = text?.length ? (select ? [text] : selections.map(() => text)) : await register.get(); if (contents === undefined || contents.length === 0) { throw new Error(`register "${register.name}" does not contain any saved text`); } if (select || shift === Shift.Select) { const textToInsert = contents.join(""), insert = handleNewLine ? apiInsert.byIndex.withFullLines : apiInsert.byIndex, flags = apiInsert.flagsAtEdge(where) | apiInsert.Select; const insertedRanges = await insert(flags, () => textToInsert, selections), allSelections = [] as vscode.Selection[], document = _.document; for (const insertedRange of insertedRanges) { let offset = document.offsetAt(insertedRange.start); for (const content of contents) { const newSelection = Selections.fromLength(offset, content.length, false, document); allSelections.push(newSelection); offset += content.length; } } Selections.set(Selections.bottomToTop(allSelections)); return; } if (adjust) { contents = extendArrayToLength(contents, selections.length); } else { LengthMismatchError.throwIfLengthMismatch(selections, contents); } if (repetitions > 1) { contents = contents.map((content) => content.repeat(repetitions)); } if (where === undefined) { Selections.set(await replace.byIndex((i) => contents![i], selections)); return; } if (!["active", "anchor", "start", "end"].includes(where)) { throw new Error(`"where" must be one of "active", "anchor", "start", "end", or undefined`); } const keepOrExtend = shift === Shift.Extend ? apiInsert.Extend : apiInsert.Keep, flags = apiInsert.flagsAtEdge(where) | keepOrExtend; Selections.set( handleNewLine ? await apiInsert.byIndex.withFullLines(flags, (i) => contents![i], selections) : await apiInsert.byIndex(flags, (i) => contents![i], selections), ); } /** * Join lines. * * @keys `a-j` (normal) */ export function join(_: Context, separator?: Argument<string>) { return joinLines(selectionsLines(), separator); } /** * Join lines and select inserted separators. * * @keys `s-a-j` (normal) */ export function join_select(_: Context, separator?: Argument<string>) { return joinLines(selectionsLines(), separator).then(setSelections); } /** * Indent selected lines. * * @keys `>` (normal) */ export function indent(_: Context, repetitions: number) { return indentLines(selectionsLines(), repetitions, /* indentEmpty= */ false); } /** * Indent selected lines (including empty lines). * * @keys `a->` (normal) */ export function indent_withEmpty(_: Context, repetitions: number) { return indentLines(selectionsLines(), repetitions, /* indentEmpty= */ true); } /** * Deindent selected lines. * * @keys `a-<` (normal) */ export function deindent(_: Context, repetitions: number) { return deindentLines(selectionsLines(), repetitions, /* deindentIncomplete= */ false); } /** * Deindent selected lines (including incomplete indent). * * @keys `<` (normal) */ export function deindent_withIncomplete(_: Context, repetitions: number) { return deindentLines(selectionsLines(), repetitions, /* deindentIncomplete= */ true); } /** * Transform to lower case. * * @keys `` ` `` (normal) */ export function case_toLower(_: Context) { return replace((text) => text.toLocaleLowerCase()); } /** * Transform to upper case. * * @keys `` s-` `` (normal) */ export function case_toUpper(_: Context) { return replace((text) => text.toLocaleUpperCase()); } /** * Swap case. * * @keys `` a-` `` (normal) */ export function case_swap(_: Context) { return replace((text) => { let builtText = ""; for (let i = 0, len = text.length; i < len; i++) { const x = text[i], loCase = x.toLocaleLowerCase(); builtText += loCase === x ? x.toLocaleUpperCase() : loCase; } return builtText; }); } /** * Replace characters. * * @keys `r` (normal) */ export async function replaceCharacters( _: Context, repetitions: number, inputOr: InputOr<string>, ) { const input = (await inputOr(() => keypress(_))).repeat(repetitions); return _.run(() => edit((editBuilder, selections, document) => { for (const selection of selections) { let i = selection.start.line; if (selection.end.line === i) { // A single line-selection; replace the selection directly editBuilder.replace( selection, input!.repeat(selection.end.character - selection.start.character), ); continue; } // Replace in first line const firstLine = document.lineAt(i).range.with(selection.start); editBuilder.replace( firstLine, input!.repeat(firstLine.end.character - firstLine.start.character), ); // Replace in intermediate lines while (++i < selection.end.line) { const line = document.lineAt(i); editBuilder.replace(line.range, input!.repeat(line.text.length)); } // Replace in last line const lastLine = document.lineAt(i).range.with(undefined, selection.end); editBuilder.replace( lastLine, input!.repeat(lastLine.end.character - lastLine.start.character), ); } })); } /** * Align selections. * * Align selections, aligning the cursor of each selection by inserting spaces * before the first character of each selection. * * @keys `&` (normal) */ export function align( _: Context, selections: readonly vscode.Selection[], fill: Argument<string> = " ", ) { const startChar = selections.reduce( (max, sel) => (sel.start.character > max ? sel.start.character : max), 0, ); return edit((builder, selections) => { for (let i = 0, len = selections.length; i < len; i++) { const selection = selections[i]; builder.insert(selection.start, fill.repeat(startChar - selection.start.character)); } }); } /** * Copy indentation. * * Copy the indentation of the main selection (or the count one if a count is * given) to all other ones. * * @keys `a-&` (normal) */ export function copyIndentation( _: Context, document: vscode.TextDocument, selections: readonly vscode.Selection[], count: number, ) { const sourceSelection = selections[count] ?? selections[0], sourceIndent = document .lineAt(sourceSelection.start) .firstNonWhitespaceCharacterIndex; return edit((builder, selections, document) => { for (let i = 0, len = selections.length; i < len; i++) { if (i === sourceSelection.start.line) { continue; } const line = document.lineAt(selections[i].start), indent = line.firstNonWhitespaceCharacterIndex; if (indent > sourceIndent) { builder.delete( line.range.with( undefined, line.range.start.translate(undefined, indent - sourceIndent), ), ); } else if (indent < sourceIndent) { builder.insert(line.range.start, " ".repeat(indent - sourceIndent)); } } }); } /** * Insert new line above each selection. * * Specify `"shift": "select"` to select the inserted selections, and nothing to * keep the current selections. * * `select` is deprecated; use `shift` with `"select"` instead. * * @keys `s-a-o` (normal) * * #### Additional keybindings * * | Title | Identifier | Keybinding | Commands | * | ------------------------------------------ | ---------------------- | -------------- | ------------------------------------------------------------------------ | * | Insert new line above and switch to insert | `newLine.above.insert` | `s-o` (normal) | `[".edit.newLine.above", { shift: "select" }], [".modes.insert.before"]` | */ export function newLine_above( _: Context, repetitions: number, select: Argument<boolean> = false, shift?: Argument<Shift>, ) { if (select || shift === Shift.Select) { return insertLinesNativelyAndCopySelections(_, repetitions, "editor.action.insertLineBefore"); } return edit((builder, selections, document) => { const newLine = (document.eol === vscode.EndOfLine.LF ? "\n" : "\r\n").repeat(repetitions), processedLines = new Set<number>(); for (let i = 0, len = selections.length; i < len; i++) { const selection = selections[i], activeLine = Selections.activeLine(selection); if (processedLines.size !== processedLines.add(activeLine).size) { builder.insert(new vscode.Position(activeLine, 0), newLine); } } }); } /** * Insert new line below each selection. * * Specify `"shift": "select"` to select the inserted selections, and nothing to * keep the current selections. * * `select` is deprecated; use `shift` with `"select"` instead. * * @keys `a-o` (normal) * * #### Additional keybindings * * | Title | Identifier | Keybinding | Commands | * | ------------------------------------------ | ---------------------- | ------------ | ------------------------------------------------------------------------ | * | Insert new line below and switch to insert | `newLine.below.insert` | `o` (normal) | `[".edit.newLine.below", { shift: "select" }], [".modes.insert.before"]` | */ export function newLine_below( _: Context, repetitions: number, select: Argument<boolean> = false, shift?: Argument<Shift>, ) { if (select || shift === Shift.Select) { return insertLinesNativelyAndCopySelections(_, repetitions, "editor.action.insertLineAfter"); } return edit((builder, selections, document) => { const newLine = (document.eol === vscode.EndOfLine.LF ? "\n" : "\r\n").repeat(repetitions), processedLines = new Set<number>(); for (let i = 0, len = selections.length; i < len; i++) { const selection = selections[i], activeLine = Selections.activeLine(selection); if (processedLines.size !== processedLines.add(activeLine).size) { builder.insert(new vscode.Position(activeLine + 1, 0), newLine); } } }); } function prepareSelectionForLineInsertion(_: number, selection: vscode.Selection) { const activeLine = Selections.activeLine(selection); if (selection.active.line !== activeLine) { return new vscode.Selection(selection.anchor, selection.active.with(activeLine)); } return selection; } function extendArrayToLength<T>(array: readonly T[], length: number) { const arrayLen = array.length; if (length > arrayLen) { const newArray = array.slice(), last = array[arrayLen - 1]; for (let i = arrayLen; i < length; i++) { newArray.push(last); } return newArray; } else { return array.slice(0, length); } } /** * Inserts lines below or above each current selection, and copies the new * selections the given number of times. * * This function uses the native VS Code insertion strategy to get a valid * indentation for the new selections, and copies the inserted selections down * if more than one repetition is requested. */ function insertLinesNativelyAndCopySelections( _: Context, repetitions: number, command: "editor.action.insertLineAfter" | "editor.action.insertLineBefore", ) { Selections.update.byIndex(prepareSelectionForLineInsertion); if (repetitions === 1) { return vscode.commands.executeCommand(command); } const isLastCharacterAt = [] as boolean[]; return vscode.commands.executeCommand(command).then(() => _.edit((builder, selections, document) => { for (const selection of selections) { const active = selection.active, lineStart = Positions.lineStart(active.line), indentationRange = new vscode.Range(lineStart, active), indentation = (document.getText(indentationRange) + "\n").repeat(repetitions - 1); if (active.line === document.lineCount - 1) { isLastCharacterAt.push(true); builder.insert(Positions.lineEnd(active.line), "\n" + indentation.slice(0, -1)); } else { isLastCharacterAt.push(false); builder.insert(lineStart.translate(1), indentation); } } }), ).then(() => { const selections = [] as vscode.Selection[]; let selectionIndex = 0; for (let selection of _.selections) { if (isLastCharacterAt[selectionIndex++]) { // Selection corresponds to the last character in the document. We // couldn't simply insert a line above, so we must correct the current // selection. selection = Selections.fromAnchorActive( selection.anchor.translate(-repetitions + 1), selection.active.translate(-repetitions + 1), ); } const active = selection.active, anchor = selection.anchor; for (let i = repetitions - 1; i > 0; i--) { selections.push(Selections.fromAnchorActive(anchor.translate(i), active.translate(i))); } selections.push(selection); } _.selections = selections; }); }
the_stack
import crypto from 'crypto'; import {EventEmitter} from 'events'; import { Db, GridFSBucket, GridFSBucketWriteStream, MongoClient, MongoClientOptions, ObjectId, } from 'mongodb'; import isPromise from 'is-promise'; import isGenerator from 'is-generator'; import pump from 'pump'; import {Request} from 'express'; import {StorageEngine} from 'multer'; import mongoUri from 'mongodb-uri'; import {getDatabase, shouldListenOnDb} from './utils'; import {Cache} from './cache'; import { CacheIndex, GridFile, ConnectionResult, NodeCallback, UrlStorageOptions, DbStorageOptions, } from './types'; const isGeneratorFn = isGenerator.fn; /** * Default file information * @const defaults **/ const defaults = { metadata: null, chunkSize: 261_120, bucketName: 'fs', aliases: null, }; /** * Multer GridFS Storage Engine class definition. * @extends EventEmitter * @param {object} configuration * @param {string} [configuration.url] - The url pointing to a MongoDb database * @param {object} [configuration.options] - Options to use when connection with an url. * @param {object} [configuration.connectionOpts] - DEPRECATED: Use options instead. * @param {boolean | string} [configuration.cache] - Store this connection in the internal cache. * @param {Db | Promise} [configuration.db] - The MongoDb database instance to use or a promise that resolves with it * @param {Function} [configuration.file] - A function to control the file naming in the database * @fires GridFsStorage#connection * @fires GridFsStorage#connectionFailed * @fires GridFsStorage#file * @fires GridFsStorage#streamError * @fires GridFsStorage#dbError * @version 0.0.3 */ export class GridFsStorage extends EventEmitter implements StorageEngine { static cache: Cache = new Cache(); db: Db = null; client: MongoClient = null; configuration: DbStorageOptions | UrlStorageOptions; connected = false; connecting = false; caching = false; error: any = null; private _file: any; private readonly _options: any; private readonly cacheName: string; private readonly cacheIndex: CacheIndex; constructor(configuration: UrlStorageOptions | DbStorageOptions) { super(); if ( !configuration || (!(configuration as UrlStorageOptions).url && !(configuration as DbStorageOptions).db) ) { throw new Error( 'Error creating storage engine. At least one of url or db option must be provided.', ); } this.setMaxListeners(0); this.configuration = configuration; this._file = this.configuration.file; const {url, cache, options} = this.configuration as UrlStorageOptions; if (url) { this.caching = Boolean(cache); this._options = options; } if (this.caching) { const {cache, url} = configuration as UrlStorageOptions; const cacheName = typeof cache === 'string' ? cache : 'default'; this.cacheName = cacheName; this.cacheIndex = GridFsStorage.cache.initialize({ url, cacheName, init: this._options, }); } this._connect(); } /** * Generates 16 bytes long strings in hexadecimal format */ static async generateBytes(): Promise<{filename: string}> { return new Promise((resolve, reject) => { crypto.randomBytes(16, (error, buffer) => { if (error) { reject(error); return; } resolve({filename: buffer.toString('hex')}); }); }); } /** * Merge the properties received in the file function with default values * @param extra Extra properties like contentType * @param fileSettings Properties received in the file function * @return An object with the merged properties wrapped in a promise */ private static async _mergeProps(extra, fileSettings): Promise<any> { // If the filename is not provided generate one const previous: any = await (fileSettings.filename ? {} : GridFsStorage.generateBytes()); // If no id is provided generate one // If an error occurs the emitted file information will contain the id const hasId = fileSettings.id; if (!hasId) { previous.id = new ObjectId(); } return {...previous, ...defaults, ...extra, ...fileSettings}; } /** * Handles generator function and promise results * @param result - Can be a promise or a generator yielded value * @param isGen - True if is a yielded value **/ private static async _handleResult( result: any, isGen: boolean, ): Promise<any> { let value = result; if (isGen) { if (result.done) { throw new Error('Generator ended unexpectedly'); } value = result.value; } return value; } /** * Storage interface method to handle incoming files * @param {Request} request - The request that trigger the upload * @param {File} file - The uploaded file stream * @param cb - A standard node callback to signal the end of the upload or an error **/ _handleFile(request: Request, file, cb: NodeCallback): void { if (this.connecting) { this.ready() /* eslint-disable-next-line promise/prefer-await-to-then */ .then(async () => this.fromFile(request, file)) /* eslint-disable-next-line promise/prefer-await-to-then */ .then((file) => { cb(null, file); }) .catch(cb); return; } this._updateConnectionStatus(); if (this.connected) { this.fromFile(request, file) /* eslint-disable-next-line promise/prefer-await-to-then */ .then((file) => { cb(null, file); }) .catch(cb); return; } cb(new Error('The database connection must be open to store files')); } /** * Storage interface method to delete files in case an error turns the request invalid * @param request - The request that trigger the upload * @param {File} file - The uploaded file stream * @param cb - A standard node callback to signal the end of the upload or an error **/ _removeFile(request: Request, file, cb: NodeCallback): void { const options = {bucketName: file.bucketName}; const bucket = new GridFSBucket(this.db, options); bucket.delete(file.id, cb); } /** * Waits for the MongoDb connection associated to the storage to succeed or fail */ async ready(): Promise<ConnectionResult> { if (this.error) { throw this.error; } if (this.connected) { return {db: this.db, client: this.client}; } return new Promise((resolve, reject) => { const done = (result) => { this.removeListener('connectionFailed', fail); resolve(result); }; const fail = (error) => { this.removeListener('connection', done); reject(error); }; this.once('connection', done); this.once('connectionFailed', fail); }); } /** * Pipes the file stream to the MongoDb database. The file requires a property named `file` which is a readable stream * @param request - The http request where the file was uploaded * @param {File} file - The file stream to pipe * @return {Promise} Resolves with the uploaded file */ async fromFile(request: Request, file): Promise<GridFile> { return this.fromStream(file.stream, request, file); } /** * Pipes the file stream to the MongoDb database. The request and file parameters are optional and used for file generation only * @param readStream - The http request where the file was uploaded * @param [request] - The http request where the file was uploaded * @param {File} [file] - The file stream to pipe * @return Resolves with the uploaded file */ async fromStream( readStream: NodeJS.ReadableStream, request: Request, file: any, ): Promise<GridFile> { return new Promise<GridFile>((resolve, reject) => { readStream.on('error', reject); this.fromMulterStream(readStream, request, file) /* eslint-disable-next-line promise/prefer-await-to-then */ .then(resolve) .catch(reject); }); } protected async _openConnection( url: string, options: MongoClientOptions, ): Promise<ConnectionResult> { let client = null; let db; const connection = await MongoClient.connect(url, options); if (connection instanceof MongoClient) { client = connection; const parsedUri = mongoUri.parse(url); db = client.db(parsedUri.database); } else { db = connection; } return {client, db}; } /** * Create a writable stream with backwards compatibility with GridStore * @param {object} options - The stream options */ protected createStream(options): GridFSBucketWriteStream { const settings = { id: options.id, chunkSizeBytes: options.chunkSize, contentType: options.contentType, metadata: options.metadata, aliases: options.aliases, disableMD5: options.disableMD5, }; const gfs = new GridFSBucket(this.db, {bucketName: options.bucketName}); return gfs.openUploadStream(options.filename, settings); } private async fromMulterStream( readStream: NodeJS.ReadableStream, request: Request, file: any, ): Promise<GridFile> { if (this.connecting) { await this.ready(); } const fileSettings = await this._generate(request, file); let settings; const setType = typeof fileSettings; const allowedTypes = new Set(['undefined', 'number', 'string', 'object']); if (!allowedTypes.has(setType)) { throw new Error('Invalid type for file settings, got ' + setType); } if (fileSettings === null || fileSettings === undefined) { settings = {}; } else if (setType === 'string' || setType === 'number') { settings = { filename: fileSettings.toString(), }; } else { settings = fileSettings; } const contentType = file ? file.mimetype : undefined; const streamOptions = await GridFsStorage._mergeProps( {contentType}, settings, ); return new Promise((resolve, reject) => { const emitError = (streamError) => { this.emit('streamError', streamError, streamOptions); reject(streamError); }; const emitFile = (f) => { const storedFile: GridFile = { id: f._id, filename: f.filename, metadata: f.metadata || null, bucketName: streamOptions.bucketName, chunkSize: f.chunkSize, size: f.length, md5: f.md5, uploadDate: f.uploadDate, contentType: f.contentType, }; this.emit('file', storedFile); resolve(storedFile); }; const writeStream = this.createStream(streamOptions); // Multer already handles the error event on the readable stream(Busboy). // Invoking the callback with an error will cause file removal and aborting routines to be called twice writeStream.on('error', emitError); writeStream.on('finish', emitFile); // @ts-ignore pump([readStream, writeStream]); }); } /** * Determines if a new connection should be created, a explicit connection is provided or a cached instance is required. */ private _connect() { const {db, client = null} = this.configuration as DbStorageOptions<Db>; if (db && !isPromise(db) && !isPromise(client)) { this._setDb(db, client); return; } this._resolveConnection() /* eslint-disable-next-line promise/prefer-await-to-then */ .then(({db, client}) => { this._setDb(db, client); }) .catch((error) => { this._fail(error); }); } /** * Returns a promise that will resolve to the db and client from the cache or a new connection depending on the provided configuration */ private async _resolveConnection(): Promise<ConnectionResult> { this.connecting = true; const {db, client = null} = this.configuration as DbStorageOptions<Db>; if (db) { const [_db, _client] = await Promise.all([db, client]); return {db: _db, client: _client}; } if (!this.caching) { return this._createConnection(); } const {cache} = GridFsStorage; if (!cache.isOpening(this.cacheIndex) && cache.isPending(this.cacheIndex)) { const cached = cache.get(this.cacheIndex); cached.opening = true; return this._createConnection(); } return cache.waitFor(this.cacheIndex); } /** * Handles creating a new connection from an url and storing it in the cache if necessary*}>} */ private async _createConnection(): Promise<ConnectionResult> { const {url} = this.configuration as UrlStorageOptions; const options: MongoClientOptions = this._options; const {cache} = GridFsStorage; try { const {db, client} = await this._openConnection(url, options); if (this.caching) { cache.resolve(this.cacheIndex, db, client); } return {db, client}; } catch (error: unknown) { if (this.cacheIndex) { cache.reject(this.cacheIndex, error); } throw error; } } /** * Updates the connection status based on the internal db or client object **/ private _updateConnectionStatus(): void { if (!this.db) { this.connected = false; this.connecting = false; return; } if (this.client) { // @ts-ignore this.connected = this.client.isConnected ? // @ts-ignore this.client.isConnected() : true; return; } // @ts-expect-error this.connected = this.db?.topology?.isConnected() || true; } /** * Sets the database connection and emit the connection event * @param db - Database instance or Mongoose instance to set * @param [client] - Optional Mongo client for MongoDb v3 **/ private _setDb(db: Db, client?: MongoClient): void { this.connecting = false; // Check if the object is a mongoose instance, a mongoose Connection or a mongo Db object this.db = getDatabase(db); if (client) { this.client = client; } const errorEvent = (error_) => { // Needs verification. Sometimes the event fires without an error object // although the docs specify each of the events has a MongoError argument this._updateConnectionStatus(); const error = error_ || new Error('Unknown database error'); this.emit('dbError', error); }; // This are all the events that emit errors const errorEventNames = ['error', 'parseError', 'timeout', 'close']; let eventSource; if (shouldListenOnDb()) { eventSource = this.db; } else if (this.client) { eventSource = this.client; } if (eventSource) { for (const evt of errorEventNames) eventSource.on(evt, errorEvent); } this._updateConnectionStatus(); // Emit on next tick so user code can set listeners in case the db object is already available process.nextTick(() => { this.emit('connection', {db: this.db, client: this.client}); }); } /** * Removes the database reference and emit the connectionFailed event * @param err - The error received while trying to connect **/ private _fail(error: any): void { this.connecting = false; this.db = null; this.client = null; this.error = error; this._updateConnectionStatus(); // Fail event is only emitted after either a then promise handler or an I/O phase so is guaranteed to be asynchronous this.emit('connectionFailed', error); } /** * Tests for generator functions or plain functions and delegates to the appropriate method * @param request - The request that trigger the upload as received in _handleFile * @param {File} file - The uploaded file stream as received in _handleFile * @return A promise with the value generated by the file function **/ private async _generate(request: Request, file): Promise<any> { let result; let generator; let isGen = false; if (!this._file) { return {}; } if (isGeneratorFn(this._file)) { isGen = true; generator = this._file(request, file); this._file = generator; result = generator.next(); } else if (isGenerator(this._file)) { isGen = true; generator = this._file; result = generator.next([request, file]); } else { result = this._file(request, file); } return GridFsStorage._handleResult(result, isGen); } } /** * Event emitted when the MongoDb connection is ready to use * @event module:multer-gridfs-storage/gridfs~GridFSStorage#connection * @param {{db: Db, client: MongoClient}} result - An object containing the mongodb database and client * @version 0.0.3 */ /** * Event emitted when the MongoDb connection fails to open * @event module:multer-gridfs-storage/gridfs~GridFSStorage#connectionFailed * @param {Error} err - The error received when attempting to connect * @version 2.0.0 */ /** * Event emitted when a new file is uploaded * @event module:multer-gridfs-storage/gridfs~GridFSStorage#file * @param {File} file - The uploaded file * @version 0.0.3 */ /** * Event emitted when an error occurs streaming to MongoDb * @event module:multer-gridfs-storage/gridfs~GridFSStorage#streamError * @param {Error} error - The error thrown by the stream * @param {Object} conf - The failed file configuration * @version 1.3 */ /** * Event emitted when the internal database connection emits an error * @event module:multer-gridfs-storage/gridfs~GridFSStorage#dbError * @param {Error} error - The error thrown by the database connection * @version 1.2.2 **/ export const GridFsStorageCtr = new Proxy(GridFsStorage, { apply(target, thisArg, argumentsList) { // @ts-expect-error return new target(...argumentsList); // eslint-disable-line new-cap }, });
the_stack
import { Injectable, Logger, OnApplicationBootstrap, OnModuleInit, } from '@nestjs/common'; import { Peripheral, Advertisement } from '@mkerix/noble'; import { EntitiesService } from '../../entities/entities.service'; import { ConfigService } from '../../config/config.service'; import { XiaomiMiConfig, XiaomiMiSensorOptions } from './xiaomi-mi.config'; import { DISTRIBUTED_DEVICE_ID } from '../home-assistant/home-assistant.const'; import { Device } from '../home-assistant/device'; import { makeId } from '../../util/id'; import { EventType, ProductId, ServiceData, Parser } from './parser'; import { Sensor } from '../../entities/sensor'; import { EntityCustomization } from '../../entities/entity-customization.interface'; import { SensorConfig } from '../home-assistant/sensor-config'; import { BluetoothService } from '../../integration-support/bluetooth/bluetooth.service'; import { StateClass } from '../home-assistant/entity-config'; const SERVICE_DATA_UUID = 'fe95'; const SERVICE_BATTERY_UUID = '0000120400001000800000805f9b34fb'; const CHARACTERISTIC_BATTERY_UUID = '00001a0200001000800000805f9b34fb'; const BATTERY_QUERY_WINDOW = 60 * 60 * 1000; // Stagger battery queries to reduce adapter contention const BATTERY_QUERY_INTERVAL = 23.5 * 60 * 60 * 1000; // Refresh battery level every 23.5-24.5 hours const BATTERY_QUERY_ATTEMPTS = 3; class SensorMetadata { name: string; deviceClass: string; stateClass?: StateClass; units: string; } const SensorMetadataList: { [index: number]: SensorMetadata } = { [EventType.temperature]: { name: 'Temperature', deviceClass: 'temperature', stateClass: StateClass.MEASUREMENT, units: '°C', }, [EventType.humidity]: { name: 'Humidity', deviceClass: 'humidity', stateClass: StateClass.MEASUREMENT, units: '%', }, [EventType.battery]: { name: 'Battery', deviceClass: 'battery', stateClass: StateClass.MEASUREMENT, units: '%', }, [EventType.illuminance]: { name: 'Illuminance', deviceClass: 'illuminance', stateClass: StateClass.MEASUREMENT, units: 'lx', }, [EventType.moisture]: { name: 'Moisture', deviceClass: undefined, stateClass: StateClass.MEASUREMENT, units: '%', }, [EventType.fertility]: { name: 'Conductivity', deviceClass: undefined, stateClass: StateClass.MEASUREMENT, units: 'µS/cm', }, }; class BatterySchedule { nextQueryAfter: Date; attempts: number; } @Injectable() export class XiaomiMiService implements OnModuleInit, OnApplicationBootstrap { private readonly logger: Logger; private config: XiaomiMiConfig; private lastFrameSeen: number[] = []; private batterySchedule: BatterySchedule[] = []; constructor( private readonly bluetoothService: BluetoothService, private readonly entitiesService: EntitiesService, private readonly configService: ConfigService ) { this.logger = new Logger(XiaomiMiService.name); } /** * Lifecycle hook, called once the host module has been initialized. */ onModuleInit(): void { this.config = this.configService.get('xiaomiMi'); if (!this.hasSensors()) { this.logger.warn( 'No sensors entries in the config, so no sensors will be created! ' + 'Enable the bluetooth-low-energy integration to log discovered IDs.' ); } } /** * Lifecycle hook, called once the application has started. */ onApplicationBootstrap(): void { this.bluetoothService.onLowEnergyDiscovery(this.handleDiscovery.bind(this)); } /** * Determines whether we have any sensors. * * @returns Sensors status */ private hasSensors(): boolean { return this.config?.sensors?.length > 0; } /** * Record a measurement. * * @param device - The device and associated information that took the measurement. * @param sensor - The sensor meta-data including name, device class and units of measure. * @param state - The current measurement. */ private recordMeasure( device: Device, sensor: SensorMetadata, state: number | string ): void { this.logger.debug( `${device.name}: ${sensor.name}: ${state}${sensor.units}` ); const id = makeId(`xiaomi ${device.identifiers} ${sensor.name}`); let entity = this.entitiesService.get(id); if (!entity) { const customizations: Array<EntityCustomization<any>> = [ { for: SensorConfig, overrides: { deviceClass: sensor.deviceClass, stateClass: sensor.stateClass, unitOfMeasurement: sensor.units, device: device, }, }, ]; entity = this.entitiesService.add( new Sensor(id, `${device.name} ${sensor.name}`, true, false), customizations ) as Sensor; } entity.state = state; } /** * Filters found BLE peripherals and publishes new readings to sensors, depending on configuration. * * @param peripheral - BLE peripheral */ async handleDiscovery(peripheral: Peripheral): Promise<void> { const sensorConfig = this.config?.sensors?.find( (el) => el.address === peripheral.id ); if (!sensorConfig) { return; } const serviceData = this.parseAdvertisement( peripheral.advertisement, sensorConfig ); if (!serviceData) { return; } if (this.lastFrameSeen[peripheral.id] == serviceData.frameCounter) { return; } this.lastFrameSeen[peripheral.id] = serviceData.frameCounter; const device: Device = { name: sensorConfig.name, manufacturer: 'Xiaomi', model: serviceData.productName, identifiers: peripheral.id, viaDevice: DISTRIBUTED_DEVICE_ID, }; serviceData.events.forEach((event) => { const metadata = SensorMetadataList[event.type]; if (metadata) { this.recordMeasure(device, metadata, event.value); } else { this.logger.error( `${sensorConfig.name}: unknown event type: ${serviceData.eventType}` ); } }); const checkBattery = sensorConfig.enableMifloraBattery ?? this.config.enableMifloraBattery; if (serviceData.productId == ProductId.HHCCJCV01 && checkBattery) { await this.checkMifloraBattery(peripheral, device); } } /** * Parse the advertisement data and extract sensor readings if available. * * @param advertisement - raw advertisement data * @param sensorConfig - sensor configuration settings */ private parseAdvertisement( advertisement: Advertisement, sensorConfig: XiaomiMiSensorOptions ): ServiceData | null { const buffer = XiaomiMiService.findServiceData( advertisement, SERVICE_DATA_UUID ); if (!buffer) { this.logger.debug( `${ sensorConfig.name }: skipping message as supported data format not present: ${JSON.stringify( advertisement )}` ); return null; } let serviceData: ServiceData | null = null; try { serviceData = XiaomiMiService.parseServiceData( buffer, sensorConfig.bindKey ); } catch (error) { this.logger.error( `${sensorConfig.name}: skipping message as received data corrupt: ${error}` ); return null; } if (!serviceData.frameControl.hasEvent) { this.logger.debug( `${ sensorConfig.name }: skipping message as no sensor data provided: ${buffer.toString( 'hex' )}` ); return null; } return serviceData; } /** * Extract service data. * * @returns The service data buffer for the Xiamoi service data UUID or null * if it doesn't exist. */ private static findServiceData( advertisement: Advertisement, suuid: string ): Buffer | null { if (!advertisement?.serviceData) { return null; } const uuidPair = advertisement.serviceData.find( (data) => data.uuid.toLowerCase() === suuid ); if (!uuidPair) { return null; } return uuidPair.data; } /** * Parses the service data buffer. * * @param buffer - The servie data buffer. * @param bindKey - An optional bindKey for use in decripting the payload. * * @returns A ServiceData object. */ private static parseServiceData( buffer: Buffer, bindKey: string | null ): ServiceData { return new Parser(buffer, bindKey).parse(); } /** * Query the peripheral's battery service every 24 hours. * * @param peripheral - BLE peripheral * @param device - Device information */ async checkMifloraBattery( peripheral: Peripheral, device: Device ): Promise<void> { if (!this.batterySchedule.hasOwnProperty(peripheral.id)) { this.batterySchedule[peripheral.id] = { nextQueryAfter: new Date( Date.now() + Math.random() * BATTERY_QUERY_WINDOW ), attempts: 0, }; } const schedule: BatterySchedule = this.batterySchedule[peripheral.id]; if (Date.now() > schedule.nextQueryAfter.getTime()) { let buffer: Buffer = null; if (!this.bluetoothService.acquireQueryMutex()) { this.logger.debug(`${device.name}: Canceled battery reading as BLE adapter is already in use`); return; } schedule.attempts += 1; try { buffer = await this.bluetoothService.queryLowEnergyDevice( peripheral, SERVICE_BATTERY_UUID, CHARACTERISTIC_BATTERY_UUID ); if (!buffer) { throw new Error('data unavailable'); } } catch (error) { this.logger.warn( `${device.name}: Error reading battery level (attempt ${schedule.attempts} of ${BATTERY_QUERY_ATTEMPTS}): ${error}` ); } this.bluetoothService.releaseQueryMutex(); if (buffer) { // buffer[0] -> battery level (0-100) // buffer[2:] -> device firmware version (e.g. "3.2.4") if (buffer.length > 2) { device.swVersion = buffer.toString('utf-8', 2); } this.recordMeasure( device, SensorMetadataList[EventType.battery], buffer[0] ); this.logger.log( `${device.name}: Battery level updated to ${buffer[0]}%` ); } if (buffer || schedule.attempts >= BATTERY_QUERY_ATTEMPTS) { schedule.nextQueryAfter = new Date( Date.now() + BATTERY_QUERY_INTERVAL + Math.random() * BATTERY_QUERY_WINDOW ); schedule.attempts = 0; if (!buffer) { this.logger.error( `${device.name}: Battery query aborted after reaching maximum number of retries` ); } } } } }
the_stack
import { OverlayContainer } from '@angular/cdk/overlay'; import { Component, ElementRef, ViewChild } from '@angular/core'; import { fakeAsync, inject, tick, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { dispatchMouseEvent, dispatchFakeEvent } from '@ptsecurity/cdk/testing'; import { MC_POPOVER_CONFIRM_BUTTON_TEXT, MC_POPOVER_CONFIRM_TEXT } from './popover-confirm.component'; import { McPopoverModule } from './popover.module'; // tslint:disable:no-magic-numbers // tslint:disable:max-line-length // tslint:disable:no-console describe('McPopover', () => { let overlayContainer: OverlayContainer; let overlayContainerElement: HTMLElement; let componentFixture; let component; beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports : [ McPopoverModule, NoopAnimationsModule ], declarations: [ McPopoverTestComponent, McPopoverConfirmTestComponent, McPopoverConfirmWithProvidersTestComponent ] }); TestBed.compileComponents(); })); beforeEach(inject([ OverlayContainer ], (oc: OverlayContainer) => { overlayContainer = oc; overlayContainerElement = oc.getContainerElement(); })); afterEach(() => { overlayContainer.ngOnDestroy(); componentFixture.destroy(); }); describe('Check test cases', () => { beforeEach(() => { componentFixture = TestBed.createComponent(McPopoverTestComponent); component = componentFixture.componentInstance; componentFixture.detectChanges(); }); it('mcTrigger = hover', fakeAsync(() => { const expectedValue = '_TEST1'; const triggerElement = component.test1.nativeElement; expect(overlayContainerElement.textContent).not.toEqual(expectedValue); dispatchMouseEvent(triggerElement, 'mouseenter'); tick(); componentFixture.detectChanges(); expect(overlayContainerElement.textContent).toEqual(expectedValue); dispatchMouseEvent(triggerElement, 'mouseleave'); componentFixture.detectChanges(); dispatchMouseEvent(overlayContainerElement, 'mouseenter'); componentFixture.detectChanges(); expect(overlayContainerElement.textContent).toContain(expectedValue); // Move out from the tooltip element to hide it dispatchMouseEvent(overlayContainerElement, 'mouseleave'); tick(100); // tslint:disable-line componentFixture.detectChanges(); tick(); // wait for next tick to hide expect(overlayContainerElement.textContent).not.toEqual(expectedValue); })); it('mcTrigger = manual', fakeAsync(() => { const expectedValue = '_TEST2'; expect(overlayContainerElement.textContent).not.toEqual(expectedValue); component.popoverVisibility = true; tick(); componentFixture.detectChanges(); expect(overlayContainerElement.textContent).toEqual(expectedValue); component.popoverVisibility = false; componentFixture.detectChanges(); tick(500); // wait for next tick to hide componentFixture.detectChanges(); expect(overlayContainerElement.textContent).not.toEqual(expectedValue); })); it('mcTrigger = focus', fakeAsync(() => { const featureKey = '_TEST3'; const triggerElement = component.test3.nativeElement; dispatchFakeEvent(triggerElement, 'focus'); componentFixture.detectChanges(); expect(overlayContainerElement.textContent).toContain(featureKey); dispatchFakeEvent(triggerElement, 'blur'); tick(100); // tslint:disable-line componentFixture.detectChanges(); tick(); // wait for next tick to hide componentFixture.detectChanges(); tick(); // wait for next tick to hide expect(overlayContainerElement.textContent).not.toContain(featureKey); })); it('Can set mcPopoverHeader', fakeAsync(() => { const expectedValue = '_TEST4'; const triggerElement = component.test4.nativeElement; dispatchMouseEvent(triggerElement, 'mouseenter'); tick(); componentFixture.detectChanges(); const header = componentFixture.debugElement.query(By.css('.mc-popover__header')); expect(header.nativeElement.textContent).toEqual(expectedValue); })); it('Can set mcPopoverContent', fakeAsync(() => { const expectedValue = '_TEST5'; const triggerElement = component.test5.nativeElement; dispatchMouseEvent(triggerElement, 'mouseenter'); tick(); componentFixture.detectChanges(); const content = componentFixture.debugElement.query(By.css('.mc-popover__content')); expect(content.nativeElement.textContent).toEqual(expectedValue); })); it('Can set mcPopoverFooter', fakeAsync(() => { const expectedValue = '_TEST6'; const triggerElement = component.test6.nativeElement; dispatchMouseEvent(triggerElement, 'mouseenter'); tick(); componentFixture.detectChanges(); const footer = componentFixture.debugElement.query(By.css('.mc-popover__footer')); expect(footer.nativeElement.textContent).toEqual(expectedValue); })); it('Can set mcPopoverClass', fakeAsync(() => { const expectedValue = '_TEST7'; const triggerElement = component.test7.nativeElement; dispatchMouseEvent(triggerElement, 'click'); tick(); componentFixture.detectChanges(); const popover = componentFixture.debugElement.query(By.css('.mc-popover')); expect(popover.nativeElement.classList.contains(expectedValue)).toBeTruthy(); })); }); describe('Check popover confirm', () => { beforeEach(() => { componentFixture = TestBed.createComponent(McPopoverConfirmTestComponent); component = componentFixture.componentInstance; componentFixture.detectChanges(); }); it('Default text is correct', fakeAsync(() => { const triggerElement = component.test8.nativeElement; dispatchMouseEvent(triggerElement, 'click'); tick(); componentFixture.detectChanges(); const button = componentFixture.debugElement.query(By.css('.mc-popover-confirm button')); expect(button.nativeElement.textContent).toEqual('Да'); const confirmText = componentFixture.debugElement.query(By.css('.mc-popover-confirm .mc-popover__content div')); expect(confirmText.nativeElement.textContent).toEqual('Вы уверены, что хотите продолжить?'); })); it('Can set confirm text through input', fakeAsync(() => { const expectedValue = 'new confirm text'; const triggerElement = component.test9.nativeElement; dispatchMouseEvent(triggerElement, 'click'); tick(); componentFixture.detectChanges(); const confirmText = componentFixture.debugElement.query(By.css('.mc-popover-confirm .mc-popover__content div')); expect(confirmText.nativeElement.textContent).toEqual(expectedValue); })); it('Can set button text through input', fakeAsync(() => { const expectedValue = 'new button text'; const triggerElement = component.test10.nativeElement; dispatchMouseEvent(triggerElement, 'click'); tick(); componentFixture.detectChanges(); const button = componentFixture.debugElement.query(By.css('.mc-popover-confirm button')); expect(button.nativeElement.textContent).toEqual(expectedValue); })); it('Click emits confirm', fakeAsync(() => { spyOn(component, 'onConfirm'); const triggerElement = component.test11.nativeElement; dispatchMouseEvent(triggerElement, 'click'); tick(); const confirmButton = componentFixture.debugElement.query(By.css('.mc-popover-confirm button')); dispatchMouseEvent(confirmButton.nativeElement, 'click'); tick(); componentFixture.detectChanges(); expect(component.onConfirm).toHaveBeenCalled(); })); }); describe('Check popover confirm with providers', () => { beforeEach(() => { componentFixture = TestBed.createComponent(McPopoverConfirmWithProvidersTestComponent); component = componentFixture.componentInstance; componentFixture.detectChanges(); }); it('Provided text is correct', fakeAsync(() => { const triggerElement = component.test12.nativeElement; dispatchMouseEvent(triggerElement, 'click'); tick(); componentFixture.detectChanges(); const button = componentFixture.debugElement.query(By.css('.mc-popover-confirm button')); expect(button.nativeElement.textContent).toEqual('provided button text'); const confirmText = componentFixture.debugElement.query(By.css('.mc-popover-confirm .mc-popover__content div')); expect(confirmText.nativeElement.textContent).toEqual('provided confirm text'); })); }); }); @Component({ selector: 'mc-popover-test-component', template: ` <button #test1 mcPopover [mcTrigger]="'hover'" [mcPopoverContent]="'_TEST1'">_TEST1asdasd</button> <button #test2 mcPopover [mcTrigger]="'manual'" [mcPopoverVisible]="popoverVisibility" mcPopoverContent="_TEST2">_TEST2</button> <button #test3 mcPopover [mcTrigger]="'focus'" [mcPopoverContent]="'_TEST3'">_TEST3</button> <button #test4 mcPopover [mcTrigger]="'hover'" [mcPopoverHeader]="'_TEST4'">_TEST4</button> <button #test5 mcPopover [mcTrigger]="'hover'" [mcPopoverContent]="'_TEST5'">_TEST5</button> <button #test6 mcPopover [mcTrigger]="'hover'" [mcPopoverFooter]="'_TEST6'">_TEST6</button> <button #test7 mcPopover [mcPopoverClass]="'_TEST7'" [mcPopoverContent]="'_TEST7'">_TEST7</button> ` }) class McPopoverTestComponent { popoverVisibility: boolean = false; @ViewChild('test1', {static: false}) test1: ElementRef; @ViewChild('test2', {static: false}) test2: ElementRef; @ViewChild('test3', {static: false}) test3: ElementRef; @ViewChild('test4', {static: false}) test4: ElementRef; @ViewChild('test5', {static: false}) test5: ElementRef; @ViewChild('test6', {static: false}) test6: ElementRef; @ViewChild('test7', {static: false}) test7: ElementRef; } @Component({ selector: 'mc-popover-test-component', template: ` <button #test8 mcPopoverConfirm>_TEST8</button> <button #test9 mcPopoverConfirm mcPopoverConfirmText="new confirm text">_TEST9</button> <button #test10 mcPopoverConfirm mcPopoverConfirmButtonText="new button text">_TEST10</button> <button #test11 mcPopoverConfirm (confirm)="onConfirm()">_TEST11</button> ` }) class McPopoverConfirmTestComponent { @ViewChild('test8', {static: false}) test8: ElementRef; @ViewChild('test9', {static: false}) test9: ElementRef; @ViewChild('test10', {static: false}) test10: ElementRef; @ViewChild('test11', {static: false}) test11: ElementRef; onConfirm() { return; } } @Component({ selector: 'mc-popover-test-with-providers-component', template: ` <button #test12 mcPopoverConfirm>_TEST12</button> `, providers: [ {provide: MC_POPOVER_CONFIRM_TEXT, useValue: 'provided confirm text'}, {provide: MC_POPOVER_CONFIRM_BUTTON_TEXT, useValue: 'provided button text'} ] }) class McPopoverConfirmWithProvidersTestComponent { @ViewChild('test12', {static: false}) test12: ElementRef; }
the_stack
import SObject from '../Core/SObject'; import {SClass} from '../Core/Decorator'; import {Vector3, Quaternion} from '../Core/Math'; import {IPhysicWorld, TColliderParams, EColliderType, IPickOptions, IPickResult, EPickMode, ERigidBodyType, TJointParams, EJointType, IPointToPointJointOptions, IDistanceJointOptions, ISpringJointOptions} from '../types/Physic'; import ColliderComponent from '../Physic/ColliderComponent'; import JointComponent from '../Physic/JointComponent'; import RigidBodyComponent, {IRigidBodyComponentState} from './RigidBodyComponent'; import SceneActor from '../Renderer/ISceneActor'; import Debug from '../Debug'; import UnmetRequireException from '../Exception/UnmetRequireException'; import {bfs} from '../utils/actorIterators'; import SpringJointComponent from './SpringJointComponent'; /** * 基于cannon.js的物理世界类,完成了CANNON到Sein.js的物理引擎的桥接。 * **一般情况下你并不需要直接操作这个实例,而是使用刚体和碰撞体组件!** * CANNON的工程(魔改过的)请见这里:[https://github.com/dtysky/cannon.js](https://github.com/dtysky/cannon.js),可以使用`npm i cannon-dtysky`获取。 * 详细使用请见[Physic](../../guide/physic)。 * * @noInheritDoc */ @SClass({className: 'CannonPhysicWorld', classType: 'PhysicWorld'}) export default class CannonPhysicWorld extends SObject implements IPhysicWorld { public isPhysicWorld = true; public isCannonPhysicWorld = true; /** * CANNON模块引用。 */ public CANNON: any; private _world: any; private _fixedTimeStep: number = 1 / 60; private _physicsMaterials: any[] = []; private _ray: any; private _rayResult: any; /** * 构造器。 * * @param Cannon CANNON模块引用`Cannon`。 * @param gravity 世界重力。 * @param iterations 迭代次数。 */ constructor( Cannon: any, gravity: Vector3 = new Vector3(0, -9.81, 0), iterations: number = 10 ) { super('SeinCannonPhysicWorld'); if (!Cannon) { throw new UnmetRequireException( this, 'The newest version Cannonjs is required ! Goto "https://github.com/dtysky/cannon.js/tree/master/build" get it !' ); } this.CANNON = Cannon; this._world = new this.CANNON.World(); this._world.broadphase = new this.CANNON.NaiveBroadphase(); this._world.solver.iterations = iterations; this._world.gravity.set(gravity.x, gravity.y, gravity.z); this._ray = new this.CANNON.Ray(); this._rayResult = new this.CANNON.RaycastResult(); } /** * 设置固定步长(秒)。 */ set timeStep(value: number) { this._fixedTimeStep = value; } /** * 获取固定步长(秒)。 */ get timeStep() { return this._fixedTimeStep; } /** * 设置重力。 */ set gravity(gravity: Vector3) { this._world.gravity.set(gravity.x, gravity.y, gravity.z); } /** * 获取重力。 */ get gravity() { const {x, y, z} = this._world.gravity; return new Vector3(x, y, z); } /** * 启用高级碰撞事件,这可以让你拥有对碰撞更细致的控制,但会有一些性能损耗。 */ public initContactEvents() { this._world.addEventListener('beginContact', args => { if (!args.bodyA || !args.bodyB) { return; } if (args.bodyA.component.valid) { (args.bodyA.component as RigidBodyComponent).handleBodyEnter( args.bodyA.component, args.bodyB.component ); } if (args.bodyB.component.valid) { (args.bodyB.component as RigidBodyComponent).handleBodyEnter( args.bodyB.component, args.bodyA.component ); } }); this._world.addEventListener('endContact', args => { if (!args.bodyA || !args.bodyB) { return; } if (args.bodyA.component.valid) { (args.bodyA.component as RigidBodyComponent).handleBodyLeave( args.bodyA.component, args.bodyB.component ); } if (args.bodyB.component.valid) { (args.bodyB.component as RigidBodyComponent).handleBodyLeave( args.bodyB.component, args.bodyA.component ); } }); this._world.addEventListener('beginShapeContact', args => { if (!args.bodyA || !args.bodyB) { return; } if (args.bodyA.component.valid) { (args.bodyA.component as RigidBodyComponent).handleColliderEnter( args.bodyA.component, args.bodyB.component, args.shapeA.component, args.shapeB.component ); } if (args.bodyB.component.valid) { (args.bodyB.component as RigidBodyComponent).handleColliderEnter( args.bodyB.component, args.bodyA.component, args.shapeB.component, args.shapeA.component ); } }); this._world.addEventListener('endShapeContact', args => { if (!args.bodyA || !args.bodyB) { return; } if (args.bodyA.component.valid) { (args.bodyA.component as RigidBodyComponent).handleColliderLeave( args.bodyA.component, args.bodyB.component, args.shapeA.component, args.shapeB.component ); } if (args.bodyB.component.valid) { (args.bodyB.component as RigidBodyComponent).handleColliderLeave( args.bodyB.component, args.bodyA.component, args.shapeB.component, args.shapeA.component ); } }); } /** * 设置重力。 */ public setGravity(gravity: Vector3) { this._world.gravity.x = gravity.x; this._world.gravity.y = gravity.y; this._world.gravity.z = gravity.z; return this; } /** * **不要自己调用!!** * * @hidden */ public update(delta: number = 0, components: RigidBodyComponent[] = []): void { this._world.step(this._fixedTimeStep, delta, 3); } /** * 添加脉冲力。 */ public applyImpulse(component: RigidBodyComponent, force: Vector3, contactPoint: Vector3) { const worldPoint = new this.CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z); const impulse = new this.CANNON.Vec3(force.x, force.y, force.z); component.rigidBody.applyImpulse(impulse, worldPoint); } /** * 添加力。 */ public applyForce(component: RigidBodyComponent, force: Vector3, contactPoint: Vector3) { const worldPoint = new this.CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z); const impulse = new this.CANNON.Vec3(force.x, force.y, force.z); component.rigidBody.applyForce(impulse, worldPoint); } /** * 拾取操作。 */ public pick( from: Vector3, to: Vector3, onPick: (result: IPickResult[]) => void, origOptions: IPickOptions = {} ) { const options = {...origOptions}; this._ray.from.copy(from); this._ray.to.copy(to); this._ray.checkCollisionResponse = options.checkCollisionResponse === true ? true : false; switch (options.mode) { case EPickMode.All: (options as any).mode = this.CANNON.Ray.ALL; break; case EPickMode.Any: (options as any).mode = this.CANNON.Ray.ANY; break; case EPickMode.Closest: (options as any).mode = this.CANNON.Ray.CLOSEST; default: (options as any).mode = this.CANNON.Ray.CLOSEST; break; } options.skipBackfaces = options.skipBackfaces === false ? false : true; (options as any).result = this._rayResult; const result = []; (options as any).callback = () => { const {body, shape, distance, hitPointWorld} = this._rayResult; if (!body.component.valid) { return; } result.push({rigidBody: body.component, collider: shape.component, actor: body.component.getOwner(), distance, point: new Vector3(hitPointWorld.x, hitPointWorld.y, hitPointWorld.z)}); }; if (options.bodies) { (options as any).bodies = options.bodies.map(body => body.rigidBody); } const hit = this._ray.intersectWorld(this._world, options); if (hit) { if (options.mode === EPickMode.CLOSEST) { const {body, shape, distance, hitPointWorld} = this._rayResult; result.push({rigidBody: body.component, collider: shape.component, actor: body.component.getOwner(), distance, point: new Vector3(hitPointWorld.x, hitPointWorld.y, hitPointWorld.z)}); } } onPick(result); return hit; } /** * 创建一个刚体。 */ public createRigidBody(component: RigidBodyComponent, options: IRigidBodyComponentState) { const material = this.addMaterial( `mat-${component.uuid}`, options.friction, options.restitution ); const bodyCreationObject = { mass: options.mass, material: material }; for (const key in options.nativeOptions) { bodyCreationObject[key] = options.nativeOptions[key]; } const rigidBody = new this.CANNON.Body(bodyCreationObject); rigidBody.component = component; const [position, rotation, scale] = component.getCurrentTransform(); this.setBodyTransform(rigidBody, position, rotation, scale); rigidBody.updateMassProperties(); rigidBody.updateBoundingRadius(); if (Debug.devMode) { this.checkNest(component); } this._world.addBody(rigidBody); return rigidBody; } /** * 暂时使得刚体失去效应,可以用`enableRigidBody`恢复。 */ public disableRigidBody(component: RigidBodyComponent) { this._world.remove(component.rigidBody); } /** * 使得一个暂时失去效应的刚体恢复。 */ public enableRigidBody(component: RigidBodyComponent) { this._world.add(component.rigidBody); } /** * 在开发环境下,检测是否有物理嵌套。 */ private checkNest(component: RigidBodyComponent) { const actor = component.getOwner<SceneActor>(); let parent: any = actor.parent; while (parent) { if ((parent as SceneActor).rigidBody) { Debug.warn( 'You should never have a parent and child "none isTrigger and 0 mass" rigidBody together', actor, parent ); break; } parent = parent.parent; } bfs(actor, (child: SceneActor) => { if (child.rigidBody) { Debug.warn( 'You should never have a parent and child "none isTrigger and 0 mass" rigidBody together', actor, child ); return false; } return true; }); } /** * 初始化基本事件。 */ public initEvents(component: RigidBodyComponent) { this._world.addEventListener('preStep', component.handleBeforeStep); this._world.addEventListener('postStep', component.handleAfterStep); component.rigidBody.addEventListener('collide', component.handleCollision); } /** * 移除一个刚体。 */ public removeRigidBody(component: RigidBodyComponent) { this._world.removeEventListener('preStep', component.handleBeforeStep); this._world.removeEventListener('postStep', component.handleAfterStep); component.rigidBody.removeEventListener('collision', component.handleCollision); this._world.remove(component.rigidBody); } /** * 清空物理世界。 */ public clear() { this._world._listeners.preStep = []; this._world._listeners.postStep = []; this._world.bodies = []; } public createJoint(rigidBody: RigidBodyComponent, component: JointComponent, params: TJointParams) { const {type, options} = params; const {actor, ...data} = options; const mainBody = rigidBody.rigidBody; const connectedBody = actor.rigidBody.rigidBody; let constraint: any; switch (type) { case EJointType.Hinge: constraint = new this.CANNON.HingeConstraint(mainBody, connectedBody, data); break; case EJointType.Distance: constraint = new this.CANNON.DistanceConstraint(mainBody, connectedBody, (<IDistanceJointOptions>data).distance, (<IDistanceJointOptions>data).maxForce); break; case EJointType.Spring: constraint = new this.CANNON.Spring(mainBody, connectedBody, <ISpringJointOptions>data); break; case EJointType.Lock: constraint = new this.CANNON.LockConstraint(mainBody, connectedBody, data); break; case EJointType.PointToPoint: default: constraint = new this.CANNON.PointToPointConstraint(mainBody, (<IPointToPointJointOptions>data).pivotA, connectedBody, (<IPointToPointJointOptions>data).pivotB, (<IPointToPointJointOptions>data).maxForce); break; } constraint.collideConnected = !!data.collideConnected; constraint.wakeUpBodies = !!data.wakeUpBodies; constraint.component = constraint; //don't add spring as constraint, as it is not one. if (type !== EJointType.Spring) { this._world.addConstraint(constraint); } else { rigidBody.event.add('AfterStep', (<SpringJointComponent>component).applyForce); } return constraint; } public removeJoint(rigidBody: RigidBodyComponent, component: JointComponent) { if (component.type !== EJointType.Spring) { this._world.removeConstraint(component.joint); } else { rigidBody.event.remove('AfterStep', (<SpringJointComponent>component).applyForce); } } public enableJoint(component: JointComponent) { component.joint.enable(); } public disableJoint(component: JointComponent) { component.joint.disable(); } private addMaterial(name: string, friction: number, restitution: number) { let index; let mat; for (index = 0; index < this._physicsMaterials.length; index += 1) { mat = this._physicsMaterials[index]; if (mat.friction === friction && mat.restitution === restitution) { return mat; } } const currentMat = new this.CANNON.Material(name); currentMat.friction = friction; currentMat.restitution = restitution; this._physicsMaterials.push(currentMat); return currentMat; } /** * 创建碰撞体。 */ public createCollider(bodyComp: RigidBodyComponent, colliderComp: ColliderComponent, params: TColliderParams): any { let shape: any; switch (params.type) { case EColliderType.Sphere: shape = new this.CANNON.Sphere(params.options.radius); break; case EColliderType.Cylinder: shape = new this.CANNON.Cylinder( params.options.radiusTop, params.options.radiusBottom, params.options.height, params.options.numSegments ); break; case EColliderType.Box: shape = new this.CANNON.Box( new this.CANNON.Vec3( params.options.size[0] / 2, params.options.size[1] / 2, params.options.size[2] / 2 ) ); break; case EColliderType.Plane: Debug.warn('Attention, PlaneCollider might not behave as you expect. Consider using BoxCollider instead'); shape = new this.CANNON.Plane(); break; // case EColliderType.Heightmap: // let oldPosition2 = object.position.clone(); // let oldRotation2 = object.rotation && object.rotation.clone(); // let oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone(); // object.position.copyFromFloats(0, 0, 0); // object.rotation && object.rotation.copyFromFloats(0, 0, 0); // object.rotationQuaternion && object.rotationQuaternion.copyFrom(component.getParentsRotation()); // object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace(); // object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X); // shape = this._createHeightmap(object); // object.position.copyFrom(oldPosition2); // oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2); // oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2); // object.computeWorldMatrix(true); // break; // case EColliderType.Particle: // shape = new this.CANNON.Particle(); // break; default: break; } let {offset, quaternion, isTrigger} = params.options; const rigidBody: any = bodyComp.rigidBody; offset = offset || [0, 0, 0]; quaternion = quaternion || [0, 0, 0, 1]; isTrigger = isTrigger || false; rigidBody.addShape( shape, new this.CANNON.Vec3(...offset), new this.CANNON.Quaternion(...quaternion) ); shape.collisionResponse = !isTrigger; shape.component = colliderComp; return shape; } /** * 移除碰撞体。 */ public removeCollider(rigidBodyComp: RigidBodyComponent, colliderComp: ColliderComponent) { const rigidBody: any = rigidBodyComp.rigidBody; const collider: any = colliderComp.collider; const index = rigidBody.shapes.indexOf(collider); rigidBody.shapes.splice(index, 1); rigidBody.shapeOffsets.splice(index, 1); rigidBody.shapeOrientations.splice(index, 1); } // private _createHeightmap(object: IPhysicsEnabledObject, pointDepth?: number) { // const pos = <FloatArray>(object.getVerticesData(VertexBuffer.PositionKind)); // let transform = object.computeWorldMatrix(true); // // convert rawVerts to object space // const temp = new Array<number>(); // const index: number; // for (index = 0; index < pos.length; index += 3) { // Vector3.TransformCoordinates(Vector3.FromArray(pos, index), transform).toArray(temp, index); // } // pos = temp; // const matrix = new Array<Array<any>>(); // //For now pointDepth will not be used and will be automatically calculated. // //Future reference - try and find the best place to add a reference to the pointDepth constiable. // const arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1); // let boundingInfo = object.getBoundingInfo(); // const dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y); // const minY = boundingInfo.boundingBox.extendSizeWorld.z; // const elementSize = dim * 2 / arraySize; // for (const i = 0; i < pos.length; i = i + 3) { // const x = Math.round((pos[i + 0]) / elementSize + arraySize / 2); // const z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1); // const y = -pos[i + 2] + minY; // if (!matrix[x]) { // matrix[x] = []; // } // if (!matrix[x][z]) { // matrix[x][z] = y; // } // matrix[x][z] = Math.max(y, matrix[x][z]); // } // for (const x = 0; x <= arraySize; ++x) { // if (!matrix[x]) { // const loc = 1; // while (!matrix[(x + loc) % arraySize]) { // loc++; // } // matrix[x] = matrix[(x + loc) % arraySize].slice(); // //console.log("missing x", x); // } // for (const z = 0; z <= arraySize; ++z) { // if (!matrix[x][z]) { // const loc = 1; // const newValue; // while (newValue === undefined) { // newValue = matrix[x][(z + loc++) % arraySize]; // } // matrix[x][z] = newValue; // } // } // } // const shape = new this.CANNON.Heightfield(matrix, { // elementSize: elementSize // }); // //For future reference, needed for body transformation // shape.minY = minY; // return shape; // } /** * 设置某个刚体的父级Actor的`transform`。 */ public setRootTransform(component: RigidBodyComponent) { const {transform} = component.getOwner<SceneActor>(); const {position, quaternion} = component.rigidBody; transform.setPosition(position.x, position.y, position.z); transform.setQuaternion(quaternion.x, quaternion.y, quaternion.z, quaternion.w); } /** * 设置某个刚体的`transform`。 */ public setRigidBodyTransform( component: RigidBodyComponent, newPosition?: Vector3, newRotation?: Quaternion, // only for sphere, box, cylinder newScale?: Vector3 ) { this.setBodyTransform(component.rigidBody, newPosition, newRotation, newScale); } protected setBodyTransform( body: any, newPosition?: Vector3, newRotation?: Quaternion, newScale?: Vector3 ) { if (newPosition) { body.position.copy(newPosition); } if (newRotation) { body.quaternion.copy(newRotation); } if (newScale && body.shapes) { body.shapes.forEach((collider, index) => { this.setColliderScale(collider.component, body.component, newScale, index); }); } } public setColliderTransform( component: ColliderComponent, // note: position and rotation not working in current time newPosition?: Vector3, newRotation?: Quaternion, // only for sphere, box, capsule newScale?: Vector3 ) { if (!component) { return; } const {collider} = component; const {rigidBody} = component.getOwner<SceneActor>(); const index = rigidBody.rigidBody.shapes.indexOf(collider); if (newScale) { this.setColliderScale(component, rigidBody, newScale, index); } // if want to change qrientation, change the shapeOrientations and rigidBody.updateBoundingRadius rigidBody.needUpdateCollider = true; } protected setColliderScale( component: ColliderComponent, rigidBodyComp: RigidBodyComponent, newScale: Vector3, index: number ) { const {collider} = component; const options = component.initState as any; // todo: better scale for multiple collider switch (component.type) { case EColliderType.Box: collider.halfExtents.set( options.size[0] / 2 * newScale.x, options.size[1] / 2 * newScale.y, options.size[2] / 2 * newScale.z ); break; case EColliderType.Sphere: collider.radius = options.radius * newScale.x; break; default: break; } if (component.type !== EColliderType.Sphere) { collider.updateConvexPolyhedronRepresentation(); } const {offset} = options; if (offset[0] !== 0 || offset[1] !== 0 || offset[2] !== 0) { const off = rigidBodyComp.rigidBody.shapeOffsets[index]; off.x = offset[0] * newScale.x; off.y = offset[1] * newScale.y; off.z = -offset[2] * newScale.z; } } /** * 强制更新包围盒。 */ public updateBounding(component: RigidBodyComponent) { component.rigidBody.updateMassProperties(); component.rigidBody.updateBoundingRadius(); } /** * 设置线速度。 */ public setLinearVelocity(component: RigidBodyComponent, velocity: Vector3) { component.rigidBody.velocity.copy(velocity); } /** * 设置角速度。 */ public setAngularVelocity(component: RigidBodyComponent, velocity: Vector3) { component.rigidBody.angularVelocity.copy(velocity); } /** * 获取线速度。 */ public getLinearVelocity(component: RigidBodyComponent): Vector3 { const v = component.rigidBody.velocity; if (!v) { return null; } return new Vector3(v.x, v.y, v.z); } /** * 获取角速度。 */ public getAngularVelocity(component: RigidBodyComponent): Vector3 { const v = component.rigidBody.angularVelocity; if (!v) { return null; } return new Vector3(v.x, v.y, v.z); } /** * 设置重力。 */ public setBodyMass(component: RigidBodyComponent, mass: number) { component.rigidBody.mass = mass; if (!component.physicStatic && mass > 0) { this.setBodyType(component, ERigidBodyType.Dynamic); } component.rigidBody.updateMassProperties(); } /** * 获取重力。 */ public getBodyMass(component: RigidBodyComponent): number { return component.rigidBody.mass; } /** * 设置filterGroup,一个32bits的整数,用于给刚体分组。 */ public setFilterGroup(component: RigidBodyComponent, group: number) { component.rigidBody.collisionFilterGroup = group; } /** * 获取filterGroup。 */ public getFilterGroup(component: RigidBodyComponent) { return component.rigidBody.collisionFilterGroup; } /** * 设置filterMask,一个32bits的整数,用于给分组后的刚体设置碰撞对象范围。 */ public setFilterMask(component: RigidBodyComponent, mask: number) { component.rigidBody.collisionFilterMask = mask; } /** * 获取filterMask。 */ public getFilterMask(component: RigidBodyComponent) { return component.rigidBody.collisionFilterMask; } /** * 设置刚体摩擦力。 */ public getBodyFriction(component: RigidBodyComponent): number { return component.rigidBody.material.friction; } /** * 获取刚体摩擦力。 */ public setBodyFriction(component: RigidBodyComponent, friction: number) { component.rigidBody.material.friction = friction; } /** * 获取刚体弹性系数。 */ public getBodyRestitution(component: RigidBodyComponent): number { return component.rigidBody.material.restitution; } /** * 设置刚体弹性系数。 */ public setBodyRestitution(component: RigidBodyComponent, restitution: number) { component.rigidBody.material.restitution = restitution; } /** * 使刚体进入睡眠状态,不会触发任何碰撞事件,但可以正确响应拾取操作。 */ public sleepBody(component: RigidBodyComponent) { component.rigidBody.sleep(); } /** * 唤醒刚体。 */ public wakeUpBody(component: RigidBodyComponent) { component.rigidBody.wakeUp(); } /** * 设置刚体类型。 */ public setBodyType(component: RigidBodyComponent, type: ERigidBodyType) { component.rigidBody.type = type; } /** * 设置碰撞体为触发器。 */ public setColliderIsTrigger(component: ColliderComponent, isTrigger: boolean) { component.collider.collisionResponse = !isTrigger; } /** * 获取碰撞体是否为触发器。 */ public getColliderIsTrigger(component: ColliderComponent): boolean { return !component.collider.collisionResponse; } // public updateDistanceJoint(joint: PhysicsJoint, maxDistance: number, minDistance?: number) { // joint.physicsJoint.distance = maxDistance; // } // // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) { // // if (!motorIndex) { // // joint.physicsJoint.enableMotor(); // // } // // } // // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) { // // if (!motorIndex) { // // joint.physicsJoint.disableMotor(); // // } // // } // public setMotor(joint: IMotorEnabledJoint, speed?: number, maxForce?: number, motorIndex?: number) { // if (!motorIndex) { // joint.physicsJoint.enableMotor(); // joint.physicsJoint.setMotorSpeed(speed); // if (maxForce) { // this.setLimit(joint, maxForce); // } // } // } // public setLimit(joint: IMotorEnabledJoint, upperLimit: number, lowerLimit?: number) { // joint.physicsJoint.motorEquation.maxForce = upperLimit; // joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit; // } // public syncMeshWithImpostor(mesh: AbstractMesh, component: RigidBodyComponent) { // const body = component.rigidBody; // mesh.position.x = body.position.x; // mesh.position.y = body.position.y; // mesh.position.z = body.position.z; // if (mesh.rotationQuaternion) { // mesh.rotationQuaternion.x = body.quaternion.x; // mesh.rotationQuaternion.y = body.quaternion.y; // mesh.rotationQuaternion.z = body.quaternion.z; // mesh.rotationQuaternion.w = body.quaternion.w; // } // } }
the_stack
import { Layouts } from '../../src' import { mathEqual } from '../util'; import MDS from '../../src/layout/radial/mds'; // import G6 from '@antv/g6'; // const div = document.createElement('div'); // div.id = 'global-spec'; // document.body.appendChild(div); // const graph = new G6.Graph({ // container: div, // width: 500, // height: 500, // }); // data.nodes.forEach(node => { // node.label = node.id // }) // graph.data(data); // graph.render() const data: any = { nodes: [ { id: '0', label: '0' }, { id: '1', label: '1' }, { id: '2', label: '2' }, { id: '3', label: '3' }, { id: '4', label: '4' }, { id: '5', label: '5' }, ], edges: [ { source: '0', target: '1', }, { source: '0', target: '2', }, { source: '3', target: '4', }, ], }; describe('#RadialLayout', () => { it('return correct default config', () => { const radial = new Layouts['radial'](); expect(radial.getDefaultCfg()).toEqual({ maxIteration: 1000, focusNode: null, unitRadius: null, linkDistance: 50, preventOverlap: false, nodeSize: undefined, nodeSpacing: undefined, strictRadial: true, maxPreventOverlapIteration: 200, sortBy: undefined, sortStrength: 10, }); radial.layout(data); expect((data.nodes[0] as any).x).not.toBe(undefined); expect((data.nodes[0] as any).y).not.toBe(undefined); }); it('new graph with radial layout, without configurations', () => { const radial = new Layouts['radial']({ width: 500, height: 600 }); radial.layout(data) const focusNode = data.nodes[0]; expect(mathEqual(focusNode.x, 250)).toEqual(true); expect(mathEqual(focusNode.y, 300)).toEqual(true); }); it('new graph with radial layout, with configurations', () => { const unitRadius = 100; const fnIndex = 1; const focusNode = data.nodes[fnIndex]; const center: any = [250, 250]; const radial = new Layouts['radial']({ width: 500, height: 600, center, maxIteration: 100, focusNode, unitRadius, linkDistance: 100, }); radial.layout(data) const oneStepNode = data.nodes[0]; const DistFnToOneStepNode = (oneStepNode.x - focusNode.x) * (oneStepNode.x - focusNode.x) + (oneStepNode.y - focusNode.y) * (oneStepNode.y - focusNode.y); const twoStepNode = data.nodes[2]; const DistFnToTwoStepNode = (twoStepNode.x - focusNode.x) * (twoStepNode.x - focusNode.x) + (twoStepNode.y - focusNode.y) * (twoStepNode.y - focusNode.y); const descreteNode = data.nodes[5]; const DistFnToDescreteNode = (descreteNode.x - focusNode.x) * (descreteNode.x - focusNode.x) + (descreteNode.y - focusNode.y) * (descreteNode.y - focusNode.y); const descreteComNode1 = data.nodes[3]; const DistFnToDescreteComNode1 = (descreteComNode1.x - focusNode.x) * (descreteComNode1.x - focusNode.x) + (descreteComNode1.y - focusNode.y) * (descreteComNode1.y - focusNode.y); const descreteComNode2 = data.nodes[4]; const DistFnToDescreteComNode2 = (descreteComNode2.x - focusNode.x) * (descreteComNode2.x - focusNode.x) + (descreteComNode2.y - focusNode.y) * (descreteComNode2.y - focusNode.y); expect(mathEqual(DistFnToOneStepNode, unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToTwoStepNode, 4 * unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteNode, 9 * unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteComNode1, 9 * unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteComNode2, 16 * unitRadius * unitRadius)).toEqual(true); }); it('radial layout with no node', () => { const radial = new Layouts['radial'](); radial.layout({ nodes: [], }) }); it('radial layout with one node', () => { const radial = new Layouts['radial']({ width: 500, height: 600 }); const data1: any = { nodes: [ { id: 'node', }, ], }; radial.layout(data1) const nodeModel = data1.nodes[0]; expect(nodeModel.x).toEqual(250); expect(nodeModel.y).toEqual(300); }); it('focus on descrete node, prevent overlapping', () => { const unitRadius = 100; const focusNode = data.nodes[5]; //data.nodes[5];//'5'; const nodeSize = 40; const radial = new Layouts['radial']({ focusNode: '5', unitRadius, preventOverlap: true, maxPreventOverlapIteration: 800, }); radial.layout(data); const descreteCom1Node1 = data.nodes[0]; const DistFnToDescreteCom1Node1 = (descreteCom1Node1.x - focusNode.x) * (descreteCom1Node1.x - focusNode.x) + (descreteCom1Node1.y - focusNode.y) * (descreteCom1Node1.y - focusNode.y); const descreteCom1Node2 = data.nodes[1]; const DistFnToDescreteCom1Node2 = (descreteCom1Node2.x - focusNode.x) * (descreteCom1Node2.x - focusNode.x) + (descreteCom1Node2.y - focusNode.y) * (descreteCom1Node2.y - focusNode.y); const descreteCom2Node1 = data.nodes[3]; const DistFnToDescreteCom2Node1 = (descreteCom2Node1.x - focusNode.x) * (descreteCom2Node1.x - focusNode.x) + (descreteCom2Node1.y - focusNode.y) * (descreteCom2Node1.y - focusNode.y); const descreteCom2Node2 = data.nodes[4]; const DistFnToDescreteCom2Node2 = (descreteCom2Node2.x - focusNode.x) * (descreteCom2Node2.x - focusNode.x) + (descreteCom2Node2.y - focusNode.y) * (descreteCom2Node2.y - focusNode.y); expect(mathEqual(DistFnToDescreteCom1Node1, unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteCom1Node2, 4 * unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteCom2Node1, unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteCom2Node2, 4 * unitRadius * unitRadius)).toEqual(true); // non overlap const overlapDist1 = (descreteCom1Node1.x - descreteCom2Node1.x) * (descreteCom1Node1.x - descreteCom2Node1.x) + (descreteCom1Node1.y - descreteCom2Node1.y) * (descreteCom1Node1.y - descreteCom2Node1.y); expect(overlapDist1 > nodeSize + nodeSize).toEqual(true); }); it('focus on descrete node, prevent overlapping with number nodeSpacing', () => { const unitRadius = 100; const focusNode = data.nodes[5]; const nodeSize = 40; const radial = new Layouts['radial']({ focusNode, unitRadius, preventOverlap: true, nodeSpacing: 10, nodeSize, maxPreventOverlapIteration: 800, }); radial.layout(data); const descreteCom1Node1 = data.nodes[0]; const DistFnToDescreteCom1Node1 = (descreteCom1Node1.x - focusNode.x) * (descreteCom1Node1.x - focusNode.x) + (descreteCom1Node1.y - focusNode.y) * (descreteCom1Node1.y - focusNode.y); const descreteCom1Node2 = data.nodes[1]; const DistFnToDescreteCom1Node2 = (descreteCom1Node2.x - focusNode.x) * (descreteCom1Node2.x - focusNode.x) + (descreteCom1Node2.y - focusNode.y) * (descreteCom1Node2.y - focusNode.y); const descreteCom2Node1 = data.nodes[3]; const DistFnToDescreteCom2Node1 = (descreteCom2Node1.x - focusNode.x) * (descreteCom2Node1.x - focusNode.x) + (descreteCom2Node1.y - focusNode.y) * (descreteCom2Node1.y - focusNode.y); const descreteCom2Node2 = data.nodes[4]; const DistFnToDescreteCom2Node2 = (descreteCom2Node2.x - focusNode.x) * (descreteCom2Node2.x - focusNode.x) + (descreteCom2Node2.y - focusNode.y) * (descreteCom2Node2.y - focusNode.y); expect(mathEqual(DistFnToDescreteCom1Node1, unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteCom1Node2, 4 * unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteCom2Node1, unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteCom2Node2, 4 * unitRadius * unitRadius)).toEqual(true); // non overlap const overlapDist1 = (descreteCom1Node1.x - descreteCom2Node1.x) * (descreteCom1Node1.x - descreteCom2Node1.x) + (descreteCom1Node1.y - descreteCom2Node1.y) * (descreteCom1Node1.y - descreteCom2Node1.y); expect(overlapDist1 > nodeSize * nodeSize).toEqual(true); }); it('focus on descrete node, prevent overlapping with function nodeSpacing', () => { const unitRadius = 100; const focusNode = data.nodes[5]; const nodeSize = 40; const radial = new Layouts['radial']({ focusNode, unitRadius, preventOverlap: true, nodeSpacing: (d) => { return 5; }, nodeSize: [nodeSize, nodeSize], }); radial.layout(data); const descreteCom1Node1 = data.nodes[0]; const DistFnToDescreteCom1Node1 = (descreteCom1Node1.x - focusNode.x) * (descreteCom1Node1.x - focusNode.x) + (descreteCom1Node1.y - focusNode.y) * (descreteCom1Node1.y - focusNode.y); const descreteCom1Node2 = data.nodes[1]; const DistFnToDescreteCom1Node2 = (descreteCom1Node2.x - focusNode.x) * (descreteCom1Node2.x - focusNode.x) + (descreteCom1Node2.y - focusNode.y) * (descreteCom1Node2.y - focusNode.y); const descreteCom2Node1 = data.nodes[3]; const DistFnToDescreteCom2Node1 = (descreteCom2Node1.x - focusNode.x) * (descreteCom2Node1.x - focusNode.x) + (descreteCom2Node1.y - focusNode.y) * (descreteCom2Node1.y - focusNode.y); const descreteCom2Node2 = data.nodes[4]; const DistFnToDescreteCom2Node2 = (descreteCom2Node2.x - focusNode.x) * (descreteCom2Node2.x - focusNode.x) + (descreteCom2Node2.y - focusNode.y) * (descreteCom2Node2.y - focusNode.y); expect(mathEqual(DistFnToDescreteCom1Node1, unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteCom1Node2, 4 * unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteCom2Node1, unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteCom2Node2, 4 * unitRadius * unitRadius)).toEqual(true); // non overlap const overlapDist1 = (descreteCom1Node1.x - descreteCom2Node1.x) * (descreteCom1Node1.x - descreteCom2Node1.x) + (descreteCom1Node1.y - descreteCom2Node1.y) * (descreteCom1Node1.y - descreteCom2Node1.y); expect(overlapDist1 > nodeSize * nodeSize).toEqual(true); }); it('preventOverlap, node size is array', () => { const unitRadius = 100; const focusNode = data.nodes[5]; const nodeSize = [40, 20]; data.nodes.forEach((node) => { node.size = nodeSize; }); const radial = new Layouts['radial']({ focusNode, unitRadius, preventOverlap: true, }); radial.layout(data); const descreteCom1Node1 = data.nodes[0]; const DistFnToDescreteCom1Node1 = (descreteCom1Node1.x - focusNode.x) * (descreteCom1Node1.x - focusNode.x) + (descreteCom1Node1.y - focusNode.y) * (descreteCom1Node1.y - focusNode.y); const descreteCom1Node2 = data.nodes[1]; const DistFnToDescreteCom1Node2 = (descreteCom1Node2.x - focusNode.x) * (descreteCom1Node2.x - focusNode.x) + (descreteCom1Node2.y - focusNode.y) * (descreteCom1Node2.y - focusNode.y); const descreteCom2Node1 = data.nodes[3]; const DistFnToDescreteCom2Node1 = (descreteCom2Node1.x - focusNode.x) * (descreteCom2Node1.x - focusNode.x) + (descreteCom2Node1.y - focusNode.y) * (descreteCom2Node1.y - focusNode.y); const descreteCom2Node2 = data.nodes[4]; const DistFnToDescreteCom2Node2 = (descreteCom2Node2.x - focusNode.x) * (descreteCom2Node2.x - focusNode.x) + (descreteCom2Node2.y - focusNode.y) * (descreteCom2Node2.y - focusNode.y); expect(mathEqual(DistFnToDescreteCom1Node1, unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteCom1Node2, 4 * unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteCom2Node1, unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteCom2Node2, 4 * unitRadius * unitRadius)).toEqual(true); // non overlap const overlapDist1 = (descreteCom1Node1.x - descreteCom2Node1.x) * (descreteCom1Node1.x - descreteCom2Node1.x) + (descreteCom1Node1.y - descreteCom2Node1.y) * (descreteCom1Node1.y - descreteCom2Node1.y); expect(overlapDist1 > nodeSize[0] * nodeSize[0]).toEqual(true); expect(overlapDist1 > nodeSize[1] * nodeSize[1]).toEqual(true); }); it('preventOverlap, no nodeSize, no data size', () => { const unitRadius = 100; const focusNode = data.nodes[5]; data.nodes.forEach((node) => { node.size = undefined; }); const radial = new Layouts['radial']({ focusNode, unitRadius, preventOverlap: true, }); radial.layout(data); const descreteCom1Node1 = data.nodes[0]; const DistFnToDescreteCom1Node1 = (descreteCom1Node1.x - focusNode.x) * (descreteCom1Node1.x - focusNode.x) + (descreteCom1Node1.y - focusNode.y) * (descreteCom1Node1.y - focusNode.y); const descreteCom1Node2 = data.nodes[1]; const DistFnToDescreteCom1Node2 = (descreteCom1Node2.x - focusNode.x) * (descreteCom1Node2.x - focusNode.x) + (descreteCom1Node2.y - focusNode.y) * (descreteCom1Node2.y - focusNode.y); const descreteCom2Node1 = data.nodes[3]; const DistFnToDescreteCom2Node1 = (descreteCom2Node1.x - focusNode.x) * (descreteCom2Node1.x - focusNode.x) + (descreteCom2Node1.y - focusNode.y) * (descreteCom2Node1.y - focusNode.y); const descreteCom2Node2 = data.nodes[4]; const DistFnToDescreteCom2Node2 = (descreteCom2Node2.x - focusNode.x) * (descreteCom2Node2.x - focusNode.x) + (descreteCom2Node2.y - focusNode.y) * (descreteCom2Node2.y - focusNode.y); expect(mathEqual(DistFnToDescreteCom1Node1, unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteCom1Node2, 4 * unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteCom2Node1, unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteCom2Node2, 4 * unitRadius * unitRadius)).toEqual(true); // non overlap const overlapDist1 = (descreteCom1Node1.x - descreteCom2Node1.x) * (descreteCom1Node1.x - descreteCom2Node1.x) + (descreteCom1Node1.y - descreteCom2Node1.y) * (descreteCom1Node1.y - descreteCom2Node1.y); expect(overlapDist1 > 100).toEqual(true); expect(overlapDist1 > 100).toEqual(true); }); it('sort by data', () => { const unitRadius = 100; const focusNode = data.nodes[5]; const nodeSize = 40; const radial = new Layouts['radial']({ focusNode, unitRadius, sortBy: 'data', preventOverlap: true, nodeSize, maxPreventOverlapIteration: 1200, }); radial.layout(data); const node1 = data.nodes[1]; const node2 = data.nodes[2]; const node4 = data.nodes[4]; const overlapDist1 = (node1.x - node2.x) * (node1.x - node2.x) + (node1.y - node2.y) * (node1.y - node2.y); const overlapDist2 = (node1.x - node4.x) * (node1.x - node4.x) + (node1.y - node4.y) * (node1.y - node4.y); expect(overlapDist1 < overlapDist2).toEqual(true); }); it('sort by sortProperty', () => { const unitRadius = 100; const focusNode = data.nodes[5]; const nodeSize = 40; const radial = new Layouts['radial']({ focusNode, unitRadius, sortBy: 'sortProperty', preventOverlap: true, maxPreventOverlapIteration: 1200, nodeSize }); data.nodes.forEach((node, i) => { node['sortProperty'] = i % 2; }); radial.layout(data); const node1 = data.nodes[1]; const node2 = data.nodes[2]; const node4 = data.nodes[4]; const overlapDist1 = (node1.x - node2.x) * (node1.x - node2.x) + (node1.y - node2.y) * (node1.y - node2.y); const overlapDist2 = (node2.x - node4.x) * (node2.x - node4.x) + (node2.y - node4.y) * (node2.y - node4.y); expect(overlapDist1 > overlapDist2).toEqual(true); }); }); describe('radial layout', () => { it('new graph with radial layout, with focusnode id', () => { const unitRadius = 100; const focusNodeId = '3'; const radial = new Layouts['radial']({ focusNode: focusNodeId, unitRadius, nodeSize: 30 }); radial.layout(data); let focusNode; data.nodes.forEach(node => { if (node.id === focusNodeId) focusNode = node; }) const descreteNode = data.nodes[5]; const DistFnToDescreteNode = (descreteNode.x - focusNode.x) * (descreteNode.x - focusNode.x) + (descreteNode.y - focusNode.y) * (descreteNode.y - focusNode.y); const descreteComNode1 = data.nodes[0]; const DistFnToDescreteComNode1 = (descreteComNode1.x - focusNode.x) * (descreteComNode1.x - focusNode.x) + (descreteComNode1.y - focusNode.y) * (descreteComNode1.y - focusNode.y); const descreteComNode2 = data.nodes[1]; const DistFnToDescreteComNode2 = (descreteComNode2.x - focusNode.x) * (descreteComNode2.x - focusNode.x) + (descreteComNode2.y - focusNode.y) * (descreteComNode2.y - focusNode.y); const descreteComNode3 = data.nodes[2]; const DistFnToDescreteComNode3 = (descreteComNode3.x - focusNode.x) * (descreteComNode3.x - focusNode.x) + (descreteComNode3.y - focusNode.y) * (descreteComNode3.y - focusNode.y); expect(mathEqual(DistFnToDescreteNode, 4 * unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteComNode1, 4 * unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteComNode2, 9 * unitRadius * unitRadius)).toEqual(true); expect(mathEqual(DistFnToDescreteComNode3, 9 * unitRadius * unitRadius)).toEqual(true); }); it('focus node does not exist', () => { const unitRadius = 100; const focusNodeId = 'test'; // does not exist in data const radial = new Layouts['radial']({ focusNode: focusNodeId, unitRadius, nodeSize: 30 }); radial.layout(data); expect((radial.focusNode as any).id).toEqual('0'); }); it('focus node undefined', () => { const unitRadius = 100; const radial = new Layouts['radial']({ focusNode: undefined, unitRadius, nodeSize: 30 }); radial.layout(data); expect((radial.focusNode as any).id).toEqual('0'); }); it('instantiate layout', () => { const unitRadius = 50; const radial = new Layouts['radial']({ unitRadius, preventOverlap: true, maxPreventOverlapIteration: null, sortBy: 'sortProperty', center: [250, 250], }); data.nodes.forEach((node, i) => { node['sortProperty'] = '' + (i % 3); }); radial.layout(data); const focusNode = data.nodes[0]; const descreteNode = data.nodes[5]; const DistFnToDescreteNode = (descreteNode.x - focusNode.x) * (descreteNode.x - focusNode.x) + (descreteNode.y - focusNode.y) * (descreteNode.y - focusNode.y); const descreteComNode1 = data.nodes[1]; const DistFnToDescreteComNode1 = (descreteComNode1.x - focusNode.x) * (descreteComNode1.x - focusNode.x) + (descreteComNode1.y - focusNode.y) * (descreteComNode1.y - focusNode.y); const descreteComNode2 = data.nodes[4]; const DistFnToDescreteComNode2 = (descreteComNode2.x - focusNode.x) * (descreteComNode2.x - focusNode.x) + (descreteComNode2.y - focusNode.y) * (descreteComNode2.y - focusNode.y); const descreteComNode3 = data.nodes[2]; const DistFnToDescreteComNode3 = (descreteComNode3.x - focusNode.x) * (descreteComNode3.x - focusNode.x) + (descreteComNode3.y - focusNode.y) * (descreteComNode3.y - focusNode.y); expect(mathEqual(Math.sqrt(DistFnToDescreteNode), 2 * unitRadius)).toEqual(true); expect(mathEqual(Math.sqrt(DistFnToDescreteComNode1), unitRadius)).toEqual(true); expect(mathEqual(Math.sqrt(DistFnToDescreteComNode2), 3 * unitRadius)).toEqual(true); expect(mathEqual(Math.sqrt(DistFnToDescreteComNode3), unitRadius)).toEqual(true); }); it('instantiate layout with center on the left', () => { const radial = new Layouts['radial']({ center: [0, 250], }); radial.layout(data); expect(data.nodes[0].x).not.toEqual(NaN); expect(data.nodes[0].y).not.toEqual(NaN); }); it('instantiate layout with center on the top', () => { data.nodes.forEach((node) => { delete node.size; }); const radial = new Layouts['radial']({ center: [250, 0], preventOverlap: true, }); radial.layout(data); expect(data.nodes[0].x).not.toEqual(NaN); expect(data.nodes[0].y).not.toEqual(NaN); }); it('mds try catch', () => { const mds = new MDS({ distances: [[0, 0]], linkDistance: 10 }); const positions = mds.layout(); expect(positions[0][0]).not.toEqual(NaN); expect(positions[0][1]).not.toEqual(NaN); }); it('radial with data sort', () => { const data2: any = { nodes: [ { id: '0', label: '0', sortAttr: 0, sortAttr2: 'a', }, { id: '1', label: '1', sortAttr: 0, sortAttr2: 'a', }, { id: '2', label: '2', sortAttr: 0, sortAttr2: 'a', }, { id: '3', label: '3', sortAttr: 0, sortAttr2: 'a', }, { id: '4', label: '4', sortAttr: 2, sortAttr2: 'c', }, { id: '5', label: '5', sortAttr: 0, sortAttr2: 'a', }, { id: '6', label: '6', sortAttr: 1, sortAttr2: 'b', }, { id: '7', label: '7', sortAttr: 1, sortAttr2: 'b', }, { id: '8', label: '8', sortAttr: 2, sortAttr2: 'c', }, { id: '9', label: '9', sortAttr: 3, sortAttr2: 'd', }, { id: '10', label: '10', sortAttr: 3, sortAttr2: 'd', }, { id: '11', label: '11', sortAttr: 1, sortAttr2: 'b', }, { id: '12', label: '12', sortAttr: 2, sortAttr2: 'c', }, { id: '13', label: '13', sortAttr: 1, sortAttr2: 'b', }, { id: '14', label: '14', sortAttr: 3, sortAttr2: 'd', }, { id: '15', label: '15', sortAttr: 3, sortAttr2: 'd', }, { id: '16', label: '16', sortAttr: 1, sortAttr2: 'b', }, { id: '17', label: '17', sortAttr: 2, sortAttr2: 'c', }, { id: '18', label: '18', sortAttr: 2, sortAttr2: 'c', }, { id: '19', label: '19', sortAttr: 1, sortAttr2: 'b', }, { id: '20', label: '20', sortAttr: 1, sortAttr2: 'b', }, { id: '21', label: '21', sortAttr: 3, sortAttr2: 'd', }, { id: '22', label: '22', sortAttr: 3, sortAttr2: 'd', }, { id: '23', label: '23', sortAttr: 3, sortAttr2: 'd', }, { id: '24', label: '24', sortAttr: 0, sortAttr2: 'a', }, { id: '25', label: '25', sortAttr: 0, sortAttr2: 'a', }, { id: '26', label: '26', sortAttr: 1, sortAttr2: 'b', }, { id: '27', label: '27', sortAttr: 1, sortAttr2: 'b', }, { id: '28', label: '28', sortAttr: 3, sortAttr2: 'd', }, { id: '29', label: '29', sortAttr: 2, sortAttr2: 'c', }, { id: '30', label: '30', sortAttr: 2, sortAttr2: 'c', }, { id: '31', label: '31', sortAttr: 1, sortAttr2: 'b', }, { id: '32', label: '32', sortAttr: 1, sortAttr2: 'b', }, { id: '33', label: '33', sortAttr: 0, sortAttr2: 'a', }, ], edges: [ { source: '0', target: '1', }, { source: '0', target: '2', }, { source: '0', target: '3', }, { source: '0', target: '4', }, { source: '0', target: '5', }, { source: '0', target: '7', }, { source: '0', target: '8', }, { source: '0', target: '9', }, { source: '0', target: '10', }, { source: '0', target: '11', }, { source: '0', target: '13', }, { source: '0', target: '14', }, { source: '0', target: '15', }, { source: '0', target: '16', }, { source: '2', target: '3', }, { source: '4', target: '5', }, { source: '4', target: '6', }, { source: '5', target: '6', }, { source: '7', target: '13', }, { source: '8', target: '14', }, { source: '9', target: '10', }, { source: '10', target: '22', }, { source: '10', target: '14', }, { source: '10', target: '12', }, { source: '10', target: '24', }, { source: '10', target: '21', }, { source: '10', target: '20', }, { source: '11', target: '24', }, { source: '11', target: '22', }, { source: '11', target: '14', }, { source: '12', target: '13', }, { source: '16', target: '17', }, { source: '16', target: '18', }, { source: '16', target: '21', }, { source: '16', target: '22', }, { source: '17', target: '18', }, { source: '17', target: '20', }, { source: '18', target: '19', }, { source: '19', target: '20', }, { source: '19', target: '33', }, { source: '19', target: '22', }, { source: '19', target: '23', }, { source: '20', target: '21', }, { source: '21', target: '22', }, { source: '22', target: '24', }, { source: '22', target: '25', }, { source: '22', target: '26', }, { source: '22', target: '23', }, { source: '22', target: '28', }, { source: '22', target: '30', }, { source: '22', target: '31', }, { source: '22', target: '32', }, { source: '22', target: '33', }, { source: '23', target: '28', }, { source: '23', target: '27', }, { source: '23', target: '29', }, { source: '23', target: '30', }, { source: '23', target: '31', }, { source: '23', target: '33', }, { source: '32', target: '33', }, ], }; const colors = ['#e5e5e5', 'green', '#5AD8A6', 'rgb(95, 149, 255)']; const colorsObj = { a: '#e5e5e5', b: 'green', c: '#5AD8A6', d: 'rgb(95, 149, 255)' }; data2.nodes.forEach((node) => { node.size = 15; node.label = ' '; node.style = { lineWidth: 3, fill: '#fff', stroke: colors[node.sortAttr2] || colorsObj[node.sortAttr2], }; }); const radial = new Layouts['radial']({ center: [250, 250], preventOverlap: true, sortBy: 'sortAttr2', sortStrength: 100, }); radial.layout(data); }); })
the_stack
import { DirectiveResolver } from '../linker/directive_resolver'; import { assign, isFunction, noop, resolveDirectiveNameFromSelector, stringify, isJsObject } from '../../facade/lang'; import { StringMapWrapper } from '../../facade/collections'; import { Type } from '../../facade/type'; import { resolveImplementedLifeCycleHooks, ImplementedLifeCycleHooks } from '../linker/directive_lifecycles_reflector'; import { ChildrenChangeHook } from '../linker/directive_lifecycle_interfaces'; import { DirectiveMetadata, ComponentMetadata, LegacyDirectiveDefinition } from './metadata_directives'; import { directiveControllerFactory } from './controller/controller_factory'; import { _getParentCheckNotifiers, _setupQuery } from './query/children_resolver'; import { _parseHost } from './host/host_parser'; import { _setHostStaticAttributes, _setHostBindings, _setHostListeners } from './host/host_resolver'; import { _setupDestroyHandler } from './directives_utils'; import { NgmDirective, DirectiveCtrl } from './constants'; /** * @internal */ export class DirectiveProvider { constructor( private directiveResolver: DirectiveResolver ) {} private static _ddoShell = { require: [], controller: noop, link: { pre: noop, post: noop } }; private static _controllerAs = `$ctrl`; private static _transclude = false; /** * creates directiveName and DirectiveFactory for angularJS container * * it produces directive for classes decorated with @Directive with following DDO: * ``` * { * require: ['directiveName'], * controller: ClassDirective, * link: postLinkFn * } * ``` * * it produces component for classes decorated with @Component with following DDO: * ``` * { * require: ['directiveName'], * controller: ClassDirective, * controllerAs: '$ctrl', * template: 'component template string', * scope:{}, * bindToController:{}, * transclude: false, * link: postLinkFn * } * ``` * @param type * @returns {string|function(): ng.IDirective[]} */ createFromType( type: Type ): [string, ng.IDirectiveFactory] { const metadata: DirectiveMetadata | ComponentMetadata = this.directiveResolver.resolve( type ); const directiveName = resolveDirectiveNameFromSelector( metadata.selector ); const requireMap = this.directiveResolver.getRequiredDirectivesMap( type ); const lfHooks = resolveImplementedLifeCycleHooks(type); const _ddo = { restrict: 'A', controller: _controller, link: { pre: function () { _ddo._ngOnInitBound() }, post: this._createLink( type, metadata, lfHooks ) }, // @TODO this will be removed after @Query handling is moved to directiveControllerFactory require: this._createRequires( requireMap, directiveName ), _ngOnInitBound: noop } as NgmDirective; // Component controllers must be created from a factory. Checkout out // util/directive-controller.js for more information about what's going on here _controller.$inject = ['$scope', '$element', '$attrs', '$transclude', '$injector']; function _controller($scope: any, $element: any, $attrs: any, $transclude: any, $injector: any): any{ const locals = { $scope, $element, $attrs, $transclude }; return directiveControllerFactory( this, type, $injector, locals, requireMap, _ddo, metadata ); } // specific DDO augmentation for @Component if ( metadata instanceof ComponentMetadata ) { const assetsPath = this.directiveResolver.parseAssetUrl( metadata ); const componentSpecificDDO = { restrict: 'E', scope: {}, bindToController: {}, controllerAs: DirectiveProvider._controllerAs, transclude: DirectiveProvider._transclude } as ng.IDirective; if ( metadata.template && metadata.templateUrl ) { throw new Error( 'cannot have both template and templateUrl' ); } if ( metadata.template ) { componentSpecificDDO.template = metadata.template; } if ( metadata.templateUrl ) { componentSpecificDDO.templateUrl = `${assetsPath}${metadata.templateUrl}`; } StringMapWrapper.assign( _ddo, componentSpecificDDO ); } // allow compile defined as static method on Type if ( isFunction( (type as any).compile ) ) { _ddo.compile = function compile( tElement, tAttrs ) { const linkFn = (type as any).compile( tElement, tAttrs ); // if user custom compile fn returns link use that one instead use generated return isJsObject( linkFn ) ? linkFn : this.link; } } // allow link defined as static method on Type override the created one // you should not use this very often // Note: if you use this any @Host property decorators or lifeCycle hooks wont work if ( isFunction((type as any).link) ) { _ddo.link = (type as any).link; } // legacy property overrides all generated DDO stuff const ddo = this._createDDO( _ddo, metadata.legacy ); function directiveFactory() { return ddo } // ========================== // ngComponentRouter Support: // ========================== // @TODO(pete) remove the following `forEach` before we release 1.6.0 // The component-router@0.2.0 looks for the annotations on the controller constructor // Nothing in Angular looks for annotations on the factory function but we can't remove // it from 1.5.x yet. // Copy any annotation properties (starting with $) over to the factory and controller constructor functions // These could be used by libraries such as the new component router StringMapWrapper.forEach( ddo as any, function ( val: any, key: string ) { if ( key.charAt( 0 ) === '$' ) { directiveFactory[ key ] = val; // Don't try to copy over annotations to named controller if ( isFunction( ddo.controller ) ) { ddo.controller[ key ] = val } } } ); // support componentRouter $canActivate lc hook as static instead of defined within legacy object // componentRouter reads all lc hooks from directiveFactory ¯\_(ツ)_/¯ // @TODO update this when new component router will be available for Angular 1 ( 1.6 release probably ) if ( isFunction( (type as any).$canActivate ) ) { (directiveFactory as any).$canActivate = (type as any).$canActivate; } return [ directiveName, directiveFactory ] } _createDDO( ddo: ng.IDirective, legacyDDO: LegacyDirectiveDefinition ): ng.IDirective { return assign( {}, DirectiveProvider._ddoShell, ddo, legacyDDO ) } /** * * @param requireMap * @param directiveName * @returns {Array} * @private * @internal */ _createRequires( requireMap: StringMap, directiveName: string ): string[] { return [ directiveName, ...StringMapWrapper.values( requireMap ) ]; } /** * Directive lifeCycles: * - ngOnInit from preLink (all children compiled and DOM ready) * - ngAfterContentInit from postLink ( DOM in children ready ) * - ngOnDestroy from postLink * * Component lifeCycles: * - ngOnInit from preLink (controller require ready) * - ngAfterViewInit from postLink ( all children in view+content compiled and DOM ready ) * - ngAfterContentInit from postLink ( same as ngAfterViewInit ) * - ngOnDestroy from postLink * @param type * @param metadata * @param lfHooks * @private * @internal */ _createLink( type: Type, metadata: DirectiveMetadata | ComponentMetadata, lfHooks: ImplementedLifeCycleHooks ): ng.IDirectiveLinkFn { if ( (lfHooks.ngAfterContentChecked || lfHooks.ngAfterViewChecked) && StringMapWrapper.size( metadata.queries ) === 0 ) { throw new Error( ` Hooks Impl for ${ stringify( type ) }: =================================== You've implement AfterContentChecked/AfterViewChecked lifecycle, but @ViewChild(ren)/@ContentChild(ren) decorators are not used. we cannot invoke After(Content|View)Checked without provided @Query decorators ` ) } if ( metadata instanceof ComponentMetadata ) { if ( (lfHooks.ngAfterContentInit || lfHooks.ngAfterContentChecked) && !StringMapWrapper.getValueFromPath( metadata, 'legacy.transclude' ) ) { throw new Error( ` Hooks Impl for ${ stringify( type ) }: =================================== You cannot implement AfterContentInit lifecycle, without allowed transclusion. turn transclusion on within decorator like this: @Component({legacy:{transclude:true}}) ` ) } } // we need to implement this if query are present on class, because during postLink _ngOnChildrenChanged is not yet // implemented on controller instance if ( StringMapWrapper.size( metadata.queries ) ) { type.prototype._ngOnChildrenChanged = noop; } const hostProcessed = _parseHost( metadata.host ); return postLink; function postLink( scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, controller: [DirectiveCtrl,any], transclude?: ng.ITranscludeFunction ) { const _watchers = []; const [ctrl,...requiredCtrls] = controller; _setHostStaticAttributes( element, hostProcessed.hostStatic ); // setup @HostBindings _watchers.push( ..._setHostBindings( scope, element, ctrl, hostProcessed.hostBindings ) ); // setup @HostListeners _setHostListeners( scope, element, ctrl, hostProcessed.hostListeners ); // @ContentChild/@ContentChildren/@ViewChild/@ViewChildren related logic const parentCheckedNotifiers = _getParentCheckNotifiers( ctrl, requiredCtrls ); _watchers.push( ...parentCheckedNotifiers ); _setupQuery( scope, element, ctrl, metadata.queries ); // AfterContentInit/AfterViewInit Hooks // if there are query defined schedule $evalAsync semaphore if ( StringMapWrapper.size( metadata.queries ) ) { ctrl._ngOnChildrenChanged( ChildrenChangeHook.FromView, [ parentCheckedNotifiers.forEach( cb=>cb() ), ctrl.ngAfterViewInit && ctrl.ngAfterViewInit.bind( ctrl ), ctrl.ngAfterViewChecked && ctrl.ngAfterViewChecked.bind( ctrl ), ] ); ctrl._ngOnChildrenChanged( ChildrenChangeHook.FromContent, [ parentCheckedNotifiers.forEach( cb=>cb() ), ctrl.ngAfterContentInit && ctrl.ngAfterContentInit.bind( ctrl ), ctrl.ngAfterContentChecked && ctrl.ngAfterContentChecked.bind( ctrl ), ] ); } else { // no @ContentChild/@ViewChild(ref) decorators exist, call just controller init method parentCheckedNotifiers.forEach( cb=>cb() ); ctrl.ngAfterViewInit && ctrl.ngAfterViewInit(); ctrl.ngAfterContentInit && ctrl.ngAfterContentInit(); } _setupDestroyHandler( scope, element, ctrl, lfHooks.ngOnDestroy, _watchers ); } } } export const directiveProvider = new DirectiveProvider( new DirectiveResolver() );
the_stack
import _ = require('lodash'); import url = require('url'); import type * as net from 'net'; import { encode as encodeBase64 } from 'base64-arraybuffer'; import { Readable, Transform } from 'stream'; import { stripIndent } from 'common-tags'; import { Headers, CompletedRequest, CompletedBody, Explainable, RawHeaders } from "../../types"; import { MaybePromise, Replace } from '../../util/type-utils'; import { buildBodyReader } from '../../util/request-utils'; import { asBuffer } from '../../util/buffer-utils'; import { Serializable, ClientServerChannel, serializeBuffer, SerializedProxyConfig, serializeProxyConfig } from "../../serialization/serialization"; import { withDeserializedBodyReader, withSerializedCallbackBuffers } from '../../serialization/body-serialization'; import { ProxyConfig } from '../proxy-config'; /* This file defines request handler *definitions*, which includes everything necessary to define and serialize a request handler's behaviour, but doesn't include the actual handling logic (which lives in ./request-handlers instead). This is intended to allow tree-shaking in browser usage or remote clients to import only the necessary code, with no need to include all the real request-processing and handling code that is only used at HTTP-runtime, so isn't relevant when defining rules. Every RequestHandler extends its definition, simply adding a handle() method, which handles requests according to the configuration, and adding a deserialize static method that takes the serialized output from the serialize() methods defined here and creates a working handler. */ export interface RequestHandlerDefinition extends Explainable, Serializable { type: keyof typeof HandlerDefinitionLookup; } export type SerializedBuffer = { type: 'Buffer', data: number[] }; /** * Can be returned from callbacks to override parts of a request. * * All fields are optional, and omitted values will default to the original * request value. */ export interface CallbackRequestResult { /** * A replacement HTTP method, capitalized. */ method?: string; /** * The full URL to send the request to. If set, this will redirect * the request and automatically update the Host header accordingly, * unless you also provide a `headers` value that includes a Host * header, in which case that will take used as-is. */ url?: string; /** * The replacement HTTP headers, as an object of string keys and either * single string or array of string values. */ headers?: Headers; /** * A string or buffer, which replaces the request body if set. This will * be automatically content-encoded to match the Content-Encoding defined * in your request headers. * * If this is set, the Content-Length header will be automatically updated * accordingly to match, unless you also provide a `headers` value that * includes a Content-Length header, in which case that will take used * as-is. * * You should only return one body field: either `body`, `rawBody` or * `json`. */ body?: string | Buffer | Uint8Array; /** * A buffer, which replaces the request body if set, which is sent exactly * as is, and is not automatically encoded. * * If this is set, the Content-Length header will be automatically updated * accordingly to match, unless you also provide a `headers` value that * includes a Content-Length header, in which case that will take used * as-is. * * You should only return one body field: either `body`, `rawBody` or * `json`. */ rawBody?: Buffer | Uint8Array; /** * A JSON value, which will be stringified and send as a JSON-encoded * request body. This will be automatically content-encoded to match * the Content-Encoding defined in your request headers. * * If this is set, the Content-Length header will be automatically updated * accordingly to match, unless you also provide a `headers` value that * includes a Content-Length header, in which case that will take used * as-is. * * You should only return one body field: either `body`, `rawBody` or * `json`. */ json?: any; /** * A response: either a response object defining the fields of a response * or the string 'close' to immediately close the connection. * * See {@link CallbackResponseMessageResult} for the possible fields that can * be set to define the response. * * If set, the request will not be forwarded at all, and this will be used * as the response to immediately return to the client (or for 'close', this * will immediately close the connection to the client). */ response?: CallbackResponseResult; } export type CallbackResponseResult = | CallbackResponseMessageResult | 'close'; /** * Can be returned from callbacks to define parts of a response, or * override parts when given an existing repsonse. * * All fields are optional, and omitted values will default to the original * response value or a default value. */ export interface CallbackResponseMessageResult { /** * The response status code as a number. * * Defaults to 200 if not set. */ statusCode?: number; /** * Supported only for backward compatibility. * * @deprecated Use statusCode instead. */ status?: number; /** * The response status message, as a string. This is ignored for * HTTP/2 responses. * * Defaults to the default status message for the status code if not set. */ statusMessage?: string; /** * The replacement HTTP headers, as an object of string keys and either * single string or array of string values. * * Defaults to a minimum set of standard required headers if not set. */ headers?: Headers; /** * A string or buffer, which replaces the response body if set. This will * be automatically encoded to match the Content-Encoding defined in your * response headers. * * If this is set, the Content-Length header will be automatically updated * accordingly to match, unless you also provide a `headers` value that * includes a Content-Length header, in which case that will take used * as-is. * * Defaults to empty. * * You should only return one body field: either `body`, `rawBody` or * `json`. */ body?: string | Buffer | Uint8Array; /** * A buffer, which replaces the response body if set, which is sent exactly * as is, and is not automatically encoded. * * If this is set, the Content-Length header will be automatically updated * accordingly to match, unless you also provide a `headers` value that * includes a Content-Length header, in which case that will take used * as-is. * * You should only return one body field: either `body`, `rawBody` or * `json`. */ rawBody?: Buffer | Uint8Array; /** * A JSON value, which will be stringified and send as a JSON-encoded * request body. This will be automatically content-encoded to match the * Content-Encoding defined in your response headers. * * If this is set, the Content-Length header will be automatically updated * accordingly to match, unless you also provide a `headers` value that * includes a Content-Length header, in which case that will take used * as-is. * * You should only return one body field: either `body`, `rawBody` or * `json`. */ json?: any; } function validateCustomHeaders( originalHeaders: Headers, modifiedHeaders: Headers | undefined, headerWhitelist: readonly string[] = [] ) { if (!modifiedHeaders) return; // We ignore most returned pseudo headers, so we error if you try to manually set them const invalidHeaders = _(modifiedHeaders) .pickBy((value, name) => name.toString().startsWith(':') && // We allow returning a preexisting header value - that's ignored // silently, so that mutating & returning the provided headers is always safe. value !== originalHeaders[name] && // In some cases, specific custom pseudoheaders may be allowed, e.g. requests // can have custom :scheme and :authority headers set. !headerWhitelist.includes(name) ) .keys(); if (invalidHeaders.size() > 0) { throw new Error( `Cannot set custom ${invalidHeaders.join(', ')} pseudoheader values` ); } } export class SimpleHandlerDefinition extends Serializable implements RequestHandlerDefinition { readonly type = 'simple'; constructor( public status: number, public statusMessage?: string, public data?: string | Uint8Array | Buffer | SerializedBuffer, public headers?: Headers ) { super(); validateCustomHeaders({}, headers); } explain() { return `respond with status ${this.status}` + (this.statusMessage ? ` (${this.statusMessage})`: "") + (this.headers ? `, headers ${JSON.stringify(this.headers)}` : "") + (this.data ? ` and body "${this.data}"` : ""); } } /** * @internal */ export interface SerializedCallbackHandlerData { type: string; name?: string; version?: number; } /** * @internal */ export interface CallbackRequestMessage { args: [ | Replace<CompletedRequest, { body: string }> // New format | CompletedRequest // Old format with directly serialized body ]; } export class CallbackHandlerDefinition extends Serializable implements RequestHandlerDefinition { readonly type = 'callback'; constructor( public callback: (request: CompletedRequest) => MaybePromise<CallbackResponseResult> ) { super(); } explain() { return 'respond using provided callback' + (this.callback.name ? ` (${this.callback.name})` : ''); } /** * @internal */ serialize(channel: ClientServerChannel): SerializedCallbackHandlerData { channel.onRequest< CallbackRequestMessage, CallbackResponseResult >(async (streamMsg) => { const request = _.isString(streamMsg.args[0].body) ? withDeserializedBodyReader( // New format: body serialized as base64 streamMsg.args[0] as Replace<CompletedRequest, { body: string }> ) : { // Backward compat: old fully-serialized format ...streamMsg.args[0], body: buildBodyReader(streamMsg.args[0].body.buffer, streamMsg.args[0].headers) }; const callbackResult = await this.callback.call(null, request); if (typeof callbackResult === 'string') { return callbackResult; } else { return withSerializedCallbackBuffers(callbackResult); } }); return { type: this.type, name: this.callback.name, version: 2 }; } } /** * @internal */ export interface SerializedStreamHandlerData { type: string; status: number; headers?: Headers; }; interface StreamHandlerMessage { event: 'data' | 'end' | 'close' | 'error'; content: StreamHandlerEventMessage; } type StreamHandlerEventMessage = { type: 'string', value: string } | { type: 'buffer', value: string } | { type: 'arraybuffer', value: string } | { type: 'nil' }; export class StreamHandlerDefinition extends Serializable implements RequestHandlerDefinition { readonly type = 'stream'; constructor( public status: number, public stream: Readable & { done?: true }, public headers?: Headers ) { super(); validateCustomHeaders({}, headers); } explain() { return `respond with status ${this.status}` + (this.headers ? `, headers ${JSON.stringify(this.headers)},` : "") + ' and a stream of response data'; } /** * @internal */ serialize(channel: ClientServerChannel): SerializedStreamHandlerData { const serializationStream = new Transform({ objectMode: true, transform: function (this: Transform, chunk, _encoding, callback) { let serializedEventData: StreamHandlerEventMessage | false = _.isString(chunk) ? { type: 'string', value: chunk } : _.isBuffer(chunk) ? { type: 'buffer', value: chunk.toString('base64') } : (_.isArrayBuffer(chunk) || _.isTypedArray(chunk)) ? { type: 'arraybuffer', value: encodeBase64(<any> chunk) } : _.isNil(chunk) && { type: 'nil' }; if (!serializedEventData) { callback(new Error(`Can't serialize streamed value: ${chunk.toString()}. Streaming must output strings, buffers or array buffers`)); } callback(undefined, <StreamHandlerMessage> { event: 'data', content: serializedEventData }); }, flush: function(this: Transform, callback) { this.push(<StreamHandlerMessage> { event: 'end' }); callback(); } }); // When we get a ping from the server-side, pipe the real stream to serialize it and send the data across channel.once('data', () => { this.stream.pipe(serializationStream).pipe(channel, { end: false }); }); return { type: this.type, status: this.status, headers: this.headers }; } } export class FileHandlerDefinition extends Serializable implements RequestHandlerDefinition { readonly type = 'file'; constructor( public status: number, public statusMessage: string | undefined, public filePath: string, public headers?: Headers ) { super(); validateCustomHeaders({}, headers); } explain() { return `respond with status ${this.status}` + (this.statusMessage ? ` (${this.statusMessage})`: "") + (this.headers ? `, headers ${JSON.stringify(this.headers)}` : "") + (this.filePath ? ` and body from file ${this.filePath}` : ""); } } // This is different from CompletedResponse because CompletedResponse is a client request to Mockttp // whereas this is a real response from an upstream server that we modify before forwarding. // We aim for a similar shape, but they're not exactly the same. export interface PassThroughResponse { id: string; statusCode: number; statusMessage?: string; headers: Headers; rawHeaders: RawHeaders; body: CompletedBody; } export interface ForwardingOptions { targetHost: string, // Should the host (H1) or :authority (H2) header be updated to match? updateHostHeader?: true | false | string // Change automatically/ignore/change to custom value } export interface PassThroughLookupOptions { /** * The maximum time to cache a DNS response. Up to this limit, * responses will be cached according to their own TTL. Defaults * to Infinity. */ maxTtl?: number; /** * How long to cache a DNS ENODATA or ENOTFOUND response. Defaults * to 0.15. */ errorTtl?: number; /** * The primary servers to use. DNS queries will be resolved against * these servers first. If no data is available, queries will fall * back to dns.lookup, and use the OS's default DNS servers. * * This defaults to dns.getServers(). */ servers?: string[]; } export interface PassThroughHandlerOptions { /** * The forwarding configuration for the passthrough rule. * This generally shouldn't be used explicitly unless you're * building rule data by hand. Instead, call `thenPassThrough` * to send data directly or `thenForwardTo` with options to * configure traffic forwarding. */ forwarding?: ForwardingOptions, /** * A list of hostnames for which server certificate and TLS version errors * should be ignored (none, by default). */ ignoreHostHttpsErrors?: string[]; /** * An array of additional certificates, which should be trusted as certificate * authorities for upstream hosts, in addition to Node.js's built-in certificate * authorities. * * Each certificate should be an object with either a `cert` key and a string * or buffer value containing the PEM certificate, or a `certPath` key and a * string value containing the local path to the PEM certificate. */ trustAdditionalCAs?: Array<{ cert: string | Buffer } | { certPath: string }>; /** * A mapping of hosts to client certificates to use, in the form of * `{ key, cert }` objects (none, by default) */ clientCertificateHostMap?: { [host: string]: { pfx: Buffer, passphrase?: string } }; /** * Upstream proxy configuration: pass through requests via this proxy. * * If this is undefined, no proxy will be used. To configure a proxy * provide either: * - a ProxySettings object * - a callback which will be called with an object containing the * hostname, and must return a ProxySettings object or undefined. * - an array of ProxySettings or callbacks. The array will be * processed in order, and the first not-undefined ProxySettings * found will be used. * * When using a remote client, this parameter or individual array * values may be passed by reference, using the name of a rule * parameter configured in the admin server. */ proxyConfig?: ProxyConfig; /** * Custom DNS options, to allow configuration of the resolver used * when forwarding requests upstream. Passing any option switches * from using node's default dns.lookup function to using the * cacheable-lookup module, which will cache responses. */ lookupOptions?: PassThroughLookupOptions; /** * A set of data to automatically transform a request. This includes properties * to support many transformation common use cases. * * For advanced cases, a custom callback using beforeRequest can be used instead. * Using this field however where possible is typically simpler, more declarative, * and can be more performant. The two options are mutually exclusive: you cannot * use both transformRequest and a beforeRequest callback. * * Only one transformation for each target (method, headers & body) can be * specified. If more than one is specified then an error will be thrown when the * rule is registered. */ transformRequest?: RequestTransform; /** * A set of data to automatically transform a response. This includes properties * to support many transformation common use cases. * * For advanced cases, a custom callback using beforeResponse can be used instead. * Using this field however where possible is typically simpler, more declarative, * and can be more performant. The two options are mutually exclusive: you cannot * use both transformResponse and a beforeResponse callback. * * Only one transformation for each target (status, headers & body) can be * specified. If more than one is specified then an error will be thrown when the * rule is registered. */ transformResponse?: ResponseTransform; /** * A callback that will be passed the full request before it is passed through, * and which returns an object that defines how the the request content should * be transformed before it's passed to the upstream server. * * The callback can return an object to define how the request should be changed. * All fields on the object are optional, and returning undefined is equivalent * to returning an empty object (transforming nothing). * * See {@link CallbackRequestResult} for the possible fields that can be set. */ beforeRequest?: (req: CompletedRequest) => MaybePromise<CallbackRequestResult | void> | void; /** * A callback that will be passed the full response before it is passed through, * and which returns a value that defines how the the response content should * be transformed before it's returned to the client. * * The callback can either return an object to define how the response should be * changed, or the string 'close' to immediately close the underlying connection. * * All fields on the object are optional, and returning undefined is equivalent * to returning an empty object (transforming nothing). * * See {@link CallbackResponseMessageResult} for the possible fields that can be set. */ beforeResponse?: (res: PassThroughResponse) => MaybePromise<CallbackResponseResult | void> | void; } export interface RequestTransform { /** * A replacement HTTP method. Case insensitive. */ replaceMethod?: string; /** * A headers object which will be merged with the real request headers to add or * replace values. Headers with undefined values will be removed. */ updateHeaders?: Headers; /** * A headers object which will completely replace the real request headers. */ replaceHeaders?: Headers; /** * A string or buffer that replaces the request body entirely. * * If this is specified, the upstream request will not wait for the original request * body, so this may make responses faster than they would be otherwise given large * request bodies or slow/streaming clients. */ replaceBody?: string | Uint8Array | Buffer; /** * The path to a file, which will be used to replace the request body entirely. The * file will be re-read for each request, so the body will always reflect the latest * file contents. * * If this is specified, the upstream request will not wait for the original request * body, so this may make responses faster than they would be otherwise given large * request bodies or slow/streaming clients. */ replaceBodyFromFile?: string; /** * A JSON object which will be merged with the real request body. Undefined values * will be removed. Any requests which are received with an invalid JSON body that * match this rule will fail. */ updateJsonBody?: { [key: string]: any; }; } export interface ResponseTransform { /** * A replacement response status code. */ replaceStatus?: number; /** * A headers object which will be merged with the real response headers to add or * replace values. Headers with undefined values will be removed. */ updateHeaders?: Headers; /** * A headers object which will completely replace the real response headers. */ replaceHeaders?: Headers; /** * A string or buffer that replaces the response body entirely. * * If this is specified, the downstream response will not wait for the original response * body, so this may make responses arrive faster than they would be otherwise given large * response bodies or slow/streaming servers. */ replaceBody?: string | Uint8Array | Buffer; /** * The path to a file, which will be used to replace the response body entirely. The * file will be re-read for each response, so the body will always reflect the latest * file contents. * * If this is specified, the downstream response will not wait for the original response * body, so this may make responses arrive faster than they would be otherwise given large * response bodies or slow/streaming servers. */ replaceBodyFromFile?: string; /** * A JSON object which will be merged with the real response body. Undefined values * will be removed. Any responses which are received with an invalid JSON body that * match this rule will fail. */ updateJsonBody?: { [key: string]: any; }; } /** * @internal */ export interface SerializedPassThroughData { type: 'passthrough'; forwardToLocation?: string; forwarding?: ForwardingOptions; proxyConfig?: SerializedProxyConfig; ignoreHostCertificateErrors?: string[]; // Doesn't match option name, backward compat extraCACertificates?: Array<{ cert: string } | { certPath: string }>; clientCertificateHostMap?: { [host: string]: { pfx: string, passphrase?: string } }; lookupOptions?: PassThroughLookupOptions; transformRequest?: Replace<RequestTransform, { 'replaceBody'?: string, // Serialized as base64 buffer 'updateHeaders'?: string, // // Serialized as a string to preserve undefined values 'updateJsonBody'?: string // Serialized as a string to preserve undefined values }>, transformResponse?: Replace<ResponseTransform, { 'replaceBody'?: string, // Serialized as base64 buffer 'updateHeaders'?: string, // // Serialized as a string to preserve undefined values 'updateJsonBody'?: string // Serialized as a string to preserve undefined values }>, hasBeforeRequestCallback?: boolean; hasBeforeResponseCallback?: boolean; } /** * @internal */ export interface BeforePassthroughRequestRequest { args: [Replace<CompletedRequest, { body: string }>]; } /** * @internal */ export interface BeforePassthroughResponseRequest { args: [Replace<PassThroughResponse, { body: string }>]; } /** * Used in merging as a marker for values to omit, because lodash ignores undefineds. * @internal */ export const SERIALIZED_OMIT = "__mockttp__transform__omit__"; export class PassThroughHandlerDefinition extends Serializable implements RequestHandlerDefinition { readonly type = 'passthrough'; public readonly forwarding?: ForwardingOptions; public readonly ignoreHostHttpsErrors: string[] = []; public readonly clientCertificateHostMap: { [host: string]: { pfx: Buffer, passphrase?: string } }; public readonly extraCACertificates: Array<{ cert: string | Buffer } | { certPath: string }> = []; public readonly transformRequest?: RequestTransform; public readonly transformResponse?: ResponseTransform; public readonly beforeRequest?: (req: CompletedRequest) => MaybePromise<CallbackRequestResult | void> | void; public readonly beforeResponse?: (res: PassThroughResponse) => MaybePromise<CallbackResponseResult | void> | void; public readonly proxyConfig?: ProxyConfig; public readonly lookupOptions?: PassThroughLookupOptions; // Used in subclass - awkwardly needs to be initialized here to ensure that its set when using a // handler built from a definition. In future, we could improve this (compose instead of inheritance // to better control handler construction?) but this will do for now. protected outgoingSockets = new Set<net.Socket>(); constructor(options: PassThroughHandlerOptions = {}) { super(); // If a location is provided, and it's not a bare hostname, it must be parseable const { forwarding } = options; if (forwarding && forwarding.targetHost.includes('/')) { const { protocol, hostname, port, path } = url.parse(forwarding.targetHost); if (path && path.trim() !== "/") { const suggestion = url.format({ protocol, hostname, port }) || forwarding.targetHost.slice(0, forwarding.targetHost.indexOf('/')); throw new Error(stripIndent` URLs for forwarding cannot include a path, but "${forwarding.targetHost}" does. ${'' }Did you mean ${suggestion}? `); } } this.forwarding = forwarding; this.ignoreHostHttpsErrors = options.ignoreHostHttpsErrors || []; if (!Array.isArray(this.ignoreHostHttpsErrors)) { throw new Error("ignoreHostHttpsErrors must be an array"); } this.lookupOptions = options.lookupOptions; this.proxyConfig = options.proxyConfig; this.clientCertificateHostMap = options.clientCertificateHostMap || {}; this.extraCACertificates = options.trustAdditionalCAs || []; if (options.beforeRequest && options.transformRequest && !_.isEmpty(options.transformRequest)) { throw new Error("BeforeRequest and transformRequest options are mutually exclusive"); } else if (options.beforeRequest) { this.beforeRequest = options.beforeRequest; } else if (options.transformRequest) { if ([ options.transformRequest.updateHeaders, options.transformRequest.replaceHeaders ].filter(o => !!o).length > 1) { throw new Error("Only one request header transform can be specified at a time"); } if ([ options.transformRequest.replaceBody, options.transformRequest.replaceBodyFromFile, options.transformRequest.updateJsonBody ].filter(o => !!o).length > 1) { throw new Error("Only one request body transform can be specified at a time"); } this.transformRequest = options.transformRequest; } if (options.beforeResponse && options.transformResponse && !_.isEmpty(options.transformResponse)) { throw new Error("BeforeResponse and transformResponse options are mutually exclusive"); } else if (options.beforeResponse) { this.beforeResponse = options.beforeResponse; } else if (options.transformResponse) { if ([ options.transformResponse.updateHeaders, options.transformResponse.replaceHeaders ].filter(o => !!o).length > 1) { throw new Error("Only one response header transform can be specified at a time"); } if ([ options.transformResponse.replaceBody, options.transformResponse.replaceBodyFromFile, options.transformResponse.updateJsonBody ].filter(o => !!o).length > 1) { throw new Error("Only one response body transform can be specified at a time"); } this.transformResponse = options.transformResponse; } } explain() { return this.forwarding ? `forward the request to ${this.forwarding.targetHost}` : 'pass the request through to the target host'; } /** * @internal */ serialize(channel: ClientServerChannel): SerializedPassThroughData { if (this.beforeRequest) { channel.onRequest< BeforePassthroughRequestRequest, CallbackRequestResult | undefined >('beforeRequest', async (req) => { const callbackResult = await this.beforeRequest!( withDeserializedBodyReader(req.args[0]) ); const serializedResult = callbackResult ? withSerializedCallbackBuffers(callbackResult) : undefined; if (serializedResult?.response && typeof serializedResult?.response !== 'string') { serializedResult.response = withSerializedCallbackBuffers(serializedResult.response); } return serializedResult; }); } if (this.beforeResponse) { channel.onRequest< BeforePassthroughResponseRequest, CallbackResponseResult | undefined >('beforeResponse', async (req) => { const callbackResult = await this.beforeResponse!( withDeserializedBodyReader(req.args[0]) ); if (typeof callbackResult === 'string') { return callbackResult; } else if (callbackResult) { return withSerializedCallbackBuffers(callbackResult); } else { return undefined; } }); } return { type: this.type, ...this.forwarding ? { forwardToLocation: this.forwarding.targetHost, forwarding: this.forwarding } : {}, proxyConfig: serializeProxyConfig(this.proxyConfig, channel), lookupOptions: this.lookupOptions, ignoreHostCertificateErrors: this.ignoreHostHttpsErrors, extraCACertificates: this.extraCACertificates.map((certObject) => { // We use toString to make sure that buffers always end up as // as UTF-8 string, to avoid serialization issues. Strings are an // easy safe format here, since it's really all just plain-text PEM // under the hood. if ('cert' in certObject) { return { cert: certObject.cert.toString('utf8') } } else { return certObject; } }), clientCertificateHostMap: _.mapValues(this.clientCertificateHostMap, ({ pfx, passphrase }) => ({ pfx: serializeBuffer(pfx), passphrase }) ), transformRequest: this.transformRequest ? { ...this.transformRequest, // Body is always serialized as a base64 buffer: replaceBody: !!this.transformRequest?.replaceBody ? serializeBuffer(asBuffer(this.transformRequest.replaceBody)) : undefined, // Update objects need to capture undefined & null as distict values: updateHeaders: !!this.transformRequest?.updateHeaders ? JSON.stringify( this.transformRequest.updateHeaders, (k, v) => v === undefined ? SERIALIZED_OMIT : v ) : undefined, updateJsonBody: !!this.transformRequest?.updateJsonBody ? JSON.stringify( this.transformRequest.updateJsonBody, (k, v) => v === undefined ? SERIALIZED_OMIT : v ) : undefined } : undefined, transformResponse: this.transformResponse ? { ...this.transformResponse, // Body is always serialized as a base64 buffer: replaceBody: !!this.transformResponse?.replaceBody ? serializeBuffer(asBuffer(this.transformResponse.replaceBody)) : undefined, // Update objects need to capture undefined & null as distict values: updateHeaders: !!this.transformResponse?.updateHeaders ? JSON.stringify( this.transformResponse.updateHeaders, (k, v) => v === undefined ? SERIALIZED_OMIT : v ) : undefined, updateJsonBody: !!this.transformResponse?.updateJsonBody ? JSON.stringify( this.transformResponse.updateJsonBody, (k, v) => v === undefined ? SERIALIZED_OMIT : v ) : undefined } : undefined, hasBeforeRequestCallback: !!this.beforeRequest, hasBeforeResponseCallback: !!this.beforeResponse }; } } export class CloseConnectionHandlerDefinition extends Serializable implements RequestHandlerDefinition { readonly type = 'close-connection'; explain() { return 'close the connection'; } } export class TimeoutHandlerDefinition extends Serializable implements RequestHandlerDefinition { readonly type = 'timeout'; explain() { return 'time out (never respond)'; } } export const HandlerDefinitionLookup = { 'simple': SimpleHandlerDefinition, 'callback': CallbackHandlerDefinition, 'stream': StreamHandlerDefinition, 'file': FileHandlerDefinition, 'passthrough': PassThroughHandlerDefinition, 'close-connection': CloseConnectionHandlerDefinition, 'timeout': TimeoutHandlerDefinition }
the_stack
import * as utils from "../utils/utils"; import * as React from "react"; //const connect = require("react-redux").connect; import { connect } from "react-redux"; import * as _ from "lodash"; import { addListItem, removeListItem, getListItemsAction, saveListItemAction, undoListItemChangesAction, updateListItemAction, } from "../actions/listItemActions"; import { getLookupOptionAction } from "../actions/lookupOptionsActions"; import { getSiteUsersAction } from "../actions/siteUsersActions"; import ListItem from "../model/ListItem"; import ColumnDefinition from "../model/ColumnDefinition"; import { LookupOptions, LookupOptionStatus } from "../model/LookupOptions"; import { SiteUsers, SiteUsersStatus } from "../model/SiteUsers"; import GridRowStatus from "../model/GridRowStatus"; import ListDefinition from "../model/ListDefinition"; import { Button, ButtonType, TextField, IDropdownOption, Dropdown, Spinner, SpinnerType } from "office-ui-fabric-react"; import { CommandBar } from "office-ui-fabric-react/lib/CommandBar"; import { DatePicker, IDatePickerStrings } from "office-ui-fabric-react/lib/DatePicker"; import Container from "../components/container"; import { Log } from "@microsoft/sp-core-library"; interface IListViewPageProps extends React.Props<any> { /** An array of ListItems fetched from sharepoint */ siteUsers: Array<SiteUsers>; /** An array of ListItems fetched from sharepoint */ listItems: Array<ListItem>; /** An array of LookupOptions. One for each Lookup Column */ lookupOptions: Array<LookupOptions>; /** An array of columns to be displayed on the grid */ columns: Array<ColumnDefinition>; /** The listDefinitions. Says which lists to pull data from */ listDefinitions: Array<ListDefinition>; /** Redux Action to add a new listitem */ addListItem: (ListItem) => void; /** Redux Action to add a new remove a list item */ removeListItem: (l: ListItem, ListDef: ListDefinition) => void; /** Redux Action to get listitems from a specific list */ getListItems: (listDefinitions: Array<ListDefinition>, columnDefinitions: Array<ColumnDefinition>) => void; /** Redux Action to update a listitem in sharepoint */ updateListItem: (ListItem: ListItem, ListDef: ListDefinition) => Promise<any>; /** Redux Action to get the lookup options for a specific field */ getLookupOptionAction: (lookupSite, lookupWebId, lookupListId, lookupField) => void; /** Redux Action to get the lookup options for a specific field */ getSiteUsersAction: (site) => Promise<any>; /** Redux Action to undo changes made to the listitem */ undoItemChanges: (ListItem) => void; /** Redux Action to save the listitem in the store (NOT to sharepoint*/ saveListItem: (ListItem) => void; } function mapStateToProps(state) { return { listItems: state.items, columns: state.columns, listDefinitions: state.lists, systemStatus: state.systemStatus, lookupOptions: state.lookupOptions, siteUsers: state.siteUsers }; } export class GridColumn { constructor( public id: string, public name: string, public editable: boolean, public width: number, public formatter: string = "", public editor?: string) { } } function mapDispatchToProps(dispatch) { return { addListItem: (listItem: ListItem): void => { dispatch(addListItem(listItem)); }, removeListItem: (listItem: ListItem, listDef: ListDefinition): void => { dispatch(removeListItem(dispatch, listItem, listDef)); }, updateListItem: (listItem: ListItem, listDef: ListDefinition): Promise<any> => { const action = updateListItemAction(dispatch, listDef, listItem); dispatch(action); // need to ewname this one to be digfferent from the omported ome return action.payload.promise; }, saveListItem: (listItem: ListItem): void => { dispatch(saveListItemAction(listItem)); }, undoItemChanges: (listItem: ListItem): void => { dispatch(undoListItemChangesAction(listItem)); }, getListItems: (listDefinitions: Array<ListDefinition>, columnDefinitions: Array<ColumnDefinition>): void => { dispatch(getListItemsAction(dispatch, listDefinitions, columnDefinitions));// Column Defs needed to sort }, getLookupOptionAction: (lookupSite, lookupWebId, lookupListId, lookupField): void => { dispatch(getLookupOptionAction(dispatch, lookupSite, lookupWebId, lookupListId, lookupField)); }, getSiteUsersAction: (site): void => { const action = getSiteUsersAction(dispatch, site); dispatch(action); return action.payload.promise; }, }; } /** * */ interface IGridState { editing: { /**The Sharepoint GUID of the listitem being edited */ entityid: string; /**The id of the column being edited */ columnid: string; }; } /** * This component is the Grid for editing listitems. */ class ListItemContainer extends React.Component<IListViewPageProps, IGridState> { public constructor() { super(); this.CellContentsEditable = this.CellContentsEditable.bind(this); this.CellContents = this.CellContents.bind(this); this.TableDetail = this.TableDetail.bind(this); this.TableRow = this.TableRow.bind(this); this.TableRows = this.TableRows.bind(this); this.toggleEditing = this.toggleEditing.bind(this); this.addListItem = this.addListItem.bind(this); // this.removeListItem = this.removeListItem.bind(this); this.handleCellUpdated = this.handleCellUpdated.bind(this); this.handleCellUpdatedEvent = this.handleCellUpdatedEvent.bind(this); this.HandleUndoItemChangesEvent = this.HandleUndoItemChangesEvent.bind(this); this.handleUpdateListItemEvent = this.handleUpdateListItemEvent.bind(this); this.updateListItem = this.updateListItem.bind(this); this.getLookupOptions = this.getLookupOptions.bind(this); this.saveAll = this.saveAll.bind(this); this.undoAll = this.undoAll.bind(this); this.markListItemAsDeleted = this.markListItemAsDeleted.bind(this); } private saveAll(): void { const unsavedItems = _.filter(this.props.listItems, item => { return item.__metadata__OriginalValues; }); for (const entity of unsavedItems) { this.updateListItem(entity); } } private undoAll(): void { const unsavedItems = _.filter(this.props.listItems, item => { return item.__metadata__OriginalValues; }); for (const unsavedItem of unsavedItems) { this.props.undoItemChanges(unsavedItem); } } private addListItem(): void { let listItem = new ListItem(); for (const column of this.props.columns) { listItem[column.name] = null; } if (this.props.listDefinitions.length === 1) { listItem.__metadata__ListDefinitionId = this.props.listDefinitions[0].guid; } else { listItem.__metadata__ListDefinitionId = null; } this.props.addListItem(listItem); } // private removeListItem(event): void { // const parentTD = this.getParent(event.target, "TD"); // const attributes: NamedNodeMap = parentTD.attributes; // const entityid = attributes.getNamedItem("data-entityid").value; // theid of the SPListItem // const listItem: ListItem = _.find(this.props.listItems, (temp) => temp.GUID === entityid); // the listItemItself // const listDef = this.getListDefinition(listItem.__metadata__ListDefinitionId);// The list Definition this item is associated with. // this.props.removeListItem(listItem, listDef); // } /** * When the component Mounts, call an action to get the listitems for all the listdefinitions */ public componentWillMount() { this.props.getListItems(this.props.listDefinitions, this.props.columns); } public componentWillReceiveProps(newProps: IListViewPageProps) { if (newProps.listDefinitions === this.props.listDefinitions && newProps.columns === this.props.columns) { return; } this.props.getListItems(this.props.listDefinitions, this.props.columns); } /** * Method to get the parent TD of any cell, * The listItemId and columnID are stored as attributes of the cells parent TD. */ public getParent(node: Node, type: string): Node { while (node.nodeName !== "TD") { node = node.parentNode; } return node; } /** * This event gets fired whenever a cell on the grid recieves focus. * The "editing" propery of this component determines which cell is being edited. * This method gets the clicked on (the entityid-- the id of the SPLIstItem) and the columnId (the id of the ColumnDefinition) * and sets them in the "editing"property of state. * When Component then redraws, it draws that cell as an editable (See the TableDetail method). * * If the rendering of that column in edit mode requires additional Info, dispatch a redux action to get the data. * (Dispatching the action from within the render mehod itself cused infinite loop) * */ public toggleEditing(event) { Log.verbose("list-Page", "focus event fired editing when entering cell"); const target = this.getParent(event.target, "TD"); // walk up the Dom to the TD, thats where the IDs are stored const attributes: NamedNodeMap = target.attributes; const entityid = attributes.getNamedItem("data-entityid").value; const columnid = attributes.getNamedItem("data-columnid").value; if (columnid != "") { //user clicked on a column, not a button( Buttons are in a td with am column id of "" /** * Need to fire events here to get data needed for the rerender */ const listitem = _.find(this.props.listItems, li => li.GUID === entityid); const listDef = this.getListDefinition(listitem.__metadata__ListDefinitionId); if (listDef) {// if user just added an item we may not hava a lisdef yest const colref = _.find(listDef.columnReferences, cr => cr.columnDefinitionId === columnid); if (colref) {// Listname does not have a columnReference switch (colref.fieldDefinition.TypeAsString) { case "Lookup": let lookupField = colref.fieldDefinition.LookupField; let lookupListId = colref.fieldDefinition.LookupList; let lookupWebId = colref.fieldDefinition.LookupWebId; /** * We are assuming here that the lookup listy is in the same web. * */ lookupWebId = utils.ParseSPField(listDef.webLookup).id; // temp fix. Need to use graph to get the web by id in the site let lookupSite = listDef.siteUrl; this.ensureLookupOptions(lookupSite, lookupWebId, lookupListId, lookupField); break; case "User": lookupWebId = utils.ParseSPField(listDef.webLookup).id; // temp fix. Need to use graph to get the web by id in the site let site = listDef.siteUrl; this.ensureSiteUsers(site); break; default: break; } } } } this.setState({ "editing": { entityid: entityid, columnid: columnid } }); } /** * This event gets fired to revert any changes made to the ListItem. */ public HandleUndoItemChangesEvent(event): void { const parentTD = this.getParent(event.target, "TD"); // the listitemId and the column ID are always stored as attributes of the parent TD. const attributes: NamedNodeMap = parentTD.attributes; const entityitem = attributes.getNamedItem("data-entityid"); const entityid = entityitem.value; const entity: ListItem = _.find(this.props.listItems, (temp) => temp.GUID === entityid); this.props.undoItemChanges(entity); } /** * This event gets fired, to save the item back to SharePoint. */ public updateListItem(entity: ListItem): void { const listDef: ListDefinition = this.getListDefinition(entity.__metadata__ListDefinitionId); if (entity.__metadata__ListDefinitionId === entity.__metadata__OriginalValues.__metadata__ListDefinitionId) {// List not changed switch (entity.__metadata__GridRowStatus) { case GridRowStatus.toBeDeleted: this.props.removeListItem(entity, listDef); break; case GridRowStatus.new: case GridRowStatus.modified: this.props.updateListItem(entity, listDef); break; default: Log.warn("ListItemContainer", "Invalid GrodrowStatus in update ListiteRender-- " + entity.__metadata__GridRowStatus.toString()); } } else {// list changed const oldListDef: ListDefinition = this.getListDefinition(entity.__metadata__OriginalValues.__metadata__ListDefinitionId); switch (entity.__metadata__GridRowStatus) { case GridRowStatus.toBeDeleted: // delete from orignal list this.props.removeListItem(entity, oldListDef); break; case GridRowStatus.modified: entity.__metadata__GridRowStatus = GridRowStatus.new; /* falls through */ case GridRowStatus.new:// add to new list , delete from orignal list this.props.updateListItem(entity, listDef).then(response => { this.props.removeListItem(entity.__metadata__OriginalValues, oldListDef); }); break; default: Log.warn("ListItemContainer", "Invalid GrodrowStatus in update ListiteRender-- " + entity.__metadata__GridRowStatus.toString()); } } } public handleUpdateListItemEvent(event): void { const parentTD = this.getParent(event.target, "TD"); const attributes: NamedNodeMap = parentTD.attributes; const entityid = attributes.getNamedItem("data-entityid").value; // theid of the SPListItem const entity: ListItem = _.find(this.props.listItems, (temp) => temp.GUID === entityid); this.updateListItem(entity); } /** * This method gets called when react events are used to update a cell in the grid. * It just gets the value and passes it to handleCellUpdated. */ private handleCellUpdatedEvent(event) { //native react uses a Synthetic event this.handleCellUpdated(event.target.value); } /** * This method gets called when user changes the listdefinition for an item. * the old fields are moved to the corresponing new fields and translated as needed */ private mapOldListFieldsToNewListFields(listItem: ListItem) { const newListDef = this.getListDefinition(listItem.__metadata__ListDefinitionId); const oldListDef = this.getListDefinition(listItem.__metadata__OriginalValues.__metadata__ListDefinitionId); for (const newColRef of newListDef.columnReferences) { // find the old columnReference const oldColRef = _.find(oldListDef.columnReferences, cr => cr.columnDefinitionId === newColRef.columnDefinitionId); const newFieldName = utils.ParseSPField(newColRef.name).id; const oldFieldName = utils.ParseSPField(oldColRef.name).id; switch (newColRef.fieldDefinition.TypeAsString) { case "User": // should male a local copy befor i start messing with these.// fieldd names may overlap on old and new // const name = listItem.__metadata__OriginalValues[oldFieldName].Name;// the user login name const name = listItem[oldFieldName].Name;// the user login name const siteUsersOnNewSite = _.find(this.props.siteUsers, su => su.siteUrl === newListDef.siteUrl); const newUser = _.find(siteUsersOnNewSite.siteUser, user => user.loginName === name); if (newUser) { listItem[newFieldName].Id = newUser.id; listItem[newFieldName].Name = newUser.loginName; listItem[newFieldName].Title = newUser.value; } else { delete listItem[newFieldName]; } break; default: listItem[newFieldName] = listItem[oldFieldName]; } } } /** * This method gets called when user clicks delete listitem. * Office UI Fabric does not use events. It just calls this method with the new value. * It reformats the data to fit the format we recievbed from SP in the first place , * and dispatches an action to save the data in the store. * * Also, it saves the original version of the record, so we can undo later. */ private markListItemAsDeleted(event) { const parentTD = this.getParent(event.target, "TD"); const attributes: NamedNodeMap = parentTD.attributes; const entityid = attributes.getNamedItem("data-entityid").value; // theid of the SPListItem const listItem: ListItem = _.find(this.props.listItems, (temp) => temp.GUID === entityid); // the listItemItself if (!listItem.__metadata__OriginalValues) { //SAVE orgininal values so we can undo; listItem.__metadata__OriginalValues = _.cloneDeep(listItem); // need deep if we have lookup values } listItem.__metadata__GridRowStatus = GridRowStatus.toBeDeleted; this.props.saveListItem(listItem); } /** * This method gets called when cells in the grid get updated. * Office UI Fabric does not use events. It just calls this method with the new value. * It reformats the data to fit the format we recievbed from SP in the first place , * and dispatches an action to save the data in the store. * * Also, it saves the original version of the record, so we can undo later. */ private handleCellUpdated(value) { const {entityid, columnid} = this.state.editing; const entity: ListItem = _.find(this.props.listItems, (temp) => temp.GUID === entityid); const listDef = this.getListDefinition(entity.__metadata__ListDefinitionId); const titleColumn = _.find(this.props.columns, c => { return c.type === "__LISTDEFINITIONTITLE__"; }); if (titleColumn) { if (columnid === titleColumn.guid) { // user just changed the listDef, if (entity.__metadata__GridRowStatus === GridRowStatus.pristine) { if (!entity.__metadata__OriginalValues) { //SAVE orgininal values so we can undo; entity.__metadata__OriginalValues = _.cloneDeep(entity); // need deep if we have lookup values } } entity.__metadata__ListDefinitionId = value.key; // value is a DropDDownOptions if (entity.__metadata__GridRowStatus !== GridRowStatus.new) { const newListDef = this.getListDefinition(value.key); this.props.getSiteUsersAction(newListDef.siteUrl).then(r => { this.mapOldListFieldsToNewListFields(entity); this.props.saveListItem(entity); }); } else { this.props.saveListItem(entity); } return; } } const columnReference = _.find(listDef.columnReferences, cr => cr.columnDefinitionId === columnid); const internalName = utils.ParseSPField(columnReference.name).id; if (!entity.__metadata__OriginalValues) { //SAVE orgininal values so we can undo; entity.__metadata__OriginalValues = _.cloneDeep(entity); // need deep if we have lookup values } if (entity.__metadata__GridRowStatus === GridRowStatus.pristine) { entity.__metadata__GridRowStatus = GridRowStatus.modified; } switch (columnReference.fieldDefinition.TypeAsString) { case "User": if (!entity[internalName]) {// if value was not previously set , then this is undefined// entity[internalName] = {};// set new value to an empty objecte } entity[internalName].Id = value.key;//and then fill in the values entity[internalName].Title = value.text; break; case "Choice": entity[internalName] = value.text; break; case "DateTime": let year = value.getFullYear().toString(); let month = (value.getMonth() + 1).toString(); let day = value.getDate().toString(); if (month.length === 1) { month = "0" + month; } if (day.length === 1) { day = "0" + day; } entity[internalName] = year + "-" + month + "-" + day + "T00:00:00Z"; break; case "Lookup": if (!entity[internalName]) {// if value was not previously set , then this is undefined// entity[internalName] = {};// set new value to an empty objecte } entity[internalName]["Id"] = value.key;//and then fill in the values entity[internalName][columnReference.fieldDefinition.LookupField] = value.text; break; default: entity[internalName] = value; } this.props.saveListItem(entity); } /** * If the the options for a lookup list are not in the cache, fire an event to get them * This method is called when a lookup column receives focus. */ public ensureSiteUsers(siteUrl: string): SiteUsers { // see if the options are in the store, if so, return them, otherwoise dispatch an action to get them const siteUsers = _.find(this.props.siteUsers, x => { return (x.siteUrl === siteUrl); }); if (siteUsers === undefined) { this.props.getSiteUsersAction(siteUrl); } return siteUsers; } /** * Gets the options to display for a lookupField * This method is called when a lookup column gets rendered... we fire the event to get the data when its focused, * then we use the data when it gets renderd */ public getSiteUsers(siteUrl: string): SiteUsers { // see if the options are in the store, if so, return them, otherwoise dispatch an action to get them const siteUsers = _.find(this.props.siteUsers, x => { return (x.siteUrl === siteUrl); }); return siteUsers; } /** * If the the options for a lookup list are not in the cache, fire an event to get them * This method is called when a lookup column receives focus. */ public ensureLookupOptions(lookupSite: string, lookupWebId: string, lookupListId: string, lookupField: string): LookupOptions { // see if the options are in the store, if so, return them, otherwoise dispatch an action to get them const lookupoptions = _.find(this.props.lookupOptions, x => { return (x.lookupField === lookupField) && (x.lookupListId === lookupListId) && (x.lookupSite === lookupSite) && (x.lookupWebId === lookupWebId); }); if (lookupoptions === undefined) { this.props.getLookupOptionAction(lookupSite, lookupWebId, lookupListId, lookupField); } return lookupoptions; } /** * Gets the options to display for a lookupField * This method is called when a lookup column gets rendered... we fire the event to get the data when its focused, * then we use the data when it gets renderd */ public getLookupOptions(lookupSite: string, lookupWebId: string, lookupListId: string, lookupField: string): LookupOptions { // see if the options are in the store, if so, return them, otherwoise dispatch an action to get them let lookupoptions = _.find(this.props.lookupOptions, x => { return (x.lookupField === lookupField) && (x.lookupListId === lookupListId) && (x.lookupSite === lookupSite) && (x.lookupWebId === lookupWebId); }); return lookupoptions; } /** * Returns the ListDefinition for the given ListDefinionId * */ public getListDefinition( /** The id of the list definition to be retrieved */ listdefid: string ): ListDefinition { return _.find(this.props.listDefinitions, ld => ld.guid === listdefid); } /** * This method renders the contents of an individual cell in an editable format. */ public CellContentsEditable(props: { entity: ListItem, column: ColumnDefinition, cellUpdated: (newValue) => void, cellUpdatedEvent: (event: React.SyntheticEvent<any>) => void; }): JSX.Element { const {entity, column, cellUpdated, cellUpdatedEvent} = props; if (column.type === "__LISTDEFINITIONTITLE__") { const opts: Array<IDropdownOption> = this.props.listDefinitions.map(ld => { return { key: ld.guid, text: ld.listDefTitle }; }); // if (!entity.__metadata__ListDefinitionId) { // opts.unshift({ key: null, text: "Select one" }); // } // should I have a different handler for this? return ( <Dropdown options={opts} selectedKey={entity.__metadata__ListDefinitionId} label="" onChanged={(selection: IDropdownOption) => { cellUpdated(selection); }} /> ); } const listDef = this.getListDefinition(entity.__metadata__ListDefinitionId); const colref = _.find(listDef.columnReferences, cr => cr.columnDefinitionId === column.guid); const internalName = utils.ParseSPField(colref.name).id; const columnValue = entity[internalName]; switch (colref.fieldDefinition.TypeAsString) { case "Counter":// disable editting return (<span> {entity[internalName]} </span> ); /* falls through */ case "User": let siteUrl = listDef.siteUrl; let siteUsers = this.getSiteUsers(siteUrl); if (siteUsers) { switch (siteUsers.status) { case SiteUsersStatus.fetched: let options: IDropdownOption[] = siteUsers.siteUser.map((opt, index, options) => { return { key: opt.id, text: opt.value }; }); const selectedKey = columnValue ? columnValue.Id : null; return ( <Dropdown label="" options={options} selectedKey={selectedKey} onChanged={(selection: IDropdownOption) => { cellUpdated(selection); }} > </Dropdown > ); case SiteUsersStatus.fetching: return ( <Spinner type={SpinnerType.normal} /> ); case SiteUsersStatus.error: return ( <Spinner label="Error" type={SpinnerType.normal} /> ); default: return ( <Spinner type={SpinnerType.normal} /> ); } } else { return ( <Spinner type={SpinnerType.normal} /> ); } /* falls through */ case "Lookup": let lookupField = colref.fieldDefinition.LookupField; let lookupListId = colref.fieldDefinition.LookupList; let lookupWebId = colref.fieldDefinition.LookupWebId; /** * We are assuming here that the lookup listy is in the same web. * */ lookupWebId = utils.ParseSPField(listDef.webLookup).id; // temp fix. Need to use graph to get the web by id in the site let lookupSite = listDef.siteUrl; let lookupOptions = this.getLookupOptions(lookupSite, lookupWebId, lookupListId, lookupField); if (lookupOptions) { switch (lookupOptions.status) { case LookupOptionStatus.fetched: let options: IDropdownOption[] = lookupOptions.lookupOption.map((opt, index, options) => { return { key: opt.id, text: opt.value }; }); return ( <Dropdown label="" options={options} selectedKey={(columnValue ? columnValue.Id : null)} onChanged={(selection: IDropdownOption) => { cellUpdated(selection); }} > </Dropdown > ); case LookupOptionStatus.fetching: return ( <Spinner type={SpinnerType.normal} /> ); case LookupOptionStatus.error: return ( <Spinner label="Error" type={SpinnerType.normal} /> ); default: return ( <Spinner type={SpinnerType.normal} /> ); } } else { return ( <Spinner type={SpinnerType.normal} /> ); } /* falls through */ case "Choice": const choices = colref.fieldDefinition.Choices.map((c, i) => { let opt: IDropdownOption = { index: i, key: i, text: c, isSelected: (c === columnValue) }; return opt; }); return ( <Dropdown label="" selectedKey={entity[columnValue]} options={choices} onChanged={(selection: IDropdownOption) => cellUpdated(selection)} > </Dropdown > ); case "Text": return ( <input autoFocus type="text" value={columnValue} onChange={cellUpdatedEvent} />); case "Note": return ( <TextField autoFocus value={columnValue} onChanged={cellUpdated} />); case "DateTime": const datpickerStrings: IDatePickerStrings = { "months": [""], "shortMonths": [""], "days": [""], "shortDays": [""], goToToday: "yes" }; let date = null; if (columnValue) { const year = parseInt(columnValue.substring(0, 34)); const month = parseInt(columnValue.substring(5, 7)) - 1; const day = parseInt(columnValue.substring(8, 10)); date = new Date(year, month, day); } return ( <DatePicker strings={datpickerStrings} onSelectDate={cellUpdated} value={date} allowTextInput={true} isRequired={colref.fieldDefinition.Required} />); default: return ( <input autoFocus type="text" value={columnValue} onChange={cellUpdatedEvent} />); } } /** * This method renders the contents of an individual cell in a non-editable format. */ public CellContents(props: { entity: ListItem, column: ColumnDefinition }): JSX.Element { const {entity, column} = props; if (!entity.__metadata__ListDefinitionId) { // item is new and list not yet selected } const listDef = this.getListDefinition(entity.__metadata__ListDefinitionId); if (column.type === "__LISTDEFINITIONTITLE__") {// this type is sued to show the listdefinition name if (listDef != null) {//listdef has been selected return (<a href="#" onFocus={this.toggleEditing} style={{ textDecoration: (entity.__metadata__GridRowStatus === GridRowStatus.toBeDeleted) ? "line-through" : "none" }} > {listDef.listDefTitle} </a>); } else {//listdef not yet selected return (<a href="#" onFocus={this.toggleEditing} style={{ textDecoration: "none" }} > Select a list </a>); } } if (!listDef) { // cant edit columns til we select a listdef, not NO onFocus={this.toggleEditing} return (<a href="#" style={{ textDecoration: "none" }} > select a list first </a> ); } const colref = _.find(listDef.columnReferences, cr => cr.columnDefinitionId === column.guid); if (colref === undefined) { //Column has not been configured for this list return (<a href="#" onFocus={this.toggleEditing} style={{ textDecoration: "none" }} > 'Column Not Defined' </a> ); } const internalName = utils.ParseSPField(colref.name).id; switch (colref.fieldDefinition.TypeAsString) { case "User": if (entity[internalName] === undefined) { // value not set return (<a href="#" onFocus={this.toggleEditing} style={{ textDecoration: (entity.__metadata__GridRowStatus === GridRowStatus.toBeDeleted) ? "line-through" : "none" }} > </a> ); } else { return (<a href="#" onFocus={this.toggleEditing} style={{ textDecoration: (entity.__metadata__GridRowStatus === GridRowStatus.toBeDeleted) ? "line-through" : "none" }} > {entity[internalName]["Title"]} </a> ); } /* falls through */ case "Lookup": if (entity[internalName] === undefined) { // value not set return (<a href="#" onFocus={this.toggleEditing} style={{ textDecoration: (entity.__metadata__GridRowStatus === GridRowStatus.toBeDeleted) ? "line-through" : "none" }} > </a> ); } else { return (<a href="#" onFocus={this.toggleEditing} style={{ textDecoration: (entity.__metadata__GridRowStatus === GridRowStatus.toBeDeleted) ? "line-through" : "none" }} > {entity[internalName][colref.fieldDefinition.LookupField]} </a> ); } /* falls through */ case "Text": return (<a href="#" onFocus={this.toggleEditing} style={{ textDecoration: (entity.__metadata__GridRowStatus === GridRowStatus.toBeDeleted) ? "line-through" : "none" }} > {entity[internalName]} </a> ); /* falls through */ case "Note": return (<a href="#" onFocus={this.toggleEditing} style={{ textDecoration: (entity.__metadata__GridRowStatus === GridRowStatus.toBeDeleted) ? "line-through" : "none" }} dangerouslySetInnerHTML={{ __html: entity[internalName] }} > </a> ); /* falls through */ case "DateTime": let value: string; if (entity[internalName] === null) { return (<a href="#" onFocus={this.toggleEditing} style={{ textDecoration: (entity.__metadata__GridRowStatus === GridRowStatus.toBeDeleted) ? "line-through" : "none" }} > </a>); } if (colref.fieldDefinition.EntityPropertyName === "DateOnly") { value = entity[internalName].split("T")[0]; } else { value = entity[internalName]; } return (<a href="#" onFocus={this.toggleEditing} style={{ textDecoration: (entity.__metadata__GridRowStatus === GridRowStatus.toBeDeleted) ? "line-through" : "none" }} > {value} </a> ); /* falls through */ case "Counter":// disable tabbing to field return (<span> {entity[internalName]} </span> ); /* falls through */ default: return (<a href="#" onFocus={this.toggleEditing} style={{ textDecoration: (entity.__metadata__GridRowStatus === GridRowStatus.toBeDeleted) ? "line-through" : "none" }} > {entity[internalName]} </a> ); } } /** * This method renders the A TD for an individual Cell. The TD contains the listItemID and the ColumnID as attributes. * It calls CellContentsEditable or CellContents based on whether the cell is being edited. * It determines if the cell is being edited by looking at this,props.editing(which got set by ToggleEditing). */ public TableDetail(props: { entity: ListItem, column: ColumnDefinition, cellUpdated: (newValue) => void, cellUpdatedEvent: (event: React.SyntheticEvent<any>) => void; }): JSX.Element { const {entity, column, cellUpdated, cellUpdatedEvent} = props; if (this.state && this.state.editing && this.state.editing.entityid === entity.GUID && this.state.editing.columnid === column.guid && column.editable) { return (<td key={entity.GUID + column.guid} data-entityid={entity.GUID} data-columnid={column.guid} style={{ border: "2px solid black", padding: "0px" }}> <this.CellContentsEditable entity={entity} column={column} cellUpdated={this.handleCellUpdated} cellUpdatedEvent={this.handleCellUpdatedEvent} /> </td> ); } else { return (<td key={entity.GUID + column.guid} data-entityid={entity.GUID} data-columnid={column.guid} style={{ border: "1px solid black", padding: "0px" }} onClick={this.toggleEditing} > <this.CellContents entity={entity} column={column} /> </td> ); } } /** * This method renders a tableRow for an individual listitem */ public TableRow(props: { entity: ListItem, columns: Array<ColumnDefinition>, cellUpdated: (newValue) => void, cellUpdatedEvent: (event: React.SyntheticEvent<any>) => void; }): JSX.Element { const {entity, columns, cellUpdated, cellUpdatedEvent} = props; return ( <tr> { columns.map(function (column) { return ( <this.TableDetail key={column.guid} entity={entity} column={column} cellUpdated={this.handleCellUpdated} cellUpdatedEvent={this.handleCellUpdatedEvent} /> ); }, this) } <td data-entityid={entity.GUID} data-columnid={""} width="200" onClick={this.toggleEditing} > <div> <Button width="20" style={{ padding: 0 }} onClick={this.handleUpdateListItemEvent} alt="Save to Sharepoint" buttonType={ButtonType.icon} icon="Save" disabled={!(entity.__metadata__OriginalValues)} /> {/*<Button width="20" style={{ padding: 0 }} onClick={this.removeListItem} buttonType={ButtonType.icon} icon="Delete" />*/} <Button width="20" style={{ padding: 0 }} onClick={this.markListItemAsDeleted} disabled={(entity.__metadata__GridRowStatus === GridRowStatus.toBeDeleted)} buttonType={ButtonType.icon} icon="Delete" /> <Button width="20" style={{ padding: 0 }} buttonType={ButtonType.icon} disabled={(!(entity.__metadata__OriginalValues))} onClick={this.HandleUndoItemChangesEvent} icon="Undo" /> </div> </td> </tr>); }; /** * Render rows for the listItems */ public TableRows(props: { entities: Array<ListItem>, columns: Array<ColumnDefinition>, cellUpdated: (newValue) => void, cellUpdatedEvent: (event: React.SyntheticEvent<any>) => void; }): JSX.Element { const {entities, columns, cellUpdated, cellUpdatedEvent} = props; return ( <tbody> { entities.map(function (list) { return ( <this.TableRow key={list.GUID} entity={list} columns={columns} cellUpdated={this.handleCellUpdated} cellUpdatedEvent={this.handleCellUpdatedEvent} /> ); }, this) } </tbody> ); } public render() { const { listItems } = this.props; Log.info("ListItemContainer", "In Render"); return ( <Container testid="columns" size={2} center> <CommandBar items={[{ key: "AddItem", name: "Add an Item", icon: "Add", onClick: this.addListItem }, { key: "DleteAll", name: "DeleteAll", icon: "Delete" }, { key: "Undo All changes", name: "UndoAll", icon: "Undo", onClick: this.undoAll }, { key: "Save All ", name: "Save All", icon: "Save", onClick: this.saveAll }]} /> <table > <thead> <tr> {this.props.columns.map((column) => { return <th key={column.name}>{column.name}</th>; })} </tr> </thead> { <this.TableRows entities={listItems} columns={this.props.columns} cellUpdated={this.handleCellUpdated} cellUpdatedEvent={this.handleCellUpdatedEvent} /> })} </table> </Container> ); } } export default connect( mapStateToProps, mapDispatchToProps )(ListItemContainer);
the_stack
import * as assert from "assert"; import { AccountSASPermissions, AccountSASResourceTypes, AccountSASServices, AnonymousCredential, generateAccountSASQueryParameters, generateQueueSASQueryParameters, QueueSASPermissions, SASProtocol, StorageSharedKeyCredential, QueueServiceClient, newPipeline, QueueClient } from "@azure/storage-queue"; import { configLogger } from "../../src/common/Logger"; import { StoreDestinationArray } from "../../src/common/persistence/IExtentStore"; import QueueConfiguration from "../../src/queue/QueueConfiguration"; import Server from "../../src/queue/QueueServer"; import { EMULATOR_ACCOUNT_KEY, EMULATOR_ACCOUNT_NAME, getUniqueName, rmRecursive, sleep } from "../testutils"; // Set true to enable debug log configLogger(false); describe("Queue SAS test", () => { // TODO: Create a server factory as tests utils const host = "127.0.0.1"; const port = 11001; const metadataDbPath = "__queueTestsStorage__"; const extentDbPath = "__extentTestsStorage__"; const persistencePath = "__queueTestsPersistence__"; const DEFUALT_QUEUE_PERSISTENCE_ARRAY: StoreDestinationArray = [ { locationId: "queueTest", locationPath: persistencePath, maxConcurrency: 10 } ]; const config = new QueueConfiguration( host, port, metadataDbPath, extentDbPath, DEFUALT_QUEUE_PERSISTENCE_ARRAY, false ); const baseURL = `http://${host}:${port}/devstoreaccount1`; const serviceClient = new QueueServiceClient( baseURL, newPipeline( new StorageSharedKeyCredential( EMULATOR_ACCOUNT_NAME, EMULATOR_ACCOUNT_KEY ), { retryOptions: { maxTries: 1 } } ) ); let server: Server; before(async () => { server = new Server(config); await server.start(); }); after(async () => { await server.close(); await rmRecursive(metadataDbPath); await rmRecursive(extentDbPath); await rmRecursive(persistencePath); }); it("generateAccountSASQueryParameters should work @loki", async () => { const now = new Date(); now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server const tmr = new Date(); tmr.setDate(tmr.getDate() + 1); // By default, credential is always the last element of pipeline factories const factories = (serviceClient as any).pipeline.factories; const storageSharedKeyCredential = factories[factories.length - 1]; const sas = generateAccountSASQueryParameters( { expiresOn: tmr, ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, permissions: AccountSASPermissions.parse("rwdlacup"), protocol: SASProtocol.HttpsAndHttp, resourceTypes: AccountSASResourceTypes.parse("sco").toString(), services: AccountSASServices.parse("btqf").toString(), startsOn: now, version: "2019-02-02" }, storageSharedKeyCredential as StorageSharedKeyCredential ).toString(); const sasURL = `${serviceClient.url}?${sas}`; const serviceClientWithSAS = new QueueServiceClient( sasURL, newPipeline(new AnonymousCredential()) ); await serviceClientWithSAS.getProperties(); }); it("generateAccountSASQueryParameters should not work with invalid permission @loki", async () => { const tmr = new Date(); tmr.setDate(tmr.getDate() + 1); // By default, credential is always the last element of pipeline factories const factories = (serviceClient as any).pipeline.factories; const storageSharedKeyCredential = factories[factories.length - 1]; const sas = generateAccountSASQueryParameters( { expiresOn: tmr, permissions: AccountSASPermissions.parse("wdlcup"), resourceTypes: AccountSASResourceTypes.parse("sco").toString(), services: AccountSASServices.parse("btqf").toString() }, storageSharedKeyCredential as StorageSharedKeyCredential ).toString(); const sasURL = `${serviceClient.url}?${sas}`; const serviceClientWithSAS = new QueueServiceClient( sasURL, newPipeline(new AnonymousCredential()) ); let error; try { await serviceClientWithSAS.getProperties(); } catch (err) { error = err; } assert.ok(error); assert.deepEqual(error.statusCode, 403); }); it("generateAccountSASQueryParameters should not work with invalid service @loki", async () => { const tmr = new Date(); tmr.setDate(tmr.getDate() + 1); // By default, credential is always the last element of pipeline factories const factories = (serviceClient as any).pipeline.factories; const storageSharedKeyCredential = factories[factories.length - 1]; const sas = generateAccountSASQueryParameters( { expiresOn: tmr, permissions: AccountSASPermissions.parse("rwdlacup"), resourceTypes: AccountSASResourceTypes.parse("sco").toString(), services: AccountSASServices.parse("btf").toString() }, storageSharedKeyCredential as StorageSharedKeyCredential ).toString(); const sasURL = `${serviceClient.url}?${sas}`; const serviceClientWithSAS = new QueueServiceClient( sasURL, newPipeline(new AnonymousCredential()) ); let error; try { await serviceClientWithSAS.getProperties(); } catch (err) { error = err; } assert.ok(error); assert.deepEqual(error.statusCode, 403); }); it("generateAccountSASQueryParameters should not work with invalid resource type @loki", async () => { const tmr = new Date(); tmr.setDate(tmr.getDate() + 1); // By default, credential is always the last element of pipeline factories const factories = (serviceClient as any).pipeline.factories; const storageSharedKeyCredential = factories[factories.length - 1]; const sas = generateAccountSASQueryParameters( { expiresOn: tmr, ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, permissions: AccountSASPermissions.parse("rwdlacup"), protocol: SASProtocol.HttpsAndHttp, resourceTypes: AccountSASResourceTypes.parse("co").toString(), services: AccountSASServices.parse("btqf").toString(), version: "2019-02-02" }, storageSharedKeyCredential as StorageSharedKeyCredential ).toString(); const sasURL = `${serviceClient.url}?${sas}`; const serviceClientWithSAS = new QueueServiceClient( sasURL, newPipeline(new AnonymousCredential()) ); let error; try { await serviceClientWithSAS.getProperties(); } catch (err) { error = err; } assert.ok(error); assert.deepEqual(error.statusCode, 403); }); it("Create queue should work with write (w) or create (c) permission in account SAS @loki", async () => { const tmr = new Date(); tmr.setDate(tmr.getDate() + 1); // By default, credential is always the last element of pipeline factories const factories = (serviceClient as any).pipeline.factories; const storageSharedKeyCredential = factories[factories.length - 1]; const sas1 = generateAccountSASQueryParameters( { expiresOn: tmr, ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, permissions: AccountSASPermissions.parse("rdlacup"), protocol: SASProtocol.HttpsAndHttp, resourceTypes: AccountSASResourceTypes.parse("co").toString(), services: AccountSASServices.parse("btqf").toString(), version: "2019-02-02" }, storageSharedKeyCredential as StorageSharedKeyCredential ).toString(); const sas2 = generateAccountSASQueryParameters( { expiresOn: tmr, ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, permissions: AccountSASPermissions.parse("rwdlaup"), protocol: SASProtocol.HttpsAndHttp, resourceTypes: AccountSASResourceTypes.parse("co").toString(), services: AccountSASServices.parse("btqf").toString(), version: "2019-02-02" }, storageSharedKeyCredential as StorageSharedKeyCredential ).toString(); const sasURL1 = `${serviceClient.url}?${sas1}`; const sasURL2 = `${serviceClient.url}?${sas2}`; const serviceClientWithSAS1 = new QueueServiceClient( sasURL1, newPipeline(new AnonymousCredential()) ); const serviceClientWithSAS2 = new QueueServiceClient( sasURL2, newPipeline(new AnonymousCredential()) ); const queueName1 = getUniqueName("queue1"); const queueName2 = getUniqueName("queue2"); const queueClient1 = serviceClientWithSAS1.getQueueClient(queueName1); await queueClient1.create(); const queueClient2 = serviceClientWithSAS2.getQueueClient(queueName2); await queueClient2.create(); await queueClient1.delete(); await queueClient2.delete(); }); it("Create queue shouldn't work without write (w) and create (c) permission in account SAS @loki", async () => { const tmr = new Date(); tmr.setDate(tmr.getDate() + 1); // By default, credential is always the last element of pipeline factories const factories = (serviceClient as any).pipeline.factories; const storageSharedKeyCredential = factories[factories.length - 1]; const sas = generateAccountSASQueryParameters( { expiresOn: tmr, ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, permissions: AccountSASPermissions.parse("rdlaup"), protocol: SASProtocol.HttpsAndHttp, resourceTypes: AccountSASResourceTypes.parse("co").toString(), services: AccountSASServices.parse("btqf").toString(), version: "2019-02-02" }, storageSharedKeyCredential as StorageSharedKeyCredential ).toString(); const sasURL = `${serviceClient.url}?${sas}`; const serviceClientWithSAS = new QueueServiceClient( sasURL, newPipeline(new AnonymousCredential()) ); const queueName = getUniqueName("queue"); const queueClient = serviceClientWithSAS.getQueueClient(queueName); // this copy should throw 403 error let error; try { await queueClient.create(); } catch (err) { error = err; } assert.deepEqual(error.statusCode, 403); assert.ok(error !== undefined); }); it("generateAccountSASQueryParameters should work for queue @loki", async () => { const now = new Date(); now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server const tmr = new Date(); tmr.setDate(tmr.getDate() + 1); // By default, credential is always the last element of pipeline factories const factories = (serviceClient as any).pipeline.factories; const storageSharedKeyCredential = factories[factories.length - 1]; const sas = generateAccountSASQueryParameters( { expiresOn: tmr, ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, permissions: AccountSASPermissions.parse("rwdlcaup"), protocol: SASProtocol.HttpsAndHttp, resourceTypes: AccountSASResourceTypes.parse("co").toString(), services: AccountSASServices.parse("btqf").toString(), version: "2019-02-02" }, storageSharedKeyCredential as StorageSharedKeyCredential ).toString(); const sasURL = `${serviceClient.url}?${sas}`; const serviceClientWithSAS = new QueueServiceClient( sasURL, newPipeline(new AnonymousCredential()) ); const queueName = getUniqueName("queue"); const queueClient = serviceClientWithSAS.getQueueClient(queueName); await queueClient.create(); const properties = await queueClient.getProperties(); await queueClient.setMetadata(properties.metadata); await queueClient.delete(); }); it("Get/Set ACL with AccountSAS is not allowed @loki", async () => { const now = new Date(); now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server const tmr = new Date(); tmr.setDate(tmr.getDate() + 1); // By default, credential is always the last element of pipeline factories const factories = (serviceClient as any).pipeline.factories; const storageSharedKeyCredential = factories[factories.length - 1]; const queueName = getUniqueName("queue"); const queueClient = serviceClient.getQueueClient(queueName); await queueClient.create(); const sas = generateAccountSASQueryParameters( { expiresOn: tmr, ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, permissions: AccountSASPermissions.parse("rwdlcaup"), protocol: SASProtocol.HttpsAndHttp, resourceTypes: AccountSASResourceTypes.parse("co").toString(), services: AccountSASServices.parse("btqf").toString(), version: "2019-02-02" }, storageSharedKeyCredential as StorageSharedKeyCredential ).toString(); const sasURL = `${serviceClient.url}?${sas}`; const serviceClientWithSAS = new QueueServiceClient( sasURL, newPipeline(new AnonymousCredential()) ); const queueClientWithSAS = serviceClientWithSAS.getQueueClient(queueName); let errorGet; try { await queueClientWithSAS.getAccessPolicy(); } catch (err) { errorGet = err; } assert.ok(errorGet); assert.deepEqual(errorGet.statusCode, 403); let errorSet; try { await queueClientWithSAS.setAccessPolicy(); } catch (err) { errorSet = err; } assert.ok(errorSet); assert.deepEqual(errorSet.statusCode, 403); await queueClient.delete(); }); it("generateAccountSASQueryParameters should work for messages @loki", async () => { const now = new Date(); now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server const tmr = new Date(); tmr.setDate(tmr.getDate() + 1); // By default, credential is always the last element of pipeline factories const factories = (serviceClient as any).pipeline.factories; const storageSharedKeyCredential = factories[factories.length - 1]; const queueName = getUniqueName("queue"); const queueClient = serviceClient.getQueueClient(queueName); await queueClient.create(); const sas = generateAccountSASQueryParameters( { expiresOn: tmr, ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, permissions: AccountSASPermissions.parse("rwdlcaup"), protocol: SASProtocol.HttpsAndHttp, resourceTypes: AccountSASResourceTypes.parse("co").toString(), services: AccountSASServices.parse("btqf").toString(), version: "2019-02-02" }, storageSharedKeyCredential as StorageSharedKeyCredential ).toString(); const sasURL = `${serviceClient.url}?${sas}`; const serviceClientWithSAS = new QueueServiceClient( sasURL, newPipeline(new AnonymousCredential()) ); const queueClientWithSAS = serviceClientWithSAS.getQueueClient(queueName); const messageContent = "test text"; await queueClientWithSAS.sendMessage(messageContent); await queueClientWithSAS.sendMessage(messageContent); await queueClientWithSAS.peekMessages(); await queueClientWithSAS.receiveMessages(); await queueClientWithSAS.clearMessages(); let pResult2 = await queueClientWithSAS.peekMessages(); assert.deepStrictEqual(pResult2.peekedMessageItems.length, 0); await queueClient.delete(); }); it("generateAccountSASQueryParameters should work for messages @loki", async () => { const now = new Date(); now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server const tmr = new Date(); tmr.setDate(tmr.getDate() + 1); // By default, credential is always the last element of pipeline factories const factories = (serviceClient as any).pipeline.factories; const storageSharedKeyCredential = factories[factories.length - 1]; const queueName = getUniqueName("queue"); const queueClient = serviceClient.getQueueClient(queueName); await queueClient.create(); const sas = generateAccountSASQueryParameters( { expiresOn: tmr, ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, permissions: AccountSASPermissions.parse("rwdlcaup"), protocol: SASProtocol.HttpsAndHttp, resourceTypes: AccountSASResourceTypes.parse("co").toString(), services: AccountSASServices.parse("btqf").toString(), version: "2019-02-02" }, storageSharedKeyCredential as StorageSharedKeyCredential ).toString(); const sasURL = `${serviceClient.url}?${sas}`; const serviceClientWithSAS = new QueueServiceClient( sasURL, newPipeline(new AnonymousCredential()) ); const queueClientWithSAS = serviceClientWithSAS.getQueueClient(queueName); const messageContent = "test text"; await queueClientWithSAS.sendMessage(messageContent); await queueClientWithSAS.sendMessage(messageContent); await queueClientWithSAS.peekMessages(); await queueClientWithSAS.receiveMessages(); await queueClientWithSAS.clearMessages(); let pResult2 = await queueClientWithSAS.peekMessages(); assert.deepStrictEqual(pResult2.peekedMessageItems.length, 0); await queueClient.delete(); }); it("generateQueueSASQueryParameters should work for queue @loki", async () => { const now = new Date(); now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server const tmr = new Date(); tmr.setDate(tmr.getDate() + 1); // By default, credential is always the last element of pipeline factories const factories = (serviceClient as any).pipeline.factories; const storageSharedKeyCredential = factories[factories.length - 1]; const queueName = getUniqueName("queue"); const queueClient = serviceClient.getQueueClient(queueName); await queueClient.create(); const queueSAS = generateQueueSASQueryParameters( { queueName, expiresOn: tmr, ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, permissions: QueueSASPermissions.parse("raup"), protocol: SASProtocol.HttpsAndHttp, startsOn: now, version: "2019-02-02" }, storageSharedKeyCredential as StorageSharedKeyCredential ); const sasURL = `${queueClient.url}?${queueSAS}`; const queueClientWithSAS = new QueueClient( sasURL, newPipeline(new AnonymousCredential()) ); await queueClientWithSAS.getProperties(); await queueClient.delete(); }); it("generateQueueSASQueryParameters should work for messages @loki", async () => { const now = new Date(); now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server const tmr = new Date(); tmr.setDate(tmr.getDate() + 1); // By default, credential is always the last element of pipeline factories const factories = (serviceClient as any).pipeline.factories; const storageSharedKeyCredential = factories[factories.length - 1]; const queueName = getUniqueName("queue"); const queueClient = serviceClient.getQueueClient(queueName); await queueClient.create(); const queueSAS = generateQueueSASQueryParameters( { queueName: queueName, expiresOn: tmr, ipRange: { start: "0.0.0.0", end: "255.255.255.255" }, permissions: QueueSASPermissions.parse("raup"), protocol: SASProtocol.HttpsAndHttp, startsOn: now, version: "2016-05-31" }, storageSharedKeyCredential as StorageSharedKeyCredential ); const messageContent = "Hello World!"; const sasURLForMessages = `${queueClient.url}?${queueSAS}`; const queueClientWithSAS = new QueueClient( sasURLForMessages, newPipeline(new AnonymousCredential()) ); const enqueueResult = await queueClientWithSAS.sendMessage(messageContent); let pResult = await queueClientWithSAS.peekMessages(); assert.deepStrictEqual(pResult.peekedMessageItems.length, 1); const sasURLForMessageId = `${queueClientWithSAS.url}?${queueSAS}`; const queueIdClientWithSAS = new QueueClient( sasURLForMessageId, newPipeline(new AnonymousCredential()) ); await queueIdClientWithSAS.deleteMessage( enqueueResult.messageId, enqueueResult.popReceipt ); pResult = await queueClient.peekMessages(); assert.deepStrictEqual(pResult.peekedMessageItems.length, 0); await queueClient.delete(); }); it("generateQueueSASQueryParameters should work for queue with access policy @loki", async () => { const now = new Date(); now.setMinutes(now.getMinutes() - 5); // Skip clock skew with server const tmr = new Date(); tmr.setDate(tmr.getDate() + 1); // By default, credential is always the last element of pipeline factories const factories = (serviceClient as any).pipeline.factories; const storageSharedKeyCredential = factories[factories.length - 1]; const queueName = getUniqueName("queue"); const queueClient = serviceClient.getQueueClient(queueName); await queueClient.create(); const id = "unique-id"; await queueClient.setAccessPolicy([ { accessPolicy: { expiresOn: tmr, permissions: QueueSASPermissions.parse("raup").toString(), startsOn: now }, id } ]); const queueSAS = generateQueueSASQueryParameters( { queueName, identifier: id }, storageSharedKeyCredential as StorageSharedKeyCredential ); const sasURL = `${queueClient.url}?${queueSAS}`; const queueClientWithSAS = new QueueClient( sasURL, newPipeline(new AnonymousCredential()) ); const messageContent = "hello"; const eResult = await queueClientWithSAS.sendMessage(messageContent); assert.ok(eResult.messageId); const pResult = await queueClientWithSAS.peekMessages(); assert.deepStrictEqual( pResult.peekedMessageItems[0].messageText, messageContent ); const dResult = await queueClientWithSAS.receiveMessages({ visibilitytimeout: 1 }); assert.deepStrictEqual( dResult.receivedMessageItems[0].messageText, messageContent ); await sleep(2 * 1000); const sasURLForMessage = `${queueClientWithSAS.url}?${queueSAS}`; const queueIdClientWithSAS = new QueueClient( sasURLForMessage, newPipeline(new AnonymousCredential()) ); const deleteResult = await queueIdClientWithSAS.deleteMessage( dResult.receivedMessageItems[0].messageId, dResult.receivedMessageItems[0].popReceipt ); assert.ok(deleteResult.requestId); }); });
the_stack
import React from 'react'; import { composeRefs } from '@radix-ui/react-compose-refs'; import { range } from 'utils'; import { Children, createContext, CSSProperties, ForwardedRef, forwardRef, isValidElement, memo, ReactElement, ReactNode, Ref, useCallback, useContext, useImperativeHandle, useLayoutEffect, useMemo, useRef, } from 'react'; import { WindowScroller } from 'react-virtualized'; import { ListChildComponentProps, VariableSizeList } from 'react-window'; import styled from 'styled-components'; import { InputField } from '..'; import { useHover } from '../hooks/useHover'; import { mergeEventHandlers } from '../hooks/mergeEventHandlers'; import ContextMenu from './ContextMenu'; import { MenuItem } from './internal/Menu'; import ScrollArea from './ScrollArea'; import * as Sortable from './Sortable'; import { isLeftButtonClicked } from '../utils/mouseEvent'; import { SpacerHorizontal } from 'components'; export type ListRowMarginType = 'none' | 'top' | 'bottom' | 'vertical'; export type ListRowPosition = 'only' | 'first' | 'middle' | 'last'; type Size = { width: number; height: number }; type PressEventName = 'onClick' | 'onPointerDown'; type ListRowContextValue = { marginType: ListRowMarginType; selectedPosition: ListRowPosition; sortable: boolean; expandable: boolean; indentation: number; pressEventName: PressEventName; }; export const ListRowContext = createContext<ListRowContextValue>({ marginType: 'none', selectedPosition: 'only', sortable: false, expandable: true, indentation: 12, pressEventName: 'onClick', }); /* ---------------------------------------------------------------------------- * RowTitle * ------------------------------------------------------------------------- */ const ListViewRowTitle = styled.span(({ theme }) => ({ flex: '1 1 0', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'pre', })); /* ---------------------------------------------------------------------------- * EditableRowTitle * ------------------------------------------------------------------------- */ interface EditableRowProps { value: string; onSubmitEditing: (value: string) => void; autoFocus: boolean; } function ListViewEditableRowTitle({ value, onSubmitEditing, autoFocus, }: EditableRowProps) { const inputRef = useRef<HTMLInputElement | null>(null); useLayoutEffect(() => { const element = inputRef.current; if (!element || !autoFocus) return; // Calling `focus` is necessary, in addition to `select`, to ensure // the `onBlur` fires correctly. element.focus(); setTimeout(() => { element.select(); }, 0); }, [autoFocus]); return ( <InputField.Input ref={inputRef} variant="bare" value={value} onSubmit={onSubmitEditing} allowSubmittingWithSameValue /> ); } function getPositionMargin(marginType: ListRowMarginType) { return { top: marginType === 'top' || marginType === 'vertical' ? 8 : 0, bottom: marginType === 'bottom' || marginType === 'vertical' ? 8 : 0, }; } /* ---------------------------------------------------------------------------- * Row * ------------------------------------------------------------------------- */ const RowContainer = styled.div<{ marginType: ListRowMarginType; selected: boolean; selectedPosition: ListRowPosition; disabled: boolean; hovered: boolean; isSectionHeader: boolean; showsActiveState: boolean; }>( ({ theme, marginType, selected, selectedPosition, disabled, hovered, isSectionHeader, showsActiveState, }) => { const margin = getPositionMargin(marginType); return { ...theme.textStyles.small, ...(isSectionHeader && { fontWeight: 500 }), flex: '0 0 auto', userSelect: 'none', cursor: 'default', borderRadius: '4px', paddingTop: '6px', paddingRight: '12px', paddingBottom: '6px', paddingLeft: '12px', marginLeft: '8px', marginRight: '8px', marginTop: `${margin.top}px`, marginBottom: `${margin.bottom}px`, color: theme.colors.textMuted, ...(isSectionHeader && { backgroundColor: theme.colors.listView.raisedBackground, }), ...(disabled && { color: theme.colors.textDisabled, }), ...(selected && { color: 'white', backgroundColor: theme.colors.primary, }), display: 'flex', alignItems: 'center', ...(selected && !isSectionHeader && (selectedPosition === 'middle' || selectedPosition === 'last') && { borderTopRightRadius: '0px', borderTopLeftRadius: '0px', }), ...(selected && !isSectionHeader && (selectedPosition === 'middle' || selectedPosition === 'first') && { borderBottomRightRadius: '0px', borderBottomLeftRadius: '0px', }), position: 'relative', ...(hovered && { boxShadow: `0 0 0 1px ${theme.colors.primary}`, }), ...(showsActiveState && { '&:active': { backgroundColor: selected ? theme.colors.primaryLight : theme.colors.activeBackground, }, }), }; }, ); export const DragIndicatorElement = styled.div<{ relativeDropPosition: Sortable.RelativeDropPosition; offsetLeft: number; }>(({ theme, relativeDropPosition, offsetLeft }) => ({ zIndex: 1, position: 'absolute', borderRadius: '3px', ...(relativeDropPosition === 'inside' ? { inset: 2, boxShadow: `0 0 0 1px ${theme.colors.sidebar.background}, 0 0 0 3px ${theme.colors.dragOutline}`, } : { top: relativeDropPosition === 'above' ? -3 : undefined, bottom: relativeDropPosition === 'below' ? -3 : undefined, left: offsetLeft, right: 0, height: 6, background: theme.colors.primary, border: `2px solid white`, boxShadow: '0 0 2px rgba(0,0,0,0.5)', }), })); export interface ListViewClickInfo { shiftKey: boolean; altKey: boolean; metaKey: boolean; ctrlKey: boolean; } export interface ListViewRowProps<MenuItemType extends string = string> { id?: string; selected?: boolean; depth?: number; disabled?: boolean; draggable?: boolean; hovered?: boolean; sortable?: boolean; onPress?: (info: ListViewClickInfo) => void; onDoubleClick?: () => void; onHoverChange?: (isHovering: boolean) => void; children?: ReactNode; isSectionHeader?: boolean; menuItems?: MenuItem<MenuItemType>[]; onSelectMenuItem?: (value: MenuItemType) => void; onContextMenu?: () => void; } const ListViewRow = forwardRef(function ListViewRow< MenuItemType extends string, >( { id, selected = false, depth = 0, disabled = false, hovered = false, isSectionHeader = false, sortable: overrideSortable, onPress, onDoubleClick, onHoverChange, children, menuItems, onContextMenu, onSelectMenuItem, }: ListViewRowProps<MenuItemType>, forwardedRef: ForwardedRef<HTMLElement>, ) { const { marginType, selectedPosition, sortable, indentation, pressEventName, } = useContext(ListRowContext); const { hoverProps } = useHover({ onHoverChange, }); const handlePress = useCallback( (event: React.MouseEvent) => { // We use preventDefault as a hack to mark this event as handled. We check for // this in the ListView.Root. We can't stopPropagation here or existing ContextMenus // won't close (onPointerDownOutside won't fire). event.preventDefault(); if (!isLeftButtonClicked(event)) return; onPress?.(event); }, [onPress], ); const handleDoubleClick = useCallback( (event: React.MouseEvent) => { event.stopPropagation(); onDoubleClick?.(); }, [onDoubleClick], ); const renderContent = ( { relativeDropPosition, ...renderProps }: React.ComponentProps<typeof RowContainer> & { relativeDropPosition?: Sortable.RelativeDropPosition; }, ref: Ref<HTMLElement>, ) => { const element = ( <RowContainer ref={ref} onContextMenu={onContextMenu} isSectionHeader={isSectionHeader} id={id} {...hoverProps} onDoubleClick={handleDoubleClick} marginType={marginType} disabled={disabled} hovered={hovered} selected={selected} selectedPosition={selectedPosition} showsActiveState={pressEventName === 'onClick'} aria-selected={selected} {...renderProps} {...mergeEventHandlers( { onPointerDown: renderProps.onPointerDown }, { [pressEventName]: handlePress }, )} > {relativeDropPosition && ( <DragIndicatorElement relativeDropPosition={relativeDropPosition} offsetLeft={33 + depth * indentation} /> )} {depth > 0 && <SpacerHorizontal size={depth * indentation} />} {children} </RowContainer> ); if (menuItems && onSelectMenuItem) { return ( <ContextMenu<MenuItemType> items={menuItems} onSelect={onSelectMenuItem} > {element} </ContextMenu> ); } return element; }; if (sortable && id) { return ( <Sortable.Item<HTMLElement> id={id} disabled={overrideSortable === false}> {({ ref: sortableRef, ...sortableProps }) => renderContent(sortableProps, composeRefs(sortableRef, forwardedRef)) } </Sortable.Item> ); } return renderContent({}, forwardedRef); }); /* ---------------------------------------------------------------------------- * VirtualizedListRow * ------------------------------------------------------------------------- */ const RenderItemContext = createContext<(index: number) => ReactNode>( () => null, ); const VirtualizedListRow = memo(function VirtualizedListRow({ index, style, }: ListChildComponentProps) { const renderItem = useContext(RenderItemContext); return ( <div key={index} style={style}> {renderItem(index)} </div> ); }); /* ---------------------------------------------------------------------------- * VirtualizedList * ------------------------------------------------------------------------- */ interface VirtualizedListProps<T> { size: Size; scrollElement: HTMLDivElement; items: T[]; getItemHeight: (index: number) => number; keyExtractor: (index: number) => string; renderItem: (index: number) => ReactNode; } export interface IVirtualizedList { scrollToIndex(index: number): void; } const VirtualizedListInner = forwardRef(function VirtualizedListInner<T>( { size, scrollElement, items, getItemHeight, keyExtractor, renderItem, }: VirtualizedListProps<T>, ref: ForwardedRef<IVirtualizedList>, ) { const listRef = useRef<VariableSizeList<T> | null>(null); useImperativeHandle(ref, () => ({ scrollToIndex(index) { listRef.current?.scrollToItem(index); }, })); useLayoutEffect(() => { listRef.current?.resetAfterIndex(0); }, [ // When items change, we need to re-render the virtualized list, // since it doesn't currently support row height changes items, ]); // Internally, react-virtualized updates these properties. We always want // to use our custom scroll element, so we override them. It may update // overflowX/Y individually in addition to `overflow`, so we include all 3. const listStyle = useMemo( (): CSSProperties => ({ overflowX: 'initial', overflowY: 'initial', overflow: 'initial', }), [], ); return ( <RenderItemContext.Provider value={renderItem}> <WindowScroller scrollElement={scrollElement} style={useMemo(() => ({ flex: '1 1 auto' }), [])} > {useCallback( ({ registerChild, onChildScroll, scrollTop }) => ( <div ref={registerChild}> <VariableSizeList<T> ref={listRef} // The list won't update on scroll unless we force it to by changing key key={scrollTop} style={listStyle} itemKey={keyExtractor} onScroll={({ scrollOffset }) => { onChildScroll({ scrollTop: scrollOffset }); }} initialScrollOffset={scrollTop} width={size.width} height={size.height} itemCount={items.length} itemSize={getItemHeight} estimatedItemSize={31} > {VirtualizedListRow} </VariableSizeList> </div> ), [ listStyle, keyExtractor, size.width, size.height, items.length, getItemHeight, ], )} </WindowScroller> </RenderItemContext.Provider> ); }); const VirtualizedList = memo( VirtualizedListInner, ) as typeof VirtualizedListInner; /* ---------------------------------------------------------------------------- * Root * ------------------------------------------------------------------------- */ const RootContainer = styled.div<{ scrollable?: boolean }>( ({ theme, scrollable }) => ({ flex: scrollable ? '1 0 0' : '0 0 auto', display: 'flex', flexDirection: 'column', flexWrap: 'nowrap', color: theme.colors.textMuted, }), ); export type ItemInfo = { isDragging: boolean; }; type ChildrenProps = { children: ReactNode; }; type RenderProps<T> = { data: T[]; renderItem: (item: T, index: number, info: ItemInfo) => ReactNode; keyExtractor: (item: T, index: number) => string; sortable?: boolean; virtualized?: Size; }; type ListViewRootProps = { onPress?: () => void; scrollable?: boolean; expandable?: boolean; onMoveItem?: ( sourceIndex: number, destinationIndex: number, position: Sortable.RelativeDropPosition, ) => void; indentation?: number; acceptsDrop?: Sortable.DropValidator; pressEventName?: PressEventName; }; const ListViewRootInner = forwardRef(function ListViewRootInner<T>( { onPress, scrollable = false, expandable = true, sortable = false, onMoveItem, indentation = 12, acceptsDrop, data, renderItem, keyExtractor, virtualized, pressEventName = 'onClick', }: RenderProps<T> & ListViewRootProps, forwardedRef: ForwardedRef<IVirtualizedList>, ) { const handleClick = useCallback( (event: React.MouseEvent) => { if ( event.target instanceof HTMLElement && event.target.classList.contains('scroll-component') ) return; // As a hack, we call preventDefault in a row if the event was handled. // If the event wasn't handled already, we call onPress here. if (!event.isDefaultPrevented()) { onPress?.(); } }, [onPress], ); const renderChild = useCallback( (index: number) => renderItem(data[index], index, { isDragging: false }), [data, renderItem], ); const renderOverlay = useCallback( (index: number) => renderItem(data[index], index, { isDragging: true }), [renderItem, data], ); const getItemContextValue = useCallback( (i: number): ListRowContextValue | undefined => { const current = renderChild(i); if (!isValidElement(current)) return; const prevChild = i - 1 >= 0 && renderChild(i - 1); const nextChild = i + 1 < data.length && renderChild(i + 1); const next = isValidElement(nextChild) ? nextChild : undefined; const prev = isValidElement(prevChild) ? prevChild : undefined; const hasMarginTop = !prev; const hasMarginBottom = !next || current.props.isSectionHeader || (next && next.props.isSectionHeader); let marginType: ListRowMarginType; if (hasMarginTop && hasMarginBottom) { marginType = 'vertical'; } else if (hasMarginBottom) { marginType = 'bottom'; } else if (hasMarginTop) { marginType = 'top'; } else { marginType = 'none'; } let selectedPosition: ListRowPosition = 'only'; if (current.props.selected) { const nextSelected = next && !next.props.isSectionHeader && next.props.selected; const prevSelected = prev && !prev.props.isSectionHeader && prev.props.selected; if (nextSelected && prevSelected) { selectedPosition = 'middle'; } else if (nextSelected && !prevSelected) { selectedPosition = 'first'; } else if (!nextSelected && prevSelected) { selectedPosition = 'last'; } } return { marginType, selectedPosition, sortable, expandable, indentation, pressEventName, }; }, [ renderChild, data.length, sortable, expandable, indentation, pressEventName, ], ); const renderWrappedChild = useCallback( (index: number) => { const contextValue = getItemContextValue(index); const current = renderChild(index); if (!contextValue || !isValidElement(current)) return null; return ( <ListRowContext.Provider key={current.key} value={contextValue}> {current} </ListRowContext.Provider> ); }, [getItemContextValue, renderChild], ); const ids = useMemo(() => data.map(keyExtractor), [keyExtractor, data]); const withSortable = (children: ReactNode) => sortable ? ( <Sortable.Root onMoveItem={onMoveItem} keys={ids} renderOverlay={renderOverlay} acceptsDrop={acceptsDrop} > {children} </Sortable.Root> ) : ( children ); const withScrollable = ( children: (scrollElementRef: HTMLDivElement | null) => ReactNode, ) => (scrollable ? <ScrollArea>{children}</ScrollArea> : children(null)); const getItemHeight = useCallback( (index: number) => { const child = getItemContextValue(index); const margin = child?.marginType ? getPositionMargin(child.marginType) : { top: 0, bottom: 0 }; const height = margin.top + 31 + margin.bottom; return height; }, [getItemContextValue], ); const getKey = useCallback( (index: number) => keyExtractor(data[index], index), [data, keyExtractor], ); return ( <RootContainer {...{ [pressEventName]: handleClick, }} scrollable={scrollable} > {withScrollable((scrollElementRef: HTMLDivElement | null) => withSortable( virtualized ? ( <VirtualizedList<T> ref={forwardedRef} scrollElement={scrollElementRef!} items={data} size={virtualized} getItemHeight={getItemHeight} keyExtractor={getKey} renderItem={renderWrappedChild} /> ) : ( range(0, data.length).map(renderWrappedChild) ), ), )} </RootContainer> ); }); const ListViewRoot = memo(ListViewRootInner) as typeof ListViewRootInner; const ChildrenListViewInner = forwardRef(function ChildrenListViewInner( { children, ...rest }: ChildrenProps & ListViewRootProps, forwardedRef: ForwardedRef<IVirtualizedList>, ) { const items: ReactElement[] = useMemo( () => Children.toArray(children).flatMap((child) => isValidElement(child) ? [child] : [], ), [children], ); return ( <ListViewRoot ref={forwardedRef} {...rest} data={items} keyExtractor={useCallback( ({ key }: { key: string | number | null }, index: number) => typeof key === 'string' ? key : (key ?? index).toString(), [], )} renderItem={useCallback((item: ReactElement) => item, [])} /> ); }); const ChildrenListView = memo(ChildrenListViewInner); const SimpleListViewInner = forwardRef(function SimpleListView<T = any>( props: (ChildrenProps | RenderProps<T>) & ListViewRootProps, forwardedRef: ForwardedRef<IVirtualizedList>, ) { if ('children' in props) { return <ChildrenListView ref={forwardedRef} {...props} />; } else { return <ListViewRoot ref={forwardedRef} {...props} />; } }); /** * A ListView can be created either with `children` or render props */ const SimpleListView = memo(SimpleListViewInner); export const RowTitle = memo(ListViewRowTitle); export const EditableRowTitle = memo(ListViewEditableRowTitle); export const Row = memo(ListViewRow); export const Root = memo(SimpleListView);
the_stack
import {BackgroundGeolocation} from "./background-geolocation"; import * as utils from "utils/utils"; declare var TSLocationManager: any; declare var TSConfig: any; declare var NSString: any; declare var NSDictionary: any; declare var NSArray: any; declare var NSUTF8StringEncoding: any; declare var CLCircularRegion: any; declare var UIApplication: any; declare var CLAuthorizationStatus: any; declare var TSCurrentPositionRequest: any; declare var TSWatchPositionRequest: any; declare var TSGeofence: any; let TS_LOCATION_TYPE_MOTIONCHANGE = 0; let TS_LOCATION_TYPE_CURRENT = 1; let TS_LOCATION_TYPE_SAMPLE = 2; let emptyFn = () => {}; class Api { private static adapter:any; /** * Configuration Methods */ public static addListener(event:any, success:Function, failure?:Function) { let callback; failure = failure || emptyFn; switch (event) { case 'location': callback = (tsLocation:any) => { let location = this.getJsObjectFromNSDictionary(tsLocation.toDictionary()); success(location); }; this.getAdapter().onLocationFailure(callback, failure); break; case 'motionchange': callback = (tsLocation:any) => { let location = this.getJsObjectFromNSDictionary(tsLocation.toDictionary()); let isMoving = tsLocation.isMoving; success(isMoving, location); }; this.getAdapter().onMotionChange(callback); break; case 'activitychange': callback = (event:any) => { let params = {activity: event.activity, confidence: event.confidence}; success(params); } this.getAdapter().onActivityChange(callback); break; case 'heartbeat': callback = (event:any) => { let location = this.getJsObjectFromNSDictionary(event.location.toDictionary()); let params = {location: location}; success(params); }; this.getAdapter().onHeartbeat(callback); break; case 'geofence': callback = (event:any) => { let params = event.toDictionary().mutableCopy(); params.setObjectForKey(event.location.toDictionary(), "location"); success(this.getJsObjectFromNSDictionary(params)); }; this.getAdapter().onGeofence(callback); break; case 'geofenceschange': callback = (event:any) => { let params = this.getJsObjectFromNSDictionary(event.toDictionary()); success(params); }; this.getAdapter().onGeofencesChange(callback); break; case 'http': callback = (event:any) => { let params = { "success": event.isSuccess, "status": event.statusCode, "responseText": event.responseText }; if (event.isSuccess) { success(params); } else { failure(params); } }; this.getAdapter().onHttp(callback); break; case 'providerchange': callback = (event:any) => { let params = this.getJsObjectFromNSDictionary(event.toDictionary()); success(params); }; this.getAdapter().onProviderChange(callback); break; case 'schedule': callback = (event:any) => { let state = this.getJsObjectFromNSDictionary(event.state); success(state); }; this.getAdapter().onSchedule(callback); break; case 'powersavechange': callback = (event:any) => { success(event.isPowerSaveMode); }; this.getAdapter().onPowerSaveChange(callback); break; case 'enabledchange': callback = (event:any) => { let params = { enabled: event.enabled }; success(params); }; this.getAdapter().onEnabledChange(callback); break; case 'connectivitychange': callback = (event:any) => { let params = { connected: event.hasConnection }; success(params); } this.getAdapter().onConnectivityChange(callback); break; } return callback; } public static removeListener(event:string, callback:Function) { return new Promise((resolve, reject) => { this.getAdapter().removeListenerCallback(event, callback); // It's not possible to remove single event-listener with NativeScript since the native block is wrapped in a Javascript function reject("BackgroundGeolocation#removeListener - Unfortunately it's not possible to remove a single event-listener with NativeScript. You can only remove ALL listeners for a particular event, eg: removeListeners('location')"); }); } public static removeListeners(event?:string) { return new Promise((resolve, reject) => { if (event) { this.getAdapter().removeListenersForEvent(event); } else { this.getAdapter().removeListeners(); } resolve(); }); } public static ready(params:any) { return new Promise((resolve, reject) => { let config = TSConfig.sharedInstance(); if (config.isFirstBoot) { config.updateWithDictionary(params); } else if (params.reset === true) { config.reset(); config.updateWithDictionary(params); } let locationManager = this.getAdapter(); locationManager.ready(); resolve(this.getJsObjectFromNSDictionary(config.toDictionary())); }); } public static configure(params:any) { return new Promise((resolve, reject) => { let config = TSConfig.sharedInstance(); let locationManager = this.getAdapter(); locationManager.configure(params); resolve(this.getJsObjectFromNSDictionary(config.toDictionary())); }); } public static setConfig(params:any) { return new Promise((resolve, reject) => { let config = TSConfig.sharedInstance(); config.updateWithDictionary(params); resolve(this.getJsObjectFromNSDictionary(config.toDictionary())); }); } public static reset(params:any) { return new Promise((resolve, reject) => { let config = TSConfig.sharedInstance(); config.reset(); config.updateWithDictionary(params); resolve(this.getJsObjectFromNSDictionary(config.toDictionary())); }); } public static getState() { return new Promise((resolve, reject) => { let config = TSConfig.sharedInstance(); resolve(this.getJsObjectFromNSDictionary(config.toDictionary())); }); } /** * Tracking Methods */ public static start() { return new Promise((resolve, reject) => { this.getAdapter().start(); let config = TSConfig.sharedInstance(); resolve(this.getJsObjectFromNSDictionary(config.toDictionary())); }); } public static stop(success?:Function, failure?:Function) { return new Promise((resolve, reject) => { this.getAdapter().stop(); let config = TSConfig.sharedInstance(); resolve(this.getJsObjectFromNSDictionary(config.toDictionary())); }); } public static startGeofences(success?:Function, failure?:Function) { return new Promise((resolve, reject) => { this.getAdapter().startGeofences(); let config = TSConfig.sharedInstance(); resolve(this.getJsObjectFromNSDictionary(config.toDictionary())); }); } public static changePace(value: boolean, success?:any, failure?:any) { return new Promise((resolve, reject) => { this.getAdapter().changePace(value); resolve(value); }); } public static startSchedule(success?:Function, failure?:Function) { return new Promise((resolve, reject) => { this.getAdapter().startSchedule(); let config = TSConfig.sharedInstance(); resolve(this.getJsObjectFromNSDictionary(config.toDictionary())); }); } public static stopSchedule(success?:Function, failure?:Function) { return new Promise((resolve, reject) => { this.getAdapter().stopSchedule(); let config = TSConfig.sharedInstance(); resolve(this.getJsObjectFromNSDictionary(config.toDictionary())); }); } public static getCurrentPosition(options:any) { return new Promise((resolve, reject) => { let request = new TSCurrentPositionRequest(); request.success = (tsLocation:any) => { resolve(this.getJsObjectFromNSDictionary(tsLocation.toDictionary())); }; request.failure = (error) => { reject(error); }; if (typeof(options.timeout) === 'number') { request.timeout = options.timeout; } if (typeof(options.maximumAge) === 'number') { request.maximumAge = options.maximumAge; } if (typeof(options.persist) === 'boolean') { request.persist = options.persist; } if (typeof(options.samples) === 'number') { request.samples = options.samples; } if (typeof(options.desiredAccuracy) === 'number') { request.desiredAccuracy = options.desiredAccuracy; } if (typeof(options.extras) === 'object') { request.extras = options.extras; } this.getAdapter().getCurrentPosition(request); }); } public static watchPosition(success:Function, failure:Function, options:any) { let request = new TSWatchPositionRequest(); request.success = (tsLocation:any) => { success(this.getJsObjectFromNSDictionary(tsLocation.toDictionary())); }; request.failure = (error) => { failure(error); }; if (typeof(options.interval) === 'number') { request.interval = options.interval; } if (typeof(options.desiredAccuracy) === 'number') { request.desiredAccuracy = options.desiredAccuracy; } if (typeof(options.persist) === 'boolean') { request.persist = options.persist; } if (typeof(options.extras) === 'object') { request.extras = options.extras; } if (typeof(options.timeout) === 'number') { request.timeout = options.timeout; } this.getAdapter().watchPosition(request); } public static stopWatchPosition(success?:Function, failure?:Function) { return new Promise((resolve, reject) => { this.getAdapter().stopWatchPosition(); resolve(true); }); } public static getOdometer() { return new Promise((resolve, reject) => { resolve(this.getAdapter().getOdometer()); }); } public static setOdometer(value:number) { return new Promise((resolve, reject) => { let request = new TSCurrentPositionRequest(); request.success = (tsLocation:any) => { resolve(this.getJsObjectFromNSDictionary(tsLocation.toDictionary())); } request.failure = (error) => { reject(error) } this.getAdapter().setOdometerRequest(value, request); }); } public static resetOdometer() { return this.setOdometer(0); } /** * HTTP & Persistence Methods */ public static sync() { return new Promise((resolve, reject) => { this.getAdapter().syncFailure((records) => { resolve(this.getJsArrayFromNSArray(records)); }, (error:any) => { reject(error.code); }); }); } public static getLocations(success:Function, failure?:Function) { return new Promise((resolve, reject) => { this.getAdapter().getLocationsFailure((rs:any) => { resolve(this.getJsArrayFromNSArray(rs)); }, (error:any) => { reject(error); }); }); } public static getCount(success: Function) { return new Promise((resolve, reject) => { resolve(this.getAdapter().getCount()); }); } public static insertLocation(data:any) { return new Promise((resolve, reject) => { this.getAdapter().insertLocationSuccessFailure(data, (uuid:string) => { resolve(uuid); }, (error:string) => { reject(error); }); }); } // @deprecated public static clearDatabase() { return this.destroyLocations(); } public static destroyLocations() { return new Promise((resolve, reject) => { this.getAdapter().destroyLocationsFailure(() => { resolve(); }, (error) => { reject(error); }); }); } /** * Geofencing Methods */ public static addGeofence(params:any) { return new Promise((resolve, reject) => { let success = () => { resolve() } let failure = (error) => { reject(error) } let geofence = this.buildGeofence(params); if (geofence) { this.getAdapter().addGeofenceSuccessFailure(geofence, success, failure); } else { reject('Invalid geofence data'); } }); } public static removeGeofence(identifier:string) { return new Promise((resolve, reject) => { let success = () => { resolve() } let failure = (error) => { reject(error) } this.getAdapter().removeGeofenceSuccessFailure(identifier, success, failure); }); } public static addGeofences(geofences?:Array<any>) { return new Promise((resolve, reject) => { let rs = []; for (let n=0,len=geofences.length;n<len;n++) { let geofence = this.buildGeofence(geofences[n]); if (geofence != null) { rs.push(geofence); } else { reject('Invalid geofence data: ' + JSON.stringify(geofences[n])); return; } } let success = () => { resolve() } let failure = (error) => { reject(error) } this.getAdapter().addGeofencesSuccessFailure(rs, success, failure); }); } public static removeGeofences(geofences?:Array<string>) { return new Promise((resolve, reject) => { let success = () => { resolve() } let failure = (error) => { reject(error) } this.getAdapter().removeGeofencesSuccessFailure(geofences, success, failure); }); } public static getGeofences() { return new Promise((resolve, reject) => { this.getAdapter().getGeofencesFailure((geofences:any) => { let rs = []; for (let loop = 0; loop < geofences.count; loop ++) { let geofence = geofences.objectAtIndex(loop); rs.push(this.getJsObjectFromNSDictionary(geofence.toDictionary())); } resolve(rs); }, (error:string) => { reject(error); }); }); } public static startBackgroundTask() { return new Promise((resolve, reject) => { resolve(this.getAdapter().createBackgroundTask()); }); } public static finish(taskId:number) { return new Promise((resolve, reject) => { this.getAdapter().stopBackgroundTask(taskId); resolve(); }); } /** * Logging & Debug methods */ public static playSound(soundId:number) { return new Promise((resolve, reject) => { this.getAdapter().playSound(soundId); resolve(); }); } public static getLog() { return new Promise((resolve, reject) => { let success = (log) => { resolve(log) } let failure = (error) => { reject(error) } this.getAdapter().getLogFailure(success, failure); }); } public static destroyLog() { return new Promise((resolve, reject) => { if (this.getAdapter().destroyLog()) { resolve(); } else { reject(); } }); } public static emailLog(email:string) { return new Promise((resolve, reject) => { let success = () => { resolve() } let failure = (error) => { reject(error) } this.getAdapter().emailLogSuccessFailure(email, success, failure); }); } public static getSensors() { return new Promise((resolve, reject) => { let adapter = this.getAdapter(); let result = { "platform": "ios", "accelerometer": adapter.isAccelerometerAvailable(), "gyroscope": adapter.isGyroAvailable(), "magnetometer": adapter.isMagnetometerAvailable(), "motion_hardware": adapter.isMotionHardwareAvailable() }; resolve(result); }); } public static isPowerSaveMode(success: Function, failure?:Function) { return new Promise((resolve, reject) => { resolve(this.getAdapter().isPowerSaveMode()); }); } public static log(level, msg) { this.getAdapter().logMessage(level, msg); } /** * Private */ private static buildGeofence(params:any) { if (!params.identifier || !params.radius || !params.latitude || !params.longitude) { return null; } let geofence = new TSGeofence(); geofence.identifier = params.identifier; geofence.radius = params.radius; geofence.latitude = params.latitude; geofence.longitude = params.longitude; if (typeof(params.notifyOnEntry) === 'boolean') { geofence.notifyOnEntry = params.notifyOnEntry; } if (typeof(params.notifyOnExit) === 'boolean') { geofence.notifyOnExit = params.notifyOnExit; } if (typeof(params.notifyOnDwell) === 'boolean') { geofence.notifyOnDwell = params.notifyOnDwell; } if (typeof(params.loiteringDelay) === 'number') { geofence.loiteringDelay = params.loiteringDelay; } if (typeof(params.extras) === 'object') { geofence.extras = params.extras; } return geofence; } private static getAdapter() { if (!this.adapter) { let app = utils.ios.getter(UIApplication, UIApplication.sharedApplication); this.adapter = TSLocationManager.sharedInstance(); this.adapter.viewController = app.keyWindow.rootViewController; } return this.adapter; } private static getJsObjectFromNSDictionary(dictionary:any) { let keys = dictionary.allKeys; let result = {}; for (let loop = 0; loop < keys.count; loop++) { let key = keys[loop]; let item = dictionary.objectForKey(key); result[key] = this.getJsObject(item); } return result; } private static getJsArrayFromNSArray(array: any): Array<Object> { let result = []; for (let loop = 0; loop < array.count; loop ++) { result.push(this.getJsObject(array.objectAtIndex(loop))); } return result; } private static getJsObject(object: any): any { if (object instanceof NSDictionary) { return this.getJsObjectFromNSDictionary(object); } if (object instanceof NSArray) { return this.getJsArrayFromNSArray(object); } return object; } } BackgroundGeolocation.mountNativeApi(Api); export {BackgroundGeolocation};
the_stack
import {AuditoryDescription} from '../audio/auditory_description'; import * as L10n from '../l10n/l10n'; import {SpeechRuleEngine} from '../rule_engine/speech_rule_engine'; import * as BaseUtil from './base_util'; import {Debugger} from './debugger'; import {Engine, EngineConst} from './engine'; import {SREError} from './engine'; import {KeyCode} from './event_util'; import {ProcessorFactory} from './processors'; import SystemExternal from './system_external'; import {Variables} from './variables'; /** * Version number. */ export const version: string = Variables.VERSION; /** * Number of open files. */ let files_: number = 0; Engine.registerTest(() => !!!files_); /** * Setup Methods functionality. */ // These are all API interface functions. Therefore, avoid any usage of "this" // in the code. /** * Method to setup and initialize the speech rule engine. Currently the * feature parameter is ignored, however, this could be used to fine tune the * setup. * @param feature An object describing some * setup features. */ export function setupEngine(feature: {[key: string]: boolean|string}) { let engine = Engine.getInstance() as any; // This preserves the possibility to specify default as domain. // < 3.2 this lead to the use of chromevox rules in English. // >= 3.2 this defaults to Mathspeak. It also ensures that in other locales // we // get a meaningful output. if (feature.domain === 'default' && (feature.modality === 'speech' || (!feature.modality || engine.modality === 'speech'))) { feature.domain = 'mathspeak'; } let setIf = (feat: string) => { if (typeof feature[feat] !== 'undefined') { engine[feat] = !!feature[feat]; } }; let setMulti = (feat: string) => { engine[feat] = feature[feat] || engine[feat]; }; setMulti('mode'); configBlocks_(feature); Engine.BINARY_FEATURES.forEach(setIf); Engine.STRING_FEATURES.forEach(setMulti); if (feature.json) { SystemExternal.jsonPath = BaseUtil.makePath(feature.json as string); } if (feature.xpath) { SystemExternal.WGXpath = feature.xpath as string; } engine.setupBrowsers(); L10n.setLocale(); engine.setDynamicCstr(); SpeechRuleEngine.getInstance().updateEngine(); } /** * Reads configuration blocks and adds them to the feature vector. * @param feature An object describing some * setup features. */ function configBlocks_(feature: {[key: string]: boolean|string}) { if (Engine.getInstance().config || Engine.getInstance().mode !== EngineConst.Mode.HTTP) { return; } Engine.getInstance().config = true; let scripts = document.documentElement.querySelectorAll( 'script[type="text/x-sre-config"]'); for (let i = 0, m = scripts.length; i < m; i++) { let inner; try { inner = scripts[i].innerHTML; let config = JSON.parse(inner); for (let f in config) { feature[f] = config[f]; } } catch (err) { Debugger.getInstance().output('Illegal configuration ', inner); } } } /** * Setting engine to async mode once it is ready. */ export function setAsync() { if (!Engine.isReady()) { setTimeout(setAsync, 500); } setupEngine({'mode': EngineConst.Mode.ASYNC}); } /** * Query the engine setup. * @return Object vector with all engine feature * values. */ export function engineSetup(): {[key: string]: boolean|string} { let engineFeatures = ['mode'].concat(Engine.STRING_FEATURES, Engine.BINARY_FEATURES); let engine = Engine.getInstance() as any; let features: {[key: string]: string|boolean} = {}; engineFeatures.forEach(function(x) { features[x] = engine[x]; }); features.json = SystemExternal.jsonPath; features.xpath = SystemExternal.WGXpath; features.rules = engine.ruleSets.slice(); return features; } /** * @return True if engine is ready, i.e., unicode file for the current * locale has been loaded. */ export function engineReady(): boolean { return Engine.isReady(); } // Naming convention: // Input is either an XML expression as a string or from a file. // Output: // toSpeech: Aural rendering string. // toSemantic: XML of semantic tree. // toJson: Json version of the semantic tree. // toEnriched: Enriched MathML node. // toDescription: List of auditory descriptions. // Output for the file version are strings. // TODO: (sorge) Need an async versions of these. /** * Main function to translate expressions into auditory descriptions. * @param expr Processes a given XML expression for translation. * @return The aural rendering of the expression. */ export function toSpeech(expr: string): string { return processString('speech', expr); } /** * Function to translate MathML string into Semantic Tree. * @param expr Processes a given MathML expression for translation. * @return The semantic tree as Xml. */ export function toSemantic(expr: string): Node { return processString('semantic', expr); } /** * Function to translate MathML string into JSON version of the Semantic Tree. * @param expr Processes a given MathML expression for translation. * @return The semantic tree as Json. */ // TODO (TS): Define the correct JSONType somewhere. export function toJson(expr: string): any { return processString('json', expr); } /** * Main function to translate expressions into auditory descriptions. * @param expr Processes a given Xml expression for translation. * @return The auditory descriptions. */ export function toDescription(expr: string): AuditoryDescription[] { return processString('description', expr); } /** * Function to translate MathML string into semantically enriched MathML. * @param expr Processes a given MathML expression for translation. * @return The enriched MathML node. */ export function toEnriched(expr: string): Element { return processString('enriched', expr); } /** * Processes an input string with the given processor. * @param processor The name of the processor to call. * @param input The input string. * @return The computed data structure. */ function processString<T>(processor: string, input: string): T { return ProcessorFactory.process(processor, input); } export namespace file { /** * Reads an xml expression from a file and returns its aural rendering to a * file. * @param input The input filename. * @param opt_output The output filename if one is given. */ export function toSpeech(input: string, opt_output?: string) { processFile('speech', input, opt_output); } /** * Reads an xml expression from a file and returns the XML for the semantic * tree to a file. * @param input The input filename. * @param opt_output The output filename if one is given. */ export function toSemantic(input: string, opt_output?: string) { processFile('semantic', input, opt_output); } /** * Function to translate MathML string into JSON version of the Semantic Tree * to a file. * @param input The input filename. * @param opt_output The output filename if one is given. */ export function toJson(input: string, opt_output?: string) { processFile('json', input, opt_output); } /** * Main function to translate expressions into auditory descriptions * a file. * @param input The input filename. * @param opt_output The output filename if one is given. */ export function toDescription(input: string, opt_output?: string) { processFile('description', input, opt_output); } /** * Function to translate MathML string into semantically enriched MathML in a * file. * @param input The input filename. * @param opt_output The output filename if one is given. */ export function toEnriched(input: string, opt_output?: string) { processFile('enriched', input, opt_output); } /** * Reads an xml expression from a file, processes with the given function and * returns the result either to a file or to stdout. * @param processor The name of the processor to call. * @param input The input filename. * @param opt_output The output filename if one is given. */ export function processFile( processor: string, input: string, opt_output?: string) { if (!Engine.isReady()) { setTimeout(() => processFile(processor, input, opt_output), 100); return; } if (Engine.getInstance().mode === EngineConst.Mode.SYNC) { processFileSync_(processor, input, opt_output); return; } processFileAsync_(processor, input, opt_output); } } /** * Reads an xml expression from a file. Throws exception if file does not * exist. * @param file The input filename. * @return The input string read from file. */ function inputFileSync_(file: string): string { let expr; try { expr = SystemExternal.fs.readFileSync(file, {encoding: 'utf8'}); } catch (err) { throw new SREError('Can not open file: ' + file); } return expr; } /** * Reads an xml expression from a file, processes with the given function and * returns the result either to a file or to stdout in synchronous mode. * @param processor The name of the processor. * @param input The input filename. * @param opt_output The output filename if one is given. */ function processFileSync_( processor: string, input: string, opt_output?: string) { let expr = inputFileSync_(input); let result = ProcessorFactory.output(processor, expr); if (!opt_output) { console.info(result); return; } try { SystemExternal.fs.writeFileSync(opt_output, result); } catch (err) { throw new SREError('Can not write to file: ' + opt_output); } } /** * Reads an xml expression from a file. Throws exception if file does not * exist. * @param file The input filename. * @param callback The callback to apply to the input. */ function inputFileAsync_(file: string, callback: (p1: string) => any) { SystemExternal.fs.readFile( file, {encoding: 'utf8'}, (err: Error, data: any) => { if (err) { throw new SREError('Can not open file: ' + file); } callback(data); }); } /** * Reads an xml expression from a file, processes with the given function and * returns the result either to a file or to stdout in asynchronous mode. * @param processor The name of the processor. * @param input The input filename. * @param opt_output The output filename if one is given. */ function processFileAsync_( processor: string, input: string, opt_output?: string) { files_++; inputFileAsync_( input, (expr) => { let result = ProcessorFactory.output(processor, expr); if (!opt_output) { console.info(result); files_--; return; } SystemExternal.fs.writeFile(opt_output, result, (err: Error) => { if (err) { files_--; throw new SREError('Can not write to file: ' + opt_output); } }); files_--; }); } // These are still considered experimental. /** * Walk a math expression provided by an external system. * @param expr The string containing a MathML representation. * @return The initial speech string for that expression. */ export function walk(expr: string): string { return ProcessorFactory.output('walker', expr); } /** * Moves in the math expression that is currently being walked. * @param direction The direction of the move * given either as string or keycode. * @return The speech string generated by the walk. Null if a boundary * is hit. */ export function move(direction: KeyCode|string): string|null { return ProcessorFactory.keypress('move', direction); } /** * A clean exit method, that ensures all file processes are completed. * @param opt_value The exit value. Defaults to 0. */ export function exit(opt_value?: number) { let value = opt_value || 0; if (!value && !Engine.isReady()) { setTimeout(() => exit(value), 100); return; } process.exit(value); } if (SystemExternal.documentSupported) { setupEngine({'mode': EngineConst.Mode.HTTP}); } else { // Currently we only allow for sync. setupEngine({'mode': EngineConst.Mode.SYNC}); }
the_stack
import { Button, ButtonGroup, Card, CardContent, Divider, Grid, MenuItem, Skeleton, Tab, Tabs, Typography } from '@mui/material'; import { Suspense, useCallback, useContext, useEffect, useMemo, useState } from 'react'; import { ArtifactSheet } from '../Artifact/ArtifactSheet'; import { buildContext } from '../Build/Build'; import CardDark from '../Components/Card/CardDark'; import CardLight from '../Components/Card/CardLight'; import { CharacterSelectionModal } from '../Components/Character/CharacterSelectionModal'; import ThumbSide from '../Components/Character/ThumbSide'; import CloseButton from '../Components/CloseButton'; import CustomNumberInput, { CustomNumberInputButtonGroupWrapper } from '../Components/CustomNumberInput'; import DropdownButton from '../Components/DropdownMenu/DropdownButton'; import { EnemyExpandCard } from '../Components/EnemyEditor'; import FormulaCalcCard from '../Components/FormulaCalcCard'; import { DamageOptionsCard } from '../Components/HitModeEditor'; import ImgIcon from '../Components/Image/ImgIcon'; import ElementalData from '../Data/ElementalData'; import { ambiguousLevel, ascensionMaxLevel, milestoneLevels } from '../Data/LevelData'; import { DatabaseContext } from '../Database/Database'; import useCharacterReducer from '../ReactHooks/useCharacterReducer'; import useForceUpdate from '../ReactHooks/useForceUpdate'; import usePromise from '../ReactHooks/usePromise'; import { ICachedCharacter } from '../Types/character'; import { CharacterKey } from '../Types/consts'; import { ICalculatedStats } from '../Types/stats'; import { clamp, deepClone } from '../Util/Util'; import WeaponSheet from '../Weapon/WeaponSheet'; import Character from './Character'; import CharacterArtifactPane from './CharacterDisplay/CharacterArtifactPane'; import CharacterOverviewPane from './CharacterDisplay/CharacterOverviewPane'; import CharacterTalentPane from './CharacterDisplay/CharacterTalentPane'; import CharacterSheet from './CharacterSheet'; import { initialCharacter } from './CharacterUtil'; interface TabPanelProps { children?: React.ReactNode; value: string; current: string | boolean; } function TabPanel({ children, current, value, ...other }: TabPanelProps) { if (value !== current) return null return <Suspense fallback={<Skeleton variant="rectangular" width="100%" height={1000} />}> <div role="tabpanel" hidden={value !== current} id={`simple-tabpanel-${value}`} aria-labelledby={`simple-tab-${value}`} {...other} > {children} </div> </Suspense> } type CharacterDisplayCardProps = { characterKey: CharacterKey, setCharacterKey?: (any: CharacterKey) => void footer?: JSX.Element newBuild?: ICalculatedStats, onClose?: (any) => void, tabName?: string } export default function CharacterDisplayCard({ characterKey, setCharacterKey, footer, newBuild: propNewBuild, onClose, tabName }: CharacterDisplayCardProps) { const database = useContext(DatabaseContext) const [compareBuild, setCompareBuild] = useState(false) // Use databaseToken anywhere `database._get*` is used // Use onDatabaseUpdate when `following` database entries const [databaseToken, onDatabaseUpdate] = useForceUpdate() // TODO: We probably don't need to fetch all sheets, // though this wouldn't affect the performance currently. const weaponSheets = usePromise(WeaponSheet.getAll(), []) const characterSheets = usePromise(CharacterSheet.getAll(), []) const artifactSheets = usePromise(ArtifactSheet.getAll(), []) const character = useMemo(() => databaseToken && (database._getChar(characterKey) ?? initialCharacter(characterKey)), [characterKey, databaseToken, database]) const weapon = useMemo(() => databaseToken && database._getWeapon(character.equippedWeapon), [character.equippedWeapon, databaseToken, database]) const characterSheet = characterSheets?.[characterKey] const weaponSheet = weapon ? weaponSheets?.[weapon.key] : undefined const sheets = characterSheet && weaponSheet && artifactSheets && { characterSheet, weaponSheet, artifactSheets } useEffect(() => { return database.followChar(characterKey, onDatabaseUpdate) }, [characterKey, onDatabaseUpdate, database]) useEffect(() => database.followWeapon(character.equippedWeapon, onDatabaseUpdate), [character.equippedWeapon, onDatabaseUpdate, database]) const newBuild = useMemo(() => { if (!propNewBuild) return undefined return deepClone(propNewBuild) }, [propNewBuild]) // set initial state to false, because it fails to check validity of the tab values on 1st load const [tab, settab] = useState<string | boolean>(tabName ? tabName : (newBuild ? "newartifacts" : "character")) const onTab = useCallback((e, v) => settab(v), [settab]) const mainStatAssumptionLevel = newBuild?.mainStatAssumptionLevel ?? 0 const equippedBuild = useMemo(() => databaseToken && characterSheet && weaponSheet && artifactSheets && Character.calculateBuild(character, database, characterSheet, weaponSheet, artifactSheets, mainStatAssumptionLevel), [databaseToken, character, characterSheet, weaponSheet, artifactSheets, mainStatAssumptionLevel, database]) // main CharacterDisplayCard return <CardDark > <buildContext.Provider value={{ newBuild, equippedBuild, compareBuild, setCompareBuild }}> <CardContent sx={{ "> div:not(:last-child)": { mb: 1 }, }}> <Grid container spacing={1}> <Grid item flexGrow={1}> <CharSelectDropdown characterSheet={characterSheet} character={character} setCharacterKey={setCharacterKey} /> </Grid> {!!mainStatAssumptionLevel && <Grid item><Card sx={{ p: 1, bgcolor: t => t.palette.warning.dark }}><Typography><strong>Assume Main Stats are Level {mainStatAssumptionLevel}</strong></Typography></Card></Grid>} {!!onClose && <Grid item> <CloseButton onClick={onClose} /> </Grid>} </Grid> <CardLight> <Tabs onChange={onTab} value={tab} variant="fullWidth" > <Tab value="character" label="Character" /> {!!newBuild && <Tab value="newartifacts" label="New Artifacts" />} <Tab value="artifacts" label={newBuild ? "Current Artifacts" : "Artifacts"} /> <Tab value="talent" label="Talents" /> </Tabs> </CardLight> <DamageOptionsCard character={character} /> {!!sheets && <FormulaCalcCard sheets={sheets} />} <EnemyExpandCard character={character} /> {/* Character Panel */} {characterSheet && <TabPanel value="character" current={tab}> <CharacterOverviewPane characterSheet={characterSheet} character={character} /> </TabPanel >} {/* Artifacts Panel */} {sheets && <buildContext.Provider value={{ newBuild: undefined, equippedBuild, compareBuild, setCompareBuild }}> <TabPanel value="artifacts" current={tab} > <CharacterArtifactPane sheets={sheets} character={character} /> </TabPanel > </buildContext.Provider>} {/* new build panel */} {newBuild && sheets && <TabPanel value="newartifacts" current={tab} > <CharacterArtifactPane sheets={sheets} character={character} /> </TabPanel >} {/* talent panel */} {characterSheet && <TabPanel value="talent" current={tab}> <CharacterTalentPane characterSheet={characterSheet} character={character} /> </TabPanel >} </CardContent> {!!footer && <Divider />} {footer && <CardContent sx={{ py: 1 }}> {footer} </CardContent>} </buildContext.Provider> </CardDark> } type CharSelectDropdownProps = { characterSheet?: CharacterSheet, character: ICachedCharacter disabled?: boolean setCharacterKey?: (any: CharacterKey) => void } function CharSelectDropdown({ characterSheet, character, character: { key: characterKey, elementKey = "anemo", level = 1, ascension = 0 }, disabled, setCharacterKey }: CharSelectDropdownProps) { const [showModal, setshowModal] = useState(false) const characterDispatch = useCharacterReducer(characterKey) const HeaderIconDisplay = characterSheet ? <span > <ImgIcon src={characterSheet.thumbImg} sx={{ mr: 1 }} /> {characterSheet.name} </span> : <span>Select a Character</span> const setLevel = useCallback((level) => { level = clamp(level, 1, 90) const ascension = ascensionMaxLevel.findIndex(ascenML => level <= ascenML) characterDispatch({ level, ascension }) }, [characterDispatch]) const setAscension = useCallback(() => { const lowerAscension = ascensionMaxLevel.findIndex(ascenML => level !== 90 && level === ascenML) if (ascension === lowerAscension) characterDispatch({ ascension: ascension + 1 }) else characterDispatch({ ascension: lowerAscension }) }, [characterDispatch, ascension, level]) return <>{!disabled ? <> <CharacterSelectionModal show={showModal} onHide={() => setshowModal(false)} onSelect={setCharacterKey} /> <ButtonGroup sx={{ bgcolor: t => t.palette.contentDark.main }} > <Button disabled={!setCharacterKey} onClick={() => setshowModal(true)} startIcon={<ThumbSide src={characterSheet?.thumbImgSide} />} >{characterSheet?.name ?? "Select a Character"}</Button> {characterSheet?.sheet && "talents" in characterSheet?.sheet && <DropdownButton title={ElementalData[elementKey].name}> {Object.keys(characterSheet.sheet.talents).map(eleKey => <MenuItem key={eleKey} selected={elementKey === eleKey} disabled={elementKey === eleKey} onClick={() => characterDispatch({ elementKey: eleKey })}> <strong>{ElementalData[eleKey].name}</strong></MenuItem>)} </DropdownButton>} <CustomNumberInputButtonGroupWrapper > <CustomNumberInput onChange={setLevel} value={level} startAdornment="Lvl. " inputProps={{ min: 1, max: 90, sx: { textAlign: "center" } }} sx={{ width: "100%", height: "100%", pl: 2 }} disabled={!characterSheet} /> </CustomNumberInputButtonGroupWrapper> <Button sx={{ pl: 1 }} disabled={!ambiguousLevel(level) || !characterSheet} onClick={setAscension}><strong>/ {ascensionMaxLevel[ascension]}</strong></Button> <DropdownButton title={"Select Level"} disabled={!characterSheet}> {milestoneLevels.map(([lv, as]) => { const sameLevel = lv === ascensionMaxLevel[as] const lvlstr = sameLevel ? `Lv. ${lv}` : `Lv. ${lv}/${ascensionMaxLevel[as]}` const selected = lv === level && as === ascension return <MenuItem key={`${lv}/${as}`} selected={selected} disabled={selected} onClick={() => characterDispatch({ level: lv, ascension: as })}>{lvlstr}</MenuItem> })} </DropdownButton> </ButtonGroup> </> : <Typography variant="h6">{HeaderIconDisplay} {characterSheet && Character.getLevelString(character)}</Typography>}</> }
the_stack
module android.view { import SparseArray = android.util.SparseArray; import LayoutDirection = android.util.LayoutDirection; import Drawable = android.graphics.drawable.Drawable; import ColorDrawable = android.graphics.drawable.ColorDrawable; import ScrollBarDrawable = android.graphics.drawable.ScrollBarDrawable; import InsetDrawable = android.graphics.drawable.InsetDrawable; import ShadowDrawable = android.graphics.drawable.ShadowDrawable; import RoundRectDrawable = android.graphics.drawable.RoundRectDrawable; import PixelFormat = android.graphics.PixelFormat; import Matrix = android.graphics.Matrix; import Color = android.graphics.Color; import Paint = android.graphics.Paint; import StringBuilder = java.lang.StringBuilder; import Runnable = java.lang.Runnable; import JavaObject = java.lang.JavaObject; import System = java.lang.System; //import ViewRootImpl = android.view.ViewRootImpl; import ViewParent = android.view.ViewParent; import SystemClock = android.os.SystemClock; import Handler = android.os.Handler; import Log = android.util.Log; import Rect = android.graphics.Rect; import RectF = android.graphics.RectF; import Point = android.graphics.Point; import Canvas = android.graphics.Canvas; import CopyOnWriteArrayList = java.lang.util.concurrent.CopyOnWriteArrayList; import ArrayList = java.util.ArrayList; import OnAttachStateChangeListener = View.OnAttachStateChangeListener; import Context = android.content.Context; import Resources = android.content.res.Resources; import ColorStateList = android.content.res.ColorStateList; import Pools = android.util.Pools; import LinearInterpolator = android.view.animation.LinearInterpolator; import AnimationUtils = android.view.animation.AnimationUtils; import AttrBinder = androidui.attr.AttrBinder; import PerformanceAdjuster = androidui.util.PerformanceAdjuster; import NetDrawable = androidui.image.NetDrawable; import KeyEvent = android.view.KeyEvent; import Animation = android.view.animation.Animation; import Transformation = android.view.animation.Transformation; import TypedArray = android.content.res.TypedArray; /** * <p> * This class represents the basic building block for user interface components. A View * occupies a rectangular area on the screen and is responsible for drawing and * event handling. View is the base class for <em>widgets</em>, which are * used to create interactive UI components (buttons, text fields, etc.). The * {@link android.view.ViewGroup} subclass is the base class for <em>layouts</em>, which * are invisible containers that hold other Views (or other ViewGroups) and define * their layout properties. * </p> * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For information about using this class to develop your application's user interface, * read the <a href="{@docRoot}guide/topics/ui/index.html">User Interface</a> developer guide. * </div> * * <a name="Using"></a> * <h3>Using Views</h3> * <p> * All of the views in a window are arranged in a single tree. You can add views * either from code or by specifying a tree of views in one or more XML layout * files. There are many specialized subclasses of views that act as controls or * are capable of displaying text, images, or other content. * </p> * <p> * Once you have created a tree of views, there are typically a few types of * common operations you may wish to perform: * <ul> * <li><strong>Set properties:</strong> for example setting the text of a * {@link android.widget.TextView}. The available properties and the methods * that set them will vary among the different subclasses of views. Note that * properties that are known at build time can be set in the XML layout * files.</li> * <li><strong>Set focus:</strong> The framework will handled moving focus in * response to user input. To force focus to a specific view, call * {@link #requestFocus}.</li> * <li><strong>Set up listeners:</strong> Views allow clients to set listeners * that will be notified when something interesting happens to the view. For * example, all views will let you set a listener to be notified when the view * gains or loses focus. You can register such a listener using * {@link #setOnFocusChangeListener(android.view.View.OnFocusChangeListener)}. * Other view subclasses offer more specialized listeners. For example, a Button * exposes a listener to notify clients when the button is clicked.</li> * <li><strong>Set visibility:</strong> You can hide or show views using * {@link #setVisibility(int)}.</li> * </ul> * </p> * <p><em> * Note: The Android framework is responsible for measuring, laying out and * drawing views. You should not call methods that perform these actions on * views yourself unless you are actually implementing a * {@link android.view.ViewGroup}. * </em></p> * * <a name="Lifecycle"></a> * <h3>Implementing a Custom View</h3> * * <p> * To implement a custom view, you will usually begin by providing overrides for * some of the standard methods that the framework calls on all views. You do * not need to override all of these methods. In fact, you can start by just * overriding {@link #onDraw(android.graphics.Canvas)}. * <table border="2" width="85%" align="center" cellpadding="5"> * <thead> * <tr><th>Category</th> <th>Methods</th> <th>Description</th></tr> * </thead> * * <tbody> * <tr> * <td rowspan="2">Creation</td> * <td>Constructors</td> * <td>There is a form of the constructor that are called when the view * is created from code and a form that is called when the view is * inflated from a layout file. The second form should parse and apply * any attributes defined in the layout file. * </td> * </tr> * <tr> * <td><code>{@link #onFinishInflate()}</code></td> * <td>Called after a view and all of its children has been inflated * from XML.</td> * </tr> * * <tr> * <td rowspan="3">Layout</td> * <td><code>{@link #onMeasure(int, int)}</code></td> * <td>Called to determine the size requirements for this view and all * of its children. * </td> * </tr> * <tr> * <td><code>{@link #onLayout(boolean, int, int, int, int)}</code></td> * <td>Called when this view should assign a size and position to all * of its children. * </td> * </tr> * <tr> * <td><code>{@link #onSizeChanged(int, int, int, int)}</code></td> * <td>Called when the size of this view has changed. * </td> * </tr> * * <tr> * <td>Drawing</td> * <td><code>{@link #onDraw(android.graphics.Canvas)}</code></td> * <td>Called when the view should render its content. * </td> * </tr> * * <tr> * <td rowspan="4">Event processing</td> * <td><code>{@link #onKeyDown(int, KeyEvent)}</code></td> * <td>Called when a new hardware key event occurs. * </td> * </tr> * <tr> * <td><code>{@link #onKeyUp(int, KeyEvent)}</code></td> * <td>Called when a hardware key up event occurs. * </td> * </tr> * <tr> * <td><code>{@link #onTrackballEvent(MotionEvent)}</code></td> * <td>Called when a trackball motion event occurs. * </td> * </tr> * <tr> * <td><code>{@link #onTouchEvent(MotionEvent)}</code></td> * <td>Called when a touch screen motion event occurs. * </td> * </tr> * * <tr> * <td rowspan="2">Focus</td> * <td><code>{@link #onFocusChanged(boolean, int, android.graphics.Rect)}</code></td> * <td>Called when the view gains or loses focus. * </td> * </tr> * * <tr> * <td><code>{@link #onWindowFocusChanged(boolean)}</code></td> * <td>Called when the window containing the view gains or loses focus. * </td> * </tr> * * <tr> * <td rowspan="3">Attaching</td> * <td><code>{@link #onAttachedToWindow()}</code></td> * <td>Called when the view is attached to a window. * </td> * </tr> * * <tr> * <td><code>{@link #onDetachedFromWindow}</code></td> * <td>Called when the view is detached from its window. * </td> * </tr> * * <tr> * <td><code>{@link #onWindowVisibilityChanged(int)}</code></td> * <td>Called when the visibility of the window containing the view * has changed. * </td> * </tr> * </tbody> * * </table> * </p> * * <a name="IDs"></a> * <h3>IDs</h3> * Views may have an integer id associated with them. These ids are typically * assigned in the layout XML files, and are used to find specific views within * the view tree. A common pattern is to: * <ul> * <li>Define a Button in the layout file and assign it a unique ID. * <pre> * &lt;Button * android:id="@+id/my_button" * android:layout_width="wrap_content" * android:layout_height="wrap_content" * android:text="@string/my_button_text"/&gt; * </pre></li> * <li>From the onCreate method of an Activity, find the Button * <pre class="prettyprint"> * Button myButton = (Button) findViewById(R.id.my_button); * </pre></li> * </ul> * <p> * View IDs need not be unique throughout the tree, but it is good practice to * ensure that they are at least unique within the part of the tree you are * searching. * </p> * * <a name="Position"></a> * <h3>Position</h3> * <p> * The geometry of a view is that of a rectangle. A view has a location, * expressed as a pair of <em>left</em> and <em>top</em> coordinates, and * two dimensions, expressed as a width and a height. The unit for location * and dimensions is the pixel. * </p> * * <p> * It is possible to retrieve the location of a view by invoking the methods * {@link #getLeft()} and {@link #getTop()}. The former returns the left, or X, * coordinate of the rectangle representing the view. The latter returns the * top, or Y, coordinate of the rectangle representing the view. These methods * both return the location of the view relative to its parent. For instance, * when getLeft() returns 20, that means the view is located 20 pixels to the * right of the left edge of its direct parent. * </p> * * <p> * In addition, several convenience methods are offered to avoid unnecessary * computations, namely {@link #getRight()} and {@link #getBottom()}. * These methods return the coordinates of the right and bottom edges of the * rectangle representing the view. For instance, calling {@link #getRight()} * is similar to the following computation: <code>getLeft() + getWidth()</code> * (see <a href="#SizePaddingMargins">Size</a> for more information about the width.) * </p> * * <a name="SizePaddingMargins"></a> * <h3>Size, padding and margins</h3> * <p> * The size of a view is expressed with a width and a height. A view actually * possess two pairs of width and height values. * </p> * * <p> * The first pair is known as <em>measured width</em> and * <em>measured height</em>. These dimensions define how big a view wants to be * within its parent (see <a href="#Layout">Layout</a> for more details.) The * measured dimensions can be obtained by calling {@link #getMeasuredWidth()} * and {@link #getMeasuredHeight()}. * </p> * * <p> * The second pair is simply known as <em>width</em> and <em>height</em>, or * sometimes <em>drawing width</em> and <em>drawing height</em>. These * dimensions define the actual size of the view on screen, at drawing time and * after layout. These values may, but do not have to, be different from the * measured width and height. The width and height can be obtained by calling * {@link #getWidth()} and {@link #getHeight()}. * </p> * * <p> * To measure its dimensions, a view takes into account its padding. The padding * is expressed in pixels for the left, top, right and bottom parts of the view. * Padding can be used to offset the content of the view by a specific amount of * pixels. For instance, a left padding of 2 will push the view's content by * 2 pixels to the right of the left edge. Padding can be set using the * {@link #setPadding(int, int, int, int)} or {@link #setPaddingRelative(int, int, int, int)} * method and queried by calling {@link #getPaddingLeft()}, {@link #getPaddingTop()}, * {@link #getPaddingRight()}, {@link #getPaddingBottom()}, {@link #getPaddingStart()}, * {@link #getPaddingEnd()}. * </p> * * <p> * Even though a view can define a padding, it does not provide any support for * margins. However, view groups provide such a support. Refer to * {@link android.view.ViewGroup} and * {@link android.view.ViewGroup.MarginLayoutParams} for further information. * </p> * * <a name="Layout"></a> * <h3>Layout</h3> * <p> * Layout is a two pass process: a measure pass and a layout pass. The measuring * pass is implemented in {@link #measure(int, int)} and is a top-down traversal * of the view tree. Each view pushes dimension specifications down the tree * during the recursion. At the end of the measure pass, every view has stored * its measurements. The second pass happens in * {@link #layout(int,int,int,int)} and is also top-down. During * this pass each parent is responsible for positioning all of its children * using the sizes computed in the measure pass. * </p> * * <p> * When a view's measure() method returns, its {@link #getMeasuredWidth()} and * {@link #getMeasuredHeight()} values must be set, along with those for all of * that view's descendants. A view's measured width and measured height values * must respect the constraints imposed by the view's parents. This guarantees * that at the end of the measure pass, all parents accept all of their * children's measurements. A parent view may call measure() more than once on * its children. For example, the parent may measure each child once with * unspecified dimensions to find out how big they want to be, then call * measure() on them again with actual numbers if the sum of all the children's * unconstrained sizes is too big or too small. * </p> * * <p> * The measure pass uses two classes to communicate dimensions. The * {@link MeasureSpec} class is used by views to tell their parents how they * want to be measured and positioned. The base LayoutParams class just * describes how big the view wants to be for both width and height. For each * dimension, it can specify one of: * <ul> * <li> an exact number * <li>MATCH_PARENT, which means the view wants to be as big as its parent * (minus padding) * <li> WRAP_CONTENT, which means that the view wants to be just big enough to * enclose its content (plus padding). * </ul> * There are subclasses of LayoutParams for different subclasses of ViewGroup. * For example, AbsoluteLayout has its own subclass of LayoutParams which adds * an X and Y value. * </p> * * <p> * MeasureSpecs are used to push requirements down the tree from parent to * child. A MeasureSpec can be in one of three modes: * <ul> * <li>UNSPECIFIED: This is used by a parent to determine the desired dimension * of a child view. For example, a LinearLayout may call measure() on its child * with the height set to UNSPECIFIED and a width of EXACTLY 240 to find out how * tall the child view wants to be given a width of 240 pixels. * <li>EXACTLY: This is used by the parent to impose an exact size on the * child. The child must use this size, and guarantee that all of its * descendants will fit within this size. * <li>AT_MOST: This is used by the parent to impose a maximum size on the * child. The child must gurantee that it and all of its descendants will fit * within this size. * </ul> * </p> * * <p> * To intiate a layout, call {@link #requestLayout}. This method is typically * called by a view on itself when it believes that is can no longer fit within * its current bounds. * </p> * * <a name="Drawing"></a> * <h3>Drawing</h3> * <p> * Drawing is handled by walking the tree and rendering each view that * intersects the invalid region. Because the tree is traversed in-order, * this means that parents will draw before (i.e., behind) their children, with * siblings drawn in the order they appear in the tree. * If you set a background drawable for a View, then the View will draw it for you * before calling back to its <code>onDraw()</code> method. * </p> * * <p> * Note that the framework will not draw views that are not in the invalid region. * </p> * * <p> * To force a view to draw, call {@link #invalidate()}. * </p> * * <a name="EventHandlingThreading"></a> * <h3>Event Handling and Threading</h3> * <p> * The basic cycle of a view is as follows: * <ol> * <li>An event comes in and is dispatched to the appropriate view. The view * handles the event and notifies any listeners.</li> * <li>If in the course of processing the event, the view's bounds may need * to be changed, the view will call {@link #requestLayout()}.</li> * <li>Similarly, if in the course of processing the event the view's appearance * may need to be changed, the view will call {@link #invalidate()}.</li> * <li>If either {@link #requestLayout()} or {@link #invalidate()} were called, * the framework will take care of measuring, laying out, and drawing the tree * as appropriate.</li> * </ol> * </p> * * <p><em>Note: The entire view tree is single threaded. You must always be on * the UI thread when calling any method on any view.</em> * If you are doing work on other threads and want to update the state of a view * from that thread, you should use a {@link Handler}. * </p> * * <a name="FocusHandling"></a> * <h3>Focus Handling</h3> * <p> * The framework will handle routine focus movement in response to user input. * This includes changing the focus as views are removed or hidden, or as new * views become available. Views indicate their willingness to take focus * through the {@link #isFocusable} method. To change whether a view can take * focus, call {@link #setFocusable(boolean)}. When in touch mode (see notes below) * views indicate whether they still would like focus via {@link #isFocusableInTouchMode} * and can change this via {@link #setFocusableInTouchMode(boolean)}. * </p> * <p> * Focus movement is based on an algorithm which finds the nearest neighbor in a * given direction. In rare cases, the default algorithm may not match the * intended behavior of the developer. In these situations, you can provide * explicit overrides by using these XML attributes in the layout file: * <pre> * nextFocusDown * nextFocusLeft * nextFocusRight * nextFocusUp * </pre> * </p> * * * <p> * To get a particular view to take focus, call {@link #requestFocus()}. * </p> * * <a name="TouchMode"></a> * <h3>Touch Mode</h3> * <p> * When a user is navigating a user interface via directional keys such as a D-pad, it is * necessary to give focus to actionable items such as buttons so the user can see * what will take input. If the device has touch capabilities, however, and the user * begins interacting with the interface by touching it, it is no longer necessary to * always highlight, or give focus to, a particular view. This motivates a mode * for interaction named 'touch mode'. * </p> * <p> * For a touch capable device, once the user touches the screen, the device * will enter touch mode. From this point onward, only views for which * {@link #isFocusableInTouchMode} is true will be focusable, such as text editing widgets. * Other views that are touchable, like buttons, will not take focus when touched; they will * only fire the on click listeners. * </p> * <p> * Any time a user hits a directional key, such as a D-pad direction, the view device will * exit touch mode, and find a view to take focus, so that the user may resume interacting * with the user interface without touching the screen again. * </p> * <p> * The touch mode state is maintained across {@link android.app.Activity}s. Call * {@link #isInTouchMode} to see whether the device is currently in touch mode. * </p> * * <a name="Scrolling"></a> * <h3>Scrolling</h3> * <p> * The framework provides basic support for views that wish to internally * scroll their content. This includes keeping track of the X and Y scroll * offset as well as mechanisms for drawing scrollbars. See * {@link #scrollBy(int, int)}, {@link #scrollTo(int, int)}, and * {@link #awakenScrollBars()} for more details. * </p> * * <a name="Tags"></a> * <h3>Tags</h3> * <p> * Unlike IDs, tags are not used to identify views. Tags are essentially an * extra piece of information that can be associated with a view. They are most * often used as a convenience to store data related to views in the views * themselves rather than by putting them in a separate structure. * </p> * * <a name="Properties"></a> * <h3>Properties</h3> * <p> * The View class exposes an {@link #ALPHA} property, as well as several transform-related * properties, such as {@link #TRANSLATION_X} and {@link #TRANSLATION_Y}. These properties are * available both in the {@link Property} form as well as in similarly-named setter/getter * methods (such as {@link #setAlpha(float)} for {@link #ALPHA}). These properties can * be used to set persistent state associated with these rendering-related properties on the view. * The properties and methods can also be used in conjunction with * {@link android.animation.Animator Animator}-based animations, described more in the * <a href="#Animation">Animation</a> section. * </p> * * <a name="Animation"></a> * <h3>Animation</h3> * <p> * Starting with Android 3.0, the preferred way of animating views is to use the * {@link android.animation} package APIs. These {@link android.animation.Animator Animator}-based * classes change actual properties of the View object, such as {@link #setAlpha(float) alpha} and * {@link #setTranslationX(float) translationX}. This behavior is contrasted to that of the pre-3.0 * {@link android.view.animation.Animation Animation}-based classes, which instead animate only * how the view is drawn on the display. In particular, the {@link ViewPropertyAnimator} class * makes animating these View properties particularly easy and efficient. * </p> * <p> * Alternatively, you can use the pre-3.0 animation classes to animate how Views are rendered. * You can attach an {@link Animation} object to a view using * {@link #setAnimation(Animation)} or * {@link #startAnimation(Animation)}. The animation can alter the scale, * rotation, translation and alpha of a view over time. If the animation is * attached to a view that has children, the animation will affect the entire * subtree rooted by that node. When an animation is started, the framework will * take care of redrawing the appropriate views until the animation completes. * </p> * * <a name="Security"></a> * <h3>Security</h3> * <p> * Sometimes it is essential that an application be able to verify that an action * is being performed with the full knowledge and consent of the user, such as * granting a permission request, making a purchase or clicking on an advertisement. * Unfortunately, a malicious application could try to spoof the user into * performing these actions, unaware, by concealing the intended purpose of the view. * As a remedy, the framework offers a touch filtering mechanism that can be used to * improve the security of views that provide access to sensitive functionality. * </p><p> * To enable touch filtering, call {@link #setFilterTouchesWhenObscured(boolean)} or set the * android:filterTouchesWhenObscured layout attribute to true. When enabled, the framework * will discard touches that are received whenever the view's window is obscured by * another visible window. As a result, the view will not receive touches whenever a * toast, dialog or other window appears above the view's window. * </p><p> * For more fine-grained control over security, consider overriding the * {@link #onFilterTouchEventForSecurity(MotionEvent)} method to implement your own * security policy. See also {@link MotionEvent#FLAG_WINDOW_IS_OBSCURED}. * </p> * * @attr ref android.R.styleable#View_alpha * @attr ref android.R.styleable#View_background * @attr ref android.R.styleable#View_clickable * @attr ref android.R.styleable#View_contentDescription * @attr ref android.R.styleable#View_drawingCacheQuality * @attr ref android.R.styleable#View_duplicateParentState * @attr ref android.R.styleable#View_id * @attr ref android.R.styleable#View_requiresFadingEdge * @attr ref android.R.styleable#View_fadeScrollbars * @attr ref android.R.styleable#View_fadingEdgeLength * @attr ref android.R.styleable#View_filterTouchesWhenObscured * @attr ref android.R.styleable#View_fitsSystemWindows * @attr ref android.R.styleable#View_isScrollContainer * @attr ref android.R.styleable#View_focusable * @attr ref android.R.styleable#View_focusableInTouchMode * @attr ref android.R.styleable#View_hapticFeedbackEnabled * @attr ref android.R.styleable#View_keepScreenOn * @attr ref android.R.styleable#View_layerType * @attr ref android.R.styleable#View_layoutDirection * @attr ref android.R.styleable#View_longClickable * @attr ref android.R.styleable#View_minHeight * @attr ref android.R.styleable#View_minWidth * @attr ref android.R.styleable#View_nextFocusDown * @attr ref android.R.styleable#View_nextFocusLeft * @attr ref android.R.styleable#View_nextFocusRight * @attr ref android.R.styleable#View_nextFocusUp * @attr ref android.R.styleable#View_onClick * @attr ref android.R.styleable#View_padding * @attr ref android.R.styleable#View_paddingBottom * @attr ref android.R.styleable#View_paddingLeft * @attr ref android.R.styleable#View_paddingRight * @attr ref android.R.styleable#View_paddingTop * @attr ref android.R.styleable#View_paddingStart * @attr ref android.R.styleable#View_paddingEnd * @attr ref android.R.styleable#View_saveEnabled * @attr ref android.R.styleable#View_rotation * @attr ref android.R.styleable#View_rotationX * @attr ref android.R.styleable#View_rotationY * @attr ref android.R.styleable#View_scaleX * @attr ref android.R.styleable#View_scaleY * @attr ref android.R.styleable#View_scrollX * @attr ref android.R.styleable#View_scrollY * @attr ref android.R.styleable#View_scrollbarSize * @attr ref android.R.styleable#View_scrollbarStyle * @attr ref android.R.styleable#View_scrollbars * @attr ref android.R.styleable#View_scrollbarDefaultDelayBeforeFade * @attr ref android.R.styleable#View_scrollbarFadeDuration * @attr ref android.R.styleable#View_scrollbarTrackHorizontal * @attr ref android.R.styleable#View_scrollbarThumbHorizontal * @attr ref android.R.styleable#View_scrollbarThumbVertical * @attr ref android.R.styleable#View_scrollbarTrackVertical * @attr ref android.R.styleable#View_scrollbarAlwaysDrawHorizontalTrack * @attr ref android.R.styleable#View_scrollbarAlwaysDrawVerticalTrack * @attr ref android.R.styleable#View_soundEffectsEnabled * @attr ref android.R.styleable#View_tag * @attr ref android.R.styleable#View_textAlignment * @attr ref android.R.styleable#View_textDirection * @attr ref android.R.styleable#View_transformPivotX * @attr ref android.R.styleable#View_transformPivotY * @attr ref android.R.styleable#View_translationX * @attr ref android.R.styleable#View_translationY * @attr ref android.R.styleable#View_visibility * * @see android.view.ViewGroup * * AndroidUIX NOTE: something modified */ export class View extends JavaObject implements Drawable.Callback, KeyEvent.Callback { static DBG = Log.View_DBG; static VIEW_LOG_TAG = "View"; static PFLAG_WANTS_FOCUS = 0x00000001; static PFLAG_FOCUSED = 0x00000002; static PFLAG_SELECTED = 0x00000004; static PFLAG_IS_ROOT_NAMESPACE = 0x00000008; static PFLAG_HAS_BOUNDS = 0x00000010; static PFLAG_DRAWN = 0x00000020; static PFLAG_DRAW_ANIMATION = 0x00000040; static PFLAG_SKIP_DRAW = 0x00000080; static PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; static PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; static PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; static PFLAG_MEASURED_DIMENSION_SET = 0x00000800; static PFLAG_FORCE_LAYOUT = 0x00001000; static PFLAG_LAYOUT_REQUIRED = 0x00002000; static PFLAG_PRESSED = 0x00004000; static PFLAG_DRAWING_CACHE_VALID = 0x00008000; static PFLAG_ANIMATION_STARTED = 0x00010000; static PFLAG_ALPHA_SET = 0x00040000; static PFLAG_SCROLL_CONTAINER = 0x00080000; static PFLAG_SCROLL_CONTAINER_ADDED = 0x00100000; static PFLAG_DIRTY = 0x00200000; static PFLAG_DIRTY_OPAQUE = 0x00400000; static PFLAG_DIRTY_MASK = 0x00600000; static PFLAG_OPAQUE_BACKGROUND = 0x00800000; static PFLAG_OPAQUE_SCROLLBARS = 0x01000000; static PFLAG_OPAQUE_MASK = 0x01800000; static PFLAG_PREPRESSED = 0x02000000; static PFLAG_CANCEL_NEXT_UP_EVENT = 0x04000000; static PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH = 0x08000000; static PFLAG_HOVERED = 0x10000000; static PFLAG_PIVOT_EXPLICITLY_SET = 0x20000000; static PFLAG_ACTIVATED = 0x40000000; static PFLAG_INVALIDATED = 0x80000000; static PFLAG2_VIEW_QUICK_REJECTED = 0x10000000; static PFLAG2_HAS_TRANSIENT_STATE = 0x80000000; static PFLAG3_VIEW_IS_ANIMATING_TRANSFORM = 0x1; static PFLAG3_VIEW_IS_ANIMATING_ALPHA = 0x2; static PFLAG3_IS_LAID_OUT = 0x4; static PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT = 0x8; static PFLAG3_CALLED_SUPER = 0x10; private static NOT_FOCUSABLE = 0x00000000; private static FOCUSABLE = 0x00000001; private static FOCUSABLE_MASK = 0x00000001; static NO_ID;//undefined static OVER_SCROLL_ALWAYS = 0; static OVER_SCROLL_IF_CONTENT_SCROLLS = 1; static OVER_SCROLL_NEVER = 2; static MEASURED_SIZE_MASK = 0x00ffffff; static MEASURED_STATE_MASK = 0xff000000; static MEASURED_HEIGHT_STATE_SHIFT = 16; static MEASURED_STATE_TOO_SMALL = 0x01000000; static VISIBILITY_MASK = 0x0000000C; static VISIBLE = 0x00000000; static INVISIBLE = 0x00000004; static GONE = 0x00000008; static ENABLED = 0x00000000; static DISABLED = 0x00000020; static ENABLED_MASK = 0x00000020; static WILL_NOT_DRAW = 0x00000080; static DRAW_MASK = 0x00000080; static SCROLLBARS_NONE = 0x00000000; static SCROLLBARS_HORIZONTAL = 0x00000100; static SCROLLBARS_VERTICAL = 0x00000200; static SCROLLBARS_MASK = 0x00000300; static FOCUSABLES_ALL = 0x00000000; static FOCUSABLES_TOUCH_MODE = 0x00000001; static FOCUS_BACKWARD = 0x00000001; static FOCUS_FORWARD = 0x00000002; static FOCUS_LEFT = 0x00000011; static FOCUS_UP = 0x00000021; static FOCUS_RIGHT = 0x00000042; static FOCUS_DOWN = 0x00000082; /** * Base View state sets */ // Singles /** * Indicates the view has no states set. States are used with * {@link android.graphics.drawable.Drawable} to change the drawing of the * view depending on its state. * * @see android.graphics.drawable.Drawable * @see #getDrawableState() */ static EMPTY_STATE_SET:number[]; /** * Indicates the view is enabled. States are used with * {@link android.graphics.drawable.Drawable} to change the drawing of the * view depending on its state. * * @see android.graphics.drawable.Drawable * @see #getDrawableState() */ static ENABLED_STATE_SET:number[]; /** * Indicates the view is focused. States are used with * {@link android.graphics.drawable.Drawable} to change the drawing of the * view depending on its state. * * @see android.graphics.drawable.Drawable * @see #getDrawableState() */ static FOCUSED_STATE_SET:number[]; /** * Indicates the view is selected. States are used with * {@link android.graphics.drawable.Drawable} to change the drawing of the * view depending on its state. * * @see android.graphics.drawable.Drawable * @see #getDrawableState() */ static SELECTED_STATE_SET:number[]; /** * Indicates the view is pressed. States are used with * {@link android.graphics.drawable.Drawable} to change the drawing of the * view depending on its state. * * @see android.graphics.drawable.Drawable * @see #getDrawableState() */ static PRESSED_STATE_SET:number[]; /** * Indicates the view's window has focus. States are used with * {@link android.graphics.drawable.Drawable} to change the drawing of the * view depending on its state. * * @see android.graphics.drawable.Drawable * @see #getDrawableState() */ static WINDOW_FOCUSED_STATE_SET:number[]; // Doubles /** * Indicates the view is enabled and has the focus. * * @see #ENABLED_STATE_SET * @see #FOCUSED_STATE_SET */ static ENABLED_FOCUSED_STATE_SET:number[]; /** * Indicates the view is enabled and selected. * * @see #ENABLED_STATE_SET * @see #SELECTED_STATE_SET */ static ENABLED_SELECTED_STATE_SET:number[]; /** * Indicates the view is enabled and that its window has focus. * * @see #ENABLED_STATE_SET * @see #WINDOW_FOCUSED_STATE_SET */ static ENABLED_WINDOW_FOCUSED_STATE_SET:number[]; /** * Indicates the view is focused and selected. * * @see #FOCUSED_STATE_SET * @see #SELECTED_STATE_SET */ static FOCUSED_SELECTED_STATE_SET:number[]; /** * Indicates the view has the focus and that its window has the focus. * * @see #FOCUSED_STATE_SET * @see #WINDOW_FOCUSED_STATE_SET */ static FOCUSED_WINDOW_FOCUSED_STATE_SET:number[]; /** * Indicates the view is selected and that its window has the focus. * * @see #SELECTED_STATE_SET * @see #WINDOW_FOCUSED_STATE_SET */ static SELECTED_WINDOW_FOCUSED_STATE_SET:number[]; // Triples /** * Indicates the view is enabled, focused and selected. * * @see #ENABLED_STATE_SET * @see #FOCUSED_STATE_SET * @see #SELECTED_STATE_SET */ static ENABLED_FOCUSED_SELECTED_STATE_SET:number[]; /** * Indicates the view is enabled, focused and its window has the focus. * * @see #ENABLED_STATE_SET * @see #FOCUSED_STATE_SET * @see #WINDOW_FOCUSED_STATE_SET */ static ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET:number[]; /** * Indicates the view is enabled, selected and its window has the focus. * * @see #ENABLED_STATE_SET * @see #SELECTED_STATE_SET * @see #WINDOW_FOCUSED_STATE_SET */ static ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET:number[]; /** * Indicates the view is focused, selected and its window has the focus. * * @see #FOCUSED_STATE_SET * @see #SELECTED_STATE_SET * @see #WINDOW_FOCUSED_STATE_SET */ static FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET:number[]; /** * Indicates the view is enabled, focused, selected and its window * has the focus. * * @see #ENABLED_STATE_SET * @see #FOCUSED_STATE_SET * @see #SELECTED_STATE_SET * @see #WINDOW_FOCUSED_STATE_SET */ static ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET:number[]; /** * Indicates the view is pressed and its window has the focus. * * @see #PRESSED_STATE_SET * @see #WINDOW_FOCUSED_STATE_SET */ static PRESSED_WINDOW_FOCUSED_STATE_SET:number[]; /** * Indicates the view is pressed and selected. * * @see #PRESSED_STATE_SET * @see #SELECTED_STATE_SET */ static PRESSED_SELECTED_STATE_SET:number[]; /** * Indicates the view is pressed, selected and its window has the focus. * * @see #PRESSED_STATE_SET * @see #SELECTED_STATE_SET * @see #WINDOW_FOCUSED_STATE_SET */ static PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET:number[]; /** * Indicates the view is pressed and focused. * * @see #PRESSED_STATE_SET * @see #FOCUSED_STATE_SET */ static PRESSED_FOCUSED_STATE_SET:number[]; /** * Indicates the view is pressed, focused and its window has the focus. * * @see #PRESSED_STATE_SET * @see #FOCUSED_STATE_SET * @see #WINDOW_FOCUSED_STATE_SET */ static PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET:number[]; /** * Indicates the view is pressed, focused and selected. * * @see #PRESSED_STATE_SET * @see #SELECTED_STATE_SET * @see #FOCUSED_STATE_SET */ static PRESSED_FOCUSED_SELECTED_STATE_SET:number[]; /** * Indicates the view is pressed, focused, selected and its window has the focus. * * @see #PRESSED_STATE_SET * @see #FOCUSED_STATE_SET * @see #SELECTED_STATE_SET * @see #WINDOW_FOCUSED_STATE_SET */ static PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET:number[]; /** * Indicates the view is pressed and enabled. * * @see #PRESSED_STATE_SET * @see #ENABLED_STATE_SET */ static PRESSED_ENABLED_STATE_SET:number[]; /** * Indicates the view is pressed, enabled and its window has the focus. * * @see #PRESSED_STATE_SET * @see #ENABLED_STATE_SET * @see #WINDOW_FOCUSED_STATE_SET */ static PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET:number[]; /** * Indicates the view is pressed, enabled and selected. * * @see #PRESSED_STATE_SET * @see #ENABLED_STATE_SET * @see #SELECTED_STATE_SET */ static PRESSED_ENABLED_SELECTED_STATE_SET:number[]; /** * Indicates the view is pressed, enabled, selected and its window has the * focus. * * @see #PRESSED_STATE_SET * @see #ENABLED_STATE_SET * @see #SELECTED_STATE_SET * @see #WINDOW_FOCUSED_STATE_SET */ static PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET:number[]; /** * Indicates the view is pressed, enabled and focused. * * @see #PRESSED_STATE_SET * @see #ENABLED_STATE_SET * @see #FOCUSED_STATE_SET */ static PRESSED_ENABLED_FOCUSED_STATE_SET:number[]; /** * Indicates the view is pressed, enabled, focused and its window has the * focus. * * @see #PRESSED_STATE_SET * @see #ENABLED_STATE_SET * @see #FOCUSED_STATE_SET * @see #WINDOW_FOCUSED_STATE_SET */ static PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET:number[]; /** * Indicates the view is pressed, enabled, focused and selected. * * @see #PRESSED_STATE_SET * @see #ENABLED_STATE_SET * @see #SELECTED_STATE_SET * @see #FOCUSED_STATE_SET */ static PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET:number[]; /** * Indicates the view is pressed, enabled, focused, selected and its window * has the focus. * * @see #PRESSED_STATE_SET * @see #ENABLED_STATE_SET * @see #SELECTED_STATE_SET * @see #FOCUSED_STATE_SET * @see #WINDOW_FOCUSED_STATE_SET */ static PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET:number[]; static VIEW_STATE_SETS:Array<Array<number>>; static VIEW_STATE_WINDOW_FOCUSED = 1; static VIEW_STATE_SELECTED = 1 << 1; static VIEW_STATE_FOCUSED = 1 << 2; static VIEW_STATE_ENABLED = 1 << 3; static VIEW_STATE_PRESSED = 1 << 4; static VIEW_STATE_ACTIVATED = 1 << 5; //static VIEW_STATE_ACCELERATED = 1 << 6; static VIEW_STATE_HOVERED = 1 << 7; //static VIEW_STATE_DRAG_CAN_ACCEPT = 1 << 8; //static VIEW_STATE_DRAG_HOVERED = 1 << 9; //for CompoundButton static VIEW_STATE_CHECKED = 1 << 10; //for TextView static VIEW_STATE_MULTILINE = 1 << 11; //for ExpandableListView static VIEW_STATE_EXPANDED = 1 << 12; static VIEW_STATE_EMPTY = 1 << 13; static VIEW_STATE_LAST = 1 << 14; //android default use attr id, there use state value as id static VIEW_STATE_IDS = [ View.VIEW_STATE_WINDOW_FOCUSED, View.VIEW_STATE_WINDOW_FOCUSED, View.VIEW_STATE_SELECTED, View.VIEW_STATE_SELECTED, View.VIEW_STATE_FOCUSED, View.VIEW_STATE_FOCUSED, View.VIEW_STATE_ENABLED, View.VIEW_STATE_ENABLED, View.VIEW_STATE_PRESSED, View.VIEW_STATE_PRESSED, View.VIEW_STATE_ACTIVATED, View.VIEW_STATE_ACTIVATED, //View.VIEW_STATE_ACCELERATED, View.VIEW_STATE_ACCELERATED, View.VIEW_STATE_HOVERED, View.VIEW_STATE_HOVERED, //View.VIEW_STATE_DRAG_CAN_ACCEPT, View.VIEW_STATE_DRAG_CAN_ACCEPT, //View.VIEW_STATE_DRAG_HOVERED, View.VIEW_STATE_DRAG_HOVERED ]; private static _static = (()=>{ function Integer_bitCount(i):number{ // HD, Figure 5-2 i = i - ((i >>> 1) & 0x55555555); i = (i & 0x33333333) + ((i >>> 2) & 0x33333333); i = (i + (i >>> 4)) & 0x0f0f0f0f; i = i + (i >>> 8); i = i + (i >>> 16); return i & 0x3f; } let orderedIds = View.VIEW_STATE_IDS; const NUM_BITS = View.VIEW_STATE_IDS.length / 2; View.VIEW_STATE_SETS = new Array<Array<number>>(1 << NUM_BITS); for (let i = 0; i < View.VIEW_STATE_SETS.length; i++) { let numBits = Integer_bitCount(i); const stataSet = androidui.util.ArrayCreator.newNumberArray(numBits); let pos = 0; for (let j = 0; j < orderedIds.length; j += 2) { if ((i & orderedIds[j+1]) != 0) { stataSet[pos++] = orderedIds[j]; } } View.VIEW_STATE_SETS[i] = stataSet; } View.EMPTY_STATE_SET = View.VIEW_STATE_SETS[0]; View.WINDOW_FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_WINDOW_FOCUSED]; View.SELECTED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_SELECTED]; View.SELECTED_WINDOW_FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_WINDOW_FOCUSED | View.VIEW_STATE_SELECTED]; View.FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_FOCUSED]; View.FOCUSED_WINDOW_FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_WINDOW_FOCUSED | View.VIEW_STATE_FOCUSED]; View.FOCUSED_SELECTED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_SELECTED | View.VIEW_STATE_FOCUSED]; View.FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_WINDOW_FOCUSED | View.VIEW_STATE_SELECTED | View.VIEW_STATE_FOCUSED]; View.ENABLED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_ENABLED]; View.ENABLED_WINDOW_FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_WINDOW_FOCUSED | View.VIEW_STATE_ENABLED]; View.ENABLED_SELECTED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_SELECTED | View.VIEW_STATE_ENABLED]; View.ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_WINDOW_FOCUSED | View.VIEW_STATE_SELECTED | View.VIEW_STATE_ENABLED]; View.ENABLED_FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_FOCUSED | View.VIEW_STATE_ENABLED]; View.ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_WINDOW_FOCUSED | View.VIEW_STATE_FOCUSED | View.VIEW_STATE_ENABLED]; View.ENABLED_FOCUSED_SELECTED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_SELECTED | View.VIEW_STATE_FOCUSED | View.VIEW_STATE_ENABLED]; View.ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_WINDOW_FOCUSED | View.VIEW_STATE_SELECTED | View.VIEW_STATE_FOCUSED | View.VIEW_STATE_ENABLED]; View.PRESSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_PRESSED]; View.PRESSED_WINDOW_FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_WINDOW_FOCUSED | View.VIEW_STATE_PRESSED]; View.PRESSED_SELECTED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_SELECTED | View.VIEW_STATE_PRESSED]; View.PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_WINDOW_FOCUSED | View.VIEW_STATE_SELECTED | View.VIEW_STATE_PRESSED]; View.PRESSED_FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_FOCUSED | View.VIEW_STATE_PRESSED]; View.PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_WINDOW_FOCUSED | View.VIEW_STATE_FOCUSED | View.VIEW_STATE_PRESSED]; View.PRESSED_FOCUSED_SELECTED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_SELECTED | View.VIEW_STATE_FOCUSED | View.VIEW_STATE_PRESSED]; View.PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_WINDOW_FOCUSED | View.VIEW_STATE_SELECTED | View.VIEW_STATE_FOCUSED | View.VIEW_STATE_PRESSED]; View.PRESSED_ENABLED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_ENABLED | View.VIEW_STATE_PRESSED]; View.PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_WINDOW_FOCUSED | View.VIEW_STATE_ENABLED | View.VIEW_STATE_PRESSED]; View.PRESSED_ENABLED_SELECTED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_SELECTED | View.VIEW_STATE_ENABLED | View.VIEW_STATE_PRESSED]; View.PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_WINDOW_FOCUSED | View.VIEW_STATE_SELECTED | View.VIEW_STATE_ENABLED | View.VIEW_STATE_PRESSED]; View.PRESSED_ENABLED_FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_FOCUSED | View.VIEW_STATE_ENABLED | View.VIEW_STATE_PRESSED]; View.PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_WINDOW_FOCUSED | View.VIEW_STATE_FOCUSED | View.VIEW_STATE_ENABLED | View.VIEW_STATE_PRESSED]; View.PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_SELECTED | View.VIEW_STATE_FOCUSED | View.VIEW_STATE_ENABLED | View.VIEW_STATE_PRESSED]; View.PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET = View.VIEW_STATE_SETS[View.VIEW_STATE_WINDOW_FOCUSED | View.VIEW_STATE_SELECTED | View.VIEW_STATE_FOCUSED | View.VIEW_STATE_ENABLED | View.VIEW_STATE_PRESSED]; })(); static CLICKABLE = 0x00004000; static DRAWING_CACHE_ENABLED = 0x00008000; static WILL_NOT_CACHE_DRAWING = 0x000020000; private static FOCUSABLE_IN_TOUCH_MODE = 0x00040000; static LONG_CLICKABLE = 0x00200000; static DUPLICATE_PARENT_STATE = 0x00400000; static LAYER_TYPE_NONE = 0; static LAYER_TYPE_SOFTWARE = 1; /** * Horizontal layout direction of this view is from Left to Right. * Use with {@link #setLayoutDirection}. */ static LAYOUT_DIRECTION_LTR:number = LayoutDirection.LTR; /** * Horizontal layout direction of this view is from Right to Left. * Use with {@link #setLayoutDirection}. */ static LAYOUT_DIRECTION_RTL:number = LayoutDirection.RTL; /** * Horizontal layout direction of this view is inherited from its parent. * Use with {@link #setLayoutDirection}. */ static LAYOUT_DIRECTION_INHERIT:number = LayoutDirection.INHERIT; /** * Horizontal layout direction of this view is from deduced from the default language * script for the locale. Use with {@link #setLayoutDirection}. */ static LAYOUT_DIRECTION_LOCALE:number = LayoutDirection.LOCALE; /** * Text direction is inherited thru {@link ViewGroup} */ static TEXT_DIRECTION_INHERIT:number = 0; /** * Text direction is using "first strong algorithm". The first strong directional character * determines the paragraph direction. If there is no strong directional character, the * paragraph direction is the view's resolved layout direction. */ static TEXT_DIRECTION_FIRST_STRONG:number = 1; /** * Text direction is using "any-RTL" algorithm. The paragraph direction is RTL if it contains * any strong RTL character, otherwise it is LTR if it contains any strong LTR characters. * If there are neither, the paragraph direction is the view's resolved layout direction. */ static TEXT_DIRECTION_ANY_RTL:number = 2; /** * Text direction is forced to LTR. */ static TEXT_DIRECTION_LTR:number = 3; /** * Text direction is forced to RTL. */ static TEXT_DIRECTION_RTL:number = 4; /** * Text direction is coming from the system Locale. */ static TEXT_DIRECTION_LOCALE:number = 5; /** * Default text direction is inherited */ private static TEXT_DIRECTION_DEFAULT:number = View.TEXT_DIRECTION_INHERIT; /** * Default resolved text direction * @hide */ static TEXT_DIRECTION_RESOLVED_DEFAULT:number = View.TEXT_DIRECTION_FIRST_STRONG; /* * Default text alignment. The text alignment of this View is inherited from its parent. * Use with {@link #setTextAlignment(int)} */ static TEXT_ALIGNMENT_INHERIT:number = 0; /** * Default for the root view. The gravity determines the text alignment, ALIGN_NORMAL, * ALIGN_CENTER, or ALIGN_OPPOSITE, which are relative to each paragraph’s text direction. * * Use with {@link #setTextAlignment(int)} */ static TEXT_ALIGNMENT_GRAVITY:number = 1; /** * Align to the start of the paragraph, e.g. ALIGN_NORMAL. * * Use with {@link #setTextAlignment(int)} */ static TEXT_ALIGNMENT_TEXT_START:number = 2; /** * Align to the end of the paragraph, e.g. ALIGN_OPPOSITE. * * Use with {@link #setTextAlignment(int)} */ static TEXT_ALIGNMENT_TEXT_END:number = 3; /** * Center the paragraph, e.g. ALIGN_CENTER. * * Use with {@link #setTextAlignment(int)} */ static TEXT_ALIGNMENT_CENTER:number = 4; /** * Align to the start of the view, which is ALIGN_LEFT if the view’s resolved * layoutDirection is LTR, and ALIGN_RIGHT otherwise. * * Use with {@link #setTextAlignment(int)} */ static TEXT_ALIGNMENT_VIEW_START:number = 5; /** * Align to the end of the view, which is ALIGN_RIGHT if the view’s resolved * layoutDirection is LTR, and ALIGN_LEFT otherwise. * * Use with {@link #setTextAlignment(int)} */ static TEXT_ALIGNMENT_VIEW_END:number = 6; /** * Default text alignment is inherited */ private static TEXT_ALIGNMENT_DEFAULT:number = View.TEXT_ALIGNMENT_GRAVITY; /** * Default resolved text alignment * @hide */ static TEXT_ALIGNMENT_RESOLVED_DEFAULT:number = View.TEXT_ALIGNMENT_GRAVITY; protected mID:string; protected mTag:any; protected mPrivateFlags = 0; private mPrivateFlags2 = 0; private mPrivateFlags3 = 0; protected mContext:Context; protected mCurrentAnimation:Animation = null; private mOldWidthMeasureSpec = Number.MIN_SAFE_INTEGER; private mOldHeightMeasureSpec = Number.MIN_SAFE_INTEGER; private mMeasuredWidth = 0; private mMeasuredHeight = 0; private mBackground:Drawable; private mBackgroundSizeChanged=false; private mBackgroundWidth = 0; private mBackgroundHeight = 0; private mScrollCache:ScrollabilityCache; private mDrawableState:Array<number>; private mNextFocusLeftId:string; private mNextFocusRightId:string; private mNextFocusUpId:string; private mNextFocusDownId:string; mNextFocusForwardId:string; private mPendingCheckForLongPress:CheckForLongPress; private mPendingCheckForTap:CheckForTap; private mPerformClick:PerformClick; private mPerformClickAfterPressDraw:PerformClickAfterPressDraw; private mUnsetPressedState:UnsetPressedState; private mHasPerformedLongPress = false; mMinWidth = 0; mMinHeight = 0; private mTouchDelegate : TouchDelegate; private mFloatingTreeObserver : ViewTreeObserver; /** * Solid color to use as a background when creating the drawing cache. Enables * the cache to use 16 bit bitmaps instead of 32 bit. */ private mDrawingCacheBackgroundColor = 0; private mUnscaledDrawingCache:Canvas; mTouchSlop = 0; private mVerticalScrollFactor = 0; private mOverScrollMode = View.OVER_SCROLL_IF_CONTENT_SCROLLS; mParent:ViewParent; private mMeasureCache:Map<string, number[]>; mAttachInfo:View.AttachInfo; mLayoutParams:ViewGroup.LayoutParams; mTransformationInfo:View.TransformationInfo; mViewFlags=0; mLayerType = View.LAYER_TYPE_NONE; mLocalDirtyRect:Rect; mCachingFailed = false; private mOverlay:ViewOverlay; private mWindowAttachCount=0; private mTransientStateCount = 0; private mListenerInfo:View.ListenerInfo; private mClipBounds:Rect; private mLastIsOpaque = false; private mMatchIdPredicate : MatchIdPredicate; private _mLeft = 0; private _mRight = 0; private _mTop = 0; private _mBottom = 0; get mLeft():number { return this._mLeft; } set mLeft(value:number) { this._mLeft = Math.floor(value); this.requestSyncBoundToElement(); } get mRight():number { return this._mRight; } set mRight(value:number) { this._mRight = Math.floor(value); this.requestSyncBoundToElement(); } get mTop():number { return this._mTop; } set mTop(value:number) { if (Number.isNaN(value)) { debugger; } this._mTop = Math.floor(value); this.requestSyncBoundToElement(); } get mBottom():number { return this._mBottom; } set mBottom(value:number) { this._mBottom = Math.floor(value); this.requestSyncBoundToElement(); } private _mScrollX = 0; private _mScrollY = 0; get mScrollX():number { return this._mScrollX; } set mScrollX(value:number) { this._mScrollX = Math.floor(value); this.requestSyncBoundToElement(); } get mScrollY():number { return this._mScrollY; } set mScrollY(value:number) { this._mScrollY = Math.floor(value); this.requestSyncBoundToElement(); } protected mPaddingLeft = 0; protected mPaddingRight = 0; protected mPaddingTop = 0; protected mPaddingBottom = 0; //androidui add: //clip with the cornerRadius: private mCornerRadiusTopLeft = 0; private mCornerRadiusTopRight = 0; private mCornerRadiusBottomRight = 0; private mCornerRadiusBottomLeft = 0; //draw shadow with background: private mShadowPaint:Paint; private mShadowDrawable:Drawable; constructor(context:Context, bindElement?:HTMLElement, defStyleAttr?:Map<string, string>) { super(); this.mContext = context; this.mTouchSlop = ViewConfiguration.get().getScaledTouchSlop(); // AndroidUI add logic: this.initBindAttr(); this.initBindElement(bindElement); // AndroidUI add end const a:TypedArray = context.obtainStyledAttributes(bindElement, defStyleAttr); let background:Drawable = null; let leftPadding = -1; let topPadding = -1; let rightPadding = -1; let bottomPadding = -1; // let startPadding = -1;//View.UNDEFINED_PADDING; // let endPadding = -1;//View.UNDEFINED_PADDING; let padding = -1; let viewFlagValues = 0; let viewFlagMasks = 0; let setScrollContainer = false; let x = 0; let y = 0; let tx = 0; let ty = 0; let rotation = 0; let rotationX = 0; let rotationY = 0; let sx = 1; let sy = 1; let transformSet = false; // let scrollbarStyle = View.SCROLLBARS_INSIDE_OVERLAY; let overScrollMode = this.mOverScrollMode; let initializeScrollbars = false; // let startPaddingDefined = false; // let endPaddingDefined = false; // let leftPaddingDefined = false; // let rightPaddingDefined = false; // const targetSdkVersion = context.getApplicationInfo().targetSdkVersion; for (let attr of a.getLowerCaseNoNamespaceAttrNames()) { switch (attr) { case 'background': background = a.getDrawable(attr); break; case 'padding': padding = a.getDimensionPixelSize(attr, -1); // this.mUserPaddingLeftInitial = padding; // this.mUserPaddingRightInitial = padding; // leftPaddingDefined = true; // rightPaddingDefined = true; break; case 'paddingleft': leftPadding = a.getDimensionPixelSize(attr, -1); // this.mUserPaddingLeftInitial = leftPadding; // leftPaddingDefined = true; break; case 'paddingtop': topPadding = a.getDimensionPixelSize(attr, -1); break; case 'paddingright': rightPadding = a.getDimensionPixelSize(attr, -1); // this.mUserPaddingRightInitial = rightPadding; // rightPaddingDefined = true; break; case 'paddingbottom': bottomPadding = a.getDimensionPixelSize(attr, -1); break; case 'paddingstart': leftPadding = a.getDimensionPixelSize(attr, -1); // leftPaddingDefined = true; // startPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); // startPaddingDefined = (startPadding != UNDEFINED_PADDING); break; case 'paddingend': rightPadding = a.getDimensionPixelSize(attr, -1); // rightPaddingDefined = true; // endPadding = a.getDimensionPixelSize(attr, UNDEFINED_PADDING); // endPaddingDefined = (endPadding != UNDEFINED_PADDING); break; case 'scrollx': x = a.getDimensionPixelOffset(attr, 0); break; case 'scrolly': y = a.getDimensionPixelOffset(attr, 0); break; case 'alpha': this.setAlpha(a.getFloat(attr, 1)); break; case 'transformpivotx': this.setPivotX(a.getDimensionPixelOffset(attr, 0)); break; case 'transformpivoty': this.setPivotY(a.getDimensionPixelOffset(attr, 0)); break; case 'translationx': tx = a.getDimensionPixelOffset(attr, 0); transformSet = true; break; case 'translationy': ty = a.getDimensionPixelOffset(attr, 0); transformSet = true; break; case 'rotation': rotation = a.getFloat(attr, 0); transformSet = true; break; case 'rotationx': rotationX = a.getFloat(attr, 0); transformSet = true; break; case 'rotationy': rotationY = a.getFloat(attr, 0); transformSet = true; break; case 'scalex': sx = a.getFloat(attr, 1); transformSet = true; break; case 'scaley': sy = a.getFloat(attr, 1); transformSet = true; break; case 'id': this.mID = a.getString(attr); break; case 'tag': this.mTag = a.getText(attr); break; case 'fitssystemwindows': // if (a.getBoolean(attr, false)) { // viewFlagValues |= FITS_SYSTEM_WINDOWS; // viewFlagMasks |= FITS_SYSTEM_WINDOWS; // } break; case 'focusable': if (a.getBoolean(attr, false)) { viewFlagValues |= View.FOCUSABLE; viewFlagMasks |= View.FOCUSABLE_MASK; } break; case 'focusableintouchmode': if (a.getBoolean(attr, false)) { viewFlagValues |= View.FOCUSABLE_IN_TOUCH_MODE | View.FOCUSABLE; viewFlagMasks |= View.FOCUSABLE_IN_TOUCH_MODE | View.FOCUSABLE_MASK; } break; case 'clickable': if (a.getBoolean(attr, false)) { viewFlagValues |= View.CLICKABLE; viewFlagMasks |= View.CLICKABLE; } break; case 'longclickable': if (a.getBoolean(attr, false)) { viewFlagValues |= View.LONG_CLICKABLE; viewFlagMasks |= View.LONG_CLICKABLE; } break; case 'saveenabled': // if (!a.getBoolean(attr, true)) { // viewFlagValues |= View.SAVE_DISABLED; // viewFlagMasks |= View.SAVE_DISABLED_MASK; // } break; case 'duplicateparentstate': if (a.getBoolean(attr, false)) { viewFlagValues |= View.DUPLICATE_PARENT_STATE; viewFlagMasks |= View.DUPLICATE_PARENT_STATE; } break; case 'visibility': const visibility = a.getAttrValue(attr); if(visibility === 'gone') { viewFlagValues |= View.GONE; viewFlagMasks |= View.VISIBILITY_MASK; } else if(visibility === 'invisible') { viewFlagValues |= View.INVISIBLE; viewFlagMasks |= View.VISIBILITY_MASK; } else if(visibility === 'visible') { viewFlagValues |= View.VISIBLE; viewFlagMasks |= View.VISIBILITY_MASK; } break; case 'layoutdirection': // // Clear any layout direction flags (included resolved bits) already set // this.mPrivateFlags2 &= // ~(PFLAG2_LAYOUT_DIRECTION_MASK | PFLAG2_LAYOUT_DIRECTION_RESOLVED_MASK); // // Set the layout direction flags depending on the value of the attribute // const layoutDirection = a.getInt(attr, -1); // const value = (layoutDirection != -1) ? // LAYOUT_DIRECTION_FLAGS[layoutDirection] : LAYOUT_DIRECTION_DEFAULT; // this.mPrivateFlags2 |= (value << PFLAG2_LAYOUT_DIRECTION_MASK_SHIFT); break; case 'drawingcachequality': // const cacheQuality = a.getInt(attr, 0); // if (cacheQuality != 0) { // viewFlagValues |= View.DRAWING_CACHE_QUALITY_FLAGS[cacheQuality]; // viewFlagMasks |= View.DRAWING_CACHE_QUALITY_MASK; // } break; case 'contentdescription': // this.setContentDescription(a.getString(attr)); break; case 'labelfor': // this.setLabelFor(a.getString(attr)); break; case 'soundeffectsenabled': // if (!a.getBoolean(attr, true)) { // viewFlagValues &= ~View.SOUND_EFFECTS_ENABLED; // viewFlagMasks |= View.SOUND_EFFECTS_ENABLED; // } break; case 'hapticfeedbackenabled': // if (!a.getBoolean(attr, true)) { // viewFlagValues &= ~View.HAPTIC_FEEDBACK_ENABLED; // viewFlagMasks |= View.HAPTIC_FEEDBACK_ENABLED; // } break; case 'scrollbars': const scrollbars = a.getAttrValue(attr); if (scrollbars === 'horizontal') { viewFlagValues |= View.SCROLLBARS_HORIZONTAL; viewFlagMasks |= View.SCROLLBARS_MASK; initializeScrollbars = true; } else if (scrollbars === 'vertical') { viewFlagValues |= View.SCROLLBARS_VERTICAL; viewFlagMasks |= View.SCROLLBARS_MASK; initializeScrollbars = true; } break; //noinspection deprecation case 'fadingedge': // if (targetSdkVersion >= ICE_CREAM_SANDWICH) { // // Ignore the attribute starting with ICS // break; // } // With builds < ICS, fall through and apply fading edges case 'requiresfadingedge': // const fadingEdge = a.getInt(attr, FADING_EDGE_NONE); // if (fadingEdge != FADING_EDGE_NONE) { // viewFlagValues |= fadingEdge; // viewFlagMasks |= View.FADING_EDGE_MASK; // this.initializeFadingEdge(a); // } break; case 'scrollbarstyle': // scrollbarStyle = a.getInt(attr, View.SCROLLBARS_INSIDE_OVERLAY); // if (scrollbarStyle != View.SCROLLBARS_INSIDE_OVERLAY) { // viewFlagValues |= scrollbarStyle & View.SCROLLBARS_STYLE_MASK; // viewFlagMasks |= View.SCROLLBARS_STYLE_MASK; // } break; case 'isscrollcontainer': setScrollContainer = true; if (a.getBoolean(attr, false)) { this.setScrollContainer(true); } break; case 'keepscreenon': // if (a.getBoolean(attr, false)) { // viewFlagValues |= View.KEEP_SCREEN_ON; // viewFlagMasks |= View.KEEP_SCREEN_ON; // } break; case 'filtertoucheswhenobscured': // if (a.getBoolean(attr, false)) { // viewFlagValues |= View.FILTER_TOUCHES_WHEN_OBSCURED; // viewFlagMasks |= View.FILTER_TOUCHES_WHEN_OBSCURED; // } break; case 'nextfocusleft': this.mNextFocusLeftId = a.getResourceId(attr, View.NO_ID); break; case 'nextfocusright': this.mNextFocusRightId = a.getResourceId(attr, View.NO_ID); break; case 'nextfocusup': this.mNextFocusUpId = a.getResourceId(attr, View.NO_ID); break; case 'nextfocusdown': this.mNextFocusDownId = a.getResourceId(attr, View.NO_ID); break; case 'nextfocusforward': this.mNextFocusForwardId = a.getResourceId(attr, View.NO_ID); break; case 'minwidth': this.mMinWidth = a.getDimensionPixelSize(attr, 0); break; case 'minheight': this.mMinHeight = a.getDimensionPixelSize(attr, 0); break; case 'onclick': this.setOnClickListenerByAttrValueString(a.getString(attr)); break; case 'overscrollmode': let scrollMode = View[('OVER_SCROLL_'+a.getAttrValue(attr)).toUpperCase()]; overScrollMode = scrollMode || View.OVER_SCROLL_IF_CONTENT_SCROLLS; break; case 'verticalscrollbarposition': // this.mVerticalScrollbarPosition = a.getInt(attr, SCROLLBAR_POSITION_DEFAULT); break; case 'layertype': if((a.getAttrValue(attr)+'').toLowerCase() == 'software') { this.setLayerType(View.LAYER_TYPE_SOFTWARE); }else{ this.setLayerType(View.LAYER_TYPE_NONE); } break; case 'textdirection': // Clear any text direction flag already set // this.mPrivateFlags2 &= ~PFLAG2_TEXT_DIRECTION_MASK; // // Set the text direction flags depending on the value of the attribute // final int textDirection = a.getInt(attr, -1); // if (textDirection != -1) { // this.mPrivateFlags2 |= PFLAG2_TEXT_DIRECTION_FLAGS[textDirection]; // } break; case 'textalignment': // // Clear any text alignment flag already set // this.mPrivateFlags2 &= ~PFLAG2_TEXT_ALIGNMENT_MASK; // // Set the text alignment flag depending on the value of the attribute // final int textAlignment = a.getInt(attr, TEXT_ALIGNMENT_DEFAULT); // this.mPrivateFlags2 |= PFLAG2_TEXT_ALIGNMENT_FLAGS[textAlignment]; break; case 'importantforaccessibility': // setImportantForAccessibility(a.getInt(attr, IMPORTANT_FOR_ACCESSIBILITY_DEFAULT)); break; case 'accessibilityliveregion': // setAccessibilityLiveRegion(a.getInt(attr, ACCESSIBILITY_LIVE_REGION_DEFAULT)); break; case 'cornerradius': case 'cornerradiustopleft': case 'cornerradiustopright': case 'cornerradiusbottomleft': case 'cornerradiusbottomright': case 'viewshadowcolor': case 'viewshadowdx': case 'viewshadowdy': case 'viewshadowradius': //AndroidUIX add: these cases, attr pass to attr Binder (let attr Binder parse and set these values). this._attrBinder.onAttrChange(attr, a.getAttrValue(attr), this.getContext()); break; default: if (attr && attr.startsWith('state_')) { this._stateAttrList.addStatedAttr(attr, a.getAttrValue(attr)); } } } this.setOverScrollMode(overScrollMode); // // Cache start/end user padding as we cannot fully resolve padding here (we dont have yet // // the resolved layout direction). Those cached values will be used later during padding // // resolution. // this.mUserPaddingStart = startPadding; // this.mUserPaddingEnd = endPadding; if (background != null) { this.setBackground(background); } // setBackground above will record that padding is currently provided by the background. // If we have padding specified via xml, record that here instead and use it. // this.mLeftPaddingDefined = leftPaddingDefined; // this.mRightPaddingDefined = rightPaddingDefined; if (padding >= 0) { leftPadding = padding; topPadding = padding; rightPadding = padding; bottomPadding = padding; // this.mUserPaddingLeftInitial = padding; // this.mUserPaddingRightInitial = padding; } // if (isRtlCompatibilityMode()) { // // RTL compatibility mode: pre Jelly Bean MR1 case OR no RTL support case. // // left / right padding are used if defined (meaning here nothing to do). If they are not // // defined and start / end padding are defined (e.g. in Frameworks resources), then we use // // start / end and resolve them as left / right (layout direction is not taken into account). // // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial // // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if // // defined. // if (!mLeftPaddingDefined && startPaddingDefined) { // leftPadding = startPadding; // } // this.mUserPaddingLeftInitial = (leftPadding >= 0) ? leftPadding : this.mUserPaddingLeftInitial; // if (!mRightPaddingDefined && endPaddingDefined) { // rightPadding = endPadding; // } // this.mUserPaddingRightInitial = (rightPadding >= 0) ? rightPadding : this.mUserPaddingRightInitial; // } else { // // Jelly Bean MR1 and after case: if start/end defined, they will override any left/right // // values defined. Otherwise, left /right values are used. // // Padding from the background drawable is stored at this point in mUserPaddingLeftInitial // // and mUserPaddingRightInitial) so drawable padding will be used as ultimate default if // // defined. // const hasRelativePadding = startPaddingDefined || endPaddingDefined; // // if (mLeftPaddingDefined && !hasRelativePadding) { // this.mUserPaddingLeftInitial = leftPadding; // } // if (mRightPaddingDefined && !hasRelativePadding) { // this.mUserPaddingRightInitial = rightPadding; // } // } this.setPadding(leftPadding >= 0 ? leftPadding : this.mPaddingLeft, topPadding >= 0 ? topPadding : this.mPaddingTop, rightPadding >= 0 ? rightPadding : this.mPaddingRight, bottomPadding >= 0 ? bottomPadding : this.mPaddingBottom); if (viewFlagMasks != 0) { this.setFlags(viewFlagValues, viewFlagMasks); } if (initializeScrollbars) { this.initializeScrollbars(a); } a.recycle(); // // Needs to be called after mViewFlags is set // if (scrollbarStyle != View.SCROLLBARS_INSIDE_OVERLAY) { // this.recomputePadding(); // } if (x != 0 || y != 0) { scrollTo(x, y); } if (transformSet) { this.setTranslationX(tx); this.setTranslationY(ty); this.setRotation(rotation); this.setRotationX(rotationX); this.setRotationY(rotationY); this.setScaleX(sx); this.setScaleY(sy); } if (!setScrollContainer && (viewFlagValues&View.SCROLLBARS_VERTICAL) != 0) { this.setScrollContainer(true); } this.computeOpaqueFlags(); } getContext():Context { return this.mContext; } getWidth():number { return this.mRight - this.mLeft; } getHeight():number { return this.mBottom - this.mTop; } getPaddingLeft():number{ return this.mPaddingLeft; } getPaddingTop():number{ return this.mPaddingTop; } getPaddingRight():number{ return this.mPaddingRight; } getPaddingBottom():number{ return this.mPaddingBottom; } setPaddingLeft(left:number):void{ if (this.mPaddingLeft != left) { this.mPaddingLeft = left; this.requestLayout(); } } setPaddingTop(top:number):void{ if (this.mPaddingTop != top) { this.mPaddingTop = top; this.requestLayout(); } } setPaddingRight(right:number):void{ if (this.mPaddingRight != right) { this.mPaddingRight = right; this.requestLayout(); } } setPaddingBottom(bottom:number):void{ if (this.mPaddingBottom != bottom) { this.mPaddingBottom = bottom; this.requestLayout(); } } setPadding(left:number, top:number, right:number, bottom:number){ let changed = false; if (this.mPaddingLeft != left) { changed = true; this.mPaddingLeft = left; } if (this.mPaddingTop != top) { changed = true; this.mPaddingTop = top; } if (this.mPaddingRight != right) { changed = true; this.mPaddingRight = right; } if (this.mPaddingBottom != bottom) { changed = true; this.mPaddingBottom = bottom; } if (changed) { this.requestLayout(); } } resolvePadding():void { //no need resolve padding.(not support RTL now) } setScrollX(value:number) { this.scrollTo(value, this.mScrollY); } setScrollY(value:number) { this.scrollTo(this.mScrollX, value); } getScrollX():number { return this.mScrollX; } getScrollY():number { return this.mScrollY; } /** * Offset this view's vertical location by the specified number of pixels. * * @param offset the number of pixels to offset the view by */ offsetTopAndBottom(offset:number):void { if (offset != 0) { this.updateMatrix(); const matrixIsIdentity = this.mTransformationInfo == null || this.mTransformationInfo.mMatrixIsIdentity; if (matrixIsIdentity) { // if (mDisplayList != null) { // invalidateViewProperty(false, false); // } else { const p = this.mParent; if (p != null && this.mAttachInfo != null) { const r = this.mAttachInfo.mTmpInvalRect; let minTop; let maxBottom; let yLoc; if (offset < 0) { minTop = this.mTop + offset; maxBottom = this.mBottom; yLoc = offset; } else { minTop = this.mTop; maxBottom = this.mBottom + offset; yLoc = 0; } r.set(0, yLoc, this.mRight - this.mLeft, maxBottom - minTop); p.invalidateChild(this, r); } // } } else { this.invalidateViewProperty(false, false); } this.mTop += offset; this.mBottom += offset; // if (mDisplayList != null) { // mDisplayList.offsetTopAndBottom(offset); // invalidateViewProperty(false, false); // } else { if (!matrixIsIdentity) { this.invalidateViewProperty(false, true); } this.invalidateParentIfNeeded(); // } } } /** * Offset this view's horizontal location by the specified amount of pixels. * * @param offset the number of pixels to offset the view by */ offsetLeftAndRight(offset:number) { if (offset != 0) { this.updateMatrix(); const matrixIsIdentity = this.mTransformationInfo == null || this.mTransformationInfo.mMatrixIsIdentity; if (matrixIsIdentity) { // if (mDisplayList != null) { // invalidateViewProperty(false, false); // } else { const p = this.mParent; if (p != null && this.mAttachInfo != null) { const r = this.mAttachInfo.mTmpInvalRect; let minLeft; let maxRight; if (offset < 0) { minLeft = this.mLeft + offset; maxRight = this.mRight; } else { minLeft = this.mLeft; maxRight = this.mRight + offset; } r.set(0, 0, maxRight - minLeft, this.mBottom - this.mTop); p.invalidateChild(this, r); } // } } else { this.invalidateViewProperty(false, false); } this.mLeft += offset; this.mRight += offset; // if (mDisplayList != null) { // mDisplayList.offsetLeftAndRight(offset); // invalidateViewProperty(false, false); // } else { if (!matrixIsIdentity) { this.invalidateViewProperty(false, true); } this.invalidateParentIfNeeded(); // } } } /** * The transform matrix of this view, which is calculated based on the current * roation, scale, and pivot properties. * * @see #getRotation() * @see #getScaleX() * @see #getScaleY() * @see #getPivotX() * @see #getPivotY() * @return The current transform matrix for the view */ getMatrix():Matrix { if (this.mTransformationInfo != null) { this.updateMatrix(); return this.mTransformationInfo.mMatrix; } return Matrix.IDENTITY_MATRIX; } ///** // * Utility function to determine if the value is far enough away from zero to be // * considered non-zero. // * @param value A floating point value to check for zero-ness // * @return whether the passed-in value is far enough away from zero to be considered non-zero // */ //private static nonzero(value:number):boolean { // return (value < -View.NONZERO_EPSILON || value > View.NONZERO_EPSILON); //} /** * Returns true if the transform matrix is the identity matrix. * Recomputes the matrix if necessary. * * @return True if the transform matrix is the identity matrix, false otherwise. */ hasIdentityMatrix():boolean { if (this.mTransformationInfo != null) { this.updateMatrix(); return this.mTransformationInfo.mMatrixIsIdentity; } return true; } ensureTransformationInfo():void { if (this.mTransformationInfo == null) { this.mTransformationInfo = new View.TransformationInfo(); } } /** * Recomputes the transform matrix if necessary. */ private updateMatrix():void { const info:View.TransformationInfo = this.mTransformationInfo; if (info == null) { this._syncMatrixToElement(); return; } if (info.mMatrixDirty) { // Figure out if we need to update the pivot point if ((this.mPrivateFlags & View.PFLAG_PIVOT_EXPLICITLY_SET) == 0) { if ((this.mRight - this.mLeft) != info.mPrevWidth || (this.mBottom - this.mTop) != info.mPrevHeight) { info.mPrevWidth = this.mRight - this.mLeft; info.mPrevHeight = this.mBottom - this.mTop; info.mPivotX = info.mPrevWidth / 2; info.mPivotY = info.mPrevHeight / 2; } } info.mMatrix.reset(); //if (!View.nonzero(info.mRotationX) && !View.nonzero(info.mRotationY)) { info.mMatrix.setTranslate(info.mTranslationX, info.mTranslationY); info.mMatrix.preRotate(info.mRotation, info.mPivotX, info.mPivotY); info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); //} else { // if (info.mCamera == null) { // info.mCamera = new Camera(); // info.matrix3D = new Matrix(); // } // info.mCamera.save(); // info.mMatrix.preScale(info.mScaleX, info.mScaleY, info.mPivotX, info.mPivotY); // info.mCamera.rotate(info.mRotationX, info.mRotationY, -info.mRotation); // info.mCamera.getMatrix(info.matrix3D); // info.matrix3D.preTranslate(-info.mPivotX, -info.mPivotY); // info.matrix3D.postTranslate(info.mPivotX + info.mTranslationX, info.mPivotY + info.mTranslationY); // info.mMatrix.postConcat(info.matrix3D); // info.mCamera.restore(); //} info.mMatrixDirty = false; info.mMatrixIsIdentity = info.mMatrix.isIdentity(); info.mInverseMatrixDirty = true; } this._syncMatrixToElement(); } ///** // * Utility method to retrieve the inverse of the current mMatrix property. // * We cache the matrix to avoid recalculating it when transform properties // * have not changed. // * // * @return The inverse of the current matrix of this view. // */ //getInverseMatrix():Matrix { // const info:View.TransformationInfo = this.mTransformationInfo; // if (info != null) { // this.updateMatrix(); // if (info.mInverseMatrixDirty) { // if (info.mInverseMatrix == null) { // info.mInverseMatrix = new Matrix(); // } // info.mMatrix.invert(info.mInverseMatrix); // info.mInverseMatrixDirty = false; // } // return info.mInverseMatrix; // } // return Matrix.IDENTITY_MATRIX; //} ///** // * Gets the distance along the Z axis from the camera to this view. // * // * @see #setCameraDistance(float) // * // * @return The distance along the Z axis. // */ //getCameraDistance():number { // this.ensureTransformationInfo(); // const dpi:number = this.mResources.getDisplayMetrics().densityDpi; // const info:View.TransformationInfo = this.mTransformationInfo; // if (info.mCamera == null) { // info.mCamera = new Camera(); // info.matrix3D = new Matrix(); // } // return -(info.mCamera.getLocationZ() * dpi); //} // ///** // * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which // * views are drawn) from the camera to this view. The camera's distance // * affects 3D transformations, for instance rotations around the X and Y // * axis. If the rotationX or rotationY properties are changed and this view is // * large (more than half the size of the screen), it is recommended to always // * use a camera distance that's greater than the height (X axis rotation) or // * the width (Y axis rotation) of this view.</p> // * // * <p>The distance of the camera from the view plane can have an affect on the // * perspective distortion of the view when it is rotated around the x or y axis. // * For example, a large distance will result in a large viewing angle, and there // * will not be much perspective distortion of the view as it rotates. A short // * distance may cause much more perspective distortion upon rotation, and can // * also result in some drawing artifacts if the rotated view ends up partially // * behind the camera (which is why the recommendation is to use a distance at // * least as far as the size of the view, if the view is to be rotated.)</p> // * // * <p>The distance is expressed in "depth pixels." The default distance depends // * on the screen density. For instance, on a medium density display, the // * default distance is 1280. On a high density display, the default distance // * is 1920.</p> // * // * <p>If you want to specify a distance that leads to visually consistent // * results across various densities, use the following formula:</p> // * <pre> // * float scale = context.getResources().getDisplayMetrics().density; // * view.setCameraDistance(distance * scale); // * </pre> // * // * <p>The density scale factor of a high density display is 1.5, // * and 1920 = 1280 * 1.5.</p> // * // * @param distance The distance in "depth pixels", if negative the opposite // * value is used // * // * @see #setRotationX(float) // * @see #setRotationY(float) // */ //setCameraDistance(distance:number):void { // this.invalidateViewProperty(true, false); // this.ensureTransformationInfo(); // const dpi:number = this.mResources.getDisplayMetrics().densityDpi; // const info:View.TransformationInfo = this.mTransformationInfo; // if (info.mCamera == null) { // info.mCamera = new Camera(); // info.matrix3D = new Matrix(); // } // info.mCamera.setLocation(0.0, 0.0, -Math.abs(distance) / dpi); // info.mMatrixDirty = true; // this.invalidateViewProperty(false, false); // if (this.mDisplayList != null) { // this.mDisplayList.setCameraDistance(-Math.abs(distance) / dpi); // } // if ((this.mPrivateFlags2 & View.PFLAG2_VIEW_QUICK_REJECTED) == View.PFLAG2_VIEW_QUICK_REJECTED) { // // View was rejected last time it was drawn by its parent; this may have changed // this.invalidateParentIfNeeded(); // } //} /** * The degrees that the view is rotated around the pivot point. * * @see #setRotation(float) * @see #getPivotX() * @see #getPivotY() * * @return The degrees of rotation. */ getRotation():number { return this.mTransformationInfo != null ? this.mTransformationInfo.mRotation : 0; } /** * Sets the degrees that the view is rotated around the pivot point. Increasing values * result in clockwise rotation. * * @param rotation The degrees of rotation. * * @see #getRotation() * @see #getPivotX() * @see #getPivotY() * @see #setRotationX(float) * @see #setRotationY(float) * * @attr ref android.R.styleable#View_rotation */ setRotation(rotation:number):void { this.ensureTransformationInfo(); const info:View.TransformationInfo = this.mTransformationInfo; if (info.mRotation != rotation) { // Double-invalidation is necessary to capture view's old and new areas this.invalidateViewProperty(true, false); info.mRotation = rotation; info.mMatrixDirty = true; this.invalidateViewProperty(false, true); //if (this.mDisplayList != null) { // this.mDisplayList.setRotation(rotation); //} if ((this.mPrivateFlags2 & View.PFLAG2_VIEW_QUICK_REJECTED) == View.PFLAG2_VIEW_QUICK_REJECTED) { // View was rejected last time it was drawn by its parent; this may have changed this.invalidateParentIfNeeded(); } } } /** * The degrees that the view is rotated around the vertical axis through the pivot point. * * @see #getPivotX() * @see #getPivotY() * @see #setRotationY(float) * * @return The degrees of Y rotation. */ getRotationY():number { return 0;//this.mTransformationInfo != null ? this.mTransformationInfo.mRotationY : 0; } /** * Sets the degrees that the view is rotated around the vertical axis through the pivot point. * Increasing values result in counter-clockwise rotation from the viewpoint of looking * down the y axis. * * When rotating large views, it is recommended to adjust the camera distance * accordingly. Refer to {@link #setCameraDistance(float)} for more information. * * @param rotationY The degrees of Y rotation. * * @see #getRotationY() * @see #getPivotX() * @see #getPivotY() * @see #setRotation(float) * @see #setRotationX(float) * @see #setCameraDistance(float) * * @attr ref android.R.styleable#View_rotationY */ setRotationY(rotationY:number):void { // this.ensureTransformationInfo(); // const info:View.TransformationInfo = this.mTransformationInfo; // if (info.mRotationY != rotationY) { // this.invalidateViewProperty(true, false); // info.mRotationY = rotationY; // info.mMatrixDirty = true; // this.invalidateViewProperty(false, true); // if (this.mDisplayList != null) { // this.mDisplayList.setRotationY(rotationY); // } // if ((this.mPrivateFlags2 & View.PFLAG2_VIEW_QUICK_REJECTED) == View.PFLAG2_VIEW_QUICK_REJECTED) { // // View was rejected last time it was drawn by its parent; this may have changed // this.invalidateParentIfNeeded(); // } // } } /** * The degrees that the view is rotated around the horizontal axis through the pivot point. * * @see #getPivotX() * @see #getPivotY() * @see #setRotationX(float) * * @return The degrees of X rotation. */ getRotationX():number { return 0;//this.mTransformationInfo != null ? this.mTransformationInfo.mRotationX : 0; } /** * Sets the degrees that the view is rotated around the horizontal axis through the pivot point. * Increasing values result in clockwise rotation from the viewpoint of looking down the * x axis. * * When rotating large views, it is recommended to adjust the camera distance * accordingly. Refer to {@link #setCameraDistance(float)} for more information. * * @param rotationX The degrees of X rotation. * * @see #getRotationX() * @see #getPivotX() * @see #getPivotY() * @see #setRotation(float) * @see #setRotationY(float) * @see #setCameraDistance(float) * * @attr ref android.R.styleable#View_rotationX */ setRotationX(rotationX:number):void { // this.ensureTransformationInfo(); // const info:View.TransformationInfo = this.mTransformationInfo; // if (info.mRotationX != rotationX) { // this.invalidateViewProperty(true, false); // info.mRotationX = rotationX; // info.mMatrixDirty = true; // this.invalidateViewProperty(false, true); // if (this.mDisplayList != null) { // this.mDisplayList.setRotationX(rotationX); // } // if ((this.mPrivateFlags2 & View.PFLAG2_VIEW_QUICK_REJECTED) == View.PFLAG2_VIEW_QUICK_REJECTED) { // // View was rejected last time it was drawn by its parent; this may have changed // this.invalidateParentIfNeeded(); // } // } } /** * The amount that the view is scaled in x around the pivot point, as a proportion of * the view's unscaled width. A value of 1, the default, means that no scaling is applied. * * <p>By default, this is 1.0f. * * @see #getPivotX() * @see #getPivotY() * @return The scaling factor. */ getScaleX():number { return this.mTransformationInfo != null ? this.mTransformationInfo.mScaleX : 1; } /** * Sets the amount that the view is scaled in x around the pivot point, as a proportion of * the view's unscaled width. A value of 1 means that no scaling is applied. * * @param scaleX The scaling factor. * @see #getPivotX() * @see #getPivotY() * * @attr ref android.R.styleable#View_scaleX */ setScaleX(scaleX:number):void { this.ensureTransformationInfo(); const info:View.TransformationInfo = this.mTransformationInfo; if (info.mScaleX != scaleX) { this.invalidateViewProperty(true, false); info.mScaleX = scaleX; info.mMatrixDirty = true; this.invalidateViewProperty(false, true); //if (this.mDisplayList != null) { // this.mDisplayList.setScaleX(scaleX); //} if ((this.mPrivateFlags2 & View.PFLAG2_VIEW_QUICK_REJECTED) == View.PFLAG2_VIEW_QUICK_REJECTED) { // View was rejected last time it was drawn by its parent; this may have changed this.invalidateParentIfNeeded(); } } } /** * The amount that the view is scaled in y around the pivot point, as a proportion of * the view's unscaled height. A value of 1, the default, means that no scaling is applied. * * <p>By default, this is 1.0f. * * @see #getPivotX() * @see #getPivotY() * @return The scaling factor. */ getScaleY():number { return this.mTransformationInfo != null ? this.mTransformationInfo.mScaleY : 1; } /** * Sets the amount that the view is scaled in Y around the pivot point, as a proportion of * the view's unscaled width. A value of 1 means that no scaling is applied. * * @param scaleY The scaling factor. * @see #getPivotX() * @see #getPivotY() * * @attr ref android.R.styleable#View_scaleY */ setScaleY(scaleY:number):void { this.ensureTransformationInfo(); const info:View.TransformationInfo = this.mTransformationInfo; if (info.mScaleY != scaleY) { this.invalidateViewProperty(true, false); info.mScaleY = scaleY; info.mMatrixDirty = true; this.invalidateViewProperty(false, true); //if (this.mDisplayList != null) { // this.mDisplayList.setScaleY(scaleY); //} if ((this.mPrivateFlags2 & View.PFLAG2_VIEW_QUICK_REJECTED) == View.PFLAG2_VIEW_QUICK_REJECTED) { // View was rejected last time it was drawn by its parent; this may have changed this.invalidateParentIfNeeded(); } } } /** * The x location of the point around which the view is {@link #setRotation(float) rotated} * and {@link #setScaleX(float) scaled}. * * @see #getRotation() * @see #getScaleX() * @see #getScaleY() * @see #getPivotY() * @return The x location of the pivot point. * * @attr ref android.R.styleable#View_transformPivotX */ getPivotX():number { return this.mTransformationInfo != null ? this.mTransformationInfo.mPivotX : 0; } /** * Sets the x location of the point around which the view is * {@link #setRotation(float) rotated} and {@link #setScaleX(float) scaled}. * By default, the pivot point is centered on the object. * Setting this property disables this behavior and causes the view to use only the * explicitly set pivotX and pivotY values. * * @param pivotX The x location of the pivot point. * @see #getRotation() * @see #getScaleX() * @see #getScaleY() * @see #getPivotY() * * @attr ref android.R.styleable#View_transformPivotX */ setPivotX(pivotX:number):void { this.ensureTransformationInfo(); const info:View.TransformationInfo = this.mTransformationInfo; let pivotSet:boolean = (this.mPrivateFlags & View.PFLAG_PIVOT_EXPLICITLY_SET) == View.PFLAG_PIVOT_EXPLICITLY_SET; if (info.mPivotX != pivotX || !pivotSet) { this.mPrivateFlags |= View.PFLAG_PIVOT_EXPLICITLY_SET; this.invalidateViewProperty(true, false); info.mPivotX = pivotX; info.mMatrixDirty = true; this.invalidateViewProperty(false, true); //if (this.mDisplayList != null) { // this.mDisplayList.setPivotX(pivotX); //} if ((this.mPrivateFlags2 & View.PFLAG2_VIEW_QUICK_REJECTED) == View.PFLAG2_VIEW_QUICK_REJECTED) { // View was rejected last time it was drawn by its parent; this may have changed this.invalidateParentIfNeeded(); } } } /** * The y location of the point around which the view is {@link #setRotation(float) rotated} * and {@link #setScaleY(float) scaled}. * * @see #getRotation() * @see #getScaleX() * @see #getScaleY() * @see #getPivotY() * @return The y location of the pivot point. * * @attr ref android.R.styleable#View_transformPivotY */ getPivotY():number { return this.mTransformationInfo != null ? this.mTransformationInfo.mPivotY : 0; } /** * Sets the y location of the point around which the view is {@link #setRotation(float) rotated} * and {@link #setScaleY(float) scaled}. By default, the pivot point is centered on the object. * Setting this property disables this behavior and causes the view to use only the * explicitly set pivotX and pivotY values. * * @param pivotY The y location of the pivot point. * @see #getRotation() * @see #getScaleX() * @see #getScaleY() * @see #getPivotY() * * @attr ref android.R.styleable#View_transformPivotY */ setPivotY(pivotY:number):void { this.ensureTransformationInfo(); const info:View.TransformationInfo = this.mTransformationInfo; let pivotSet:boolean = (this.mPrivateFlags & View.PFLAG_PIVOT_EXPLICITLY_SET) == View.PFLAG_PIVOT_EXPLICITLY_SET; if (info.mPivotY != pivotY || !pivotSet) { this.mPrivateFlags |= View.PFLAG_PIVOT_EXPLICITLY_SET; this.invalidateViewProperty(true, false); info.mPivotY = pivotY; info.mMatrixDirty = true; this.invalidateViewProperty(false, true); //if (this.mDisplayList != null) { // this.mDisplayList.setPivotY(pivotY); //} if ((this.mPrivateFlags2 & View.PFLAG2_VIEW_QUICK_REJECTED) == View.PFLAG2_VIEW_QUICK_REJECTED) { // View was rejected last time it was drawn by its parent; this may have changed this.invalidateParentIfNeeded(); } } } /** * The opacity of the view. This is a value from 0 to 1, where 0 means the view is * completely transparent and 1 means the view is completely opaque. * * <p>By default this is 1.0f. * @return The opacity of the view. */ getAlpha():number { return this.mTransformationInfo != null ? this.mTransformationInfo.mAlpha : 1; } /** * Returns whether this View has content which overlaps. * * <p>This function, intended to be overridden by specific View types, is an optimization when * alpha is set on a view. If rendering overlaps in a view with alpha < 1, that view is drawn to * an offscreen buffer and then composited into place, which can be expensive. If the view has * no overlapping rendering, the view can draw each primitive with the appropriate alpha value * directly. An example of overlapping rendering is a TextView with a background image, such as * a Button. An example of non-overlapping rendering is a TextView with no background, or an * ImageView with only the foreground image. The default implementation returns true; subclasses * should override if they have cases which can be optimized.</p> * * <p>The current implementation of the saveLayer and saveLayerAlpha methods in {@link Canvas} * necessitates that a View return true if it uses the methods internally without passing the * {@link Canvas#CLIP_TO_LAYER_SAVE_FLAG}.</p> * * @return true if the content in this view might overlap, false otherwise. */ hasOverlappingRendering():boolean { return true; } /** * <p>Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is * completely transparent and 1 means the view is completely opaque.</p> * * <p> Note that setting alpha to a translucent value (0 < alpha < 1) can have significant * performance implications, especially for large views. It is best to use the alpha property * sparingly and transiently, as in the case of fading animations.</p> * * <p>For a view with a frequently changing alpha, such as during a fading animation, it is * strongly recommended for performance reasons to either override * {@link #hasOverlappingRendering()} to return false if appropriate, or setting a * {@link #setLayerType(int, android.graphics.Paint) layer type} on the view.</p> * * <p>If this view overrides {@link #onSetAlpha(int)} to return true, then this view is * responsible for applying the opacity itself.</p> * * <p>Note that if the view is backed by a * {@link #setLayerType(int, android.graphics.Paint) layer} and is associated with a * {@link #setLayerPaint(android.graphics.Paint) layer paint}, setting an alpha value less than * 1.0 will supercede the alpha of the layer paint.</p> * * @param alpha The opacity of the view. * * @see #hasOverlappingRendering() * @see #setLayerType(int, android.graphics.Paint) * * @attr ref android.R.styleable#View_alpha */ setAlpha(alpha:number):void { this.ensureTransformationInfo(); if (this.mTransformationInfo.mAlpha != alpha) { this.mTransformationInfo.mAlpha = alpha; if (this.onSetAlpha(Math.floor((alpha * 255)))) { this.mPrivateFlags |= View.PFLAG_ALPHA_SET; // subclass is handling alpha - don't optimize rendering cache invalidation this.invalidateParentCaches(); this.invalidate(true); } else { this.mPrivateFlags &= ~View.PFLAG_ALPHA_SET; this.invalidateViewProperty(true, false); //if (this.mDisplayList != null) { // this.mDisplayList.setAlpha(this.getFinalAlpha()); //} } } } /** * Faster version of setAlpha() which performs the same steps except there are * no calls to invalidate(). The caller of this function should perform proper invalidation * on the parent and this object. The return value indicates whether the subclass handles * alpha (the return value for onSetAlpha()). * * @param alpha The new value for the alpha property * @return true if the View subclass handles alpha (the return value for onSetAlpha()) and * the new value for the alpha property is different from the old value */ setAlphaNoInvalidation(alpha:number):boolean { this.ensureTransformationInfo(); if (this.mTransformationInfo.mAlpha != alpha) { this.mTransformationInfo.mAlpha = alpha; let subclassHandlesAlpha:boolean = this.onSetAlpha(Math.floor((alpha * 255))); if (subclassHandlesAlpha) { this.mPrivateFlags |= View.PFLAG_ALPHA_SET; return true; } else { this.mPrivateFlags &= ~View.PFLAG_ALPHA_SET; //if (this.mDisplayList != null) { // this.mDisplayList.setAlpha(this.getFinalAlpha()); //} } } return false; } /** * This property is hidden and intended only for use by the Fade transition, which * animates it to produce a visual translucency that does not side-effect (or get * affected by) the real alpha property. This value is composited with the other * alpha value (and the AlphaAnimation value, when that is present) to produce * a final visual translucency result, which is what is passed into the DisplayList. * * @hide */ setTransitionAlpha(alpha:number):void { this.ensureTransformationInfo(); if (this.mTransformationInfo.mTransitionAlpha != alpha) { this.mTransformationInfo.mTransitionAlpha = alpha; this.mPrivateFlags &= ~View.PFLAG_ALPHA_SET; this.invalidateViewProperty(true, false); //if (this.mDisplayList != null) { // this.mDisplayList.setAlpha(this.getFinalAlpha()); //} } } /** * Calculates the visual alpha of this view, which is a combination of the actual * alpha value and the transitionAlpha value (if set). */ private getFinalAlpha():number { if (this.mTransformationInfo != null) { return this.mTransformationInfo.mAlpha * this.mTransformationInfo.mTransitionAlpha; } return 1; } /** * This property is hidden and intended only for use by the Fade transition, which * animates it to produce a visual translucency that does not side-effect (or get * affected by) the real alpha property. This value is composited with the other * alpha value (and the AlphaAnimation value, when that is present) to produce * a final visual translucency result, which is what is passed into the DisplayList. * * @hide */ getTransitionAlpha():number { return this.mTransformationInfo != null ? this.mTransformationInfo.mTransitionAlpha : 1; } /** * Top position of this view relative to its parent. * * @return The top of this view, in pixels. */ getTop():number { return this.mTop; } /** * Sets the top position of this view relative to its parent. This method is meant to be called * by the layout system and should not generally be called otherwise, because the property * may be changed at any time by the layout. * * @param top The top of this view, in pixels. */ setTop(top:number):void { if (top != this.mTop) { this.updateMatrix(); const matrixIsIdentity:boolean = this.mTransformationInfo == null || this.mTransformationInfo.mMatrixIsIdentity; if (matrixIsIdentity) { if (this.mAttachInfo != null) { let minTop:number; let yLoc:number; if (top < this.mTop) { minTop = top; yLoc = top - this.mTop; } else { minTop = this.mTop; yLoc = 0; } this.invalidate(0, yLoc, this.mRight - this.mLeft, this.mBottom - minTop); } } else { // Double-invalidation is necessary to capture view's old and new areas this.invalidate(true); } let width:number = this.mRight - this.mLeft; let oldHeight:number = this.mBottom - this.mTop; this.mTop = top; //if (this.mDisplayList != null) { // this.mDisplayList.setTop(this.mTop); //} this.sizeChange(width, this.mBottom - this.mTop, width, oldHeight); if (!matrixIsIdentity) { if ((this.mPrivateFlags & View.PFLAG_PIVOT_EXPLICITLY_SET) == 0) { // A change in dimension means an auto-centered pivot point changes, too this.mTransformationInfo.mMatrixDirty = true; } // force another invalidation with the new orientation this.mPrivateFlags |= View.PFLAG_DRAWN; this.invalidate(true); } this.mBackgroundSizeChanged = true; this.invalidateParentIfNeeded(); if ((this.mPrivateFlags2 & View.PFLAG2_VIEW_QUICK_REJECTED) == View.PFLAG2_VIEW_QUICK_REJECTED) { // View was rejected last time it was drawn by its parent; this may have changed this.invalidateParentIfNeeded(); } } } /** * Bottom position of this view relative to its parent. * * @return The bottom of this view, in pixels. */ getBottom():number { return this.mBottom; } /** * True if this view has changed since the last time being drawn. * * @return The dirty state of this view. */ isDirty():boolean { return (this.mPrivateFlags & View.PFLAG_DIRTY_MASK) != 0; } /** * Sets the bottom position of this view relative to its parent. This method is meant to be * called by the layout system and should not generally be called otherwise, because the * property may be changed at any time by the layout. * * @param bottom The bottom of this view, in pixels. */ setBottom(bottom:number):void { if (bottom != this.mBottom) { this.updateMatrix(); const matrixIsIdentity:boolean = this.mTransformationInfo == null || this.mTransformationInfo.mMatrixIsIdentity; if (matrixIsIdentity) { if (this.mAttachInfo != null) { let maxBottom:number; if (bottom < this.mBottom) { maxBottom = this.mBottom; } else { maxBottom = bottom; } this.invalidate(0, 0, this.mRight - this.mLeft, maxBottom - this.mTop); } } else { // Double-invalidation is necessary to capture view's old and new areas this.invalidate(true); } let width:number = this.mRight - this.mLeft; let oldHeight:number = this.mBottom - this.mTop; this.mBottom = bottom; //if (this.mDisplayList != null) { // this.mDisplayList.setBottom(this.mBottom); //} this.sizeChange(width, this.mBottom - this.mTop, width, oldHeight); if (!matrixIsIdentity) { if ((this.mPrivateFlags & View.PFLAG_PIVOT_EXPLICITLY_SET) == 0) { // A change in dimension means an auto-centered pivot point changes, too this.mTransformationInfo.mMatrixDirty = true; } // force another invalidation with the new orientation this.mPrivateFlags |= View.PFLAG_DRAWN; this.invalidate(true); } this.mBackgroundSizeChanged = true; this.invalidateParentIfNeeded(); if ((this.mPrivateFlags2 & View.PFLAG2_VIEW_QUICK_REJECTED) == View.PFLAG2_VIEW_QUICK_REJECTED) { // View was rejected last time it was drawn by its parent; this may have changed this.invalidateParentIfNeeded(); } } } /** * Left position of this view relative to its parent. * * @return The left edge of this view, in pixels. */ getLeft():number { return this.mLeft; } /** * Sets the left position of this view relative to its parent. This method is meant to be called * by the layout system and should not generally be called otherwise, because the property * may be changed at any time by the layout. * * @param left The bottom of this view, in pixels. */ setLeft(left:number):void { if (left != this.mLeft) { this.updateMatrix(); const matrixIsIdentity:boolean = this.mTransformationInfo == null || this.mTransformationInfo.mMatrixIsIdentity; if (matrixIsIdentity) { if (this.mAttachInfo != null) { let minLeft:number; let xLoc:number; if (left < this.mLeft) { minLeft = left; xLoc = left - this.mLeft; } else { minLeft = this.mLeft; xLoc = 0; } this.invalidate(xLoc, 0, this.mRight - minLeft, this.mBottom - this.mTop); } } else { // Double-invalidation is necessary to capture view's old and new areas this.invalidate(true); } let oldWidth:number = this.mRight - this.mLeft; let height:number = this.mBottom - this.mTop; this.mLeft = left; //if (this.mDisplayList != null) { // this.mDisplayList.setLeft(left); //} this.sizeChange(this.mRight - this.mLeft, height, oldWidth, height); if (!matrixIsIdentity) { if ((this.mPrivateFlags & View.PFLAG_PIVOT_EXPLICITLY_SET) == 0) { // A change in dimension means an auto-centered pivot point changes, too this.mTransformationInfo.mMatrixDirty = true; } // force another invalidation with the new orientation this.mPrivateFlags |= View.PFLAG_DRAWN; this.invalidate(true); } this.mBackgroundSizeChanged = true; this.invalidateParentIfNeeded(); if ((this.mPrivateFlags2 & View.PFLAG2_VIEW_QUICK_REJECTED) == View.PFLAG2_VIEW_QUICK_REJECTED) { // View was rejected last time it was drawn by its parent; this may have changed this.invalidateParentIfNeeded(); } } } /** * Right position of this view relative to its parent. * * @return The right edge of this view, in pixels. */ getRight():number { return this.mRight; } /** * Sets the right position of this view relative to its parent. This method is meant to be called * by the layout system and should not generally be called otherwise, because the property * may be changed at any time by the layout. * * @param right The bottom of this view, in pixels. */ setRight(right:number):void { if (right != this.mRight) { this.updateMatrix(); const matrixIsIdentity:boolean = this.mTransformationInfo == null || this.mTransformationInfo.mMatrixIsIdentity; if (matrixIsIdentity) { if (this.mAttachInfo != null) { let maxRight:number; if (right < this.mRight) { maxRight = this.mRight; } else { maxRight = right; } this.invalidate(0, 0, maxRight - this.mLeft, this.mBottom - this.mTop); } } else { // Double-invalidation is necessary to capture view's old and new areas this.invalidate(true); } let oldWidth:number = this.mRight - this.mLeft; let height:number = this.mBottom - this.mTop; this.mRight = right; //if (this.mDisplayList != null) { // this.mDisplayList.setRight(this.mRight); //} this.sizeChange(this.mRight - this.mLeft, height, oldWidth, height); if (!matrixIsIdentity) { if ((this.mPrivateFlags & View.PFLAG_PIVOT_EXPLICITLY_SET) == 0) { // A change in dimension means an auto-centered pivot point changes, too this.mTransformationInfo.mMatrixDirty = true; } // force another invalidation with the new orientation this.mPrivateFlags |= View.PFLAG_DRAWN; this.invalidate(true); } this.mBackgroundSizeChanged = true; this.invalidateParentIfNeeded(); if ((this.mPrivateFlags2 & View.PFLAG2_VIEW_QUICK_REJECTED) == View.PFLAG2_VIEW_QUICK_REJECTED) { // View was rejected last time it was drawn by its parent; this may have changed this.invalidateParentIfNeeded(); } } } /** * The visual x position of this view, in pixels. This is equivalent to the * {@link #setTranslationX(float) translationX} property plus the current * {@link #getLeft() left} property. * * @return The visual x position of this view, in pixels. */ getX():number { return this.mLeft + (this.mTransformationInfo != null ? this.mTransformationInfo.mTranslationX : 0); } /** * Sets the visual x position of this view, in pixels. This is equivalent to setting the * {@link #setTranslationX(float) translationX} property to be the difference between * the x value passed in and the current {@link #getLeft() left} property. * * @param x The visual x position of this view, in pixels. */ setX(x:number):void { this.setTranslationX(x - this.mLeft); } /** * The visual y position of this view, in pixels. This is equivalent to the * {@link #setTranslationY(float) translationY} property plus the current * {@link #getTop() top} property. * * @return The visual y position of this view, in pixels. */ getY():number { return this.mTop + (this.mTransformationInfo != null ? this.mTransformationInfo.mTranslationY : 0); } /** * Sets the visual y position of this view, in pixels. This is equivalent to setting the * {@link #setTranslationY(float) translationY} property to be the difference between * the y value passed in and the current {@link #getTop() top} property. * * @param y The visual y position of this view, in pixels. */ setY(y:number):void { this.setTranslationY(y - this.mTop); } /** * The horizontal location of this view relative to its {@link #getLeft() left} position. * This position is post-layout, in addition to wherever the object's * layout placed it. * * @return The horizontal position of this view relative to its left position, in pixels. */ getTranslationX():number { return this.mTransformationInfo != null ? this.mTransformationInfo.mTranslationX : 0; } /** * Sets the horizontal location of this view relative to its {@link #getLeft() left} position. * This effectively positions the object post-layout, in addition to wherever the object's * layout placed it. * * @param translationX The horizontal position of this view relative to its left position, * in pixels. * * @attr ref android.R.styleable#View_translationX */ setTranslationX(translationX:number):void { this.ensureTransformationInfo(); const info:View.TransformationInfo = this.mTransformationInfo; if (info.mTranslationX != translationX) { // Double-invalidation is necessary to capture view's old and new areas this.invalidateViewProperty(true, false); info.mTranslationX = translationX; info.mMatrixDirty = true; this.invalidateViewProperty(false, true); //if (this.mDisplayList != null) { // this.mDisplayList.setTranslationX(translationX); //} if ((this.mPrivateFlags2 & View.PFLAG2_VIEW_QUICK_REJECTED) == View.PFLAG2_VIEW_QUICK_REJECTED) { // View was rejected last time it was drawn by its parent; this may have changed this.invalidateParentIfNeeded(); } } } /** * The horizontal location of this view relative to its {@link #getTop() top} position. * This position is post-layout, in addition to wherever the object's * layout placed it. * * @return The vertical position of this view relative to its top position, * in pixels. */ getTranslationY():number { return this.mTransformationInfo != null ? this.mTransformationInfo.mTranslationY : 0; } /** * Sets the vertical location of this view relative to its {@link #getTop() top} position. * This effectively positions the object post-layout, in addition to wherever the object's * layout placed it. * * @param translationY The vertical position of this view relative to its top position, * in pixels. * * @attr ref android.R.styleable#View_translationY */ setTranslationY(translationY:number):void { this.ensureTransformationInfo(); const info:View.TransformationInfo = this.mTransformationInfo; if (info.mTranslationY != translationY) { this.invalidateViewProperty(true, false); info.mTranslationY = translationY; info.mMatrixDirty = true; this.invalidateViewProperty(false, true); //if (this.mDisplayList != null) { // this.mDisplayList.setTranslationY(translationY); //} if ((this.mPrivateFlags2 & View.PFLAG2_VIEW_QUICK_REJECTED) == View.PFLAG2_VIEW_QUICK_REJECTED) { // View was rejected last time it was drawn by its parent; this may have changed this.invalidateParentIfNeeded(); } } } transformRect(rect:Rect){ if (!this.getMatrix().isIdentity()) { let boundingRect = this.mAttachInfo.mTmpTransformRect; boundingRect.set(rect); this.getMatrix().mapRect(boundingRect); rect.set(boundingRect); } } pointInView(localX:number, localY:number, slop=0):boolean { return localX >= -slop && localY >= -slop && localX < ((this.mRight - this.mLeft) + slop) && localY < ((this.mBottom - this.mTop) + slop); } getHandler():Handler { let attachInfo = this.mAttachInfo; if (attachInfo != null) { return attachInfo.mHandler; } return null; } getViewRootImpl():ViewRootImpl{ if (this.mAttachInfo != null) { return this.mAttachInfo.mViewRootImpl; } if(this.mContext!=null){ return this.mContext.androidUI._viewRootImpl; } return null; } post(action:Runnable):boolean { let attachInfo = this.mAttachInfo; if (attachInfo != null) { return attachInfo.mHandler.post(action); } // Assume that post will succeed later ViewRootImpl.getRunQueue().post(action); return true; } postDelayed(action:Runnable, delayMillis:number):boolean { let attachInfo = this.mAttachInfo; if (attachInfo != null) { return attachInfo.mHandler.postDelayed(action, delayMillis); } // Assume that post will succeed later ViewRootImpl.getRunQueue().postDelayed(action, delayMillis); return true; } postOnAnimation(action:Runnable):boolean { return this.post(action); } postOnAnimationDelayed(action:Runnable, delayMillis:number):boolean { return this.postDelayed(action, delayMillis); } removeCallbacks(action:Runnable):boolean { if (action != null) { let attachInfo = this.mAttachInfo; if (attachInfo != null) { attachInfo.mHandler.removeCallbacks(action); } else { // Assume that post will succeed later ViewRootImpl.getRunQueue().removeCallbacks(action); } } return true; } getParent():ViewParent { return this.mParent; } setFlags(flags:number , mask:number){ let old = this.mViewFlags; this.mViewFlags = (this.mViewFlags & ~mask) | (flags & mask); let changed = this.mViewFlags ^ old; if (changed == 0) { return; } let privateFlags = this.mPrivateFlags; if (((changed & View.FOCUSABLE_MASK) != 0) && ((privateFlags & View.PFLAG_HAS_BOUNDS) !=0)) { if (((old & View.FOCUSABLE_MASK) == View.FOCUSABLE) && ((privateFlags & View.PFLAG_FOCUSED) != 0)) { /* Give up focus if we are no longer focusable */ this.clearFocus(); } else if (((old & View.FOCUSABLE_MASK) == View.NOT_FOCUSABLE) && ((privateFlags & View.PFLAG_FOCUSED) == 0)) { /* * Tell the view system that we are now available to take focus * if no one else already has it. */ if (this.mParent != null) this.mParent.focusableViewAvailable(this); } } const newVisibility = flags & View.VISIBILITY_MASK; if (newVisibility == View.VISIBLE) { if ((changed & View.VISIBILITY_MASK) != 0) { /* * If this view is becoming visible, invalidate it in case it changed while * it was not visible. Marking it drawn ensures that the invalidation will * go through. */ this.mPrivateFlags |= View.PFLAG_DRAWN; this.invalidate(true); //needGlobalAttributesUpdate(true); // a view becoming visible is worth notifying the parent // about in case nothing has focus. even if this specific view // isn't focusable, it may contain something that is, so let // the root view try to give this focus if nothing else does. if ((this.mParent != null) && (this.mBottom > this.mTop) && (this.mRight > this.mLeft)) { this.mParent.focusableViewAvailable(this); } } } /* Check if the GONE bit has changed */ if ((changed & View.GONE) != 0) { //needGlobalAttributesUpdate(false); this.requestLayout(); if (((this.mViewFlags & View.VISIBILITY_MASK) == View.GONE)) { if (this.hasFocus()) this.clearFocus(); this.destroyDrawingCache(); if (this.mParent instanceof View) { // GONE views noop invalidation, so invalidate the parent (<any> this.mParent).invalidate(true); } // Mark the view drawn to ensure that it gets invalidated properly the next // time it is visible and gets invalidated this.mPrivateFlags |= View.PFLAG_DRAWN; } //if (this.mAttachInfo != null) { // this.mAttachInfo.mViewVisibilityChanged = true; //} } /* Check if the VISIBLE bit has changed */ if ((changed & View.INVISIBLE) != 0) { //needGlobalAttributesUpdate(false); /* * If this view is becoming invisible, set the DRAWN flag so that * the next invalidate() will not be skipped. */ this.mPrivateFlags |= View.PFLAG_DRAWN; if (((this.mViewFlags & View.VISIBILITY_MASK) == View.INVISIBLE)) { // root view becoming invisible shouldn't clear focus and accessibility focus if (this.getRootView() != this) { if (this.hasFocus()) this.clearFocus(); } } //if (this.mAttachInfo != null) { // this.mAttachInfo.mViewVisibilityChanged = true; //} } if ((changed & View.VISIBILITY_MASK) != 0) { // If the view is invisible, cleanup its display list to free up resources if (newVisibility != View.VISIBLE) { this.cleanupDraw(); } if (this.mParent instanceof ViewGroup) { (<any>this.mParent).onChildVisibilityChanged(this, (changed & View.VISIBILITY_MASK), newVisibility); (<any>this.mParent).invalidate(true); } else if (this.mParent != null) { this.mParent.invalidateChild(this, null); } this.dispatchVisibilityChanged(this, newVisibility); this.syncVisibleToElement(); } if ((changed & View.WILL_NOT_CACHE_DRAWING) != 0) { this.destroyDrawingCache(); } if ((changed & View.DRAWING_CACHE_ENABLED) != 0) { this.destroyDrawingCache(); this.mPrivateFlags &= ~View.PFLAG_DRAWING_CACHE_VALID; this.invalidateParentCaches(); } //if ((changed & DRAWING_CACHE_QUALITY_MASK) != 0) { // destroyDrawingCache(); // mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; //} if ((changed & View.DRAW_MASK) != 0) { if ((this.mViewFlags & View.WILL_NOT_DRAW) != 0) { if (this.mBackground != null) { this.mPrivateFlags &= ~View.PFLAG_SKIP_DRAW; this.mPrivateFlags |= View.PFLAG_ONLY_DRAWS_BACKGROUND; } else { this.mPrivateFlags |= View.PFLAG_SKIP_DRAW; } } else { this.mPrivateFlags &= ~View.PFLAG_SKIP_DRAW; } this.requestLayout(); this.invalidate(true); } } bringToFront() { if (this.mParent != null) { this.mParent.bringChildToFront(this); } } onScrollChanged(l:number, t:number, oldl:number, oldt:number) { this.mBackgroundSizeChanged = true; let rootImpl = this.getViewRootImpl(); if (rootImpl != null) { rootImpl.mViewScrollChanged = true; } } protected onSizeChanged(w:number, h:number, oldw:number, oldh:number):void { } /** * Find and return all touchable views that are descendants of this view, * possibly including this view if it is touchable itself. * * @return A list of touchable views */ getTouchables():ArrayList<View> { let result = new ArrayList<View>(); this.addTouchables(result); return result; } /** * Add any touchable views that are descendants of this view (possibly * including this view if it is touchable itself) to views. * * @param views Touchable views found so far */ addTouchables(views:ArrayList<View>):void { const viewFlags = this.mViewFlags; if (((viewFlags & View.CLICKABLE) == View.CLICKABLE || (viewFlags & View.LONG_CLICKABLE) == View.LONG_CLICKABLE) && (viewFlags & View.ENABLED_MASK) == View.ENABLED) { views.add(this); } } /** * Request that a rectangle of this view be visible on the screen, * scrolling if necessary just enough. * * <p>A View should call this if it maintains some notion of which part * of its content is interesting. For example, a text editing view * should call this when its cursor moves. * * <p>When <code>immediate</code> is set to true, scrolling will not be * animated. * * @param rectangle The rectangle. * @param immediate True to forbid animated scrolling, false otherwise * @return Whether any parent scrolled. */ requestRectangleOnScreen(rectangle:Rect, immediate=false):boolean { if (this.mParent == null) { return false; } let child:View = this; let position:RectF = (this.mAttachInfo != null) ? this.mAttachInfo.mTmpTransformRect : new RectF(); position.set(rectangle); let parent:ViewParent = this.mParent; let scrolled:boolean = false; while (parent != null) { rectangle.set(Math.floor(position.left), Math.floor(position.top), Math.floor(position.right), Math.floor(position.bottom)); scrolled = parent.requestChildRectangleOnScreen(child, rectangle, immediate) || scrolled; if (!child.hasIdentityMatrix()) { child.getMatrix().mapRect(position); } position.offset(child.mLeft, child.mTop); if (!(parent instanceof View)) { break; } let parentView:View = <View><any>parent; position.offset(-parentView.getScrollX(), -parentView.getScrollY()); child = parentView; parent = child.getParent(); } return scrolled; } onFocusLost() { this.resetPressedState(); } resetPressedState() { if ((this.mViewFlags & View.ENABLED_MASK) == View.DISABLED) { return; } if (this.isPressed()) { this.setPressed(false); if (!this.mHasPerformedLongPress) { this.removeLongPressCallback(); } } } isFocused():boolean { return (this.mPrivateFlags & View.PFLAG_FOCUSED) != 0; } findFocus():View { return (this.mPrivateFlags & View.PFLAG_FOCUSED) != 0 ? this : null; } getNextFocusLeftId():string { return this.mNextFocusLeftId; } setNextFocusLeftId(nextFocusLeftId:string) { this.mNextFocusLeftId = nextFocusLeftId; } getNextFocusRightId():string { return this.mNextFocusRightId; } setNextFocusRightId(nextFocusRightId:string) { this.mNextFocusRightId = nextFocusRightId; } getNextFocusUpId():string { return this.mNextFocusUpId; } setNextFocusUpId(nextFocusUpId:string) { this.mNextFocusUpId = nextFocusUpId; } getNextFocusDownId():string { return this.mNextFocusDownId; } setNextFocusDownId(nextFocusDownId:string) { this.mNextFocusDownId = nextFocusDownId; } getNextFocusForwardId():string { return this.mNextFocusForwardId; } setNextFocusForwardId(nextFocusForwardId:string) { this.mNextFocusForwardId = nextFocusForwardId; } setFocusable(focusable:boolean) { if (!focusable) { this.setFlags(0, View.FOCUSABLE_IN_TOUCH_MODE); } this.setFlags(focusable ? View.FOCUSABLE : View.NOT_FOCUSABLE, View.FOCUSABLE_MASK); } isFocusable():boolean { return View.FOCUSABLE == (this.mViewFlags & View.FOCUSABLE_MASK); } setFocusableInTouchMode(focusableInTouchMode:boolean) { // Focusable in touch mode should always be set before the focusable flag // otherwise, setting the focusable flag will trigger a focusableViewAvailable() // which, in touch mode, will not successfully request focus on this view // because the focusable in touch mode flag is not set this.setFlags(focusableInTouchMode ? View.FOCUSABLE_IN_TOUCH_MODE : 0, View.FOCUSABLE_IN_TOUCH_MODE); if (focusableInTouchMode) { this.setFlags(View.FOCUSABLE, View.FOCUSABLE_MASK); } } isFocusableInTouchMode():boolean { return View.FOCUSABLE_IN_TOUCH_MODE == (this.mViewFlags & View.FOCUSABLE_IN_TOUCH_MODE); } hasFocusable():boolean { return (this.mViewFlags & View.VISIBILITY_MASK) == View.VISIBLE && this.isFocusable(); } clearFocus() { if (View.DBG) { System.out.println(this + " clearFocus()"); } this.clearFocusInternal(true, true); } clearFocusInternal(propagate:boolean, refocus:boolean) { if ((this.mPrivateFlags & View.PFLAG_FOCUSED) != 0) { this.mPrivateFlags &= ~View.PFLAG_FOCUSED; if (propagate && this.mParent != null) { this.mParent.clearChildFocus(this); } this.onFocusChanged(false, 0, null); this.refreshDrawableState(); if (propagate && (!refocus || !this.rootViewRequestFocus())) { this.notifyGlobalFocusCleared(this); } } } notifyGlobalFocusCleared(oldFocus:View) { //if (oldFocus != null && this.mAttachInfo != null) { // this.mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, null); //} } rootViewRequestFocus() { const root = this.getRootView(); return root != null && root.requestFocus(); } unFocus() { if (View.DBG) { System.out.println(this + " unFocus()"); } this.clearFocusInternal(false, false); } hasFocus():boolean{ return (this.mPrivateFlags & View.PFLAG_FOCUSED) != 0; } protected onFocusChanged(gainFocus:boolean, direction:number, previouslyFocusedRect:Rect) { if (!gainFocus) { if (this.isPressed()) { this.setPressed(false); } this.onFocusLost(); } this.invalidate(true); let li = this.mListenerInfo; if (li != null && li.mOnFocusChangeListener != null) { li.mOnFocusChangeListener.onFocusChange(this, gainFocus); } if (this.mAttachInfo != null) { this.mAttachInfo.mKeyDispatchState.reset(this); } } focusSearch(direction:number):View { if (this.mParent != null) { return this.mParent.focusSearch(this, direction); } else { return null; } } dispatchUnhandledMove(focused:View, direction:number):boolean { return false; } findUserSetNextFocus(root:View, direction:number):View { switch (direction) { case View.FOCUS_LEFT: if (!this.mNextFocusLeftId) return null; return this.findViewInsideOutShouldExist(root, this.mNextFocusLeftId); case View.FOCUS_RIGHT: if (!this.mNextFocusRightId) return null; return this.findViewInsideOutShouldExist(root, this.mNextFocusRightId); case View.FOCUS_UP: if (!this.mNextFocusUpId) return null; return this.findViewInsideOutShouldExist(root, this.mNextFocusUpId); case View.FOCUS_DOWN: if (!this.mNextFocusDownId) return null; return this.findViewInsideOutShouldExist(root, this.mNextFocusDownId); case View.FOCUS_FORWARD: if (!this.mNextFocusForwardId) return null; return this.findViewInsideOutShouldExist(root, this.mNextFocusForwardId); case View.FOCUS_BACKWARD: { if (!this.mID) return null; let id = this.mID; return root.findViewByPredicateInsideOut(this, { apply(t:View):boolean { return t.mNextFocusForwardId == id; } }); } } return null; } private findViewInsideOutShouldExist(root:View, id:string):View { if (this.mMatchIdPredicate == null) { this.mMatchIdPredicate = new MatchIdPredicate(); } this.mMatchIdPredicate.mId = id; let result = root.findViewByPredicateInsideOut(this, this.mMatchIdPredicate); if (result == null) { Log.w(View.VIEW_LOG_TAG, "couldn't find view with id " + id); } return result; } getFocusables(direction:number):ArrayList<View> { let result = new ArrayList<View>(24); this.addFocusables(result, direction); return result; } addFocusables(views:ArrayList<View>, direction:number, focusableMode=View.FOCUSABLES_TOUCH_MODE):void { if (views == null) { return; } if (!this.isFocusable()) { return; } if ((focusableMode & View.FOCUSABLES_TOUCH_MODE) == View.FOCUSABLES_TOUCH_MODE && this.isInTouchMode() && !this.isFocusableInTouchMode()) { return; } views.add(this); } setOnFocusChangeListener(l:View.OnFocusChangeListener|((v:View, hasFocus:boolean)=>void)) { if(typeof l == "function"){ l = View.OnFocusChangeListener.fromFunction(<(v:View, hasFocus:boolean)=>void>l); } this.getListenerInfo().mOnFocusChangeListener = <View.OnFocusChangeListener>l; } getOnFocusChangeListener():View.OnFocusChangeListener { let li = this.mListenerInfo; return li != null ? li.mOnFocusChangeListener : null; } requestFocus(direction=View.FOCUS_DOWN, previouslyFocusedRect=null):boolean{ return this.requestFocusNoSearch(direction, previouslyFocusedRect); } private requestFocusNoSearch(direction:number, previouslyFocusedRect:Rect):boolean { // need to be focusable if ((this.mViewFlags & View.FOCUSABLE_MASK) != View.FOCUSABLE || (this.mViewFlags & View.VISIBILITY_MASK) != View.VISIBLE) { return false; } // need to be focusable in touch mode if in touch mode if (this.isInTouchMode() && (View.FOCUSABLE_IN_TOUCH_MODE != (this.mViewFlags & View.FOCUSABLE_IN_TOUCH_MODE))) { return false; } // need to not have any parents blocking us if (this.hasAncestorThatBlocksDescendantFocus()) { return false; } this.handleFocusGainInternal(direction, previouslyFocusedRect); return true; } requestFocusFromTouch():boolean { // Leave touch mode if we need to if (this.isInTouchMode()) { let viewRoot = this.getViewRootImpl(); if (viewRoot != null) { viewRoot.ensureTouchMode(false); } } return this.requestFocus(View.FOCUS_DOWN); } private hasAncestorThatBlocksDescendantFocus():boolean { let ancestor = this.mParent; while (ancestor instanceof ViewGroup) { const vgAncestor = <ViewGroup>ancestor; if (vgAncestor.getDescendantFocusability() == ViewGroup.FOCUS_BLOCK_DESCENDANTS) { return true; } else { ancestor = vgAncestor.getParent(); } } return false; } handleFocusGainInternal(direction:number, previouslyFocusedRect:Rect) { if (View.DBG) { System.out.println(this + " requestFocus()"); } if ((this.mPrivateFlags & View.PFLAG_FOCUSED) == 0) { this.mPrivateFlags |= View.PFLAG_FOCUSED; let oldFocus = (this.mAttachInfo != null) ? this.getRootView().findFocus() : null; if (this.mParent != null) { this.mParent.requestChildFocus(this, this); } //if (this.mAttachInfo != null) { // this.mAttachInfo.mTreeObserver.dispatchOnGlobalFocusChange(oldFocus, this); //} this.onFocusChanged(true, direction, previouslyFocusedRect); this.refreshDrawableState(); } } hasTransientState():boolean { return (this.mPrivateFlags2 & View.PFLAG2_HAS_TRANSIENT_STATE) == View.PFLAG2_HAS_TRANSIENT_STATE; } setHasTransientState(hasTransientState:boolean) { this.mTransientStateCount = hasTransientState ? this.mTransientStateCount + 1 : this.mTransientStateCount - 1; if (this.mTransientStateCount < 0) { this.mTransientStateCount = 0; Log.e(View.VIEW_LOG_TAG, "hasTransientState decremented below 0: " + "unmatched pair of setHasTransientState calls"); } else if ((hasTransientState && this.mTransientStateCount == 1) || (!hasTransientState && this.mTransientStateCount == 0)) { // update flag if we've just incremented up from 0 or decremented down to 0 this.mPrivateFlags2 = (this.mPrivateFlags2 & ~View.PFLAG2_HAS_TRANSIENT_STATE) | (hasTransientState ? View.PFLAG2_HAS_TRANSIENT_STATE : 0); if (this.mParent != null) { this.mParent.childHasTransientStateChanged(this, hasTransientState); } } } /** * Indicates whether this view is one of the set of scrollable containers in * its window. * * @return whether this view is one of the set of scrollable containers in * its window * * @attr ref android.R.styleable#View_isScrollContainer */ isScrollContainer():boolean { return (this.mPrivateFlags & View.PFLAG_SCROLL_CONTAINER_ADDED) != 0; } /** * Change whether this view is one of the set of scrollable containers in * its window. This will be used to determine whether the window can * resize or must pan when a soft input area is open -- scrollable * containers allow the window to use resize mode since the container * will appropriately shrink. * * @attr ref android.R.styleable#View_isScrollContainer */ setScrollContainer(isScrollContainer:boolean):void { if (isScrollContainer) { if (this.mAttachInfo != null && (this.mPrivateFlags & View.PFLAG_SCROLL_CONTAINER_ADDED) == 0) { this.mAttachInfo.mScrollContainers.add(this); this.mPrivateFlags |= View.PFLAG_SCROLL_CONTAINER_ADDED; } this.mPrivateFlags |= View.PFLAG_SCROLL_CONTAINER; } else { if ((this.mPrivateFlags & View.PFLAG_SCROLL_CONTAINER_ADDED) != 0) { this.mAttachInfo.mScrollContainers.delete(this); } this.mPrivateFlags &= ~(View.PFLAG_SCROLL_CONTAINER | View.PFLAG_SCROLL_CONTAINER_ADDED); } } isInTouchMode():boolean{ if (this.getViewRootImpl() != null) { return this.getViewRootImpl().mInTouchMode; } else { return false; } } isShown():boolean { let current:View = this; //noinspection ConstantConditions do { if ((current.mViewFlags & View.VISIBILITY_MASK) != View.VISIBLE) { return false; } let parent = current.mParent; if (parent == null) { return false; // We are not attached to the view root } if (!(parent instanceof View)) { return true; } current = <View><any>parent; } while (current != null); return false; } getVisibility():number { return this.mViewFlags & View.VISIBILITY_MASK; } setVisibility(visibility:number) { this.setFlags(visibility, View.VISIBILITY_MASK); if (this.mBackground != null) this.mBackground.setVisible(visibility == View.VISIBLE, false); } dispatchVisibilityChanged(changedView:View, visibility:number) { this.onVisibilityChanged(changedView, visibility); } protected onVisibilityChanged(changedView:View, visibility:number):void { if (visibility == View.VISIBLE) { if (this.mAttachInfo != null) { this.initialAwakenScrollBars(); } else { this.mPrivateFlags |= View.PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; } } } /** * Dispatch a hint about whether this view is displayed. For instance, when * a View moves out of the screen, it might receives a display hint indicating * the view is not displayed. Applications should not <em>rely</em> on this hint * as there is no guarantee that they will receive one. * * @param hint A hint about whether or not this view is displayed: * {@link #VISIBLE} or {@link #INVISIBLE}. */ dispatchDisplayHint(hint:number):void { this.onDisplayHint(hint); } /** * Gives this view a hint about whether is displayed or not. For instance, when * a View moves out of the screen, it might receives a display hint indicating * the view is not displayed. Applications should not <em>rely</em> on this hint * as there is no guarantee that they will receive one. * * @param hint A hint about whether or not this view is displayed: * {@link #VISIBLE} or {@link #INVISIBLE}. */ onDisplayHint(hint:number):void { } dispatchWindowVisibilityChanged(visibility:number) { this.onWindowVisibilityChanged(visibility); } onWindowVisibilityChanged(visibility:number) { if (visibility == View.VISIBLE) { this.initialAwakenScrollBars(); } } getWindowVisibility() { return this.mAttachInfo != null ? this.mAttachInfo.mWindowVisibility : View.GONE; } isEnabled():boolean { return (this.mViewFlags & View.ENABLED_MASK) == View.ENABLED; } setEnabled(enabled:boolean) { if (enabled == this.isEnabled()) return; this.setFlags(enabled ? View.ENABLED : View.DISABLED, View.ENABLED_MASK); /* * The View most likely has to change its appearance, so refresh * the drawable state. */ this.refreshDrawableState(); // Invalidate too, since the default behavior for views is to be // be drawn at 50% alpha rather than to change the drawable. this.invalidate(true); //if (!enabled) { // cancelPendingInputEvents(); //} } dispatchGenericMotionEvent(event:MotionEvent):boolean{ if (event.isPointerEvent()) { const action = event.getAction(); if (action == MotionEvent.ACTION_HOVER_ENTER || action == MotionEvent.ACTION_HOVER_MOVE || action == MotionEvent.ACTION_HOVER_EXIT) { //if (dispatchHoverEvent(event)) {//TODO when hover impl // return true; //} } else if (this.dispatchGenericPointerEvent(event)) { return true; } } //else if (dispatchGenericFocusedEvent(event)) { // return true; //} if (this.dispatchGenericMotionEventInternal(event)) { return true; } return false; } private dispatchGenericMotionEventInternal(event:MotionEvent):boolean { //noinspection SimplifiableIfStatement let li = this.mListenerInfo; if (li != null && li.mOnGenericMotionListener != null && (this.mViewFlags & View.ENABLED_MASK) == View.ENABLED && li.mOnGenericMotionListener.onGenericMotion(this, event)) { return true; } if (this.onGenericMotionEvent(event)) { return true; } return false; } onGenericMotionEvent(event:MotionEvent):boolean { return false; } dispatchGenericPointerEvent(event:MotionEvent):boolean{ return false; } dispatchKeyEvent(event:KeyEvent):boolean { // Give any attached key listener a first crack at the event. //noinspection SimplifiableIfStatement let li = this.mListenerInfo; if (li != null && li.mOnKeyListener != null && (this.mViewFlags & View.ENABLED_MASK) == View.ENABLED && li.mOnKeyListener.onKey(this, event.getKeyCode(), event)) { return true; } if (event.dispatch(this, this.mAttachInfo != null ? this.mAttachInfo.mKeyDispatchState : null, this)) { return true; } return false; } setOnKeyListener(l:View.OnKeyListener|((v:View, keyCode:number, event:KeyEvent)=>void)) { if(typeof l == "function"){ l = View.OnKeyListener.fromFunction(<(v:View, keyCode:number, event:KeyEvent)=>void>l); } this.getListenerInfo().mOnKeyListener = <View.OnKeyListener>l; } getKeyDispatcherState():KeyEvent.DispatcherState { return this.mAttachInfo != null ? this.mAttachInfo.mKeyDispatchState : null; } onKeyDown(keyCode:number, event:android.view.KeyEvent):boolean { let result = false; if (KeyEvent.isConfirmKey(keyCode)) { if ((this.mViewFlags & View.ENABLED_MASK) == View.DISABLED) { return true; } // Long clickable items don't necessarily have to be clickable if (((this.mViewFlags & View.CLICKABLE) == View.CLICKABLE || (this.mViewFlags & View.LONG_CLICKABLE) == View.LONG_CLICKABLE) && (event.getRepeatCount() == 0)) { this.setPressed(true); this.checkForLongClick(0); return true; } } return result; } onKeyLongPress(keyCode:number, event:android.view.KeyEvent):boolean { return false; } onKeyUp(keyCode:number, event:android.view.KeyEvent):boolean { if (KeyEvent.isConfirmKey(keyCode)) { if ((this.mViewFlags & View.ENABLED_MASK) == View.DISABLED) { return true; } if ((this.mViewFlags & View.CLICKABLE) == View.CLICKABLE && this.isPressed()) { this.setPressed(false); if (!this.mHasPerformedLongPress) { // This is a tap, so remove the longpress check this.removeLongPressCallback(); return this.performClick(); } } } return false; } dispatchTouchEvent(event:MotionEvent):boolean { if (this.onFilterTouchEventForSecurity(event)) { let li = this.mListenerInfo; if (li != null && li.mOnTouchListener != null && (this.mViewFlags & View.ENABLED_MASK) == View.ENABLED && li.mOnTouchListener.onTouch(this, event)) { return true; } if (this.onTouchEvent(event)) { return true; } } return false; } onFilterTouchEventForSecurity(event:MotionEvent):boolean { return true; } onTouchEvent(event:MotionEvent):boolean { let viewFlags = this.mViewFlags; if ((viewFlags & View.ENABLED_MASK) == View.DISABLED) { if (event.getAction() == MotionEvent.ACTION_UP && (this.mPrivateFlags & View.PFLAG_PRESSED) != 0) { this.setPressed(false); } // A disabled view that is clickable still consumes the touch // events, it just doesn't respond to them. return (((viewFlags & View.CLICKABLE) == View.CLICKABLE || (viewFlags & View.LONG_CLICKABLE) == View.LONG_CLICKABLE)); } if (this.mTouchDelegate != null) { if (this.mTouchDelegate.onTouchEvent(event)) { return true; } } if (((viewFlags & View.CLICKABLE) == View.CLICKABLE || (viewFlags & View.LONG_CLICKABLE) == View.LONG_CLICKABLE)) { switch (event.getAction()) { case MotionEvent.ACTION_UP: let prepressed = (this.mPrivateFlags & View.PFLAG_PREPRESSED) != 0; if ((this.mPrivateFlags & View.PFLAG_PRESSED) != 0 || prepressed) { // take focus if we don't have it already and we should in // touch mode. let focusTaken = false; if (this.isFocusable() && this.isFocusableInTouchMode() && !this.isFocused()) { focusTaken = this.requestFocus(); } if (prepressed) { // The button is being released before we actually // showed it as pressed. Make it show the pressed // state now (before scheduling the click) to ensure // the user sees it. this.setPressed(true); } if (!this.mHasPerformedLongPress) { // This is a tap, so remove the longpress check this.removeLongPressCallback(); // Only perform take click actions if we were in the pressed state if (!focusTaken) { // Use a Runnable and post this rather than calling // performClick directly. This lets other visual state // of the view update before click actions start. if (this.mPerformClick == null) { this.mPerformClick = new PerformClick(this); } if (prepressed) { // androidui add: do click actions after press state draw to canvas. if (this.mPerformClickAfterPressDraw == null) { this.mPerformClickAfterPressDraw = new PerformClickAfterPressDraw(this); } this.post(this.mPerformClickAfterPressDraw); } else if (!this.post(this.mPerformClick)) { this.performClick(event); } } } if (this.mUnsetPressedState == null) { this.mUnsetPressedState = new UnsetPressedState(this); } if (prepressed) { this.postDelayed(this.mUnsetPressedState, ViewConfiguration.getPressedStateDuration()); } else if (!this.post(this.mUnsetPressedState)) { // If the post failed, unpress right now this.mUnsetPressedState.run(); } this.removeTapCallback(); } break; case MotionEvent.ACTION_DOWN: this.mHasPerformedLongPress = false; // Walk up the hierarchy to determine if we're inside a scrolling container. let isInScrollingContainer = this.isInScrollingContainer(); // For views inside a scrolling container, delay the pressed feedback for // a short period in case this is a scroll. if (isInScrollingContainer) { this.mPrivateFlags |= View.PFLAG_PREPRESSED; if (this.mPendingCheckForTap == null) { this.mPendingCheckForTap = new CheckForTap(this); } this.postDelayed(this.mPendingCheckForTap, ViewConfiguration.getTapTimeout()); } else { // Not inside a scrolling container, so show the feedback right away this.setPressed(true); this.checkForLongClick(0); } break; case MotionEvent.ACTION_CANCEL: this.setPressed(false); this.removeTapCallback(); this.removeLongPressCallback(); break; case MotionEvent.ACTION_MOVE: const x = event.getX(); const y = event.getY(); // Be lenient about moving outside of buttons if (!this.pointInView(x, y, this.mTouchSlop)) { // Outside button this.removeTapCallback(); if ((this.mPrivateFlags & View.PFLAG_PRESSED) != 0) { // Remove any future long press/tap checks this.removeLongPressCallback(); this.setPressed(false); } } break; } return true; } return false; } isInScrollingContainer():boolean { let p = this.getParent(); while (p != null && p instanceof ViewGroup) { if ((<ViewGroup> p).shouldDelayChildPressedState()) { return true; } p = p.getParent(); } return false; } /** * Cancel any deferred high-level input events that were previously posted to the event queue. * * <p>Many views post high-level events such as click handlers to the event queue * to run deferred in order to preserve a desired user experience - clearing visible * pressed states before executing, etc. This method will abort any events of this nature * that are currently in flight.</p> * * <p>Custom views that generate their own high-level deferred input events should override * {@link #onCancelPendingInputEvents()} and remove those pending events from the queue.</p> * * <p>This will also cancel pending input events for any child views.</p> * * <p>Note that this may not be sufficient as a debouncing strategy for clicks in all cases. * This will not impact newer events posted after this call that may occur as a result of * lower-level input events still waiting in the queue. If you are trying to prevent * double-submitted events for the duration of some sort of asynchronous transaction * you should also take other steps to protect against unexpected double inputs e.g. calling * {@link #setEnabled(boolean) setEnabled(false)} and re-enabling the view when * the transaction completes, tracking already submitted transaction IDs, etc.</p> */ cancelPendingInputEvents():void { this.dispatchCancelPendingInputEvents(); } /** * Called by {@link #cancelPendingInputEvents()} to cancel input events in flight. * Overridden by ViewGroup to dispatch. Package scoped to prevent app-side meddling. */ dispatchCancelPendingInputEvents():void { this.mPrivateFlags3 &= ~View.PFLAG3_CALLED_SUPER; this.onCancelPendingInputEvents(); if ((this.mPrivateFlags3 & View.PFLAG3_CALLED_SUPER) != View.PFLAG3_CALLED_SUPER) { throw Error(`new SuperNotCalledException("View " + this.getClass().getSimpleName() + " did not call through to super.onCancelPendingInputEvents()")`); } } /** * Called as the result of a call to {@link #cancelPendingInputEvents()} on this view or * a parent view. * * <p>This method is responsible for removing any pending high-level input events that were * posted to the event queue to run later. Custom view classes that post their own deferred * high-level events via {@link #post(Runnable)}, {@link #postDelayed(Runnable, long)} or * {@link android.os.Handler} should override this method, call * <code>super.onCancelPendingInputEvents()</code> and remove those callbacks as appropriate. * </p> */ onCancelPendingInputEvents():void { this.removePerformClickCallback(); this.cancelLongPress(); this.mPrivateFlags3 |= View.PFLAG3_CALLED_SUPER; } private removeLongPressCallback() { if (this.mPendingCheckForLongPress != null) { this.removeCallbacks(this.mPendingCheckForLongPress); } } private removePerformClickCallback() { if (this.mPerformClick != null) { this.removeCallbacks(this.mPerformClick); } if (this.mPerformClickAfterPressDraw != null) { this.removeCallbacks(this.mPerformClickAfterPressDraw); } } private removeUnsetPressCallback() { if ((this.mPrivateFlags & View.PFLAG_PRESSED) != 0 && this.mUnsetPressedState != null) { this.setPressed(false); this.removeCallbacks(this.mUnsetPressedState); } } private removeTapCallback() { if (this.mPendingCheckForTap != null) { this.mPrivateFlags &= ~View.PFLAG_PREPRESSED; this.removeCallbacks(this.mPendingCheckForTap); } } cancelLongPress() { this.removeLongPressCallback(); /* * The prepressed state handled by the tap callback is a display * construct, but the tap callback will post a long press callback * less its own timeout. Remove it here. */ this.removeTapCallback(); } setTouchDelegate(delegate:TouchDelegate) { this.mTouchDelegate = delegate; } getTouchDelegate() { return this.mTouchDelegate; } getListenerInfo() { if (this.mListenerInfo != null) { return this.mListenerInfo; } this.mListenerInfo = new View.ListenerInfo(); return this.mListenerInfo; } addOnLayoutChangeListener(listener:View.OnLayoutChangeListener) { let li = this.getListenerInfo(); if (li.mOnLayoutChangeListeners == null) { li.mOnLayoutChangeListeners = new ArrayList<View.OnLayoutChangeListener>(); } if (!li.mOnLayoutChangeListeners.contains(listener)) { li.mOnLayoutChangeListeners.add(listener); } } removeOnLayoutChangeListener(listener:View.OnLayoutChangeListener) { let li = this.mListenerInfo; if (li == null || li.mOnLayoutChangeListeners == null) { return; } li.mOnLayoutChangeListeners.remove(listener); } addOnAttachStateChangeListener(listener:View.OnAttachStateChangeListener) { let li = this.getListenerInfo(); if (li.mOnAttachStateChangeListeners == null) { li.mOnAttachStateChangeListeners = new CopyOnWriteArrayList<View.OnAttachStateChangeListener>(); } li.mOnAttachStateChangeListeners.add(listener); } removeOnAttachStateChangeListener(listener:View.OnAttachStateChangeListener) { let li = this.mListenerInfo; if (li == null || li.mOnAttachStateChangeListeners == null) { return; } li.mOnAttachStateChangeListeners.remove(listener); } //AndroidUIX add: call for init view from xml / onclick attr value change private setOnClickListenerByAttrValueString(onClickAttrString:string):void { this.setOnClickListener((view:View) => { if (!onClickAttrString) return; // call activity method let activityClickMethod = view.getContext()[onClickAttrString]; if (typeof activityClickMethod === 'function') { try { activityClickMethod.call(view.getContext(), view); } catch (e) { console.error(e); throw new Error(`Could not execute method '${onClickAttrString}' of the activity`); } return; } else { // eval js code try { new Function(onClickAttrString).call(view); } catch (e) { console.error(e); throw new Error("Could not execute or find a method " + onClickAttrString + "(View) in the activity " + view.getContext().constructor.name + " for onClick handler" + " on view " + view.getClass() + view.getId()); } } }); } setOnClickListener(l:View.OnClickListener|((v:View)=>void)) { if (!this.isClickable()) { this.setClickable(true); } if(typeof l == "function"){ l = View.OnClickListener.fromFunction(<(v:View)=>void>l); } this.getListenerInfo().mOnClickListener = <View.OnClickListener>l; } hasOnClickListeners():boolean { let li = this.mListenerInfo; return (li != null && li.mOnClickListener != null); } setOnLongClickListener(l:View.OnLongClickListener|((v:View)=>boolean)) { if (!this.isLongClickable()) { this.setLongClickable(true); } if(typeof l == "function"){ l = View.OnLongClickListener.fromFunction(<(v:View)=>boolean>l); } this.getListenerInfo().mOnLongClickListener = <View.OnLongClickListener>l; } playSoundEffect(soundConstant:number){ //no impl } performHapticFeedback(feedbackConstant:number):boolean { //no impl return false; } performClick(event?:MotionEvent):boolean { let li = this.mListenerInfo; if (li != null && li.mOnClickListener != null) { li.mOnClickListener.onClick(this); return true; } return false; } callOnClick():boolean { let li = this.mListenerInfo; if (li != null && li.mOnClickListener != null) { li.mOnClickListener.onClick(this); return true; } return false; } performLongClick():boolean { let handled = false; let li = this.mListenerInfo; if (li != null && li.mOnLongClickListener != null) { handled = li.mOnLongClickListener.onLongClick(this); } return handled; } /** * Performs button-related actions during a touch down event. * * @param event The event. * @return True if the down was consumed. * * @hide */ performButtonActionOnTouchDown(event:MotionEvent):boolean { //no impl //if ((event.getButtonState() & MotionEvent.BUTTON_SECONDARY) != 0) { // if (this.showContextMenu(event.getX(), event.getY(), event.getMetaState())) { // return true; // } //} return false; } private checkForLongClick(delayOffset=0) { if ((this.mViewFlags & View.LONG_CLICKABLE) == View.LONG_CLICKABLE) { this.mHasPerformedLongPress = false; if (this.mPendingCheckForLongPress == null) { this.mPendingCheckForLongPress = new CheckForLongPress(this); } this.mPendingCheckForLongPress.rememberWindowAttachCount(); this.postDelayed(this.mPendingCheckForLongPress, ViewConfiguration.getLongPressTimeout() - delayOffset); } } setOnTouchListener(l:View.OnTouchListener|((v:View, event:MotionEvent)=>void)) { if(typeof l == "function"){ l = View.OnTouchListener.fromFunction(<()=>void>l); } this.getListenerInfo().mOnTouchListener = <View.OnTouchListener>l; } isClickable() { return (this.mViewFlags & View.CLICKABLE) == View.CLICKABLE; } setClickable(clickable:boolean) { this.setFlags(clickable ? View.CLICKABLE : 0, View.CLICKABLE); } isLongClickable():boolean { return (this.mViewFlags & View.LONG_CLICKABLE) == View.LONG_CLICKABLE; } setLongClickable(longClickable:boolean) { this.setFlags(longClickable ? View.LONG_CLICKABLE : 0, View.LONG_CLICKABLE); } setPressed(pressed:boolean){ const needsRefresh = pressed != ((this.mPrivateFlags & View.PFLAG_PRESSED) == View.PFLAG_PRESSED); if (pressed) { this.mPrivateFlags |= View.PFLAG_PRESSED; } else { this.mPrivateFlags &= ~View.PFLAG_PRESSED; } if (needsRefresh) { this.refreshDrawableState(); } this.dispatchSetPressed(pressed); } dispatchSetPressed(pressed:boolean):void { } isPressed():boolean { return (this.mPrivateFlags & View.PFLAG_PRESSED) == View.PFLAG_PRESSED; } setSelected(selected:boolean) { if (((this.mPrivateFlags & View.PFLAG_SELECTED) != 0) != selected) { this.mPrivateFlags = (this.mPrivateFlags & ~View.PFLAG_SELECTED) | (selected ? View.PFLAG_SELECTED : 0); if (!selected) this.resetPressedState(); this.invalidate(true); this.refreshDrawableState(); this.dispatchSetSelected(selected); } } dispatchSetSelected(selected:boolean) { } isSelected() { return (this.mPrivateFlags & View.PFLAG_SELECTED) != 0; } setActivated(activated:boolean) { if (((this.mPrivateFlags & View.PFLAG_ACTIVATED) != 0) != activated) { this.mPrivateFlags = (this.mPrivateFlags & ~View.PFLAG_ACTIVATED) | (activated ? View.PFLAG_ACTIVATED : 0); this.invalidate(true); this.refreshDrawableState(); this.dispatchSetActivated(activated); } } dispatchSetActivated(activated:boolean) { } isActivated() { return (this.mPrivateFlags & View.PFLAG_ACTIVATED) != 0; } getViewTreeObserver() { if (this.mAttachInfo != null) { return this.mAttachInfo.mViewRootImpl.mTreeObserver; } if (this.mFloatingTreeObserver == null) { this.mFloatingTreeObserver = new ViewTreeObserver(); } return this.mFloatingTreeObserver; } setLayoutDirection(layoutDirection:number):void { } getLayoutDirection():number { return View.LAYOUT_DIRECTION_LTR; } isLayoutRtl():boolean { return (this.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL); } /** * Return the resolved text direction. * * @return the resolved text direction. Returns one of: * * {@link #TEXT_DIRECTION_FIRST_STRONG} * {@link #TEXT_DIRECTION_ANY_RTL}, * {@link #TEXT_DIRECTION_LTR}, * {@link #TEXT_DIRECTION_RTL}, * {@link #TEXT_DIRECTION_LOCALE} * * @attr ref android.R.styleable#View_textDirection */ getTextDirection():number { return View.TEXT_DIRECTION_LTR; //(this.mPrivateFlags2 & View.PFLAG2_TEXT_DIRECTION_RESOLVED_MASK) >> View.PFLAG2_TEXT_DIRECTION_RESOLVED_MASK_SHIFT; } setTextDirection(textDirection:number):void { //do nothing } /** * Return the resolved text alignment. * * @return the resolved text alignment. Returns one of: * * {@link #TEXT_ALIGNMENT_GRAVITY}, * {@link #TEXT_ALIGNMENT_CENTER}, * {@link #TEXT_ALIGNMENT_TEXT_START}, * {@link #TEXT_ALIGNMENT_TEXT_END}, * {@link #TEXT_ALIGNMENT_VIEW_START}, * {@link #TEXT_ALIGNMENT_VIEW_END} * * @attr ref android.R.styleable#View_textAlignment */ getTextAlignment():number { return View.TEXT_ALIGNMENT_DEFAULT;//(this.mPrivateFlags2 & View.PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK) >> View.PFLAG2_TEXT_ALIGNMENT_RESOLVED_MASK_SHIFT; } setTextAlignment(textAlignment:number):void { //do nothing } getBaseline():number { return -1; } isLayoutRequested():boolean { return (this.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) == View.PFLAG_FORCE_LAYOUT; } getLayoutParams():ViewGroup.LayoutParams { return this.mLayoutParams; } setLayoutParams(params:ViewGroup.LayoutParams) { if (params == null) { throw new Error("Layout parameters cannot be null"); } this.mLayoutParams = params; //resolveLayoutParams(); let p = this.mParent; if (p instanceof ViewGroup) { p.onSetLayoutParams(this, params); } this.requestLayout(); } isInLayout():boolean { let viewRoot:ViewRootImpl = this.getViewRootImpl(); return (viewRoot != null && viewRoot.isInLayout()); } requestLayout():void { if (this.mMeasureCache != null) this.mMeasureCache.clear(); if (this.mAttachInfo != null && this.mAttachInfo.mViewRequestingLayout == null) { // Only trigger request-during-layout logic if this is the view requesting it, // not the views in its parent hierarchy let viewRoot = this.getViewRootImpl(); if (viewRoot != null && viewRoot.isInLayout()) { if (!viewRoot.requestLayoutDuringLayout(this)) { return; } } this.mAttachInfo.mViewRequestingLayout = this; } this.mPrivateFlags |= View.PFLAG_FORCE_LAYOUT; this.mPrivateFlags |= View.PFLAG_INVALIDATED; if (this.mParent != null && !this.mParent.isLayoutRequested()) { this.mParent.requestLayout(); } if (this.mAttachInfo != null && this.mAttachInfo.mViewRequestingLayout == this) { this.mAttachInfo.mViewRequestingLayout = null; } } forceLayout() { if (this.mMeasureCache != null) this.mMeasureCache.clear(); this.mPrivateFlags |= View.PFLAG_FORCE_LAYOUT; this.mPrivateFlags |= View.PFLAG_INVALIDATED; } isLaidOut():boolean { return (this.mPrivateFlags3 & View.PFLAG3_IS_LAID_OUT) == View.PFLAG3_IS_LAID_OUT; } layout(l:number, t:number, r:number, b:number):void { if ((this.mPrivateFlags3 & View.PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { this.onMeasure(this.mOldWidthMeasureSpec, this.mOldHeightMeasureSpec); this.mPrivateFlags3 &= ~View.PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; } let oldL = this.mLeft; let oldT = this.mTop; let oldB = this.mBottom; let oldR = this.mRight; let changed = this.setFrame(l, t, r, b); if (changed || (this.mPrivateFlags & View.PFLAG_LAYOUT_REQUIRED) == View.PFLAG_LAYOUT_REQUIRED) { this.onLayout(changed, l, t, r, b); this.mPrivateFlags &= ~View.PFLAG_LAYOUT_REQUIRED; let li = this.mListenerInfo; if (li != null && li.mOnLayoutChangeListeners != null) { let listenersCopy = li.mOnLayoutChangeListeners.clone(); let numListeners = listenersCopy.size(); for (let i = 0; i < numListeners; ++i) { listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB); } } } this.mPrivateFlags &= ~View.PFLAG_FORCE_LAYOUT; this.mPrivateFlags3 |= View.PFLAG3_IS_LAID_OUT; } protected onLayout(changed:boolean, left:number, top:number, right:number, bottom:number):void { } protected setFrame(left:number, top:number, right:number, bottom:number) { let changed = false; if (View.DBG) { Log.i("View", this + " View.setFrame(" + left + "," + top + "," + right + "," + bottom + ")"); } if (this.mLeft != left || this.mRight != right || this.mTop != top || this.mBottom != bottom) { changed = true; // Remember our drawn bit let drawn = this.mPrivateFlags & View.PFLAG_DRAWN; let oldWidth = this.mRight - this.mLeft; let oldHeight = this.mBottom - this.mTop; let newWidth = right - left; let newHeight = bottom - top; let sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight); // Invalidate our old position this.invalidate(sizeChanged); this.mLeft = left; this.mTop = top; this.mRight = right; this.mBottom = bottom; this.mPrivateFlags |= View.PFLAG_HAS_BOUNDS; if (sizeChanged) { if ((this.mPrivateFlags & View.PFLAG_PIVOT_EXPLICITLY_SET) == 0) { // A change in dimension means an auto-centered pivot point changes, too if (this.mTransformationInfo != null) { this.mTransformationInfo.mMatrixDirty = true; } } this.sizeChange(newWidth, newHeight, oldWidth, oldHeight); } if ((this.mViewFlags & View.VISIBILITY_MASK) == View.VISIBLE) { // If we are visible, force the DRAWN bit to on so that // this invalidate will go through (at least to our parent). // This is because someone may have invalidated this view // before this call to setFrame came in, thereby clearing // the DRAWN bit. this.mPrivateFlags |= View.PFLAG_DRAWN; this.invalidate(sizeChanged); // parent display list may need to be recreated based on a change in the bounds // of any child //this.invalidateParentCaches(); } // Reset drawn bit to original value (invalidate turns it off) this.mPrivateFlags |= drawn; this.mBackgroundSizeChanged = true; } return changed; } private sizeChange(newWidth:number, newHeight:number, oldWidth:number, oldHeight:number):void { this.onSizeChanged(newWidth, newHeight, oldWidth, oldHeight); if (this.mOverlay != null) { this.mOverlay.getOverlayView().setRight(newWidth); this.mOverlay.getOverlayView().setBottom(newHeight); } } /** * Hit rectangle in parent's coordinates * * @param outRect The hit rectangle of the view. */ getHitRect(outRect:Rect):void { this.updateMatrix(); const info:View.TransformationInfo = this.mTransformationInfo; if (info == null || info.mMatrixIsIdentity || this.mAttachInfo == null) { outRect.set(this.mLeft, this.mTop, this.mRight, this.mBottom); } else { const tmpRect:RectF = this.mAttachInfo.mTmpTransformRect; tmpRect.set(0, 0, this.getWidth(), this.getHeight()); info.mMatrix.mapRect(tmpRect); outRect.set(Math.floor(tmpRect.left) + this.mLeft, Math.floor(tmpRect.top) + this.mTop, Math.floor(tmpRect.right) + this.mLeft, Math.floor(tmpRect.bottom) + this.mTop); } } getFocusedRect(r:Rect) { this.getDrawingRect(r); } getDrawingRect(outRect:Rect) { outRect.left = this.mScrollX; outRect.top = this.mScrollY; outRect.right = this.mScrollX + (this.mRight - this.mLeft); outRect.bottom = this.mScrollY + (this.mBottom - this.mTop); } /** * If some part of this view is not clipped by any of its parents, then * return that area in r in global (root) coordinates. To convert r to local * coordinates (without taking possible View rotations into account), offset * it by -globalOffset (e.g. r.offset(-globalOffset.x, -globalOffset.y)). * If the view is completely clipped or translated out, return false. * * @param r If true is returned, r holds the global coordinates of the * visible portion of this view. * @param globalOffset If true is returned, globalOffset holds the dx,dy * between this view and its root. globalOffet may be null. * @return true if r is non-empty (i.e. part of the view is visible at the * root level. */ getGlobalVisibleRect(r:Rect, globalOffset:Point = null):boolean { let width:number = this.mRight - this.mLeft; let height:number = this.mBottom - this.mTop; if (width > 0 && height > 0) { r.set(0, 0, width, height); if (globalOffset != null) { globalOffset.set(-this.mScrollX, -this.mScrollY); } return this.mParent == null || this.mParent.getChildVisibleRect(this, r, globalOffset); } return false; } /** * <p>Computes the coordinates of this view on the screen. The argument * must be an array of two integers. After the method returns, the array * contains the x and y location in that order.</p> * * @param location an array of two integers in which to hold the coordinates */ getLocationOnScreen(location:number[]):void { this.getLocationInWindow(location); const info:View.AttachInfo = this.mAttachInfo; //if (info != null) { // location[0] += info.mWindowLeft; // location[1] += info.mWindowTop; //} } /** * <p>Computes the coordinates of this view in its window. The argument * must be an array of two integers. After the method returns, the array * contains the x and y location in that order.</p> * * @param location an array of two integers in which to hold the coordinates */ getLocationInWindow(location:number[]):void { if (location == null || location.length < 2) { throw Error(`new IllegalArgumentException("location must be an array of two integers")`); } if (this.mAttachInfo == null) { // When the view is not attached to a window, this method does not make sense location[0] = location[1] = 0; return; } let position:number[] = this.mAttachInfo.mTmpTransformLocation; position[0] = position[1] = 0.0; if (!this.hasIdentityMatrix()) { this.getMatrix().mapPoints(position); } position[0] += this.mLeft; position[1] += this.mTop; let viewParent:ViewParent = this.mParent; while (viewParent instanceof View) { const view:View = <View><any>viewParent; position[0] -= view.mScrollX; position[1] -= view.mScrollY; if (!view.hasIdentityMatrix()) { view.getMatrix().mapPoints(position); } position[0] += view.mLeft; position[1] += view.mTop; viewParent = view.mParent; } //if (viewParent instanceof ViewRootImpl) { // // *cough* // const vr:ViewRootImpl = <ViewRootImpl> viewParent; // position[1] -= vr.mCurScrollY; //} location[0] = Math.floor((position[0] + 0.5)); location[1] = Math.floor((position[1] + 0.5)); } /** * Retrieve the overall visible display size in which the window this view is * attached to has been positioned in. This takes into account screen * decorations above the window, for both cases where the window itself * is being position inside of them or the window is being placed under * then and covered insets are used for the window to position its content * inside. In effect, this tells you the available area where content can * be placed and remain visible to users. * * <p>This function requires an IPC back to the window manager to retrieve * the requested information, so should not be used in performance critical * code like drawing. * * @param outRect Filled in with the visible display frame. If the view * is not attached to a window, this is simply the raw display size. */ getWindowVisibleDisplayFrame(outRect:Rect):void { if (this.mAttachInfo != null) { let rootView = this.mAttachInfo.mRootView; let xy = [0, 0]; rootView.getLocationOnScreen(xy); outRect.set(xy[0], xy[1], rootView.getWidth()+xy[0], rootView.getHeight()+xy[1]); return; } // The view is not attached to a display so we don't have a context. // Make a best guess about the display size. let dm = Resources.getSystem().getDisplayMetrics(); outRect.set(0, 0, dm.widthPixels, dm.heightPixels); } /** * Computes whether the given portion of this view is visible to the user. * Such a view is attached, visible, all its predecessors are visible, * has an alpha greater than zero, and the specified portion is not * clipped entirely by its predecessors. * * @param boundInView the portion of the view to test; coordinates should be relative; may be * <code>null</code>, and the entire view will be tested in this case. * When <code>true</code> is returned by the function, the actual visible * region will be stored in this parameter; that is, if boundInView is fully * contained within the view, no modification will be made, otherwise regions * outside of the visible area of the view will be clipped. * * @return Whether the specified portion of the view is visible on the screen. * * @hide */ protected isVisibleToUser(boundInView:Rect = null):boolean { if (this.mAttachInfo != null) { // Attached to invisible window means this view is not visible. if (this.mAttachInfo.mWindowVisibility != View.VISIBLE) { return false; } // An invisible predecessor or one with alpha zero means // that this view is not visible to the user. let current:any = this; while (current instanceof View) { let view:View = <View> current; // need to check whether we reach to ViewRootImpl on the way up. if (view.getAlpha() <= 0 || view.getTransitionAlpha() <= 0 || view.getVisibility() != View.VISIBLE) { return false; } current = view.mParent; } // Check if the view is entirely covered by its predecessors. let visibleRect:Rect = this.mAttachInfo.mTmpInvalRect; let offset:Point = this.mAttachInfo.mPoint; if (!this.getGlobalVisibleRect(visibleRect, offset)) { return false; } // Check if the visible portion intersects the rectangle of interest. if (boundInView != null) { visibleRect.offset(-offset.x, -offset.y); return boundInView.intersect(visibleRect); } return true; } return false; } getMeasuredWidth():number { return this.mMeasuredWidth & View.MEASURED_SIZE_MASK; } getMeasuredWidthAndState() { return this.mMeasuredWidth; } getMeasuredHeight():number { return this.mMeasuredHeight & View.MEASURED_SIZE_MASK; } getMeasuredHeightAndState():number { return this.mMeasuredHeight; } getMeasuredState():number { return (this.mMeasuredWidth&View.MEASURED_STATE_MASK) | ((this.mMeasuredHeight>>View.MEASURED_HEIGHT_STATE_SHIFT) & (View.MEASURED_STATE_MASK>>View.MEASURED_HEIGHT_STATE_SHIFT)); } measure(widthMeasureSpec:number, heightMeasureSpec:number) { // Suppress sign extension for the low bytes let key = widthMeasureSpec + ',' + heightMeasureSpec; if (this.mMeasureCache == null) this.mMeasureCache = new Map<string, number[]>(); if ((this.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) == View.PFLAG_FORCE_LAYOUT || widthMeasureSpec != this.mOldWidthMeasureSpec || heightMeasureSpec != this.mOldHeightMeasureSpec) { // first clears the measured dimension flag this.mPrivateFlags &= ~View.PFLAG_MEASURED_DIMENSION_SET; //resolveRtlPropertiesIfNeeded(); let cacheValue:number[] = (this.mPrivateFlags & View.PFLAG_FORCE_LAYOUT) == View.PFLAG_FORCE_LAYOUT ? null : this.mMeasureCache.get(key); if (cacheValue==null) { // measure ourselves, this should set the measured dimension flag back this.onMeasure(widthMeasureSpec, heightMeasureSpec); this.mPrivateFlags3 &= ~View.PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; } else { // Casting a long to int drops the high 32 bits, no mask needed this.setMeasuredDimension(cacheValue[0], cacheValue[1]); this.mPrivateFlags3 |= View.PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; } // flag not set, setMeasuredDimension() was not invoked, we raise // an exception to warn the developer if ((this.mPrivateFlags & View.PFLAG_MEASURED_DIMENSION_SET) != View.PFLAG_MEASURED_DIMENSION_SET) { throw new Error("onMeasure() did not set the" + " measured dimension by calling" + " setMeasuredDimension()"); } this.mPrivateFlags |= View.PFLAG_LAYOUT_REQUIRED; } this.mOldWidthMeasureSpec = widthMeasureSpec; this.mOldHeightMeasureSpec = heightMeasureSpec; this.mMeasureCache.set(key, [this.mMeasuredWidth, this.mMeasuredHeight]); // suppress sign extension } protected onMeasure(widthMeasureSpec:number, heightMeasureSpec:number):void { this.setMeasuredDimension(View.getDefaultSize(this.getSuggestedMinimumWidth(), widthMeasureSpec), View.getDefaultSize(this.getSuggestedMinimumHeight(), heightMeasureSpec)); } setMeasuredDimension(measuredWidth, measuredHeight) { this.mMeasuredWidth = measuredWidth; this.mMeasuredHeight = measuredHeight; this.mPrivateFlags |= View.PFLAG_MEASURED_DIMENSION_SET; } static combineMeasuredStates(curState, newState) { return curState | newState; } static resolveSize(size, measureSpec) { return View.resolveSizeAndState(size, measureSpec, 0) & View.MEASURED_SIZE_MASK; } static resolveSizeAndState(size, measureSpec, childMeasuredState) { let MeasureSpec = View.MeasureSpec; let result = size; let specMode = MeasureSpec.getMode(measureSpec); let specSize = MeasureSpec.getSize(measureSpec); switch (specMode) { case MeasureSpec.UNSPECIFIED: result = size; break; case MeasureSpec.AT_MOST: if (specSize < size) { result = specSize | View.MEASURED_STATE_TOO_SMALL; } else { result = size; } break; case MeasureSpec.EXACTLY: result = specSize; break; } return result | (childMeasuredState & View.MEASURED_STATE_MASK); } static getDefaultSize(size, measureSpec) { let MeasureSpec = View.MeasureSpec; let result = size; let specMode = MeasureSpec.getMode(measureSpec); let specSize = MeasureSpec.getSize(measureSpec); switch (specMode) { case MeasureSpec.UNSPECIFIED: result = size; break; case MeasureSpec.AT_MOST: case MeasureSpec.EXACTLY: result = specSize; break; } return result; } getSuggestedMinimumHeight() { return (this.mBackground == null) ? this.mMinHeight : Math.max(this.mMinHeight, this.mBackground.getMinimumHeight()); } getSuggestedMinimumWidth() { return (this.mBackground == null) ? this.mMinWidth : Math.max(this.mMinWidth, this.mBackground.getMinimumWidth()); } getMinimumHeight() { return this.mMinHeight; } setMinimumHeight(minHeight) { this.mMinHeight = minHeight; this.requestLayout(); } getMinimumWidth() { return this.mMinWidth; } setMinimumWidth(minWidth) { this.mMinWidth = minWidth; this.requestLayout(); } /** * Get the animation currently associated with this view. * * @return The animation that is currently playing or * scheduled to play for this view. */ getAnimation():Animation { return this.mCurrentAnimation; } /** * Start the specified animation now. * * @param animation the animation to start now */ startAnimation(animation:Animation):void { animation.setStartTime(Animation.START_ON_FIRST_FRAME); this.setAnimation(animation); this.invalidateParentCaches(); this.invalidate(true); } /** * Cancels any animations for this view. */ clearAnimation():void { if (this.mCurrentAnimation != null) { this.mCurrentAnimation.detach(); } this.mCurrentAnimation = null; this.invalidateParentIfNeeded(); } /** * Sets the next animation to play for this view. * If you want the animation to play immediately, use * {@link #startAnimation(android.view.animation.Animation)} instead. * This method provides allows fine-grained * control over the start time and invalidation, but you * must make sure that 1) the animation has a start time set, and * 2) the view's parent (which controls animations on its children) * will be invalidated when the animation is supposed to * start. * * @param animation The next animation, or null. */ setAnimation(animation:Animation):void { this.mCurrentAnimation = animation; if (animation != null) { // would cause the animation to start when the screen turns back on //if (this.mAttachInfo != null // && !this.mAttachInfo.mScreenOn // && animation.getStartTime() == Animation.START_ON_FIRST_FRAME) { // animation.setStartTime(AnimationUtils.currentAnimationTimeMillis()); //} animation.reset(); } } /** * Invoked by a parent ViewGroup to notify the start of the animation * currently associated with this view. If you override this method, * always call super.onAnimationStart(); * * @see #setAnimation(android.view.animation.Animation) * @see #getAnimation() */ protected onAnimationStart():void { this.mPrivateFlags |= View.PFLAG_ANIMATION_STARTED; } /** * Invoked by a parent ViewGroup to notify the end of the animation * currently associated with this view. If you override this method, * always call super.onAnimationEnd(); * * @see #setAnimation(android.view.animation.Animation) * @see #getAnimation() */ protected onAnimationEnd():void { this.mPrivateFlags &= ~View.PFLAG_ANIMATION_STARTED; } /** * Invoked if there is a Transform that involves alpha. Subclass that can * draw themselves with the specified alpha should return true, and then * respect that alpha when their onDraw() is called. If this returns false * then the view may be redirected to draw into an offscreen buffer to * fulfill the request, which will look fine, but may be slower than if the * subclass handles it internally. The default implementation returns false. * * @param alpha The alpha (0..255) to apply to the view's drawing * @return true if the view can draw with the specified alpha. */ protected onSetAlpha(alpha:number):boolean { return false; } private _invalidateRect(l:number, t:number, r:number, b:number){ if (this.skipInvalidate()) { return; } if ((this.mPrivateFlags & (View.PFLAG_DRAWN | View.PFLAG_HAS_BOUNDS)) == (View.PFLAG_DRAWN | View.PFLAG_HAS_BOUNDS) || (this.mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) == View.PFLAG_DRAWING_CACHE_VALID || (this.mPrivateFlags & View.PFLAG_INVALIDATED) != View.PFLAG_INVALIDATED) { this.mPrivateFlags &= ~View.PFLAG_DRAWING_CACHE_VALID; this.mPrivateFlags |= View.PFLAG_INVALIDATED; this.mPrivateFlags |= View.PFLAG_DIRTY; const p = this.mParent; const ai = this.mAttachInfo; //noinspection PointlessBooleanExpression,ConstantConditions // if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { // if (p != null && ai != null && ai.mHardwareAccelerated) { // // fast-track for GL-enabled applications; just invalidate the whole hierarchy // // with a null dirty rect, which tells the ViewAncestor to redraw everything // p.invalidateChild(this, null); // return; // } // } if (p != null && ai != null && l < r && t < b) { const scrollX = this.mScrollX; const scrollY = this.mScrollY; const tmpr = ai.mTmpInvalRect; tmpr.set(l - scrollX, t - scrollY, r - scrollX, b - scrollY); p.invalidateChild(this, tmpr); } } } private _invalidateCache(invalidateCache=true){ if (this.skipInvalidate()) { return; } if ((this.mPrivateFlags & (View.PFLAG_DRAWN | View.PFLAG_HAS_BOUNDS)) == (View.PFLAG_DRAWN | View.PFLAG_HAS_BOUNDS) || (invalidateCache && (this.mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) == View.PFLAG_DRAWING_CACHE_VALID) || (this.mPrivateFlags & View.PFLAG_INVALIDATED) != View.PFLAG_INVALIDATED || this.isOpaque() != this.mLastIsOpaque) { this.mLastIsOpaque = this.isOpaque(); this.mPrivateFlags &= ~View.PFLAG_DRAWN; this.mPrivateFlags |= View.PFLAG_DIRTY; if (invalidateCache) { this.mPrivateFlags |= View.PFLAG_INVALIDATED; this.mPrivateFlags &= ~View.PFLAG_DRAWING_CACHE_VALID; } const ai = this.mAttachInfo; const p = this.mParent; if (p != null && ai != null) { const r = ai.mTmpInvalRect; r.set(0, 0, this.mRight - this.mLeft, this.mBottom - this.mTop); // Don't call invalidate -- we don't want to internally scroll // our own bounds p.invalidateChild(this, r); } } } invalidate(); invalidate(invalidateCache:boolean); invalidate(dirty:Rect); invalidate(l:number, t:number, r:number, b:number); invalidate(...args){ if(args.length===0){ this._invalidateCache(true); }else if(args.length===1 && args[0] instanceof Rect){ let rect:Rect = args[0]; this._invalidateRect(rect.left, rect.top, rect.right, rect.bottom); }else if(args.length===1){ this._invalidateCache(args[0]); }else if(args.length===4){ (<any>this)._invalidateRect(...args); } } invalidateViewProperty(invalidateParent:boolean, forceRedraw:boolean){ if ((this.mPrivateFlags & View.PFLAG_DRAW_ANIMATION) == View.PFLAG_DRAW_ANIMATION) { if (invalidateParent) { this.invalidateParentCaches(); } if (forceRedraw) { this.mPrivateFlags |= View.PFLAG_DRAWN; // force another invalidation with the new orientation } this.invalidate(false); } else { const ai = this.mAttachInfo; const p = this.mParent; if (p != null && ai != null) { const r = ai.mTmpInvalRect; r.set(0, 0, this.mRight - this.mLeft, this.mBottom - this.mTop); if (this.mParent instanceof ViewGroup) { (<ViewGroup>this.mParent).invalidateChildFast(this, r); } else { this.mParent.invalidateChild(this, r); } } } } invalidateParentCaches(){ if (this.mParent instanceof View) { (<any> this.mParent).mPrivateFlags |= View.PFLAG_INVALIDATED; } } invalidateParentIfNeeded(){ //no HardwareAccelerated, no need //if (isHardwareAccelerated() && mParent instanceof View) { // ((View) mParent).invalidate(true); //} } postInvalidate(l?:number, t?:number, r?:number, b?:number){ this.postInvalidateDelayed(0, l, t, r, b); } postInvalidateDelayed(delayMilliseconds:number, left?:number, top?:number, right?:number, bottom?:number){ const attachInfo = this.mAttachInfo; if (attachInfo != null) { if(!Number.isInteger(left) || !Number.isInteger(top) || !Number.isInteger(right) || !Number.isInteger(bottom)){ attachInfo.mViewRootImpl.dispatchInvalidateDelayed(this, delayMilliseconds); }else{ const info = View.AttachInfo.InvalidateInfo.obtain(); info.target = this; info.left = left; info.top = top; info.right = right; info.bottom = bottom; attachInfo.mViewRootImpl.dispatchInvalidateRectDelayed(info, delayMilliseconds); } } } postInvalidateOnAnimation(left?:number, top?:number, right?:number, bottom?:number){ const attachInfo = this.mAttachInfo; if (attachInfo != null) { if(!Number.isInteger(left) || !Number.isInteger(top) || !Number.isInteger(right) || !Number.isInteger(bottom)){ attachInfo.mViewRootImpl.dispatchInvalidateOnAnimation(this); }else{ const info = View.AttachInfo.InvalidateInfo.obtain(); info.target = this; info.left = left; info.top = top; info.right = right; info.bottom = bottom; attachInfo.mViewRootImpl.dispatchInvalidateRectOnAnimation(info); } } } private skipInvalidate() { return (this.mViewFlags & View.VISIBILITY_MASK) != View.VISIBLE && this.mCurrentAnimation == null //TODO when transition ok //&&(!(mParent instanceof ViewGroup) || //!mParent.isViewTransitioning(this)) ; } isOpaque():boolean { return (this.mPrivateFlags & View.PFLAG_OPAQUE_MASK) == View.PFLAG_OPAQUE_MASK && this.getFinalAlpha() >= 1; } private computeOpaqueFlags() { // Opaque if: // - Has a background // - Background is opaque // - Doesn't have scrollbars or scrollbars overlay if (this.mBackground != null && this.mBackground.getOpacity() == PixelFormat.OPAQUE) { this.mPrivateFlags |= View.PFLAG_OPAQUE_BACKGROUND; } else { this.mPrivateFlags &= ~View.PFLAG_OPAQUE_BACKGROUND; } const flags = this.mViewFlags; if (((flags & View.SCROLLBARS_VERTICAL) == 0 && (flags & View.SCROLLBARS_HORIZONTAL) == 0) ////scroll bar is always inside_overlay //|| //(flags & View.SCROLLBARS_STYLE_MASK) == View.SCROLLBARS_INSIDE_OVERLAY || //(flags & View.SCROLLBARS_STYLE_MASK) == View.SCROLLBARS_OUTSIDE_OVERLAY ) { this.mPrivateFlags |= View.PFLAG_OPAQUE_SCROLLBARS; } else { this.mPrivateFlags &= ~View.PFLAG_OPAQUE_SCROLLBARS; } } setLayerType(layerType:number):void { if (layerType < View.LAYER_TYPE_NONE || layerType > View.LAYER_TYPE_SOFTWARE) { throw Error(`new IllegalArgumentException("Layer type can only be one of: LAYER_TYPE_NONE, " + "LAYER_TYPE_SOFTWARE")`); } if (layerType == this.mLayerType) { return; } // Destroy any previous software drawing cache if needed switch(this.mLayerType) { //case View.LAYER_TYPE_HARDWARE: // this.destroyLayer(false); // fall through - non-accelerated views may use software layer mechanism instead case View.LAYER_TYPE_SOFTWARE: this.destroyDrawingCache(); break; default: break; } this.mLayerType = layerType; const layerDisabled:boolean = this.mLayerType == View.LAYER_TYPE_NONE; //this.mLayerPaint = layerDisabled ? null : (paint == null ? new Paint() : paint); this.mLocalDirtyRect = layerDisabled ? null : new Rect(); this.invalidateParentCaches(); this.invalidate(true); } getLayerType():number { return this.mLayerType; } setClipBounds(clipBounds:Rect) { if (clipBounds != null) { if (clipBounds.equals(this.mClipBounds)) { return; } if (this.mClipBounds == null) { this.invalidate(); this.mClipBounds = new Rect(clipBounds); } else { this.invalidate(Math.min(this.mClipBounds.left, clipBounds.left), Math.min(this.mClipBounds.top, clipBounds.top), Math.max(this.mClipBounds.right, clipBounds.right), Math.max(this.mClipBounds.bottom, clipBounds.bottom)); this.mClipBounds.set(clipBounds); } } else { if (this.mClipBounds != null) { this.invalidate(); this.mClipBounds = null; } } } getClipBounds():Rect { return (this.mClipBounds != null) ? new Rect(this.mClipBounds) : null; } setCornerRadius(radiusTopLeft:number, radiusTopRight=radiusTopLeft, radiusBottomRight=radiusTopRight, radiusBottomLeft=radiusBottomRight):void { this.setCornerRadiusTopLeft(radiusTopLeft); this.setCornerRadiusTopRight(radiusTopRight); this.setCornerRadiusBottomRight(radiusBottomRight); this.setCornerRadiusBottomLeft(radiusBottomLeft); } setCornerRadiusTopLeft(value:number):void { if(this.mCornerRadiusTopLeft != value){ this.mCornerRadiusTopLeft = value; this.mShadowDrawable = null; this.invalidate(); } } getCornerRadiusTopLeft():number { return this.mCornerRadiusTopLeft; } setCornerRadiusTopRight(value:number):void { if(this.mCornerRadiusTopRight != value){ this.mCornerRadiusTopRight = value; this.mShadowDrawable = null; this.invalidate(); } } getCornerRadiusTopRight():number { return this.mCornerRadiusTopRight; } setCornerRadiusBottomRight(value:number):void { if(this.mCornerRadiusBottomRight != value){ this.mCornerRadiusBottomRight = value; this.mShadowDrawable = null; this.invalidate(); } } getCornerRadiusBottomRight():number { return this.mCornerRadiusBottomRight; } setCornerRadiusBottomLeft(value:number):void { if(this.mCornerRadiusBottomLeft != value){ this.mCornerRadiusBottomLeft = value; this.mShadowDrawable = null; this.invalidate(); } } getCornerRadiusBottomLeft():number { return this.mCornerRadiusBottomLeft; } setShadowView(radius:number, dx:number, dy:number, color:number):void { if(!this.mShadowPaint) this.mShadowPaint = new Paint(); this.mShadowPaint.setShadowLayer(radius, dx, dy, color); this.invalidate(); } getDrawingTime() { return this.getViewRootImpl() != null ? this.getViewRootImpl().mDrawingTime : 0; } protected drawFromParent(canvas:Canvas, parent:ViewGroup, drawingTime:number):boolean { let useDisplayListProperties = false; let more = false; let childHasIdentityMatrix = this.hasIdentityMatrix(); let flags = parent.mGroupFlags; if ((flags & ViewGroup.FLAG_CLEAR_TRANSFORMATION) == ViewGroup.FLAG_CLEAR_TRANSFORMATION) { parent.getChildTransformation().clear(); parent.mGroupFlags &= ~ViewGroup.FLAG_CLEAR_TRANSFORMATION; } let transformToApply:Transformation = null; let concatMatrix = false; let scalingRequired = false; let caching = false; let layerType = this.getLayerType(); const hardwareAccelerated = false; const nativeAccelerated = canvas.isNativeAccelerated(); if ((flags & ViewGroup.FLAG_CHILDREN_DRAWN_WITH_CACHE) != 0 || (flags & ViewGroup.FLAG_ALWAYS_DRAWN_WITH_CACHE) != 0) { caching = true; } else { caching = (layerType != View.LAYER_TYPE_NONE) || hardwareAccelerated || nativeAccelerated; } const a:Animation = this.getAnimation(); if (a != null) { more = this.drawAnimation(parent, drawingTime, a, scalingRequired); concatMatrix = a.willChangeTransformationMatrix(); if (concatMatrix) { this.mPrivateFlags3 |= View.PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; } transformToApply = parent.getChildTransformation(); } else { //if ((this.mPrivateFlags3 & View.PFLAG3_VIEW_IS_ANIMATING_TRANSFORM) == View.PFLAG3_VIEW_IS_ANIMATING_TRANSFORM && this.mDisplayList != null) { // // No longer animating: clear out old animation matrix // this.mDisplayList.setAnimationMatrix(null); // this.mPrivateFlags3 &= ~View.PFLAG3_VIEW_IS_ANIMATING_TRANSFORM; //} if (!useDisplayListProperties && (flags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { const t:Transformation = parent.getChildTransformation(); const hasTransform:boolean = parent.getChildStaticTransformation(this, t); if (hasTransform) { const transformType:number = t.getTransformationType(); transformToApply = transformType != Transformation.TYPE_IDENTITY ? t : null; concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; } } } concatMatrix = !childHasIdentityMatrix || concatMatrix; // Sets the flag as early as possible to allow draw() implementations // to call invalidate() successfully when doing animations this.mPrivateFlags |= View.PFLAG_DRAWN; if (!concatMatrix && (flags & (ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS | ViewGroup.FLAG_CLIP_CHILDREN)) == ViewGroup.FLAG_CLIP_CHILDREN && canvas.quickReject(this.mLeft, this.mTop, this.mRight, this.mBottom) && (this.mPrivateFlags & View.PFLAG_DRAW_ANIMATION) == 0) { this.mPrivateFlags2 |= View.PFLAG2_VIEW_QUICK_REJECTED; return more; } this.mPrivateFlags2 &= ~View.PFLAG2_VIEW_QUICK_REJECTED; //if (hardwareAccelerated) { // // Clear INVALIDATED flag to allow invalidation to occur during rendering, but // // retain the flag's value temporarily in the mRecreateDisplayList flag // this.mRecreateDisplayList = (this.mPrivateFlags & View.PFLAG_INVALIDATED) == View.PFLAG_INVALIDATED; // this.mPrivateFlags &= ~View.PFLAG_INVALIDATED; //} let cache:Canvas = null; if (caching) { if (layerType != View.LAYER_TYPE_NONE) { layerType = View.LAYER_TYPE_SOFTWARE; this.buildDrawingCache(true); } cache = this.getDrawingCache(true); } this.computeScroll(); let sx = this.mScrollX; let sy = this.mScrollY; this.requestSyncBoundToElement(); let hasNoCache = cache == null; let offsetForScroll = cache == null; let restoreTo:number = canvas.save(); if (offsetForScroll) { canvas.translate(this.mLeft - sx, this.mTop - sy); }else{ canvas.translate(this.mLeft, this.mTop); } let alpha = this.getAlpha() * this.getTransitionAlpha(); if (transformToApply != null || alpha < 1 || !this.hasIdentityMatrix() || (this.mPrivateFlags3 & View.PFLAG3_VIEW_IS_ANIMATING_ALPHA) == View.PFLAG3_VIEW_IS_ANIMATING_ALPHA) { if (transformToApply != null || !childHasIdentityMatrix) { let transX:number = 0; let transY:number = 0; if (offsetForScroll) { transX = -sx; transY = -sy; } if (transformToApply != null) { if (concatMatrix) { //if (useDisplayListProperties) { // displayList.setAnimationMatrix(transformToApply.getMatrix()); //} else { // Undo the scroll translation, apply the transformation matrix, // then redo the scroll translate to get the correct result. canvas.translate(-transX, -transY); canvas.concat(transformToApply.getMatrix()); canvas.translate(transX, transY); //} parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; } let transformAlpha:number = transformToApply.getAlpha(); if (transformAlpha < 1) { alpha *= transformAlpha; parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; } } if (!childHasIdentityMatrix && !useDisplayListProperties) { canvas.translate(-transX, -transY); canvas.concat(this.getMatrix()); canvas.translate(transX, transY); } } // Deal with alpha if it is or used to be <1 if (alpha < 1 || (this.mPrivateFlags3 & View.PFLAG3_VIEW_IS_ANIMATING_ALPHA) == View.PFLAG3_VIEW_IS_ANIMATING_ALPHA) { if (alpha < 1) { this.mPrivateFlags3 |= View.PFLAG3_VIEW_IS_ANIMATING_ALPHA; } else { this.mPrivateFlags3 &= ~View.PFLAG3_VIEW_IS_ANIMATING_ALPHA; } parent.mGroupFlags |= ViewGroup.FLAG_CLEAR_TRANSFORMATION; if (hasNoCache) { const multipliedAlpha:number = Math.floor((255 * alpha)); if (!this.onSetAlpha(multipliedAlpha)) { canvas.multiplyGlobalAlpha(alpha); //let layerFlags:number = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; //if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) != 0 || layerType != View.LAYER_TYPE_NONE) { // layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; //} //if (useDisplayListProperties) { // displayList.setAlpha(alpha * this.getAlpha() * this.getTransitionAlpha()); //} else //if (layerType == View.LAYER_TYPE_NONE) { // const scrollX:number = hasDisplayList ? 0 : sx; // const scrollY:number = hasDisplayList ? 0 : sy; // canvas.saveLayerAlpha(scrollX, scrollY, scrollX + this.mRight - this.mLeft, scrollY + this.mBottom - this.mTop, multipliedAlpha, layerFlags); //} } else { // Alpha is handled by the child directly, clobber the layer's alpha this.mPrivateFlags |= View.PFLAG_ALPHA_SET; } } } } else if ((this.mPrivateFlags & View.PFLAG_ALPHA_SET) == View.PFLAG_ALPHA_SET) { this.onSetAlpha(255); this.mPrivateFlags &= ~View.PFLAG_ALPHA_SET; } //androidui add: draw shadow before clip if(this.mShadowPaint!=null) this.drawShadow(canvas); if ((flags & ViewGroup.FLAG_CLIP_CHILDREN) == ViewGroup.FLAG_CLIP_CHILDREN && !useDisplayListProperties && cache == null) { if (offsetForScroll) { canvas.clipRect(sx, sy, sx + (this.mRight - this.mLeft), sy + (this.mBottom - this.mTop), this.mCornerRadiusTopLeft, this.mCornerRadiusTopRight, this.mCornerRadiusBottomRight, this.mCornerRadiusBottomLeft); } else { //androidui always false here. if (!scalingRequired || cache == null) { canvas.clipRect(0, 0, this.mRight - this.mLeft, this.mBottom - this.mTop, this.mCornerRadiusTopLeft, this.mCornerRadiusTopRight, this.mCornerRadiusBottomRight, this.mCornerRadiusBottomLeft); } else { canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight(), this.mCornerRadiusTopLeft, this.mCornerRadiusTopRight, this.mCornerRadiusBottomRight, this.mCornerRadiusBottomLeft); } } } if (hasNoCache) { // Fast path for layouts with no backgrounds if ((this.mPrivateFlags & View.PFLAG_SKIP_DRAW) == View.PFLAG_SKIP_DRAW) { this.mPrivateFlags &= ~View.PFLAG_DIRTY_MASK; this.dispatchDraw(canvas); } else { this.draw(canvas); } } else if (cache != null) { this.mPrivateFlags &= ~View.PFLAG_DIRTY_MASK; canvas.multiplyGlobalAlpha(alpha); if (layerType == View.LAYER_TYPE_NONE) { if (alpha < 1) { parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; } } //let cachePaint:Paint; //if (layerType == View.LAYER_TYPE_NONE) { // cachePaint = parent.mCachePaint; // if (cachePaint == null) { // cachePaint = new Paint(); // cachePaint.setDither(false); // parent.mCachePaint = cachePaint; // } // if (alpha < 1) { // cachePaint.setAlpha(Math.floor((alpha * 255))); // parent.mGroupFlags |= ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; // } else if ((flags & ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE) != 0) { // cachePaint.setAlpha(255); // parent.mGroupFlags &= ~ViewGroup.FLAG_ALPHA_LOWER_THAN_ONE; // } //} else { // cachePaint = this.mLayerPaint; // cachePaint.setAlpha(Math.floor((alpha * 255))); //} //androidui add canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight(), this.mCornerRadiusTopLeft, this.mCornerRadiusTopRight, this.mCornerRadiusBottomRight, this.mCornerRadiusBottomLeft); canvas.drawCanvas(cache, 0, 0); } if (restoreTo >= 0) { canvas.restoreToCount(restoreTo); } if (a != null && !more) { if (!hardwareAccelerated && !a.getFillAfter()) { this.onSetAlpha(255); } parent.finishAnimatingView(this, a); } return more; } private drawShadow(canvas:Canvas):void { let shadowPaint = this.mShadowPaint; if(!shadowPaint || !shadowPaint.shadowRadius) return; let color = shadowPaint.shadowColor; if(!this.mShadowDrawable){ let drawable = new RoundRectDrawable(shadowPaint.shadowColor, this.mCornerRadiusTopLeft, this.mCornerRadiusTopRight, this.mCornerRadiusBottomLeft, this.mCornerRadiusBottomRight); this.mShadowDrawable = new ShadowDrawable(drawable, shadowPaint.shadowRadius, shadowPaint.shadowDx, shadowPaint.shadowDy, shadowPaint.shadowColor); } this.mShadowDrawable.draw(canvas); } draw(canvas:Canvas):void { if (this.mClipBounds != null) { canvas.clipRect(this.mClipBounds); } let privateFlags = this.mPrivateFlags; const dirtyOpaque = (privateFlags & View.PFLAG_DIRTY_MASK) == View.PFLAG_DIRTY_OPAQUE && (this.getViewRootImpl() == null || !this.getViewRootImpl().mIgnoreDirtyState); this.mPrivateFlags = (privateFlags & ~View.PFLAG_DIRTY_MASK) | View.PFLAG_DRAWN; // draw the background, if needed if (!dirtyOpaque) { let background = this.mBackground; if (background != null) { let scrollX = this.mScrollX; let scrollY = this.mScrollY; if (this.mBackgroundSizeChanged) { background.setBounds(0, 0, this.mRight - this.mLeft, this.mBottom - this.mTop); this.mBackgroundSizeChanged = false; } if ((scrollX | scrollY) == 0) { background.draw(canvas); } else { canvas.translate(scrollX, scrollY); background.draw(canvas); canvas.translate(-scrollX, -scrollY); } } } // draw the content if (!dirtyOpaque) this.onDraw(canvas); // draw the children this.dispatchDraw(canvas); //draw decorations (scrollbars) this.onDrawScrollBars(canvas); if (this.mOverlay != null && !this.mOverlay.isEmpty()) { this.mOverlay.getOverlayView().dispatchDraw(canvas); } } protected onDraw(canvas:Canvas):void { } protected dispatchDraw(canvas:Canvas):void { } private drawAnimation(parent:ViewGroup, drawingTime:number, a:Animation, scalingRequired?:boolean):boolean { let invalidationTransform:Transformation; const flags:number = parent.mGroupFlags; const initialized:boolean = a.isInitialized(); if (!initialized) { a.initialize(this.mRight - this.mLeft, this.mBottom - this.mTop, parent.getWidth(), parent.getHeight()); a.initializeInvalidateRegion(0, 0, this.mRight - this.mLeft, this.mBottom - this.mTop); if (this.mAttachInfo != null) a.setListenerHandler(this.mAttachInfo.mHandler); this.onAnimationStart(); } const t:Transformation = parent.getChildTransformation(); let more:boolean = a.getTransformation(drawingTime, t, 1); //if (scalingRequired && this.mAttachInfo.mApplicationScale != 1) { // if (parent.mInvalidationTransformation == null) { // parent.mInvalidationTransformation = new Transformation(); // } // invalidationTransform = parent.mInvalidationTransformation; // a.getTransformation(drawingTime, invalidationTransform, 1); //} else { invalidationTransform = t; //} if (more) { if (!a.willChangeBounds()) { if ((flags & (ViewGroup.FLAG_OPTIMIZE_INVALIDATE | ViewGroup.FLAG_ANIMATION_DONE)) == ViewGroup.FLAG_OPTIMIZE_INVALIDATE) { parent.mGroupFlags |= ViewGroup.FLAG_INVALIDATE_REQUIRED; } else if ((flags & ViewGroup.FLAG_INVALIDATE_REQUIRED) == 0) { // The child need to draw an animation, potentially offscreen, so // make sure we do not cancel invalidate requests parent.mPrivateFlags |= View.PFLAG_DRAW_ANIMATION; parent.invalidate(this.mLeft, this.mTop, this.mRight, this.mBottom); } } else { if (parent.mInvalidateRegion == null) { parent.mInvalidateRegion = new RectF(); } const region:RectF = parent.mInvalidateRegion; a.getInvalidateRegion(0, 0, this.mRight - this.mLeft, this.mBottom - this.mTop, region, invalidationTransform); // The child need to draw an animation, potentially offscreen, so // make sure we do not cancel invalidate requests parent.mPrivateFlags |= View.PFLAG_DRAW_ANIMATION; const left:number = this.mLeft + Math.floor(region.left); const top:number = this.mTop + Math.floor(region.top); parent.invalidate(left, top, left + Math.floor((region.width() + .5)), top + Math.floor((region.height() + .5))); } } return more; } onDrawScrollBars(canvas:Canvas) { // scrollbars are drawn only when the animation is running const cache = this.mScrollCache; if (cache != null) { let state = cache.state; if (state == ScrollabilityCache.OFF) { return; } let invalidate = false; if (state == ScrollabilityCache.FADING) { // We're fading -- get our fade interpolation //if (cache.interpolatorValues == null) { // cache.interpolatorValues = androidui.util.ArrayCreator.newNumberArray(1); //} //let values = cache.interpolatorValues; // Stops the animation if we're done //if (cache.scrollBarInterpolator.timeToValues(values) == // Interpolator.Result.FREEZE_END) { // cache.state = ScrollabilityCache.OFF; //} else { // cache.scrollBar.setAlpha(Math.round(values[0])); //} cache._computeAlphaToScrollBar(); // This will make the scroll bars inval themselves after // drawing. We only want this when we're fading so that // we prevent excessive redraws invalidate = true; } else { // We're just on -- but we may have been fading before so // reset alpha cache.scrollBar.setAlpha(255); } const viewFlags = this.mViewFlags; const drawHorizontalScrollBar = (viewFlags & View.SCROLLBARS_HORIZONTAL) == View.SCROLLBARS_HORIZONTAL; const drawVerticalScrollBar = (viewFlags & View.SCROLLBARS_VERTICAL) == View.SCROLLBARS_VERTICAL && !this.isVerticalScrollBarHidden(); if (drawVerticalScrollBar || drawHorizontalScrollBar) { const width = this.mRight - this.mLeft; const height = this.mBottom - this.mTop; const scrollBar = cache.scrollBar; const scrollX = this.mScrollX; const scrollY = this.mScrollY; const inside = true;//(viewFlags & View.SCROLLBARS_OUTSIDE_MASK) == 0 ? ~0 : 0; let left; let top; let right; let bottom; if (drawHorizontalScrollBar) { let size = scrollBar.getSize(false); if (size <= 0) { size = cache.scrollBarSize; } scrollBar.setParameters(this.computeHorizontalScrollRange(), this.computeHorizontalScrollOffset(), this.computeHorizontalScrollExtent(), false); const verticalScrollBarGap = drawVerticalScrollBar ? this.getVerticalScrollbarWidth() : 0; top = scrollY + height - size;// - (this.mUserPaddingBottom & inside); left = scrollX + (this.mPaddingLeft);// & inside); right = scrollX + width - /*(this.mUserPaddingRight & inside)*/ - verticalScrollBarGap; bottom = top + size; this.onDrawHorizontalScrollBar(canvas, scrollBar, left, top, right, bottom); if (invalidate) { this.invalidate(left, top, right, bottom); } } if (drawVerticalScrollBar) { let size = scrollBar.getSize(true); if (size <= 0) { size = cache.scrollBarSize; } scrollBar.setParameters(this.computeVerticalScrollRange(), this.computeVerticalScrollOffset(), this.computeVerticalScrollExtent(), true); //let verticalScrollbarPosition = this.mVerticalScrollbarPosition; //if (verticalScrollbarPosition == View.SCROLLBAR_POSITION_DEFAULT) { // verticalScrollbarPosition = isLayoutRtl() ? // View.SCROLLBAR_POSITION_LEFT : View.SCROLLBAR_POSITION_RIGHT; //} //switch (verticalScrollbarPosition) { // default: // case View.SCROLLBAR_POSITION_RIGHT: // left = scrollX + width - size - (this.mUserPaddingRight & inside); // break; // case View.SCROLLBAR_POSITION_LEFT: // left = scrollX + (mUserPaddingLeft & inside); // break; //} left = scrollX + width - size;// - (this.mUserPaddingRight & inside); top = scrollY + (this.mPaddingTop);// & inside); right = left + size; bottom = scrollY + height;// - (this.mUserPaddingBottom & inside); this.onDrawVerticalScrollBar(canvas, scrollBar, left, top, right, bottom); if (invalidate) { this.invalidate(left, top, right, bottom); } } } } } isVerticalScrollBarHidden():boolean { return false; } onDrawHorizontalScrollBar(canvas:Canvas, scrollBar:Drawable, l:number, t:number, r:number, b:number) { scrollBar.setBounds(l, t, r, b); scrollBar.draw(canvas); } onDrawVerticalScrollBar(canvas:Canvas, scrollBar:Drawable, l:number, t:number, r:number, b:number) { scrollBar.setBounds(l, t, r, b); scrollBar.draw(canvas); } isHardwareAccelerated():boolean{ return false;//Hardware Accelerate not impl (may use webgl accelerate later?) } setDrawingCacheEnabled(enabled:boolean) { this.mCachingFailed = false; this.setFlags(enabled ? View.DRAWING_CACHE_ENABLED : 0, View.DRAWING_CACHE_ENABLED); } isDrawingCacheEnabled():boolean { return (this.mViewFlags & View.DRAWING_CACHE_ENABLED) == View.DRAWING_CACHE_ENABLED; } /** * <p>Returns the bitmap in which this view drawing is cached. The returned bitmap * is null when caching is disabled. If caching is enabled and the cache is not ready, * this method will create it. Calling {@link #draw(android.graphics.Canvas)} will not * draw from the cache when the cache is enabled. To benefit from the cache, you must * request the drawing cache by calling this method and draw it on screen if the * returned bitmap is not null.</p> * * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, * this method will create a bitmap of the same size as this view. Because this bitmap * will be drawn scaled by the parent ViewGroup, the result on screen might show * scaling artifacts. To avoid such artifacts, you should call this method by setting * the auto scaling to true. Doing so, however, will generate a bitmap of a different * size than the view. This implies that your application must be able to handle this * size.</p> * * @param autoScale Indicates whether the generated bitmap should be scaled based on * the current density of the screen when the application is in compatibility * mode. * * @return A bitmap representing this view or null if cache is disabled. * * @see #setDrawingCacheEnabled(boolean) * @see #isDrawingCacheEnabled() * @see #buildDrawingCache(boolean) * @see #destroyDrawingCache() */ getDrawingCache(autoScale=false):Canvas { if ((this.mViewFlags & View.WILL_NOT_CACHE_DRAWING) == View.WILL_NOT_CACHE_DRAWING) { return null; } if ((this.mViewFlags & View.DRAWING_CACHE_ENABLED) == View.DRAWING_CACHE_ENABLED) { this.buildDrawingCache(autoScale); } return this.mUnscaledDrawingCache; } /** * Setting a solid background color for the drawing cache's bitmaps will improve * performance and memory usage. Note, though that this should only be used if this * view will always be drawn on top of a solid color. * * @param color The background color to use for the drawing cache's bitmap * * @see #setDrawingCacheEnabled(boolean) * @see #buildDrawingCache() * @see #getDrawingCache() */ setDrawingCacheBackgroundColor(color:number):void { if (color != this.mDrawingCacheBackgroundColor) { this.mDrawingCacheBackgroundColor = color; this.mPrivateFlags &= ~View.PFLAG_DRAWING_CACHE_VALID; } } /** * @see #setDrawingCacheBackgroundColor(int) * * @return The background color to used for the drawing cache's bitmap */ getDrawingCacheBackgroundColor():number { return this.mDrawingCacheBackgroundColor; } destroyDrawingCache() { if (this.mUnscaledDrawingCache != null) { this.mUnscaledDrawingCache.recycle(); this.mUnscaledDrawingCache = null; } } /** * <p>Forces the drawing cache to be built if the drawing cache is invalid.</p> * * <p>If you call {@link #buildDrawingCache()} manually without calling * {@link #setDrawingCacheEnabled(boolean) setDrawingCacheEnabled(true)}, you * should cleanup the cache by calling {@link #destroyDrawingCache()} afterwards.</p> * * <p>Note about auto scaling in compatibility mode: When auto scaling is not enabled, * this method will create a bitmap of the same size as this view. Because this bitmap * will be drawn scaled by the parent ViewGroup, the result on screen might show * scaling artifacts. To avoid such artifacts, you should call this method by setting * the auto scaling to true. Doing so, however, will generate a bitmap of a different * size than the view. This implies that your application must be able to handle this * size.</p> * * <p>You should avoid calling this method when hardware acceleration is enabled. If * you do not need the drawing cache bitmap, calling this method will increase memory * usage and cause the view to be rendered in software once, thus negatively impacting * performance.</p> * * @see #getDrawingCache() * @see #destroyDrawingCache() */ buildDrawingCache(autoScale=false):void { if ((this.mPrivateFlags & View.PFLAG_DRAWING_CACHE_VALID) == 0 || this.mUnscaledDrawingCache == null){ this.mCachingFailed = false; let width:number = this.mRight - this.mLeft; let height:number = this.mBottom - this.mTop; const attachInfo:View.AttachInfo = this.mAttachInfo; const drawingCacheBackgroundColor:number = this.mDrawingCacheBackgroundColor; const opaque:boolean = drawingCacheBackgroundColor != 0 || this.isOpaque(); //const use32BitCache:boolean = true; const projectedBitmapSize:number = width * height * 4;//(opaque && !use32BitCache ? 2 : 4); const drawingCacheSize:number = ViewConfiguration.get().getScaledMaximumDrawingCacheSize(); if (width <= 0 || height <= 0 || projectedBitmapSize > drawingCacheSize) { if (width > 0 && height > 0) { Log.w(View.VIEW_LOG_TAG, "View too large to fit into drawing cache, needs " + projectedBitmapSize + " bytes, only " + drawingCacheSize + " available"); } this.destroyDrawingCache(); this.mCachingFailed = true; return; } if(this.mUnscaledDrawingCache && (this.mUnscaledDrawingCache.getWidth()!==width || this.mUnscaledDrawingCache.getHeight()!==height)){ this.mUnscaledDrawingCache.recycle(); this.mUnscaledDrawingCache = null; } if(this.mUnscaledDrawingCache){ this.mUnscaledDrawingCache.clearColor(); } else{ this.mUnscaledDrawingCache = new Canvas(width, height); } const canvas = this.mUnscaledDrawingCache; this.computeScroll(); const restoreCount:number = canvas.save(); canvas.translate(-this.mScrollX, -this.mScrollY); this.mPrivateFlags |= View.PFLAG_DRAWN; if (this.mAttachInfo == null || /*!this.mAttachInfo.mHardwareAccelerated ||*/ this.mLayerType != View.LAYER_TYPE_NONE) { this.mPrivateFlags |= View.PFLAG_DRAWING_CACHE_VALID; } // Fast path for layouts with no backgrounds if ((this.mPrivateFlags & View.PFLAG_SKIP_DRAW) == View.PFLAG_SKIP_DRAW) { this.mPrivateFlags &= ~View.PFLAG_DIRTY_MASK; this.dispatchDraw(canvas); if (this.mOverlay != null && !this.mOverlay.isEmpty()) { this.mOverlay.getOverlayView().draw(canvas); } } else { this.draw(canvas); } canvas.restoreToCount(restoreCount); } } setWillNotDraw(willNotDraw:boolean) { this.setFlags(willNotDraw ? View.WILL_NOT_DRAW : 0, View.DRAW_MASK); } willNotDraw():boolean { return (this.mViewFlags & View.DRAW_MASK) == View.WILL_NOT_DRAW; } setWillNotCacheDrawing(willNotCacheDrawing:boolean) { this.setFlags(willNotCacheDrawing ? View.WILL_NOT_CACHE_DRAWING : 0, View.WILL_NOT_CACHE_DRAWING); } willNotCacheDrawing():boolean { return (this.mViewFlags & View.WILL_NOT_CACHE_DRAWING) == View.WILL_NOT_CACHE_DRAWING; } drawableSizeChange(who : Drawable):void{ if(who === this.mBackground) { let w:number = who.getIntrinsicWidth(); if (w < 0) w = this.mBackgroundWidth; let h:number = who.getIntrinsicHeight(); if (h < 0) h = this.mBackgroundHeight; if (w != this.mBackgroundWidth || h != this.mBackgroundHeight) { let padding = new Rect(); //this.resetResolvedDrawables(); //background.setLayoutDirection(getLayoutDirection()); if (who.getPadding(padding)) { //this.resetResolvedPadding(); this.setPadding(padding.left, padding.top, padding.right, padding.bottom); } this.mBackgroundWidth = w; this.mBackgroundHeight = h; this.requestLayout(); } }else if(this.verifyDrawable(who)) { //common case, child View should request Layout when drawable size change this.requestLayout(); } } invalidateDrawable(drawable:Drawable):void{ if (this.verifyDrawable(drawable)) { const dirty = drawable.getBounds(); const scrollX = this.mScrollX; const scrollY = this.mScrollY; this.invalidate(dirty.left + scrollX, dirty.top + scrollY, dirty.right + scrollX, dirty.bottom + scrollY); } } scheduleDrawable(who:Drawable, what:Runnable, when:number):void{ if (this.verifyDrawable(who) && what != null) { const delay = when - SystemClock.uptimeMillis(); if (this.mAttachInfo != null) { this.mAttachInfo.mHandler.postAtTime(what, who, when); } else { ViewRootImpl.getRunQueue().postDelayed(what, delay); } } } unscheduleDrawable(who:Drawable, what?:Runnable){ if (this.verifyDrawable(who) && what != null) { if (this.mAttachInfo != null) { this.mAttachInfo.mHandler.removeCallbacks(what, who); } else { ViewRootImpl.getRunQueue().removeCallbacks(what); } }else if(what===null){ if (this.mAttachInfo != null && who != null) { this.mAttachInfo.mHandler.removeCallbacksAndMessages(who); } } } protected verifyDrawable(who:Drawable):boolean { return who == this.mBackground; } protected drawableStateChanged() { this.getDrawableState();//androidui: fire may state change to stateAttrList let d = this.mBackground; if (d != null && d.isStateful()) { d.setState(this.getDrawableState()); } } resolveDrawables(){ //do nothing } refreshDrawableState() { this.mPrivateFlags |= View.PFLAG_DRAWABLE_STATE_DIRTY; this.drawableStateChanged(); let parent = this.mParent; if (parent != null) { parent.childDrawableStateChanged(this); } } getDrawableState():Array<number> { if ((this.mDrawableState != null) && ((this.mPrivateFlags & View.PFLAG_DRAWABLE_STATE_DIRTY) == 0)) { return this.mDrawableState; } else { let oldDrawableState = this.mDrawableState; this.mDrawableState = this.onCreateDrawableState(0); this.mPrivateFlags &= ~View.PFLAG_DRAWABLE_STATE_DIRTY; this._fireStateChangeToAttribute(oldDrawableState, this.mDrawableState); return this.mDrawableState; } } protected onCreateDrawableState(extraSpace:number):Array<number> { if ((this.mViewFlags & View.DUPLICATE_PARENT_STATE) == View.DUPLICATE_PARENT_STATE && this.mParent instanceof View) { return (<View><any>this.mParent).onCreateDrawableState(extraSpace); } let drawableState:Array<number>; let privateFlags = this.mPrivateFlags; let viewStateIndex = 0; if ((privateFlags & View.PFLAG_PRESSED) != 0) viewStateIndex |= View.VIEW_STATE_PRESSED; if ((this.mViewFlags & View.ENABLED_MASK) == View.ENABLED) viewStateIndex |= View.VIEW_STATE_ENABLED; if (this.isFocused()) viewStateIndex |= View.VIEW_STATE_FOCUSED; if ((privateFlags & View.PFLAG_SELECTED) != 0) viewStateIndex |= View.VIEW_STATE_SELECTED; if (this.hasWindowFocus()) viewStateIndex |= View.VIEW_STATE_WINDOW_FOCUSED; if ((privateFlags & View.PFLAG_ACTIVATED) != 0) viewStateIndex |= View.VIEW_STATE_ACTIVATED; // if (mAttachInfo != null && mAttachInfo.mHardwareAccelerationRequested && // HardwareRenderer.isAvailable()) { // // This is set if HW acceleration is requested, even if the current // // process doesn't allow it. This is just to allow app preview // // windows to better match their app. // viewStateIndex |= VIEW_STATE_ACCELERATED; // } // if ((privateFlags & View.PFLAG_HOVERED) != 0) viewStateIndex |= View.VIEW_STATE_HOVERED; const privateFlags2 = this.mPrivateFlags2; //if ((privateFlags2 & View.PFLAG2_DRAG_CAN_ACCEPT) != 0) viewStateIndex |= View.VIEW_STATE_DRAG_CAN_ACCEPT;//no drag state //if ((privateFlags2 & View.PFLAG2_DRAG_HOVERED) != 0) viewStateIndex |= View.VIEW_STATE_DRAG_HOVERED; drawableState = View.VIEW_STATE_SETS[viewStateIndex]; //noinspection ConstantIfStatement //if (false) { // Log.i("View", "drawableStateIndex=" + viewStateIndex); // Log.i("View", toString() // + " pressed=" + ((privateFlags & PFLAG_PRESSED) != 0) // + " en=" + ((mViewFlags & ENABLED_MASK) == ENABLED) // + " fo=" + hasFocus() // + " sl=" + ((privateFlags & PFLAG_SELECTED) != 0) // + " wf=" + hasWindowFocus() // + ": " + Arrays.toString(drawableState)); //} if (extraSpace == 0) { return drawableState; } let fullState:Array<number>; if (drawableState != null) { fullState = androidui.util.ArrayCreator.newNumberArray(drawableState.length + extraSpace); System.arraycopy(drawableState, 0, fullState, 0, drawableState.length); } else { fullState = androidui.util.ArrayCreator.newNumberArray(extraSpace); } return fullState; } static mergeDrawableStates(baseState:Array<number>, additionalState:Array<number>) { const N = baseState.length; let i = N - 1; while (i >= 0 && !baseState[i]) {// 0 or null i--; } System.arraycopy(additionalState, 0, baseState, i + 1, additionalState.length); return baseState; } jumpDrawablesToCurrentState() { if (this.mBackground != null) { this.mBackground.jumpToCurrentState(); } } setBackgroundColor(color:number) { if (this.mBackground instanceof ColorDrawable) { (<ColorDrawable>this.mBackground.mutate()).setColor(color); this.computeOpaqueFlags(); //this.mBackgroundResource = 0; } else { this.setBackground(new ColorDrawable(color)); } } setBackground(background:Drawable) { this.setBackgroundDrawable(background); } getBackground():Drawable { return this.mBackground; } setBackgroundDrawable(background:Drawable) { this.computeOpaqueFlags(); if (background == this.mBackground) { return; } let requestLayout = false; //this.mBackgroundResource = 0; /* * Regardless of whether we're setting a new background or not, we want * to clear the previous drawable. */ if (this.mBackground != null) { this.mBackground.setCallback(null); this.unscheduleDrawable(this.mBackground); } if (background != null) { let padding = new Rect(); //this.resetResolvedDrawables(); //background.setLayoutDirection(getLayoutDirection()); if (background.getPadding(padding)) { //this.resetResolvedPadding(); this.setPadding(padding.left, padding.top, padding.right, padding.bottom); } // Compare the minimum sizes of the old Drawable and the new. If there isn't an old or // if it has a different minimum size, we should layout again if (this.mBackground == null || this.mBackground.getMinimumHeight() != background.getMinimumHeight() || this.mBackground.getMinimumWidth() != background.getMinimumWidth()) { requestLayout = true; } background.setCallback(this); if (background.isStateful()) { background.setState(this.getDrawableState()); } background.setVisible(this.getVisibility() == View.VISIBLE, false); this.mBackground = background; this.mBackgroundWidth = background.getIntrinsicWidth(); this.mBackgroundHeight = background.getIntrinsicHeight(); if ((this.mPrivateFlags & View.PFLAG_SKIP_DRAW) != 0) { this.mPrivateFlags &= ~View.PFLAG_SKIP_DRAW; this.mPrivateFlags |= View.PFLAG_ONLY_DRAWS_BACKGROUND; requestLayout = true; } } else { /* Remove the background */ this.mBackground = null; this.mBackgroundWidth = this.mBackgroundHeight = -1; if ((this.mPrivateFlags & View.PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { /* * This view ONLY drew the background before and we're removing * the background, so now it won't draw anything * (hence we SKIP_DRAW) */ this.mPrivateFlags &= ~View.PFLAG_ONLY_DRAWS_BACKGROUND; this.mPrivateFlags |= View.PFLAG_SKIP_DRAW; } /* * When the background is set, we try to apply its padding to this * View. When the background is removed, we don't touch this View's * padding. This is noted in the Javadocs. Hence, we don't need to * requestLayout(), the invalidate() below is sufficient. */ // The old background's minimum size could have affected this // View's layout, so let's requestLayout requestLayout = true; } this.computeOpaqueFlags(); if (requestLayout) { this.requestLayout(); } this.mBackgroundSizeChanged = true; this.mShadowDrawable = null; this.invalidate(true); } protected computeHorizontalScrollRange():number { return this.getWidth(); } protected computeHorizontalScrollOffset():number { return this.mScrollX; } protected computeHorizontalScrollExtent():number { return this.getWidth(); } protected computeVerticalScrollRange():number { return this.getHeight(); } protected computeVerticalScrollOffset():number { return this.mScrollY; } protected computeVerticalScrollExtent():number { return this.getHeight(); } canScrollHorizontally(direction:number):boolean { const offset = this.computeHorizontalScrollOffset(); const range = this.computeHorizontalScrollRange() - this.computeHorizontalScrollExtent(); if (range == 0) return false; if (direction < 0) { return offset > 0; } else { return offset < range - 1; } } canScrollVertically(direction:number):boolean { const offset = this.computeVerticalScrollOffset(); const range = this.computeVerticalScrollRange() - this.computeVerticalScrollExtent(); if (range == 0) return false; if (direction < 0) { return offset > 0; } else { return offset < range - 1; } } protected overScrollBy(deltaX:number, deltaY:number, scrollX:number, scrollY:number, scrollRangeX:number, scrollRangeY:number, maxOverScrollX:number, maxOverScrollY:number, isTouchEvent:boolean):boolean { const overScrollMode = this.mOverScrollMode; const canScrollHorizontal = this.computeHorizontalScrollRange() > this.computeHorizontalScrollExtent(); const canScrollVertical = this.computeVerticalScrollRange() > this.computeVerticalScrollExtent(); const overScrollHorizontal = overScrollMode == View.OVER_SCROLL_ALWAYS || (overScrollMode == View.OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal); const overScrollVertical = overScrollMode == View.OVER_SCROLL_ALWAYS || (overScrollMode == View.OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical); //over drag if(isTouchEvent) { if ((deltaX < 0 && scrollX <= 0) || (deltaX > 0 && scrollX >= scrollRangeX)) { deltaX /= 2; } if ((deltaY < 0 && scrollY <= 0) || (deltaY > 0 && scrollY >= scrollRangeY)) { deltaY /= 2; } } let newScrollX = scrollX + deltaX; if (!overScrollHorizontal) { maxOverScrollX = 0; } let newScrollY = scrollY + deltaY; if (!overScrollVertical) { maxOverScrollY = 0; } // Clamp values if at the limits and record const left = -maxOverScrollX; const right = maxOverScrollX + scrollRangeX; const top = -maxOverScrollY; const bottom = maxOverScrollY + scrollRangeY; let clampedX = false; if (newScrollX > right) { newScrollX = right; clampedX = true; } else if (newScrollX < left) { newScrollX = left; clampedX = true; } let clampedY = false; if (newScrollY > bottom) { newScrollY = bottom; clampedY = true; } else if (newScrollY < top) { newScrollY = top; clampedY = true; } this.onOverScrolled(newScrollX, newScrollY, clampedX, clampedY); return clampedX || clampedY; } protected onOverScrolled(scrollX:number, scrollY:number, clampedX:boolean, clampedY:boolean) { // Intentionally empty. } getOverScrollMode() { return this.mOverScrollMode; } setOverScrollMode(overScrollMode:number) { if (overScrollMode != View.OVER_SCROLL_ALWAYS && overScrollMode != View.OVER_SCROLL_IF_CONTENT_SCROLLS && overScrollMode != View.OVER_SCROLL_NEVER) { throw new Error("Invalid overscroll mode " + overScrollMode); } this.mOverScrollMode = overScrollMode; } getVerticalScrollFactor():number { if (this.mVerticalScrollFactor == 0) { this.mVerticalScrollFactor = Resources.getDisplayMetrics().density * 1; } return this.mVerticalScrollFactor; } getHorizontalScrollFactor():number { // TODO: Should use something else. return this.getVerticalScrollFactor(); } computeScroll() { } scrollTo(x:number, y:number) { if (this.mScrollX != x || this.mScrollY != y) { let oldX = this.mScrollX; let oldY = this.mScrollY; this.mScrollX = x; this.mScrollY = y; this.invalidateParentCaches(); this.onScrollChanged(this.mScrollX, this.mScrollY, oldX, oldY); if (!this.awakenScrollBars()) { this.postInvalidateOnAnimation(); } } } scrollBy(x:number, y:number) { this.scrollTo(this.mScrollX + x, this.mScrollY + y); } private initialAwakenScrollBars() { return this.mScrollCache != null && this.awakenScrollBars(this.mScrollCache.scrollBarDefaultDelayBeforeFade * 4, true); } awakenScrollBars(startDelay?:number, invalidate=true):boolean{ const scrollCache = this.mScrollCache; if(scrollCache==null) return false; startDelay = startDelay || scrollCache.scrollBarDefaultDelayBeforeFade if (scrollCache == null || !scrollCache.fadeScrollBars) { return false; } if (scrollCache.scrollBar == null) { scrollCache.scrollBar = new ScrollBarDrawable(); } if (this.isHorizontalScrollBarEnabled() || this.isVerticalScrollBarEnabled()) { if (invalidate) { // Invalidate to show the scrollbars this.postInvalidateOnAnimation(); } if (scrollCache.state == ScrollabilityCache.OFF) { // FIX-ME: this is copied from WindowManagerService. // We should get this value from the system when it // is possible to do so. const KEY_REPEAT_FIRST_DELAY = 750; startDelay = Math.max(KEY_REPEAT_FIRST_DELAY, startDelay); } // Tell mScrollCache when we should start fading. This may // extend the fade start time if one was already scheduled let fadeStartTime = AnimationUtils.currentAnimationTimeMillis() + startDelay; scrollCache.fadeStartTime = fadeStartTime; scrollCache.state = ScrollabilityCache.ON; // Schedule our fader to run, unscheduling any old ones first if (this.mAttachInfo != null) { this.mAttachInfo.mHandler.removeCallbacks(scrollCache); this.mAttachInfo.mHandler.postAtTime(scrollCache, fadeStartTime); } return true; } return false; } getVerticalFadingEdgeLength():number{ return 0; } setVerticalFadingEdgeEnabled(enable:boolean){ //no need impl fade edge. use overscroll instead } setHorizontalFadingEdgeEnabled(enable:boolean){ //no need impl fade edge. use overscroll instead } setFadingEdgeLength(length:number){ //no need impl fade edge. use overscroll instead } getHorizontalFadingEdgeLength():number { //no need impl fade edge. use overscroll instead return 0; } getVerticalScrollbarWidth():number { let cache = this.mScrollCache; if (cache != null) { let scrollBar = cache.scrollBar; if (scrollBar != null) { let size = scrollBar.getSize(true); if (size <= 0) { size = cache.scrollBarSize; } return size; } return 0; } return 0; } getHorizontalScrollbarHeight():number { let cache = this.mScrollCache; if (cache != null) { let scrollBar = cache.scrollBar; if (scrollBar != null) { let size = scrollBar.getSize(false); if (size <= 0) { size = cache.scrollBarSize; } return size; } return 0; } return 0; } initializeScrollbars(a?:TypedArray):void { this.initScrollCache(); } initScrollCache() { if (this.mScrollCache == null) { this.mScrollCache = new ScrollabilityCache(this); } } private getScrollCache():ScrollabilityCache { this.initScrollCache(); return this.mScrollCache; } isHorizontalScrollBarEnabled():boolean { return (this.mViewFlags & View.SCROLLBARS_HORIZONTAL) == View.SCROLLBARS_HORIZONTAL; } setHorizontalScrollBarEnabled(horizontalScrollBarEnabled:boolean) { if (this.isHorizontalScrollBarEnabled() != horizontalScrollBarEnabled) { this.mViewFlags ^= View.SCROLLBARS_HORIZONTAL; this.computeOpaqueFlags(); //this.resolvePadding(); } } isVerticalScrollBarEnabled():boolean { return (this.mViewFlags & View.SCROLLBARS_VERTICAL) == View.SCROLLBARS_VERTICAL; } setVerticalScrollBarEnabled(verticalScrollBarEnabled:boolean) { if (this.isVerticalScrollBarEnabled() != verticalScrollBarEnabled) { this.mViewFlags ^= View.SCROLLBARS_VERTICAL; this.computeOpaqueFlags(); //this.resolvePadding(); } } setScrollbarFadingEnabled(fadeScrollbars:boolean) { this.initScrollCache(); const scrollabilityCache = this.mScrollCache; scrollabilityCache.fadeScrollBars = fadeScrollbars; if (fadeScrollbars) { scrollabilityCache.state = ScrollabilityCache.OFF; } else { scrollabilityCache.state = ScrollabilityCache.ON; } } setVerticalScrollbarPosition(position:number){ //scrollbar position not impl } setHorizontalScrollbarPosition(position:number){ //scrollbar position not impl } setScrollBarStyle(position:number){ //scrollbar style not impl } protected getTopFadingEdgeStrength():number{ return 0;//no fading edge } protected getBottomFadingEdgeStrength():number{ return 0;//no fading edge } protected getLeftFadingEdgeStrength():number{ return 0;//no fading edge } protected getRightFadingEdgeStrength():number{ return 0;//no fading edge } isScrollbarFadingEnabled():boolean { return this.mScrollCache != null && this.mScrollCache.fadeScrollBars; } getScrollBarDefaultDelayBeforeFade():number { return this.mScrollCache == null ? ViewConfiguration.getScrollDefaultDelay() : this.mScrollCache.scrollBarDefaultDelayBeforeFade; } setScrollBarDefaultDelayBeforeFade(scrollBarDefaultDelayBeforeFade:number) { this.getScrollCache().scrollBarDefaultDelayBeforeFade = scrollBarDefaultDelayBeforeFade; } getScrollBarFadeDuration():number { return this.mScrollCache == null ? ViewConfiguration.getScrollBarFadeDuration() : this.mScrollCache.scrollBarFadeDuration; } setScrollBarFadeDuration(scrollBarFadeDuration:number) { this.getScrollCache().scrollBarFadeDuration = scrollBarFadeDuration; } getScrollBarSize():number { return this.mScrollCache == null ? ViewConfiguration.get().getScaledScrollBarSize() : this.mScrollCache.scrollBarSize; } setScrollBarSize(scrollBarSize:number) { this.getScrollCache().scrollBarSize = scrollBarSize; } hasOpaqueScrollbars():boolean{ return true; } /* * Caller is responsible for calling requestLayout if necessary. * (This allows addViewInLayout to not request a new layout.) */ assignParent(parent:ViewParent) { if (this.mParent == null) { this.mParent = parent; } else if (parent == null) { this.mParent = null; } else { throw new Error("view " + this + " being added, but" + " it already has a parent"); } } protected onFinishInflate():void { } /** * @hide */ dispatchStartTemporaryDetach():void { //this.clearDisplayList(); this.onStartTemporaryDetach(); } /** * This is called when a container is going to temporarily detach a child, with * {@link ViewGroup#detachViewFromParent(View) ViewGroup.detachViewFromParent}. * It will either be followed by {@link #onFinishTemporaryDetach()} or * {@link #onDetachedFromWindow()} when the container is done. */ onStartTemporaryDetach():void { this.removeUnsetPressCallback(); this.mPrivateFlags |= View.PFLAG_CANCEL_NEXT_UP_EVENT; } /** * @hide */ dispatchFinishTemporaryDetach():void { this.onFinishTemporaryDetach(); } /** * Called after {@link #onStartTemporaryDetach} when the container is done * changing the view. */ onFinishTemporaryDetach():void { } /** * Called when the window containing this view gains or loses window focus. * ViewGroups should override to route to their children. * * @param hasFocus True if the window containing this view now has focus, * false otherwise. */ dispatchWindowFocusChanged(hasFocus:boolean):void { this.onWindowFocusChanged(hasFocus); } /** * Called when the window containing this view gains or loses focus. Note * that this is separate from view focus: to receive key events, both * your view and its window must have focus. If a window is displayed * on top of yours that takes input focus, then your own window will lose * focus but the view focus will remain unchanged. * * @param hasWindowFocus True if the window containing this view now has * focus, false otherwise. */ onWindowFocusChanged(hasWindowFocus:boolean):void { //let imm:InputMethodManager = InputMethodManager.peekInstance(); if (!hasWindowFocus) { if (this.isPressed()) { this.setPressed(false); } //if (imm != null && (this.mPrivateFlags & View.PFLAG_FOCUSED) != 0) { // imm.focusOut(this); //} this.removeLongPressCallback(); this.removeTapCallback(); this.onFocusLost(); } //else if (imm != null && (this.mPrivateFlags & View.PFLAG_FOCUSED) != 0) { // imm.focusIn(this); //} this.refreshDrawableState(); } /** * Returns true if this view is in a window that currently has window focus. * Note that this is not the same as the view itself having focus. * * @return True if this view is in a window that currently has window focus. */ hasWindowFocus():boolean { return this.mAttachInfo != null && this.mAttachInfo.mHasWindowFocus; } /** * @return The number of times this view has been attached to a window */ getWindowAttachCount():number { return this.mWindowAttachCount; } /** * Returns true if this view is currently attached to a window. */ isAttachedToWindow():boolean { return this.mAttachInfo != null; } dispatchAttachedToWindow(info: View.AttachInfo, visibility:number) { //System.out.println("Attached! " + this); this.mAttachInfo = info; if (this.mOverlay != null) { this.mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility); } this.mWindowAttachCount++; // We will need to evaluate the drawable state at least once. this.mPrivateFlags |= View.PFLAG_DRAWABLE_STATE_DIRTY; if (this.mFloatingTreeObserver != null) { info.mViewRootImpl.mTreeObserver.merge(this.mFloatingTreeObserver); this.mFloatingTreeObserver = null; } if ((this.mPrivateFlags&View.PFLAG_SCROLL_CONTAINER) != 0) { this.mAttachInfo.mScrollContainers.add(this); this.mPrivateFlags |= View.PFLAG_SCROLL_CONTAINER_ADDED; } //performCollectViewAttributes(mAttachInfo, visibility); this.onAttachedToWindow(); //AndroidUI: force show debug layout if the view depend on debug layout. if(this.dependOnDebugLayout()){ this.getContext().androidUI.viewAttachedDependOnDebugLayout(this); } let li = this.mListenerInfo; let listeners = li != null ? li.mOnAttachStateChangeListeners : null; if (listeners != null && listeners.size() > 0) { // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to // perform the dispatching. The iterator is a safe guard against listeners that // could mutate the list by calling the various add/remove methods. This prevents // the array from being modified while we iterate it. for (let listener of listeners) { listener.onViewAttachedToWindow(this); } } let vis = info.mWindowVisibility; if (vis != View.GONE) { this.onWindowVisibilityChanged(vis); } if ((this.mPrivateFlags&View.PFLAG_DRAWABLE_STATE_DIRTY) != 0) { // If nobody has evaluated the drawable state yet, then do it now. this.refreshDrawableState(); } //needGlobalAttributesUpdate(false); } protected onAttachedToWindow():void { //if ((this.mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) != 0) { // this.mParent.requestTransparentRegion(this); //} if ((this.mPrivateFlags & View.PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH) != 0) { this.initialAwakenScrollBars(); this.mPrivateFlags &= ~View.PFLAG_AWAKEN_SCROLL_BARS_ON_ATTACH; } this.mPrivateFlags3 &= ~View.PFLAG3_IS_LAID_OUT; this.jumpDrawablesToCurrentState(); } dispatchDetachedFromWindow():void { let info = this.mAttachInfo; if (info != null) { let vis = info.mWindowVisibility; if (vis != View.GONE) { this.onWindowVisibilityChanged(View.GONE); } } this.onDetachedFromWindow(); //AndroidUI: notity debug layout the view depend on debug layout has detached. if(this.dependOnDebugLayout()){ this.getContext().androidUI.viewDetachedDependOnDebugLayout(this); } let li = this.mListenerInfo; let listeners = li != null ? li.mOnAttachStateChangeListeners : null; if (listeners != null && listeners.size() > 0) { // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to // perform the dispatching. The iterator is a safe guard against listeners that // could mutate the list by calling the various add/remove methods. This prevents // the array from being modified while we iterate it. for (let listener of listeners) { listener.onViewDetachedFromWindow(this); } } if ((this.mPrivateFlags & View.PFLAG_SCROLL_CONTAINER_ADDED) != 0) { this.mAttachInfo.mScrollContainers.delete(this); this.mPrivateFlags &= ~View.PFLAG_SCROLL_CONTAINER_ADDED; } this.mAttachInfo = null; if (this.mOverlay != null) { this.mOverlay.getOverlayView().dispatchDetachedFromWindow(); } } protected onDetachedFromWindow():void { this.mPrivateFlags &= ~View.PFLAG_CANCEL_NEXT_UP_EVENT; this.mPrivateFlags3 &= ~View.PFLAG3_IS_LAID_OUT; this.removeUnsetPressCallback(); this.removeLongPressCallback(); this.removePerformClickCallback(); this.destroyDrawingCache(); //this.destroyLayer(false); this.cleanupDraw(); this.mCurrentAnimation = null; } cleanupDraw():void { if (this.mAttachInfo != null) { this.mAttachInfo.mViewRootImpl.cancelInvalidate(this); } } isInEditMode():boolean { return false;//always false } debug(depth=0){ //androidui impl: console.dir(this.bindElement); } toString():String{ return this.tagName(); } getRootView():View { if (this.mAttachInfo != null) { let v = this.mAttachInfo.mRootView; if (v != null) { return v; } } let parent = this; while (parent.mParent != null && parent.mParent instanceof View) { parent = <any>parent.mParent; } return parent; } findViewById(id:string):View{ if(!id) return null; return this.findViewTraversal(id); } findViewWithTag(tag:any):View{ if(!tag) return null; return this.findViewWithTagTraversal(tag); } protected findViewTraversal(id:string):View { if (id == this.mID) { return this; } return null; } protected findViewWithTagTraversal(tag:any):View{ if (tag != null && tag === this.mTag) { return this; } return null; } findViewByPredicate(predicate:View.Predicate<View>) { return this.findViewByPredicateTraversal(predicate, null); } protected findViewByPredicateTraversal(predicate:View.Predicate<View>, childToSkip:View):View { if (predicate.apply(this)) { return this; } return null; } findViewByPredicateInsideOut(start:View, predicate:View.Predicate<View>) { let childToSkip = null; for (;;) { let view = start.findViewByPredicateTraversal(predicate, childToSkip); if (view != null || start == this) { return view; } let parent = start.getParent(); if (parent == null || !(parent instanceof View)) { return null; } childToSkip = start; start = <View><any>parent; } } setId(id:string) { this.mID = id; } getId():string { return this.mID; } getTag():any { return this.mTag; } setTag(tag:any):void { this.mTag = tag; } setIsRootNamespace(isRoot:boolean) { if (isRoot) { this.mPrivateFlags |= View.PFLAG_IS_ROOT_NAMESPACE; } else { this.mPrivateFlags &= ~View.PFLAG_IS_ROOT_NAMESPACE; } } isRootNamespace():boolean { return (this.mPrivateFlags&View.PFLAG_IS_ROOT_NAMESPACE) != 0; } getResources():Resources { let context = this.getContext(); if(context!=null){ return context.getResources(); } return Resources.getSystem(); } static inflate(context:Context, xml:HTMLElement|string, root?:ViewGroup):View{ return LayoutInflater.from(context).inflate(xml, root); } //bind Element show the layout and extra info bindElement: HTMLElement; private _AttrObserver:MutationObserver; private _stateAttrList = new androidui.attr.StateAttrList(this); private _attrBinder = new AttrBinder(this); private static ViewClassAttrBinderClazzMap = new Map<java.lang.Class, AttrBinder.ClassBinderMap>(); static AndroidViewProperty = 'AndroidView'; private static _AttrObserverCallBack(arr: MutationRecord[], observer: MutationObserver) { arr.forEach((record)=>{ let target = <Element>record.target; let androidView:View = target[View.AndroidViewProperty]; if(!androidView) return; let attrName = record.attributeName; let newValue = target.getAttribute(attrName); let oldValue = record.oldValue; if(newValue === oldValue) return; androidView.onBindElementAttributeChanged(attrName, record.oldValue, newValue); }); } protected initBindElement(bindElement?:HTMLElement):void{ if(this.bindElement){ this.bindElement[View.AndroidViewProperty] = null; } this.bindElement = bindElement || document.createElement(this.tagName()); this.bindElement.style.position = 'absolute'; let oldBindView:View = this.bindElement[View.AndroidViewProperty]; if(oldBindView){ if(oldBindView._AttrObserver) oldBindView._AttrObserver.disconnect(); } this.bindElement[View.AndroidViewProperty]=this; this._initAttrObserver(); } protected initBindAttr():void { let classAttrBinder = View.ViewClassAttrBinderClazzMap.get(this.getClass()); if (!classAttrBinder) { classAttrBinder = this.createClassAttrBinder(); View.ViewClassAttrBinderClazzMap.set(this.getClass(), classAttrBinder); } this._attrBinder.setClassAttrBind(classAttrBinder); } /** * AndroidUIX add: * override this method to create the attr binder for current view class. * this method will call once when the first view instance of the class create, later will use cache. * Should call super.createClassAttrBinder() when override, so code will be like: * return super.createClassAttrBinder().set('xxx', {setter(v, value){}, getter(v){}}); * * AttrBinder design for: * 1. bind the xml's attr to view * 2. stash stated attr value when change state_xxx attrs value in xml * @returns created class attr binder */ protected createClassAttrBinder(): AttrBinder.ClassBinderMap { const classAttrBinder = new AttrBinder.ClassBinderMap() .set('background', { setter(v: View, value: any, attrBinder:AttrBinder) { v.setBackground(attrBinder.parseDrawable(value)); }, getter(v: View) { return v.mBackground; }, }).set('padding', { setter(v: View, value: any, attrBinder:AttrBinder) { if (value == null) value = 0; let [top, right, bottom, left] = attrBinder.parsePaddingMarginTRBL(value); v.setPadding(left, top, right, bottom); }, getter(v: View) { return v.mPaddingTop + ' ' + v.mPaddingRight + ' ' + v.mPaddingBottom + ' ' + v.mPaddingLeft; }, }).set('paddingLeft', { setter(v: View, value: any, attrBinder:AttrBinder) { if (value == null) value = 0; v.setPadding(attrBinder.parseDimension(value, 0), v.mPaddingTop, v.mPaddingRight, v.mPaddingBottom); }, getter(v: View) { return v.mPaddingLeft; }, }).set('paddingTop', { setter(v: View, value: any, attrBinder:AttrBinder) { if (value == null) value = 0; v.setPadding(v.mPaddingLeft, attrBinder.parseDimension(value, 0), v.mPaddingRight, v.mPaddingBottom); }, getter(v: View) { return v.mPaddingTop; }, }).set('paddingRight', { setter(v: View, value: any, attrBinder:AttrBinder) { if (value == null) value = 0; v.setPadding(v.mPaddingLeft, v.mPaddingTop, attrBinder.parseDimension(value, 0), v.mPaddingBottom); }, getter(v: View) { return v.mPaddingRight; }, }).set('paddingBottom', { setter(v: View, value: any, attrBinder:AttrBinder) { if (value == null) value = 0; v.setPadding(v.mPaddingLeft, v.mPaddingTop, v.mPaddingRight, attrBinder.parseDimension(value, 0)); }, getter(v: View) { return v.mPaddingBottom; }, }).set('scrollX', { setter(v: View, value: any, attrBinder:AttrBinder) { value = attrBinder.parseNumberPixelOffset(value); if (Number.isInteger(value)) v.scrollTo(value, v.mScrollY); }, getter(v: View) { v.getScrollX(); }, }).set('scrollY', { setter(v: View, value: any, attrBinder:AttrBinder) { value = attrBinder.parseNumberPixelOffset(value); if (Number.isInteger(value)) v.scrollTo(v.mScrollX, value); }, getter(v: View) { return v.getScrollY(); }, }).set('alpha', { setter(v: View, value: any, attrBinder:AttrBinder) { v.setAlpha(attrBinder.parseFloat(value, v.getAlpha())); }, getter(v: View) { return v.getAlpha(); }, }).set('transformPivotX', { setter(v: View, value: any, attrBinder:AttrBinder) { v.setPivotX(attrBinder.parseNumberPixelOffset(value, v.getPivotX())); }, getter(v: View) { return v.getPivotX(); }, }).set('transformPivotY', { setter(v: View, value: any, attrBinder:AttrBinder) { v.setPivotY(attrBinder.parseNumberPixelOffset(value, v.getPivotY())); }, getter(v: View) { return v.getPivotY(); }, }).set('translationX', { setter(v: View, value: any, attrBinder:AttrBinder) { v.setTranslationX(attrBinder.parseNumberPixelOffset(value, v.getTranslationX())); }, getter(v: View) { return v.getTranslationX(); }, }).set('translationY', { setter(v: View, value: any, attrBinder:AttrBinder) { v.setTranslationY(attrBinder.parseNumberPixelOffset(value, v.getTranslationY())); }, getter(v: View) { return v.getTranslationY(); }, }).set('rotation', { setter(v: View, value: any, attrBinder:AttrBinder) { v.setRotation(attrBinder.parseFloat(value, v.getRotation())); }, getter(v: View) { return v.getRotation(); }, }).set('scaleX', { setter(v: View, value: any, attrBinder:AttrBinder) { v.setScaleX(attrBinder.parseFloat(value, v.getScaleX())); }, getter(v: View) { return v.getScaleX(); }, }).set('scaleY', { setter(v: View, value: any, attrBinder:AttrBinder) { v.setScaleY(attrBinder.parseFloat(value, v.getScaleY())); }, getter(v: View) { return v.getScaleY(); }, }).set('tag', { setter(v: View, value: any, attrBinder:AttrBinder) { v.setTag(value); }, getter(v: View) { return v.getTag(); }, }).set('id', { setter(v: View, value: any, attrBinder:AttrBinder) { v.setId(value); }, getter(v: View) { return v.getId(); }, }).set('focusable', { setter(v: View, value: any, attrBinder:AttrBinder) { if (attrBinder.parseBoolean(value, false)) { v.setFlags(View.FOCUSABLE, View.FOCUSABLE_MASK); } }, getter(v: View) { return v.isFocusable(); }, }).set('focusableInTouchMode', { setter(v: View, value: any, attrBinder:AttrBinder) { if (attrBinder.parseBoolean(value, false)) { v.setFlags(View.FOCUSABLE_IN_TOUCH_MODE | View.FOCUSABLE, View.FOCUSABLE_IN_TOUCH_MODE | View.FOCUSABLE_MASK); } }, getter(v: View) { return v.isFocusableInTouchMode(); }, }).set('clickable', { setter(v: View, value: any, attrBinder:AttrBinder) { if (attrBinder.parseBoolean(value, false)) { v.setFlags(View.CLICKABLE, View.CLICKABLE); } }, getter(v: View) { return v.isClickable(); }, }).set('longClickable', { setter(v: View, value: any, attrBinder:AttrBinder) { if (attrBinder.parseBoolean(value, false)) { v.setFlags(View.LONG_CLICKABLE, View.LONG_CLICKABLE); } }, getter(v: View) { return v.isLongClickable(); }, }).set('duplicateParentState', { setter(v: View, value: any, attrBinder:AttrBinder) { if (attrBinder.parseBoolean(value, false)) { v.setFlags(View.DUPLICATE_PARENT_STATE, View.DUPLICATE_PARENT_STATE); } }, getter(v: View) { return (v.mViewFlags & View.DUPLICATE_PARENT_STATE) == View.DUPLICATE_PARENT_STATE; }, }).set('visibility', { setter(v: View, value: any, attrBinder:AttrBinder) { if (value === 'gone') v.setVisibility(View.GONE); else if (value === 'invisible') v.setVisibility(View.INVISIBLE); else if (value === 'visible') v.setVisibility(View.VISIBLE); }, getter(v: View) { return v.getVisibility(); }, }).set('scrollbars', { setter(v: View, value: any, attrBinder:AttrBinder) { if (value === 'none') { v.setHorizontalScrollBarEnabled(false); v.setVerticalScrollBarEnabled(false); } else if (value === 'horizontal') { v.setHorizontalScrollBarEnabled(true); v.setVerticalScrollBarEnabled(false); } else if (value === 'vertical') { v.setHorizontalScrollBarEnabled(false); v.setVerticalScrollBarEnabled(true); } }, }).set('isScrollContainer', { setter(v: View, value: any, attrBinder:AttrBinder) { if (attrBinder.parseBoolean(value, false)) { v.setScrollContainer(true); } }, getter(v: View) { return v.isScrollContainer(); }, }).set('minWidth', { setter(v: View, value: any, attrBinder:AttrBinder) { v.setMinimumWidth(attrBinder.parseNumberPixelSize(value, 0)); }, getter(v: View) { return v.mMinWidth; }, }).set('minHeight', { setter(v: View, value: any, attrBinder:AttrBinder) { v.setMinimumHeight(attrBinder.parseNumberPixelSize(value, 0)); }, getter(v: View) { return v.mMinHeight; }, }).set('onClick', { setter(v: View, value: any, attrBinder:AttrBinder) { if (value && typeof value === 'string') { v.setOnClickListenerByAttrValueString(value); } // remove attr to avoid when debug layout show dom to click again on safari. v.bindElement.removeAttribute('onclick'); }, }).set('overScrollMode', { setter(v: View, value: any, attrBinder:AttrBinder) { let scrollMode = View[('OVER_SCROLL_' + value).toUpperCase()]; if (scrollMode === undefined) scrollMode = View.OVER_SCROLL_IF_CONTENT_SCROLLS; v.setOverScrollMode(scrollMode); } }).set('layerType', { setter(v: View, value: any, attrBinder:AttrBinder) { if ((value + '').toLowerCase() == 'software') { v.setLayerType(View.LAYER_TYPE_SOFTWARE); } else { v.setLayerType(View.LAYER_TYPE_NONE); } } }).set('cornerRadius', { // androidui add setter(v: View, value: any, attrBinder:AttrBinder) { let [topRight, rightBottom, bottomLeft, leftTop] = attrBinder.parsePaddingMarginTRBL(value); v.setCornerRadius(leftTop, topRight, rightBottom, bottomLeft); }, getter(v: View) { return v.mCornerRadiusTopRight + ' ' + v.mCornerRadiusBottomRight + ' ' + v.mCornerRadiusBottomLeft + ' ' + v.mCornerRadiusTopLeft; }, }).set('cornerRadiusTopLeft', { // androidui add setter(v: View, value: any, attrBinder:AttrBinder) { v.setCornerRadiusTopLeft(attrBinder.parseNumberPixelSize(value, v.mCornerRadiusTopLeft)); }, getter(v: View) { return v.mCornerRadiusTopLeft; }, }).set('cornerRadiusTopRight', { // androidui add setter(v: View, value: any, attrBinder:AttrBinder) { v.setCornerRadiusTopRight(attrBinder.parseNumberPixelSize(value, v.mCornerRadiusTopRight)); }, getter(v: View) { return v.mCornerRadiusTopRight; }, }).set('cornerRadiusBottomLeft', { // androidui add setter(v: View, value: any, attrBinder:AttrBinder) { v.setCornerRadiusBottomLeft(attrBinder.parseNumberPixelSize(value, v.mCornerRadiusBottomLeft)); }, getter(v: View) { return v.mCornerRadiusBottomLeft; }, }).set('cornerRadiusBottomRight', { // androidui add setter(v: View, value: any, attrBinder:AttrBinder) { v.setCornerRadiusBottomRight(attrBinder.parseNumberPixelSize(value, v.mCornerRadiusBottomRight)); }, getter(v: View) { return v.mCornerRadiusBottomRight; }, }).set('viewShadowColor', { // androidui add setter(v: View, value: any, attrBinder:AttrBinder) { if (!v.mShadowPaint) v.mShadowPaint = new Paint(); v.setShadowView(v.mShadowPaint.shadowRadius, v.mShadowPaint.shadowDx, v.mShadowPaint.shadowDy, attrBinder.parseColor(value, v.mShadowPaint.shadowColor)); }, getter(v: View) { if (v.mShadowPaint) return v.mShadowPaint.shadowColor; }, }).set('viewShadowDx', { // androidui add setter(v: View, value: any, attrBinder:AttrBinder) { if (!v.mShadowPaint) v.mShadowPaint = new Paint(); let dx = attrBinder.parseNumberPixelSize(value, v.mShadowPaint.shadowDx); v.setShadowView(v.mShadowPaint.shadowRadius, dx, v.mShadowPaint.shadowDy, v.mShadowPaint.shadowColor); }, getter(v: View) { if (v.mShadowPaint) return v.mShadowPaint.shadowDx; }, }).set('viewShadowDy', { // androidui add setter(v: View, value: any, attrBinder:AttrBinder) { if (!v.mShadowPaint) v.mShadowPaint = new Paint(); let dy = attrBinder.parseNumberPixelSize(value, v.mShadowPaint.shadowDy); v.setShadowView(v.mShadowPaint.shadowRadius, v.mShadowPaint.shadowDx, dy, v.mShadowPaint.shadowColor); }, getter(v: View) { if (v.mShadowPaint) return v.mShadowPaint.shadowDy; }, }).set('viewShadowRadius', { // androidui add setter(v: View, value: any, attrBinder:AttrBinder) { if (!v.mShadowPaint) v.mShadowPaint = new Paint(); let radius = attrBinder.parseNumberPixelSize(value, v.mShadowPaint.shadowRadius); v.setShadowView(radius, v.mShadowPaint.shadowDx, v.mShadowPaint.shadowDy, v.mShadowPaint.shadowColor); }, getter(v: View) { if (v.mShadowPaint) return v.mShadowPaint.shadowRadius; }, }); classAttrBinder.set('paddingStart', classAttrBinder.get('paddingLeft')); classAttrBinder.set('paddingEnd', classAttrBinder.get('paddingRight')); return classAttrBinder; } private _syncToElementLock:boolean; private _syncToElementImmediatelyLock:boolean; private _syncToElementRun: Runnable; requestSyncBoundToElement(immediately=this.dependOnDebugLayout()):void { let rootView = this.getRootView(); if(!rootView) return; if(!rootView._syncToElementRun){ rootView._syncToElementRun = { run:()=>{ rootView._syncToElementLock = false; rootView._syncToElementImmediatelyLock = false; rootView._syncBoundAndScrollToElement(); } }; } if(immediately){ if(rootView._syncToElementImmediatelyLock) return; rootView._syncToElementImmediatelyLock = true; rootView._syncToElementLock = true; rootView.removeCallbacks(rootView._syncToElementRun); rootView.post(rootView._syncToElementRun); return; } if(rootView._syncToElementLock) return; rootView._syncToElementLock = true; rootView.postDelayed(rootView._syncToElementRun, 1000); } private _lastSyncLeft:number; private _lastSyncTop:number; private _lastSyncWidth:number; private _lastSyncHeight:number; private _lastSyncScrollX:number; private _lastSyncScrollY:number; // sync bound to element from rootView protected _syncBoundAndScrollToElement():void { if(!this.isAttachedToWindow()){ return; } //bound const left = this.mLeft; const top = this.mTop; const width = this.getWidth(); const height = this.getHeight(); const parent = this.getParent(); const pScrollX = parent instanceof View ? (<View><any>parent).mScrollX : 0; const pScrollY = parent instanceof View ? (<View><any>parent).mScrollY : 0; if(left !== this._lastSyncLeft || top !== this._lastSyncTop || width !== this._lastSyncWidth || height !== this._lastSyncHeight || pScrollX !== this._lastSyncScrollX || pScrollY !== this._lastSyncScrollY) { this._lastSyncLeft = left; this._lastSyncTop = top; this._lastSyncWidth = width; this._lastSyncHeight = height; this._lastSyncScrollX = pScrollX; this._lastSyncScrollY = pScrollY; const density = this.getResources().getDisplayMetrics().density; let bind = this.bindElement; bind.style.width = width / density + 'px'; bind.style.height = height / density + 'px'; bind.style.left = (left-pScrollX)/density + 'px'; bind.style.top = (top-pScrollY)/density + 'px'; if (bind.parentElement) { // some case browser will do scroll to show input element. reset it. bind.parentElement.scrollTop = 0; } this.getMatrix(); // sync matrix to element } // children sync bound if(this instanceof ViewGroup){ const group = <ViewGroup><View>this; for (var i = 0 , count = group.getChildCount(); i<count; i++){ group.getChildAt(i)._syncBoundAndScrollToElement(); } } } private static TempMatrixValue = androidui.util.ArrayCreator.newNumberArray(9); private _lastSyncTransform:string; protected _syncMatrixToElement(){ let matrix = this.mTransformationInfo == null ? Matrix.IDENTITY_MATRIX : this.mTransformationInfo.mMatrix; matrix = matrix || Matrix.IDENTITY_MATRIX; let v = View.TempMatrixValue; matrix.getValues(v); let transfrom = `matrix(${v[Matrix.MSCALE_X]}, ${-v[Matrix.MSKEW_X]}, ${-v[Matrix.MSKEW_Y]}, ${v[Matrix.MSCALE_Y]}, ${v[Matrix.MTRANS_X]}, ${v[Matrix.MTRANS_Y]})`; if(this._lastSyncTransform != transfrom){ this._lastSyncTransform = this.bindElement.style.transform = this.bindElement.style.webkitTransform = transfrom; } } syncVisibleToElement(){ let visibility = this.getVisibility(); if(visibility === View.VISIBLE){ this.bindElement.style.display = ''; this.bindElement.style.visibility = ''; }else if(visibility === View.INVISIBLE){ this.bindElement.style.display = ''; this.bindElement.style.visibility = 'hidden'; }else{ this.bindElement.style.display = 'none'; this.bindElement.style.visibility = ''; } } protected dependOnDebugLayout(){ return false; } private _initAttrObserver(){ if(!window['MutationObserver']) return; if(!this._AttrObserver) this._AttrObserver = new MutationObserver(View._AttrObserverCallBack); else this._AttrObserver.disconnect(); this._AttrObserver.observe(this.bindElement, {attributes : true, attributeOldValue : true}); } private _fireStateChangeToAttribute(oldState:number[], newState:number[]){ if(!this._stateAttrList) return; if(java.util.Arrays.equals(oldState, newState)) return; let oldMatchedAttr = this._stateAttrList.getMatchedStateAttr(oldState); let matchedAttr = this._stateAttrList.getMatchedStateAttr(newState); //let attrMap = matchedAttr.createDiffKeyAsNullValueAttrMap(oldMatchedAttr); for(let [key, value] of matchedAttr.getAttrMap().entries()){ let attrValue = this._getBinderAttrValue(key); //set the current value to oldStateAttr, so if state change back, current value will restore if(oldMatchedAttr) { oldMatchedAttr.setAttr(key, attrValue); } if(value == attrValue) continue; this.onBindElementAttributeChanged(key, null, value); } } private _getBinderAttrValue(key:string):string { if(!key) return null; if(key.startsWith('layout_') || key.startsWith('android:layout_')) { let params = this.getLayoutParams(); if(params){ return params.getAttrBinder().getAttrValue(key); } }else{ return this._attrBinder.getAttrValue(key); } } private onBindElementAttributeChanged(attributeName:string, oldVal:string, newVal:string):void { //remove namespace 'android:' let parts = attributeName.split(":"); let attrName = parts[parts.length-1].toLowerCase(); if(newVal === 'true') newVal = <any>true; else if(newVal === 'false') newVal = <any>false; //layout attr if(attrName.startsWith('layout_')){ let params = this.getLayoutParams(); if(params){ params.getAttrBinder().onAttrChange(attrName, newVal, this.getContext()); this.requestLayout(); } return; } this._attrBinder.onAttrChange(attrName, newVal, this.getContext()); } tagName() : string{ return this.constructor.name; } } export module View{ export class TransformationInfo { /** * The transform matrix for the View. This transform is calculated internally * based on the rotation, scaleX, and scaleY properties. The identity matrix * is used by default. Do *not* use this variable directly; instead call * getMatrix(), which will automatically recalculate the matrix if necessary * to get the correct matrix based on the latest rotation and scale properties. */ mMatrix:Matrix = new Matrix(); /** * The transform matrix for the View. This transform is calculated internally * based on the rotation, scaleX, and scaleY properties. The identity matrix * is used by default. Do *not* use this variable directly; instead call * getInverseMatrix(), which will automatically recalculate the matrix if necessary * to get the correct matrix based on the latest rotation and scale properties. */ private mInverseMatrix:Matrix; /** * An internal variable that tracks whether we need to recalculate the * transform matrix, based on whether the rotation or scaleX/Y properties * have changed since the matrix was last calculated. */ mMatrixDirty:boolean = false; /** * An internal variable that tracks whether we need to recalculate the * transform matrix, based on whether the rotation or scaleX/Y properties * have changed since the matrix was last calculated. */ mInverseMatrixDirty:boolean = true; /** * A variable that tracks whether we need to recalculate the * transform matrix, based on whether the rotation or scaleX/Y properties * have changed since the matrix was last calculated. This variable * is only valid after a call to updateMatrix() or to a function that * calls it such as getMatrix(), hasIdentityMatrix() and getInverseMatrix(). */ mMatrixIsIdentity:boolean = true; ///** // * The Camera object is used to compute a 3D matrix when rotationX or rotationY are set. // */ //private mCamera:Camera = null; // ///** // * This matrix is used when computing the matrix for 3D rotations. // */ //private matrix3D:Matrix = null; /** * These prev values are used to recalculate a centered pivot point when necessary. The * pivot point is only used in matrix operations (when rotation, scale, or translation are * set), so thes values are only used then as well. */ mPrevWidth:number = -1; mPrevHeight:number = -1; ///** // * The degrees rotation around the vertical axis through the pivot point. // */ //mRotationY:number = 0; // ///** // * The degrees rotation around the horizontal axis through the pivot point. // */ //mRotationX:number = 0; /** * The degrees rotation around the pivot point. */ mRotation:number = 0; /** * The amount of translation of the object away from its left property (post-layout). */ mTranslationX:number = 0; /** * The amount of translation of the object away from its top property (post-layout). */ mTranslationY:number = 0; /** * The amount of scale in the x direction around the pivot point. A * value of 1 means no scaling is applied. */ mScaleX:number = 1; /** * The amount of scale in the y direction around the pivot point. A * value of 1 means no scaling is applied. */ mScaleY:number = 1; /** * The x location of the point around which the view is rotated and scaled. */ mPivotX:number = 0; /** * The y location of the point around which the view is rotated and scaled. */ mPivotY:number = 0; /** * The opacity of the View. This is a value from 0 to 1, where 0 means * completely transparent and 1 means completely opaque. */ mAlpha:number = 1; /** * The opacity of the view as manipulated by the Fade transition. This is a hidden * property only used by transitions, which is composited with the other alpha * values to calculate the final visual alpha value. */ mTransitionAlpha:number = 1; } export class MeasureSpec { static MODE_SHIFT = 30; static MODE_MASK = 0x3 << MeasureSpec.MODE_SHIFT; static UNSPECIFIED = 0 << MeasureSpec.MODE_SHIFT; static EXACTLY = 1 << MeasureSpec.MODE_SHIFT; static AT_MOST = 2 << MeasureSpec.MODE_SHIFT; static makeMeasureSpec(size, mode) { return (size & ~MeasureSpec.MODE_MASK) | (mode & MeasureSpec.MODE_MASK); } static getMode(measureSpec) { return (measureSpec & MeasureSpec.MODE_MASK); } static getSize(measureSpec) { return (measureSpec & ~MeasureSpec.MODE_MASK); } static adjust(measureSpec, delta) { return MeasureSpec.makeMeasureSpec( MeasureSpec.getSize(measureSpec + delta), MeasureSpec.getMode(measureSpec)); } static toString(measureSpec) { let mode = MeasureSpec.getMode(measureSpec); let size = MeasureSpec.getSize(measureSpec); let sb = new StringBuilder("MeasureSpec: "); if (mode == MeasureSpec.UNSPECIFIED) sb.append("UNSPECIFIED "); else if (mode == MeasureSpec.EXACTLY) sb.append("EXACTLY "); else if (mode == MeasureSpec.AT_MOST) sb.append("AT_MOST "); else sb.append(mode).append(" "); sb.append(size); return sb.toString(); } } export class AttachInfo { mRootView:View;//root view of window //mWindowLeft = 0; //mWindowTop = 0; mKeyDispatchState = new KeyEvent.DispatcherState(); //mDrawingTime=0; //mCanvas : Canvas; mViewRootImpl : ViewRootImpl; mHandler : Handler; mTmpInvalRect = new Rect(); mTmpTransformRect = new Rect(); mPoint:Point = new Point(); /** * Temporary for use in transforming invalidation rect */ mTmpMatrix:Matrix = new Matrix(); /** * Temporary for use in transforming invalidation rect */ mTmpTransformation:Transformation = new Transformation(); mTmpTransformLocation:number[] = androidui.util.ArrayCreator.newNumberArray(2); mScrollContainers = new Set<View>(); //mViewScrollChanged = false; //mTreeObserver = new ViewTreeObserver(); mViewRequestingLayout:View; //mViewVisibilityChanged = false; mInvalidateChildLocation = androidui.util.ArrayCreator.newNumberArray(2); mHasWindowFocus = false; mWindowVisibility = 0; //mInTouchMode = false; constructor(mViewRootImpl:ViewRootImpl, mHandler:Handler) { this.mViewRootImpl = mViewRootImpl; this.mHandler = mHandler; } } export class ListenerInfo{ mOnFocusChangeListener:OnFocusChangeListener; mOnAttachStateChangeListeners:CopyOnWriteArrayList<OnAttachStateChangeListener>; mOnLayoutChangeListeners:ArrayList<OnLayoutChangeListener>; mOnClickListener:OnClickListener; mOnLongClickListener:OnLongClickListener; mOnTouchListener:OnTouchListener; mOnKeyListener:OnKeyListener; mOnGenericMotionListener:OnGenericMotionListener; } export interface OnAttachStateChangeListener{ onViewAttachedToWindow(v:View); onViewDetachedFromWindow(v:View); } export interface OnLayoutChangeListener{ onLayoutChange(v:View, left:number , top:number, right:number, bottom:number, oldLeft:number, oldTop:number , oldRight:number , oldBottom:number):void; } export interface OnClickListener{ onClick(v:View):void; } export module OnClickListener{ export function fromFunction(func:(v:View)=>void):OnClickListener { return { onClick : func } } } export interface OnLongClickListener{ onLongClick(v:View):boolean; } export module OnLongClickListener{ export function fromFunction(func:(v:View)=>boolean):OnLongClickListener { return { onLongClick : func } } } export interface OnFocusChangeListener{ onFocusChange(v:View, hasFocus:boolean):void; } export module OnFocusChangeListener{ export function fromFunction(func:(v:View, hasFocus:boolean)=>void):OnFocusChangeListener { return { onFocusChange : func } } } export interface OnTouchListener{ onTouch(v:View, event:MotionEvent):void; } export module OnTouchListener{ export function fromFunction(func:(v:View, event:MotionEvent)=>void):OnTouchListener { return { onTouch : func } } } export interface OnKeyListener{ onKey(v:View, keyCode:number, event:KeyEvent):void; } export module OnKeyListener{ export function fromFunction(func:(v:View, keyCode:number, event:KeyEvent)=>void):OnKeyListener { return { onKey : func } } } export interface OnGenericMotionListener{ onGenericMotion(v:View, event:MotionEvent); } export module OnGenericMotionListener{ export function fromFunction(func:(v:View, event:MotionEvent)=>void):OnGenericMotionListener { return { onGenericMotion : func } } } export interface Predicate<T>{ apply(t:T):boolean; } } export module View.AttachInfo{ export class InvalidateInfo{ private static POOL_LIMIT = 10; private static sPool = new Pools.SynchronizedPool<InvalidateInfo>(InvalidateInfo.POOL_LIMIT); target:View; left = 0; top = 0; right = 0; bottom = 0; static obtain():InvalidateInfo { let instance = InvalidateInfo.sPool.acquire(); return (instance != null) ? instance : new InvalidateInfo(); } recycle():void { this.target = null; InvalidateInfo.sPool.release(this); } } } class CheckForLongPress implements Runnable{ private View_this : any;//don't check private private mOriginalWindowAttachCount = 0; constructor(View_this:View) { this.View_this = View_this; } run() { if (this.View_this.isPressed() && (this.View_this.mParent != null) && this.mOriginalWindowAttachCount == this.View_this.mWindowAttachCount) { if (this.View_this.performLongClick()) { this.View_this.mHasPerformedLongPress = true; } } } rememberWindowAttachCount() { this.mOriginalWindowAttachCount = this.View_this.mWindowAttachCount; } } class CheckForTap implements Runnable { private View_this : any; constructor(View_this:View) { this.View_this = View_this; } run() { this.View_this.mPrivateFlags &= ~View.PFLAG_PREPRESSED; this.View_this.setPressed(true); this.View_this.checkForLongClick(ViewConfiguration.getTapTimeout()); } } class PerformClick implements Runnable { private View_this : any; constructor(View_this:View) { this.View_this = View_this; } run() { this.View_this.performClick(); } } class PerformClickAfterPressDraw implements Runnable { private View_this : any; constructor(View_this:View) { this.View_this = View_this; } run() { this.View_this.post(this.View_this.mPerformClick); } } class UnsetPressedState implements Runnable { private View_this : any; constructor(View_this:View) { this.View_this = View_this; } run() { this.View_this.setPressed(false); } } class ScrollabilityCache implements Runnable { static OFF = 0; static ON = 1; static FADING = 2; fadeScrollBars = true; fadingEdgeLength = ViewConfiguration.get().getScaledFadingEdgeLength(); scrollBarDefaultDelayBeforeFade = ViewConfiguration.getScrollDefaultDelay(); scrollBarFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); scrollBarSize = ViewConfiguration.get().getScaledScrollBarSize(); scrollBar:ScrollBarDrawable; //interpolatorValues:Array<number>; private interpolator = new LinearInterpolator(); host:View; paint:Paint; fadeStartTime:number; state = ScrollabilityCache.OFF; constructor(host:View){ this.host = host; this.scrollBar = new ScrollBarDrawable(); //no track //let track = null; //this.scrollBar.setHorizontalTrackDrawable(track); //this.scrollBar.setVerticalTrackDrawable(track); let thumbColor = new ColorDrawable(0x44000000); let density = Resources.getDisplayMetrics().density; let thumb = new InsetDrawable(thumbColor, 0, 2*density, ViewConfiguration.get().getScaledScrollBarSize()/2, 2*density); this.scrollBar.setHorizontalThumbDrawable(thumb); this.scrollBar.setVerticalThumbDrawable(thumb); } run() { let now = AnimationUtils.currentAnimationTimeMillis(); if (now >= this.fadeStartTime) { //TODO compute scroll bar optical this.state = ScrollabilityCache.FADING; // Kick off the fade animation this.host.invalidate(true); } } _computeAlphaToScrollBar(){ let now = AnimationUtils.currentAnimationTimeMillis(); let factor = (now - this.fadeStartTime) / this.scrollBarFadeDuration; if(factor>=1){ this.state = ScrollabilityCache.OFF; factor = 1; } let alpha = 1 - this.interpolator.getInterpolation(factor); this.scrollBar.setAlpha(255 * alpha); } } class MatchIdPredicate implements View.Predicate<View>{ mId:string; apply(view:View):boolean { return view.mID === this.mId; } } }
the_stack
/// <reference path="./definitions/mocha.d.ts"/> import assert = require('assert'); import path = require('path'); import fm = require('./lib/feedback'); import trp = require('../agent/testrunpublisher'); import trr = require('../agent/testresultreader'); import cm = require('../agent/common'); import ifm = require('../agent/interfaces'); import testifm = require('vso-node-api/interfaces/TestInterfaces'); import tc = require('./lib/testcommand'); import rp = require('../agent/commands/results.publish'); import tec = require('./lib/testExecutionContext'); var jobInf = require('./lib/testJobInfo'); function resultFile(filename: string) { return path.resolve(__dirname, 'testresults', filename); } describe('PublisherTests', function() { const runContext: trp.TestRunContext = { requestedFor: "userx", buildId: "21", platform: "mac", config: "debug", runTitle: "My Title", publishRunAttachments: true, fileNumber: "3", releaseUri: "abc", releaseEnvironmentUri: "xyz" }; let command: cm.ITaskCommand; const readerJUnit = new trr.JUnitResultReader(command); const readerNUnit = new trr.NUnitResultReader(command); const readerXUnit = new trr.XUnitResultReader(command); const emptyFile = resultFile('empty.xml'); const resultsFileJUnit = resultFile('junitresults1.xml'); const resultsFileJUnit2 = resultFile('junitresults2.xml'); const resultstFileJUnitMultiNode = resultFile('Junit_test2.xml'); const resultsFileJUnitNoTestCases = resultFile('junit_with_no_test_cases.xml'); const resultsFileJUnitNoTestSuites = resultFile('junit_with_no_test_suites.xml'); const resultsFileNUnit = resultFile('nunitresults.xml'); const resultsFileNUnit2 = resultFile('nunitresults.1.xml'); const resultsFileXUnit = resultFile('xunitresults.xml'); const resultsFileXUnit2 = resultFile('xunitresults.1.xml'); var junitFilePath = path.resolve(__dirname, './testresults/junitresults1.xml'); var testExecutionContext; it('results.publish : JUnit results file', () => { const feedbackChannel = new fm.TestFeedbackChannel(); const testRunPublisher = new trp.TestRunPublisher(feedbackChannel, null, "teamProject", runContext, readerJUnit); return testRunPublisher.publishTestRun(resultsFileJUnit).then(createdTestRun => { assert(feedbackChannel.jobsCompletedSuccessfully(), 'ResultPublish Task Failed! Details : ' + feedbackChannel.getRecordsString()); }); }); it('results.publish : JUnit results file with multiple test suite nodes (karma format)', () => { const feedbackChannel = new fm.TestFeedbackChannel(); const testRunPublisher = new trp.TestRunPublisher(feedbackChannel, null, "teamProject", runContext, readerJUnit); return testRunPublisher.publishTestRun(resultstFileJUnitMultiNode).then(createdTestRun => { assert(feedbackChannel.jobsCompletedSuccessfully(), 'ResultPublish Task Failed! Details : ' + feedbackChannel.getRecordsString()); }); }); it('results.publish : JUnit results file with a suite and no cases', () => { const feedbackChannel = new fm.TestFeedbackChannel(); const testRunPublisher = new trp.TestRunPublisher(feedbackChannel, null, "teamProject", runContext, readerJUnit); return testRunPublisher.publishTestRun(resultsFileJUnitNoTestCases).then(createdTestRun => { assert(feedbackChannel.jobsCompletedSuccessfully(), 'ResultPublish Task Failed! Details : ' + feedbackChannel.getRecordsString()); }); }); it('results.publish : JUnit results file with no suites', () => { const feedbackChannel = new fm.TestFeedbackChannel(); const testRunPublisher = new trp.TestRunPublisher(feedbackChannel, null, "teamProject", runContext, readerJUnit); return testRunPublisher.publishTestRun(resultsFileJUnitNoTestSuites).then(createdTestRun => { assert(feedbackChannel.jobsCompletedSuccessfully(), 'ResultPublish Task Failed! Details : ' + feedbackChannel.getRecordsString()); }); }); it('results.publish : NUnit results file', () => { const feedbackChannel = new fm.TestFeedbackChannel(); const testRunPublisher = new trp.TestRunPublisher(feedbackChannel, null, "teamProject", runContext, readerNUnit); return testRunPublisher.publishTestRun(resultsFileNUnit).then(createdTestRun => { assert(feedbackChannel.jobsCompletedSuccessfully(), 'ResultPublish Task Failed! Details : ' + feedbackChannel.getRecordsString()); }); }); it('results.publish : XUnit results file', () => { const feedbackChannel = new fm.TestFeedbackChannel(); const testRunPublisher = new trp.TestRunPublisher(feedbackChannel, null, "teamProject", runContext, readerXUnit); return testRunPublisher.publishTestRun(resultsFileXUnit).then(createdTestRun => { assert(feedbackChannel.jobsCompletedSuccessfully(), 'ResultPublish Task Failed! Details : ' + feedbackChannel.getRecordsString()); }); }); it('results.publish : error handling for end test run', () => { const feedbackChannel = new fm.TestFeedbackChannel(); const testRunPublisher = new trp.TestRunPublisher(feedbackChannel, null, "teamProject", runContext, readerJUnit); var testRun = { name: "foobar", id: -1, resultsFile: resultsFileJUnit }; // error handling/propagation from end test run return testRunPublisher.endTestRun(testRun.id, testRun.resultsFile) .then(createdTestRun => assert(false, 'ResultPublish Task did not fail as expected')) .catch(err => { assert(err.message == "Too bad - endTestRun failed", 'ResultPublish Task error message does not match expected - ' + err.message); }); }); it('results.publish : error handling for reading results', () => { const feedbackChannel = new fm.TestFeedbackChannel(); const testRunPublisher = new trp.TestRunPublisher(feedbackChannel, null, "teamProject", runContext, readerJUnit); // error handling/propagation from parsing failures of junit/nunit files var resultsFile = path.resolve(__dirname, './testresults/junit_bad.xml'); return testRunPublisher.publishTestRun(resultsFile) .then(createdTestRun => { assert(!feedbackChannel.jobsCompletedSuccessfully(), 'ResultPublish Task Failed! Details : ' + feedbackChannel.getRecordsString()); }) .catch(err => { assert(err.message == "Unmatched closing tag: XYZXYZuite\nLine: 13\nColumn: 16\nChar: >", 'ResultPublish Task Failed as expected! Details : ' + err.message); }); }); it('results.publish : JUnit reader sanity check without run title', () => { var results; var testRun; runContext.runTitle = ""; runContext.fileNumber = "0"; return readerJUnit.readResults(resultsFileJUnit, runContext).then(res => { testRun = res.testRun; results = res.testResults; //Verifying the test run details assert.strictEqual("JUnitXmlReporter", testRun.name); assert.equal("debug", testRun.buildFlavor); assert.equal("mac", testRun.buildPlatform); assert.equal("abc", testRun.releaseUri); assert.equal("xyz", testRun.releaseEnvironmentUri); assert.equal(21, testRun.build.id); assert.strictEqual(true, testRun.automated); //Verifying Test Results assert.strictEqual(3, results.length); assert.strictEqual("should default path to an empty string", results[0].automatedTestName); assert.strictEqual("should default consolidate to true", results[1].automatedTestName); assert.strictEqual("should default useDotNotation to true", results[2].automatedTestName); }); }); it('results.publish : JUnit reader sanity check with run title', () => { var testRun; runContext.runTitle = "My Title"; runContext.fileNumber = "0"; return readerJUnit.readResults(resultsFileJUnit, runContext).then(res => { testRun = res.testRun; //Verifying the test run details assert.strictEqual("My Title", testRun.name); }); }); it('results.publish : JUnit reader sanity check with run title and file number', () => { var testRun; runContext.fileNumber = "3"; return readerJUnit.readResults(resultsFileJUnit, runContext).then(res => { testRun = res.testRun; //Verifying the test run details assert.strictEqual("My Title 3", testRun.name); }); }); it('results.publish : NUnit reader sanity check without run title', () => { var results; var testRun; runContext.runTitle = ""; runContext.fileNumber = "0"; return readerNUnit.readResults(resultsFileNUnit, runContext).then(res => { testRun = res.testRun; results = res.testResults; //Verifying the test run details assert.strictEqual("/Volumes/Data/xamarin/workspaces/android-csharp-test-job-c2a0f46d-7bf3-4ba8-97ce-ce8a8fdd1c4720150429-96377-8lrqzf/CreditCardValidation.Tests.dll", testRun.name); assert.equal("debug", testRun.buildFlavor); assert.equal("mac", testRun.buildPlatform); assert.equal("abc", testRun.releaseUri); assert.equal("xyz", testRun.releaseEnvironmentUri); assert.equal(21, testRun.build.id); assert.strictEqual(true, testRun.automated); //Verifying Test Results assert.strictEqual(4, results.length); assert.strictEqual("CreditCardValidation.Tests.ValidateCreditCardTests.CreditCardNumber_CorrectSize_DisplaySuccessScreen(Android)_lg_nexus_5_4_4_4", results[0].automatedTestName); assert.strictEqual("CreditCardValidation.Tests.ValidateCreditCardTests.CreditCardNumber_IsBlank_DisplayErrorMessage(Android)_lg_nexus_5_4_4_4", results[1].automatedTestName); assert.strictEqual("CreditCardValidation.Tests.ValidateCreditCardTests.CreditCardNumber_TooLong_DisplayErrorMessage(Android)_lg_nexus_5_4_4_4", results[2].automatedTestName); assert.strictEqual("CreditCardValidation.Tests.ValidateCreditCardTests.CreditCardNumber_TooShort_DisplayErrorMessage(Android)_lg_nexus_5_4_4_4", results[3].automatedTestName); }); }); it('results.publish : NUnit reader sanity check with run title', () => { var testRun; runContext.runTitle = "My Title"; runContext.fileNumber = "0"; return readerNUnit.readResults(resultsFileNUnit, runContext).then(res => { testRun = res.testRun; //Verifying the test run details assert.strictEqual("My Title", testRun.name); }); }); it('results.publish : NUnit reader sanity check with run title and file number', () => { var testRun; runContext.fileNumber = "3"; return readerNUnit.readResults(resultsFileNUnit, runContext).then(res => { testRun = res.testRun; //Verifying the test run details assert.strictEqual("My Title 3", testRun.name); }); }); it('results.publish : XUnit reader sanity check without run title', () => { var results; var testRun; runContext.runTitle = ""; runContext.fileNumber = "0"; return readerXUnit.readResults(resultsFileXUnit, runContext).then(res => { testRun = res.testRun; results = res.testResults; //Verifying the test run details assert.strictEqual("XUnit Test Run debug mac", testRun.name); assert.equal("debug", testRun.buildFlavor); assert.equal("mac", testRun.buildPlatform); assert.equal("abc", testRun.releaseUri); assert.equal("xyz", testRun.releaseEnvironmentUri); assert.equal(21, testRun.build.id); assert.strictEqual(true, testRun.automated); //Verifying Test Results assert.strictEqual(4, results.length); assert.strictEqual("FailingTest", results[0].automatedTestName); assert.strictEqual("PassingTest", results[1].automatedTestName); assert.strictEqual("tset2", results[2].automatedTestName); assert.strictEqual("test1", results[3].automatedTestName); }); }); it('results.publish : XUnit reader sanity check with run title', () => { var testRun; runContext.runTitle = "My Title"; runContext.fileNumber = "0"; return readerXUnit.readResults(resultsFileXUnit, runContext).then(res => { testRun = res.testRun; //Verifying the test run details assert.strictEqual("My Title", testRun.name); }); }); it('results.publish : XUnit reader sanity check with run title and file number', () => { var testRun; runContext.fileNumber = "3"; return readerXUnit.readResults(resultsFileXUnit, runContext).then(res => { testRun = res.testRun; //Verifying the test run details assert.strictEqual("My Title 3", testRun.name); }); }); it('results.publish : JUnit results file with merge support', () => { const feedbackChannel = new fm.TestFeedbackChannel(); const testRunPublisher = new trp.TestRunPublisher(feedbackChannel, null, "teamProject", runContext, readerJUnit); return testRunPublisher.publishMergedTestRun([resultsFileJUnit, resultsFileJUnit2]).then(createTestRun => { assert(feedbackChannel.jobsCompletedSuccessfully(), 'ResultPublish Task Failed! Details : ' + feedbackChannel.getRecordsString()); }); }) it('results.publish : NUnit results file with merge support', () => { const feedbackChannel = new fm.TestFeedbackChannel(); const testRunPublisher = new trp.TestRunPublisher(feedbackChannel, null, "teamProject", runContext, readerNUnit); return testRunPublisher.publishMergedTestRun([resultsFileNUnit, resultsFileNUnit2]).then(createdTestRun => { assert(feedbackChannel.jobsCompletedSuccessfully(), 'ResultPublish Task Failed! Details : ' + feedbackChannel.getRecordsString()); }); }) it('results.publish : XUnit results file with merge support', () => { const feedbackChannel = new fm.TestFeedbackChannel(); const testRunPublisher = new trp.TestRunPublisher(feedbackChannel, null, "teamProject", runContext, readerXUnit); return testRunPublisher.publishMergedTestRun([resultsFileXUnit, resultsFileXUnit2]).then(createdTestRun => { assert(feedbackChannel.jobsCompletedSuccessfully(), 'ResultPublish Task Failed! Details : ' + feedbackChannel.getRecordsString()); }); }) it('results.publish : JUnit results file with merge support with one invalid xml file', () => { const feedbackChannel = new fm.TestFeedbackChannel(); const testRunPublisher = new trp.TestRunPublisher(feedbackChannel, null, "teamProject", runContext, readerXUnit); return testRunPublisher.publishMergedTestRun([resultsFileJUnit, resultsFileJUnit2, emptyFile]).then(createdTestRun => { assert(feedbackChannel.jobsCompletedSuccessfully(), 'ResultPublish Task Failed! Details : ' + feedbackChannel.getRecordsString()); }); }) it('results.publish : Publish Test Results with old task compat', () => { var properties: { [name: string]: string } = { "type": "junit", "platform": "platform", "config": "config", "runTitle": "Test Title", "publishRunAttachments": "true", "fileNumber": "1" }; var message = junitFilePath; var command: cm.ITaskCommand = new tc.TestCommand(null, properties, message); testExecutionContext = new tec.TestExecutionContext(new jobInf.TestJobInfo({})); testExecutionContext.variables['system.teamProject'] = "teamProject"; var testResultsPublisher = new rp.ResultsPublishCommand(testExecutionContext, command); testResultsPublisher.runCommandAsync().then(function(result) { assert(testExecutionContext.service.jobsCompletedSuccessfully()); }, function(err) { assert(false, 'Publish Test Results failed for old tasks: ' + testExecutionContext.service.getRecordsString()) }); }) });
the_stack
import Entity from '../Entity'; import { EntityCompanionDefinition } from '../EntityCompanionProvider'; import EntityConfiguration from '../EntityConfiguration'; import { EntityEdgeDeletionBehavior } from '../EntityFieldDefinition'; import { UUIDField } from '../EntityFields'; import { EntityTriggerMutationInfo, EntityMutationType } from '../EntityMutationInfo'; import { EntityMutationTrigger } from '../EntityMutationTriggerConfiguration'; import EntityPrivacyPolicy from '../EntityPrivacyPolicy'; import { EntityTransactionalQueryContext } from '../EntityQueryContext'; import { CacheStatus } from '../internal/ReadThroughEntityCache'; import AlwaysAllowPrivacyPolicyRule from '../rules/AlwaysAllowPrivacyPolicyRule'; import TestViewerContext from '../testfixtures/TestViewerContext'; import { InMemoryFullCacheStubCacheAdapter } from '../utils/testing/StubCacheAdapter'; import { createUnitTestEntityCompanionProvider } from '../utils/testing/createUnitTestEntityCompanionProvider'; interface ParentFields { id: string; } interface ChildFields { id: string; parent_id: string; } interface GrandChildFields { id: string; parent_id: string; } class TestEntityPrivacyPolicy extends EntityPrivacyPolicy< any, string, TestViewerContext, any, any > { protected override readonly readRules = [ new AlwaysAllowPrivacyPolicyRule<any, string, TestViewerContext, any, any>(), ]; protected override readonly createRules = [ new AlwaysAllowPrivacyPolicyRule<any, string, TestViewerContext, any, any>(), ]; protected override readonly updateRules = [ new AlwaysAllowPrivacyPolicyRule<any, string, TestViewerContext, any, any>(), ]; protected override readonly deleteRules = [ new AlwaysAllowPrivacyPolicyRule<any, string, TestViewerContext, any, any>(), ]; } // eslint-disable-next-line @typescript-eslint/explicit-function-return-type const makeEntityClasses = (edgeDeletionBehavior: EntityEdgeDeletionBehavior) => { const triggerExecutionCounts = { parent: 0, child: 0, grandchild: 0, }; class ParentCheckInfoTrigger extends EntityMutationTrigger< ParentFields, string, TestViewerContext, ParentEntity > { async executeAsync( _viewerContext: TestViewerContext, _queryContext: EntityTransactionalQueryContext, _entity: ParentEntity, mutationInfo: EntityTriggerMutationInfo<ParentFields, string, TestViewerContext, ParentEntity> ): Promise<void> { if (mutationInfo.type !== EntityMutationType.DELETE) { return; } if (mutationInfo.cascadingDeleteCause !== null) { throw new Error('Parent entity should not have casade delete cause'); } triggerExecutionCounts.parent++; } } class ChildCheckInfoTrigger extends EntityMutationTrigger< ChildFields, string, TestViewerContext, ChildEntity > { async executeAsync( _viewerContext: TestViewerContext, _queryContext: EntityTransactionalQueryContext, _entity: ChildEntity, mutationInfo: EntityTriggerMutationInfo<ChildFields, string, TestViewerContext, ChildEntity> ): Promise<void> { if (mutationInfo.type !== EntityMutationType.DELETE) { return; } if (mutationInfo.cascadingDeleteCause === null) { throw new Error('Child entity should have casade delete cause'); } const cascadingDeleteCauseEntity = mutationInfo.cascadingDeleteCause.entity; if (!(cascadingDeleteCauseEntity instanceof ParentEntity)) { throw new Error('Child entity should have casade delete cause entity of type ParentEntity'); } const secondLevelCascadingDeleteCause = mutationInfo.cascadingDeleteCause.cascadingDeleteCause; if (secondLevelCascadingDeleteCause) { throw new Error('Child entity should not have two-level casade delete cause'); } triggerExecutionCounts.child++; } } class GrandChildCheckInfoTrigger extends EntityMutationTrigger< GrandChildFields, string, TestViewerContext, GrandChildEntity > { async executeAsync( _viewerContext: TestViewerContext, _queryContext: EntityTransactionalQueryContext, _entity: GrandChildEntity, mutationInfo: EntityTriggerMutationInfo< GrandChildFields, string, TestViewerContext, GrandChildEntity > ): Promise<void> { if (mutationInfo.type !== EntityMutationType.DELETE) { return; } if (mutationInfo.cascadingDeleteCause === null) { throw new Error('GrandChild entity should have cascade delete cause'); } const cascadingDeleteCauseEntity = mutationInfo.cascadingDeleteCause.entity; if (!(cascadingDeleteCauseEntity instanceof ChildEntity)) { throw new Error( 'GrandChild entity should have cascade delete cause entity of type ChildEntity' ); } const secondLevelCascadingDeleteCause = mutationInfo.cascadingDeleteCause.cascadingDeleteCause; if (!secondLevelCascadingDeleteCause) { throw new Error('GrandChild entity should have two-level casade delete cause'); } const secondLevelCascadingDeleteCauseEntity = secondLevelCascadingDeleteCause.entity; if (!(secondLevelCascadingDeleteCauseEntity instanceof ParentEntity)) { throw new Error( 'GrandChild entity should have second level casade delete cause entity of type ParentEntity' ); } const thirdLevelCascadingDeleteCause = secondLevelCascadingDeleteCause.cascadingDeleteCause; if (thirdLevelCascadingDeleteCause) { throw new Error('GrandChild entity should not have three-level casade delete cause'); } triggerExecutionCounts.grandchild++; } } class ParentEntity extends Entity<ParentFields, string, TestViewerContext> { static getCompanionDefinition(): EntityCompanionDefinition< ParentFields, string, TestViewerContext, ParentEntity, TestEntityPrivacyPolicy > { return parentEntityCompanion; } } class ChildEntity extends Entity<ChildFields, string, TestViewerContext> { static getCompanionDefinition(): EntityCompanionDefinition< ChildFields, string, TestViewerContext, ChildEntity, TestEntityPrivacyPolicy > { return childEntityCompanion; } } class GrandChildEntity extends Entity<GrandChildFields, string, TestViewerContext> { static getCompanionDefinition(): EntityCompanionDefinition< GrandChildFields, string, TestViewerContext, GrandChildEntity, TestEntityPrivacyPolicy > { return grandChildEntityCompanion; } } const parentEntityConfiguration = new EntityConfiguration<ParentFields>({ idField: 'id', tableName: 'parents', getInboundEdges: () => [ChildEntity], schema: { id: new UUIDField({ columnName: 'id', cache: true, }), }, databaseAdapterFlavor: 'postgres', cacheAdapterFlavor: 'redis', }); const childEntityConfiguration = new EntityConfiguration<ChildFields>({ idField: 'id', tableName: 'children', getInboundEdges: () => [GrandChildEntity], schema: { id: new UUIDField({ columnName: 'id', cache: true, }), parent_id: new UUIDField({ columnName: 'parent_id', cache: true, association: { getAssociatedEntityClass: () => ParentEntity, edgeDeletionBehavior, }, }), }, databaseAdapterFlavor: 'postgres', cacheAdapterFlavor: 'redis', }); const grandChildEntityConfiguration = new EntityConfiguration<GrandChildFields>({ idField: 'id', tableName: 'grandchildren', schema: { id: new UUIDField({ columnName: 'id', cache: true, }), parent_id: new UUIDField({ columnName: 'parent_id', cache: true, association: { getAssociatedEntityClass: () => ChildEntity, edgeDeletionBehavior, }, }), }, databaseAdapterFlavor: 'postgres', cacheAdapterFlavor: 'redis', }); const parentEntityCompanion = new EntityCompanionDefinition({ entityClass: ParentEntity, entityConfiguration: parentEntityConfiguration, privacyPolicyClass: TestEntityPrivacyPolicy, mutationTriggers: () => ({ beforeDelete: [new ParentCheckInfoTrigger()], afterDelete: [new ParentCheckInfoTrigger()], }), }); const childEntityCompanion = new EntityCompanionDefinition({ entityClass: ChildEntity, entityConfiguration: childEntityConfiguration, privacyPolicyClass: TestEntityPrivacyPolicy, mutationTriggers: () => ({ beforeDelete: [new ChildCheckInfoTrigger()], afterDelete: [new ChildCheckInfoTrigger()], }), }); const grandChildEntityCompanion = new EntityCompanionDefinition({ entityClass: GrandChildEntity, entityConfiguration: grandChildEntityConfiguration, privacyPolicyClass: TestEntityPrivacyPolicy, mutationTriggers: () => ({ beforeDelete: [new GrandChildCheckInfoTrigger()], afterDelete: [new GrandChildCheckInfoTrigger()], }), }); return { ParentEntity, ChildEntity, GrandChildEntity, triggerExecutionCounts, }; }; describe('EntityMutator.processEntityDeletionForInboundEdgesAsync', () => { describe('EntityEdgeDeletionBehavior.CASCADE_DELETE', () => { it('deletes', async () => { const { ParentEntity, ChildEntity, GrandChildEntity, triggerExecutionCounts } = makeEntityClasses(EntityEdgeDeletionBehavior.CASCADE_DELETE); const companionProvider = createUnitTestEntityCompanionProvider(); const viewerContext = new TestViewerContext(companionProvider); const parent = await ParentEntity.creator(viewerContext).enforceCreateAsync(); const child = await ChildEntity.creator(viewerContext) .setField('parent_id', parent.getID()) .enforceCreateAsync(); const grandchild = await GrandChildEntity.creator(viewerContext) .setField('parent_id', child.getID()) .enforceCreateAsync(); await expect( ParentEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parent.getID()) ).resolves.not.toBeNull(); await expect( ChildEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(child.getID()) ).resolves.not.toBeNull(); await expect( GrandChildEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(grandchild.getID()) ).resolves.not.toBeNull(); await ParentEntity.enforceDeleteAsync(parent); await expect( ParentEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parent.getID()) ).resolves.toBeNull(); await expect( ChildEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(child.getID()) ).resolves.toBeNull(); await expect( GrandChildEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(grandchild.getID()) ).resolves.toBeNull(); // two calls for each trigger, one beforeDelete, one afterDelete expect(triggerExecutionCounts).toMatchObject({ parent: 2, child: 2, grandchild: 2, }); }); }); describe('EntityEdgeDeletionBehavior.SET_NULL', () => { it('sets null', async () => { const { ParentEntity, ChildEntity, GrandChildEntity, triggerExecutionCounts } = makeEntityClasses(EntityEdgeDeletionBehavior.SET_NULL); const companionProvider = createUnitTestEntityCompanionProvider(); const viewerContext = new TestViewerContext(companionProvider); const parent = await ParentEntity.creator(viewerContext).enforceCreateAsync(); const child = await ChildEntity.creator(viewerContext) .setField('parent_id', parent.getID()) .enforceCreateAsync(); const grandchild = await GrandChildEntity.creator(viewerContext) .setField('parent_id', child.getID()) .enforceCreateAsync(); await expect( ParentEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parent.getID()) ).resolves.not.toBeNull(); await expect( ChildEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(child.getID()) ).resolves.not.toBeNull(); await expect( GrandChildEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(grandchild.getID()) ).resolves.not.toBeNull(); await ParentEntity.enforceDeleteAsync(parent); await expect( ParentEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parent.getID()) ).resolves.toBeNull(); const loadedChild = await ChildEntity.loader(viewerContext) .enforcing() .loadByIDAsync(child.getID()); expect(loadedChild.getField('parent_id')).toBeNull(); const loadedGrandchild = await GrandChildEntity.loader(viewerContext) .enforcing() .loadByIDAsync(grandchild.getID()); expect(loadedGrandchild.getField('parent_id')).toEqual(loadedChild.getID()); // two calls for only parent trigger, one beforeDelete, one afterDelete // when using set null the descendants aren't deleted expect(triggerExecutionCounts).toMatchObject({ parent: 2, child: 0, grandchild: 0, }); }); }); describe('EntityEdgeDeletionBehavior.CASCADE_DELETE_INVALIDATE_CACHE', () => { it('invalidates the cache', async () => { const { ParentEntity, ChildEntity, GrandChildEntity, triggerExecutionCounts } = makeEntityClasses(EntityEdgeDeletionBehavior.CASCADE_DELETE_INVALIDATE_CACHE); const companionProvider = createUnitTestEntityCompanionProvider(); const viewerContext = new TestViewerContext(companionProvider); const parent = await ParentEntity.creator(viewerContext).enforceCreateAsync(); const child = await ChildEntity.creator(viewerContext) .setField('parent_id', parent.getID()) .enforceCreateAsync(); const grandchild = await GrandChildEntity.creator(viewerContext) .setField('parent_id', child.getID()) .enforceCreateAsync(); await expect( ParentEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parent.getID()) ).resolves.not.toBeNull(); await expect( ChildEntity.loader(viewerContext) .enforcing() .loadByFieldEqualingAsync('parent_id', parent.getID()) ).resolves.not.toBeNull(); await expect( GrandChildEntity.loader(viewerContext) .enforcing() .loadByFieldEqualingAsync('parent_id', child.getID()) ).resolves.not.toBeNull(); const childCacheAdapter = viewerContext.getViewerScopedEntityCompanionForClass(ChildEntity)[ 'entityCompanion' ]['tableDataCoordinator']['cacheAdapter'] as InMemoryFullCacheStubCacheAdapter<ChildFields>; const childCachedBefore = await childCacheAdapter.loadManyAsync('parent_id', [ parent.getID(), ]); expect(childCachedBefore.get(parent.getID())?.status).toEqual(CacheStatus.HIT); const grandChildCacheAdapter = viewerContext.getViewerScopedEntityCompanionForClass( GrandChildEntity )['entityCompanion']['tableDataCoordinator'][ 'cacheAdapter' ] as InMemoryFullCacheStubCacheAdapter<ChildFields>; const grandChildCachedBefore = await grandChildCacheAdapter.loadManyAsync('parent_id', [ child.getID(), ]); expect(grandChildCachedBefore.get(child.getID())?.status).toEqual(CacheStatus.HIT); await ParentEntity.enforceDeleteAsync(parent); const childCachedAfter = await childCacheAdapter.loadManyAsync('parent_id', [parent.getID()]); expect(childCachedAfter.get(parent.getID())?.status).toEqual(CacheStatus.MISS); const grandChildCachedAfter = await grandChildCacheAdapter.loadManyAsync('parent_id', [ child.getID(), ]); expect(grandChildCachedAfter.get(child.getID())?.status).toEqual(CacheStatus.MISS); await expect( ParentEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(parent.getID()) ).resolves.toBeNull(); await expect( ChildEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(child.getID()) ).resolves.not.toBeNull(); await expect( GrandChildEntity.loader(viewerContext).enforcing().loadByIDNullableAsync(grandchild.getID()) ).resolves.not.toBeNull(); // two calls for each trigger, one beforeDelete, one afterDelete expect(triggerExecutionCounts).toMatchObject({ parent: 2, child: 2, grandchild: 2, }); }); }); });
the_stack
import type {Class} from "@swim/util"; import type {MemberFastenerClass} from "@swim/component"; import type {TraitConstructor, TraitClass, Trait} from "@swim/model"; import type {View} from "@swim/view"; import type {HtmlViewClass, HtmlView} from "@swim/dom"; import {Controller, TraitViewRef, TraitViewControllerSet} from "@swim/controller"; import type {ColLayout} from "../layout/ColLayout"; import type {ColView} from "../col/ColView"; import type {ColTrait} from "../col/ColTrait"; import {ColController} from "../col/ColController"; import {HeaderView} from "./HeaderView"; import {HeaderTrait} from "./HeaderTrait"; import type {HeaderControllerObserver} from "./HeaderControllerObserver"; /** @public */ export type HeaderControllerColExt = { attachColTrait(colTrait: ColTrait, colController: ColController): void; detachColTrait(colTrait: ColTrait, colController: ColController): void; attachColView(colView: ColView, colController: ColController): void; detachColView(colView: ColView, colController: ColController): void; attachColLabelView(colLabelView: HtmlView, colController: ColController): void; detachColLabelView(colLabelView: HtmlView, colController: ColController): void; }; /** @public */ export class HeaderController extends Controller { override readonly observerType?: Class<HeaderControllerObserver>; @TraitViewRef<HeaderController, HeaderTrait, HeaderView>({ traitType: HeaderTrait, observesTrait: true, willAttachTrait(headerTrait: HeaderTrait): void { this.owner.callObservers("controllerWillAttachHeaderTrait", headerTrait, this.owner); }, didAttachTrait(headerTrait: HeaderTrait): void { const colTraits = headerTrait.cols.traits; for (const traitId in colTraits) { const colTrait = colTraits[traitId]!; this.owner.cols.addTraitController(colTrait); } }, willDetachTrait(headerTrait: HeaderTrait): void { const colTraits = headerTrait.cols.traits; for (const traitId in colTraits) { const colTrait = colTraits[traitId]!; this.owner.cols.deleteTraitController(colTrait); } }, didDetachTrait(headerTrait: HeaderTrait): void { this.owner.callObservers("controllerDidDetachHeaderTrait", headerTrait, this.owner); }, traitWillAttachCol(colTrait: ColTrait, targetTrait: Trait): void { this.owner.cols.addTraitController(colTrait, targetTrait); }, traitDidDetachCol(colTrait: ColTrait): void { this.owner.cols.deleteTraitController(colTrait); }, viewType: HeaderView, observesView: true, initView(headerView: HeaderView): void { const colControllers = this.owner.cols.controllers; for (const controllerId in colControllers) { const colController = colControllers[controllerId]!; const colView = colController.col.view; if (colView !== null && colView.parent === null) { const colTrait = colController.col.trait; if (colTrait !== null) { colController.col.insertView(headerView, void 0, void 0, colTrait.key); } } } }, willAttachView(headerView: HeaderView): void { this.owner.callObservers("controllerWillAttachHeaderView", headerView, this.owner); }, didDetachView(headerView: HeaderView): void { this.owner.callObservers("controllerDidDetachHeaderView", headerView, this.owner); }, insertChildView(parent: View, childView: HeaderView, targetView: View | null, key: string | undefined): void { parent.prependChild(childView, key); }, }) readonly header!: TraitViewRef<this, HeaderTrait, HeaderView>; static readonly header: MemberFastenerClass<HeaderController, "header">; getColTrait(key: string): ColTrait | null; getColTrait<R extends ColTrait>(key: string, colTraitClass: TraitClass<R>): R | null; getColTrait(key: string, colTraitClass?: TraitClass<ColTrait>): ColTrait | null { const headerTrait = this.header.trait; return headerTrait !== null ? headerTrait.getCol(key, colTraitClass!) : null; } getOrCreateColTrait(key: string): ColTrait; getOrCreateColTrait<R extends ColTrait>(key: string, colTraitConstructor: TraitConstructor<R>): R; getOrCreateColTrait(key: string, colTraitConstructor?: TraitConstructor<ColTrait>): ColTrait { const headerTrait = this.header.trait; if (headerTrait === null) { throw new Error("no header trait"); } return headerTrait.getOrCreateCol(key, colTraitConstructor!); } setColTrait(key: string, colTrait: ColTrait): void { const headerTrait = this.header.trait; if (headerTrait === null) { throw new Error("no header trait"); } headerTrait.setCol(key, colTrait); } getColView(key: string): ColView | null; getColView<V extends ColView>(key: string, colViewClass: Class<V>): V | null; getColView(key: string, colViewClass?: Class<ColView>): ColView | null { const headerView = this.header.view; return headerView !== null ? headerView.getCol(key, colViewClass!) : null; } getOrCreateColView(key: string): ColView; getOrCreateColView<V extends ColView>(key: string, colViewClass: HtmlViewClass<V>): V; getOrCreateColView(key: string, colViewClass?: HtmlViewClass<ColView>): ColView { let headerView = this.header.view; if (headerView === null) { headerView = this.header.createView(); if (headerView === null) { throw new Error("no header view"); } this.header.setView(headerView); } return headerView.getOrCreateCol(key, colViewClass!); } setColView(key: string, colView: ColView): void { let headerView = this.header.view; if (headerView === null) { headerView = this.header.createView(); if (headerView === null) { throw new Error("no header view"); } this.header.setView(headerView); } headerView.setCol(key, colView); } @TraitViewControllerSet<HeaderController, ColTrait, ColView, ColController, HeaderControllerColExt>({ implements: true, type: ColController, binds: true, observes: true, get parentView(): HeaderView | null { return this.owner.header.view; }, getTraitViewRef(colController: ColController): TraitViewRef<unknown, ColTrait, ColView> { return colController.col; }, willAttachController(colController: ColController): void { this.owner.callObservers("controllerWillAttachCol", colController, this.owner); }, didAttachController(colController: ColController): void { const colTrait = colController.col.trait; if (colTrait !== null) { this.attachColTrait(colTrait, colController); } const colView = colController.col.view; if (colView !== null) { this.attachColView(colView, colController); } }, willDetachController(colController: ColController): void { const colView = colController.col.view; if (colView !== null) { this.detachColView(colView, colController); } const colTrait = colController.col.trait; if (colTrait !== null) { this.detachColTrait(colTrait, colController); } }, didDetachController(colController: ColController): void { this.owner.callObservers("controllerDidDetachCol", colController, this.owner); }, controllerWillAttachColTrait(colTrait: ColTrait, colController: ColController): void { this.owner.callObservers("controllerWillAttachColTrait", colTrait, colController, this.owner); this.attachColTrait(colTrait, colController); }, controllerDidDetachColTrait(colTrait: ColTrait, colController: ColController): void { this.detachColTrait(colTrait, colController); this.owner.callObservers("controllerDidDetachColTrait", colTrait, colController, this.owner); }, attachColTrait(colTrait: ColTrait, colController: ColController): void { // hook }, detachColTrait(colTrait: ColTrait, colController: ColController): void { // hook }, controllerWillAttachColView(colView: ColView, colController: ColController): void { this.owner.callObservers("controllerWillAttachColView", colView, colController, this.owner); this.attachColView(colView, colController); }, controllerDidDetachColView(colView: ColView, colController: ColController): void { this.detachColView(colView, colController); this.owner.callObservers("controllerDidDetachColView", colView, colController, this.owner); }, attachColView(colView: ColView, colController: ColController): void { const colLabelView = colView.label.view; if (colLabelView !== null) { this.attachColLabelView(colLabelView, colController); } }, detachColView(colView: ColView, colController: ColController): void { const colLabelView = colView.label.view; if (colLabelView !== null) { this.detachColLabelView(colLabelView, colController); } colView.remove(); }, controllerWillSetColLayout(newColLayout: ColLayout | null, oldColLayout: ColLayout | null, colController: ColController): void { this.owner.callObservers("controllerWillSetColLayout", newColLayout, oldColLayout, colController, this.owner); }, controllerDidSetColLayout(newColLayout: ColLayout | null, oldColLayout: ColLayout | null, colController: ColController): void { this.owner.callObservers("controllerDidSetColLayout", newColLayout, oldColLayout, colController, this.owner); }, controllerWillAttachColLabelView(colLabelView: HtmlView, colController: ColController): void { this.owner.callObservers("controllerWillAttachColLabelView", colLabelView, colController, this.owner); this.attachColLabelView(colLabelView, colController); }, controllerDidDetachColLabelView(colLabelView: HtmlView, colController: ColController): void { this.detachColLabelView(colLabelView, colController); this.owner.callObservers("controllerDidDetachColLabelView", colLabelView, colController, this.owner); }, attachColLabelView(colLabelView: HtmlView, colController: ColController): void { // hook }, detachColLabelView(colLabelView: HtmlView, colController: ColController): void { // hook }, }) readonly cols!: TraitViewControllerSet<this, ColTrait, ColView, ColController>; static readonly cols: MemberFastenerClass<HeaderController, "cols">; }
the_stack
import { buildSchema, GraphQLSchema, graphqlSync, IntrospectionQuery, getIntrospectionQuery, } from 'graphql' import { JSONSchema6 } from 'json-schema' import { isEqual, cloneDeepWith } from 'lodash' type GetTodoSchemaIntrospectionResult = { schema: GraphQLSchema introspection: IntrospectionQuery } export const getTodoSchemaIntrospection = (): GetTodoSchemaIntrospectionResult => { const schema = buildSchema(` "A ToDo Object" type Todo implements Node { "A unique identifier" id: String! name: String! completed: Boolean color: Color "A required list containing colors that cannot contain nulls" requiredColors: [Color!]! "A non-required list containing colors that cannot contain nulls" optionalColors: [Color!] fieldWithOptionalArgument( optionalFilter: [String!] ): [String!] fieldWithRequiredArgument( requiredFilter: [String!]! ): [String!] nullableFieldThatReturnsListOfNonNullStrings( nonRequiredArgumentOfNullableStrings: [String] nonRequiredArgumentOfNonNullableStrings: [String!] requiredArgumentOfNullableStrings: [String]! requiredArgumentOfNonNullableStrings: [String!]! ): [String!] nullableFieldThatReturnsListOfNullableStrings: [String] } "A simpler ToDo Object" type SimpleTodo { id: String! name: String! } "A Union of Todo and SimpleTodo" union TodoUnion = Todo | SimpleTodo enum Color { "Red color" RED "Green color" GREEN } """ A type that describes ToDoInputType. Its description might not fit within the bounds of 80 width and so you want MULTILINE """ input TodoInputType { name: String! completed: Boolean color: Color=RED } "Anything with an ID can be a node" interface Node { "A unique identifier" id: String! } type Query { todo( "todo identifier" id: String! isCompleted: Boolean=false requiredNonNullStrings: [String!]! optionalNonNullStrings: [String!] requiredNullableStrings: [String]! optionalNullableStringsWithDefault: [String]=["foo"] color: Color requiredColor: Color! requiredColorWithDefault: Color! = RED colors: [Color] requiredColors: [Color]! requiredColorsNonNullable: [Color!]! requiredColorsWithDefault: [Color]! = [GREEN, RED] requiredColorsNonNullableWithDefault: [Color!]! = [GREEN, RED] ): Todo! todos: [Todo!]! node( "Node identifier" id: String! ): Node } type Mutation { update_todo(id: String!, todo: TodoInputType!): Todo create_todo(todo: TodoInputType!): Todo } `) const result = graphqlSync(schema, getIntrospectionQuery()) return { introspection: result.data as IntrospectionQuery, schema, } } export const todoSchemaAsJsonSchema: JSONSchema6 = { $schema: 'http://json-schema.org/draft-06/schema#', properties: { Query: { type: 'object', properties: { todo: { type: 'object', properties: { arguments: { type: 'object', properties: { id: { $ref: '#/definitions/String', description: 'todo identifier', }, isCompleted: { $ref: '#/definitions/Boolean', default: false }, requiredNonNullStrings: { type: 'array', items: { $ref: '#/definitions/String' }, }, optionalNonNullStrings: { type: 'array', items: { $ref: '#/definitions/String', }, }, requiredNullableStrings: { type: 'array', items: { anyOf: [{ $ref: '#/definitions/String' }, { type: 'null' }], }, }, optionalNullableStringsWithDefault: { type: 'array', items: { anyOf: [{ $ref: '#/definitions/String' }, { type: 'null' }], }, default: ['foo'], }, color: { $ref: '#/definitions/Color' }, requiredColor: { $ref: '#/definitions/Color' }, requiredColorWithDefault: { $ref: '#/definitions/Color', default: 'RED' }, colors: { type: 'array', items: { anyOf: [{ $ref: '#/definitions/Color' }, { type: 'null' }], }, }, requiredColors: { type: 'array', items: { anyOf: [{ $ref: '#/definitions/Color' }, { type: 'null' }], }, }, requiredColorsNonNullable: { type: 'array', items: { $ref: '#/definitions/Color' }, }, requiredColorsWithDefault: { type: 'array', items: { anyOf: [{ $ref: '#/definitions/Color' }, { type: 'null' }], }, default: ['GREEN', 'RED'], }, requiredColorsNonNullableWithDefault: { type: 'array', items: { $ref: '#/definitions/Color' }, default: ['GREEN', 'RED'], }, }, required: [ 'id', 'requiredNonNullStrings', 'requiredNullableStrings', 'requiredColor', 'requiredColorWithDefault', 'requiredColors', 'requiredColorsNonNullable', 'requiredColorsWithDefault', 'requiredColorsNonNullableWithDefault', ], }, return: { $ref: '#/definitions/Todo', }, }, required: [], }, todos: { type: 'object', properties: { arguments: { type: 'object', properties: {}, required: [], }, return: { type: 'array', items: { $ref: '#/definitions/Todo' }, }, }, required: [], }, node: { type: 'object', properties: { arguments: { type: 'object', properties: { id: { description: 'Node identifier', $ref: '#/definitions/String', }, }, required: ['id'], }, return: { $ref: '#/definitions/Node', }, }, required: [], }, }, // Inappropriate for individual queries to be required, despite possibly having // NON_NULL return types required: [], }, Mutation: { type: 'object', properties: { update_todo: { type: 'object', properties: { arguments: { type: 'object', properties: { id: { $ref: '#/definitions/String' }, todo: { $ref: '#/definitions/TodoInputType' }, }, required: ['id', 'todo'], }, return: { $ref: '#/definitions/Todo', }, }, required: [], }, create_todo: { type: 'object', properties: { arguments: { type: 'object', properties: { todo: { $ref: '#/definitions/TodoInputType' }, }, required: ['todo'], }, return: { $ref: '#/definitions/Todo', }, }, required: [], }, }, // Inappropriate for individual mutations to be required, despite possibly having // NON_NULL return types required: [], }, }, definitions: { Boolean: { type: 'boolean', title: 'Boolean', description: 'The `Boolean` scalar type represents `true` or `false`.', }, String: { type: 'string', title: 'String', description: 'The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.', }, Todo: { type: 'object', description: 'A ToDo Object', properties: { id: { description: 'A unique identifier', type: 'object', properties: { return: { $ref: '#/definitions/String' }, arguments: { type: 'object', properties: {}, required: [] }, }, required: [], }, name: { type: 'object', properties: { return: { $ref: '#/definitions/String' }, arguments: { type: 'object', properties: {}, required: [] }, }, required: [], }, completed: { type: 'object', properties: { return: { $ref: '#/definitions/Boolean' }, arguments: { type: 'object', properties: {}, required: [] }, }, required: [], }, color: { type: 'object', properties: { return: { $ref: '#/definitions/Color' }, arguments: { type: 'object', properties: {}, required: [] }, }, required: [], }, requiredColors: { description: 'A required list containing colors that cannot contain nulls', type: 'object', properties: { return: { type: 'array', items: { $ref: '#/definitions/Color' }, }, arguments: { type: 'object', properties: {}, required: [] }, }, required: [], }, optionalColors: { description: 'A non-required list containing colors that cannot contain nulls', type: 'object', properties: { return: { type: 'array', items: { $ref: '#/definitions/Color' }, }, arguments: { type: 'object', properties: {}, required: [] }, }, required: [], }, fieldWithOptionalArgument: { type: 'object', properties: { return: { type: 'array', items: { $ref: '#/definitions/String' }, }, arguments: { type: 'object', properties: { optionalFilter: { type: 'array', items: { $ref: '#/definitions/String' }, }, }, required: [], }, }, required: [], }, fieldWithRequiredArgument: { type: 'object', properties: { return: { type: 'array', items: { $ref: '#/definitions/String' }, }, arguments: { type: 'object', properties: { requiredFilter: { type: 'array', items: { $ref: '#/definitions/String' }, }, }, required: ['requiredFilter'], }, }, required: [], }, nullableFieldThatReturnsListOfNonNullStrings: { type: 'object', properties: { return: { type: 'array', items: { $ref: '#/definitions/String' }, }, arguments: { type: 'object', properties: { nonRequiredArgumentOfNullableStrings: { type: 'array', items: { anyOf: [{ $ref: '#/definitions/String' }, { type: 'null' }], }, }, nonRequiredArgumentOfNonNullableStrings: { type: 'array', items: { $ref: '#/definitions/String' }, }, requiredArgumentOfNullableStrings: { type: 'array', items: { anyOf: [{ $ref: '#/definitions/String' }, { type: 'null' }], }, }, requiredArgumentOfNonNullableStrings: { type: 'array', items: { $ref: '#/definitions/String' }, }, }, required: [ 'requiredArgumentOfNullableStrings', 'requiredArgumentOfNonNullableStrings', ], }, }, required: [], }, nullableFieldThatReturnsListOfNullableStrings: { type: 'object', properties: { return: { type: 'array', items: { anyOf: [{ $ref: '#/definitions/String' }, { type: 'null' }], }, }, arguments: { type: 'object', properties: {}, required: [] }, }, required: [], }, }, required: ['id', 'name', 'requiredColors'], }, SimpleTodo: { type: 'object', description: 'A simpler ToDo Object', properties: { id: { type: 'object', properties: { return: { $ref: '#/definitions/String' }, arguments: { type: 'object', properties: {}, required: [] }, }, required: [], }, name: { type: 'object', properties: { return: { $ref: '#/definitions/String' }, arguments: { type: 'object', properties: {}, required: [] }, }, required: [], }, }, required: ['id', 'name'], }, Color: { // Yes, ENUM types should be the JSON built-in "string" type type: 'string', anyOf: [ { enum: ['RED'], title: 'Red color', description: 'Red color', }, { enum: ['GREEN'], title: 'Green color', description: 'Green color', }, ], }, TodoInputType: { type: 'object', description: 'A type that describes ToDoInputType. Its description might not\nfit within the bounds of 80 width and so you want MULTILINE', properties: { name: { $ref: '#/definitions/String' }, completed: { $ref: '#/definitions/Boolean' }, color: { default: 'RED', $ref: '#/definitions/Color' }, }, required: ['name'], }, TodoUnion: { description: 'A Union of Todo and SimpleTodo', oneOf: [ { $ref: '#/definitions/Todo' }, { $ref: '#/definitions/SimpleTodo' }, ], }, Node: { type: 'object', description: 'Anything with an ID can be a node', properties: { id: { type: 'object', description: 'A unique identifier', properties: { return: { $ref: '#/definitions/String' }, arguments: { type: 'object', properties: {}, required: [] }, }, required: [], }, }, required: ['id'], }, }, } export const todoSchemaAsJsonSchemaWithoutNullableArrayItems: JSONSchema6 = cloneDeepWith( todoSchemaAsJsonSchema, (value, key, object, stack) => { // Convert the new way back to the old way if ( key === 'items' && isEqual(Object.keys(value), ['anyOf']) && value.anyOf.length === 2 && value.anyOf.find((e: any) => isEqual(e, { type: 'null' })) ) { return value.anyOf.find((e: any) => !isEqual(e, { type: 'null' })) } } )
the_stack
declare module 'amf-client-js' { /* amf-client-js */ export class ResourceNotFound { constructor(error: String) } export class AMF { static init(): Promise<void> static raml10Parser(): Raml10Parser static ramlParser(): RamlParser static raml10Generator(): Raml10Renderer static raml08Parser(): Raml08Parser static raml08Generator(): Raml08Renderer static oas20Parser(): Oas20Parser static oas20Generator(): Oas20Renderer static amfGraphParser(): parse.AmfGraphParser static amfGraphGenerator(): AmfGraphRenderer static validate(model: model.document.BaseUnit, profileName: ProfileName, messageStyle: MessageStyle, env?: client.environment.Environment): Promise<client.validate.ValidationReport> static validateResolved(model: model.document.BaseUnit, profileName: ProfileName, messageStyle: MessageStyle, env?: client.environment.Environment): Promise<client.validate.ValidationReport> static loadValidationProfile(url: string): Promise<ProfileName> static registerNamespace(alias: string, prefix: string): boolean // static registerDialect(url: string): Promise<Dialect> static resolveRaml10(unit: model.document.BaseUnit): model.document.BaseUnit static resolveRaml08(unit: model.document.BaseUnit): model.document.BaseUnit static resolveOas20(unit: model.document.BaseUnit): model.document.BaseUnit static resolveAmfGraph(unit: model.document.BaseUnit): model.document.BaseUnit static jsonPayloadParser(): JsonPayloadParser static yamlPayloadParser(): YamlPayloadParser } export class ProfileNames { static AMF: ProfileName static OAS: ProfileName static OAS3: ProfileName static RAML: ProfileName static RAML08: ProfileName } export class ProfileName { readonly profile: String readonly messageStyle: MessageStyle constructor(profile: String) } export interface MessageStyle { profileName: ProfileName } export class MessageStyles { static RAML: MessageStyle static OAS: MessageStyle static AMF: MessageStyle } export class AmfGraphRenderer extends render.Renderer { constructor() generateToBuilder<T>(unit: model.document.BaseUnit, options: render.RenderOptions, builder: org.yaml.builder.DocBuilder<T>): Promise<void> generateToBuilder<T>(unit: model.document.BaseUnit, builder: org.yaml.builder.DocBuilder<T>): Promise<void> } export class AmfGraphResolver extends resolve.Resolver {} export class Core { static init(): Promise<void> static generator(vendor: string, mediaType: string): render.Renderer static resolver(vendor: string): resolve.Resolver static parser(vendor: string, mediaType: string): parse.Parser static parser(vendor: string, mediaType: string, env: client.environment.Environment): parse.Parser static validate(model: model.document.BaseUnit, profileName: ProfileName, messageStyle?: MessageStyle): Promise<client.validate.ValidationReport> static validate(model: model.document.BaseUnit, profileName: ProfileName, messageStyle: MessageStyle, env: client.environment.Environment): Promise<client.validate.ValidationReport> static loadValidationProfile(url: string): Promise<ProfileName> static registerNamespace(alias: string, prefix: string): boolean static registerPlugin(plugin: client.plugins.ClientAMFPlugin): void static registerPayloadPlugin(plugin: client.plugins.ClientAMFPayloadValidationPlugin): void } export class JsonPayloadParser extends parse.Parser { constructor() constructor(env: client.environment.Environment) } export class JsonldRenderer extends render.Renderer { constructor() } export class Oas20Parser extends parse.Parser { constructor() constructor(env: client.environment.Environment) } export class Oas20YamlParser extends parse.Parser { constructor() constructor(env: client.environment.Environment) } export class Oas30Parser extends parse.Parser { constructor() constructor(env: client.environment.Environment) } export class Oas30YamlParser extends parse.Parser { constructor() constructor(env: client.environment.Environment) } export class Oas20Renderer extends render.Renderer {} export class Oas30Renderer extends render.Renderer {} export class Oas20Resolver extends resolve.Resolver {} export class Oas30Resolver extends resolve.Resolver {} export class Raml08Parser extends parse.Parser { constructor() constructor(env: client.environment.Environment) } export class Raml08Renderer extends render.Renderer {} export class Raml08Resolver extends resolve.Resolver {} export class Raml10Parser extends parse.Parser { constructor() constructor(env: client.environment.Environment) } export class Raml10Renderer extends render.Renderer {} export class Raml10Resolver extends resolve.Resolver {} export class RamlParser extends parse.Parser { constructor() constructor(env: client.environment.Environment) } export class VocabulariesParser extends parse.Parser { constructor() constructor(env: client.environment.Environment) } export class YamlPayloadParser extends parse.Parser { constructor() constructor(env: client.environment.Environment) } export class ValidationMode { static StrictValidationMode: ValidationMode static ScalarRelaxedValidationMode: ValidationMode } export class ResolutionPipeline { static readonly DEFAULT_PIPELINE: 'default' static readonly EDITING_PIPELINE: 'editing' static readonly COMPATIBILITY_PIPELINE: 'compatibility' } /* Not exported */ export abstract class BaseHttpResourceLoader implements resource.ResourceLoader { accepts(resource: string): boolean abstract fetch(resource: string): Promise<client.remote.Content> } export abstract class BaseFileResourceLoader implements resource.ResourceLoader { accepts(resource: string): boolean abstract fetch(resource: string): Promise<client.remote.Content> } export class JsBrowserHttpResourceLoader extends BaseHttpResourceLoader { fetch(resource: string): Promise<client.remote.Content> } export class JsServerFileResourceLoader extends BaseFileResourceLoader { fetch(resource: string): Promise<client.remote.Content> } namespace org { namespace mulesoft { namespace common { namespace io { export class LimitedStringBuffer { constructor(limit: number) length: number toString(): string } class LimitReachedException {} } } } namespace yaml { namespace builder { /* Not exported */ abstract class DocBuilder<T> { result: T isDefined: boolean list(f: (p: DocBuilder.Part) => void): T obj(f: (e: DocBuilder.Entry) => void): T doc(f: (p: DocBuilder.Part) => void): T } namespace DocBuilder { /* Not exported */ abstract class Part { } /* Not exported */ abstract class Entry { } } class JsOutputBuilder extends DocBuilder<any> { } } } } namespace client { export class DefaultEnvironment {static apply(): environment.Environment} namespace environment { export class Environment { constructor() loaders: resource.ResourceLoader[] addClientLoader(loader: resource.ResourceLoader): Environment withLoaders(loaders: resource.ResourceLoader[]): Environment withClientResolver(clientResolver: remote.ClientReferenceResolver): Environment static empty(): Environment static apply(loader: resource.ResourceLoader): Environment } } namespace remote { export class Content { stream: string url: string constructor(stream: string, url: string) constructor(stream: string, url: string, mime: string) } export interface ClientReferenceResolver { fetch(url: string): Promise<CachedReference> } export class CachedReference { constructor(url: String, content: model.document.BaseUnit, resolved: Boolean) url: string content: model.document.BaseUnit resolved: boolean } } namespace plugins { interface ClientAMFPlugin { ID: string dependencies(): ClientAMFPlugin[] init(): Promise<ClientAMFPlugin> } interface ClientAMFPayloadValidationPlugin extends ClientAMFPlugin { payloadMediaType: String[] canValidate(shape: model.domain.Shape, env: client.environment.Environment): boolean validator(shape: model.domain.Shape, env: client.environment.Environment, validationMode: ValidationMode): ClientPayloadValidator } interface ClientPayloadValidator { shape: model.domain.Shape defaultSeverity: string validationMode: ValidationMode env: client.environment.Environment validate(payload: string, mediaType: string): Promise<client.validate.ValidationReport> validate(payloadFragment: model.domain.PayloadFragment): Promise<client.validate.ValidationReport> isValid(payload: string, mediaType: string): Promise<Boolean> } export class ValidationShapeSet { constructor(candidates: ValidationCandidate[], defaultSeverity: string) candidates: ValidationCandidate[] defaultServerity: string } export class ValidationCandidate { constructor(shape: model.domain.Shape, payload: model.domain.PayloadFragment) shape: model.domain.Shape payload: model.domain.PayloadFragment } } namespace validate { export class PayloadParsingResult { constructor(fragment: model.domain.PayloadFragment, results: ValidationResult[]) fragment: model.domain.PayloadFragment results: ValidationResult[] } export class ValidationReport { constructor(conforms: boolean, model: string, profile: ProfileName, results: ValidationResult[]) conforms: boolean model: string profile: ProfileName results: ValidationResult[] } export class ValidationResult { constructor(message: string, level: string, targetNode: string, targetProperty: string, validationId: string, position: core.parser.Range, location: string) message: string level: string targetNode: string targetProperty: string validationId: string position: core.parser.Range source: any location: string } } } namespace model { /* Not exported */ interface Annotable { annotations(): Annotations } /* Not exported */ interface BaseField extends Annotable {} /* Not exported */ class Annotations { lexical(): core.parser.Range custom(): model.domain.DomainExtension[] } /* Not exported */ abstract class ValueField<T> { abstract option: T | undefined abstract value(): T is(other: T): boolean is(accepts: (t: T) => boolean): boolean isNull: boolean nonNull: boolean toString(): string abstract remove(): void } /* Not exported */ class StrField extends ValueField<string> implements BaseField { option: string | undefined annotations(): Annotations value(): string isNullOrEmpty: boolean nonEmpty: boolean remove(): void } /* Not exported */ class BoolField extends ValueField<boolean> implements BaseField { option: boolean | undefined annotations(): Annotations value(): boolean remove(): void } /* Not exported */ class IntField extends ValueField<number> implements BaseField { option: number | undefined annotations(): Annotations value(): number remove(): void } /* Not exported */ class DoubleField extends ValueField<number> implements BaseField { option: number | undefined annotations(): Annotations value(): number remove(): void } class AnyField extends ValueField<any> implements BaseField { option: any | undefined; remove(): void; value(): any; annotations(): Annotations; } namespace document { abstract class EncodesModel { encodes: domain.DomainElement withEncodes(enocdes: domain.DomainElement): this } /* Not exported */ abstract class DeclaresModel { declares: domain.DomainElement[] withDeclaredElement(declared: domain.DomainElement): this withDeclares(declares: domain.DomainElement[]): this } /* Not exported */ abstract class BaseUnit { id: string references(): BaseUnit[] raw: string | undefined location: string usage: StrField withReferences(references: BaseUnit[]): this withRaw(raw: string): this withLocation(location: string): this withUsage(usage: string): this findById(id: string): domain.DomainElement | undefined findByType(typeId: string): domain.DomainElement[] withReferenceAlias(alias: string, fullUrl: string, relativeUrl: string): this } /* Not exported */ abstract class BaseUnitWithDeclaresModel extends BaseUnit implements DeclaresModel { /* DeclaresModel methods */ declares: domain.DomainElement[] withDeclaredElement(declared: domain.DomainElement): this withDeclares(declares: domain.DomainElement[]): this } /* Not exported */ abstract class BaseUnitWithEncodesModel extends BaseUnit implements EncodesModel { /* EncodesModel methods */ encodes: domain.DomainElement withEncodes(enocdes: domain.DomainElement): this } /* Not exported */ abstract class BaseUnitWithDeclaresModelAndEncodesModel extends BaseUnit implements DeclaresModel, EncodesModel { /* DeclaresModel methods */ declares: domain.DomainElement[] withId(id: String): this withDeclaredElement(declared: domain.DomainElement): this withDeclares(declares: domain.DomainElement[]): this /* EncodesModel methods */ encodes: domain.DomainElement withEncodes(enocdes: domain.DomainElement): this } export class Document extends BaseUnitWithDeclaresModelAndEncodesModel { declares: domain.DomainElement[] encodes: domain.DomainElement withEncodes(enocdes: domain.DomainElement): this; } /* Not exported */ class Fragment extends BaseUnitWithEncodesModel {} export class ExternalFragment extends Fragment {} export class Module extends BaseUnitWithDeclaresModel {} export class Extension extends Fragment {} export class Overlay extends Fragment {} export class DocumentationItem extends Fragment {} export class NamedExample extends Fragment {} export class ResourceTypeFragment extends Fragment {} export class TraitFragment extends Fragment {} export class AnnotationTypeDeclaration extends Fragment {} export class SecuritySchemeFragment extends Fragment {} export class Dialect extends BaseUnit { name: StrField; declares: domain.DomainElement[]; encodes: domain.DomainElement; version: StrField; documents: model.domain.DocumentsModel; nameAndVersion: string withName(name: string): Dialect; withVersion(version: string): Dialect withExternals(externals: model.domain.External[]): DialectLibrary; withDocuments(documentsMapping: model.domain.DocumentsModel): Dialect } export class DialectLibrary extends BaseUnit { externals: model.domain.External[]; declares: domain.DomainElement[] nodeMappings(): model.domain.NodeMapping[]; withExternals(externals: model.domain.External[]): DialectLibrary; withNodeMappings(nodeMappings: model.domain.NodeMapping[]): DialectLibrary; } export class DialectInstance extends Document { withDefinedBy(id: string): DialectInstance definedBy(): StrField } export class Vocabulary extends BaseUnit { name: StrField description: StrField base: StrField imports: domain.VocabularyReference[] externals: domain.External[] withName(name: string): Vocabulary withBase(base: string): Vocabulary withExternals(externals: domain.External[]): Vocabulary withImports(vocabularies: domain.VocabularyReference[]): Vocabulary objectPropertyTerms(): domain.ObjectPropertyTerm[] datatypePropertyTerms(): domain.DatatypePropertyTerm[] classTerms(): domain.ClassTerm[] } } namespace domain { class AmfScalar { value: any } export class DataType extends model.document.Fragment {} /* Not exported */ abstract class DomainElement implements Annotable { customDomainProperties: DomainExtension[] extendsNode: DomainElement[] id: string position: core.parser.Range annotations(): any withCustomDomainProperties(extensions: DomainExtension[]): this withExtendsNode(extension: ParametrizedDeclaration[]): this withId(id: string): this graph(): Graph } export class Graph { types(): string[] properties(): string[] scalarByProperty(id: string): any[] getObjectByPropertyId(id: string): DomainElement[] remove(uri: string): this } export class DialectDomainElement extends DomainElement { withDefinedby(nodeMapping: NodeMapping): DialectDomainElement definedBy(): NodeMapping withInstanceTypes(types: string[]): DialectDomainElement setProperty(property: PropertyMapping, value: any): DialectDomainElement setLiteralProperty(property: string, value: any): DialectDomainElement setObjectProperty(propertyId: String, value: DialectDomainElement): DialectDomainElement setObjectCollectionProperty(propertyId: String, value: DialectDomainElement[]): DialectDomainElement getScalarByPropertyUri(propertyId: String): core.parser.Value[]; getScalarValueByPropertyUri(propertyId: String): any[]; getObjectPropertyUri(propertyId: String): DialectDomainElement[]; } export class DocumentsModel extends DomainElement { root(): DocumentMapping; withRoot(documentMapping: DocumentMapping): DocumentsModel; fragments(): DocumentMapping[]; withFragments(fragments: DocumentMapping): DocumentsModel; library(): DocumentMapping; withLibrary(library: DocumentMapping): DocumentsModel; selfEncoded(): BoolField; withSelfEncoded(selfEncoded: boolean): DocumentsModel; declarationsPath(): StrField; withDeclarationsPath(declarationsPath: string): DocumentsModel; keyProperty(): BoolField; withKeyProperty(keyProperty: boolean): DocumentsModel; } export class DocumentMapping extends DomainElement { documentName(): StrField; withDocumentName(name: String): DocumentMapping; encoded(): StrField; withEncoded(encodedNode: StrField): DocumentMapping; declaredNodes(): PublicNodeMapping[]; withDeclaredNodes(declarations: PublicNodeMapping[]): DocumentMapping; } export class PublicNodeMapping extends DomainElement { name: StrField; withName(name: string): PublicNodeMapping; mappedNode(): StrField; withMappedNode(mappedNode: string): PublicNodeMapping; } export class NodeMapping extends DomainElement implements Linkable { name: StrField; nodetypeMapping: StrField; propertiesMapping(): PropertyMapping[]; idTemplate: StrField; mergePolicy: StrField; isLink: boolean; linkLabel: StrField; linkTarget: DomainElement | undefined; linkCopy(): NodeMapping; withLinkLabel(label: string): this; withLinkTarget(target: Linkable): this; withName(name: string): NodeMapping; withNodeTypeMapping(nodeType: string): NodeMapping; withPropertiesMapping(props: string[]): NodeMapping; withIdTemplate(idTemplate: string): NodeMapping; withMergePolicy(mergePolicy: string): NodeMapping; } export class UnionNodeMapping extends DomainElement implements Linkable { isLink: boolean; linkLabel: StrField; linkTarget: DomainElement | undefined; linkCopy(): UnionNodeMapping; withLinkLabel(label: string): this; withLinkTarget(target: Linkable): this; name: StrField; withName(name: StrField): UnionNodeMapping; typeDiscriminatorName(): StrField; typeDiscriminator(): {[name:string]: string}; objectRange(): StrField[]; withObjectRange(range: string[]): UnionNodeMapping; withTypeDiscriminatorName(name: string):UnionNodeMapping; withTypeDiscriminator(typesMapping: {[name:string]: string}): UnionNodeMapping; } export class PropertyMapping extends DomainElement { withName(name: string): PropertyMapping; name(): StrField withNodePropertyMapping(propertyId: string): PropertyMapping; nodePropertyMapping(): StrField withLiteralRange(range: string): PropertyMapping; literalRange(): StrField; withObjectRange(range: string[]): PropertyMapping objectRange(): StrField[]; mapKeyProperty(): StrField; withMapKeyProperty(key: string): PropertyMapping mapValueProperty(): StrField; withMapValueProperty(value: string): PropertyMapping minCount(): IntField; withMinCount(minCount: number): IntField pattern(): StrField withPattern(pattern: string): PropertyMapping; minimum(): DoubleField; withMinimum(min: number): PropertyMapping; maximum(): DoubleField; withMaximum(max: number): PropertyMapping; allowMultiple(): BoolField; withAllowMultiple(allow: Boolean): PropertyMapping enum(): AnyField; withEnum(values: any[]): PropertyMapping; sorted(): BoolField withSorted(sorted: Boolean): PropertyMapping typeDiscriminator(): {[t:string]: string}; withTypeDiscriminator(typesMapping: {[t:string]:string} ): PropertyMapping; typeDiscriminatorName(): StrField; withTypeDiscriminatorName(name: string): PropertyMapping classification(): string; } export class ClassTerm extends DomainElement { name: StrField displayName: StrField description: StrField properties: StrField[] subClassOf: StrField[] withName(name: string): this withDisplayName(displayName: string): this withDescription(description: string): this withProperties(properties: string[]): this withSubClassOf(superClasses: string[]): this } export class VocabularyReference extends DomainElement { alias: StrField reference: StrField withAlias(alias: string): VocabularyReference withReference(reference: string): VocabularyReference } export class External extends DomainElement { alias: StrField base: StrField withAlias(alias: string): External withBase(base: string): External } export class PropertyTerm extends DomainElement { name: StrField displayName: StrField description: StrField range: StrField subPropertyOf: StrField[] withName(name: string): this withDisplayName(displayName: string): this withDescription(description: string): this withRange(range: string): this } export class ObjectPropertyTerm extends PropertyTerm {} export class DatatypePropertyTerm extends PropertyTerm {} export class CustomDomainProperty extends DomainElement implements Linkable { name: StrField displayName: StrField description: StrField domain: StrField[] schema: Shape withName(name: string): this withDisplayName(displayName: string): this withDescription(description: string): this withDomain(domain: string[]): this withSchema(schema: Shape): this /* Linkable methods */ linkTarget: DomainElement | undefined isLink: boolean linkLabel: StrField linkCopy(): Linkable withLinkTarget(target: Linkable): this withLinkLabel(label: string): this link(): CustomDomainProperty } export class ExternalDomainElement extends DomainElement { raw: StrField mediaType: StrField withRaw(raw: String): this withMediaType(mediaType: String): this } export abstract class Linkable { linkTarget: DomainElement | undefined isLink: boolean linkLabel: StrField linkCopy(): Linkable withLinkTarget(target: Linkable): this withLinkLabel(label: string): this } export class PayloadFragment extends document.Fragment { dataNode: DataNode mediaType: string constructor(scalar: model.domain.ScalarNode, mediaType: string) constructor(object: model.domain.ObjectNode, mediaType: string) constructor(array: model.domain.ArrayNode, mediaType: string) } export class Shape extends DomainElement implements Linkable { name: StrField displayName: StrField description: StrField defaultValue: DataNode defaultValueStr: StrField readOnly: BoolField writeOnly: BoolField deprecated: BoolField values: DataNode[] location: string inherits: Shape[] or: Shape[] and: Shape[] xone: Shape[] not: Shape withName(name: string): this withReadOnly(readOnly: boolean): this withWriteOnly(writeOnly: boolean): this withDeprecated(deprecated: boolean): this withDisplayName(name: string): this withDescription(description: string): this withDefaultValue(default_: DataNode): this withValues(values: DataNode[]): this withInherits(inherits: Shape[]): this withOr(subShapes: Shape[]): this withAnd(subShapes: Shape[]): this withXone(subShapes: Shape[]): this withNode(shape: Shape): this withDefaultStr(value: string): this /* Linkable methods */ linkTarget: DomainElement | undefined isLink: boolean linkLabel: StrField linkCopy(): Linkable withLinkTarget(target: Linkable): this withLinkLabel(label: string): this link(): Shape } export class PropertyShape extends Shape { path: StrField range: Shape minCount: IntField maxCount: IntField patternName: StrField withPath(path: string): this withRange(range: Shape): this withMinCount(min: number): this withMaxCount(max: number): this withPatternName(pattern: string): this } export class AnyShape extends Shape { documentation: CreativeWork xmlSerialization: XMLSerializer examples: Example[] withDocumentation(documentation: CreativeWork): this withXMLSerialization(xmlSerialization: XMLSerializer): this withExamples(examples: Example[]): this withExample(mediaType: string): Example linkCopy(): AnyShape toJsonSchema(): string validate(payload: string): Promise<client.validate.ValidationReport> validate(fragment: model.domain.PayloadFragment): Promise<client.validate.ValidationReport> isDefaultEmpty: string } export class XMLSerializer extends DomainElement { attribute: BoolField wrapped: BoolField name: StrField namespace: StrField prefix: StrField withAttribute(attribute: boolean): this; withWrapped(wrapped: boolean): this; withName(name: string): this; withNamespace(namespace: string): this; withPrefix(prefix: string): this; } export class ArrayShape extends DataArrangeShape { items: Shape withItems(items: Shape): this } export class MatrixShape extends ArrayShape { withItems(items: Shape): this } export class DataArrangeShape extends AnyShape { minItems: IntField maxItems: IntField uniqueItems: BoolField withMinItems(minItems: number): this withMaxItems(maxItems: number): this withUniqueItems(uniqueItems: boolean): this } export class CreativeWork extends DomainElement { url: StrField description: StrField title: StrField withUrl(url: string): this withTitle(title: string): this withDescription(description: string): this } export class UnionShape extends AnyShape { anyOf: Shape[] withAnyOf(anyOf: Shape[]): UnionShape } export class RecursiveShape extends Shape { fixpoint: StrField withFixPoint(shapeId: string): this } export class DataNode extends DomainElement { name: StrField withName(name: string): this } export class DomainExtension extends DomainElement { name: StrField definedBy: CustomDomainProperty extension: DataNode withName(name: string): this withDefinedBy(property: CustomDomainProperty): this withExtension(node: DataNode): this } export class AbstractDeclaration extends DomainElement implements Linkable { name: StrField description: StrField dataNode: DataNode variables: StrField[] withName(name: string): this withDescription(description: string): this withDataNode(dataNode: DataNode): this withVariables(variables: string[]): this /* Linkable methods */ linkTarget: DomainElement | undefined isLink: boolean linkLabel: StrField linkCopy(): Linkable withLinkTarget(target: Linkable): this withLinkLabel(label: string): this link(): AbstractDeclaration } export class Trait extends AbstractDeclaration {} export class ResourceType extends AbstractDeclaration {} export class ParametrizedDeclaration extends DomainElement { name: StrField target: AbstractDeclaration variables: VariableValue[] withName(name: string): this withTarget(target: AbstractDeclaration): this withVariables(variables: VariableValue[]): this } export class Variable { name: string value: DataNode } export class VariableValue extends DomainElement { name: StrField value: DataNode withName(name: string): this withValue(value: DataNode): this } export class Server extends DomainElement { url: StrField description: StrField variables: Parameter[] withUrl(url: string): this withDescription(description: string): this withVariables(variables: Parameter[]): this withVariable(name: string): Parameter } export class EndPoint extends DomainElement { name: StrField description: StrField summary: StrField path: StrField operations: Operation[] parameters: Parameter[] payloads: Payload[] servers: Server[] security: SecurityRequirement[] relativePath: string withName(name: string): this withDescription(description: string): this withSummary(summary: string): this withPath(path: string): this withOperations(operations: Operation[]): this withParameters(parameters: Parameter[]): this withPayloads(payloads: Payload[]): this withServers(servers: Server[]): this withSecurity(security: SecurityRequirement[]): this withOperation(method: string): Operation withParameter(name: string): Parameter withPayload(name: string): Payload withServer(url: string): Server } export class SecurityRequirement extends DomainElement { name: StrField schemes: ParametrizedSecurityScheme[] withName(name: string): this withSchemes(schemes: ParametrizedSecurityScheme[]): this withScheme(): ParametrizedSecurityScheme } export class ParametrizedSecurityScheme extends DomainElement { name: StrField scheme: SecurityScheme settings: Settings withName(name: string): this withScheme(scheme: SecurityScheme): this withSettings(settings: Settings): this withDefaultSettings(): Settings withOAuth1Settings(): OAuth1Settings withOAuth2Settings(): OAuth2Settings withApiKeySettings(): ApiKeySettings } export class SecurityScheme extends DomainElement implements Linkable { name: StrField type: StrField displayName: StrField description: StrField headers: Parameter[] queryParameters: Parameter[] responses: Response[] settings: Settings queryString: Shape withName(name: string): this withType(type: string): this withDisplayName(displayName: string): this withDescription(description: string): this withHeaders(headers: Parameter[]): this withQueryParameters(queryParameters: Parameter[]): this withResponses(responses: Response[]): this withSettings(settings: Settings): this withQueryString(queryString: Shape): this withHeader(name: string): Parameter withQueryParameter(name: string): Parameter withResponse(name: string): Response withDefaultSettings(): Settings withOAuth1Settings(): OAuth1Settings withOAuth2Settings(): OAuth2Settings withApiKeySettings(): ApiKeySettings withHttpSettings(): HttpSettings withOpenIdConnectSettings(): OpenIdConnectSettings /* Linkable methods */ linkTarget: DomainElement | undefined isLink: boolean linkLabel: StrField linkCopy(): Linkable withLinkTarget(target: Linkable): this withLinkLabel(label: string): this link(): SecurityScheme } export class ParametrizedResourceType extends ParametrizedDeclaration {} export class ParametrizedTrait extends ParametrizedDeclaration {} export class Parameter extends DomainElement { name: StrField description: StrField required: BoolField deprecated: BoolField allowEmptyValue: BoolField style: StrField explode: BoolField allowReserved: BoolField binding: StrField schema: Shape payloads: Payload[] examples: Example[] withName(name: string): this withDescription(description: string): this withRequired(required: boolean): this withDeprecated(deprecated: boolean): this withAllowEmptyValue(allowEmptyValue: boolean): this withStyle(style: string): this withExplode(explode: boolean): this withAllowReserved(allowReserved: boolean): this withBinding(binding: string): this withPayloads(payloads: Payload[]): this withExamples(examples: Example[]): this withSchema(schema: Shape): this withObjectSchema(name: string): NodeShape withScalarSchema(name: string): ScalarShape withPayload(mediaType: string): Payload withExample(name: string): Example } export class Example extends DomainElement implements Linkable { name: StrField displayName: StrField description: StrField value: StrField structuredValue: DataNode strict: BoolField mediaType: StrField withName(name: string): this withDisplayName(displayName: string): this withDescription(description: string): this withValue(value: string): this withStructuredValue(value: DataNode): this withStrict(strict: boolean): this withMediaType(mediaType: string): this linkCopy(): Example /* Linkable methods */ linkTarget: DomainElement | undefined isLink: boolean linkLabel: StrField linkCopy(): Linkable withLinkTarget(target: Linkable): this withLinkLabel(label: string): this link(): Example } export class FileShape extends AnyShape { fileTypes: StrField[] pattern: StrField minLength: IntField maxLength: IntField minimum: DoubleField maximum: DoubleField exclusiveMinimum: BoolField exclusiveMaximum: BoolField format: StrField multipleOf: DoubleField withFileTypes(fileTypes: string[]): this withPattern(pattern: string): this withMinLength(min: number): this withMaxLength(max: number): this withMinimum(min: number): this withMaximum(max: number): this withExclusiveMinimum(min: boolean): this withExclusiveMaximum(max: boolean): this withFormat(format: string): this withMultipleOf(multiple: number): this } export class License extends DomainElement { url: StrField name: StrField withUrl(url: string): this withName(name: string): this } export class NilShape extends AnyShape {} export class NodeShape extends AnyShape { minProperties: IntField maxProperties: IntField closed: BoolField customShapeProperties: PropertyShape[] customShapePropertyDefinitions: PropertyShape[] discriminator: StrField discriminatorValue: StrField properties: PropertyShape[] dependencies: PropertyDependencies[] withMinProperties(min: number): this withMaxProperties(max: number): this withClosed(closed: boolean): this withCustomShapeProperty(name: string): PropertyShape withCustomShapeProperties(properties: PropertyShape[]): this withCustomShapePropertyDefinition(name: string): PropertyShape withCustomShapePropertyDefinitions(properties: PropertyShape[]): this withDiscriminator(discriminator: string): this withDiscriminatorValue(value: string): this withProperties(properties: PropertyShape[]): this withProperty(name: string): PropertyShape withDependencies(dependencies: PropertyDependencies[]): this withDependency(): PropertyDependencies withInheritsObject(name: string): NodeShape withInheritsScalar(name: string): ScalarShape } export class PropertyDependencies extends DomainElement { source: StrField target: StrField[] withPropertySource(propertySource: string): this withPropertyTarget(propertyTarget: string[]): this } export class Request extends DomainElement { description: StrField required: BoolField queryParameters: Parameter[] headers: Parameter[] payloads: Payload[] queryString: Shape uriParameters: Parameter[] cookieParameters: Parameter[] withDescription(description: string): this withRequired(required: boolean): this withQueryParameters(parameters: Parameter[]): this withHeaders(headers: Parameter[]): this withPayloads(payloads: Payload[]): this withQueryString(queryString: Shape): this withUriParameters(uriParameters: Parameter[]): this withCookieParameters(cookieParameters: Parameter[]): this withQueryParameter(name: string): Parameter withHeader(name: string): Parameter withPayload(): Payload withPayload(mediaType: string): Payload withUriParameter(name: string): Parameter withCookieParameter(name: string): Parameter } export class Settings extends DomainElement { additionalProperties: DataNode withAdditionalProperties(properties: DataNode): this } export class OAuth1Settings extends Settings { requestTokenUri: StrField authorizationUri: StrField tokenCredentialsUri: StrField signatures: StrField[] withRequestTokenUri(requestTokenUri: string): this withAuthorizationUri(authorizationUri: string): this withTokenCredentialsUri(tokenCredentialsUri: string): this withSignatures(signatures: string[]): this } export class OAuth2Settings extends Settings { authorizationGrants: StrField[] flows: OAuth2Flow[] withAuthorizationGrants(grants: string[]): this withFlows(flows: OAuth2Flow[]): this } export class OAuth2Flow extends Settings { authorizationUri: StrField accessTokenUri: StrField flow: StrField refreshUri: StrField scopes: Scope[] withAuthorizationUri(uri: string): this withAccessTokenUri(token: string): this withFlow(flow: string): this withRefreshUri(refreshUri: string): this withScopes(scopes: Scope[]): this } export class ApiKeySettings extends Settings { name: StrField in: StrField withName(name: string): this withIn(in_: string): this } export class HttpSettings extends Settings { scheme: StrField bearerFormat: StrField withScheme(scheme: string): this withBearerFormat(bearerFormat: string): this } export class OpenIdConnectSettings extends Settings { url: StrField withUrl(url: string): this } export class Scope extends DomainElement { name: StrField description: StrField withName(name: string): this withDescription(description: string): this } export class Callback extends DomainElement { name: StrField expression: StrField endpoint: EndPoint withName(name: string): this withExpression(expression: string): this withEndpoint(endpoint: EndPoint): this withEndpoint(): EndPoint } export class Operation extends DomainElement { method: StrField name: StrField description: StrField deprecated: BoolField summary: StrField documentation: CreativeWork schemes: StrField[] accepts: StrField[] contentType: StrField[] request: Request requests: Request[] responses: Response[] security: SecurityRequirement[] callbacks: Callback[] servers: Server[] withMethod(method: string): this withName(name: string): this withDescription(description: string): this withDeprecated(deprecated: boolean): this withSummary(summary: string): this withDocumentation(documentation: CreativeWork): this withSchemes(schemes: string[]): this withAccepts(accepts: string[]): this withContentType(contentType: string[]): this withRequests(requests: Request[]): this withRequest(request: Request): this withResponses(responses: Response[]): this withSecurity(security: SecurityRequirement[]): this withCallbacks(callbacks: Callback[]): this withServers(servers: Server[]): this withResponse(name: string): Response withRequest(): Request withCallback(name: string): Callback withServer(name: string): Server } export class IriTemplateMapping extends DomainElement { templateVariable: StrField linkExpression: StrField withTemplateVariable(variable: string): this withLinkExpression(expression: string): this } export class TemplatedLink extends DomainElement { name: StrField description: StrField template: StrField operationId: StrField mapping: IriTemplateMapping requestBody: StrField server: Server withName(name: string): this withDescription(description: string): this withTemplate(template: string): this withOperationId(operationId: string): this withMapping(mapping: IriTemplateMapping): this withRequestBody(requestBody: string): this withServer(server: Server): this } export class Response extends DomainElement { name: StrField description: StrField statusCode: StrField headers: Parameter[] payloads: Payload[] examples: Example[] links: TemplatedLink[] withName(name: string): this withDescription(description: string): this withStatusCode(statusCode: string): this withHeaders(headers: Parameter[]): this withPayloads(payloads: Payload[]): this withExamples(examples: Example[]): this withLinks(links: TemplatedLink[]): this withHeader(name: string): Parameter withPayload(): Payload withPayload(mediaType: string): Payload } export class Organization extends DomainElement { url: StrField name: StrField email: StrField withUrl(url: string): this withName(name: string): this withEmail(email: string): this } export class Encoding extends DomainElement { propertyName: StrField contentType: StrField headers: Parameter[] style: StrField explode: BoolField allowReserved: BoolField withPropertyName(propertyName: string): this withContentType(contentType: string): this withHeaders(headers: Parameter[]): this withStyle(style: string): this withExplode(explode: boolean): this withAllowReserved(allowReserved: boolean): this withHeader(name: string): Parameter } export class Payload extends DomainElement { name: StrField mediaType: StrField schema: Shape examples: Example[] encoding: Encoding[] withName(name: string): this withMediaType(mediaType: string): this withSchema(schema: Shape): this withExamples(examples: Example[]): this withEncoding(encoding: Encoding[]): this withObjectSchema(name: string): NodeShape withScalarSchema(name: string): ScalarShape withExample(name: string): Example withEncoding(name: string): Encoding } export class ScalarShape extends AnyShape { dataType: StrField pattern: StrField minLength: IntField maxLength: IntField minimum: DoubleField maximum: DoubleField exclusiveMinimum: BoolField exclusiveMaximum: BoolField format: StrField multipleOf: DoubleField withDataType(dataType: string): this withPattern(pattern: string): this withMinLength(min: number): this withMaxLength(max: number): this withMinimum(min: number): this withMaximum(max: number): this withExclusiveMinimum(min: boolean): this withExclusiveMaximum(max: boolean): this withFormat(format: string): this withMultipleOf(multiple: number): this linkCopy(): ScalarShape } export class SchemaShape extends AnyShape { mediaType: StrField raw: StrField withMediatype(mediaType: string): this withRaw(text: string): this } export class TupleShape extends DataArrangeShape { items: Shape[] withItems(items: Shape[]): this additionalItems: BoolField withAdditionalItems(additionalItems: boolean): this } export class ObjectNode extends DataNode { properties: { [key: string]: DataNode } addProperty(property: string, node: DataNode): this } export class ScalarNode extends DataNode { constructor() constructor(value: string, dataType: string) value: StrField dataType: StrField toString(): string static build(value: string, dataType: string): ScalarNode } export class ArrayNode extends DataNode { members: DataNode[] addMember(member: DataNode): this } abstract class Api extends DomainElement { name: StrField description: StrField identifier: StrField schemes: StrField[] endPoints: EndPoint[] accepts: StrField[] contentType: StrField[] version: StrField termsOfService: StrField provider: Organization license: License documentations: CreativeWork[] servers: Server[] security: SecurityRequirement[] withDocumentationTitle(title: string): CreativeWork withDocumentationUrl(url: string): CreativeWork withEndPoint(path: string): EndPoint withServer(url: string): Server withDefaultServer(url: string): Server } export class WebApi extends Api { withName(name: string): this withDescription(description: string): this withSchemes(schemes: string[]): this withEndPoints(endPoints: EndPoint[]): this withAccepts(accepts: string[]): this withContentType(contentType: string[]): this withVersion(version: string): this withTermsOfService(terms: string): this withProvider(provider: Organization): this withLicense(license: License): this withDocumentation(documentations: CreativeWork[]): this withServers(servers: Server[]): this withSecurity(security: SecurityRequirement[]): this } export class AsyncApi extends Api { withName(name: string): this withDescription(description: string): this withSchemes(schemes: string[]): this withEndPoints(endPoints: EndPoint[]): this withAccepts(accepts: string[]): this withContentType(contentType: string[]): this withVersion(version: string): this withTermsOfService(terms: string): this withProvider(provider: Organization): this withLicense(license: License): this withDocumentation(documentations: CreativeWork[]): this withServers(servers: Server[]): this withSecurity(security: SecurityRequirement[]): this } } } namespace plugins { namespace document { export class WebApi { static register(): any static validatePayload(shape: model.domain.Shape, payload: model.domain.DataNode): Promise<client.validate.ValidationReport> } export class Vocabularies { static register(): any } } namespace features { export class AMFValidation { static register(): any } export class AMFCustomValidation { static register(): any } } } namespace render { export class RenderOptions { withCompactedEmission: RenderOptions withoutCompactedEmission: RenderOptions isWithCompactedEmission: boolean withSourceMaps: RenderOptions withoutSourceMaps: RenderOptions isWithSourceMaps: boolean withCompactUris: RenderOptions withoutCompactUris: RenderOptions isWithCompactUris: boolean withPrettyPrint: RenderOptions withoutPrettyPrint: RenderOptions isPrettyPrint: boolean withRawSourceMaps : RenderOptions withoutRawSourceMaps : RenderOptions isRawSourceMaps : boolean withValidation : RenderOptions withoutValidation : RenderOptions isValidation : boolean withNodeIds : RenderOptions withoutNodeIds : RenderOptions isNodeIds : boolean withAmfJsonLdSerialization : RenderOptions withoutAmfJsonLdSerialization : RenderOptions isAmfJsonLdSerialization : boolean withFlattenedJsonLd : RenderOptions withoutFlattenedJsonLd : RenderOptions isFlattenedJsonLd : boolean static apply(): RenderOptions } /* Not exported */ class Renderer { constructor(vendor: string, mediaType: string) generateFile(unit: model.document.BaseUnit, url: string, handler: handler.FileHandler): void generateFile(unit: model.document.BaseUnit, url: string, options: RenderOptions, handler: handler.FileHandler): void generateString(unit: model.document.BaseUnit, handler: handler.JsHandler<string>): void generateString(unit: model.document.BaseUnit, options: RenderOptions, handler: handler.JsHandler<String>): void generateFile(unit: model.document.BaseUnit, url: string): Promise<void> generateFile(unit: model.document.BaseUnit, url: string, options: RenderOptions): Promise<void> generateString(unit: model.document.BaseUnit): Promise<string> generateString(unit: model.document.BaseUnit, options: RenderOptions): Promise<string> generateToWriter(unit: model.document.BaseUnit, buffer: org.mulesoft.common.io.LimitedStringBuffer): Promise<void> generateToWriter(unit: model.document.BaseUnit, options: RenderOptions, buffer: org.mulesoft.common.io.LimitedStringBuffer): Promise<void> } } /* Not exported */ namespace handler { /* Not exported */ interface JsHandler<T> { success(t: T): void; error(e: any): void; } /* Not exported */ interface FileHandler { success(): void; error(e: any): void; } } /* Not exported */ namespace parse { class Parser { constructor(vendor: string, mediaType: string) constructor(vendor: string, mediaType: string, env: any) parseFile(url: string, handler: handler.JsHandler<model.document.BaseUnit>): void parseString(stream: string, handler: handler.JsHandler<model.document.BaseUnit>): void parseFileAsync(url: string): Promise<model.document.BaseUnit> parseFileAsync(url: string, options: parser.ParsingOptions): Promise<model.document.BaseUnit> parseStringAsync(url: string, stream: string): Promise<model.document.BaseUnit> parseStringAsync(stream: string): Promise<model.document.BaseUnit> parseStringAsync(stream: string, options: parser.ParsingOptions): Promise<model.document.BaseUnit> parseStringAsync(url: string, stream: string, options: parser.ParsingOptions): Promise<model.document.BaseUnit> reportValidation(profileName: string, messageStyle: string): Promise<client.validate.ValidationReport> reportCustomValidation(profileName: string, customProfilePath: string): Promise<client.validate.ValidationReport> } export class AmfGraphParser extends parse.Parser { constructor() constructor(env: client.environment.Environment) } } /* Not exported */ namespace resolve { /* Not exported */ class Resolver { constructor(vendor?: string) resolve(unit: model.document.BaseUnit): model.document.BaseUnit resolve(unit: model.document.BaseUnit, pipeline: string): model.document.BaseUnit } } /* Not exported */ namespace resource { /* Not exported */ interface ResourceLoader { fetch(resource: string): Promise<client.remote.Content> accepts(resource: string): boolean } } namespace core { export class Vendor { static RAML: Vendor static RAML08: Vendor static RAML10: Vendor static OAS: Vendor static OAS20: Vendor static OAS30: Vendor static AMF: Vendor static PAYLOAD: Vendor static AML: Vendor } namespace parser { class Position { constructor(line: number, column: number) line: number column: number } class Range { constructor(start: core.parser.Position, end: core.parser.Position) start: core.parser.Position end: core.parser.Position toString(): string } class Value { value: model.domain.AmfScalar } } namespace validation { export class SeverityLevels { static readonly WARNING: 'Warning' static readonly INFO: 'Info' static readonly VIOLATION: 'Violation' } } } namespace parser { export class ParsingOptions { withoutAmfJsonLdSerialization: ParsingOptions; withAmfJsonLdSerialization: ParsingOptions; withBaseUnitUrl(baseUnit: string): ParsingOptions; withoutBaseUnitUrl(): ParsingOptions; setMaxYamlReferences(value: number): ParsingOptions; isAmfJsonLdSerilization: boolean; definedBaseUrl: String|undefined; getMaxYamlReferences: number|undefined; } } }
the_stack
import { describe, it, expect } from "@jest/globals"; import { NamedNode } from "@rdfjs/types"; import { DataFactory } from "n3"; import { createThing, getThing, getThingAll, setThing } from "../thing/thing"; import { addAgent, addNoneOfRuleUrl, addGroup, addAnyOfRuleUrl, addAllOfRuleUrl, createRule, getAgentAll, getNoneOfRuleUrlAll, getGroupAll, getAnyOfRuleUrlAll, getAllOfRuleUrlAll, removeNoneOfRuleUrl, removeAnyOfRuleUrl, removeAllOfRuleUrl, getRule, hasAuthenticated, hasPublic, removeAgent, removeGroup, Rule, setAgent, setAuthenticated, setNoneOfRuleUrl, setGroup, setAnyOfRuleUrl, setPublic, setAllOfRuleUrl, getRuleAll, setRule, hasCreator, setCreator, ruleAsMarkdown, removeRule, getClientAll, setClient, addClient, removeClient, hasAnyClient, setAnyClient, removePublic, removeAuthenticated, removeCreator, removeAnyClient, getResourceRule, getResourceRuleAll, removeResourceRule, setResourceRule, createResourceRuleFor, } from "./rule"; import { Policy } from "./policy"; import { createSolidDataset } from "../resource/solidDataset"; import { setUrl } from "../thing/set"; import { Thing, ThingPersisted, Url } from "../interfaces"; import { acp, rdf } from "../constants"; import { getIri, getIriAll, getSourceUrl, mockSolidDatasetFrom, } from "../index"; import { addMockAcrTo, mockAcrFor } from "./mock"; import { internal_getAcr } from "./control.internal"; import { addUrl } from "../thing/add"; import { getUrl, getUrlAll } from "../thing/get"; // Vocabulary terms const ACP_ANY = DataFactory.namedNode("http://www.w3.org/ns/solid/acp#anyOf"); const ACP_ALL = DataFactory.namedNode("http://www.w3.org/ns/solid/acp#allOf"); const ACP_NONE = DataFactory.namedNode("http://www.w3.org/ns/solid/acp#noneOf"); const RDF_TYPE = DataFactory.namedNode( "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" ); const ACP_RULE = DataFactory.namedNode("http://www.w3.org/ns/solid/acp#Rule"); const ACP_AGENT = DataFactory.namedNode("http://www.w3.org/ns/solid/acp#agent"); const ACP_GROUP = DataFactory.namedNode("http://www.w3.org/ns/solid/acp#group"); const ACP_CLIENT = DataFactory.namedNode( "http://www.w3.org/ns/solid/acp#client" ); const ACP_PUBLIC = DataFactory.namedNode( "http://www.w3.org/ns/solid/acp#PublicAgent" ); const ACP_AUTHENTICATED = DataFactory.namedNode( "http://www.w3.org/ns/solid/acp#AuthenticatedAgent" ); const ACP_CREATOR = DataFactory.namedNode( "http://www.w3.org/ns/solid/acp#CreatorAgent" ); const SOLID_PUBLIC_CLIENT = DataFactory.namedNode( "http://www.w3.org/ns/solid/terms#PublicOidcClient" ); // Test data const MOCKED_POLICY_IRI = DataFactory.namedNode( "https://some.pod/policy-resource#policy" ); const MOCKED_RULE_IRI = DataFactory.namedNode( "https://some.pod/rule-resource#a-rule" ); const OTHER_MOCKED_RULE_IRI = DataFactory.namedNode( "https://some.pod/rule-resource#another-rule" ); const ALLOF_RULE_IRI = DataFactory.namedNode( "https://some.pod/rule-resource#allOf-rule" ); const ANYOF_RULE_IRI = DataFactory.namedNode( "https://some.pod/rule-resource#anyOf-rule" ); const NONEOF_RULE_IRI = DataFactory.namedNode( "https://some.pod/rule-resource#noneOf-rule" ); const MOCK_WEBID_ME = DataFactory.namedNode("https://my.pod/profile#me"); const MOCK_WEBID_YOU = DataFactory.namedNode("https://your.pod/profile#you"); const MOCK_GROUP_IRI = DataFactory.namedNode("https://my.pod/group#a-group"); const MOCK_GROUP_OTHER_IRI = DataFactory.namedNode( "https://my.pod/group#another-group" ); const MOCK_CLIENT_WEBID_1 = DataFactory.namedNode( "https://my.app/registration#it" ); const MOCK_CLIENT_WEBID_2 = DataFactory.namedNode( "https://your.app/registration#it" ); const addAllObjects = ( thing: ThingPersisted, predicate: NamedNode, objects: Url[] ): ThingPersisted => { return objects.reduce((thingAcc, object) => { return addUrl(thingAcc, predicate, object); }, thing); }; const addAllThingObjects = ( thing: ThingPersisted, predicate: NamedNode, objects: Thing[] ): ThingPersisted => { return objects.reduce((thingAcc, object) => { return addUrl(thingAcc, predicate, object); }, thing); }; const mockRule = ( url: Url, content?: { agents?: Url[]; groups?: Url[]; public?: boolean; authenticated?: boolean; creator?: boolean; clients?: Url[]; publicClient?: boolean; } ): Rule => { let mockedRule = createThing({ url: url.value, }); mockedRule = addUrl(mockedRule, RDF_TYPE, ACP_RULE); if (content?.agents) { mockedRule = addAllObjects(mockedRule, ACP_AGENT, content.agents); } if (content?.groups) { mockedRule = addAllObjects(mockedRule, ACP_GROUP, content.groups); } if (content?.clients) { mockedRule = addAllObjects(mockedRule, ACP_CLIENT, content.clients); } if (content?.public) { mockedRule = addUrl(mockedRule, ACP_AGENT, ACP_PUBLIC); } if (content?.authenticated) { mockedRule = addUrl(mockedRule, ACP_AGENT, ACP_AUTHENTICATED); } if (content?.creator) { mockedRule = addUrl(mockedRule, ACP_AGENT, ACP_CREATOR); } if (content?.publicClient) { mockedRule = addUrl(mockedRule, ACP_CLIENT, SOLID_PUBLIC_CLIENT); } return mockedRule; }; const mockPolicy = ( url: NamedNode, rules?: { allOf?: Rule[]; anyOf?: Rule[]; noneOf?: Rule[] } ): Policy => { let mockPolicy = createThing({ url: url.value }); if (rules?.noneOf) { mockPolicy = addAllThingObjects(mockPolicy, ACP_NONE, rules.noneOf); } if (rules?.anyOf) { mockPolicy = addAllThingObjects(mockPolicy, ACP_ANY, rules.anyOf); } if (rules?.allOf) { mockPolicy = addAllThingObjects(mockPolicy, ACP_ALL, rules.allOf); } return mockPolicy; }; describe("addNoneOfRuleUrl", () => { it("adds the rule in the noneOf rules of the policy", () => { const myPolicy = addNoneOfRuleUrl( mockPolicy(MOCKED_POLICY_IRI), mockRule(MOCKED_RULE_IRI) ); expect(getUrlAll(myPolicy, ACP_NONE)).toContain(MOCKED_RULE_IRI.value); }); it("does not remove the existing noneOf rules", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockRule(OTHER_MOCKED_RULE_IRI)], }); const myPolicy = addNoneOfRuleUrl(mockedPolicy, mockRule(MOCKED_RULE_IRI)); expect(getUrlAll(myPolicy, ACP_NONE)).toContain( OTHER_MOCKED_RULE_IRI.value ); }); it("does not change the existing allOf and anyOf rules", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { anyOf: [mockRule(ANYOF_RULE_IRI)], allOf: [mockRule(ALLOF_RULE_IRI)], }); const myPolicy = addNoneOfRuleUrl(mockedPolicy, mockRule(NONEOF_RULE_IRI)); expect(getUrlAll(myPolicy, ACP_ALL)).toContain(ALLOF_RULE_IRI.value); expect(getUrlAll(myPolicy, ACP_ANY)).toContain(ANYOF_RULE_IRI.value); }); it("does not change the input policy", () => { const myPolicy = mockPolicy(MOCKED_POLICY_IRI); const updatedPolicy = addNoneOfRuleUrl(myPolicy, mockRule(MOCKED_RULE_IRI)); expect(myPolicy).not.toStrictEqual(updatedPolicy); }); }); describe("addAnyOfRuleUrl", () => { it("adds the rule in the anyOf rules of the policy", () => { const myPolicy = addAnyOfRuleUrl( mockPolicy(MOCKED_POLICY_IRI), mockRule(MOCKED_RULE_IRI) ); expect(getUrlAll(myPolicy, ACP_ANY)).toContain(MOCKED_RULE_IRI.value); }); it("does not remove the existing anyOf rules", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { anyOf: [mockRule(OTHER_MOCKED_RULE_IRI)], }); const myPolicy = addAnyOfRuleUrl(mockedPolicy, mockRule(MOCKED_POLICY_IRI)); expect(getUrlAll(myPolicy, ACP_ANY)).toContain(OTHER_MOCKED_RULE_IRI.value); }); it("does not change the existing allOf and noneOf rules", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockRule(NONEOF_RULE_IRI)], allOf: [mockRule(ALLOF_RULE_IRI)], }); const myPolicy = addAnyOfRuleUrl(mockedPolicy, mockRule(ANYOF_RULE_IRI)); expect(getUrlAll(myPolicy, ACP_ALL)).toContain(ALLOF_RULE_IRI.value); expect(getUrlAll(myPolicy, ACP_NONE)).toContain(NONEOF_RULE_IRI.value); }); it("does not change the input policy", () => { const myPolicy = mockPolicy(MOCKED_POLICY_IRI); const updatedPolicy = addAnyOfRuleUrl(myPolicy, mockRule(MOCKED_RULE_IRI)); expect(myPolicy).not.toStrictEqual(updatedPolicy); }); }); describe("addAllOfRule", () => { it("adds the rule in the allOf rules of the policy", () => { const myPolicy = addAllOfRuleUrl( mockPolicy(MOCKED_POLICY_IRI), mockRule(MOCKED_RULE_IRI) ); expect(getUrlAll(myPolicy, ACP_ALL)).toContain(MOCKED_RULE_IRI.value); }); it("does not remove the existing allOf rules", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { allOf: [mockRule(OTHER_MOCKED_RULE_IRI)], }); const myPolicy = addAllOfRuleUrl(mockedPolicy, mockRule(MOCKED_RULE_IRI)); expect(getUrlAll(myPolicy, ACP_ALL)).toContain(OTHER_MOCKED_RULE_IRI.value); }); it("does not change the existing anyOf and noneOf rules", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockRule(NONEOF_RULE_IRI)], anyOf: [mockRule(ANYOF_RULE_IRI)], }); const myPolicy = addAllOfRuleUrl(mockedPolicy, mockRule(ANYOF_RULE_IRI)); expect(getUrlAll(myPolicy, ACP_ANY)).toContain(ANYOF_RULE_IRI.value); expect(getUrlAll(myPolicy, ACP_NONE)).toContain(NONEOF_RULE_IRI.value); }); it("does not change the input policy", () => { const myPolicy = mockPolicy(MOCKED_POLICY_IRI); const updatedPolicy = addAnyOfRuleUrl(myPolicy, mockRule(MOCKED_RULE_IRI)); expect(myPolicy).not.toStrictEqual(updatedPolicy); }); }); describe("setNoneOfRuleUrl", () => { it("sets the provided rules as the noneOf rules for the policy", () => { const myPolicy = setNoneOfRuleUrl( mockPolicy(MOCKED_POLICY_IRI), mockRule(MOCKED_RULE_IRI) ); expect(getUrlAll(myPolicy, ACP_NONE)).toContain(MOCKED_RULE_IRI.value); }); it("removes any previous noneOf rules for on the policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockRule(OTHER_MOCKED_RULE_IRI)], }); const myPolicy = setNoneOfRuleUrl(mockedPolicy, mockRule(MOCKED_RULE_IRI)); expect(getUrlAll(myPolicy, ACP_NONE)).not.toContain( OTHER_MOCKED_RULE_IRI.value ); }); it("does not change the existing anyOf and allOf rules on the policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { anyOf: [mockRule(ANYOF_RULE_IRI)], allOf: [mockRule(ALLOF_RULE_IRI)], }); const myPolicy = setNoneOfRuleUrl(mockedPolicy, mockRule(NONEOF_RULE_IRI)); expect(getUrlAll(myPolicy, ACP_ALL)).toContain(ALLOF_RULE_IRI.value); expect(getUrlAll(myPolicy, ACP_ANY)).toContain(ANYOF_RULE_IRI.value); }); it("does not change the input policy", () => { const myPolicy = mockPolicy(MOCKED_POLICY_IRI); const updatedPolicy = setNoneOfRuleUrl(myPolicy, mockRule(MOCKED_RULE_IRI)); expect(myPolicy).not.toStrictEqual(updatedPolicy); }); }); describe("setAnyOfRuleUrl", () => { it("sets the provided rules as the anyOf rules for the policy", () => { const myPolicy = setAnyOfRuleUrl( mockPolicy(MOCKED_POLICY_IRI), mockRule(MOCKED_RULE_IRI) ); expect(getUrlAll(myPolicy, ACP_ANY)).toContain(MOCKED_RULE_IRI.value); }); it("removes any previous anyOf rules for on the policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { anyOf: [mockRule(OTHER_MOCKED_RULE_IRI)], }); const myPolicy = setAnyOfRuleUrl(mockedPolicy, mockRule(MOCKED_RULE_IRI)); expect(getUrlAll(myPolicy, ACP_ANY)).not.toContain( OTHER_MOCKED_RULE_IRI.value ); }); it("does not change the existing noneOf and allOf rules on the policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockRule(NONEOF_RULE_IRI)], allOf: [mockRule(ALLOF_RULE_IRI)], }); const myPolicy = setAnyOfRuleUrl(mockedPolicy, mockRule(ANYOF_RULE_IRI)); expect(getUrlAll(myPolicy, ACP_ALL)).toContain(ALLOF_RULE_IRI.value); expect(getUrlAll(myPolicy, ACP_NONE)).toContain(NONEOF_RULE_IRI.value); }); it("does not change the input policy", () => { const myPolicy = mockPolicy(MOCKED_POLICY_IRI); const updatedPolicy = setAnyOfRuleUrl(myPolicy, mockRule(MOCKED_RULE_IRI)); expect(myPolicy).not.toStrictEqual(updatedPolicy); }); }); describe("setAllOfRuleUrl", () => { it("sets the provided rules as the allOf rules for the policy", () => { const myPolicy = setAllOfRuleUrl( mockPolicy(MOCKED_POLICY_IRI), mockRule(MOCKED_RULE_IRI) ); expect(getUrlAll(myPolicy, ACP_ALL)).toContain(MOCKED_RULE_IRI.value); }); it("removes any previous allOf rules for on the policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { allOf: [mockRule(OTHER_MOCKED_RULE_IRI)], }); const myPolicy = setAllOfRuleUrl(mockedPolicy, mockRule(MOCKED_RULE_IRI)); expect(getUrlAll(myPolicy, ACP_ALL)).not.toContain( OTHER_MOCKED_RULE_IRI.value ); }); it("does not change the existing noneOf and anyOf rules on the policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockRule(NONEOF_RULE_IRI)], anyOf: [mockRule(ANYOF_RULE_IRI)], }); const myPolicy = setAllOfRuleUrl(mockedPolicy, mockRule(ALLOF_RULE_IRI)); expect(getUrlAll(myPolicy, ACP_ANY)).toContain(ANYOF_RULE_IRI.value); expect(getUrlAll(myPolicy, ACP_NONE)).toContain(NONEOF_RULE_IRI.value); }); it("does not change the input policy", () => { const myPolicy = mockPolicy(MOCKED_POLICY_IRI); const updatedPolicy = setAllOfRuleUrl(myPolicy, mockRule(MOCKED_RULE_IRI)); expect(myPolicy).not.toStrictEqual(updatedPolicy); }); }); describe("getNoneOfRuleurlAll", () => { it("returns all the noneOf rules for the given policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockRule(MOCKED_RULE_IRI), mockRule(OTHER_MOCKED_RULE_IRI)], }); const noneOfRules = getNoneOfRuleUrlAll(mockedPolicy); expect(noneOfRules).toContain(MOCKED_RULE_IRI.value); expect(noneOfRules).toContain(OTHER_MOCKED_RULE_IRI.value); expect(noneOfRules).toHaveLength(2); }); it("returns only the noneOf rules for the given policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockRule(NONEOF_RULE_IRI)], anyOf: [mockRule(ANYOF_RULE_IRI)], allOf: [mockRule(ALLOF_RULE_IRI)], }); const noneOfRules = getNoneOfRuleUrlAll(mockedPolicy); expect(noneOfRules).not.toContain(ANYOF_RULE_IRI.value); expect(noneOfRules).not.toContain(ALLOF_RULE_IRI.value); expect(noneOfRules).toHaveLength(1); }); }); describe("getAnyOfRulesOnPolicyAll", () => { it("returns all the anyOf rules for the given policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { anyOf: [mockRule(MOCKED_RULE_IRI), mockRule(OTHER_MOCKED_RULE_IRI)], }); const anyOfRules = getAnyOfRuleUrlAll(mockedPolicy); expect(anyOfRules).toContain(MOCKED_RULE_IRI.value); expect(anyOfRules).toContain(OTHER_MOCKED_RULE_IRI.value); expect(anyOfRules).toHaveLength(2); }); it("returns only the anyOf rules for the given policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockRule(NONEOF_RULE_IRI)], anyOf: [mockRule(ANYOF_RULE_IRI)], allOf: [mockRule(ALLOF_RULE_IRI)], }); const anyOfRules = getAnyOfRuleUrlAll(mockedPolicy); expect(anyOfRules).not.toContain(NONEOF_RULE_IRI.value); expect(anyOfRules).not.toContain(ALLOF_RULE_IRI.value); expect(anyOfRules).toHaveLength(1); }); }); describe("getAllOfRulesOnPolicyAll", () => { it("returns all the allOf rules for the given policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { allOf: [mockRule(MOCKED_RULE_IRI), mockRule(OTHER_MOCKED_RULE_IRI)], }); const allOfRules = getAllOfRuleUrlAll(mockedPolicy); expect(allOfRules).toContain(MOCKED_RULE_IRI.value); expect(allOfRules).toContain(OTHER_MOCKED_RULE_IRI.value); expect(allOfRules).toHaveLength(2); }); it("returns only the allOf rules for the given policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockRule(NONEOF_RULE_IRI)], anyOf: [mockRule(ANYOF_RULE_IRI)], allOf: [mockRule(ALLOF_RULE_IRI)], }); const allOfRules = getAllOfRuleUrlAll(mockedPolicy); expect(allOfRules).not.toContain(NONEOF_RULE_IRI.value); expect(allOfRules).not.toContain(ANYOF_RULE_IRI.value); expect(allOfRules).toHaveLength(1); }); }); describe("removeAllOfRule", () => { it("removes the rule from the allOf rules for the given policy", () => { const mockedRule = mockRule(MOCKED_RULE_IRI); const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { allOf: [mockedRule], }); const result = removeAllOfRuleUrl(mockedPolicy, mockedRule); expect(getUrlAll(result, ACP_ALL)).not.toContain(MOCKED_RULE_IRI.value); }); it("does not remove the rule from the anyOf/noneOf rules for the given policy", () => { const mockedRule = mockRule(MOCKED_RULE_IRI); const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { anyOf: [mockedRule], noneOf: [mockedRule], }); const result = removeAllOfRuleUrl(mockedPolicy, mockedRule); expect(getUrlAll(result, ACP_ANY)).toContain(MOCKED_RULE_IRI.value); expect(getUrlAll(result, ACP_NONE)).toContain(MOCKED_RULE_IRI.value); }); }); describe("removeAnyOfRuleUrl", () => { it("removes the rule from the allOf rules for the given policy", () => { const mockedRule = mockRule(MOCKED_RULE_IRI); const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { anyOf: [mockedRule], }); const result = removeAnyOfRuleUrl(mockedPolicy, mockedRule); expect(getUrlAll(result, ACP_ANY)).not.toContain(MOCKED_RULE_IRI.value); }); it("does not remove the rule from the allOf/noneOf rules for the given policy", () => { const mockedRule = mockRule(MOCKED_RULE_IRI); const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { allOf: [mockedRule], noneOf: [mockedRule], }); const result = removeAnyOfRuleUrl(mockedPolicy, mockedRule); expect(getUrlAll(result, ACP_ALL)).toContain(MOCKED_RULE_IRI.value); expect(getUrlAll(result, ACP_NONE)).toContain(MOCKED_RULE_IRI.value); }); }); describe("removeNoneOfRuleUrl", () => { it("removes the rule from the noneOf rules for the given policy", () => { const mockedRule = mockRule(MOCKED_RULE_IRI); const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockedRule], }); const result = removeNoneOfRuleUrl(mockedPolicy, mockedRule); expect(getUrlAll(result, ACP_NONE)).not.toContain(MOCKED_RULE_IRI.value); }); it("does not remove the rule from the allOf/anyOf rules for the given policy", () => { const mockedRule = mockRule(MOCKED_RULE_IRI); const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { allOf: [mockedRule], anyOf: [mockedRule], }); const result = removeNoneOfRuleUrl(mockedPolicy, mockedRule); expect(getUrlAll(result, ACP_ALL)).toContain(MOCKED_RULE_IRI.value); expect(getUrlAll(result, ACP_ANY)).toContain(MOCKED_RULE_IRI.value); }); }); describe("createRule", () => { it("returns a acp:Rule", () => { const myRule = createRule(MOCKED_RULE_IRI.value); expect(getUrl(myRule, RDF_TYPE)).toBe(ACP_RULE.value); }); it("returns an **empty** rule", () => { const myRule = createRule("https://my.pod/rule-resource#rule"); // The rule should only contain a type triple. expect(Object.keys(myRule.predicates)).toHaveLength(1); }); }); describe("createResourceRuleFor", () => { it("returns a acp:Rule", () => { const mockedAcr = mockAcrFor("https://some.pod/resource"); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const myRule = createResourceRuleFor(mockedResourceWithAcr, "myRule"); expect(getIri(myRule, RDF_TYPE)).toBe(ACP_RULE.value); }); it("returns an **empty** rule", () => { const mockedAcr = mockAcrFor("https://some.pod/resource"); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const myRule = createResourceRuleFor(mockedResourceWithAcr, "myRule"); // The rule should only contain a type triple. expect(Object.keys(myRule.predicates)).toHaveLength(1); }); }); describe("getRule", () => { it("returns the rule with a matching IRI", () => { const rule = mockRule(MOCKED_RULE_IRI); const dataset = setThing(createSolidDataset(), rule); const result = getRule(dataset, MOCKED_RULE_IRI.value); expect(result).not.toBeNull(); }); it("does not return a Thing with a matching IRI but the wrong type", () => { const notARule = createThing({ url: "https://my.pod/rule-resource#not-a-rule", }); const dataset = setThing( createSolidDataset(), setUrl(notARule, RDF_TYPE, "http://example.org/ns#NotRuleType") ); const result = getRule(dataset, "https://my.pod/rule-resource#not-a-rule"); expect(result).toBeNull(); }); it("does not return a rule with a mismatching IRI", () => { const rule = mockRule(MOCKED_RULE_IRI); const dataset = setThing(createSolidDataset(), rule); const result = getRule(dataset, OTHER_MOCKED_RULE_IRI); expect(result).toBeNull(); }); }); describe("getResourceRule", () => { it("returns the rule with a matching name", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedRule = createThing({ url: `${getSourceUrl(mockedAcr)}#rule`, }); mockedRule = setUrl(mockedRule, rdf.type, acp.Rule); mockedAcr = setThing(mockedAcr, mockedRule); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const result = getResourceRule(mockedResourceWithAcr, "rule"); expect(result).not.toBeNull(); }); it("does not return a Thing with a matching IRI but the wrong type", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedRule = createThing({ url: `${getSourceUrl(mockedAcr)}#rule`, }); mockedRule = setUrl( mockedRule, rdf.type, "http://example.org/ns#NotRuleType" ); mockedAcr = setThing(mockedAcr, mockedRule); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const result = getResourceRule(mockedResourceWithAcr, "rule"); expect(result).toBeNull(); }); it("does not return a rule with a mismatching IRI", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedRule = createThing({ url: `${getSourceUrl(mockedAcr)}#rule`, }); mockedRule = setUrl(mockedRule, rdf.type, acp.Rule); mockedAcr = setThing(mockedAcr, mockedRule); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const result = getResourceRule(mockedResourceWithAcr, "other-rule"); expect(result).toBeNull(); }); }); describe("getRuleAll", () => { it("returns an empty array if there are no Rules in the given Dataset", () => { expect(getRuleAll(createSolidDataset())).toHaveLength(0); }); it("returns all the rules in a rule resource", () => { const rule = mockRule(MOCKED_RULE_IRI); const dataset = setThing(createSolidDataset(), rule); let result = getRuleAll(dataset); expect(result).toHaveLength(1); const anotherRule = mockRule(OTHER_MOCKED_RULE_IRI); const newDataset = setThing(dataset, anotherRule); result = getRuleAll(newDataset); expect(result).toHaveLength(2); }); }); describe("getResourceRuleAll", () => { it("returns an empty array if there are no Rules in the given Resource's ACR", () => { const mockedAcr = mockAcrFor("https://some.pod/resource"); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); expect(getResourceRuleAll(mockedResourceWithAcr)).toHaveLength(0); }); it("returns all the rules in a Resource's ACR", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedRule1 = createThing({ url: `${getSourceUrl(mockedAcr)}#rule1`, }); mockedRule1 = setUrl(mockedRule1, rdf.type, acp.Rule); let mockedRule2 = createThing({ url: `${getSourceUrl(mockedAcr)}#rule2`, }); mockedRule2 = setUrl(mockedRule2, rdf.type, acp.Rule); mockedAcr = setThing(mockedAcr, mockedRule1); mockedAcr = setThing(mockedAcr, mockedRule2); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const result = getResourceRuleAll(mockedResourceWithAcr); expect(result).toHaveLength(2); }); }); describe("removeRule", () => { it("removes the Rule from the given empty Dataset", () => { const rule = mockRule(MOCKED_RULE_IRI); const dataset = setThing(createSolidDataset(), rule); const updatedDataset = removeRule(dataset, MOCKED_RULE_IRI); expect(getThingAll(updatedDataset)).toHaveLength(0); }); }); describe("removeResourceRule", () => { it("removes the Rule from the given Resource's Access control Resource", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedRule = createThing({ url: `${getSourceUrl(mockedAcr)}#rule`, }); mockedRule = setUrl(mockedRule, rdf.type, acp.Rule); mockedAcr = setThing(mockedAcr, mockedRule); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const updatedDataset = removeResourceRule( mockedResourceWithAcr, mockedRule ); expect(getResourceRuleAll(updatedDataset)).toHaveLength(0); }); it("accepts a plain name to remove a Rule", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedRule = createThing({ url: `${getSourceUrl(mockedAcr)}#rule`, }); mockedRule = setUrl(mockedRule, rdf.type, acp.Rule); mockedAcr = setThing(mockedAcr, mockedRule); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const updatedDataset = removeResourceRule(mockedResourceWithAcr, "rule"); expect(getResourceRuleAll(updatedDataset)).toHaveLength(0); }); it("accepts a full URL to remove a Rule", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedRule = createThing({ url: `${getSourceUrl(mockedAcr)}#rule`, }); mockedRule = setUrl(mockedRule, rdf.type, acp.Rule); mockedAcr = setThing(mockedAcr, mockedRule); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const updatedDataset = removeResourceRule( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#rule` ); expect(getResourceRuleAll(updatedDataset)).toHaveLength(0); }); it("accepts a Named Node to remove a Rule", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedRule = createThing({ url: `${getSourceUrl(mockedAcr)}#rule`, }); mockedRule = setUrl(mockedRule, rdf.type, acp.Rule); mockedAcr = setThing(mockedAcr, mockedRule); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const updatedDataset = removeResourceRule( mockedResourceWithAcr, DataFactory.namedNode(`${getSourceUrl(mockedAcr)}#rule`) ); expect(getResourceRuleAll(updatedDataset)).toHaveLength(0); }); it("does not remove a non-Rule with the same name", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedRule = createThing({ url: `${getSourceUrl(mockedAcr)}#rule`, }); mockedRule = setUrl( mockedRule, rdf.type, "https://example.vocab/not-a-rule" ); mockedAcr = setThing(mockedAcr, mockedRule); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const updatedDataset = removeResourceRule(mockedResourceWithAcr, "rule"); const updatedAcr = internal_getAcr(updatedDataset); expect( getThing(updatedAcr, `${getSourceUrl(mockedAcr)}#rule`) ).not.toBeNull(); }); }); describe("setRule", () => { it("sets the Rule in the given empty Dataset", () => { const rule = mockRule(MOCKED_RULE_IRI); const dataset = setRule(createSolidDataset(), rule); const result = getThing(dataset, MOCKED_RULE_IRI); expect(result).not.toBeNull(); expect(getIriAll(result as Thing, rdf.type)).toContain(acp.Rule); }); }); describe("setResourceRule", () => { it("sets the Rule in the given Resource's ACR", () => { const mockedAcr = mockAcrFor("https://some.pod/resource"); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); let mockedRule = createThing({ url: `${getSourceUrl(mockedAcr)}#rule`, }); mockedRule = setUrl(mockedRule, rdf.type, acp.Rule); const updatedResource = setResourceRule(mockedResourceWithAcr, mockedRule); expect(getResourceRuleAll(updatedResource)).toHaveLength(1); }); }); describe("getAgentAll", () => { it("returns all the agents a rule applies to by WebID", () => { const rule = mockRule(MOCKED_RULE_IRI, { agents: [MOCK_WEBID_ME, MOCK_WEBID_YOU], }); const agents = getAgentAll(rule); expect(agents).toContain(MOCK_WEBID_ME.value); expect(agents).toContain(MOCK_WEBID_YOU.value); expect(agents).toHaveLength(2); }); it("does not return the groups/public/authenticated/creator/clients a rule applies to", () => { const rule = mockRule(MOCKED_RULE_IRI, { groups: [MOCK_GROUP_IRI], public: true, authenticated: true, creator: true, clients: [MOCK_CLIENT_WEBID_1], }); const agents = getAgentAll(rule); expect(agents).not.toContain(MOCK_GROUP_IRI.value); expect(agents).not.toContain(ACP_CREATOR.value); expect(agents).not.toContain(ACP_AUTHENTICATED.value); expect(agents).not.toContain(ACP_PUBLIC.value); expect(agents).toHaveLength(0); }); }); describe("setAgent", () => { it("sets the given agents for the rule", () => { const rule = mockRule(MOCKED_RULE_IRI); const result = setAgent(rule, MOCK_WEBID_ME.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); }); it("deletes any agents previously set for the rule", () => { const rule = mockRule(MOCKED_RULE_IRI, { agents: [MOCK_WEBID_YOU], }); const result = setAgent(rule, MOCK_WEBID_ME.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); expect(getUrlAll(result, ACP_AGENT)).not.toContain(MOCK_WEBID_YOU.value); }); it("does not change the input rule", () => { const rule = mockRule(MOCKED_RULE_IRI, { agents: [MOCK_WEBID_YOU], }); setAgent(rule, MOCK_WEBID_ME.value); expect(getUrlAll(rule, ACP_AGENT)).not.toContain(MOCK_WEBID_ME.value); expect(getUrlAll(rule, ACP_AGENT)).toContain(MOCK_WEBID_YOU.value); }); it("does not overwrite public, authenticated and creator agents", () => { const rule = mockRule(MOCKED_RULE_IRI, { public: true, authenticated: true, creator: true, }); const result = setAgent(rule, MOCK_WEBID_YOU.value); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_PUBLIC.value); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_AUTHENTICATED.value); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_CREATOR.value); }); }); describe("addAgent", () => { it("adds the given agent to the rule", () => { const rule = mockRule(MOCKED_RULE_IRI); const result = addAgent(rule, MOCK_WEBID_YOU.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_YOU.value); }); it("does not override existing agents/public/authenticated/groups", () => { const rule = mockRule(MOCKED_RULE_IRI, { agents: [MOCK_WEBID_ME], groups: [MOCK_GROUP_IRI], public: true, authenticated: true, }); const result = addAgent(rule, MOCK_WEBID_YOU.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_YOU.value); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_PUBLIC.value); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_AUTHENTICATED.value); expect(getUrlAll(result, ACP_GROUP)).toContain(MOCK_GROUP_IRI.value); }); }); describe("removeAgent", () => { it("removes the given agent from the rule", () => { const rule = mockRule(MOCKED_RULE_IRI, { agents: [MOCK_WEBID_YOU], }); const result = removeAgent(rule, MOCK_WEBID_YOU.value); expect(getUrlAll(result, ACP_AGENT)).not.toContain(MOCK_WEBID_YOU.value); }); it("does not delete unrelated agents", () => { const rule = mockRule(MOCKED_RULE_IRI, { agents: [MOCK_WEBID_ME, MOCK_WEBID_YOU], public: true, authenticated: true, }); const result = removeAgent(rule, MOCK_WEBID_YOU.value); expect(getUrlAll(result, ACP_AGENT)).not.toContain(MOCK_WEBID_YOU.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_PUBLIC.value); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_AUTHENTICATED.value); }); it("does not remove groups, even with matching IRI", () => { const rule = mockRule(MOCKED_RULE_IRI, { groups: [MOCK_GROUP_IRI], }); const result = removeAgent(rule, MOCK_GROUP_IRI.value); expect(getUrlAll(result, ACP_GROUP)).toContain(MOCK_GROUP_IRI.value); }); }); describe("getGroupAll", () => { it("returns all the groups a rule applies to", () => { const rule = mockRule(MOCKED_RULE_IRI, { groups: [MOCK_GROUP_IRI, MOCK_GROUP_OTHER_IRI], }); const groups = getGroupAll(rule); expect(groups).toContain(MOCK_GROUP_IRI.value); expect(groups).toContain(MOCK_GROUP_OTHER_IRI.value); expect(groups).toHaveLength(2); }); it("does not return the agents/public/authenticated/clients a rule applies to", () => { const rule = mockRule(MOCKED_RULE_IRI, { agents: [MOCK_WEBID_ME], public: true, authenticated: true, clients: [MOCK_CLIENT_WEBID_1], }); const groups = getGroupAll(rule); expect(groups).not.toContain(MOCK_WEBID_ME.value); expect(groups).not.toContain(ACP_AUTHENTICATED.value); expect(groups).not.toContain(ACP_PUBLIC.value); expect(groups).toHaveLength(0); }); }); describe("setGroup", () => { it("sets the given groups for the rule", () => { const rule = mockRule(MOCKED_RULE_IRI); const result = setGroup(rule, MOCK_GROUP_IRI.value); expect(getUrlAll(result, ACP_GROUP)).toContain(MOCK_GROUP_IRI.value); }); it("deletes any groups previously set for the rule", () => { const rule = mockRule(MOCKED_RULE_IRI, { groups: [MOCK_GROUP_OTHER_IRI], }); const result = setGroup(rule, MOCK_GROUP_IRI.value); expect(getUrlAll(result, ACP_GROUP)).toContain(MOCK_GROUP_IRI.value); expect(getUrlAll(result, ACP_GROUP)).not.toContain( MOCK_GROUP_OTHER_IRI.value ); }); it("does not change the input rule", () => { const rule = mockRule(MOCKED_RULE_IRI, { groups: [MOCK_GROUP_OTHER_IRI], }); setGroup(rule, MOCK_GROUP_IRI.value); expect(getUrlAll(rule, ACP_GROUP)).not.toContain(MOCK_GROUP_IRI.value); expect(getUrlAll(rule, ACP_GROUP)).toContain(MOCK_GROUP_OTHER_IRI.value); }); }); describe("addGroup", () => { it("adds the given group to the rule", () => { const rule = mockRule(MOCKED_RULE_IRI); const result = addGroup(rule, "https://your.pod/groups#a-group"); expect(getUrlAll(result, ACP_GROUP)).toContain( "https://your.pod/groups#a-group" ); }); it("does not override existing agents/public/authenticated/groups", () => { const rule = mockRule(MOCKED_RULE_IRI, { agents: [MOCK_WEBID_ME], groups: [MOCK_GROUP_IRI], public: true, authenticated: true, }); const result = addGroup(rule, MOCK_GROUP_OTHER_IRI.value); expect(getUrlAll(result, ACP_GROUP)).toContain(MOCK_GROUP_OTHER_IRI.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_PUBLIC.value); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_AUTHENTICATED.value); expect(getUrlAll(result, ACP_GROUP)).toContain(MOCK_GROUP_IRI.value); }); }); describe("removeGroup", () => { it("removes the given group from the rule", () => { const rule = mockRule(MOCKED_RULE_IRI, { groups: [MOCK_GROUP_IRI], }); const result = removeGroup(rule, MOCK_GROUP_IRI.value); expect(getUrlAll(result, ACP_GROUP)).not.toContain(MOCK_GROUP_IRI.value); }); it("does not delete unrelated groups", () => { const rule = mockRule(MOCKED_RULE_IRI, { groups: [MOCK_GROUP_IRI, MOCK_GROUP_OTHER_IRI], }); const result = removeGroup(rule, MOCK_GROUP_IRI.value); expect(getUrlAll(result, ACP_GROUP)).not.toContain(MOCK_GROUP_IRI.value); expect(getUrlAll(result, ACP_GROUP)).toContain(MOCK_GROUP_OTHER_IRI.value); }); it("does not remove agents, even with matching IRI", () => { const rule = mockRule(MOCKED_RULE_IRI, { agents: [MOCK_WEBID_ME], }); const result = removeGroup(rule, MOCK_WEBID_ME.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); }); }); describe("hasPublic", () => { it("returns true if the rule applies to the public agent", () => { const rule = mockRule(MOCKED_RULE_IRI, { public: true, }); expect(hasPublic(rule)).toBe(true); }); it("returns false if the rule only applies to other agent", () => { const rule = mockRule(MOCKED_RULE_IRI, { public: false, authenticated: true, agents: [MOCK_WEBID_ME], }); expect(hasPublic(rule)).toBe(false); }); }); describe("setPublic", () => { it("applies the given rule to the public agent", () => { const rule = mockRule(MOCKED_RULE_IRI); const result = setPublic(rule); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_PUBLIC.value); }); it("does not change the input rule", () => { const rule = mockRule(MOCKED_RULE_IRI); setPublic(rule); expect(getUrlAll(rule, ACP_AGENT)).not.toContain(ACP_PUBLIC.value); }); it("does not change the other agents", () => { const rule = mockRule(MOCKED_RULE_IRI, { authenticated: true, agents: [MOCK_WEBID_ME], }); const result = setPublic(rule); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_AUTHENTICATED.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); }); it("throws an error when you attempt to use the deprecated API", () => { const rule = mockRule(MOCKED_RULE_IRI); expect( // @ts-expect-error The type signature should warn about passing a second argument: () => setPublic(rule, true) ).toThrow( "The function `setPublic` no longer takes a second parameter. It is now used together with `removePublic` instead." ); }); }); describe("removePublic", () => { it("prevents the rule from applying to the public agent", () => { const rule = mockRule(MOCKED_RULE_IRI, { public: true, }); const result = removePublic(rule); expect(getUrlAll(result, ACP_AGENT)).not.toContain(ACP_PUBLIC.value); }); it("does not change the input rule", () => { const rule = mockRule(MOCKED_RULE_IRI, { public: true }); removePublic(rule); expect(getUrlAll(rule, ACP_AGENT)).toContain(ACP_PUBLIC.value); }); it("does not change the other agents", () => { const rule = mockRule(MOCKED_RULE_IRI, { authenticated: true, agents: [MOCK_WEBID_ME], public: true, }); const result = removePublic(rule); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_AUTHENTICATED.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); }); }); describe("hasAuthenticated", () => { it("returns true if the rule applies to authenticated agents", () => { const rule = mockRule(MOCKED_RULE_IRI, { authenticated: true, }); expect(hasAuthenticated(rule)).toBe(true); }); it("returns false if the rule only applies to other agent", () => { const rule = mockRule(MOCKED_RULE_IRI, { public: true, authenticated: false, agents: [MOCK_WEBID_ME], }); expect(hasAuthenticated(rule)).toBe(false); }); }); describe("setAuthenticated", () => { it("applies to given rule to authenticated agents", () => { const rule = mockRule(MOCKED_RULE_IRI); const result = setAuthenticated(rule); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_AUTHENTICATED.value); }); it("does not change the input rule", () => { const rule = mockRule(MOCKED_RULE_IRI); setAuthenticated(rule); expect(getUrlAll(rule, ACP_AGENT)).not.toContain(ACP_AUTHENTICATED.value); }); it("does not change the other agents", () => { const rule = mockRule(MOCKED_RULE_IRI, { public: true, agents: [MOCK_WEBID_ME], }); const result = setAuthenticated(rule); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_PUBLIC.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); }); it("throws an error when you attempt to use the deprecated API", () => { const rule = mockRule(MOCKED_RULE_IRI); expect( // @ts-expect-error The type signature should warn about passing a second argument: () => setAuthenticated(rule, true) ).toThrow( "The function `setAuthenticated` no longer takes a second parameter. It is now used together with `removeAuthenticated` instead." ); }); }); describe("removeAuthenticated", () => { it("prevents the rule from applying to authenticated agents", () => { const rule = mockRule(MOCKED_RULE_IRI, { authenticated: true, }); const result = removeAuthenticated(rule); expect(getUrlAll(result, ACP_AGENT)).not.toContain(ACP_AUTHENTICATED.value); }); it("does not change the input rule", () => { const rule = mockRule(MOCKED_RULE_IRI, { authenticated: true }); removeAuthenticated(rule); expect(getUrlAll(rule, ACP_AGENT)).toContain(ACP_AUTHENTICATED.value); }); it("does not change the other agents", () => { const rule = mockRule(MOCKED_RULE_IRI, { public: true, authenticated: true, agents: [MOCK_WEBID_ME], }); const result = removeAuthenticated(rule); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_PUBLIC.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); }); }); describe("hasCreator", () => { it("returns true if the rule applies to the Resource's creator", () => { const rule = mockRule(MOCKED_RULE_IRI, { creator: true, }); expect(hasCreator(rule)).toBe(true); }); it("returns false if the rule only applies to other agents", () => { const rule = mockRule(MOCKED_RULE_IRI, { public: true, creator: false, agents: [MOCK_WEBID_ME], }); expect(hasCreator(rule)).toBe(false); }); }); describe("setCreator", () => { it("applies the given rule to the Resource's creator", () => { const rule = mockRule(MOCKED_RULE_IRI); const result = setCreator(rule); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_CREATOR.value); }); it("does not change the input rule", () => { const rule = mockRule(MOCKED_RULE_IRI); setCreator(rule); expect(getUrlAll(rule, ACP_AGENT)).not.toContain(ACP_CREATOR.value); }); it("does not change the other agents", () => { const rule = mockRule(MOCKED_RULE_IRI, { public: true, agents: [MOCK_WEBID_ME], }); const result = setCreator(rule); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_PUBLIC.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); }); it("throws an error when you attempt to use the deprecated API", () => { const rule = mockRule(MOCKED_RULE_IRI); expect( // @ts-expect-error The type signature should warn about passing a second argument: () => setCreator(rule, true) ).toThrow( "The function `setCreator` no longer takes a second parameter. It is now used together with `removeCreator` instead." ); }); }); describe("removeCreator", () => { it("prevents the rule from applying to the Resource's creator", () => { const rule = mockRule(MOCKED_RULE_IRI, { creator: true, }); const result = removeCreator(rule); expect(getUrlAll(result, ACP_AGENT)).not.toContain(ACP_CREATOR.value); }); it("does not change the input rule", () => { const rule = mockRule(MOCKED_RULE_IRI, { creator: true }); removeCreator(rule); expect(getUrlAll(rule, ACP_AGENT)).toContain(ACP_CREATOR.value); }); it("does not change the other agents", () => { const rule = mockRule(MOCKED_RULE_IRI, { creator: true, public: true, agents: [MOCK_WEBID_ME], }); const result = removeCreator(rule); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_PUBLIC.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); }); }); describe("getClientAll", () => { it("returns all the clients a rule applies to by WebID", () => { const rule = mockRule(MOCKED_RULE_IRI, { clients: [MOCK_CLIENT_WEBID_1, MOCK_CLIENT_WEBID_2], }); const clients = getClientAll(rule); expect(clients).toContain(MOCK_CLIENT_WEBID_1.value); expect(clients).toContain(MOCK_CLIENT_WEBID_2.value); expect(clients).toHaveLength(2); }); it("does not return the agents/groups/public client a rule applies to", () => { const rule = mockRule(MOCKED_RULE_IRI, { agents: [MOCK_WEBID_ME], groups: [MOCK_GROUP_IRI], public: true, authenticated: true, creator: true, publicClient: true, }); const clients = getClientAll(rule); expect(clients).not.toContain(MOCK_GROUP_IRI.value); expect(clients).not.toContain(ACP_CREATOR.value); expect(clients).not.toContain(ACP_AUTHENTICATED.value); expect(clients).not.toContain(ACP_PUBLIC.value); expect(clients).toHaveLength(0); }); }); describe("setClient", () => { it("sets the given clients for the rule", () => { const rule = mockRule(MOCKED_RULE_IRI); const result = setClient(rule, MOCK_CLIENT_WEBID_1.value); expect(getUrlAll(result, ACP_CLIENT)).toContain(MOCK_CLIENT_WEBID_1.value); }); it("deletes any clients previously set for the rule", () => { const rule = mockRule(MOCKED_RULE_IRI, { clients: [MOCK_CLIENT_WEBID_1], }); const result = setClient(rule, MOCK_CLIENT_WEBID_2.value); expect(getUrlAll(result, ACP_CLIENT)).toContain(MOCK_CLIENT_WEBID_2.value); expect(getUrlAll(result, ACP_CLIENT)).not.toContain( MOCK_CLIENT_WEBID_1.value ); }); it("does not change the input rule", () => { const rule = mockRule(MOCKED_RULE_IRI, { clients: [MOCK_CLIENT_WEBID_1], }); setClient(rule, MOCK_CLIENT_WEBID_2.value); expect(getUrlAll(rule, ACP_CLIENT)).not.toContain( MOCK_CLIENT_WEBID_2.value ); expect(getUrlAll(rule, ACP_CLIENT)).toContain(MOCK_CLIENT_WEBID_1.value); }); it("does not overwrite the public client class", () => { const rule = mockRule(MOCKED_RULE_IRI, { publicClient: true, }); const result = setClient(rule, MOCK_CLIENT_WEBID_1.value); expect(getUrlAll(result, ACP_CLIENT)).toContain(SOLID_PUBLIC_CLIENT.value); }); }); describe("addClient", () => { it("adds the given client to the rule", () => { const rule = mockRule(MOCKED_RULE_IRI); const result = addClient(rule, MOCK_CLIENT_WEBID_1.value); expect(getUrlAll(result, ACP_CLIENT)).toContain(MOCK_CLIENT_WEBID_1.value); }); it("does not override existing clients/the public client class", () => { const rule = mockRule(MOCKED_RULE_IRI, { clients: [MOCK_CLIENT_WEBID_1], publicClient: true, }); const result = addClient(rule, MOCK_CLIENT_WEBID_2.value); expect(getUrlAll(result, ACP_CLIENT)).toContain(MOCK_CLIENT_WEBID_1.value); expect(getUrlAll(result, ACP_CLIENT)).toContain(MOCK_CLIENT_WEBID_2.value); expect(getUrlAll(result, ACP_CLIENT)).toContain(SOLID_PUBLIC_CLIENT.value); }); }); describe("removeClient", () => { it("removes the given client from the rule", () => { const rule = mockRule(MOCKED_RULE_IRI, { clients: [MOCK_CLIENT_WEBID_1], }); const result = removeClient(rule, MOCK_CLIENT_WEBID_1.value); expect(getUrlAll(result, ACP_CLIENT)).not.toContain( MOCK_CLIENT_WEBID_1.value ); }); it("does not delete unrelated clients", () => { const rule = mockRule(MOCKED_RULE_IRI, { clients: [MOCK_CLIENT_WEBID_1, MOCK_CLIENT_WEBID_2], publicClient: true, }); const result = removeClient(rule, MOCK_CLIENT_WEBID_2.value); expect(getUrlAll(result, ACP_CLIENT)).not.toContain( MOCK_CLIENT_WEBID_2.value ); expect(getUrlAll(result, ACP_CLIENT)).toContain(MOCK_CLIENT_WEBID_1.value); expect(getUrlAll(result, ACP_CLIENT)).toContain(SOLID_PUBLIC_CLIENT.value); }); it("does not remove agents, even with a matching IRI", () => { const rule = mockRule(MOCKED_RULE_IRI, { agents: [MOCK_WEBID_ME], }); const result = removeClient(rule, MOCK_WEBID_ME.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); }); it("does not remove groups, even with a matching IRI", () => { const rule = mockRule(MOCKED_RULE_IRI, { groups: [MOCK_GROUP_IRI], }); const result = removeClient(rule, MOCK_GROUP_IRI.value); expect(getUrlAll(result, ACP_GROUP)).toContain(MOCK_GROUP_IRI.value); }); }); describe("hasAnyClient", () => { it("returns true if the rule applies to any client", () => { const rule = mockRule(MOCKED_RULE_IRI, { publicClient: true, }); expect(hasAnyClient(rule)).toBe(true); }); it("returns false if the rule only applies to individual clients", () => { const rule = mockRule(MOCKED_RULE_IRI, { clients: [MOCK_CLIENT_WEBID_1], }); expect(hasAnyClient(rule)).toBe(false); }); }); describe("setAnyClient", () => { it("applies to given rule to the public client class", () => { const rule = mockRule(MOCKED_RULE_IRI); const result = setAnyClient(rule); expect(getUrlAll(result, ACP_CLIENT)).toContain(SOLID_PUBLIC_CLIENT.value); }); it("does not change the input rule", () => { const rule = mockRule(MOCKED_RULE_IRI); setAnyClient(rule); expect(getUrlAll(rule, ACP_CLIENT)).not.toContain( SOLID_PUBLIC_CLIENT.value ); }); it("does not change the other clients", () => { const rule = mockRule(MOCKED_RULE_IRI, { clients: [MOCK_CLIENT_WEBID_1], }); const result = setAnyClient(rule); expect(getUrlAll(result, ACP_CLIENT)).toContain(MOCK_CLIENT_WEBID_1.value); }); }); describe("removeAnyClient", () => { it("prevents the rule from applying to the public client class", () => { const rule = mockRule(MOCKED_RULE_IRI, { publicClient: true, }); const result = removeAnyClient(rule); expect(getUrlAll(result, ACP_CLIENT)).not.toContain( SOLID_PUBLIC_CLIENT.value ); }); it("does not change the input rule", () => { const rule = mockRule(MOCKED_RULE_IRI, { publicClient: true }); removeAnyClient(rule); expect(getUrlAll(rule, ACP_CLIENT)).toContain(SOLID_PUBLIC_CLIENT.value); }); it("does not change the other clients", () => { const rule = mockRule(MOCKED_RULE_IRI, { publicClient: true, clients: [MOCK_CLIENT_WEBID_1], }); const result = removeAnyClient(rule); expect(getUrlAll(result, ACP_CLIENT)).toContain(MOCK_CLIENT_WEBID_1.value); }); }); describe("ruleAsMarkdown", () => { it("shows when a rule is empty", () => { const rule = createRule("https://some.pod/policyResource#rule"); expect(ruleAsMarkdown(rule)).toBe( "## Rule: https://some.pod/policyResource#rule\n" + "\n" + "<empty>\n" ); }); it("can show everything to which the rule applies", () => { let rule = createRule("https://some.pod/policyResource#rule"); rule = setCreator(rule); rule = setAuthenticated(rule); rule = setPublic(rule); rule = setAnyClient(rule); rule = addAgent(rule, "https://some.pod/profile#agent"); rule = addAgent(rule, "https://some-other.pod/profile#agent"); rule = addGroup(rule, "https://some.pod/groups#family"); rule = addClient(rule, "https://some.app/registration#it"); expect(ruleAsMarkdown(rule)).toBe( "## Rule: https://some.pod/policyResource#rule\n" + "\n" + "This rule applies to:\n" + "- Everyone\n" + "- All authenticated agents\n" + "- The creator of this resource\n" + "- Users of any client application\n" + "- The following agents:\n" + " - https://some.pod/profile#agent\n" + " - https://some-other.pod/profile#agent\n" + "- Members of the following groups:\n" + " - https://some.pod/groups#family\n" + "- Users of the following client applications:\n" + " - https://some.app/registration#it\n" ); }); });
the_stack
import {log} from "@blitzjs/display" import chalk from "chalk" import spawn from "cross-spawn" import {readJSONSync, writeJson} from "fs-extra" import {join} from "path" import username from "username" import {Generator, GeneratorOptions, SourceRootType} from "../generator" import {fetchLatestVersionsFor} from "../utils/fetch-latest-version-for" import {getBlitzDependencyVersion} from "../utils/get-blitz-dependency-version" function assert(condition: any, message: string): asserts condition { if (!condition) throw new Error(message) } type TemplateConfig = { path: string skipForms?: boolean skipDatabase?: boolean } export interface AppGeneratorOptions extends GeneratorOptions { template: TemplateConfig appName: string useTs: boolean yarn: boolean pnpm?: boolean version: string skipInstall: boolean skipGit: boolean form?: "React Final Form" | "React Hook Form" | "Formik" onPostInstall?: () => Promise<void> } type PkgManager = "npm" | "yarn" | "pnpm" export class AppGenerator extends Generator<AppGeneratorOptions> { sourceRoot: SourceRootType = {type: "template", path: this.options.template.path} // Disable file-level prettier because we manually run prettier at the end prettierDisabled = true packageInstallSuccess: boolean = false filesToIgnore() { if (!this.options.useTs) { return [ "tsconfig.json", "blitz-env.d.ts", "jest.config.ts", "package.ts.json", "pre-push-ts", "types.ts", ] } return ["jsconfig.json", "jest.config.js", "package.js.json", "pre-push-js"] } async getTemplateValues() { return { name: this.options.appName, safeNameSlug: this.options.appName.replace(/[^a-zA-Z0-9-_]/g, "-"), username: await username(), } } getTargetDirectory() { return "" } // eslint-disable-next-line require-await async preCommit() { this.fs.move(this.destinationPath("gitignore"), this.destinationPath(".gitignore")) this.fs.move(this.destinationPath("npmrc"), this.destinationPath(".npmrc")) this.fs.move( this.destinationPath(this.options.useTs ? ".husky/pre-push-ts" : ".husky/pre-push-js"), this.destinationPath(".husky/pre-push"), ) this.fs.move( this.destinationPath(this.options.useTs ? "package.ts.json" : "package.js.json"), this.destinationPath("package.json"), ) if (!this.options.template.skipForms) { this.updateForms() } } async postWrite() { const {pkgManager} = this let gitInitSuccessful if (!this.options.skipGit) { const initResult = spawn.sync("git", ["init"], { stdio: "ignore", }) gitInitSuccessful = initResult.status === 0 if (!gitInitSuccessful) { log.warning("Failed to run git init.") log.warning("Find out more about how to install git here: https://git-scm.com/downloads.") } } const pkgJsonLocation = join(this.destinationPath(), "package.json") const pkg = readJSONSync(pkgJsonLocation) console.log("") // New line needed const spinner = log.spinner(log.withBrand("Retrieving the freshest of dependencies")).start() const [ {value: newDependencies, isFallback: dependenciesUsedFallback}, {value: newDevDependencies, isFallback: devDependenciesUsedFallback}, {value: blitzDependencyVersion, isFallback: blitzUsedFallback}, ] = await Promise.all([ fetchLatestVersionsFor(pkg.dependencies), fetchLatestVersionsFor(pkg.devDependencies), getBlitzDependencyVersion(this.options.version), ]) pkg.dependencies = newDependencies pkg.devDependencies = newDevDependencies pkg.dependencies.blitz = blitzDependencyVersion const fallbackUsed = dependenciesUsedFallback || devDependenciesUsedFallback || blitzUsedFallback await writeJson(pkgJsonLocation, pkg, {spaces: 2}) if (!fallbackUsed && !this.options.skipInstall) { spinner.succeed() await new Promise<void>((resolve) => { const logFlag = pkgManager === "yarn" ? "--json" : "--loglevel=error" const cp = spawn(pkgManager, ["install", logFlag], { stdio: ["inherit", "pipe", "pipe"], }) const getJSON = (data: string) => { try { return JSON.parse(data) } catch { return null } } const spinners: any[] = [] if (pkgManager !== "yarn") { const spinner = log .spinner(log.withBrand("Installing those dependencies (this will take a few minutes)")) .start() spinners.push(spinner) } cp.stdout?.setEncoding("utf8") cp.stderr?.setEncoding("utf8") cp.stdout?.on("data", (data) => { if (pkgManager === "yarn") { let json = getJSON(data) if (json && json.type === "step") { spinners[spinners.length - 1]?.succeed() const spinner = log.spinner(log.withBrand(json.data.message)).start() spinners.push(spinner) } if (json && json.type === "success") { spinners[spinners.length - 1]?.succeed() } } }) cp.stderr?.on("data", (data) => { if (pkgManager === "yarn") { let json = getJSON(data) if (json && json.type === "error") { spinners[spinners.length - 1]?.fail() console.error(json.data) } } else { // Hide the annoying Prisma warning about not finding the schema file // because we generate the client ourselves if (!data.includes("schema.prisma")) { console.error(`\n${data}`) } } }) cp.on("exit", (code) => { if (pkgManager !== "yarn" && spinners[spinners.length - 1].isSpinning) { if (code !== 0) spinners[spinners.length - 1].fail() else { spinners[spinners.length - 1].succeed() this.packageInstallSuccess = true } } resolve() }) }) await this.options.onPostInstall?.() const runLocalNodeCLI = (command: string) => { const {pkgManager} = this if (pkgManager === "yarn") { return spawn.sync("yarn", ["run", ...command.split(" ")]) } else if (pkgManager === "pnpm") { return spawn.sync("pnpx", command.split(" ")) } else { return spawn.sync("npx", command.split(" ")) } } // Ensure the generated files are formatted with the installed prettier version if (this.packageInstallSuccess) { const formattingSpinner = log.spinner(log.withBrand("Formatting your code")).start() const prettierResult = runLocalNodeCLI("prettier --loglevel silent --write .") if (prettierResult.status !== 0) { formattingSpinner.fail( chalk.yellow.bold( "We had an error running Prettier, but don't worry your app will still run fine :)", ), ) } else { formattingSpinner.succeed() } } } else { console.log("") // New line needed if (this.options.skipInstall) { spinner.succeed() } else { spinner.fail( chalk.red.bold( `We had some trouble connecting to the network, so we'll skip installing your dependencies right now. Make sure to run ${`${this.pkgManager} install`} once you're connected again.`, ), ) } } if (!this.options.skipGit && gitInitSuccessful) { this.commitChanges() } } preventFileFromLogging(path: string): boolean { if (path.includes(".env")) return false if (path.includes("eslint")) return false const filename = path.split("/").pop() as string return path[0] === "." || filename[0] === "." } commitChanges() { const commitSpinner = log.spinner(log.withBrand("Committing your app")).start() const commands: Array<[string, string[], object]> = [ ["git", ["add", "."], {stdio: "ignore"}], [ "git", [ "-c", "user.name='Blitz.js CLI'", "-c", "user.email='noop@blitzjs.com'", "commit", "--no-gpg-sign", "--no-verify", "-m", "Brand new Blitz app!", ], {stdio: "ignore", timeout: 10000}, ], ] for (let command of commands) { const result = spawn.sync(...command) if (result.status !== 0) { commitSpinner.fail( chalk.red.bold( `Failed to run command ${command[0]} with ${command[1].join(" ")} options.`, ), ) return } } commitSpinner.succeed() } private updateForms() { const pkg = this.fs.readJSON(this.destinationPath("package.json")) as | Record<string, any> | undefined assert(pkg, "couldn't find package.json") const ext = this.options.useTs ? "tsx" : "js" let type: string = "" switch (this.options.form) { case "React Final Form": type = "finalform" pkg.dependencies["final-form"] = "4.x" pkg.dependencies["react-final-form"] = "6.x" break case "React Hook Form": type = "hookform" pkg.dependencies["react-hook-form"] = "7.x" pkg.dependencies["@hookform/resolvers"] = "2.x" break case "Formik": type = "formik" pkg.dependencies["formik"] = "2.x" break } this.fs.move( this.destinationPath(`_forms/${type}/Form.${ext}`), this.destinationPath(`app/core/components/Form.${ext}`), ) this.fs.move( this.destinationPath(`_forms/${type}/LabeledTextField.${ext}`), this.destinationPath(`app/core/components/LabeledTextField.${ext}`), ) this.fs.writeJSON(this.destinationPath("package.json"), pkg) this.fs.delete(this.destinationPath("_forms")) } private get pkgManager(): PkgManager { if (this.options.pnpm) { return "pnpm" } else if (this.options.yarn) { return "yarn" } else { return "npm" } } }
the_stack
import { readFileSync } from 'fs' import JSON5 from 'next/dist/compiled/json5' import { createConfigItem, loadOptions } from 'next/dist/compiled/babel/core' import loadConfig from 'next/dist/compiled/babel/core-lib-config' import { NextBabelLoaderOptions, NextJsLoaderContext } from './types' import { consumeIterator } from './util' import * as Log from '../../output/log' const nextDistPath = /(next[\\/]dist[\\/]shared[\\/]lib)|(next[\\/]dist[\\/]client)|(next[\\/]dist[\\/]pages)/ /** * The properties defined here are the conditions with which subsets of inputs * can be identified that are able to share a common Babel config. For example, * in dev mode, different transforms must be applied to a source file depending * on whether you're compiling for the client or for the server - thus `isServer` * is germane. * * However, these characteristics need not protect against circumstances that * will not be encountered in Next.js. For example, a source file may be * transformed differently depending on whether we're doing a production compile * or for HMR in dev mode. However, those two circumstances will never be * encountered within the context of a single V8 context (and, thus, shared * cache). Therefore, hasReactRefresh is _not_ germane to caching. * * NOTE: This approach does not support multiple `.babelrc` files in a * single project. A per-cache-key config will be generated once and, * if `.babelrc` is present, that config will be used for any subsequent * transformations. */ interface CharacteristicsGermaneToCaching { isServer: boolean isPageFile: boolean isNextDist: boolean hasModuleExports: boolean fileExt: string } const fileExtensionRegex = /\.([a-z]+)$/ function getCacheCharacteristics( loaderOptions: NextBabelLoaderOptions, source: string, filename: string ): CharacteristicsGermaneToCaching { const { isServer, pagesDir } = loaderOptions const isPageFile = filename.startsWith(pagesDir) const isNextDist = nextDistPath.test(filename) const hasModuleExports = source.indexOf('module.exports') !== -1 const fileExt = fileExtensionRegex.exec(filename)?.[1] || 'unknown' return { isServer, isPageFile, isNextDist, hasModuleExports, fileExt, } } /** * Return an array of Babel plugins, conditioned upon loader options and * source file characteristics. */ function getPlugins( loaderOptions: NextBabelLoaderOptions, cacheCharacteristics: CharacteristicsGermaneToCaching ) { const { isServer, isPageFile, isNextDist, hasModuleExports } = cacheCharacteristics const { hasReactRefresh, development } = loaderOptions const applyCommonJsItem = hasModuleExports ? createConfigItem(require('../plugins/commonjs'), { type: 'plugin' }) : null const reactRefreshItem = hasReactRefresh ? createConfigItem( [ require('next/dist/compiled/react-refresh/babel'), { skipEnvCheck: true }, ], { type: 'plugin' } ) : null const pageConfigItem = !isServer && isPageFile ? createConfigItem([require('../plugins/next-page-config')], { type: 'plugin', }) : null const disallowExportAllItem = !isServer && isPageFile ? createConfigItem( [require('../plugins/next-page-disallow-re-export-all-exports')], { type: 'plugin' } ) : null const transformDefineItem = createConfigItem( [ require.resolve('next/dist/compiled/babel/plugin-transform-define'), { 'process.env.NODE_ENV': development ? 'development' : 'production', 'typeof window': isServer ? 'undefined' : 'object', 'process.browser': isServer ? false : true, }, 'next-js-transform-define-instance', ], { type: 'plugin' } ) const nextSsgItem = !isServer && isPageFile ? createConfigItem([require.resolve('../plugins/next-ssg-transform')], { type: 'plugin', }) : null const commonJsItem = isNextDist ? createConfigItem( require('next/dist/compiled/babel/plugin-transform-modules-commonjs'), { type: 'plugin' } ) : null return [ reactRefreshItem, pageConfigItem, disallowExportAllItem, applyCommonJsItem, transformDefineItem, nextSsgItem, commonJsItem, ].filter(Boolean) } const isJsonFile = /\.(json|babelrc)$/ const isJsFile = /\.js$/ /** * While this function does block execution while reading from disk, it * should not introduce any issues. The function is only invoked when * generating a fresh config, and only a small handful of configs should * be generated during compilation. */ function getCustomBabelConfig(configFilePath: string) { if (isJsonFile.exec(configFilePath)) { const babelConfigRaw = readFileSync(configFilePath, 'utf8') return JSON5.parse(babelConfigRaw) } else if (isJsFile.exec(configFilePath)) { return require(configFilePath) } throw new Error( 'The Next.js Babel loader does not support .mjs or .cjs config files.' ) } /** * Generate a new, flat Babel config, ready to be handed to Babel-traverse. * This config should have no unresolved overrides, presets, etc. */ function getFreshConfig( this: NextJsLoaderContext, cacheCharacteristics: CharacteristicsGermaneToCaching, loaderOptions: NextBabelLoaderOptions, target: string, filename: string, inputSourceMap?: object | null ) { let { isServer, pagesDir, development, hasJsxRuntime, configFile } = loaderOptions let customConfig: any = configFile ? getCustomBabelConfig(configFile) : undefined let options = { babelrc: false, cloneInputAst: false, filename, inputSourceMap: inputSourceMap || undefined, // Set the default sourcemap behavior based on Webpack's mapping flag, // but allow users to override if they want. sourceMaps: loaderOptions.sourceMaps === undefined ? this.sourceMap : loaderOptions.sourceMaps, // Ensure that Webpack will get a full absolute path in the sourcemap // so that it can properly map the module back to its internal cached // modules. sourceFileName: filename, plugins: [ ...getPlugins(loaderOptions, cacheCharacteristics), ...(customConfig?.plugins || []), ], // target can be provided in babelrc target: isServer ? undefined : customConfig?.target, // env can be provided in babelrc env: customConfig?.env, presets: (() => { // If presets is defined the user will have next/babel in their babelrc if (customConfig?.presets) { return customConfig.presets } // If presets is not defined the user will likely have "env" in their babelrc if (customConfig) { return undefined } // If no custom config is provided the default is to use next/babel return ['next/babel'] })(), overrides: loaderOptions.overrides, caller: { name: 'next-babel-turbo-loader', supportsStaticESM: true, supportsDynamicImport: true, // Provide plugins with insight into webpack target. // https://github.com/babel/babel-loader/issues/787 target: target, // Webpack 5 supports TLA behind a flag. We enable it by default // for Babel, and then webpack will throw an error if the experimental // flag isn't enabled. supportsTopLevelAwait: true, isServer, pagesDir, isDev: development, hasJsxRuntime, ...loaderOptions.caller, }, } as any // Babel does strict checks on the config so undefined is not allowed if (typeof options.target === 'undefined') { delete options.target } Object.defineProperty(options.caller, 'onWarning', { enumerable: false, writable: false, value: (reason: any) => { if (!(reason instanceof Error)) { reason = new Error(reason) } this.emitWarning(reason) }, }) const loadedOptions = loadOptions(options) const config = consumeIterator(loadConfig(loadedOptions)) return config } /** * Each key returned here corresponds with a Babel config that can be shared. * The conditions of permissible sharing between files is dependent on specific * file attributes and Next.js compiler states: `CharacteristicsGermaneToCaching`. */ function getCacheKey(cacheCharacteristics: CharacteristicsGermaneToCaching) { const { isServer, isPageFile, isNextDist, hasModuleExports, fileExt } = cacheCharacteristics const flags = 0 | (isServer ? 0b0001 : 0) | (isPageFile ? 0b0010 : 0) | (isNextDist ? 0b0100 : 0) | (hasModuleExports ? 0b1000 : 0) return fileExt + flags } type BabelConfig = any const configCache: Map<any, BabelConfig> = new Map() const configFiles: Set<string> = new Set() export default function getConfig( this: NextJsLoaderContext, { source, target, loaderOptions, filename, inputSourceMap, }: { source: string loaderOptions: NextBabelLoaderOptions target: string filename: string inputSourceMap?: object | null } ): BabelConfig { const cacheCharacteristics = getCacheCharacteristics( loaderOptions, source, filename ) if (loaderOptions.configFile) { // Ensures webpack invalidates the cache for this loader when the config file changes this.addDependency(loaderOptions.configFile) } const cacheKey = getCacheKey(cacheCharacteristics) if (configCache.has(cacheKey)) { const cachedConfig = configCache.get(cacheKey) return { ...cachedConfig, options: { ...cachedConfig.options, cwd: loaderOptions.cwd, root: loaderOptions.cwd, filename, sourceFileName: filename, }, } } if (loaderOptions.configFile && !configFiles.has(loaderOptions.configFile)) { configFiles.add(loaderOptions.configFile) Log.info( `Using external babel configuration from ${loaderOptions.configFile}` ) } const freshConfig = getFreshConfig.call( this, cacheCharacteristics, loaderOptions, target, filename, inputSourceMap ) configCache.set(cacheKey, freshConfig) return freshConfig }
the_stack
import { EventEmitter, NgZone } from '@angular/core'; import { fakeAsync, TestBed, tick } from '@angular/core/testing'; import { StateRecordedVoiceoversService } from // eslint-disable-next-line max-len 'components/state-editor/state-editor-properties-services/state-recorded-voiceovers.service'; import { SiteAnalyticsService } from 'services/site-analytics.service'; import { RecordedVoiceovers } from 'domain/exploration/recorded-voiceovers.model'; import { EditabilityService } from 'services/editability.service'; import { AlertsService } from 'services/alerts.service'; import { AudioPlayerService } from 'services/audio-player.service'; import WaveSurfer from 'wavesurfer.js'; import $ from 'jquery'; // TODO(#7222): Remove the following block of unnnecessary imports once // the code corresponding to the spec is upgraded to Angular 8. import { importAllAngularServices } from 'tests/unit-test-utils.ajs'; import { OppiaAngularRootComponent } from 'components/oppia-angular-root.component'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; // ^^^ This block is to be removed. require( 'pages/exploration-editor-page/translation-tab/audio-translation-bar/' + 'audio-translation-bar.directive.ts'); describe('Audio translation bar directive', function() { var ctrl = null; var $interval = null; var $q = null; var $rootScope = null; var $scope = null; var $uibModal = null; var ngbModal = null; var alertsService = null; var assetsBackendApiService = null; var audioPlayerService: AudioPlayerService = null; var contextService = null; var editabilityService = null; var explorationStatesService = null; var siteAnalyticsService = null; var stateEditorService = null; var stateRecordedVoiceoversService = null; var translationLanguageService = null; var translationTabActiveContentIdService = null; var userExplorationPermissionsService = null; var userService = null; var voiceoverRecordingService = null; let zone = null; var stateName = 'State1'; var explorationId = 'exp1'; var isTranslatableSpy = null; var mockExternalSaveEventEmitter = null; var mockActiveContentIdChangedEventEmitter = new EventEmitter(); var mockActiveLanguageChangedEventEmitter = new EventEmitter(); var mockShowTranslationTabBusyModalEventEmitter = new EventEmitter(); importAllAngularServices(); beforeEach(angular.mock.module('directiveTemplates')); beforeEach(() => { alertsService = TestBed.inject(AlertsService); editabilityService = TestBed.inject(EditabilityService); siteAnalyticsService = TestBed.inject(SiteAnalyticsService); stateRecordedVoiceoversService = TestBed.inject( StateRecordedVoiceoversService); zone = TestBed.inject(NgZone); OppiaAngularRootComponent.ngZone = zone; spyOn(zone, 'runOutsideAngular').and.callFake((fn: Function) => fn()); spyOn(zone, 'run').and.callFake((fn: Function) => fn()); }); beforeEach(angular.mock.module('oppia', function($provide) { mockExternalSaveEventEmitter = new EventEmitter(); $provide.value('ExternalSaveService', { onExternalSave: mockExternalSaveEventEmitter }); $provide.value('NgbModal', { open: () => { return { result: Promise.resolve() }; } }); })); beforeEach(angular.mock.inject(function($injector) { $interval = $injector.get('$interval'); $q = $injector.get('$q'); $rootScope = $injector.get('$rootScope'); $scope = $rootScope.$new(); $uibModal = $injector.get('$uibModal'); ngbModal = $injector.get('NgbModal'); assetsBackendApiService = $injector.get('AssetsBackendApiService'); audioPlayerService = $injector.get('AudioPlayerService'); contextService = $injector.get('ContextService'); spyOn(contextService, 'getExplorationId').and.returnValue(explorationId); explorationStatesService = $injector.get('ExplorationStatesService'); stateEditorService = $injector.get('StateEditorService'); translationLanguageService = $injector.get('TranslationLanguageService'); translationTabActiveContentIdService = $injector.get( 'TranslationTabActiveContentIdService'); voiceoverRecordingService = $injector.get('VoiceoverRecordingService'); isTranslatableSpy = spyOn(editabilityService, 'isTranslatable'); isTranslatableSpy.and.returnValue(false); spyOn(translationLanguageService, 'getActiveLanguageCode').and .returnValue('en'); spyOn(translationTabActiveContentIdService, 'getActiveContentId').and .returnValue('content'); spyOn(stateEditorService, 'getActiveStateName').and.returnValue( stateName); // This method is being mocked because this spec only handles with // recordedvoiceovers and not all the exploration. spyOn(explorationStatesService, 'saveRecordedVoiceovers').and .callFake(function() {}); spyOn(ngbModal, 'open').and.returnValue({ componentInstance: { busyMessage: '' }, result: Promise.resolve() } as NgbModalRef); spyOnProperty( translationTabActiveContentIdService, 'onActiveContentIdChanged').and.returnValue( mockActiveContentIdChangedEventEmitter); spyOnProperty( translationLanguageService, 'onActiveLanguageChanged').and.returnValue( mockActiveLanguageChangedEventEmitter); spyOnProperty( stateEditorService, 'onShowTranslationTabBusyModal').and.returnValue( mockShowTranslationTabBusyModalEventEmitter); stateRecordedVoiceoversService.init( stateName, RecordedVoiceovers.createFromBackendDict({ voiceovers_mapping: { content: { en: { duration_secs: 0, filename: '', file_size_bytes: 0, needs_update: false } } } })); var directive = $injector.get('audioTranslationBarDirective')[0]; ctrl = $injector.instantiate(directive.controller, { $scope: $scope, AlertsService: alertsService, StateRecordedVoiceoversService: stateRecordedVoiceoversService }); ctrl.$onInit(); $scope.getVoiceoverRecorder(); })); afterEach(() => { ctrl.$onDestroy(); }); it('should evaluate $scope properties after audio bar initialization', function() { expect($scope.languageCode).toBe('en'); expect($scope.contentId).toBe('content'); }); it('should not check and start recording when user deny access', function() { spyOn(voiceoverRecordingService, 'status').and.returnValue({ isAvailable: true }); spyOn(voiceoverRecordingService, 'startRecordingAsync').and.returnValue( $q.reject()); $scope.checkAndStartRecording(); $scope.$apply(); expect($scope.unsupportedBrowser).toBe(false); expect($scope.recordingPermissionDenied).toBe(true); expect($scope.cannotRecord).toBe(true); }); it('should not check and start recording when voiceover recorder is' + ' not available', function() { spyOn(voiceoverRecordingService, 'status').and.returnValue({ isAvailable: false }); spyOn(voiceoverRecordingService, 'startRecordingAsync').and.returnValue( $q.resolve()); $scope.checkAndStartRecording(); expect($scope.unsupportedBrowser).toBe(true); expect($scope.cannotRecord).toBe(true); }); it('should stop recording when reaching recording time limit', function() { spyOn(voiceoverRecordingService, 'status').and.returnValue({ isAvailable: true }); spyOn(voiceoverRecordingService, 'startRecordingAsync').and.returnValue( $q.resolve()); spyOn($scope.voiceoverRecorder, 'getMp3Data').and.returnValue( $q.resolve([])); var waveSurferObjSpy = { load: () => {}, on: () => {}, pause: () => {}, play: () => {}, }; // This throws "Argument of type '{ load: () => void; ... }' // is not assignable to parameter of type 'WaveSurfer'." // This is because the actual 'WaveSurfer.create` function returns a // object with around 50 more properties than `waveSurferObjSpy`. // We need to suppress this error because we have defined the properties // we need for this test in 'waveSurferObjSpy' object. // @ts-expect-error spyOn(WaveSurfer, 'create').and.returnValue(waveSurferObjSpy); $scope.checkAndStartRecording(); $scope.$apply(); $scope.elapsedTime = 298; $interval.flush(1000); expect($scope.recordingComplete).toBe(true); expect($scope.unsupportedBrowser).toBe(false); expect($scope.showRecorderWarning).toBe(true); expect($scope.recordingPermissionDenied).toBe(false); expect($scope.cannotRecord).toBe(false); expect($scope.selectedRecording).toBe(true); expect($scope.getTranslationTabBusyMessage()).toBe( 'You haven\'t saved your recording. Please save or ' + 'cancel the recording.'); }); it('should stop record when content id changes', function() { spyOn(voiceoverRecordingService, 'status').and.returnValue({ isAvailable: true, isRecording: true }); spyOn(voiceoverRecordingService, 'startRecordingAsync').and.returnValue( $q.resolve()); spyOn(voiceoverRecordingService, 'stopRecord'); spyOn(voiceoverRecordingService, 'closeRecorder'); $scope.checkAndStartRecording(); $scope.$apply(); mockActiveContentIdChangedEventEmitter.emit(); expect(voiceoverRecordingService.stopRecord).toHaveBeenCalled(); expect(voiceoverRecordingService.closeRecorder).toHaveBeenCalled(); expect($scope.getTranslationTabBusyMessage()).toBe( 'You haven\'t finished recording. Please stop ' + 'recording and either save or cancel the recording.'); }); it('should stop record when language changes', function() { spyOn(voiceoverRecordingService, 'status').and.returnValue({ isAvailable: true, isRecording: true }); spyOn(voiceoverRecordingService, 'startRecordingAsync').and.returnValue( $q.resolve()); spyOn(voiceoverRecordingService, 'stopRecord'); spyOn(voiceoverRecordingService, 'closeRecorder'); $scope.checkAndStartRecording(); $scope.$apply(); mockActiveLanguageChangedEventEmitter.emit(); expect(voiceoverRecordingService.stopRecord).toHaveBeenCalled(); expect(voiceoverRecordingService.closeRecorder).toHaveBeenCalled(); }); it('should open translation busy modal on event', () => { mockShowTranslationTabBusyModalEventEmitter.emit(); expect(ngbModal.open).toHaveBeenCalled(); }); it('should stop record when externalSave flag is broadcasted', function() { spyOn(voiceoverRecordingService, 'status').and.returnValue({ isAvailable: true, isRecording: true }); spyOn(voiceoverRecordingService, 'startRecordingAsync').and.returnValue( $q.resolve()); spyOn(voiceoverRecordingService, 'stopRecord'); spyOn(voiceoverRecordingService, 'closeRecorder'); spyOn(audioPlayerService, 'stop'); spyOn(audioPlayerService, 'clear'); $scope.checkAndStartRecording(); $scope.$apply(); mockExternalSaveEventEmitter.emit(); expect(voiceoverRecordingService.stopRecord).toHaveBeenCalled(); expect(voiceoverRecordingService.closeRecorder).toHaveBeenCalled(); expect(audioPlayerService.stop).toHaveBeenCalled(); expect(audioPlayerService.clear).toHaveBeenCalled(); expect($scope.audioBlob).toBe(null); }); it('should toggle audio needs update', function() { spyOn( stateRecordedVoiceoversService.displayed, 'toggleNeedsUpdateAttribute'); $scope.toggleAudioNeedsUpdate(); expect( stateRecordedVoiceoversService.displayed.toggleNeedsUpdateAttribute) .toHaveBeenCalled(); expect($scope.audioNeedsUpdate).toBe(true); $scope.toggleAudioNeedsUpdate(); expect( stateRecordedVoiceoversService.displayed.toggleNeedsUpdateAttribute) .toHaveBeenCalled(); expect($scope.audioNeedsUpdate).toBe(false); }); it('should play and pause unsaved audio when wave surfer calls on method' + ' callback', fakeAsync(() => { spyOn($scope.voiceoverRecorder, 'getMp3Data').and.returnValue( $q.resolve([])); var waveSurferObjSpy = { load: () => {}, on: (evt, callback) => { callback(); }, pause: () => {}, play: () => {}, }; spyOn(waveSurferObjSpy, 'play'); // This throws "Argument of type '{ load: () => void; ... }' // is not assignable to parameter of type 'WaveSurfer'." // This is because the actual 'WaveSurfer.create` function returns a // object with around 50 more properties than `waveSurferObjSpy`. // We need to suppress this error because we have defined the properties // we need for this test in 'waveSurferObjSpy' object. // @ts-expect-error spyOn(WaveSurfer, 'create').and.returnValue(waveSurferObjSpy); $scope.stopRecording(); tick(); $scope.$apply(); $scope.playAndPauseUnsavedAudio(); expect($scope.unsavedAudioIsPlaying).toBe(false); expect(waveSurferObjSpy.play).toHaveBeenCalled(); })); it('should play and pause unsaved audio when wave surfer on method does' + ' not call the callbacl', function() { spyOn($scope.voiceoverRecorder, 'getMp3Data').and.returnValue( $q.resolve([])); var waveSurferObjSpy = { load: () => {}, on: () => {}, pause: () => {}, play: () => {}, }; spyOn(waveSurferObjSpy, 'play'); spyOn(waveSurferObjSpy, 'pause'); // This throws "Argument of type '{ load: () => void; ... }' // is not assignable to parameter of type 'WaveSurfer'." // This is because the actual 'WaveSurfer.create` function returns a // object with around 50 more properties than `waveSurferObjSpy`. // We need to suppress this error because we have defined the properties // we need for this test in 'waveSurferObjSpy' object. // @ts-expect-error spyOn(WaveSurfer, 'create').and.returnValue(waveSurferObjSpy); $scope.stopRecording(); $scope.$apply(); $scope.playAndPauseUnsavedAudio(); expect($scope.unsavedAudioIsPlaying).toBe(true); expect(waveSurferObjSpy.play).toHaveBeenCalled(); $scope.playAndPauseUnsavedAudio(); expect($scope.unsavedAudioIsPlaying).toBe(false); expect(waveSurferObjSpy.pause).toHaveBeenCalled(); }); it('should toggle start and stop recording on keyup event', function() { $scope.canVoiceover = true; $scope.isAudioAvailable = false; spyOn(siteAnalyticsService, 'registerStartAudioRecordingEvent'); var keyEvent = new KeyboardEvent('keyup', { code: 'KeyR' }); document.body.dispatchEvent(keyEvent); expect(siteAnalyticsService.registerStartAudioRecordingEvent) .toHaveBeenCalled(); spyOn(voiceoverRecordingService, 'status').and.returnValue({ isAvailable: true, isRecording: true }); spyOn($scope.voiceoverRecorder, 'getMp3Data').and.returnValue( $q.resolve([])); var waveSurferObjSpy = { load: () => {}, on: () => {}, pause: () => {}, play: () => {}, }; // This throws "Argument of type '{ load: () => void; ... }' // is not assignable to parameter of type 'WaveSurfer'." // This is because the actual 'WaveSurfer.create` function returns a // object with around 50 more properties than `waveSurferObjSpy`. // We need to suppress this error because we have defined the properties // we need for this test in 'waveSurferObjSpy' object. // @ts-expect-error spyOn(WaveSurfer, 'create').and.returnValue(waveSurferObjSpy); document.body.dispatchEvent(keyEvent); expect($scope.recordingComplete).toBe(true); // Reset value to not affect other specs. $scope.canVoiceover = false; }); it('should not toggle start and stop recording on keyup event', function() { $scope.canVoiceover = false; spyOn(siteAnalyticsService, 'registerStartAudioRecordingEvent'); var keyEvent = new KeyboardEvent('keyup', { code: 'KeyR' }); document.body.dispatchEvent(keyEvent); expect(siteAnalyticsService.registerStartAudioRecordingEvent) .not.toHaveBeenCalled(); }); it('should rerecord successfully', function() { $scope.reRecord(); $scope.$apply(); expect($scope.selectedRecording).toBe(false); }); it('should cancel recording successfully', function() { $scope.cancelRecording(); expect($scope.selectedRecording).toBe(false); expect($scope.audioIsUpdating).toBe(false); expect($scope.audioBlob).toBe(null); expect($scope.showRecorderWarning).toBe(false); }); it('should save recorded audio successfully', function() { $scope.updateAudio(); $scope.$apply(); spyOn(siteAnalyticsService, 'registerSaveRecordedAudioEvent'); spyOn(alertsService, 'addSuccessMessage'); spyOn(stateRecordedVoiceoversService.displayed, 'addVoiceover'); spyOn(assetsBackendApiService, 'saveAudio').and.returnValue($q.resolve({ duration_secs: 90 })); $scope.saveRecordedAudio(); expect(siteAnalyticsService.registerSaveRecordedAudioEvent) .toHaveBeenCalled(); expect($scope.audioIsCurrentlyBeingSaved).toBe(true); $scope.$apply(); expect(stateRecordedVoiceoversService.displayed.addVoiceover) .toHaveBeenCalled(); expect($scope.durationSecs).toBe(90); expect($scope.audioIsCurrentlyBeingSaved).toBe(false); expect(alertsService.addSuccessMessage).toHaveBeenCalledWith( 'Succesfuly uploaded recorded audio.'); }); it('should use reject handler when saving recorded audio fails', function() { spyOn(siteAnalyticsService, 'registerSaveRecordedAudioEvent'); spyOn(alertsService, 'addWarning'); spyOn(assetsBackendApiService, 'saveAudio').and.returnValue($q.reject({ error: 'It was not possible to save the recorded audio' })); $scope.saveRecordedAudio(); expect(siteAnalyticsService.registerSaveRecordedAudioEvent) .toHaveBeenCalled(); $scope.$apply(); expect($scope.audioIsCurrentlyBeingSaved).toBe(false); expect(alertsService.addWarning).toHaveBeenCalledWith( 'It was not possible to save the recorded audio'); }); it('should open translation tab busy modal with NgbModal', fakeAsync(() => { $scope.openTranslationTabBusyModal(); tick(); $rootScope.$applyAsync(); expect(ngbModal.open).toHaveBeenCalled(); })); it('should play a loaded audio translation', function() { spyOn(audioPlayerService, 'isPlaying').and.returnValue(false); spyOn(audioPlayerService, 'isTrackLoaded').and.returnValue(true); spyOn(audioPlayerService, 'play'); expect($scope.isPlayingUploadedAudio()).toBe(false); $scope.playPauseUploadedAudioTranslation('en'); expect($scope.audioTimerIsShown).toBe(true); expect(audioPlayerService.play).toHaveBeenCalled(); }); it('should play a not loaded audio translation', function() { spyOn(audioPlayerService, 'isPlaying').and.returnValue(false); spyOn(audioPlayerService, 'isTrackLoaded').and.returnValue(false); spyOn(audioPlayerService, 'loadAsync').and.returnValue($q.resolve()); spyOn(audioPlayerService, 'play'); expect($scope.isPlayingUploadedAudio()).toBe(false); $scope.playPauseUploadedAudioTranslation('en'); $scope.$apply(); expect($scope.audioLoadingIndicatorIsShown).toBe(false); expect($scope.audioIsLoading).toBe(false); expect($scope.audioTimerIsShown).toBe(true); expect(audioPlayerService.play).toHaveBeenCalled(); }); it('should pause ongoing audio translation', function() { spyOn(audioPlayerService, 'isPlaying').and.returnValue(true); spyOn(audioPlayerService, 'pause'); expect($scope.isPlayingUploadedAudio()).toBe(true); $scope.playPauseUploadedAudioTranslation('en'); expect(audioPlayerService.pause).toHaveBeenCalled(); }); it('should get set progress audio timer', function() { const setCurrentTimeSpy = spyOn(audioPlayerService, 'setCurrentTime'); setCurrentTimeSpy.and.returnValue(undefined); $scope.setProgress({value: 100}); expect(setCurrentTimeSpy).toHaveBeenCalledWith(100); }); it('should delete audio when closing delete audio translation modal', fakeAsync(() => { spyOn(stateRecordedVoiceoversService.displayed, 'deleteVoiceover'); $scope.openDeleteAudioTranslationModal(); tick(); $scope.$apply(); expect(stateRecordedVoiceoversService.displayed.deleteVoiceover) .toHaveBeenCalled(); expect(explorationStatesService.saveRecordedVoiceovers) .toHaveBeenCalled(); })); it('should not delete audio when dismissing delete audio translation' + ' modal', fakeAsync(() => { spyOn(stateRecordedVoiceoversService.displayed, 'deleteVoiceover'); ngbModal.open = jasmine.createSpy().and.returnValue({ result: Promise.reject() } as NgbModalRef); $scope.openDeleteAudioTranslationModal(); tick(); $scope.$apply(); expect(stateRecordedVoiceoversService.displayed.deleteVoiceover) .not.toHaveBeenCalled(); })); it('should add audio translation when closing add audio translation modal', fakeAsync(() => { spyOn(stateRecordedVoiceoversService.displayed, 'deleteVoiceover'); spyOn(stateRecordedVoiceoversService.displayed, 'addVoiceover').and .callFake(function() {}); spyOn($uibModal, 'open').and.returnValue({ result: $q.resolve({ durationSecs: 100 }) }); $scope.openAddAudioTranslationModal(); tick(); $scope.$apply(); expect(stateRecordedVoiceoversService.displayed.deleteVoiceover) .toHaveBeenCalled(); expect(stateRecordedVoiceoversService.displayed.addVoiceover) .toHaveBeenCalled(); expect($scope.durationSecs).toBe(0); })); it('should not add audio translation when dismissing add audio' + ' translation modal', function() { spyOn(alertsService, 'clearWarnings'); spyOn($uibModal, 'open').and.returnValue({ result: $q.reject() }); $scope.openAddAudioTranslationModal(); $scope.$apply(); expect(alertsService.clearWarnings).toHaveBeenCalled(); }); it('should apply changed when view update emits', fakeAsync(() => { const applyAsyncSpy = spyOn($scope, '$applyAsync'); audioPlayerService.viewUpdate.emit(); audioPlayerService.onAudioStop.next(); tick(); $rootScope.$applyAsync(); expect(applyAsyncSpy).toHaveBeenCalled(); })); describe('when compiling html element', function() { var compiledElement = null; var mainBodyDivMock = null; var translationTabDivMock = null; var dropAreaMessageDivMock = null; var scope = null; beforeEach(angular.mock.inject(function($injector, $compile) { $q = $injector.get('$q'); $rootScope = $injector.get('$rootScope'); $scope = $rootScope.$new(); $uibModal = $injector.get('$uibModal'); userExplorationPermissionsService = $injector.get( 'UserExplorationPermissionsService'); userService = $injector.get('UserService'); spyOn(userService, 'getUserInfoAsync').and.returnValue( $q.resolve({ isLoggedIn: () => true })); spyOn(userExplorationPermissionsService, 'getPermissionsAsync').and .returnValue($q.resolve({ canVoiceover: true })); stateRecordedVoiceoversService.init( stateName, RecordedVoiceovers.createFromBackendDict({ voiceovers_mapping: { content: { en: { duration_secs: 0, filename: '', file_size_bytes: 0, needs_update: false } } } })); dropAreaMessageDivMock = document.createElement('div'); dropAreaMessageDivMock.classList.add('oppia-drop-area-message'); translationTabDivMock = $(document.createElement('div')); mainBodyDivMock = $(document.createElement('div')); var jQuerySpy = spyOn(window, '$'); jQuerySpy .withArgs('.oppia-translation-tab').and.returnValue( translationTabDivMock) .withArgs('.oppia-main-body').and.returnValue(mainBodyDivMock); jQuerySpy.and.callThrough(); var element = angular.element( '<audio-translation-bar is-translation-tab-busy="true">' + '</audio-translation-bar>'); compiledElement = $compile(element)($scope); $rootScope.$digest(); scope = compiledElement[0].getControllerScope(); })); it('should trigger dragover event in translation tab element', function() { translationTabDivMock.triggerHandler('dragover'); expect(scope.dropAreaIsAccessible).toBe(true); expect(scope.userIsGuest).toBe(false); }); it('should trigger drop event in translation tab element and open add' + ' audio translation modal', function() { translationTabDivMock.triggerHandler('dragover'); spyOn($uibModal, 'open').and.callThrough(); translationTabDivMock.triggerHandler({ originalEvent: { dataTransfer: { files: [] } }, preventDefault: () => {}, stopPropagation: () => {}, target: dropAreaMessageDivMock, type: 'drop', }); expect(scope.dropAreaIsAccessible) .toBe(false); $scope.$apply(); expect($uibModal.open).toHaveBeenCalled(); }); it('should trigger dragleave event in main body element', function() { mainBodyDivMock.triggerHandler({ pageX: 0, pageY: 0, preventDefault: () => {}, type: 'dragleave' }); expect(compiledElement[0].getControllerScope().dropAreaIsAccessible) .toBe(false); expect(compiledElement[0].getControllerScope().userIsGuest).toBe(false); }); }); });
the_stack
import { BSONRegExp, Decimal128, ObjectId } from 'bson'; import { expectAssignable, expectNotType, expectType } from 'tsd'; import { Filter, MongoClient } from '../../../../src'; /** * test the Filter type using collection.find<T>() method * MongoDB uses Filter type for every method that performs a document search * for example: findX, updateX, deleteX, distinct, countDocuments * So we don't add duplicate tests for every collection method and only use find */ const client = new MongoClient(''); const db = client.db('test'); /** * Test the generic Filter using collection.find<T>() method */ // a collection model for all possible MongoDB BSON types and TypeScript types interface PetModel { _id: ObjectId; // ObjectId field name?: string; // optional field family: string; // string field age: number; // number field type: 'dog' | 'cat' | 'fish'; // union field isCute: boolean; // boolean field bestFriend?: PetModel; // object field (Embedded/Nested Documents) createdAt: Date; // date field treats: string[]; // array of string playTimePercent: Decimal128; // bson Decimal128 type readonly friends?: ReadonlyArray<PetModel>; // readonly array of objects playmates?: PetModel[]; // writable array of objects } const spot = { _id: new ObjectId('577fa2d90c4cc47e31cf4b6f'), name: 'Spot', family: 'Andersons', age: 2, type: 'dog' as const, isCute: true, createdAt: new Date(), treats: ['kibble', 'bone'], playTimePercent: new Decimal128('0.999999') }; expectAssignable<PetModel>(spot); const collectionT = db.collection<PetModel>('test.filterQuery'); // Assert that collection.find uses the Filter helper like so: const filter: Filter<PetModel> = {}; collectionT.find(filter); collectionT.find(spot); // a whole model definition is also a valid filter // Now tests below can directly test the Filter helper, and are implicitly checking collection.find /** * test simple field queries e.g. `{ name: 'Spot' }` */ /// it should query __string__ fields expectType<PetModel[]>(await collectionT.find({ name: 'Spot' }).toArray()); // it should query string fields by regex expectType<PetModel[]>(await collectionT.find({ name: /Blu/i }).toArray()); // it should query string fields by RegExp object, and bson regex expectType<PetModel[]>(await collectionT.find({ name: new RegExp('MrMeow', 'i') }).toArray()); expectType<PetModel[]>(await collectionT.find({ name: new BSONRegExp('MrMeow', 'i') }).toArray()); /// it should not accept wrong types for string fields expectNotType<Filter<PetModel>>({ name: 23 }); expectNotType<Filter<PetModel>>({ name: { suffix: 'Jr' } }); expectNotType<Filter<PetModel>>({ name: ['Spot'] }); /// it should query __number__ fields await collectionT.find({ age: 12 }).toArray(); /// it should not accept wrong types for number fields expectNotType<Filter<PetModel>>({ age: /12/i }); // it cannot query number fields by regex expectNotType<Filter<PetModel>>({ age: '23' }); expectNotType<Filter<PetModel>>({ age: { prefix: 43 } }); expectNotType<Filter<PetModel>>({ age: [23, 43] }); /// it should query __nested document__ fields only by exact match // TODO: we currently cannot enforce field order but field order is important for mongo await collectionT.find({ bestFriend: spot }).toArray(); /// nested documents query should contain all required fields expectNotType<Filter<PetModel>>({ bestFriend: { family: 'Andersons' } }); /// it should not accept wrong types for nested document fields expectNotType<Filter<PetModel>>({ bestFriend: 21 }); expectNotType<Filter<PetModel>>({ bestFriend: 'Andersons' }); expectNotType<Filter<PetModel>>({ bestFriend: [spot] }); expectNotType<Filter<PetModel>>({ bestFriend: [{ family: 'Andersons' }] }); /// it should query __array__ fields by exact match await collectionT.find({ treats: ['kibble', 'bone'] }).toArray(); /// it should query __array__ fields by element type expectType<PetModel[]>(await collectionT.find({ treats: 'kibble' }).toArray()); expectType<PetModel[]>(await collectionT.find({ treats: /kibble/i }).toArray()); expectType<PetModel[]>(await collectionT.find({ friends: spot }).toArray()); /// it should not query array fields by wrong types expectNotType<Filter<PetModel>>({ treats: 12 }); expectNotType<Filter<PetModel>>({ friends: { name: 'not a full model' } }); /// it should accept MongoDB ObjectId and Date as query parameter await collectionT.find({ createdAt: new Date() }).toArray(); await collectionT.find({ _id: new ObjectId() }).toArray(); /// it should not accept other types for ObjectId and Date expectNotType<Filter<PetModel>>({ createdAt: { a: 12 } }); expectNotType<Filter<PetModel>>({ createdAt: spot }); expectNotType<Filter<PetModel>>({ _id: '577fa2d90c4cc47e31cf4b6f' }); expectNotType<Filter<PetModel>>({ _id: { a: 12 } }); /** * test comparison query operators */ /// $eq $ne $gt $gte $lt $lte queries should behave exactly like simple queries above await collectionT.find({ name: { $eq: 'Spot' } }).toArray(); await collectionT.find({ name: { $eq: /Spot/ } }).toArray(); await collectionT.find({ type: { $eq: 'dog' } }).toArray(); await collectionT.find({ age: { $gt: 12, $lt: 13 } }).toArray(); await collectionT.find({ treats: { $eq: 'kibble' } }).toArray(); await collectionT.find({ scores: { $gte: 23 } }).toArray(); await collectionT.find({ createdAt: { $lte: new Date() } }).toArray(); await collectionT.find({ friends: { $ne: spot } }).toArray(); /// it should not accept wrong queries expectNotType<Filter<PetModel>>({ name: { $ne: 12 } }); expectNotType<Filter<PetModel>>({ gender: { $eq: '123' } }); expectNotType<Filter<PetModel>>({ createdAt: { $lte: '1232' } }); /// it should not accept undefined query selectors in query object expectNotType<Filter<PetModel>>({ age: { $undefined: 12 } }); /// it should query simple fields using $in and $nin selectors await collectionT.find({ name: { $in: ['Spot', 'MrMeow', 'Bubbles'] } }).toArray(); await collectionT.find({ age: { $in: [12, 13] } }).toArray(); await collectionT.find({ friends: { $in: [spot] } }).toArray(); await collectionT.find({ createdAt: { $nin: [new Date()] } }).toArray(); /// it should query array fields using $in and $nin selectors await collectionT.find({ treats: { $in: ['kibble', 'bone', 'tuna'] } }).toArray(); await collectionT.find({ treats: { $in: [/kibble/, /bone/, /tuna/] } }).toArray(); /// it should not accept wrong params for $in and $nin selectors expectNotType<Filter<PetModel>>({ name: { $in: ['Spot', 32, 42] } }); expectNotType<Filter<PetModel>>({ age: { $in: [/12/, 12] } }); expectNotType<Filter<PetModel>>({ createdAt: { $nin: [12] } }); expectNotType<Filter<PetModel>>({ friends: { $in: [{ name: 'MrMeow' }] } }); expectNotType<Filter<PetModel>>({ treats: { $in: [{ $eq: 21 }] } }); /** * test logical query operators */ /// it should accept any query selector for __$not operator__ await collectionT.find({ name: { $not: { $eq: 'Spot' } } }).toArray(); /// it should accept regex for string fields await collectionT.find({ name: { $not: /Hi/i } }).toArray(); await collectionT.find({ treats: { $not: /Hi/ } }).toArray(); /// it should not accept simple queries in $not operator expectNotType<Filter<PetModel>>({ name: { $not: 'Spot' } }); /// it should not accept regex for non strings expectNotType<Filter<PetModel>>({ age: { $not: /sdsd/ } }); /// it should accept any filter query for __$and, $or, $nor operator__ await collectionT.find({ $and: [{ name: 'Spot' }] }).toArray(); await collectionT.find({ $and: [{ name: 'Spot' }, { age: { $in: [12, 14] } }] }).toArray(); await collectionT.find({ $or: [{ name: /Spot/i }, { treats: 's12' }] }).toArray(); await collectionT.find({ $nor: [{ name: { $ne: 'Spot' } }] }).toArray(); /// it should not accept __$and, $or, $nor operator__ as non-root query expectNotType<Filter<PetModel>>({ name: { $or: ['Spot', 'Bubbles'] } }); /// it should not accept single objects for __$and, $or, $nor operator__ query expectNotType<Filter<PetModel>>({ $and: { name: 'Spot' } }); /** * test 'element' query operators */ /// it should query using $exists await collectionT.find({ name: { $exists: true } }).toArray(); await collectionT.find({ name: { $exists: false } }).toArray(); /// it should not query $exists by wrong values expectNotType<Filter<PetModel>>({ name: { $exists: '' } }); expectNotType<Filter<PetModel>>({ name: { $exists: 'true' } }); /** * test evaluation query operators */ /// it should query using $regex await collectionT.find({ name: { $regex: /12/i } }).toArray(); /// it should query using $regex and $options await collectionT.find({ name: { $regex: /12/, $options: 'i' } }).toArray(); /// it should not accept $regex for none string fields expectNotType<Filter<PetModel>>({ age: { $regex: /12/ } }); expectNotType<Filter<PetModel>>({ age: { $options: '3' } }); /// it should query using $mod await collectionT.find({ age: { $mod: [12, 2] } }).toArray(); /// it should not accept $mod for none number fields expectNotType<Filter<PetModel>>({ name: { $mod: [12, 2] } }); /// it should not accept $mod with less/more than 2 elements expectNotType<Filter<PetModel>>({ age: { $mod: [12, 2, 2] } }); expectNotType<Filter<PetModel>>({ age: { $mod: [12] } }); expectNotType<Filter<PetModel>>({ age: { $mod: [] } }); /// it should fulltext search using $text await collectionT.find({ $text: { $search: 'Hello' } }).toArray(); await collectionT.find({ $text: { $search: 'Hello', $caseSensitive: true } }).toArray(); /// it should fulltext search only by string expectNotType<Filter<PetModel>>({ $text: { $search: 21, $caseSensitive: 'true' } }); expectNotType<Filter<PetModel>>({ $text: { $search: { name: 'MrMeow' } } }); expectNotType<Filter<PetModel>>({ $text: { $search: /regex/g } }); /// it should query using $where await collectionT.find({ $where: 'function() { return true }' }).toArray(); await collectionT .find({ $where: function () { expectType<PetModel>(this); return this.name === 'MrMeow'; } }) .toArray(); /// it should not fail when $where is not Function or String expectNotType<Filter<PetModel>>({ $where: 12 }); expectNotType<Filter<PetModel>>({ $where: /regex/g }); /** * test array query operators */ /// it should query array fields await collectionT.find({ treats: { $size: 2 } }).toArray(); await collectionT.find({ treats: { $all: ['kibble', 'bone'] } }).toArray(); await collectionT.find({ friends: { $elemMatch: { name: 'MrMeow' } } }).toArray(); await collectionT.find({ playmates: { $elemMatch: { name: 'MrMeow' } } }).toArray(); /// it should not query non array fields expectNotType<Filter<PetModel>>({ name: { $all: ['world', 'world'] } }); expectNotType<Filter<PetModel>>({ age: { $elemMatch: [1, 2] } }); expectNotType<Filter<PetModel>>({ type: { $size: 2 } }); // dot key case that shows it is assignable even when the referenced key is the wrong type expectAssignable<Filter<PetModel>>({ 'bestFriend.name': 23 }); // using dot notation permits any type for the key expectNotType<Filter<PetModel>>({ bestFriend: { name: 23 } });
the_stack
import { $, addDisposableListener, addStandardDisposableListener, append, clearNode, Dimension, EventHelper, EventType, isAncestor } from 'vs/base/browser/dom'; import { ActionBar } from 'vs/base/browser/ui/actionbar/actionbar'; import { ButtonBar } from 'vs/base/browser/ui/button/button'; import { IMessage, InputBox, MessageType } from 'vs/base/browser/ui/inputbox/inputBox'; import { DomScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement'; import { ITableRenderer, ITableVirtualDelegate } from 'vs/base/browser/ui/table/table'; import { Action, IAction } from 'vs/base/common/actions'; import { CancellationToken } from 'vs/base/common/cancellation'; import { Codicon, registerCodicon } from 'vs/base/common/codicons'; import { debounce } from 'vs/base/common/decorators'; import { Emitter, Event } from 'vs/base/common/event'; import { KeyCode } from 'vs/base/common/keyCodes'; import { splitName } from 'vs/base/common/labels'; import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { parseLinkedText } from 'vs/base/common/linkedText'; import { Schemas } from 'vs/base/common/network'; import { ScrollbarVisibility } from 'vs/base/common/scrollable'; import { URI } from 'vs/base/common/uri'; import { localize } from 'vs/nls'; import { ConfigurationScope, Extensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry'; import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { IFileDialogService } from 'vs/platform/dialogs/common/dialogs'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ILabelService } from 'vs/platform/label/common/label'; import { WorkbenchTable } from 'vs/platform/list/browser/listService'; import { Link } from 'vs/platform/opener/browser/link'; import product from 'vs/platform/product/common/product'; import { Registry } from 'vs/platform/registry/common/platform'; import { isVirtualResource, isVirtualWorkspace } from 'vs/platform/remote/common/remoteHosts'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { buttonBackground, buttonSecondaryBackground, editorErrorForeground } from 'vs/platform/theme/common/colorRegistry'; import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace'; import { attachButtonStyler, attachInputBoxStyler, attachStylerCallback } from 'vs/platform/theme/common/styler'; import { IThemeService, ThemeIcon } from 'vs/platform/theme/common/themeService'; import { IWorkspaceTrustManagementService } from 'vs/platform/workspace/common/workspaceTrust'; import { ISingleFolderWorkspaceIdentifier, toWorkspaceIdentifier } from 'vs/platform/workspaces/common/workspaces'; import { EditorPane } from 'vs/workbench/browser/parts/editor/editorPane'; import { IEditorOpenContext } from 'vs/workbench/common/editor'; import { ChoiceAction } from 'vs/workbench/common/notifications'; import { debugIconStartForeground } from 'vs/workbench/contrib/debug/browser/debugColors'; import { IExtensionsWorkbenchService, LIST_WORKSPACE_UNSUPPORTED_EXTENSIONS_COMMAND_ID } from 'vs/workbench/contrib/extensions/common/extensions'; import { settingsEditIcon, settingsRemoveIcon } from 'vs/workbench/contrib/preferences/browser/preferencesIcons'; import { IWorkbenchConfigurationService } from 'vs/workbench/services/configuration/common/configuration'; import { IExtensionManifestPropertiesService } from 'vs/workbench/services/extensions/common/extensionManifestPropertiesService'; import { IUriIdentityService } from 'vs/workbench/services/uriIdentity/common/uriIdentity'; import { WorkspaceTrustEditorInput } from 'vs/workbench/services/workspaces/browser/workspaceTrustEditorInput'; import { IEditorOptions } from 'vs/platform/editor/common/editor'; import { getExtensionDependencies } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { EnablementState, IWorkbenchExtensionEnablementService } from 'vs/workbench/services/extensionManagement/common/extensionManagement'; import { posix } from 'vs/base/common/path'; import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent'; export const shieldIcon = registerCodicon('workspace-trust-icon', Codicon.shield); const checkListIcon = registerCodicon('workspace-trusted-check-icon', Codicon.check); const xListIcon = registerCodicon('workspace-trusted-x-icon', Codicon.x); const folderPickerIcon = registerCodicon('folder-picker', Codicon.folder); interface ITrustedUriItem { parentOfWorkspaceItem: boolean; uri: URI; } class WorkspaceTrustedUrisTable extends Disposable { private readonly _onDidAcceptEdit: Emitter<ITrustedUriItem> = this._register(new Emitter<ITrustedUriItem>()); readonly onDidAcceptEdit: Event<ITrustedUriItem> = this._onDidAcceptEdit.event; private readonly _onDidRejectEdit: Emitter<ITrustedUriItem> = this._register(new Emitter<ITrustedUriItem>()); readonly onDidRejectEdit: Event<ITrustedUriItem> = this._onDidRejectEdit.event; private _onEdit: Emitter<ITrustedUriItem> = this._register(new Emitter<ITrustedUriItem>()); readonly onEdit: Event<ITrustedUriItem> = this._onEdit.event; private _onDelete: Emitter<ITrustedUriItem> = this._register(new Emitter<ITrustedUriItem>()); readonly onDelete: Event<ITrustedUriItem> = this._onDelete.event; private readonly table: WorkbenchTable<ITrustedUriItem>; private readonly descriptionElement: HTMLElement; constructor( private readonly container: HTMLElement, @IInstantiationService private readonly instantiationService: IInstantiationService, @IWorkspaceContextService private readonly workspaceService: IWorkspaceContextService, @IWorkspaceTrustManagementService private readonly workspaceTrustManagementService: IWorkspaceTrustManagementService, @IUriIdentityService private readonly uriService: IUriIdentityService, @ILabelService private readonly labelService: ILabelService, @IThemeService private readonly themeService: IThemeService, @IFileDialogService private readonly fileDialogService: IFileDialogService ) { super(); this.descriptionElement = container.appendChild($('.workspace-trusted-folders-description')); const tableElement = container.appendChild($('.trusted-uris-table')); const addButtonBarElement = container.appendChild($('.trusted-uris-button-bar')); this.table = this.instantiationService.createInstance( WorkbenchTable, 'WorkspaceTrust', tableElement, new TrustedUriTableVirtualDelegate(), [ { label: localize('hostColumnLabel', "Host"), tooltip: '', weight: 1, templateId: TrustedUriHostColumnRenderer.TEMPLATE_ID, project(row: ITrustedUriItem): ITrustedUriItem { return row; } }, { label: localize('pathColumnLabel', "Path"), tooltip: '', weight: 8, templateId: TrustedUriPathColumnRenderer.TEMPLATE_ID, project(row: ITrustedUriItem): ITrustedUriItem { return row; } }, { label: '', tooltip: '', weight: 1, minimumWidth: 75, maximumWidth: 75, templateId: TrustedUriActionsColumnRenderer.TEMPLATE_ID, project(row: ITrustedUriItem): ITrustedUriItem { return row; } }, ], [ this.instantiationService.createInstance(TrustedUriHostColumnRenderer), this.instantiationService.createInstance(TrustedUriPathColumnRenderer, this), this.instantiationService.createInstance(TrustedUriActionsColumnRenderer, this, this.currentWorkspaceUri), ], { horizontalScrolling: false, alwaysConsumeMouseWheel: false, openOnSingleClick: false, multipleSelectionSupport: false, accessibilityProvider: { getAriaLabel: (item: ITrustedUriItem) => { const hostLabel = getHostLabel(this.labelService, item); if (hostLabel === undefined || hostLabel.length === 0) { return localize('trustedFolderAriaLabel', "{0}, trusted", this.labelService.getUriLabel(item.uri)); } return localize('trustedFolderWithHostAriaLabel', "{0} on {1}, trusted", this.labelService.getUriLabel(item.uri), hostLabel); }, getWidgetAriaLabel: () => localize('trustedFoldersAndWorkspaces', "Trusted Folders & Workspaces") } } ) as WorkbenchTable<ITrustedUriItem>; this._register(this.table.onDidOpen(item => { // default prevented when input box is double clicked #125052 if (item && item.element && !item.browserEvent?.defaultPrevented) { this.edit(item.element, true); } })); const buttonBar = this._register(new ButtonBar(addButtonBarElement)); const addButton = this._register(buttonBar.addButton({ title: localize('addButton', "Add Folder") })); addButton.label = localize('addButton', "Add Folder"); this._register(attachButtonStyler(addButton, this.themeService)); this._register(addButton.onDidClick(async () => { const uri = await this.fileDialogService.showOpenDialog({ canSelectFiles: false, canSelectFolders: true, canSelectMany: false, defaultUri: this.currentWorkspaceUri, openLabel: localize('trustUri', "Trust Folder"), title: localize('selectTrustedUri', "Select Folder To Trust") }); if (uri) { this.workspaceTrustManagementService.setUrisTrust(uri, true); } })); this._register(this.workspaceTrustManagementService.onDidChangeTrustedFolders(() => { this.updateTable(); })); } private getIndexOfTrustedUriEntry(item: ITrustedUriItem): number { const index = this.trustedUriEntries.indexOf(item); if (index === -1) { for (let i = 0; i < this.trustedUriEntries.length; i++) { if (this.trustedUriEntries[i].uri === item.uri) { return i; } } } return index; } private selectTrustedUriEntry(item: ITrustedUriItem, focus: boolean = true): void { const index = this.getIndexOfTrustedUriEntry(item); if (index !== -1) { if (focus) { this.table.domFocus(); this.table.setFocus([index]); } this.table.setSelection([index]); } } private get currentWorkspaceUri(): URI { return this.workspaceService.getWorkspace().folders[0]?.uri || URI.file('/'); } private get trustedUriEntries(): ITrustedUriItem[] { const currentWorkspace = this.workspaceService.getWorkspace(); const currentWorkspaceUris = currentWorkspace.folders.map(folder => folder.uri); if (currentWorkspace.configuration) { currentWorkspaceUris.push(currentWorkspace.configuration); } const entries = this.workspaceTrustManagementService.getTrustedUris().map(uri => { let relatedToCurrentWorkspace = false; for (const workspaceUri of currentWorkspaceUris) { relatedToCurrentWorkspace = relatedToCurrentWorkspace || this.uriService.extUri.isEqualOrParent(workspaceUri, uri); } return { uri, parentOfWorkspaceItem: relatedToCurrentWorkspace }; }); // Sort entries const sortedEntries = entries.sort((a, b) => { if (a.uri.scheme !== b.uri.scheme) { if (a.uri.scheme === Schemas.file) { return -1; } if (b.uri.scheme === Schemas.file) { return 1; } } const aIsWorkspace = a.uri.path.endsWith('.code-workspace'); const bIsWorkspace = b.uri.path.endsWith('.code-workspace'); if (aIsWorkspace !== bIsWorkspace) { if (aIsWorkspace) { return 1; } if (bIsWorkspace) { return -1; } } return a.uri.fsPath.localeCompare(b.uri.fsPath); }); return sortedEntries; } layout(): void { this.table.layout((this.trustedUriEntries.length * TrustedUriTableVirtualDelegate.ROW_HEIGHT) + TrustedUriTableVirtualDelegate.HEADER_ROW_HEIGHT, undefined); } updateTable(): void { const entries = this.trustedUriEntries; this.container.classList.toggle('empty', entries.length === 0); this.descriptionElement.innerText = entries.length ? localize('trustedFoldersDescription', "You trust the following folders, their subfolders, and workspace files.") : localize('noTrustedFoldersDescriptions', "You haven't trusted any folders or workspace files yet."); this.table.splice(0, Number.POSITIVE_INFINITY, this.trustedUriEntries); this.layout(); } validateUri(path: string, item?: ITrustedUriItem): IMessage | null { if (!item) { return null; } if (item.uri.scheme === 'vscode-vfs') { const segments = path.split(posix.sep).filter(s => s.length); if (segments.length === 0 && path.startsWith(posix.sep)) { return { type: MessageType.WARNING, content: localize('trustAll', "You will trust all repositories on {0}.", getHostLabel(this.labelService, item)) }; } if (segments.length === 1) { return { type: MessageType.WARNING, content: localize('trustOrg', "You will trust all repositories and forks under '{0}' on {1}.", segments[0], getHostLabel(this.labelService, item)) }; } if (segments.length > 2) { return { type: MessageType.ERROR, content: localize('invalidTrust', "You cannot trust individual folders within a repository.", path) }; } } return null; } acceptEdit(item: ITrustedUriItem, uri: URI) { const trustedFolders = this.workspaceTrustManagementService.getTrustedUris(); const index = trustedFolders.findIndex(u => this.uriService.extUri.isEqual(u, item.uri)); if (index >= trustedFolders.length || index === -1) { trustedFolders.push(uri); } else { trustedFolders[index] = uri; } this.workspaceTrustManagementService.setTrustedUris(trustedFolders); this._onDidAcceptEdit.fire(item); } rejectEdit(item: ITrustedUriItem) { this._onDidRejectEdit.fire(item); } async delete(item: ITrustedUriItem) { await this.workspaceTrustManagementService.setUrisTrust([item.uri], false); this._onDelete.fire(item); } async edit(item: ITrustedUriItem, usePickerIfPossible?: boolean) { const canUseOpenDialog = item.uri.scheme === Schemas.file || ( item.uri.scheme === this.currentWorkspaceUri.scheme && this.uriService.extUri.isEqualAuthority(this.currentWorkspaceUri.authority, item.uri.authority) && !isVirtualResource(item.uri) ); if (canUseOpenDialog && usePickerIfPossible) { const uri = await this.fileDialogService.showOpenDialog({ canSelectFiles: false, canSelectFolders: true, canSelectMany: false, defaultUri: item.uri, openLabel: localize('trustUri', "Trust Folder"), title: localize('selectTrustedUri', "Select Folder To Trust") }); if (uri) { this.acceptEdit(item, uri[0]); } else { this.rejectEdit(item); } } else { this.selectTrustedUriEntry(item); this._onEdit.fire(item); } } } class TrustedUriTableVirtualDelegate implements ITableVirtualDelegate<ITrustedUriItem> { static readonly HEADER_ROW_HEIGHT = 30; static readonly ROW_HEIGHT = 24; readonly headerRowHeight = TrustedUriTableVirtualDelegate.HEADER_ROW_HEIGHT; getHeight(item: ITrustedUriItem) { return TrustedUriTableVirtualDelegate.ROW_HEIGHT; } } interface IActionsColumnTemplateData { readonly actionBar: ActionBar; } class TrustedUriActionsColumnRenderer implements ITableRenderer<ITrustedUriItem, IActionsColumnTemplateData> { static readonly TEMPLATE_ID = 'actions'; readonly templateId: string = TrustedUriActionsColumnRenderer.TEMPLATE_ID; constructor( private readonly table: WorkspaceTrustedUrisTable, private readonly currentWorkspaceUri: URI, @IUriIdentityService private readonly uriService: IUriIdentityService) { } renderTemplate(container: HTMLElement): IActionsColumnTemplateData { const element = container.appendChild($('.actions')); const actionBar = new ActionBar(element, { animated: false }); return { actionBar }; } renderElement(item: ITrustedUriItem, index: number, templateData: IActionsColumnTemplateData, height: number | undefined): void { templateData.actionBar.clear(); const canUseOpenDialog = item.uri.scheme === Schemas.file || ( item.uri.scheme === this.currentWorkspaceUri.scheme && this.uriService.extUri.isEqualAuthority(this.currentWorkspaceUri.authority, item.uri.authority) && !isVirtualResource(item.uri) ); const actions: IAction[] = []; if (canUseOpenDialog) { actions.push(this.createPickerAction(item)); } actions.push(this.createEditAction(item)); actions.push(this.createDeleteAction(item)); templateData.actionBar.push(actions, { icon: true }); } private createEditAction(item: ITrustedUriItem): IAction { return <IAction>{ class: ThemeIcon.asClassName(settingsEditIcon), enabled: true, id: 'editTrustedUri', tooltip: localize('editTrustedUri', "Edit Path"), run: () => { this.table.edit(item, false); } }; } private createPickerAction(item: ITrustedUriItem): IAction { return <IAction>{ class: ThemeIcon.asClassName(folderPickerIcon), enabled: true, id: 'pickerTrustedUri', tooltip: localize('pickerTrustedUri', "Open File Picker"), run: () => { this.table.edit(item, true); } }; } private createDeleteAction(item: ITrustedUriItem): IAction { return <IAction>{ class: ThemeIcon.asClassName(settingsRemoveIcon), enabled: true, id: 'deleteTrustedUri', tooltip: localize('deleteTrustedUri', "Delete Path"), run: async () => { await this.table.delete(item); } }; } disposeTemplate(templateData: IActionsColumnTemplateData): void { templateData.actionBar.dispose(); } } interface ITrustedUriPathColumnTemplateData { element: HTMLElement; pathLabel: HTMLElement; pathInput: InputBox; renderDisposables: DisposableStore; disposables: DisposableStore; } class TrustedUriPathColumnRenderer implements ITableRenderer<ITrustedUriItem, ITrustedUriPathColumnTemplateData> { static readonly TEMPLATE_ID = 'path'; readonly templateId: string = TrustedUriPathColumnRenderer.TEMPLATE_ID; private currentItem?: ITrustedUriItem; constructor( private readonly table: WorkspaceTrustedUrisTable, @IContextViewService private readonly contextViewService: IContextViewService, @IThemeService private readonly themeService: IThemeService, ) { } renderTemplate(container: HTMLElement): ITrustedUriPathColumnTemplateData { const element = container.appendChild($('.path')); const pathLabel = element.appendChild($('div.path-label')); const pathInput = new InputBox(element, this.contextViewService, { validationOptions: { validation: value => this.table.validateUri(value, this.currentItem) } }); const disposables = new DisposableStore(); disposables.add(attachInputBoxStyler(pathInput, this.themeService)); const renderDisposables = disposables.add(new DisposableStore()); return { element, pathLabel, pathInput, disposables, renderDisposables }; } renderElement(item: ITrustedUriItem, index: number, templateData: ITrustedUriPathColumnTemplateData, height: number | undefined): void { templateData.renderDisposables.clear(); this.currentItem = item; templateData.renderDisposables.add(this.table.onEdit(async (e) => { if (item === e) { templateData.element.classList.add('input-mode'); templateData.pathInput.focus(); templateData.pathInput.select(); templateData.element.parentElement!.style.paddingLeft = '0px'; } })); // stop double click action from re-rendering the element on the table #125052 templateData.renderDisposables.add(addDisposableListener(templateData.pathInput.element, EventType.DBLCLICK, e => { EventHelper.stop(e); })); const hideInputBox = () => { templateData.element.classList.remove('input-mode'); templateData.element.parentElement!.style.paddingLeft = '5px'; }; const accept = () => { hideInputBox(); const uri = item.uri.with({ path: templateData.pathInput.value }); templateData.pathLabel.innerText = templateData.pathInput.value; if (uri) { this.table.acceptEdit(item, uri); } }; const reject = () => { hideInputBox(); templateData.pathInput.value = stringValue; this.table.rejectEdit(item); }; templateData.renderDisposables.add(addStandardDisposableListener(templateData.pathInput.inputElement, EventType.KEY_DOWN, e => { let handled = false; if (e.equals(KeyCode.Enter)) { accept(); handled = true; } else if (e.equals(KeyCode.Escape)) { reject(); handled = true; } if (handled) { e.preventDefault(); e.stopPropagation(); } })); templateData.renderDisposables.add((addDisposableListener(templateData.pathInput.inputElement, EventType.BLUR, () => { reject(); }))); const stringValue = item.uri.scheme === Schemas.file ? URI.revive(item.uri).fsPath : item.uri.path; templateData.pathInput.value = stringValue; templateData.pathLabel.innerText = stringValue; templateData.element.classList.toggle('current-workspace-parent', item.parentOfWorkspaceItem); // templateData.pathLabel.style.display = ''; } disposeTemplate(templateData: ITrustedUriPathColumnTemplateData): void { templateData.disposables.dispose(); templateData.renderDisposables.dispose(); } } interface ITrustedUriHostColumnTemplateData { element: HTMLElement; hostContainer: HTMLElement; buttonBarContainer: HTMLElement; disposables: DisposableStore; renderDisposables: DisposableStore; } function getHostLabel(labelService: ILabelService, item: ITrustedUriItem): string { return item.uri.authority ? labelService.getHostLabel(item.uri.scheme, item.uri.authority) : localize('localAuthority', "Local"); } class TrustedUriHostColumnRenderer implements ITableRenderer<ITrustedUriItem, ITrustedUriHostColumnTemplateData> { static readonly TEMPLATE_ID = 'host'; readonly templateId: string = TrustedUriHostColumnRenderer.TEMPLATE_ID; constructor( @ILabelService private readonly labelService: ILabelService, ) { } renderTemplate(container: HTMLElement): ITrustedUriHostColumnTemplateData { const disposables = new DisposableStore(); const renderDisposables = disposables.add(new DisposableStore()); const element = container.appendChild($('.host')); const hostContainer = element.appendChild($('div.host-label')); const buttonBarContainer = element.appendChild($('div.button-bar')); return { element, hostContainer, buttonBarContainer, disposables, renderDisposables }; } renderElement(item: ITrustedUriItem, index: number, templateData: ITrustedUriHostColumnTemplateData, height: number | undefined): void { templateData.renderDisposables.clear(); templateData.renderDisposables.add({ dispose: () => { clearNode(templateData.buttonBarContainer); } }); templateData.hostContainer.innerText = getHostLabel(this.labelService, item); templateData.element.classList.toggle('current-workspace-parent', item.parentOfWorkspaceItem); templateData.hostContainer.style.display = ''; templateData.buttonBarContainer.style.display = 'none'; } disposeTemplate(templateData: ITrustedUriHostColumnTemplateData): void { templateData.disposables.dispose(); } } export class WorkspaceTrustEditor extends EditorPane { static readonly ID: string = 'workbench.editor.workspaceTrust'; private rootElement!: HTMLElement; // Header Section private headerContainer!: HTMLElement; private headerTitleContainer!: HTMLElement; private headerTitleIcon!: HTMLElement; private headerTitleText!: HTMLElement; private headerDescription!: HTMLElement; private bodyScrollBar!: DomScrollableElement; // Affected Features Section private affectedFeaturesContainer!: HTMLElement; private trustedContainer!: HTMLElement; private untrustedContainer!: HTMLElement; // Settings Section private configurationContainer!: HTMLElement; private workspaceTrustedUrisTable!: WorkspaceTrustedUrisTable; constructor( @ITelemetryService telemetryService: ITelemetryService, @IThemeService themeService: IThemeService, @IStorageService storageService: IStorageService, @IWorkspaceContextService private readonly workspaceService: IWorkspaceContextService, @IExtensionsWorkbenchService private readonly extensionWorkbenchService: IExtensionsWorkbenchService, @IExtensionManifestPropertiesService private readonly extensionManifestPropertiesService: IExtensionManifestPropertiesService, @IInstantiationService private readonly instantiationService: IInstantiationService, @IContextMenuService private readonly contextMenuService: IContextMenuService, @IWorkspaceTrustManagementService private readonly workspaceTrustManagementService: IWorkspaceTrustManagementService, @IWorkbenchConfigurationService private readonly configurationService: IWorkbenchConfigurationService, @IWorkbenchExtensionEnablementService private readonly extensionEnablementService: IWorkbenchExtensionEnablementService ) { super(WorkspaceTrustEditor.ID, telemetryService, themeService, storageService); } protected createEditor(parent: HTMLElement): void { this.rootElement = append(parent, $('.workspace-trust-editor', { tabindex: '0' })); this.rootElement.style.visibility = 'hidden'; this.createHeaderElement(this.rootElement); const scrollableContent = $('.workspace-trust-editor-body'); this.bodyScrollBar = this._register(new DomScrollableElement(scrollableContent, { horizontal: ScrollbarVisibility.Hidden, vertical: ScrollbarVisibility.Auto, })); append(this.rootElement, this.bodyScrollBar.getDomNode()); this.createAffectedFeaturesElement(scrollableContent); this.createConfigurationElement(scrollableContent); this._register(attachStylerCallback(this.themeService, { debugIconStartForeground, editorErrorForeground, buttonBackground, buttonSecondaryBackground }, colors => { this.rootElement.style.setProperty('--workspace-trust-selected-color', colors.buttonBackground?.toString() || ''); this.rootElement.style.setProperty('--workspace-trust-unselected-color', colors.buttonSecondaryBackground?.toString() || ''); this.rootElement.style.setProperty('--workspace-trust-check-color', colors.debugIconStartForeground?.toString() || ''); this.rootElement.style.setProperty('--workspace-trust-x-color', colors.editorErrorForeground?.toString() || ''); })); // Navigate page with keyboard this._register(addDisposableListener(this.rootElement, EventType.KEY_DOWN, e => { const event = new StandardKeyboardEvent(e); if (event.equals(KeyCode.UpArrow) || event.equals(KeyCode.DownArrow)) { const navOrder = [this.headerContainer, this.trustedContainer, this.untrustedContainer, this.configurationContainer]; const currentIndex = navOrder.findIndex(element => { return isAncestor(document.activeElement, element); }); let newIndex = currentIndex; if (event.equals(KeyCode.DownArrow)) { newIndex++; } else if (event.equals(KeyCode.UpArrow)) { newIndex = Math.max(0, newIndex); newIndex--; } newIndex += navOrder.length; newIndex %= navOrder.length; navOrder[newIndex].focus(); } else if (event.equals(KeyCode.Escape)) { this.rootElement.focus(); } })); } override focus() { this.rootElement.focus(); } override async setInput(input: WorkspaceTrustEditorInput, options: IEditorOptions | undefined, context: IEditorOpenContext, token: CancellationToken): Promise<void> { await super.setInput(input, options, context, token); if (token.isCancellationRequested) { return; } await this.workspaceTrustManagementService.workspaceTrustInitialized; this.registerListeners(); this.render(); } private registerListeners(): void { this._register(this.extensionWorkbenchService.onChange(() => this.render())); this._register(this.configurationService.onDidChangeRestrictedSettings(() => this.render())); this._register(this.workspaceTrustManagementService.onDidChangeTrust(() => this.render())); this._register(this.workspaceTrustManagementService.onDidChangeTrustedFolders(() => this.render())); } private getHeaderContainerClass(trusted: boolean): string { if (trusted) { return 'workspace-trust-header workspace-trust-trusted'; } return 'workspace-trust-header workspace-trust-untrusted'; } private getHeaderTitleText(trusted: boolean): string { if (trusted) { if (this.workspaceTrustManagementService.isWorkspaceTrustForced()) { return localize('trustedUnsettableWindow', "This window is trusted"); } switch (this.workspaceService.getWorkbenchState()) { case WorkbenchState.EMPTY: return localize('trustedHeaderWindow', "You trust this window"); case WorkbenchState.FOLDER: return localize('trustedHeaderFolder', "You trust this folder"); case WorkbenchState.WORKSPACE: return localize('trustedHeaderWorkspace', "You trust this workspace"); } } return localize('untrustedHeader', "You are in Restricted Mode"); } private getHeaderTitleIconClassNames(trusted: boolean): string[] { return shieldIcon.classNamesArray; } private getFeaturesHeaderText(trusted: boolean): [string, string] { let title: string = ''; let subTitle: string = ''; switch (this.workspaceService.getWorkbenchState()) { case WorkbenchState.EMPTY: { title = trusted ? localize('trustedWindow', "In a Trusted Window") : localize('untrustedWorkspace', "In Restricted Mode"); subTitle = trusted ? localize('trustedWindowSubtitle', "You trust the authors of the files in the current window. All features are enabled:") : localize('untrustedWindowSubtitle', "You do not trust the authors of the files in the current window. The following features are disabled:"); break; } case WorkbenchState.FOLDER: { title = trusted ? localize('trustedFolder', "In a Trusted Folder") : localize('untrustedWorkspace', "In Restricted Mode"); subTitle = trusted ? localize('trustedFolderSubtitle', "You trust the authors of the files in the current folder. All features are enabled:") : localize('untrustedFolderSubtitle', "You do not trust the authors of the files in the current folder. The following features are disabled:"); break; } case WorkbenchState.WORKSPACE: { title = trusted ? localize('trustedWorkspace', "In a Trusted Workspace") : localize('untrustedWorkspace', "In Restricted Mode"); subTitle = trusted ? localize('trustedWorkspaceSubtitle', "You trust the authors of the files in the current workspace. All features are enabled:") : localize('untrustedWorkspaceSubtitle', "You do not trust the authors of the files in the current workspace. The following features are disabled:"); break; } } return [title, subTitle]; } private rendering = false; private rerenderDisposables: DisposableStore = this._register(new DisposableStore()); @debounce(100) private async render() { if (this.rendering) { return; } this.rendering = true; this.rerenderDisposables.clear(); const isWorkspaceTrusted = this.workspaceTrustManagementService.isWorkspaceTrusted(); this.rootElement.classList.toggle('trusted', isWorkspaceTrusted); this.rootElement.classList.toggle('untrusted', !isWorkspaceTrusted); // Header Section this.headerTitleText.innerText = this.getHeaderTitleText(isWorkspaceTrusted); this.headerTitleIcon.className = 'workspace-trust-title-icon'; this.headerTitleIcon.classList.add(...this.getHeaderTitleIconClassNames(isWorkspaceTrusted)); this.headerDescription.innerText = ''; const headerDescriptionText = append(this.headerDescription, $('div')); headerDescriptionText.innerText = isWorkspaceTrusted ? localize('trustedDescription', "All features are enabled because trust has been granted to the workspace.") : localize('untrustedDescription', "{0} is in a restricted mode intended for safe code browsing.", product.nameShort); const headerDescriptionActions = append(this.headerDescription, $('div')); const headerDescriptionActionsText = localize({ key: 'workspaceTrustEditorHeaderActions', comment: ['Please ensure the markdown link syntax is not broken up with whitespace [text block](link block)'] }, "[Configure your settings]({0}) or [learn more](https://aka.ms/vscode-workspace-trust).", `command:workbench.trust.configure`); for (const node of parseLinkedText(headerDescriptionActionsText).nodes) { if (typeof node === 'string') { append(headerDescriptionActions, document.createTextNode(node)); } else { this.rerenderDisposables.add(this.instantiationService.createInstance(Link, headerDescriptionActions, { ...node, tabIndex: -1 }, {})); } } this.headerContainer.className = this.getHeaderContainerClass(isWorkspaceTrusted); this.rootElement.setAttribute('aria-label', `${localize('root element label', "Manage Workspace Trust")}: ${this.headerContainer.innerText}`); // Settings const restrictedSettings = this.configurationService.restrictedSettings; const configurationRegistry = Registry.as<IConfigurationRegistry>(Extensions.Configuration); const settingsRequiringTrustedWorkspaceCount = restrictedSettings.default.filter(key => { const property = configurationRegistry.getConfigurationProperties()[key]; // cannot be configured in workspace if (property.scope === ConfigurationScope.APPLICATION || property.scope === ConfigurationScope.MACHINE) { return false; } // If deprecated include only those configured in the workspace if (property.deprecationMessage || property.markdownDeprecationMessage) { if (restrictedSettings.workspace?.includes(key)) { return true; } if (restrictedSettings.workspaceFolder) { for (const workspaceFolderSettings of restrictedSettings.workspaceFolder.values()) { if (workspaceFolderSettings.includes(key)) { return true; } } } return false; } return true; }).length; // Features List this.renderAffectedFeatures(settingsRequiringTrustedWorkspaceCount, this.getExtensionCount()); // Configuration Tree this.workspaceTrustedUrisTable.updateTable(); this.bodyScrollBar.getDomNode().style.height = `calc(100% - ${this.headerContainer.clientHeight}px)`; this.bodyScrollBar.scanDomNode(); this.rootElement.style.visibility = ''; this.rendering = false; } private getExtensionCount(): number { const set = new Set<string>(); const inVirtualWorkspace = isVirtualWorkspace(this.workspaceService.getWorkspace()); const localExtensions = this.extensionWorkbenchService.local.filter(ext => ext.local).map(ext => ext.local!); for (const extension of localExtensions) { const enablementState = this.extensionEnablementService.getEnablementState(extension); if (enablementState !== EnablementState.EnabledGlobally && enablementState !== EnablementState.EnabledWorkspace && enablementState !== EnablementState.DisabledByTrustRequirement && enablementState !== EnablementState.DisabledByExtensionDependency) { continue; } if (inVirtualWorkspace && this.extensionManifestPropertiesService.getExtensionVirtualWorkspaceSupportType(extension.manifest) === false) { continue; } if (this.extensionManifestPropertiesService.getExtensionUntrustedWorkspaceSupportType(extension.manifest) !== true) { set.add(extension.identifier.id); continue; } const dependencies = getExtensionDependencies(localExtensions, extension); if (dependencies.some(ext => this.extensionManifestPropertiesService.getExtensionUntrustedWorkspaceSupportType(ext.manifest) === false)) { set.add(extension.identifier.id); } } return set.size; } private createHeaderElement(parent: HTMLElement): void { this.headerContainer = append(parent, $('.workspace-trust-header', { tabIndex: '0' })); this.headerTitleContainer = append(this.headerContainer, $('.workspace-trust-title')); this.headerTitleIcon = append(this.headerTitleContainer, $('.workspace-trust-title-icon')); this.headerTitleText = append(this.headerTitleContainer, $('.workspace-trust-title-text')); this.headerDescription = append(this.headerContainer, $('.workspace-trust-description')); } private createConfigurationElement(parent: HTMLElement): void { this.configurationContainer = append(parent, $('.workspace-trust-settings', { tabIndex: '0' })); const configurationTitle = append(this.configurationContainer, $('.workspace-trusted-folders-title')); configurationTitle.innerText = localize('trustedFoldersAndWorkspaces', "Trusted Folders & Workspaces"); this.workspaceTrustedUrisTable = this._register(this.instantiationService.createInstance(WorkspaceTrustedUrisTable, this.configurationContainer)); } private createAffectedFeaturesElement(parent: HTMLElement): void { this.affectedFeaturesContainer = append(parent, $('.workspace-trust-features')); this.trustedContainer = append(this.affectedFeaturesContainer, $('.workspace-trust-limitations.trusted', { tabIndex: '0' })); this.untrustedContainer = append(this.affectedFeaturesContainer, $('.workspace-trust-limitations.untrusted', { tabIndex: '0' })); } private async renderAffectedFeatures(numSettings: number, numExtensions: number): Promise<void> { clearNode(this.trustedContainer); clearNode(this.untrustedContainer); // Trusted features const [trustedTitle, trustedSubTitle] = this.getFeaturesHeaderText(true); this.renderLimitationsHeaderElement(this.trustedContainer, trustedTitle, trustedSubTitle); const trustedContainerItems = this.workspaceService.getWorkbenchState() === WorkbenchState.EMPTY ? [ localize('trustedTasks', "Tasks are allowed to run"), localize('trustedDebugging', "Debugging is enabled"), localize('trustedExtensions', "All extensions are enabled") ] : [ localize('trustedTasks', "Tasks are allowed to run"), localize('trustedDebugging', "Debugging is enabled"), localize('trustedSettings', "All workspace settings are applied"), localize('trustedExtensions', "All extensions are enabled") ]; this.renderLimitationsListElement(this.trustedContainer, trustedContainerItems, checkListIcon.classNamesArray); // Restricted Mode features const [untrustedTitle, untrustedSubTitle] = this.getFeaturesHeaderText(false); this.renderLimitationsHeaderElement(this.untrustedContainer, untrustedTitle, untrustedSubTitle); const untrustedContainerItems = this.workspaceService.getWorkbenchState() === WorkbenchState.EMPTY ? [ localize('untrustedTasks', "Tasks are not allowed to run"), localize('untrustedDebugging', "Debugging is disabled"), localize({ key: 'untrustedExtensions', comment: ['Please ensure the markdown link syntax is not broken up with whitespace [text block](link block)'] }, "[{0} extensions]({1}) are disabled or have limited functionality", numExtensions, `command:${LIST_WORKSPACE_UNSUPPORTED_EXTENSIONS_COMMAND_ID}`) ] : [ localize('untrustedTasks', "Tasks are not allowed to run"), localize('untrustedDebugging', "Debugging is disabled"), numSettings ? localize({ key: 'untrustedSettings', comment: ['Please ensure the markdown link syntax is not broken up with whitespace [text block](link block)'] }, "[{0} workspace settings]({1}) are not applied", numSettings, 'command:settings.filterUntrusted') : localize('no untrustedSettings', "Workspace settings requiring trust are not applied"), localize({ key: 'untrustedExtensions', comment: ['Please ensure the markdown link syntax is not broken up with whitespace [text block](link block)'] }, "[{0} extensions]({1}) are disabled or have limited functionality", numExtensions, `command:${LIST_WORKSPACE_UNSUPPORTED_EXTENSIONS_COMMAND_ID}`) ]; this.renderLimitationsListElement(this.untrustedContainer, untrustedContainerItems, xListIcon.classNamesArray); if (this.workspaceTrustManagementService.isWorkspaceTrusted()) { if (this.workspaceTrustManagementService.canSetWorkspaceTrust()) { this.addDontTrustButtonToElement(this.untrustedContainer); } else { this.addTrustedTextToElement(this.untrustedContainer); } } else { if (this.workspaceTrustManagementService.canSetWorkspaceTrust()) { this.addTrustButtonToElement(this.trustedContainer); } } } private createButtonRow(parent: HTMLElement, actions: Action | Action[], enabled?: boolean): void { const buttonRow = append(parent, $('.workspace-trust-buttons-row')); const buttonContainer = append(buttonRow, $('.workspace-trust-buttons')); const buttonBar = this.rerenderDisposables.add(new ButtonBar(buttonContainer)); if (actions instanceof Action) { actions = [actions]; } for (const action of actions) { const button = action instanceof ChoiceAction && action.menu?.length ? buttonBar.addButtonWithDropdown({ title: true, actions: action.menu ?? [], contextMenuProvider: this.contextMenuService }) : buttonBar.addButton(); button.label = action.label; button.enabled = enabled !== undefined ? enabled : action.enabled; this.rerenderDisposables.add(button.onDidClick(e => { if (e) { EventHelper.stop(e, true); } action.run(); })); this.rerenderDisposables.add(attachButtonStyler(button, this.themeService)); } } private addTrustButtonToElement(parent: HTMLElement): void { const trustActions = [ new Action('workspace.trust.button.action.grant', localize('trustButton', "Trust"), undefined, true, async () => { await this.workspaceTrustManagementService.setWorkspaceTrust(true); }) ]; if (this.workspaceTrustManagementService.canSetParentFolderTrust()) { const workspaceIdentifier = toWorkspaceIdentifier(this.workspaceService.getWorkspace()) as ISingleFolderWorkspaceIdentifier; const { name } = splitName(splitName(workspaceIdentifier.uri.fsPath).parentPath); const trustMessageElement = append(parent, $('.trust-message-box')); trustMessageElement.innerText = localize('trustMessage', "Trust the authors of all files in the current folder or its parent '{0}'.", name); trustActions.push(new Action('workspace.trust.button.action.grantParent', localize('trustParentButton', "Trust Parent"), undefined, true, async () => { await this.workspaceTrustManagementService.setParentFolderTrust(true); })); } this.createButtonRow(parent, trustActions); } private addDontTrustButtonToElement(parent: HTMLElement): void { this.createButtonRow(parent, new Action('workspace.trust.button.action.deny', localize('dontTrustButton', "Don't Trust"), undefined, true, async () => { await this.workspaceTrustManagementService.setWorkspaceTrust(false); })); } private addTrustedTextToElement(parent: HTMLElement): void { if (this.workspaceService.getWorkbenchState() === WorkbenchState.EMPTY) { return; } const textElement = append(parent, $('.workspace-trust-untrusted-description')); if (!this.workspaceTrustManagementService.isWorkspaceTrustForced()) { textElement.innerText = this.workspaceService.getWorkbenchState() === WorkbenchState.WORKSPACE ? localize('untrustedWorkspaceReason', "This workspace is trusted via the bolded entries in the trusted folders below.") : localize('untrustedFolderReason', "This folder is trusted via the bolded entries in the the trusted folders below."); } else { textElement.innerText = localize('trustedForcedReason', "This window is trusted by nature of the workspace that is opened."); } } private renderLimitationsHeaderElement(parent: HTMLElement, headerText: string, subtitleText: string): void { const limitationsHeaderContainer = append(parent, $('.workspace-trust-limitations-header')); const titleElement = append(limitationsHeaderContainer, $('.workspace-trust-limitations-title')); const textElement = append(titleElement, $('.workspace-trust-limitations-title-text')); const subtitleElement = append(limitationsHeaderContainer, $('.workspace-trust-limitations-subtitle')); textElement.innerText = headerText; subtitleElement.innerText = subtitleText; } private renderLimitationsListElement(parent: HTMLElement, limitations: string[], iconClassNames: string[]): void { const listContainer = append(parent, $('.workspace-trust-limitations-list-container')); const limitationsList = append(listContainer, $('ul')); for (const limitation of limitations) { const limitationListItem = append(limitationsList, $('li')); const icon = append(limitationListItem, $('.list-item-icon')); const text = append(limitationListItem, $('.list-item-text')); icon.classList.add(...iconClassNames); const linkedText = parseLinkedText(limitation); for (const node of linkedText.nodes) { if (typeof node === 'string') { append(text, document.createTextNode(node)); } else { this.rerenderDisposables.add(this.instantiationService.createInstance(Link, text, { ...node, tabIndex: -1 }, {})); } } } } private layoutParticipants: { layout: () => void; }[] = []; layout(dimension: Dimension): void { if (!this.isVisible()) { return; } this.workspaceTrustedUrisTable.layout(); this.layoutParticipants.forEach(participant => { participant.layout(); }); this.bodyScrollBar.scanDomNode(); } }
the_stack
import { Template } from '@aws-cdk/assertions'; import * as iam from '@aws-cdk/aws-iam'; import * as kms from '@aws-cdk/aws-kms'; import * as cdk from '@aws-cdk/core'; import * as cxapi from '@aws-cdk/cx-api'; import * as ssm from '../lib'; test('creating a String SSM Parameter', () => { // GIVEN const stack = new cdk.Stack(); // WHEN new ssm.StringParameter(stack, 'Parameter', { allowedPattern: '.*', description: 'The value Foo', parameterName: 'FooParameter', stringValue: 'Foo', }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::SSM::Parameter', { AllowedPattern: '.*', Description: 'The value Foo', Name: 'FooParameter', Type: 'String', Value: 'Foo', }); }); test('type cannot be specified as AWS_EC2_IMAGE_ID', () => { // GIVEN const stack = new cdk.Stack(); // THEN expect(() => new ssm.StringParameter(stack, 'myParam', { stringValue: 'myValue', type: ssm.ParameterType.AWS_EC2_IMAGE_ID, })).toThrow('The type must either be ParameterType.STRING or ParameterType.STRING_LIST. Did you mean to set dataType: ParameterDataType.AWS_EC2_IMAGE instead?'); }); test('dataType can be specified', () => { // GIVEN const stack = new cdk.Stack(); // WHEN new ssm.StringParameter(stack, 'myParam', { stringValue: 'myValue', dataType: ssm.ParameterDataType.AWS_EC2_IMAGE, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::SSM::Parameter', { Value: 'myValue', DataType: 'aws:ec2:image', }); }); test('expect String SSM Parameter to have tier properly set', () => { // GIVEN const stack = new cdk.Stack(); // WHEN new ssm.StringParameter(stack, 'Parameter', { allowedPattern: '.*', description: 'The value Foo', parameterName: 'FooParameter', stringValue: 'Foo', tier: ssm.ParameterTier.ADVANCED, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::SSM::Parameter', { Tier: 'Advanced', }); }); test('String SSM Parameter rejects invalid values', () => { // GIVEN const stack = new cdk.Stack(); // THEN expect(() => new ssm.StringParameter(stack, 'Parameter', { allowedPattern: '^Bar$', stringValue: 'FooBar' })).toThrow( /does not match the specified allowedPattern/); }); test('String SSM Parameter allows unresolved tokens', () => { // GIVEN const stack = new cdk.Stack(); // THEN expect(() => { new ssm.StringParameter(stack, 'Parameter', { allowedPattern: '^Bar$', stringValue: cdk.Lazy.string({ produce: () => 'Foo!' }), }); }).not.toThrow(); }); test('creating a StringList SSM Parameter', () => { // GIVEN const stack = new cdk.Stack(); // WHEN new ssm.StringListParameter(stack, 'Parameter', { allowedPattern: '(Foo|Bar)', description: 'The values Foo and Bar', parameterName: 'FooParameter', stringListValue: ['Foo', 'Bar'], }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::SSM::Parameter', { AllowedPattern: '(Foo|Bar)', Description: 'The values Foo and Bar', Name: 'FooParameter', Type: 'StringList', Value: 'Foo,Bar', }); }); test('String SSM Parameter throws on long descriptions', () => { // GIVEN const stack = new cdk.Stack(); // THEN expect(() => { new ssm.StringParameter(stack, 'Parameter', { stringValue: 'Foo', description: '1024+ character long description: Lorem ipsum dolor sit amet, consectetuer adipiscing elit. \ Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, \ nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat \ massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, \ imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. \ Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, \ eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus \ varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. \ Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing \ sem neque sed ipsum.', }); }).toThrow(/Description cannot be longer than 1024 characters./); }); test('String SSM Parameter throws on long names', () => { // GIVEN const stack = new cdk.Stack(); // THEN expect(() => { new ssm.StringParameter(stack, 'Parameter', { stringValue: 'Foo', parameterName: '2048+ character long name: Lorem ipsum dolor sit amet, consectetuer adipiscing elit. \ Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, \ nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat \ massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, \ imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. \ Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, \ eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus \ varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. \ Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing \ sem neque sed ipsum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. \ Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, \ nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat \ massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, \ imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. \ Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, \ eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus \ varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. \ Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing \ sem neque sed ipsum.', }); }).toThrow(/name cannot be longer than 2048 characters./); }); test.each([ '/parameter/with spaces', 'charactersOtherThan^allowed', 'trying;this', ])('String SSM Parameter throws on invalid name %s', (parameterName) => { // GIVEN const stack = new cdk.Stack(); // THEN expect(() => { new ssm.StringParameter(stack, 'Parameter', { stringValue: 'Foo', parameterName }); }).toThrow(/name must only contain letters, numbers, and the following 4 symbols.*/); }); test('StringList SSM Parameter throws on long descriptions', () => { // GIVEN const stack = new cdk.Stack(); // THEN expect(() => { new ssm.StringListParameter(stack, 'Parameter', { stringListValue: ['Foo', 'Bar'], description: '1024+ character long description: Lorem ipsum dolor sit amet, consectetuer adipiscing elit. \ Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, \ nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat \ massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, \ imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. \ Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, \ eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus \ varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. \ Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing \ sem neque sed ipsum.', }); }).toThrow(/Description cannot be longer than 1024 characters./); }); test('StringList SSM Parameter throws on long names', () => { // GIVEN const stack = new cdk.Stack(); // THEN expect(() => { new ssm.StringListParameter(stack, 'Parameter', { stringListValue: ['Foo', 'Bar'], parameterName: '2048+ character long name: Lorem ipsum dolor sit amet, consectetuer adipiscing elit. \ Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, \ nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat \ massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, \ imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. \ Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, \ eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus \ varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. \ Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing \ sem neque sed ipsum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. \ Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, \ nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat \ massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, \ imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. \ Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, \ eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus \ varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. \ Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing \ sem neque sed ipsum.', }); }).toThrow(/name cannot be longer than 2048 characters./); }); test.each([ '/parameter/with spaces', 'charactersOtherThan^allowed', 'trying;this', ])('StringList SSM Parameter throws on invalid name %s', (parameterName) => { // GIVEN const stack = new cdk.Stack(); // THEN expect(() => { new ssm.StringListParameter(stack, 'Parameter', { stringListValue: ['Foo'], parameterName }); }).toThrow(/name must only contain letters, numbers, and the following 4 symbols.*/); }); test('StringList SSM Parameter values cannot contain commas', () => { // GIVEN const stack = new cdk.Stack(); // THEN expect(() => new ssm.StringListParameter(stack, 'Parameter', { stringListValue: ['Foo,Bar'] })).toThrow( /cannot contain the ',' character/); }); test('StringList SSM Parameter rejects invalid values', () => { // GIVEN const stack = new cdk.Stack(); // THEN expect(() => new ssm.StringListParameter(stack, 'Parameter', { allowedPattern: '^(Foo|Bar)$', stringListValue: ['Foo', 'FooBar'] })).toThrow( /does not match the specified allowedPattern/); }); test('StringList SSM Parameter allows unresolved tokens', () => { // GIVEN const stack = new cdk.Stack(); // THEN expect(() => new ssm.StringListParameter(stack, 'Parameter', { allowedPattern: '^(Foo|Bar)$', stringListValue: ['Foo', cdk.Lazy.string({ produce: () => 'Baz!' })], })).not.toThrow(); }); test('parameterArn is crafted correctly', () => { // GIVEN const stack = new cdk.Stack(); const param = new ssm.StringParameter(stack, 'Parameter', { stringValue: 'Foo' }); // THEN expect(stack.resolve(param.parameterArn)).toEqual({ 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, ':ssm:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':parameter/', { Ref: 'Parameter9E1B4FBA' }, ]], }); }); test('parameterName that includes a "/" must be fully qualified (i.e. begin with "/") as well', () => { // GIVEN const stack = new cdk.Stack(); // THEN expect(() => new ssm.StringParameter(stack, 'myParam', { stringValue: 'myValue', parameterName: 'path/to/parameter', })).toThrow(/Parameter names must be fully qualified/); expect(() => new ssm.StringListParameter(stack, 'myParam2', { stringListValue: ['foo', 'bar'], parameterName: 'path/to/parameter2', })).toThrow(/Parameter names must be fully qualified \(if they include \"\/\" they must also begin with a \"\/\"\)\: path\/to\/parameter2/); }); test('StringParameter.fromStringParameterName', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const param = ssm.StringParameter.fromStringParameterName(stack, 'MyParamName', 'MyParamName'); // THEN expect(stack.resolve(param.parameterArn)).toEqual({ 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, ':ssm:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':parameter/MyParamName', ]], }); expect(stack.resolve(param.parameterName)).toEqual('MyParamName'); expect(stack.resolve(param.parameterType)).toEqual('String'); expect(stack.resolve(param.stringValue)).toEqual({ Ref: 'MyParamNameParameter' }); Template.fromStack(stack).templateMatches({ Parameters: { MyParamNameParameter: { Type: 'AWS::SSM::Parameter::Value<String>', Default: 'MyParamName', }, }, }); }); test('StringParameter.fromStringParameterAttributes', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const param = ssm.StringParameter.fromStringParameterAttributes(stack, 'MyParamName', { parameterName: 'MyParamName', version: 2, }); // THEN expect(stack.resolve(param.parameterArn)).toEqual({ 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, ':ssm:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':parameter/MyParamName', ]], }); expect(stack.resolve(param.parameterName)).toEqual('MyParamName'); expect(stack.resolve(param.parameterType)).toEqual('String'); expect(stack.resolve(param.stringValue)).toEqual('{{resolve:ssm:MyParamName:2}}'); }); test('StringParameter.fromStringParameterAttributes with version from token', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const param = ssm.StringParameter.fromStringParameterAttributes(stack, 'MyParamName', { parameterName: 'MyParamName', version: cdk.Token.asNumber({ Ref: 'version' }), }); // THEN expect(stack.resolve(param.parameterArn)).toEqual({ 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, ':ssm:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':parameter/MyParamName', ]], }); expect(stack.resolve(param.parameterName)).toEqual('MyParamName'); expect(stack.resolve(param.parameterType)).toEqual('String'); expect(stack.resolve(param.stringValue)).toEqual({ 'Fn::Join': ['', [ '{{resolve:ssm:MyParamName:', { Ref: 'version' }, '}}', ]], }); }); test('StringParameter.fromSecureStringParameterAttributes', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const param = ssm.StringParameter.fromSecureStringParameterAttributes(stack, 'MyParamName', { parameterName: 'MyParamName', version: 2, }); // THEN expect(stack.resolve(param.parameterArn)).toEqual({ 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, ':ssm:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':parameter/MyParamName', ]], }); expect(stack.resolve(param.parameterName)).toEqual('MyParamName'); expect(stack.resolve(param.parameterType)).toEqual('SecureString'); expect(stack.resolve(param.stringValue)).toEqual('{{resolve:ssm-secure:MyParamName:2}}'); }); test('StringParameter.fromSecureStringParameterAttributes with version from token', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const param = ssm.StringParameter.fromSecureStringParameterAttributes(stack, 'MyParamName', { parameterName: 'MyParamName', version: cdk.Token.asNumber({ Ref: 'version' }), }); // THEN expect(stack.resolve(param.parameterArn)).toEqual({ 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, ':ssm:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':parameter/MyParamName', ]], }); expect(stack.resolve(param.parameterName)).toEqual('MyParamName'); expect(stack.resolve(param.parameterType)).toEqual('SecureString'); expect(stack.resolve(param.stringValue)).toEqual({ 'Fn::Join': ['', [ '{{resolve:ssm-secure:MyParamName:', { Ref: 'version' }, '}}', ]], }); }); test('StringParameter.fromSecureStringParameterAttributes with encryption key creates the correct policy for grantRead', () => { // GIVEN const stack = new cdk.Stack(); const key = kms.Key.fromKeyArn(stack, 'CustomKey', 'arn:aws:kms:us-east-1:123456789012:key/xyz'); const role = new iam.Role(stack, 'Role', { assumedBy: new iam.AccountRootPrincipal(), }); // WHEN const param = ssm.StringParameter.fromSecureStringParameterAttributes(stack, 'MyParamName', { parameterName: 'MyParamName', version: 2, encryptionKey: key, }); param.grantRead(role); // THEN Template.fromStack(stack).hasResourceProperties('AWS::IAM::Policy', { PolicyDocument: { Statement: [ { Action: 'kms:Decrypt', Effect: 'Allow', Resource: 'arn:aws:kms:us-east-1:123456789012:key/xyz', }, { Action: [ 'ssm:DescribeParameters', 'ssm:GetParameters', 'ssm:GetParameter', 'ssm:GetParameterHistory', ], Effect: 'Allow', Resource: { 'Fn::Join': [ '', [ 'arn:', { Ref: 'AWS::Partition', }, ':ssm:', { Ref: 'AWS::Region', }, ':', { Ref: 'AWS::AccountId', }, ':parameter/MyParamName', ], ], }, }, ], Version: '2012-10-17', }, }); }); test('StringParameter.fromSecureStringParameterAttributes with encryption key creates the correct policy for grantWrite', () => { // GIVEN const stack = new cdk.Stack(); const key = kms.Key.fromKeyArn(stack, 'CustomKey', 'arn:aws:kms:us-east-1:123456789012:key/xyz'); const role = new iam.Role(stack, 'Role', { assumedBy: new iam.AccountRootPrincipal(), }); // WHEN const param = ssm.StringParameter.fromSecureStringParameterAttributes(stack, 'MyParamName', { parameterName: 'MyParamName', version: 2, encryptionKey: key, }); param.grantWrite(role); // THEN Template.fromStack(stack).hasResourceProperties('AWS::IAM::Policy', { PolicyDocument: { Statement: [ { Action: [ 'kms:Encrypt', 'kms:ReEncrypt*', 'kms:GenerateDataKey*', ], Effect: 'Allow', Resource: 'arn:aws:kms:us-east-1:123456789012:key/xyz', }, { Action: 'ssm:PutParameter', Effect: 'Allow', Resource: { 'Fn::Join': [ '', [ 'arn:', { Ref: 'AWS::Partition', }, ':ssm:', { Ref: 'AWS::Region', }, ':', { Ref: 'AWS::AccountId', }, ':parameter/MyParamName', ], ], }, }, ], Version: '2012-10-17', }, }); }); test('StringParameter.fromSecureStringParameterAttributes without version', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const param = ssm.StringParameter.fromSecureStringParameterAttributes(stack, 'MyParamName', { parameterName: 'MyParamName', }); // THEN expect(stack.resolve(param.stringValue)).toEqual('{{resolve:ssm-secure:MyParamName:}}'); }); test('StringListParameter.fromName', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const param = ssm.StringListParameter.fromStringListParameterName(stack, 'MyParamName', 'MyParamName'); // THEN expect(stack.resolve(param.parameterArn)).toEqual({ 'Fn::Join': ['', [ 'arn:', { Ref: 'AWS::Partition' }, ':ssm:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':parameter/MyParamName', ]], }); expect(stack.resolve(param.parameterName)).toEqual('MyParamName'); expect(stack.resolve(param.parameterType)).toEqual('StringList'); expect(stack.resolve(param.stringListValue)).toEqual({ 'Fn::Split': [',', '{{resolve:ssm:MyParamName}}'] }); }); test('fromLookup will use the SSM context provider to read value during synthesis', () => { // GIVEN const app = new cdk.App({ context: { [cxapi.NEW_STYLE_STACK_SYNTHESIS_CONTEXT]: false } }); const stack = new cdk.Stack(app, 'my-staq', { env: { region: 'us-east-1', account: '12344' } }); // WHEN const value = ssm.StringParameter.valueFromLookup(stack, 'my-param-name'); // THEN expect(value).toEqual('dummy-value-for-my-param-name'); expect(app.synth().manifest.missing).toEqual([ { key: 'ssm:account=12344:parameterName=my-param-name:region=us-east-1', props: { account: '12344', region: 'us-east-1', parameterName: 'my-param-name', }, provider: 'ssm', }, ]); }); describe('valueForStringParameter', () => { test('returns a token that represents the SSM parameter value', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const value = ssm.StringParameter.valueForStringParameter(stack, 'my-param-name'); // THEN Template.fromStack(stack).templateMatches({ Parameters: { SsmParameterValuemyparamnameC96584B6F00A464EAD1953AFF4B05118Parameter: { Type: 'AWS::SSM::Parameter::Value<String>', Default: 'my-param-name', }, }, }); expect(stack.resolve(value)).toEqual({ Ref: 'SsmParameterValuemyparamnameC96584B6F00A464EAD1953AFF4B05118Parameter' }); }); test('de-dup based on parameter name', () => { // GIVEN const stack = new cdk.Stack(); // WHEN ssm.StringParameter.valueForStringParameter(stack, 'my-param-name'); ssm.StringParameter.valueForStringParameter(stack, 'my-param-name'); ssm.StringParameter.valueForStringParameter(stack, 'my-param-name-2'); ssm.StringParameter.valueForStringParameter(stack, 'my-param-name'); // THEN Template.fromStack(stack).templateMatches({ Parameters: { SsmParameterValuemyparamnameC96584B6F00A464EAD1953AFF4B05118Parameter: { Type: 'AWS::SSM::Parameter::Value<String>', Default: 'my-param-name', }, SsmParameterValuemyparamname2C96584B6F00A464EAD1953AFF4B05118Parameter: { Type: 'AWS::SSM::Parameter::Value<String>', Default: 'my-param-name-2', }, }, }); }); test('can query actual SSM Parameter Names, multiple times', () => { // GIVEN const stack = new cdk.Stack(); // WHEN ssm.StringParameter.valueForStringParameter(stack, '/my/param/name'); ssm.StringParameter.valueForStringParameter(stack, '/my/param/name'); }); }); test('rendering of parameter arns', () => { const stack = new cdk.Stack(); const param = new cdk.CfnParameter(stack, 'param'); const expectedA = { 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':ssm:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':parameter/bam']] }; const expectedB = { 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':ssm:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':parameter/', { Ref: 'param' }]] }; const expectedC = { 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':ssm:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':parameter', { Ref: 'param' }]] }; let i = 0; // WHEN const case1 = ssm.StringParameter.fromStringParameterName(stack, `p${i++}`, 'bam'); const case2 = ssm.StringParameter.fromStringParameterName(stack, `p${i++}`, '/bam'); const case4 = ssm.StringParameter.fromStringParameterAttributes(stack, `p${i++}`, { parameterName: 'bam' }); const case5 = ssm.StringParameter.fromStringParameterAttributes(stack, `p${i++}`, { parameterName: '/bam' }); const case6 = ssm.StringParameter.fromStringParameterAttributes(stack, `p${i++}`, { parameterName: param.valueAsString, simpleName: true }); const case7 = ssm.StringParameter.fromSecureStringParameterAttributes(stack, `p${i++}`, { parameterName: 'bam', version: 10 }); const case8 = ssm.StringParameter.fromSecureStringParameterAttributes(stack, `p${i++}`, { parameterName: '/bam', version: 10 }); const case9 = ssm.StringParameter.fromSecureStringParameterAttributes(stack, `p${i++}`, { parameterName: param.valueAsString, version: 10, simpleName: false }); // auto-generated name is always generated as a "simple name" (not/a/path) const case10 = new ssm.StringParameter(stack, `p${i++}`, { stringValue: 'value' }); // explicitly named physical name gives us a hint on how to render the ARN const case11 = new ssm.StringParameter(stack, `p${i++}`, { parameterName: '/foo/bar', stringValue: 'hello' }); const case12 = new ssm.StringParameter(stack, `p${i++}`, { parameterName: 'simple-name', stringValue: 'hello' }); const case13 = new ssm.StringListParameter(stack, `p${i++}`, { stringListValue: ['hello', 'world'] }); const case14 = new ssm.StringListParameter(stack, `p${i++}`, { parameterName: '/not/simple', stringListValue: ['hello', 'world'] }); const case15 = new ssm.StringListParameter(stack, `p${i++}`, { parameterName: 'simple', stringListValue: ['hello', 'world'] }); // THEN expect(stack.resolve(case1.parameterArn)).toEqual(expectedA); expect(stack.resolve(case2.parameterArn)).toEqual(expectedA); expect(stack.resolve(case4.parameterArn)).toEqual(expectedA); expect(stack.resolve(case5.parameterArn)).toEqual(expectedA); expect(stack.resolve(case6.parameterArn)).toEqual(expectedB); expect(stack.resolve(case7.parameterArn)).toEqual(expectedA); expect(stack.resolve(case8.parameterArn)).toEqual(expectedA); expect(stack.resolve(case9.parameterArn)).toEqual(expectedC); // new ssm.Parameters determine if "/" is needed based on the posture of `parameterName`. expect(stack.resolve(case10.parameterArn)).toEqual({ 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':ssm:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':parameter/', { Ref: 'p81BB0F6FE' }]] }); expect(stack.resolve(case11.parameterArn)).toEqual({ 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':ssm:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':parameter', { Ref: 'p97A508212' }]] }); expect(stack.resolve(case12.parameterArn)).toEqual({ 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':ssm:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':parameter/', { Ref: 'p107D6B8AB0' }]] }); expect(stack.resolve(case13.parameterArn)).toEqual({ 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':ssm:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':parameter/', { Ref: 'p118A9CB02C' }]] }); expect(stack.resolve(case14.parameterArn)).toEqual({ 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':ssm:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':parameter', { Ref: 'p129BE4CE91' }]] }); expect(stack.resolve(case15.parameterArn)).toEqual({ 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':ssm:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':parameter/', { Ref: 'p1326A2AEC4' }]] }); }); test('if parameterName is a token separator must be specified', () => { // GIVEN const stack = new cdk.Stack(); const param = new cdk.CfnParameter(stack, 'param'); let i = 0; // WHEN const p1 = new ssm.StringParameter(stack, `p${i++}`, { parameterName: param.valueAsString, stringValue: 'foo', simpleName: true }); const p2 = new ssm.StringParameter(stack, `p${i++}`, { parameterName: param.valueAsString, stringValue: 'foo', simpleName: false }); const p3 = new ssm.StringListParameter(stack, `p${i++}`, { parameterName: param.valueAsString, stringListValue: ['foo'], simpleName: false }); // THEN expect(stack.resolve(p1.parameterArn)).toEqual({ 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':ssm:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':parameter/', { Ref: 'p0B02A8F65' }]] }); expect(stack.resolve(p2.parameterArn)).toEqual({ 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':ssm:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':parameter', { Ref: 'p1E43AD5AC' }]] }); expect(stack.resolve(p3.parameterArn)).toEqual({ 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':ssm:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':parameter', { Ref: 'p2C1903AEB' }]] }); }); test('fails if name is a token and no explicit separator', () => { // GIVEN const stack = new cdk.Stack(); const param = new cdk.CfnParameter(stack, 'param'); let i = 0; // THEN const expected = /Unable to determine ARN separator for SSM parameter since the parameter name is an unresolved token. Use "fromAttributes" and specify "simpleName" explicitly/; expect(() => ssm.StringParameter.fromStringParameterName(stack, `p${i++}`, param.valueAsString)).toThrow(expected); expect(() => ssm.StringParameter.fromSecureStringParameterAttributes(stack, `p${i++}`, { parameterName: param.valueAsString, version: 1 })).toThrow(expected); expect(() => new ssm.StringParameter(stack, `p${i++}`, { parameterName: param.valueAsString, stringValue: 'foo' })).toThrow(expected); expect(() => new ssm.StringParameter(stack, `p${i++}`, { parameterName: param.valueAsString, stringValue: 'foo' })).toThrow(expected); }); test('fails if simpleName is wrong based on a concrete physical name', () => { // GIVEN const stack = new cdk.Stack(); let i = 0; // THEN expect(() => ssm.StringParameter.fromStringParameterAttributes(stack, `p${i++}`, { parameterName: 'simple', simpleName: false })).toThrow(/Parameter name "simple" is a simple name, but "simpleName" was explicitly set to false. Either omit it or set it to true/); expect(() => ssm.StringParameter.fromStringParameterAttributes(stack, `p${i++}`, { parameterName: '/foo/bar', simpleName: true })).toThrow(/Parameter name "\/foo\/bar" is not a simple name, but "simpleName" was explicitly set to true. Either omit it or set it to false/); }); test('fails if parameterName is undefined and simpleName is "false"', () => { // GIVEN const stack = new cdk.Stack(); // THEN expect(() => new ssm.StringParameter(stack, 'p', { simpleName: false, stringValue: 'foo' })).toThrow(/If "parameterName" is not explicitly defined, "simpleName" must be "true" or undefined since auto-generated parameter names always have simple names/); });
the_stack
import {Platform, _supportsShadowDom} from '@angular/cdk/platform'; import { Component, ViewChild, TemplateRef, ViewContainerRef, ViewEncapsulation, } from '@angular/core'; import {waitForAsync, ComponentFixture, TestBed} from '@angular/core/testing'; import {PortalModule, CdkPortalOutlet, TemplatePortal} from '@angular/cdk/portal'; import {A11yModule, FocusTrap, CdkTrapFocus} from '../index'; import {By} from '@angular/platform-browser'; describe('FocusTrap', () => { beforeEach( waitForAsync(() => { TestBed.configureTestingModule({ imports: [A11yModule, PortalModule], declarations: [ FocusTrapWithBindings, SimpleFocusTrap, FocusTrapTargets, FocusTrapWithSvg, FocusTrapWithoutFocusableElements, FocusTrapWithAutoCapture, FocusTrapUnfocusableTarget, FocusTrapInsidePortal, FocusTrapWithAutoCaptureInShadowDom, ], }); TestBed.compileComponents(); }), ); describe('with default element', () => { let fixture: ComponentFixture<SimpleFocusTrap>; let focusTrapInstance: FocusTrap; beforeEach(() => { fixture = TestBed.createComponent(SimpleFocusTrap); fixture.detectChanges(); focusTrapInstance = fixture.componentInstance.focusTrapDirective.focusTrap; }); it('wrap focus from end to start', () => { // Because we can't mimic a real tab press focus change in a unit test, just call the // focus event handler directly. const result = focusTrapInstance.focusFirstTabbableElement(); expect(getActiveElement().nodeName.toLowerCase()) .withContext('Expected input element to be focused') .toBe('input'); expect(result) .withContext('Expected return value to be true if focus was shifted.') .toBe(true); }); it('should wrap focus from start to end', () => { // Because we can't mimic a real tab press focus change in a unit test, just call the // focus event handler directly. const result = focusTrapInstance.focusLastTabbableElement(); const platform = TestBed.inject(Platform); // In iOS button elements are never tabbable, so the last element will be the input. const lastElement = platform.IOS ? 'input' : 'button'; expect(getActiveElement().nodeName.toLowerCase()) .withContext(`Expected ${lastElement} element to be focused`) .toBe(lastElement); expect(result) .withContext('Expected return value to be true if focus was shifted.') .toBe(true); }); it('should return false if it did not manage to find a focusable element', () => { fixture.destroy(); const newFixture = TestBed.createComponent(FocusTrapWithoutFocusableElements); newFixture.detectChanges(); const focusTrap = newFixture.componentInstance.focusTrapDirective.focusTrap; const result = focusTrap.focusFirstTabbableElement(); expect(result).toBe(false); }); it('should be enabled by default', () => { expect(focusTrapInstance.enabled).toBe(true); }); }); describe('with bindings', () => { let fixture: ComponentFixture<FocusTrapWithBindings>; beforeEach(() => { fixture = TestBed.createComponent(FocusTrapWithBindings); fixture.detectChanges(); }); it('should clean up its anchor sibling elements on destroy', () => { const rootElement = fixture.debugElement.nativeElement as HTMLElement; expect(rootElement.querySelectorAll('div.cdk-visually-hidden').length).toBe(2); fixture.componentInstance.renderFocusTrap = false; fixture.detectChanges(); expect(rootElement.querySelectorAll('div.cdk-visually-hidden').length).toBe(0); }); it('should set the appropriate tabindex on the anchors, based on the disabled state', () => { const anchors = Array.from( fixture.debugElement.nativeElement.querySelectorAll('div.cdk-visually-hidden'), ) as HTMLElement[]; expect(anchors.every(current => current.getAttribute('tabindex') === '0')).toBe(true); expect(anchors.every(current => current.getAttribute('aria-hidden') === 'true')).toBe(true); fixture.componentInstance._isFocusTrapEnabled = false; fixture.detectChanges(); expect(anchors.every(current => !current.hasAttribute('tabindex'))).toBe(true); }); }); describe('with focus targets', () => { let fixture: ComponentFixture<FocusTrapTargets>; let focusTrapInstance: FocusTrap; beforeEach(() => { fixture = TestBed.createComponent(FocusTrapTargets); fixture.detectChanges(); focusTrapInstance = fixture.componentInstance.focusTrapDirective.focusTrap; }); it('should be able to set initial focus target', () => { // Because we can't mimic a real tab press focus change in a unit test, just call the // focus event handler directly. focusTrapInstance.focusInitialElement(); expect(getActiveElement().id).toBe('middle'); }); it('should be able to pass in focus options to initial focusable element', () => { const options = {preventScroll: true}; const spy = spyOn(fixture.nativeElement.querySelector('#middle'), 'focus').and.callThrough(); focusTrapInstance.focusInitialElement(options); expect(spy).toHaveBeenCalledWith(options); }); it('should be able to prioritize the first focus target', () => { // Because we can't mimic a real tab press focus change in a unit test, just call the // focus event handler directly. focusTrapInstance.focusFirstTabbableElement(); expect(getActiveElement().id).toBe('first'); }); it('should be able to pass in focus options to first focusable element', () => { const options = {preventScroll: true}; const spy = spyOn(fixture.nativeElement.querySelector('#first'), 'focus').and.callThrough(); focusTrapInstance.focusFirstTabbableElement(options); expect(spy).toHaveBeenCalledWith(options); }); it('should be able to prioritize the last focus target', () => { // Because we can't mimic a real tab press focus change in a unit test, just call the // focus event handler directly. focusTrapInstance.focusLastTabbableElement(); expect(getActiveElement().id).toBe('last'); }); it('should be able to pass in focus options to last focusable element', () => { const options = {preventScroll: true}; const spy = spyOn(fixture.nativeElement.querySelector('#last'), 'focus').and.callThrough(); focusTrapInstance.focusLastTabbableElement(options); expect(spy).toHaveBeenCalledWith(options); }); it('should warn if the initial focus target is not focusable', () => { const alternateFixture = TestBed.createComponent(FocusTrapUnfocusableTarget); alternateFixture.detectChanges(); focusTrapInstance = fixture.componentInstance.focusTrapDirective.focusTrap; spyOn(console, 'warn'); focusTrapInstance.focusInitialElement(); expect(console.warn).toHaveBeenCalled(); }); }); describe('special cases', () => { it('should not throw when it has a SVG child', () => { let fixture = TestBed.createComponent(FocusTrapWithSvg); fixture.detectChanges(); let focusTrapInstance = fixture.componentInstance.focusTrapDirective.focusTrap; expect(() => focusTrapInstance.focusFirstTabbableElement()).not.toThrow(); expect(() => focusTrapInstance.focusLastTabbableElement()).not.toThrow(); }); }); describe('with autoCapture', () => { it( 'should automatically capture and return focus on init / destroy', waitForAsync(() => { const fixture = TestBed.createComponent(FocusTrapWithAutoCapture); fixture.detectChanges(); const buttonOutsideTrappedRegion = fixture.nativeElement.querySelector('button'); buttonOutsideTrappedRegion.focus(); expect(getActiveElement()).toBe(buttonOutsideTrappedRegion); fixture.componentInstance.showTrappedRegion = true; fixture.detectChanges(); fixture.whenStable().then(() => { expect(getActiveElement().id).toBe('auto-capture-target'); fixture.destroy(); expect(getActiveElement()).toBe(buttonOutsideTrappedRegion); }); }), ); it( 'should capture focus if auto capture is enabled later on', waitForAsync(() => { const fixture = TestBed.createComponent(FocusTrapWithAutoCapture); fixture.componentInstance.autoCaptureEnabled = false; fixture.componentInstance.showTrappedRegion = true; fixture.detectChanges(); const buttonOutsideTrappedRegion = fixture.nativeElement.querySelector('button'); buttonOutsideTrappedRegion.focus(); expect(getActiveElement()).toBe(buttonOutsideTrappedRegion); fixture.componentInstance.autoCaptureEnabled = true; fixture.detectChanges(); fixture.whenStable().then(() => { expect(getActiveElement().id).toBe('auto-capture-target'); fixture.destroy(); expect(getActiveElement()).toBe(buttonOutsideTrappedRegion); }); }), ); it( 'should automatically capture and return focus on init / destroy inside the shadow DOM', waitForAsync(() => { if (!_supportsShadowDom()) { return; } const fixture = TestBed.createComponent(FocusTrapWithAutoCaptureInShadowDom); fixture.detectChanges(); const buttonOutsideTrappedRegion = fixture.debugElement.query( By.css('button'), ).nativeElement; buttonOutsideTrappedRegion.focus(); expect(getActiveElement()).toBe(buttonOutsideTrappedRegion); fixture.componentInstance.showTrappedRegion = true; fixture.detectChanges(); fixture.whenStable().then(() => { expect(getActiveElement().id).toBe('auto-capture-target'); fixture.destroy(); expect(getActiveElement()).toBe(buttonOutsideTrappedRegion); }); }), ); it( 'should capture focus if auto capture is enabled later on inside the shadow DOM', waitForAsync(() => { if (!_supportsShadowDom()) { return; } const fixture = TestBed.createComponent(FocusTrapWithAutoCaptureInShadowDom); fixture.componentInstance.autoCaptureEnabled = false; fixture.componentInstance.showTrappedRegion = true; fixture.detectChanges(); const buttonOutsideTrappedRegion = fixture.debugElement.query( By.css('button'), ).nativeElement; buttonOutsideTrappedRegion.focus(); expect(getActiveElement()).toBe(buttonOutsideTrappedRegion); fixture.componentInstance.autoCaptureEnabled = true; fixture.detectChanges(); fixture.whenStable().then(() => { expect(getActiveElement().id).toBe('auto-capture-target'); fixture.destroy(); expect(getActiveElement()).toBe(buttonOutsideTrappedRegion); }); }), ); }); it('should put anchors inside the outlet when set at the root of a template portal', () => { const fixture = TestBed.createComponent(FocusTrapInsidePortal); const instance = fixture.componentInstance; fixture.detectChanges(); const outlet: HTMLElement = fixture.nativeElement.querySelector('.portal-outlet'); expect(outlet.querySelectorAll('button').length) .withContext('Expected no buttons inside the outlet on init.') .toBe(0); expect(outlet.querySelectorAll('.cdk-focus-trap-anchor').length) .withContext('Expected no focus trap anchors inside the outlet on init.') .toBe(0); const portal = new TemplatePortal(instance.template, instance.viewContainerRef); instance.portalOutlet.attachTemplatePortal(portal); fixture.detectChanges(); expect(outlet.querySelectorAll('button').length) .withContext('Expected one button inside the outlet after attaching.') .toBe(1); expect(outlet.querySelectorAll('.cdk-focus-trap-anchor').length) .withContext('Expected two focus trap anchors in the outlet after attaching.') .toBe(2); }); }); /** Gets the currently-focused element while accounting for the shadow DOM. */ function getActiveElement() { const activeElement = document.activeElement as HTMLElement | null; return (activeElement?.shadowRoot?.activeElement as HTMLElement) || activeElement; } @Component({ template: ` <div cdkTrapFocus> <input> <button>SAVE</button> </div> `, }) class SimpleFocusTrap { @ViewChild(CdkTrapFocus) focusTrapDirective: CdkTrapFocus; } const AUTO_FOCUS_TEMPLATE = ` <button type="button">Toggle</button> <div *ngIf="showTrappedRegion" cdkTrapFocus [cdkTrapFocusAutoCapture]="autoCaptureEnabled"> <input id="auto-capture-target"> <button>SAVE</button> </div> `; @Component({template: AUTO_FOCUS_TEMPLATE}) class FocusTrapWithAutoCapture { @ViewChild(CdkTrapFocus) focusTrapDirective: CdkTrapFocus; showTrappedRegion = false; autoCaptureEnabled = true; } @Component({ template: AUTO_FOCUS_TEMPLATE, encapsulation: ViewEncapsulation.ShadowDom, }) class FocusTrapWithAutoCaptureInShadowDom extends FocusTrapWithAutoCapture {} @Component({ template: ` <div *ngIf="renderFocusTrap" [cdkTrapFocus]="_isFocusTrapEnabled"> <input> <button>SAVE</button> </div> `, }) class FocusTrapWithBindings { @ViewChild(CdkTrapFocus) focusTrapDirective: CdkTrapFocus; renderFocusTrap = true; _isFocusTrapEnabled = true; } @Component({ template: ` <div cdkTrapFocus> <input> <button>before</button> <button id="first" cdkFocusRegionStart></button> <button id="middle" cdkFocusInitial></button> <button id="last" cdkFocusRegionEnd></button> <button>after</button> <input> </div> `, }) class FocusTrapTargets { @ViewChild(CdkTrapFocus) focusTrapDirective: CdkTrapFocus; } @Component({ template: ` <div cdkTrapFocus> <div cdkFocusInitial></div> </div> `, }) class FocusTrapUnfocusableTarget { @ViewChild(CdkTrapFocus) focusTrapDirective: CdkTrapFocus; } @Component({ template: ` <div cdkTrapFocus> <svg xmlns="http://www.w3.org/2000/svg"> <circle cx="100" cy="100" r="100"/> </svg> </div> `, }) class FocusTrapWithSvg { @ViewChild(CdkTrapFocus) focusTrapDirective: CdkTrapFocus; } @Component({ template: ` <div cdkTrapFocus> <p>Hello</p> </div> `, }) class FocusTrapWithoutFocusableElements { @ViewChild(CdkTrapFocus) focusTrapDirective: CdkTrapFocus; } @Component({ template: ` <div class="portal-outlet"> <ng-template cdkPortalOutlet></ng-template> </div> <ng-template #template> <div cdkTrapFocus> <button>Click me</button> </div> </ng-template> `, }) class FocusTrapInsidePortal { @ViewChild('template') template: TemplateRef<any>; @ViewChild(CdkPortalOutlet) portalOutlet: CdkPortalOutlet; constructor(public viewContainerRef: ViewContainerRef) {} }
the_stack
import { PluginKey, Selection, TextSelection } from 'prosemirror-state'; import { Decoration, DecorationSet } from 'prosemirror-view'; import { isFunction, isString, object, sort } from '@remirror/core-helpers'; import { isInvalidSplitReason, isJumpReason, isTextSelection, isValidMatch, } from './suggest-predicates'; import type { AddIgnoredProps, CompareMatchProps, EditorState, EditorStateProps, EditorView, RemoveIgnoredProps, ResolvedPos, ResolvedPosProps, SuggestChangeHandlerProps, Suggester, SuggestMatch, SuggestReasonMap, Transaction, TransactionProps, } from './suggest-types'; import { DEFAULT_SUGGESTER, findFromSuggesters, findReason, IGNORE_SUGGEST_META_KEY, } from './suggest-utils'; /** * The `prosemirror-suggest` state which manages the list of suggesters. */ export class SuggestState { /** * Create an instance of the SuggestState class. */ static create(suggesters: Suggester[]): SuggestState { return new SuggestState(suggesters); } /** * True when the doc changed in the most recently applied transaction. */ #docChanged = false; /** * Whether the next exit should be ignored. */ #ignoreNextExit = false; /** * The suggesters that have been registered for the suggesters plugin. */ #suggesters: Array<Required<Suggester>>; /** * Keeps track of the current state. */ #next?: Readonly<SuggestMatch>; /** * Holds onto the previous active state. */ #prev?: Readonly<SuggestMatch>; /** * The handler matches which are passed into the `onChange` handler. */ #handlerMatches: SuggestReasonMap = object(); /** * Holds a copy of the view */ private view!: EditorView; /** * The set of ignored decorations */ #ignored = DecorationSet.empty; /** * Lets us know whether the most recent change was to remove a mention. */ #removed = false; /** * This is true when the last change was caused by a transaction being appended via this plugin. */ #lastChangeFromAppend = false; /** * The set of all decorations. */ get decorationSet(): DecorationSet { return this.#ignored; } /** * True when the most recent change was to remove a mention. * * @remarks * * This is needed because sometimes removing a prosemirror `Mark` has no * effect. Hence we need to keep track of whether it's removed and then later * in the apply step check that a removal has happened and reset the * `handlerMatches` to prevent an infinite loop. */ get removed(): boolean { return this.#removed; } /** * Returns the current active suggester state field if one exists */ get match(): Readonly<SuggestMatch> | undefined { return this.#next ? this.#next : this.#prev && this.#handlerMatches.exit ? this.#prev : undefined; } /** * Create the state for the `prosemirror-suggest` plugin. * * @remarks * * Each suggester must provide a name value which is globally unique since it * acts as the identifier. * * It is possible to register multiple suggesters with identical `char` * properties. The matched suggester is based on the specificity of the * `regex` and the order in which they are passed in. Earlier suggesters are * prioritized. */ constructor(suggesters: Suggester[]) { const mapper = createSuggesterMapper(); this.#suggesters = suggesters.map(mapper); this.#suggesters = sort(this.#suggesters, (a, b) => b.priority - a.priority); } /** * Initialize the SuggestState with a view which is stored for use later. */ init(view: EditorView): this { this.view = view; return this; } /** * Sets the removed property to be true. * * This is useful when working with marks. */ readonly setMarkRemoved = (): void => { this.#removed = true; }; /** * Create the props which should be passed into each action handler */ private createProps(match: SuggestMatch): SuggestChangeHandlerProps { const { name, char } = match.suggester; return { view: this.view, addIgnored: this.addIgnored, clearIgnored: this.clearIgnored, ignoreNextExit: this.ignoreNextExit, setMarkRemoved: this.setMarkRemoved, name, char, ...match, }; } /** * Check whether the exit callback is valid at this time. */ private shouldRunExit(): boolean { if (this.#ignoreNextExit) { this.#ignoreNextExit = false; return false; } return true; } /** * Find the next text selection from the current selection. */ readonly findNextTextSelection = (selection: Selection): TextSelection | void => { const doc = selection.$from.doc; // Make sure the position doesn't exceed the bounds of the document. const pos = Math.min(doc.nodeSize - 2, selection.to + 1); const $pos = doc.resolve(pos); // Get the position furthest along in the editor to pass back to suggesters // which have the handler. const nextSelection = Selection.findFrom($pos, 1, true); // Ignore non-text selections and null / undefined values. This is needed // for TS mainly, since the `true` in the `Selection.findFrom` method means // only `TextSelection` instances will be returned. if (!isTextSelection(nextSelection)) { return; } return nextSelection; }; /** * Update all the suggesters with the next valid selection. This is called * within the `appendTransaction` ProseMirror method before any of the change * handlers are called. * * @internal */ updateWithNextSelection(tr: Transaction): void { // Get the position furthest along in the editor to pass back to suggesters // which have the handler. const nextSelection = this.findNextTextSelection(tr.selection); if (!nextSelection) { return; } // Update every suggester with a method attached. for (const suggester of this.#suggesters) { const change = this.#handlerMatches.change?.suggester.name; const exit = this.#handlerMatches.exit?.suggester.name; suggester.checkNextValidSelection?.(nextSelection.$from, tr, { change, exit }); } } /** * Call the `onChange` handlers. * * @internal */ changeHandler(tr: Transaction, appendTransaction: boolean): void { const { change, exit } = this.#handlerMatches; const match = this.match; // Cancel update when a suggester isn't active if ((!change && !exit) || !isValidMatch(match)) { return; } const shouldRunExit = appendTransaction === exit?.suggester.appendTransaction && this.shouldRunExit(); const shouldRunChange = appendTransaction === change?.suggester.appendTransaction; if (!shouldRunExit && !shouldRunChange) { return; } // When a jump happens run the action that involves the position that occurs // later in the document. This is so that changes don't affect previous // positions. if (change && exit && isJumpReason({ change, exit })) { const exitDetails = this.createProps(exit); const changeDetails = this.createProps(change); // Whether the jump was forwards or backwards. A forwards jump means that // the user was within a suggester nearer the beginning of the document, // before jumping forward to a point later on in the document. const movedForwards = exit.range.from < change.range.from; if (movedForwards) { // Subtle change to call exit first. Conceptually it happens before the // change so call the handler before the change handler. shouldRunExit && exit.suggester.onChange(exitDetails, tr); shouldRunChange && change.suggester.onChange(changeDetails, tr); } else { shouldRunExit && exit.suggester.onChange(exitDetails, tr); shouldRunChange && change.suggester.onChange(changeDetails, tr); } if (shouldRunExit) { this.#removed = false; } return; } if (change && shouldRunChange) { change.suggester.onChange(this.createProps(change), tr); } if (exit && shouldRunExit) { exit.suggester.onChange(this.createProps(exit), tr); this.#removed = false; if (isInvalidSplitReason(exit.exitReason)) { // When the split has made the match invalid, remove the matches before // the next input. this.#handlerMatches = object(); } } return; } /** * Update the current ignored decorations based on the latest changes to the * prosemirror document. */ private mapIgnoredDecorations(tr: Transaction) { // Map over and update the ignored decorations. const ignored = this.#ignored.map(tr.mapping, tr.doc); const decorations = ignored.find(); // For suggesters with multiple characters it is possible for a `paste` or // any edit action within the decoration to expand the ignored section. We // check for that here and if the section size has changed it should be // marked as invalid and removed from the ignored `DecorationSet`. const invalid = decorations.filter(({ from, to, spec }) => { const charLength = isString(spec.char) ? spec.char.length : 1; if (to - from !== charLength) { return true; } return false; }); this.#ignored = ignored.remove(invalid); } /** * This sets the next exit to not trigger the exit reason inside the * `onChange` callback. * * This can be useful when you trigger a command, that exists the suggestion * match and want to prevent further onChanges from occurring for the * currently active suggester. */ readonly ignoreNextExit = (): void => { this.#ignoreNextExit = true; }; /** * Ignores the match specified. Until the match is deleted no more `onChange` * handler will be triggered. It will be like the match doesn't exist. * * @remarks * * All we need to ignore is the match character. This means that any further * matches from the activation character will be ignored. */ readonly addIgnored = ({ from, name, specific = false }: AddIgnoredProps): void => { const suggester = this.#suggesters.find((value) => value.name === name); if (!suggester) { throw new Error(`No suggester exists for the name provided: ${name}`); } const offset = isString(suggester.char) ? suggester.char.length : 1; const to = from + offset; const attributes = suggester.ignoredClassName ? { class: suggester.ignoredClassName } : {}; const decoration = Decoration.inline( from, to, { nodeName: suggester.ignoredTag, ...attributes }, // @ts-expect-error: TS types here don't allow us to set custom properties { name, specific, char: suggester.char }, ); this.#ignored = this.#ignored.add(this.view.state.doc, [decoration]); }; /** * Removes a single match character from the ignored decorations. * * @remarks * * After this point event handlers will begin to be called again for the match * character. */ readonly removeIgnored = ({ from, name }: RemoveIgnoredProps): void => { const suggester = this.#suggesters.find((value) => value.name === name); if (!suggester) { throw new Error(`No suggester exists for the name provided: ${name}`); } const offset = isString(suggester.char) ? suggester.char.length : 1; const decoration = this.#ignored.find(from, from + offset)[0]; if (!decoration || decoration.spec.name !== name) { return; } this.#ignored = this.#ignored.remove([decoration]); }; /** * Removes all the ignored sections of the document. Once this happens * suggesters will be able to activate in the previously ignored sections. */ readonly clearIgnored = (name?: string): void => { if (!name) { this.#ignored = DecorationSet.empty; return; } const decorations = this.#ignored.find(); const decorationsToClear = decorations.filter(({ spec }) => { return spec.name === name; }); this.#ignored = this.#ignored.remove(decorationsToClear); }; /** * Checks whether a match should be ignored. * * TODO add logic here to decide whether to ignore a match based on the active * node, or mark. */ private shouldIgnoreMatch({ range, suggester: { name } }: SuggestMatch) { const decorations = this.#ignored.find(); const shouldIgnore = decorations.some(({ spec, from }) => { if (from !== range.from) { return false; } return spec.specific ? spec.name === name : true; }); return shouldIgnore; } /** * Reset the state. */ private resetState() { this.#handlerMatches = object(); this.#next = undefined; this.#removed = false; this.#lastChangeFromAppend = false; } /** * Update the next state value. */ private updateReasons(props: UpdateReasonsProps) { const { $pos, state } = props; const docChanged = this.#docChanged; const suggesters = this.#suggesters; const selectionEmpty = state.selection.empty; const match = isTextSelection(state.selection) ? findFromSuggesters({ suggesters, $pos, docChanged, selectionEmpty }) : undefined; // Track the next match if not being ignored. this.#next = match && this.shouldIgnoreMatch(match) ? undefined : match; // Store the matches with reasons this.#handlerMatches = findReason({ next: this.#next, prev: this.#prev, state, $pos }); } /** * A helper method to check is a match exists for the provided suggester name * at the provided position. */ readonly findMatchAtPosition = ($pos: ResolvedPos, name?: string): SuggestMatch | undefined => { const suggesters = name ? this.#suggesters.filter((suggester) => suggester.name === name) : this.#suggesters; return findFromSuggesters({ suggesters, $pos, docChanged: false, selectionEmpty: true }); }; /** * Add a new suggest or replace it if it already exists. */ addSuggester(suggester: Suggester): () => void { const previous = this.#suggesters.find((item) => item.name === suggester.name); const mapper = createSuggesterMapper(); if (previous) { this.#suggesters = this.#suggesters.map((item) => item === previous ? mapper(suggester) : item, ); } else { const suggesters = [...this.#suggesters, mapper(suggester)]; this.#suggesters = sort(suggesters, (a, b) => b.priority - a.priority); } return () => this.removeSuggester(suggester.name); } /** * Remove a suggester if it exists. */ removeSuggester(suggester: Suggester | string): void { const name = isString(suggester) ? suggester : suggester.name; this.#suggesters = this.#suggesters.filter((item) => item.name !== name); // When removing a suggester make sure to clear the ignored sections. this.clearIgnored(name); } toJSON(): SuggestMatch | undefined { return this.match; } /** * Applies updates to the state to be used within the plugins apply method. * * @param - params */ apply(props: TransactionProps & EditorStateProps): this { const { exit, change } = this.#handlerMatches; if (this.#lastChangeFromAppend) { this.#lastChangeFromAppend = false; if (!exit?.suggester.appendTransaction && !change?.suggester.appendTransaction) { return this; } } const { tr, state } = props; const transactionHasChanged = tr.docChanged || tr.selectionSet; const shouldIgnoreUpdate: boolean = tr.getMeta(IGNORE_SUGGEST_META_KEY); if (shouldIgnoreUpdate || (!transactionHasChanged && !this.#removed)) { return this; } this.#docChanged = tr.docChanged; this.mapIgnoredDecorations(tr); // If the previous run was an exit, reset the suggester matches. if (exit) { this.resetState(); } // Track the previous match. this.#prev = this.#next; // Match against the current selection position this.updateReasons({ $pos: tr.selection.$from, state }); return this; } /** * Handle the decorations which wrap the mention while it is active and not * yet complete. */ createDecorations(state: EditorState): DecorationSet { const match = this.match; if (!isValidMatch(match)) { return this.#ignored; } const { disableDecorations } = match.suggester; const shouldSkip = isFunction(disableDecorations) ? disableDecorations(state, match) : disableDecorations; if (shouldSkip) { return this.#ignored; } const { range, suggester } = match; const { name, suggestTag, suggestClassName } = suggester; const { from, to } = range; return this.shouldIgnoreMatch(match) ? this.#ignored : this.#ignored.add(state.doc, [ Decoration.inline( from, to, { nodeName: suggestTag, class: name ? `${suggestClassName} suggest-${name}` : suggestClassName, }, // @ts-expect-error: TS types here don't allow us to set custom properties { name }, ), ]); } /** * Set that the last change was caused by an appended transaction. * * @internal */ setLastChangeFromAppend = (): void => { this.#lastChangeFromAppend = true; }; } interface UpdateReasonsProps extends EditorStateProps, ResolvedPosProps, Partial<CompareMatchProps> {} /** * Map over the suggesters provided and make sure they have all the required * properties. */ function createSuggesterMapper() { const names = new Set<string>(); return (suggester: Suggester): Required<Suggester> => { if (names.has(suggester.name)) { throw new Error( `A suggester already exists with the name '${suggester.name}'. The name provided must be unique.`, ); } // Attach the defaults to the passed in suggester. const suggesterWithDefaults = { ...DEFAULT_SUGGESTER, ...suggester }; names.add(suggester.name); return suggesterWithDefaults; }; } /** * This key is stored to provide access to the plugin state. */ export const suggestPluginKey = new PluginKey('suggest');
the_stack
import { Nullable } from "babylonjs/types"; import { Observable } from "babylonjs/Misc/observable"; import { Deferred } from "babylonjs/Misc/deferred"; import { Material } from "babylonjs/Materials/material"; import { TransformNode } from "babylonjs/Meshes/transformNode"; import { Mesh } from "babylonjs/Meshes/mesh"; import { BaseTexture } from "babylonjs/Materials/Textures/baseTexture"; import { INode, IMaterial, IBuffer, IScene } from "../glTFLoaderInterfaces"; import { IGLTFLoaderExtension } from "../glTFLoaderExtension"; import { GLTFLoader, ArrayItem } from "../glTFLoader"; import { IProperty, IMSFTLOD } from "babylonjs-gltf2interface"; const NAME = "MSFT_lod"; interface IBufferInfo { start: number; end: number; loaded: Deferred<ArrayBufferView>; } /** * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod) */ export class MSFT_lod implements IGLTFLoaderExtension { /** * The name of this extension. */ public readonly name = NAME; /** * Defines whether this extension is enabled. */ public enabled: boolean; /** * Defines a number that determines the order the extensions are applied. */ public order = 100; /** * Maximum number of LODs to load, starting from the lowest LOD. */ public maxLODsToLoad = 10; /** * Observable raised when all node LODs of one level are loaded. * The event data is the index of the loaded LOD starting from zero. * Dispose the loader to cancel the loading of the next level of LODs. */ public onNodeLODsLoadedObservable = new Observable<number>(); /** * Observable raised when all material LODs of one level are loaded. * The event data is the index of the loaded LOD starting from zero. * Dispose the loader to cancel the loading of the next level of LODs. */ public onMaterialLODsLoadedObservable = new Observable<number>(); private _loader: GLTFLoader; private _bufferLODs = new Array<IBufferInfo>(); private _nodeIndexLOD: Nullable<number> = null; private _nodeSignalLODs = new Array<Deferred<void>>(); private _nodePromiseLODs = new Array<Array<Promise<any>>>(); private _nodeBufferLODs = new Array<IBufferInfo>(); private _materialIndexLOD: Nullable<number> = null; private _materialSignalLODs = new Array<Deferred<void>>(); private _materialPromiseLODs = new Array<Array<Promise<any>>>(); private _materialBufferLODs = new Array<IBufferInfo>(); /** @hidden */ constructor(loader: GLTFLoader) { this._loader = loader; this.enabled = this._loader.isExtensionUsed(NAME); } /** @hidden */ public dispose() { (this._loader as any) = null; this._nodeIndexLOD = null; this._nodeSignalLODs.length = 0; this._nodePromiseLODs.length = 0; this._nodeBufferLODs.length = 0; this._materialIndexLOD = null; this._materialSignalLODs.length = 0; this._materialPromiseLODs.length = 0; this._materialBufferLODs.length = 0; this.onMaterialLODsLoadedObservable.clear(); this.onNodeLODsLoadedObservable.clear(); } /** @hidden */ public onReady(): void { for (let indexLOD = 0; indexLOD < this._nodePromiseLODs.length; indexLOD++) { const promise = Promise.all(this._nodePromiseLODs[indexLOD]).then(() => { if (indexLOD !== 0) { this._loader.endPerformanceCounter(`Node LOD ${indexLOD}`); this._loader.log(`Loaded node LOD ${indexLOD}`); } this.onNodeLODsLoadedObservable.notifyObservers(indexLOD); if (indexLOD !== this._nodePromiseLODs.length - 1) { this._loader.startPerformanceCounter(`Node LOD ${indexLOD + 1}`); this._loadBufferLOD(this._nodeBufferLODs, indexLOD + 1); if (this._nodeSignalLODs[indexLOD]) { this._nodeSignalLODs[indexLOD].resolve(); } } }); this._loader._completePromises.push(promise); } for (let indexLOD = 0; indexLOD < this._materialPromiseLODs.length; indexLOD++) { const promise = Promise.all(this._materialPromiseLODs[indexLOD]).then(() => { if (indexLOD !== 0) { this._loader.endPerformanceCounter(`Material LOD ${indexLOD}`); this._loader.log(`Loaded material LOD ${indexLOD}`); } this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD); if (indexLOD !== this._materialPromiseLODs.length - 1) { this._loader.startPerformanceCounter(`Material LOD ${indexLOD + 1}`); this._loadBufferLOD(this._materialBufferLODs, indexLOD + 1); if (this._materialSignalLODs[indexLOD]) { this._materialSignalLODs[indexLOD].resolve(); } } }); this._loader._completePromises.push(promise); } } /** @hidden */ public loadSceneAsync(context: string, scene: IScene): Nullable<Promise<void>> { const promise = this._loader.loadSceneAsync(context, scene); this._loadBufferLOD(this._bufferLODs, 0); return promise; } /** @hidden */ public loadNodeAsync(context: string, node: INode, assign: (babylonTransformNode: TransformNode) => void): Nullable<Promise<TransformNode>> { return GLTFLoader.LoadExtensionAsync<IMSFTLOD, TransformNode>(context, node, this.name, (extensionContext, extension) => { let firstPromise: Promise<TransformNode>; const nodeLODs = this._getLODs(extensionContext, node, this._loader.gltf.nodes, extension.ids); this._loader.logOpen(`${extensionContext}`); const transformNodes: Nullable<TransformNode>[] = []; for (let indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) { transformNodes.push(null); } for (let indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) { const nodeLOD = nodeLODs[indexLOD]; if (indexLOD !== 0) { this._nodeIndexLOD = indexLOD; this._nodeSignalLODs[indexLOD] = this._nodeSignalLODs[indexLOD] || new Deferred(); } const assignChild = (babylonTransformNode: TransformNode, index: number) => { babylonTransformNode.setEnabled(false); transformNodes[index] = babylonTransformNode; let fullArray = true; for (let i = 0; i < transformNodes.length; i++) { if (!transformNodes[i]) { fullArray = false; } } const lod0 = transformNodes[transformNodes.length - 1]; if (fullArray && lod0 && this._isMesh(lod0)) { const screenCoverages = lod0.metadata?.gltf?.extras?.MSFT_screencoverage as number[]; if (screenCoverages && screenCoverages.length) { screenCoverages.reverse(); lod0.useLODScreenCoverage = true; for (let i = 0; i < transformNodes.length - 1; i++) { const transformNode = transformNodes[i]; if (transformNode && this._isMesh(transformNode)) { lod0.addLODLevel(screenCoverages[i + 1], transformNode); } } if (screenCoverages[0] > 0) { // Adding empty LOD lod0.addLODLevel(screenCoverages[0], null); } } } }; const promise = this._loader.loadNodeAsync(`/nodes/${nodeLOD.index}`, nodeLOD, (node: TransformNode) => assignChild(node, indexLOD)).then((babylonMesh) => { const screenCoverages = (nodeLODs[nodeLODs.length - 1]._babylonTransformNode as Mesh).metadata?.gltf?.extras?.MSFT_screencoverage; if (indexLOD !== 0 && !screenCoverages) { // TODO: should not rely on _babylonTransformNode const previousNodeLOD = nodeLODs[indexLOD - 1]; if (previousNodeLOD._babylonTransformNode) { this._disposeTransformNode(previousNodeLOD._babylonTransformNode); delete previousNodeLOD._babylonTransformNode; } } assign(babylonMesh); babylonMesh.setEnabled(true); return babylonMesh; }); this._nodePromiseLODs[indexLOD] = this._nodePromiseLODs[indexLOD] || []; if (indexLOD === 0) { firstPromise = promise; } else { this._nodeIndexLOD = null; this._nodePromiseLODs[indexLOD].push(promise); } } this._loader.logClose(); return firstPromise!; }); } /** @hidden */ public _loadMaterialAsync( context: string, material: IMaterial, babylonMesh: Nullable<Mesh>, babylonDrawMode: number, assign: (babylonMaterial: Material) => void ): Nullable<Promise<Material>> { // Don't load material LODs if already loading a node LOD. if (this._nodeIndexLOD) { return null; } return GLTFLoader.LoadExtensionAsync<IMSFTLOD, Material>(context, material, this.name, (extensionContext, extension) => { let firstPromise: Promise<Material>; const materialLODs = this._getLODs(extensionContext, material, this._loader.gltf.materials, extension.ids); this._loader.logOpen(`${extensionContext}`); for (let indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) { const materialLOD = materialLODs[indexLOD]; if (indexLOD !== 0) { this._materialIndexLOD = indexLOD; } const promise = this._loader ._loadMaterialAsync(`/materials/${materialLOD.index}`, materialLOD, babylonMesh, babylonDrawMode, (babylonMaterial) => { if (indexLOD === 0) { assign(babylonMaterial); } }) .then((babylonMaterial) => { if (indexLOD !== 0) { assign(babylonMaterial); // TODO: should not rely on _data const previousDataLOD = materialLODs[indexLOD - 1]._data!; if (previousDataLOD[babylonDrawMode]) { this._disposeMaterials([previousDataLOD[babylonDrawMode].babylonMaterial]); delete previousDataLOD[babylonDrawMode]; } } return babylonMaterial; }); this._materialPromiseLODs[indexLOD] = this._materialPromiseLODs[indexLOD] || []; if (indexLOD === 0) { firstPromise = promise; } else { this._materialIndexLOD = null; this._materialPromiseLODs[indexLOD].push(promise); } } this._loader.logClose(); return firstPromise!; }); } /** @hidden */ public _loadUriAsync(context: string, property: IProperty, uri: string): Nullable<Promise<ArrayBufferView>> { // Defer the loading of uris if loading a node or material LOD. if (this._nodeIndexLOD !== null) { this._loader.log(`deferred`); const previousIndexLOD = this._nodeIndexLOD - 1; this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new Deferred<void>(); return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(() => { return this._loader.loadUriAsync(context, property, uri); }); } else if (this._materialIndexLOD !== null) { this._loader.log(`deferred`); const previousIndexLOD = this._materialIndexLOD - 1; this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new Deferred<void>(); return this._materialSignalLODs[previousIndexLOD].promise.then(() => { return this._loader.loadUriAsync(context, property, uri); }); } return null; } /** @hidden */ public loadBufferAsync(context: string, buffer: IBuffer, byteOffset: number, byteLength: number): Nullable<Promise<ArrayBufferView>> { if (this._loader.parent.useRangeRequests && !buffer.uri) { if (!this._loader.bin) { throw new Error(`${context}: Uri is missing or the binary glTF is missing its binary chunk`); } const loadAsync = (bufferLODs: Array<IBufferInfo>, indexLOD: number) => { const start = byteOffset; const end = start + byteLength - 1; let bufferLOD = bufferLODs[indexLOD]; if (bufferLOD) { bufferLOD.start = Math.min(bufferLOD.start, start); bufferLOD.end = Math.max(bufferLOD.end, end); } else { bufferLOD = { start: start, end: end, loaded: new Deferred() }; bufferLODs[indexLOD] = bufferLOD; } return bufferLOD.loaded.promise.then((data) => { return new Uint8Array(data.buffer, data.byteOffset + byteOffset - bufferLOD.start, byteLength); }); }; this._loader.log(`deferred`); if (this._nodeIndexLOD !== null) { return loadAsync(this._nodeBufferLODs, this._nodeIndexLOD); } else if (this._materialIndexLOD !== null) { return loadAsync(this._materialBufferLODs, this._materialIndexLOD); } else { return loadAsync(this._bufferLODs, 0); } } return null; } private _isMesh(mesh: TransformNode | Mesh): mesh is Mesh { return !!(mesh as Mesh).addLODLevel; } private _loadBufferLOD(bufferLODs: Array<IBufferInfo>, indexLOD: number): void { const bufferLOD = bufferLODs[indexLOD]; if (bufferLOD) { this._loader.log(`Loading buffer range [${bufferLOD.start}-${bufferLOD.end}]`); this._loader.bin!.readAsync(bufferLOD.start, bufferLOD.end - bufferLOD.start + 1).then( (data) => { bufferLOD.loaded.resolve(data); }, (error) => { bufferLOD.loaded.reject(error); } ); } } /** * Gets an array of LOD properties from lowest to highest. */ private _getLODs<T>(context: string, property: T, array: ArrayLike<T> | undefined, ids: number[]): T[] { if (this.maxLODsToLoad <= 0) { throw new Error("maxLODsToLoad must be greater than zero"); } const properties = new Array<T>(); for (let i = ids.length - 1; i >= 0; i--) { properties.push(ArrayItem.Get(`${context}/ids/${ids[i]}`, array, ids[i])); if (properties.length === this.maxLODsToLoad) { return properties; } } properties.push(property); return properties; } private _disposeTransformNode(babylonTransformNode: TransformNode): void { const babylonMaterials = new Array<Material>(); const babylonMaterial = (babylonTransformNode as Mesh).material; if (babylonMaterial) { babylonMaterials.push(babylonMaterial); } for (const babylonMesh of babylonTransformNode.getChildMeshes()) { if (babylonMesh.material) { babylonMaterials.push(babylonMesh.material); } } babylonTransformNode.dispose(); const babylonMaterialsToDispose = babylonMaterials.filter((babylonMaterial) => this._loader.babylonScene.meshes.every((mesh) => mesh.material != babylonMaterial)); this._disposeMaterials(babylonMaterialsToDispose); } private _disposeMaterials(babylonMaterials: Material[]): void { const babylonTextures: { [uniqueId: number]: BaseTexture } = {}; for (const babylonMaterial of babylonMaterials) { for (const babylonTexture of babylonMaterial.getActiveTextures()) { babylonTextures[babylonTexture.uniqueId] = babylonTexture; } babylonMaterial.dispose(); } for (const uniqueId in babylonTextures) { for (const babylonMaterial of this._loader.babylonScene.materials) { if (babylonMaterial.hasTexture(babylonTextures[uniqueId])) { delete babylonTextures[uniqueId]; } } } for (const uniqueId in babylonTextures) { babylonTextures[uniqueId].dispose(); } } } GLTFLoader.RegisterExtension(NAME, (loader) => new MSFT_lod(loader));
the_stack
import { ViewChild, Component, Input, Output, EventEmitter } from '@angular/core'; import { MetricQuery } from 'app/view/game/module/shared/class/index'; import { Observable } from 'rxjs/Observable'; import { ToastsManager } from 'ng2-toastr/ng2-toastr'; import { ModalComponent } from 'app/shared/component/index'; import { ElementRef } from '@angular/core'; export enum DefectDatabaseMode { Show, CreateJiraTickets } @Component({ selector: 'defect-datatable', templateUrl: 'node_modules/@cloud-gems/cloudgemdefectreporter/defect-datatable.component.html', styleUrls: ['node_modules/@cloud-gems/cloudgemdefectreporter/defect-datatable.component.css', 'node_modules/@cloud-gems/cloudgemdefectreporter/create-jira-issue-window.component.css'] }) export class CloudGemDefectReproterDefectDatatableComponent { @Input() aws: any; @Input() metricApiHandler: any; @Input() isJiraIntegrationEnabled: any; @Input() defectReporterApiHandler: any; @Input() partialQuery: string; @Input() tableName: string; @Input() limit: string; @Input() toDefectDetailsPageCallback: Function; @Input() bookmark: boolean; @Output() updateJiraMappings = new EventEmitter<any>(); private mode: DefectDatabaseMode; private Modes: any; public loading: boolean; public loadingSort: boolean = false; private metricQueryBuilder: MetricQuery; readonly numberOfRowsPerPage: number = 10; private tmpRows = []; private partialInputQuery: string = ""; private manualUpdate = false; private rows: any[]; private columns: any[]; private allColumns: any[]; private filteredRows = []; private readStatusOption: string = ""; private group: boolean; private selectedRows: Object[] = []; private reportsToSubmit: Object[] = []; private currentReport: Object = {}; private currentGroupMapping: Object = {}; private selectedReportIndex = 0; private fillingError = {}; public reportFields = []; @ViewChild(ModalComponent) modalRef: ModalComponent; @ViewChild('CreateJiraIssueWindow') createJiraIssueWindow; @ViewChild('BulkActionsButton') bulkActionsButton; get numberOfDefectsInGroup() { return Object.keys(this.currentGroupMapping).length; } constructor(private toastr: ToastsManager) { } ngOnInit() { this.metricQueryBuilder = new MetricQuery(this.aws, "defect"); this.Modes = DefectDatabaseMode; this.fetchQueryFromInput(this.partialQuery, false); } /** * Takes input from html textfield, converts partial input into a query and fetches results. * @param input String input from user. * @param manualUpdate Whether the operation is triggered by users **/ public fetchQueryFromInput(input: string, manualUpdate: boolean): void { this.partialInputQuery = input; let query = this.constructQuery(input); this.manualUpdate = manualUpdate; this.fetch(query); } /** * Checks if columns and rows are populated with data. * @param rows The rows to check. * @returns Boolean that indicates if data is available. **/ public isDataAvailable(rows): boolean { this.filteredRows = [...this.filteredRows]; if (this.allColumns.length > 0 && rows.length > 0) { return true; } else { return false; } } /** * Getter for the limit of results per query to Athena. * @returns The maximum number of results that can be returned. **/ public getMaximumLimit(): string { return this.limit; } /** * Update the rows on display according to the bookmark and read status. **/ public updateFilteredRows(): void { this.filteredRows = this.bookmark ? this.rows.filter(row => row.bookmark === 1) : this.rows; if (this.readStatusOption !== "") { if (this.readStatusOption === "nojira") { this.filteredRows = this.filteredRows.filter( row => row.jira_status === "pending"); } else { this.filteredRows = this.filteredRows.filter( row => row.report_status === this.readStatusOption); } } } /** * Takes input string from portal and adds necessary fields to query the Metrics gem. * @param input String input from user. * @param orderBY String of SQL column name to use for sorting. * @param direction String input defining direction of sort (ascending or decending). * @returns String query ready to be sent to AWS Athena. **/ private constructQuery(input:string, orderBy?:string, direction?:string): string { let isInputEmpty = !input; let partialWhereClause = isInputEmpty ? `WHERE p_event_name='defect' and p_server_timestamp_strftime >= date_format((current_timestamp - interval '7' day), '%Y%m%d%H0000')` : `WHERE p_event_name='defect' and`; let inputWhereClause = isInputEmpty ? "" : input; let orderByClause = !orderBy ? "" : `ORDER BY ` + orderBy; let directionClause = !direction ? "" : direction; let limit = this.getMaximumLimit(); let query = this.metricQueryBuilder.toString("SELECT * FROM ${database}.${table} " + partialWhereClause + ` ` + inputWhereClause + ` ` + orderByClause + ` ` + directionClause + ` LIMIT ` + limit); return query; } /** * Observable wrapper for Metric Api Handler call. * @returns Observable of query to subscribe to. **/ private postQuery(query): Observable<any> { return this.metricApiHandler.postQuery(query); } /** * Handles retrieval of data from Athena. * @param query String ANSI SQL query. **/ private fetch(query): void { this.loading = true; this.clearData(); this.postQuery(query).subscribe( response => { this.populateData(response, false); }, err => { this.toastr.error("Unable to fetch query. Error: ", err); this.clearData(); this.loading = false; } ); } /** * Listener to sort event on table. * @param event Event emitted by ngx-datatable **/ private onSort(event) { const columnName = event.column.prop; const sort = event.sorts[0]; let direction = sort.dir === 'desc' ? 'DESC':'ASC'; this.loadingSort = true; if (columnName === 'report_status') { this.filteredRows.sort((r1, r2) => { let r1Status = r1[columnName] === 'read' ? 1 : 0; let r2Status = r2[columnName] === 'read' ? 1 : 0; if (r1Status > r2Status) { return direction === 'ASC' ? 1 : -1; } if (r1Status < r2Status) { return direction === 'ASC' ? -1 : 1; } return 0; }); this.loadingSort = false; return; } let query = this.constructQuery(this.partialQuery, columnName, direction); this.postQuery(query).subscribe( response => { this.populateData(response, true); this.loadingSort = false; }, err=>{ this.toastr.error("Unable to sort data. Error: ", err); this.clearData(); this.loadingSort = false; } ) } /** * Toggles a column's visibility in the table. * @param col Column object in column selector. **/ private toggle(col) { const isSelected = this.isSelected(col); if (isSelected) { this.columns = this.columns.filter(c => { return c.name !== col.name; }); } else { let index = this.allColumns.findIndex(c => { return c.prop === col.prop; }); this.columns.splice(index, 0, col); this.columns = [...this.columns]; } } /** * Logic to check when a column is selected in the column selector. * @param col Column object in column selector. * @returns Boolean indicating if the column is selected. **/ private isSelected(col): boolean { return this.columns.find(c => { return c.name === col.name; }); } /** * Logic for when to show an entry in the column selector. Takes filtering into account. * @param input String from filter text input field * @param columnName String of the column name. * @returns Boolean the indicates if the column entry should be shown. **/ private isInColumnSelectorView(input:string, columnName:string): boolean { if (!input){ return true; } else { let isInputInColumnName = columnName.toLowerCase().includes(input.toLowerCase()); return isInputInColumnName ? true : false; } } /** * Sets all checkboxes in column selector to selected **/ private selectAllColumns(): void { this.columns = this.allColumns.slice(); this.columns = [...this.columns]; } /** * Sets all checkboxes in column selector to unselected **/ private clearSelections(): void { this.columns = []; this.columns = [...this.columns]; } /** * Function that is called when any activation(ex. mouseOver) ocurrs on a row in the data table * @param event Event emmited on row activation by ngx-datatable. **/ private onRowActivation(event:any): void { if (event.type === 'click') { let defect = event.row; if (event.column.prop === 'bookmark') { defect['bookmark'] = defect['bookmark'] === 0 ? 1 : 0; this.saveReportHeader(defect); this.updateFilteredRows(); } else if (event.column.prop !== 'selected') { this.onShowDefectDetailsPage(defect); } } } /** * Use function to call out when handling the onShow click * @param defect Defect row data. **/ private onShowDefectDetailsPage = (defect: any) => { if (this.toDefectDetailsPageCallback) { this.toDefectDetailsPageCallback(defect); } } /** * Checks response from query to confirm the query was succesful since failed queries also return 200 * @param response Response object; **/ private isSuccessfulQuery(response): boolean { if (!!response.Status && !!response.Status.State) { if (response.Status.State === "SUCCEEDED") { return true; } else { return false; } } else { return false; } } /** * Populate columns and rows from query response * @param response Response object from query. * @param isSort Boolean that indicates if this data came from a sort operation. **/ private populateData(response, isSort?:boolean): void { if (!this.isSuccessfulQuery(response)) { if (response.Status.StateChangeReason.indexOf("not found") !== -1) { this.toastr.error("No data is found in the database."); } else { this.toastr.error("Unable to populate data. Check query format."); } this.clearData(); this.loading = false; return; } if (this.manualUpdate) { this.onSuccessfulQuery(); } let headers = response.Result.slice(0, 1); if (headers.length > 0) { this.reportFields = headers[0]; } if (!isSort){ this.columns = []; } this.allColumns = []; this.addColumnObject('report_status', isSort); for (let header of headers) { for (let cell of header) { this.addColumnObject(cell, isSort); } } this.tmpRows = []; let responseRows = response.Result.slice(1, response.Result.length); for (let row of responseRows) { let rowObject = {}; row.forEach((element, index) => { let headerName = headers[0][index]; rowObject[headerName] = element; }); rowObject['selected'] = false; rowObject['bookmark'] = 0; rowObject['prop'] = row; this.tmpRows.push(rowObject); } this.updateReportHeaders(); } /** * Store the search information on success **/ private onSuccessfulQuery(): void { let body = { user_id: this.aws.context.authentication.user.username, query_params: this.partialInputQuery }; this.defectReporterApiHandler.addNewSearch(body).subscribe( response => { }, err => { this.toastr.error("Failed to save the search. ", err); } ); } /** * Update the report header information * @param row The row to check. **/ private updateReportHeaders(): void { this.defectReporterApiHandler.getReportHeaders().subscribe(response => { let obj = JSON.parse(response.body.text()); let reportHeaders = obj.result; let reportUuids = []; for (let reportHeader of reportHeaders) { reportUuids.push(reportHeader['universal_unique_identifier']) } this.rows = []; for (let row of this.tmpRows) { let index = reportUuids.indexOf(row['universal_unique_identifier']); let header = index === -1 ? { bookmark: 0, report_status: 'unread', jira_status: 'pending' } : reportHeaders[index]; this.mergeReportProperties(row, header); if (index=== -1) { this.saveReportHeader(row); } } this.updateFilteredRows(); this.loading = false; }, err => { this.loading = false; this.toastr.error("Failed to update the addtional report information. " + err.message); }); } /** * Save header information of the current report to the DynamoDB table. * @param row The row to update. **/ private saveReportHeader(row): void { let body = { universal_unique_identifier: row["universal_unique_identifier"], bookmark: row["bookmark"], report_status: row["report_status"] } this.defectReporterApiHandler.updateReportHeader(body).subscribe(response => { }, err => { this.toastr.error("Failed to update the report header. " + err.message); }); } /** * Merge the header information with the current row * @param row The row to update. * @param header Addtional header information including bookmark and read status **/ private mergeReportProperties(row, header): void { for (let key of Object.keys(header)) { row[key] = JSON.parse(JSON.stringify(header[key])); } this.rows.push(row); } /** * Clears stored data for columns and rows **/ private clearData(): void { this.columns = []; this.allColumns = []; this.rows = []; this.filteredRows = []; } /** * Add a new cell to the columns * @param cell The cell to add. * @param isSort Boolean that indicates if this data came from a sort operation. **/ private addColumnObject(cell: string, isSort: boolean): void { let cellName = cell.toUpperCase(); let columnObject = {}; columnObject['name'] = cellName; columnObject['prop'] = cell; columnObject['sortable'] = true; this.allColumns.push(columnObject); if (!isSort) { this.columns.push(columnObject); } } /** * Update the selected rows when the user checks or unchecks the check box * @param row The changed row **/ private updateSelectedRows(row): void { if (row.selected) { this.selectedRows.push(row); } else { for (let i = 0; i < this.selectedRows.length; ++i) { let selectedRow = this.selectedRows[i]; if (selectedRow['universal_unique_identifier'] === row.universal_unique_identifier) { this.selectedRows.splice(i, 1); break; } } } } /** * Define CreateJiraTickets modal **/ public createJiraTicketsModal = () => { this.group = this.selectedRows.length <= 1 ? false : true; setTimeout(() => { this.fillingError['message'] = null; }); this.reportsToSubmit = []; let i = 0; while (i < this.selectedRows.length) { let selectedRow = this.selectedRows[i]; if (selectedRow['jira_status'] !== 'pending') { this.toastr.error(`The selected report '${selectedRow['universal_unique_identifier']}' has already been filed.`); selectedRow['selected'] = false; this.selectedRows.splice(i, 1); } else { let report = {}; for (let key of Object.keys(selectedRow)) { try { report[key] = { value: JSON.parse(selectedRow[key]), valid: true, message: `Required field cannot be empty.` } } catch (e) { report[key] = { value: selectedRow[key], valid: true, message: `Required field cannot be empty.` } } } this.reportsToSubmit.push(report); i++; } } if (this.reportsToSubmit.length > 0) { this.selectedReportIndex = 0; this.currentReport = this.reportsToSubmit[this.selectedReportIndex]; this.mode = DefectDatabaseMode.CreateJiraTickets; } this.bulkActionsButton.nativeElement.click(); } /** * Define Dismiss modal **/ public dismissModal = () => { this.mode = DefectDatabaseMode.Show; this.currentGroupMapping = {} } /** * Create new Jira ticket(s) based on the selected defect reports and grouping option **/ private submitCreationRequest(): void { setTimeout(() => { this.fillingError['message'] = null; }); if (!this.createJiraIssueWindow.validateJiraFields()) { setTimeout(() => { this.fillingError['message'] = "There is an error in one of the required fields."; }); return; } let reports = [] for (let i = 0; i < this.selectedRows.length; ++i) { reports.push(this.createJiraIssueWindow.retriveReportData(this.reportsToSubmit[i], this.selectedRows[i])); } let group_map = {} if (this.group) { group_map = this.createJiraIssueWindow.retriveReportData(this.currentGroupMapping); } let body = this.group ? { reports: reports, groupContent: group_map } : reports; this.createJiraIssueWindow.isLoadingJiraFieldMappings = true; this.createJiraIssues(body).subscribe(response => { this.modalRef.close(); for (let i = 0; i < this.selectedRows.length; ++i) { this.selectedRows[i]['selected'] = false; this.selectedRows[i]['jira_status'] = 'filed'; } this.selectedRows = []; this.toastr.success("New Jira tickets were created successfully."); }, err => { this.createJiraIssueWindow.isLoadingJiraFieldMappings = false; let msg = "Failed to create new Jira tickets. " + err.message; setTimeout(() => { this.fillingError['message'] = "There is an error in one of the required fields.\n" + msg; }); this.toastr.error(msg); }); } /** * Create one Jira ticket for each selected report or create a Jira ticket for the report group **/ private createJiraIssues(body): Observable<any> { return this.group ? this.defectReporterApiHandler.groupDefectReports(body) : this.defectReporterApiHandler.createJiraIssue(body); } /** * Switch to the next available selected report **/ private updateSelectedReportIndex(): void { if (this.createJiraIssueWindow.validateJiraFields()) { this.currentReport = this.reportsToSubmit[++this.selectedReportIndex]; } } /** * Send the event to update Jira integration settings **/ private updateJiraIntegrationSettings(): void { this.modalRef.close(); this.updateJiraMappings.emit(); } /** * Close the Create Jira Issue window **/ private closeCreateJiraIssueWindow(): void { this.modalRef.close(); this.dismissModal(); } private updateReportsToSubmitList(defect): void { setTimeout(() => { this.fillingError['message'] = null; }); if (this.group) { this.currentGroupMapping = defect; } else { this.reportsToSubmit[this.selectedReportIndex] = defect; } } }
the_stack
import { equals } from "../../Data/Eq" import { blackbirdF } from "../../Data/Function" import { fmap, fmapF, mapReplace } from "../../Data/Functor" import { consF, elem, filter, find, flength, head, List, map, maximum, NonEmptyList, notNull } from "../../Data/List" import { any, bind, bindF, ensure, fromJust, fromMaybe, isJust, isNothing, join, Just, liftM2, mapMaybe, maybe, Maybe, Nothing, or } from "../../Data/Maybe" import { add, gte, lt, max, multiply, subtractBy } from "../../Data/Num" import { elems, foldr, lookup, lookupF } from "../../Data/OrderedMap" import { Record } from "../../Data/Record" import { fst, snd, Tuple } from "../../Data/Tuple" import { uncurryN, uncurryN3 } from "../../Data/Tuple/Curry" import { sel1, sel2, sel3 } from "../../Data/Tuple/Select" import { AttrId } from "../Constants/Ids" import { AttributeDependent, createPlainAttributeDependent } from "../Models/ActiveEntries/AttributeDependent" import { Energies } from "../Models/Hero/Energies" import { HeroModel, HeroModelRecord } from "../Models/Hero/HeroModel" import { AttributeCombined, AttributeCombinedA_ } from "../Models/View/AttributeCombined" import { AttributeWithRequirements } from "../Models/View/AttributeWithRequirements" import { Attribute } from "../Models/Wiki/Attribute" import { ExperienceLevel } from "../Models/Wiki/ExperienceLevel" import { Race } from "../Models/Wiki/Race" import { StaticData, StaticDataRecord } from "../Models/Wiki/WikiModel" import { createMaybeSelector } from "../Utilities/createMaybeSelector" import { flattenDependencies } from "../Utilities/Dependencies/flattenDependencies" import { getSkillCheckAttributeMinimum } from "../Utilities/Increasable/AttributeSkillCheckMinimum" import { pipe, pipe_ } from "../Utilities/pipe" import { mapTradHeroEntryToAttrCombined } from "../Utilities/primaryAttributeUtils" import { getCurrentEl, getStartEl } from "./elSelectors" import { getBlessedTraditionFromState } from "./liturgicalChantsSelectors" import { getRace } from "./raceSelectors" import { getMagicalTraditionsFromHero } from "./spellsSelectors" import { getAttributes, getAttributeValueLimit, getCurrentAttributeAdjustmentId, getCurrentHeroPresent, getCurrentPhase, getHeroProp, getWiki, getWikiAttributes } from "./stateSelectors" const SDA = StaticData.A const HA = HeroModel.A const EA = Energies.A const ACA = AttributeCombined.A const ACA_ = AttributeCombinedA_ const AA = Attribute.A const AtDA = AttributeDependent.A const AWRA = AttributeWithRequirements.A export const getAttributeSum = createMaybeSelector ( getAttributes, getWikiAttributes, uncurryN (hero_attrs => foldr (pipe ( AA.id, lookupF (hero_attrs), maybe (add (8)) (pipe (AtDA.value, add)) )) (0)) ) /** * Returns the modifier if the attribute specified by `id` is a member of the * race `race` */ const getModIfSelectedAdjustment = (id: string) => (race: Record<Race>) => pipe_ ( race, Race.A.attributeAdjustmentsSelection, snd, ensure (elem (id)), mapReplace (fst (Race.A.attributeAdjustmentsSelection (race))), Maybe.sum ) const getModIfStaticAdjustment = (id: string) => pipe ( Race.A.attributeAdjustments, List.lookup (id), Maybe.sum ) const getAttributeMaximum = (id: string) => (mrace: Maybe<Record<Race>>) => (adjustmentId: string) => (startEl: Maybe<Record<ExperienceLevel>>) => (currentEl: Maybe<Record<ExperienceLevel>>) => (phase: Maybe<number>) => (attributeValueLimit: Maybe<boolean>): Maybe<number> => { if (any (lt (3)) (phase)) { if (isJust (mrace)) { const race = fromJust (mrace) const selectedAdjustment = adjustmentId === id ? getModIfSelectedAdjustment (id) (race) : 0 const staticAdjustment = getModIfStaticAdjustment (id) (race) return fmapF (startEl) (pipe ( ExperienceLevel.A.maxAttributeValue, add (selectedAdjustment + staticAdjustment) )) } return Just (0) } if (or (attributeValueLimit)) { return fmapF (currentEl) (pipe (ExperienceLevel.A.maxAttributeValue, add (2))) } return Nothing } const getAttributeMinimum = (wiki: StaticDataRecord) => (hero: HeroModelRecord) => /** * `(lp, ae, kp)` */ (added: Tuple<[number, number, number]>) => (mblessed_primary_attr: Maybe<Record<AttributeCombined>>) => (mhighest_magical_primary_attr: Maybe<Record<AttributeCombined>>) => (hero_entry: Record<AttributeDependent>): number => maximum (List<number> ( ...flattenDependencies (wiki) (hero) (AtDA.dependencies (hero_entry)), ...( AtDA.id (hero_entry) === AttrId.Constitution ? List (sel1 (added)) : List<number> () ), ...(Maybe.elem (AtDA.id (hero_entry)) (fmap (ACA_.id) (mhighest_magical_primary_attr)) ? List (sel2 (added)) : List<number> ()), ...(Maybe.elem (AtDA.id (hero_entry)) (fmap (ACA_.id) (mblessed_primary_attr)) ? List (sel3 (added)) : List<number> ()), fromMaybe (8) (getSkillCheckAttributeMinimum ( SDA.skills (wiki), SDA.spells (wiki), SDA.liturgicalChants (wiki), HA.attributes (hero), HA.skills (hero), HA.spells (hero), HA.liturgicalChants (hero), HA.skillCheckAttributeCache (hero), AtDA.id (hero_entry), )) )) const getAddedEnergies = createMaybeSelector ( getHeroProp, hero => Tuple ( pipe_ (hero, HA.energies, EA.addedLifePoints), pipe_ (hero, HA.energies, EA.addedArcaneEnergyPoints), pipe_ (hero, HA.energies, EA.addedKarmaPoints) ) ) /** * Returns a `List` of attributes containing the current state and full wiki * info. */ export const getAttributesForSheet = createMaybeSelector ( getAttributes, getWikiAttributes, uncurryN (hero_entries => pipe ( elems, map (wiki_entry => { const id = AA.id (wiki_entry) return AttributeCombined ({ stateEntry: fromMaybe (createPlainAttributeDependent (id)) (lookup (id) (hero_entries)), wikiEntry: wiki_entry, }) }) )) ) /** * Returns the maximum attribute value of the list of given attribute ids. */ export const getMaxAttributeValueByID = (attributes: HeroModel["attributes"]) => pipe ( mapMaybe (pipe (lookupF (attributes), fmap (AtDA.value))), consF (8), maximum ) export const getPrimaryMagicalAttributes = createMaybeSelector ( getWikiAttributes, getAttributes, getMagicalTraditionsFromHero, uncurryN3 (wiki_attributes => hero_attributes => mapMaybe (mapTradHeroEntryToAttrCombined (wiki_attributes) (hero_attributes))) ) export const getHighestPrimaryMagicalAttributeValue = createMaybeSelector ( getPrimaryMagicalAttributes, pipe (ensure (notNull), fmap (List.foldr (pipe (ACA_.value, max)) (0))) ) export const getHighestPrimaryMagicalAttributes = createMaybeSelector ( getPrimaryMagicalAttributes, getHighestPrimaryMagicalAttributeValue, uncurryN (attrs => fmap (max_value => filter (pipe (ACA_.value, equals (max_value))) (attrs))) ) type AttrCs = List<Record<AttributeCombined>> type NonEmotyAttrCs = NonEmptyList<Record<AttributeCombined>> export const getHighestPrimaryMagicalAttribute = createMaybeSelector ( getHighestPrimaryMagicalAttributes, pipe ( bindF (ensure (pipe (flength, equals (1)) as (xs: AttrCs) => xs is NonEmotyAttrCs)), fmap (head) ) ) export const getPrimaryMagicalAttributeForSheet = createMaybeSelector ( getPrimaryMagicalAttributes, map (ACA_.short) ) export const getPrimaryBlessedAttribute = createMaybeSelector ( getBlessedTraditionFromState, getAttributes, getWikiAttributes, (mtradition, hero_attributes, wiki_attributes) => bind (mtradition) (mapTradHeroEntryToAttrCombined (wiki_attributes) (hero_attributes)) ) export const getPrimaryBlessedAttributeForSheet = createMaybeSelector ( getPrimaryBlessedAttribute, fmap (pipe (ACA.wikiEntry, AA.short)) ) /** * Returns a `List` of attributes including state, full wiki infos and a * minimum and optional maximum value. */ export const getAttributesForView = createMaybeSelector ( getCurrentHeroPresent, getStartEl, getCurrentEl, getCurrentPhase, getAttributeValueLimit, getWiki, getRace, getAddedEnergies, getPrimaryBlessedAttribute, getHighestPrimaryMagicalAttribute, ( mhero, startEl, currentEl, mphase, attributeValueLimit, wiki, mrace, added, mblessed_primary_attr, mhighest_magical_primary_attr ) => fmapF (mhero) (hero => foldr ((wiki_entry: Record<Attribute>) => { const current_id = AA.id (wiki_entry) const hero_entry = fromMaybe (createPlainAttributeDependent (current_id)) (pipe_ ( hero, HeroModel.A.attributes, lookup (current_id) )) const max_value = getAttributeMaximum (current_id) (mrace) (HeroModel.A.attributeAdjustmentSelected (hero)) (startEl) (currentEl) (mphase) (attributeValueLimit) const min_value = getAttributeMinimum (wiki) (hero) (added) (mblessed_primary_attr) (mhighest_magical_primary_attr) (hero_entry) return consF (AttributeWithRequirements ({ max: max_value, min: min_value, stateEntry: hero_entry, wikiEntry: wiki_entry, })) }) (List.empty) (StaticData.A.attributes (wiki))) ) export const getCarryingCapacity = createMaybeSelector ( getAttributes, pipe (lookup<string> (AttrId.Strength), maybe (8) (AtDA.value), multiply (2)) ) export const getAdjustmentValue = createMaybeSelector ( getRace, fmap (pipe (Race.A.attributeAdjustmentsSelection, fst)) ) export const getCurrentAttributeAdjustment = createMaybeSelector ( getCurrentAttributeAdjustmentId, getAttributesForView, uncurryN (blackbirdF (liftM2 ((id: string) => find (pipe (AWRA.wikiEntry, AA.id, equals (id))))) (join as join<Record<AttributeWithRequirements>>)) ) export const getAvailableAdjustmentIds = createMaybeSelector ( getRace, getAdjustmentValue, getAttributesForView, getCurrentAttributeAdjustment, (mrace, madjustmentValue, mattrsCalculated, mcurr_attr) => fmapF (mrace) (pipe ( Race.A.attributeAdjustmentsSelection, snd, adjustmentIds => { if (isJust (mcurr_attr)) { const curr_attr = fromJust (mcurr_attr) const curr_attr_val = pipe_ (curr_attr, AWRA.stateEntry, AtDA.value) if (or (pipe_ (curr_attr, AWRA.max, liftM2 (blackbirdF (subtractBy) (lt (curr_attr_val))) (madjustmentValue)))) { const curr_attr_id = pipe_ (curr_attr, AWRA.stateEntry, AtDA.id) return List (curr_attr_id) } } return filter ((id: string) => { const mattr = bind (mattrsCalculated) (find (pipe (AWRA.wikiEntry, AA.id, equals (id)))) if (isJust (mattr)) { const attr = fromJust (mattr) const mmax = AWRA.max (attr) const mcurr_attr_id = fmapF (mcurr_attr) (pipe (AWRA.stateEntry, AtDA.id)) if (isNothing (mmax) || Maybe.elem (id) (mcurr_attr_id)) { return true } if (isJust (madjustmentValue)) { const attr_val = pipe_ (attr, AWRA.stateEntry, AtDA.value) return maybe (true) (pipe ( add (fromJust (madjustmentValue)), gte (attr_val) )) (mmax) } } return false }) (adjustmentIds) } )) )
the_stack
import { mount } from '@vue/test-utils'; import QueryBuilder from '@/QueryBuilder.vue'; import QueryBuilderGroup from '@/QueryBuilderGroup.vue'; import QueryBuilderRule from '@/QueryBuilderRule.vue'; import { QueryBuilderConfig } from '@/types'; import App from '../components/App.vue'; import Component from '../components/Component.vue'; interface QueryBuilderTemplate { value: any, config: QueryBuilderConfig, } describe('Test basic functionality of QueryBuilder.vue', () => { const getTemplate = (): QueryBuilderTemplate => ({ value: null, config: { operators: [ { name: 'AND', identifier: 'and', }, { name: 'OR', identifier: 'or', }, ], rules: [ { identifier: 'txt', name: 'Text Selection', component: Component, initialValue: '', }, { identifier: 'num', name: 'Number Selection', component: Component, initialValue: 10, }, ], }, }); it('it renders with blank configuration', () => { const template = getTemplate(); template.config.operators = []; template.config.rules = []; // The bare minimum configuration. // It entirely useless, but according to the spec, this is a valid configuration and show not // fail. mount(QueryBuilder, { propsData: template, }); }); it('selects an operator', () => { const app = mount(App, { data: getTemplate, }); const wrapper = app.findComponent(QueryBuilder); // Assert operators are available const options = wrapper.find('.query-builder-group__group-selection select').findAll('option'); expect(options).toHaveLength(3); expect(options.at(0).text()).toBe('Select an operator'); expect(options.at(0).element.attributes.getNamedItem('disabled')).toBeTruthy(); expect(options.at(1).text()).toBe('AND'); expect((options.at(1).element as HTMLOptionElement).value).toBe('and'); expect(options.at(2).text()).toBe('OR'); expect((options.at(2).element as HTMLOptionElement).value).toBe('or'); // Assert update has propagated options.at(2).setSelected(); expect(wrapper.emitted('input')).toHaveLength(1); expect(wrapper.emitted('input')).toStrictEqual([[{ operatorIdentifier: 'or', children: [] }]]); }); it('selects a rule', async () => { const app = mount(App, { data: getTemplate, }); const wrapper = app.findComponent(QueryBuilder); // Assert rules are available const rules = wrapper.find('.query-builder-group__group-control select').findAll('option'); expect(rules).toHaveLength(3); expect(rules.at(0).text()).toBe('Select a rule'); expect(rules.at(0).element.attributes.getNamedItem('disabled')).toBeTruthy(); expect(rules.at(1).text()).toBe('Text Selection'); expect((rules.at(1).element as HTMLOptionElement).value).toBe('txt'); expect(rules.at(2).text()).toBe('Number Selection'); expect((rules.at(2).element as HTMLOptionElement).value).toBe('num'); const addRuleBtn = wrapper.find('.query-builder-group__rule-adding-button'); expect((addRuleBtn.element as HTMLButtonElement).disabled).toBeTruthy(); // Assert update has propagated with default value rules.at(2).setSelected(); await wrapper.vm.$nextTick(); expect((addRuleBtn.element as HTMLButtonElement).disabled).toBeFalsy(); addRuleBtn.trigger('click'); expect(wrapper.emitted('input')).toHaveLength(1); expect(wrapper.emitted('input')).toStrictEqual([[{ operatorIdentifier: 'and', children: [{ identifier: 'num', value: 10 }] }]]); // Manually update value await wrapper.vm.$nextTick(); const num = wrapper.findComponent(Component); num.vm.$emit('input', 20); expect(wrapper.emitted('input')).toHaveLength(2); expect((wrapper.emitted('input') as any)[1]).toStrictEqual([{ operatorIdentifier: 'and', children: [{ identifier: 'num', value: 20 }] }]); }); it('makes use of an initial value\'s factory function', async () => { const initialValue = jest.fn(() => 'Hello World'); const data = getTemplate(); data.config.rules = [ { identifier: 'txt', name: 'Text Selection', component: Component, initialValue, }, ]; const app = mount(App, { data() { return { ...data }; }, }); const wrapper = app.findComponent(QueryBuilder); // Assert rules are available const group = wrapper.findComponent(QueryBuilderGroup); const rules = group.find('.query-builder-group__group-control select').findAll('option'); const addRuleBtn = group.find('.query-builder-group__rule-adding-button'); // Assert update has propagated with default value rules.at(1).setSelected(); await group.vm.$nextTick(); addRuleBtn.trigger('click'); expect(group.emitted('query-update')).toHaveLength(1); expect((group.emitted('query-update') as any)[0]).toStrictEqual([{ operatorIdentifier: 'and', children: [{ identifier: 'txt', value: 'Hello World' }] }]); expect(wrapper.emitted('input')).toHaveLength(1); expect((wrapper.emitted('input') as any)[0]).toStrictEqual([{ operatorIdentifier: 'and', children: [{ identifier: 'txt', value: 'Hello World' }] }]); expect(initialValue).toHaveBeenCalled(); }); it('deletes a rule', () => { const data = () => ({ query: { operatorIdentifier: 'and', children: [ { identifier: 'txt', value: 'A', }, { identifier: 'txt', value: 'B', }, { identifier: 'txt', value: 'C', }, ], }, config: { operators: [ { name: 'AND', identifier: 'and', }, { name: 'OR', identifier: 'or', }, ], rules: [ { identifier: 'txt', name: 'Text Selection', component: Component, initialValue: '', }, { identifier: 'num', name: 'Number Selection', component: Component, initialValue: 10, }, ], }, }); const app = mount(App, { data, }); app.findAllComponents(QueryBuilderRule) .filter(({ vm }) => vm.$props.query.identifier === 'txt' && vm.$props.query.value === 'B') .at(0) .vm .$parent .$emit('delete-child'); expect(app.vm.$data.query).toStrictEqual({ operatorIdentifier: 'and', children: [ { identifier: 'txt', value: 'A', }, { identifier: 'txt', value: 'C', }, ], }); }); it('renders a complex dataset', async () => { const data = () => ({ query: { operatorIdentifier: 'or', children: [ { operatorIdentifier: 'and', children: [ { identifier: 'txt', value: 'A', }, { identifier: 'txt', value: 'B', }, { identifier: 'txt', value: 'C', }, { operatorIdentifier: 'and', // <-- on this group, we're performing our tests children: [ { identifier: 'txt', value: 'c', }, { identifier: 'txt', value: 'd', }, { operatorIdentifier: 'and', children: [ { identifier: 'txt', value: 'a', }, { identifier: 'txt', value: 'b', }, ], }, ], }, ], }, { operatorIdentifier: 'and', children: [ { identifier: 'txt', value: 'X', }, { identifier: 'txt', value: 'Y', }, { identifier: 'txt', value: 'Z', }, ], }, ], }, config: { operators: [ { name: 'AND', identifier: 'and', }, { name: 'OR', identifier: 'or', }, ], rules: [ { identifier: 'txt', name: 'Text Selection', component: Component, initialValue: '', }, { identifier: 'num', name: 'Number Selection', component: Component, initialValue: 10, }, ], }, }); const app = mount(App, { data, }); const wrapper = app.findComponent(QueryBuilder); const qbGroup = wrapper.findAllComponents(QueryBuilderGroup) .filter( ({ vm }) => (vm as (QueryBuilderGroup & { readonly selectedOperator: string })).selectedOperator === 'and' && vm.$props.query.children.length === 3 && vm.$props.query.children[0].identifier === 'txt' && vm.$props.query.children[0].value === 'c', ) .at(0); // Assert operators are available const options = qbGroup.find('.query-builder-group__group-selection select').findAll('option'); expect(options).toHaveLength(3); expect(options.at(0).text()).toBe('Select an operator'); expect(options.at(0).element.attributes.getNamedItem('disabled')).toBeTruthy(); expect(options.at(1).text()).toBe('AND'); expect((options.at(1).element as HTMLOptionElement).value).toBe('and'); expect(options.at(2).text()).toBe('OR'); expect((options.at(2).element as HTMLOptionElement).value).toBe('or'); // Assert update has propagated options.at(2).setSelected(); expect(app.vm.$data.query).toStrictEqual({ operatorIdentifier: 'or', children: [ { operatorIdentifier: 'and', children: [ { identifier: 'txt', value: 'A', }, { identifier: 'txt', value: 'B', }, { identifier: 'txt', value: 'C', }, { operatorIdentifier: 'or', // <-- changed children: [ { identifier: 'txt', value: 'c', }, { identifier: 'txt', value: 'd', }, { operatorIdentifier: 'and', children: [ { identifier: 'txt', value: 'a', }, { identifier: 'txt', value: 'b', }, ], }, ], }, ], }, { operatorIdentifier: 'and', children: [ { identifier: 'txt', value: 'X', }, { identifier: 'txt', value: 'Y', }, { identifier: 'txt', value: 'Z', }, ], }, ], }); // Edit a rule expect(qbGroup.vm.$props.query.children).toHaveLength(3); const rules = qbGroup.findAllComponents(QueryBuilderRule); expect(rules).toHaveLength(4); const rule = rules .filter(({ vm: { $props } }) => $props.query.identifier === 'txt' && $props.query.value === 'd') .at(0); await wrapper.vm.$nextTick(); rule.find('.dummy-component').vm.$emit('input', 'D'); expect(app.vm.$data.query).toStrictEqual({ operatorIdentifier: 'or', children: [ { operatorIdentifier: 'and', children: [ { identifier: 'txt', value: 'A', }, { identifier: 'txt', value: 'B', }, { identifier: 'txt', value: 'C', }, { operatorIdentifier: 'or', children: [ { identifier: 'txt', value: 'c', }, { identifier: 'txt', value: 'D', // <-- changed }, { operatorIdentifier: 'and', children: [ { identifier: 'txt', value: 'a', }, { identifier: 'txt', value: 'b', }, ], }, ], }, ], }, { operatorIdentifier: 'and', children: [ { identifier: 'txt', value: 'X', }, { identifier: 'txt', value: 'Y', }, { identifier: 'txt', value: 'Z', }, ], }, ], }); // Add another group await wrapper.vm.$nextTick(); qbGroup.find('.query-builder-group__group-adding-button') .trigger('click'); expect(app.vm.$data.query).toStrictEqual({ operatorIdentifier: 'or', children: [ { operatorIdentifier: 'and', children: [ { identifier: 'txt', value: 'A', }, { identifier: 'txt', value: 'B', }, { identifier: 'txt', value: 'C', }, { operatorIdentifier: 'or', children: [ { identifier: 'txt', value: 'c', }, { identifier: 'txt', value: 'D', }, { operatorIdentifier: 'and', children: [ { identifier: 'txt', value: 'a', }, { identifier: 'txt', value: 'b', }, ], }, { // <-- Added operatorIdentifier: 'and', children: [], }, ], }, ], }, { operatorIdentifier: 'and', children: [ { identifier: 'txt', value: 'X', }, { identifier: 'txt', value: 'Y', }, { identifier: 'txt', value: 'Z', }, ], }, ], }); // Remove a rule await wrapper.vm.$nextTick(); rule.vm.$parent.$emit('delete-child'); expect(app.vm.$data.query).toStrictEqual({ operatorIdentifier: 'or', children: [ { operatorIdentifier: 'and', children: [ { identifier: 'txt', value: 'A', }, { identifier: 'txt', value: 'B', }, { identifier: 'txt', value: 'C', }, { operatorIdentifier: 'or', children: [ { identifier: 'txt', value: 'c', }, // Delete child here { operatorIdentifier: 'and', children: [ { identifier: 'txt', value: 'a', }, { identifier: 'txt', value: 'b', }, ], }, { // <-- Added operatorIdentifier: 'and', children: [], }, ], }, ], }, { operatorIdentifier: 'and', children: [ { identifier: 'txt', value: 'X', }, { identifier: 'txt', value: 'Y', }, { identifier: 'txt', value: 'Z', }, ], }, ], }); }); });
the_stack
declare class MXAnimationMetric extends MXMetric { static alloc(): MXAnimationMetric; // inherited from NSObject static new(): MXAnimationMetric; // inherited from NSObject readonly scrollHitchTimeRatio: NSMeasurement<NSUnit>; } declare class MXAppExitMetric extends MXMetric { static alloc(): MXAppExitMetric; // inherited from NSObject static new(): MXAppExitMetric; // inherited from NSObject readonly backgroundExitData: MXBackgroundExitData; readonly foregroundExitData: MXForegroundExitData; } declare class MXAppLaunchMetric extends MXMetric { static alloc(): MXAppLaunchMetric; // inherited from NSObject static new(): MXAppLaunchMetric; // inherited from NSObject readonly histogrammedApplicationResumeTime: MXHistogram<NSUnitDuration>; readonly histogrammedTimeToFirstDraw: MXHistogram<NSUnitDuration>; } declare class MXAppResponsivenessMetric extends MXMetric { static alloc(): MXAppResponsivenessMetric; // inherited from NSObject static new(): MXAppResponsivenessMetric; // inherited from NSObject readonly histogrammedApplicationHangTime: MXHistogram<NSUnitDuration>; } declare class MXAppRunTimeMetric extends MXMetric { static alloc(): MXAppRunTimeMetric; // inherited from NSObject static new(): MXAppRunTimeMetric; // inherited from NSObject readonly cumulativeBackgroundAudioTime: NSMeasurement<NSUnitDuration>; readonly cumulativeBackgroundLocationTime: NSMeasurement<NSUnitDuration>; readonly cumulativeBackgroundTime: NSMeasurement<NSUnitDuration>; readonly cumulativeForegroundTime: NSMeasurement<NSUnitDuration>; } declare class MXAverage<UnitType> extends NSObject implements NSSecureCoding { static alloc<UnitType>(): MXAverage<UnitType>; // inherited from NSObject static new<UnitType>(): MXAverage<UnitType>; // inherited from NSObject readonly averageMeasurement: NSMeasurement<UnitType>; readonly sampleCount: number; readonly standardDeviation: number; static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { coder: NSCoder; }); // inherited from NSCoding encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; } declare class MXBackgroundExitData extends NSObject implements NSSecureCoding { static alloc(): MXBackgroundExitData; // inherited from NSObject static new(): MXBackgroundExitData; // inherited from NSObject readonly cumulativeAbnormalExitCount: number; readonly cumulativeAppWatchdogExitCount: number; readonly cumulativeBackgroundTaskAssertionTimeoutExitCount: number; readonly cumulativeBadAccessExitCount: number; readonly cumulativeCPUResourceLimitExitCount: number; readonly cumulativeIllegalInstructionExitCount: number; readonly cumulativeMemoryPressureExitCount: number; readonly cumulativeMemoryResourceLimitExitCount: number; readonly cumulativeNormalAppExitCount: number; readonly cumulativeSuspendedWithLockedFileExitCount: number; static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { coder: NSCoder; }); // inherited from NSCoding encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; } declare class MXCPUExceptionDiagnostic extends MXDiagnostic { static alloc(): MXCPUExceptionDiagnostic; // inherited from NSObject static new(): MXCPUExceptionDiagnostic; // inherited from NSObject readonly callStackTree: MXCallStackTree; readonly totalCPUTime: NSMeasurement<NSUnitDuration>; readonly totalSampledTime: NSMeasurement<NSUnitDuration>; } declare class MXCPUMetric extends MXMetric { static alloc(): MXCPUMetric; // inherited from NSObject static new(): MXCPUMetric; // inherited from NSObject readonly cumulativeCPUInstructions: NSMeasurement<NSUnit>; readonly cumulativeCPUTime: NSMeasurement<NSUnitDuration>; } declare class MXCallStackTree extends NSObject implements NSSecureCoding { static alloc(): MXCallStackTree; // inherited from NSObject static new(): MXCallStackTree; // inherited from NSObject static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { coder: NSCoder; }); // inherited from NSCoding JSONRepresentation(): NSData; encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; } declare class MXCellularConditionMetric extends MXMetric { static alloc(): MXCellularConditionMetric; // inherited from NSObject static new(): MXCellularConditionMetric; // inherited from NSObject readonly histogrammedCellularConditionTime: MXHistogram<MXUnitSignalBars>; } declare class MXCrashDiagnostic extends MXDiagnostic { static alloc(): MXCrashDiagnostic; // inherited from NSObject static new(): MXCrashDiagnostic; // inherited from NSObject readonly callStackTree: MXCallStackTree; readonly exceptionCode: number; readonly exceptionType: number; readonly signal: number; readonly terminationReason: string; readonly virtualMemoryRegionInfo: string; } declare class MXDiagnostic extends NSObject implements NSSecureCoding { static alloc(): MXDiagnostic; // inherited from NSObject static new(): MXDiagnostic; // inherited from NSObject readonly applicationVersion: string; readonly metaData: MXMetaData; static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { coder: NSCoder; }); // inherited from NSCoding JSONRepresentation(): NSData; dictionaryRepresentation(): NSDictionary<any, any>; encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; } declare class MXDiagnosticPayload extends NSObject implements NSSecureCoding { static alloc(): MXDiagnosticPayload; // inherited from NSObject static new(): MXDiagnosticPayload; // inherited from NSObject readonly cpuExceptionDiagnostics: NSArray<MXCPUExceptionDiagnostic>; readonly crashDiagnostics: NSArray<MXCrashDiagnostic>; readonly diskWriteExceptionDiagnostics: NSArray<MXDiskWriteExceptionDiagnostic>; readonly hangDiagnostics: NSArray<MXHangDiagnostic>; readonly timeStampBegin: Date; readonly timeStampEnd: Date; static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { coder: NSCoder; }); // inherited from NSCoding JSONRepresentation(): NSData; dictionaryRepresentation(): NSDictionary<any, any>; encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; } declare class MXDiskIOMetric extends MXMetric { static alloc(): MXDiskIOMetric; // inherited from NSObject static new(): MXDiskIOMetric; // inherited from NSObject readonly cumulativeLogicalWrites: NSMeasurement<NSUnitInformationStorage>; } declare class MXDiskWriteExceptionDiagnostic extends MXDiagnostic { static alloc(): MXDiskWriteExceptionDiagnostic; // inherited from NSObject static new(): MXDiskWriteExceptionDiagnostic; // inherited from NSObject readonly callStackTree: MXCallStackTree; readonly totalWritesCaused: NSMeasurement<NSUnitInformationStorage>; } declare class MXDisplayMetric extends MXMetric { static alloc(): MXDisplayMetric; // inherited from NSObject static new(): MXDisplayMetric; // inherited from NSObject readonly averagePixelLuminance: MXAverage<MXUnitAveragePixelLuminance>; } declare class MXForegroundExitData extends NSObject implements NSSecureCoding { static alloc(): MXForegroundExitData; // inherited from NSObject static new(): MXForegroundExitData; // inherited from NSObject readonly cumulativeAbnormalExitCount: number; readonly cumulativeAppWatchdogExitCount: number; readonly cumulativeBadAccessExitCount: number; readonly cumulativeIllegalInstructionExitCount: number; readonly cumulativeMemoryResourceLimitExitCount: number; readonly cumulativeNormalAppExitCount: number; static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { coder: NSCoder; }); // inherited from NSCoding encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; } declare class MXGPUMetric extends MXMetric { static alloc(): MXGPUMetric; // inherited from NSObject static new(): MXGPUMetric; // inherited from NSObject readonly cumulativeGPUTime: NSMeasurement<NSUnitDuration>; } declare class MXHangDiagnostic extends MXDiagnostic { static alloc(): MXHangDiagnostic; // inherited from NSObject static new(): MXHangDiagnostic; // inherited from NSObject readonly callStackTree: MXCallStackTree; readonly hangDuration: NSMeasurement<NSUnitDuration>; } declare class MXHistogram<UnitType> extends NSObject implements NSSecureCoding { static alloc<UnitType>(): MXHistogram<UnitType>; // inherited from NSObject static new<UnitType>(): MXHistogram<UnitType>; // inherited from NSObject readonly bucketEnumerator: NSEnumerator<MXHistogramBucket<UnitType>>; readonly totalBucketCount: number; static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { coder: NSCoder; }); // inherited from NSCoding encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; } declare class MXHistogramBucket<UnitType> extends NSObject implements NSSecureCoding { static alloc<UnitType>(): MXHistogramBucket<UnitType>; // inherited from NSObject static new<UnitType>(): MXHistogramBucket<UnitType>; // inherited from NSObject readonly bucketCount: number; readonly bucketEnd: NSMeasurement<UnitType>; readonly bucketStart: NSMeasurement<UnitType>; static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { coder: NSCoder; }); // inherited from NSCoding encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; } declare class MXLocationActivityMetric extends MXMetric { static alloc(): MXLocationActivityMetric; // inherited from NSObject static new(): MXLocationActivityMetric; // inherited from NSObject readonly cumulativeBestAccuracyForNavigationTime: NSMeasurement<NSUnitDuration>; readonly cumulativeBestAccuracyTime: NSMeasurement<NSUnitDuration>; readonly cumulativeHundredMetersAccuracyTime: NSMeasurement<NSUnitDuration>; readonly cumulativeKilometerAccuracyTime: NSMeasurement<NSUnitDuration>; readonly cumulativeNearestTenMetersAccuracyTime: NSMeasurement<NSUnitDuration>; readonly cumulativeThreeKilometersAccuracyTime: NSMeasurement<NSUnitDuration>; } declare class MXMemoryMetric extends MXMetric { static alloc(): MXMemoryMetric; // inherited from NSObject static new(): MXMemoryMetric; // inherited from NSObject readonly averageSuspendedMemory: MXAverage<NSUnitInformationStorage>; readonly peakMemoryUsage: NSMeasurement<NSUnitInformationStorage>; } declare class MXMetaData extends NSObject implements NSSecureCoding { static alloc(): MXMetaData; // inherited from NSObject static new(): MXMetaData; // inherited from NSObject readonly applicationBuildVersion: string; readonly deviceType: string; readonly osVersion: string; readonly platformArchitecture: string; readonly regionFormat: string; static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { coder: NSCoder; }); // inherited from NSCoding DictionaryRepresentation(): NSDictionary<any, any>; JSONRepresentation(): NSData; dictionaryRepresentation(): NSDictionary<any, any>; encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; } declare class MXMetric extends NSObject implements NSSecureCoding { static alloc(): MXMetric; // inherited from NSObject static new(): MXMetric; // inherited from NSObject static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { coder: NSCoder; }); // inherited from NSCoding DictionaryRepresentation(): NSDictionary<any, any>; JSONRepresentation(): NSData; dictionaryRepresentation(): NSDictionary<any, any>; encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; } declare class MXMetricManager extends NSObject { static alloc(): MXMetricManager; // inherited from NSObject static makeLogHandleWithCategory(category: string): NSObject; static new(): MXMetricManager; // inherited from NSObject readonly pastDiagnosticPayloads: NSArray<MXDiagnosticPayload>; readonly pastPayloads: NSArray<MXMetricPayload>; static readonly sharedManager: MXMetricManager; addSubscriber(subscriber: MXMetricManagerSubscriber): void; removeSubscriber(subscriber: MXMetricManagerSubscriber): void; } interface MXMetricManagerSubscriber extends NSObjectProtocol { didReceiveDiagnosticPayloads?(payloads: NSArray<MXDiagnosticPayload> | MXDiagnosticPayload[]): void; didReceiveMetricPayloads?(payloads: NSArray<MXMetricPayload> | MXMetricPayload[]): void; } declare var MXMetricManagerSubscriber: { prototype: MXMetricManagerSubscriber; }; declare class MXMetricPayload extends NSObject implements NSSecureCoding { static alloc(): MXMetricPayload; // inherited from NSObject static new(): MXMetricPayload; // inherited from NSObject readonly animationMetrics: MXAnimationMetric; readonly applicationExitMetrics: MXAppExitMetric; readonly applicationLaunchMetrics: MXAppLaunchMetric; readonly applicationResponsivenessMetrics: MXAppResponsivenessMetric; readonly applicationTimeMetrics: MXAppRunTimeMetric; readonly cellularConditionMetrics: MXCellularConditionMetric; readonly cpuMetrics: MXCPUMetric; readonly diskIOMetrics: MXDiskIOMetric; readonly displayMetrics: MXDisplayMetric; readonly gpuMetrics: MXGPUMetric; readonly includesMultipleApplicationVersions: boolean; readonly latestApplicationVersion: string; readonly locationActivityMetrics: MXLocationActivityMetric; readonly memoryMetrics: MXMemoryMetric; readonly metaData: MXMetaData; readonly networkTransferMetrics: MXNetworkTransferMetric; readonly signpostMetrics: NSArray<MXSignpostMetric>; readonly timeStampBegin: Date; readonly timeStampEnd: Date; static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { coder: NSCoder; }); // inherited from NSCoding DictionaryRepresentation(): NSDictionary<any, any>; JSONRepresentation(): NSData; dictionaryRepresentation(): NSDictionary<any, any>; encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; } declare class MXNetworkTransferMetric extends MXMetric { static alloc(): MXNetworkTransferMetric; // inherited from NSObject static new(): MXNetworkTransferMetric; // inherited from NSObject readonly cumulativeCellularDownload: NSMeasurement<NSUnitInformationStorage>; readonly cumulativeCellularUpload: NSMeasurement<NSUnitInformationStorage>; readonly cumulativeWifiDownload: NSMeasurement<NSUnitInformationStorage>; readonly cumulativeWifiUpload: NSMeasurement<NSUnitInformationStorage>; } declare class MXSignpostIntervalData extends NSObject implements NSSecureCoding { static alloc(): MXSignpostIntervalData; // inherited from NSObject static new(): MXSignpostIntervalData; // inherited from NSObject readonly averageMemory: MXAverage<NSUnitInformationStorage>; readonly cumulativeCPUTime: NSMeasurement<NSUnitDuration>; readonly cumulativeHitchTimeRatio: NSMeasurement<NSUnit>; readonly cumulativeLogicalWrites: NSMeasurement<NSUnitInformationStorage>; readonly histogrammedSignpostDuration: MXHistogram<NSUnitDuration>; static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { coder: NSCoder; }); // inherited from NSCoding encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; } declare class MXSignpostMetric extends MXMetric { static alloc(): MXSignpostMetric; // inherited from NSObject static new(): MXSignpostMetric; // inherited from NSObject readonly signpostCategory: string; readonly signpostIntervalData: MXSignpostIntervalData; readonly signpostName: string; readonly totalCount: number; } declare class MXUnitAveragePixelLuminance extends NSDimension { static alloc(): MXUnitAveragePixelLuminance; // inherited from NSObject static baseUnit(): MXUnitAveragePixelLuminance; // inherited from NSDimension static new(): MXUnitAveragePixelLuminance; // inherited from NSObject static readonly apl: MXUnitAveragePixelLuminance; } declare class MXUnitSignalBars extends NSDimension { static alloc(): MXUnitSignalBars; // inherited from NSObject static baseUnit(): MXUnitSignalBars; // inherited from NSDimension static new(): MXUnitSignalBars; // inherited from NSObject static readonly bars: MXUnitSignalBars; }
the_stack
import Restful from '../../'; import { FulfillmentPolicyRequest, PaymentPolicyRequest, Program, ReturnPolicyRequest, SalesTaxBase } from '../../../../types'; import {PaymentsProgramType} from '../../../../enums'; /** * The <b>Account API</b> gives sellers the ability to configure their eBay seller accounts, * including the seller's policies (the Fulfillment Policy, Payment Policy, and Return Policy), * opt in and out of eBay seller programs, configure sales tax tables, and get account information. */ export default class Account extends Restful { static id = 'Account'; get basePath(): string { return '/sell/account/v1'; } /** * This method retrieves all the fulfillment policies configured for the marketplace you specify using the * marketplace_id query parameter. * * @param marketplaceId This query parameter specifies the eBay marketplace of the policies you want to retrieve. */ public getFulfillmentPolicies(marketplaceId: string) { return this.get(`/fulfillment_policy`, { params: { marketplace_id: marketplaceId } }); } /** * This method creates a new fulfillment policy where the policy encapsulates seller's terms for fulfilling item * purchases. * * @param body Request to create a seller account fulfillment policy. */ public createFulfillmentPolicy(body: FulfillmentPolicyRequest) { return this.post(`/fulfillment_policy`, body); } /** * This method updates an existing fulfillment policy. * * @param fulfillmentPolicyId This path parameter specifies the ID of the fulfillment policy you want to update. * @param body Request to create a seller account fulfillment policy. */ public updateFulfillmentPolicy(fulfillmentPolicyId: string, body: FulfillmentPolicyRequest) { const id = encodeURIComponent(fulfillmentPolicyId); return this.put(`/fulfillment_policy/${id}`, body); } /** * This method deletes a fulfillment policy. * * @param fulfillmentPolicyId This path parameter specifies the ID of the fulfillment policy to delete. */ public deleteFulfillmentPolicy(fulfillmentPolicyId: string) { const id = encodeURIComponent(fulfillmentPolicyId); return this.delete(`/fulfillment_policy/${id}`); } /** * This method retrieves the complete details of a fulfillment policy. * Supply the ID of the policy you want to retrieve using the fulfillmentPolicyId path parameter. * * @param fulfillmentPolicyId This path parameter specifies the ID of the fulfillment policy you want to retrieve. */ public getFulfillmentPolicy(fulfillmentPolicyId: string) { return this.get(`/fulfillment_policy/${fulfillmentPolicyId}`); } /** * This method retrieves the complete details for a single fulfillment policy. * * @param marketplaceId This query parameter specifies the eBay marketplace of the policy you want to retrieve. * @param name This query parameter specifies the user-defined name of the fulfillment policy you want to retrieve. */ public getFulfillmentPolicyByName(marketplaceId: string, name: string) { return this.get(`/fulfillment_policy/get_by_policy_name`, { params: { marketplace_id: marketplaceId, name } }); } /** * This method retrieves all the payment policies configured for the marketplace you specify using the * marketplace_id query parameter. * * @param marketplaceId This query parameter specifies the eBay marketplace of the policy you want to retrieve. */ public getPaymentPolicies(marketplaceId: string) { return this.get(`/payment_policy`, { params: { marketplace_id: marketplaceId } }); } /** * This method retrieves the complete details of a payment policy. Supply the ID of the policy you want to retrieve * using the paymentPolicyId path parameter. * * @param paymentPolicyId This path parameter specifies the ID of the payment policy you want to retrieve. */ public getPaymentPolicy(paymentPolicyId: string) { paymentPolicyId = encodeURIComponent(paymentPolicyId); return this.get(`/payment_policy/${paymentPolicyId}`); } /** * This method creates a new payment policy where the policy encapsulates seller's terms for purchase payments. * * @param body Payment policy request */ public createPaymentPolicy(body: PaymentPolicyRequest) { return this.post(`/payment_policy`, body); } /** * This method updates an existing payment policy. * * @param paymentPolicyId This path parameter specifies the ID of the payment policy you want to update. * @param body Payment policy request */ public updatePaymentPolicy(paymentPolicyId: string, body: PaymentPolicyRequest) { paymentPolicyId = encodeURIComponent(paymentPolicyId); return this.put(`/payment_policy/${paymentPolicyId}`, body); } /** * This method updates an existing payment policy. * * @param paymentPolicyId This path parameter specifies the ID of the payment policy you want to delete. */ public deletePaymentPolicy(paymentPolicyId: string) { paymentPolicyId = encodeURIComponent(paymentPolicyId); return this.delete(`/payment_policy/${paymentPolicyId}`); } /** * This method retrieves the complete details of a single payment policy. * * @param marketplaceId This query parameter specifies the eBay marketplace of the policy you want to retrieve. * @param name This query parameter specifies the user-defined name of the payment policy you want to retrieve. */ public getPaymentPolicyByName(marketplaceId: string, name: string) { return this.get(`/payment_policy/get_by_policy_name`, { params: { marketplace_id: marketplaceId, name } }); } /** * This method returns whether or not the user is opted-in to the payment program. * * @param marketplaceId This query parameter specifies the eBay marketplace of the policy you want to retrieve. * @param paymentsProgramType This path parameter specifies the payments program whose status is returned by the * call. */ public getPaymentsProgram(marketplaceId: string, paymentsProgramType: PaymentsProgramType) { marketplaceId = encodeURIComponent(marketplaceId); const type = encodeURIComponent(paymentsProgramType); return this.get(`/payments_program/${marketplaceId}/${type}`); } /** * This method retrieves a seller's onboarding status of eBay managed payments for a specified marketplace. * * @param marketplaceId This query parameter specifies the eBay marketplace of the policy you want to retrieve. * @param paymentsProgramType This path parameter specifies the payments program whose status is returned by the * call. */ public getPaymentsProgramOnboarding(marketplaceId: string, paymentsProgramType: PaymentsProgramType) { marketplaceId = encodeURIComponent(marketplaceId); const type = encodeURIComponent(paymentsProgramType); return this.get(`/payments_program/${marketplaceId}/${type}/onboarding`); } /** * This method retrieves the seller's current set of privileges. */ public getPrivileges() { return this.get(`/privilege`); } /** * This method gets a list of the seller programs that the seller has opted-in to. */ public getOptedInPrograms() { return this.get(`/program/get_opted_in_programs`); } /** * This method opts the seller in to an eBay seller program. * * @param body Program being opted-in to. */ public optInToProgram(body?: Program) { return this.post(`/program/opt_in`, body); } /** * This method opts the seller out of a seller program to which you have previously opted-in to. * * @param body Program being opted-out of. */ public optOutOfProgram(body?: Program) { return this.post(`/program/opt_out`, body); } /** * This method retrieves a seller's shipping rate tables for the country specified in the country_code query * parameter. * * @param countryCode This query parameter specifies the two-letter ISO 3166-1 Alpha-2 code of country for which * you want shipping-rate table information. */ public getRateTables(countryCode?: string) { return this.get(`/rate_table`, { params: { country_code: countryCode } }); } /** * This method retrieves all the return policies configured for the marketplace you specify using the * marketplace_id query parameter. * * @param marketplaceId This query parameter specifies the ID of the eBay marketplace of the policy you want to * retrieve. */ public getReturnPolicies(marketplaceId: string) { return this.get(`/return_policy`, { params: { marketplace_id: marketplaceId } }); } /** * This method retrieves the complete details of the return policy specified by the returnPolicyId path parameter. * * @param returnPolicyId This path parameter specifies the of the return policy you want to retrieve. */ public getReturnPolicy(returnPolicyId: string) { returnPolicyId = encodeURIComponent(returnPolicyId); return this.get(`/return_policy/${returnPolicyId}`); } /** * This method creates a new return policy where the policy encapsulates seller's terms for returning items. * * @param body Return policy request */ public createReturnPolicy(body: ReturnPolicyRequest) { return this.post(`/return_policy`, body); } /** * This method creates a new return policy where the policy encapsulates seller's terms for returning items. * * @param returnPolicyId This path parameter specifies the ID of the return policy you want to update. * @param body Return policy request */ public updateReturnPolicy(returnPolicyId: string, body: ReturnPolicyRequest) { returnPolicyId = encodeURIComponent(returnPolicyId); return this.put(`/return_policy/${returnPolicyId}`, body); } /** * This method deletes a return policy. * * @param returnPolicyId This path parameter specifies the ID of the return policy you want to delete. */ public deleteReturnPolicy(returnPolicyId: string) { returnPolicyId = encodeURIComponent(returnPolicyId); return this.delete(`/return_policy/${returnPolicyId}`); } /** * This method retrieves the complete details of a single return policy. * * @param marketplaceId This query parameter specifies the ID of the eBay marketplace of the policy you want to * retrieve. * @param name This query parameter specifies the user-defined name of the return policy you want to retrieve. */ public getReturnPolicyByName(marketplaceId: string, name: string) { return this.get(`/return_policy/get_by_policy_name`, { params: { marketplace_id: marketplaceId, name } }); } /** * This call gets the current tax table entry for a specific tax jurisdiction. * * @param countryCode This path parameter specifies the two-letter ISO 3166-1 Alpha-2 code for the country whose * tax table you want to retrieve. * @param jurisdictionId This path parameter specifies the ID of the sales tax jurisdiction for the tax table entry * you want to retrieve. */ public getSalesTax(countryCode: string, jurisdictionId: string) { countryCode = encodeURIComponent(countryCode); jurisdictionId = encodeURIComponent(jurisdictionId); return this.get(`/sales_tax/${countryCode}/${jurisdictionId}`); } /** * This method creates or updates a sales tax table entry for a jurisdiction. * * @param countryCode This path parameter specifies the two-letter ISO 3166-1 Alpha-2 code for the country for * which you want to create tax table entry. * @param jurisdictionId This path parameter specifies the ID of the sales-tax jurisdiction for the table entry you * want to create. * @param body A container that describes the how the sales tax is calculated. */ public createOrReplaceSalesTax(countryCode: string, jurisdictionId: string, body: SalesTaxBase) { countryCode = encodeURIComponent(countryCode); jurisdictionId = encodeURIComponent(jurisdictionId); return this.put(`/sales_tax/${countryCode}/${jurisdictionId}`, body); } /** * This call deletes a tax table entry for a jurisdiction. * * @param countryCode This path parameter specifies the two-letter ISO 3166-1 Alpha-2 code for the country for * which you want to create tax table entry. * @param jurisdictionId This path parameter specifies the ID of the sales-tax jurisdiction for the table entry you * want to delete. */ public deleteSalesTax(countryCode: string, jurisdictionId: string) { countryCode = encodeURIComponent(countryCode); jurisdictionId = encodeURIComponent(jurisdictionId); return this.delete(`/sales_tax/${countryCode}/${jurisdictionId}`); } /** * Use this call to retrieve a sales tax table that the seller established for a specific country. * * @param countryCode This path parameter specifies the two-letter ISO 3166-1 Alpha-2 code for the country whose * tax table you want to retrieve. */ public getSalesTaxes(countryCode: string) { return this.get(`/sales_tax`, { params: { country_code: countryCode } }); } /** * his method is used by sellers onboarded for eBay managed payments, or sellers who are currently going through, or who are eligible for onboarding for eBay managed payments. */ public getKYC() { return this.get(`/kyc`, ); } }
the_stack
'use strict'; var $ = require('preconditions').singleton(); import { BitcoreLib, BitcoreLibCash, Deriver, Transactions } from 'crypto-wallet-core'; import * as _ from 'lodash'; import 'source-map-support/register'; import { Constants, Utils } from './common'; import { Credentials } from './credentials'; var Bitcore = BitcoreLib; var Mnemonic = require('bitcore-mnemonic'); var sjcl = require('sjcl'); var log = require('./log'); const async = require('async'); const Uuid = require('uuid'); var Errors = require('./errors'); const wordsForLang: any = { en: Mnemonic.Words.ENGLISH, es: Mnemonic.Words.SPANISH, ja: Mnemonic.Words.JAPANESE, zh: Mnemonic.Words.CHINESE, fr: Mnemonic.Words.FRENCH, it: Mnemonic.Words.ITALIAN }; // we always set 'livenet' for xprivs. it has not consecuences // other than the serialization const NETWORK: string = 'livenet'; export class Key { #xPrivKey: string; #xPrivKeyEncrypted: string; #version: number; #mnemonic: string; #mnemonicEncrypted: string; #mnemonicHasPassphrase: boolean; public id: any; public use0forBCH: boolean; public use44forMultisig: boolean; public compliantDerivation: boolean; public BIP45: boolean; public fingerPrint: string; /* * public readonly exportFields = { * 'xPrivKey': '#xPrivKey', * 'xPrivKeyEncrypted': '#xPrivKeyEncrypted', * 'mnemonic': '#mnemonic', * 'mnemonicEncrypted': '#mnemonicEncrypted', * 'version': '#version', * 'mnemonicHasPassphrase': 'mnemonicHasPassphrase', * 'fingerPrint': 'fingerPrint', // 32bit fingerprint * 'compliantDerivation': 'compliantDerivation', * 'BIP45': 'BIP45', * * // data for derived credentials. * 'use0forBCH': 'use0forBCH', // use the 0 coin' path element in BCH (legacy) * 'use44forMultisig': 'use44forMultisig', // use the purpose 44' for multisig wallts (legacy) * 'id': 'id', * }; */ // * // * @param {Object} opts // * @param {String} opts.password encrypting password // * @param {String} seedType new|extendedPrivateKey|object|mnemonic // * @param {String} seedData // */ constructor( opts: { seedType: string; seedData?: any; passphrase?: string; // seed passphrase password?: string; // encrypting password sjclOpts?: any; // options to SJCL encrypt use0forBCH?: boolean; useLegacyPurpose?: boolean; useLegacyCoinType?: boolean; nonCompliantDerivation?: boolean; language?: string; } = { seedType: 'new' } ) { this.#version = 1; this.id = Uuid.v4(); // bug backwards compatibility flags this.use0forBCH = opts.useLegacyCoinType; this.use44forMultisig = opts.useLegacyPurpose; this.compliantDerivation = !opts.nonCompliantDerivation; let x = opts.seedData; switch (opts.seedType) { case 'new': if (opts.language && !wordsForLang[opts.language]) throw new Error('Unsupported language'); let m = new Mnemonic(wordsForLang[opts.language]); while (!Mnemonic.isValid(m.toString())) { m = new Mnemonic(wordsForLang[opts.language]); } this.setFromMnemonic(m, opts); break; case 'mnemonic': $.checkArgument(x, 'Need to provide opts.seedData'); $.checkArgument(_.isString(x), 'sourceData need to be a string'); this.setFromMnemonic(new Mnemonic(x), opts); break; case 'extendedPrivateKey': $.checkArgument(x, 'Need to provide opts.seedData'); let xpriv; try { xpriv = new Bitcore.HDPrivateKey(x); } catch (e) { throw new Error('Invalid argument'); } this.fingerPrint = xpriv.fingerPrint.toString('hex'); if (opts.password) { this.#xPrivKeyEncrypted = sjcl.encrypt( opts.password, xpriv.toString(), opts ); if (!this.#xPrivKeyEncrypted) throw new Error('Could not encrypt'); } else { this.#xPrivKey = xpriv.toString(); } this.#mnemonic = null; this.#mnemonicHasPassphrase = null; break; case 'object': $.shouldBeObject(x, 'Need to provide an object at opts.seedData'); $.shouldBeUndefined( opts.password, 'opts.password not allowed when source is object' ); if (this.#version != x.version) { throw new Error('Bad Key version'); } this.#xPrivKey = x.xPrivKey; this.#xPrivKeyEncrypted = x.xPrivKeyEncrypted; this.#mnemonic = x.mnemonic; this.#mnemonicEncrypted = x.mnemonicEncrypted; this.#mnemonicHasPassphrase = x.mnemonicHasPassphrase; this.#version = x.version; this.fingerPrint = x.fingerPrint; this.compliantDerivation = x.compliantDerivation; this.BIP45 = x.BIP45; this.id = x.id; this.use0forBCH = x.use0forBCH; this.use44forMultisig = x.use44forMultisig; $.checkState( this.#xPrivKey || this.#xPrivKeyEncrypted, 'Failed state: #xPrivKey || #xPrivKeyEncrypted at Key constructor' ); break; case 'objectV1': // Default Values for V1 this.use0forBCH = false; this.use44forMultisig = false; this.compliantDerivation = true; this.id = Uuid.v4(); if (!_.isUndefined(x.compliantDerivation)) this.compliantDerivation = x.compliantDerivation; if (!_.isUndefined(x.id)) this.id = x.id; this.#xPrivKey = x.xPrivKey; this.#xPrivKeyEncrypted = x.xPrivKeyEncrypted; this.#mnemonic = x.mnemonic; this.#mnemonicEncrypted = x.mnemonicEncrypted; this.#mnemonicHasPassphrase = x.mnemonicHasPassphrase; this.#version = x.version || 1; this.fingerPrint = x.fingerPrint; // If the wallet was single seed... multisig walelts accounts // will be 48' this.use44forMultisig = x.n > 1 ? true : false; // if old credentials had use145forBCH...use it. // else,if the wallet is bch, set it to true. this.use0forBCH = x.use145forBCH ? false : x.coin == 'bch' ? true : false; this.BIP45 = x.derivationStrategy == 'BIP45'; break; default: throw new Error('Unknown seed source: ' + opts.seedType); } } static match(a, b) { // fingerPrint is not always available (because xPriv could has // been imported encrypted) return a.id == b.id || a.fingerPrint == b.fingerPrint; } private setFromMnemonic( m, opts: { passphrase?: string; password?: string; sjclOpts?: any } ) { const xpriv = m.toHDPrivateKey(opts.passphrase, NETWORK); this.fingerPrint = xpriv.fingerPrint.toString('hex'); if (opts.password) { this.#xPrivKeyEncrypted = sjcl.encrypt( opts.password, xpriv.toString(), opts.sjclOpts ); if (!this.#xPrivKeyEncrypted) throw new Error('Could not encrypt'); this.#mnemonicEncrypted = sjcl.encrypt( opts.password, m.phrase, opts.sjclOpts ); if (!this.#mnemonicEncrypted) throw new Error('Could not encrypt'); } else { this.#xPrivKey = xpriv.toString(); this.#mnemonic = m.phrase; this.#mnemonicHasPassphrase = !!opts.passphrase; } } toObj = function () { const ret = { xPrivKey: this.#xPrivKey, xPrivKeyEncrypted: this.#xPrivKeyEncrypted, mnemonic: this.#mnemonic, mnemonicEncrypted: this.#mnemonicEncrypted, version: this.#version, mnemonicHasPassphrase: this.#mnemonicHasPassphrase, fingerPrint: this.fingerPrint, // 32bit fingerprint compliantDerivation: this.compliantDerivation, BIP45: this.BIP45, // data for derived credentials. use0forBCH: this.use0forBCH, use44forMultisig: this.use44forMultisig, id: this.id }; return _.clone(ret); }; isPrivKeyEncrypted = function () { return !!this.#xPrivKeyEncrypted && !this.#xPrivKey; }; checkPassword = function (password) { if (this.isPrivKeyEncrypted()) { try { sjcl.decrypt(password, this.#xPrivKeyEncrypted); } catch (ex) { return false; } return true; } return null; }; get = function (password) { let keys: any = {}; let fingerPrintUpdated = false; if (this.isPrivKeyEncrypted()) { $.checkArgument( password, 'Private keys are encrypted, a password is needed' ); try { keys.xPrivKey = sjcl.decrypt(password, this.#xPrivKeyEncrypted); // update fingerPrint if not set. if (!this.fingerPrint) { let xpriv = new Bitcore.HDPrivateKey(keys.xPrivKey); this.fingerPrint = xpriv.fingerPrint.toString('hex'); fingerPrintUpdated = true; } if (this.#mnemonicEncrypted) { keys.mnemonic = sjcl.decrypt(password, this.#mnemonicEncrypted); } } catch (ex) { throw new Error('Could not decrypt'); } } else { keys.xPrivKey = this.#xPrivKey; keys.mnemonic = this.#mnemonic; if (fingerPrintUpdated) { keys.fingerPrintUpdated = true; } } keys.mnemonicHasPassphrase = this.#mnemonicHasPassphrase || false; return keys; }; encrypt = function (password, opts) { if (this.#xPrivKeyEncrypted) throw new Error('Private key already encrypted'); if (!this.#xPrivKey) throw new Error('No private key to encrypt'); this.#xPrivKeyEncrypted = sjcl.encrypt(password, this.#xPrivKey, opts); if (!this.#xPrivKeyEncrypted) throw new Error('Could not encrypt'); if (this.#mnemonic) this.#mnemonicEncrypted = sjcl.encrypt(password, this.#mnemonic, opts); this.#xPrivKey = null; this.#mnemonic = null; }; decrypt = function (password) { if (!this.#xPrivKeyEncrypted) throw new Error('Private key is not encrypted'); try { this.#xPrivKey = sjcl.decrypt(password, this.#xPrivKeyEncrypted); if (this.#mnemonicEncrypted) { this.#mnemonic = sjcl.decrypt(password, this.#mnemonicEncrypted); } this.#xPrivKeyEncrypted = null; this.#mnemonicEncrypted = null; } catch (ex) { log.error('error decrypting:', ex); throw new Error('Could not decrypt'); } }; derive = function (password, path) { $.checkArgument(path, 'no path at derive()'); var xPrivKey = new Bitcore.HDPrivateKey( this.get(password).xPrivKey, NETWORK ); var deriveFn = this.compliantDerivation ? _.bind(xPrivKey.deriveChild, xPrivKey) : _.bind(xPrivKey.deriveNonCompliantChild, xPrivKey); return deriveFn(path); }; _checkCoin = function (coin) { if (!_.includes(Constants.COINS, coin)) throw new Error('Invalid coin'); }; _checkNetwork = function (network) { if (!_.includes(['livenet', 'testnet'], network)) throw new Error('Invalid network'); }; /* * This is only used on "create" * no need to include/support * BIP45 */ getBaseAddressDerivationPath = function (opts) { $.checkArgument(opts, 'Need to provide options'); $.checkArgument(opts.n >= 1, 'n need to be >=1'); let purpose = opts.n == 1 || this.use44forMultisig ? '44' : '48'; var coinCode = '0'; if (opts.network == 'testnet' && Constants.UTXO_COINS.includes(opts.coin)) { coinCode = '1'; } else if (opts.coin == 'bch') { if (this.use0forBCH) { coinCode = '0'; } else { coinCode = '145'; } } else if (opts.coin == 'btc') { coinCode = '0'; } else if (opts.coin == 'eth') { coinCode = '60'; } else if (opts.coin == 'xrp') { coinCode = '144'; } else if (opts.coin == 'doge') { coinCode = '3'; } else if (opts.coin == 'ltc') { coinCode = '2'; } else { throw new Error('unknown coin: ' + opts.coin); } return 'm/' + purpose + "'/" + coinCode + "'/" + opts.account + "'"; }; /* * opts.coin * opts.network * opts.account * opts.n */ createCredentials = function (password, opts) { opts = opts || {}; if (password) $.shouldBeString(password, 'provide password'); this._checkNetwork(opts.network); $.shouldBeNumber(opts.account, 'Invalid account'); $.shouldBeNumber(opts.n, 'Invalid n'); $.shouldBeUndefined(opts.useLegacyCoinType); $.shouldBeUndefined(opts.useLegacyPurpose); let path = this.getBaseAddressDerivationPath(opts); let xPrivKey = this.derive(password, path); let requestPrivKey = this.derive( password, Constants.PATHS.REQUEST_KEY ).privateKey.toString(); if (opts.network == 'testnet') { // Hacky: BTC/BCH xPriv depends on network: This code is to // convert a livenet xPriv to a testnet xPriv let x = xPrivKey.toObject(); x.network = 'testnet'; delete x.xprivkey; delete x.checksum; x.privateKey = _.padStart(x.privateKey, 64, '0'); xPrivKey = new Bitcore.HDPrivateKey(x); } return Credentials.fromDerivedKey({ xPubKey: xPrivKey.hdPublicKey.toString(), coin: opts.coin, network: opts.network, account: opts.account, n: opts.n, rootPath: path, keyId: this.id, requestPrivKey, addressType: opts.addressType, walletPrivKey: opts.walletPrivKey }); }; /* * opts * opts.path * opts.requestPrivKey */ createAccess = function (password, opts) { opts = opts || {}; $.shouldBeString(opts.path); var requestPrivKey = new Bitcore.PrivateKey(opts.requestPrivKey || null); var requestPubKey = requestPrivKey.toPublicKey().toString(); var xPriv = this.derive(password, opts.path); var signature = Utils.signRequestPubKey(requestPubKey, xPriv); requestPrivKey = requestPrivKey.toString(); return { signature, requestPrivKey }; }; sign = function (rootPath, txp, password, cb) { $.shouldBeString(rootPath); if (this.isPrivKeyEncrypted() && !password) { return cb(new Errors.ENCRYPTED_PRIVATE_KEY()); } var privs = []; var derived: any = {}; var derived = this.derive(password, rootPath); var xpriv = new Bitcore.HDPrivateKey(derived); var t = Utils.buildTx(txp); if (Constants.UTXO_COINS.includes(txp.coin)) { _.each(txp.inputs, function (i) { $.checkState( i.path, 'Input derivation path not available (signing transaction)' ); if (!derived[i.path]) { derived[i.path] = xpriv.deriveChild(i.path).privateKey; privs.push(derived[i.path]); } }); var signatures = _.map(privs, function (priv, i) { return t.getSignatures(priv, undefined, txp.signingMethod); }); signatures = _.map( _.sortBy(_.flatten(signatures), 'inputIndex'), function (s) { return s.signature.toDER(txp.signingMethod).toString('hex'); } ); return signatures; } else { let tx = t.uncheckedSerialize(); tx = typeof tx === 'string' ? [tx] : tx; const chain = txp.chain ? txp.chain.toUpperCase() : Utils.getChain(txp.coin); const txArray = _.isArray(tx) ? tx : [tx]; const isChange = false; const addressIndex = 0; const { privKey, pubKey } = Deriver.derivePrivateKey( chain, txp.network, derived, addressIndex, isChange ); let signatures = []; for (const rawTx of txArray) { const signed = Transactions.getSignature({ chain, tx: rawTx, key: { privKey, pubKey } }); signatures.push(signed); } return signatures; } }; }
the_stack
import {Subject} from "../Subject"; import {OrmUtils} from "../../util/OrmUtils"; import {ObjectLiteral} from "../../common/ObjectLiteral"; import {RelationMetadata} from "../../metadata/RelationMetadata"; /** * Builds operations needs to be executed for many-to-many relations of the given subjects. * * by example: post contains owner many-to-many relation with categories in the property called "categories", e.g. * @ManyToMany(type => Category, category => category.posts) categories: Category[] * If user adds categories into the post and saves post we need to bind them. * This operation requires updation of junction table. */ export class ManyToManySubjectBuilder { // --------------------------------------------------------------------- // Constructor // --------------------------------------------------------------------- constructor(protected subjects: Subject[]) { } // --------------------------------------------------------------------- // Public Methods // --------------------------------------------------------------------- /** * Builds operations for any changes in the many-to-many relations of the subjects. */ build(): void { this.subjects.forEach(subject => { // if subject doesn't have entity then no need to find something that should be inserted or removed if (!subject.entity) return; // go through all persistence enabled many-to-many relations and build subject operations for them subject.metadata.manyToManyRelations.forEach(relation => { // skip relations for which persistence is disabled if (relation.persistenceEnabled === false) return; this.buildForSubjectRelation(subject, relation); }); }); } /** * Builds operations for removal of all many-to-many records of all many-to-many relations of the given subject. */ buildForAllRemoval(subject: Subject) { // if subject does not have a database entity then it means it does not exist in the database // if it does not exist in the database then we don't have anything for deletion if (!subject.databaseEntity) return; // go through all persistence enabled many-to-many relations and build subject operations for them subject.metadata.manyToManyRelations.forEach(relation => { // skip relations for which persistence is disabled if (relation.persistenceEnabled === false) return; // get all related entities (actually related entity relation ids) bind to this subject entity // by example: returns category ids of the post we are currently working with (subject.entity is post) const relatedEntityRelationIdsInDatabase: ObjectLiteral[] = relation.getEntityValue(subject.databaseEntity!); // go through all related entities and create a new junction subject for each row in junction table relatedEntityRelationIdsInDatabase.forEach(relationId => { const junctionSubject = new Subject({ metadata: relation.junctionEntityMetadata!, parentSubject: subject, mustBeRemoved: true, identifier: this.buildJunctionIdentifier(subject, relation, relationId) }); // we use unshift because we need to perform those operations before post deletion is performed // but post deletion was already added as an subject // this is temporary solution, later we need to implement proper sorting of subjects before their removal this.subjects.push(junctionSubject); }); }); } // --------------------------------------------------------------------- // Protected Methods // --------------------------------------------------------------------- /** * Builds operations for a given subject and relation. * * by example: subject is "post" entity we are saving here and relation is "categories" inside it here. */ protected buildForSubjectRelation(subject: Subject, relation: RelationMetadata) { // load from db all relation ids of inverse entities that are "bind" to the subject's entity // this way we gonna check which relation ids are missing and which are new (e.g. inserted or removed) let databaseRelatedEntityIds: ObjectLiteral[] = []; // if subject don't have database entity it means all related entities in persisted subject are new and must be bind // and we don't need to remove something that is not exist if (subject.databaseEntity) databaseRelatedEntityIds = relation.getEntityValue(subject.databaseEntity); // extract entity's relation value // by example: categories inside our post (subject.entity is post) let relatedEntities: ObjectLiteral[] = relation.getEntityValue(subject.entity!); if (relatedEntities === null) // if value set to null its equal if we set it to empty array - all items must be removed from the database relatedEntities = []; if (!(Array.isArray(relatedEntities))) return; // from all related entities find only those which aren't found in the db - for them we will create operation subjects relatedEntities.forEach(relatedEntity => { // by example: relatedEntity is category from categories saved with post // todo: check how it will work for entities which are saved by cascades, but aren't saved in the database yet // extract only relation id from the related entities, since we only need it for comparision // by example: extract from category only relation id (category id, or let's say category title, depend on join column options) let relatedEntityRelationIdMap = relation.inverseEntityMetadata!.getEntityIdMap(relatedEntity); // try to find a subject of this related entity, maybe it was loaded or was marked for persistence const relatedEntitySubject = this.subjects.find(subject => { return subject.entity === relatedEntity; }); // if subject with entity was found take subject identifier as relation id map since it may contain extra properties resolved if (relatedEntitySubject) relatedEntityRelationIdMap = relatedEntitySubject.identifier; // if related entity relation id map is empty it means related entity is newly persisted if (!relatedEntityRelationIdMap) { // we decided to remove this error because it brings complications when saving object with non-saved entities // if related entity does not have a subject then it means user tries to bind entity which wasn't saved // in this persistence because he didn't pass this entity for save or he did not set cascades // but without entity being inserted we cannot bind it in the relation operation, so we throw an exception here // we decided to remove this error because it brings complications when saving object with non-saved entities // if (!relatedEntitySubject) // throw new TypeORMError(`Many-to-many relation "${relation.entityMetadata.name}.${relation.propertyPath}" contains ` + // `entities which do not exist in the database yet, thus they cannot be bind in the database. ` + // `Please setup cascade insertion or save entities before binding it.`); if (!relatedEntitySubject) return; } // try to find related entity in the database // by example: find post's category in the database post's categories const relatedEntityExistInDatabase = databaseRelatedEntityIds.find(databaseRelatedEntityRelationId => { return OrmUtils.compareIds(databaseRelatedEntityRelationId, relatedEntityRelationIdMap); }); // if entity is found then don't do anything - it means binding in junction table already exist, we don't need to add anything if (relatedEntityExistInDatabase) return; const ownerValue = relation.isOwning ? subject : (relatedEntitySubject || relatedEntity); // by example: ownerEntityMap is post from subject here const inverseValue = relation.isOwning ? (relatedEntitySubject || relatedEntity) : subject; // by example: inverseEntityMap is category from categories array here // create a new subject for insert operation of junction rows const junctionSubject = new Subject({ metadata: relation.junctionEntityMetadata!, parentSubject: subject, canBeInserted: true, }); this.subjects.push(junctionSubject); relation.junctionEntityMetadata!.ownerColumns.forEach(column => { junctionSubject.changeMaps.push({ column: column, value: ownerValue, // valueFactory: (value) => column.referencedColumn!.getEntityValue(value) // column.referencedColumn!.getEntityValue(ownerEntityMap), }); }); relation.junctionEntityMetadata!.inverseColumns.forEach(column => { junctionSubject.changeMaps.push({ column: column, value: inverseValue, // valueFactory: (value) => column.referencedColumn!.getEntityValue(value) // column.referencedColumn!.getEntityValue(inverseEntityMap), }); }); }); // get all inverse entities relation ids that are "bind" to the currently persisted entity const changedInverseEntityRelationIds: ObjectLiteral[] = []; relatedEntities.forEach(relatedEntity => { // relation.inverseEntityMetadata!.getEntityIdMap(relatedEntity) let relatedEntityRelationIdMap = relation.inverseEntityMetadata!.getEntityIdMap(relatedEntity); // try to find a subject of this related entity, maybe it was loaded or was marked for persistence const relatedEntitySubject = this.subjects.find(subject => { return subject.entity === relatedEntity; }); // if subject with entity was found take subject identifier as relation id map since it may contain extra properties resolved if (relatedEntitySubject) relatedEntityRelationIdMap = relatedEntitySubject.identifier; if (relatedEntityRelationIdMap !== undefined && relatedEntityRelationIdMap !== null) changedInverseEntityRelationIds.push(relatedEntityRelationIdMap); }); // now from all entities in the persisted entity find only those which aren't found in the db const removedJunctionEntityIds = databaseRelatedEntityIds.filter(existRelationId => { return !changedInverseEntityRelationIds.find(changedRelationId => { return OrmUtils.compareIds(changedRelationId, existRelationId); }); }); // finally create a new junction remove operations for missing related entities removedJunctionEntityIds.forEach(removedEntityRelationId => { const junctionSubject = new Subject({ metadata: relation.junctionEntityMetadata!, parentSubject: subject, mustBeRemoved: true, identifier: this.buildJunctionIdentifier(subject, relation, removedEntityRelationId) }); this.subjects.push(junctionSubject); }); } /** * Creates identifiers for junction table. * Example: { postId: 1, categoryId: 2 } */ protected buildJunctionIdentifier(subject: Subject, relation: RelationMetadata, relationId: ObjectLiteral) { const ownerEntityMap = relation.isOwning ? subject.entity! : relationId; const inverseEntityMap = relation.isOwning ? relationId : subject.entity!; const identifier: ObjectLiteral = {}; relation.junctionEntityMetadata!.ownerColumns.forEach(column => { OrmUtils.mergeDeep(identifier, column.createValueMap(column.referencedColumn!.getEntityValue(ownerEntityMap))); }); relation.junctionEntityMetadata!.inverseColumns.forEach(column => { OrmUtils.mergeDeep(identifier, column.createValueMap(column.referencedColumn!.getEntityValue(inverseEntityMap))); }); return identifier; } }
the_stack
require('./data-cube-edit.css'); import * as React from 'react'; import { List } from 'immutable'; import { AttributeInfo, Attributes, findByName, Nameable } from 'plywood'; import { classNames } from '../../../utils/dom/dom'; import { Ajax } from '../../../utils/ajax/ajax'; import { generateUniqueName } from '../../../../common/utils/string/string'; import { pluralIfNeeded } from "../../../../common/utils/general/general"; import { Notifier } from '../../../components/notifications/notifications'; import { Duration, Timezone } from 'chronoshift'; import { DATA_CUBES_STRATEGIES_LABELS, STRINGS } from '../../../config/constants'; import { SvgIcon, FormLabel, Button, SimpleTableColumn, SimpleTable, ImmutableInput, ImmutableList, ImmutableDropdown } from '../../../components/index'; import { DimensionModal, MeasureModal, SuggestionModal } from '../../../modals/index'; import { AppSettings, ListItem, Cluster, DataCube, Dimension, DimensionJS, Measure, MeasureJS, Customization } from '../../../../common/models/index'; import { DATA_CUBE as LABELS } from '../../../../common/models/labels'; import { ImmutableFormDelegate, ImmutableFormState } from '../../../delegates/index'; import { DataTable } from '../data-table/data-table'; export interface DataCubeEditProps extends React.Props<any> { isNewDataCube?: boolean; dataCube?: DataCube; clusters?: Cluster[]; tab?: string; onSave: (newDataCube: DataCube) => void; onCancel?: () => void; } export interface DataCubeEditState extends ImmutableFormState<DataCube> { tab?: any; modal?: Modal; } export interface Tab { label: string; value: string; render: () => JSX.Element; icon: string; } export interface Modal extends Nameable { name: string; render: (arg?: any) => JSX.Element; active?: boolean; } export class DataCubeEdit extends React.Component<DataCubeEditProps, DataCubeEditState> { private tabs: Tab[] = [ { label: 'General', value: 'general', render: this.renderGeneral, icon: require(`../../../icons/full-settings.svg`) }, { label: 'Data', value: 'data', render: this.renderData, icon: require(`../../../icons/data.svg`) }, { label: 'Dimensions', value: 'dimensions', render: this.renderDimensions, icon: require(`../../../icons/full-cube.svg`) }, { label: 'Measures', value: 'measures', render: this.renderMeasures, icon: require(`../../../icons/measures.svg`) }, { label: 'Other', value: 'other', render: this.renderOther, icon: require(`../../../icons/full-more.svg`) } ]; private modals: Modal[] = [ { name: 'dimensions', render: this.renderDimensionSuggestions }, { name: 'measures', render: this.renderMeasureSuggestions } ]; private delegate: ImmutableFormDelegate<DataCube>; constructor() { super(); this.delegate = new ImmutableFormDelegate<DataCube>(this); } componentWillReceiveProps(nextProps: DataCubeEditProps) { if (nextProps.dataCube) { this.initFromProps(nextProps); } } componentDidMount() { if (this.props.dataCube) this.initFromProps(this.props); } initFromProps(props: DataCubeEditProps) { this.setState({ newInstance: this.state.newInstance || new DataCube(props.dataCube.valueOf()), canSave: true, errors: {}, tab: props.isNewDataCube ? this.tabs[0] : this.tabs.filter((tab) => tab.value === props.tab)[0], modal: null }); } selectTab(tab: Tab) { if (this.props.isNewDataCube) { this.setState({tab}); } else { var hash = window.location.hash.split('/'); hash.splice(-1); window.location.hash = hash.join('/') + '/' + tab.value; } } renderTabs(activeTab: Tab): JSX.Element[] { return this.tabs.map((tab) => { return <Button className={classNames({active: activeTab.value === tab.value})} title={tab.label} type="primary" svg={tab.icon} key={tab.value} onClick={this.selectTab.bind(this, tab)} />; }); } cancel() { const { isNewDataCube } = this.props; if (isNewDataCube) { this.props.onCancel(); return; } // Setting newInstance to undefined resets the inputs this.setState({newInstance: undefined}, () => this.initFromProps(this.props)); } save() { if (this.props.onSave) this.props.onSave(this.state.newInstance); } goBack() { const { dataCube, tab } = this.props; var hash = window.location.hash; window.location.hash = hash.replace(`/${dataCube.name}/${tab}`, ''); } renderGeneral(): JSX.Element { const { clusters } = this.props; const { newInstance, errors } = this.state; var makeLabel = FormLabel.simpleGenerator(LABELS, errors); var makeTextInput = ImmutableInput.simpleGenerator(newInstance, this.delegate.onChange); var makeDropdownInput = ImmutableDropdown.simpleGenerator(newInstance, this.delegate.onChange); var possibleClusters = [ { value: 'native', label: 'Load a file and serve it natively' } ].concat(clusters.map((cluster) => { return { value: cluster.name, label: cluster.title }; })); var timezones = Customization.DEFAULT_TIMEZONES.map((tz) => { return { label: tz.toString(), value: tz }; }); return <form className="general vertical"> {makeLabel('title')} {makeTextInput('title', /.*/, true)} {makeLabel('description')} {makeTextInput('description')} {makeLabel('clusterName')} {makeDropdownInput('clusterName', possibleClusters)} {makeLabel('source')} {makeTextInput('source')} {makeLabel('defaultTimezone')} {makeDropdownInput('defaultTimezone', timezones) } </form>; } // --------------------------------------------------- renderData(): JSX.Element { const { newInstance } = this.state; const onChange = (newDataCube: DataCube) => { this.setState({ newInstance: newDataCube }); }; return <DataTable dataCube={newInstance} onChange={onChange}/>; } openModal(name: string) { this.setState({ modal: findByName(this.modals, name) }); } closeModal() { this.setState({ modal: null }); } // --------------------------------------------------- renderDimensions(): JSX.Element { const { newInstance } = this.state; const onChange = (newDimensions: List<Dimension>) => { const newCube = newInstance.changeDimensions(newDimensions); this.setState({ newInstance: newCube }); }; const getModal = (item: Dimension) => { return <DimensionModal dimension={item} validate={newInstance.validateFormula.bind(newInstance)} />; }; const getNewItem = () => Dimension.fromJS({ name: generateUniqueName('d', name => !newInstance.dimensions.find(m => m.name === name)), title: 'New dimension' }); const getRows = (items: List<Dimension>) => items.toArray().map((dimension) => { return { title: dimension.title, description: dimension.expression.toString(), icon: require(`../../../icons/dim-${dimension.kind}.svg`) }; }); const DimensionsList = ImmutableList.specialize<Dimension>(); return <DimensionsList label={STRINGS.dimensions} items={newInstance.dimensions} onChange={onChange.bind(this)} getModal={getModal} getNewItem={getNewItem} getRows={getRows} toggleSuggestions={this.openModal.bind(this, 'dimensions')} />; } addDimensions(extraDimensions: Dimension[]) { const { newInstance } = this.state; this.setState({ newInstance: newInstance.appendDimensions(extraDimensions) }); } renderDimensionSuggestions() { const { newInstance } = this.state; const onOk = { label: (n: number) => `${STRINGS.add} ${pluralIfNeeded(n, 'dimension')}`, callback: (newDimensions: Dimension[]) => { this.addDimensions(newDimensions); this.closeModal(); } }; const onDoNothing = { label: () => STRINGS.cancel, callback: this.closeModal.bind(this) }; const suggestions = newInstance.getSuggestedDimensions().map(d => { return {label: `${d.title} (${d.formula})`, value: d}; }); const DimensionSuggestionModal = SuggestionModal.specialize<Dimension>(); return <DimensionSuggestionModal onOk={onOk} onDoNothing={onDoNothing} onClose={this.closeModal.bind(this)} suggestions={suggestions} title={`${STRINGS.dimension} ${STRINGS.suggestion}s`} />; } // --------------------------------------------------- renderMeasures(): JSX.Element { var { newInstance } = this.state; const onChange = (newMeasures: List<Measure>) => { var { defaultSortMeasure } = newInstance; if (defaultSortMeasure) { if (!newMeasures.find((measure) => measure.name === defaultSortMeasure)) { newInstance = newInstance.changeDefaultSortMeasure(null); } } const newCube = newInstance.changeMeasures(newMeasures); this.setState({ newInstance: newCube }); }; const getModal = (item: Measure) => { return <MeasureModal measure={item} validate={newInstance.validateFormulaInMeasureContext.bind(newInstance)}/>; }; const getNewItem = () => Measure.fromJS({ name: generateUniqueName('m', name => !newInstance.measures.find(m => m.name === name)), title: 'New measure' }); const getRows = (items: List<Measure>) => items.toArray().map((measure) => { return { title: measure.title, description: measure.expression.toString(), icon: require(`../../../icons/measures.svg`) }; }); const MeasuresList = ImmutableList.specialize<Measure>(); return <MeasuresList label={STRINGS.measures} items={newInstance.measures} onChange={onChange.bind(this)} getModal={getModal} getNewItem={getNewItem} getRows={getRows} toggleSuggestions={this.openModal.bind(this, 'measures')} />; } addMeasures(extraMeasures: Measure[]) { const { newInstance } = this.state; this.setState({ newInstance: newInstance.appendMeasures(extraMeasures) }); } renderMeasureSuggestions() { const { newInstance } = this.state; const onOk = { label: (n: number) => `${STRINGS.add} ${pluralIfNeeded(n, 'measure')}`, callback: (newMeasures: Measure[]) => { this.addMeasures(newMeasures); this.closeModal(); } }; const onDoNothing = { label: () => STRINGS.cancel, callback: this.closeModal.bind(this) }; const suggestions = newInstance.getSuggestedMeasures().map(d => { return {label: `${d.title} (${d.formula})`, value: d}; }); const MeasureSuggestionModal = SuggestionModal.specialize<Measure>(); return <MeasureSuggestionModal onOk={onOk} onDoNothing={onDoNothing} onClose={this.closeModal.bind(this)} suggestions={suggestions} title={`${STRINGS.measure} ${STRINGS.suggestion}s`} />; } // --------------------------------------------------- renderOther(): JSX.Element { const { newInstance, errors } = this.state; var makeLabel = FormLabel.simpleGenerator(LABELS, errors); return <form className="general vertical"> {makeLabel('options')} <ImmutableInput instance={newInstance} path={'options'} onChange={this.delegate.onChange} valueToString={(value: AttributeInfo[]) => value ? JSON.stringify(value, null, 2) : undefined} stringToValue={(str: string) => str ? JSON.parse(str) : undefined} type="textarea" /> </form>; } renderButtons(): JSX.Element { const { dataCube, isNewDataCube } = this.props; const { canSave, newInstance } = this.state; const hasChanged = !dataCube.equals(newInstance); const cancelButton = <Button className="cancel" title={isNewDataCube ? "Cancel" : "Revert changes"} type="secondary" onClick={this.cancel.bind(this)} />; const saveButton = <Button className={classNames("save", {disabled: !canSave || (!isNewDataCube && !hasChanged)})} title={isNewDataCube ? "Create cube" : "Save"} type="primary" onClick={this.save.bind(this)} />; if (!isNewDataCube && !hasChanged) { return <div className="button-group"> {saveButton} </div>; } return <div className="button-group"> {cancelButton} {saveButton} </div>; } getTitle(): string { const { isNewDataCube } = this.props; const { newInstance } = this.state; const lastBit = newInstance.title ? `: ${newInstance.title}` : ''; return (isNewDataCube ? STRINGS.createDataCube : STRINGS.editDataCube) + lastBit; } render() { const { dataCube, isNewDataCube } = this.props; const { tab, newInstance, modal } = this.state; if (!newInstance || !tab || !dataCube) return null; return <div className="data-cube-edit"> <div className="title-bar"> {isNewDataCube ? null : <Button className="button back" type="secondary" svg={require('../../../icons/full-back.svg')} onClick={this.goBack.bind(this)} /> } <div className="title">{this.getTitle()}</div> {this.renderButtons()} </div> <div className="content"> <div className="tabs"> {this.renderTabs(tab)} </div> <div className="tab-content"> {tab.render.bind(this)()} </div> </div> { modal ? modal.render.bind(this)() : null } </div>; } }
the_stack
import { IntentRequest, ui } from 'ask-sdk-model'; import { expect } from 'chai'; import { HandlerInput } from '../../../lib/dispatcher/request/handler/HandlerInput'; import { BaseSkillFactory } from '../../../lib/skill/factory/BaseSkillFactory'; import { MockAlwaysFalseErrorHandler } from '../../mocks/error/MockAlwaysFalseErrorHandler'; import { MockAlwaysTrueErrorHandler } from '../../mocks/error/MockAlwaysTrueErrorHandler'; import { JsonProvider } from '../../mocks/JsonProvider'; import { MockAlwaysFalseRequestHandler } from '../../mocks/request/MockAlwaysFalseRequestHandler'; import { MockAlwaysTrueRequestHandler } from '../../mocks/request/MockAlwaysTrueRequestHandler'; describe('BaseSkillFactory', () => { it('should be able to add single request handler using matcher and executor', async () => { const skill = BaseSkillFactory.init() .addRequestHandler( 'LaunchRequest', ({responseBuilder} : HandlerInput) => responseBuilder.speak('In LaunchRequest').getResponse()) .addRequestHandler( ({requestEnvelope} : HandlerInput) => (<IntentRequest> requestEnvelope.request).intent.name === 'HelloWorldIntent', ({responseBuilder} : HandlerInput) => responseBuilder.speak('In HelloWorldIntent').getResponse()) .create(); const LaunchRequestEnvelope = JsonProvider.requestEnvelope(); LaunchRequestEnvelope.request = { type : 'LaunchRequest', requestId : null, timestamp : null, locale : null, }; const HelloWorldIntent = JsonProvider.intent(); HelloWorldIntent.name = 'HelloWorldIntent'; const HelloWorldIntentEnvelope = JsonProvider.requestEnvelope(); HelloWorldIntentEnvelope.request = { type : 'IntentRequest', requestId : null, timestamp : null, locale : null, dialogState : null, intent : HelloWorldIntent, }; const LaunchRequestResponse = await skill.invoke(LaunchRequestEnvelope); const HelloWorldIntentResponse = await skill.invoke(HelloWorldIntentEnvelope); expect((<ui.SsmlOutputSpeech> LaunchRequestResponse.response.outputSpeech).ssml) .equal('<speak>In LaunchRequest</speak>'); expect((<ui.SsmlOutputSpeech> HelloWorldIntentResponse.response.outputSpeech).ssml) .equal('<speak>In HelloWorldIntent</speak>'); }); it('should thrown an error if request handler matcher is invalid', () => { try { BaseSkillFactory.init() .addRequestHandler(true as any, (input : HandlerInput) => input.responseBuilder.speak('Hello!').getResponse()) .create(); } catch (error) { expect(error.message).equal('Incompatible matcher type: boolean'); return; } throw new Error('should have thrown an error!'); }); it('should be able to add multiple request handlers', async () => { const skill = BaseSkillFactory.init() .addRequestHandlers( new MockAlwaysFalseRequestHandler(), new MockAlwaysTrueRequestHandler(), ) .create(); const requestEnvelope = JsonProvider.requestEnvelope(); const responseEnvelope = await skill.invoke(requestEnvelope); expect((<ui.SsmlOutputSpeech> responseEnvelope.response.outputSpeech).ssml) .equal('<speak>Request received at MockAlwaysTrueRequestHandler.</speak>'); }); it('should be able to add multiple request interceptors with either object or function', async () => { const skill = BaseSkillFactory.init() .addRequestHandler( 'LaunchRequest', (input : HandlerInput) => input.responseBuilder.speak('Hello').getResponse(), ) .addRequestInterceptors( { process : (input) => { const attributes = input.attributesManager.getSessionAttributes(); attributes.firstInterceptor = true; input.attributesManager.setSessionAttributes(attributes); }, }, { process : (input) => { const attributes = input.attributesManager.getSessionAttributes(); attributes.secondInterceptor = true; input.attributesManager.setSessionAttributes(attributes); }, }, (input) => { const attributes = input.attributesManager.getSessionAttributes(); attributes.thirdInterceptor = true; input.attributesManager.setSessionAttributes(attributes); }, (input) => { const attributes = input.attributesManager.getSessionAttributes(); attributes.fourthInterceptor = true; input.attributesManager.setSessionAttributes(attributes); }, ) .create(); const requestEnvelope = JsonProvider.requestEnvelope(); requestEnvelope.request = { type : 'LaunchRequest', requestId : null, timestamp : null, locale : null, }; const responseEnvelope = await skill.invoke(requestEnvelope); expect((<ui.SsmlOutputSpeech> responseEnvelope.response.outputSpeech).ssml) .equal('<speak>Hello</speak>'); expect(responseEnvelope.sessionAttributes).deep.equal({ firstInterceptor : true, secondInterceptor : true, thirdInterceptor : true, fourthInterceptor : true, }); }); it('should thrown an error if request interceptor is invalid', () => { try { BaseSkillFactory.init() .addRequestHandler('LaunchRequest', (input : HandlerInput) => input.responseBuilder.speak('Hello!').getResponse()) .addRequestInterceptors(true as any) .create(); } catch (error) { expect(error.message).equal('Incompatible executor type: boolean'); return; } throw new Error('should have thrown an error!'); }); it('should be able to add multiple response interceptors with either object or function', async () => { const skill = BaseSkillFactory.init() .addRequestHandler('LaunchRequest', (input : HandlerInput) => input.responseBuilder.speak('Hello').getResponse()) .addResponseInterceptors( { process : (input) => { const attributes = input.attributesManager.getSessionAttributes(); attributes.firstInterceptor = true; input.attributesManager.setSessionAttributes(attributes); }, }, { process : (input) => { const attributes = input.attributesManager.getSessionAttributes(); attributes.secondInterceptor = true; input.attributesManager.setSessionAttributes(attributes); }, }, (input) => { const attributes = input.attributesManager.getSessionAttributes(); attributes.thirdInterceptor = true; input.attributesManager.setSessionAttributes(attributes); }, (input) => { const attributes = input.attributesManager.getSessionAttributes(); attributes.fourthInterceptor = true; input.attributesManager.setSessionAttributes(attributes); }, ) .create(); const requestEnvelope = JsonProvider.requestEnvelope(); requestEnvelope.request = { type : 'LaunchRequest', requestId : null, timestamp : null, locale : null, }; const responseEnvelope = await skill.invoke(requestEnvelope); expect((<ui.SsmlOutputSpeech> responseEnvelope.response.outputSpeech).ssml) .equal('<speak>Hello</speak>'); expect(responseEnvelope.sessionAttributes).deep.equal({ firstInterceptor : true, secondInterceptor : true, thirdInterceptor : true, fourthInterceptor : true, }); }); it('should thrown an error if response interceptor is invalid', () => { try { BaseSkillFactory.init() .addRequestHandler('LaunchRequest', (input : HandlerInput) => input.responseBuilder.speak('Hello!').getResponse()) .addResponseInterceptors(true as any) .create(); } catch (error) { expect(error.message).equal('Incompatible executor type: boolean'); return; } throw new Error('should have thrown an error!'); }); it('should be able to add single error handle using matcher and executor', async () => { const skill = BaseSkillFactory.init() .addErrorHandler( (input, error) => error.message === `Unable to find a suitable request handler.`, (input, error) => input.responseBuilder.speak('In ErrorHandler').getResponse(), ) .create(); const responseEnvelope = await skill.invoke(JsonProvider.requestEnvelope()); expect((<ui.SsmlOutputSpeech> responseEnvelope.response.outputSpeech).ssml) .equal('<speak>In ErrorHandler</speak>'); }); it('should be able to add multiple error handlers', async () => { const skill = BaseSkillFactory.init() .addErrorHandlers( new MockAlwaysFalseErrorHandler(), new MockAlwaysTrueErrorHandler(), ) .create(); const requestEnvelope = JsonProvider.requestEnvelope(); const responseEnvelope = await skill.invoke(requestEnvelope); expect((<ui.SsmlOutputSpeech> responseEnvelope.response.outputSpeech).ssml) .equal('<speak>AskSdk.GenericRequestDispatcher Error received at MockAlwaysTrueErrorHandler.</speak>'); }); it('should be able to add skill id and custom user agent', async () => { const config = BaseSkillFactory.init() .withCustomUserAgent('CustomUserAgent') .withSkillId('testSkillId') .getSkillConfiguration(); expect(config.customUserAgent).equal('CustomUserAgent'); expect(config.skillId).equal('testSkillId'); }); it('should be able to create a lambda handler', (done) => { const skillLambda = BaseSkillFactory.init() .addRequestHandler( 'LaunchRequest', ({responseBuilder} : HandlerInput) => responseBuilder.speak('In LaunchRequest').getResponse(), ) .lambda(); const LaunchRequestEnvelope = JsonProvider.requestEnvelope(); LaunchRequestEnvelope.request = { type : 'LaunchRequest', requestId : null, timestamp : null, locale : null, }; skillLambda(LaunchRequestEnvelope, null, (error, responseEnvelope) => { expect((<ui.SsmlOutputSpeech> responseEnvelope.response.outputSpeech).ssml) .equal('<speak>In LaunchRequest</speak>'); }); const wrongRequestEnvelope = JsonProvider.requestEnvelope(); wrongRequestEnvelope.request = { type : 'SessionEndedRequest', requestId : null, timestamp : null, locale : null, reason : null, }; skillLambda(wrongRequestEnvelope, null, (error, responseEnvelope) => { expect(error.message).equal(`Unable to find a suitable request handler.`); done(); }); }); });
the_stack
import { LoggerFactoryMethod } from '@stryker-mutator/api/logging'; import { commonTokens } from '@stryker-mutator/api/plugin'; import { testInjector, assertions, factory, tick } from '@stryker-mutator/test-helpers'; import { expect } from 'chai'; import { TestResults } from 'karma'; import sinon from 'sinon'; // eslint-disable-next-line @typescript-eslint/no-require-imports import { Task } from '@stryker-mutator/util'; import { DryRunOptions, MutantRunOptions, TestStatus } from '@stryker-mutator/api/test-runner'; import { MutantCoverage } from '@stryker-mutator/api/core'; import strykerKarmaConf from '../../src/starters/stryker-karma.conf'; import { KarmaTestRunner } from '../../src/karma-test-runner'; import * as projectStarter from '../../src/starters/project-starter'; import { StrykerKarmaSetup, NgConfigOptions } from '../../src-generated/karma-runner-options'; import { Browser, KarmaSpec, StrykerReporter } from '../../src/karma-plugins/stryker-reporter'; import { TestHooksMiddleware } from '../../src/karma-plugins/test-hooks-middleware'; import { karma } from '../../src/karma-wrapper'; // Unit tests for both the KarmaTestRunner and the StrykerReporter, as they are closely related describe(KarmaTestRunner.name, () => { let projectStarterMock: sinon.SinonStubbedInstance<projectStarter.ProjectStarter>; let setGlobalsStub: sinon.SinonStubbedMember<typeof strykerKarmaConf.setGlobals>; let karmaRunStub: sinon.SinonStubbedMember<typeof karma.runner.run>; let getLogger: LoggerFactoryMethod; let testHooksMiddlewareMock: sinon.SinonStubbedInstance<TestHooksMiddleware>; beforeEach(() => { projectStarterMock = sinon.createStubInstance(projectStarter.ProjectStarter); testHooksMiddlewareMock = sinon.createStubInstance(TestHooksMiddleware); sinon.stub(projectStarter, 'ProjectStarter').returns(projectStarterMock); setGlobalsStub = sinon.stub(strykerKarmaConf, 'setGlobals'); karmaRunStub = sinon.stub(karma.runner, 'run'); sinon.stub(TestHooksMiddleware, 'instance').value(testHooksMiddlewareMock); getLogger = testInjector.injector.resolve(commonTokens.getLogger); }); function createSut() { return testInjector.injector.injectClass(KarmaTestRunner); } it('should load default setup', () => { createSut(); expect(setGlobalsStub).calledWith({ getLogger, karmaConfig: undefined, karmaConfigFile: undefined, disableBail: false, }); }); it('should setup karma from stryker options', () => { const expectedSetup: StrykerKarmaSetup = { config: { basePath: 'foo/bar', }, configFile: 'baz.conf.js', projectType: 'angular-cli', }; testInjector.options.karma = expectedSetup; testInjector.options.disableBail = true; createSut(); expect(setGlobalsStub).calledWith({ getLogger, karmaConfig: expectedSetup.config, karmaConfigFile: expectedSetup.configFile, disableBail: true, }); expect(testInjector.logger.warn).not.called; expect(projectStarter.ProjectStarter).calledWith(sinon.match.func, expectedSetup); }); it('should run ng test with parameters from stryker options', () => { const ngConfig: NgConfigOptions = {}; ngConfig.testArguments = { project: '@ns/mypackage', }; const expectedSetup: StrykerKarmaSetup = { config: { basePath: 'foo/bar', }, configFile: 'baz.conf.js', ngConfig, projectType: 'angular-cli', }; testInjector.options.karma = expectedSetup; testInjector.options.disableBail = true; createSut(); expect(setGlobalsStub).calledWith({ getLogger, karmaConfig: expectedSetup.config, karmaConfigFile: expectedSetup.configFile, disableBail: true, }); expect(testInjector.logger.warn).not.called; expect(projectStarter.ProjectStarter).calledWith(sinon.match.func, expectedSetup); }); describe('init', () => { let sut: KarmaTestRunner; async function actInit() { const initPromise = sut.init(); StrykerReporter.instance.onBrowsersReady(); await initPromise; } beforeEach(async () => { sut = createSut(); StrykerReporter.instance.karmaConfig = await karma.config.parseConfig(null, {}, { promiseConfig: true }); }); it('should start karma', async () => { projectStarterMock.start.resolves({ exitPromise: new Task<number>().promise }); await actInit(); expect(projectStarterMock.start).called; }); it('should reject when karma start rejects', async () => { const expected = new Error('karma unavailable'); projectStarterMock.start.rejects(expected); await expect(sut.init()).rejectedWith(expected); }); it('should reject on browser errors', async () => { projectStarterMock.start.resolves({ exitPromise: new Task<number>().promise }); const expected = new Error('karma unavailable'); const onGoingInit = sut.init(); StrykerReporter.instance.onBrowserError(createBrowser(), expected); await expect(onGoingInit).rejectedWith(expected); }); it('should reject when karma exists during init', async () => { const exitTask = new Task<number>(); projectStarterMock.start.resolves({ exitPromise: exitTask.promise }); const onGoingInit = sut.init(); exitTask.resolve(1); await expect(onGoingInit).rejectedWith( "Karma exited prematurely with exit code 1. Please run stryker with `--logLevel trace` to see the karma logging and figure out what's wrong." ); }); }); describe('dryRun', () => { let sut: KarmaTestRunner; beforeEach(() => { sut = createSut(); karmaRunStub.callsArgOnWith(1, null, 0); }); function actDryRun({ specResults = [], runResults = createKarmaTestResults(), options = factory.dryRunOptions(), mutantCoverage = factory.mutantCoverage(), browserError = undefined, }: { specResults?: KarmaSpec[]; runResults?: TestResults; options?: DryRunOptions; mutantCoverage?: MutantCoverage; browserError?: [browser: Browser, error: any] | undefined; }) { const dryRunPromise = sut.dryRun(options); actRun({ browserError, specResults, mutantCoverage, hitCount: undefined, runResults }); return dryRunPromise; } it('should report completed specs as test results', async () => { const specResults = [ createKarmaSpec({ id: 'spec1', suite: ['foo'], description: 'should bar', time: 42, success: true }), createKarmaSpec({ id: 'spec2', suite: ['bar', 'when baz'], description: 'should qux', log: ['expected quux to be qux', 'expected length of 1'], time: 44, success: false, }), createKarmaSpec({ id: 'spec3', suite: ['quux'], description: 'should corge', time: 45, skipped: true }), ]; const expectedTests = [ factory.testResult({ id: 'spec1', status: TestStatus.Success, timeSpentMs: 42, name: 'foo should bar' }), factory.testResult({ id: 'spec2', status: TestStatus.Failed, timeSpentMs: 44, name: 'bar when baz should qux', failureMessage: 'expected quux to be qux, expected length of 1', }), factory.testResult({ id: 'spec3', status: TestStatus.Skipped, timeSpentMs: 45, name: 'quux should corge' }), ]; const actualResult = await actDryRun({ specResults }); assertions.expectCompleted(actualResult); expect(actualResult.tests).deep.eq(expectedTests); }); it('should run karma with custom karma configuration', async () => { // Arrange projectStarterMock.start.resolves({ exitPromise: new Task<number>().promise }); StrykerReporter.instance.karmaConfig = await karma.config.parseConfig(null, {}, { promiseConfig: true }); StrykerReporter.instance.karmaConfig.hostname = 'www.localhost.com'; StrykerReporter.instance.karmaConfig.port = 1337; StrykerReporter.instance.karmaConfig.listenAddress = 'www.localhost.com:1337'; const parseConfigStub = sinon.stub(karma.config, 'parseConfig'); const expectedRunConfig = { custom: 'config' }; parseConfigStub.resolves(expectedRunConfig); const initPromise = sut.init(); StrykerReporter.instance.onBrowsersReady(); await initPromise; // Act await actDryRun({}); // Assert expect(karmaRunStub).calledWith(expectedRunConfig, sinon.match.func); expect(parseConfigStub).calledWithExactly(null, { hostname: 'www.localhost.com', port: 1337, listenAddress: 'www.localhost.com:1337' }); }); it('should log when karma run is done', async () => { await actDryRun({}); expect(testInjector.logger.debug).calledWith('karma run done with ', 0); }); it('should clear run results between runs', async () => { const firstTestResult = createKarmaSpec({ id: 'spec1', suite: ['foo'], description: 'should bar', time: 42, success: true }); const expectedTestResult = factory.testResult({ id: 'spec1', status: TestStatus.Success, timeSpentMs: 42, name: 'foo should bar' }); const actualFirstResult = await actDryRun({ specResults: [firstTestResult] }); const actualSecondResult = await actDryRun({}); assertions.expectCompleted(actualFirstResult); assertions.expectCompleted(actualSecondResult); expect(actualFirstResult.tests).deep.eq([expectedTestResult]); expect(actualSecondResult.tests).lengthOf(0); }); it('should configure the coverage analysis in the test hooks middleware', async () => { await actDryRun({ options: factory.dryRunOptions({ coverageAnalysis: 'all' }) }); expect(testHooksMiddlewareMock.configureCoverageAnalysis).calledWithExactly('all'); }); it('should add coverage report when the reporter raises the "coverage_report" event', async () => { const expectedCoverageReport = factory.mutantCoverage({ static: { '1': 4 } }); const actualResult = await actDryRun({ mutantCoverage: expectedCoverageReport }); assertions.expectCompleted(actualResult); expect(actualResult.mutantCoverage).eq(expectedCoverageReport); }); it('should add error when the reporter raises the "browser_error" event', async () => { const expectedError = 'Global variable undefined'; const actualResult = await actDryRun({ runResults: createKarmaTestResults({ error: true }), browserError: [createBrowser(), expectedError] }); assertions.expectErrored(actualResult); expect(actualResult.errorMessage).deep.eq(expectedError); }); it('should report state Error when tests where ran and run completed in an error', async () => { const actualResult = await actDryRun({ runResults: createKarmaTestResults({ error: true }), specResults: [createKarmaSpec()], browserError: [createBrowser(), 'some error'], }); assertions.expectErrored(actualResult); }); }); describe('mutantRun', () => { let sut: KarmaTestRunner; function actMutantRun({ specResults = [], runResults = createKarmaTestResults(), options = factory.mutantRunOptions(), mutantCoverage = factory.mutantCoverage(), hitCount = undefined, browserError = undefined, }: { specResults?: KarmaSpec[]; runResults?: TestResults; options?: MutantRunOptions; hitCount?: number; mutantCoverage?: MutantCoverage; browserError?: [browser: Browser, error: any] | undefined; }) { const promise = sut.mutantRun(options); actRun({ specResults, runResults, mutantCoverage, hitCount, browserError }); return promise; } beforeEach(() => { sut = createSut(); karmaRunStub.callsArgOn(1, 0); }); it('should configure the mutant run on the middleware', async () => { const options = factory.mutantRunOptions({ testFilter: ['foobar'] }); await actMutantRun({ options }); expect(testHooksMiddlewareMock.configureMutantRun).calledOnceWithExactly(options); }); it('should correctly report a survived mutant', async () => { const result = await actMutantRun({ specResults: [createKarmaSpec({ success: true })] }); assertions.expectSurvived(result); expect(result.nrOfTests).eq(1); }); it('should correctly report a killed mutant', async () => { const result = await actMutantRun({ specResults: [createKarmaSpec({ success: true }), createKarmaSpec({ success: false })] }); assertions.expectKilled(result); expect(result.nrOfTests).eq(2); }); it('should report a timeout when the browser disconnects', async () => { arrangeLauncherMock(); const onGoingRun = sut.mutantRun(factory.mutantRunOptions()); StrykerReporter.instance.onRunStart(); StrykerReporter.instance.onBrowserError(createBrowser({ id: '42', state: 'DISCONNECTED' }), 'disconnected'); StrykerReporter.instance.onRunComplete(null, createKarmaTestResults({ disconnected: true })); StrykerReporter.instance.onBrowsersReady(); const result = await onGoingRun; assertions.expectTimeout(result); expect(result.reason).eq('Browser disconnected during test execution. Karma error: disconnected'); }); it('should restart the browser and wait until it is restarted when it gets disconnected (issue #2989)', async () => { // Arrange const { launcher, karmaServer } = arrangeLauncherMock(); // Act let runCompleted = false; const onGoingRun = sut.mutantRun(factory.mutantRunOptions()).then(() => (runCompleted = true)); StrykerReporter.instance.onRunStart(); StrykerReporter.instance.onBrowserError(createBrowser({ id: '42', state: 'DISCONNECTED' }), 'disconnected'); // Assert expect(launcher.restart).calledWith('42'); expect(karmaServer.get).calledWith('launcher'); StrykerReporter.instance.onRunComplete(null, createKarmaTestResults({ disconnected: true })); await tick(); expect(runCompleted).false; StrykerReporter.instance.onBrowsersReady(); await onGoingRun; }); it('should report a timeout when the hitLimit was reached', async () => { const result = await actMutantRun({ options: factory.mutantRunOptions({ hitLimit: 9 }), specResults: [createKarmaSpec({ success: false })], hitCount: 10, }); assertions.expectTimeout(result); expect(result.reason).contains('Hit limit reached (10/9)'); }); it('should reset the hitLimit between runs', async () => { const firstResult = await actMutantRun({ options: factory.mutantRunOptions({ hitLimit: 9 }), specResults: [createKarmaSpec({ success: false })], hitCount: 10, }); const secondResult = await actMutantRun({ options: factory.mutantRunOptions({ hitLimit: undefined }), specResults: [createKarmaSpec({ success: false })], hitCount: 10, }); assertions.expectTimeout(firstResult); assertions.expectKilled(secondResult); }); }); describe('dispose', () => { beforeEach(async () => { StrykerReporter.instance.karmaConfig = await karma.config.parseConfig(null, {}, { promiseConfig: true }); }); it('should not do anything if there is no karma server', async () => { const sut = createSut(); await expect(sut.dispose()).not.rejected; }); it('should stop the karma server', async () => { const karmaServerMock = sinon.createStubInstance(karma.Server); StrykerReporter.instance.karmaServer = karmaServerMock; const sut = createSut(); await sut.dispose(); expect(karmaServerMock.stop).called; }); it('should await the exit promise provided at startup', async () => { // Arrange const sut = createSut(); const karmaServerMock = sinon.createStubInstance(karma.Server); StrykerReporter.instance.karmaServer = karmaServerMock; const exitTask = new Task<number>(); let disposeResolved = false; projectStarterMock.start.resolves({ exitPromise: exitTask.promise }); const initPromise = sut.init(); StrykerReporter.instance.onBrowsersReady(); await initPromise; // Act const onGoingDisposal = sut.dispose().then(() => (disposeResolved = true)); // Assert await tick(); expect(disposeResolved).false; exitTask.resolve(1); await onGoingDisposal; }); }); function actRun({ specResults, runResults, mutantCoverage, hitCount, browserError, }: { specResults: KarmaSpec[]; runResults: TestResults; mutantCoverage: MutantCoverage; hitCount: number | undefined; browserError: [browser: Browser, error: any] | undefined; }) { StrykerReporter.instance.onRunStart(); specResults.forEach((spec) => StrykerReporter.instance.onSpecComplete(null, spec)); if (browserError) { StrykerReporter.instance.onBrowserError(...browserError); } StrykerReporter.instance.onBrowserComplete(null, { mutantCoverage, hitCount }); StrykerReporter.instance.onRunComplete(null, runResults); } }); function arrangeLauncherMock() { const karmaServerMock = sinon.createStubInstance(karma.Server); const launcherMock = sinon.createStubInstance(karma.launcher.Launcher); StrykerReporter.instance.karmaServer = karmaServerMock; karmaServerMock.get.returns(launcherMock); return { launcher: launcherMock, karmaServer: karmaServerMock }; } function createKarmaSpec(overrides?: Partial<KarmaSpec>): KarmaSpec { return { description: 'baz', id: '1', log: [], skipped: false, success: true, suite: ['foo', 'bar'], time: 42, ...overrides, }; } function createKarmaTestResults(overrides?: Partial<TestResults>): TestResults { return { disconnected: false, error: false, exitCode: 0, failed: 0, success: 0, ...overrides, }; } function createBrowser(overrides?: Partial<Browser>): Browser { return { id: '123123', state: 'CONNECTED', ...overrides, }; }
the_stack
import * as _ from 'lodash' import {isUndefined,isNullOrUndefined} from 'util'; import {ActivatedRoute} from '@angular/router'; import {Component, ElementRef, Injector, OnDestroy, OnInit, ViewChild} from '@angular/core'; import {Modal} from '@common/domain/modal'; import {Alert} from '@common/util/alert.util'; import {MomentDatePipe} from '@common/pipe/moment.date.pipe'; import {AbstractComponent} from '@common/component/abstract.component'; import {DeleteModalComponent} from '@common/component/modal/delete/delete.component'; import {PrDataSnapshot, SsType, Status} from '@domain/data-preparation/pr-snapshot'; import {StorageService} from '../../data-storage/service/storage.service'; import {PreparationCommonUtil} from '../util/preparation-common.util'; import {PreparationAlert} from '../util/preparation-alert.util'; import {DataSnapshotService} from './service/data-snapshot.service'; import {DataSnapshotDetailComponent} from './data-snapshot-detail.component'; @Component({ selector: 'app-data-snapshot', templateUrl: './data-snapshot.component.html', providers: [MomentDatePipe] }) export class DataSnapshotComponent extends AbstractComponent implements OnInit, OnDestroy { /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ @ViewChild(DataSnapshotDetailComponent) private ssDetailComponent : DataSnapshotDetailComponent; // 검색 파라메터 private _searchParams: { [key: string]: string }; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ @ViewChild(DeleteModalComponent) public deleteModalComponent: DeleteModalComponent; public datasnapshots: PrDataSnapshot[]; // 지울 데이터스냅샷 아이디 public selectedDeletessId: string; public ssStatus: string; public searchText: string; public step: string; // 상세 조회 할 데이터스냅샷 아이디 public ssId: string; public ssType : SsType; public selectedContentSort: Order = new Order(); public interval : any; public prepCommonUtil = PreparationCommonUtil; public snapshotTypes: SnapshotType[]; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Constructor |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ constructor(private dataSnapshotService: DataSnapshotService, private _activatedRoute: ActivatedRoute, protected elementRef: ElementRef, protected injector: Injector) { super(elementRef, injector); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ public ngOnInit() { // Init super.ngOnInit(); this._initView(); this.subscriptions.push( // Get query param from url this._activatedRoute.queryParams.subscribe((params) => { if (!_.isEmpty(params)) { if (!isNullOrUndefined(params['size'])) { this.page.size = params['size']; } if (!isNullOrUndefined(params['page'])) { this.page.page = params['page']; } if (!isNullOrUndefined(params['ssName'])) { this.searchText = params['ssName']; } if (!isNullOrUndefined(params['status'])) { this.ssStatus = params['status']; } if (!isNullOrUndefined(params['type'])) { this.ssType = params['type']; } const sort = params['sort']; if (!isNullOrUndefined(sort)) { const sortInfo = decodeURIComponent(sort).split(','); this.selectedContentSort.key = sortInfo[0]; this.selectedContentSort.sort = sortInfo[1]; } } this.getSnapshots(); }) ); } public ngOnDestroy() { super.ngOnDestroy(); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * Get elapsed day * @param item */ public getElapsedDay(item?) { if (isUndefined(item) || isUndefined(item.elapsedTime) ) { return 0; } return item.elapsedTime.days; } /** * Returns formatted elapsed time * hour:minute:second.millisecond * @param item */ public getElapsedTime(item: PrDataSnapshot) { if (isUndefined(item) || isUndefined(item.elapsedTime) || isUndefined(item.elapsedTime.hours) || isUndefined(item.elapsedTime.minutes) || isUndefined(item.elapsedTime.seconds) || isUndefined(item.elapsedTime.milliseconds) ) { return '--:--:--'; } return `${this.prepCommonUtil.padLeft(item.elapsedTime.hours)}:${this.prepCommonUtil.padLeft(item.elapsedTime.minutes)}:${this.prepCommonUtil.padLeft(item.elapsedTime.seconds)}.${this.prepCommonUtil.padLeft(item.elapsedTime.milliseconds)}`; } /** * Fetch snapshot list */ public getSnapshots() { this.loadingShow(); const params = this._getSsParams(); this.datasnapshots = []; this.dataSnapshotService.getSnapshots(params).then((data) => { this._searchParams = params; this.pageResult = data['page']; this.datasnapshots = data['_embedded'] ? this.datasnapshots.concat(data['_embedded'].preparationsnapshots) : []; const preparing = [Status.INITIALIZING,Status.RUNNING,Status.WRITING,Status.TABLE_CREATING,Status.CANCELING]; this.datasnapshots.forEach((obj : PrDataSnapshot) => { if ( [Status.SUCCEEDED].indexOf(obj.status) >= 0){ obj.displayStatus = 'SUCCESS'; } else if (preparing.indexOf(obj.status) >= 0) { obj.displayStatus = 'PREPARING'; } else { obj.displayStatus = 'FAIL'; } }); this.loadingHide(); }).catch((error) => { this.loadingHide(); const prepError = this.dataprepExceptionHandler(error); PreparationAlert.output(prepError, this.translateService.instant(prepError.message)); }); } /** * 검색 input 에서 keydown event * @param event */ public onSearchInputKeyPress(event : any) { // ESC or ENTER if (27 === event.keyCode || 13 === event.keyCode) { event.keyCode === 27 ? this.searchText = '' : null; this.page.page = 0; this.reloadPage(); } } /** 데이터스냅샷 삭제 * @param event 이벤트 * @param dataset 선택한 데이터셋 */ public confirmDelete(event, dataset) { // stop event bubbling event.stopPropagation(); // delete modal const modal = new Modal(); modal.name = this.translateService.instant('msg.dp.alert.ss.del.title'); modal.description = dataset.finishTime ? this.translateService.instant('msg.dp.alert.ss.del.description') : 'Snapshot is preparing. Are you sure you want to stop this process and delete it?'; modal.btnName = this.translateService.instant('msg.comm.ui.confirm'); this.selectedDeletessId = dataset.ssId; this.deleteModalComponent.init(modal); } /** * Delete snapshot */ public deleteDataSnapshot() { this.dataSnapshotService.deleteDataSnapshot(this.selectedDeletessId).then(() => { Alert.success(this.translateService.instant('msg.dp.alert.del.success')); if (this.page.page > 0 && this.datasnapshots.length === 1) { this.page.page = this.page.page - 1; } this.reloadPage(false); }).catch(() => { Alert.error(this.translateService.instant('msg.dp.alert.del.fail')); }); } /** * Open snapshot detail * @param item */ public snapshotDetail(item) { this.safelyDetectChanges(); this.ssDetailComponent.init(item.ssId); } /** * Sorting * @param key */ public changeOrder(key: string) { // 초기화 this.selectedContentSort.sort = this.selectedContentSort.key !== key ? 'default' : this.selectedContentSort.sort; // 정렬 정보 저장 this.selectedContentSort.key = key; if (this.selectedContentSort.key === key) { // asc, desc switch (this.selectedContentSort.sort) { case 'asc': this.selectedContentSort.sort = 'desc'; break; case 'desc': this.selectedContentSort.sort = 'asc'; break; case 'default': this.selectedContentSort.sort = 'desc'; break; } } this.reloadPage(); } /** * Close snapshot detail */ public closeDetail(){ this.step = 'close-detail'; this.reloadPage(false); } /** * When status is changed * @param status */ public onChangeStatus(status: string) { this.ssStatus = status; this.reloadPage(); } /** * When snapshot type is changed * @param data */ public onChangeType(data: SnapshotType) { this.ssType = data.value; this.reloadPage(); } /** * 페이지 변경 * @param data */ public changePage(data: { page: number, size: number }) { if (data) { this.page.page = data.page; this.page.size = data.size; this.reloadPage(false); } } // function - changePage /** * Returns name for svg component * @param snapshot */ public getSvgName(snapshot: PrDataSnapshot) { const csv : string = 'CSV'; if (snapshot.ssType === SsType.STAGING_DB) { return 'HIVE' } if (snapshot.storedUri.endsWith('.json')) { return 'JSON'; } return csv; } /** * 페이지를 새로 불러온다. * @param {boolean} isFirstPage */ public reloadPage(isFirstPage: boolean = true) { (isFirstPage) && (this.page.page = 0); this._searchParams = this._getSsParams(); this.router.navigate( [this.router.url.replace(/\?.*/gi, '')], {queryParams: this._searchParams, replaceUrl: true} ).then(); } // function - reloadPage /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * Initialise values * @private */ private _initView() { this.snapshotTypes = [ {label:'All', value : null}, {label: 'FILE', value : SsType.URI}, // {label: 'Database', value : SsType.DATABASE}, // {label: 'DRUID', value : SsType.DRUID} ]; this.ssStatus = 'all'; this.searchText = ''; this.selectedContentSort.sort = 'desc'; this.selectedContentSort.key = 'createdTime'; // Add staging db option in snapshot type filter is staging is enabled if (StorageService.isEnableStageDB) { this.snapshotTypes.push({label: 'Staging DB', value : SsType.STAGING_DB}); } } /** * Returns parameter for fetching snapshot list * @private */ private _getSsParams(): any { const params = { page: this.page.page, size: this.page.size, status : this.ssStatus, type: this.ssType, projection:'listing', ssName: this.searchText, pseudoParam : (new Date()).getTime() }; this.selectedContentSort.sort !== 'default' && (params['sort'] = this.selectedContentSort.key + ',' + this.selectedContentSort.sort); return params; } } class Order { key: string = 'createdTime'; sort: string = 'default'; } class SnapshotType { public label: string; public value: SsType; }
the_stack
export const sevenzip = "https://user-images.githubusercontent.com/43678736/132086517-72a51a12-e403-4675-bfd7-22c23affa730.png"; export const aac = "https://user-images.githubusercontent.com/43678736/132086518-7026d4f1-ea16-4ed0-89fd-37c1aa8ac3ed.png"; export const abw = "https://user-images.githubusercontent.com/43678736/132086519-863c63b4-917e-4471-94ff-7e15651cc14b.png"; export const accdb = "https://user-images.githubusercontent.com/43678736/132086520-9bc6aa3b-51c9-4da2-9ef7-349162b86d0b.png"; export const avi = "https://user-images.githubusercontent.com/43678736/132086521-dbd6cf0d-d4d7-4b92-bb26-17e8a51a9383.png"; export const azw = "https://user-images.githubusercontent.com/43678736/132086522-070f48e8-78a8-4294-8dbb-aab81525e164.png"; export const bmp = "https://user-images.githubusercontent.com/43678736/132086595-90ab7f90-f87e-4900-94d9-d0b26745df48.png"; export const bz = "https://user-images.githubusercontent.com/43678736/132086597-e285ad5c-613a-4679-a270-493e5be4ffd9.png"; export const bz2 = "https://user-images.githubusercontent.com/43678736/132086598-623c410a-084a-4395-a448-211b2ff61cfe.png"; export const c = "https://user-images.githubusercontent.com/43678736/132086599-7a5cd692-b4df-45f5-80d9-384cb3e0c314.png"; export const cda = "https://user-images.githubusercontent.com/43678736/132086600-8b70a007-512d-4252-9c66-eabd3ddd6573.png"; export const csh = "https://user-images.githubusercontent.com/43678736/132086601-e62e5d1a-d8a2-4475-a14f-85922cec9272.png"; export const css = "https://user-images.githubusercontent.com/43678736/132086602-4c772934-f608-4f01-8459-c4622cee8ad5.png"; export const csv = "https://user-images.githubusercontent.com/43678736/132086604-b5b019fe-572e-477e-92c2-3769a48a1304.png"; //export const default = "https://user-images.githubusercontent.com/43678736/132086605-d03db898-045c-477e-bae6-156699833eb0.png"; export const docx = "https://user-images.githubusercontent.com/43678736/132086606-715ccb66-4702-4f7d-9b09-ac93ba17b643.png"; export const docx2 = "https://user-images.githubusercontent.com/43678736/132086607-a246b386-52c9-4fe1-a7e4-204894e6722d.png"; export const drawio = "https://user-images.githubusercontent.com/43678736/132086608-bcae9d57-8e54-488c-90c4-4952ae530b5e.png"; export const dw = "https://user-images.githubusercontent.com/43678736/132086616-0c7842d6-d20e-4ede-988b-3dd063a4de8d.png"; export const eml = "https://user-images.githubusercontent.com/43678736/132086617-1e351075-ffaf-4b81-a1fe-0b7b338772a2.png"; export const eot = "https://user-images.githubusercontent.com/43678736/132086618-397d6bd2-9fda-43ed-a135-cb40388c35af.png"; export const eps = "https://user-images.githubusercontent.com/43678736/132086619-9daf0b61-dbb0-4d47-8a12-9fba13b88856.png"; export const epub = "https://user-images.githubusercontent.com/43678736/132086620-2586ba40-c583-4589-b1a4-8bb5b258b44d.png"; export const freearc = "https://user-images.githubusercontent.com/43678736/132086621-3b95fb64-2533-4ccc-abcd-bd2beba572e9.png"; export const gif = "https://user-images.githubusercontent.com/43678736/132086622-af705a0c-2b25-4ba7-8ab6-bd69ec97f7e2.png"; export const gzip = "https://user-images.githubusercontent.com/43678736/132086624-89141a46-64e4-4fa0-bf69-54a0eb4d48c9.png"; export const html = "https://user-images.githubusercontent.com/43678736/132086625-1b8f2652-1de0-4475-8c12-7da4a9973ffb.png"; export const icalendar = "https://user-images.githubusercontent.com/43678736/132086626-38699705-1e6f-4bca-984b-03167b236faa.png"; export const ind = "https://user-images.githubusercontent.com/43678736/132086627-2f24067a-00bc-424a-af36-349a9ba14b6c.png"; export const ini = "https://user-images.githubusercontent.com/43678736/132086649-20c9c9e6-8e63-4d87-9b8e-8fe8eba12ada.png"; export const java = "https://user-images.githubusercontent.com/43678736/132086650-f1166246-b361-4c30-a04e-9781c555d14a.png"; export const jar = "https://user-images.githubusercontent.com/43678736/132086650-f1166246-b361-4c30-a04e-9781c555d14a.png"; export const javascript = "https://user-images.githubusercontent.com/43678736/132086652-4562942e-aaea-466c-968f-380fffabf3f9.png"; export const jpeg = "https://user-images.githubusercontent.com/43678736/132086653-0487e7e2-1ee3-49e2-8cfe-3e20f1f7490a.png"; export const jsf = "https://user-images.githubusercontent.com/43678736/132086654-c510bd8f-8de7-4afe-8c20-cc810b004b07.png"; export const json = "https://user-images.githubusercontent.com/43678736/132086656-6e96c815-e4e2-4ffd-9d71-57e9cc2450bc.png"; export const jsonld = "https://user-images.githubusercontent.com/43678736/132086658-5d27d3c2-394f-43fb-b512-9b414a257875.png"; export const midi = "https://user-images.githubusercontent.com/43678736/132086659-98f3ef6e-b9f3-4b6d-b18f-469b5334ba27.png"; export const mov = "https://user-images.githubusercontent.com/43678736/132086660-adcecedd-56b4-4286-8b0f-69417f77e961.png"; export const mp3 = "https://user-images.githubusercontent.com/43678736/132086661-a5484553-06c7-4ffa-a8f9-96b57b1b0344.png"; export const mp4 = "https://user-images.githubusercontent.com/43678736/132086662-05ad1597-d5e5-4efa-833e-2876e966a745.png"; export const mpeg = "https://user-images.githubusercontent.com/43678736/132086663-90c58955-f7fb-4bdb-ac53-92667d16d4a3.png"; export const mpkg = "https://user-images.githubusercontent.com/43678736/132086664-9a7530e7-6d78-4ef3-a176-20cf7f57b555.png"; export const octet = "https://user-images.githubusercontent.com/43678736/132086666-ab3c505d-b2c0-4177-9a06-aed5d9c39ee4.png"; export const odp = "https://user-images.githubusercontent.com/43678736/132086667-6c7dcbcc-8d83-41a2-8e0a-85b09e2791ae.png"; export const ods = "https://user-images.githubusercontent.com/43678736/132086668-9f246e91-cf2e-49cf-9617-e1fbb71abbbb.png"; export const odt = "https://user-images.githubusercontent.com/43678736/132086669-46113762-84d1-4b32-9441-b0138ce17a5d.png"; //ogg type export const oga = "https://user-images.githubusercontent.com/43678736/145835364-2054509d-3448-4d34-921f-73dd6e297fc7.png"; export const ogv = "https://user-images.githubusercontent.com/43678736/145835367-19172bf8-cd5a-4cbe-b512-d0de1d91f269.png"; export const ogx = "https://user-images.githubusercontent.com/43678736/145835373-a57ef0f5-3968-483b-9f55-6d67e7f1dcea.png"; export const opus = "https://user-images.githubusercontent.com/43678736/132086670-0f96e770-cedc-4635-a5f9-cf97894c1d7a.png"; export const otf = "https://user-images.githubusercontent.com/43678736/132086671-02ad35ef-ec3a-4a65-abd5-5bf794dfcf7b.png"; export const pdf = "https://user-images.githubusercontent.com/43678736/132086672-3a856fda-823d-4997-b802-c7c640e6ef44.png"; export const php = "https://user-images.githubusercontent.com/43678736/132086673-0c4409ab-754e-4619-8cfa-179d0ccf1bd9.png"; export const png = "https://user-images.githubusercontent.com/43678736/132086674-fdb56d02-5845-49b7-8462-6357bc963464.png"; export const pptx = "https://user-images.githubusercontent.com/43678736/132086675-c879645d-acb4-41a6-ab3c-4e6c2048badb.png"; export const pptx2 = "https://user-images.githubusercontent.com/43678736/132086676-6de1bbd7-764f-4197-9aa4-405a60ce6734.png"; export const proj = "https://user-images.githubusercontent.com/43678736/132086683-3dc0a8b8-72f8-4fa1-a08a-fcfd75b465e1.png"; export const psd = "https://user-images.githubusercontent.com/43678736/132086685-4e327c4c-a409-4b83-b36a-8d88936b314b.png"; export const pst = "https://user-images.githubusercontent.com/43678736/132086686-3888e43a-5abf-41f7-9940-4b86e436521f.png"; export const publisher = "https://user-images.githubusercontent.com/43678736/132086687-d92b56ff-f7f7-4be7-bbf4-47b8a33f4c6f.png"; export const python = "https://user-images.githubusercontent.com/43678736/132086688-8e82fae4-3a9b-49c0-bf99-77189525514c.png"; export const tar = "https://user-images.githubusercontent.com/43678736/132086689-fe1fef9f-d2db-455b-8f4b-09acd095f571.png"; export const rar = "https://user-images.githubusercontent.com/43678736/132086689-fe1fef9f-d2db-455b-8f4b-09acd095f571.png"; export const react = "https://user-images.githubusercontent.com/43678736/132086691-d472576b-ec6a-4332-acd2-dd6a00b72952.png"; export const richtextformat = "https://user-images.githubusercontent.com/43678736/132086692-df6e3518-2e6a-4553-883d-e21694980449.png"; export const rtf = "https://user-images.githubusercontent.com/43678736/132086693-9d43571e-0c86-438f-b247-e2cb42e19e06.png"; export const sass = "https://user-images.githubusercontent.com/43678736/132086694-4e661d6a-1118-441e-8bc3-c52fcb2133b6.png"; export const settings = "https://user-images.githubusercontent.com/43678736/132086696-0dd21f83-b9fc-490c-9ed5-bd88151dc9bb.png"; export const sh = "https://user-images.githubusercontent.com/43678736/132086697-1d82d724-35b6-4f06-847a-3c59a5deda6e.png"; export const swf = "https://user-images.githubusercontent.com/43678736/132086698-19384230-dbd7-4e05-bc69-ef4537b6aae3.png"; export const text = "https://user-images.githubusercontent.com/43678736/132086699-5993a482-04f4-4915-b105-9037f527cf61.png"; export const tiff = "https://user-images.githubusercontent.com/43678736/132086700-c23461c8-6819-46e1-aecd-0a1f8d3507bb.png"; export const ttf = "https://user-images.githubusercontent.com/43678736/132086701-c8044c09-8d95-4af1-9410-66761001d7da.png"; export const typescript = "https://user-images.githubusercontent.com/43678736/132086702-59294337-ed99-4302-badd-316b2c1ff62f.png"; export const url = "https://user-images.githubusercontent.com/43678736/132086703-86d97476-b76e-4949-b89a-31ecb03f3b6e.png"; export const vsd = "https://user-images.githubusercontent.com/43678736/132086704-8fd51e7c-afa2-47a3-ab2f-d0bcd0ecae9f.png"; export const vue = "https://user-images.githubusercontent.com/43678736/132086705-33294da1-5c0f-49f7-b890-e4857cec0a6d.png"; export const wav = "https://user-images.githubusercontent.com/43678736/132086706-22f805d0-39d4-494b-824e-47dc75d05eb7.png"; export const webm = "https://user-images.githubusercontent.com/43678736/132086707-e61a84de-d396-4dbf-8d1b-1d6ee19e1ac8.png"; export const weba = "https://user-images.githubusercontent.com/43678736/132086707-e61a84de-d396-4dbf-8d1b-1d6ee19e1ac8.png"; export const webp = "https://user-images.githubusercontent.com/43678736/132086708-21d096dd-7148-40aa-97f1-cbb099339740.png"; export const wma = "https://user-images.githubusercontent.com/43678736/132086709-811d4e90-3cfa-4044-a956-aeda9c67fc92.png"; export const wmv = "https://user-images.githubusercontent.com/43678736/132086710-c5479c6c-0249-4542-adad-48b0ef40b775.png"; export const woff = "https://user-images.githubusercontent.com/43678736/132086711-1524a3e7-3e33-4822-a34f-ff3235404045.png"; export const xlsx = "https://user-images.githubusercontent.com/43678736/132086712-17e2c491-f6e4-4586-aef6-06bcc5f4b0e5.png"; export const xlsx2 = "https://user-images.githubusercontent.com/43678736/132086714-7ddf285d-2b83-4115-80a5-f02f510300a1.png"; export const xml = "https://user-images.githubusercontent.com/43678736/132086715-204b5a8b-9c5a-4bac-8294-9237ebc16089.png"; export const xul = "https://user-images.githubusercontent.com/43678736/132086716-64511d20-58cb-45a8-85df-f4d9408b469d.png"; export const zip = "https://user-images.githubusercontent.com/43678736/132086718-a8499333-6282-4820-aa1f-4d133eb54648.png"; //export { aac, abw, accdb, avi, azw, bmp, bz, bz2, cda, csh, css, csv, docx, drawio, eot, epub, freearc, gif, gzip, html, icalendar, jar, java, javascript, jpeg, json, jsonld, midi, mp3, mp4, mpeg, mpkg, octet, odp, ods, odt, opus, otf, pdf, php, png, pptx, psd, python, rar, react, rtf,sass, sevenzip, sh, swf, tar, text, tiff, ttf, typescript, vsd, vue, wav, weba, webm, webp, wma, wmv, woff, xlsx, xml, xul, zip };
the_stack
import {Buffer} from 'buffer'; import $ from 'jquery'; import 'bootstrap'; import skBootstrap from 'bootstrap/dist/css/bootstrap.min.css'; import { name as packageName, productName as packageProductName, author as packageAuthor, year as packageYear, version as packageVersion, } from '../package.json'; import skStyles from './style.css'; import skFormats from './formats'; import sak32009 from './sak32009.svg'; $(() => { class Sak32009 { public formats: Record<string, any> = skFormats; public data: Record<string, any> = { appId: '', name: '', dlcs: {}, dlcsUnknowns: {}, countDlcs: 0, countDlcsUnknowns: 0, countAll: 0, withDlcsUnknowns: false, }; public urls = { steamdbApp: 'https://steamdb.info/app/', steamdbDepot: 'https://steamdb.info/depot/', steamPowered: 'https://store.steampowered.com/app/', epicGames: 'https://www.epicgames.com/store/', }; public is = { steamdbApp: false, steamdbDepot: false, steamPowered: false, epicGames: false, }; public titleScript = `${packageProductName} v${packageVersion}<br><small>by ${packageAuthor.name} | ${packageYear}</small>`; public constructor() { const href = window.location.href; if (href.startsWith(this.urls.steamdbApp)) { this.is.steamdbApp = true; this.steamDbApp(); } else if (href.startsWith(this.urls.steamdbDepot)) { this.is.steamdbDepot = true; this.steamDbDepot(); } else if (href.startsWith(this.urls.steamPowered)) { this.is.steamPowered = true; this.steamPowered(); } else if (/https:\/\/www.epicgames.com\/store\/(.+)\/p\/(.+)/gm.test(href)) { this.is.epicGames = true; this.epicGames(); } } public steamDbApp() { this.data.appId = $('div[data-appid]').data('appid'); this.data.name = $('h1[itemprop="name"]').text().trim(); $('#dlc.tab-pane tr.app[data-appid]').each((_index, element) => { const $dom = $(element); const appId = $dom.attr('data-appid'); const appName = $dom.find('td:nth-of-type(2)').text().trim(); if (typeof appId !== 'undefined' && typeof appName !== 'undefined') { if ($dom.find('td:nth-of-type(2)').hasClass('muted')) { this.data.dlcsUnknowns[appId] = appName; this.data.countDlcsUnknowns += 1; } else { this.data.dlcs[appId] = appName; this.data.countDlcs += 1; } this.data.countAll += 1; } }); if (this.data.countAll > 0) { this.setModal(); } } public steamPowered() { this.data.appId = $('div[data-appid]').data('appid'); this.data.name = $('div#appHubAppName').text().trim(); $('a.game_area_dlc_row').each((_index, element) => { const $dom = $(element); const appId = $dom.data('ds-appid'); const appName = $dom.find('.game_area_dlc_name').text().trim(); if (typeof appId !== 'undefined' && typeof appName !== 'undefined') { this.data.dlcs[appId] = appName; this.data.countDlcs += 1; this.data.countAll += 1; } }); if (this.data.countAll > 0) { this.setModal(); } } public steamDbDepot() { let content = ''; // eslint-disable-next-line new-cap const dataTable = unsafeWindow.jQuery('div#files .table.file-tree').DataTable().data(); const depotId: string = $(`div[data-depotid]`).data('depotid'); $.each(dataTable, (_index: string, values: string) => { const fileName = values[0]; const sha1 = values[1]; if (this.isValidSha1(sha1)) { content += `${sha1} *${fileName}\n`; } }); if (content.length > 0) { this.setModal(); $('a#sake_download').attr({ href: this.encodeToDataUri(content), download: `${depotId}.sha1`, }); $('textarea#sake_textarea').val(content); } } public epicGames() { this.setModal(); } public setStyles() { // Revert before new css // eslint-disable-next-line new-cap GM_addStyle(`.sak32009 *{all:revert;}`); // eslint-disable-next-line new-cap GM_addStyle(skBootstrap); // eslint-disable-next-line new-cap GM_addStyle(skStyles); } public setModal() { this.setStyles(); this.setModalContainer(); this.setModalEvents(); if (!this.is.epicGames) { this.setCommonEvents(); if (!this.is.steamdbDepot) { this.setEvents(); } } this.setModalButton(); } public setModalButton() { $(`<div class="sak32009"> <button type="button" class="btn btn-sake me-2" data-bs-toggle="modal" data-bs-target="#${packageName}">${this.titleScript}</button> </div>`).appendTo('body'); } public setModalContainer() { const modalTop = `<div class="sak32009"> <div class="modal" id="${packageName}"> <div class="modal-dialog modal-dialog-centered modal-lg"> <div class="modal-content bg-dark text-white shadow-lg"> <div class="modal-header flex-column border-secondary"> <div class="modal-header-logo"> <img src="${sak32009 as string}" alt="${packageProductName}"> </div> <h5 class="text-center">${this.titleScript}</h5> </div> <div class="modal-body p-0">`; let modalContainer = ''; const modalBottom = `</div> <div class="modal-footer flex-column border-secondary"> <h6><strong>Protect</strong> development and free things,<br>because their survival is in our hands.</h6> <p class="mb-3">Source code licensed <a href="https://opensource.org/licenses/mit-license.php" target="_blank">MIT</a>.</p> <div> <a class="btn btn-primary" target="_blank" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&amp;hosted_button_id=U7TLCVMHN9HA2&amp;source=url">PayPal Donation</a> <a class="btn btn-secondary" target="_blank" href="https://github.com/Sak32009/GetDLCInfoFromSteamDB/">GitHub Project</a> </div> </div> </div> </div> </div> </div>`; if (this.is.epicGames) { modalContainer = `<h5 class="text-center m-3">Patience is the virtue of the strong!</h5>`; } else if (this.is.steamdbDepot) { modalContainer = `<div class="d-flex flex-row justify-content-end m-2"> <a id="sake_download" href="#" class="btn btn-dark border border-secondary">Download as file</a> </div> <div class="m-2"> <textarea id="sake_textarea" class="form-control resize-none bg-dark text-white border-secondary" readonly rows="14"></textarea> </div>`; } else { let sakeSelect = ''; $.each(this.formats, (index, values) => { const name = values.name as string; sakeSelect += `<option value='${index}'>${name}</option>`; }); modalContainer = `<div class="input-group p-2 border-bottom border-secondary"> <select id="sake_select" class="form-select bg-dark text-white border-secondary">${sakeSelect}</select> <button id="sake_convert" type="button" class="btn btn-dark border border-secondary">Convert</button> <label class="btn btn-dark border border-secondary${ this.is.steamdbApp ? '' : ' d-none' }" for="sake_unknowns"> <input class="form-check-input" type="checkbox" id="sake_unknowns"> <span>With DLCS Unknowns</span> </label> <a id="sake_download" href="#" class="btn btn-dark border border-secondary disabled">Download as file</a> </div> <div class="m-2 relative"> <textarea id="sake_textarea" class="form-control resize-none bg-dark text-white border-secondary" rows="14" placeholder="Select an option and click 'Convert'" readonly></textarea> <div class="d-flex flex-row justify-content-end m-2 fixed-to-textarea"> <div class="mx-1">DLCs: ${this.data.countDlcs as string}</div> ${ this.is.steamdbApp ? `<div class="mx-1">DLCs Unknown: ${this.data.countDlcsUnknowns as string}</div> ` : '' } <div class="mx-1">Total DLCs: ${this.data.countAll as string}</div> </div> </div>`; } $(modalTop + modalContainer + modalBottom).appendTo('body'); } public setModalEvents() { const $modal = document.querySelector('#' + packageName); if ($modal !== null) { $modal.addEventListener('shown.bs.modal', () => { $('.modal-backdrop').wrap($('<div class="sak32009"></div>')); }); $modal.addEventListener('hidden.bs.modal', () => { $('.sak32009:empty').remove(); }); } } public setEvents() { $(document).on('click', 'button#sake_convert', (event) => { event.preventDefault(); const selected = $(`select#sake_select option:selected`).val(); if (typeof selected === 'string') { const dataFormat = this.formats[selected]; const fileText = dataFormat.file.text; const fileName = this.parse(dataFormat.file.name); const content = this.parse(fileText); $(`textarea#sake_textarea`).html(content).scrollTop(0); $(`a#sake_download`) .attr({ href: this.encodeToDataUri(content), download: fileName, }) .removeClass('disabled'); } }); $(document).on('change', 'input#sake_unknowns', (event) => { this.data.withDlcsUnknowns = $(event.currentTarget).is(':checked'); }); } public setCommonEvents() { // Empty } public encodeToDataUri(content: string) { const strip = ($('<textarea>').html(content).get(0) as HTMLInputElement).value; const wordArray = Buffer.from(strip, 'utf8'); const base64 = wordArray.toString('base64'); return 'data:text/plain;charset=utf-8;base64,' + base64; } public isValidSha1(string: string) { return /^[a-fA-F\d]{40}$/gm.test(string); } public parse(content: string) { let newContent = content; newContent = newContent.replace( /\[dlcs(?: fromZero="(.*?)")?(?: prefix="(.*?)")?]([^[]+)\[\/dlcs]/gm, this.parseDlcsMatch.bind(this), ); newContent = newContent.replace(/\[data]([^[]+)\[\/data]/gm, this.parseDataMatch.bind(this)); newContent = newContent.replace(/\\n/gm, '\n'); return newContent; } public parseDlcsMatch(_match: any, p1: any, p2: any, p3: any) { const indexFromZero = typeof p1 === 'undefined' ? false : p1 === 'true'; const indexPrefix = typeof p2 === 'undefined' ? '0' : p2; const content = p3; return this.parseDlcsMatchValue(content, indexFromZero, indexPrefix); } public parseDlcsMatchPrefix(index: string, prefix: string) { const prefixInt = Number(prefix); return prefixInt > index.length ? '0'.repeat(prefixInt - index.length) + index : index; } public parseDlcsMatchValue(content: string, indexFromZero: boolean, indexPrefix: string) { let newContent = ''; let index = indexFromZero ? 0 : -1; const dlcs = this.data.withDlcsUnknowns ? { ...this.data.dlcs, ...this.data.dlcsUnknowns, } : this.data.dlcs; $.each(dlcs, (appid, name) => { index += 1; newContent += content.replace(/{(.*?)}/gm, (_match: any, content: any) => { const values: Record<string, any> = { // eslint-disable-next-line @typescript-eslint/naming-convention dlc_id: appid, // eslint-disable-next-line @typescript-eslint/naming-convention dlc_name: name, // eslint-disable-next-line @typescript-eslint/naming-convention dlc_index: this.parseDlcsMatchPrefix(index.toString(), indexPrefix), }; return values[content] as string; }); }); return newContent; } public parseDataMatch(_match: any, content: any) { return this.data[content] as string; } } // eslint-disable-next-line @typescript-eslint/no-unused-vars const a = new Sak32009(); });
the_stack
import { Toolbar } from '@jupyterlab/apputils'; import { Contents } from '@jupyterlab/services'; import { INotebookContent } from '@jupyterlab/nbformat'; import { IRenderMimeRegistry } from '@jupyterlab/rendermime'; import { PromiseDelegate } from '@lumino/coreutils'; import { Message } from '@lumino/messaging'; import { Panel, Widget } from '@lumino/widgets'; import { IDiffEntry } from 'nbdime/lib/diff/diffentries'; import { IMergeDecision } from 'nbdime/lib/merge/decisions'; import { NotebookMergeModel } from 'nbdime/lib/merge/model'; import { CELLMERGE_CLASS, NotebookMergeWidget } from 'nbdime/lib/merge/widget'; import { UNCHANGED_MERGE_CLASS } from 'nbdime/lib/merge/widget/common'; import { NotebookDiffModel } from 'nbdime/lib/diff/model'; import { CELLDIFF_CLASS, NotebookDiffWidget } from 'nbdime/lib/diff/widget'; import { CHUNK_PANEL_CLASS, UNCHANGED_DIFF_CLASS } from 'nbdime/lib/diff/widget/common'; import { requestAPI } from '../../git'; import { Git } from '../../tokens'; import { ITranslator, nullTranslator, TranslationBundle } from '@jupyterlab/translation'; /** * Class of the outermost widget, the draggable tab */ const NBDIME_CLASS = 'nbdime-Widget'; /** * Class of the root of the actual diff, the scroller element */ export const ROOT_CLASS = 'nbdime-root'; /** * DOM class for whether or not to hide unchanged cells */ const HIDE_UNCHANGED_CLASS = 'jp-mod-hideUnchanged'; /** * Data return by the ndbime api endpoint */ interface INbdimeDiff { /** * Base notebook content */ base: INotebookContent; /** * Diff to obtain challenger from base */ diff: IDiffEntry[]; } interface INbdimeMergeDiff { /** * Base notebook content */ base: INotebookContent; /** * Set of decisions made by comparing * reference, challenger, and base notebooks */ merge_decisions: IMergeDecision[]; } /** * Diff callback to be registered for notebook files. * * @param model Diff model * @param toolbar MainAreaWidget toolbar * @returns Diff notebook widget */ export const createNotebookDiff = async ( model: Git.Diff.IModel, renderMime: IRenderMimeRegistry, toolbar?: Toolbar, translator?: ITranslator ): Promise<NotebookDiff> => { // Create the notebook diff view const trans = translator.load('jupyterlab_git'); const diffWidget = new NotebookDiff(model, renderMime, trans); diffWidget.addClass('jp-git-diff-root'); await diffWidget.ready; // Add elements in toolbar if (toolbar) { const checkbox = document.createElement('input'); const label = document.createElement('label'); checkbox.className = 'nbdime-hide-unchanged'; checkbox.type = 'checkbox'; checkbox.checked = true; label.appendChild(checkbox); label.appendChild(document.createElement('span')).textContent = trans.__( 'Hide unchanged cells' ); toolbar.addItem('hideUnchanged', new Widget({ node: label })); if (model.hasConflict) { // Move merge notebook controls in the toolbar toolbar.addItem('clear-outputs', diffWidget.nbdimeWidget.widgets[0]); } // Connect toolbar checkbox and notebook diff widget diffWidget.areUnchangedCellsHidden = checkbox.checked; checkbox.onchange = () => { diffWidget.areUnchangedCellsHidden = checkbox.checked; }; } return diffWidget; }; /** * NotebookDiff widget */ export class NotebookDiff extends Panel implements Git.Diff.IDiffWidget { constructor( model: Git.Diff.IModel, renderMime: IRenderMimeRegistry, translator?: TranslationBundle ) { super(); const getReady = new PromiseDelegate<void>(); this._isReady = getReady.promise; this._model = model; this._renderMime = renderMime; this._trans = translator ?? nullTranslator.load('jupyterlab_git'); this.addClass(NBDIME_CLASS); this.refresh() .then(() => { getReady.resolve(); }) .catch(reason => { console.error( this._trans.__('Failed to refresh Notebook diff.'), reason, reason?.traceback ); }); } /** * Whether the unchanged cells are hidden or not */ get areUnchangedCellsHidden(): boolean { return this._areUnchangedCellsHidden; } set areUnchangedCellsHidden(v: boolean) { if (this._areUnchangedCellsHidden !== v) { Private.toggleShowUnchanged( this._scroller, this._hasConflict, this._areUnchangedCellsHidden ); this._areUnchangedCellsHidden = v; } } /** * Helper to determine if a notebook merge should be shown. */ private get _hasConflict(): boolean { return this._model.hasConflict; } /** * Nbdime notebook widget. */ get nbdimeWidget(): NotebookDiffWidget | NotebookMergeWidget { return this._nbdWidget; } /** * Promise which fulfills when the widget is ready. */ get ready(): Promise<void> { return this._isReady; } /** * Checks if all conflicts have been resolved. * * @see https://github.com/jupyter/nbdime/blob/a74b538386d05e3e9c26753ad21faf9ff4d269d7/packages/webapp/src/app/save.ts#L2 */ get isFileResolved(): boolean { const widget = this.nbdimeWidget as NotebookMergeWidget; this._lastSerializeModel = widget.model.serialize(); const validated = widget.validateMerged(this._lastSerializeModel); return ( JSON.stringify(this._lastSerializeModel) === JSON.stringify(validated) ); } /** * Gets the file model of a resolved merge conflict, * and rejects if unable to retrieve. * * Note: `isFileResolved` is assumed to not have been called, * or to have been called just before calling this method for caching purposes. */ async getResolvedFile(): Promise<Partial<Contents.IModel>> { return Promise.resolve({ format: 'json', type: 'notebook', content: this._lastSerializeModel ?? (this.nbdimeWidget as NotebookMergeWidget).model.serialize() }); } /** * Refresh diff * * Note: Update the content and recompute the diff */ async refresh(): Promise<void> { if (!this._scroller?.parent) { while (this.widgets.length > 0) { this.widgets[0].dispose(); } const header = Private.diffHeader( this._model.reference.label, this._model.challenger.label, this._hasConflict, this._trans.__('Common Ancestor') ); this.addWidget(header); this._scroller = new Panel(); this._scroller.addClass(ROOT_CLASS); this._scroller.node.tabIndex = -1; this.addWidget(this._scroller); } try { // ENH request content only if it changed const referenceContent = await this._model.reference.content(); const challengerContent = await this._model.challenger.content(); const baseContent = await this._model.base?.content(); const createView = baseContent ? this.createMergeView.bind(this) : this.createDiffView.bind(this); this._nbdWidget = await createView( challengerContent, referenceContent, baseContent ); while (this._scroller.widgets.length > 0) { this._scroller.widgets[0].dispose(); } this._scroller.addWidget(this._nbdWidget); try { await this._nbdWidget.init(); Private.markUnchangedRanges(this._scroller.node, this._hasConflict); } catch (reason) { // FIXME there is a bug in nbdime and init got reject due to recursion limit hit // console.error(`Failed to init notebook diff view: ${reason}`); // getReady.reject(reason); console.debug( this._trans.__('Failed to init notebook diff view: %1', reason) ); Private.markUnchangedRanges(this._scroller.node, this._hasConflict); } } catch (reason) { this.showError(reason as Error); } } protected async createDiffView( challengerContent: string, referenceContent: string ): Promise<NotebookDiffWidget> { const data = await requestAPI<INbdimeDiff>('diffnotebook', 'POST', { currentContent: challengerContent, previousContent: referenceContent }); const model = new NotebookDiffModel(data.base, data.diff); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore return new NotebookDiffWidget(model, this._renderMime); } protected async createMergeView( challengerContent: string, referenceContent: string, baseContent: string ): Promise<NotebookMergeWidget> { const data = await requestAPI<INbdimeMergeDiff>('diffnotebook', 'POST', { currentContent: challengerContent, previousContent: referenceContent, baseContent }); const model = new NotebookMergeModel(data.base, data.merge_decisions); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore return new NotebookMergeWidget(model, this._renderMime); } /** * Handle `'activate-request'` messages. */ protected onActivateRequest(msg: Message): void { if (this._scroller?.parent) { this._scroller.node.focus(); } } /** * Display an error instead of the file diff * * @param error Error object */ protected showError(error: Error): void { console.error( this._trans.__('Failed to load file diff.'), error, (error as any)?.traceback ); while (this.widgets.length > 0) { this.widgets[0].dispose(); } const msg = ((error.message || error) as string).replace('\n', '<br />'); this.node.innerHTML = `<p class="jp-git-diff-error"> <span>${this._trans.__('Error Loading Notebook Diff:')}</span> <span class="jp-git-diff-error-message">${msg}</span> </p>`; } protected _areUnchangedCellsHidden = false; protected _isReady: Promise<void>; protected _lastSerializeModel: INotebookContent | null = null; protected _model: Git.Diff.IModel; protected _nbdWidget: NotebookMergeWidget | NotebookDiffWidget; protected _renderMime: IRenderMimeRegistry; protected _scroller: Panel; protected _trans: TranslationBundle; } namespace Private { /** * Create a header widget for the diff view. */ export function diffHeader( localLabel: string, remoteLabel: string, hasConflict: boolean, baseLabel?: string ): Widget { const bannerClass = hasConflict ? 'jp-git-merge-banner' : 'jp-git-diff-banner'; const node = document.createElement('div'); node.className = 'jp-git-diff-header'; node.innerHTML = `<div class="${bannerClass}"> <span>${localLabel}</span> <span class="jp-spacer"></span> ${ hasConflict ? // Add extra space during notebook merge view `<span>${baseLabel}</span><span class="jp-spacer"></span>` : '' } <span>${remoteLabel}</span> </div>`; return new Widget({ node }); } /** * Toggle whether to show or hide unchanged cells. * * This simply marks with a class, real work is done by CSS. */ export function toggleShowUnchanged( root: Widget, hasConflict: boolean, show?: boolean ): void { const hiding = root.hasClass(HIDE_UNCHANGED_CLASS); if (show === undefined) { show = hiding; } else if (hiding !== show) { // Nothing to do return; } if (show) { root.removeClass(HIDE_UNCHANGED_CLASS); } else { markUnchangedRanges(root.node, hasConflict); root.addClass(HIDE_UNCHANGED_CLASS); } root.update(); } /** * Gets the chunk element of an added/removed cell, or the cell element for others * @param cellElement */ function getChunkElement(cellElement: Element): Element { if ( !cellElement.parentElement || !cellElement.parentElement.parentElement ) { return cellElement; } const chunkCandidate = cellElement.parentElement.parentElement; if (chunkCandidate.classList.contains(CHUNK_PANEL_CLASS)) { return chunkCandidate; } return cellElement; } /** * Marks certain cells with */ export function markUnchangedRanges( root: HTMLElement, hasConflict: boolean ): void { const CELL_CLASS = hasConflict ? CELLMERGE_CLASS : CELLDIFF_CLASS; const UNCHANGED_CLASS = hasConflict ? UNCHANGED_MERGE_CLASS : UNCHANGED_DIFF_CLASS; const NOTEBOOK_CLASS = hasConflict ? '.jp-Notebook-merge' : '.jp-Notebook-diff'; const children = root.querySelectorAll(`.${CELL_CLASS}`); let rangeStart = -1; for (let i = 0; i < children.length; ++i) { const child = children[i]; if (!child.classList.contains(UNCHANGED_CLASS)) { // Visible if (rangeStart !== -1) { // Previous was hidden const N = i - rangeStart; getChunkElement(child).setAttribute( 'data-nbdime-NCellsHiddenBefore', N.toString() ); rangeStart = -1; } } else if (rangeStart === -1) { rangeStart = i; } } if (rangeStart !== -1) { // Last element was part of a hidden range, need to mark // the last cell that will be visible. const N = children.length - rangeStart; if (rangeStart === 0) { // All elements were hidden, nothing to mark // Add info on root instead const tag = root.querySelector(NOTEBOOK_CLASS) ?? root; tag.setAttribute('data-nbdime-AllCellsHidden', N.toString()); return; } const lastVisible = children[rangeStart - 1]; getChunkElement(lastVisible).setAttribute( 'data-nbdime-NCellsHiddenAfter', N.toString() ); } } }
the_stack
import { template, types as t } from "@babel/core"; import type { Visitor } from "@babel/traverse"; const buildClassDecorator = template(` DECORATOR(CLASS_REF = INNER) || CLASS_REF; `) as (replacements: { DECORATOR; CLASS_REF; INNER }) => t.ExpressionStatement; const buildClassPrototype = template(` CLASS_REF.prototype; `) as (replacements: { CLASS_REF }) => t.ExpressionStatement; const buildGetDescriptor = template(` Object.getOwnPropertyDescriptor(TARGET, PROPERTY); `) as (replacements: { TARGET; PROPERTY }) => t.ExpressionStatement; const buildGetObjectInitializer = template(` (TEMP = Object.getOwnPropertyDescriptor(TARGET, PROPERTY), (TEMP = TEMP ? TEMP.value : undefined), { enumerable: true, configurable: true, writable: true, initializer: function(){ return TEMP; } }) `) as (replacements: { TEMP; TARGET; PROPERTY }) => t.ExpressionStatement; const WARNING_CALLS = new WeakSet(); /** * If the decorator expressions are non-identifiers, hoist them to before the class so we can be sure * that they are evaluated in order. */ function applyEnsureOrdering(path) { // TODO: This should probably also hoist computed properties. const decorators = ( path.isClass() ? [path].concat(path.get("body.body")) : path.get("properties") ).reduce((acc, prop) => acc.concat(prop.node.decorators || []), []); const identDecorators = decorators.filter( decorator => !t.isIdentifier(decorator.expression), ); if (identDecorators.length === 0) return; return t.sequenceExpression( identDecorators .map(decorator => { const expression = decorator.expression; const id = (decorator.expression = path.scope.generateDeclaredUidIdentifier("dec")); return t.assignmentExpression("=", id, expression); }) .concat([path.node]), ); } /** * Given a class expression with class-level decorators, create a new expression * with the proper decorated behavior. */ function applyClassDecorators(classPath) { if (!hasClassDecorators(classPath.node)) return; const decorators = classPath.node.decorators || []; classPath.node.decorators = null; const name = classPath.scope.generateDeclaredUidIdentifier("class"); return decorators .map(dec => dec.expression) .reverse() .reduce(function (acc, decorator) { return buildClassDecorator({ CLASS_REF: t.cloneNode(name), DECORATOR: t.cloneNode(decorator), INNER: acc, }).expression; }, classPath.node); } function hasClassDecorators(classNode) { return !!(classNode.decorators && classNode.decorators.length); } /** * Given a class expression with method-level decorators, create a new expression * with the proper decorated behavior. */ function applyMethodDecorators(path, state) { if (!hasMethodDecorators(path.node.body.body)) return; return applyTargetDecorators(path, state, path.node.body.body); } function hasMethodDecorators(body) { return body.some(node => node.decorators?.length); } /** * Given an object expression with property decorators, create a new expression * with the proper decorated behavior. */ function applyObjectDecorators(path, state) { if (!hasMethodDecorators(path.node.properties)) return; return applyTargetDecorators(path, state, path.node.properties); } /** * A helper to pull out property decorators into a sequence expression. */ function applyTargetDecorators(path, state, decoratedProps) { const name = path.scope.generateDeclaredUidIdentifier( path.isClass() ? "class" : "obj", ); const exprs = decoratedProps.reduce(function (acc, node) { const decorators = node.decorators || []; node.decorators = null; if (decorators.length === 0) return acc; if (node.computed) { throw path.buildCodeFrameError( "Computed method/property decorators are not yet supported.", ); } const property = t.isLiteral(node.key) ? node.key : t.stringLiteral(node.key.name); const target = path.isClass() && !node.static ? buildClassPrototype({ CLASS_REF: name, }).expression : name; if (t.isClassProperty(node, { static: false })) { const descriptor = path.scope.generateDeclaredUidIdentifier("descriptor"); const initializer = node.value ? t.functionExpression( null, [], t.blockStatement([t.returnStatement(node.value)]), ) : t.nullLiteral(); node.value = t.callExpression( state.addHelper("initializerWarningHelper"), [descriptor, t.thisExpression()], ); WARNING_CALLS.add(node.value); acc.push( t.assignmentExpression( "=", t.cloneNode(descriptor), t.callExpression(state.addHelper("applyDecoratedDescriptor"), [ t.cloneNode(target), t.cloneNode(property), t.arrayExpression( decorators.map(dec => t.cloneNode(dec.expression)), ), t.objectExpression([ t.objectProperty( t.identifier("configurable"), t.booleanLiteral(true), ), t.objectProperty( t.identifier("enumerable"), t.booleanLiteral(true), ), t.objectProperty( t.identifier("writable"), t.booleanLiteral(true), ), t.objectProperty(t.identifier("initializer"), initializer), ]), ]), ), ); } else { acc.push( t.callExpression(state.addHelper("applyDecoratedDescriptor"), [ t.cloneNode(target), t.cloneNode(property), t.arrayExpression(decorators.map(dec => t.cloneNode(dec.expression))), t.isObjectProperty(node) || t.isClassProperty(node, { static: true }) ? buildGetObjectInitializer({ TEMP: path.scope.generateDeclaredUidIdentifier("init"), TARGET: t.cloneNode(target), PROPERTY: t.cloneNode(property), }).expression : buildGetDescriptor({ TARGET: t.cloneNode(target), PROPERTY: t.cloneNode(property), }).expression, t.cloneNode(target), ]), ); } return acc; }, []); return t.sequenceExpression([ t.assignmentExpression("=", t.cloneNode(name), path.node), t.sequenceExpression(exprs), t.cloneNode(name), ]); } function decoratedClassToExpression({ node, scope }) { if (!hasClassDecorators(node) && !hasMethodDecorators(node.body.body)) { return; } const ref = node.id ? t.cloneNode(node.id) : scope.generateUidIdentifier("class"); return t.variableDeclaration("let", [ t.variableDeclarator(ref, t.toExpression(node)), ]); } export default { ExportDefaultDeclaration(path) { const decl = path.get("declaration"); if (!decl.isClassDeclaration()) return; const replacement = decoratedClassToExpression(decl); if (replacement) { const [varDeclPath] = path.replaceWithMultiple([ replacement, t.exportNamedDeclaration(null, [ t.exportSpecifier( // @ts-expect-error todo(flow->ts) might be add more specific return type for decoratedClassToExpression t.cloneNode(replacement.declarations[0].id), t.identifier("default"), ), ]), ]); if (!decl.node.id) { path.scope.registerDeclaration(varDeclPath); } } }, ClassDeclaration(path) { const replacement = decoratedClassToExpression(path); if (replacement) { path.replaceWith(replacement); } }, ClassExpression(path, state) { // Create a replacement for the class node if there is one. We do one pass to replace classes with // class decorators, and a second pass to process method decorators. const decoratedClass = applyEnsureOrdering(path) || applyClassDecorators(path) || applyMethodDecorators(path, state); if (decoratedClass) path.replaceWith(decoratedClass); }, ObjectExpression(path, state) { const decoratedObject = applyEnsureOrdering(path) || applyObjectDecorators(path, state); if (decoratedObject) path.replaceWith(decoratedObject); }, AssignmentExpression(path, state) { if (!WARNING_CALLS.has(path.node.right)) return; path.replaceWith( t.callExpression(state.addHelper("initializerDefineProperty"), [ // @ts-expect-error todo(flow->ts) typesafe NodePath.get t.cloneNode(path.get("left.object").node), t.stringLiteral( // @ts-expect-error todo(flow->ts) typesafe NodePath.get path.get("left.property").node.name || // @ts-expect-error todo(flow->ts) typesafe NodePath.get path.get("left.property").node.value, ), // @ts-expect-error todo(flow->ts) t.cloneNode(path.get("right.arguments")[0].node), // @ts-expect-error todo(flow->ts) t.cloneNode(path.get("right.arguments")[1].node), ]), ); }, CallExpression(path, state) { if (path.node.arguments.length !== 3) return; if (!WARNING_CALLS.has(path.node.arguments[2])) return; // If the class properties plugin isn't enabled, this line will add an unused helper // to the code. It's not ideal, but it's ok since the configuration is not valid anyway. // @ts-expect-error todo(flow->ts) check that `callee` is Identifier if (path.node.callee.name !== state.addHelper("defineProperty").name) { return; } path.replaceWith( t.callExpression(state.addHelper("initializerDefineProperty"), [ t.cloneNode(path.get("arguments")[0].node), t.cloneNode(path.get("arguments")[1].node), // @ts-expect-error todo(flow->ts) t.cloneNode(path.get("arguments.2.arguments")[0].node), // @ts-expect-error todo(flow->ts) t.cloneNode(path.get("arguments.2.arguments")[1].node), ]), ); }, } as Visitor<any>;
the_stack
import { createProgramFromScripts } from './utils'; import { ImageSource } from '@nativescript/core'; export function imageFilter(canvas) { var vertexShaderSource = `#version 300 es // an attribute is an input (in) to a vertex shader. // It will receive data from a buffer in vec2 a_position; in vec2 a_texCoord; // Used to pass in the resolution of the canvas uniform vec2 u_resolution; uniform float u_flipY; // Used to pass the texture coordinates to the fragment shader out vec2 v_texCoord; // all shaders have a main function void main() { // convert the position from pixels to 0.0 to 1.0 vec2 zeroToOne = a_position / u_resolution; // convert from 0->1 to 0->2 vec2 zeroToTwo = zeroToOne * 2.0; // convert from 0->2 to -1->+1 (clipspace) vec2 clipSpace = zeroToTwo - 1.0; gl_Position = vec4(clipSpace * vec2(1, u_flipY), 0, 1); // pass the texCoord to the fragment shader // The GPU will interpolate this value between points. v_texCoord = a_texCoord; } `; var fragmentShaderSource = `#version 300 es // fragment shaders don't have a default precision so we need // to pick one. highp is a good default. It means "high precision" precision highp float; // our texture uniform sampler2D u_image; // the convolution kernal data uniform float u_kernel[9]; uniform float u_kernelWeight; // the texCoords passed in from the vertex shader. in vec2 v_texCoord; // we need to declare an output for the fragment shader out vec4 outColor; void main() { vec2 onePixel = vec2(1) / vec2(textureSize(u_image, 0)); vec4 colorSum = texture(u_image, v_texCoord + onePixel * vec2(-1, -1)) * u_kernel[0] + texture(u_image, v_texCoord + onePixel * vec2( 0, -1)) * u_kernel[1] + texture(u_image, v_texCoord + onePixel * vec2( 1, -1)) * u_kernel[2] + texture(u_image, v_texCoord + onePixel * vec2(-1, 0)) * u_kernel[3] + texture(u_image, v_texCoord + onePixel * vec2( 0, 0)) * u_kernel[4] + texture(u_image, v_texCoord + onePixel * vec2( 1, 0)) * u_kernel[5] + texture(u_image, v_texCoord + onePixel * vec2(-1, 1)) * u_kernel[6] + texture(u_image, v_texCoord + onePixel * vec2( 0, 1)) * u_kernel[7] + texture(u_image, v_texCoord + onePixel * vec2( 1, 1)) * u_kernel[8] ; outColor = vec4((colorSum / u_kernelWeight).rgb, 1); } `; function main() { ImageSource.fromUrl('https://webglfundamentals.org/webgl/resources/leaves.jpg') .then(image => { render(image); }); } function render(image) { var gl = canvas.getContext('webgl2'); if (!gl) { return; } // setup GLSL program var program = createProgramFromScripts(gl, [{type: 'vertex', src: vertexShaderSource}, {type:'fragment',src: fragmentShaderSource}]); // look up where the vertex data needs to go. var positionAttributeLocation = gl.getAttribLocation(program, 'a_position'); var texCoordAttributeLocation = gl.getAttribLocation(program, 'a_texCoord'); // lookup uniforms var resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); var imageLocation = gl.getUniformLocation(program, 'u_image'); var kernelLocation = gl.getUniformLocation(program, 'u_kernel[0]'); var kernelWeightLocation = gl.getUniformLocation(program, 'u_kernelWeight'); var flipYLocation = gl.getUniformLocation(program, 'u_flipY'); // Create a vertex array object (attribute state) var vao = gl.createVertexArray(); // and make it the one we're currently working with gl.bindVertexArray(vao); // Create a buffer and put a single pixel space rectangle in // it (2 triangles) var positionBuffer = gl.createBuffer(); // Turn on the attribute gl.enableVertexAttribArray(positionAttributeLocation); // Bind it to ARRAY_BUFFER (think of it as ARRAY_BUFFER = positionBuffer) gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); // Tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER) var size = 2; // 2 components per iteration var type = gl.FLOAT; // the data is 32bit floats var normalize = false; // don't normalize the data var stride = 0; // 0 = move forward size * sizeof(type) each iteration to get the next position var offset = 0; // start at the beginning of the buffer gl.vertexAttribPointer( positionAttributeLocation, size, type, normalize, stride, offset); // provide texture coordinates for the rectangle. var texCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, ]), gl.STATIC_DRAW); gl.enableVertexAttribArray(texCoordAttributeLocation); var size = 2; // 2 components per iteration var type = gl.FLOAT; // the data is 32bit floats var normalize = false; // don't normalize the data var stride = 0; // 0 = move forward size * sizeof(type) each iteration to get the next position var offset = 0; // start at the beginning of the buffer gl.vertexAttribPointer( texCoordAttributeLocation, size, type, normalize, stride, offset); function createAndSetupTexture(gl) { var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); // Set up texture so we can render any size image and so we are // working with pixels. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); return texture; } // Create a texture and put the image in it. var originalImageTexture = createAndSetupTexture(gl); // Upload the image into the texture. var mipLevel = 0; // the largest mip var internalFormat = gl.RGBA; // format we want in the texture var srcFormat = gl.RGBA; // format of data we are supplying var srcType = gl.UNSIGNED_BYTE; // type of data we are supplying gl.texImage2D(gl.TEXTURE_2D, mipLevel, internalFormat, srcFormat, srcType, image); // create 2 textures and attach them to framebuffers. var textures = []; var framebuffers = []; for (var ii = 0; ii < 2; ++ii) { var texture = createAndSetupTexture(gl); textures.push(texture); // make the texture the same size as the image var mipLevel = 0; // the largest mip var internalFormat = gl.RGBA; // format we want in the texture var border = 0; // must be 0 var srcFormat = gl.RGBA; // format of data we are supplying var srcType = gl.UNSIGNED_BYTE; // type of data we are supplying var data = null; // no data = create a blank texture gl.texImage2D( gl.TEXTURE_2D, mipLevel, internalFormat, image.width, image.height, border, srcFormat, srcType, data); // Create a framebuffer var fbo = gl.createFramebuffer(); framebuffers.push(fbo); gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); // Attach a texture to it. var attachmentPoint = gl.COLOR_ATTACHMENT0; gl.framebufferTexture2D( gl.FRAMEBUFFER, attachmentPoint, gl.TEXTURE_2D, texture, mipLevel); } // Bind the position buffer so gl.bufferData that will be called // in setRectangle puts data in the position buffer gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); // Set a rectangle the same size as the image. setRectangle(gl, 0, 0, image.width, image.height); // Define several convolution kernels var kernels = { normal: [ 0, 0, 0, 0, 1, 0, 0, 0, 0, ], gaussianBlur: [ 0.045, 0.122, 0.045, 0.122, 0.332, 0.122, 0.045, 0.122, 0.045, ], gaussianBlur2: [ 1, 2, 1, 2, 4, 2, 1, 2, 1, ], gaussianBlur3: [ 0, 1, 0, 1, 1, 1, 0, 1, 0, ], unsharpen: [ -1, -1, -1, -1, 9, -1, -1, -1, -1, ], sharpness: [ 0, -1, 0, -1, 5, -1, 0, -1, 0, ], sharpen: [ -1, -1, -1, -1, 16, -1, -1, -1, -1, ], edgeDetect: [ -0.125, -0.125, -0.125, -0.125, 1, -0.125, -0.125, -0.125, -0.125, ], edgeDetect2: [ -1, -1, -1, -1, 8, -1, -1, -1, -1, ], edgeDetect3: [ -5, 0, 0, 0, 0, 0, 0, 0, 5, ], edgeDetect4: [ -1, -1, -1, 0, 0, 0, 1, 1, 1, ], edgeDetect5: [ -1, -1, -1, 2, 2, 2, -1, -1, -1, ], edgeDetect6: [ -5, -5, -5, -5, 39, -5, -5, -5, -5, ], sobelHorizontal: [ 1, 2, 1, 0, 0, 0, -1, -2, -1, ], sobelVertical: [ 1, 0, -1, 2, 0, -2, 1, 0, -1, ], previtHorizontal: [ 1, 1, 1, 0, 0, 0, -1, -1, -1, ], previtVertical: [ 1, 0, -1, 1, 0, -1, 1, 0, -1, ], boxBlur: [ 0.111, 0.111, 0.111, 0.111, 0.111, 0.111, 0.111, 0.111, 0.111, ], triangleBlur: [ 0.0625, 0.125, 0.0625, 0.125, 0.25, 0.125, 0.0625, 0.125, 0.0625, ], emboss: [ -2, -1, 0, -1, 1, 1, 0, 1, 2, ], }; var effects = [ { name: 'gaussianBlur3', on: true }, { name: 'gaussianBlur3', on: true }, { name: 'gaussianBlur3', on: true }, { name: 'sharpness', }, { name: 'sharpness', }, { name: 'sharpness', }, { name: 'sharpen', }, { name: 'sharpen', }, { name: 'sharpen', }, { name: 'unsharpen', }, { name: 'unsharpen', }, { name: 'unsharpen', }, { name: 'emboss', on: true }, { name: 'edgeDetect', }, { name: 'edgeDetect', }, { name: 'edgeDetect3', }, { name: 'edgeDetect3', }, ]; /* add btns // Setup a ui. var ui = document.querySelector("#ui"); var table = document.createElement("table"); var tbody = document.createElement("tbody"); for (var ii = 0; ii < effects.length; ++ii) { var effect = effects[ii]; var tr = document.createElement("tr"); var td = document.createElement("td"); var chk = document.createElement("input"); chk.value = effect.name; chk.type = "checkbox"; if (effect.on) { chk.checked = "true"; } chk.onchange = drawEffects; td.appendChild(chk); td.appendChild(document.createTextNode(effect.name)); tr.appendChild(td); tbody.appendChild(tr); } table.appendChild(tbody); ui.appendChild(table); $("#ui table").tableDnD({onDrop: drawEffects}); */ drawEffects(); function computeKernelWeight(kernel) { var weight = kernel.reduce(function (prev, curr) { return prev + curr; }); return weight <= 0 ? 1 : weight; } function drawEffects() { // webglUtils.resizeCanvasToDisplaySize(gl.canvas); // Tell WebGL how to convert from clip space to pixels gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); // Clear the canvas gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); // Tell it to use our program (pair of shaders) gl.useProgram(program); // Bind the attribute/buffer set we want. gl.bindVertexArray(vao); // start with the original image on unit 0 gl.activeTexture(gl.TEXTURE0 + 0); gl.bindTexture(gl.TEXTURE_2D, originalImageTexture); // Tell the shader to get the texture from texture unit 0 gl.uniform1i(imageLocation, 0); // don't y flip images while drawing to the textures gl.uniform1f(flipYLocation, 1); // loop through each effect we want to apply. var count = 0; var length = effects.length; for (var ii = 0; ii < length; ++ii) { var checkbox = effects[ii]; if (checkbox.on) { // Setup to draw into one of the framebuffers. setFramebuffer(framebuffers[ count % 2 ], image.width, image.height); drawWithKernel(checkbox.name); // for the next draw, use the texture we just rendered to. gl.bindTexture(gl.TEXTURE_2D, textures[ count % 2 ]); // increment count so we use the other texture next time. ++count; } } // finally draw the result to the canvas. gl.uniform1f(flipYLocation, -1); // need to y flip for canvas setFramebuffer(null, gl.drawingBufferWidth, gl.drawingBufferHeight); // Clear the canvas gl.clearColor(0, 0, 0, 0); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); drawWithKernel('normal'); } function setFramebuffer(fbo, width, height) { // make this the framebuffer we are rendering to. gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); // Tell the shader the resolution of the framebuffer. gl.uniform2f(resolutionLocation, width, height); // Tell WebGL how to convert from clip space to pixels gl.viewport(0, 0, width, height); } function drawWithKernel(name) { // set the kernel and it's weight gl.uniform1fv(kernelLocation, kernels[ name ]); gl.uniform1f(kernelWeightLocation, computeKernelWeight(kernels[ name ])); // Draw the rectangle. var primitiveType = gl.TRIANGLES; var offset = 0; var count = 6; gl.drawArrays(primitiveType, offset, count); } } function setRectangle(gl, x, y, width, height) { var x1 = x; var x2 = x + width; var y1 = y; var y2 = y + height; gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ x1, y1, x2, y1, x1, y2, x1, y2, x2, y1, x2, y2, ]), gl.STATIC_DRAW); } main(); }
the_stack
import { SpreadsheetHelper } from '../util/spreadsheethelper.spec'; import { defaultData, filterData } from '../util/datasource.spec'; import { Spreadsheet, filterByCellValue } from '../../../src/index'; import { classList, getComponent } from '@syncfusion/ej2-base'; import { PredicateModel } from '@syncfusion/ej2-grids'; describe('Filter ->', () => { const helper: SpreadsheetHelper = new SpreadsheetHelper('spreadsheet'); describe('public method ->', () => { beforeAll((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }] }] }, done); }); afterAll(() => { helper.invoke('destroy'); }); it('Apply Filter', (done: Function) => { helper.invoke('applyFilter', [[{ field: 'E', predicate: 'or', operator: 'equal', value: '10' }], 'A1:H1']); setTimeout(() => { expect(helper.invoke('getCell', [0, 0]).children[0].classList).toContain('e-filter-btn'); expect(helper.invoke('getCell', [0, 4]).children[0].children[0].classList).toContain('e-filtered'); done(); }); }); it('Clear Filter', (done: Function) => { helper.invoke('clearFilter', ['E']); setTimeout(() => { expect(helper.invoke('getCell', [0, 4]).children[0].children[0].classList).not.toContain('e-filtered'); done(); }); }); it('Remove Filter', (done: Function) => { helper.invoke('applyFilter', [null, 'A1:A1']); setTimeout(() => { expect(helper.invoke('getCell', [0, 1]).children[0]).toBeUndefined(); done(); }); }); }); describe('UI interaction checking ->', () => { beforeAll((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }] }] }, done); }); afterAll(() => { helper.invoke('destroy'); }); it('Apply and remove filter using toolbar', (done: Function) => { const spreadsheet: any = helper.getInstance(); const firstCell: HTMLElement = helper.invoke('getCell', [0, 0]); const lastCell: HTMLElement = helper.invoke('getCell', [0, spreadsheet.sheets[0].usedRange.colIndex]); expect(firstCell.querySelector('.e-filter-icon')).toBeNull(); expect(lastCell.querySelector('.e-filter-icon')).toBeNull(); helper.getElement('#' + helper.id + '_sorting').click(); helper.getElement('#' + helper.id + '_applyfilter').click(); expect(firstCell.querySelector('.e-filter-icon')).not.toBeNull(); expect(lastCell.querySelector('.e-filter-icon')).not.toBeNull(); expect(spreadsheet.filterModule.filterRange.size).toBe(1); expect(spreadsheet.filterModule.filterRange.get(0).range).toEqual([0, 0, 10, 7]); expect(spreadsheet.filterModule.filterRange.get(0).useFilterRange).toBeFalsy(); expect(spreadsheet.filterModule.filterCollection.size).toBe(1); expect(spreadsheet.filterModule.filterCollection.get(0)).toEqual([]); helper.getElement('#' + helper.id + '_sorting').click(); helper.getElement('#' + helper.id + '_applyfilter').click(); expect(firstCell.querySelector('.e-filter-icon')).toBeNull(); expect(lastCell.querySelector('.e-filter-icon')).toBeNull(); expect(spreadsheet.filterModule.filterRange.size).toBe(0); expect(spreadsheet.filterModule.filterCollection.size).toBe(0); helper.getElement('#' + helper.id + '_sorting').click(); helper.getElement('#' + helper.id + '_applyfilter').click(); done(); }); it('Filter popup open close using key action', (done: Function) => { helper.triggerKeyNativeEvent(40, false, false, null, 'keydown', true); setTimeout(() => { let filterPopup: HTMLElement = helper.getElement().lastElementChild; expect(filterPopup.classList.contains('e-filter-popup')).toBeTruthy(); expect(parseInt(filterPopup.style.left, 10)).toBeGreaterThan(0); // Left collision check helper.triggerKeyNativeEvent(38, false, false, null, 'keydown', true); expect(helper.getElement().querySelector('.e-filter-popup')).toBeNull(); done(); }); }); }); describe('Date column filter ->', () => { const dataSource: Object[] = [ { 'Item Name': 'Casual Shoes', Date: '02/14/2014', Amount: 200 }, { 'Item Name': 'Sports Shoes', Date: '06/11/2016', Amount: 600 }, { 'Item Name': 'Formal Shoes', Date: '07/27/2014', Amount: 300 }, { 'Item Name': 'Sandals & Floaters', Date: '11/21/2014', Amount: 300 }, { 'Item Name': 'Flip- Flops & Slippers', Date: '06/23/2015', Amount: 300 }, { 'Item Name': 'Sneakers', Date: '07/22/2014', Amount: 800 }, { 'Item Name': 'Running Shoes', Date: '02/04/2014', Amount: 200 }, { 'Item Name': 'Loafers', Date: '11/30/2015', Amount: 310 }, { 'Item Name': 'Cricket Shoes', Date: '07/09/2014', Amount: 1210 }, { 'Item Name': 'T-Shirts', Date: '10/31/2014', Amount: 500 }, ]; let spreadsheet: any; let checkboxList: HTMLElement; let ulList: HTMLElement; let treeObj: any; let filterCol: PredicateModel[]; let selectAll: HTMLElement; beforeAll((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: dataSource }], selectedRange: 'B1:B1' }] }, done); }); afterAll(() => { helper.invoke('destroy'); }); it('Date filter popup rendering check', (done: Function) => { helper.invoke('applyFilter'); const cell: HTMLElement = helper.invoke('getCell', [0, 1]); cell.focus(); helper.triggerKeyNativeEvent(40, false, false, null, 'keydown', true); setTimeout(() => { checkboxList = helper.getElement('.e-checkboxlist'); expect(checkboxList.childElementCount).toBe(0); setTimeout(() => { expect(checkboxList.childElementCount).toBe(2); selectAll = checkboxList.firstElementChild as HTMLElement; expect(selectAll.classList.contains('e-spreadsheet-ftrchk')).toBeTruthy(); expect(selectAll.querySelector('.e-selectall').classList.contains('e-check')).toBeTruthy(); expect((selectAll.querySelector('.e-chk-hidden') as HTMLInputElement).checked).toBeTruthy(); done(); }); }); }); it('Treeview rendering check', (done: Function) => { expect(checkboxList.lastElementChild.classList.contains('e-checkboxtree')).toBeTruthy(); treeObj = getComponent(checkboxList.lastElementChild as HTMLElement, 'treeview'); expect(treeObj.fields.id).toBe('__rowIndex'); expect(treeObj.fields.parentID).toBe('pId'); expect(treeObj.fields.text).toBe('B'); expect(treeObj.fields.hasChildren).toBe('hasChild'); expect(treeObj.fields.dataSource.length).toBe(20); expect(treeObj.fields.dataSource.length === treeObj.checkedNodes.length).toBeTruthy(); expect(treeObj.fields.dataSource[0]['__rowIndex']).toBe('2016'); expect(treeObj.fields.dataSource[1]['B']).toBe('2015'); expect(treeObj.fields.dataSource[2]['hasChild']).toBeTruthy(); expect(treeObj.fields.dataSource[0]['pId']).toBeUndefined(); expect(treeObj.fields.dataSource[4]['__rowIndex']).toBe('2016 June'); expect(treeObj.fields.dataSource[4]['B']).toBe('June'); expect(treeObj.fields.dataSource[9]['hasChild']).toBeTruthy(); expect(treeObj.fields.dataSource[6]['pId']).toBe('2014'); expect(treeObj.fields.dataSource[19]['__rowIndex']).toBe('2014 October 31'); expect(treeObj.fields.dataSource[19]['B']).toBe(31); expect(treeObj.fields.dataSource[17]['hasChild']).toBeUndefined(); expect(treeObj.fields.dataSource[15]['pId']).toBe('2014 July'); ulList = checkboxList.lastElementChild.querySelector('.e-ul'); expect(ulList.childElementCount).toBe(3); expect(ulList.getElementsByClassName('e-check').length).toBe(3); done(); }); it('Checkbox interaction and filtering', (done: Function) => { selectAll.click(); expect(selectAll.querySelector('.e-selectall').classList.contains('e-check')).toBeFalsy(); expect((selectAll.querySelector('.e-chk-hidden') as HTMLInputElement).checked).toBeFalsy(); expect(ulList.getElementsByClassName('e-check').length).toBe(0); const okBtn: HTMLButtonElement = helper.getElement().querySelector('.e-excelfilter .e-footer-content .e-primary'); expect(okBtn.disabled).toBeTruthy(); selectAll.click(); expect(selectAll.querySelector('.e-selectall').classList.contains('e-check')).toBeTruthy(); expect((selectAll.querySelector('.e-chk-hidden') as HTMLInputElement).checked).toBeTruthy(); expect(ulList.getElementsByClassName('e-check').length).toBe(3); expect(okBtn.disabled).toBeFalsy(); const list: HTMLElement = ulList.children[1].querySelector('.e-frame'); let e = new MouseEvent('mousedown', { view: window, bubbles: true, cancelable: true }); list.dispatchEvent(e); e = new MouseEvent('mouseup', { view: window, bubbles: true, cancelable: true }); list.dispatchEvent(e); e = new MouseEvent('click', { view: window, bubbles: true, cancelable: true }); list.dispatchEvent(e); expect(list.parentElement.querySelector('.e-check')).toBeNull(); expect(selectAll.querySelector('.e-check')).toBeNull(); expect(selectAll.querySelector('.e-selectall').classList.contains('e-stop')).toBeTruthy(); expect((selectAll.querySelector('.e-chk-hidden') as HTMLInputElement).checked).toBeFalsy(); okBtn.click(); spreadsheet = helper.getInstance(); filterCol = spreadsheet.filterModule.filterCollection.get(0); expect(filterCol.length).toBe(2); expect(filterCol[0].type).toBe('date'); expect(filterCol[0].predicate).toBe('and'); expect(filterCol[0].operator).toBe('notequal'); let date: Date = filterCol[0].value as Date; expect(date.getDate()).toBe(23); expect(date.getMonth()).toBe(5); expect(date.getFullYear()).toBe(2015); date = filterCol[1].value as Date; expect(date.getDate()).toBe(30); expect(date.getMonth()).toBe(10); expect(date.getFullYear()).toBe(2015); done(); }); it('Checkbox rendering with same filtered column and Clear filter action', (done: Function) => { spreadsheet.element.focus(); helper.triggerKeyNativeEvent(40, false, false, null, 'keydown', true); setTimeout(() => { setTimeout(() => { checkboxList = helper.getElement('.e-checkboxlist'); expect((getComponent(checkboxList.lastElementChild as HTMLElement, 'treeview') as any).checkedNodes.length).toBe(15); selectAll = checkboxList.firstElementChild as HTMLElement; expect(selectAll.querySelector('.e-selectall').classList.contains('e-stop')).toBeTruthy(); expect((selectAll.querySelector('.e-chk-hidden') as HTMLInputElement).checked).toBeFalsy(); ulList = checkboxList.lastElementChild.querySelector('.e-ul'); expect(ulList.children[1].querySelector('.e-check')).toBeNull(); selectAll.click(); expect(selectAll.querySelector('.e-stop')).toBeNull(); expect((selectAll.querySelector('.e-chk-hidden') as HTMLInputElement).checked).toBeTruthy(); expect(ulList.getElementsByClassName('e-check').length).toBe(3); helper.getElement().querySelector('.e-excelfilter .e-footer-content .e-primary').click(); expect(filterCol.length).toBe(0); done(); }); }); }); it('Checkbox rendering with other filtered column', (done: Function) => { helper.invoke('applyFilter', [[{ 'value': 300, 'field': 'C', 'predicate': 'and', 'operator': 'notequal', 'type': 'number', 'matchCase': false, 'ignoreAccent': false }], 'A1:C11']); setTimeout(() => { expect(spreadsheet.filterModule.filterCollection.get(0).length).toBe(1); spreadsheet.element.focus(); helper.triggerKeyNativeEvent(40, false, false, null, 'keydown', true); setTimeout(() => { setTimeout(() => { checkboxList = helper.getElement('.e-checkboxlist'); treeObj = getComponent(checkboxList.lastElementChild as HTMLElement, 'treeview'); expect(treeObj.fields.dataSource.length).toBe(15); expect(treeObj.fields.dataSource.length === treeObj.checkedNodes.length).toBeTruthy(); done(); }); }); }); }); it('Searching day, month and year then filter', (done: Function) => { const serachBox: HTMLInputElement = helper.getElement().querySelector('.e-searchinput'); serachBox.value = '2014'; spreadsheet.notify('refreshCheckbox', { event: { type: 'keyup', target: serachBox } }); expect(treeObj.fields.dataSource.length).toBe(9); expect(treeObj.fields.dataSource[0]['__rowIndex']).toBe('2014'); expect(treeObj.fields.dataSource[1]['__rowIndex']).toBe('2014 February'); expect(treeObj.fields.dataSource[6]['__rowIndex']).toBe('2014 February 14'); expect(treeObj.fields.dataSource.length === treeObj.checkedNodes.length).toBeTruthy(); serachBox.value = ''; spreadsheet.notify('refreshCheckbox', { event: { type: 'click', target: serachBox } }); expect(treeObj.fields.dataSource.length).toBe(15); expect(treeObj.fields.dataSource.length === treeObj.checkedNodes.length).toBeTruthy(); spreadsheet.notify('refreshCheckbox', { event: { type: 'click', target: serachBox.parentElement.querySelector('.e-search-icon') } }); expect(treeObj.fields.dataSource.length).toBe(15); serachBox.value = '30'; spreadsheet.notify('refreshCheckbox', { event: { type: 'keyup', target: serachBox } }); expect(treeObj.fields.dataSource.length).toBe(3); expect(treeObj.fields.dataSource[0]['__rowIndex']).toBe('2015'); expect(treeObj.fields.dataSource[1]['__rowIndex']).toBe('2015 November'); expect(treeObj.fields.dataSource[2]['__rowIndex']).toBe('2015 November 30'); expect(treeObj.fields.dataSource.length === treeObj.checkedNodes.length).toBeTruthy(); serachBox.value = 'Jun'; spreadsheet.notify('refreshCheckbox', { event: { type: 'keyup', target: serachBox } }); expect(treeObj.fields.dataSource.length).toBe(3); expect(treeObj.fields.dataSource.length === treeObj.checkedNodes.length).toBeTruthy(); helper.getElement().querySelector('.e-excelfilter .e-footer-content .e-primary').click(); filterCol = spreadsheet.filterModule.filterCollection.get(0); expect(filterCol.length).toBe(2); expect(filterCol[1].operator).toBe('equal'); expect(filterCol[1].predicate).toBe('or'); expect(filterCol[1].type).toBe('date'); const date: Date = filterCol[1].value as Date; expect(date.getDate()).toBe(11); expect(date.getMonth()).toBe(5); expect(date.getFullYear()).toBe(2016); done(); }); it('Checkbox rendering with same and other filtered columns', (done: Function) => { spreadsheet.element.focus(); helper.triggerKeyNativeEvent(40, false, false, null, 'keydown', true); setTimeout(() => { setTimeout(() => { checkboxList = helper.getElement('.e-checkboxlist'); treeObj = getComponent(checkboxList.lastElementChild as HTMLElement, 'treeview'); expect(treeObj.fields.dataSource.length).toBe(15); expect(treeObj.checkedNodes.length).toBe(3); selectAll = checkboxList.firstElementChild as HTMLElement; expect(selectAll.querySelector('.e-selectall').classList.contains('e-stop')).toBeTruthy(); expect((selectAll.querySelector('.e-chk-hidden') as HTMLInputElement).checked).toBeFalsy(); ulList = checkboxList.lastElementChild.querySelector('.e-ul'); expect(ulList.children[0].querySelector('.e-frame').classList.contains('e-check')).toBeTruthy(); expect(ulList.children[1].querySelector('.e-check')).toBeNull(); expect(ulList.children[2].querySelector('.e-check')).toBeNull(); selectAll.click(); expect(selectAll.querySelector('.e-stop')).toBeNull(); expect((selectAll.querySelector('.e-chk-hidden') as HTMLInputElement).checked).toBeTruthy(); expect(ulList.getElementsByClassName('e-check').length).toBe(3); treeObj.uncheckAll(['2014 February 14']); helper.getElement().querySelector('.e-excelfilter .e-footer-content .e-primary').click(); filterCol = spreadsheet.filterModule.filterCollection.get(0); expect(filterCol.length).toBe(2); expect(filterCol[1].operator).toBe('notequal'); const date: Date = filterCol[1].value as Date; expect(date.getDate()).toBe(14); expect(date.getMonth()).toBe(1); expect(date.getFullYear()).toBe(2014); done(); }); }); }); it('Columns with blank cell and other format cell', (done: Function) => { helper.invoke('updateCell', [{ value: '', format: 'General' }, 'B8']); helper.invoke('updateCell', [{ value: 'Test', format: 'General' }, 'B9']); spreadsheet.element.focus(); helper.triggerKeyNativeEvent(40, false, false, null, 'keydown', true); setTimeout(() => { setTimeout(() => { selectAll = helper.getElement('.e-spreadsheet-ftrchk'); selectAll.click(); const searchBox: HTMLInputElement = helper.getElement().querySelector('.e-searchinput'); searchBox.value = 'Blan'; spreadsheet.notify('refreshCheckbox', { event: { type: 'keyup', target: searchBox } }); treeObj = getComponent(helper.getElement('.e-checkboxtree'), 'treeview'); expect(treeObj.fields.dataSource.length).toBe(1); expect(treeObj.fields.dataSource.length === treeObj.checkedNodes.length).toBeTruthy(); expect(treeObj.fields.dataSource[0]['__rowIndex']).toBe('blanks'); searchBox.value = 'Tes'; spreadsheet.notify('refreshCheckbox', { event: { type: 'keyup', target: searchBox } }); expect(treeObj.fields.dataSource.length).toBe(1); expect(treeObj.fields.dataSource.length === treeObj.checkedNodes.length).toBeTruthy(); expect(treeObj.fields.dataSource[0]['__rowIndex']).toBe('text test'); helper.getElement().querySelector('.e-excelfilter .e-footer-content .e-primary').click(); filterCol = spreadsheet.filterModule.filterCollection.get(0); expect(filterCol.length).toBe(2); expect(filterCol[1].value).toBe('test'); expect(filterCol[1].predicate).toBe('or'); expect(filterCol[1].type).toBe('string'); done(); }); }); }); }); describe('CR-Issues ->', () => { describe('I289560, FB22087, FB24231 ->', () => { beforeAll((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }] }], created: (): void => { const spreadsheet: Spreadsheet = helper.getInstance(); spreadsheet.cellFormat({ backgroundColor: '#e56590', color: '#fff', fontWeight: 'bold', textAlign: 'center' }, 'A1:F1'); } }, done); }); afterAll(() => { helper.invoke('destroy'); }); it('Facing issues on spreadsheet - Filter applied after the specified range using applyFilter method', (done: Function) => { const spreadsheet: Spreadsheet = helper.getInstance(); spreadsheet.applyFilter(null, 'A1:F11'); expect(!!helper.invoke('getCell', [0, 0]).querySelector('.e-filter-iconbtn')).toBeTruthy(); expect(!!helper.invoke('getCell', [0, 1]).querySelector('.e-filter-iconbtn')).toBeTruthy(); expect(!!helper.invoke('getCell', [0, 5]).querySelector('.e-filter-iconbtn')).toBeTruthy(); expect(!!helper.invoke('getCell', [0, 6]).querySelector('.e-filter-iconbtn')).toBeFalsy(); done(); }); it('Filter icon disappears after refresh', (done: Function) => { const spreadsheet: Spreadsheet = helper.getInstance(); spreadsheet.applyFilter([{ field: 'H', predicate: 'or', operator: 'contains', value: '10' }]); setTimeout(() => { spreadsheet.refresh(); setTimeout(() => { setTimeout(() => { expect(helper.invoke('getCell', [0, 0]).querySelector('.e-filter-iconbtn')).not.toBeNull(); expect(helper.invoke('getCell', [0, 7]).querySelector('.e-filtered')).not.toBeNull(); expect(helper.invoke('getCell', [1, 7]).textContent).toBe('10'); done(); }); }); }); }); // it('Filter with unchecked values after open from json', (done: Function) => { // const spreadsheet: Spreadsheet = helper.getInstance(); // spreadsheet.applyFilter(); // spreadsheet.applyFilter([{ field: 'A', predicate: 'and', operator: 'notequal', value: 'Casual Shoes' }, { field: 'A', predicate: 'and', operator: 'notequal', value: 'Sneakers' }]); // setTimeout(() => { // spreadsheet.saveAsJson().then((json: any) => { // spreadsheet.openFromJson({ file: json.jsonObject }); // setTimeout(() => { // expect(spreadsheet.filterCollection[0].predicates.toString()).toBe('and,and'); // expect((helper.getContentTableElement().querySelector('tbody tr:nth-child(2)') as any).ariaRowIndex).toBe('3'); // expect(helper.getContentTableElement().querySelector('tbody tr:nth-child(2) td').textContent).toBe('Sports Shoes'); // expect(helper.getContentTableElement().querySelector('tbody tr:nth-child(6) td').textContent).toBe('Running Shoes'); // done(); // }); // }); // }); // }); // it('Cleared filter is not removed after open from json', (done: Function) => { // const spreadsheet: Spreadsheet = helper.getInstance(); // helper.triggerKeyEvent('keydown', 76, null, true, true); // expect(spreadsheet.filterCollection.length).toBe(0); // spreadsheet.saveAsJson().then((json: any) => { // spreadsheet.openFromJson({ file: json.jsonObject }); // setTimeout(() => { // expect(helper.invoke('getCell', [0, 0]).querySelector('.e-filter-iconbtn')).toBeNull(); // expect(helper.invoke('getCell', [0, 7]).querySelector('.e-filtered')).toBeNull(); // expect((helper.getContentTableElement().querySelector('tbody tr:nth-child(2)') as any).ariaRowIndex).toBe('2'); // done(); // }); // }); // }); }); // describe('I307401 -> Fiter UI updating ->', () => { // beforeAll((done: Function) => { // helper.initializeSpreadsheet({ // sheets: [{ ranges: [{ dataSource: defaultData }] }, {}, { ranges: [{ dataSource: defaultData }] }], // created: (): void => { // const spreadsheet: any = helper.getInstance(); // spreadsheet.applyFilter([{ field: "F", operator: "contains", value: 200 }]); // setTimeout(() => { // spreadsheet.filterModule.selectSortItemHandler(createElement('div', { className: 'e-filter-sortdesc' })); // }); // } // }, done); // }); // afterAll(() => { // helper.invoke('destroy'); // }); // it('Insert sheet', (done: Function) => { // helper.invoke('insertSheet', [0]); // setTimeout(() => { // helper.invoke('goTo', ['Sheet1!A1']); // setTimeout(() => { // let td: Element = helper.invoke('getCell', [0, 0]); // expect(td.children[0].children[0].classList).toContain('e-sortdesc-filter'); // expect(helper.getContentTableElement().querySelector('tbody tr:nth-child(2) td').textContent).toBe('Running Shoes'); // expect((helper.getContentTableElement().querySelector('tbody tr:nth-child(3)') as any).ariaRowIndex).toBe('8'); // td = helper.invoke('getCell', [0, 5]); // expect(td.children[0].children[0].classList).toContain('e-filtered'); // expect(helper.getInstance().filterCollection[0].sheetIndex).toBe(1); // done(); // }); // }); // }); // it('Delete sheet', (done: Function) => { // const spreadsheet: any = helper.getInstance(); // spreadsheet.goTo('Sheet3!F2'); // setTimeout(() => { // spreadsheet.applyFilter([{ field: "D", operator: "contains", value: 20 }]); // setTimeout(() => { // spreadsheet.filterModule.selectSortItemHandler(createElement('div', { className: 'e-filter-sortdesc' })); // setTimeout(() => { // helper.invoke('goTo', ['Sheet4!A1']); // setTimeout(() => { // helper.getInstance().notify('removeSheetTab', {}); // setTimeout(() => { // let td: Element = helper.invoke('getCell', [0, 0]); // expect(td.children[0].children[0].classList).toContain('e-sortdesc-filter'); // expect(helper.getContentTableElement().querySelector('tbody tr:nth-child(2) td').textContent).toBe('Running Shoes'); // expect((helper.getContentTableElement().querySelector('tbody tr:nth-child(3)') as any).ariaRowIndex).toBe('8'); // td = helper.invoke('getCell', [0, 5]); // expect(td.children[0].children[0].classList).toContain('e-filtered'); // expect(helper.getInstance().filterCollection[0].sheetIndex).toBe(0); // helper.invoke('goTo', ['Sheet3!A1']); // setTimeout(() => { // td = helper.invoke('getCell', [0, 5]); // expect(td.children[0].children[0].classList).toContain('e-sortdesc-filter'); // expect(helper.getContentTableElement().querySelector('tbody tr:nth-child(2) td').textContent).toBe('Sports Shoes'); // expect((helper.getContentTableElement().querySelector('tbody tr:nth-child(3)') as any).ariaRowIndex).toBe('4'); // td = helper.invoke('getCell', [0, 3]); // expect(td.children[0].children[0].classList).toContain('e-filtered'); // expect(helper.getInstance().filterCollection[1].sheetIndex).toBe(2); // done(); // }, 30); // }, 20); // }); // }); // }); // }); // }); // it('Insert Column', (done: Function) => { // helper.invoke('insertColumn', [0, 1]); // setTimeout(() => { // let td: Element = helper.invoke('getCell', [0, 7]); // expect(td.children[0].children[0].classList).toContain('e-sortdesc-filter'); // expect(helper.getContentTableElement().querySelector('tbody tr:nth-child(2) td:nth-child(3)').textContent).toBe('Sports Shoes'); // expect((helper.getContentTableElement().querySelector('tbody tr:nth-child(3)') as any).ariaRowIndex).toBe('4'); // td = helper.invoke('getCell', [0, 5]); // expect(td.children[0].children[0].classList).toContain('e-filtered'); // expect(helper.getInstance().filterCollection[1].filterRange).toBe('C1:J11'); // helper.invoke('insertColumn', [3, 4]); // setTimeout(() => { // td = helper.invoke('getCell', [0, 9]); // expect(td.children[0].children[0].classList).toContain('e-sortdesc-filter'); // td = helper.invoke('getCell', [0, 7]); // expect(td.children[0].children[0].classList).toContain('e-filtered'); // expect(helper.getInstance().filterCollection[1].filterRange).toBe('C1:L11'); // done(); // }); // }); // }); // it('Delete Column', (done: Function) => { // helper.invoke('delete', [0, 1, 'Column']); // setTimeout(() => { // let td: Element = helper.invoke('getCell', [0, 7]); // expect(td.children[0].children[0].classList).toContain('e-sortdesc-filter'); // expect(helper.getContentTableElement().querySelector('tbody tr:nth-child(2) td').textContent).toBe('Sports Shoes'); // expect((helper.getContentTableElement().querySelector('tbody tr:nth-child(3)') as any).ariaRowIndex).toBe('4'); // td = helper.invoke('getCell', [0, 5]); // expect(td.children[0].children[0].classList).toContain('e-filtered'); // expect(helper.getInstance().filterCollection[1].filterRange).toBe('A1:J11'); // helper.invoke('delete', [1, 3, 'Column']); // setTimeout(() => { // td = helper.invoke('getCell', [0, 4]); // expect(td.children[0].children[0].classList).toContain('e-sortdesc-filter'); // td = helper.invoke('getCell', [0, 2]); // expect(td.children[0].children[0].classList).toContain('e-filtered'); // expect(helper.getInstance().filterCollection[1].filterRange).toBe('A1:G11'); // helper.invoke('delete', [2, 2, 'Column']); // setTimeout(() => { // expect(helper.getContentTableElement().querySelector('tbody tr:nth-child(2) td').textContent).toBe('Casual Shoes'); // expect((helper.getContentTableElement().querySelector('tbody tr:nth-child(3)') as any).ariaRowIndex).toBe('3'); // expect(helper.getInstance().filterCollection[1].column.length).toBe(0); // done(); // }); // }); // }); // }); // }); describe('I328009 ->', () => { let filterArgs: any; beforeAll((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }] }], actionComplete: (args: any): void => { if (args.action === 'filter') { filterArgs = args.eventArgs; } } }, done); }); afterAll(() => { helper.invoke('destroy'); }); it('Filter event argument checking', (done: Function) => { helper.invoke('selectRange', ['E2']); helper.getInstance().filterModule.filterByCellValueHandler(); setTimeout(() => { expect(JSON.stringify(filterArgs.predicates)).toBe(JSON.stringify(helper.getInstance().filterModule.filterCollection.get(0))); expect(filterArgs.range).toBe('A1:H11'); done(); }); }); }); describe('SF-360112 ->', () => { let filterArgs: any; beforeEach((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: filterData }] }] }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Script error while performing undo continuously after applying filters', (done: Function) => { const id: string = '#' + helper.id; helper.getElement(`${id}_sorting`).click(); helper.getElement(`${id}_applyfilter`).click(); expect(helper.invoke('getCell', [0, 0]).querySelector('.e-filter-iconbtn')).not.toBeNull(); helper.invoke('selectRange', ['G1']); helper.triggerKeyNativeEvent(40, false, false, null, 'keydown', true); setTimeout(() => { setTimeout(() => { const cbox: HTMLElement = helper.getElement('.e-checkboxlist').lastElementChild.querySelector('.e-checkbox-wrapper'); (cbox.querySelector('.e-chk-hidden') as HTMLInputElement).checked = false; classList(cbox.querySelector('.e-frame') as HTMLInputElement, ['e-uncheck'], ['e-check']); helper.getElement('.e-filter-popup .e-btn.e-primary').click(); setTimeout(() => { helper.triggerKeyNativeEvent(90, true); helper.triggerKeyNativeEvent(90); setTimeout(() => { helper.invoke('endEdit'); helper.triggerKeyNativeEvent(90, true); expect(helper.invoke('getCell', [0, 0]).querySelector('.e-filter-iconbtn')).toBeNull(); done(); }); }); }); }); }); }); describe('SF-361036, SF-361123 ->', () => { beforeAll((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }] }] }, done); }); afterAll(() => { helper.invoke('destroy'); }); it('Paste is not working on filtered rows', (done: Function) => { helper.invoke('applyFilter', [[{ field: 'E', predicate: 'or', operator: 'equal', value: '10' }, { field: 'E', predicate: 'or', operator: 'equal', value: '20' }], 'A1:H1']); setTimeout(() => { helper.invoke('copy', ['A9']).then(() => { helper.invoke('paste', ['A5']); setTimeout(() => { expect(helper.invoke('getCell', [4, 0]).textContent).toBe('Loafers'); expect(helper.invoke('getCell', [6, 0]).textContent).toBe('Sneakers'); done(); }); }); }); }); }); describe('SF-364894 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet( { sheets: [{ ranges: [{ dataSource: defaultData }], rowCount: 11 }], scrollSettings: { isFinite: true }, created: (): void => { helper.invoke('merge', ['A2:G2']); } }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Filtering is not proper in finite mode with less row count and merged cell', (done: Function) => { helper.invoke('applyFilter', [[{ field: 'F', predicate: 'or', operator: 'equal', value: '1210' }], 'A1:H11']); setTimeout(() => { expect(helper.invoke('getContentTable').rows.length).toBe(2); expect(helper.getInstance().viewport.bottomIndex).toBe(9); done(); }); }); }); describe('SF-367021 ->', () => { let spreadsheet: any; beforeEach((done: Function) => { helper.initializeSpreadsheet( { sheets: [{ ranges: [{ dataSource: defaultData }], selectedRange: 'B4:B4' }], created: (): void => { spreadsheet = helper.getInstance() for (let i: number = 1; i < 11; i++) { spreadsheet.updateCell({ format: 'dd/MM/yyyy' }, 'B' + (i + 1)); } } }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Filter by date cell value not working', (done: Function) => { spreadsheet.notify(filterByCellValue, null); setTimeout(() => { const predicates: any[] = spreadsheet.filterModule.filterCollection.get(0); expect(predicates.length).toBe(1); expect(predicates[0].field).toBe('B'); expect(spreadsheet.sheets[0].rows[1].hidden).toBeTruthy(); expect(spreadsheet.sheets[0].rows[1].isFiltered).toBeTruthy(); expect(helper.invoke('getContentTable').rows[1].cells[1].textContent).toBe('27/07/2014'); done(); }); }); }); describe('SF-368464 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }], frozenRows: 1, frozenColumns: 1, paneTopLeftCell: 'A1002' }] }, done); }); afterEach(() => { helper.invoke('destroy'); }); it('Filtering issue with freeze pane when the sheet is scrolled', (done: Function) => { const tableRowCount: number = helper.invoke('getContentTable').rows.length; helper.invoke('applyFilter', [[{ field: 'E', predicate: 'or', operator: 'equal', value: '10' }], 'A1:H1']); setTimeout(() => { expect(helper.invoke('getContentTable').rows.length).toBe(tableRowCount); done(); }); }); }); describe('SF-369477 ->', () => { let spreadsheet: any; beforeAll((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }], selectedRange: 'D7:D9', paneTopLeftCell: 'A7', frozenRows: 1 }] }, done); }); afterAll(() => { helper.invoke('destroy'); }); it('Cells jumbled up while filtering with freeze pane', (done: Function) => { spreadsheet = helper.getInstance(); expect(spreadsheet.sheets[0].topLeftCell).toBe('A1'); expect(spreadsheet.sheets[0].paneTopLeftCell).toBe('A7'); helper.triggerKeyNativeEvent(46); helper.invoke( 'applyFilter', [[{ field: 'D', matchCase: false, operator: 'notequal', predicate: 'and', value: null, ignoreAccent: false }, { field: 'D', matchCase: false, operator: 'notequal', predicate: 'and', value: undefined }], 'A1:H11']) setTimeout(() => { expect(spreadsheet.sheets[0].topLeftCell).toBe('A1'); expect(spreadsheet.sheets[0].paneTopLeftCell).toBe('A10'); done(); }); }); it('Apply filter in multiple column and clear filter using context menu', (done: Function) => { helper.invoke('selectRange', ['E2']); let predicates: any[] = [].slice.call(spreadsheet.filterModule.filterCollection.get(0)); predicates.push( { value: 10, field: 'E', predicate: 'and', operator: 'notequal', type: 'number', matchCase: false, ignoreAccent: false }); helper.invoke('applyFilter', [predicates, 'A1:H11']); setTimeout(() => { predicates = spreadsheet.filterModule.filterCollection.get(0); expect(predicates.length).toBe(3); expect(predicates[2].field).toBe('E'); expect(spreadsheet.sheets[0].rows[5].hidden).toBeTruthy(); expect(spreadsheet.sheets[0].rows[5].isFiltered).toBeTruthy(); expect(helper.invoke('getCell', [0, 4]).querySelector('.e-filter-icon').classList.contains('e-filtered')).toBeTruthy(); helper.setAnimationToNone('#spreadsheet_contextmenu'); const checkFn: Function = (): void => { expect(helper.getElement('#' + helper.id + '_cmenu_clearfilter').classList.contains('e-disabled')).toBeFalsy(); }; helper.openAndClickCMenuItem(4, 1, [6, 1], false, false, checkFn); setTimeout(() => { expect(spreadsheet.filterModule.filterCollection.get(0).length).toBe(2); expect(spreadsheet.sheets[0].rows[5].hidden).toBeFalsy(); expect(spreadsheet.sheets[0].rows[5].isFiltered).toBeFalsy(); expect(helper.invoke('getCell', [0, 4]).querySelector('.e-filter-icon').classList.contains('e-filtered')).toBeFalsy(); done(); }); }); }); it('Clear filter in final filtered column in a range using context menu', (done: Function) => { helper.invoke('selectRange', ['D2']); expect(helper.invoke('getCell', [0, 3]).querySelector('.e-filter-icon').classList.contains('e-filtered')).toBeTruthy(); helper.openAndClickCMenuItem(3, 1, [6, 1]); setTimeout(() => { expect(spreadsheet.filterModule.filterCollection.get(0).length).toBe(0); expect(spreadsheet.sheets[0].rows[6].hidden).toBeFalsy(); expect(spreadsheet.sheets[0].rows[6].isFiltered).toBeFalsy(); expect(helper.invoke('getCell', [0, 3]).querySelector('.e-filter-icon').classList.contains('e-filtered')).toBeFalsy(); done(); }); }); }); }); describe('Filter Icon Missing In Duplicate Sheet ->', () => { describe('EJ2-55527 ->', () => { beforeEach((done: Function) => { helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }] }] }, done); }); afterAll(() => { helper.invoke('destroy'); }); it('Filter issue in duplicate sheet', (done: Function) => { helper.invoke('applyFilter', [[{ field: 'A', predicate: 'or', operator: 'equal', value: 'Casual Shoes' }], 'A1:H11']); helper.invoke('duplicateSheet', [0]); setTimeout(() => { expect(helper.invoke("getCell",[0,0]).querySelector('span').classList).toContain('e-filtered'); expect(helper.getInstance().filterCollection[1].filterRange).toContain('A1:H11'); expect(JSON.stringify(helper.getInstance().filterModule.filterRange.get(1))).toBe('{"range":[0,0,10,7]}'); done(); }); }); }); }); });
the_stack
/// <reference types="node" /> export type ValueOfAnObservable<T extends Observable<any, any>> = T['']; export interface Subscription { unsubscribe(): void; readonly closed: boolean; } export interface Observer<T, S> { value?: ((value: T) => void) | undefined; error?: ((error: S) => void) | undefined; end?: (() => void) | undefined; } interface ESObserver<T, S> { start?: Function | undefined, next?: ((value: T) => any) | undefined, error?: ((error: S) => any) | undefined, complete?: (() => any) | undefined, } interface ESObservable<T, S> { subscribe(callbacks: ESObserver<T, S>): { unsubscribe(): void }; } export class Observable<T, S> { '': T; // TypeScript hack to enable value unwrapping for combine/flatMap toProperty(): Property<T, S>; toProperty<T2>(getCurrent?: () => T2): Property<T | T2, S>; changes(): Observable<T, S>; // Subscribe / add side effects onValue(callback: (value: T) => void): this; offValue(callback: (value: T) => void): this; onError(callback: (error: S) => void): this; offError(callback: (error: S) => void): this; onEnd(callback: () => void): this; offEnd(callback: () => void): this; onAny(callback: (event: Event<T, S>) => void): this; offAny(callback: (event: Event<T, S>) => void): this; log(name?: string): this; spy(name?: string): this; offLog(name?: string): this; offSpy(name?: string): this; flatten<U>(transformer?: (value: T) => U[]): Stream<U, S>; toPromise(): Promise<T>; toPromise<W extends PromiseLike<T>>(PromiseConstructor: () => W): W; toESObservable(): ESObservable<T, S>; // This method is designed to replace all other methods for subscribing observe(params: Observer<T, S>): Subscription; observe( onValue?: (value: T) => void, onError?: (error: S) => void, onEnd?: () => void ): Subscription; setName(source: Observable<any, any>, selfName: string): this; setName(selfName: string): this; thru<R>(cb: (obs: Observable<T, S>) => R): R; // Modify an stream map<U>(fn: (value: T) => U): Observable<U, S>; filter<U extends T>(fn: (value: T) => value is U): Observable<U, S> filter(predicate?: (value: T) => boolean): Observable<T, S>; take(n: number): Observable<T, S>; takeWhile(predicate?: (value: T) => boolean): Observable<T, S>; last(): Observable<T, S>; skip(n: number): Observable<T, S>; skipWhile(predicate?: (value: T) => boolean): Observable<T, S>; skipDuplicates(comparator?: (a: T, b: T) => boolean): Observable<T, S>; diff(fn?: (prev: T, next: T) => T, seed?: T): Observable<T, S>; scan<W>(fn: (prev: T | W, next: T) => W): Observable<W, S>; scan<W>(fn: (prev: W, next: T) => W, seed: W): Observable<W, S>; delay(wait: number): Observable<T, S>; throttle(wait: number, options?: { leading?: boolean | undefined, trailing?: boolean | undefined }): Observable<T, S>; debounce(wait: number, options?: { immediate: boolean }): Observable<T, S>; valuesToErrors(): Observable<never, S | T>; valuesToErrors<U>(handler: (value: T) => { convert: boolean, error: U }): Observable<never, S | U>; errorsToValues<U>(handler?: (error: S) => { convert: boolean, value: U }): Observable<T | U, never>; mapErrors<U>(fn: (error: S) => U): Observable<T, U>; filterErrors(predicate?: (error: S) => boolean): Observable<T, S>; endOnError(): Observable<T, S>; takeErrors(n: number): Observable<T, S>; ignoreValues(): Observable<never, S>; ignoreErrors(): Observable<T, never>; ignoreEnd(): Observable<T, S>; beforeEnd<U>(fn: () => U): Observable<T | U, S>; slidingWindow(max: number, mix?: number): Observable<T[], S>; bufferWhile(predicate: (value: T) => boolean): Observable<T[], S>; bufferWithCount(count: number, options?: { flushOnEnd: boolean }): Observable<T[], S>; bufferWithTimeOrCount(interval: number, count: number, options?: { flushOnEnd: boolean }): Observable<T[], S>; transduce<U>(transducer: any): Observable<U, S>; withHandler<U, V>(handler: (emitter: Emitter<U, V>, event: Event<T, S>) => void): Observable<U, V>; // Combine streams combine<U, V, W>(otherObs: Observable<U, V>, combinator?: (value: T, ...values: U[]) => W): Observable<W, S | V>; zip<U, V, W>(otherObs: Observable<U, V>, combinator?: (value: T, ...values: U[]) => W): Observable<W, S | V>; merge<U, V>(otherObs: Observable<U, V>): Observable<T | U, S | V>; concat<U, V>(otherObs: Observable<U, V>): Observable<T | U, S | V>; flatMap<U, V>(transform: (value: T) => Observable<U, V>): Observable<U, V | S>; flatMap<X extends T & Property<T, any>>(): Observable<ValueOfAnObservable<X>, any>; flatMapLatest<U, V>(fn: (value: T) => Observable<U, V>): Observable<U, V | S>; flatMapLatest<X extends T & Property<T, any>>(): Observable<ValueOfAnObservable<X>, any>; flatMapFirst<U, V>(fn: (value: T) => Observable<U, V>): Observable<U, V | S>; flatMapFirst<X extends T & Property<T, any>>(): Observable<ValueOfAnObservable<X>, any>; flatMapConcat<U, V>(fn: (value: T) => Observable<U, V>): Observable<U, V | S>; flatMapConcat<X extends T & Property<T, any>>(): Observable<ValueOfAnObservable<X>, any>; flatMapConcurLimit<U, V>(fn: (value: T) => Observable<U, V>, limit: number): Observable<U, V | S>; flatMapErrors<U, V>(transform: (error: S) => Observable<U, V>): Observable<U | T, V>; // Combine two streams filterBy<U>(otherObs: Observable<boolean, U>): Observable<T, S>; sampledBy(otherObs: Observable<any, any>): Observable<T, S>; sampledBy<U, W>(otherObs: Observable<U, any>, combinator: (a: T, b: U) => W): Observable<W, S>; skipUntilBy<U, V>(otherObs: Observable<U, V>): Observable<U, V>; takeUntilBy<U, V>(otherObs: Observable<U, V>): Observable<T, S>; bufferBy<U, V>(otherObs: Observable<U, V>, options?: { flushOnEnd: boolean }): Observable<T[], S>; bufferWhileBy<U>(otherObs: Observable<boolean, U>, options?: { flushOnEnd?: boolean | undefined, flushOnChange?: boolean | undefined }): Observable<T[], S>; awaiting<U, V>(otherObs: Observable<U, V>): Observable<boolean, S>; } export class Stream<T, S> extends Observable<T, S> { } export class Property<T, S> extends Observable<T, S> { } export class Pool<T, S> extends Observable<T, S> { plug(obs: Observable<T, S>): this; unplug(obs: Observable<T, S>): this; } export type Event<V,E> = { type: 'value', value: V } | { type: 'error', value: E } | { type: 'end', value: void }; export interface Emitter<V, E> { value(value: V): boolean; event(event: Event<V, E>): boolean; error(e: E): boolean; end(): void; // Deprecated methods emit(value: V): boolean; emitEvent(event: Event<V, E>): boolean; } // Create a stream export function never(): Stream<never, never>; export function later<T>(wait: number, value: T): Stream<T, never>; export function interval<T>(interval: number, value: T): Stream<T, never>; export function sequentially<T>(interval: number, values: T[]): Stream<T, never>; export function fromPoll<T>(interval: number, fn: () => T): Stream<T, never>; export function withInterval<T, S>(interval: number, handler: (emitter: Emitter<T, S>) => void): Stream<T, S>; export function fromCallback<T>(fn: (callback: (value: T) => void) => void): Stream<T, never>; export function fromNodeCallback<T, S>(fn: (callback: (error: S | null, result: T) => void) => void): Stream<T, S>; export function fromEvents<T, S>(target: EventTarget | NodeJS.EventEmitter | { on: Function, off: Function }, eventName: string, transform?: (value: T) => S): Stream<T, S>; export function stream<T, S>(subscribe: (emitter: Emitter<T, S>) => Function | void): Stream<T, S>; export function fromESObservable<T, S>(observable: any): Stream<T, S> // Create a property export function constant<T>(value: T): Property<T, never>; export function constantError<T>(error: T): Property<never, T>; export function fromPromise<T, S>(promise: Promise<T>): Property<T, S>; // Combine observables export function combine<T, S, U>(obss: Observable<T, S>[], passiveObss: Observable<T, S>[], combinator?: (...values: T[]) => U): Stream<U, S>; export function combine<T, S, U>(obss: Observable<T, S>[], combinator: (...values: T[]) => U): Stream<U, S>; export function combine<T extends { [name: string]: Observable<any, any> }>(obss: T): Stream<{ [P in keyof T]: ValueOfAnObservable<T[P]> }, any>; export function combine<T extends { [name: string]: Observable<any, any> }, K extends { [name: string]: Observable<any, any> }>(obss: T, passiveObss: K): Stream<{ [P in keyof T]: ValueOfAnObservable<T[P]> } & { [P in keyof K]: ValueOfAnObservable<K[P]> }, any>; export function combine<T extends [Observable<any, any>], P extends keyof T>(obss: T): Stream<[ValueOfAnObservable<T[0]>], any>; export function combine<T extends [Observable<any, any>, Observable<any, any>, Observable<any, any>, Observable<any, any>, Observable<any, any>, Observable<any, any>, Observable<any, any>, Observable<any, any>]>(obss: T): Stream<[ValueOfAnObservable<T[0]>, ValueOfAnObservable<T[1]>, ValueOfAnObservable<T[2]>, ValueOfAnObservable<T[3]>, ValueOfAnObservable<T[4]>, ValueOfAnObservable<T[5]>, ValueOfAnObservable<T[6]>, ValueOfAnObservable<T[7]>], any>; export function combine<T extends [Observable<any, any>, Observable<any, any>, Observable<any, any>, Observable<any, any>, Observable<any, any>, Observable<any, any>, Observable<any, any>]>(obss: T): Stream<[ValueOfAnObservable<T[0]>, ValueOfAnObservable<T[1]>, ValueOfAnObservable<T[2]>, ValueOfAnObservable<T[3]>, ValueOfAnObservable<T[4]>, ValueOfAnObservable<T[5]>, ValueOfAnObservable<T[6]>], any>; export function combine<T extends [Observable<any, any>, Observable<any, any>, Observable<any, any>, Observable<any, any>, Observable<any, any>, Observable<any, any>]>(obss: T): Stream<[ValueOfAnObservable<T[0]>, ValueOfAnObservable<T[1]>, ValueOfAnObservable<T[2]>, ValueOfAnObservable<T[3]>, ValueOfAnObservable<T[4]>, ValueOfAnObservable<T[5]>], any>; export function combine<T extends [Observable<any, any>, Observable<any, any>, Observable<any, any>, Observable<any, any>, Observable<any, any>]>(obss: T): Stream<[ValueOfAnObservable<T[0]>, ValueOfAnObservable<T[1]>, ValueOfAnObservable<T[2]>, ValueOfAnObservable<T[3]>, ValueOfAnObservable<T[4]>], any>; export function combine<T extends [Observable<any, any>, Observable<any, any>, Observable<any, any>, Observable<any, any>]>(obss: T): Stream<[ValueOfAnObservable<T[0]>, ValueOfAnObservable<T[1]>, ValueOfAnObservable<T[2]>, ValueOfAnObservable<T[3]>], any>; export function combine<T extends [Observable<any, any>, Observable<any, any>, Observable<any, any>]>(obss: T): Stream<[ValueOfAnObservable<T[0]>, ValueOfAnObservable<T[1]>, ValueOfAnObservable<T[2]>], any>; export function combine<T extends [Observable<any, any>, Observable<any, any>]>(obss: T): Stream<[ValueOfAnObservable<T[0]>, ValueOfAnObservable<T[1]>], any>; export function combine<T extends [Observable<any, any>]>(obss: T): Stream<[ValueOfAnObservable<T[0]>], any>; export function combine<T extends never[]>(obss: T): Stream<never, never>; export function combine<T extends[Observable<any, any>], P extends [Observable<any, any>], K>(obss: T, obssP: P, combinator: (a: T[0][''], b: P[0]['']) => K): Observable<K, any>; export function zip<T, S, U>(obss: Observable<T, S>[], passiveObss?: Observable<T, S>[], combinator?: (...values: T[]) => U): Observable<U, S>; export function merge<T, S>(obss: Observable<T, S>[]): Observable<T, S>; export function concat<T, S>(obss: Observable<T, S>[]): Observable<T, S>; export function pool<T, S>(): Pool<T, S>; export function repeat<T, S>(generator: (i: number) => Observable<T, S> | boolean): Observable<T, S>; export var staticLand: { Observable: { ap<A, B, E1, E2>(obsF: Observable<(x: A) => B, E1>, obsV: Observable<A, E2>): Observable<B, E1|E2>; bimap<V1, E1, V2, E2>(fnE: (x: E1) => E2, fnV: (x: V1) => V2, obs: Observable<V1, E1>): Observable<V2, E2>; chain<V, V2, E, E2>(cb: (value: V) => Observable<V2, E2>, s: Observable<V, E>): Observable<V2, E | E2>; concat<V1, E1, V2, E2>(obs1: Observable<V1, E1>, obs2: Observable<V2, E2>): Observable<V1 | V2, E1 | E2>; empty(): Observable<never, never>; map<V, V2, E>(cb: (value: V) => V2, s: Observable<V, E>): Observable<V2, E>; of<V>(value: V): Observable<V, never>; } } declare var kefir: { Observable: typeof Observable; Pool: typeof Pool; Stream: typeof Stream; Property: typeof Property; never: typeof never, later: typeof later, interval: typeof interval, sequentially: typeof sequentially, fromPoll: typeof fromPoll, withInterval: typeof withInterval, fromCallback: typeof fromCallback, fromNodeCallback: typeof fromNodeCallback, fromEvents: typeof fromEvents, stream: typeof stream, fromESObservable: typeof fromESObservable, constant: typeof constant, constantError: typeof constantError, fromPromise: typeof fromPromise, combine: typeof combine, zip: typeof zip, merge: typeof merge, concat: typeof concat, pool: typeof pool, repeat: typeof repeat, staticLand: typeof staticLand }; export default kefir;
the_stack
import { sp, SPBatch, SPRest } from "@pnp/sp"; import { testSettings } from "../main.js"; import { expect } from "chai"; import "@pnp/sp/lists"; import "@pnp/sp/content-types/list"; import "@pnp/sp/views/list"; import "@pnp/sp/folders/list"; import "@pnp/sp/fields/list"; import "@pnp/sp/forms/list"; import "@pnp/sp/items/list"; import "@pnp/sp/subscriptions/list"; import "@pnp/sp/user-custom-actions/list"; import { IList, IRenderListDataParameters, ControlMode, IListEnsureResult, ICamlQuery, IChangeLogItemQuery, RenderListDataOptions } from "@pnp/sp/lists"; import * as assert from "assert"; import { IConfigOptions, getRandomString } from "@pnp/common"; describe("Lists", function () { if (testSettings.enableWebTests) { it(".getById", function () { return expect(sp.web.lists.getByTitle("Documents").select("ID").get<{ Id: string }>().then((list) => { return sp.web.lists.getById(list.Id).select("Title").get(); })).to.eventually.have.property("Title", "Documents"); }); it(".getByTitle", async function () { return expect(sp.web.lists.getByTitle("Documents").select("Title").get()).to.eventually.be.fulfilled; }); it(".add 1", function () { const title = `pnp testing add 1 ${getRandomString(4)}`; return expect(sp.web.lists.add(title, title)).to.eventually.be.fulfilled; }); it(".add 2", function () { const title = `pnp testing add 2 ${getRandomString(4)}`; return expect(sp.web.lists.add(title, title, 101, true, <any>{ OnQuickLaunch: true })).to.eventually.be.fulfilled; }); it(".ensure", async function () { const title = "pnp testing ensure"; return expect(sp.web.lists.ensure(title)).to.eventually.be.fulfilled; }); it(".ensure with too long title", async function () { const title = getRandomString(512); return expect(sp.web.lists.ensure(title)).to.eventually.be.rejected; }); it(".ensure fail update already existing list", async function () { const title = "pnp testing ensure fail update already existing list"; await sp.web.lists.ensure(title); return expect(sp.web.lists.ensure(title, title, 100, false, <any>{ RandomPropertyThatDoesntExistOnObject: "RandomValue" })).to.eventually.be.rejected; }); it(".ensure with additional settings", async function () { const title = "pnp testing ensure with additional settings"; return expect(sp.web.lists.ensure(title, title, 101, true, <any>{ OnQuickLaunch: true })).to.eventually.be.fulfilled; }); it(".ensure existing list with additional settings", async function () { const title = "pnp testing ensure existing list with additional settings"; await sp.web.lists.ensure(title); return expect(sp.web.lists.ensure(title, title, 101, true, <any>{ OnQuickLaunch: true })).to.eventually.be.fulfilled; }); it(".ensure already existing list", async function () { const title = "pnp testing ensure"; await sp.web.lists.ensure(title); return expect(sp.web.lists.ensure(title)).to.eventually.be.fulfilled; }); it(".ensure with batch fails", async function () { const title = "pnp testing ensure"; const batch: SPBatch = sp.web.createBatch(); try { await sp.web.lists.inBatch(batch).ensure(title); } catch (e) { return assert(true); } return assert(false); }); it(".ensureSiteAssetsLibrary", function () { return expect(sp.web.lists.ensureSiteAssetsLibrary()).to.eventually.be.fulfilled; }); it(".ensureSitePagesLibrary", function () { return expect(sp.web.lists.ensureSitePagesLibrary()).to.eventually.be.fulfilled; }); } }); describe("List", function () { let list: IList; beforeEach(async () => { list = await sp.web.lists.getByTitle("Documents"); }); if (testSettings.enableWebTests) { it(".effectiveBasePermissions", async function () { const listEnsure: IListEnsureResult = await sp.web.lists.ensure("pnp testing effectiveBasePermissions"); return expect(listEnsure.list.effectiveBasePermissions.get()).to.eventually.be.fulfilled; }); it(".eventReceivers", async function () { const listEnsure: IListEnsureResult = await sp.web.lists.ensure("pnp testing eventReceivers"); return expect(listEnsure.list.eventReceivers.get()).to.eventually.be.fulfilled; }); it(".relatedFields", async function () { const listEnsure: IListEnsureResult = await sp.web.lists.ensure("pnp testing relatedFields"); return expect(listEnsure.list.relatedFields.get()).to.eventually.be.fulfilled; }); it(".informationRightsManagementSettings", async function () { const listEnsure: IListEnsureResult = await sp.web.lists.ensure("pnp testing informationRightsManagementSettings"); return expect(listEnsure.list.informationRightsManagementSettings.get()).to.eventually.be.fulfilled; }); it(".update", async function () { const listEnsure: IListEnsureResult = await sp.web.lists.ensure("pnp testing update"); const newTitle = "New title after update"; return expect(listEnsure.list.update({ Title: newTitle })).to.eventually.be.fulfilled; }); it(".update verbose", async function () { // config the node client to use verbose mode const verboseOptions: IConfigOptions = { headers: { "Accept": "application/json;odata=verbose", }, }; const spVerbose: SPRest = sp.configure(verboseOptions); const listEnsure: IListEnsureResult = await spVerbose.web.lists.ensure("pnp testing update verbose"); const newTitle = "New title after update"; return expect(listEnsure.list.update({ Title: newTitle })).to.eventually.be.fulfilled; }); it(".getChanges", async function () { const listEnsure: IListEnsureResult = await sp.web.lists.ensure("pnp testing getChanges"); return expect(listEnsure.list.getChanges({ Add: true, DeleteObject: true, Restore: true, })).to.eventually.be.fulfilled; }); it(".getItemsByCAMLQuery", async function () { const listEnsure: IListEnsureResult = await sp.web.lists.ensure("pnp testing getItemsByCAMLQuery"); const caml: ICamlQuery = { ViewXml: "<View><ViewFields><FieldRef Name='Title' /><FieldRef Name='RoleAssignments' /></ViewFields><RowLimit>5</RowLimit></View>", }; return expect(listEnsure.list.getItemsByCAMLQuery(caml, "RoleAssignments")).to.eventually.be.fulfilled; }); it(".getListItemChangesSinceToken", async function () { const listEnsure: IListEnsureResult = await sp.web.lists.ensure("pnp testing getListItemChangesSinceToken"); const query: IChangeLogItemQuery = { Contains: "<Contains><FieldRef Name=\"Title\"/><Value Type=\"Text\">Testing</Value></Contains>", QueryOptions: `<QueryOptions> <IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns> <DateInUtc>False</DateInUtc> <IncludePermissions>TRUE</IncludePermissions> <IncludeAttachmentUrls>FALSE</IncludeAttachmentUrls> <Folder>Shared Documents/Test1</Folder></QueryOptions>`, }; return expect(listEnsure.list.getListItemChangesSinceToken(query)).to.eventually.be.fulfilled; }); it(".recycle", async function () { const listEnsure: IListEnsureResult = await sp.web.lists.ensure("pnp testing recycle"); const recycleResponse = await listEnsure.list.recycle(); if (typeof recycleResponse !== "string") { throw Error("Expected a string returned from recycle."); } return expect(listEnsure.list.select("Title").get()).to.eventually.be.rejected; }); it(".recycle verbose", async function () { // config the node client to use verbose mode const verboseOptions: IConfigOptions = { headers: { "Accept": "application/json;odata=verbose", }, }; const spVerbose: SPRest = sp.configure(verboseOptions); const listEnsure: IListEnsureResult = await spVerbose.web.lists.ensure("pnp testing recycle"); const recycleResponse = await listEnsure.list.recycle(); if (typeof recycleResponse !== "string") { throw Error("Expected a string returned from recycle."); } return expect(listEnsure.list.select("Title").get()).to.eventually.be.rejected; }); it(".renderListData", async function () { const listEnsure: IListEnsureResult = await sp.web.lists.ensure("pnp testing renderListData"); await listEnsure.list.items.add({ Title: "Item 1", }); await listEnsure.list.items.add({ Title: "Item 2", }); await listEnsure.list.items.add({ Title: "Item 3", }); return expect(listEnsure.list.renderListData("<View><RowLimit>5</RowLimit></View>")).to.eventually.have.property("Row").that.is.not.empty; }); it(".renderListData verbose", async function () { // config the node client to use verbose mode const verboseOptions: IConfigOptions = { headers: { "Accept": "application/json;odata=verbose", }, }; const spVerbose: SPRest = sp.configure(verboseOptions); const listEnsure: IListEnsureResult = await spVerbose.web.lists.ensure("pnp testing renderListDataVerbose"); await listEnsure.list.items.add({ Title: "Item 1", }); await listEnsure.list.items.add({ Title: "Item 2", }); await listEnsure.list.items.add({ Title: "Item 3", }); return expect(listEnsure.list.renderListData("<View><RowLimit>5</RowLimit></View>")).to.eventually.be.fulfilled; }); const setupRenderListDataAsStream = async function (): Promise<IList> { const listEnsure: IListEnsureResult = await sp.web.lists.ensure("pnp testing renderListDataAsStream"); if (listEnsure.created) { await listEnsure.list.items.add({ Title: "Item 1", }); await listEnsure.list.items.add({ Title: "Item 2", }); await listEnsure.list.items.add({ Title: "Item 3", }); } return listEnsure.list; }; it(".renderListDataAsStream", async function () { const rList = await setupRenderListDataAsStream(); const renderListDataParams: IRenderListDataParameters = { ViewXml: "<View><RowLimit>5</RowLimit></View>", }; return expect(rList.renderListDataAsStream(renderListDataParams)).to.eventually.have.property("Row").that.is.not.empty; }); it(".renderListDataAsStream - advanced options", async function () { const rList = await setupRenderListDataAsStream(); const renderListDataParams: IRenderListDataParameters = { AddRequiredFields: true, RenderOptions: [ RenderListDataOptions.ContextInfo, RenderListDataOptions.ListSchema, RenderListDataOptions.MenuView, RenderListDataOptions.FileSystemItemId, RenderListDataOptions.QuickLaunch, RenderListDataOptions.Spotlight, RenderListDataOptions.Visualization, RenderListDataOptions.ViewMetadata, RenderListDataOptions.DisableAutoHyperlink, ], ViewXml: "<View><RowLimit>5</RowLimit></View>", }; return expect(rList.renderListDataAsStream(renderListDataParams)).to.eventually.be.fulfilled; }); it(".renderListDataAsStream - no override params", async function () { const rList = await setupRenderListDataAsStream(); const renderListDataParams: IRenderListDataParameters = { AddRequiredFields: true, ViewXml: "<View><RowLimit>5</RowLimit></View>", }; return expect(rList.renderListDataAsStream(renderListDataParams)).to.eventually.be.fulfilled; }); it(".renderListDataAsStream - query params", async function () { const rList = await setupRenderListDataAsStream(); const renderListDataParams: IRenderListDataParameters = { AddRequiredFields: false, ViewXml: "<View><RowLimit>5</RowLimit></View>", }; const r = await rList.renderListDataAsStream(renderListDataParams, {}, new Map([["FilterField1", "Title"], ["FilterValue1", encodeURIComponent("Item 2")]])); // eslint-disable-next-line @typescript-eslint/no-unused-expressions expect(r).to.not.be.null; expect(r.Row.length).to.eq(1); }); it(".renderListFormData", async function () { const listEnsure: IListEnsureResult = await sp.web.lists.ensure("pnp testing renderListFormData"); await listEnsure.list.items.add({ Title: "Item 1", }); return expect(listEnsure.list.renderListFormData(1, "editform", ControlMode.Edit)).to.be.eventually.fulfilled; }); it(".renderListFormData verbose", async function () { // config the node client to use verbose mode const verboseOptions: IConfigOptions = { headers: { "Accept": "application/json;odata=verbose", }, }; const spVerbose: SPRest = sp.configure(verboseOptions); const listEnsure: IListEnsureResult = await spVerbose.web.lists.ensure("pnp testing renderListFormData"); await listEnsure.list.items.add({ Title: "Item 1", }); return expect(listEnsure.list.renderListFormData(1, "editform", ControlMode.Edit)).to.be.eventually.fulfilled; }); it(".reserveListItemId", function () { return expect(list.reserveListItemId()).to.eventually.be.fulfilled; }); it(".reserveListItemId verbose", async function () { // config the node client to use verbose mode const verboseOptions: IConfigOptions = { headers: { "Accept": "application/json;odata=verbose", }, }; const spVerbose: SPRest = sp.configure(verboseOptions); const listEnsure: IListEnsureResult = await spVerbose.web.lists.ensure("pnp testing reserveListItemId verbose"); return expect(listEnsure.list.reserveListItemId()).to.eventually.be.fulfilled; }); it(".getListItemEntityTypeFullName", function () { return expect(list.getListItemEntityTypeFullName()).to.eventually.be.fulfilled; }); // Removing unit tests for failing and undocumented APIs that seem to no longer be supported. // it(".addValidateUpdateItemUsingPath", async function () { // const listTitle = "pnp-testing-addValidateUpdateItemUsingPath"; // const listAddRes = await sp.web.lists.ensure(listTitle); // const testList = await listAddRes.list.select("ParentWebUrl")<{ ParentWebUrl: string }>(); // const title = "PnPTest_ListAddValidateUpdateItemUsingPath"; // const formValues: IListItemFormUpdateValue[] = [ // { // FieldName: "Title", // FieldValue: title, // }, // ]; // const folderName = `PnPTestAddFolder2-${getRandomString(4)}`; // await listAddRes.list.rootFolder.folders.add(folderName); // return expect(listAddRes.list.addValidateUpdateItemUsingPath(formValues, // combine(testList.ParentWebUrl, "Lists", listTitle, folderName))).to.eventually.be.fulfilled; // }); // it(".addValidateUpdateItemUsingPath Folder", async function () { // const listTitle = "pnp-testing-addValidateUpdateItemUsingPath2"; // const listAddRes = await sp.web.lists.ensure(listTitle, "", 101); // const testList = await listAddRes.list.select("ParentWebUrl")<{ ParentWebUrl: string }>(); // const title = "PnPTest_ListAddValidateUpdateItemUsingPath"; // const formValues: IListItemFormUpdateValue[] = [ // { // FieldName: "Title", // FieldValue: title, // }, // ]; // return expect(listAddRes.list.addValidateUpdateItemUsingPath(formValues, // `${testList.ParentWebUrl}/${listTitle}`, true, "", { // leafName: "MyFolder", // objectType: 1, // })).to.eventually.be.fulfilled; // }); it(".contentTypes", function () { return expect(list.contentTypes()).to.eventually.be.fulfilled; }); it(".fields", function () { return expect(list.fields()).to.eventually.be.fulfilled; }); it(".rootFolder", function () { return expect(list.rootFolder()).to.eventually.be.fulfilled; }); it(".items", function () { return expect(list.items()).to.eventually.be.fulfilled; }); it(".views", async function () { const defaultView = await list.defaultView(); expect(list.getView(defaultView.Id)); return expect(list.views()).to.eventually.be.fulfilled; }); it(".subscriptions", function () { return expect(list.subscriptions()).to.eventually.be.fulfilled; }); it(".userCustomActions", function () { return expect(list.userCustomActions()).to.eventually.be.fulfilled; }); it(".delete", async function () { const result = await sp.web.lists.add("pnp testing delete"); return expect(result.list.delete()).to.eventually.be.fulfilled; }); } });
the_stack
import React, { ReactInstance } from 'react'; import ReactDOM from 'react-dom'; import cls from 'classnames'; import { isEqual } from 'lodash'; import PropTypes from 'prop-types'; import { IconClose } from '@douyinfe/semi-icons'; // eslint-disable-next-line max-len import CalendarFoundation, { CalendarAdapter, EventObject, MonthData, MonthlyEvent, ParsedEventsType, ParsedEventsWithArray, ParsedRangeEvent } from '@douyinfe/semi-foundation/calendar/foundation'; import { cssClasses } from '@douyinfe/semi-foundation/calendar/constants'; import { DateObj } from '@douyinfe/semi-foundation/calendar/eventUtil'; import LocaleConsumer from '../locale/localeConsumer'; import localeContext from '../locale/context'; import BaseComponent from '../_base/baseComponent'; import Popover from '../popover'; import Button from '../iconButton'; import { Locale } from '../locale/interface'; import { MonthCalendarProps } from './interface'; import '@douyinfe/semi-foundation/calendar/calendar.scss'; const toPercent = (num: number) => { const res = num < 1 ? num * 100 : 100; return `${res}%`; }; const prefixCls = `${cssClasses.PREFIX}-month`; const contentPadding = 60; const contentHeight = 24; export interface MonthCalendarState { itemLimit: number; showCard: Record<string, [boolean] | [boolean, string]>; parsedEvents: MonthlyEvent; cachedKeys: Array<string>; } export default class monthCalendar extends BaseComponent<MonthCalendarProps, MonthCalendarState> { static propTypes = { displayValue: PropTypes.instanceOf(Date), header: PropTypes.node, events: PropTypes.array, mode: PropTypes.string, markWeekend: PropTypes.bool, width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), style: PropTypes.object, className: PropTypes.string, dateGridRender: PropTypes.func, onClick: PropTypes.func, onClose: PropTypes.func, }; static defaultProps = { displayValue: new Date(), events: [] as EventObject[], mode: 'month', }; static contextType = localeContext; cellDom: React.RefObject<HTMLDivElement>; foundation: CalendarFoundation; cardRef: Map<string, ReactInstance>; contentCellHeight: number; monthlyData: MonthData; clickOutsideHandler: (e: MouseEvent) => void; constructor(props: MonthCalendarProps) { super(props); this.state = { itemLimit: 0, showCard: {}, parsedEvents: {} as MonthlyEvent, cachedKeys: [] }; this.cellDom = React.createRef(); this.foundation = new CalendarFoundation(this.adapter); this.handleClick = this.handleClick.bind(this); this.cardRef = new Map(); } get adapter(): CalendarAdapter<MonthCalendarProps, MonthCalendarState> { return { ...super.adapter, registerClickOutsideHandler: (key: string, cb: () => void) => { const clickOutsideHandler = (e: MouseEvent) => { const cardInstance = this.cardRef && this.cardRef.get(key); // eslint-disable-next-line react/no-find-dom-node const cardDom = ReactDOM.findDOMNode(cardInstance); if (cardDom && !cardDom.contains(e.target as any)) { cb(); } }; this.clickOutsideHandler = clickOutsideHandler; document.addEventListener('mousedown', clickOutsideHandler, false); }, unregisterClickOutsideHandler: () => { document.removeEventListener('mousedown', this.clickOutsideHandler, false); }, setMonthlyData: data => { this.monthlyData = data; }, getMonthlyData: () => this.monthlyData, notifyClose: (e, key) => { const updates = {}; updates[key] = [false]; this.setState(prevState => ({ showCard: { ...prevState.showCard, ...updates } })); this.props.onClose && this.props.onClose(e); }, openCard: (key, spacing) => { const updates = {}; const pos = spacing ? 'leftTopOver' : 'rightTopOver'; updates[key] = [true, pos]; this.setState(prevState => ({ showCard: { ...updates } })); }, setParsedEvents: (parsedEvents: ParsedEventsType) => { this.setState({ parsedEvents: parsedEvents as MonthlyEvent }); }, setItemLimit: itemLimit => { this.setState({ itemLimit }); }, cacheEventKeys: cachedKeys => { this.setState({ cachedKeys }); } }; } calcItemLimit = () => { this.contentCellHeight = this.cellDom.current.getBoundingClientRect().height; return Math.max(0, Math.ceil((this.contentCellHeight - contentPadding) / contentHeight)); }; componentDidMount() { this.foundation.init(); const itemLimit = this.calcItemLimit(); this.foundation.parseMonthlyEvents(itemLimit); } componentWillUnmount() { this.foundation.destroy(); } componentDidUpdate(prevProps: MonthCalendarProps, prevState: MonthCalendarState) { const prevEventKeys = prevState.cachedKeys; const nowEventKeys = this.props.events.map(event => event.key); let itemLimitUpdate = false; let { itemLimit } = this.state; if (prevProps.height !== this.props.height) { itemLimit = this.calcItemLimit(); if (prevState.itemLimit !== itemLimit) { itemLimitUpdate = true; } } if (!isEqual(prevEventKeys, nowEventKeys) || itemLimitUpdate) { this.foundation.parseMonthlyEvents((itemLimit || this.props.events) as any); } } handleClick = (e: React.MouseEvent, val: [Date]) => { const { onClick } = this.props; const value = this.foundation.formatCbValue(val); onClick && onClick(e, value); }; closeCard(e: React.MouseEvent, key: string) { this.foundation.closeCard(e, key); } showCard = (e: React.MouseEvent, key: string) => { this.foundation.showCard(e, key); }; renderHeader = (dateFnsLocale: Locale['dateFnsLocale']) => { const { markWeekend, displayValue } = this.props; this.monthlyData = this.foundation.getMonthlyData(displayValue, dateFnsLocale); return ( <div className={`${prefixCls}-header`} role="presentation"> <div role="presentation" className={`${prefixCls}-grid`}> <ul role="row" className={`${prefixCls}-grid-row`}> {this.monthlyData[0].map(day => { const { weekday } = day; const listCls = cls({ [`${cssClasses.PREFIX}-weekend`]: markWeekend && day.isWeekend, }); return ( <li role="columnheader" aria-label={weekday} key={`${weekday}-monthheader`} className={listCls}> <span>{weekday}</span> </li> ); })} </ul> </div> </div> ); }; renderEvents = (events: ParsedRangeEvent[]) => { if (!events) { return undefined; } const list = events.map((event, ind) => { const { leftPos, width, topInd, key, children } = event; const style = { left: toPercent(leftPos), width: toPercent(width), top: `${topInd}em` }; return ( <li className={`${cssClasses.PREFIX}-event-item ${cssClasses.PREFIX}-event-month`} key={key || `${ind}-monthevent`} style={style} > {children} </li> ); }); return list; }; renderCollapsed = (events: MonthlyEvent['day'][number], itemInfo: DateObj, listCls: string, month: string) => { const { itemLimit, showCard } = this.state; const { weekday, dayString, date } = itemInfo; const key = date.toString(); const remained = events.filter(i => Boolean(i)).length - itemLimit; const cardCls = `${prefixCls}-event-card`; // const top = contentPadding / 2 + this.state.itemLimit * contentHeight; const shouldRenderCard = remained > 0; const closer = ( <Button className={`${cardCls}-close`} onClick={e => this.closeCard(e, key)} type="tertiary" icon={<IconClose />} theme="borderless" size="small" /> ); const header = ( <div className={`${cardCls}-header-info`}> <div className={`${cardCls}-header-info-weekday`}>{weekday}</div> <div className={`${cardCls}-header-info-date`}>{dayString}</div> </div> ); const content = ( <div className={cardCls}> <div className={`${cardCls}-content`}> <div className={`${cardCls}-header`}> {header} {closer} </div> <div className={`${cardCls}-body`}> <ul className={`${cardCls}-list`}> {events.map(item => ( <li key={item.key || `${item.start.toString()}-event`}>{item.children}</li> ))} </ul> </div> </div> </div> ); const pos = showCard && showCard[key] ? showCard[key][1] : 'leftTopOver'; const text = ( <LocaleConsumer componentName="Calendar"> {(locale: Locale['Calendar']) => (// eslint-disable-next-line jsx-a11y/no-static-element-interactions <div className={`${cardCls}-wrapper`} style={{ bottom: 0 }} onClick={e => this.showCard(e, key)} > {locale.remaining.replace('${remained}', String(remained))} </div> )} </LocaleConsumer> ); return ( <Popover key={`${date.valueOf()}`} content={content} position={pos as any} trigger="custom" visible={showCard && showCard[key] && showCard[key][0]} ref={ref => this.cardRef.set(key, ref)} > <li key={date as any} className={listCls} onClick={e => this.handleClick(e, [date])}> {this.formatDayString(month, dayString)} {shouldRenderCard ? text : null} {this.renderCusDateGrid(date)} </li> </Popover> ); }; formatDayString = (month: string, date: string) => { if (date === '1') { return ( <LocaleConsumer componentName="Calendar"> {(locale: Locale['Calendar'], localeCode: string) => ( <span className={`${prefixCls}-date`}> {month} <span className={`${cssClasses.PREFIX}-today-date`}>&nbsp;{date}</span> {locale.datestring} </span> )} </LocaleConsumer> ); } return ( // eslint-disable-next-line max-len <span className={`${prefixCls}-date`}><span className={`${cssClasses.PREFIX}-today-date`}>{date}</span></span> ); }; renderCusDateGrid = (date: Date) => { const { dateGridRender } = this.props; if (!dateGridRender) { return null; } return dateGridRender(date.toString(), date); }; renderWeekRow = (index: number | string, weekDay: MonthData[number], events: MonthlyEvent = {} as MonthlyEvent) => { const { markWeekend } = this.props; const { itemLimit } = this.state; const { display, day } = events; return ( <div role="presentation" className={`${prefixCls}-weekrow`} ref={this.cellDom} key={`${index}-weekrow`}> <ul role="row" className={`${prefixCls}-skeleton`}> {weekDay.map(each => { const { date, dayString, isToday, isSameMonth, isWeekend, month, ind } = each; const listCls = cls({ [`${cssClasses.PREFIX}-today`]: isToday, [`${cssClasses.PREFIX}-weekend`]: markWeekend && isWeekend, [`${prefixCls}-same`]: isSameMonth }); const shouldRenderCollapsed = Boolean(day && day[ind] && day[ind].length > itemLimit); const inner = ( <li role="gridcell" aria-label={date.toLocaleDateString()} aria-current={isToday ? "date" : false} key={`${date}-weeksk`} className={listCls} onClick={e => this.handleClick(e, [date])}> {this.formatDayString(month, dayString)} {this.renderCusDateGrid(date)} </li> ); if (!shouldRenderCollapsed) { return inner; } return this.renderCollapsed(day[ind], each, listCls, month); })} </ul> <ul className={`${cssClasses.PREFIX}-event-items`}> {display ? this.renderEvents(display) : null} </ul> </div> ); }; renderMonthGrid = () => { const { parsedEvents } = this.state; return ( <div role="presentation" className={`${prefixCls}-week`}> <ul role="presentation" className={`${prefixCls}-grid-col`}> {Object.keys(this.monthlyData).map(weekInd => this.renderWeekRow(weekInd, this.monthlyData[weekInd], parsedEvents[weekInd]) )} </ul> </div> ); }; render() { const { className, height, width, style, header } = this.props; const monthCls = cls(prefixCls, className); const monthStyle = { height, width, ...style, }; return ( <LocaleConsumer componentName="Calendar"> {(locale: Locale['Calendar'], localeCode: string, dateFnsLocale: Locale['dateFnsLocale']) => ( <div role="grid" className={monthCls} key={this.state.itemLimit} style={monthStyle}> <div role="presentation" className={`${prefixCls}-sticky-top`}> {header} {this.renderHeader(dateFnsLocale)} </div> <div role="presentation" className={`${prefixCls}-grid-wrapper`}> {this.renderMonthGrid()} </div> </div> )} </LocaleConsumer> ); } }
the_stack
import React, { useState } from "react"; import { StyleSheet, Share, Platform, LayoutAnimation, ScrollView, TouchableOpacity } from "react-native"; import DialogAndroid from "react-native-dialogs"; import Clipboard from "@react-native-community/clipboard"; import { Card, Text, CardItem, H1, View, Button, Icon } from "native-base"; import { fromUnixTime } from "date-fns"; import MapView, { PROVIDER_DEFAULT } from "react-native-maps"; import Blurmodal from "../components/BlurModal"; import QrCode from "../components/QrCode"; import { capitalize, formatISO, isLong, decryptLNURLPayAesTagMessage, toast, bytesToHexString } from "../utils"; import { formatBitcoin } from "../utils/bitcoin-units" import { useStoreState, useStoreActions } from "../state/store"; import { extractDescription } from "../utils/NameDesc"; import { smallScreen } from "../utils/device"; import CopyAddress from "../components/CopyAddress"; import { MapStyle } from "../utils/google-maps"; import TextLink from "../components/TextLink"; import { ITransaction } from "../storage/database/transaction"; import { blixtTheme } from ".././native-base-theme/variables/commonColor"; import { PLATFORM } from "../utils/constants"; import { Alert } from "../utils/alert"; interface IMetaDataProps { title: string; data: string; url?: string; } function MetaData({ title, data, url }: IMetaDataProps) { return ( <Text style={style.detailText} onPress={() => { Clipboard.setString(data); toast("Copied to clipboard", undefined, "warning"); }} > <Text style={{ fontWeight: "bold" }}>{title}:{"\n"}</Text> {!url && data} {url && <TextLink url={url}>{data}</TextLink>} </Text> ); }; function MetaDataLightningAddress({ title, data: lightningAddress, url }: IMetaDataProps) { const getContactByLightningAddress = useStoreState((actions) => actions.contacts.getContactByLightningAddress); const syncContact = useStoreActions((actions) => actions.contacts.syncContact); const promptLightningAddressContact = () => { if (!lightningAddress) { return; } if (getContactByLightningAddress(lightningAddress)) { Alert.alert("",`${lightningAddress} is in your contact list!`); } else { Alert.alert( "Add to Contact List", `Would you like to add ${lightningAddress} to your contact list?`, [{ text: "No", style: "cancel", }, { text: "Yes", style: "default", onPress: async () => { console.log(lightningAddress); const domain = lightningAddress.split("@")[1] ?? ""; console.log(domain); syncContact({ type: "PERSON", domain, lnUrlPay: null, lnUrlWithdraw: null, lightningAddress: lightningAddress, lud16IdentifierMimeType: "text/identifier", note: "", }); }, }], ); } }; return ( <Text style={[style.detailText, {}]} onPress={() => { Clipboard.setString(lightningAddress); toast("Copied to clipboard", undefined, "warning"); }} > <Text style={{ fontWeight: "bold" }}>{title}:{"\n"}</Text> {lightningAddress} <TouchableOpacity onPress={promptLightningAddressContact} style={{justifyContent:"center", paddingLeft: 10, paddingRight: 15 }}> <Icon onPress={promptLightningAddressContact} style={{ fontSize: 22, marginBottom: -6 }} type="AntDesign" name={getContactByLightningAddress(lightningAddress) !== undefined ? "check" : "adduser"} /> </TouchableOpacity> </Text> ); }; export interface ITransactionDetailsProps { navigation: any; route: any; } export default function TransactionDetails({ route, navigation }: ITransactionDetailsProps) { const rHash: string = route.params.rHash; const transaction = useStoreState((store) => store.transaction.getTransactionByRHash(rHash)); const checkOpenTransactions = useStoreActions((store) => store.transaction.checkOpenTransactions); const cancelInvoice = useStoreActions((store) => store.receive.cancelInvoice); const bitcoinUnit = useStoreState((store) => store.settings.bitcoinUnit); const transactionGeolocationMapStyle = useStoreState((store) => store.settings.transactionGeolocationMapStyle); const [mapActive, setMapActive] = useState(false); const syncTransaction = useStoreActions((store) => store.transaction.syncTransaction); const [currentScreen, setCurrentScreen] = useState<"Overview" | "Map">("Overview"); if (!transaction) { console.log("No transaction"); return (<></>); } const { name, description } = extractDescription(transaction.description); const onQrPress = async () => { await Share.share({ message: "lightning:" + transaction.paymentRequest, }); }; const onPaymentRequestTextPress = () => { Clipboard.setString(transaction.paymentRequest); toast("Copied to clipboard", undefined, "warning"); }; const onPressCancelInvoice = async () => { // There's a LayoutAnimation.configureNext() in the Transaction store // to animate the removal of the invoice if hideArchivedInvoices is `true`. // React Native cannot figure out which component(s) should have an // animation as both the navigation will pop and the invoice // will be removed at approximately the same time. // So we delay the cancellation for 35ms. setTimeout(async () => { await cancelInvoice({ rHash: transaction.rHash }); await checkOpenTransactions(); }, 35); navigation.pop(); }; const onPressSetNote = async () => { if (PLATFORM === "android") { const result = await DialogAndroid.prompt(null, "Set a note for this transaction", { defaultValue: transaction.note, }); if (result.action === DialogAndroid.actionPositive) { await syncTransaction({ ...transaction, note: result.text?.trim() || null, }); } } else { Alert.prompt( "Note", "Set a note for this transaction", async (text) => { await syncTransaction({ ...transaction, note: text || null, }); }, "plain-text", transaction.note ?? undefined, ) } } let transactionValue: Long; let direction: "send" | "receive"; if (isLong(transaction.value) && transaction.value.greaterThanOrEqual(0)) { direction = "receive"; transactionValue = transaction.value; } else { direction = "send"; transactionValue = transaction.value; } const hasCoordinates = transaction.locationLat && transaction.locationLong; if (currentScreen === "Overview") { return ( <Blurmodal goBackByClickingOutside={true}> <Card style={style.card}> <CardItem> <ScrollView alwaysBounceVertical={false}> <View style={{ display: "flex", flexDirection: "row", justifyContent: "space-between", width: "100%" }}> <H1 style={style.header}> Transaction </H1> </View> <View style={{ flexDirection: "row", marginTop: 5, marginBottom: 10 }}> <Button small style={style.actionBarButton} onPress={onPressSetNote}> <Text>Set note</Text> </Button> {transaction.status === "OPEN" && <Button small danger onPress={onPressCancelInvoice} style={style.actionBarButton}> <Text>Cancel invoice</Text> </Button> } {hasCoordinates && <Button small={true} onPress={() => { LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut); setCurrentScreen("Map"); setTimeout(() => { setMapActive(true); }, 750); }} style={style.actionBarButton}> <Text>Show map</Text> </Button> } </View> <MetaData title="Date" data={formatISO(fromUnixTime(transaction.date.toNumber()))} /> {transaction.note && <MetaData title="Note" data={transaction.note} />} {transaction.website && <MetaData title="Website" data={transaction.website} url={"https://" + transaction.website} />} {transaction.type !== "NORMAL" && <MetaData title="Type" data={transaction.type} />} {(transaction.type === "LNURL" && transaction.lnurlPayResponse && transaction.lnurlPayResponse.successAction) && <LNURLMetaData transaction={transaction} />} {(transaction.nodeAliasCached && name === null) && <MetaData title="Node alias" data={transaction.nodeAliasCached} />} {direction === "send" && transaction.lightningAddress && <MetaDataLightningAddress title="Lightning Address" data={transaction.lightningAddress} />} {direction === "receive" && !transaction.tlvRecordName && transaction.payer && <MetaData title="Payer" data={transaction.payer} />} {direction === "receive" && transaction.tlvRecordName && <MetaData title="Payer" data={transaction.tlvRecordName} />} {(direction === "send" && name) && <MetaData title="Recipient" data={name} />} {(description !== null && description.length > 0) && <MetaData title="Description" data={description} />} <MetaData title="Amount" data={formatBitcoin(transactionValue, bitcoinUnit)} /> {transaction.valueFiat != null && transaction.valueFiatCurrency && <MetaData title="Amount in Fiat (Time of Payment)" data={`${transaction.valueFiat.toFixed(2)} ${transaction.valueFiatCurrency}`} />} {transaction.fee !== null && transaction.fee !== undefined && <MetaData title="Fee" data={transaction.fee.toString() + " Satoshi"} />} {transaction.hops && transaction.hops.length > 0 && <MetaData title="Number of hops" data={transaction.hops.length.toString()} />} {direction === "send" && <MetaData title="Remote pubkey" data={transaction.remotePubkey} />} <MetaData title="Payment hash" data={transaction.rHash}/> {transaction.status === "SETTLED" && transaction.preimage && <MetaData title="Preimage" data={bytesToHexString(transaction.preimage)}/>} <MetaData title="Status" data={capitalize(transaction.status)} /> {transaction.status === "OPEN" && transaction.type !== "LNURL" && <> <View style={{ width: "100%", alignItems: "center", justifyContent: "center" }}> <QrCode size={smallScreen ? 220 : 280} data={transaction.paymentRequest.toUpperCase()} onPress={onQrPress} border={25} /> </View> <CopyAddress text={transaction.paymentRequest} onPress={onPaymentRequestTextPress} /> </> } </ScrollView> </CardItem> </Card> </Blurmodal> ); } else if (currentScreen === "Map") { return ( <Blurmodal> <Card style={style.card}> <CardItem> <ScrollView alwaysBounceVertical={false}> <View style={{ marginBottom: 8, display: "flex", flexDirection: "row", justifyContent: "space-between", alignItems: "center", width: "100%" }}> <H1 style={style.header}> Transaction </H1> <Button small={true} onPress={() => { LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut); setCurrentScreen("Overview"); setMapActive(false); }}> <Text style={{ fontSize: 9 }}>Go back</Text> </Button> </View> <MapView provider={PROVIDER_DEFAULT} style={{ width: "100%", height: 475, backgroundColor:blixtTheme.gray, opacity: mapActive ? 1 : 0, }} initialRegion={{ longitude: transaction.locationLong!, latitude: transaction.locationLat!, latitudeDelta: 0.00622, longitudeDelta: 0.00251, }} customMapStyle={MapStyle[transactionGeolocationMapStyle]} > <MapView.Marker coordinate={{ longitude: transaction.locationLong!, latitude: transaction.locationLat!, }} /> </MapView> </ScrollView> </CardItem> </Card> </Blurmodal> ); } }; interface IWebLNMetaDataProps { transaction: ITransaction; } function LNURLMetaData({ transaction }: IWebLNMetaDataProps) { let secretMessage: string | null = null; if (transaction.lnurlPayResponse?.successAction?.tag === "aes") { secretMessage = decryptLNURLPayAesTagMessage( transaction.preimage, transaction.lnurlPayResponse.successAction.iv, transaction.lnurlPayResponse.successAction.ciphertext, ); } return ( <> {transaction.lnurlPayResponse?.successAction?.tag === "message" && <MetaData title={`Message from ${transaction.website}`} data={transaction.lnurlPayResponse.successAction.message} /> } {transaction.lnurlPayResponse?.successAction?.tag === "url" && <> <MetaData title={`Messsage from ${transaction.website}`} data={transaction.lnurlPayResponse.successAction.description} /> <MetaData title={`URL received from ${transaction.website}`} data={transaction.lnurlPayResponse.successAction.url} url={transaction.lnurlPayResponse.successAction.url} /> </> } {transaction.lnurlPayResponse?.successAction?.tag === "aes" && <> <MetaData title={`Messsage from ${transaction.website}`} data={transaction.lnurlPayResponse.successAction.description} /> <MetaData title="Secret Message" data={secretMessage!} /> </> } </> ); } const style = StyleSheet.create({ card: { padding: 5, minHeight: PLATFORM !== "web" ? "50%" : undefined, maxHeight: PLATFORM !== "web" ? "85%" : undefined, overflow: "hidden", }, header: { fontWeight: "bold", }, detailText: { marginBottom: 7, ...Platform.select({ web: { wordBreak: "break-all" }, }), }, qrText: { marginBottom: 7, paddingTop: 4, paddingLeft: 18, paddingRight: 18, }, actionBarButton: { marginLeft: 7, } });
the_stack
declare namespace GoogleAdsScripts { namespace AdsApp { /** * Represents an ad customizer data item. * Each ad customizer item can be seen as one row in an ad customizer source in the Business Data section of the Shared Library. * Ad customizer items have attribute values, which are values that correspond to the attributes of the item's source (see `AdCustomizerSource`). * These values can be substituted into an ad with placeholders of the form `{=SourceName.AttributeName}`. * Refer to the feature guide for more information. */ interface AdCustomizerItem { /** Clears the ad customizer item's end date. */ clearEndDate(): void; /** Clears the ad customizer item's start date. */ clearStartDate(): void; /** Clears the set target ad group and campaign. */ clearTargetAdGroup(): void; /** Clears the set target campaign. */ clearTargetCampaign(): void; /** Clears the set target keyword. */ clearTargetKeyword(): void; /** Returns the value of the named attribute. */ getAttributeValue(name: string): any; /** Returns a map from attribute name to attribute value. */ getAttributeValues(): Record<string, string | number>; /** Returns the end date of the ad customizer item, or null if no end date is set. */ getEndDate(): GoogleAdsDate; /** Clears the ad customizer item's end date. */ getEntityType(): string; /** Clears the ad customizer item's end date. */ getId(): number; /** Clears the ad customizer item's end date. */ getSchedules(): ExtensionSchedule[]; /** Clears the ad customizer item's end date. */ getStartDate(): GoogleAdsDate; /** Clears the ad customizer item's end date. */ getTargetAdGroupName(): string; /** Clears the ad customizer item's end date. */ getTargetCampaignName(): string; /** Clears the ad customizer item's end date. */ getTargetKeywordText(): string; /** Clears the ad customizer item's end date. */ isMobilePreferred(): boolean; /** Clears the ad customizer item's end date. */ remove(): void; /** Clears the ad customizer item's end date. */ setAttributeValue(name: string, value: any): void; /** Clears the ad customizer item's end date. */ setAttributeValues(attributes: any): void; /** Clears the ad customizer item's end date. */ setEndDate(date: string | GoogleAdsDate): void; /** Clears the ad customizer item's end date. */ setMobilePreferred(isMobilePreferred: boolean): void; /** Clears the ad customizer item's end date. */ setSchedules(schedules: any[]): void; /** Clears the ad customizer item's end date. */ setStartDate(date: string | GoogleAdsDate): void; /** Clears the ad customizer item's end date. */ setTargetAdGroup(campaignName: string, adGroupName: string): void; /** Clears the ad customizer item's end date. */ setTargetCampaign(campaignName: string): void; /** Clears the ad customizer item's end date. */ setTargetKeyword(keywordText: string): void; } /** * Builder for AdCustomizerItem objects. Example usage: * * adCustomizerSource.adCustomizerItemBuilder() * .withAttributeValues({numLeft: 5, lowCost: "$0.99"}) // at least one value is required * .withTargetCampaign("Campaign name") // * .withTargetKeyword("[keyword]") // optional * .withMobilePreferred(true) // optional * .build(); // create the ad customizer item */ interface AdCustomizerItemBuilder extends Base.Builder<AdCustomizerItemOperation> { /** Sets the value of the named attribute of the ad customizer item. */ withAttributeValue(name: string, value: string | number | null): this; /** * Sets the values of the ad customizer item's attributes. * Expects an object containing the name-value pairs of the attribute values to set. For instance, * `adCustomizerItemBuilder.withAttributeValues({numLeft: 5, lowCost: "$0.99"})` sets the attribute `numLeft` to have the value `5`, * and `lowCost` to have value `"$0.99"`. */ withAttributeValues(attributeValues: Record<string, string | number | null>): this; /** * Sets the ad customizer item's end date from either an object containing year, month, and day fields, or an 8-digit string in YYYYMMDD format. * This field is optional. */ withEndDate(date: string | GoogleAdsDate): this; /** * Sets the ad customizer item's end date from either an object containing year, month, and day fields, or an 8-digit string in YYYYMMDD format. * This field is optional. * @param isMobilePreferred Whether or not this ad customizer item should be mobile preferred. If true is passed in, device preference will be set to mobile. * If false is passed in, device preference will be set to none. */ withMobilePreferred(isMobilePreferred: boolean): this; /** * Sets the ad customizer item scheduling. Scheduling of a ad customizer item allows you to control the days of week and times of day during which * the ad customizer item will show alongside your ads. * Passing in an empty array clears the scheduling field, causing the ad customizer item to run at all times. * * The following example sets the ad customizer item to run on Mondays and Tuesday from 8:00 to 11:00. * * * var mondayMorning = { * dayOfWeek: "MONDAY", * startHour: 8, * startMinute: 0, * endHour: 11, * endMinute: 0 * }; * var tuesdayMorning = { * dayOfWeek: "TUESDAY", * startHour: 8, * startMinute: 0, * endHour: 11, * endMinute: 0 * }; * * adCustomizerItemBuilder.withSchedules([mondayMorning, tuesdayMorning]); */ withSchedules(schedules: ExtensionSchedule[]): this; /** Sets the ad customizer item's start date from either an object containing year, month, and day fields, or an 8-digit string in YYYYMMDD format. This field is optional. */ withStartDate(date: string | GoogleAdsDate): this; /** Sets the target ad group and campaign of the new ad customizer item. This will fail if there were any previous calls to `withTargetCampaign("previous campaign")`. */ withTargetAdGroup(campaignName: string, adGroupName: string): this; /** Sets the target campaign of the new ad customizer item. This will fail if there were any previous calls to `withTargetAdGroup("previous ad group", "campaign")`. */ withTargetCampaign(campaignName: string): this; /** * Sets the target keyword of the new ad customizer item. * The keyword includes its match type. * For instance, `adCustomizerItemBuilder.withTargetKeyword("[shoes]");` will target exact matches to "shoes". * Setting the target keyword to one that does not yet exist in your account will not cause an error, but will prevent the ad customizer item from being used to populate ads * (until you create the keyword in your account). */ withTargetKeyword(keyword: string): this; } /** * An iterator of ad customizer items. * Typical usage: * * while (adCustomizerItemIterator.hasNext()) { * var adCustomizerItem = adCustomizerItemIterator.next(); * } */ interface AdCustomizerItemIterator extends Base.Iterator<AdCustomizerItem> {} /** * An operation representing creation of a new ad customizer item. * Calling any method (getErrors, getResult, or isSuccessful) will cause the operation to execute and create the ad customizer item. * To make the script more efficient, it's recommended that you store the operations in an array and only call these methods once you've constructed all the operations you want. */ interface AdCustomizerItemOperation extends Base.Operation<AdCustomizerItem> {} /** * Fetches ad customizer items. Supports filtering and sorting. * Typical usage: * * var adCustomizerItemSelector = adCustomizerSource * .items() * .withCondition("Impressions > 100") * .forDateRange("LAST_MONTH") * .orderBy("Clicks DESC"); * * var adCustomizerItemIterator = adCustomizerItemSelector.get(); * while (adCustomizerItemIterator.hasNext()) { * var adCustomizerItem = adCustomizerItemIterator.next(); * } */ interface AdCustomizerItemSelector extends Base.Selector<AdCustomizerItemIterator>, Base.SelectorWithCondition, Base.SelectorWithIds, Base.SelectorWithLimit, Base.SelectorOrderBy, Base.SelectorForDateRange {} } }
the_stack
import { isUndefined, difference, pick, cloneDeep, get } from 'lodash'; import BaseFoundation, { DefaultAdapter } from '../base/foundation'; import { flattenTreeData, findDescendantKeys, findAncestorKeys, filter, normalizedArr, normalizeKeyList, getMotionKeys, calcCheckedKeysForChecked, calcCheckedKeysForUnchecked, calcCheckedKeys, getValueOrKey, getDragNodesKeys, calcDropRelativePosition, calcDropActualPosition } from './treeUtil'; export interface BasicTreeNodeProps { [x: string]: any; expanded?: boolean; selected?: boolean; checked?: boolean; halfChecked?: boolean; active?: boolean; disabled?: boolean; loaded?: boolean; loading?: boolean; isLeaf?: boolean; pos?: string; children?: BasicTreeNodeData[]; icon?: any; directory?: boolean; selectedKey?: string; motionKey?: string[] | string; eventKey?: string; } export interface BasicTreeNodeData { [x: string]: any; key: string; value?: number | string; label?: any; icon?: any; disabled?: boolean; isLeaf?: boolean; children?: BasicTreeNodeData[]; } export interface BasicKeyEntities { [key: string]: BasicKeyEntity; } export interface BasicKeyEntity { children?: BasicKeyEntities; data?: BasicTreeNodeData; ind?: number; key?: string; level?: number; parent?: undefined | BasicKeyEntity; parentPos?: null | string; pos?: string; } export interface BasicDragTreeNode extends BasicTreeNodeData { expanded: boolean; /** * The positional relationship of the current node in the entire * treeData, such as the 0th node of the 2nd node of the 1st node * of the 0th layer: '0-1-2-0' */ pos: string; } export interface BasicFlattenNode { _innerDataTag?: boolean; children?: BasicFlattenNode[]; data?: BasicTreeNodeData; key?: string; label?: any; parent?: null | BasicFlattenNode; pos?: string; value?: string; } export interface BasicDragProps { event: any; node: BasicDragTreeNode; } export interface BasicDragEnterProps extends BasicDragProps { expandedKeys?: string[]; } export type ExpandAction = false | 'click' | 'doubleClick'; export type BasicValue = string | number | BasicTreeNodeData | Array<BasicTreeNodeData | string | number>; export interface BasicOnDragProps { event: any; node: BasicDragTreeNode; dragNode: BasicDragTreeNode; dragNodesKeys: string[]; /** * dropPosition represents the position of the dragged node being * dropped in the current level. If inserted before the 0th node * of the same level, it is -1, after the 0th node, it is 1, and * it is 0 when it falls on it. And so on. With dropToGap, a more * complete judgment can be obtained. */ dropPosition: number; /** * Indicates whether the dragged node is dropped between nodes, if * it is false, it is dropped above a node */ dropToGap: boolean; } export interface BasicRenderFullLabelProps { /* Click the callback of the entire row to control the expansion behavior and selection */ onClick: (e: any) => void; /* Right-click the callback for the entire row */ onContextMenu: (e: any) => void; /* Double-click the entire line of callback */ onDoubleClick: (e: any) => void; /* Class name, including built-in styles such as indentation, expand button, filter, disable, select, etc. */ className: string; /* Expand callback */ onExpand: (e: any) => void; /* The original data of the row */ data: BasicTreeNodeData; /* The level of the line can be used to customize the indentation value */ level: number; /* The style required for virtualization, if virtualization is used, the style must be assigned to the DOM element */ style: any; /* Multi-select click callback */ onCheck: (e: any) => void; /* icon of Expand button */ expandIcon: any; /* Selected state */ checkStatus: { /* Whether to select in the multi-select state */ checked: boolean; /* Whether to half-select in the multi-select state */ halfChecked: boolean; }; /* Expand status */ expandStatus: { /* Has it been expanded */ expanded: boolean; /* Is it unfolding */ loading: boolean; }; } export interface BasicSearchRenderProps { className: string; placeholder: string; prefix: any; showClear?: boolean; value: string; onChange: (value: string) => void; } export interface TreeDataSimpleJson { [x: string]: string | TreeDataSimpleJson; } export interface Virtualize { itemSize: number; height?: number | string; width?: number | string; } export type CheckRelation = 'related' | 'unRelated'; export interface BasicTreeProps { autoExpandParent?: boolean; autoExpandWhenDragEnter?: boolean; blockNode?: boolean; children?: any; className?: string; expandAll?: boolean; defaultExpandAll?: boolean; defaultExpandedKeys?: string[]; defaultValue?: BasicValue; directory?: boolean; disabled?: boolean; disableStrictly?: boolean; draggable?: boolean; emptyContent?: any; expandAction?: ExpandAction; expandedKeys?: string[]; filterTreeNode?: boolean | ((inputValue: string, treeNodeString: string) => boolean); hideDraggingNode?: boolean; labelEllipsis?: boolean; leafOnly?: boolean; loadData?: (treeNode?: BasicTreeNodeData) => Promise<void>; loadedKeys?: string[]; motion?: boolean; multiple?: boolean; onChange?: (value?: BasicValue) => void; onChangeWithObject?: boolean; onDoubleClick?: (e: any, node: BasicTreeNodeData) => void; onDragEnd?: (dragProps: BasicDragProps) => void; onDragEnter?: (dragEnterProps: BasicDragEnterProps) => void; onDragLeave?: (dragProps: BasicDragProps) => void; onDragOver?: (dragProps: BasicDragProps) => void; onDragStart?: (dragProps: BasicDragProps) => void; onDrop?: (onDragProps: BasicOnDragProps) => void; onExpand?: (expandedKeys: string[], expandedOtherProps: BasicExpandedOtherProps) => void; onLoad?: (loadedKeys?: Set<string>, treeNode?: BasicTreeNodeData) => void; onContextMenu?: (e: any, node: BasicTreeNodeData) => void; onSearch?: (sunInput: string) => void; onSelect?: (selectedKeys: string, selected: boolean, selectedNode: BasicTreeNodeData) => void; renderDraggingNode?: (nodeInstance: HTMLElement, node: BasicTreeNodeData) => HTMLElement; renderFullLabel?: (renderFullLabelProps: BasicRenderFullLabelProps) => any; renderLabel?: (label?: any, treeNode?: BasicTreeNodeData) => any; searchClassName?: string; searchPlaceholder?: string; searchRender?: ((searchRenderProps: BasicSearchRenderProps) => any) | false; searchStyle?: any; showClear?: boolean; showFilteredOnly?: boolean; style?: any; treeData?: BasicTreeNodeData[]; treeDataSimpleJson?: TreeDataSimpleJson; treeNodeFilterProp?: string; value?: BasicValue; virtualize?: Virtualize; icon?: any; checkRelation?: CheckRelation; 'aria-label'?: string; } /* Data maintained internally. At the React framework level, corresponding to state */ export interface BasicTreeInnerData { /* The input content of the input box */ inputValue: string; /* keyEntities */ keyEntities: BasicKeyEntities; /* treeData */ treeData: BasicTreeNodeData[]; /* Expanded node */ flattenNodes: BasicFlattenNode[]; /* The selected node when single-selected */ selectedKeys: string[]; /* Select all nodes in multiple selection */ checkedKeys: Set<string>; /* Half-selected node when multiple selection */ halfCheckedKeys: Set<string>; /* real selected nodes in multiple selection */ realCheckedKeys: Set<string>; /* Animation node */ motionKeys: Set<string>; /* Animation type */ motionType: string; /* Expand node */ expandedKeys: Set<string>; /* Searched node */ filteredKeys: Set<string>; /* The ancestor node expanded because of the searched node*/ filteredExpandedKeys: Set<string>; /* Because of the searched node, the expanded ancestor node + the searched node + the descendant nodes of the searched node */ filteredShownKeys: Set<string>; /* Prev props */ prevProps: null | BasicTreeProps; /* loaded nodes */ loadedKeys: Set<string>; /* loading nodes */ loadingKeys: Set<string>; /* cache */ cachedFlattenNodes: BasicFlattenNode[] | undefined; cachedKeyValuePairs: { [x: string]: string }; /* Strictly disabled node */ disabledKeys: Set<string>; /* Is dragging */ dragging: boolean; /* Dragged node */ dragNodesKeys: Set<string>; /* DragOver node */ dragOverNodeKey: string[] | string | null; /* Drag position */ dropPosition: number | null; } export interface BasicExpandedOtherProps { expanded: boolean; node: BasicTreeNodeData; } export interface TreeAdapter extends DefaultAdapter<BasicTreeProps, BasicTreeInnerData> { updateInputValue: (value: string) => void; focusInput: () => void; updateState: (states: Partial<BasicTreeInnerData>) => void; notifyExpand: (expandedKeys: Set<string>, { expanded: bool, node }: BasicExpandedOtherProps) => void; notifySelect: (selectKey: string, bool: boolean, node: BasicTreeNodeData) => void; notifyChange: (value: BasicValue) => void; notifySearch: (input: string) => void; notifyRightClick: (e: any, node: BasicTreeNodeData) => void; notifyDoubleClick: (e: any, node: BasicTreeNodeData) => void; cacheFlattenNodes: (bool: boolean) => void; setDragNode: (treeNode: any) => void; } export default class TreeFoundation extends BaseFoundation<TreeAdapter, BasicTreeProps, BasicTreeInnerData> { delayedDragEnterLogic: any; constructor(adapter: TreeAdapter) { super({ ...adapter, }); } _isMultiple() { return this.getProp('multiple'); } _isAnimated() { return this.getProp('motion'); } _isDisabled(treeNode: BasicTreeNodeProps = {}) { return this.getProp('disabled') || treeNode.disabled; } _isExpandControlled() { return !isUndefined(this.getProp('expandedKeys')); } _isLoadControlled() { return !isUndefined(this.getProp('loadedKeys')); } _isFilterable() { // filter can be boolean or function return Boolean(this.getProp('filterTreeNode')); } _showFilteredOnly() { const { inputValue } = this.getStates(); const { showFilteredOnly } = this.getProps(); return Boolean(inputValue) && showFilteredOnly; } getCopyFromState(items: string[] | string) { const res: Partial<BasicTreeInnerData> = {}; normalizedArr(items).forEach(key => { res[key] = cloneDeep(this.getState(key)); }); return res; } getTreeNodeProps(key: string) { const { expandedKeys = new Set([]), selectedKeys = [], checkedKeys = new Set([]), halfCheckedKeys = new Set([]), realCheckedKeys = new Set([]), keyEntities = {}, filteredKeys = new Set([]), inputValue = '', loadedKeys = new Set([]), loadingKeys = new Set([]), filteredExpandedKeys = new Set([]), disabledKeys = new Set([]), } = this.getStates(); const { treeNodeFilterProp, checkRelation } = this.getProps(); const entity = keyEntities[key]; const notExist = !entity; if (notExist) { return null; } // if checkRelation is invalid, the checked status of node will be false let realChecked = false; let realHalfChecked = false; if (checkRelation === 'related') { realChecked = checkedKeys.has(key); realHalfChecked = halfCheckedKeys.has(key); } else if (checkRelation === 'unRelated') { realChecked = realCheckedKeys.has(key); realHalfChecked = false; } const isSearching = Boolean(inputValue); const treeNodeProps: BasicTreeNodeProps = { eventKey: key, expanded: isSearching ? filteredExpandedKeys.has(key) : expandedKeys.has(key), selected: selectedKeys.includes(key), checked: realChecked, halfChecked: realHalfChecked, pos: String(entity ? entity.pos : ''), level: entity.level, filtered: filteredKeys.has(key), loading: loadingKeys.has(key) && !loadedKeys.has(key), loaded: loadedKeys.has(key), keyword: inputValue, treeNodeFilterProp, }; if (this.getProp('disableStrictly') && disabledKeys.has(key)) { treeNodeProps.disabled = true; } return treeNodeProps; } notifyJsonChange(key: string[] | string, e: any) { const data = this.getProp('treeDataSimpleJson'); const selectedPath = normalizedArr(key).map(i => i.replace('-', '.')); const value = pick(data, selectedPath); this._adapter.notifyChange(value as BasicValue); } notifyMultipleChange(key: string[], e: any) { const { keyEntities } = this.getStates(); const { leafOnly, checkRelation } = this.getProps(); let value; let keyList = []; if (checkRelation === 'related') { keyList = normalizeKeyList(key, keyEntities, leafOnly); } else if (checkRelation === 'unRelated') { keyList = key; } if (this.getProp('onChangeWithObject')) { value = keyList.map((itemKey: string) => keyEntities[itemKey].data); } else { value = getValueOrKey(keyList.map((itemKey: string) => keyEntities[itemKey].data)); } this._adapter.notifyChange(value); } notifyChange(key: string[] | string, e: any) { const isMultiple = this._isMultiple(); const { keyEntities } = this.getStates(); if (this.getProp('treeDataSimpleJson')) { this.notifyJsonChange(key, e); } else if (isMultiple) { this.notifyMultipleChange(key as string[], e); } else { let value; if (this.getProp('onChangeWithObject')) { value = get(keyEntities, key).data; } else { const { data } = get(keyEntities, key); value = getValueOrKey(data); } this._adapter.notifyChange(value); } } handleInputChange(sugInput: string) { // Input is a controlled component, so the value value needs to be updated this._adapter.updateInputValue(sugInput); const { expandedKeys, selectedKeys, keyEntities, treeData } = this.getStates(); const { showFilteredOnly, filterTreeNode, treeNodeFilterProp } = this.getProps(); let filteredOptsKeys: string[] = []; let expandedOptsKeys: string[] = []; let flattenNodes: BasicFlattenNode[] = []; let filteredShownKeys = new Set([]); if (!sugInput) { expandedOptsKeys = findAncestorKeys(selectedKeys, keyEntities); expandedOptsKeys.forEach(item => expandedKeys.add(item)); flattenNodes = flattenTreeData(treeData, expandedKeys); } else { filteredOptsKeys = Object.values(keyEntities) .filter((item: BasicKeyEntity) => filter(sugInput, item.data, filterTreeNode, treeNodeFilterProp)) .map((item: BasicKeyEntity) => item.key); expandedOptsKeys = findAncestorKeys(filteredOptsKeys, keyEntities, false); const shownChildKeys = findDescendantKeys(filteredOptsKeys, keyEntities, true); filteredShownKeys = new Set([...shownChildKeys, ...expandedOptsKeys]); flattenNodes = flattenTreeData( treeData, new Set(expandedOptsKeys), showFilteredOnly && filteredShownKeys ); } this._adapter.notifySearch(sugInput); this._adapter.updateState({ expandedKeys, flattenNodes, motionKeys: new Set([]), filteredKeys: new Set(filteredOptsKeys), filteredExpandedKeys: new Set(expandedOptsKeys), filteredShownKeys, }); } handleNodeSelect(e: any, treeNode: BasicTreeNodeProps) { const isDisabled = this._isDisabled(treeNode); if (isDisabled) { return; } if (!this._isMultiple()) { this.handleSingleSelect(e, treeNode); } else { this.handleMultipleSelect(e, treeNode); } } handleNodeRightClick(e: any, treeNode: BasicTreeNodeProps) { this._adapter.notifyRightClick(e, treeNode.data); } handleNodeDoubleClick(e: any, treeNode: BasicTreeNodeProps) { this._adapter.notifyDoubleClick(e, treeNode.data); } handleSingleSelect(e: any, treeNode: BasicTreeNodeProps) { let { selectedKeys } = this.getCopyFromState('selectedKeys'); const { selected, eventKey, data } = treeNode; const targetSelected = !selected; this._adapter.notifySelect(eventKey, true, data); if (!targetSelected) { return; } if (!selectedKeys.includes(eventKey)) { selectedKeys = [eventKey]; this.notifyChange(eventKey, e); if (!this._isControlledComponent()) { this._adapter.updateState({ selectedKeys }); } } } calcCheckedKeys(eventKey: string, targetStatus: boolean) { const { keyEntities } = this.getStates(); const { checkedKeys, halfCheckedKeys } = this.getCopyFromState(['checkedKeys', 'halfCheckedKeys']); return targetStatus ? calcCheckedKeysForChecked(eventKey, keyEntities, checkedKeys, halfCheckedKeys) : calcCheckedKeysForUnchecked(eventKey, keyEntities, checkedKeys, halfCheckedKeys); } /* * Compute the checked state of the node */ calcCheckedStatus(targetStatus: boolean, eventKey: string) { // From checked to unchecked, you can change it directly if (!targetStatus) { return targetStatus; } // Starting from unchecked, you need to judge according to the descendant nodes const { checkedKeys, keyEntities, disabledKeys } = this.getStates(); const descendantKeys = normalizeKeyList(findDescendantKeys([eventKey], keyEntities, false), keyEntities, true); const hasDisabled = descendantKeys.some((key: string) => disabledKeys.has(key)); // If the descendant nodes are not disabled, they will be directly changed to checked if (!hasDisabled) { return targetStatus; } // If all descendant nodes that are not disabled are selected, return unchecked, otherwise, return checked const nonDisabledKeys = descendantKeys.filter((key: string) => !disabledKeys.has(key)); const allChecked = nonDisabledKeys.every((key: string) => checkedKeys.has(key)); return !allChecked; } /* * In strict disable mode, calculate the nodes of checked and halfCheckedKeys and return their corresponding keys */ calcNonDisabledCheckedKeys(eventKey: string, targetStatus: boolean) { const { keyEntities, disabledKeys } = this.getStates(); const { checkedKeys } = this.getCopyFromState(['checkedKeys']); const descendantKeys = normalizeKeyList(findDescendantKeys([eventKey], keyEntities, false), keyEntities, true); const hasDisabled = descendantKeys.some((key: string) => disabledKeys.has(key)); // If none of the descendant nodes are disabled, follow the normal logic if (!hasDisabled) { return this.calcCheckedKeys(eventKey, targetStatus); } const nonDisabled = descendantKeys.filter((key: string) => !disabledKeys.has(key)); const newCheckedKeys = targetStatus ? [...nonDisabled, ...checkedKeys] : difference(normalizeKeyList([...checkedKeys], keyEntities, true), nonDisabled); return calcCheckedKeys(newCheckedKeys, keyEntities); } /* * Handle the selection event in the case of multiple selection */ handleMultipleSelect(e: any, treeNode: BasicTreeNodeProps) { const { disableStrictly, checkRelation } = this.getProps(); const { realCheckedKeys } = this.getStates(); // eventKey: The key value of the currently clicked node const { checked, eventKey, data } = treeNode; if (checkRelation === 'related') { // Find the checked state of the current node const targetStatus = disableStrictly ? this.calcCheckedStatus(!checked, eventKey) : !checked; const { checkedKeys, halfCheckedKeys } = disableStrictly ? this.calcNonDisabledCheckedKeys(eventKey, targetStatus) : this.calcCheckedKeys(eventKey, targetStatus); this._adapter.notifySelect(eventKey, targetStatus, data); this.notifyChange([...checkedKeys], e); if (!this._isControlledComponent()) { this._adapter.updateState({ checkedKeys, halfCheckedKeys }); } } else if (checkRelation === 'unRelated') { const newRealCheckedKeys: Set<string> = new Set(realCheckedKeys); let targetStatus: boolean; if (realCheckedKeys.has(eventKey)) { newRealCheckedKeys.delete(eventKey); targetStatus = false; } else { newRealCheckedKeys.add(eventKey); targetStatus = true; } this._adapter.notifySelect(eventKey, targetStatus, data); this.notifyChange([...newRealCheckedKeys], e); if (!this._isControlledComponent()) { this._adapter.updateState({ realCheckedKeys: newRealCheckedKeys }); } } } setExpandedStatus(treeNode: BasicTreeNodeProps) { const { inputValue, treeData, filteredShownKeys, keyEntities } = this.getStates(); const isSearching = Boolean(inputValue); const showFilteredOnly = this._showFilteredOnly(); const expandedStateKey = isSearching ? 'filteredExpandedKeys' : 'expandedKeys'; const expandedKeys = this.getCopyFromState(expandedStateKey)[expandedStateKey]; let motionType = 'show'; const { eventKey, expanded, data } = treeNode; if (!expanded) { expandedKeys.add(eventKey); } else if (expandedKeys.has(eventKey)) { expandedKeys.delete(eventKey); motionType = 'hide'; } this._adapter.cacheFlattenNodes(motionType === 'hide' && this._isAnimated()); if (!this._isExpandControlled()) { const flattenNodes = flattenTreeData( treeData, expandedKeys, isSearching && showFilteredOnly && filteredShownKeys ); const motionKeys = this._isAnimated() ? getMotionKeys(eventKey, expandedKeys, keyEntities) : []; const newState = { [expandedStateKey]: expandedKeys, flattenNodes, motionKeys: new Set(motionKeys), motionType, }; this._adapter.updateState(newState); } return { expandedKeys, expanded: !expanded, data, }; } handleNodeExpand(e: any, treeNode: BasicTreeNodeProps) { const { loadData } = this.getProps(); if (!loadData && (!treeNode.children || !treeNode.children.length)) { return; } const { expandedKeys, data, expanded } = this.setExpandedStatus(treeNode); this._adapter.notifyExpand(expandedKeys, { expanded, node: data, }); } // eslint-disable-next-line max-len handleNodeLoad(loadedKeys: Set<string>, loadingKeys: Set<string>, data: BasicTreeNodeData, resolve: (value?: any) => void) { const { loadData, onLoad } = this.getProps(); const { key } = data; if (!loadData || loadedKeys.has(key) || loadingKeys.has(key)) { return {}; } // Process the loaded data loadData(data).then(() => { const { loadedKeys: prevLoadedKeys, loadingKeys: prevLoadingKeys } = this.getCopyFromState(['loadedKeys', 'loadingKeys']); const newLoadedKeys = prevLoadedKeys.add(key); const newLoadingKeys = new Set([...prevLoadingKeys]); newLoadingKeys.delete(key); // onLoad should be triggered before internal setState to avoid `loadData` being triggered twice onLoad && onLoad(newLoadedKeys, data); if (!this._isLoadControlled()) { this._adapter.updateState({ loadedKeys: newLoadedKeys, }); } this._adapter.setState({ loadingKeys: newLoadingKeys, } as any); resolve(); }); return { loadingKeys: loadingKeys.add(key), }; } // Drag and drop related processing logic getDragEventNodeData(node: BasicTreeNodeData) { return { ...node.data, ...pick(node, ['expanded', 'pos', 'children']), }; } triggerDragEvent(name: string, event: any, node: BasicTreeNodeData, extra = {}) { const callEvent = this.getProp(name); callEvent && callEvent({ event, node: this.getDragEventNodeData(node), ...extra, }); } clearDragState = () => { this._adapter.updateState({ dragOverNodeKey: '', dragging: false, }); }; handleNodeDragStart(e: any, treeNode: BasicTreeNodeData) { const { keyEntities } = this.getStates(); const { hideDraggingNode, renderDraggingNode } = this.getProps(); const { eventKey, nodeInstance, data } = treeNode; if (hideDraggingNode || renderDraggingNode) { let dragImg; if (typeof renderDraggingNode === 'function') { dragImg = renderDraggingNode(nodeInstance, data); } else if (hideDraggingNode) { dragImg = nodeInstance.cloneNode(true); dragImg.style.opacity = 0; } document.body.appendChild(dragImg); e.dataTransfer.setDragImage(dragImg, 0, 0); } this._adapter.setDragNode(treeNode); this._adapter.updateState({ dragging: true, dragNodesKeys: new Set(getDragNodesKeys(eventKey, keyEntities)), }); this.triggerDragEvent('onDragStart', e, treeNode); } handleNodeDragEnter(e: any, treeNode: BasicTreeNodeData, dragNode: any) { const { dragging, dragNodesKeys } = this.getStates(); const { autoExpandWhenDragEnter } = this.getProps(); const { pos, eventKey, expanded } = treeNode; if (!dragNode || dragNodesKeys.has(eventKey)) { return; } const dropPosition = calcDropRelativePosition(e, treeNode); // If the drag node is itself, skip if (dragNode.eventKey === eventKey && dropPosition === 0) { this._adapter.updateState({ dragOverNodeKey: '', dropPosition: null, }); return; } // Trigger dragenter after clearing the prev state in dragleave setTimeout(() => { this._adapter.updateState({ dragOverNodeKey: eventKey, dropPosition, }); // If autoExpand is already expanded or not allowed, trigger the event and return if (!autoExpandWhenDragEnter || expanded) { this.triggerDragEvent('onDragEnter', e, treeNode); return; } // Side effects of delayed drag if (!this.delayedDragEnterLogic) { this.delayedDragEnterLogic = {}; } Object.keys(this.delayedDragEnterLogic).forEach(key => { clearTimeout(this.delayedDragEnterLogic[key]); }); this.delayedDragEnterLogic[pos] = window.setTimeout(() => { if (!dragging) { return; } const { expandedKeys: newExpandedKeys } = this.setExpandedStatus(treeNode); this.triggerDragEvent('onDragEnter', e, treeNode, { expandedKeys: [...newExpandedKeys] }); }, 400); }, 0); } handleNodeDragOver(e: any, treeNode: BasicTreeNodeData, dragNode: any) { const { dropPosition, dragNodesKeys, dragOverNodeKey } = this.getStates(); const { eventKey } = treeNode; if (dragNodesKeys.has(eventKey)) { return; } // Update the drag position if (dragNode && eventKey === dragOverNodeKey) { const newPos = calcDropRelativePosition(e, treeNode); if (dropPosition === newPos) { return; } this._adapter.updateState({ dropPosition: newPos, }); } this.triggerDragEvent('onDragOver', e, treeNode); } handleNodeDragLeave(e: any, treeNode: BasicTreeNodeData) { this._adapter.updateState({ dragOverNodeKey: '', }); this.triggerDragEvent('onDragLeave', e, treeNode); } handleNodeDragEnd(e: any, treeNode: BasicTreeNodeData) { this.clearDragState(); this.triggerDragEvent('onDragEnd', e, treeNode); this._adapter.setDragNode(null); } handleNodeDrop(e: any, treeNode: BasicTreeNodeData, dragNode: any) { const { dropPosition, dragNodesKeys } = this.getStates(); const { eventKey, pos } = treeNode; this.clearDragState(); if (dragNodesKeys.has(eventKey)) { return; } const dropRes = { dragNode: dragNode ? this.getDragEventNodeData(dragNode) : null, dragNodesKeys: [...dragNodesKeys], dropPosition: calcDropActualPosition(pos, dropPosition), dropToGap: dropPosition !== 0, }; this.triggerDragEvent('onDrop', e, treeNode, dropRes); this._adapter.setDragNode(null); } }
the_stack
namespace Word { export interface Collection<T> { count: number; item(index: number): T; } export interface Font { bold: boolean; italic: boolean; subscript: boolean; superscript: boolean; } export interface Find { font: Font; format: boolean; replacement: Replacement; style: any; text: string; clearFormatting(): void; execute( findText: string, matchCase: boolean, matchWholeWord: boolean, matchWildcards: boolean, matchSoundsLike: boolean, matchAllWordForms: boolean, forward: boolean, wrap: number, format: boolean, replaceWith: string, replace: number): boolean; } export interface Replacement { font: Font; style: any; text: string; clearFormatting(): void; } export interface ListFormat { listLevelNumber: number; listString: string; } export interface Column { } export interface Columns extends Collection<Column> { } export interface Table { columns: Columns; } export interface Tables extends Collection<Table> { } export interface Range { find: Find; listFormat: ListFormat; tables: Tables; text: string; textRetrievalMode: { includeHiddenText: boolean; } words: Ranges; } export interface Ranges extends Collection<Range> { } export interface Style { nameLocal: string; } export interface Paragraph { alignment: number; range: Range; style: Style; next(): Paragraph; } export interface Paragraphs extends Collection<Paragraph> { first: Paragraph; } export interface Field { } export interface Fields extends Collection<Field> { toggleShowCodes(): void; } export interface Hyperlink { address: string; textToDisplay: string; range: Range; } export interface Hyperlinks extends Collection<Hyperlink> { } export interface Document { fields: Fields; paragraphs: Paragraphs; hyperlinks: Hyperlinks; builtInDocumentProperties: Collection<any>; close(saveChanges: boolean): void; range(): Range; } export interface Documents extends Collection<Document> { open(filename: string): Document; } export interface Application { documents: Documents; quit(): void; } } const sys = (() => { const fileStream = new ActiveXObject("ADODB.Stream"); fileStream.Type = 2 /* text */; const binaryStream = new ActiveXObject("ADODB.Stream"); binaryStream.Type = 1 /* binary */; const args: string[] = []; for (let i = 0; i < WScript.Arguments.length; i++) { args[i] = WScript.Arguments.Item(i); } return { args, createObject: (typeName: string) => new ActiveXObject(typeName), write(s: string): void { WScript.StdOut.Write(s); }, writeFile: (fileName: string, data: string): void => { fileStream.Open(); binaryStream.Open(); try { // Write characters in UTF-8 encoding fileStream.Charset = "utf-8"; fileStream.WriteText(data); // We don't want the BOM, skip it by setting the starting location to 3 (size of BOM). fileStream.Position = 3; fileStream.CopyTo(binaryStream); binaryStream.SaveToFile(fileName, 2 /*overwrite*/); } finally { binaryStream.Close(); fileStream.Close(); } } }; })(); interface FindReplaceOptions { style?: any; font?: { bold?: boolean; italic?: boolean; subscript?: boolean; }; } function convertDocumentToMarkdown(doc: Word.Document): string { const columnAlignment: number[] = []; let tableColumnCount: number; let tableCellIndex: number; let lastInTable: boolean; let lastStyle: string; let result = ""; function setProperties(target: any, properties: any) { for (const name in properties) { if (properties.hasOwnProperty(name)) { const value = properties[name]; if (typeof value === "object") { setProperties(target[name], value); } else { target[name] = value; } } } } function findReplace(findText: string, findOptions: FindReplaceOptions, replaceText: string, replaceOptions: FindReplaceOptions) { const find = doc.range().find; find.clearFormatting(); setProperties(find, findOptions); const replace = find.replacement; replace.clearFormatting(); setProperties(replace, replaceOptions); find.execute(findText, /* matchCase */ false, /* matchWholeWord */ false, /* matchWildcards */ false, /* matchSoundsLike */ false, /* matchAllWordForms */ false, /* forward */ true, 0, /* format */ true, replaceText, 2 ); } function fixHyperlinks() { const count = doc.hyperlinks.count; for (let i = 0; i < count; i++) { const hyperlink = doc.hyperlinks.item(i + 1); const address = hyperlink.address; if (address && address.length > 0) { const textToDisplay = hyperlink.textToDisplay; hyperlink.textToDisplay = "[" + textToDisplay + "](" + address + ")"; } } } function write(s: string) { result += s; } function writeTableHeader() { for (let i = 0; i < tableColumnCount - 1; i++) { switch (columnAlignment[i]) { case 1: write("|:---:"); break; case 2: write("|---:"); break; default: write("|---"); } } write("|\n"); } function trimEndFormattingMarks(text: string) { let i = text.length; while (i > 0 && text.charCodeAt(i - 1) < 0x20) i--; return text.substr(0, i); } function writeBlockEnd() { switch (lastStyle) { case "Code": write("```\n\n"); break; case "List Paragraph": case "Table": case "TOC": write("\n"); break; } } function writeParagraph(p: Word.Paragraph) { const range = p.range; const inTable = range.tables.count > 0; const sectionBreak = range.text.indexOf("\x0C") >= 0; let level = 1; let style = p.style.nameLocal; let text = range.text; text = trimEndFormattingMarks(text); if (text === "/") { // An inline image shows up in the text as a "/". When we see a paragraph // consisting of nothing but "/", we check to see if the paragraph contains // hidden text and, if so, emit that instead. The hidden text is assumed to // contain an appropriate markdown image link. range.textRetrievalMode.includeHiddenText = true; const fullText = range.text; range.textRetrievalMode.includeHiddenText = false; if (text !== fullText) { text = "&emsp;&emsp;" + fullText.substr(1); } } if (inTable) { style = "Table"; } else if (style.match(/\s\d$/)) { level = +style.substr(style.length - 1); style = style.substr(0, style.length - 2); } if (lastStyle && style !== lastStyle) { writeBlockEnd(); } switch (style) { case "Heading": case "Appendix": const section = range.listFormat.listString; write("####".substr(0, level) + ' <a name="' + section + '"/>' + section + " " + text + "\n\n"); break; case "Normal": if (text.length) { write(text + "\n\n"); } break; case "List Paragraph": write(" ".substr(0, range.listFormat.listLevelNumber * 2 - 2) + "* " + text + "\n"); break; case "Grammar": write("&emsp;&emsp;" + text.replace(/\s\s\s/g, "&emsp;").replace(/\x0B/g, " \n&emsp;&emsp;&emsp;") + "\n\n"); break; case "Code": if (lastStyle !== "Code") { write("```TypeScript\n"); } else { write("\n"); } write(text.replace(/\x0B/g, " \n") + "\n"); break; case "Table": if (!lastInTable) { tableColumnCount = range.tables.item(1).columns.count + 1; tableCellIndex = 0; } if (tableCellIndex < tableColumnCount) { columnAlignment[tableCellIndex] = p.alignment; } write("|" + text); tableCellIndex++; if (tableCellIndex % tableColumnCount === 0) { write("\n"); if (tableCellIndex === tableColumnCount) { writeTableHeader(); } } break; case "TOC Heading": write("## " + text + "\n\n"); break; case "TOC": const strings = text.split("\t"); write(" ".substr(0, level * 2 - 2) + "* [" + strings[0] + " " + strings[1] + "](#" + strings[0] + ")\n"); break; } if (sectionBreak) { write("<br/>\n\n"); } lastStyle = style; lastInTable = inTable; } function writeDocument() { const title = doc.builtInDocumentProperties.item(1) + ""; if (title.length) { write("# " + title + "\n\n"); } for (let p = doc.paragraphs.first; p; p = p.next()) { writeParagraph(p); } writeBlockEnd(); } findReplace("<", {}, "&lt;", {}); findReplace("&lt;", { style: "Code" }, "<", {}); findReplace("&lt;", { style: "Code Fragment" }, "<", {}); findReplace("&lt;", { style: "Terminal" }, "<", {}); findReplace("", { font: { subscript: true } }, "<sub>^&</sub>", { font: { subscript: false } }); findReplace("", { style: "Code Fragment" }, "`^&`", { style: -66 /* default font */ }); findReplace("", { style: "Production" }, "*^&*", { style: -66 /* default font */ }); findReplace("", { style: "Terminal" }, "`^&`", { style: -66 /* default font */ }); findReplace("", { font: { bold: true, italic: true } }, "***^&***", { font: { bold: false, italic: false } }); findReplace("", { font: { italic: true } }, "*^&*", { font: { italic: false } }); doc.fields.toggleShowCodes(); findReplace("^19 REF", {}, "[^&](#^&)", {}); doc.fields.toggleShowCodes(); fixHyperlinks(); writeDocument(); result = result.replace(/\x85/g, "\u2026"); result = result.replace(/\x96/g, "\u2013"); result = result.replace(/\x97/g, "\u2014"); return result; } function main(args: string[]) { if (args.length !== 2) { sys.write("Syntax: word2md <inputfile> <outputfile>\n"); return; } const app: Word.Application = sys.createObject("Word.Application"); const doc = app.documents.open(args[0]); sys.writeFile(args[1], convertDocumentToMarkdown(doc)); doc.close(/* saveChanges */ false); app.quit(); } main(sys.args);
the_stack
namespace collections { export interface SortOptions<T> { comparer: (a: T, b: T) => number; sort: "insertion" | "comparison"; } export class SortedMap<K, V> { private _comparer: (a: K, b: K) => number; private _keys: K[] = []; private _values: V[] = []; private _order: number[] | undefined; private _version = 0; private _copyOnWrite = false; constructor(comparer: ((a: K, b: K) => number) | SortOptions<K>, iterable?: Iterable<[K, V]>) { this._comparer = typeof comparer === "object" ? comparer.comparer : comparer; this._order = typeof comparer === "object" && comparer.sort === "insertion" ? [] : undefined; if (iterable) { const iterator = getIterator(iterable); try { for (let i = nextResult(iterator); i; i = nextResult(iterator)) { const [key, value] = i.value; this.set(key, value); } } finally { closeIterator(iterator); } } } public get size() { return this._keys.length; } public get comparer() { return this._comparer; } public get [Symbol.toStringTag]() { return "SortedMap"; } public has(key: K) { return ts.binarySearch(this._keys, key, ts.identity, this._comparer) >= 0; } public get(key: K) { const index = ts.binarySearch(this._keys, key, ts.identity, this._comparer); return index >= 0 ? this._values[index] : undefined; } public set(key: K, value: V) { const index = ts.binarySearch(this._keys, key, ts.identity, this._comparer); if (index >= 0) { this._values[index] = value; } else { this.writePreamble(); insertAt(this._keys, ~index, key); insertAt(this._values, ~index, value); if (this._order) insertAt(this._order, ~index, this._version); this.writePostScript(); } return this; } public delete(key: K) { const index = ts.binarySearch(this._keys, key, ts.identity, this._comparer); if (index >= 0) { this.writePreamble(); ts.orderedRemoveItemAt(this._keys, index); ts.orderedRemoveItemAt(this._values, index); if (this._order) ts.orderedRemoveItemAt(this._order, index); this.writePostScript(); return true; } return false; } public clear() { if (this.size > 0) { this.writePreamble(); this._keys.length = 0; this._values.length = 0; if (this._order) this._order.length = 0; this.writePostScript(); } } public forEach(callback: (value: V, key: K, collection: this) => void, thisArg?: any) { const keys = this._keys; const values = this._values; const indices = this.getIterationOrder(); const version = this._version; this._copyOnWrite = true; try { if (indices) { for (const i of indices) { callback.call(thisArg, values[i], keys[i], this); } } else { for (let i = 0; i < keys.length; i++) { callback.call(thisArg, values[i], keys[i], this); } } } finally { if (version === this._version) { this._copyOnWrite = false; } } } public * keys() { const keys = this._keys; const indices = this.getIterationOrder(); const version = this._version; this._copyOnWrite = true; try { if (indices) { for (const i of indices) { yield keys[i]; } } else { yield* keys; } } finally { if (version === this._version) { this._copyOnWrite = false; } } } public * values() { const values = this._values; const indices = this.getIterationOrder(); const version = this._version; this._copyOnWrite = true; try { if (indices) { for (const i of indices) { yield values[i]; } } else { yield* values; } } finally { if (version === this._version) { this._copyOnWrite = false; } } } public * entries() { const keys = this._keys; const values = this._values; const indices = this.getIterationOrder(); const version = this._version; this._copyOnWrite = true; try { if (indices) { for (const i of indices) { yield [keys[i], values[i]] as [K, V]; } } else { for (let i = 0; i < keys.length; i++) { yield [keys[i], values[i]] as [K, V]; } } } finally { if (version === this._version) { this._copyOnWrite = false; } } } public [Symbol.iterator]() { return this.entries(); } private writePreamble() { if (this._copyOnWrite) { this._keys = this._keys.slice(); this._values = this._values.slice(); if (this._order) this._order = this._order.slice(); this._copyOnWrite = false; } } private writePostScript() { this._version++; } private getIterationOrder() { if (this._order) { const order = this._order; return this._order .map((_, i) => i) .sort((x, y) => order[x] - order[y]); } return undefined; } } export function insertAt<T>(array: T[], index: number, value: T): void { if (index === 0) { array.unshift(value); } else if (index === array.length) { array.push(value); } else { for (let i = array.length; i > index; i--) { array[i] = array[i - 1]; } array[index] = value; } } export function getIterator<T>(iterable: Iterable<T>): Iterator<T> { return iterable[Symbol.iterator](); } export function nextResult<T>(iterator: Iterator<T>): IteratorResult<T> | undefined { const result = iterator.next(); return result.done ? undefined : result; } export function closeIterator<T>(iterator: Iterator<T>) { const fn = iterator.return; if (typeof fn === "function") fn.call(iterator); } /** * A collection of metadata that supports inheritance. */ export class Metadata { private static readonly _undefinedValue = {}; private _parent: Metadata | undefined; private _map: { [key: string]: any }; private _version = 0; private _size = -1; private _parentVersion: number | undefined; constructor(parent?: Metadata) { this._parent = parent; this._map = Object.create(parent ? parent._map : null); // tslint:disable-line:no-null-keyword } public get size(): number { if (this._size === -1 || (this._parent && this._parent._version !== this._parentVersion)) { let size = 0; for (const _ in this._map) size++; this._size = size; if (this._parent) { this._parentVersion = this._parent._version; } } return this._size; } public get parent() { return this._parent; } public has(key: string): boolean { return this._map[Metadata._escapeKey(key)] !== undefined; } public get(key: string): any { const value = this._map[Metadata._escapeKey(key)]; return value === Metadata._undefinedValue ? undefined : value; } public set(key: string, value: any): this { this._map[Metadata._escapeKey(key)] = value === undefined ? Metadata._undefinedValue : value; this._size = -1; this._version++; return this; } public delete(key: string): boolean { const escapedKey = Metadata._escapeKey(key); if (this._map[escapedKey] !== undefined) { delete this._map[escapedKey]; this._size = -1; this._version++; return true; } return false; } public clear(): void { this._map = Object.create(this._parent ? this._parent._map : null); // tslint:disable-line:no-null-keyword this._size = -1; this._version++; } public forEach(callback: (value: any, key: string, map: this) => void) { for (const key in this._map) { callback(this._map[key], Metadata._unescapeKey(key), this); } } private static _escapeKey(text: string) { return (text.length >= 2 && text.charAt(0) === "_" && text.charAt(1) === "_" ? "_" + text : text); } private static _unescapeKey(text: string) { return (text.length >= 3 && text.charAt(0) === "_" && text.charAt(1) === "_" && text.charAt(2) === "_" ? text.slice(1) : text); } } }
the_stack
import { GraphQLClient } from 'graphql-request'; import * as Dom from 'graphql-request/dist/types.dom'; import gql from 'graphql-tag'; export type Maybe<T> = T | null; export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] }; export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> }; export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> }; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; BigDecimal: any; BigInt: any; Bytes: any; }; export type AssetBalance = { __typename?: 'AssetBalance'; id: Scalars['ID']; amount: Scalars['BigInt']; router: Router; assetId: Scalars['Bytes']; supplied: Scalars['BigInt']; removed: Scalars['BigInt']; lockedIn: Scalars['BigInt']; volumeIn: Scalars['BigInt']; locked: Scalars['BigInt']; volume: Scalars['BigInt']; sendingPrepareTxCount: Scalars['BigInt']; sendingFulfillTxCount: Scalars['BigInt']; sendingCancelTxCount: Scalars['BigInt']; receivingPrepareTxCount: Scalars['BigInt']; receivingFulfillTxCount: Scalars['BigInt']; receivingCancelTxCount: Scalars['BigInt']; }; export type AssetBalance_Filter = { id?: Maybe<Scalars['ID']>; id_not?: Maybe<Scalars['ID']>; id_gt?: Maybe<Scalars['ID']>; id_lt?: Maybe<Scalars['ID']>; id_gte?: Maybe<Scalars['ID']>; id_lte?: Maybe<Scalars['ID']>; id_in?: Maybe<Array<Scalars['ID']>>; id_not_in?: Maybe<Array<Scalars['ID']>>; amount?: Maybe<Scalars['BigInt']>; amount_not?: Maybe<Scalars['BigInt']>; amount_gt?: Maybe<Scalars['BigInt']>; amount_lt?: Maybe<Scalars['BigInt']>; amount_gte?: Maybe<Scalars['BigInt']>; amount_lte?: Maybe<Scalars['BigInt']>; amount_in?: Maybe<Array<Scalars['BigInt']>>; amount_not_in?: Maybe<Array<Scalars['BigInt']>>; router?: Maybe<Scalars['String']>; router_not?: Maybe<Scalars['String']>; router_gt?: Maybe<Scalars['String']>; router_lt?: Maybe<Scalars['String']>; router_gte?: Maybe<Scalars['String']>; router_lte?: Maybe<Scalars['String']>; router_in?: Maybe<Array<Scalars['String']>>; router_not_in?: Maybe<Array<Scalars['String']>>; router_contains?: Maybe<Scalars['String']>; router_not_contains?: Maybe<Scalars['String']>; router_starts_with?: Maybe<Scalars['String']>; router_not_starts_with?: Maybe<Scalars['String']>; router_ends_with?: Maybe<Scalars['String']>; router_not_ends_with?: Maybe<Scalars['String']>; assetId?: Maybe<Scalars['Bytes']>; assetId_not?: Maybe<Scalars['Bytes']>; assetId_in?: Maybe<Array<Scalars['Bytes']>>; assetId_not_in?: Maybe<Array<Scalars['Bytes']>>; assetId_contains?: Maybe<Scalars['Bytes']>; assetId_not_contains?: Maybe<Scalars['Bytes']>; supplied?: Maybe<Scalars['BigInt']>; supplied_not?: Maybe<Scalars['BigInt']>; supplied_gt?: Maybe<Scalars['BigInt']>; supplied_lt?: Maybe<Scalars['BigInt']>; supplied_gte?: Maybe<Scalars['BigInt']>; supplied_lte?: Maybe<Scalars['BigInt']>; supplied_in?: Maybe<Array<Scalars['BigInt']>>; supplied_not_in?: Maybe<Array<Scalars['BigInt']>>; removed?: Maybe<Scalars['BigInt']>; removed_not?: Maybe<Scalars['BigInt']>; removed_gt?: Maybe<Scalars['BigInt']>; removed_lt?: Maybe<Scalars['BigInt']>; removed_gte?: Maybe<Scalars['BigInt']>; removed_lte?: Maybe<Scalars['BigInt']>; removed_in?: Maybe<Array<Scalars['BigInt']>>; removed_not_in?: Maybe<Array<Scalars['BigInt']>>; lockedIn?: Maybe<Scalars['BigInt']>; lockedIn_not?: Maybe<Scalars['BigInt']>; lockedIn_gt?: Maybe<Scalars['BigInt']>; lockedIn_lt?: Maybe<Scalars['BigInt']>; lockedIn_gte?: Maybe<Scalars['BigInt']>; lockedIn_lte?: Maybe<Scalars['BigInt']>; lockedIn_in?: Maybe<Array<Scalars['BigInt']>>; lockedIn_not_in?: Maybe<Array<Scalars['BigInt']>>; volumeIn?: Maybe<Scalars['BigInt']>; volumeIn_not?: Maybe<Scalars['BigInt']>; volumeIn_gt?: Maybe<Scalars['BigInt']>; volumeIn_lt?: Maybe<Scalars['BigInt']>; volumeIn_gte?: Maybe<Scalars['BigInt']>; volumeIn_lte?: Maybe<Scalars['BigInt']>; volumeIn_in?: Maybe<Array<Scalars['BigInt']>>; volumeIn_not_in?: Maybe<Array<Scalars['BigInt']>>; locked?: Maybe<Scalars['BigInt']>; locked_not?: Maybe<Scalars['BigInt']>; locked_gt?: Maybe<Scalars['BigInt']>; locked_lt?: Maybe<Scalars['BigInt']>; locked_gte?: Maybe<Scalars['BigInt']>; locked_lte?: Maybe<Scalars['BigInt']>; locked_in?: Maybe<Array<Scalars['BigInt']>>; locked_not_in?: Maybe<Array<Scalars['BigInt']>>; volume?: Maybe<Scalars['BigInt']>; volume_not?: Maybe<Scalars['BigInt']>; volume_gt?: Maybe<Scalars['BigInt']>; volume_lt?: Maybe<Scalars['BigInt']>; volume_gte?: Maybe<Scalars['BigInt']>; volume_lte?: Maybe<Scalars['BigInt']>; volume_in?: Maybe<Array<Scalars['BigInt']>>; volume_not_in?: Maybe<Array<Scalars['BigInt']>>; sendingPrepareTxCount?: Maybe<Scalars['BigInt']>; sendingPrepareTxCount_not?: Maybe<Scalars['BigInt']>; sendingPrepareTxCount_gt?: Maybe<Scalars['BigInt']>; sendingPrepareTxCount_lt?: Maybe<Scalars['BigInt']>; sendingPrepareTxCount_gte?: Maybe<Scalars['BigInt']>; sendingPrepareTxCount_lte?: Maybe<Scalars['BigInt']>; sendingPrepareTxCount_in?: Maybe<Array<Scalars['BigInt']>>; sendingPrepareTxCount_not_in?: Maybe<Array<Scalars['BigInt']>>; sendingFulfillTxCount?: Maybe<Scalars['BigInt']>; sendingFulfillTxCount_not?: Maybe<Scalars['BigInt']>; sendingFulfillTxCount_gt?: Maybe<Scalars['BigInt']>; sendingFulfillTxCount_lt?: Maybe<Scalars['BigInt']>; sendingFulfillTxCount_gte?: Maybe<Scalars['BigInt']>; sendingFulfillTxCount_lte?: Maybe<Scalars['BigInt']>; sendingFulfillTxCount_in?: Maybe<Array<Scalars['BigInt']>>; sendingFulfillTxCount_not_in?: Maybe<Array<Scalars['BigInt']>>; sendingCancelTxCount?: Maybe<Scalars['BigInt']>; sendingCancelTxCount_not?: Maybe<Scalars['BigInt']>; sendingCancelTxCount_gt?: Maybe<Scalars['BigInt']>; sendingCancelTxCount_lt?: Maybe<Scalars['BigInt']>; sendingCancelTxCount_gte?: Maybe<Scalars['BigInt']>; sendingCancelTxCount_lte?: Maybe<Scalars['BigInt']>; sendingCancelTxCount_in?: Maybe<Array<Scalars['BigInt']>>; sendingCancelTxCount_not_in?: Maybe<Array<Scalars['BigInt']>>; receivingPrepareTxCount?: Maybe<Scalars['BigInt']>; receivingPrepareTxCount_not?: Maybe<Scalars['BigInt']>; receivingPrepareTxCount_gt?: Maybe<Scalars['BigInt']>; receivingPrepareTxCount_lt?: Maybe<Scalars['BigInt']>; receivingPrepareTxCount_gte?: Maybe<Scalars['BigInt']>; receivingPrepareTxCount_lte?: Maybe<Scalars['BigInt']>; receivingPrepareTxCount_in?: Maybe<Array<Scalars['BigInt']>>; receivingPrepareTxCount_not_in?: Maybe<Array<Scalars['BigInt']>>; receivingFulfillTxCount?: Maybe<Scalars['BigInt']>; receivingFulfillTxCount_not?: Maybe<Scalars['BigInt']>; receivingFulfillTxCount_gt?: Maybe<Scalars['BigInt']>; receivingFulfillTxCount_lt?: Maybe<Scalars['BigInt']>; receivingFulfillTxCount_gte?: Maybe<Scalars['BigInt']>; receivingFulfillTxCount_lte?: Maybe<Scalars['BigInt']>; receivingFulfillTxCount_in?: Maybe<Array<Scalars['BigInt']>>; receivingFulfillTxCount_not_in?: Maybe<Array<Scalars['BigInt']>>; receivingCancelTxCount?: Maybe<Scalars['BigInt']>; receivingCancelTxCount_not?: Maybe<Scalars['BigInt']>; receivingCancelTxCount_gt?: Maybe<Scalars['BigInt']>; receivingCancelTxCount_lt?: Maybe<Scalars['BigInt']>; receivingCancelTxCount_gte?: Maybe<Scalars['BigInt']>; receivingCancelTxCount_lte?: Maybe<Scalars['BigInt']>; receivingCancelTxCount_in?: Maybe<Array<Scalars['BigInt']>>; receivingCancelTxCount_not_in?: Maybe<Array<Scalars['BigInt']>>; }; export enum AssetBalance_OrderBy { Id = 'id', Amount = 'amount', Router = 'router', AssetId = 'assetId', Supplied = 'supplied', Removed = 'removed', LockedIn = 'lockedIn', VolumeIn = 'volumeIn', Locked = 'locked', Volume = 'volume', SendingPrepareTxCount = 'sendingPrepareTxCount', SendingFulfillTxCount = 'sendingFulfillTxCount', SendingCancelTxCount = 'sendingCancelTxCount', ReceivingPrepareTxCount = 'receivingPrepareTxCount', ReceivingFulfillTxCount = 'receivingFulfillTxCount', ReceivingCancelTxCount = 'receivingCancelTxCount' } export type Block_Height = { hash?: Maybe<Scalars['Bytes']>; number?: Maybe<Scalars['Int']>; number_gte?: Maybe<Scalars['Int']>; }; export type DayMetric = { __typename?: 'DayMetric'; id: Scalars['ID']; dayStartTimestamp: Scalars['BigInt']; assetId: Scalars['String']; volume: Scalars['BigInt']; relayerFee: Scalars['BigInt']; sendingTxCount: Scalars['BigInt']; receivingTxCount: Scalars['BigInt']; cancelTxCount: Scalars['BigInt']; volumeIn: Scalars['BigInt']; }; export type DayMetric_Filter = { id?: Maybe<Scalars['ID']>; id_not?: Maybe<Scalars['ID']>; id_gt?: Maybe<Scalars['ID']>; id_lt?: Maybe<Scalars['ID']>; id_gte?: Maybe<Scalars['ID']>; id_lte?: Maybe<Scalars['ID']>; id_in?: Maybe<Array<Scalars['ID']>>; id_not_in?: Maybe<Array<Scalars['ID']>>; dayStartTimestamp?: Maybe<Scalars['BigInt']>; dayStartTimestamp_not?: Maybe<Scalars['BigInt']>; dayStartTimestamp_gt?: Maybe<Scalars['BigInt']>; dayStartTimestamp_lt?: Maybe<Scalars['BigInt']>; dayStartTimestamp_gte?: Maybe<Scalars['BigInt']>; dayStartTimestamp_lte?: Maybe<Scalars['BigInt']>; dayStartTimestamp_in?: Maybe<Array<Scalars['BigInt']>>; dayStartTimestamp_not_in?: Maybe<Array<Scalars['BigInt']>>; assetId?: Maybe<Scalars['String']>; assetId_not?: Maybe<Scalars['String']>; assetId_gt?: Maybe<Scalars['String']>; assetId_lt?: Maybe<Scalars['String']>; assetId_gte?: Maybe<Scalars['String']>; assetId_lte?: Maybe<Scalars['String']>; assetId_in?: Maybe<Array<Scalars['String']>>; assetId_not_in?: Maybe<Array<Scalars['String']>>; assetId_contains?: Maybe<Scalars['String']>; assetId_not_contains?: Maybe<Scalars['String']>; assetId_starts_with?: Maybe<Scalars['String']>; assetId_not_starts_with?: Maybe<Scalars['String']>; assetId_ends_with?: Maybe<Scalars['String']>; assetId_not_ends_with?: Maybe<Scalars['String']>; volume?: Maybe<Scalars['BigInt']>; volume_not?: Maybe<Scalars['BigInt']>; volume_gt?: Maybe<Scalars['BigInt']>; volume_lt?: Maybe<Scalars['BigInt']>; volume_gte?: Maybe<Scalars['BigInt']>; volume_lte?: Maybe<Scalars['BigInt']>; volume_in?: Maybe<Array<Scalars['BigInt']>>; volume_not_in?: Maybe<Array<Scalars['BigInt']>>; relayerFee?: Maybe<Scalars['BigInt']>; relayerFee_not?: Maybe<Scalars['BigInt']>; relayerFee_gt?: Maybe<Scalars['BigInt']>; relayerFee_lt?: Maybe<Scalars['BigInt']>; relayerFee_gte?: Maybe<Scalars['BigInt']>; relayerFee_lte?: Maybe<Scalars['BigInt']>; relayerFee_in?: Maybe<Array<Scalars['BigInt']>>; relayerFee_not_in?: Maybe<Array<Scalars['BigInt']>>; sendingTxCount?: Maybe<Scalars['BigInt']>; sendingTxCount_not?: Maybe<Scalars['BigInt']>; sendingTxCount_gt?: Maybe<Scalars['BigInt']>; sendingTxCount_lt?: Maybe<Scalars['BigInt']>; sendingTxCount_gte?: Maybe<Scalars['BigInt']>; sendingTxCount_lte?: Maybe<Scalars['BigInt']>; sendingTxCount_in?: Maybe<Array<Scalars['BigInt']>>; sendingTxCount_not_in?: Maybe<Array<Scalars['BigInt']>>; receivingTxCount?: Maybe<Scalars['BigInt']>; receivingTxCount_not?: Maybe<Scalars['BigInt']>; receivingTxCount_gt?: Maybe<Scalars['BigInt']>; receivingTxCount_lt?: Maybe<Scalars['BigInt']>; receivingTxCount_gte?: Maybe<Scalars['BigInt']>; receivingTxCount_lte?: Maybe<Scalars['BigInt']>; receivingTxCount_in?: Maybe<Array<Scalars['BigInt']>>; receivingTxCount_not_in?: Maybe<Array<Scalars['BigInt']>>; cancelTxCount?: Maybe<Scalars['BigInt']>; cancelTxCount_not?: Maybe<Scalars['BigInt']>; cancelTxCount_gt?: Maybe<Scalars['BigInt']>; cancelTxCount_lt?: Maybe<Scalars['BigInt']>; cancelTxCount_gte?: Maybe<Scalars['BigInt']>; cancelTxCount_lte?: Maybe<Scalars['BigInt']>; cancelTxCount_in?: Maybe<Array<Scalars['BigInt']>>; cancelTxCount_not_in?: Maybe<Array<Scalars['BigInt']>>; volumeIn?: Maybe<Scalars['BigInt']>; volumeIn_not?: Maybe<Scalars['BigInt']>; volumeIn_gt?: Maybe<Scalars['BigInt']>; volumeIn_lt?: Maybe<Scalars['BigInt']>; volumeIn_gte?: Maybe<Scalars['BigInt']>; volumeIn_lte?: Maybe<Scalars['BigInt']>; volumeIn_in?: Maybe<Array<Scalars['BigInt']>>; volumeIn_not_in?: Maybe<Array<Scalars['BigInt']>>; }; export enum DayMetric_OrderBy { Id = 'id', DayStartTimestamp = 'dayStartTimestamp', AssetId = 'assetId', Volume = 'volume', RelayerFee = 'relayerFee', SendingTxCount = 'sendingTxCount', ReceivingTxCount = 'receivingTxCount', CancelTxCount = 'cancelTxCount', VolumeIn = 'volumeIn' } export enum OrderDirection { Asc = 'asc', Desc = 'desc' } export type Query = { __typename?: 'Query'; assetBalance?: Maybe<AssetBalance>; assetBalances: Array<AssetBalance>; router?: Maybe<Router>; routers: Array<Router>; dayMetric?: Maybe<DayMetric>; dayMetrics: Array<DayMetric>; /** Access to subgraph metadata */ _meta?: Maybe<_Meta_>; }; export type QueryAssetBalanceArgs = { id: Scalars['ID']; block?: Maybe<Block_Height>; subgraphError?: _SubgraphErrorPolicy_; }; export type QueryAssetBalancesArgs = { skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; orderBy?: Maybe<AssetBalance_OrderBy>; orderDirection?: Maybe<OrderDirection>; where?: Maybe<AssetBalance_Filter>; block?: Maybe<Block_Height>; subgraphError?: _SubgraphErrorPolicy_; }; export type QueryRouterArgs = { id: Scalars['ID']; block?: Maybe<Block_Height>; subgraphError?: _SubgraphErrorPolicy_; }; export type QueryRoutersArgs = { skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; orderBy?: Maybe<Router_OrderBy>; orderDirection?: Maybe<OrderDirection>; where?: Maybe<Router_Filter>; block?: Maybe<Block_Height>; subgraphError?: _SubgraphErrorPolicy_; }; export type QueryDayMetricArgs = { id: Scalars['ID']; block?: Maybe<Block_Height>; subgraphError?: _SubgraphErrorPolicy_; }; export type QueryDayMetricsArgs = { skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; orderBy?: Maybe<DayMetric_OrderBy>; orderDirection?: Maybe<OrderDirection>; where?: Maybe<DayMetric_Filter>; block?: Maybe<Block_Height>; subgraphError?: _SubgraphErrorPolicy_; }; export type Query_MetaArgs = { block?: Maybe<Block_Height>; }; export type Router = { __typename?: 'Router'; id: Scalars['ID']; assetBalances: Array<AssetBalance>; }; export type RouterAssetBalancesArgs = { skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; orderBy?: Maybe<AssetBalance_OrderBy>; orderDirection?: Maybe<OrderDirection>; where?: Maybe<AssetBalance_Filter>; }; export type Router_Filter = { id?: Maybe<Scalars['ID']>; id_not?: Maybe<Scalars['ID']>; id_gt?: Maybe<Scalars['ID']>; id_lt?: Maybe<Scalars['ID']>; id_gte?: Maybe<Scalars['ID']>; id_lte?: Maybe<Scalars['ID']>; id_in?: Maybe<Array<Scalars['ID']>>; id_not_in?: Maybe<Array<Scalars['ID']>>; }; export enum Router_OrderBy { Id = 'id', AssetBalances = 'assetBalances' } export type Subscription = { __typename?: 'Subscription'; assetBalance?: Maybe<AssetBalance>; assetBalances: Array<AssetBalance>; router?: Maybe<Router>; routers: Array<Router>; dayMetric?: Maybe<DayMetric>; dayMetrics: Array<DayMetric>; /** Access to subgraph metadata */ _meta?: Maybe<_Meta_>; }; export type SubscriptionAssetBalanceArgs = { id: Scalars['ID']; block?: Maybe<Block_Height>; subgraphError?: _SubgraphErrorPolicy_; }; export type SubscriptionAssetBalancesArgs = { skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; orderBy?: Maybe<AssetBalance_OrderBy>; orderDirection?: Maybe<OrderDirection>; where?: Maybe<AssetBalance_Filter>; block?: Maybe<Block_Height>; subgraphError?: _SubgraphErrorPolicy_; }; export type SubscriptionRouterArgs = { id: Scalars['ID']; block?: Maybe<Block_Height>; subgraphError?: _SubgraphErrorPolicy_; }; export type SubscriptionRoutersArgs = { skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; orderBy?: Maybe<Router_OrderBy>; orderDirection?: Maybe<OrderDirection>; where?: Maybe<Router_Filter>; block?: Maybe<Block_Height>; subgraphError?: _SubgraphErrorPolicy_; }; export type SubscriptionDayMetricArgs = { id: Scalars['ID']; block?: Maybe<Block_Height>; subgraphError?: _SubgraphErrorPolicy_; }; export type SubscriptionDayMetricsArgs = { skip?: Maybe<Scalars['Int']>; first?: Maybe<Scalars['Int']>; orderBy?: Maybe<DayMetric_OrderBy>; orderDirection?: Maybe<OrderDirection>; where?: Maybe<DayMetric_Filter>; block?: Maybe<Block_Height>; subgraphError?: _SubgraphErrorPolicy_; }; export type Subscription_MetaArgs = { block?: Maybe<Block_Height>; }; export type _Block_ = { __typename?: '_Block_'; /** The hash of the block */ hash?: Maybe<Scalars['Bytes']>; /** The block number */ number: Scalars['Int']; }; /** The type for the top-level _meta field */ export type _Meta_ = { __typename?: '_Meta_'; /** * Information about a specific subgraph block. The hash of the block * will be null if the _meta field has a block constraint that asks for * a block number. It will be filled if the _meta field has no block constraint * and therefore asks for the latest block * */ block: _Block_; /** The deployment ID */ deployment: Scalars['String']; /** If `true`, the subgraph encountered indexing errors at some past block */ hasIndexingErrors: Scalars['Boolean']; }; export enum _SubgraphErrorPolicy_ { /** Data will be returned even if the subgraph has indexing errors */ Allow = 'allow', /** If the subgraph has indexing errors, data will be omitted. The default. */ Deny = 'deny' } export type GetExpressiveAssetBalancesQueryVariables = Exact<{ routerId: Scalars['String']; }>; export type GetExpressiveAssetBalancesQuery = { __typename?: 'Query', assetBalances: Array<{ __typename?: 'AssetBalance', amount: any, assetId: any, locked: any, supplied: any, removed: any }> }; export type GetBlockNumberQueryVariables = Exact<{ [key: string]: never; }>; export type GetBlockNumberQuery = { __typename?: 'Query', _meta?: Maybe<{ __typename?: '_Meta_', block: { __typename?: '_Block_', number: number } }> }; export const GetExpressiveAssetBalancesDocument = gql` query GetExpressiveAssetBalances($routerId: String!) { assetBalances(where: {router: $routerId}) { amount assetId locked supplied removed } } `; export const GetBlockNumberDocument = gql` query GetBlockNumber { _meta { block { number } } } `; export type SdkFunctionWrapper = <T>(action: (requestHeaders?:Record<string, string>) => Promise<T>, operationName: string) => Promise<T>; const defaultWrapper: SdkFunctionWrapper = (action, _operationName) => action(); export function getSdk(client: GraphQLClient, withWrapper: SdkFunctionWrapper = defaultWrapper) { return { GetExpressiveAssetBalances(variables: GetExpressiveAssetBalancesQueryVariables, requestHeaders?: Dom.RequestInit["headers"]): Promise<GetExpressiveAssetBalancesQuery> { return withWrapper((wrappedRequestHeaders) => client.request<GetExpressiveAssetBalancesQuery>(GetExpressiveAssetBalancesDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'GetExpressiveAssetBalances'); }, GetBlockNumber(variables?: GetBlockNumberQueryVariables, requestHeaders?: Dom.RequestInit["headers"]): Promise<GetBlockNumberQuery> { return withWrapper((wrappedRequestHeaders) => client.request<GetBlockNumberQuery>(GetBlockNumberDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'GetBlockNumber'); } }; } export type Sdk = ReturnType<typeof getSdk>;
the_stack
import { Injectable } from "@angular/core"; import { DraggablePort } from "@ng-public/directive/draggable/draggable.interface"; import { CornerPinModel, ProfileModel } from "./model"; import { PanelScopeEnchantmentService } from "./panel-scope-enchantment.service"; import { PanelWidgetModel } from "../panel-widget/model"; import { BehaviorSubject } from "rxjs"; /** * 八个方位的拖拽拉伸计算 服务 */ @Injectable() export class DraggableTensileCursorService { // 是否按住了shift键从而等比例的进行缩放 public isOpenConstrainShift$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false); constructor(private readonly panelScopeEnchantmentService: PanelScopeEnchantmentService) {} // 计算pro轮廓的sin偏移量 public calcSinOffset(pro: ProfileModel, type: "height" | "width"): number { return this.panelScopeEnchantmentService.calcNumSin((pro[type] - pro.immobilizationData[type]) / 2, pro.rotate); } // 计算pro轮廓的cos偏移量 public calcCosOffset(pro: ProfileModel, type: "height" | "width"): number { return ( this.panelScopeEnchantmentService.calcNumCos((pro[type] - pro.immobilizationData[type]) / 2, pro.rotate) + (pro[type] - pro.immobilizationData[type]) / 2 ); } // 计算pro轮廓的1-cos偏移量,用于计算right拉伸和bottom的拉伸计算 public calcCosOffsetReducOne(pro: ProfileModel, type: "height" | "width"): number { return ( ((1 - Math.cos(this.panelScopeEnchantmentService.conversionRotateToMathDegree(pro.rotate))) * (pro[type] - pro.immobilizationData[type])) / 2 ); } // 根据旋转角度计算DraggablePort鼠标坐标点返回的坐标点,使其在旋转到对应的角度之后,被拉伸的方向也一致 public calcRotateDraggablePort(drag: DraggablePort, rotate: number, type: "l" | "t" | "r" | "b"): number { const s = { l: this.panelScopeEnchantmentService.calcNumCos(drag.left * -1, rotate) + this.panelScopeEnchantmentService.calcNumSin(drag.top * -1, rotate), t: this.panelScopeEnchantmentService.calcNumCos(drag.top * -1, rotate) + this.panelScopeEnchantmentService.calcNumSin(drag.left, rotate), r: this.panelScopeEnchantmentService.calcNumCos(drag.left, rotate) + this.panelScopeEnchantmentService.calcNumSin(drag.top, rotate), b: this.panelScopeEnchantmentService.calcNumCos(drag.top, rotate) + this.panelScopeEnchantmentService.calcNumSin(drag.left * -1, rotate), }; return s[type] ? Math.round(s[type]) : 0; } /** * 调整被选中组件在主轮廓里的位置比例 * 同时根据角度限制主轮廓完全包住被选组件 */ public handleInsetWidgetPositionProportion(wPro: PanelWidgetModel): void { const pro = this.panelScopeEnchantmentService.scopeEnchantmentModel.valueProfileOuterSphere; if (wPro.profileModel.insetProOuterSphereFourProportion) { wPro.profileModel.left = pro.width * wPro.profileModel.insetProOuterSphereFourProportion.left + pro.left; wPro.profileModel.top = pro.height * wPro.profileModel.insetProOuterSphereFourProportion.top + pro.top; wPro.profileModel.width = pro.width * wPro.profileModel.insetProOuterSphereFourProportion.right - wPro.profileModel.left + pro.left; wPro.profileModel.height = pro.height * wPro.profileModel.insetProOuterSphereFourProportion.bottom - wPro.profileModel.top + pro.top; wPro.addStyleToUltimatelyStyle({ height: `${wPro.profileModel.height}px`, width: `${wPro.profileModel.width}px`, }); } } /** * 在拖拽的过程当中重新计算主轮廓的大小和位置 * 重新调整使其能够完全包住所有被选组件 */ public handleCalcProfileOuterSphere(drag: DraggablePort): void { const pro = this.panelScopeEnchantmentService.scopeEnchantmentModel.valueProfileOuterSphere; const insetWidget = this.panelScopeEnchantmentService.scopeEnchantmentModel.outerSphereInsetWidgetList$.value; if (insetWidget.length > 1 && drag) { const sphere = this.panelScopeEnchantmentService.calcProfileOuterSphereInfo(); pro.setData({ left: sphere.left, top: sphere.top, width: sphere.width, height: sphere.height, }); } } /** * 接受八个拖拽点移动的回调 */ public acceptDraggableCursor(drag: DraggablePort, corner: CornerPinModel): void { const insetWidget = this.panelScopeEnchantmentService.scopeEnchantmentModel.outerSphereInsetWidgetList$.value; if (drag && corner.cursor != undefined) { const pro = this.panelScopeEnchantmentService.scopeEnchantmentModel.valueProfileOuterSphere; const objCur = { l: () => { pro.setData({ width: pro.width + this.calcRotateDraggablePort(drag, pro.rotate, "l"), }); pro.setData({ height: this.isOpenConstrainShift$.value ? (pro.immobilizationData.height / pro.immobilizationData.width) * pro.width : pro.immobilizationData.height, }); pro.setData({ left: Math.round( pro.immobilizationData.left - this.calcSinOffset(pro, "height") - this.calcCosOffset(pro, "width") ), top: Math.round( pro.immobilizationData.top - this.calcCosOffsetReducOne(pro, "height") - this.calcSinOffset(pro, "width") ), }); }, t: () => { pro.setData({ height: pro.height + this.calcRotateDraggablePort(drag, pro.rotate, "t"), }); pro.setData({ width: this.isOpenConstrainShift$.value ? (pro.immobilizationData.width / pro.immobilizationData.height) * pro.height : pro.immobilizationData.width, }); pro.setData({ left: Math.round( pro.immobilizationData.left - this.calcCosOffsetReducOne(pro, "width") + this.calcSinOffset(pro, "height") ), top: Math.round( pro.immobilizationData.top + this.calcSinOffset(pro, "width") - this.calcCosOffset(pro, "height") ), }); }, r: () => { pro.setData({ width: pro.width + this.calcRotateDraggablePort(drag, pro.rotate, "r"), }); pro.setData({ height: this.isOpenConstrainShift$.value ? (pro.immobilizationData.height / pro.immobilizationData.width) * pro.width : pro.immobilizationData.height, }); pro.setData({ left: Math.round( pro.immobilizationData.left - this.calcSinOffset(pro, "height") - this.calcCosOffsetReducOne(pro, "width") ), top: Math.round( pro.immobilizationData.top - this.calcCosOffsetReducOne(pro, "height") + this.calcSinOffset(pro, "width") ), }); }, b: () => { pro.setData({ height: pro.height + this.calcRotateDraggablePort(drag, pro.rotate, "b"), }); pro.setData({ width: this.isOpenConstrainShift$.value ? (pro.immobilizationData.width / pro.immobilizationData.height) * pro.height : pro.immobilizationData.width, }); pro.setData({ left: Math.round( pro.immobilizationData.left - this.calcSinOffset(pro, "height") - this.calcCosOffsetReducOne(pro, "width") ), top: Math.round( pro.immobilizationData.top - this.calcCosOffsetReducOne(pro, "height") + this.calcSinOffset(pro, "width") ), }); }, lt: () => { const calcWidth = pro.width + this.calcRotateDraggablePort(drag, pro.rotate, "l"); pro.setData({ height: pro.height + this.calcRotateDraggablePort(drag, pro.rotate, "t"), }); pro.setData({ width: this.isOpenConstrainShift$.value ? (pro.immobilizationData.width / pro.immobilizationData.height) * pro.height : calcWidth, }); pro.setData({ left: Math.round( pro.immobilizationData.left - this.calcCosOffset(pro, "width") + this.calcSinOffset(pro, "height") ), top: Math.round( pro.immobilizationData.top - this.calcSinOffset(pro, "width") - this.calcCosOffset(pro, "height") ), }); }, rt: () => { const calcWidth = pro.width + this.calcRotateDraggablePort(drag, pro.rotate, "r"); pro.setData({ height: pro.height + this.calcRotateDraggablePort(drag, pro.rotate, "t"), }); pro.setData({ width: this.isOpenConstrainShift$.value ? (pro.immobilizationData.width / pro.immobilizationData.height) * pro.height : calcWidth, }); pro.setData({ left: Math.round( pro.immobilizationData.left - this.calcCosOffsetReducOne(pro, "width") + this.calcSinOffset(pro, "height") ), top: Math.round( pro.immobilizationData.top + this.calcSinOffset(pro, "width") - this.calcCosOffset(pro, "height") ), }); }, rb: () => { const calcWidth = pro.width + this.calcRotateDraggablePort(drag, pro.rotate, "r"); pro.setData({ height: pro.height + this.calcRotateDraggablePort(drag, pro.rotate, "b"), }); pro.setData({ width: this.isOpenConstrainShift$.value ? (pro.immobilizationData.width / pro.immobilizationData.height) * pro.height : calcWidth, }); pro.setData({ left: Math.round( pro.immobilizationData.left - this.calcSinOffset(pro, "height") - this.calcCosOffsetReducOne(pro, "width") ), top: Math.round( pro.immobilizationData.top - this.calcCosOffsetReducOne(pro, "height") + this.calcSinOffset(pro, "width") ), }); }, lb: () => { const calcWidth = pro.width + this.calcRotateDraggablePort(drag, pro.rotate, "l"); pro.setData({ height: pro.height + this.calcRotateDraggablePort(drag, pro.rotate, "b"), }); pro.setData({ width: this.isOpenConstrainShift$.value ? (pro.immobilizationData.width / pro.immobilizationData.height) * pro.height : calcWidth, }); pro.setData({ left: Math.round( pro.immobilizationData.left - this.calcSinOffset(pro, "height") - this.calcCosOffset(pro, "width") ), top: Math.round( pro.immobilizationData.top - this.calcCosOffsetReducOne(pro, "height") - this.calcSinOffset(pro, "width") ), }); }, }; if (objCur[corner.cursor]) { objCur[corner.cursor](); insetWidget.forEach(e => { this.handleInsetWidgetPositionProportion(e); }); } } // 重新计算主轮廓的大小和位置 this.handleCalcProfileOuterSphere(drag); // 如果有文本设置的组件则改变文本设置的状态 insetWidget.forEach(w => { if (w.panelTextModel) { setTimeout(() => { const textStyle = w.panelTextModel.styleContent(w.conventionSiteModel.height); w.addStyleToUltimatelyStyle(textStyle); }); } }); } }
the_stack
import { Store } from '@t/store'; import { SelectionRange } from '@t/store/selection'; import { KeyboardEventCommandType, TabCommandType } from '../helper/keyboard'; import { getNextCellIndex, getRemoveRange, getNextCellIndexWithRowSpan } from '../query/keyboard'; import { changeFocus, startEditing } from './focus'; import { changeSelectionRange } from './selection'; import { isRowHeader } from '../helper/column'; import { getRowRangeWithRowSpan, isRowSpanEnabled } from '../query/rowSpan'; import { getDataManager } from '../instance'; import { getEventBus } from '../event/eventBus'; import GridEvent from '../event/gridEvent'; import { createChangeInfo, isEditableCell, getRowKeyByIndexWithPageRange } from '../query/data'; import { forceValidateUniquenessOfColumns } from '../store/helper/validation'; import { copyDataToRange, getRangeToPaste } from '../query/clipboard'; import { mapProp } from '../helper/common'; import { CellChange, Origin } from '@t/event'; import { updateAllSummaryValues } from './summary'; import { appendRows, updateHeights } from './data'; type ChangeValueFn = () => number; interface ChangeInfo { prevChanges: CellChange[]; nextChanges: CellChange[]; changeValueFns: ChangeValueFn[]; } export function moveFocus(store: Store, command: KeyboardEventCommandType) { const { focus, data, column: { visibleColumnsWithRowHeader }, id, } = store; const { rowIndex, totalColumnIndex: columnIndex } = focus; if (rowIndex === null || columnIndex === null) { return; } const [nextRowIndex, nextColumnIndex] = getNextCellIndex(store, command, [rowIndex, columnIndex]); const nextColumnName = visibleColumnsWithRowHeader[nextColumnIndex].name; if (!isRowHeader(nextColumnName)) { focus.navigating = true; changeFocus(store, getRowKeyByIndexWithPageRange(data, nextRowIndex), nextColumnName, id); } } export function editFocus(store: Store, command: KeyboardEventCommandType) { const { rowKey, columnName } = store.focus; if (rowKey === null || columnName === null) { return; } if (command === 'currentCell') { startEditing(store, rowKey, columnName); } else if (command === 'nextCell' || command === 'prevCell') { // move prevCell or nextCell by tab keyMap moveTabFocus(store, command); } } export function moveTabFocus(store: Store, command: TabCommandType) { const { focus, data, column, id } = store; const { visibleColumnsWithRowHeader } = column; const { rowKey, columnName, rowIndex, totalColumnIndex: columnIndex } = focus; if (rowKey === null || columnName === null || rowIndex === null || columnIndex === null) { return; } const [nextRowIndex, nextColumnIndex] = getNextCellIndex(store, command, [rowIndex, columnIndex]); const nextRowKey = getRowKeyByIndexWithPageRange(data, nextRowIndex); const nextColumnName = visibleColumnsWithRowHeader[nextColumnIndex].name; if (!isRowHeader(nextColumnName)) { focus.navigating = true; changeFocus(store, nextRowKey, nextColumnName, id); if ( focus.tabMode === 'moveAndEdit' && focus.rowKey === nextRowKey && focus.columnName === nextColumnName ) { setTimeout(() => { startEditing(store, nextRowKey, nextColumnName); }); } } } export function moveSelection(store: Store, command: KeyboardEventCommandType) { const { selection, focus, data, column, id } = store; const { visibleColumnsWithRowHeader, rowHeaderCount } = column; const { filteredViewData, sortState } = data; const { rowIndex: focusRowIndex, totalColumnIndex: totalFocusColumnIndex } = focus; let { inputRange: currentInputRange } = selection; if (focusRowIndex === null || totalFocusColumnIndex === null) { return; } if (!currentInputRange) { currentInputRange = selection.inputRange = { row: [focusRowIndex, focusRowIndex], column: [totalFocusColumnIndex, totalFocusColumnIndex], }; } const rowLength = filteredViewData.length; const columnLength = visibleColumnsWithRowHeader.length; let rowStartIndex = currentInputRange.row[0]; const rowIndex = currentInputRange.row[1]; let columnStartIndex = currentInputRange.column[0]; const columnIndex = currentInputRange.column[1]; let nextCellIndexes; if (command === 'all') { rowStartIndex = 0; columnStartIndex = rowHeaderCount; nextCellIndexes = [rowLength - 1, columnLength - 1]; } else { nextCellIndexes = getNextCellIndex(store, command, [rowIndex, columnIndex]); if (isRowSpanEnabled(sortState, column)) { nextCellIndexes = getNextCellIndexWithRowSpan( store, command, rowIndex, [columnStartIndex, columnIndex], nextCellIndexes ); } } const [nextRowIndex, nextColumnIndex] = nextCellIndexes; const nextColumnName = visibleColumnsWithRowHeader[nextColumnIndex].name; let startRowIndex = rowStartIndex; let endRowIndex = nextRowIndex; if (command !== 'all') { [startRowIndex, endRowIndex] = getRowRangeWithRowSpan( [startRowIndex, endRowIndex], [columnStartIndex, nextColumnIndex], column, focus.rowIndex, data ); } if (!isRowHeader(nextColumnName)) { const inputRange: SelectionRange = { row: [startRowIndex, endRowIndex], column: [columnStartIndex, nextColumnIndex], }; changeSelectionRange(selection, inputRange, id); } } export function removeContent(store: Store) { const { column, data } = store; const range = getRemoveRange(store); if (!range) { return; } const { column: [columnStart, columnEnd], row: [rowStart, rowEnd], } = range; const changeValueFns: ChangeValueFn[] = []; const prevChanges: CellChange[] = []; const nextChanges: CellChange[] = []; data.filteredRawData.slice(rowStart, rowEnd + 1).forEach((row, index) => { column.visibleColumnsWithRowHeader.slice(columnStart, columnEnd + 1).forEach(({ name }) => { const rowIndex = index + rowStart; if (isEditableCell(store, rowIndex, name)) { const { prevChange, nextChange, changeValue } = createChangeInfo( store, row, name, '', rowIndex ); prevChanges.push(prevChange); nextChanges.push(nextChange); changeValueFns.push(changeValue); } }); }); updateDataByKeyMap(store, 'delete', { prevChanges, nextChanges, changeValueFns }); } function applyCopiedData(store: Store, copiedData: string[][], range: SelectionRange) { const { data, column } = store; const { filteredRawData, filteredViewData } = data; const { visibleColumnsWithRowHeader } = column; const { row: [startRowIndex, endRowIndex], column: [startColumnIndex, endColumnIndex], } = range; const columnNames = mapProp('name', visibleColumnsWithRowHeader); const changeValueFns = []; const prevChanges = []; const nextChanges = []; for (let rowIndex = 0; rowIndex + startRowIndex <= endRowIndex; rowIndex += 1) { const rawRowIndex = rowIndex + startRowIndex; for (let columnIndex = 0; columnIndex + startColumnIndex <= endColumnIndex; columnIndex += 1) { const name = columnNames[columnIndex + startColumnIndex]; if (filteredViewData.length && isEditableCell(store, rawRowIndex, name)) { const targetRow = filteredRawData[rawRowIndex]; const { prevChange, nextChange, changeValue } = createChangeInfo( store, targetRow, name, copiedData[rowIndex][columnIndex], rawRowIndex ); prevChanges.push(prevChange); nextChanges.push(nextChange); changeValueFns.push(changeValue); } } } updateDataByKeyMap(store, 'paste', { prevChanges, nextChanges, changeValueFns }); } export function paste(store: Store, copiedData: string[][]) { const { selection, id, data: { viewData }, } = store; const { originalRange } = selection; if (originalRange) { copiedData = copyDataToRange(originalRange, copiedData); } const rangeToPaste = getRangeToPaste(store, copiedData); const endRowIndex = rangeToPaste.row[1]; if (endRowIndex > viewData.length - 1) { appendRows( store, [...Array(endRowIndex - viewData.length + 1)].map(() => ({})) ); } applyCopiedData(store, copiedData, rangeToPaste); changeSelectionRange(selection, rangeToPaste, id); } export function updateDataByKeyMap(store: Store, origin: Origin, changeInfo: ChangeInfo) { const { id, data, column } = store; const { rawData, filteredRawData } = data; const { prevChanges, nextChanges, changeValueFns } = changeInfo; const eventBus = getEventBus(id); const manager = getDataManager(id); let gridEvent = new GridEvent({ origin, changes: prevChanges }); /** * Occurs before one or more cells is changed * @event Grid#beforeChange * @property {string} origin - The type of change('paste', 'delete', 'cell') * @property {Array.<object>} changes - rowKey, column name, original values and next values before changing the values * @property {Grid} instance - Current grid instance */ eventBus.trigger('beforeChange', gridEvent); if (gridEvent.isStopped()) { return; } let index: number | null = null; changeValueFns.forEach((changeValue) => { const targetRowIndex = changeValue(); if (index !== targetRowIndex) { index = targetRowIndex; manager.push('UPDATE', filteredRawData[index]); } }); updateAllSummaryValues(store); forceValidateUniquenessOfColumns(rawData, column); updateHeights(store); gridEvent = new GridEvent({ origin, changes: nextChanges }); /** * Occurs after one or more cells is changed * @event Grid#afterChange * @property {string} origin - The type of change('paste', 'delete', 'cell') * @property {Array.<object>} changes - rowKey, column name, previous values and changed values after changing the values * @property {Grid} instance - Current grid instance */ eventBus.trigger('afterChange', gridEvent); }
the_stack
import stream from "@/api"; import { fieldDelimiter, intervalTime, restfulDecode, restfulFields, restfulParam, strategy, writeDataSequence, writeDocForADB } from "@/components/helpDoc/docs"; import { NEST_KEYS, RESTFUL_METHOD, RESTFUL_PROPTOCOL, RESTFUL_RESP_MODE, RESTFUL_STRATEGY } from "@/constant"; import { Button, Card, Checkbox, Form, Input, InputNumber, message, Radio, Select, Table } from "antd"; import { MinusCircleOutlined, UpOutlined } from "@ant-design/icons"; import React, { useEffect, useState } from "react"; import { checkUrl } from "../../helper"; import { streamTaskActions } from "../../taskFunc"; import EditTable from "../editTable"; import Editor from "@/components/editor"; const FormItem = Form.Item; const Option = Select.Option; const tabList = [{ key: '0', tab: '第一次请求' }, { key: '1', tab: '第二次请求' }]; const editorOptions: any = { mode: 'resetfulPreview', lineNumbers: false, readOnly: true, autofocus: false, indentWithTabs: true, smartIndent: true } export default (props: { collectionData: any; }) => { const { collectionData } = props; const { isEdit, targetMap, sourceMap } = collectionData; const { requestMode, decode, param, body, url, requestInterval } = sourceMap; const [failedValiData, setFailedValiData] = useState<any>({}); const [previewLoading, setPreviewLoading] = useState(false); const [restfulPreviewVisable, setRestfulPreviewVisable] = useState(false); const [restfulPreviewData, setRestfulPreviewData] = useState<any>({}); const [previewTabKey, setPreviewTabKey] = useState('0') const loadRestFulPreview = async () => { if (!checkUrl(url) || !requestInterval) { message.error(!checkUrl(url) ? '请输入正确的URL' : '请输入请求间隔') return } setPreviewLoading(true) const res = await stream.getRestfulDataPreview(sourceMap) if (!(res && res?.success)) { setPreviewLoading(false) return } setPreviewLoading(false); setRestfulPreviewVisable(true); setRestfulPreviewData(res?.data); } const validateParams = (dataSource: any, requireFields: any) => { if (!requireFields.length) return true for (let i = 0; i <= dataSource.length - 1; i++) { const data = dataSource[i] for (const field of requireFields) { if (!data[field]) { setFailedValiData({ [i]: { [field]: 'error' } }) return false } } } setFailedValiData({}) return true } const tableValueChange = (e: any, field: any, index: any, onTableCellChange: any) => { const data = { field, value: e.target?.value } if (e.target?.checked && !e.target?.value) data.value = e.target.checked onTableCellChange(data, index) } const validateUrl = (rule: any, val: any, callback: any) => { if (!val) { return Promise.reject(new Error('请输入URL!')) } if (val.includes(' ')) { const msg = '不支持输入空格' return Promise.reject(new Error(msg)) } if (checkUrl(val)) { return Promise.resolve(); } else { return Promise.reject(new Error('请检查您的URL链接格式!')) } } const renderSelect = (dataSource: any[]) => <Select> {dataSource.map(({ text, value }) => <Option value={value} key={value}>{text}</Option>)} </Select> const paramOrBody = requestMode === 'get' ? 'param' : 'body'; const isNesting = (param || body)?.some(({ nest }: any) => nest); const isJson = decode === 'json'; return <React.Fragment> <FormItem name="protocol" label="协议" style={{ textAlign: 'left' }} > {renderSelect(RESTFUL_PROPTOCOL)} </FormItem> <FormItem name="requestMode" label="请求方式" style={{ textAlign: 'left' }} > {renderSelect(RESTFUL_METHOD)} </FormItem> <FormItem name="url" label="URL" style={{ textAlign: 'left' }} rules={[{ validator: validateUrl }]} validateTrigger='onBlur' > <Input placeholder="http(s)://host:port" /> </FormItem> <FormItem name="header" label="Header 参数" style={{ textAlign: 'left' }} > <EditTable columns={[ { title: 'Key', dataIndex: 'key', width: '30%', render: (text: any, record: any, index: any, onTableCellChange: any) => ( <Input value={text} onChange={(e) => { tableValueChange(e, 'key', index, onTableCellChange) }} />) }, { title: 'Value', dataIndex: 'value', width: '30%', render: (text: any, record: any, index: any, onTableCellChange: any) => ( <Input value={text} onChange={(e) => { tableValueChange(e, 'value', index, onTableCellChange) }} />) }, { title: 'Description', dataIndex: 'description', width: '40%', render: (text: any, record: any, index: any, onTableCellChange: any, operations: any) => ( <div style={{ 'position': 'relative' }}> <Input value={text} onChange={(e) => { tableValueChange(e, 'description', index, onTableCellChange) }} /> <MinusCircleOutlined className="c-icon-delete" onClick={operations} /> </div>) } ]} /> </FormItem> <FormItem name={paramOrBody} label={paramOrBody === 'param' ? 'Param参数' : 'Body参数'} style={{ textAlign: 'left' }} tooltip={restfulParam} > <EditTable validator={validateParams} columns={[ { title: 'Key', dataIndex: 'key', width: '20%', required: true, render: (text: any, record: any, index: any, onTableCellChange: any) => ( <FormItem validateStatus={failedValiData[index]?.key || 'success'} help={failedValiData[index]?.key && '请输入key'} > <Input value={text} onChange={(e) => { tableValueChange(e, 'key', index, onTableCellChange) }} /> </FormItem>) }, { title: 'Value', dataIndex: 'value', width: '20%', required: true, render: (text: any, record: any, index: any, onTableCellChange: any) => ( <FormItem validateStatus={failedValiData[index]?.value || 'success'} help={failedValiData[index]?.value && '请输入value'} > <Input value={text} onChange={(e) => { tableValueChange(e, 'value', index, onTableCellChange) }} /> </FormItem>) }, { title: 'NextValue', dataIndex: 'nextValue', width: '20%', render: (text: any, record: any, index: any, onTableCellChange: any) => ( <Input value={text} onChange={(e) => { tableValueChange(e, 'nextValue', index, onTableCellChange) }} />) }, { title: '嵌套', dataIndex: 'nest', width: '10%', render: (text: any, record: any, index: any, onTableCellChange: any) => ( <Checkbox checked={text} onChange={(e: any) => { tableValueChange(e, 'nest', index, onTableCellChange) }} /> ) }, { title: 'Format', dataIndex: 'format', width: '30%', render: (text: any, record: any, index: any, onTableCellChange: any, operations: any) => ( <div style={{ 'position': 'relative' }}> <Input value={text} onChange={(e) => { tableValueChange(e, 'format', index, onTableCellChange) }} /> <MinusCircleOutlined className="c-icon-delete" onClick={operations} /> </div>) } ]} /> </FormItem> {isNesting && <FormItem name="fieldDelimiter" label="嵌套切分键" style={{ textAlign: 'left' }} rules={[{ required: true, message: '请选择嵌套切分键' }]} tooltip={fieldDelimiter} > {renderSelect(NEST_KEYS)} </FormItem>} <FormItem name="strategy" label="异常策略" style={{ textAlign: 'left' }} tooltip={strategy} > <EditTable columns={[ { title: 'Key', dataIndex: 'key', width: '30%', render: (text: any, record: any, index: any, onTableCellChange: any) => ( <Input value={text} onChange={(e) => { tableValueChange(e, 'key', index, onTableCellChange) }} />) }, { title: 'Value', dataIndex: 'value', width: '30%', render: (text: any, record: any, index: any, onTableCellChange: any) => ( <Input value={text} onChange={(e) => { tableValueChange(e, 'value', index, onTableCellChange) }} />) }, { title: 'Strategy', dataIndex: 'handle', width: '40%', render: (text: any, record: any, index: any, onTableCellChange: any, operations: any) => ( <div style={{ 'position': 'relative' }}> <Select value={text} placeholder="请选择Strategy" onChange={(value) => { onTableCellChange({ field: 'handle', value }, index) }} > {RESTFUL_STRATEGY.map(({ text, value }: any) => <Option key={value} value={value}>{text}</Option>)} </Select> <MinusCircleOutlined className="c-icon-delete" onClick={operations} /> </div>) } ]} /> </FormItem> <FormItem name="decode" label="返回类型" style={{ textAlign: 'left' }} tooltip={restfulDecode} > {renderSelect(RESTFUL_RESP_MODE)} </FormItem> {isJson && <FormItem name="fields" label="指定解析字段" style={{ textAlign: 'left' }} tooltip={restfulFields} > <Input placeholder="请填写JSON中指定解析字段,多个字段用英文逗号隔开,默认不做解析" /> </FormItem>} <FormItem name="requestInterval" label="请求间隔" style={{ textAlign: 'left' }} rules={[{ required: true, message: '请输入请求时间间隔' }]} tooltip={intervalTime} > <InputNumber style={{ width: '96%' }} min={1} step={1} max={999999} precision={0} addonAfter='s' /> </FormItem> <FormItem key="startLocation" label="采集起点" style={{ textAlign: 'left' }} > 从任务运行时开始 </FormItem> <FormItem key="preview" label="数据预览" > <Button ghost loading={previewLoading} onClick={loadRestFulPreview} > 数据预览 </Button> </FormItem> {restfulPreviewVisable && <FormItem key="previewTab" label=" " className="c-restful-preview" > <Card key="previewCard" tabBarExtraContent={ <a onClick={() => { setRestfulPreviewVisable(false) }}> <UpOutlined /> </a> } tabList={tabList} activeTabKey={previewTabKey} onTabChange={(key: any) => { setPreviewTabKey(key) }} > <Editor sync value={restfulPreviewData[previewTabKey] || ''} style={{ height: '100%', maxHeight: '400px', minHeight: '0px' }} options={editorOptions} /> </Card> </FormItem>} </React.Fragment> }
the_stack
import {runInEachFileSystem} from '../../src/ngtsc/file_system/testing'; import {loadStandardTestFiles} from '../../src/ngtsc/testing'; import {NgtscTestEnvironment} from './env'; const testFiles = loadStandardTestFiles(); runInEachFileSystem(() => { describe('ngtsc incremental compilation', () => { let env!: NgtscTestEnvironment; beforeEach(() => { env = NgtscTestEnvironment.setup(testFiles); env.enableMultipleCompilations(); env.tsconfig(); }); it('should not crash if CLI does not provide getModifiedResourceFiles()', () => { env.write('component1.ts', ` import {Component} from '@angular/core'; @Component({selector: 'cmp', templateUrl: './component1.template.html'}) export class Cmp1 {} `); env.write('component1.template.html', 'cmp1'); env.driveMain(); // Simulate a change to `component1.html` env.flushWrittenFileTracking(); env.invalidateCachedFile('component1.html'); env.simulateLegacyCLICompilerHost(); env.driveMain(); }); it('should skip unchanged services', () => { env.write('service.ts', ` import {Injectable} from '@angular/core'; @Injectable() export class Service {} `); env.write('test.ts', ` import {Component} from '@angular/core'; import {Service} from './service'; @Component({selector: 'cmp', template: 'cmp'}) export class Cmp { constructor(service: Service) {} } `); env.driveMain(); env.flushWrittenFileTracking(); // Pretend a change was made to test.ts. env.invalidateCachedFile('test.ts'); env.driveMain(); const written = env.getFilesWrittenSinceLastFlush(); // The changed file should be recompiled, but not the service. expect(written).toContain('/test.js'); expect(written).not.toContain('/service.js'); }); it('should rebuild components that have changed', () => { env.tsconfig({strictTemplates: true}); env.write('component1.ts', ` import {Component} from '@angular/core'; @Component({selector: 'cmp', template: 'cmp'}) export class Cmp1 {} `); env.write('component2.ts', ` import {Component} from '@angular/core'; @Component({selector: 'cmp2', template: 'cmp'}) export class Cmp2 {} `); env.driveMain(); // Pretend a change was made to Cmp1 env.flushWrittenFileTracking(); env.invalidateCachedFile('component1.ts'); env.driveMain(); const written = env.getFilesWrittenSinceLastFlush(); expect(written).toContain('/component1.js'); expect(written).not.toContain('/component2.js'); }); it('should rebuild components whose templates have changed', () => { env.write('component1.ts', ` import {Component} from '@angular/core'; @Component({selector: 'cmp', templateUrl: './component1.template.html'}) export class Cmp1 {} `); env.write('component1.template.html', 'cmp1'); env.write('component2.ts', ` import {Component} from '@angular/core'; @Component({selector: 'cmp2', templateUrl: './component2.template.html'}) export class Cmp2 {} `); env.write('component2.template.html', 'cmp2'); env.driveMain(); // Make a change to Cmp1 template env.flushWrittenFileTracking(); env.write('component1.template.html', 'changed'); env.driveMain(); const written = env.getFilesWrittenSinceLastFlush(); expect(written).toContain('/component1.js'); expect(written).not.toContain('/component2.js'); }); it('should rebuild components whose partial-evaluation dependencies have changed', () => { env.write('component1.ts', ` import {Component} from '@angular/core'; @Component({selector: 'cmp', template: 'cmp'}) export class Cmp1 {} `); env.write('component2.ts', ` import {Component} from '@angular/core'; import {SELECTOR} from './constants'; @Component({selector: SELECTOR, template: 'cmp'}) export class Cmp2 {} `); env.write('constants.ts', ` export const SELECTOR = 'cmp'; `); env.driveMain(); // Pretend a change was made to SELECTOR env.flushWrittenFileTracking(); env.invalidateCachedFile('constants.ts'); env.driveMain(); const written = env.getFilesWrittenSinceLastFlush(); expect(written).toContain('/constants.js'); expect(written).not.toContain('/component1.js'); expect(written).toContain('/component2.js'); }); it('should rebuild components whose imported dependencies have changed', () => { setupFooBarProgram(env); // Pretend a change was made to BarDir. env.write('bar_directive.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[barr]'}) export class BarDir {} `); env.driveMain(); let written = env.getFilesWrittenSinceLastFlush(); expect(written).toContain('/bar_directive.js'); expect(written).toContain('/bar_component.js'); expect(written).toContain('/bar_module.js'); expect(written).not.toContain('/foo_component.js'); // BarDir is not exported by BarModule, // so upstream NgModule is not affected expect(written).not.toContain('/foo_pipe.js'); expect(written).not.toContain('/foo_module.js'); }); // https://github.com/angular/angular/issues/32416 it('should rebuild full NgModule scope when a dependency of a declaration has changed', () => { env.write('component1.ts', ` import {Component} from '@angular/core'; import {SELECTOR} from './dep'; @Component({selector: SELECTOR, template: 'cmp'}) export class Cmp1 {} `); env.write('component2.ts', ` import {Component} from '@angular/core'; @Component({selector: 'cmp2', template: '<cmp></cmp>'}) export class Cmp2 {} `); env.write('dep.ts', ` export const SELECTOR = 'cmp'; `); env.write('directive.ts', ` import {Directive} from '@angular/core'; @Directive({selector: 'dir'}) export class Dir {} `); env.write('pipe.ts', ` import {Pipe} from '@angular/core'; @Pipe({name: 'myPipe'}) export class MyPipe { transform() {} } `); env.write('module.ts', ` import {NgModule, NO_ERRORS_SCHEMA} from '@angular/core'; import {Cmp1} from './component1'; import {Cmp2} from './component2'; import {Dir} from './directive'; import {MyPipe} from './pipe'; @NgModule({declarations: [Cmp1, Cmp2, Dir, MyPipe], schemas: [NO_ERRORS_SCHEMA]}) export class Mod {} `); env.driveMain(); // Pretend a change was made to 'dep'. Since the selector is updated this affects the NgModule // scope, so all components in the module scope need to be recompiled. env.flushWrittenFileTracking(); env.write('dep.ts', ` export const SELECTOR = 'cmp_updated'; `); env.driveMain(); const written = env.getFilesWrittenSinceLastFlush(); expect(written).not.toContain('/directive.js'); expect(written).not.toContain('/pipe.js'); expect(written).not.toContain('/module.js'); expect(written).toContain('/component1.js'); expect(written).toContain('/component2.js'); expect(written).toContain('/dep.js'); }); it('should rebuild components where their NgModule declared dependencies have changed', () => { setupFooBarProgram(env); // Rename the pipe so components that use it need to be recompiled. env.write('foo_pipe.ts', ` import {Pipe} from '@angular/core'; @Pipe({name: 'foo_changed'}) export class FooPipe { transform() {} } `); env.driveMain(); const written = env.getFilesWrittenSinceLastFlush(); expect(written).not.toContain('/bar_directive.js'); expect(written).not.toContain('/bar_component.js'); expect(written).not.toContain('/bar_module.js'); expect(written).toContain('/foo_component.js'); expect(written).toContain('/foo_pipe.js'); expect(written).toContain('/foo_module.js'); }); it('should rebuild components where their NgModule has changed', () => { setupFooBarProgram(env); // Pretend a change was made to FooModule. env.write('foo_module.ts', ` import {NgModule} from '@angular/core'; import {FooCmp} from './foo_component'; import {FooPipe} from './foo_pipe'; import {BarModule} from './bar_module'; @NgModule({ declarations: [FooCmp], // removed FooPipe imports: [BarModule], }) export class FooModule {} `); env.driveMain(); const written = env.getFilesWrittenSinceLastFlush(); expect(written).not.toContain('/bar_directive.js'); expect(written).not.toContain('/bar_component.js'); expect(written).not.toContain('/bar_module.js'); expect(written).not.toContain('/foo_pipe.js'); expect(written).toContain('/foo_component.js'); expect(written).toContain('/foo_module.js'); }); it('should rebuild a component if one of its deep NgModule dependencies changes', () => { // This test constructs a chain of NgModules: // - EntryModule imports MiddleAModule // - MiddleAModule exports MiddleBModule // - MiddleBModule exports DirModule // The last link (MiddleBModule exports DirModule) is not present initially, but is added // during a recompilation. // // Since the dependency from EntryModule on the contents of MiddleBModule is not "direct" // (meaning MiddleBModule is not discovered during analysis of EntryModule), this test is // verifying that NgModule dependency tracking correctly accounts for this situation. env.write('entry.ts', ` import {Component, NgModule} from '@angular/core'; import {MiddleAModule} from './middle-a'; @Component({ selector: 'test-cmp', template: '<div dir>', }) export class TestCmp {} @NgModule({ declarations: [TestCmp], imports: [MiddleAModule], }) export class EntryModule {} `); env.write('middle-a.ts', ` import {NgModule} from '@angular/core'; import {MiddleBModule} from './middle-b'; @NgModule({ exports: [MiddleBModule], }) export class MiddleAModule {} `); env.write('middle-b.ts', ` import {NgModule} from '@angular/core'; @NgModule({}) export class MiddleBModule {} `); env.write('dir_module.ts', ` import {NgModule} from '@angular/core'; import {Dir} from './dir'; @NgModule({ declarations: [Dir], exports: [Dir], }) export class DirModule {} `); env.write('dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', }) export class Dir {} `); env.driveMain(); expect(env.getContents('entry.js')).not.toContain('Dir'); env.write('middle-b.ts', ` import {NgModule} from '@angular/core'; import {DirModule} from './dir_module'; @NgModule({ exports: [DirModule], }) export class MiddleBModule {} `); env.driveMain(); expect(env.getContents('entry.js')).toContain('Dir'); }); it('should rebuild a component if removed from an NgModule', () => { // This test consists of a component with a dependency (the directive DepDir) provided via an // NgModule. Initially this configuration is built, then the component is removed from its // module (which removes DepDir from the component's scope) and a rebuild is performed. // The compiler should re-emit the component without DepDir in its scope. // // This is a tricky scenario due to the backwards dependency arrow from a component to its // module. env.write('dep.ts', ` import {Directive, NgModule} from '@angular/core'; @Directive({selector: '[dep]'}) export class DepDir {} @NgModule({ declarations: [DepDir], exports: [DepDir], }) export class DepModule {} `); env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div dep></div>', }) export class Cmp {} `); env.write('module.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {DepModule} from './dep'; @NgModule({ declarations: [Cmp], imports: [DepModule], }) export class Module {} `); env.driveMain(); env.flushWrittenFileTracking(); // Remove the component from the module and recompile. env.write('module.ts', ` import {NgModule} from '@angular/core'; import {DepModule} from './dep'; @NgModule({ declarations: [], imports: [DepModule], }) export class Module {} `); env.driveMain(); // After removing the component from the module, it should have been re-emitted without DepDir // in its scope. expect(env.getFilesWrittenSinceLastFlush()).toContain('/cmp.js'); expect(env.getContents('cmp.js')).not.toContain('DepDir'); }); it('should rebuild only a Component (but with the correct CompilationScope) if its template has changed', () => { setupFooBarProgram(env); // Make a change to the template of BarComponent. env.write('bar_component.html', '<div bar>changed</div>'); env.driveMain(); const written = env.getFilesWrittenSinceLastFlush(); expect(written).not.toContain('/bar_directive.js'); expect(written).toContain('/bar_component.js'); expect(written).not.toContain('/bar_module.js'); expect(written).not.toContain('/foo_component.js'); expect(written).not.toContain('/foo_pipe.js'); expect(written).not.toContain('/foo_module.js'); // Ensure that the used directives are included in the component's generated template. expect(env.getContents('/built/bar_component.js')).toMatch(/directives:\s*\[.+\.BarDir\]/); }); it('should rebuild everything if a typings file changes', () => { setupFooBarProgram(env); // Pretend a change was made to a typings file. env.invalidateCachedFile('foo_selector.d.ts'); env.driveMain(); const written = env.getFilesWrittenSinceLastFlush(); expect(written).toContain('/bar_directive.js'); expect(written).toContain('/bar_component.js'); expect(written).toContain('/bar_module.js'); expect(written).toContain('/foo_component.js'); expect(written).toContain('/foo_pipe.js'); expect(written).toContain('/foo_module.js'); }); it('should compile incrementally with template type-checking turned on', () => { env.tsconfig({fullTemplateTypeCheck: true}); env.write('main.ts', ` import {Component} from '@angular/core'; @Component({template: ''}) export class MyComponent {} `); env.driveMain(); env.invalidateCachedFile('main.ts'); env.driveMain(); // If program reuse were configured incorrectly (as was responsible for // https://github.com/angular/angular/issues/30079), this would have crashed. }); // https://github.com/angular/angular/issues/38979 it('should retain ambient types provided by auto-discovered @types', () => { // This test verifies that ambient types declared in node_modules/@types are still available // in incremental compilations. In the below code, the usage of `require` should be valid // in the original program and the incremental program. env.tsconfig({fullTemplateTypeCheck: true}); env.write('node_modules/@types/node/index.d.ts', 'declare var require: any;'); env.write('main.ts', ` import {Component} from '@angular/core'; require('path'); @Component({template: ''}) export class MyComponent {} `); env.driveMain(); env.invalidateCachedFile('main.ts'); const diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); // https://github.com/angular/angular/pull/26036 it('should handle redirected source files', () => { env.tsconfig({fullTemplateTypeCheck: true}); // This file structure has an identical version of "a" under the root node_modules and inside // of "b". Because their package.json file indicates it is the exact same version of "a", // TypeScript will transform the source file of "node_modules/b/node_modules/a/index.d.ts" // into a redirect to "node_modules/a/index.d.ts". During incremental compilations, we must // assure not to reintroduce "node_modules/b/node_modules/a/index.d.ts" as its redirected // source file, but instead use its original file. env.write('node_modules/a/index.js', `export class ServiceA {}`); env.write('node_modules/a/index.d.ts', `export declare class ServiceA {}`); env.write('node_modules/a/package.json', `{"name": "a", "version": "1.0"}`); env.write('node_modules/b/node_modules/a/index.js', `export class ServiceA {}`); env.write('node_modules/b/node_modules/a/index.d.ts', `export declare class ServiceA {}`); env.write('node_modules/b/node_modules/a/package.json', `{"name": "a", "version": "1.0"}`); env.write('node_modules/b/index.js', `export {ServiceA as ServiceB} from 'a';`); env.write('node_modules/b/index.d.ts', `export {ServiceA as ServiceB} from 'a';`); env.write('test.ts', ` import {Component} from '@angular/core'; import {ServiceA} from 'a'; import {ServiceB} from 'b'; @Component({template: ''}) export class MyComponent {} `); env.driveMain(); env.flushWrittenFileTracking(); // Pretend a change was made to test.ts. If redirect sources were introduced into the new // program, this would fail due to an assertion failure in TS. env.invalidateCachedFile('test.ts'); env.driveMain(); }); it('should allow incremental compilation with redirected source files', () => { env.tsconfig({fullTemplateTypeCheck: true}); // This file structure has an identical version of "a" under the root node_modules and inside // of "b". Because their package.json file indicates it is the exact same version of "a", // TypeScript will transform the source file of "node_modules/b/node_modules/a/index.d.ts" // into a redirect to "node_modules/a/index.d.ts". During incremental compilations, the // redirected "node_modules/b/node_modules/a/index.d.ts" source file should be considered as // its unredirected source file to avoid a change in declaration files. env.write('node_modules/a/index.js', `export class ServiceA {}`); env.write('node_modules/a/index.d.ts', `export declare class ServiceA {}`); env.write('node_modules/a/package.json', `{"name": "a", "version": "1.0"}`); env.write('node_modules/b/node_modules/a/index.js', `export class ServiceA {}`); env.write('node_modules/b/node_modules/a/index.d.ts', `export declare class ServiceA {}`); env.write('node_modules/b/node_modules/a/package.json', `{"name": "a", "version": "1.0"}`); env.write('node_modules/b/index.js', `export {ServiceA as ServiceB} from 'a';`); env.write('node_modules/b/index.d.ts', `export {ServiceA as ServiceB} from 'a';`); env.write('component1.ts', ` import {Component} from '@angular/core'; import {ServiceA} from 'a'; import {ServiceB} from 'b'; @Component({selector: 'cmp', template: 'cmp'}) export class Cmp1 {} `); env.write('component2.ts', ` import {Component} from '@angular/core'; import {ServiceA} from 'a'; import {ServiceB} from 'b'; @Component({selector: 'cmp2', template: 'cmp'}) export class Cmp2 {} `); env.driveMain(); env.flushWrittenFileTracking(); // Now update `component1.ts` and change its imports to avoid complete structure reuse, which // forces recreation of source file redirects. env.write('component1.ts', ` import {Component} from '@angular/core'; import {ServiceA} from 'a'; @Component({selector: 'cmp', template: 'cmp'}) export class Cmp1 {} `); env.driveMain(); const written = env.getFilesWrittenSinceLastFlush(); expect(written).toContain('/component1.js'); expect(written).not.toContain('/component2.js'); }); describe('template type-checking', () => { beforeEach(() => { env.tsconfig({strictTemplates: true}); }); it('should repeat type errors across rebuilds, even if nothing has changed', () => { // This test verifies that when a project is rebuilt multiple times with no changes, all // template diagnostics are produced each time. Different types of errors are checked: // - a general type error // - an unmatched binding // - a DOM schema error env.write('component.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: \` {{notAProperty}} <not-a-component></not-a-component> <div [notMatched]="1"></div> \`, }) export class TestCmp {} `); let diags = env.driveDiagnostics(); // Should get a diagnostic for each line in the template. expect(diags.length).toBe(3); // Now rebuild without any changes, and verify they're still produced. diags = env.driveDiagnostics(); expect(diags.length).toBe(3); // If it's worth testing, it's worth overtesting. // // Actually, the above only tests the transition from "initial" to "incremental" // compilation. The next build verifies that an "incremental to incremental" transition // preserves the diagnostics as well. diags = env.driveDiagnostics(); expect(diags.length).toBe(3); }); it('should pick up errors caused by changing an unrelated interface', () => { // The premise of this test is that `iface.ts` declares an interface which is used to type // a property of a component. The interface is then changed in a subsequent compilation in // a way that introduces a type error in the template. The test verifies the resulting // diagnostic is produced. env.write('iface.ts', ` export interface SomeType { field: string; } `); env.write('component.ts', ` import {Component} from '@angular/core'; import {SomeType} from './iface'; @Component({ selector: 'test-cmp', template: '{{ doSomething(value.field) }}', }) export class TestCmp { value!: SomeType; // Takes a string value only. doSomething(param: string): string { return param; } } `); expect(env.driveDiagnostics().length).toBe(0); env.flushWrittenFileTracking(); // Change the interface. env.write('iface.ts', ` export interface SomeType { field: number; } `); expect(env.driveDiagnostics().length).toBe(1); }); it('should retain default imports that have been converted into a value expression', () => { // This test defines the component `TestCmp` that has a default-imported class as // constructor parameter, and uses `TestDir` in its template. An incremental compilation // updates `TestDir` and changes its inputs, thereby triggering re-emit of `TestCmp` without // performing re-analysis of `TestCmp`. The output of the re-emitted file for `TestCmp` // should continue to have retained the default import. env.write('service.ts', ` import {Injectable} from '@angular/core'; @Injectable({ providedIn: 'root' }) export default class DefaultService {} `); env.write('cmp.ts', ` import {Component, Directive} from '@angular/core'; import DefaultService from './service'; @Component({ template: '<div dir></div>', }) export class TestCmp { constructor(service: DefaultService) {} } `); env.write('dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]' }) export class TestDir {} `); env.write('mod.ts', ` import {NgModule} from '@angular/core'; import {TestDir} from './dir'; import {TestCmp} from './cmp'; @NgModule({ declarations: [TestDir, TestCmp] }) export class TestMod {} `); env.driveMain(); env.flushWrittenFileTracking(); // Update `TestDir` to change its inputs, triggering a re-emit of `TestCmp` that uses // `TestDir`. env.write('dir.ts', ` import {Directive} from '@angular/core'; @Directive({ selector: '[dir]', inputs: ['added'] }) export class TestDir {} `); env.driveMain(); // Verify that `TestCmp` was indeed re-emitted. const written = env.getFilesWrittenSinceLastFlush(); expect(written).toContain('/dir.js'); expect(written).toContain('/cmp.js'); // Verify that the default import is still present. const content = env.getContents('cmp.js'); expect(content).toContain(`import DefaultService from './service';`); }); it('should recompile when a remote change happens to a scope', () => { // The premise of this test is that the component Cmp has a template error (a binding to an // unknown property). Cmp is in ModuleA, which imports ModuleB, which declares Dir that has // the property. Because ModuleB doesn't export Dir, it's not visible to Cmp - hence the // error. // In the test, during the incremental rebuild Dir is exported from ModuleB. This is a // change to the scope of ModuleA made by changing ModuleB (hence, a "remote change"). The // test verifies that incremental template type-checking. env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '<div dir [someInput]="1"></div>', }) export class Cmp {} `); env.write('module-a.ts', ` import {NgModule} from '@angular/core'; import {Cmp} from './cmp'; import {ModuleB} from './module-b'; @NgModule({ declarations: [Cmp], imports: [ModuleB], }) export class ModuleA {} `); // Declare ModuleB and a directive Dir, but ModuleB does not yet export Dir. env.write('module-b.ts', ` import {NgModule} from '@angular/core'; import {Dir} from './dir'; @NgModule({ declarations: [Dir], }) export class ModuleB {} `); env.write('dir.ts', ` import {Directive, Input} from '@angular/core'; @Directive({selector: '[dir]'}) export class Dir { @Input() someInput!: any; } `); let diags = env.driveDiagnostics(); // Should get a diagnostic about [dir] not being a valid binding. expect(diags.length).toBe(1); // As a precautionary check, run the build a second time with no changes, to ensure the // diagnostic is repeated. diags = env.driveDiagnostics(); // Should get a diagnostic about [dir] not being a valid binding. expect(diags.length).toBe(1); // Modify ModuleB to now export Dir. env.write('module-b.ts', ` import {NgModule} from '@angular/core'; import {Dir} from './dir'; @NgModule({ declarations: [Dir], exports: [Dir], }) export class ModuleB {} `); diags = env.driveDiagnostics(); // Diagnostic should be gone, as the error has been fixed. expect(diags.length).toBe(0); }); describe('inline operations', () => { it('should still pick up on errors from inlined type check blocks', () => { // In certain cases the template type-checker has to inline type checking blocks into user // code, instead of placing it in a parallel template type-checking file. In these cases // incremental checking cannot be used, and the type-checking code must be regenerated on // each build. This test verifies that the above mechanism works properly, by performing // type-checking on an unexported class (not exporting the class forces the inline // checking de-optimization). env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '{{test}}', }) class Cmp {} `); // On the first compilation, an error should be produced. let diags = env.driveDiagnostics(); expect(diags.length).toBe(1); // Next, two more builds are run, one with no changes made to the file, and the other with // changes made that should remove the error. // The error should still be present when rebuilding. diags = env.driveDiagnostics(); expect(diags.length).toBe(1); // Now, correct the error by adding the 'test' property to the component. env.write('cmp.ts', ` import {Component} from '@angular/core'; @Component({ selector: 'test-cmp', template: '{{test}}', }) class Cmp { test!: string; } `); env.driveMain(); // The error should be gone. diags = env.driveDiagnostics(); expect(diags.length).toBe(0); }); it('should still pick up on errors caused by inlined type constructors', () => { // In certain cases the template type-checker cannot generate a type constructor for a // directive within the template type-checking file which requires it, but must inline the // type constructor within its original source file. In these cases, template type // checking cannot be performed incrementally. This test verifies that such cases still // work correctly, by repeatedly performing diagnostics on a component which depends on a // directive with an inlined type constructor. env.write('dir.ts', ` import {Directive, Input} from '@angular/core'; export interface Keys { alpha: string; beta: string; } @Directive({ selector: '[dir]' }) export class Dir<T extends keyof Keys> { // The use of 'keyof' in the generic bound causes a deopt to an inline type // constructor. @Input() dir: T; } `); env.write('cmp.ts', ` import {Component, NgModule} from '@angular/core'; import {Dir} from './dir'; @Component({ selector: 'test-cmp', template: '<div dir="gamma"></div>', }) export class Cmp {} @NgModule({ declarations: [Cmp, Dir], }) export class Module {} `); let diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText) .toContain(`Type '"gamma"' is not assignable to type 'keyof Keys'.`); // On a rebuild, the same errors should be present. diags = env.driveDiagnostics(); expect(diags.length).toBe(1); expect(diags[0].messageText) .toContain(`Type '"gamma"' is not assignable to type 'keyof Keys'.`); }); it('should not re-emit files that need inline type constructors', () => { // Setup a directive that requires an inline type constructor, as it has a generic type // parameter that refer an interface that has not been exported. The inline operation // causes an updated dir.ts to be used in the type-check program, which should not // confuse the incremental engine in undesirably considering dir.ts as affected in // incremental rebuilds. env.write('dir.ts', ` import {Directive, Input} from '@angular/core'; interface Keys { alpha: string; beta: string; } @Directive({ selector: '[dir]' }) export class Dir<T extends keyof Keys> { @Input() dir: T; } `); env.write('cmp.ts', ` import {Component, NgModule} from '@angular/core'; import {Dir} from './dir'; @Component({ selector: 'test-cmp', template: '<div dir="alpha"></div>', }) export class Cmp {} @NgModule({ declarations: [Cmp, Dir], }) export class Module {} `); env.driveMain(); // Trigger a recompile by changing cmp.ts. env.invalidateCachedFile('cmp.ts'); env.flushWrittenFileTracking(); env.driveMain(); // Verify that only cmp.ts was emitted, but not dir.ts as it was not affected. const written = env.getFilesWrittenSinceLastFlush(); expect(written).toContain('/cmp.js'); expect(written).not.toContain('/dir.js'); }); }); }); }); function setupFooBarProgram(env: NgtscTestEnvironment) { env.write('foo_component.ts', ` import {Component} from '@angular/core'; import {fooSelector} from './foo_selector'; @Component({ selector: fooSelector, template: '{{ 1 | foo }}' }) export class FooCmp {} `); env.write('foo_pipe.ts', ` import {Pipe} from '@angular/core'; @Pipe({name: 'foo'}) export class FooPipe { transform() {} } `); env.write('foo_module.ts', ` import {NgModule} from '@angular/core'; import {FooCmp} from './foo_component'; import {FooPipe} from './foo_pipe'; import {BarModule} from './bar_module'; @NgModule({ declarations: [FooCmp, FooPipe], imports: [BarModule], }) export class FooModule {} `); env.write('bar_component.ts', ` import {Component} from '@angular/core'; @Component({selector: 'bar', templateUrl: './bar_component.html'}) export class BarCmp {} `); env.write('bar_component.html', '<div bar></div>'); env.write('bar_directive.ts', ` import {Directive} from '@angular/core'; @Directive({selector: '[bar]'}) export class BarDir {} `); env.write('bar_pipe.ts', ` import {Pipe} from '@angular/core'; @Pipe({name: 'foo'}) export class BarPipe { transform() {} } `); env.write('bar_module.ts', ` import {NgModule} from '@angular/core'; import {BarCmp} from './bar_component'; import {BarDir} from './bar_directive'; import {BarPipe} from './bar_pipe'; @NgModule({ declarations: [BarCmp, BarDir, BarPipe], exports: [BarCmp, BarPipe], }) export class BarModule {} `); env.write('foo_selector.d.ts', ` export const fooSelector = 'foo'; `); env.driveMain(); env.flushWrittenFileTracking(); } });
the_stack
import * as assert from 'assert'; import { EventEmitter } from 'events'; import { createServer, Socket } from 'net'; import { tmpdir } from 'os'; import { Barrier, timeout } from 'vs/base/common/async'; import { VSBuffer } from 'vs/base/common/buffer'; import { Emitter, Event } from 'vs/base/common/event'; import { Disposable, DisposableStore } from 'vs/base/common/lifecycle'; import { ILoadEstimator, PersistentProtocol, Protocol, ProtocolConstants, SocketCloseEvent, SocketDiagnosticsEventType } from 'vs/base/parts/ipc/common/ipc.net'; import { createRandomIPCHandle, createStaticIPCHandle, NodeSocket, WebSocketNodeSocket } from 'vs/base/parts/ipc/node/ipc.net'; import { flakySuite } from 'vs/base/test/common/testUtils'; import { runWithFakedTimers } from 'vs/base/test/common/timeTravelScheduler'; import { ensureNoDisposablesAreLeakedInTestSuite } from 'vs/base/test/common/utils'; class MessageStream extends Disposable { private _currentComplete: ((data: VSBuffer) => void) | null; private _messages: VSBuffer[]; constructor(x: Protocol | PersistentProtocol) { super(); this._currentComplete = null; this._messages = []; this._register(x.onMessage(data => { this._messages.push(data); this._trigger(); })); } private _trigger(): void { if (!this._currentComplete) { return; } if (this._messages.length === 0) { return; } const complete = this._currentComplete; const msg = this._messages.shift()!; this._currentComplete = null; complete(msg); } public waitForOne(): Promise<VSBuffer> { return new Promise<VSBuffer>((complete) => { this._currentComplete = complete; this._trigger(); }); } } class EtherStream extends EventEmitter { constructor( private readonly _ether: Ether, private readonly _name: 'a' | 'b' ) { super(); } write(data: Buffer, cb?: Function): boolean { if (!Buffer.isBuffer(data)) { throw new Error(`Invalid data`); } this._ether.write(this._name, data); return true; } destroy(): void { } } class Ether { private readonly _a: EtherStream; private readonly _b: EtherStream; private _ab: Buffer[]; private _ba: Buffer[]; public get a(): Socket { return <any>this._a; } public get b(): Socket { return <any>this._b; } constructor( private readonly _wireLatency = 0 ) { this._a = new EtherStream(this, 'a'); this._b = new EtherStream(this, 'b'); this._ab = []; this._ba = []; } public write(from: 'a' | 'b', data: Buffer): void { setTimeout(() => { if (from === 'a') { this._ab.push(data); } else { this._ba.push(data); } setTimeout(() => this._deliver(), 0); }, this._wireLatency); } private _deliver(): void { if (this._ab.length > 0) { const data = Buffer.concat(this._ab); this._ab.length = 0; this._b.emit('data', data); setTimeout(() => this._deliver(), 0); return; } if (this._ba.length > 0) { const data = Buffer.concat(this._ba); this._ba.length = 0; this._a.emit('data', data); setTimeout(() => this._deliver(), 0); return; } } } suite('IPC, Socket Protocol', () => { ensureNoDisposablesAreLeakedInTestSuite(); let ether: Ether; setup(() => { ether = new Ether(); }); test('read/write', async () => { const a = new Protocol(new NodeSocket(ether.a)); const b = new Protocol(new NodeSocket(ether.b)); const bMessages = new MessageStream(b); a.send(VSBuffer.fromString('foobarfarboo')); const msg1 = await bMessages.waitForOne(); assert.strictEqual(msg1.toString(), 'foobarfarboo'); const buffer = VSBuffer.alloc(1); buffer.writeUInt8(123, 0); a.send(buffer); const msg2 = await bMessages.waitForOne(); assert.strictEqual(msg2.readUInt8(0), 123); bMessages.dispose(); a.dispose(); b.dispose(); }); test('read/write, object data', async () => { const a = new Protocol(new NodeSocket(ether.a)); const b = new Protocol(new NodeSocket(ether.b)); const bMessages = new MessageStream(b); const data = { pi: Math.PI, foo: 'bar', more: true, data: 'Hello World'.split('') }; a.send(VSBuffer.fromString(JSON.stringify(data))); const msg = await bMessages.waitForOne(); assert.deepStrictEqual(JSON.parse(msg.toString()), data); bMessages.dispose(); a.dispose(); b.dispose(); }); }); suite('PersistentProtocol reconnection', () => { ensureNoDisposablesAreLeakedInTestSuite(); test('acks get piggybacked with messages', async () => { const ether = new Ether(); const a = new PersistentProtocol(new NodeSocket(ether.a)); const aMessages = new MessageStream(a); const b = new PersistentProtocol(new NodeSocket(ether.b)); const bMessages = new MessageStream(b); a.send(VSBuffer.fromString('a1')); assert.strictEqual(a.unacknowledgedCount, 1); assert.strictEqual(b.unacknowledgedCount, 0); a.send(VSBuffer.fromString('a2')); assert.strictEqual(a.unacknowledgedCount, 2); assert.strictEqual(b.unacknowledgedCount, 0); a.send(VSBuffer.fromString('a3')); assert.strictEqual(a.unacknowledgedCount, 3); assert.strictEqual(b.unacknowledgedCount, 0); const a1 = await bMessages.waitForOne(); assert.strictEqual(a1.toString(), 'a1'); assert.strictEqual(a.unacknowledgedCount, 3); assert.strictEqual(b.unacknowledgedCount, 0); const a2 = await bMessages.waitForOne(); assert.strictEqual(a2.toString(), 'a2'); assert.strictEqual(a.unacknowledgedCount, 3); assert.strictEqual(b.unacknowledgedCount, 0); const a3 = await bMessages.waitForOne(); assert.strictEqual(a3.toString(), 'a3'); assert.strictEqual(a.unacknowledgedCount, 3); assert.strictEqual(b.unacknowledgedCount, 0); b.send(VSBuffer.fromString('b1')); assert.strictEqual(a.unacknowledgedCount, 3); assert.strictEqual(b.unacknowledgedCount, 1); const b1 = await aMessages.waitForOne(); assert.strictEqual(b1.toString(), 'b1'); assert.strictEqual(a.unacknowledgedCount, 0); assert.strictEqual(b.unacknowledgedCount, 1); a.send(VSBuffer.fromString('a4')); assert.strictEqual(a.unacknowledgedCount, 1); assert.strictEqual(b.unacknowledgedCount, 1); const b2 = await bMessages.waitForOne(); assert.strictEqual(b2.toString(), 'a4'); assert.strictEqual(a.unacknowledgedCount, 1); assert.strictEqual(b.unacknowledgedCount, 0); aMessages.dispose(); bMessages.dispose(); a.dispose(); b.dispose(); }); test('ack gets sent after a while', async () => { await runWithFakedTimers({ useFakeTimers: true, maxTaskCount: 100 }, async () => { const loadEstimator: ILoadEstimator = { hasHighLoad: () => false }; const ether = new Ether(); const aSocket = new NodeSocket(ether.a); const a = new PersistentProtocol(aSocket, null, loadEstimator); const aMessages = new MessageStream(a); const bSocket = new NodeSocket(ether.b); const b = new PersistentProtocol(bSocket, null, loadEstimator); const bMessages = new MessageStream(b); // send one message A -> B a.send(VSBuffer.fromString('a1')); assert.strictEqual(a.unacknowledgedCount, 1); assert.strictEqual(b.unacknowledgedCount, 0); const a1 = await bMessages.waitForOne(); assert.strictEqual(a1.toString(), 'a1'); assert.strictEqual(a.unacknowledgedCount, 1); assert.strictEqual(b.unacknowledgedCount, 0); // wait for ack to arrive B -> A await timeout(2 * ProtocolConstants.AcknowledgeTime); assert.strictEqual(a.unacknowledgedCount, 0); assert.strictEqual(b.unacknowledgedCount, 0); aMessages.dispose(); bMessages.dispose(); a.dispose(); b.dispose(); }); }); test('messages that are never written to a socket should not cause an ack timeout', async () => { await runWithFakedTimers( { useFakeTimers: true, useSetImmediate: true, maxTaskCount: 1000 }, async () => { // Date.now() in fake timers starts at 0, which is very inconvenient // since we want to test exactly that a certain field is not initialized with Date.now() // As a workaround we wait such that Date.now() starts producing more realistic values await timeout(60 * 60 * 1000); const loadEstimator: ILoadEstimator = { hasHighLoad: () => false }; const ether = new Ether(); const aSocket = new NodeSocket(ether.a); const a = new PersistentProtocol(aSocket, null, loadEstimator); const aMessages = new MessageStream(a); const bSocket = new NodeSocket(ether.b); const b = new PersistentProtocol(bSocket, null, loadEstimator); const bMessages = new MessageStream(b); // send message a1 before reconnection to get _recvAckCheck() scheduled a.send(VSBuffer.fromString('a1')); assert.strictEqual(a.unacknowledgedCount, 1); assert.strictEqual(b.unacknowledgedCount, 0); // read message a1 at B const a1 = await bMessages.waitForOne(); assert.strictEqual(a1.toString(), 'a1'); assert.strictEqual(a.unacknowledgedCount, 1); assert.strictEqual(b.unacknowledgedCount, 0); // send message b1 to send the ack for a1 b.send(VSBuffer.fromString('b1')); assert.strictEqual(a.unacknowledgedCount, 1); assert.strictEqual(b.unacknowledgedCount, 1); // read message b1 at A to receive the ack for a1 const b1 = await aMessages.waitForOne(); assert.strictEqual(b1.toString(), 'b1'); assert.strictEqual(a.unacknowledgedCount, 0); assert.strictEqual(b.unacknowledgedCount, 1); // begin reconnection aSocket.dispose(); const aSocket2 = new NodeSocket(ether.a); a.beginAcceptReconnection(aSocket2, null); let timeoutListenerCalled = false; const socketTimeoutListener = a.onSocketTimeout(() => { timeoutListenerCalled = true; }); // send message 2 during reconnection a.send(VSBuffer.fromString('a2')); assert.strictEqual(a.unacknowledgedCount, 1); assert.strictEqual(b.unacknowledgedCount, 1); // wait for scheduled _recvAckCheck() to execute await timeout(2 * ProtocolConstants.TimeoutTime); assert.strictEqual(a.unacknowledgedCount, 1); assert.strictEqual(b.unacknowledgedCount, 1); assert.strictEqual(timeoutListenerCalled, false); a.endAcceptReconnection(); assert.strictEqual(timeoutListenerCalled, false); await timeout(2 * ProtocolConstants.TimeoutTime); assert.strictEqual(a.unacknowledgedCount, 0); assert.strictEqual(b.unacknowledgedCount, 0); assert.strictEqual(timeoutListenerCalled, false); socketTimeoutListener.dispose(); aMessages.dispose(); bMessages.dispose(); a.dispose(); b.dispose(); } ); }); test('acks are always sent after a reconnection', async () => { await runWithFakedTimers( { useFakeTimers: true, useSetImmediate: true, maxTaskCount: 1000 }, async () => { const loadEstimator: ILoadEstimator = { hasHighLoad: () => false }; const wireLatency = 1000; const ether = new Ether(wireLatency); const aSocket = new NodeSocket(ether.a); const a = new PersistentProtocol(aSocket, null, loadEstimator); const aMessages = new MessageStream(a); const bSocket = new NodeSocket(ether.b); const b = new PersistentProtocol(bSocket, null, loadEstimator); const bMessages = new MessageStream(b); // send message a1 to have something unacknowledged a.send(VSBuffer.fromString('a1')); assert.strictEqual(a.unacknowledgedCount, 1); assert.strictEqual(b.unacknowledgedCount, 0); // read message a1 at B const a1 = await bMessages.waitForOne(); assert.strictEqual(a1.toString(), 'a1'); assert.strictEqual(a.unacknowledgedCount, 1); assert.strictEqual(b.unacknowledgedCount, 0); // wait for B to send an ACK message, // but resume before A receives it await timeout(ProtocolConstants.AcknowledgeTime + wireLatency / 2); assert.strictEqual(a.unacknowledgedCount, 1); assert.strictEqual(b.unacknowledgedCount, 0); // simulate complete reconnection aSocket.dispose(); bSocket.dispose(); const ether2 = new Ether(wireLatency); const aSocket2 = new NodeSocket(ether2.a); const bSocket2 = new NodeSocket(ether2.b); b.beginAcceptReconnection(bSocket2, null); b.endAcceptReconnection(); a.beginAcceptReconnection(aSocket2, null); a.endAcceptReconnection(); // wait for quite some time await timeout(2 * ProtocolConstants.AcknowledgeTime + wireLatency); assert.strictEqual(a.unacknowledgedCount, 0); assert.strictEqual(b.unacknowledgedCount, 0); aMessages.dispose(); bMessages.dispose(); a.dispose(); b.dispose(); } ); }); test('onSocketTimeout is emitted at most once every 20s', async () => { await runWithFakedTimers( { useFakeTimers: true, useSetImmediate: true, maxTaskCount: 1000 }, async () => { const loadEstimator: ILoadEstimator = { hasHighLoad: () => false }; const ether = new Ether(); const aSocket = new NodeSocket(ether.a); const a = new PersistentProtocol(aSocket, null, loadEstimator); const aMessages = new MessageStream(a); const bSocket = new NodeSocket(ether.b); const b = new PersistentProtocol(bSocket, null, loadEstimator); const bMessages = new MessageStream(b); // never receive acks b.pauseSocketWriting(); // send message a1 to have something unacknowledged a.send(VSBuffer.fromString('a1')); // wait for the first timeout to fire await Event.toPromise(a.onSocketTimeout); let timeoutFiredAgain = false; const timeoutListener = a.onSocketTimeout(() => { timeoutFiredAgain = true; }); // send more messages a.send(VSBuffer.fromString('a2')); a.send(VSBuffer.fromString('a3')); // wait for 10s await timeout(ProtocolConstants.TimeoutTime / 2); assert.strictEqual(timeoutFiredAgain, false); timeoutListener.dispose(); aMessages.dispose(); bMessages.dispose(); a.dispose(); b.dispose(); } ); }); test('writing can be paused', async () => { await runWithFakedTimers({ useFakeTimers: true, maxTaskCount: 100 }, async () => { const loadEstimator: ILoadEstimator = { hasHighLoad: () => false }; const ether = new Ether(); const aSocket = new NodeSocket(ether.a); const a = new PersistentProtocol(aSocket, null, loadEstimator); const aMessages = new MessageStream(a); const bSocket = new NodeSocket(ether.b); const b = new PersistentProtocol(bSocket, null, loadEstimator); const bMessages = new MessageStream(b); // send one message A -> B a.send(VSBuffer.fromString('a1')); const a1 = await bMessages.waitForOne(); assert.strictEqual(a1.toString(), 'a1'); // ask A to pause writing b.sendPause(); // send a message B -> A b.send(VSBuffer.fromString('b1')); const b1 = await aMessages.waitForOne(); assert.strictEqual(b1.toString(), 'b1'); // send a message A -> B (this should be blocked at A) a.send(VSBuffer.fromString('a2')); // wait a long time and check that not even acks are written await timeout(2 * ProtocolConstants.AcknowledgeTime); assert.strictEqual(a.unacknowledgedCount, 1); assert.strictEqual(b.unacknowledgedCount, 1); // ask A to resume writing b.sendResume(); // check that B receives message const a2 = await bMessages.waitForOne(); assert.strictEqual(a2.toString(), 'a2'); // wait a long time and check that acks are written await timeout(2 * ProtocolConstants.AcknowledgeTime); assert.strictEqual(a.unacknowledgedCount, 0); assert.strictEqual(b.unacknowledgedCount, 0); aMessages.dispose(); bMessages.dispose(); a.dispose(); b.dispose(); }); }); }); flakySuite('IPC, create handle', () => { test('createRandomIPCHandle', async () => { return testIPCHandle(createRandomIPCHandle()); }); test('createStaticIPCHandle', async () => { return testIPCHandle(createStaticIPCHandle(tmpdir(), 'test', '1.64.0')); }); function testIPCHandle(handle: string): Promise<void> { return new Promise<void>((resolve, reject) => { const pipeName = createRandomIPCHandle(); const server = createServer(); server.on('error', () => { return new Promise(() => server.close(() => reject())); }); server.listen(pipeName, () => { server.removeListener('error', reject); return new Promise(() => { server.close(() => resolve()); }); }); }); } }); suite('WebSocketNodeSocket', () => { function toUint8Array(data: number[]): Uint8Array { const result = new Uint8Array(data.length); for (let i = 0; i < data.length; i++) { result[i] = data[i]; } return result; } function fromUint8Array(data: Uint8Array): number[] { const result = []; for (let i = 0; i < data.length; i++) { result[i] = data[i]; } return result; } function fromCharCodeArray(data: number[]): string { let result = ''; for (let i = 0; i < data.length; i++) { result += String.fromCharCode(data[i]); } return result; } class FakeNodeSocket extends Disposable { private readonly _onData = new Emitter<VSBuffer>(); public readonly onData = this._onData.event; private readonly _onClose = new Emitter<SocketCloseEvent>(); public readonly onClose = this._onClose.event; public traceSocketEvent(type: SocketDiagnosticsEventType, data?: VSBuffer | Uint8Array | ArrayBuffer | ArrayBufferView | any): void { } constructor() { super(); } public fireData(data: number[]): void { this._onData.fire(VSBuffer.wrap(toUint8Array(data))); } } async function testReading(frames: number[][], permessageDeflate: boolean): Promise<string> { const disposables = new DisposableStore(); const socket = new FakeNodeSocket(); const webSocket = disposables.add(new WebSocketNodeSocket(<any>socket, permessageDeflate, null, false)); const barrier = new Barrier(); let remainingFrameCount = frames.length; let receivedData: string = ''; disposables.add(webSocket.onData((buff) => { receivedData += fromCharCodeArray(fromUint8Array(buff.buffer)); remainingFrameCount--; if (remainingFrameCount === 0) { barrier.open(); } })); for (let i = 0; i < frames.length; i++) { socket.fireData(frames[i]); } await barrier.wait(); disposables.dispose(); return receivedData; } test('A single-frame unmasked text message', async () => { const frames = [ [0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f] // contains "Hello" ]; const actual = await testReading(frames, false); assert.deepStrictEqual(actual, 'Hello'); }); test('A single-frame masked text message', async () => { const frames = [ [0x81, 0x85, 0x37, 0xfa, 0x21, 0x3d, 0x7f, 0x9f, 0x4d, 0x51, 0x58] // contains "Hello" ]; const actual = await testReading(frames, false); assert.deepStrictEqual(actual, 'Hello'); }); test('A fragmented unmasked text message', async () => { // contains "Hello" const frames = [ [0x01, 0x03, 0x48, 0x65, 0x6c], // contains "Hel" [0x80, 0x02, 0x6c, 0x6f], // contains "lo" ]; const actual = await testReading(frames, false); assert.deepStrictEqual(actual, 'Hello'); }); suite('compression', () => { test('A single-frame compressed text message', async () => { // contains "Hello" const frames = [ [0xc1, 0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00], // contains "Hello" ]; const actual = await testReading(frames, true); assert.deepStrictEqual(actual, 'Hello'); }); test('A fragmented compressed text message', async () => { // contains "Hello" const frames = [ // contains "Hello" [0x41, 0x03, 0xf2, 0x48, 0xcd], [0x80, 0x04, 0xc9, 0xc9, 0x07, 0x00] ]; const actual = await testReading(frames, true); assert.deepStrictEqual(actual, 'Hello'); }); test('A single-frame non-compressed text message', async () => { const frames = [ [0x81, 0x05, 0x48, 0x65, 0x6c, 0x6c, 0x6f] // contains "Hello" ]; const actual = await testReading(frames, true); assert.deepStrictEqual(actual, 'Hello'); }); test('A single-frame compressed text message followed by a single-frame non-compressed text message', async () => { const frames = [ [0xc1, 0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00], // contains "Hello" [0x81, 0x05, 0x77, 0x6f, 0x72, 0x6c, 0x64] // contains "world" ]; const actual = await testReading(frames, true); assert.deepStrictEqual(actual, 'Helloworld'); }); }); });
the_stack
import { Component, OnInit, OnDestroy } from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; import {Subscription} from 'rxjs/Subscription'; import { environment } from './../../../../../environments/environment'; import {WorkflowService} from '../../../../core/services/workflow.service'; import {LoggerService} from '../../../../shared/services/logger.service'; import {DataCacheService} from '../../../../core/services/data-cache.service'; import {FilterManagementService} from '../../../../shared/services/filter-management.service'; import {ErrorHandlingService} from '../../../../shared/services/error-handling.service'; import {UtilsService} from '../../../../shared/services/utils.service'; import {RouterUtilityService} from '../../../../shared/services/router-utility.service'; import { CommonResponseService } from '../../../../shared/services/common-response.service'; import {RefactorFieldsService} from '../../../../shared/services/refactor-fields.service'; @Component({ selector: 'app-plugin-management', templateUrl: './plugin-management.component.html', styleUrls: ['./plugin-management.component.css'] }) export class PluginManagementComponent implements OnInit, OnDestroy { pageTitle: String = 'Plugin Management'; breadcrumbDetails = { breadcrumbArray: ['Admin'], breadcrumbLinks: ['policies'], breadcrumbPresent: 'Plugin Management' }; backButtonRequired: boolean; pageLevel = 0; errorMessage = 'apiResponseError'; agAndDomain = {}; totalRows = 0; selectedAssetGroup: string; errorValue = 0; currentBucket: any = []; outerArr = []; bucketNumber = 0; searchPassed = ''; firstPaginator = 1; allColumns = []; lastPaginator: number; currentPointer = 0; actionsArr = ['Edit']; paginatorSize = 25; selectedDomain; searchTxt = ''; tableSubscription: Subscription; assetGroupSubscription: Subscription; domainSubscription: Subscription; isFilterRquiredOnPage = false; appliedFilters = { queryParamsWithoutFilter: {}, /* Stores the query parameter ibject without filter */ pageLevelAppliedFilters: {} /* Stores the query parameter ibject without filter */ }; filterArray = []; /* Stores the page applied filter array */ routeSubscription: Subscription; constructor(private router: Router, private activatedRoute: ActivatedRoute, private workflowService: WorkflowService, private commonResponseService: CommonResponseService, private logger: LoggerService, private dataStore: DataCacheService, private filterManagementService: FilterManagementService, private errorHandling: ErrorHandlingService, private utils: UtilsService, private routerUtilityService: RouterUtilityService, private refactorFieldsService: RefactorFieldsService) { /* Check route parameter */ this.routeSubscription = this.activatedRoute.params.subscribe(params => { // Fetch the required params from this object. }); } ngOnInit() { this.backButtonRequired = this.workflowService.checkIfFlowExistsCurrently(this.pageLevel); this.reset(); this.init(); } reset() { /* Reset the page */ this.filterArray = []; this.outerArr = []; this.searchTxt = ''; this.currentBucket = []; this.bucketNumber = 0; this.firstPaginator = 1; this.currentPointer = 0; this.allColumns = []; this.errorValue = 0; } init() { /* Initialize */ this.routerParam(); this.updateComponent(); } updateComponent() { /* Updates the whole component */ this.reset(); this.getData(); } routerParam() { try { const currentQueryParams = this.routerUtilityService.getQueryParametersFromSnapshot(this.router.routerState.snapshot.root); if (currentQueryParams) { this.appliedFilters.queryParamsWithoutFilter = JSON.parse(JSON.stringify(currentQueryParams)); delete this.appliedFilters.queryParamsWithoutFilter['filter']; this.appliedFilters.pageLevelAppliedFilters = this.utils.processFilterObj(currentQueryParams); this.filterArray = this.filterManagementService.getFilterArray(this.appliedFilters.pageLevelAppliedFilters); } } catch (error) { this.errorMessage = 'jsError'; this.logger.log('error', error); } } updateUrlWithNewFilters(filterArr) { this.appliedFilters.pageLevelAppliedFilters = this.utils.arrayToObject( this.filterArray, 'filterkey', 'value' ); // <-- TO update the queryparam which is passed in the filter of the api this.appliedFilters.pageLevelAppliedFilters = this.utils.makeFilterObj(this.appliedFilters.pageLevelAppliedFilters); /** * To change the url * with the deleted filter value along with the other existing paramter(ex-->tv:true) */ const updatedFilters = Object.assign( this.appliedFilters.pageLevelAppliedFilters, this.appliedFilters.queryParamsWithoutFilter ); /* Update url with new filters */ this.router.navigate([], { relativeTo: this.activatedRoute, queryParams: updatedFilters }).then(success => { this.routerParam(); }); } navigateBack() { try { this.workflowService.goBackToLastOpenedPageAndUpdateLevel(this.router.routerState.snapshot.root); } catch (error) { this.logger.log('error', error); } } getData() { try { if (this.tableSubscription) { this.tableSubscription.unsubscribe(); } const payload = {}; const queryParams = {}; this.errorValue = 0; const pluginUrl = environment.getPlugins.url; const pluginMethod = environment.getPlugins.method; this.tableSubscription = this.commonResponseService .getData(pluginUrl, pluginMethod, payload, queryParams) .subscribe( response => { try { this.errorValue = 1; let data = response.plugins; if (data.length === 0) { this.errorValue = -1; this.outerArr = []; this.allColumns = []; this.totalRows = 0; this.errorMessage = 'noDataAvailable'; } if (data.length > 0) { this.totalRows = data.length; this.firstPaginator = this.bucketNumber * this.paginatorSize + 1; this.lastPaginator = this.totalRows; this.currentPointer = this.bucketNumber; if (this.lastPaginator > this.totalRows) { this.lastPaginator = this.totalRows; } data = this.massageData(data); this.currentBucket[this.bucketNumber] = data; this.processData(data); } } catch (e) { this.errorValue = -1; this.outerArr = []; this.errorMessage = 'jsError'; } }, error => { this.errorValue = -1; this.outerArr = []; this.errorMessage = 'apiResponseError'; } ); } catch (error) { this.logger.log('error', error); } } handleDropdown(event) { if ( event.type === 'Edit') { // redirect to details page this.workflowService.addRouterSnapshotToLevel(this.router.routerState.snapshot.root); this.router.navigate(['../plugin-management-details', event.data['Plugin ID'].text], { relativeTo: this.activatedRoute, queryParamsHandling: 'merge', queryParams: { } }); } } processData(data) { try { let innerArr = {}; const totalVariablesObj = {}; let cellObj = {}; this.outerArr = []; const getData = data; let getCols; if (getData.length) { getCols = Object.keys(getData[0]); } for (let row = 0; row < getData.length; row++) { innerArr = {}; for (let col = 0; col < getCols.length; col++) { cellObj = { link: '', properties: { color: '' }, colName: getCols[col], hasPreImg: false, imgLink: '', text: getData[row][getCols[col]], valText: getData[row][getCols[col]] }; innerArr[getCols[col]] = cellObj; totalVariablesObj[getCols[col]] = ''; } this.outerArr.push(innerArr); } if (this.outerArr.length > getData.length) { const halfLength = this.outerArr.length / 2; this.outerArr = this.outerArr.splice(halfLength); } this.allColumns = Object.keys(totalVariablesObj); } catch (error) { this.errorMessage = 'jsError'; this.logger.log('error', error); } } searchCalled(search) { this.searchTxt = search; if (this.searchTxt === '') { this.searchPassed = this.searchTxt; } } callNewSearch() { this.searchPassed = this.searchTxt; } massageData(data) { const refactoredService = this.refactorFieldsService; const newData = []; data.map(function(responseData) { responseData['nonDisplayableAttributes'] = responseData['pluginDetails']; delete responseData['pluginDetails']; const KeysTobeChanged = Object.keys(responseData); let newObj = {}; KeysTobeChanged.forEach(element => { const elementnew = refactoredService.getDisplayNameForAKey( element.toLocaleLowerCase() ) || element; newObj = Object.assign(newObj, { [elementnew]: responseData[element] }); }); newData.push(newObj); }); return newData; } ngOnDestroy() { try { if (this.tableSubscription) { this.tableSubscription.unsubscribe(); } } catch (error) { this.logger.log('error', 'JS Error - ' + error); } } }
the_stack
import TestRenderer from "react-test-renderer"; import { HelmetProvider } from "frontity"; import { State } from "frontity/types"; import { FilledContext } from "react-helmet-async"; import { Root as GoogleTagManager } from ".."; import { Packages } from "../../../types"; const getState = (): State<Packages> => ({ frontity: {}, analytics: { pageviews: { googleTagManagerAnalytics: true }, events: {}, }, googleTagManagerAnalytics: {}, }); /** * Render a mocked instance of the Google Tag Manager's root component. * * @param state - Frontity state object. * @returns The rendered component in JSON format, along with the head * attributes. */ const renderGTM = (state: State<Packages>) => { const helmetContext = {}; const rendered = TestRenderer.create( <HelmetProvider context={helmetContext}> <GoogleTagManager state={state} actions={null} libraries={null} /> </HelmetProvider> ).toJSON(); const head = (helmetContext as FilledContext).helmet; return { rendered, head }; }; describe("GoogleTagManager", () => { test("works with a single container id", () => { // Instantiate the Frontity state and specify the `containerId` prop. const state = getState(); state.googleTagManagerAnalytics.containerId = "GTM-XXXXXXX"; // Render the GTM's root component. const { rendered, head } = renderGTM(state); // The GTM's script library with the specified container ID should have been // rendered, an also an inline script that adds the `gtm.start` event. expect(head.script.toComponent()).toMatchInlineSnapshot(` Array [ <script async={true} data-rh={true} src="https://www.googletagmanager.com/gtm.js?id=GTM-XXXXXXX" />, <script dangerouslySetInnerHTML={ Object { "__html": " var dataLayer = window.dataLayer || []; dataLayer.push({ \\"gtm.start\\": new Date().getTime(), event: \\"gtm.js\\", }) ", } } data-rh={true} />, ] `); // A `<noscript>` tag with an `<iframe>` should be rendered as well, to make // GTM work when JS is not available. expect(rendered).toMatchInlineSnapshot(` <noscript> <style dangerouslySetInnerHTML={ Object { "__html": ".css-llz5b9-GtmCode{display:none;visibility:hidden;}", } } data-emotion="css llz5b9-GtmCode" /> <iframe className="css-llz5b9-GtmCode" height="0" src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX" title="GTM-XXXXXXX" width="0" /> </noscript> `); }); test("works with multiple container ids", () => { // Instantiate the Frontity state and specify the `containerIds` array prop. const state = getState(); state.googleTagManagerAnalytics.containerIds = [ "GTM-XXXXXXX", "GTM-YYYYYYY", ]; // Render the GTM's root component. const { rendered, head } = renderGTM(state); // The GTM's script library should have been rendered twice, one for each // container ID specified. The inline script pushing the `gtm.start` event // should be rendered once. expect(head.script.toComponent()).toMatchInlineSnapshot(` Array [ <script async={true} data-rh={true} src="https://www.googletagmanager.com/gtm.js?id=GTM-XXXXXXX" />, <script async={true} data-rh={true} src="https://www.googletagmanager.com/gtm.js?id=GTM-YYYYYYY" />, <script dangerouslySetInnerHTML={ Object { "__html": " var dataLayer = window.dataLayer || []; dataLayer.push({ \\"gtm.start\\": new Date().getTime(), event: \\"gtm.js\\", }) ", } } data-rh={true} />, ] `); // Two `<noscript>` elements should have been rendered this time, one for // each container ID. expect(rendered).toMatchInlineSnapshot(` Array [ <noscript> <style dangerouslySetInnerHTML={ Object { "__html": ".css-llz5b9-GtmCode{display:none;visibility:hidden;}", } } data-emotion="css llz5b9-GtmCode" /> <iframe className="css-llz5b9-GtmCode" height="0" src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX" title="GTM-XXXXXXX" width="0" /> </noscript>, <noscript> <style dangerouslySetInnerHTML={ Object { "__html": ".css-llz5b9-GtmCode{display:none;visibility:hidden;}", } } data-emotion="css llz5b9-GtmCode" /> <iframe className="css-llz5b9-GtmCode" height="0" src="https://www.googletagmanager.com/ns.html?id=GTM-YYYYYYY" title="GTM-YYYYYYY" width="0" /> </noscript>, ] `); }); test("doesn't add anything if there's no container ids", () => { // Instantiate the Frontity state with no container IDs. const state = getState(); // Render the GTM's root component. const { rendered, head } = renderGTM(state); // Nothing should be rendered this time. expect(head.script.toComponent()).toMatchInlineSnapshot(`Array []`); expect(rendered).toMatchInlineSnapshot(`null`); }); }); describe("GoogleTagManager (AMP)", () => { test("works with a single container id", () => { // Instantiate the Frontity state, adding a container ID. const state = getState(); state.frontity.mode = "amp"; state.googleTagManagerAnalytics.containerId = "GTM-XXXXXXX"; // Render the GTM's root component. const { rendered } = renderGTM(state); // An `<amp-analytics>` tag should have been rendered for the given // container ID. expect(rendered).toMatchInlineSnapshot(` <amp-analytics config="https://www.googletagmanager.com/amp.json?id=GTM-XXXXXXX;Tag Manager.url=SOURCE_URL" data-credentials="include" /> `); }); test("works with a single container id and config", () => { // Instantiate the Frontity state, adding a container ID and a configuration // object for the `amp-analytics` tag. const state = getState(); state.frontity.mode = "amp"; state.googleTagManagerAnalytics.containerId = "GTM-XXXXXXX"; state.googleTagManagerAnalytics.ampConfig = { vars: { someProp: "someValue", }, }; // Render the GTM's root component. const { rendered } = renderGTM(state); // If the `ampConfig` prop is set, the value should have been included as a // JSON script inside the `amp-analytics` tag. expect(rendered).toMatchInlineSnapshot(` <amp-analytics config="https://www.googletagmanager.com/amp.json?id=GTM-XXXXXXX;Tag Manager.url=SOURCE_URL" data-credentials="include" > <script dangerouslySetInnerHTML={ Object { "__html": "{\\"vars\\":{\\"someProp\\":\\"someValue\\"}}", } } type="application/json" /> </amp-analytics> `); }); test("works with multiple container ids", () => { // Instantiate the Frontity state, adding two container IDs. const state = getState(); state.frontity.mode = "amp"; state.googleTagManagerAnalytics.containerIds = [ "GTM-XXXXXXX", "GTM-YYYYYYY", ]; // Render the GTM's root component. const { rendered } = renderGTM(state); // Two `<amp-analytics>` tags should have been rendered, one for each given // container ID. expect(rendered).toMatchInlineSnapshot(` Array [ <amp-analytics config="https://www.googletagmanager.com/amp.json?id=GTM-XXXXXXX;Tag Manager.url=SOURCE_URL" data-credentials="include" />, <amp-analytics config="https://www.googletagmanager.com/amp.json?id=GTM-YYYYYYY;Tag Manager.url=SOURCE_URL" data-credentials="include" />, ] `); }); test("works with multiple container ids and config", () => { // Instantiate the Frontity state, adding two container IDs and a config // object for the `amp-analytics` tags. const state = getState(); state.frontity.mode = "amp"; state.googleTagManagerAnalytics.containerIds = [ "GTM-XXXXXXX", "GTM-YYYYYYY", ]; state.googleTagManagerAnalytics.ampConfig = { vars: { someProp: "someValue", }, }; // Render the GTM's root component. const { rendered } = renderGTM(state); // Two `<amp-analytics>` tags should have been rendered, one for each given // container ID, and both sharing the same configuration object. expect(rendered).toMatchInlineSnapshot(` Array [ <amp-analytics config="https://www.googletagmanager.com/amp.json?id=GTM-XXXXXXX;Tag Manager.url=SOURCE_URL" data-credentials="include" > <script dangerouslySetInnerHTML={ Object { "__html": "{\\"vars\\":{\\"someProp\\":\\"someValue\\"}}", } } type="application/json" /> </amp-analytics>, <amp-analytics config="https://www.googletagmanager.com/amp.json?id=GTM-YYYYYYY;Tag Manager.url=SOURCE_URL" data-credentials="include" > <script dangerouslySetInnerHTML={ Object { "__html": "{\\"vars\\":{\\"someProp\\":\\"someValue\\"}}", } } type="application/json" /> </amp-analytics>, ] `); }); test("doesn't add anything if there's no container ids", () => { // Instantiate the Frontity state mocking the `amp` package. const state = getState(); state.frontity.mode = "amp"; // Render the GTM's root component. const { rendered, head } = renderGTM(state); // Nothing should be rendered this time. expect(head.script.toComponent()).toMatchInlineSnapshot(`Array []`); expect(rendered).toMatchInlineSnapshot(`null`); }); });
the_stack
import b2 from '@cocos/box2d'; import { EDITOR } from 'internal:constants'; import { IPhysicsWorld } from '../spec/i-physics-world'; import { IVec2Like, Vec3, Quat, toRadian, Vec2, toDegree, Rect, Node, game, CCObject, find, director, Layers } from '../../core'; import { PHYSICS_2D_PTM_RATIO, ERaycast2DType, ERigidBody2DType } from '../framework/physics-types'; import { array } from '../../core/utils/js'; import { Canvas } from '../../2d/framework'; import { Graphics } from '../../2d/components'; import { b2RigidBody2D } from './rigid-body'; import { PhysicsContactListener } from './platform/physics-contact-listener'; import { PhysicsAABBQueryCallback } from './platform/physics-aabb-query-callback'; import { PhysicsRayCastCallback } from './platform/physics-ray-cast-callback'; import { PhysicsContact, b2ContactExtends } from './physics-contact'; import { Contact2DType, Collider2D, RaycastResult2D } from '../framework'; import { b2Shape2D } from './shapes/shape-2d'; import { PhysicsDebugDraw } from './platform/physics-debug-draw'; const tempVec3 = new Vec3(); const tempVec2_1 = new Vec2(); const tempVec2_2 = new Vec2(); const temoBodyDef = new b2.BodyDef(); const tempB2AABB = new b2.AABB(); const testResults: Collider2D[] = []; export class b2PhysicsWorld implements IPhysicsWorld { protected _world: b2.World; protected _bodies: b2RigidBody2D[] = []; protected _animatedBodies: b2RigidBody2D[] = []; protected _rotationAxis: Vec3 = new Vec3(); protected _contactListener: PhysicsContactListener; protected _aabbQueryCallback: PhysicsAABBQueryCallback; protected _raycastQueryCallback: PhysicsRayCastCallback; get impl () { return this._world; } constructor () { this._world = new b2.World(new b2.Vec2(0, -10)); const listener = new PhysicsContactListener(); listener.setBeginContact(this._onBeginContact); listener.setEndContact(this._onEndContact); listener.setPreSolve(this._onPreSolve); listener.setPostSolve(this._onPostSolve); this._world.SetContactListener(listener); this._contactListener = listener; this._aabbQueryCallback = new PhysicsAABBQueryCallback(); this._raycastQueryCallback = new PhysicsRayCastCallback(); } _debugGraphics: Graphics | null = null; _b2DebugDrawer: b2.Draw | null = null; _debugDrawFlags = 0; get debugDrawFlags () { return this._debugDrawFlags; } set debugDrawFlags (v) { if (EDITOR) return; if (!v) { if (this._debugGraphics) { this._debugGraphics.node.parent = null; } } this._debugDrawFlags = v; } _checkDebugDrawValid () { if (EDITOR) return; if (!this._debugGraphics || !this._debugGraphics.isValid) { let canvas = find('Canvas'); if (!canvas) { const scene = director.getScene() as any; if (!scene) { return; } canvas = new Node('Canvas'); canvas.addComponent(Canvas); canvas.parent = scene; } const node = new Node('PHYSICS_2D_DEBUG_DRAW'); // node.zIndex = cc.macro.MAX_ZINDEX; node.hideFlags |= CCObject.Flags.DontSave; node.parent = canvas; node.worldPosition = Vec3.ZERO; node.layer = Layers.Enum.UI_2D; this._debugGraphics = node.addComponent(Graphics); this._debugGraphics.lineWidth = 2; const debugDraw = new PhysicsDebugDraw(this._debugGraphics); this._b2DebugDrawer = debugDraw; this._world.SetDebugDraw(debugDraw); } const parent = this._debugGraphics.node.parent!; this._debugGraphics.node.setSiblingIndex(parent.children.length - 1); if (this._b2DebugDrawer) { this._b2DebugDrawer.SetFlags(this.debugDrawFlags); } } setGravity (v: IVec2Like) { this._world.SetGravity(v as b2.Vec2); } setAllowSleep (v: boolean) { this._world.SetAllowSleeping(true); } step (deltaTime: number, velocityIterations = 10, positionIterations = 10) { const animatedBodies = this._animatedBodies; for (let i = 0, l = animatedBodies.length; i < l; i++) { animatedBodies[i].animate(deltaTime); } this._world.Step(deltaTime, velocityIterations, positionIterations); } raycast (p1: Vec2, p2: Vec2, type: ERaycast2DType, mask: number): RaycastResult2D[] { if (p1.equals(p2)) { return []; } type = type || ERaycast2DType.Closest; tempVec2_1.x = p1.x / PHYSICS_2D_PTM_RATIO; tempVec2_1.y = p1.y / PHYSICS_2D_PTM_RATIO; tempVec2_2.x = p2.x / PHYSICS_2D_PTM_RATIO; tempVec2_2.y = p2.y / PHYSICS_2D_PTM_RATIO; const callback = this._raycastQueryCallback; callback.init(type, mask); this._world.RayCast(callback, tempVec2_1, tempVec2_2); const fixtures = callback.getFixtures(); if (fixtures.length > 0) { const points = callback.getPoints(); const normals = callback.getNormals(); const fractions = callback.getFractions(); const results: RaycastResult2D[] = []; for (let i = 0, l = fixtures.length; i < l; i++) { const fixture = fixtures[i]; const shape = fixture.m_userData as b2Shape2D; const collider = shape.collider; if (type === ERaycast2DType.AllClosest) { let result; for (let j = 0; j < results.length; j++) { if (results[j].collider === collider) { result = results[j]; } } if (result) { if (fractions[i] < result.fraction) { result.fixtureIndex = shape.getFixtureIndex(fixture); result.point.x = points[i].x * PHYSICS_2D_PTM_RATIO; result.point.y = points[i].y * PHYSICS_2D_PTM_RATIO; result.normal.x = normals[i].x; result.normal.y = normals[i].y; result.fraction = fractions[i]; } continue; } } results.push({ collider, fixtureIndex: shape.getFixtureIndex(fixture), point: new Vec2(points[i].x * PHYSICS_2D_PTM_RATIO, points[i].y * PHYSICS_2D_PTM_RATIO), normal: new Vec2(normals[i].x, normals[i].y), fraction: fractions[i], }); } return results; } return []; } syncPhysicsToScene () { const bodies = this._bodies; for (let i = 0, l = bodies.length; i < l; i++) { const body = bodies[i]; const bodyComp = body.rigidBody; if (bodyComp.type === ERigidBody2DType.Animated) { body.resetVelocity(); continue; } const node = bodyComp.node; const b2body = body.impl; // position const pos = b2body!.GetPosition(); tempVec3.x = pos.x * PHYSICS_2D_PTM_RATIO; tempVec3.y = pos.y * PHYSICS_2D_PTM_RATIO; tempVec3.z = 0; node.worldPosition = tempVec3; // rotation const angle = toDegree(b2body!.GetAngle()); node.setWorldRotationFromEuler(0, 0, angle); } } syncSceneToPhysics () { const bodies = this._bodies; for (let i = 0; i < bodies.length; i++) { bodies[i].syncRotationToPhysics(); bodies[i].syncPositionToPhysics(); } } addBody (body: b2RigidBody2D) { const bodies = this._bodies; if (bodies.includes(body)) { return; } const bodyDef = temoBodyDef; const comp = body.rigidBody; bodyDef.allowSleep = comp.allowSleep; bodyDef.gravityScale = comp.gravityScale; bodyDef.linearDamping = comp.linearDamping; bodyDef.angularDamping = comp.angularDamping; bodyDef.fixedRotation = comp.fixedRotation; bodyDef.bullet = comp.bullet; const node = comp.node; const pos = node.worldPosition; bodyDef.position.Set(pos.x / PHYSICS_2D_PTM_RATIO, pos.y / PHYSICS_2D_PTM_RATIO); tempVec3.z = Quat.getAxisAngle(this._rotationAxis, node.worldRotation); bodyDef.angle = tempVec3.z; bodyDef.awake = comp.awakeOnLoad; if (comp.type === ERigidBody2DType.Animated) { bodyDef.type = ERigidBody2DType.Kinematic as number; this._animatedBodies.push(body); body._animatedPos.set(bodyDef.position.x, bodyDef.position.y); body._animatedAngle = bodyDef.angle; } else { bodyDef.type = comp.type as number; } // read private property const compPrivate = comp as any; const linearVelocity = compPrivate._linearVelocity; bodyDef.linearVelocity.Set(linearVelocity.x, linearVelocity.y); bodyDef.angularVelocity = toRadian(compPrivate._angularVelocity); const b2Body = this._world.CreateBody(bodyDef); b2Body.m_userData = body; body._imp = b2Body; this._bodies.push(body); } removeBody (body: b2RigidBody2D) { if (!this._bodies.includes(body)) { return; } if (body.impl) { body.impl.m_userData = null; this._world.DestroyBody(body.impl); body._imp = null; } array.remove(this._bodies, body); const comp = body.rigidBody; if (comp.type === ERigidBody2DType.Animated) { array.remove(this._animatedBodies, body); } } registerContactFixture (fixture: b2.Fixture) { this._contactListener.registerContactFixture(fixture); } unregisterContactFixture (fixture: b2.Fixture) { this._contactListener.unregisterContactFixture(fixture); } testPoint (point: Vec2): readonly Collider2D[] { const x = tempVec2_1.x = point.x / PHYSICS_2D_PTM_RATIO; const y = tempVec2_1.y = point.y / PHYSICS_2D_PTM_RATIO; const d = 0.2 / PHYSICS_2D_PTM_RATIO; tempB2AABB.lowerBound.x = x - d; tempB2AABB.lowerBound.y = y - d; tempB2AABB.upperBound.x = x + d; tempB2AABB.upperBound.y = y + d; const callback = this._aabbQueryCallback; callback.init(tempVec2_1); this._world.QueryAABB(callback, tempB2AABB); const fixtures = callback.getFixtures(); testResults.length = 0; for (let i = 0; i < fixtures.length; i++) { const collider = (fixtures[i].m_userData as b2Shape2D).collider; if (!testResults.includes(collider)) { testResults.push(collider); } } return testResults; } testAABB (rect: Rect): readonly Collider2D[] { tempB2AABB.lowerBound.x = rect.xMin / PHYSICS_2D_PTM_RATIO; tempB2AABB.lowerBound.y = rect.yMin / PHYSICS_2D_PTM_RATIO; tempB2AABB.upperBound.x = rect.xMax / PHYSICS_2D_PTM_RATIO; tempB2AABB.upperBound.y = rect.yMax / PHYSICS_2D_PTM_RATIO; const callback = this._aabbQueryCallback; callback.init(); this._world.QueryAABB(callback, tempB2AABB); const fixtures = callback.getFixtures(); testResults.length = 0; for (let i = 0; i < fixtures.length; i++) { const collider = (fixtures[i].m_userData as b2Shape2D).collider; if (!testResults.includes(collider)) { testResults.push(collider); } } return testResults; } drawDebug () { this._checkDebugDrawValid(); if (!this._debugGraphics) { return; } this._debugGraphics.clear(); this._world.DrawDebugData(); } _onBeginContact (b2contact: b2ContactExtends) { const c = PhysicsContact.get(b2contact); c.emit(Contact2DType.BEGIN_CONTACT); } _onEndContact (b2contact: b2ContactExtends) { const c = b2contact.m_userData as PhysicsContact; if (!c) { return; } c.emit(Contact2DType.END_CONTACT); PhysicsContact.put(b2contact); } _onPreSolve (b2contact: b2ContactExtends) { const c = b2contact.m_userData as PhysicsContact; if (!c) { return; } c.emit(Contact2DType.PRE_SOLVE); } _onPostSolve (b2contact: b2ContactExtends, impulse: b2.ContactImpulse) { const c: PhysicsContact = b2contact.m_userData as PhysicsContact; if (!c) { return; } // impulse only survive during post sole callback c._setImpulse(impulse); c.emit(Contact2DType.POST_SOLVE); c._setImpulse(null); } }
the_stack
/* * Copyright (c) 2016 - now David Sehnal, licensed under Apache 2.0, See LICENSE file for more info. */ namespace LiteMol.Visualization { export interface Color { r: number; g: number; b: number } export namespace Color { export function copy(from: Color, to: Color) { to.r = from.r; to.g = from.g; to.b = from.b; } export function clone({r,g,b}: Color): Color { return {r,g,b}; } export function toVector(color: Color) { return new THREE.Vector3(color.r, color.g, color.b); } export function fromVector(v: { x: number, y: number, z: number }): Color { return { r: v.x, g: v.y, b: v.z }; } export function fromRgb(r: number, g: number, b: number): Color { return { r: r / 255, g: g / 255, b: b / 255 }; } function hue2rgb(p: number, q: number, t: number){ if(t < 0) t += 1; if(t > 1) t -= 1; if(t < 1/6) return p + (q - p) * 6 * t; if(t < 1/2) return q; if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; return p; } export function fromHsl(h: number, s: number, l: number): Color { //http://stackoverflow.com/questions/2353211/hsl-to-rgb-color-conversion let r: number, g: number, b: number; if(s == 0){ r = g = b = l; // achromatic }else{ let q = l < 0.5 ? l * (1 + s) : l + s - l * s; let p = 2 * l - q; r = hue2rgb(p, q, h + 1/3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1/3); } return { r, g, b }; } export function fromHsv(h: number, s: number, v: number): Color { //http://schinckel.net/2012/01/10/hsv-to-rgb-in-javascript/ let rgb:number[], i: number, data:number[] = []; if (s === 0) { rgb = [v,v,v]; } else { h = h / 60; i = Math.floor(h); data = [v*(1-s), v*(1-s*(h-i)), v*(1-s*(1-(h-i)))]; switch(i) { case 0: rgb = [v, data[2], data[0]]; break; case 1: rgb = [data[1], v, data[0]]; break; case 2: rgb = [data[0], v, data[2]]; break; case 3: rgb = [data[0], data[1], v]; break; case 4: rgb = [data[2], data[0], v]; break; default: rgb = [v, data[0], data[1]]; break; } } return { r: rgb[0], g: rgb[1], b: rgb[2] }; } export function random() { return Utils.Palette.getRandomColor(); } // #rrggbb export function fromHex(v: number): Color { return { r: ((v >> 16) & 0xFF) / 255.0, g: ((v >> 8) & 0xFF) / 255.0, b: (v & 0xFF) / 255.0 } } /** * Parse color in formats #rgb and #rrggbb */ export function fromHexString(s: string): Color { if (s[0] !== '#') return fromHex(0); if (s.length === 4) { // #rgb return fromHexString(`#${s[1]}${s[1]}${s[2]}${s[2]}${s[3]}${s[3]}`); } else if (s.length === 7) { // #rrggbb return fromHex(parseInt(s.substr(1), 16)); } return fromHex(0); } export function interpolate(a: Color, b: Color, t: number, target: Color) { target.r = a.r + (b.r - a.r) * t; target.g = a.g + (b.g - a.g) * t; target.b = a.b + (b.b - a.b) * t; } export function isColor(c: any): c is Color { return c.r !== void 0 && c.g !== void 0 && c.b !== void 0; } } export interface Theme { colors: Theme.ColorMap, variables: Theme.VariableMap, transparency: Theme.Transparency, interactive: boolean, disableFog: boolean, isSticky: boolean, setElementColor(index: number, target: Color): void } export namespace Theme { export interface Props { colors?: ColorMap, variables?: VariableMap, transparency?: Theme.Transparency, interactive?: boolean, disableFog?: boolean, isSticky?: boolean } export interface Transparency { alpha?: number; writeDepth?: boolean } export interface ColorMap { get(key: any): Color | undefined, forEach(f: (value: Color, key: any) => void): void } export interface VariableMap { get(key: any): any | undefined, forEach(f: (value: any, key: any) => void): void } export namespace Default { export const HighlightColor: Color = { r: 1.0, g: 1.0, b: 0 }; export const SelectionColor: Color = { r: 171 / 255, g: 71 / 255, b: 183 / 255 }; //{ r: 1.0, g: 0.0, b: 0.0 }; export const UniformColor: Color = { r: 68 / 255, g: 130 / 255, b: 255 }; export const Transparency: Transparency = { alpha: 1.0, writeDepth: false } } export interface ElementMapping { getProperty(index: number): any; setColor(property: any, c: Color): void; } export function isTransparent(theme: Theme) { let opacity = +theme.transparency.alpha!; if (isNaN(opacity)) opacity = 1.0; return opacity <= 0.999; } export function getColor(theme: Theme, name: string, fallback: Color) { let c = theme.colors.get(name); if (!c) return fallback; return c; } export function createUniform(props: Props = {}): Theme { let { colors, variables = Core.Utils.FastMap.create<string, any>(), transparency = Default.Transparency, interactive = true, disableFog = false, isSticky = false } = props; let finalColors = Core.Utils.FastMap.create<any, Color>(); if (colors) { colors.forEach((c, n) => finalColors.set(n, c)); } let uniform = finalColors.get('Uniform'); if (!uniform) { finalColors.set('Uniform', Default.UniformColor); uniform = Default.UniformColor; } return { colors: finalColors, variables, transparency, interactive, disableFog, isSticky, setElementColor(index: number, target: Color) { Color.copy(uniform!, target); } } } export function createMapping(mapping: ElementMapping, props: Props = {}): Theme { let { colors = Core.Utils.FastMap.create<string, Color>(), variables = Core.Utils.FastMap.create<string, any>(), transparency = Default.Transparency, interactive = true, disableFog = false, isSticky = false } = props; return { colors, variables, transparency: transparency ? transparency : Default.Transparency, interactive, disableFog, isSticky, setElementColor(index: number, target: Color) { mapping.setColor(mapping.getProperty(index), target); } } } export function createColorMapMapping(getProperty: (index: number) => any, map: ColorMap, fallbackColor:Color): ElementMapping { let mapper = new ColorMapMapper(map, fallbackColor); return { getProperty, setColor: (i, c) => mapper.setColor(i, c) }; } export function createPalleteMapping(getProperty: (index: number) => any, pallete: Color[]): ElementMapping { let mapper = new PaletteMapper(pallete); return { getProperty, setColor: (i, c) => mapper.setColor(i, c) }; } export function createPalleteIndexMapping(getProperty: (index: number) => number, pallete: Color[]): ElementMapping { let mapper = new PaletteIndexMapper(pallete); return { getProperty, setColor: (i, c) => mapper.setColor(i, c) }; } class PaletteIndexMapper { setColor(i: number, target: Color) { const color = this.pallete[i]; Color.copy(color, target); } constructor(private pallete: Color[]) { } } class PaletteMapper { private colorIndex = 0; private colorMap = Core.Utils.FastMap.create<any, Color>(); setColor(p: string | number, target: Color) { var color = this.colorMap.get(p); if (!color) { this.colorIndex = ((this.colorIndex + 1) % this.pallete.length) | 0; color = this.pallete[this.colorIndex]; this.colorMap.set(p, color); } Color.copy(color, target); } constructor(private pallete: Color[]) { } } class ColorMapMapper { setColor(p: any, target: Color) { var color = this.map.get(p); if (!color) { color = this.fallbackColor; } Color.copy(color, target); } constructor(private map: ColorMap, private fallbackColor: Color) { } } } }
the_stack
import { Attribute } from "../Attribute"; import { AttributeDefinitions } from "../AttributeDefinitions"; import { DockLocation } from "../DockLocation"; import { DropInfo } from "../DropInfo"; import { Orientation } from "../Orientation"; import { Rect } from "../Rect"; import { CLASSES } from "../Types"; import { BorderNode } from "./BorderNode"; import { IDraggable } from "./IDraggable"; import { IDropTarget } from "./IDropTarget"; import { IJsonTabSetNode } from "./IJsonModel"; import { Model, ILayoutMetrics } from "./Model"; import { Node } from "./Node"; import { RowNode } from "./RowNode"; import { TabNode } from "./TabNode"; import { adjustSelectedIndex } from "./Utils"; export class TabSetNode extends Node implements IDraggable, IDropTarget { static readonly TYPE = "tabset"; /** @internal */ static _fromJson(json: any, model: Model) { const newLayoutNode = new TabSetNode(model, json); if (json.children != null) { for (const jsonChild of json.children) { const child = TabNode._fromJson(jsonChild, model); newLayoutNode._addChild(child); } } if (newLayoutNode._children.length === 0) { newLayoutNode._setSelected(-1); } if (json.maximized && json.maximized === true) { model._setMaximizedTabset(newLayoutNode); } if (json.active && json.active === true) { model._setActiveTabset(newLayoutNode); } return newLayoutNode; } /** @internal */ private static _attributeDefinitions: AttributeDefinitions = TabSetNode._createAttributeDefinitions(); /** @internal */ private static _createAttributeDefinitions(): AttributeDefinitions { const attributeDefinitions = new AttributeDefinitions(); attributeDefinitions.add("type", TabSetNode.TYPE, true).setType(Attribute.STRING).setFixed(); attributeDefinitions.add("id", undefined).setType(Attribute.STRING); attributeDefinitions.add("weight", 100).setType(Attribute.NUMBER); attributeDefinitions.add("width", undefined).setType(Attribute.NUMBER); attributeDefinitions.add("height", undefined).setType(Attribute.NUMBER); attributeDefinitions.add("selected", 0).setType(Attribute.NUMBER); attributeDefinitions.add("name", undefined).setType(Attribute.STRING); attributeDefinitions.add("config", undefined).setType("any"); attributeDefinitions.addInherited("enableDeleteWhenEmpty", "tabSetEnableDeleteWhenEmpty"); attributeDefinitions.addInherited("enableDrop", "tabSetEnableDrop"); attributeDefinitions.addInherited("enableDrag", "tabSetEnableDrag"); attributeDefinitions.addInherited("enableDivide", "tabSetEnableDivide"); attributeDefinitions.addInherited("enableMaximize", "tabSetEnableMaximize"); attributeDefinitions.addInherited("enableClose", "tabSetEnableClose"); attributeDefinitions.addInherited("classNameTabStrip", "tabSetClassNameTabStrip"); attributeDefinitions.addInherited("classNameHeader", "tabSetClassNameHeader"); attributeDefinitions.addInherited("enableTabStrip", "tabSetEnableTabStrip"); attributeDefinitions.addInherited("borderInsets", "tabSetBorderInsets"); attributeDefinitions.addInherited("marginInsets", "tabSetMarginInsets"); attributeDefinitions.addInherited("minWidth", "tabSetMinWidth"); attributeDefinitions.addInherited("minHeight", "tabSetMinHeight"); attributeDefinitions.addInherited("headerHeight", "tabSetHeaderHeight"); attributeDefinitions.addInherited("tabStripHeight", "tabSetTabStripHeight"); attributeDefinitions.addInherited("tabLocation", "tabSetTabLocation"); attributeDefinitions.addInherited("autoSelectTab", "tabSetAutoSelectTab").setType(Attribute.BOOLEAN); return attributeDefinitions; } /** @internal */ private _contentRect?: Rect; /** @internal */ private _tabHeaderRect?: Rect; /** @internal */ private _calculatedTabBarHeight: number; /** @internal */ private _calculatedHeaderBarHeight: number; /** @internal */ constructor(model: Model, json: any) { super(model); TabSetNode._attributeDefinitions.fromJson(json, this._attributes); model._addNode(this); this._calculatedTabBarHeight = 0; this._calculatedHeaderBarHeight = 0; } getName() { return this._getAttr("name") as string | undefined; } getSelected() { const selected = this._attributes.selected; if (selected !== undefined) { return selected as number; } return -1; } getSelectedNode() { const selected = this.getSelected(); if (selected !== -1) { return this._children[selected]; } return undefined; } getWeight(): number { return this._getAttr("weight") as number; } getWidth() { return this._getAttr("width") as number | undefined; } getMinWidth() { return this._getAttr("minWidth") as number; } getHeight() { return this._getAttr("height") as number | undefined; } getMinHeight() { return this._getAttr("minHeight") as number; } /** @internal */ getMinSize(orientation: Orientation) { if (orientation === Orientation.HORZ) { return this.getMinWidth(); } else { return this.getMinHeight(); } } /** * Returns the config attribute that can be used to store node specific data that * WILL be saved to the json. The config attribute should be changed via the action Actions.updateNodeAttributes rather * than directly, for example: * this.state.model.doAction( * FlexLayout.Actions.updateNodeAttributes(node.getId(), {config:myConfigObject})); */ getConfig() { return this._attributes.config; } isMaximized() { return this._model.getMaximizedTabset() === this; } isActive() { return this._model.getActiveTabset() === this; } isEnableDeleteWhenEmpty() { return this._getAttr("enableDeleteWhenEmpty") as boolean; } isEnableDrop() { return this._getAttr("enableDrop") as boolean; } isEnableDrag() { return this._getAttr("enableDrag") as boolean; } isEnableDivide() { return this._getAttr("enableDivide") as boolean; } isEnableMaximize() { return this._getAttr("enableMaximize") as boolean; } isEnableClose() { return this._getAttr("enableClose") as boolean; } canMaximize() { if (this.isEnableMaximize()) { // always allow maximize toggle if already maximized if (this.getModel().getMaximizedTabset() === this) { return true; } // only one tabset, so disable if (this.getParent() === this.getModel().getRoot() && this.getModel().getRoot().getChildren().length === 1) { return false; } return true; } return false; } isEnableTabStrip() { return this._getAttr("enableTabStrip") as boolean; } isAutoSelectTab() { return this._getAttr("autoSelectTab") as boolean; } getClassNameTabStrip() { return this._getAttr("classNameTabStrip") as string | undefined; } getClassNameHeader() { return this._getAttr("classNameHeader") as string | undefined; } /** @internal */ calculateHeaderBarHeight(metrics: ILayoutMetrics) { const headerBarHeight = this._getAttr("headerHeight") as number; if (headerBarHeight !== 0) { // its defined this._calculatedHeaderBarHeight = headerBarHeight; } else { this._calculatedHeaderBarHeight = metrics.headerBarSize; } } /** @internal */ calculateTabBarHeight(metrics: ILayoutMetrics) { const tabBarHeight = this._getAttr("tabStripHeight") as number; if (tabBarHeight !== 0) { // its defined this._calculatedTabBarHeight = tabBarHeight; } else { this._calculatedTabBarHeight = metrics.tabBarSize; } } getHeaderHeight() { return this._calculatedHeaderBarHeight; } getTabStripHeight() { return this._calculatedTabBarHeight; } getTabLocation() { return this._getAttr("tabLocation") as string; } /** @internal */ _setWeight(weight: number) { this._attributes.weight = weight; } /** @internal */ _setSelected(index: number) { this._attributes.selected = index; } /** @internal */ canDrop(dragNode: Node & IDraggable, x: number, y: number): DropInfo | undefined { let dropInfo; if (dragNode === this) { const dockLocation = DockLocation.CENTER; const outlineRect = this._tabHeaderRect; dropInfo = new DropInfo(this, outlineRect!, dockLocation, -1, CLASSES.FLEXLAYOUT__OUTLINE_RECT); } else if (this._contentRect!.contains(x, y)) { const dockLocation = DockLocation.getLocation(this._contentRect!, x, y); const outlineRect = dockLocation.getDockRect(this._rect); dropInfo = new DropInfo(this, outlineRect, dockLocation, -1, CLASSES.FLEXLAYOUT__OUTLINE_RECT); } else if (this._tabHeaderRect != null && this._tabHeaderRect.contains(x, y)) { let r: Rect; let yy: number; let h: number; if (this._children.length === 0) { r = this._tabHeaderRect.clone(); yy = r.y + 3; h = r.height - 4; r.width = 2; } else { let child = this._children[0] as TabNode; r = child.getTabRect()!; yy = r.y; h = r.height; let p = this._tabHeaderRect.x; let childCenter = 0; for (let i = 0; i < this._children.length; i++) { child = this._children[i] as TabNode; r = child.getTabRect()!; childCenter = r.x + r.width / 2; if (x >= p && x < childCenter) { const dockLocation = DockLocation.CENTER; const outlineRect = new Rect(r.x - 2, yy, 3, h); dropInfo = new DropInfo(this, outlineRect, dockLocation, i, CLASSES.FLEXLAYOUT__OUTLINE_RECT); break; } p = childCenter; } } if (dropInfo == null) { const dockLocation = DockLocation.CENTER; const outlineRect = new Rect(r.getRight() - 2, yy, 3, h); dropInfo = new DropInfo(this, outlineRect, dockLocation, this._children.length, CLASSES.FLEXLAYOUT__OUTLINE_RECT); } } if (!dragNode._canDockInto(dragNode, dropInfo)) { return undefined; } return dropInfo; } /** @internal */ _layout(rect: Rect, metrics: ILayoutMetrics) { this.calculateHeaderBarHeight(metrics); this.calculateTabBarHeight(metrics); if (this.isMaximized()) { rect = (this._model.getRoot() as Node).getRect(); } rect = rect.removeInsets(this._getAttr("marginInsets")); this._rect = rect; rect = rect.removeInsets(this._getAttr("borderInsets")); const showHeader = this.getName() !== undefined; let y = 0; let h = 0; if (showHeader) { y += this._calculatedHeaderBarHeight; h += this._calculatedHeaderBarHeight; } if (this.isEnableTabStrip()) { if (this.getTabLocation() === "top") { this._tabHeaderRect = new Rect(rect.x, rect.y + y, rect.width, this._calculatedTabBarHeight); } else { this._tabHeaderRect = new Rect(rect.x, rect.y + rect.height - this._calculatedTabBarHeight, rect.width, this._calculatedTabBarHeight); } h += this._calculatedTabBarHeight; if (this.getTabLocation() === "top") { y += this._calculatedTabBarHeight; } } this._contentRect = new Rect(rect.x, rect.y + y, rect.width, rect.height - h); for (let i = 0; i < this._children.length; i++) { const child = this._children[i]; child._layout(this._contentRect!, metrics); child._setVisible(i === this.getSelected()); } } /** @internal */ _delete() { (this._parent as RowNode)._removeChild(this); } /** @internal */ _remove(node: TabNode) { const removedIndex = this._removeChild(node); this._model._tidy(); adjustSelectedIndex(this, removedIndex); } /** @internal */ drop(dragNode: Node & IDraggable, location: DockLocation, index: number, select?: boolean) { const dockLocation = location; if (this === dragNode) { // tabset drop into itself return; // dock back to itself } let dragParent = dragNode.getParent() as BorderNode | TabSetNode | RowNode; let fromIndex = 0; if (dragParent !== undefined) { fromIndex = dragParent._removeChild(dragNode); adjustSelectedIndex(dragParent, fromIndex); } // if dropping a tab back to same tabset and moving to forward position then reduce insertion index if (dragNode.getType() === TabNode.TYPE && dragParent === this && fromIndex < index && index > 0) { index--; } // simple_bundled dock to existing tabset if (dockLocation === DockLocation.CENTER) { let insertPos = index; if (insertPos === -1) { insertPos = this._children.length; } if (dragNode.getType() === TabNode.TYPE) { this._addChild(dragNode, insertPos); if (select || (select !== false && this.isAutoSelectTab())) { this._setSelected(insertPos); } // console.log("added child at : " + insertPos); } else { for (let i = 0; i < dragNode.getChildren().length; i++) { const child = dragNode.getChildren()[i]; this._addChild(child, insertPos); // console.log("added child at : " + insertPos); insertPos++; } } this._model._setActiveTabset(this); } else { let tabSet: TabSetNode | undefined; if (dragNode instanceof TabNode) { // create new tabset parent // console.log("create a new tabset"); const callback = this._model._getOnCreateTabSet(); tabSet = new TabSetNode(this._model, callback ? callback(dragNode as TabNode) : {}); tabSet._addChild(dragNode); // console.log("added child at end"); dragParent = tabSet; } else { tabSet = dragNode as TabSetNode; } const parentRow = this._parent as Node; const pos = parentRow.getChildren().indexOf(this); if (parentRow.getOrientation() === dockLocation._orientation) { tabSet._setWeight(this.getWeight() / 2); this._setWeight(this.getWeight() / 2); // console.log("added child 50% size at: " + pos + dockLocation.indexPlus); parentRow._addChild(tabSet, pos + dockLocation._indexPlus); } else { // create a new row to host the new tabset (it will go in the opposite direction) // console.log("create a new row"); const newRow = new RowNode(this._model, {}); newRow._setWeight(this.getWeight()); newRow._addChild(this); this._setWeight(50); tabSet._setWeight(50); // console.log("added child 50% size at: " + dockLocation.indexPlus); newRow._addChild(tabSet, dockLocation._indexPlus); parentRow._removeChild(this); parentRow._addChild(newRow, pos); } this._model._setActiveTabset(tabSet); } this._model._tidy(); } toJson(): IJsonTabSetNode { const json: any = {}; TabSetNode._attributeDefinitions.toJson(json, this._attributes); json.children = this._children.map((child) => child.toJson()); if (this.isActive()) { json.active = true; } if (this.isMaximized()) { json.maximized = true; } return json; } /** @internal */ _updateAttrs(json: any) { TabSetNode._attributeDefinitions.update(json, this._attributes); } /** @internal */ _getAttributeDefinitions() { return TabSetNode._attributeDefinitions; } /** @internal */ _getPrefSize(orientation: Orientation) { let prefSize = this.getWidth(); if (orientation === Orientation.VERT) { prefSize = this.getHeight(); } return prefSize; } /** @internal */ static getAttributeDefinitions() { return TabSetNode._attributeDefinitions; } }
the_stack
import { EL } from "./dom" import { dlog, print } from "./util" import { EventEmitter } from "./event" import { uiresponder } from "./uiresponder" import app from "./app" export interface UIWindowConfig { x? :number // position in parent window. Defaults to center of the parent window. y? :number // position in parent window. Defaults to center of the parent window. width? :number height? :number title? :string preventMove? :boolean // if true, window can't be moved by user preventClose? :boolean // if true, window can't be closed by user (no close button) } interface UIWindowEvents { "move": undefined // window moved (note: not triggered during live move) "resize": undefined // window changed size "close": undefined // window closed "focus": undefined // window's body receives keyboard input (reliable; via uiresponder) "blur": undefined // window's body stopped receiving keyboard input } const CAPTURE = {capture:true} const kZeroClientRect :ClientRect = { bottom: 0, height: 0, left: 0, right: 0, top: 0, width: 0 } function isPointInClientRect(x :number, y :number, r :ClientRect) :boolean { return ( x >= r.left && x < r.right && y >= r.top && y < r.bottom ) } let idgen = 0 const windowStack = new class UIWindowStack { windows :UIWindow[] = [] _initCalled = false _init() { this._initCalled = true app.addKeyEventHandler(ev => { // cmd-w, ctrl-w and alt-F4 -- close window in focus if ( this.windows.length > 0 && ( ((ev.ctrlKey || ev.metaKey) && ev.key == "w") || (ev.altKey && ev.key == "F4") ) ) { const topwin = this.top() if (topwin.inFocus) { topwin.close() return true } } }) } top() :UIWindow|null { return this.windows[this.windows.length - 1] || null } has(w :UIWindow) :boolean { for (let win of this.windows) { if (win === w) { return true } } return false } add(w :UIWindow) { if (!this._initCalled) { this._init() } // dlog(`[windowStack] add ${w}`) if (DEBUG) if (this.windows.indexOf(w) != -1) { console.warn(`duplicate call to windowStackAdd ${w}`) return } w._setZIndex(this.windows.length) this.windows.push(w) } remove(w :UIWindow) { let i = this.windows.indexOf(w) // dlog(`[windowStack] remove ${w} i=${i}`) this.windows.splice(i, 1) // update zindex of remaining windows above the removed window for (; i < this.windows.length; i++) { this.windows[i]._setZIndex(i) } if (this.windows.length == 0) { document.body.focus() } else if (w.inFocus) { this.top().focus() } } focus(w :UIWindow) { let topwin = this.top() if (topwin === w) { // already at top return } // move w to top of stack (end of array) let i = this.windows.indexOf(w) let len = this.windows.length for (let y = i + 1; y < len; ) { let w2 = this.windows[y] this.windows[i] = w2 w2._setZIndex(i) i++ y++ } this.windows[i] = w w._setZIndex(i) // dlog(`[windowStack] is now:\n ${this.windows.map(w => `${w}`).join("\n ")}`) } } // windowStack export class UIWindow extends EventEmitter<UIWindowEvents> { static readonly TitleHeight = 24 // keep in sync with app.css readonly id :number = idgen++ readonly domRoot :HTMLDivElement readonly titlebar :HTMLDivElement readonly title :HTMLDivElement readonly closeButton :HTMLElement|null = null readonly body :HTMLElement readonly bodyCover :HTMLDivElement readonly config :UIWindowConfig readonly inFocus :boolean = false // true when primary responder (events: "focus", "blur") readonly isClosed :boolean = false // internal state _x = 0 _y = 0 _width = 300 _height = 200 _zIndex = 0 _debugMutationObserver? :MutationObserver constructor(body :HTMLElement, config? :UIWindowConfig) { super() this.config = config || (config = {}) if (!config.preventClose) { this.closeButton = EL("div", { className: "close-button" }) this.closeButton.onclick = () => { this.close() } } if (config.width !== undefined) { this._width = Math.round(config.width) } if (config.height !== undefined) { this._height = Math.round(config.height) } // initial position const topwin = windowStack.top() this._x = ( config.x !== undefined ? Math.round(config.x) : topwin ? topwin._x + 16 : this._centerOnScreenX() ) this._y = ( config.y !== undefined ? Math.round(config.y) : topwin ? topwin._y + 16 : this._centerOnScreenY() ) this._clampBounds() if (config.x === undefined && this._x < 0) { // TODO improve _clampBounds to position a window after limiting its size this._x = 0 } this.body = body this.domRoot = EL("div", { className: "UIWindow focus", // note: always starts focused tabIndex: "-1", // needed for key focus style: { transform: `translate3d(${this._x}px,${this._y}px,0)`, width: this._width + "px", height: this._height + "px", }, }, this.titlebar = EL("div", { className: "titlebar" }, this.title = EL("div", { className: "title" }, config.title || ""), this.closeButton, ), this.bodyCover = EL("div", { className: "body-cover" }), body, // body must be last-child ) windowStack.add(this) // Note: We must call _enableMove() before adding titlebar event handlers below if (!config.preventMove) { this._enableMove() } uiresponder.addFocusListener(this.body, this._onFocusChange) if (this.closeButton) { this.closeButton.addEventListener("pointerdown", this._onClosePointerDown, CAPTURE) } this.titlebar.addEventListener("pointerdown", this._onTitlePointerDown, CAPTURE) this.titlebar.addEventListener("pointerup", this._onTitlePointerUp, CAPTURE) this.bodyCover.addEventListener("pointerdown", ev => { dlog(`${this} click on body-cover => focus`) this.focus() ev.preventDefault() ev.stopPropagation() }, CAPTURE) document.body.appendChild(this.domRoot) this.focus() if (DEBUG) if (typeof MutationObserver != "undefined") { // detect accidental removal of a window form the DOM, without call to close() // Windows needs to be explicitly close()'d so that windowStack etc can be maintained. this._debugMutationObserver = new MutationObserver((mutationsList, observer) => { for (let m of mutationsList) { for (let i = 0; i < m.removedNodes.length; i++) { if (m.removedNodes[i] === this.domRoot) { console.warn("UIWindow removed from DOM without calling close()") } } } }) this._debugMutationObserver.observe(document, { childList: true, subtree: true }) } } _disconnect() { uiresponder.removeFocusListener(this.body, this._onFocusChange) if (this.closeButton) { this.closeButton.removeEventListener("pointerdown", this._onClosePointerDown, CAPTURE) } this.titlebar.removeEventListener("pointerdown", this._onTitlePointerDown, CAPTURE) this.titlebar.removeEventListener("pointerup", this._onTitlePointerUp, CAPTURE) if (this._debugMutationObserver) { this._debugMutationObserver.disconnect() this._debugMutationObserver = undefined } windowStack.remove(this) } // position properies get x() :number { return this._x } get y() :number { return this._y } set x(x :number) { this.setPosition(x, this._y) } set y(y :number) { this.setPosition(this._x, y) } // size properties get width() :number { return this._width } get height() :number { return this._height } set width(w :number) { this.setSize(w, this._height) } set height(h :number) { this.setSize(this._width, h) } setPosition(x :number, y :number) { if (!this.config.preventMove) { this._setPositionWithEvent(x, y) } } setSize(width :number, height :number) { if (this._setSize(width, height)) { this.triggerEvent("resize") } } setBounds(x :number, y :number, width :number, height :number) { this.setPosition(x, y) this.setSize(width, height) } centerOnScreen() { this._setPositionWithEvent(this._centerOnScreenX(), this._centerOnScreenY()) } focus() { // [rsms] for some reason that I can't figure out, focus is moved to document's body // if we call this.body.focus() once, but moved to the (expected) window's body // if we call it twice... this.body.focus() this.body.focus() } close() { if (!this.isClosed) { ;(this as any).isClosed = true this._disconnect() document.body.removeChild(this.domRoot) this.triggerEvent("close") } } toString() { return `UIWindow#${this.id}` } // ----------------------------------------------------- // rest of class is internal implementation _setZIndex(z :number) { dlog(`${this} set zindex`, z) this._zIndex = z this._updateZIndex() } _updateZIndex() { this.domRoot.style.zIndex = String(100 + this._zIndex) } _setInFocus(inFocus :boolean) { dlog(`${this} ${inFocus ? "received" : "lost"} focus`) if (this.inFocus == inFocus) { return } ;(this as any).inFocus = inFocus if (inFocus) { ;(this as any).inFocus = true this.triggerEvent("focus") windowStack.focus(this) } else { ;(this as any).inFocus = false this.triggerEvent("blur") } this.domRoot.classList.toggle("focus", this.inFocus) this._updateZIndex() } _onFocusChange = (inFocus :Element, lostFocus: Element, _ :FocusEvent) :void => { dlog(`${this} focus changed`, {inFocus, lostFocus}) this._setInFocus(inFocus === this.body) } _isPointerDownInTitle = false _closeButtonRect :ClientRect = kZeroClientRect // TODO better prop name _onClosePointerDown = (ev :PointerEvent) => { // called when pointerdown starts in the close button. // Next the _onTitlePointerDown hander will be called which begins a pointer-capture session. // During the session, this rect is used to provide hover effect for the close button. // When the session ends, this rect is used to determine if the close button was clicked. this._closeButtonRect = this.closeButton.getBoundingClientRect() this.titlebar.addEventListener("pointermove", this._onTitlePointerMove, CAPTURE) ev.preventDefault() } _onTitlePointerDown = (ev :PointerEvent) => { this._isPointerDownInTitle = true if (!ev.metaKey && !ev.ctrlKey) { this.focus() } if (this.titlebar.setPointerCapture) { this.titlebar.setPointerCapture(ev.pointerId) } // needed, else browsers changes focus ev.preventDefault() } _onTitlePointerMove = (ev :PointerEvent) => { // since we use pointer capture, this is a workaround to get the hover effect on the // close button when pointer does: // - down on close button // - leave // - enter close button this.closeButton.classList.toggle("active", isPointInClientRect(ev.x, ev.y, this._closeButtonRect)) } _onTitlePointerUp = (ev :PointerEvent) => { if (this._isPointerDownInTitle) { this._isPointerDownInTitle = false if (this.titlebar.releasePointerCapture) { this.titlebar.releasePointerCapture(ev.pointerId) } if (isPointInClientRect(ev.x, ev.y, this._closeButtonRect)) { this.close() } else if (!ev.metaKey && !ev.ctrlKey) { this.focus() } // needed, else browsers changes focus ev.preventDefault() } if (this._closeButtonRect.width > 0) { this._closeButtonRect = kZeroClientRect this.closeButton.classList.remove("active") this.titlebar.removeEventListener("pointermove", this._onTitlePointerMove, CAPTURE) } } _enableMove() { let currentX = 0 let currentY = 0 let initialX = 0 let initialY = 0 let startX = 0 let startY = 0 const onpointermove = (e :PointerEvent) => { e.preventDefault() currentX = e.clientX - initialX currentY = e.clientY - initialY this._setPosition(currentX, currentY) } const onpointerdown = (e :PointerEvent) => { startX = this._x startY = this._y initialX = e.clientX - this._x initialY = e.clientY - this._y if (this.title.setPointerCapture) { this.title.setPointerCapture(e.pointerId) } document.addEventListener("pointermove", onpointermove, {capture:true}) } const onpointerup = (e :PointerEvent) => { if (this.title.releasePointerCapture) { this.title.releasePointerCapture(e.pointerId) } document.removeEventListener("pointermove", onpointermove, {capture:true}) if (startX != this._x || startY != this._y) { this.triggerEvent("move") } } this.title.addEventListener("pointerdown", onpointerdown, false) this.title.addEventListener("pointerup", onpointerup, false) } _clampBounds() { const minXVisibility = 50 const maxX = window.innerWidth - minXVisibility const maxY = window.innerHeight - UIWindow.TitleHeight this._width = Math.min(window.innerWidth - 8, this._width) this._height = Math.min(window.innerHeight - 8, this._height) this._x = Math.min(maxX, Math.max(-(this._width - minXVisibility), this._x)) this._y = Math.min(maxY, Math.max(0, this._y)) } _setPosition(x :number, y :number) :boolean { const px = window.devicePixelRatio || 1 x = Math.round(x * px) / px y = Math.round(y * px) / px let prevx = this._x let prevy = this._y this._x = x this._y = y this._clampBounds() if (prevx == this._x && prevy == this._y) { return false } this.domRoot.style.transform = `translate3d(${this._x}px, ${this._y}px, 0)` return true } _setSize(width :number, height :number) :boolean { let prevWidth = this._width let prevHeight = this._height this._width = width this._height = height this._clampBounds() if (this._width == prevWidth && this._height == prevHeight) { return false } this.domRoot.style.width = this._width + "px" this.domRoot.style.height = this._height + "px" return true } _setPositionWithEvent(x :number, y :number) { if (this._setPosition(x, y)) { this.triggerEvent("move") } } _centerOnScreenX() :number { return Math.round((window.innerWidth - this._width) * 0.5) } _centerOnScreenY() :number { return Math.round((window.innerHeight - this._height) * 0.4) } } // // DEBUG show window during development // setTimeout(function xx() { // let e = document.createElement("iframe") // e.src = "https://rsms.me/" // let w = new UIWindow(e, { // x: 40, // y: 40, // width: 600, // height: 500, // title: "Worker", // }) // }, 1000)
the_stack
const CLA = 0x55; const CHUNK_SIZE = 250; const INS = { GET_VERSION: 0x00, PUBLIC_KEY_SECP256K1: 0x01, SIGN_SECP256K1: 0x02, SHOW_ADDR_SECP256K1: 0x03, GET_ADDR_SECP256K1: 0x04, SIGN_PERSONAL_MESSAGE: 0x05 }; const ERROR_DESCRIPTION = { 1: "U2F: Unknown", 2: "U2F: Bad request", 3: "U2F: Configuration unsupported", 4: "U2F: Device Ineligible", 5: "U2F: Timeout", 14: "Timeout", 0x9000: "No errors", 0x9001: "Device is busy", 0x6400: "Execution Error", 0x6700: "Wrong Length", 0x6982: "Empty Buffer", 0x6983: "Output buffer too small", 0x6984: "Data is invalid", 0x6985: "Conditions not satisfied", 0x6986: "Transaction rejected", 0x6a80: "Bad key handle", 0x6b00: "Invalid P1/P2", 0x6d00: "Instruction not supported", 0x6e00: "IoTeX app does not seem to be open", 0x6f00: "Unknown error", 0x6f01: "Sign/verify error" }; function errorCodeToString(statusCode: number): string { if (statusCode in ERROR_DESCRIPTION) { // @ts-ignore return ERROR_DESCRIPTION[statusCode]; } return `Unknown Status Code: ${statusCode}`; } // tslint:disable-next-line:no-any function processErrorResponse(response: any): any { return { return_code: response.statusCode, error_message: errorCodeToString(response.statusCode) }; } function serializePath(path: Array<number>): Buffer { if (path == null || path.length < 3) { throw new Error("Invalid path."); } if (path.length > 10) { throw new Error("Invalid path. Length should be <= 10"); } const buf = Buffer.alloc(path.length * 4 + 1); buf.writeUInt8(path.length, 0); for (let i = 0; i < path.length; i += 1) { let v = path[i]; if (i < 3) { // tslint:disable-next-line:no-bitwise v |= 0x80000000; // Harden } buf.writeInt32LE(v, i * 4 + 1); } return buf; } // tslint:disable-next-line:no-any function signGetChunks(path: Array<number>, message: Uint8Array): Array<any> { const chunks = []; chunks.push(serializePath(path)); const buffer = Buffer.from(message); for (let i = 0; i < buffer.length; i += CHUNK_SIZE) { let end = i + CHUNK_SIZE; if (i > buffer.length) { end = buffer.length; } chunks.push(buffer.slice(i, end)); } return chunks; } export class IoTeXLedgerApp { // tslint:disable-next-line:no-any private readonly transport: any; // tslint:disable-next-line:no-any constructor(transport: any, scrambleKey: string = "CSM") { // tslint:disable-next-line:no-typeof-undefined if (typeof transport === "undefined") { throw new Error("Transport has not been defined"); } this.transport = transport; transport.decorateAppAPIMethods( this, ["getVersion", "publicKey", "sign", "appInfo", "deviceInfo"], scrambleKey ); } // tslint:disable-next-line:no-any public async getVersion(): Promise<any> { return this.transport.send(CLA, INS.GET_VERSION, 0, 0).then( // tslint:disable-next-line:no-any (response: any) => { const errorCodeData = response.slice(-2); const returnCode = errorCodeData[0] * 256 + errorCodeData[1]; return { code: returnCode, message: errorCodeToString(returnCode), mode: response[0] !== 0, major: response[1], minor: response[2], patch: response[3], deviceLocked: response[4] === 1 }; }, processErrorResponse ); } // tslint:disable-next-line:no-any public async appInfo(): Promise<any> { return this.transport.send(0xb0, 0x01, 0, 0).then( // tslint:disable-next-line:no-any (response: any) => { const errorCodeData = response.slice(-2); const returnCode = errorCodeData[0] * 256 + errorCodeData[1]; const result = {}; let appName = "err"; let appVersion = "err"; let flagLen = 0; let flagsValue = 0; if (response[0] !== 1) { // @ts-ignore result.error_message = "response format ID not recognized"; // @ts-ignore result.return_code = 0x9001; } else { const appNameLen = response[1]; appName = response.slice(2, appNameLen + 2).toString("ascii"); let idx = appNameLen + 2; const appVersionLen = response[idx]; idx += 1; appVersion = response .slice(idx, idx + appVersionLen) .toString("ascii"); idx += appVersionLen; const appFlagsLen = response[idx]; idx += 1; flagLen = appFlagsLen; flagsValue = response[idx]; } return { code: returnCode, message: errorCodeToString(returnCode), appName, appVersion, flagLen, flagsValue, // tslint:disable-next-line:no-bitwise flag_recovery: (flagsValue & 1) !== 0, // tslint:disable-next-line:no-bitwise flag_signed_mcu_code: (flagsValue & 2) !== 0, // tslint:disable-next-line:no-bitwise flag_onboarded: (flagsValue & 4) !== 0, // tslint:disable-next-line:no-bitwise flag_pin_validated: (flagsValue & 128) !== 0 }; }, processErrorResponse ); } // tslint:disable-next-line:no-any public async deviceInfo(): Promise<any> { return this.transport .send(0xe0, 0x01, 0, 0, Buffer.from([]), [0x9000, 0x6e00]) .then( // tslint:disable-next-line:no-any (response: any) => { const errorCodeData = response.slice(-2); const returnCode = errorCodeData[0] * 256 + errorCodeData[1]; if (returnCode === 0x6e00) { return { return_code: returnCode, error_message: "This command is only available in the Dashboard" }; } const targetId = response.slice(0, 4).toString("hex"); let pos = 4; const secureElementVersionLen = response[pos]; pos += 1; const seVersion = response .slice(pos, pos + secureElementVersionLen) .toString(); pos += secureElementVersionLen; const flagsLen = response[pos]; pos += 1; const flag = response.slice(pos, pos + flagsLen).toString("hex"); pos += flagsLen; const mcuVersionLen = response[pos]; pos += 1; // Patch issue in mcu version let tmp = response.slice(pos, pos + mcuVersionLen); if (tmp[mcuVersionLen - 1] === 0) { tmp = response.slice(pos, pos + mcuVersionLen - 1); } const mcuVersion = tmp.toString(); return { code: returnCode, message: errorCodeToString(returnCode), targetId, seVersion, flag, mcuVersion }; }, processErrorResponse ); } // tslint:disable-next-line:no-any public async publicKey(path: Array<number>): Promise<any> { const serializedPath = serializePath(path); return this.transport .send(CLA, INS.PUBLIC_KEY_SECP256K1, 0, 0, serializedPath) .then( // tslint:disable-next-line:no-any (response: any) => { const errorCodeData = response.slice(-2); const returnCode = errorCodeData[0] * 256 + errorCodeData[1]; const pk = Buffer.from(response.slice(0, 65)); return { publicKey: pk, code: returnCode, message: errorCodeToString(returnCode) }; }, processErrorResponse ); } public async signSendChunk( // tslint:disable-next-line:no-any type: any, // tslint:disable-next-line:no-any chunkIdx: any, // tslint:disable-next-line:no-any chunkNum: any, // tslint:disable-next-line:no-any chunk: any // tslint:disable-next-line:no-any ): Promise<any> { return this.transport .send(CLA, type, chunkIdx, chunkNum, chunk, [0x9000, 0x6a80, 0x6986]) .then( // tslint:disable-next-line:no-any (response: any) => { const errorCodeData = response.slice(-2); const returnCode = errorCodeData[0] * 256 + errorCodeData[1]; let errorMessage = errorCodeToString(returnCode); if (returnCode === 0x6a80) { errorMessage = response .slice(0, response.length - 2) .toString("ascii"); } let signature = null; if (response.length > 2) { signature = response.slice(0, response.length - 2); } return { signature, code: returnCode, message: errorMessage }; }, processErrorResponse ); } // tslint:disable-next-line:no-any public async sign(path: Array<number>, message: Uint8Array): Promise<any> { const chunks = signGetChunks(path, message); return this.signSendChunk( INS.SIGN_SECP256K1, 1, chunks.length, chunks[0] ).then(async response => { let result = { code: response.code, message: response.message, signature: null }; for (let i = 1; i < chunks.length; i += 1) { result = await this.signSendChunk( INS.SIGN_SECP256K1, i + 1, chunks.length, chunks[i] ); if (result.code !== 0x9000) { break; } } return { code: result.code, message: result.message, signature: result.signature }; }, processErrorResponse); } public async signMessage( path: Array<number>, message: Uint8Array // tslint:disable-next-line:no-any ): Promise<any> { const chunks = signGetChunks(path, message); return this.signSendChunk( INS.SIGN_PERSONAL_MESSAGE, 1, chunks.length, chunks[0] ).then(async response => { let result = { code: response.code, message: response.message, signature: null }; for (let i = 1; i < chunks.length; i += 1) { // eslint-disable-next-line no-await-in-loop result = await this.signSendChunk( INS.SIGN_PERSONAL_MESSAGE, i + 1, chunks.length, chunks[i] ); if (result.code !== 0x9000) { break; } } return { code: result.code, message: result.message, signature: result.signature }; }, processErrorResponse); } }
the_stack
* @packageDocumentation * @module std */ //================================================================ import { IForwardIterator } from "../iterator/IForwardIterator"; import { IBidirectionalIterator } from "../iterator/IBidirectionalIterator"; import { IPointer } from "../functional/IPointer"; import { General } from "../internal/functional/General"; import { Writeonly } from "../internal/functional/Writeonly"; import { less } from "../functional/comparators"; import { copy } from "./modifiers"; import { back_inserter } from "../iterator/factory"; import { Vector } from "../container/Vector"; import { Temporary } from "../internal/functional/Temporary"; import { Comparator } from "../internal/functional/Comparator"; /* ========================================================= MERGE & SET OPERATIONS - MERGE - SET OPERATION ============================================================ MERGE --------------------------------------------------------- */ /** * Merge two sorted ranges. * * @param first1 Input iteartor of the first position of the 1st range. * @param last1 Input iterator of the last position of the 1st range. * @param first2 Input iterator of the first position of the 2nd range. * @param last2 Input iterator of the last position of the 2nd range. * @param output Output iterator of the first position. * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. * * @return Output Iterator of the last position by advancing. */ export function merge< InputIterator1 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator1>, InputIterator1>>, InputIterator2 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator1>, InputIterator2>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<InputIterator1>, OutputIterator>>> ( first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, output: OutputIterator, comp: Comparator<IPointer.ValueType<InputIterator1>> = less ): OutputIterator { while (true) { if (first1.equals(last1)) return copy(<Temporary>first2, last2, output); else if (first2.equals(last2)) return copy(first1, last1, output); if (comp(first1.value, first2.value)) { output.value = first1.value; first1 = first1.next(); } else { output.value = first2.value; first2 = first2.next(); } output = output.next(); } } /** * Merge two sorted & consecutive ranges. * * @param first Bidirectional iterator of the first position. * @param middle Bidirectional iterator of the initial position of the 2nd range. * @param last Bidirectional iterator of the last position. * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. */ export function inplace_merge<BidirectionalIterator extends General<IBidirectionalIterator<IPointer.ValueType<BidirectionalIterator>, BidirectionalIterator>>> ( first: BidirectionalIterator, middle: BidirectionalIterator, last: BidirectionalIterator, comp: Comparator<IPointer.ValueType<BidirectionalIterator>> = less ): void { const vector: Vector<IPointer.ValueType<BidirectionalIterator>> = new Vector(); merge(first, middle, middle, last, back_inserter(vector), comp); copy(vector.begin(), vector.end(), first); } /* --------------------------------------------------------- SET OPERATIONS --------------------------------------------------------- */ /** * Test whether two sorted ranges are in inclusion relationship. * * @param first1 Input iteartor of the first position of the 1st range. * @param last1 Input iterator of the last position of the 1st range. * @param first2 Input iterator of the first position of the 2nd range. * @param last2 Input iterator of the last position of the 2nd range. * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. * * @return Whether [first, last1) includes [first2, last2). */ export function includes< InputIterator1 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator1>, InputIterator1>>, InputIterator2 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator1>, InputIterator2>>> ( first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, comp: Comparator<IPointer.ValueType<InputIterator1>> = less ): boolean { while (!first2.equals(last2)) { if (first1.equals(last1) || comp(first2.value, first1.value)) return false; else if (!comp(first1.value, first2.value)) first2 = first2.next(); first1 = first1.next(); } return true; } /** * Combine two sorted ranges to union relationship. * * @param first1 Input iteartor of the first position of the 1st range. * @param last1 Input iterator of the last position of the 1st range. * @param first2 Input iterator of the first position of the 2nd range. * @param last2 Input iterator of the last position of the 2nd range. * @param output Output iterator of the first position. * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. * * @return Output Iterator of the last position by advancing. */ export function set_union< InputIterator1 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator1>, InputIterator1>>, InputIterator2 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator1>, InputIterator2>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<InputIterator1>, OutputIterator>>> ( first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, output: OutputIterator, comp: Comparator<IPointer.ValueType<InputIterator1>> = less ): OutputIterator { while (true) { if (first1.equals(last1)) return copy(<Temporary>first2, last2, output); else if (first2.equals(last2)) return copy(first1, last1, output); if (comp(first1.value, first2.value)) { output.value = first1.value; first1 = first1.next(); } else if (comp(first2.value, first1.value)) { output.value = first2.value; first2 = first2.next(); } else {// equals output.value = first1.value; first1 = first1.next(); first2 = first2.next(); } output = output.next(); } } /** * Combine two sorted ranges to intersection relationship. * * @param first1 Input iteartor of the first position of the 1st range. * @param last1 Input iterator of the last position of the 1st range. * @param first2 Input iterator of the first position of the 2nd range. * @param last2 Input iterator of the last position of the 2nd range. * @param output Output iterator of the first position. * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. * * @return Output Iterator of the last position by advancing. */ export function set_intersection< InputIterator1 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator1>, InputIterator1>>, InputIterator2 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator1>, InputIterator2>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<InputIterator1>, OutputIterator>>> ( first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, output: OutputIterator, comp: Comparator<IPointer.ValueType<InputIterator1>> = less ): OutputIterator { while (!first1.equals(last1) && !first2.equals(last2)) if (comp(first1.value, first2.value)) first1 = first1.next(); else if (comp(first2.value, first1.value)) first2 = first2.next(); else { output.value = first1.value; output = output.next(); first1 = first1.next(); first2 = first2.next(); } return output; } /** * Combine two sorted ranges to difference relationship. * * @param first1 Input iteartor of the first position of the 1st range. * @param last1 Input iterator of the last position of the 1st range. * @param first2 Input iterator of the first position of the 2nd range. * @param last2 Input iterator of the last position of the 2nd range. * @param output Output iterator of the first position. * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. * * @return Output Iterator of the last position by advancing. */ export function set_difference< InputIterator1 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator1>, InputIterator1>>, InputIterator2 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator1>, InputIterator2>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<InputIterator1>, OutputIterator>>> ( first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, output: OutputIterator, comp: Comparator<IPointer.ValueType<InputIterator1>> = less ): OutputIterator { while (!first1.equals(last1) && !first2.equals(last2)) if (comp(first1.value, first2.value)) { output.value = first1.value; output = output.next(); first1 = first1.next(); } else if (comp(first2.value, first1.value)) first2 = first2.next(); else { first1 = first1.next(); first2 = first2.next(); } return copy(first1, last1, output); } /** * Combine two sorted ranges to symmetric difference relationship. * * @param first1 Input iteartor of the first position of the 1st range. * @param last1 Input iterator of the last position of the 1st range. * @param first2 Input iterator of the first position of the 2nd range. * @param last2 Input iterator of the last position of the 2nd range. * @param output Output iterator of the first position. * @param comp A binary function predicates *x* element would be placed before *y*. When returns `true`, then *x* precedes *y*. Default is {@link less}. * * @return Output Iterator of the last position by advancing. */ export function set_symmetric_difference< InputIterator1 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator1>, InputIterator1>>, InputIterator2 extends Readonly<IForwardIterator<IPointer.ValueType<InputIterator1>, InputIterator2>>, OutputIterator extends Writeonly<IForwardIterator<IPointer.ValueType<InputIterator1>, OutputIterator>>> ( first1: InputIterator1, last1: InputIterator1, first2: InputIterator2, last2: InputIterator2, output: OutputIterator, comp: Comparator<IPointer.ValueType<InputIterator1>> = less ): OutputIterator { while (true) { if (first1.equals(last1)) return copy(<Temporary>first2, last2, output); else if (first2.equals(last2)) return copy(first1, last1, output); if (comp(first1.value, first2.value)) { output.value = first1.value; output = output.next(); first1 = first1.next(); } else if (comp(first2.value, first1.value)) { output.value = first2.value; output = output.next(); first2 = first2.next(); } else {// equals first1 = first1.next(); first2 = first2.next(); } } }
the_stack
interface GlobalAttrs { typeAliases: { [ix: string]: string }; constructors: { [typeName: string]: string[] }; decoders: string[]; encoders: string[]; } interface TypeFuncNames { typeName: string; constructorParams: string[]; funcNames: string[]; } interface TypeAliases { [ix: string]: string; } interface Struct { baseName: string; typeArguments: string[]; varDecls: VarDecl[]; constructorParams: string[]; funcNames: string[]; } interface Enum { baseName: string; rawTypeName: string; constructorParams: string[]; funcNames: string[]; } interface Extension { typeBaseName: string; } interface VarDecl { name: string; type: Type; } interface Type { alias?: string; baseName: string; genericArguments: Type[]; } function globalAttrs(ast: any[]) : GlobalAttrs { var tfns = typeFuncNames(ast); var decoders = tfns .filter(d => d.funcNames.contains('decodeJson')) .map(d => d.typeName); var encoders = tfns .filter(d => d.funcNames.contains('encodeJson')) .map(d => d.typeName); var constructors: { [typeName: string]: string[] } = {} tfns.forEach(tfn => { var xs = constructors[tfn.typeName] || [] if (tfn.constructorParams.length) { constructors[tfn.typeName] = xs.concat(tfn.constructorParams) } }) return { typeAliases: typeAliases(ast), constructors: constructors, decoders: decoders, encoders: encoders, } } exports.globalAttrs = globalAttrs; function typeFuncNames(ast: any[]) : TypeFuncNames[] { var emptyAliases: TypeAliases = {}; var ds1 = structs(ast, emptyAliases) .map(s => { return { typeName: s.baseName, constructorParams: s.constructorParams, funcNames: s.funcNames } }); var ds2 = enums(ast, emptyAliases) .map(e => { return { typeName: e.baseName, constructorParams: e.constructorParams, funcNames: e.funcNames } }); var ds3 = ast .children('extension_decl') .map(s => { return { typeName: extension(s).typeBaseName, constructorParams: constructorParams(s), funcNames: funcNames(s) } }); return ds1.concat(ds2).concat(ds3); } function funcNames(ast: any[]) : string[] { return ast.children('func_decl').map(f => f.key(0) == 'implicit' ? f.key(1) : f.key(0)) } function constructorParams(ast: any[]) : string[] { return ast.children('constructor_decl') .filter(a => a.attr('access') != 'private' && a.attr('access') != 'fileprivate') .flatMap(constructorDeclParams) } function constructorDeclParams(constructorDecl: any[]) : string[] { const parts = constructorDecl .filter(obj => (typeof(obj) == 'object' && obj.length == 0) || (typeof(obj) == 'object' && obj.length == 1 && typeof(obj[0]) == 'string')) .map(a => a.length ? a[0] : '') if (parts.length < 3) { return [] } const names = parts[0] const types = parts[2] return [names + '||' + types] } function extension(ast: any[]) : Extension { var fullName = ast.key(0); var keys = ast.keys().slice(1); while (fullName.contains('<') && !fullName.contains('>') && keys.length > 0) { fullName += keys.splice(0, 1)[0] } var baseName = fullName.replace(/<([^>]*)>/g, ''); return { typeBaseName: baseName }; } function typeAliases(ast: any[]) : TypeAliases { var aliases: TypeAliases = {}; ast.children('typealias') .forEach(function (t) { var name = t.fields().name().unquote() var type = t.attrs().filter(attr => attr[0] == 'type' )[1][1] if (!type.startsWith("'") && type.endsWith("'")) { type = type.substring(0, type.length - 1) } aliases[name] = type; }); return aliases; } function getBaseName(ast: any[], prefix?: string) : string { prefix = prefix ? prefix + '.' : ''; var fullName = ast.key(0); return prefix + fullName.replace(/<([^>]*)>/g, ''); } function structs(ast: any[], aliases: TypeAliases, prefix?: string) : Struct[] { var structs1 = ast.children('struct_decl') .map(a => struct(a, aliases, prefix)); var structs2 = ast.children(['struct_decl', 'enum_decl']) .flatMap(a => structs(a, aliases, getBaseName(a, prefix))); return structs1.concat(structs2) } exports.structs = structs; function struct(ast: any[], aliases: TypeAliases, prefix?: string) : Struct { var baseName = getBaseName(ast, prefix) var fullName = ast.key(0) var typeArgs = genericArguments(ast) var varDecls = ast.children('var_decl') .filter(a => a.attr('storage_kind') == 'stored_with_trivial_accessors') .map(a => varDecl(a, aliases)) var r = { baseName: baseName, typeArguments: typeArgs, varDecls: varDecls, constructorParams: constructorParams(ast), funcNames: funcNames(ast) }; return r; } function enums(ast: any[], aliases: TypeAliases, prefix?: string) : Enum[] { var enums1 = ast .children('enum_decl') .filter(a => { var keys = a.keys() var ix = keys.indexOf('inherits:') return ix > 0 && keys.length > ix + 1 }) .map(a => enum_(a, aliases, prefix)); var enums2 = ast.children(['struct_decl', 'enum_decl']) .flatMap(a => enums(a, aliases, getBaseName(a, prefix))); return enums1.concat(enums2); } exports.enums = enums; function enum_(ast: any[], aliases: TypeAliases, prefix?: string) : Enum { var baseName = getBaseName(ast, prefix); var fullName = ast.key(0); var keys = ast.keys() var ix = keys.indexOf('inherits:') var rawTypeName = keys[ix + 1] var r = { baseName: baseName, rawTypeName: rawTypeName, constructorParams: constructorParams(ast), funcNames: funcNames(ast) }; return r; } function genericArguments(ast: any[]) : string[] { // Swift 3.0 has generic arguments as part of fullName // Swift 3.1 has generic arguments as separate parts, after fullName var generics = ast.key(0) const keys = ast.keys() for (var ix = 1; ix < keys.length; ix++) { const key = keys[ix] if (key == 'interface') { break } if (key == '@_fixed_layout') { break } generics += key } var matches = generics.match(/<([^>]*)>/); if (matches && matches.length == 2) return matches[1].split(',').map(s => s.trim()); return [] } function varDecl(ast: any, aliases: TypeAliases) : VarDecl { return { name: ast.key(0), type: type(ast.attr('type'), aliases) }; } function type(typeString: string, aliases: TypeAliases) : Type { if (aliases[typeString]) { var resolved = type(aliases[typeString], aliases); resolved.alias = typeString return resolved; } var isBracketed = typeString.startsWith('[') && typeString.endsWith(']'); var isGeneric = typeString.match(/\<(.*)>/); var isDictionary = isBracketed && typeString.contains(':'); var isArray = isBracketed && !typeString.contains(':'); var isOptional = typeString.endsWith('?'); if (isOptional) { var inner = typeString.substring(0, typeString.length - 1).trim(); return { baseName: 'Optional', genericArguments: [ type(inner, aliases) ] }; } if (isArray) { var inner = typeString.substring(1, typeString.length - 1).trim(); return { baseName: 'Array', genericArguments: [ type(inner, aliases) ] }; } if (isDictionary) { var matches = typeString.match(/\[(.*):(.*)\]/); if (matches.length != 3) throw new Error('"' + typeString + '" appears to be a Dictionary, but isn\'t'); var keyType = type(matches[1].trim(), aliases); var valueType = type(matches[2].trim(), aliases); return { baseName: 'Dictionary', genericArguments: [ keyType, valueType ] }; } if (isDictionary) { var matches = typeString.match(/\[(.*):(.*)\]/); if (matches.length != 3) throw new Error('"' + typeString + '" appears to be a Dictionary, but isn\'t'); var keyType = type(matches[1].trim(), aliases); var valueType = type(matches[2].trim(), aliases); return { baseName: 'Dictionary', genericArguments: [ keyType, valueType ] }; } if (isGeneric) { var baseName = typeString.replace(/<([^>]*)>/g, ''); var matches = typeString.match(/\<(.*)>/); if (matches.length != 2) throw new Error('"' + typeString + '" appears to be a generic type, but isn\'t'); var types = matches[1] .split(',') .map(t => t.trim()) .map(mkType); return { baseName: baseName, genericArguments: types }; } return { baseName: typeString, genericArguments: [] }; } function mkType(name: string) : Type { return { baseName: name, genericArguments: [] }; } // Based on: https://github.com/arian/LISP.js function parse(text) { var results = [] text = text.trim(); // text = text.replace(/=\[([^\]]*)\]'/g, function (n) { return n.replace(/ /g, 'JSON_GEN_SPACE') } ) // Workaround for swiftc 2.0 text = text.replace(/='([^']*)'/g, function (n) { return n.replace(/ /g, 'JSON_GEN_SPACE') } ) text = text.replace(/"<([^>]*)>/g, function (n) { return n.replace(/ /g, 'JSON_GEN_SPACE') } ) if (text.charAt(0) != '(') return text; var stack = []; var token; var tokens = ''; var inString = false; var i = 0; var current; while (i < text.length) { token = text.charAt(i++); var isOpen = token == '('; var isClose = token == ')'; var isSpace = token == ' ' && !inString; if (isOpen || isClose || isSpace) { if (current && tokens.length) { var n = +tokens; var tokens_ = tokens.replace(/JSON_GEN_SPACE/g, ' ') current.push(isNaN(n) ? tokens_ : n); } tokens = ''; } else { if (token == '"') inString = !inString; if (!/\s/.test(token) || inString) tokens += token; } if (isOpen) { var previous = current; current = []; if (previous){ stack.push(previous); previous.push(current); } } else if (isClose) { var pop = stack.pop(); if (!pop) { return current; } current = pop; } } var msg = 'INTERNAL ERROR:\n' + 'Likely due to errornous output from Swift compiler on some language construct (like a switch or array ializer).\n' + 'Workaround: Change all methods from SomeFile.swift into extensions methods in SomeFile+Extensions.swift, which is ignored by JsonGen.\n\n' + 'For details, please create an issue (including the failing Swift sources):\nhttps://github.com/tomlokhorst/swift-json-gen/issues'; console.error(msg) throw 'unbalanced parentheses' }; exports.parse = parse;
the_stack
import { ICanFetch } from "./MlsClient"; import IMlsClient, { IMlsCompletionItem, IRunRequest, IWorkspaceRequest, IWorkspaceResponse, IGistWorkspace, IRunResponse, ApiError, ICompileResponse, CompletionResult, SignatureHelpResult, DiagnosticResult } from "./IMlsClient"; import { CookieGetter } from "./constants/CookieGetter"; import { IWorkspace } from "./IState"; import ServiceError from "./ServiceError"; import { ClientConfiguration, RequestDescriptor, extractApiRequest, ApiRequest } from "./clientConfiguration"; import ICompletionItem from "./ICompletionItem"; import { IApplicationInsightsClient } from "./ApplicationInsights"; import { CreateProjectFromGistRequest, CreateProjectResponse, CreateRegionsFromFilesRequest, CreateRegionsFromFilesResponse } from "./clientApiProtocol"; export interface ICanFetch { (uri: string, request: Request): Promise<Response>; } export interface Headers { [key: string]: string; } export interface Request { body?: string; credentials?: RequestCredentials; headers: Headers; method: string; } export interface Response { json?: () => Promise<any>; text?: () => Promise<string>; ok: boolean; status?: number; statusText?: string; headers?: { map: { [x: string]: string; }; }; } const XsrfTokenKey = "XSRF-TOKEN"; const acceptCompletionKey = "acceptCompletion"; const signatureHelpKey = "signatureHelp"; const completionKey = "completion"; const diagnosticsKey = "diagnostics"; const loadFromGistKey = "loadFromGist"; const runKey = "run"; const compileKey = "compile"; const snippetKey = "snippet"; const projectFromGistKey = "projectFromGist"; const regionsFromFilesKey = "regionsFromFiles"; export default class MlsClient implements IMlsClient { constructor(fetch: ICanFetch, hostOrigin: URL, getCookie: CookieGetter = null, aiClient: IApplicationInsightsClient, trydotnetBaseAddress: URL) { this.fetch = fetch; this.trydotnetBaseAddress = trydotnetBaseAddress; this.getCookie = getCookie; this.clientConfigurationUri = new URL(this.trydotnetBaseAddress.href); this.clientConfigurationUri.pathname = "clientConfiguration"; this.hostOrigin = hostOrigin; this.clientConfiguration = null; this.aiClient = aiClient; if (hostOrigin) { this.clientConfigurationUri.searchParams.append("hostOrigin", hostOrigin.href); } } private aiClient: IApplicationInsightsClient; private fetch: ICanFetch; private trydotnetBaseAddress: URL; private clientConfigurationUri: URL; private getCookie: CookieGetter; private clientConfiguration: ClientConfiguration; private runRequestDescriptor: RequestDescriptor; private compileRequestDescriptor: RequestDescriptor; private snippetRequestDescriptor: RequestDescriptor; private loadFromGistRequestDescriptor: RequestDescriptor; private completionRequestDescriptor: RequestDescriptor; private signatureHelpRequestDescriptor: RequestDescriptor; private acceptCompletionItemRequestDescriptor: RequestDescriptor; private diagnosticsRequestDescriptor: RequestDescriptor; private projectFromGistRequestDescriptor: RequestDescriptor; private regionsFromFilesRequestDescriptor: RequestDescriptor; private hostOrigin: URL; public async getSourceCode(from: IWorkspaceRequest): Promise<IWorkspaceResponse> { return this.fetchWithConfigurationRetry<IWorkspaceResponse>( () => this.snippetRequestDescriptor, { from: from.sourceUri }); } public compile(runRequest: IRunRequest): Promise<ICompileResponse> { return this.fetchWithConfigurationRetry<ICompileResponse>( () => this.compileRequestDescriptor, null, runRequest); } public run(runRequest: IRunRequest): Promise<IRunResponse> { return this.fetchWithConfigurationRetry<IRunResponse>( () => this.runRequestDescriptor, null, runRequest); } public async getWorkspaceFromGist(gistId: string, workspaceType: string, extractBuffers: boolean = false): Promise<IGistWorkspace> { let gistInfo = this.parseGistId(gistId); return this.fetchWithConfigurationRetry<IGistWorkspace>( () => this.loadFromGistRequestDescriptor, { workspaceType, extractBuffers, gistId: gistInfo.gist, commitHash: gistInfo.commitHash }); } public async createProjectFromGist(request: CreateProjectFromGistRequest): Promise<CreateProjectResponse> { return this.fetchWithConfigurationRetry<CreateProjectResponse>( () => this.projectFromGistRequestDescriptor, null, request); } public async createRegionsFromProjectFiles(request: CreateRegionsFromFilesRequest): Promise<CreateRegionsFromFilesResponse> { return this.fetchWithConfigurationRetry<CreateRegionsFromFilesResponse>( () => this.regionsFromFilesRequestDescriptor, null, request); } public async getCompletionList(workspace: IWorkspace, bufferId: string, position: number, completionProvider: string): Promise<CompletionResult> { let result = await this.fetchWithConfigurationRetry<any>( () => this.completionRequestDescriptor, { completionProvider }, { workspace, activeBufferId: bufferId, position: position }); return { items: this.mapCompletionKindToMonacoKind(result), diagnostics: result.diagnostics }; } public async getSignatureHelp(workspace: IWorkspace, bufferId: string, position: number): Promise<SignatureHelpResult> { let result = await this.fetchWithConfigurationRetry<any>( () => this.signatureHelpRequestDescriptor, null, { workspace, activeBufferId: bufferId, position }); return { signatures: result.signatures, activeParameter: result.activeParameter, activeSignature: result.activeSignature, diagnostics: result.diagnostics }; } public async getDiagnostics(workspace: IWorkspace, bufferId: string): Promise<DiagnosticResult> { let result = await this.fetchWithConfigurationRetry<any>( () => this.diagnosticsRequestDescriptor, null, { workspace, activeBufferId: bufferId }); return { diagnostics: result.diagnostics }; } public async acceptCompletionItem(selection: ICompletionItem): Promise<void> { if (selection && selection.acceptanceUri) { return this.fetchWithConfigurationRetry<void>( () => this.acceptCompletionItemRequestDescriptor, { acceptanceUri: selection.acceptanceUri }); } } public async getConfiguration(): Promise<ClientConfiguration> { var request = this.createPostRequest({}); this.addXsrfTokenToRequest(request); let configuration = await this.fetchAndHandleErrors(this.clientConfigurationUri, request); this.clientConfiguration = <ClientConfiguration>configuration; this.processConfiguration(); return configuration; } private async fetchWithConfigurationRetry<T>( getRequestDescriptor: () => RequestDescriptor, apiParameters: any = null, body: any = null): Promise<T> { await this.ensureConfigurationIsLoaded(); let requestDescriptor = getRequestDescriptor(); let api = extractApiRequest(requestDescriptor, apiParameters, this.hostOrigin, this.trydotnetBaseAddress); let request = this.createRequest(requestDescriptor, body); request = this.addHeaders(request, api); let response = await this.fetch(api.url.href, request); let shouldRetryWithNewConfiguration = await this.shouldRefreshConfigurationAndRetry(response); if (!shouldRetryWithNewConfiguration) { if (response.ok) { return response.json(); } else { throw new ServiceError(response.status, response.statusText); } } await this.getConfiguration(); api = extractApiRequest(requestDescriptor, apiParameters, this.hostOrigin, this.trydotnetBaseAddress); request = this.createRequest(requestDescriptor, body); request = this.addHeaders(request, api); let requestId: string = undefined; if (body && body.requestId && typeof body.requestId === "string") { requestId = body.requestId; } return this.fetchAndHandleErrors(api.url, request, requestId); } private mapCompletionKindToMonacoKind(completions: any) { var mapKind = (theKind: string) => { const _kinds = Object.create(null); // types _kinds["Class"] = 6; //monaco.languages.CompletionItemKind.Class; _kinds["Delegate"] = 6; //monaco.languages.CompletionItemKind.Class; // need a better option for this. _kinds["Enum"] = 12; //monaco.languages.CompletionItemKind.Enum; _kinds["Interface"] = 7; //monaco.languages.CompletionItemKind.Interface; _kinds["Struct"] = 6; //monaco.languages.CompletionItemKind.Class; // Monaco doesn't have a Struct kind // variables _kinds["Local"] = 5; //monaco.languages.CompletionItemKind.Variable; _kinds["Parameter"] = 5; //monaco.languages.CompletionItemKind.Variable; _kinds["RangeVariable"] = 5; //monaco.languages.CompletionItemKind.Variable; // members _kinds["Const"] = 4; //monaco.languages.CompletionItemKind.Field; // Monaco doesn't have a Field kind _kinds["EnumMember"] = 12; //monaco.languages.CompletionItemKind.Enum; // Monaco doesn't have an EnumMember kind //_kinds['Event'] = monaco.languages.CompletionItemKind.Event; _kinds["Field"] = 4; //monaco.languages.CompletionItemKind.Field; _kinds["Method"] = 1; //monaco.languages.CompletionItemKind.Method; _kinds["Property"] = 9; //monaco.languages.CompletionItemKind.Property; // other stuff _kinds["Label"] = 10; //monaco.languages.CompletionItemKind.Unit; // need a better option for this. _kinds["Keyword"] = 13; //monaco.languages.CompletionItemKind.Keyword; _kinds["Namespace"] = 8; //monaco.languages.CompletionItemKind.Module; return _kinds[theKind] || 9; //monaco.languages.CompletionItemKind.Property; }; let mappedCompletions: ICompletionItem[] = completions.items.map((i: IMlsCompletionItem) => { let mappedItem: ICompletionItem = { acceptanceUri: i.acceptanceUri, documentation: i.documentation, filterText: i.filterText, insertText: i.insertText, kind: mapKind(i.kind), label: i.displayText, sortText: i.sortText }; return mappedItem; }); return mappedCompletions; } private parseGistId(gistId: string): { gist: string; commitHash?: string } { let parts = gistId.split("/"); let result: { gist: string; commitHash?: string } = { gist: parts[0] }; if (parts.length > 1) { result.commitHash = parts[1]; } return result; } private processConfiguration() { if (this.clientConfiguration) { this.completionRequestDescriptor = this.clientConfiguration._links[completionKey]; this.signatureHelpRequestDescriptor = this.clientConfiguration._links[signatureHelpKey]; this.runRequestDescriptor = this.clientConfiguration._links[runKey]; this.compileRequestDescriptor = this.clientConfiguration._links[compileKey]; this.snippetRequestDescriptor = this.clientConfiguration._links[snippetKey]; this.loadFromGistRequestDescriptor = this.clientConfiguration._links[loadFromGistKey]; this.acceptCompletionItemRequestDescriptor = this.clientConfiguration._links[acceptCompletionKey]; this.projectFromGistRequestDescriptor = this.clientConfiguration._links[projectFromGistKey]; this.regionsFromFilesRequestDescriptor = this.clientConfiguration._links[regionsFromFilesKey]; this.diagnosticsRequestDescriptor = this.clientConfiguration._links[diagnosticsKey]; } } private addXsrfTokenToRequest(request: any) { if (this.getCookie !== null) { var xsrfToken = this.getCookie(XsrfTokenKey); if (xsrfToken) { request.headers[XsrfTokenKey] = xsrfToken; } } } private createRequest(api: RequestDescriptor, data?: any) { var request: Request = { method: api.method, headers: { "Content-Type": "application/json" }, credentials: "same-origin" }; if (api.method === "POST" && data) { request.body = JSON.stringify(data); } this.addXsrfTokenToRequest(request); return request; } private createPostRequest(data: any) { var request: Request = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data), credentials: "same-origin" }; this.addXsrfTokenToRequest(request); return request; } private addHeaders(request: Request, api?: ApiRequest): Request { if (this.clientConfiguration) { request.headers["ClientConfigurationVersionId"] = this.clientConfiguration.versionId; } else { request.headers["ClientConfigurationVersionId"] = "undefined"; } request.headers["Timeout"] = this.getApiCallTimeout(api); return request; } private getApiCallTimeout(api: ApiRequest): string { let timeOutMs = "15000"; if (api) { timeOutMs = `${api.timeoutMsHeader}`; } else if (this.clientConfiguration) { timeOutMs = `${this.clientConfiguration.defaultTimeoutMs}`; } return timeOutMs; } private async shouldRefreshConfigurationAndRetry(response: Response): Promise<boolean> { let needNewConfig = false; switch (response.status) { case 400: let reason: ApiError = await response.json(); if (reason.code === "ConfigurationVersionError") { needNewConfig = true; } break; } return needNewConfig; } private async ensureConfigurationIsLoaded(): Promise<void> { if (this.clientConfiguration === null) { await this.getConfiguration(); } } private async fetchAndHandleErrors(uri: URL, request: Request, reqeustId?: string): Promise<any> { try { var response = await this.fetch(uri.href, request); if (!response) { throw new Error("ECONNREFUSED"); } if (this.aiClient !== null) { this.aiClient.trackDependency( request.method, "", uri.href, 1, response.ok, response.status, reqeustId); } if (response.ok) { return response.json(); } throw new ServiceError(response.status, response.statusText); } catch (ex) { throw ex; } } }
the_stack
import { AfterContentInit, ContentChildren, Directive, ElementRef, EventEmitter, HostBinding, Input, OnDestroy,Output, QueryList, Renderer2, ChangeDetectorRef, HostListener, Inject } from '@angular/core'; import { DOCUMENT } from '@angular/common'; import { MDCChipAdapter, MDCChipSetAdapter, MDCChipFoundation, MDCChipSetFoundation } from '@material/chips'; import { EventSource} from '@material/chips/chip/constants'; import { announce } from '../../utils/thirdparty.announce'; import { AbstractMdcRipple } from '../ripple/abstract.mdc.ripple'; import { MdcEventRegistry } from '../../utils/mdc.event.registry'; import { asBoolean } from '../../utils/value.utils'; import { Subscription } from 'rxjs'; export enum ChipEventSource { primary = EventSource.PRIMARY, trailing = EventSource.TRAILING, none = EventSource.NONE }; /** * Directive for the (optional) leading or trailing icon of an `mdcChip`. * Depending on the position within the `mdcChip` the icon will determine * whether it is a leading or trailing icon. * Trailing icons must implement the functionality to remove the chip from the set, and * must only be added to input chips (`mdcChipSet="input"`). Chips with a trailing * icon must implement the `remove` event. Trailing icons should be wrapped * inside an `mdcChipCell`. */ @Directive({ selector: '[mdcChipIcon]' }) export class MdcChipIconDirective { /** @internal */ @HostBinding('class.mdc-chip__icon') readonly _cls = true; /** @internal */ @HostBinding('class.mdc-chip__icon--leading') _leading = false; /** * Event emitted for trailing icon user interactions. Please note that chip removal should be * handled by the `remove` output of the chip, *not* by a handler for this output. */ @Output() readonly interact: EventEmitter<void> = new EventEmitter(); /** @internal */ @HostBinding('class.mdc-chip__icon--trailing') _trailing = false; private _originalTabindex: number | null = null; private __tabindex: number = -1; private __role: string | null = null; /** @internal */ _chip: MdcChipDirective | null = null; constructor(public _elm: ElementRef, private _rndr: Renderer2, public _cdRef: ChangeDetectorRef) { this.__role = _elm.nativeElement.getAttribute('role'); let tabIndex = _elm.nativeElement.getAttribute('tabindex'); if (tabIndex) { this._originalTabindex = +tabIndex; this.__tabindex = +tabIndex; } } ngOnDestroy() { this._chip = null; } /** @internal */ @HostBinding('attr.tabindex') get _tabindex() { return this._trailing ? this.__tabindex : this._originalTabindex; } /** @internal */ set _tabindex(val: number | null) { this.__tabindex = val == null ? -1 : val; } /** @internal */ @HostBinding('attr.role') get _role() { if (this.__role) return this.__role; return this._trailing ? 'button' : null; } /** @internal */ @HostListener('click', ['$event']) _handleClick(event: MouseEvent) { if (this._chip && this._trailing) this._chip._foundation?.handleTrailingIconInteraction(event); } /** @internal */ @HostListener('keydown', ['$event']) _handleInteraction(event: KeyboardEvent) { if (this._chip && this._trailing) this._chip._foundation?.handleTrailingIconInteraction(event); } } /** * Directive for the text of an `mdcChip`. Must be contained in an `mdcChipPrimaryAction` * directive. */ @Directive({ selector: '[mdcChipText]' }) export class MdcChipTextDirective { @HostBinding('class.mdc-chip__text') readonly _cls = true; constructor(public _elm: ElementRef) {} } /** * Directive for the primary action element of a chip. The `mdcChipPrimaryAction` must * contain the `mdcChipText` directive, and be contained by an `mdcChipCell` directive. */ @Directive({ selector: '[mdcChipPrimaryAction]' }) export class MdcChipPrimaryActionDirective { /** @internal */ @HostBinding('class.mdc-chip__primary-action') readonly _cls = true; private __tabindex: number = -1; /** @internal */ __role: string = 'button'; constructor(public _elm: ElementRef) { this.__tabindex = +(this._elm.nativeElement.getAttribute('tabindex') || -1); } /** @internal */ @HostBinding('attr.role') get _role() { return this.__role; } /** @internal */ @HostBinding('attr.tabindex') get _tabindex() { return this.__tabindex; } /** @internal */ set _tabindex(val: number) { this.__tabindex = val; } } /** * Directive for the main content of a chip, or for an optional trailing * action on `input` chips. This directive must contain an * `mdcChipPrimaryActione` or an `mdcChipIcon` (when used for the trailing action). * An `mdcChipCell` must always be the direct child of an `mdcChip`. */ @Directive({ selector: '[mdcChipCell]' }) export class MdcChipCellDirective { /** @internal */ @HostBinding('attr.role') _role = 'gridcell'; constructor(public _elm: ElementRef) {} } /** * Directive for a chip. Chips must be child elements of an `mdcChipSet`, * and must contain an `mdcChipCell`, and may additionally contain an `mdcChipIcon` for * the leading icon. An optional trailing icon must be wrapped in a second `mdcChipCell`. */ @Directive({ selector: '[mdcChip]' }) export class MdcChipDirective extends AbstractMdcRipple implements AfterContentInit, OnDestroy { /** @internal */ static nextValue = 1; // for computing a unique value, if no value was provided /** @internal */ @HostBinding('class.mdc-chip') readonly _cls = true; /** @internal */ @HostBinding('attr.role') _role = 'row'; private initialized = false; private selectedMem = false; private removableMem = true; private _uniqueValue: string; private _value: string | null = null; /** * Event emitted for user interaction with the chip. */ @Output() readonly interact: EventEmitter<void> = new EventEmitter(); /** * Event emitted when the user has removed (by clicking the trailing icon) the chip. * This event must be implemented when the `removable` property is set, and the chip * has a trailing icon. The implementation must remove the chip from the set. * Without such implementation the directive will animate the chip out of vision, * but will not remove the chip from the DOM. */ @Output() readonly remove: EventEmitter<void> = new EventEmitter(); /** * Event emitted when a navigation event has occured. */ @Output() readonly navigation: EventEmitter<{key: string, source: ChipEventSource}> = new EventEmitter(); /** * Event emitted when the chip changes from not-selected to selected state or vice versa * (for filter and choice chips). */ @Output() readonly selectedChange: EventEmitter<boolean> = new EventEmitter<boolean>(); // Like selectedChange, but only the events that should go to the chipset (i.e. not including the ones initiated by the chipset) /** @internal */ @Output() readonly _selectedForChipSet: EventEmitter<boolean> = new EventEmitter(); /** @internal */ @Output() readonly _notifyRemoval: EventEmitter<{removedAnnouncement: string | null}> = new EventEmitter(); /** @internal */ _set: MdcChipSetDirective | null = null; private _checkmark: HTMLElement | null = null; private _leadingIcon: MdcChipIconDirective | null = null; private _trailingIcon: MdcChipIconDirective | null = null; /** @internal */ @ContentChildren(MdcChipIconDirective, {descendants: true}) _icons?: QueryList<MdcChipIconDirective>; /** @internal */ @ContentChildren(MdcChipTextDirective, {descendants: true}) _texts?: QueryList<MdcChipTextDirective>; /** @internal */ @ContentChildren(MdcChipPrimaryActionDirective, {descendants: true}) _primaryActions?: QueryList<MdcChipPrimaryActionDirective>; /** @internal */ @ContentChildren(MdcChipCellDirective) _chipCells?: QueryList<MdcChipCellDirective>; private _adapter: MDCChipAdapter = { addClass: (className: string) => { const hasClass = this._elm.nativeElement.classList.contains(className); this._renderer.addClass(this._elm.nativeElement, className); if (!hasClass && className === 'mdc-chip--selected') { this.selectedMem = true; this.selectedChange.emit(true); } }, removeClass: (className: string) => { const hasClass = this._elm.nativeElement.classList.contains(className); this._renderer.removeClass(this._elm.nativeElement, className); if (hasClass && className === 'mdc-chip--selected') { this.selectedMem = false; this.selectedChange.emit(false); } }, hasClass: (className) => this._elm.nativeElement.classList.contains(className), addClassToLeadingIcon: (className: string) => this._leadingIcon && this._renderer.addClass(this._leadingIcon._elm.nativeElement, className), removeClassFromLeadingIcon: (className: string) => this._leadingIcon && this._renderer.removeClass(this._leadingIcon._elm.nativeElement, className), eventTargetHasClass: (target: HTMLElement, className: string) => !!target && target.classList.contains(className), getAttribute: (attr: string) => this._elm.nativeElement.getAttribute(attr), notifyInteraction: () => this.interact.emit(), notifySelection: (selected: boolean, chipSetShouldIgnore: boolean) => { if (!chipSetShouldIgnore) this._selectedForChipSet.emit(selected); }, notifyTrailingIconInteraction: () => this._trailingIcon!.interact.emit(), notifyRemoval: (removedAnnouncement: string | null) => this._notifyRemoval.emit({removedAnnouncement}), notifyNavigation: (key: string, source: EventSource) => this.navigation.emit({key, source: <number>source}), getComputedStyleValue: (propertyName: string) => getComputedStyle(this._elm.nativeElement).getPropertyValue(propertyName), setStyleProperty: (style: string, value: string) => this._renderer.setStyle(this._elm.nativeElement, style, value), hasLeadingIcon: () => !!this._leadingIcon, getRootBoundingClientRect: () => this._elm.nativeElement.getBoundingClientRect(), getCheckmarkBoundingClientRect: () => this._checkmark?.getBoundingClientRect() || null, setPrimaryActionAttr: (attr: string, value: string) => this._primaryAction && this._renderer.setAttribute(this._primaryAction._elm.nativeElement, attr, value), focusPrimaryAction: () => this._primaryAction?._elm.nativeElement.focus(), hasTrailingAction: () => !!this._trailingIcon, setTrailingActionAttr: (attr: string, value: string) => this._trailingIcon && this._renderer.setAttribute(this._trailingIcon._elm.nativeElement, attr, value), focusTrailingAction: () => this._trailingIcon?._elm.nativeElement.focus(), isRTL: () => getComputedStyle(this._elm.nativeElement).getPropertyValue('direction') === 'rtl' }; /** @internal */ _foundation: MDCChipFoundation = new MDCChipFoundation(this._adapter); constructor(private _elm: ElementRef, rndr: Renderer2, registry: MdcEventRegistry, @Inject(DOCUMENT) doc: any) { super(_elm, rndr, registry, doc as Document); this._uniqueValue = `mdc-chip-${MdcChipDirective.nextValue++}`; } ngAfterContentInit() { this.initActions(); this.initIcons(); this._icons!.changes.subscribe(() => this._reInit()); this._texts!.changes.subscribe(() => this._reInit()); this._primaryActions!.changes.subscribe(() => this._reInit()); this._chipCells!.changes.subscribe(() => this._reInit()); this.addRippleSurface('mdc-chip__ripple'); this.initCheckMark(); this.initRipple(); this._foundation.init(); if (this.selectedMem) // triggers setting the foundation selected state (and possibly for other [choice] chips too): this.selected = this.selectedMem; if (!this.removableMem) this._foundation.setShouldRemoveOnTrailingIconClick(this.removableMem); this.initialized = true; } ngOnDestroy() { this.destroyRipple(); this._foundation.destroy(); } /** @internal */ _reInit() { // if icons have changed, the foundation must be reinitialized, because // trailingIconInteractionHandler might have to be removed and/or attached // to another icon: this._foundation.destroy(); this._foundation = new MDCChipFoundation(this._adapter); this.initActions(); this.initIcons(); this.initCheckMark(); this._foundation.init(); if (!this.removableMem) this._foundation.setShouldRemoveOnTrailingIconClick(this.removableMem); // no need to call setSelected again, as the previous state will still be available via // the mdc-chip--selected class } private initActions() { if (this._set) { let role = 'button'; if (this._set._type === 'choice') role = 'radio'; else if (this._set._type === 'filter') role = 'checkbox'; this._primaryActions!.forEach(action => { action.__role = role; }); } } private initIcons() { let newLeading = this.computeLeadingIcon(); let newTrailing = this.computeTrailingIcon(newLeading); if (newLeading !== this._leadingIcon || newTrailing !== this._trailingIcon) { this._leadingIcon = newLeading; this._trailingIcon = newTrailing; this._icons!.forEach(icon => { icon._chip = this; let leading = icon === this._leadingIcon; let trailing = icon === this._trailingIcon; let changed = leading !== icon._leading || trailing !== icon._trailing; icon._leading = icon === this._leadingIcon; icon._trailing = icon === this._trailingIcon; if (changed) // if we don't do this we get ExpressionChangedAfterItHasBeenCheckedError: icon._cdRef.detectChanges(); }); this.removeCheckMark(); // checkmark may have changed position, will be readded later (for filter chips) } } private get _text() { return this._texts?.first; } private get _primaryAction() { return this._primaryActions?.first; } private get _chipCell() { return this._chipCells?.first; } private computeLeadingIcon() { if (this._icons && this._icons.length > 0) { let icon = this._icons.first; let prev = this.previousElement(icon._elm.nativeElement); let last = icon._elm.nativeElement; while (true) { // if it is contained in another element, check the siblings of the container too: if (prev == null && last != null && last.parentElement !== this._elm.nativeElement) prev = last.parentElement; // no more elements before, must be the leading icon: if (prev == null) return icon; // comes after the text, so it's not the leading icon: if (this._text && (prev === this._text._elm.nativeElement || prev.contains(this._text._elm.nativeElement))) return null; last = prev; prev = this.previousElement(prev); } } return null; } private computeTrailingIcon(leading: MdcChipIconDirective | null) { if (this._icons!.length > 0) { let icon = this._icons!.last; if (icon === leading) return null; // if not the leading icon, it must be the trailing icon: return icon; } return null; } private previousElement(el: Element): Element { let result = el.previousSibling; while (result != null && !(result instanceof Element)) result = result.previousSibling; return <Element>result; } private initCheckMark() { if (this._set && this._set._type === 'filter') this.addCheckMark(); else this.removeCheckMark(); } private addCheckMark() { if (!this._checkmark && this._chipCell) { let path = this._renderer.createElement('path', 'svg'); this._renderer.addClass(path, 'mdc-chip__checkmark-path'); this._renderer.setAttribute(path, 'fill', 'none'); this._renderer.setAttribute(path, 'stroke', 'black'); this._renderer.setAttribute(path, 'd', 'M1.73,12.91 8.1,19.28 22.79,4.59'); let svg = this._renderer.createElement('svg', 'svg'); this._renderer.appendChild(svg, path); this._renderer.addClass(svg, 'mdc-chip__checkmark-svg'); this._renderer.setAttribute(svg, 'viewBox', '-2 -3 30 30'); this._checkmark = this._renderer.createElement('div'); this._renderer.appendChild(this._checkmark, svg); this._renderer.addClass(this._checkmark, 'mdc-chip__checkmark'); this._renderer.insertBefore(this._elm.nativeElement, this._checkmark, this._chipCell._elm.nativeElement); } } private removeCheckMark() { if (this._checkmark) { this._checkmark.parentElement!.removeChild(this._checkmark); this._checkmark = null; } } /** * The value the chip represents. The value must be unique for the `mdcChipSet`. If you do not provide a value * a unique value will be computed automatically. */ @Input() get value(): string { return this._value ? this._value : this._uniqueValue; } set value(val: string) { this._value = val; } /** * The 'selected' state of the chip. Filter and choice chips are either selected or * not selected. Making a choice chip selected, will make all other chips in that set * not selected. */ @Input() get selected(): boolean { return this.initialized ? this._foundation.isSelected() : this.selectedMem; } set selected(val: boolean) { let value = asBoolean(val); this.selectedMem = value; if (this.initialized && value !== this._foundation.isSelected()) this._foundation.setSelected(value); // when not initialized the selectedChange will be emitted via the foundation after // initialization } static ngAcceptInputType_selected: boolean | ''; /** * If set to a value other than `false`, clicking the trailing icon will animate the * chip out of view, and then emit the `remove` output. */ @HostBinding('class.mdc-chip--deletable') @Input() get removable(): boolean { return this.initialized ? this._foundation.getShouldRemoveOnTrailingIconClick() : this.removableMem; } set removable(val: boolean) { let value = asBoolean(val); this.removableMem = value; if (this.initialized && value !== this._foundation.getShouldRemoveOnTrailingIconClick()) this._foundation.setShouldRemoveOnTrailingIconClick(value); // when not initialized the removable change will be set on the foundation after // initialization } static ngAcceptInputType_removable: boolean | ''; /** @docs-private */ protected computeRippleBoundingRect() { return this._foundation.getDimensions(); } /** @internal */ @HostListener('click', ['$event']) _handleInteraction(event: MouseEvent) { this._foundation?.handleInteraction(event); } /** @internal */ @HostListener('transitionend', ['$event']) _handleTransitionEnd(event: TransitionEvent) { this._foundation?.handleTransitionEnd(event); } /** @internal */ @HostListener('keydown', ['$event']) _handleKeydown(event: KeyboardEvent) { this._foundation?.handleKeydown(event); this._foundation?.handleInteraction(event); } /** @internal */ _untabbable() { if (this._primaryAction) this._primaryAction._tabindex = -1; if (this._trailingIcon) this._trailingIcon._tabindex = -1; } /** @internal */ _allowtabbable() { let result = !!this._primaryAction && this._primaryAction._tabindex !== -1; if (result && this._trailingIcon) this._trailingIcon._tabindex = -1; if (!result) result = !!this._trailingIcon && this._trailingIcon._tabindex != null && this._trailingIcon._tabindex !== -1; return result; } /** @internal */ _forceTabbable() { if (this._primaryAction) this._primaryAction._tabindex = 0; else if (this._trailingIcon) this._trailingIcon._tabindex = 0; } } /** * Directive for a chip-set (a collection of <code>mdcChip</code>). */ @Directive({ selector: '[mdcChipSet]' }) export class MdcChipSetDirective implements AfterContentInit, OnDestroy { /** @internal */ @HostBinding('class.mdc-chip-set') readonly _cls = true; /** @internal */ @HostBinding('attr.role') _role = 'grid'; /** @internal */ @ContentChildren(MdcChipDirective, {descendants: true}) _chips?: QueryList<MdcChipDirective>; private _subscriptions: Subscription[] = []; private _initialized = false; /** @internal */ _type: 'choice' | 'filter' | 'input' | 'action' = 'action'; /** @internal */ _adapter: MDCChipSetAdapter = { hasClass: (className: string) => this._elm.nativeElement.classList.contains(className), removeChipAtIndex: (index: number) => { this.chip(index)!.remove.emit(); // needed so that when focusChipTrailingActionAtIndex is called the // chip has already been removed from the DOM: this.cdRef.detectChanges(); }, selectChipAtIndex: (index: number, selected: boolean, shouldNotifyClients: boolean) => { this.chip(index)?._foundation.setSelectedFromChipSet(selected, shouldNotifyClients); }, getIndexOfChipById: (chipValue) => this.findChipIndex(chipValue), focusChipPrimaryActionAtIndex: (index) => this.chip(index)?._foundation.focusPrimaryAction(), focusChipTrailingActionAtIndex: (index) => this.chip(index)?._foundation.focusTrailingAction(), removeFocusFromChipAtIndex: (index) => this.chip(index)?._foundation.removeFocus(), isRTL: () => getComputedStyle(this._elm.nativeElement).getPropertyValue('direction') === 'rtl', getChipListCount: () => this._chips!.length, announceMessage: (message: string) => announce(message) }; /** @internal */ _foundation: MDCChipSetFoundation | null = new MDCChipSetFoundation(this._adapter); constructor(private _elm: ElementRef, private cdRef: ChangeDetectorRef) {} ngAfterContentInit() { this._chips!.changes.subscribe(() => { this.initSubscriptions(); this.initChips(); this.cdRef.detectChanges(); }); this.initSubscriptions(); this.initChips(); this._foundation!.init(); this._initialized = true; this.cdRef.detectChanges(); } ngOnDestroy() { this._foundation?.destroy(); this._foundation = null; this.destroySubscriptions(); this._initialized = false; } /** * Chip sets by default contain 'action' chips. Set this value to <code>choice</code>, * <code>filter</code>, <code>input</code>, or <code>action</code> to determine the kind * of chips that are contained in the chip set. */ @Input() get mdcChipSet() { return this._type; } set mdcChipSet(value: 'choice' | 'filter' | 'input' | 'action') { if (value !== this._type) { if (value === 'choice' || value === 'filter' || value ==='input') this._type = value; else this._type = 'action'; if (this._initialized) this.initChips(true); } } static ngAcceptInputType_mdcChipSet: 'choice' | 'filter' | 'input' | 'action' | ''; private initChips(force = false) { let hasTabbableItem = false; this._chips!.forEach(chip => { if (force || chip._set !== this) { chip._set = this; chip._reInit(); } if (hasTabbableItem) chip._untabbable(); else hasTabbableItem = chip._allowtabbable(); }); if (!hasTabbableItem && this._chips!.length > 0) this._chips!.first!._forceTabbable(); } private destroySubscriptions() { try { this._subscriptions.forEach(sub => sub.unsubscribe()); } finally { this._subscriptions = []; } } private initSubscriptions() { this.destroySubscriptions(); this._subscriptions = []; this._chips!.forEach(chip => { this._subscriptions!.push(chip.interact.subscribe(() => this._foundation!.handleChipInteraction({chipId: chip.value}))); this._subscriptions!.push(chip._selectedForChipSet.subscribe((selected: boolean) => this._foundation!.handleChipSelection({chipId: chip.value, selected, shouldIgnore: false}))); this._subscriptions!.push(chip._notifyRemoval.subscribe(({removedAnnouncement}: {removedAnnouncement: string | null}) => this._foundation!.handleChipRemoval({chipId: chip.value, removedAnnouncement}))); this._subscriptions!.push(chip.navigation.subscribe(({key, source}: {key: string, source: EventSource}) => this._foundation!.handleChipNavigation({chipId: chip.value, key, source}))); }); } private chip(index: number) { if (index < 0 || index >= this._chips!.length) return null; return this._chips!.toArray()[index]; } private findChipIndex(chipValue: any): number { return this._chips!.toArray().findIndex(chip => chip.value === chipValue); } /** @internal */ @HostBinding('class.mdc-chip-set--choice') get _choice() { return this._type === 'choice'; } /** @internal */ @HostBinding('class.mdc-chip-set--filter') get _filter() { return this._type === 'filter'; } /** @internal */ @HostBinding('class.mdc-chip-set--input') get _input() { return this._type === 'input'; } } export const CHIP_DIRECTIVES = [ MdcChipIconDirective, MdcChipTextDirective, MdcChipPrimaryActionDirective, MdcChipCellDirective, MdcChipDirective, MdcChipSetDirective ];
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config'; interface Blob {} declare class WorkSpaces extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: WorkSpaces.Types.ClientConfiguration) config: Config & WorkSpaces.Types.ClientConfiguration; /** * Creates tags for the specified WorkSpace. */ createTags(params: WorkSpaces.Types.CreateTagsRequest, callback?: (err: AWSError, data: WorkSpaces.Types.CreateTagsResult) => void): Request<WorkSpaces.Types.CreateTagsResult, AWSError>; /** * Creates tags for the specified WorkSpace. */ createTags(callback?: (err: AWSError, data: WorkSpaces.Types.CreateTagsResult) => void): Request<WorkSpaces.Types.CreateTagsResult, AWSError>; /** * Creates one or more WorkSpaces. This operation is asynchronous and returns before the WorkSpaces are created. */ createWorkspaces(params: WorkSpaces.Types.CreateWorkspacesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.CreateWorkspacesResult) => void): Request<WorkSpaces.Types.CreateWorkspacesResult, AWSError>; /** * Creates one or more WorkSpaces. This operation is asynchronous and returns before the WorkSpaces are created. */ createWorkspaces(callback?: (err: AWSError, data: WorkSpaces.Types.CreateWorkspacesResult) => void): Request<WorkSpaces.Types.CreateWorkspacesResult, AWSError>; /** * Deletes the specified tags from a WorkSpace. */ deleteTags(params: WorkSpaces.Types.DeleteTagsRequest, callback?: (err: AWSError, data: WorkSpaces.Types.DeleteTagsResult) => void): Request<WorkSpaces.Types.DeleteTagsResult, AWSError>; /** * Deletes the specified tags from a WorkSpace. */ deleteTags(callback?: (err: AWSError, data: WorkSpaces.Types.DeleteTagsResult) => void): Request<WorkSpaces.Types.DeleteTagsResult, AWSError>; /** * Describes the tags for the specified WorkSpace. */ describeTags(params: WorkSpaces.Types.DescribeTagsRequest, callback?: (err: AWSError, data: WorkSpaces.Types.DescribeTagsResult) => void): Request<WorkSpaces.Types.DescribeTagsResult, AWSError>; /** * Describes the tags for the specified WorkSpace. */ describeTags(callback?: (err: AWSError, data: WorkSpaces.Types.DescribeTagsResult) => void): Request<WorkSpaces.Types.DescribeTagsResult, AWSError>; /** * Describes the available WorkSpace bundles. You can filter the results using either bundle ID or owner, but not both. */ describeWorkspaceBundles(params: WorkSpaces.Types.DescribeWorkspaceBundlesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.DescribeWorkspaceBundlesResult) => void): Request<WorkSpaces.Types.DescribeWorkspaceBundlesResult, AWSError>; /** * Describes the available WorkSpace bundles. You can filter the results using either bundle ID or owner, but not both. */ describeWorkspaceBundles(callback?: (err: AWSError, data: WorkSpaces.Types.DescribeWorkspaceBundlesResult) => void): Request<WorkSpaces.Types.DescribeWorkspaceBundlesResult, AWSError>; /** * Describes the available AWS Directory Service directories that are registered with Amazon WorkSpaces. */ describeWorkspaceDirectories(params: WorkSpaces.Types.DescribeWorkspaceDirectoriesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.DescribeWorkspaceDirectoriesResult) => void): Request<WorkSpaces.Types.DescribeWorkspaceDirectoriesResult, AWSError>; /** * Describes the available AWS Directory Service directories that are registered with Amazon WorkSpaces. */ describeWorkspaceDirectories(callback?: (err: AWSError, data: WorkSpaces.Types.DescribeWorkspaceDirectoriesResult) => void): Request<WorkSpaces.Types.DescribeWorkspaceDirectoriesResult, AWSError>; /** * Describes the specified WorkSpaces. You can filter the results using bundle ID, directory ID, or owner, but you can specify only one filter at a time. */ describeWorkspaces(params: WorkSpaces.Types.DescribeWorkspacesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.DescribeWorkspacesResult) => void): Request<WorkSpaces.Types.DescribeWorkspacesResult, AWSError>; /** * Describes the specified WorkSpaces. You can filter the results using bundle ID, directory ID, or owner, but you can specify only one filter at a time. */ describeWorkspaces(callback?: (err: AWSError, data: WorkSpaces.Types.DescribeWorkspacesResult) => void): Request<WorkSpaces.Types.DescribeWorkspacesResult, AWSError>; /** * Describes the connection status of the specified WorkSpaces. */ describeWorkspacesConnectionStatus(params: WorkSpaces.Types.DescribeWorkspacesConnectionStatusRequest, callback?: (err: AWSError, data: WorkSpaces.Types.DescribeWorkspacesConnectionStatusResult) => void): Request<WorkSpaces.Types.DescribeWorkspacesConnectionStatusResult, AWSError>; /** * Describes the connection status of the specified WorkSpaces. */ describeWorkspacesConnectionStatus(callback?: (err: AWSError, data: WorkSpaces.Types.DescribeWorkspacesConnectionStatusResult) => void): Request<WorkSpaces.Types.DescribeWorkspacesConnectionStatusResult, AWSError>; /** * Modifies the specified WorkSpace properties. */ modifyWorkspaceProperties(params: WorkSpaces.Types.ModifyWorkspacePropertiesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.ModifyWorkspacePropertiesResult) => void): Request<WorkSpaces.Types.ModifyWorkspacePropertiesResult, AWSError>; /** * Modifies the specified WorkSpace properties. */ modifyWorkspaceProperties(callback?: (err: AWSError, data: WorkSpaces.Types.ModifyWorkspacePropertiesResult) => void): Request<WorkSpaces.Types.ModifyWorkspacePropertiesResult, AWSError>; /** * Reboots the specified WorkSpaces. You cannot reboot a WorkSpace unless its state is AVAILABLE, IMPAIRED, or INOPERABLE. This operation is asynchronous and returns before the WorkSpaces have rebooted. */ rebootWorkspaces(params: WorkSpaces.Types.RebootWorkspacesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.RebootWorkspacesResult) => void): Request<WorkSpaces.Types.RebootWorkspacesResult, AWSError>; /** * Reboots the specified WorkSpaces. You cannot reboot a WorkSpace unless its state is AVAILABLE, IMPAIRED, or INOPERABLE. This operation is asynchronous and returns before the WorkSpaces have rebooted. */ rebootWorkspaces(callback?: (err: AWSError, data: WorkSpaces.Types.RebootWorkspacesResult) => void): Request<WorkSpaces.Types.RebootWorkspacesResult, AWSError>; /** * Rebuilds the specified WorkSpaces. You cannot rebuild a WorkSpace unless its state is AVAILABLE or ERROR. Rebuilding a WorkSpace is a potentially destructive action that can result in the loss of data. For more information, see Rebuild a WorkSpace. This operation is asynchronous and returns before the WorkSpaces have been completely rebuilt. */ rebuildWorkspaces(params: WorkSpaces.Types.RebuildWorkspacesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.RebuildWorkspacesResult) => void): Request<WorkSpaces.Types.RebuildWorkspacesResult, AWSError>; /** * Rebuilds the specified WorkSpaces. You cannot rebuild a WorkSpace unless its state is AVAILABLE or ERROR. Rebuilding a WorkSpace is a potentially destructive action that can result in the loss of data. For more information, see Rebuild a WorkSpace. This operation is asynchronous and returns before the WorkSpaces have been completely rebuilt. */ rebuildWorkspaces(callback?: (err: AWSError, data: WorkSpaces.Types.RebuildWorkspacesResult) => void): Request<WorkSpaces.Types.RebuildWorkspacesResult, AWSError>; /** * Starts the specified WorkSpaces. You cannot start a WorkSpace unless it has a running mode of AutoStop and a state of STOPPED. */ startWorkspaces(params: WorkSpaces.Types.StartWorkspacesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.StartWorkspacesResult) => void): Request<WorkSpaces.Types.StartWorkspacesResult, AWSError>; /** * Starts the specified WorkSpaces. You cannot start a WorkSpace unless it has a running mode of AutoStop and a state of STOPPED. */ startWorkspaces(callback?: (err: AWSError, data: WorkSpaces.Types.StartWorkspacesResult) => void): Request<WorkSpaces.Types.StartWorkspacesResult, AWSError>; /** * Stops the specified WorkSpaces. You cannot stop a WorkSpace unless it has a running mode of AutoStop and a state of AVAILABLE, IMPAIRED, UNHEALTHY, or ERROR. */ stopWorkspaces(params: WorkSpaces.Types.StopWorkspacesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.StopWorkspacesResult) => void): Request<WorkSpaces.Types.StopWorkspacesResult, AWSError>; /** * Stops the specified WorkSpaces. You cannot stop a WorkSpace unless it has a running mode of AutoStop and a state of AVAILABLE, IMPAIRED, UNHEALTHY, or ERROR. */ stopWorkspaces(callback?: (err: AWSError, data: WorkSpaces.Types.StopWorkspacesResult) => void): Request<WorkSpaces.Types.StopWorkspacesResult, AWSError>; /** * Terminates the specified WorkSpaces. Terminating a WorkSpace is a permanent action and cannot be undone. The user's data is destroyed. If you need to archive any user data, contact Amazon Web Services before terminating the WorkSpace. You can terminate a WorkSpace that is in any state except SUSPENDED. This operation is asynchronous and returns before the WorkSpaces have been completely terminated. */ terminateWorkspaces(params: WorkSpaces.Types.TerminateWorkspacesRequest, callback?: (err: AWSError, data: WorkSpaces.Types.TerminateWorkspacesResult) => void): Request<WorkSpaces.Types.TerminateWorkspacesResult, AWSError>; /** * Terminates the specified WorkSpaces. Terminating a WorkSpace is a permanent action and cannot be undone. The user's data is destroyed. If you need to archive any user data, contact Amazon Web Services before terminating the WorkSpace. You can terminate a WorkSpace that is in any state except SUSPENDED. This operation is asynchronous and returns before the WorkSpaces have been completely terminated. */ terminateWorkspaces(callback?: (err: AWSError, data: WorkSpaces.Types.TerminateWorkspacesResult) => void): Request<WorkSpaces.Types.TerminateWorkspacesResult, AWSError>; } declare namespace WorkSpaces { export type ARN = string; export type Alias = string; export type BooleanObject = boolean; export type BundleId = string; export type BundleIdList = BundleId[]; export type BundleList = WorkspaceBundle[]; export type BundleOwner = string; export type Compute = "VALUE"|"STANDARD"|"PERFORMANCE"|"POWER"|"GRAPHICS"|string; export interface ComputeType { /** * The compute type. */ Name?: Compute; } export type ComputerName = string; export type ConnectionState = "CONNECTED"|"DISCONNECTED"|"UNKNOWN"|string; export interface CreateTagsRequest { /** * The ID of the resource. */ ResourceId: NonEmptyString; /** * The tags. Each resource can have a maximum of 50 tags. */ Tags: TagList; } export interface CreateTagsResult { } export interface CreateWorkspacesRequest { /** * Information about the WorkSpaces to create. */ Workspaces: WorkspaceRequestList; } export interface CreateWorkspacesResult { /** * Information about the WorkSpaces that could not be created. */ FailedRequests?: FailedCreateWorkspaceRequests; /** * Information about the WorkSpaces that were created. Because this operation is asynchronous, the identifier returned is not immediately available for use with other operations. For example, if you call DescribeWorkspaces before the WorkSpace is created, the information returned can be incomplete. */ PendingRequests?: WorkspaceList; } export type DefaultOu = string; export interface DefaultWorkspaceCreationProperties { /** * Indicates whether the directory is enabled for Amazon WorkDocs. */ EnableWorkDocs?: BooleanObject; /** * The public IP address to attach to all WorkSpaces that are created or rebuilt. */ EnableInternetAccess?: BooleanObject; /** * The organizational unit (OU) in the directory for the WorkSpace machine accounts. */ DefaultOu?: DefaultOu; /** * The identifier of any security groups to apply to WorkSpaces when they are created. */ CustomSecurityGroupId?: SecurityGroupId; /** * Indicates whether the WorkSpace user is an administrator on the WorkSpace. */ UserEnabledAsLocalAdministrator?: BooleanObject; } export interface DeleteTagsRequest { /** * The ID of the resource. */ ResourceId: NonEmptyString; /** * The tag keys. */ TagKeys: TagKeyList; } export interface DeleteTagsResult { } export interface DescribeTagsRequest { /** * The ID of the resource. */ ResourceId: NonEmptyString; } export interface DescribeTagsResult { /** * The tags. */ TagList?: TagList; } export interface DescribeWorkspaceBundlesRequest { /** * The IDs of the bundles. This parameter cannot be combined with any other filter. */ BundleIds?: BundleIdList; /** * The owner of the bundles. This parameter cannot be combined with any other filter. Specify AMAZON to describe the bundles provided by AWS or null to describe the bundles that belong to your account. */ Owner?: BundleOwner; /** * The token for the next set of results. (You received this token from a previous call.) */ NextToken?: PaginationToken; } export interface DescribeWorkspaceBundlesResult { /** * Information about the bundles. */ Bundles?: BundleList; /** * The token to use to retrieve the next set of results, or null if there are no more results available. This token is valid for one day and must be used within that time frame. */ NextToken?: PaginationToken; } export interface DescribeWorkspaceDirectoriesRequest { /** * The identifiers of the directories. If the value is null, all directories are retrieved. */ DirectoryIds?: DirectoryIdList; /** * The token for the next set of results. (You received this token from a previous call.) */ NextToken?: PaginationToken; } export interface DescribeWorkspaceDirectoriesResult { /** * Information about the directories. */ Directories?: DirectoryList; /** * The token to use to retrieve the next set of results, or null if there are no more results available. This token is valid for one day and must be used within that time frame. */ NextToken?: PaginationToken; } export interface DescribeWorkspacesConnectionStatusRequest { /** * The identifiers of the WorkSpaces. */ WorkspaceIds?: WorkspaceIdList; /** * The token for the next set of results. (You received this token from a previous call.) */ NextToken?: PaginationToken; } export interface DescribeWorkspacesConnectionStatusResult { /** * Information about the connection status of the WorkSpace. */ WorkspacesConnectionStatus?: WorkspaceConnectionStatusList; /** * The token to use to retrieve the next set of results, or null if there are no more results available. */ NextToken?: PaginationToken; } export interface DescribeWorkspacesRequest { /** * The IDs of the WorkSpaces. This parameter cannot be combined with any other filter. Because the CreateWorkspaces operation is asynchronous, the identifier it returns is not immediately available. If you immediately call DescribeWorkspaces with this identifier, no information is returned. */ WorkspaceIds?: WorkspaceIdList; /** * The ID of the directory. In addition, you can optionally specify a specific directory user (see UserName). This parameter cannot be combined with any other filter. */ DirectoryId?: DirectoryId; /** * The name of the directory user. You must specify this parameter with DirectoryId. */ UserName?: UserName; /** * The ID of the bundle. All WorkSpaces that are created from this bundle are retrieved. This parameter cannot be combined with any other filter. */ BundleId?: BundleId; /** * The maximum number of items to return. */ Limit?: Limit; /** * The token for the next set of results. (You received this token from a previous call.) */ NextToken?: PaginationToken; } export interface DescribeWorkspacesResult { /** * Information about the WorkSpaces. Because CreateWorkspaces is an asynchronous operation, some of the returned information could be incomplete. */ Workspaces?: WorkspaceList; /** * The token to use to retrieve the next set of results, or null if there are no more results available. This token is valid for one day and must be used within that time frame. */ NextToken?: PaginationToken; } export type Description = string; export type DirectoryId = string; export type DirectoryIdList = DirectoryId[]; export type DirectoryList = WorkspaceDirectory[]; export type DirectoryName = string; export type DnsIpAddresses = IpAddress[]; export type ErrorType = string; export type ExceptionMessage = string; export interface FailedCreateWorkspaceRequest { /** * Information about the WorkSpace. */ WorkspaceRequest?: WorkspaceRequest; /** * The error code. */ ErrorCode?: ErrorType; /** * The textual error message. */ ErrorMessage?: Description; } export type FailedCreateWorkspaceRequests = FailedCreateWorkspaceRequest[]; export type FailedRebootWorkspaceRequests = FailedWorkspaceChangeRequest[]; export type FailedRebuildWorkspaceRequests = FailedWorkspaceChangeRequest[]; export type FailedStartWorkspaceRequests = FailedWorkspaceChangeRequest[]; export type FailedStopWorkspaceRequests = FailedWorkspaceChangeRequest[]; export type FailedTerminateWorkspaceRequests = FailedWorkspaceChangeRequest[]; export interface FailedWorkspaceChangeRequest { /** * The identifier of the WorkSpace. */ WorkspaceId?: WorkspaceId; /** * The error code. */ ErrorCode?: ErrorType; /** * The textual error message. */ ErrorMessage?: Description; } export type IpAddress = string; export type Limit = number; export type ModificationResourceEnum = "ROOT_VOLUME"|"USER_VOLUME"|"COMPUTE_TYPE"|string; export interface ModificationState { /** * The resource. */ Resource?: ModificationResourceEnum; /** * The modification state. */ State?: ModificationStateEnum; } export type ModificationStateEnum = "UPDATE_INITIATED"|"UPDATE_IN_PROGRESS"|string; export type ModificationStateList = ModificationState[]; export interface ModifyWorkspacePropertiesRequest { /** * The ID of the WorkSpace. */ WorkspaceId: WorkspaceId; /** * The properties of the WorkSpace. */ WorkspaceProperties: WorkspaceProperties; } export interface ModifyWorkspacePropertiesResult { } export type NonEmptyString = string; export type PaginationToken = string; export interface RebootRequest { /** * The identifier of the WorkSpace. */ WorkspaceId: WorkspaceId; } export type RebootWorkspaceRequests = RebootRequest[]; export interface RebootWorkspacesRequest { /** * The WorkSpaces to reboot. */ RebootWorkspaceRequests: RebootWorkspaceRequests; } export interface RebootWorkspacesResult { /** * Information about the WorkSpaces that could not be rebooted. */ FailedRequests?: FailedRebootWorkspaceRequests; } export interface RebuildRequest { /** * The identifier of the WorkSpace. */ WorkspaceId: WorkspaceId; } export type RebuildWorkspaceRequests = RebuildRequest[]; export interface RebuildWorkspacesRequest { /** * The WorkSpaces to rebuild. */ RebuildWorkspaceRequests: RebuildWorkspaceRequests; } export interface RebuildWorkspacesResult { /** * Information about the WorkSpaces that could not be rebuilt. */ FailedRequests?: FailedRebuildWorkspaceRequests; } export type RegistrationCode = string; export interface RootStorage { /** * The size of the root volume. */ Capacity?: NonEmptyString; } export type RootVolumeSizeGib = number; export type RunningMode = "AUTO_STOP"|"ALWAYS_ON"|string; export type RunningModeAutoStopTimeoutInMinutes = number; export type SecurityGroupId = string; export interface StartRequest { /** * The ID of the WorkSpace. */ WorkspaceId?: WorkspaceId; } export type StartWorkspaceRequests = StartRequest[]; export interface StartWorkspacesRequest { /** * The WorkSpaces to start. */ StartWorkspaceRequests: StartWorkspaceRequests; } export interface StartWorkspacesResult { /** * Information about the WorkSpaces that could not be started. */ FailedRequests?: FailedStartWorkspaceRequests; } export interface StopRequest { /** * The ID of the WorkSpace. */ WorkspaceId?: WorkspaceId; } export type StopWorkspaceRequests = StopRequest[]; export interface StopWorkspacesRequest { /** * The WorkSpaces to stop. */ StopWorkspaceRequests: StopWorkspaceRequests; } export interface StopWorkspacesResult { /** * Information about the WorkSpaces that could not be stopped. */ FailedRequests?: FailedStopWorkspaceRequests; } export type SubnetId = string; export type SubnetIds = SubnetId[]; export interface Tag { /** * The key of the tag. */ Key: TagKey; /** * The value of the tag. */ Value?: TagValue; } export type TagKey = string; export type TagKeyList = NonEmptyString[]; export type TagList = Tag[]; export type TagValue = string; export interface TerminateRequest { /** * The identifier of the WorkSpace. */ WorkspaceId: WorkspaceId; } export type TerminateWorkspaceRequests = TerminateRequest[]; export interface TerminateWorkspacesRequest { /** * The WorkSpaces to terminate. */ TerminateWorkspaceRequests: TerminateWorkspaceRequests; } export interface TerminateWorkspacesResult { /** * Information about the WorkSpaces that could not be terminated. */ FailedRequests?: FailedTerminateWorkspaceRequests; } export type Timestamp = Date; export type UserName = string; export interface UserStorage { /** * The size of the user storage. */ Capacity?: NonEmptyString; } export type UserVolumeSizeGib = number; export type VolumeEncryptionKey = string; export interface Workspace { /** * The identifier of the WorkSpace. */ WorkspaceId?: WorkspaceId; /** * The identifier of the AWS Directory Service directory for the WorkSpace. */ DirectoryId?: DirectoryId; /** * The user for the WorkSpace. */ UserName?: UserName; /** * The IP address of the WorkSpace. */ IpAddress?: IpAddress; /** * The operational state of the WorkSpace. */ State?: WorkspaceState; /** * The identifier of the bundle used to create the WorkSpace. */ BundleId?: BundleId; /** * The identifier of the subnet for the WorkSpace. */ SubnetId?: SubnetId; /** * If the WorkSpace could not be created, contains a textual error message that describes the failure. */ ErrorMessage?: Description; /** * If the WorkSpace could not be created, contains the error code. */ ErrorCode?: WorkspaceErrorCode; /** * The name of the WorkSpace, as seen by the operating system. */ ComputerName?: ComputerName; /** * The KMS key used to encrypt data stored on your WorkSpace. */ VolumeEncryptionKey?: VolumeEncryptionKey; /** * Indicates whether the data stored on the user volume is encrypted. */ UserVolumeEncryptionEnabled?: BooleanObject; /** * Indicates whether the data stored on the root volume is encrypted. */ RootVolumeEncryptionEnabled?: BooleanObject; /** * The properties of the WorkSpace. */ WorkspaceProperties?: WorkspaceProperties; /** * The modification states of the WorkSpace. */ ModificationStates?: ModificationStateList; } export interface WorkspaceBundle { /** * The bundle identifier. */ BundleId?: BundleId; /** * The name of the bundle. */ Name?: NonEmptyString; /** * The owner of the bundle. This is the account identifier of the owner, or AMAZON if the bundle is provided by AWS. */ Owner?: BundleOwner; /** * A description. */ Description?: Description; /** * The size of the root volume. */ RootStorage?: RootStorage; /** * The size of the user storage. */ UserStorage?: UserStorage; /** * The compute type. For more information, see Amazon WorkSpaces Bundles. */ ComputeType?: ComputeType; } export interface WorkspaceConnectionStatus { /** * The ID of the WorkSpace. */ WorkspaceId?: WorkspaceId; /** * The connection state of the WorkSpace. The connection state is unknown if the WorkSpace is stopped. */ ConnectionState?: ConnectionState; /** * The timestamp of the connection state check. */ ConnectionStateCheckTimestamp?: Timestamp; /** * The timestamp of the last known user connection. */ LastKnownUserConnectionTimestamp?: Timestamp; } export type WorkspaceConnectionStatusList = WorkspaceConnectionStatus[]; export interface WorkspaceDirectory { /** * The directory identifier. */ DirectoryId?: DirectoryId; /** * The directory alias. */ Alias?: Alias; /** * The name of the directory. */ DirectoryName?: DirectoryName; /** * The registration code for the directory. This is the code that users enter in their Amazon WorkSpaces client application to connect to the directory. */ RegistrationCode?: RegistrationCode; /** * The identifiers of the subnets used with the directory. */ SubnetIds?: SubnetIds; /** * The IP addresses of the DNS servers for the directory. */ DnsIpAddresses?: DnsIpAddresses; /** * The user name for the service account. */ CustomerUserName?: UserName; /** * The identifier of the IAM role. This is the role that allows Amazon WorkSpaces to make calls to other services, such as Amazon EC2, on your behalf. */ IamRoleId?: ARN; /** * The directory type. */ DirectoryType?: WorkspaceDirectoryType; /** * The identifier of the security group that is assigned to new WorkSpaces. */ WorkspaceSecurityGroupId?: SecurityGroupId; /** * The state of the directory's registration with Amazon WorkSpaces */ State?: WorkspaceDirectoryState; /** * The default creation properties for all WorkSpaces in the directory. */ WorkspaceCreationProperties?: DefaultWorkspaceCreationProperties; } export type WorkspaceDirectoryState = "REGISTERING"|"REGISTERED"|"DEREGISTERING"|"DEREGISTERED"|"ERROR"|string; export type WorkspaceDirectoryType = "SIMPLE_AD"|"AD_CONNECTOR"|string; export type WorkspaceErrorCode = string; export type WorkspaceId = string; export type WorkspaceIdList = WorkspaceId[]; export type WorkspaceList = Workspace[]; export interface WorkspaceProperties { /** * The running mode. For more information, see Manage the WorkSpace Running Mode. */ RunningMode?: RunningMode; /** * The time after a user logs off when WorkSpaces are automatically stopped. Configured in 60 minute intervals. */ RunningModeAutoStopTimeoutInMinutes?: RunningModeAutoStopTimeoutInMinutes; /** * The size of the root volume. */ RootVolumeSizeGib?: RootVolumeSizeGib; /** * The size of the user storage. */ UserVolumeSizeGib?: UserVolumeSizeGib; /** * The compute type. For more information, see Amazon WorkSpaces Bundles. */ ComputeTypeName?: Compute; } export interface WorkspaceRequest { /** * The identifier of the AWS Directory Service directory for the WorkSpace. You can use DescribeWorkspaceDirectories to list the available directories. */ DirectoryId: DirectoryId; /** * The username of the user for the WorkSpace. This username must exist in the AWS Directory Service directory for the WorkSpace. */ UserName: UserName; /** * The identifier of the bundle for the WorkSpace. You can use DescribeWorkspaceBundles to list the available bundles. */ BundleId: BundleId; /** * The KMS key used to encrypt data stored on your WorkSpace. */ VolumeEncryptionKey?: VolumeEncryptionKey; /** * Indicates whether the data stored on the user volume is encrypted. */ UserVolumeEncryptionEnabled?: BooleanObject; /** * Indicates whether the data stored on the root volume is encrypted. */ RootVolumeEncryptionEnabled?: BooleanObject; /** * The WorkSpace properties. */ WorkspaceProperties?: WorkspaceProperties; /** * The tags for the WorkSpace. */ Tags?: TagList; } export type WorkspaceRequestList = WorkspaceRequest[]; export type WorkspaceState = "PENDING"|"AVAILABLE"|"IMPAIRED"|"UNHEALTHY"|"REBOOTING"|"STARTING"|"REBUILDING"|"MAINTENANCE"|"TERMINATING"|"TERMINATED"|"SUSPENDED"|"UPDATING"|"STOPPING"|"STOPPED"|"ERROR"|string; /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2015-04-08"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the WorkSpaces client. */ export import Types = WorkSpaces; } export = WorkSpaces;
the_stack
import * as ReactDOM from "react-dom"; import { Provider } from "react-redux"; import { dispatch, store } from "./AppRedux"; import { AppState } from "./AppState"; import { Constants as C } from "./Constants"; import { DialogBaseImpl } from "./DialogBaseImpl"; import { DialogMode } from "./enums/DialogMode"; import { PubSub } from "./PubSub"; import { Singletons } from "./Singletons"; import { BaseCompState } from "./widget/base/BaseCompState"; import { Comp } from "./widget/base/Comp"; import { CompIntf } from "./widget/base/CompIntf"; import { Div } from "./widget/Div"; import { Span } from "./widget/Span"; let S: Singletons; PubSub.sub(C.PUBSUB_SingletonsReady, (s: Singletons) => { S = s; }); export abstract class DialogBase<S extends BaseCompState = any> extends Div<S> implements DialogBaseImpl { // ref counter that allows multiple dialogs to be opened on top of each other and only // when the final one closes out do we go back to enabling scrolling on body again. static refCounter = 0; static BACKDROP_PREFIX = "backdrop-"; static backdropZIndex: number = 16000000; // z-index // NOTE: resolve function says null for EMBED mode. resolve: Function; aborted: boolean = false; backdrop: HTMLElement; /* Warning: Base 'Comp' already has 'state', I think it was wrong to rely on 'appState' everywhere inside dialogs, because we need to just let the render methods grab the latest state like every other component in the render method. */ appState: AppState; /* this is a slight hack so we can ignore 'close()' calls that are bogus, and doesn't apply to the EMBED mode */ opened: boolean = false; loaded: boolean = false; /* I added this capability to make the internals of the dialog scroll, but didn't like it ultimately */ internalScrolling: boolean = false; /* NOTE: the 'popup' option/arg was experimental and does work just fine, but one additional thing is needed which is to store the browser scroll position in the dialog, so it can be restored back after editing is complete, and the experimental overrideClass used for testing was "embedded-dlg" */ constructor(public title: string, private overrideClass: string, private closeByOutsideClick: boolean, appState: AppState, public mode: DialogMode = null, public forceMode: boolean = false) { super(null); this.close = this.close.bind(this); this.appState = appState; // new on 3/14/2021 (MessageDlg sending null into here) if (!appState) { this.appState = store.getState(); } // if no mode is given assume it based on whether mobile or not, or if this is mobile then also force fullscreen. if (!forceMode && (!this.mode || this.appState.mobileMode)) { this.mode = this.appState.mobileMode ? DialogMode.FULLSCREEN : DialogMode.POPUP; } if (this.mode === DialogMode.EMBED) { this.attribs.className = this.overrideClass; } else if (this.mode === DialogMode.FULLSCREEN) { this.attribs.className = "app-modal-content-fullscreen"; } else { this.attribs.className = this.appState.mobileMode ? (this.closeByOutsideClick ? "app-modal-main-menu" : "app-modal-content-fullscreen") : (this.overrideClass ? this.overrideClass : "app-modal-content"); } } /* To open any dialog all we do is construct the object and call open(). Returns a promise that resolves when the dialog is closed. */ open = (display: string = null): Promise<DialogBase> => { if (this.mode === DialogMode.EMBED) { return; } this.opened = true; return new Promise<DialogBase>(async (resolve, reject) => { if (this.mode === DialogMode.POPUP) { // Create dialog container and attach to document.body. this.backdrop = document.createElement("div"); this.backdrop.setAttribute("id", DialogBase.BACKDROP_PREFIX + this.getId()); // WARNING: Don't use 'className' here, this is pure javascript, and not React! this.backdrop.setAttribute("class", "app-modal " + (this.appState.mobileMode ? "normalScrollbar" : "customScrollbar")); this.backdrop.setAttribute("style", "z-index: " + (++DialogBase.backdropZIndex)); document.body.appendChild(this.backdrop); // clicking outside the dialog will close it. We only use this for the main menu of the app, because clicking outside a dialog // is too easy to do while your editing and can cause loss of work/editing. if (this.closeByOutsideClick) { this.backdrop.addEventListener("click", (evt: any) => { // get our dialog itself. const contentElm: any = S.util.domElm(this.getId()); // check if the click was outside the dialog. if (!!contentElm && !contentElm.contains(evt.target)) { this.close(); } }); } } /* If the dialog has a function to load from server, call here first */ const queryServerPromise = this.preLoad(); if (queryServerPromise) { await queryServerPromise; } if (this.mode === DialogMode.POPUP) { // this renders the dlgComp onto the screen (on the backdrop elm) this.domRender(); if (++DialogBase.refCounter === 1) { /* we only hide and reshow the scroll bar and disable scrolling when we're in mobile mode, because that's when full-screen dialogs are in use, which is when we need this. */ if (this.appState.mobileMode) { document.body.style.overflow = "hidden"; } } } else { dispatch("Action_OpenDialog", (s: AppState): AppState => { s.dialogStack.push(this); return s; }); } this.resolve = resolve; }); } /* NOTE: preLoad is always forced to complete BEFORE any dialog GUI is allowed to render (excepet in EMBED mode) in case we need to get information from the server before displaying the dialog. This is optional. Many dialogs of course don't need to get data from the server before displaying */ preLoad(): Promise<void> { return null; } domRender(): void { const reactElm = this.e(this._render, this.attribs); // console.log("Rendering with provider"); const provider = this.e(Provider, { store }, reactElm); ReactDOM.render(provider, this.backdrop); } public abort = (): void => { if (this.aborted) return; this.aborted = true; setTimeout(() => { this.close(); }, 100); } public close(): void { if (this.mode === DialogMode.EMBED) { return; } if (!this.opened) return; this.opened = false; this.resolve(this); if (this.mode === DialogMode.POPUP) { if (this.getRef()) { this.preUnmount(); ReactDOM.unmountComponentAtNode(this.backdrop); S.util.domElmRemove(this.getId()); S.util.domElmRemove(DialogBase.BACKDROP_PREFIX + this.getId()); if (--DialogBase.refCounter <= 0) { if (this.appState.mobileMode) { document.body.style.overflow = "auto"; } } } } else { dispatch("Action_CloseDialog", (s: AppState): AppState => { const index = s.dialogStack.indexOf(this); if (index > -1) { s.dialogStack.splice(index, 1); } return s; }); } } preUnmount(): any { } abstract renderDlg(): CompIntf[]; renderButtons(): CompIntf { return null; } /* Can be overridden to customize content (normally icons) in title bar */ getExtraTitleBarComps(): CompIntf[] { return null; } getTitleIconComp(): CompIntf { return null; } getTitleText(): string { return null; } preRender(): void { let timesIcon: Comp; // Dialog Header with close button (x) right justified on it. const children: CompIntf[] = []; const titleIconComp: CompIntf = this.getTitleIconComp(); const titleText: string = this.getTitleText(); const extraHeaderComps = this.getExtraTitleBarComps(); let titleChildren: CompIntf[] = [titleIconComp, new Span(titleText || this.title)]; if (extraHeaderComps) { titleChildren = titleChildren.concat(extraHeaderComps); } titleChildren = titleChildren.concat(timesIcon = new Span("&times;", { className: "float-right app-modal-title-close-icon", onClick: this.close, title: "Close Dialog" })); // NOTE: title will be null for the main menu, which is actually implemented as a dialog using this base class. if (this.title) { children.push(new Div(null, { className: "app-modal-title" }, titleChildren )); timesIcon.renderRawHtml = true; } let contentAttribs: any = null; /* This will make the content area of the dialog above the buttons be scrollable, with a max size that is the full page size before scrolling. This scrolling makes the dialog buttons always stay visible and not themselves scroll */ if (this.internalScrolling) { const style = { maxHeight: "" + (window.innerHeight - 50) + "px" }; contentAttribs = { className: "dialogContentArea", style }; } let renderComps: CompIntf[] = null; try { renderComps = this.renderDlg(); } catch (ex) { S.util.logAndReThrow("renderDlg failed on " + this.getId(), ex); } const contentDiv = new Div(null, contentAttribs, renderComps); children.push(contentDiv); let buttons: CompIntf = this.renderButtons(); if (buttons) { children.push(buttons); } this.setChildren(children); } }
the_stack
import { AfterViewInit, Component, OnInit, TemplateRef, ViewChild, ViewEncapsulation } from '@angular/core'; import { Action } from '../../../action/action'; import { ActionConfig } from '../../../action/action-config'; import { EmptyStateConfig } from '../../../empty-state/empty-state-config'; import { Filter } from '../../../filter/filter'; import { FilterConfig } from '../../../filter/filter-config'; import { FilterField } from '../../../filter/filter-field'; import { FilterEvent } from '../../../filter/filter-event'; import { FilterType } from '../../../filter/filter-type'; import { PaginationConfig } from '../../../pagination/pagination-config'; import { PaginationEvent } from '../../../pagination/pagination-event'; import { SortConfig } from '../../../sort/sort-config'; import { SortField } from '../../../sort/sort-field'; import { SortEvent } from '../../../sort/sort-event'; import { TableConfig } from '../table-config'; import { TableEvent } from '../../table-event'; import { ToolbarConfig } from '../../../toolbar/toolbar-config'; import { cloneDeep } from 'lodash'; @Component({ encapsulation: ViewEncapsulation.None, selector: 'table-empty-example', templateUrl: './table-empty-example.component.html' }) export class TableEmptyExampleComponent implements AfterViewInit, OnInit { @ViewChild('addressTemplate') addressTemplate: TemplateRef<any>; @ViewChild('birthMonthTemplate') birthMonthTemplate: TemplateRef<any>; @ViewChild('nameTemplate') nameTemplate: TemplateRef<any>; @ViewChild('weekDayTemplate') weekDayTemplate: TemplateRef<any>; actionConfig: ActionConfig; actionsText: string = ''; allRows: any[]; columns: any[]; currentSortField: SortField; tableConfig: TableConfig; emptyStateConfig: EmptyStateConfig; filterConfig: FilterConfig; filteredRows: any[]; filtersText: string = ''; isAscendingSort: boolean = true; paginationConfig: PaginationConfig; rows: any[]; rowsAvailable: boolean = false; separator: Object; sortConfig: SortConfig; toolbarConfig: ToolbarConfig; monthVals: any = { 'January': 1, 'February': 2, 'March': 3, 'April': 4, 'May': 5, 'June': 6, 'July': 7, 'August': 8, 'September': 9, 'October': 10, 'November': 11, 'December': 12 }; weekDayVals: any = { 'Sunday': 1, 'Monday': 2, 'Tuesday': 3, 'Wednesday': 4, 'Thursday': 5, 'Friday': 6, 'Saturday': 7 }; constructor() { } ngAfterViewInit(): void { // this.updateRows(false); // Reinitialize expanded rows in order to render properly with tabs } ngOnInit(): void { this.columns = [{ cellTemplate: this.nameTemplate, draggable: true, prop: 'name', name: 'Name', resizeable: true, sortable: false // using sort menu }, { cellTemplate: this.addressTemplate, draggable: true, prop: 'address', name: 'Address', resizeable: true, sortable: false // using sort menu }, { cellTemplate: this.birthMonthTemplate, draggable: true, prop: 'birthMonth', name: 'Birth Month', resizeable: true, sortable: false // using sort menu }, { cellTemplate: this.weekDayTemplate, draggable: true, prop: 'weekDay', name: 'Week Day', resizeable: true, sortable: false // using sort menu }]; this.allRows = [{ name: 'Fred Flintstone', address: '20 Dinosaur Way, Bedrock, Washingstone', birthMonth: 'February', birthMonthId: 'month2', weekDay: 'Sunday', weekdayId: 'day1' }, { name: 'John Smith', address: '415 East Main Street, Norfolk, Virginia', birthMonth: 'October', birthMonthId: '10', // selected: true, weekDay: 'Monday', weekdayId: 'day2' }, { name: 'Frank Livingston', address: '234 Elm Street, Pittsburgh, Pennsylvania', birthMonth: 'March', birthMonthId: 'month3', weekDay: 'Tuesday', weekdayId: 'day3' }, { name: 'Judy Green', address: '2 Apple Boulevard, Cincinatti, Ohio', birthMonth: 'December', birthMonthId: 'month12', weekDay: 'Wednesday', weekdayId: 'day4' }, { name: 'Pat Thomas', address: '50 Second Street, New York, New York', birthMonth: 'February', birthMonthId: 'month2', weekDay: 'Thursday', weekdayId: 'day5' }]; this.filteredRows = this.allRows; this.paginationConfig = { pageNumber: 1, pageSize: 3, pageSizeIncrements: [2, 3, 4], totalItems: this.filteredRows.length } as PaginationConfig; // Need to initialize for results/total counts // this.updateRows(false); this.filterConfig = { fields: [{ id: 'name', title: 'Name', placeholder: 'Filter by Name...', type: FilterType.TEXT }, { id: 'address', title: 'Address', placeholder: 'Filter by Address...', type: FilterType.TEXT }, { id: 'birthMonth', title: 'Birth Month', placeholder: 'Filter by Birth Month...', type: FilterType.SELECT, queries: [{ id: 'month1', value: 'January' }, { id: 'month2', value: 'February' }, { id: 'month3', value: 'March' }, { id: 'month4', value: 'April' }, { id: 'month5', value: 'May' }, { id: 'month6', value: 'June' }, { id: 'month7', value: 'July' }, { id: 'month8', value: 'August' }, { id: 'month9', value: 'September' }, { id: 'month10', value: 'October' }, { id: 'month11', value: 'November' }, { id: 'month12', value: 'December' }] }, { id: 'weekDay', title: 'Week Day', placeholder: 'Filter by Week Day...', type: FilterType.SELECT, queries: [{ id: 'day1', value: 'Sunday' }, { id: 'day2', value: 'Monday' }, { id: 'day3', value: 'Tuesday' }, { id: 'day4', value: 'Wednesday' }, { id: 'day5', value: 'Thursday' }, { id: 'day6', value: 'Friday' }, { id: 'day7', value: 'Saturday' }] }] as FilterField[], appliedFilters: [], resultsCount: 0, // this.rows.length, totalCount: 0, // this.allRows.length } as FilterConfig; this.sortConfig = { fields: [{ id: 'name', title: 'Name', sortType: 'alpha' }, { id: 'address', title: 'Address', sortType: 'alpha' }, { id: 'birthMonth', title: 'Birth Month', sortType: 'alpha' }, { id: 'weekDay', title: 'Week Day', sortType: 'alpha' }], isAscending: this.isAscendingSort } as SortConfig; this.actionConfig = { primaryActions: [{ id: 'action1', title: 'Action 1', tooltip: 'Do the first thing' }, { id: 'action2', title: 'Action 2', tooltip: 'Do something else' }], moreActions: [{ id: 'moreActions1', title: 'Action', tooltip: 'Perform an action' }, { id: 'moreActions2', title: 'Another Action', tooltip: 'Do something else' }, { disabled: true, id: 'moreActions3', title: 'Disabled Action', tooltip: 'Unavailable action', }, { id: 'moreActions4', title: 'Something Else', tooltip: 'Do something special' }, { id: 'moreActions5', title: '', separator: true }, { id: 'moreActions6', title: 'Grouped Action 1', tooltip: 'Do something' }, { id: 'moreActions7', title: 'Grouped Action 2', tooltip: 'Do something similar' }] } as ActionConfig; this.emptyStateConfig = { actions: { primaryActions: [{ id: 'action1', title: 'Main Action', tooltip: 'Start the server' }], moreActions: [{ id: 'action2', title: 'Secondary Action 1', tooltip: 'Do the first thing' }, { id: 'action3', title: 'Secondary Action 2', tooltip: 'Do something else' }, { id: 'action4', title: 'Secondary Action 3', tooltip: 'Do something special' }] } as ActionConfig, iconStyleClass: 'pficon-warning-triangle-o', title: 'No Items Available', info: 'This is the Empty State component. The goal of a empty state pattern is to provide a good first ' + 'impression that helps users to achieve their goals. It should be used when a list is empty because no ' + 'objects exists and you want to guide the user to perform specific actions.', helpLink: { hypertext: 'Table example', text: 'For more information please see the', url: '#/table' } } as EmptyStateConfig; this.toolbarConfig = { actionConfig: this.actionConfig, filterConfig: this.filterConfig, sortConfig: this.sortConfig } as ToolbarConfig; this.tableConfig = { emptyStateConfig: this.emptyStateConfig, paginationConfig: this.paginationConfig, showCheckbox: true, toolbarConfig: this.toolbarConfig, useExpandRows: true } as TableConfig; } // Actions doAdd(): void { this.actionsText = 'Add Action\n' + this.actionsText; } handleAction(action: Action): void { this.actionsText = action.title + '\n' + this.actionsText; } optionSelected(option: number): void { this.actionsText = 'Option ' + option + ' selected\n' + this.actionsText; } // Filter applyFilters(filters: Filter[]): void { this.filteredRows = []; if (filters && filters.length > 0) { this.allRows.forEach((item) => { if (this.matchesFilters(item, filters)) { this.filteredRows.push(item); } }); } else { this.filteredRows = this.allRows; } this.toolbarConfig.filterConfig.resultsCount = this.filteredRows.length; this.updateRows(true); } // Handle filter changes filterChanged($event: FilterEvent): void { this.filtersText = ''; $event.appliedFilters.forEach((filter) => { this.filtersText += filter.field.title + ' : ' + filter.value + '\n'; }); this.applyFilters($event.appliedFilters); } matchesFilter(item: any, filter: Filter): boolean { let match = true; let re = new RegExp(filter.value, 'i'); if (filter.field.id === 'name') { match = item.name.match(re) !== null; } else if (filter.field.id === 'address') { match = item.address.match(re) !== null; } else if (filter.field.id === 'birthMonth') { match = item.birthMonth === filter.value; } else if (filter.field.id === 'weekDay') { match = item.weekDay === filter.value; } return match; } matchesFilters(item: any, filters: Filter[]): boolean { let matches = true; filters.forEach((filter) => { if (!this.matchesFilter(item, filter)) { matches = false; return matches; } }); return matches; } // Drag and drop handleDrop($event: any[]): void { // Save new row order let startIndex = (this.paginationConfig.pageNumber - 1) * this.paginationConfig.pageSize; let endIndex = startIndex + this.paginationConfig.pageSize; for (let i = startIndex; i < endIndex; i++) { this.allRows[i] = $event[i]; } this.actionsText = 'Row dropped' + '\n' + this.actionsText; } // ngx-datatable handleOnActivate($event: any): void { // To much noise // this.actionsText = 'Cell or row focused' + '\n' + this.actionsText; } handleOnReorder($event: any): void { this.actionsText = 'Columns reordered' + '\n' + this.actionsText; } handleOnResize($event: any): void { this.actionsText = 'Columns resized' + '\n' + this.actionsText; } handleOnScroll($event: any): void { this.actionsText = 'Body scrolled' + '\n' + this.actionsText; } // Pagination handlePageSize($event: PaginationEvent): void { this.actionsText = 'Page Size: ' + $event.pageSize + ' Selected' + '\n' + this.actionsText; this.updateRows(false); } handlePageNumber($event: PaginationEvent): void { this.actionsText = 'Page Number: ' + $event.pageNumber + ' Selected' + '\n' + this.actionsText; this.updateRows(false); } updateRows(reset: boolean): void { if (reset) { this.paginationConfig.pageNumber = 1; } this.paginationConfig.totalItems = this.filteredRows.length; this.rows = this.filteredRows.slice((this.paginationConfig.pageNumber - 1) * this.paginationConfig.pageSize, this.paginationConfig.totalItems).slice(0, this.paginationConfig.pageSize); } // Sort compare(item1: any, item2: any): number { let compValue = 0; if (this.currentSortField.id === 'name') { compValue = item1.name.localeCompare(item2.name); } else if (this.currentSortField.id === 'address') { compValue = item1.address.localeCompare(item2.address); } else if (this.currentSortField.id === 'birthMonth') { compValue = this.monthVals[item1.birthMonth] - this.monthVals[item2.birthMonth]; } else if (this.currentSortField.id === 'weekDay') { compValue = this.weekDayVals[item1.weekDay] - this.weekDayVals[item2.weekDay]; } if (!this.isAscendingSort) { compValue = compValue * -1; } return compValue; } // Handle sort changes handleSortChanged($event: SortEvent): void { this.currentSortField = $event.field; this.isAscendingSort = $event.isAscending; this.allRows.sort((item1: any, item2: any) => this.compare(item1, item2)); this.applyFilters(this.filterConfig.appliedFilters || []); } // Selection handleSelectionChange($event: TableEvent): void { this.actionsText = $event.selectedRows.length + ' rows selected\r\n' + this.actionsText; } updateItemsAvailable(): void { if (this.rowsAvailable) { this.toolbarConfig.filterConfig.totalCount = this.allRows.length; this.filteredRows = this.allRows; this.updateRows(false); } else { // Clear previously applied properties to simulate no rows available this.toolbarConfig.filterConfig.totalCount = 0; this.filterConfig.appliedFilters = []; this.rows = []; } } }
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type QueryRenderersBidFlowQueryVariables = { artworkID: string; saleID: string; }; export type QueryRenderersBidFlowQueryResponse = { readonly artwork: { readonly sale_artwork: { readonly " $fragmentRefs": FragmentRefs<"BidFlow_sale_artwork">; } | null; } | null; readonly me: { readonly " $fragmentRefs": FragmentRefs<"BidFlow_me">; } | null; }; export type QueryRenderersBidFlowQuery = { readonly response: QueryRenderersBidFlowQueryResponse; readonly variables: QueryRenderersBidFlowQueryVariables; }; /* query QueryRenderersBidFlowQuery( $artworkID: String! $saleID: String! ) { artwork(id: $artworkID) { sale_artwork: saleArtwork(saleID: $saleID) { ...BidFlow_sale_artwork id } id } me { ...BidFlow_me id } } fragment BidFlow_sale_artwork on SaleArtwork { ...SelectMaxBid_sale_artwork } fragment BidFlow_me on Me { ...SelectMaxBid_me } fragment SelectMaxBid_me on Me { ...ConfirmBid_me } fragment ConfirmBid_me on Me { has_qualified_credit_cards: hasQualifiedCreditCards bidders(saleID: $saleID) { id } } fragment SelectMaxBid_sale_artwork on SaleArtwork { id increments(useMyMaxBid: true) { display cents } ...ConfirmBid_sale_artwork } fragment ConfirmBid_sale_artwork on SaleArtwork { id internalID sale { slug live_start_at: liveStartAt end_at: endAt isBenefit partner { name id } id } artwork { slug title date artist_names: artistNames image { url(version: "small") } id } lot_label: lotLabel ...BidResult_sale_artwork } fragment BidResult_sale_artwork on SaleArtwork { sale { liveStartAt endAt slug id } } */ const node: ConcreteRequest = (function(){ var v0 = [ { "kind": "LocalArgument", "name": "artworkID", "type": "String!", "defaultValue": null }, { "kind": "LocalArgument", "name": "saleID", "type": "String!", "defaultValue": null } ], v1 = [ { "kind": "Variable", "name": "id", "variableName": "artworkID" } ], v2 = [ { "kind": "Variable", "name": "saleID", "variableName": "saleID" } ], v3 = { "kind": "ScalarField", "alias": null, "name": "id", "args": null, "storageKey": null }, v4 = { "kind": "ScalarField", "alias": null, "name": "slug", "args": null, "storageKey": null }; return { "kind": "Request", "fragment": { "kind": "Fragment", "name": "QueryRenderersBidFlowQuery", "type": "Query", "metadata": null, "argumentDefinitions": (v0/*: any*/), "selections": [ { "kind": "LinkedField", "alias": null, "name": "artwork", "storageKey": null, "args": (v1/*: any*/), "concreteType": "Artwork", "plural": false, "selections": [ { "kind": "LinkedField", "alias": "sale_artwork", "name": "saleArtwork", "storageKey": null, "args": (v2/*: any*/), "concreteType": "SaleArtwork", "plural": false, "selections": [ { "kind": "FragmentSpread", "name": "BidFlow_sale_artwork", "args": null } ] } ] }, { "kind": "LinkedField", "alias": null, "name": "me", "storageKey": null, "args": null, "concreteType": "Me", "plural": false, "selections": [ { "kind": "FragmentSpread", "name": "BidFlow_me", "args": null } ] } ] }, "operation": { "kind": "Operation", "name": "QueryRenderersBidFlowQuery", "argumentDefinitions": (v0/*: any*/), "selections": [ { "kind": "LinkedField", "alias": null, "name": "artwork", "storageKey": null, "args": (v1/*: any*/), "concreteType": "Artwork", "plural": false, "selections": [ { "kind": "LinkedField", "alias": "sale_artwork", "name": "saleArtwork", "storageKey": null, "args": (v2/*: any*/), "concreteType": "SaleArtwork", "plural": false, "selections": [ (v3/*: any*/), { "kind": "LinkedField", "alias": null, "name": "increments", "storageKey": "increments(useMyMaxBid:true)", "args": [ { "kind": "Literal", "name": "useMyMaxBid", "value": true } ], "concreteType": "BidIncrementsFormatted", "plural": true, "selections": [ { "kind": "ScalarField", "alias": null, "name": "display", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "cents", "args": null, "storageKey": null } ] }, { "kind": "ScalarField", "alias": null, "name": "internalID", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "sale", "storageKey": null, "args": null, "concreteType": "Sale", "plural": false, "selections": [ (v4/*: any*/), { "kind": "ScalarField", "alias": "live_start_at", "name": "liveStartAt", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "end_at", "name": "endAt", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "isBenefit", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "partner", "storageKey": null, "args": null, "concreteType": "Partner", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "name", "args": null, "storageKey": null }, (v3/*: any*/) ] }, (v3/*: any*/), { "kind": "ScalarField", "alias": null, "name": "liveStartAt", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "endAt", "args": null, "storageKey": null } ] }, { "kind": "LinkedField", "alias": null, "name": "artwork", "storageKey": null, "args": null, "concreteType": "Artwork", "plural": false, "selections": [ (v4/*: any*/), { "kind": "ScalarField", "alias": null, "name": "title", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": null, "name": "date", "args": null, "storageKey": null }, { "kind": "ScalarField", "alias": "artist_names", "name": "artistNames", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "image", "storageKey": null, "args": null, "concreteType": "Image", "plural": false, "selections": [ { "kind": "ScalarField", "alias": null, "name": "url", "args": [ { "kind": "Literal", "name": "version", "value": "small" } ], "storageKey": "url(version:\"small\")" } ] }, (v3/*: any*/) ] }, { "kind": "ScalarField", "alias": "lot_label", "name": "lotLabel", "args": null, "storageKey": null } ] }, (v3/*: any*/) ] }, { "kind": "LinkedField", "alias": null, "name": "me", "storageKey": null, "args": null, "concreteType": "Me", "plural": false, "selections": [ { "kind": "ScalarField", "alias": "has_qualified_credit_cards", "name": "hasQualifiedCreditCards", "args": null, "storageKey": null }, { "kind": "LinkedField", "alias": null, "name": "bidders", "storageKey": null, "args": (v2/*: any*/), "concreteType": "Bidder", "plural": true, "selections": [ (v3/*: any*/) ] }, (v3/*: any*/) ] } ] }, "params": { "operationKind": "query", "name": "QueryRenderersBidFlowQuery", "id": "eb8986e2daea7ba7b84e51c49110a48c", "text": null, "metadata": {} } }; })(); (node as any).hash = '3ec3ffc863425fc2bd60a4aed520770d'; export default node;
the_stack
import { right } from "string-left-right"; import { version as v } from "../package.json"; const version: string = v; function isObj(something: any): boolean { return ( something && typeof something === "object" && !Array.isArray(something) ); } function isStr(something: any): boolean { return typeof something === "string"; } interface Opts { stringOffset?: number; maxDistance?: number; ignoreWhitespace?: boolean; } const defaults: Opts = { stringOffset: 0, maxDistance: 1, ignoreWhitespace: true, }; interface DataObj { idxFrom: number; idxTo: number; } function findMalformed( str: string, refStr: string, cb: (obj: DataObj) => void, originalOpts?: Opts | undefined | null ): void { console.log(`036 strFindMalformed() START:`); console.log( `* ${`\u001b[${33}m${`str`}\u001b[${39}m`} = ${JSON.stringify( str, null, 4 )}` ); console.log( `* ${`\u001b[${33}m${`refStr`}\u001b[${39}m`} = ${JSON.stringify( refStr, null, 4 )}` ); // // insurance // --------- if (!isStr(str)) { throw new TypeError( `string-find-malformed: [THROW_ID_01] the first input argument, string where to look for, must be a string! Currently it's equal to: ${str} (type: ${typeof str})` ); } else if (!str.length) { // empty string - quick ending console.log(`061 QUICK ENDING - 1st arg, "str" was empty`); return; } if (!isStr(refStr)) { throw new TypeError( `string-find-malformed: [THROW_ID_02] the second input argument, string we should find, must be a string! Currently it's equal to: ${refStr} (type: ${typeof refStr})` ); } else if (!refStr.length) { // empty string to look for - quick ending console.log(`070 QUICK ENDING - 2nd arg, "refStr" was empty`); return; } if (typeof cb !== "function") { throw new TypeError( `string-find-malformed: [THROW_ID_03] the third input argument, a callback function, must be a function! Currently it's equal to: ${cb} (type: ${typeof cb})` ); } if (originalOpts && !isObj(originalOpts)) { throw new TypeError( `string-find-malformed: [THROW_ID_04] the fourth input argument, an Optional Options Object, must be a plain object! Currently it's equal to: ${originalOpts} (type: ${typeof originalOpts})` ); } const opts = { ...defaults, ...originalOpts }; // we perform the validation upon Object-assigned "opts" instead // of incoming "originalOpts" because we don't want to mutate the // "originalOpts" and making note of fixed values, Object-assigning // "opts" and then putting those noted fixed values on top is more // tedious than letting Object-assign to do the job, then validating // it, then trying to salvage the value (if possible). if ( typeof opts.stringOffset === "string" && /^\d*$/.test(opts.stringOffset) ) { opts.stringOffset = Number(opts.stringOffset); } else if ( !Number.isInteger(opts.stringOffset) || (opts.stringOffset as number) < 0 ) { throw new TypeError( `[THROW_ID_05] opts.stringOffset must be a natural number or zero! Currently it's: ${opts.stringOffset}` ); } console.log( `107 FINAL ${`\u001b[${33}m${`opts`}\u001b[${39}m`} = ${JSON.stringify( opts, null, 4 )}` ); // // action // ------ const len = str.length; // "current" character (str[i]) is matched against first character // of "refStr", then, if opts.maxDistance allows and refStr has // enough length, current character (str[i]) is matched against the // second character of "refStr" - this time, "patience" is subtracted // by amount of skipped characters, in this case, by 1... and so on... // That matching chain is a "for" loop and that loop's length is below: const len2 = Math.min(refStr.length, (opts.maxDistance || 0) + 1); interface MatchesObj { startsAt: number; patienceLeft: number; pendingToCheck: string[]; } let pendingMatchesArr: MatchesObj[] = []; // when it attempts to dip below zero, match is failed const patience: number = opts.maxDistance || 1; let wasThisLetterMatched; for (let i = 0; i < len; i++) { // // // // // THE TOP // ███████ // // // // // Logging: // ------------------------------------------------------------------------- console.log( `\u001b[${36}m${`================================`}\u001b[${39}m \u001b[${35}m${`str[ ${i} ] = ${ str[i] && str[i].trim() ? str[i] : JSON.stringify(str[i], null, 4) }`}\u001b[${39}m \u001b[${36}m${`================================`}\u001b[${39}m\n` ); if (opts.ignoreWhitespace && !str[i].trim()) { console.log(`162 ${`\u001b[${32}m${`SKIP`}\u001b[${39}m`}`); continue; } // // // // // THE MIDDLE // ██████████ // // // // console.log( `178 ${`\u001b[${34}m${`I. tend the existing entries in pendingMatchesArr[]`}\u001b[${39}m`}` ); for (let z = 0, len3 = pendingMatchesArr.length; z < len3; z++) { console.log(" "); console.log(`-----------------------------------`); console.log(" "); console.log( `185 ${`\u001b[${33}m${`██`}\u001b[${39}m`} ${`\u001b[${33}m${`obj`}\u001b[${39}m`} = ${JSON.stringify( pendingMatchesArr[z], null, 4 )}` ); wasThisLetterMatched = false; if ( Array.isArray(pendingMatchesArr[z].pendingToCheck) && pendingMatchesArr[z].pendingToCheck.length && str[i] === pendingMatchesArr[z].pendingToCheck[0] ) { console.log(`198 CASE I. Happy path - matched.`); wasThisLetterMatched = true; console.log( `201 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} wasThisLetterMatched = ${wasThisLetterMatched}` ); // if matched, shift() it pendingMatchesArr[z].pendingToCheck.shift(); console.log( `207 ${`\u001b[${32}m${`SHIFT`}\u001b[${39}m`} pendingMatchesArr[z].pendingToCheck now = ${JSON.stringify( pendingMatchesArr[z].pendingToCheck, null, 4 )}` ); } else if ( Array.isArray(pendingMatchesArr[z].pendingToCheck) && pendingMatchesArr[z].pendingToCheck.length && str[i] === pendingMatchesArr[z].pendingToCheck[1] ) { console.log(`218 CASE II. Next-one matched instead.`); wasThisLetterMatched = true; console.log( `221 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} wasThisLetterMatched = ${wasThisLetterMatched}` ); // if matched, shift() it pendingMatchesArr[z].pendingToCheck.shift(); pendingMatchesArr[z].pendingToCheck.shift(); console.log( `228 ${`\u001b[${32}m${`SHIFT`}\u001b[${39}m`} pendingMatchesArr[z].pendingToCheck now = ${JSON.stringify( pendingMatchesArr[z].pendingToCheck, null, 4 )}` ); pendingMatchesArr[z].patienceLeft -= 1; console.log( `237 ${`\u001b[${31}m${`DECREASE PATIENCE`}\u001b[${39}m`} ${`\u001b[${33}m${`patienceLeft`}\u001b[${39}m`} = ${ pendingMatchesArr[z].patienceLeft }` ); // } else { pendingMatchesArr[z].patienceLeft -= 1; console.log( `245 ${`\u001b[${31}m${`DECREASE PATIENCE`}\u001b[${39}m`} ${`\u001b[${33}m${`patienceLeft`}\u001b[${39}m`} = ${ pendingMatchesArr[z].patienceLeft }` ); // we look up the next character, if it matches, we don't pop it if ( str[right(str, i) as number] !== pendingMatchesArr[z].pendingToCheck[0] ) { console.log( `256 ██ str[${right(str, i)}] = "${ str[right(str, i) as number] }" DIDN'T MATCH pendingMatchesArr[${z}].pendingToCheck[0] = "${ pendingMatchesArr[z].pendingToCheck[0] }"` ); pendingMatchesArr[z].pendingToCheck.shift(); console.log( `264 ${`\u001b[${31}m${`SHIFT`}\u001b[${39}m`} pendingMatchesArr[z].pendingToCheck now: ${JSON.stringify( pendingMatchesArr[z].pendingToCheck, null, 4 )}` ); // after popping, match the current character at str[i] is it // equal to the first element of recently-shifted // pendingMatchesArr[z].pendingToCheck: console.log( `275 ${`\u001b[${32}m${`CHECK`}\u001b[${39}m`}, does str[${i}]=${ str[i] } === pendingMatchesArr[${z}].pendingToCheck[0]=${ pendingMatchesArr[z].pendingToCheck[0] }` ); if (str[i] === pendingMatchesArr[z].pendingToCheck[0]) { pendingMatchesArr[z].pendingToCheck.shift(); console.log( `284 pendingMatchesArr[z].pendingToCheck now: ${JSON.stringify( pendingMatchesArr[z].pendingToCheck, null, 4 )}` ); } } } } console.log(" "); console.log(`-----------------------------------`); pendingMatchesArr = pendingMatchesArr.filter( (obj) => obj.patienceLeft >= 0 ); // out of all objects which deplete pendingToCheck[] to zero length, // we pick the one with the smallest "startsAt" value - that's filtering // the overlapping values const tempArr = pendingMatchesArr .filter((obj) => obj.pendingToCheck.length === 0) .map((obj) => obj.startsAt); if (Array.isArray(tempArr) && tempArr.length) { console.log( `310 ${`\u001b[${33}m${`tempArr`}\u001b[${39}m`} = ${JSON.stringify( tempArr, null, 4 )}` ); console.log( `317 ${`\u001b[${32}m${`PING CB`}\u001b[${39}m`} with ${JSON.stringify( { idxFrom: Math.min(...tempArr) + (opts.stringOffset || 0), idxTo: i + (wasThisLetterMatched ? 1 : 0) + (opts.stringOffset || 0), }, null, 4 )}` ); const idxFrom = Math.min(...tempArr); const idxTo = i + (wasThisLetterMatched ? 1 : 0); if (str.slice(idxFrom, idxTo) !== refStr) { // only ping malformed values, don't ping those exactly matching "refStr" cb({ idxFrom: idxFrom + (opts.stringOffset || 0), idxTo: idxTo + (opts.stringOffset || 0), }); } // remove pendingMatchesArr[] entries with no characters to check pendingMatchesArr = pendingMatchesArr.filter( (obj) => obj.pendingToCheck.length ); } console.log( `344 ${`\u001b[${34}m${`II. check the current character, maybe it matches something new`}\u001b[${39}m`}` ); for (let y = 0; y < len2; y++) { console.log( `348 ${`\u001b[${36}m${`=== matching index: ${y}, that's characters str[${i}]="${str[i]}" vs. refStr[${y}]="${refStr[y]}" ===`}\u001b[${39}m`}` ); if (str[i] === refStr[y]) { const whatToPush = { startsAt: i, patienceLeft: (patience as number) - y, pendingToCheck: Array.from(refStr.slice(y + 1)), }; console.log( `358 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${JSON.stringify( whatToPush, null, 4 )}; break` ); pendingMatchesArr.push(whatToPush); break; } } // // // // // THE BOTTOM // ██████████ // // // // // Logging console.log( `${`\u001b[${90}m${`██ pendingMatchesArr = ${JSON.stringify( pendingMatchesArr, null, 4 )}`}\u001b[${39}m`}` ); } } export { findMalformed, defaults, version };
the_stack
import * as moment from "moment"; /** * Response base */ export interface ResponseBase { /** * Polymorphic Discriminator */ _type: string; } /** * Defines the identity of a resource. */ export interface Identifiable extends ResponseBase { /** * A String identifier. */ readonly id?: string; } /** * Defines a response. All schemas that could be returned at the root of a response should inherit * from this */ export interface Response extends Identifiable { /** * The URL that returns this resource. */ readonly readLink?: string; /** * The URL To Bing's search result for this item. */ readonly webSearchUrl?: string; } /** * Defines a thing. */ export interface Thing extends Response { /** * The name of the thing represented by this object. */ readonly name?: string; /** * The URL to get more information about the thing represented by this object. */ readonly url?: string; /** * An image of the item. */ readonly image?: ImageObject; /** * A short description of the item. */ readonly description?: string; /** * An alias for the item */ readonly alternateName?: string; /** * An ID that uniquely identifies this item. */ readonly bingId?: string; } /** * Defines an organization. */ export interface Organization extends Thing { } /** * Defines an item. */ export interface PropertiesItem { /** * Text representation of an item. */ readonly text?: string; /** * Polymorphic Discriminator */ _type: string; } /** * Defines a rating. */ export interface Rating extends PropertiesItem { /** * The mean (average) rating. The possible values are 1.0 through 5.0. */ ratingValue: number; /** * The highest rated review. The possible values are 1.0 through 5.0. */ readonly bestRating?: number; } /** * Defines the metrics that indicate how well an item was rated by others. */ export interface AggregateRating extends Rating { /** * The number of times the recipe has been rated or reviewed. */ readonly reviewCount?: number; } /** * Defines a merchant's offer. */ export interface Offer extends Thing { /** * Seller for this offer */ readonly seller?: Organization; /** * The item's price. */ readonly price?: number; /** * The monetary currency. For example, USD. Possible values include: 'USD', 'CAD', 'GBP', 'EUR', * 'COP', 'JPY', 'CNY', 'AUD', 'INR', 'AED', 'AFN', 'ALL', 'AMD', 'ANG', 'AOA', 'ARS', 'AWG', * 'AZN', 'BAM', 'BBD', 'BDT', 'BGN', 'BHD', 'BIF', 'BMD', 'BND', 'BOB', 'BOV', 'BRL', 'BSD', * 'BTN', 'BWP', 'BYR', 'BZD', 'CDF', 'CHE', 'CHF', 'CHW', 'CLF', 'CLP', 'COU', 'CRC', 'CUC', * 'CUP', 'CVE', 'CZK', 'DJF', 'DKK', 'DOP', 'DZD', 'EGP', 'ERN', 'ETB', 'FJD', 'FKP', 'GEL', * 'GHS', 'GIP', 'GMD', 'GNF', 'GTQ', 'GYD', 'HKD', 'HNL', 'HRK', 'HTG', 'HUF', 'IDR', 'ILS', * 'IQD', 'IRR', 'ISK', 'JMD', 'JOD', 'KES', 'KGS', 'KHR', 'KMF', 'KPW', 'KRW', 'KWD', 'KYD', * 'KZT', 'LAK', 'LBP', 'LKR', 'LRD', 'LSL', 'LYD', 'MAD', 'MDL', 'MGA', 'MKD', 'MMK', 'MNT', * 'MOP', 'MRO', 'MUR', 'MVR', 'MWK', 'MXN', 'MXV', 'MYR', 'MZN', 'NAD', 'NGN', 'NIO', 'NOK', * 'NPR', 'NZD', 'OMR', 'PAB', 'PEN', 'PGK', 'PHP', 'PKR', 'PLN', 'PYG', 'QAR', 'RON', 'RSD', * 'RUB', 'RWF', 'SAR', 'SBD', 'SCR', 'SDG', 'SEK', 'SGD', 'SHP', 'SLL', 'SOS', 'SRD', 'SSP', * 'STD', 'SYP', 'SZL', 'THB', 'TJS', 'TMT', 'TND', 'TOP', 'TRY', 'TTD', 'TWD', 'TZS', 'UAH', * 'UGX', 'UYU', 'UZS', 'VEF', 'VND', 'VUV', 'WST', 'XAF', 'XCD', 'XOF', 'XPF', 'YER', 'ZAR', * 'ZMW' */ readonly priceCurrency?: string; /** * The item's availability. The following are the possible values: Discontinued, InStock, * InStoreOnly, LimitedAvailability, OnlineOnly, OutOfStock, PreOrder, SoldOut. Possible values * include: 'Discontinued', 'InStock', 'InStoreOnly', 'LimitedAvailability', 'OnlineOnly', * 'OutOfStock', 'PreOrder', 'SoldOut' */ readonly availability?: string; /** * An aggregated rating that indicates how well the product has been rated by others. */ readonly aggregateRating?: AggregateRating; /** * The last date that the offer was updated. The date is in the form YYYY-MM-DD. */ readonly lastUpdated?: string; } /** * Defines a list of offers from merchants that are related to the image. */ export interface AggregateOffer extends Offer { /** * A list of offers from merchants that have offerings related to the image. */ readonly offers?: Offer[]; } /** * Defines a count of the number of websites where you can shop or perform other actions related to * the image. */ export interface ImagesImageMetadata { /** * The number of websites that offer goods of the products seen in the image. */ readonly shoppingSourcesCount?: number; /** * The number of websites that offer recipes of the food seen in the image. */ readonly recipeSourcesCount?: number; /** * A summary of the online offers of products found in the image. For example, if the image is of * a dress, the offer might identify the lowest price and the number of offers found. Only * visually similar products insights include this field. The offer includes the following * fields: Name, AggregateRating, OfferCount, and LowPrice. */ readonly aggregateOffer?: AggregateOffer; } /** * The most generic kind of creative work, including books, movies, photographs, software programs, * etc. */ export interface CreativeWork extends Thing { /** * The URL to a thumbnail of the item. */ readonly thumbnailUrl?: string; /** * The source of the creative work. */ readonly provider?: Thing[]; /** * The date on which the CreativeWork was published. */ readonly datePublished?: string; /** * Text content of this creative work */ readonly text?: string; } /** * Defines a media object. */ export interface MediaObject extends CreativeWork { /** * Original URL to retrieve the source (file) for the media object (e.g the source URL for the * image). */ readonly contentUrl?: string; /** * URL of the page that hosts the media object. */ readonly hostPageUrl?: string; /** * Size of the media object content (use format "value unit" e.g "1024 B"). */ readonly contentSize?: string; /** * Encoding format (e.g mp3, mp4, jpeg, etc). */ readonly encodingFormat?: string; /** * Display URL of the page that hosts the media object. */ readonly hostPageDisplayUrl?: string; /** * The width of the source media object, in pixels. */ readonly width?: number; /** * The height of the source media object, in pixels. */ readonly height?: number; } /** * Defines an image */ export interface ImageObject extends MediaObject { /** * The URL to a thumbnail of the image */ readonly thumbnail?: ImageObject; /** * The token that you use in a subsequent call to the Image Search API to get additional * information about the image. For information about using this token, see the insightsToken * query parameter. */ readonly imageInsightsToken?: string; /** * A count of the number of websites where you can shop or perform other actions related to the * image. For example, if the image is of an apple pie, this object includes a count of the * number of websites where you can buy an apple pie. To indicate the number of offers in your * UX, include badging such as a shopping cart icon that contains the count. When the user clicks * on the icon, use imageInsightsToken to get the list of websites. */ readonly insightsMetadata?: ImagesImageMetadata; /** * Unique Id for the image */ readonly imageId?: string; /** * A three-byte hexadecimal number that represents the color that dominates the image. Use the * color as the temporary background in your client until the image is loaded. */ readonly accentColor?: string; /** * Visual representation of the image. Used for getting more sizes */ readonly visualWords?: string; } /** * Defines a search query. */ export interface Query { /** * The query string. Use this string as the query term in a new search request. */ text: string; /** * The display version of the query term. This version of the query term may contain special * characters that highlight the search term found in the query string. The string contains the * highlighting characters only if the query enabled hit highlighting */ readonly displayText?: string; /** * The URL that takes the user to the Bing search results page for the query.Only related search * results include this field. */ readonly webSearchUrl?: string; /** * The URL that you use to get the results of the related search. Before using the URL, you must * append query parameters as appropriate and include the Ocp-Apim-Subscription-Key header. Use * this URL if you're displaying the results in your own user interface. Otherwise, use the * webSearchUrl URL. */ readonly searchLink?: string; /** * The URL to a thumbnail of a related image. */ readonly thumbnail?: ImageObject; } /** * Defines the pivot segment. */ export interface PivotSuggestions { /** * The segment from the original query to pivot on. */ pivot: string; /** * A list of suggested queries for the pivot. */ suggestions: Query[]; } /** * Defines an answer. */ export interface Answer extends Response { } /** * Defines a search result answer. */ export interface SearchResultsAnswer extends Answer { /** * The estimated number of webpages that are relevant to the query. Use this number along with * the count and offset query parameters to page the results. */ readonly totalEstimatedMatches?: number; } /** * Defines an image answer */ export interface Images extends SearchResultsAnswer { /** * Used as part of deduping. Tells client the next offset that client should use in the next * pagination request */ readonly nextOffset?: number; /** * A list of image objects that are relevant to the query. If there are no results, the List is * empty. */ value: ImageObject[]; /** * A list of expanded queries that narrows the original query. For example, if the query was * Microsoft Surface, the expanded queries might be: Microsoft Surface Pro 3, Microsoft Surface * RT, Microsoft Surface Phone, and Microsoft Surface Hub. */ readonly queryExpansions?: Query[]; /** * A list of segments in the original query. For example, if the query was Red Flowers, Bing * might segment the query into Red and Flowers. The Flowers pivot may contain query suggestions * such as Red Peonies and Red Daisies, and the Red pivot may contain query suggestions such as * Green Flowers and Yellow Flowers. */ readonly pivotSuggestions?: PivotSuggestions[]; /** * A list of terms that are similar in meaning to the user's query term. */ readonly similarTerms?: Query[]; } /** * Defines the error that occurred. */ export interface ErrorModel { /** * The error code that identifies the category of error. Possible values include: 'None', * 'ServerError', 'InvalidRequest', 'RateLimitExceeded', 'InvalidAuthorization', * 'InsufficientAuthorization' */ code: string; /** * The error code that further helps to identify the error. Possible values include: * 'UnexpectedError', 'ResourceError', 'NotImplemented', 'ParameterMissing', * 'ParameterInvalidValue', 'HttpNotAllowed', 'Blocked', 'AuthorizationMissing', * 'AuthorizationRedundancy', 'AuthorizationDisabled', 'AuthorizationExpired' */ readonly subCode?: string; /** * A description of the error. */ message: string; /** * A description that provides additional information about the error. */ readonly moreDetails?: string; /** * The parameter in the request that caused the error. */ readonly parameter?: string; /** * The parameter's value in the request that was not valid. */ readonly value?: string; } /** * The top-level response that represents a failed request. */ export interface ErrorResponse extends Response { /** * A list of errors that describe the reasons why the request failed. */ errors: ErrorModel[]; } /** * Defines an image's caption. */ export interface ImageInsightsImageCaption { /** * A caption about the image. */ caption: string; /** * The URL to the website where the caption was found. You must attribute the caption to the * source. For example, by displaying the domain name from the URL next to the caption and using * the URL to link to the source website. */ dataSourceUrl: string; /** * A list of entities found in the caption. Use the contents of the Query object to find the * entity in the caption and create a link. The link takes the user to images of the entity. */ relatedSearches: Query[]; } /** * Defines a webpage that is relevant to the query. */ export interface WebPage extends CreativeWork { } /** * Defines a link to a webpage that contains a collection. */ export interface CollectionPage extends WebPage { } /** * Defines a link to a webpage that contains a collection of related images. */ export interface ImageGallery extends CollectionPage { /** * The publisher or social network where the images were found. You must attribute the publisher * as the source where the collection was found. */ readonly source?: string; /** * The number of related images found in the collection. */ readonly imagesCount?: number; /** * The number of users on the social network that follow the creator. */ readonly followersCount?: number; } /** * Defines a list of webpages that contain related images. */ export interface RelatedCollectionsModule { /** * A list of webpages that contain related images. */ readonly value?: ImageGallery[]; } /** * Defines a list of images. */ export interface ImagesModule { /** * A list of images. */ readonly value?: ImageObject[]; } /** * Defines a list of related searches. */ export interface RelatedSearchesModule { /** * A list of related searches. */ readonly value?: Query[]; } /** * Defines a cooking recipe. */ export interface Recipe extends CreativeWork { /** * The amount of time the food takes to cook. For example, PT25M. For information about the time * format, see http://en.wikipedia.org/wiki/ISO_8601#Durations. */ readonly cookTime?: string; /** * The amount of time required to prepare the ingredients. For example, PT15M. For information * about the time format, see http://en.wikipedia.org/wiki/ISO_8601#Durations. */ readonly prepTime?: string; /** * The total amount of time it takes to prepare and cook the recipe. For example, PT45M. For * information about the time format, see http://en.wikipedia.org/wiki/ISO_8601#Durations. */ readonly totalTime?: string; } /** * Defines a list of recipes. */ export interface RecipesModule { /** * A list of recipes. */ readonly value?: Recipe[]; } /** * A utility class that serves as the umbrella for a number of 'intangible' things such as * quantities, structured values, etc. */ export interface Intangible extends Thing { } export interface StructuredValue extends Intangible { } /** * Defines a region of an image. The region is defined by the coordinates of the top, left corner * and bottom, right corner of the region. The coordinates are fractional values of the original * image's width and height in the range 0.0 through 1.0. */ export interface NormalizedRectangle extends StructuredValue { /** * The left coordinate. */ left: number; /** * The top coordinate */ top: number; /** * The right coordinate */ right: number; /** * The bottom coordinate */ bottom: number; } /** * Defines a recognized entity. */ export interface RecognizedEntity extends Response { /** * The entity that was recognized. The following are the possible entity objects: Person */ readonly entity?: Thing; /** * The confidence that Bing has that the entity in the image matches this entity. The confidence * ranges from 0.0 through 1.0 with 1.0 being very confident. */ readonly matchConfidence?: number; } /** * Defines a region of the image where an entity was found and a list of entities that might match * it. */ export interface RecognizedEntityRegion extends Response { /** * A region of the image that contains an entity. The values of the rectangle are relative to the * width and height of the original image and are in the range 0.0 through 1.0. For example, if * the image is 300x200 and the region's top, left corner is at point (10, 20) and the bottom, * right corner is at point (290, 150), then the normalized rectangle is: Left = * 0.0333333333333333, Top = 0.1, Right = 0.9666666666666667, Bottom = 0.75. For people, the * region represents the person's face. */ readonly region?: NormalizedRectangle; /** * A list of entities that Bing believes match the entity found in the region. The entities are * in descending order of confidence (see the matchConfidence field of RecognizedEntity). */ readonly matchingEntities?: RecognizedEntity[]; } /** * Defines a group of previously recognized entities. */ export interface RecognizedEntityGroup { /** * The regions of the image that contain entities. */ recognizedEntityRegions: RecognizedEntityRegion[]; /** * The name of the group where images of the entity were also found. The following are possible * groups. CelebRecognitionAnnotations: Similar to CelebrityAnnotations but provides a higher * probability of an accurate match. CelebrityAnnotations: Contains celebrities such as actors, * politicians, athletes, and historical figures. */ name: string; } /** * Defines a list of previously recognized entities. */ export interface RecognizedEntitiesModule { /** * A list of recognized entities. */ readonly value?: RecognizedEntityGroup[]; } /** * Defines a characteristic of the content found in the image. */ export interface InsightsTag { /** * The name of the characteristic. For example, cat, kitty, calico cat. */ readonly name?: string; } /** * Defines the characteristics of content found in an image. */ export interface ImageTagsModule { /** * A list of tags that describe the characteristics of the content found in the image. For * example, if the image is of a musical artist, the list might include Female, Dress, and Music * to indicate the person is female music artist that's wearing a dress. */ value: InsightsTag[]; } /** * The top-level object that the response includes when an image insights request succeeds. For * information about requesting image insights, see the * [insightsToken](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#insightstoken) * query parameter. The modules query parameter affects the fields that Bing includes in the * response. If you set * [modules](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-images-api-v7-reference#modulesrequested) * to only Caption, then this object includes only the imageCaption field. */ export interface ImageInsights extends Response { /** * A token that you use in a subsequent call to the Image Search API to get more information * about the image. For information about using this token, see the insightsToken query * parameter. This token has the same usage as the token in the Image object. */ readonly imageInsightsToken?: string; /** * The query term that best represents the image. Clicking the link in the Query object, takes * the user to a webpage with more pictures of the image. */ readonly bestRepresentativeQuery?: Query; /** * The caption to use for the image. */ readonly imageCaption?: ImageInsightsImageCaption; /** * A list of links to webpages that contain related images. */ readonly relatedCollections?: RelatedCollectionsModule; /** * A list of webpages that contain the image. To access the webpage, use the URL in the image's * hostPageUrl field. */ readonly pagesIncluding?: ImagesModule; /** * A list of merchants that offer items related to the image. For example, if the image is of an * apple pie, the list contains merchants that are selling apple pies. */ readonly shoppingSources?: AggregateOffer; /** * A list of related queries made by others. */ readonly relatedSearches?: RelatedSearchesModule; /** * A list of recipes related to the image. For example, if the image is of an apple pie, the list * contains recipes for making an apple pie. */ readonly recipes?: RecipesModule; /** * A list of images that are visually similar to the original image. For example, if the * specified image is of a sunset over a body of water, the list of similar images are of a * sunset over a body of water. If the specified image is of a person, similar images might be of * the same person or they might be of persons dressed similarly or in a similar setting. The * criteria for similarity continues to evolve. */ readonly visuallySimilarImages?: ImagesModule; /** * A list of images that contain products that are visually similar to products found in the * original image. For example, if the specified image contains a dress, the list of similar * images contain a dress. The image provides summary information about offers that Bing found * online for the product. */ readonly visuallySimilarProducts?: ImagesModule; /** * A list of groups that contain images of entities that match the entity found in the specified * image. For example, the response might include images from the general celebrity group if the * entity was recognized in that group. */ readonly recognizedEntityGroups?: RecognizedEntitiesModule; /** * A list of characteristics of the content found in the image. For example, if the image is of a * person, the tags might indicate the person's gender and the type of clothes they're wearing. */ readonly imageTags?: ImageTagsModule; } /** * Defines an image tile. */ export interface TrendingImagesTile { /** * A query that returns a Bing search results page with more images of the subject. For example, * if the category is Popular People Searches, then the thumbnail is of a popular person. The * query would return a Bing search results page with more images of that person. */ query: Query; /** * The image's thumbnail. */ image: ImageObject; } /** * Defines the category of trending images. */ export interface TrendingImagesCategory { /** * The name of the image category. For example, Popular People Searches. */ title: string; /** * A list of images that are trending in the category. Each tile contains an image and a URL that * returns more images of the subject. For example, if the category is Popular People Searches, * the image is of a popular person and the URL would return more images of that person. */ tiles: TrendingImagesTile[]; } /** * The top-level object that the response includes when a trending images request succeeds. */ export interface TrendingImages extends Response { /** * A list that identifies categories of images and a list of trending images in that category. */ categories: TrendingImagesCategory[]; } /** * Defines a person. */ export interface Person extends Thing { /** * The person's job title. */ readonly jobTitle?: string; /** * The URL of the person's twitter profile. */ readonly twitterProfile?: string; }
the_stack
import { ClientBody } from '../model/clientBody'; import { PasswordResetBody } from '../model/passwordResetBody'; import { PersonBodyCreate } from '../model/personBodyCreate'; import { PersonBodyUpdate } from '../model/personBodyUpdate'; import { PersonEntry } from '../model/personEntry'; import { PersonPaging } from '../model/personPaging'; import { BaseApi } from './base.api'; import { throwIfNotDefined } from '../../../assert'; import { buildCollectionParam } from '../../../alfrescoApiClient'; /** * People service. * @module PeopleApi */ export class PeopleApi extends BaseApi { /** * Create person * * **Note:** this endpoint is available in Alfresco 5.2 and newer versions. Create a person. If applicable, the given person's login access can also be optionally disabled. You must have admin rights to create a person. You can set custom properties when you create a person: JSON { \"id\": \"abeecher\", \"firstName\": \"Alice\", \"lastName\": \"Beecher\", \"displayName\": \"Alice Beecher\", \"email\": \"abeecher@example.com\", \"password\": \"secret\", \"properties\": { \"my:property\": \"The value\" } } **Note:** setting properties of type d:content and d:category are not supported. * * @param personBodyCreate The person details. * @param opts Optional parameters * @param opts.fields A list of field names. You can use this parameter to restrict the fields returned within a response if, for example, you want to save on overall bandwidth. The list applies to a returned individual entity or entries within a collection. If the API method also supports the **include** parameter, then the fields specified in the **include** parameter are returned in addition to those specified in the **fields** parameter. * @return Promise<PersonEntry> */ createPerson(personBodyCreate: PersonBodyCreate, opts?: any): Promise<PersonEntry> { throwIfNotDefined(personBodyCreate, 'personBodyCreate'); opts = opts || {}; const postBody = personBodyCreate; const pathParams = { }; const queryParams = { 'fields': buildCollectionParam(opts['fields'], 'csv') }; const headerParams = { }; const formParams = { }; const contentTypes = ['application/json']; const accepts = ['application/json']; return this.apiClient.callApi( '/people', 'POST', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts , PersonEntry); } /** * Delete avatar image * * **Note:** this endpoint is available in Alfresco 5.2.2 and newer versions. Deletes the avatar image related to person **personId**. You must be the person or have admin rights to update a person's avatar. You can use the -me- string in place of <personId> to specify the currently authenticated user. * * @param personId The identifier of a person. * @return Promise<{}> */ deleteAvatarImage(personId: string): Promise<any> { throwIfNotDefined(personId, 'personId'); const postBody: null = null; const pathParams = { 'personId': personId }; const queryParams = { }; const headerParams = { }; const formParams = { }; const contentTypes = ['application/json']; const accepts = ['application/json']; return this.apiClient.callApi( '/people/{personId}/avatar', 'DELETE', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts ); } /** * Get avatar image * * **Note:** this endpoint is available in Alfresco 5.2.2 and newer versions. Gets the avatar image related to the person **personId**. If the person has no related avatar then the **placeholder** query parameter can be optionally used to request a placeholder image to be returned. You can use the -me- string in place of <personId> to specify the currently authenticated user. * * @param personId The identifier of a person. * @param opts Optional parameters * @param opts.attachment **true** enables a web browser to download the file as an attachment. **false** means a web browser may preview the file in a new tab or window, but not download the file. You can only set this parameter to **false** if the content type of the file is in the supported list; for example, certain image files and PDF files. If the content type is not supported for preview, then a value of **false** is ignored, and the attachment will be returned in the response. (default to true) * @param opts.ifModifiedSince Only returns the content if it has been modified since the date provided. Use the date format defined by HTTP. For example, Wed, 09 Mar 2016 16:56:34 GMT. * @param opts.placeholder If **true** and there is no avatar for this **personId** then the placeholder image is returned, rather than a 404 response. (default to true) * @return Promise<Blob> */ getAvatarImage(personId: string, opts?: any): Promise<Blob> { throwIfNotDefined(personId, 'personId'); opts = opts || {}; const postBody: null = null; const pathParams = { 'personId': personId }; const queryParams = { 'attachment': opts['attachment'], 'placeholder': opts['placeholder'] }; const headerParams = { 'If-Modified-Since': opts['ifModifiedSince'] }; const formParams = { }; const contentTypes = ['application/json']; const accepts = ['application/octet-stream']; return this.apiClient.callApi( '/people/{personId}/avatar', 'GET', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts , 'blob'); } /** * Get a person * * Gets information for the person **personId**. You can use the -me- string in place of <personId> to specify the currently authenticated user. * * @param personId The identifier of a person. * @param opts Optional parameters * @param opts.fields A list of field names. You can use this parameter to restrict the fields returned within a response if, for example, you want to save on overall bandwidth. The list applies to a returned individual entity or entries within a collection. If the API method also supports the **include** parameter, then the fields specified in the **include** parameter are returned in addition to those specified in the **fields** parameter. * @return Promise<PersonEntry> */ getPerson(personId: string, opts?: any): Promise<PersonEntry> { throwIfNotDefined(personId, 'personId'); opts = opts || {}; const postBody: null = null; const pathParams = { 'personId': personId }; const queryParams = { 'fields': buildCollectionParam(opts['fields'], 'csv') }; const headerParams = { }; const formParams = { }; const contentTypes = ['application/json']; const accepts = ['application/json']; return this.apiClient.callApi( '/people/{personId}', 'GET', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts , PersonEntry); } /** * List people * * **Note:** this endpoint is available in Alfresco 5.2 and newer versions. List people. You can use the **include** parameter to return any additional information. The default sort order for the returned list is for people to be sorted by ascending id. You can override the default by using the **orderBy** parameter. You can use any of the following fields to order the results: * id * firstName * lastName * * @param opts Optional parameters * @param opts.skipCount The number of entities that exist in the collection before those included in this list. If not supplied then the default value is 0. (default to 0) * @param opts.maxItems The maximum number of items to return in the list. If not supplied then the default value is 100. (default to 100) * @param opts.orderBy A string to control the order of the entities returned in a list. You can use the **orderBy** parameter to sort the list by one or more fields. Each field has a default sort order, which is normally ascending order. Read the API method implementation notes above to check if any fields used in this method have a descending default search order. To sort the entities in a specific order, you can use the **ASC** and **DESC** keywords for any field. * @param opts.include Returns additional information about the person. The following optional fields can be requested: * properties * aspectNames * capabilities * @param opts.fields A list of field names. You can use this parameter to restrict the fields returned within a response if, for example, you want to save on overall bandwidth. The list applies to a returned individual entity or entries within a collection. If the API method also supports the **include** parameter, then the fields specified in the **include** parameter are returned in addition to those specified in the **fields** parameter. * @return Promise<PersonPaging> */ listPeople(opts?: any): Promise<PersonPaging> { opts = opts || {}; const postBody: null = null; const pathParams = { }; const queryParams = { 'skipCount': opts['skipCount'], 'maxItems': opts['maxItems'], 'orderBy': buildCollectionParam(opts['orderBy'], 'csv'), 'include': buildCollectionParam(opts['include'], 'csv'), 'fields': buildCollectionParam(opts['fields'], 'csv') }; const headerParams = { }; const formParams = { }; const contentTypes = ['application/json']; const accepts = ['application/json']; return this.apiClient.callApi( '/people', 'GET', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts , PersonPaging); } /** * Request password reset * * **Note:** this endpoint is available in Alfresco 5.2.1 and newer versions. Initiates the reset password workflow to send an email with reset password instruction to the user's registered email. The client is mandatory in the request body. For example: JSON { \"client\": \"myClient\" } **Note:** The client must be registered before this API can send an email. See [server documentation]. However, out-of-the-box share is registered as a default client, so you could pass **share** as the client name: JSON { \"client\": \"share\" } **Note:** No authentication is required to call this endpoint. * * @param personId The identifier of a person. * @param clientBody The client name to send email with app-specific url. * @return Promise<{}> */ requestPasswordReset(personId: string, clientBody: ClientBody): Promise<any> { throwIfNotDefined(personId, 'personId'); throwIfNotDefined(clientBody, 'clientBody'); const postBody = clientBody; const pathParams = { 'personId': personId }; const queryParams = { }; const headerParams = { }; const formParams = { }; const contentTypes = ['application/json']; const accepts = ['application/json']; return this.apiClient.callApi( '/people/{personId}/request-password-reset', 'POST', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts ); } /** * Reset password * * **Note:** this endpoint is available in Alfresco 5.2.1 and newer versions. Resets user's password The password, id and key properties are mandatory in the request body. For example: JSON { \"password\":\"newPassword\", \"id\":\"activiti$10\", \"key\":\"4dad6d00-0daf-413a-b200-f64af4e12345\" } **Note:** No authentication is required to call this endpoint. * * @param personId The identifier of a person. * @param passwordResetBody The reset password details * @return Promise<{}> */ resetPassword(personId: string, passwordResetBody: PasswordResetBody): Promise<any> { throwIfNotDefined(personId, 'personId'); throwIfNotDefined(passwordResetBody, 'passwordResetBody'); const postBody = passwordResetBody; const pathParams = { 'personId': personId }; const queryParams = { }; const headerParams = { }; const formParams = { }; const contentTypes = ['application/json']; const accepts = ['application/json']; return this.apiClient.callApi( '/people/{personId}/reset-password', 'POST', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts ); } /** * Update avatar image * * **Note:** this endpoint is available in Alfresco 5.2.2 and newer versions. Updates the avatar image related to the person **personId**. The request body should be the binary stream for the avatar image. The content type of the file should be an image file. This will be used to generate an \"avatar\" thumbnail rendition. You must be the person or have admin rights to update a person's avatar. You can use the -me- string in place of <personId> to specify the currently authenticated user. * * @param personId The identifier of a person. * @param contentBodyUpdate The binary content * @return Promise<{}> */ updateAvatarImage(personId: string, contentBodyUpdate: string): Promise<any> { throwIfNotDefined(personId, 'personId'); throwIfNotDefined(contentBodyUpdate, 'contentBodyUpdate'); const postBody = contentBodyUpdate; const pathParams = { 'personId': personId }; const queryParams = { }; const headerParams = { }; const formParams = { }; const contentTypes = ['application/octet-stream']; const accepts = ['application/json']; return this.apiClient.callApi( '/people/{personId}/avatar', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts ); } /** * Update person * * **Note:** this endpoint is available in Alfresco 5.2 and newer versions. Update the given person's details. You can use the -me- string in place of <personId> to specify the currently authenticated user. If applicable, the given person's login access can also be optionally disabled or re-enabled. You must have admin rights to update a person — unless updating your own details. If you are changing your password, as a non-admin user, then the existing password must also be supplied (using the oldPassword field in addition to the new password value). Admin users cannot be disabled by setting enabled to false. Non-admin users may not disable themselves. You can set custom properties when you update a person: JSON { \"firstName\": \"Alice\", \"properties\": { \"my:property\": \"The value\" } } **Note:** setting properties of type d:content and d:category are not supported. * * @param personId The identifier of a person. * @param personBodyUpdate The person details. * @param opts Optional parameters * @param opts.fields A list of field names. You can use this parameter to restrict the fields returned within a response if, for example, you want to save on overall bandwidth. The list applies to a returned individual entity or entries within a collection. If the API method also supports the **include** parameter, then the fields specified in the **include** parameter are returned in addition to those specified in the **fields** parameter. * @return Promise<PersonEntry> */ updatePerson(personId: string, personBodyUpdate: PersonBodyUpdate, opts?: any): Promise<PersonEntry> { throwIfNotDefined(personId, 'personId'); throwIfNotDefined(personBodyUpdate, 'personBodyUpdate'); opts = opts || {}; const postBody = personBodyUpdate; const pathParams = { 'personId': personId }; const queryParams = { 'fields': buildCollectionParam(opts['fields'], 'csv') }; const headerParams = { }; const formParams = { }; const contentTypes = ['application/json']; const accepts = ['application/json']; return this.apiClient.callApi( '/people/{personId}', 'PUT', pathParams, queryParams, headerParams, formParams, postBody, contentTypes, accepts , PersonEntry); } }
the_stack
import * as path from 'path'; import * as sinon from 'sinon'; import * as fsWatcher from '../../../../../client/common/platform/fileSystemWatcher'; import * as platformUtils from '../../../../../client/common/utils/platform'; import { PythonEnvKind } from '../../../../../client/pythonEnvironments/base/info'; import { getEnvs } from '../../../../../client/pythonEnvironments/base/locatorUtils'; import * as externalDependencies from '../../../../../client/pythonEnvironments/common/externalDependencies'; import { GlobalVirtualEnvironmentLocator } from '../../../../../client/pythonEnvironments/base/locators/lowLevel/globalVirtualEnvronmentLocator'; import { createBasicEnv } from '../../common'; import { TEST_LAYOUT_ROOT } from '../../../common/commonTestConstants'; import { assertBasicEnvsEqual } from '../envTestUtils'; suite('GlobalVirtualEnvironment Locator', () => { const testVirtualHomeDir = path.join(TEST_LAYOUT_ROOT, 'virtualhome'); const testWorkOnHomePath = path.join(testVirtualHomeDir, 'workonhome'); let getEnvVariableStub: sinon.SinonStub; let getUserHomeDirStub: sinon.SinonStub; let getOSTypeStub: sinon.SinonStub; let readFileStub: sinon.SinonStub; let locator: GlobalVirtualEnvironmentLocator; let watchLocationForPatternStub: sinon.SinonStub; setup(async () => { getEnvVariableStub = sinon.stub(platformUtils, 'getEnvironmentVariable'); getEnvVariableStub.withArgs('WORKON_HOME').returns(testWorkOnHomePath); getUserHomeDirStub = sinon.stub(platformUtils, 'getUserHomeDir'); getUserHomeDirStub.returns(testVirtualHomeDir); getOSTypeStub = sinon.stub(platformUtils, 'getOSType'); getOSTypeStub.returns(platformUtils.OSType.Linux); watchLocationForPatternStub = sinon.stub(fsWatcher, 'watchLocationForPattern'); watchLocationForPatternStub.returns({ dispose: () => { /* do nothing */ }, }); const expectedDotProjectFile = path.join( testVirtualHomeDir, '.local', 'share', 'virtualenvs', 'project2-vnNIWe9P', '.project', ); readFileStub = sinon.stub(externalDependencies, 'readFile'); readFileStub.withArgs(expectedDotProjectFile).returns(path.join(TEST_LAYOUT_ROOT, 'pipenv', 'project2')); readFileStub.callThrough(); }); teardown(async () => { await locator.dispose(); readFileStub.restore(); getEnvVariableStub.restore(); getUserHomeDirStub.restore(); getOSTypeStub.restore(); watchLocationForPatternStub.restore(); }); test('iterEnvs(): Windows', async () => { getOSTypeStub.returns(platformUtils.OSType.Windows); const expectedEnvs = [ createBasicEnv(PythonEnvKind.Venv, path.join(testVirtualHomeDir, '.venvs', 'win1', 'python.exe')), createBasicEnv(PythonEnvKind.Venv, path.join(testVirtualHomeDir, '.venvs', 'win2', 'bin', 'python.exe')), createBasicEnv( PythonEnvKind.VirtualEnv, path.join(testVirtualHomeDir, '.virtualenvs', 'win1', 'python.exe'), ), createBasicEnv( PythonEnvKind.VirtualEnv, path.join(testVirtualHomeDir, '.virtualenvs', 'win2', 'bin', 'python.exe'), ), createBasicEnv( PythonEnvKind.VirtualEnv, path.join(testVirtualHomeDir, 'Envs', 'wrapper_win1', 'python.exe'), ), createBasicEnv( PythonEnvKind.VirtualEnv, path.join(testVirtualHomeDir, 'Envs', 'wrapper_win2', 'bin', 'python.exe'), ), createBasicEnv( PythonEnvKind.VirtualEnvWrapper, path.join(testVirtualHomeDir, 'workonhome', 'win1', 'python.exe'), ), createBasicEnv( PythonEnvKind.VirtualEnvWrapper, path.join(testVirtualHomeDir, 'workonhome', 'win2', 'bin', 'python.exe'), ), ]; locator = new GlobalVirtualEnvironmentLocator(); const iterator = locator.iterEnvs(); const actualEnvs = await getEnvs(iterator); assertBasicEnvsEqual(actualEnvs, expectedEnvs); }); test('iterEnvs(): Windows (WORKON_HOME NOT set)', async () => { getOSTypeStub.returns(platformUtils.OSType.Windows); getEnvVariableStub.withArgs('WORKON_HOME').returns(undefined); const expectedEnvs = [ createBasicEnv(PythonEnvKind.Venv, path.join(testVirtualHomeDir, '.venvs', 'win1', 'python.exe')), createBasicEnv(PythonEnvKind.Venv, path.join(testVirtualHomeDir, '.venvs', 'win2', 'bin', 'python.exe')), createBasicEnv( PythonEnvKind.VirtualEnv, path.join(testVirtualHomeDir, '.virtualenvs', 'win1', 'python.exe'), ), createBasicEnv( PythonEnvKind.VirtualEnv, path.join(testVirtualHomeDir, '.virtualenvs', 'win2', 'bin', 'python.exe'), ), createBasicEnv( PythonEnvKind.VirtualEnvWrapper, path.join(testVirtualHomeDir, 'Envs', 'wrapper_win1', 'python.exe'), ), createBasicEnv( PythonEnvKind.VirtualEnvWrapper, path.join(testVirtualHomeDir, 'Envs', 'wrapper_win2', 'bin', 'python.exe'), ), ]; locator = new GlobalVirtualEnvironmentLocator(); const iterator = locator.iterEnvs(); const actualEnvs = await getEnvs(iterator); assertBasicEnvsEqual(actualEnvs, expectedEnvs); }); test('iterEnvs(): Non-Windows', async () => { const expectedEnvs = [ createBasicEnv(PythonEnvKind.Venv, path.join(testVirtualHomeDir, '.venvs', 'posix1', 'python')), createBasicEnv(PythonEnvKind.Venv, path.join(testVirtualHomeDir, '.venvs', 'posix2', 'bin', 'python')), createBasicEnv(PythonEnvKind.VirtualEnv, path.join(testVirtualHomeDir, '.virtualenvs', 'posix1', 'python')), createBasicEnv( PythonEnvKind.VirtualEnv, path.join(testVirtualHomeDir, '.virtualenvs', 'posix2', 'bin', 'python'), ), createBasicEnv( PythonEnvKind.VirtualEnvWrapper, path.join(testVirtualHomeDir, 'workonhome', 'posix1', 'python'), ), createBasicEnv( PythonEnvKind.VirtualEnvWrapper, path.join(testVirtualHomeDir, 'workonhome', 'posix2', 'bin', 'python'), ), createBasicEnv( PythonEnvKind.Pipenv, path.join(testVirtualHomeDir, '.local', 'share', 'virtualenvs', 'project2-vnNIWe9P', 'bin', 'python'), ), ]; locator = new GlobalVirtualEnvironmentLocator(); const iterator = locator.iterEnvs(); const actualEnvs = await getEnvs(iterator); assertBasicEnvsEqual(actualEnvs, expectedEnvs); }); test('iterEnvs(): with depth set', async () => { const expectedEnvs = [ createBasicEnv(PythonEnvKind.Venv, path.join(testVirtualHomeDir, '.venvs', 'posix1', 'python')), createBasicEnv(PythonEnvKind.VirtualEnv, path.join(testVirtualHomeDir, '.virtualenvs', 'posix1', 'python')), createBasicEnv( PythonEnvKind.VirtualEnvWrapper, path.join(testVirtualHomeDir, 'workonhome', 'posix1', 'python'), ), ]; locator = new GlobalVirtualEnvironmentLocator(1); const iterator = locator.iterEnvs(); const actualEnvs = await getEnvs(iterator); assertBasicEnvsEqual(actualEnvs, expectedEnvs); }); test('iterEnvs(): Non-Windows (WORKON_HOME not set)', async () => { getEnvVariableStub.withArgs('WORKON_HOME').returns(undefined); const expectedEnvs = [ createBasicEnv(PythonEnvKind.Venv, path.join(testVirtualHomeDir, '.venvs', 'posix1', 'python')), createBasicEnv(PythonEnvKind.Venv, path.join(testVirtualHomeDir, '.venvs', 'posix2', 'bin', 'python')), createBasicEnv( PythonEnvKind.VirtualEnvWrapper, path.join(testVirtualHomeDir, '.virtualenvs', 'posix1', 'python'), ), createBasicEnv( PythonEnvKind.VirtualEnvWrapper, path.join(testVirtualHomeDir, '.virtualenvs', 'posix2', 'bin', 'python'), ), createBasicEnv( PythonEnvKind.Pipenv, path.join(testVirtualHomeDir, '.local', 'share', 'virtualenvs', 'project2-vnNIWe9P', 'bin', 'python'), ), ]; locator = new GlobalVirtualEnvironmentLocator(); const iterator = locator.iterEnvs(); const actualEnvs = await getEnvs(iterator); assertBasicEnvsEqual(actualEnvs, expectedEnvs); }); test('iterEnvs(): No User home dir set', async () => { getUserHomeDirStub.returns(undefined); const expectedEnvs = [ createBasicEnv( PythonEnvKind.VirtualEnvWrapper, path.join(testVirtualHomeDir, 'workonhome', 'posix1', 'python'), ), createBasicEnv( PythonEnvKind.VirtualEnvWrapper, path.join(testVirtualHomeDir, 'workonhome', 'posix2', 'bin', 'python'), ), ]; locator = new GlobalVirtualEnvironmentLocator(); const iterator = locator.iterEnvs(); const actualEnvs = await getEnvs(iterator); assertBasicEnvsEqual(actualEnvs, expectedEnvs); }); test('iterEnvs(): No default virtual environment dirs ', async () => { // We can simulate that by pointing the user home dir to some random directory getUserHomeDirStub.returns(path.join('some', 'random', 'directory')); const expectedEnvs = [ createBasicEnv( PythonEnvKind.VirtualEnvWrapper, path.join(testVirtualHomeDir, 'workonhome', 'posix1', 'python'), ), createBasicEnv( PythonEnvKind.VirtualEnvWrapper, path.join(testVirtualHomeDir, 'workonhome', 'posix2', 'bin', 'python'), ), ]; locator = new GlobalVirtualEnvironmentLocator(2); const iterator = locator.iterEnvs(); const actualEnvs = await getEnvs(iterator); assertBasicEnvsEqual(actualEnvs, expectedEnvs); }); });
the_stack
import { SendRequestReason } from "../JavaScriptSDK.Enums/SendRequestReason"; import { TelemetryUnloadReason } from "../JavaScriptSDK.Enums/TelemetryUnloadReason"; import { TelemetryUpdateReason } from "../JavaScriptSDK.Enums/TelemetryUpdateReason"; import { IAppInsightsCore } from "../JavaScriptSDK.Interfaces/IAppInsightsCore"; import { IChannelControls } from "../JavaScriptSDK.Interfaces/IChannelControls"; import { IConfiguration } from "../JavaScriptSDK.Interfaces/IConfiguration"; import { IBaseProcessingContext, IProcessTelemetryContext, IProcessTelemetryUnloadContext, IProcessTelemetryUpdateContext } from "../JavaScriptSDK.Interfaces/IProcessTelemetryContext"; import { ITelemetryItem } from "../JavaScriptSDK.Interfaces/ITelemetryItem"; import { IPlugin } from "../JavaScriptSDK.Interfaces/ITelemetryPlugin"; import { ITelemetryPluginChain } from "../JavaScriptSDK.Interfaces/ITelemetryPluginChain"; import { ITelemetryUnloadState } from "../JavaScriptSDK.Interfaces/ITelemetryUnloadState"; import { ITelemetryUpdateState } from "../JavaScriptSDK.Interfaces/ITelemetryUpdateState"; import { arrForEach, isArray, objFreeze, throwError } from "./HelperFuncs"; import { strPause, strProcessNext, strResume, strTeardown } from "./InternalConstants"; import { createProcessTelemetryContext, createTelemetryProxyChain } from "./ProcessTelemetryContext"; import { initializePlugins } from "./TelemetryHelpers"; export const ChannelControllerPriority = 500; const ChannelValidationMessage = "Channel has invalid priority - "; export interface IChannelController extends IChannelControls { flush(isAsync: boolean, callBack: (flushComplete?: boolean) => void, sendReason: SendRequestReason, cbTimeout?: number): void; getChannel<T extends IPlugin = IPlugin>(pluginIdentifier: string): T; } export interface IInternalChannelController extends IChannelController { _setQueue: (channels: _IInternalChannels[]) => void; } export interface _IInternalChannels { queue: IChannelControls[]; chain: ITelemetryPluginChain; } function _addChannelQueue(channelQueue: _IInternalChannels[], queue: IChannelControls[], config: IConfiguration, core: IAppInsightsCore) { if (queue && isArray(queue) && queue.length > 0) { queue = queue.sort((a, b) => { // sort based on priority within each queue return a.priority - b.priority; }); arrForEach(queue, queueItem => { if (queueItem.priority < ChannelControllerPriority) { throwError(ChannelValidationMessage + queueItem.identifier); } }); channelQueue.push({ queue: objFreeze(queue), chain: createTelemetryProxyChain(queue, config, core) }); } } export function createChannelControllerPlugin(channelQueue: _IInternalChannels[], core: IAppInsightsCore): IChannelController { function _getTelCtx() { return createProcessTelemetryContext(null, core.config, core, null) } function _processChannelQueue<T extends IBaseProcessingContext>(theChannels: _IInternalChannels[], itemCtx: T, processFn: (chainCtx: T) => void, onComplete: (() => void) | null) { let waiting = theChannels ? (theChannels.length + 1) : 1; function _runChainOnComplete() { waiting --; if (waiting === 0) { onComplete && onComplete(); onComplete = null; } } if (waiting > 0) { arrForEach(theChannels, (channels) => { // pass on to first item in queue if (channels && channels.queue.length > 0) { let channelChain = channels.chain; let chainCtx = itemCtx.createNew(channelChain) as T; chainCtx.onComplete(_runChainOnComplete); // Cause this chain to start processing processFn(chainCtx); } else { waiting --; } }); } _runChainOnComplete(); } function _doUpdate(updateCtx: IProcessTelemetryUpdateContext, updateState: ITelemetryUpdateState) { let theUpdateState: ITelemetryUpdateState = updateState || { reason: TelemetryUpdateReason.Unknown }; _processChannelQueue(channelQueue, updateCtx, (chainCtx: IProcessTelemetryUpdateContext) => { chainCtx[strProcessNext](theUpdateState); }, () => { updateCtx[strProcessNext](theUpdateState); }); return true; } function _doTeardown(unloadCtx: IProcessTelemetryUnloadContext, unloadState: ITelemetryUnloadState) { let theUnloadState: ITelemetryUnloadState = unloadState || { reason: TelemetryUnloadReason.ManualTeardown, isAsync: false }; _processChannelQueue(channelQueue, unloadCtx, (chainCtx: IProcessTelemetryUnloadContext) => { chainCtx[strProcessNext](theUnloadState); }, () => { unloadCtx[strProcessNext](theUnloadState); isInitialized = false; }); return true; } function _getChannel<T extends IPlugin = IPlugin>(pluginIdentifier: string): T { let thePlugin: T = null; if (channelQueue && channelQueue.length > 0) { arrForEach(channelQueue, (channels) => { // pass on to first item in queue if (channels && channels.queue.length > 0) { arrForEach(channels.queue, (ext: any) => { if (ext.identifier === pluginIdentifier) { thePlugin = ext; // Cause arrForEach to stop iterating return -1; } }); if (thePlugin) { // Cause arrForEach to stop iterating return -1; } } }); } return thePlugin; } let isInitialized = false; let channelController: IInternalChannelController = { identifier: "ChannelControllerPlugin", priority: ChannelControllerPriority, initialize: (config: IConfiguration, core: IAppInsightsCore, extensions: IPlugin[], pluginChain?: ITelemetryPluginChain) => { isInitialized = true; arrForEach(channelQueue, (channels) => { if (channels && channels.queue.length > 0) { initializePlugins(createProcessTelemetryContext(channels.chain, config, core), extensions); } }); }, isInitialized: () => { return isInitialized }, processTelemetry: (item: ITelemetryItem, itemCtx: IProcessTelemetryContext) => { _processChannelQueue(channelQueue, itemCtx || _getTelCtx(), (chainCtx: IProcessTelemetryContext) => { chainCtx[strProcessNext](item); }, () => { itemCtx[strProcessNext](item); }); }, update: _doUpdate, [strPause]: () => { _processChannelQueue(channelQueue, _getTelCtx(), (chainCtx: IProcessTelemetryContext) => { chainCtx.iterate<IChannelControls>((plugin) => { plugin[strPause] && plugin[strPause](); }); }, null); }, [strResume]: () => { _processChannelQueue(channelQueue, _getTelCtx(), (chainCtx: IProcessTelemetryContext) => { chainCtx.iterate<IChannelControls>((plugin) => { plugin[strResume] && plugin[strResume](); }); }, null); }, [strTeardown]: _doTeardown, getChannel: _getChannel, flush: (isAsync: boolean, callBack: (flushComplete?: boolean) => void, sendReason: SendRequestReason, cbTimeout?: number) => { // Setting waiting to one so that we don't call the callBack until we finish iterating let waiting = 1; let doneIterating = false; let cbTimer: any = null; cbTimeout = cbTimeout || 5000; function doCallback() { waiting--; if (doneIterating && waiting === 0) { if (cbTimer) { clearTimeout(cbTimer); cbTimer = null; } callBack && callBack(doneIterating); callBack = null; } } _processChannelQueue(channelQueue, _getTelCtx(), (chainCtx: IProcessTelemetryContext) => { chainCtx.iterate<IChannelControls>((plugin) => { if (plugin.flush) { waiting ++; let handled = false; // Not all channels will call this callback for every scenario if (!plugin.flush(isAsync, () => { handled = true; doCallback(); }, sendReason)) { if (!handled) { // If any channel doesn't return true and it didn't call the callback, then we should assume that the callback // will never be called, so use a timeout to allow the channel(s) some time to "finish" before triggering any // followup function (such as unloading) if (isAsync && cbTimer == null) { cbTimer = setTimeout(() => { cbTimer = null; doCallback(); }, cbTimeout); } else { doCallback(); } } } } }); }, () => { doneIterating = true; doCallback(); }); return true; }, _setQueue: (queue: _IInternalChannels[]) => { channelQueue = queue; } }; return channelController; } export function createChannelQueues(channels: IChannelControls[][], extensions: IPlugin[], config: IConfiguration, core: IAppInsightsCore) { let channelQueue: _IInternalChannels[] = []; if (channels) { // Add and sort the configuration channel queues arrForEach(channels, queue => _addChannelQueue(channelQueue, queue, config, core)); } if (extensions) { // Create a new channel queue for any extensions with a priority > the ChannelControllerPriority let extensionQueue: IChannelControls[] = []; arrForEach(extensions as IChannelControls[], plugin => { if (plugin.priority > ChannelControllerPriority) { extensionQueue.push(plugin); } }); _addChannelQueue(channelQueue, extensionQueue, config, core); } return channelQueue; }
the_stack
export interface IReturn<T> { createResponse(): T; } export interface IReturnVoid { createResponse(): void; } export interface IHasSessionId { sessionId: string; } export interface IHasBearerToken { bearerToken: string; } export interface IPost { } export interface IAuthTokens { provider: string; userId: string; accessToken: string; accessTokenSecret: string; refreshToken: string; refreshTokenExpiry?: string; requestToken: string; requestTokenSecret: string; items: { [index:string]: string; }; } export enum Title { Unspecified = 'Unspecified', Mr = 'Mr', Mrs = 'Mrs', Miss = 'Miss', } export class Contact { public constructor(init?:Partial<Contact>) { (<any>Object).assign(this, init); } public id: number; public userAuthId: number; public title: Title; public name: string; public color: string; public filmGenres: FilmGenres[]; public age: number; } // @DataContract export class ResponseError { public constructor(init?:Partial<ResponseError>) { (<any>Object).assign(this, init); } // @DataMember(Order=1, EmitDefaultValue=false) public errorCode: string; // @DataMember(Order=2, EmitDefaultValue=false) public fieldName: string; // @DataMember(Order=3, EmitDefaultValue=false) public message: string; // @DataMember(Order=4, EmitDefaultValue=false) public meta: { [index:string]: string; }; } // @DataContract export class ResponseStatus { public constructor(init?:Partial<ResponseStatus>) { (<any>Object).assign(this, init); } // @DataMember(Order=1) public errorCode: string; // @DataMember(Order=2) public message: string; // @DataMember(Order=3) public stackTrace: string; // @DataMember(Order=4) public errors: ResponseError[]; // @DataMember(Order=5) public meta: { [index:string]: string; }; } export enum FilmGenres { Action = 'Action', Adventure = 'Adventure', Comedy = 'Comedy', Drama = 'Drama', } export class HelloResponse { public constructor(init?:Partial<HelloResponse>) { (<any>Object).assign(this, init); } public result: string; } // @Route("/testauth") export class TestAuth implements IReturn<TestAuth> { public constructor(init?:Partial<TestAuth>) { (<any>Object).assign(this, init); } public createResponse() { return new TestAuth(); } public getTypeName() { return 'TestAuth'; } } // @DataContract export class AuthUserSession { public constructor(init?:Partial<AuthUserSession>) { (<any>Object).assign(this, init); } // @DataMember(Order=1) public referrerUrl: string; // @DataMember(Order=2) public id: string; // @DataMember(Order=3) public userAuthId: string; // @DataMember(Order=4) public userAuthName: string; // @DataMember(Order=5) public userName: string; // @DataMember(Order=6) public twitterUserId: string; // @DataMember(Order=7) public twitterScreenName: string; // @DataMember(Order=8) public facebookUserId: string; // @DataMember(Order=9) public facebookUserName: string; // @DataMember(Order=10) public firstName: string; // @DataMember(Order=11) public lastName: string; // @DataMember(Order=12) public displayName: string; // @DataMember(Order=13) public company: string; // @DataMember(Order=14) public email: string; // @DataMember(Order=15) public primaryEmail: string; // @DataMember(Order=16) public phoneNumber: string; // @DataMember(Order=17) public birthDate: string; // @DataMember(Order=18) public birthDateRaw: string; // @DataMember(Order=19) public address: string; // @DataMember(Order=20) public address2: string; // @DataMember(Order=21) public city: string; // @DataMember(Order=22) public state: string; // @DataMember(Order=23) public country: string; // @DataMember(Order=24) public culture: string; // @DataMember(Order=25) public fullName: string; // @DataMember(Order=26) public gender: string; // @DataMember(Order=27) public language: string; // @DataMember(Order=28) public mailAddress: string; // @DataMember(Order=29) public nickname: string; // @DataMember(Order=30) public postalCode: string; // @DataMember(Order=31) public timeZone: string; // @DataMember(Order=32) public requestTokenSecret: string; // @DataMember(Order=33) public createdAt: string; // @DataMember(Order=34) public lastModified: string; // @DataMember(Order=35) public roles: string[]; // @DataMember(Order=36) public permissions: string[]; // @DataMember(Order=37) public isAuthenticated: boolean; // @DataMember(Order=38) public fromToken: boolean; // @DataMember(Order=39) public profileUrl: string; // @DataMember(Order=40) public sequence: string; // @DataMember(Order=41) public tag: number; // @DataMember(Order=42) public authProvider: string; // @DataMember(Order=43) public providerOAuthAccess: IAuthTokens[]; // @DataMember(Order=44) public meta: { [index:string]: string; }; // @DataMember(Order=45) public audiences: string[]; // @DataMember(Order=46) public scopes: string[]; // @DataMember(Order=47) public dns: string; // @DataMember(Order=48) public rsa: string; // @DataMember(Order=49) public sid: string; // @DataMember(Order=50) public hash: string; // @DataMember(Order=51) public homePhone: string; // @DataMember(Order=52) public mobilePhone: string; // @DataMember(Order=53) public webpage: string; // @DataMember(Order=54) public emailConfirmed: boolean; // @DataMember(Order=55) public phoneNumberConfirmed: boolean; // @DataMember(Order=56) public twoFactorEnabled: boolean; // @DataMember(Order=57) public securityStamp: string; // @DataMember(Order=58) public type: string; } export class GetContactsResponse { public constructor(init?:Partial<GetContactsResponse>) { (<any>Object).assign(this, init); } public results: Contact[]; public responseStatus: ResponseStatus; } export class GetContactResponse { public constructor(init?:Partial<GetContactResponse>) { (<any>Object).assign(this, init); } public result: Contact; public responseStatus: ResponseStatus; } export class CreateContactResponse { public constructor(init?:Partial<CreateContactResponse>) { (<any>Object).assign(this, init); } public result: Contact; public responseStatus: ResponseStatus; } export class UpdateContactResponse { public constructor(init?:Partial<UpdateContactResponse>) { (<any>Object).assign(this, init); } public responseStatus: ResponseStatus; } // @DataContract export class AuthenticateResponse implements IHasSessionId, IHasBearerToken { public constructor(init?:Partial<AuthenticateResponse>) { (<any>Object).assign(this, init); } // @DataMember(Order=1) public userId: string; // @DataMember(Order=2) public sessionId: string; // @DataMember(Order=3) public userName: string; // @DataMember(Order=4) public displayName: string; // @DataMember(Order=5) public referrerUrl: string; // @DataMember(Order=6) public bearerToken: string; // @DataMember(Order=7) public refreshToken: string; // @DataMember(Order=8) public responseStatus: ResponseStatus; // @DataMember(Order=9) public meta: { [index:string]: string; }; } // @DataContract export class AssignRolesResponse { public constructor(init?:Partial<AssignRolesResponse>) { (<any>Object).assign(this, init); } // @DataMember(Order=1) public allRoles: string[]; // @DataMember(Order=2) public allPermissions: string[]; // @DataMember(Order=3) public responseStatus: ResponseStatus; } // @DataContract export class UnAssignRolesResponse { public constructor(init?:Partial<UnAssignRolesResponse>) { (<any>Object).assign(this, init); } // @DataMember(Order=1) public allRoles: string[]; // @DataMember(Order=2) public allPermissions: string[]; // @DataMember(Order=3) public responseStatus: ResponseStatus; } // @DataContract export class ConvertSessionToTokenResponse { public constructor(init?:Partial<ConvertSessionToTokenResponse>) { (<any>Object).assign(this, init); } // @DataMember(Order=1) public meta: { [index:string]: string; }; // @DataMember(Order=2) public accessToken: string; // @DataMember(Order=3) public responseStatus: ResponseStatus; } // @DataContract export class GetAccessTokenResponse { public constructor(init?:Partial<GetAccessTokenResponse>) { (<any>Object).assign(this, init); } // @DataMember(Order=1) public accessToken: string; // @DataMember(Order=2) public responseStatus: ResponseStatus; } // @DataContract export class RegisterResponse { public constructor(init?:Partial<RegisterResponse>) { (<any>Object).assign(this, init); } // @DataMember(Order=1) public userId: string; // @DataMember(Order=2) public sessionId: string; // @DataMember(Order=3) public userName: string; // @DataMember(Order=4) public referrerUrl: string; // @DataMember(Order=5) public bearerToken: string; // @DataMember(Order=6) public refreshToken: string; // @DataMember(Order=7) public responseStatus: ResponseStatus; // @DataMember(Order=8) public meta: { [index:string]: string; }; } // @Route("/hello") // @Route("/hello/{Name}") export class Hello implements IReturn<HelloResponse> { public constructor(init?:Partial<Hello>) { (<any>Object).assign(this, init); } public name: string; public createResponse() { return new HelloResponse(); } public getTypeName() { return 'Hello'; } } // @Route("/session") export class Session implements IReturn<AuthUserSession> { public constructor(init?:Partial<Session>) { (<any>Object).assign(this, init); } public createResponse() { return new AuthUserSession(); } public getTypeName() { return 'Session'; } } // @Route("/contacts", "GET") export class GetContacts implements IReturn<GetContactsResponse> { public constructor(init?:Partial<GetContacts>) { (<any>Object).assign(this, init); } public createResponse() { return new GetContactsResponse(); } public getTypeName() { return 'GetContacts'; } } // @Route("/contacts/{Id}", "GET") export class GetContact implements IReturn<GetContactResponse> { public constructor(init?:Partial<GetContact>) { (<any>Object).assign(this, init); } public id: number; public createResponse() { return new GetContactResponse(); } public getTypeName() { return 'GetContact'; } } // @Route("/contacts", "POST") export class CreateContact implements IReturn<CreateContactResponse> { public constructor(init?:Partial<CreateContact>) { (<any>Object).assign(this, init); } public title: Title; public name: string; public color: string; public filmGenres: FilmGenres[]; public age: number; public agree: boolean; public continue: string; public errorView: string; public createResponse() { return new CreateContactResponse(); } public getTypeName() { return 'CreateContact'; } } // @Route("/contacts/{Id}", "DELETE") // @Route("/contacts/{Id}/delete", "POST") export class DeleteContact implements IReturnVoid { public constructor(init?:Partial<DeleteContact>) { (<any>Object).assign(this, init); } public id: number; public createResponse() {} public getTypeName() { return 'DeleteContact'; } } // @Route("/contacts/{Id}", "POST PUT") export class UpdateContact implements IReturn<UpdateContactResponse> { public constructor(init?:Partial<UpdateContact>) { (<any>Object).assign(this, init); } public id: number; public title: Title; public name: string; public color: string; public filmGenres: FilmGenres[]; public age: number; public continue: string; public errorView: string; public createResponse() { return new UpdateContactResponse(); } public getTypeName() { return 'UpdateContact'; } } // @Route("/auth") // @Route("/auth/{provider}") // @Route("/authenticate") // @Route("/authenticate/{provider}") // @DataContract export class Authenticate implements IReturn<AuthenticateResponse>, IPost { public constructor(init?:Partial<Authenticate>) { (<any>Object).assign(this, init); } // @DataMember(Order=1) public provider: string; // @DataMember(Order=2) public state: string; // @DataMember(Order=3) public oauth_token: string; // @DataMember(Order=4) public oauth_verifier: string; // @DataMember(Order=5) public userName: string; // @DataMember(Order=6) public password: string; // @DataMember(Order=7) public rememberMe: boolean; // @DataMember(Order=8) public continue: string; // @DataMember(Order=9) public errorView: string; // @DataMember(Order=10) public nonce: string; // @DataMember(Order=11) public uri: string; // @DataMember(Order=12) public response: string; // @DataMember(Order=13) public qop: string; // @DataMember(Order=14) public nc: string; // @DataMember(Order=15) public cnonce: string; // @DataMember(Order=16) public useTokenCookie: boolean; // @DataMember(Order=17) public accessToken: string; // @DataMember(Order=18) public accessTokenSecret: string; // @DataMember(Order=19) public meta: { [index:string]: string; }; public createResponse() { return new AuthenticateResponse(); } public getTypeName() { return 'Authenticate'; } } // @Route("/assignroles") // @DataContract export class AssignRoles implements IReturn<AssignRolesResponse>, IPost { public constructor(init?:Partial<AssignRoles>) { (<any>Object).assign(this, init); } // @DataMember(Order=1) public userName: string; // @DataMember(Order=2) public permissions: string[]; // @DataMember(Order=3) public roles: string[]; public createResponse() { return new AssignRolesResponse(); } public getTypeName() { return 'AssignRoles'; } } // @Route("/unassignroles") // @DataContract export class UnAssignRoles implements IReturn<UnAssignRolesResponse>, IPost { public constructor(init?:Partial<UnAssignRoles>) { (<any>Object).assign(this, init); } // @DataMember(Order=1) public userName: string; // @DataMember(Order=2) public permissions: string[]; // @DataMember(Order=3) public roles: string[]; public createResponse() { return new UnAssignRolesResponse(); } public getTypeName() { return 'UnAssignRoles'; } } // @Route("/session-to-token") // @DataContract export class ConvertSessionToToken implements IReturn<ConvertSessionToTokenResponse>, IPost { public constructor(init?:Partial<ConvertSessionToToken>) { (<any>Object).assign(this, init); } // @DataMember(Order=1) public preserveSession: boolean; public createResponse() { return new ConvertSessionToTokenResponse(); } public getTypeName() { return 'ConvertSessionToToken'; } } // @Route("/access-token") // @DataContract export class GetAccessToken implements IReturn<GetAccessTokenResponse>, IPost { public constructor(init?:Partial<GetAccessToken>) { (<any>Object).assign(this, init); } // @DataMember(Order=1) public refreshToken: string; public createResponse() { return new GetAccessTokenResponse(); } public getTypeName() { return 'GetAccessToken'; } } // @Route("/register") // @DataContract export class Register implements IReturn<RegisterResponse>, IPost { public constructor(init?:Partial<Register>) { (<any>Object).assign(this, init); } // @DataMember(Order=1) public userName: string; // @DataMember(Order=2) public firstName: string; // @DataMember(Order=3) public lastName: string; // @DataMember(Order=4) public displayName: string; // @DataMember(Order=5) public email: string; // @DataMember(Order=6) public password: string; // @DataMember(Order=7) public confirmPassword: string; // @DataMember(Order=8) public autoLogin: boolean; // @DataMember(Order=9) public continue: string; // @DataMember(Order=10) public errorView: string; public createResponse() { return new RegisterResponse(); } public getTypeName() { return 'Register'; } }
the_stack
import * as tfc from '@tensorflow/tfjs-core'; import {Tensor} from '@tensorflow/tfjs-core'; import {serializeActivation, Tanh} from '../activations'; import {NonNeg, serializeConstraint, UnitNorm} from '../constraints'; import {sequential} from '../exports'; import * as tfl from '../index'; import {GlorotUniform, HeUniform, Ones, serializeInitializer} from '../initializers'; import {DataFormat, PaddingMode} from '../keras_format/common'; import {modelFromJSON} from '../models'; import {L1L2, serializeRegularizer} from '../regularizers'; import {getCartesianProductOfValues} from '../utils/generic_utils'; import {convertPythonicToTs, convertTsToPythonic} from '../utils/serialization_utils'; import {describeMathCPU, describeMathCPUAndGPU, describeMathCPUAndWebGL2, expectTensorsClose} from '../utils/test_utils'; import {ConvLSTM2DArgs, ConvLSTM2DCellArgs} from './convolutional_recurrent'; describeMathCPUAndGPU('ConvLSTM2DCell', () => { /** * The tensor values (output, h, c) can be obtained by the following Python * code * * sequence_len = 1 * data_size = 8 * data_channel = 3 * * data_format = "channels_first" * filters = 9 * kernel_size = 5 * padding = "same" * * inputs = np.ones([1, sequence_len, data_channel, data_size, data_size]) * * x = keras.Input(batch_shape=inputs.shape) * * kwargs = {'data_format': data_format, * 'return_state': True, * 'filters': filters, * 'kernel_size': kernel_size, * 'padding': padding} * * layer = keras.layers.ConvLSTM2D(kernel_initializer='ones', * bias_initializer="ones", recurrent_initializer='ones', **kwargs) * layer.build(inputs.shape) * * outputs = layer(x) * * model = keras.models.Model(x, outputs) * * y = model.predict(inputs) * * y[0].mean(), y[1].mean(), y[2].mean() */ describe('should return the correct outputs', () => { const sequenceLength = 1; const inputSize = 8; const channels = 3; const dataFormatValues: DataFormat[] = ['channelsFirst', 'channelsLast']; const filterValues = [3, 5, 9]; const kernelSizeValues = [3, 5]; const paddingValues: PaddingMode[] = ['valid', 'same']; const testArgs = getCartesianProductOfValues( dataFormatValues, filterValues, kernelSizeValues, paddingValues, ) as Array<[DataFormat, number, number, PaddingMode]>; for (const [dataFormat, filters, kernelSize, padding] of testArgs) { const testTitle = `for dataFormat=${dataFormat}, filters=${ filters}, kernelSize=${kernelSize}, padding=${padding}`; it(testTitle, () => { const inputShape = dataFormat === 'channelsFirst' ? [sequenceLength, channels, inputSize, inputSize] : [sequenceLength, inputSize, inputSize, channels]; const x = tfc.ones(inputShape); const cell = tfl.layers.convLstm2dCell({ dataFormat, filters, kernelSize, padding, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'ones', }); cell.build(x.shape); const outputSize = padding === 'same' ? inputSize : (inputSize - kernelSize + 1); const outShape = dataFormat === 'channelsFirst' ? [sequenceLength, filters, outputSize, outputSize] : [sequenceLength, outputSize, outputSize, filters]; const initialH = tfc.zeros(outShape); const initialC = tfc.zeros(outShape); const [o, h, c] = cell.call([x, initialH, initialC], {}); expect(o.shape).toEqual(outShape); expect(h.shape).toEqual(outShape); expect(c.shape).toEqual(outShape); expectTensorsClose(o.mean().flatten(), tfc.tensor1d([0.7615942])); expectTensorsClose(h.mean().flatten(), tfc.tensor1d([0.7615942])); expectTensorsClose(c.mean().flatten(), tfc.tensor1d([1])); }); } }); }); describeMathCPU('ConvLSTM2D Symbolic', () => { const dtype = 'float32'; const batchSize = 8; const sequenceLength = 10; const inputSize = 8; const channels = 3; const inputShape = [ batchSize, sequenceLength, inputSize, inputSize, channels, ]; const filters = 5; const kernelSize = [3, 3]; const outputSize = inputSize - kernelSize[0] + 1; describe('should return the correct output shape', () => { it('for returnSequences=false, returnState=false', () => { const input = new tfl.SymbolicTensor('float32', inputShape, null, [], null); const convLstm = tfl.layers.convLstm2d({filters, kernelSize}); const output = convLstm.apply(input) as tfl.SymbolicTensor; expect(output.shape).toEqual([8, 6, 6, 5]); }); it('for returnSequences=false, returnState=true', () => { const returnState = true; const input = new tfl.SymbolicTensor(dtype, inputShape, null, [], null); const convLstm = tfl.layers.convLstm2d({filters, kernelSize, returnState}); const output = convLstm.apply(input) as tfl.SymbolicTensor[]; const outputShape = [batchSize, outputSize, outputSize, filters]; expect(output.length).toEqual(3); expect(output[0].shape).toEqual(outputShape); expect(output[1].shape).toEqual(outputShape); expect(output[2].shape).toEqual(outputShape); }); it('for returnSequences=true, returnState=false', () => { const returnSequences = true; const input = new tfl.SymbolicTensor(dtype, inputShape, null, [], null); const convLstm = tfl.layers.convLstm2d({filters, kernelSize, returnSequences}); const output = convLstm.apply(input) as tfl.SymbolicTensor; const outputShape = [batchSize, sequenceLength, outputSize, outputSize, filters]; expect(output.shape).toEqual(outputShape); }); it('for returnSequences=true, returnState=true', () => { const returnSequences = true; const returnState = true; const input = new tfl.SymbolicTensor(dtype, inputShape, null, [], null); const convLstm = tfl.layers.convLstm2d( {filters, kernelSize, returnSequences, returnState}); const output = convLstm.apply(input) as tfl.SymbolicTensor[]; const outputShape = [batchSize, sequenceLength, outputSize, outputSize, filters]; const stateShape = [batchSize, outputSize, outputSize, filters]; expect(output.length).toEqual(3); expect(output[0].shape).toEqual(outputShape); expect(output[1].shape).toEqual(stateShape); expect(output[2].shape).toEqual(stateShape); }); }); it('should contain the correct number of weights', () => { const input = new tfl.SymbolicTensor(dtype, inputShape, null, [], null); const convLstm = tfl.layers.convLstm2d( {filters, kernelSize, returnSequences: true, returnState: true}); convLstm.apply(input); expect(convLstm.trainable).toEqual(true); expect(convLstm.trainableWeights.length).toEqual(3); expect(convLstm.nonTrainableWeights.length).toEqual(0); expect(convLstm.weights.length).toEqual(3); }); describe('should build the correct layer from exported config', () => { for (const implementation of [1, 2]) { it(`for implementation=${implementation}`, () => { const layer = tfl.layers.convLstm2d({ filters, kernelSize, inputShape: inputShape.slice(1), implementation, padding: 'same', returnSequences: true, }); const pythonicConfig = convertTsToPythonic(layer.getConfig()); const tsConfig = convertPythonicToTs(pythonicConfig); const layerPrime = tfl.layers.convLstm2d(tsConfig as unknown as ConvLSTM2DArgs); expect(layerPrime.getConfig().filters).toEqual(filters); expect(layerPrime.getConfig().kernelSize).toEqual(kernelSize); expect(layerPrime.getConfig().implementation).toEqual(implementation); }); } }); describe('should return equal outputs with loaded model', () => { it('for simple model', async () => { const model = tfl.sequential(); const layer = tfl.layers.convLstm2d({ filters, kernelSize, padding: 'same', inputShape: inputShape.slice(1), returnSequences: true, }); model.add(layer); const x = tfc.randomNormal(inputShape); const y = model.predict(x) as tfc.Tensor; let savedArtifacts: tfc.io.ModelArtifacts; await model.save(tfc.io.withSaveHandler(async (artifacts) => { savedArtifacts = artifacts; return null; })); const loadedModel = await tfl.loadLayersModel(tfc.io.fromMemory(savedArtifacts)); const yPrime = loadedModel.predict(x) as tfc.Tensor; expect(model.inputs[0].shape).toEqual(loadedModel.inputs[0].shape); expect(model.outputs[0].shape).toEqual(loadedModel.outputs[0].shape); expectTensorsClose(yPrime, y); }); it('for more complex model', async () => { const model = tfl.sequential(); model.add(tfl.layers.convLstm2d({ filters, kernelSize, inputShape: inputShape.slice(1), })); model.add(tfl.layers.dropout({rate: 0.2})); model.add(tfl.layers.flatten()); model.add(tfl.layers.dense({units: 256, activation: 'relu'})); model.add(tfl.layers.dropout({rate: 0.3})); model.add(tfl.layers.dense({units: 6, activation: 'softmax'})); const x = tfc.randomNormal(inputShape); const y = model.predict(x) as tfc.Tensor; let savedArtifacts: tfc.io.ModelArtifacts; await model.save(tfc.io.withSaveHandler(async (artifacts) => { savedArtifacts = artifacts; return null; })); const loadedModel = await tfl.loadLayersModel(tfc.io.fromMemory(savedArtifacts)); const yPrime = loadedModel.predict(x) as tfc.Tensor; expect(model.inputs[0].shape).toEqual(loadedModel.inputs[0].shape); expect(model.outputs[0].shape).toEqual(loadedModel.outputs[0].shape); expectTensorsClose(yPrime, y); }); }); }); describeMathCPUAndWebGL2('ConvLSTM2D Tensor', () => { const filters = 5; const kernelSize = 3; const batchSize = 4; const sequenceLength = 2; const inputSize = 5; const channels = 3; const inputShape = [batchSize, sequenceLength, inputSize, inputSize, channels]; const outputSize = inputSize - kernelSize + 1; describe('should run as expected', () => { const dropoutValues = [0.0, 0.1]; const recurrentDropoutValues = [0.0, 0.1]; const trainingValues = [true, false]; const implementationValues = [1, 2]; const args = getCartesianProductOfValues( dropoutValues, recurrentDropoutValues, trainingValues, implementationValues, ) as Array<[number, number, boolean, number]>; for (const [dropout, recurrentDropout, training, implementation] of args) { const testTitle = `for dropout=${dropout}, recurrentDropout=${ recurrentDropout},implementation=${implementation}, training=${ training}, implementation=${implementation}`; it(testTitle, () => { const dropoutFunc = jasmine.createSpy('dropout').and.callFake( (x: Tensor, level: number, noiseShape?: number[], seed?: number) => tfc.tidy(() => tfc.dropout(x, level, noiseShape, seed))); const convLstm = tfl.layers.convLstm2d({ filters, kernelSize, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'ones', dropout, recurrentDropout, implementation, dropoutFunc, }); const input = tfc.ones(inputShape); let dropoutCall = 0; if (dropout !== 0.0 && training) { dropoutCall += 4; } if (recurrentDropout !== 0.0 && training) { dropoutCall += 4; } let numTensors = 0; for (let i = 0; i < 2; i++) { tfc.dispose(convLstm.apply(input, {training}) as tfc.Tensor); expect(dropoutFunc).toHaveBeenCalledTimes((i + 1) * dropoutCall); if (i === 0) { numTensors = tfc.memory().numTensors; } else { expect(tfc.memory().numTensors).toEqual(numTensors); } } }); } it('for stateful forward'); }); describe('should return the correct outputs', () => { const returnStateValues = [true, false]; const returnSequencesValues = [true, false]; const implementationValues = [1, 2]; const args = getCartesianProductOfValues( returnStateValues, returnSequencesValues, implementationValues, ) as Array<[boolean, boolean, number]>; for (const [returnState, returnSequences, implementation] of args) { const testTitle = `for returnState=${returnState}, returnSequences=${ returnSequences}, implementation=${implementation}`; it(testTitle, () => { const convLstm = tfl.layers.convLstm2d({ filters, kernelSize, returnState, returnSequences, implementation, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'ones', }); const input = tfc.ones(inputShape); let output = convLstm.apply(input); const expectedOutputValueAtT0 = 0.76159424; const expectedOutputValueAtT1 = 0.96402746; const expectedH = expectedOutputValueAtT1; const expectedC = 2.0; let expectedOutput: tfc.Tensor; if (returnSequences) { const outputAtT0 = tfc.mul( tfc.scalar(expectedOutputValueAtT0), tfc.ones([batchSize, 1, outputSize, outputSize, filters])); const outputAtT1 = tfc.mul( tfc.scalar(expectedOutputValueAtT1), tfc.ones([batchSize, 1, outputSize, outputSize, filters])); expectedOutput = tfc.concat([outputAtT0, outputAtT1], 1); } else { expectedOutput = tfc.mul( tfc.scalar(expectedOutputValueAtT1), tfc.ones([batchSize, outputSize, outputSize, filters])); } if (returnState) { output = output as tfc.Tensor[]; expect(output.length).toEqual(3); expectTensorsClose(output[0], expectedOutput); expectTensorsClose( output[1], tfc.mul( tfc.scalar(expectedH), tfc.ones([batchSize, outputSize, outputSize, filters]))); expectTensorsClose( output[2], tfc.mul( tfc.scalar(expectedC), tfc.ones([batchSize, outputSize, outputSize, filters]))); } else { output = output as tfc.Tensor; expectTensorsClose(output, expectedOutput); } }); } it('for nested model', () => { const model = tfl.sequential(); const nestedModel = tfl.sequential(); nestedModel.add(tfl.layers.convLstm2d({ filters, kernelSize, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'ones', batchInputShape: inputShape })); model.add(nestedModel); const input = tfc.ones(inputShape); const output = model.apply(input) as tfc.Tensor; const expectedOutput = tfc.mul( tfc.scalar(0.96402746), tfc.ones([batchSize, outputSize, outputSize, filters])); expectTensorsClose(output, expectedOutput); }); }); }); // TODO: Add GPU test once Gather supports 5 rank tensor. describeMathCPU('should run BPTT correctly', () => { const filters = 3; const kernelSize = 3; const padding = 'same'; const batchSize = 4; const sequenceLength = 2; const inputSize = 5; const channels = 1; const inputShape = [batchSize, sequenceLength, inputSize, inputSize, channels]; /** * batch_size = 4 * sequence_len = 2 * data_size = 5 * data_channel = 1 * * filters = 3 * kernel_size = 3 * padding = "same" * * kwargs = {'filters': filters, 'kernel_size': kernel_size, 'padding': * padding, 'batch_input_shape': [batch_size, sequence_len, data_size, * data_size, data_channel], 'stateful': True} * * model = keras.Sequential() * * model.add(keras.layers.ConvLSTM2D(kernel_initializer='ones', * bias_initializer="ones", recurrent_initializer='ones', **kwargs)) * * model.add(keras.layers.Flatten()) * * model.add(keras.layers.Dense(units=1, kernel_initializer='zeros', * use_bias=False)) * * model.compile(loss='mean_squared_error', optimizer='sgd') * * xs_1 = np.ones([batch_size, sequence_len, data_size, data_size, * data_channel]) * xs_2 = np.zeros([batch_size, sequence_len, data_size, data_size, * data_channel]) * xs = np.concatenate([xs_1, xs_2], 0) * * ys = np.array([[1], [1], [1], [1], [0], [0], [0], [0]]) * * history = model.fit(xs, ys, batch_size=batch_size, shuffle=False, epochs=3) * print(history.history) */ it('for stateful BPTT', async () => { const model = tfl.sequential(); model.add(tfl.layers.convLstm2d({ filters, kernelSize, padding, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'ones', stateful: true, batchInputShape: inputShape })); model.add(tfl.layers.flatten()); model.add(tfl.layers.dense( {units: 1, kernelInitializer: 'zeros', useBias: false})); model.compile({loss: 'meanSquaredError', optimizer: 'sgd'}); const input = tfc.concat([tfc.ones(inputShape), tfc.zeros(inputShape)], 0); const output = tfc.tensor([1, 1, 1, 1, 0, 0, 0, 0]); const history = await model.fit(input, output, {batchSize, shuffle: false, epochs: 3}); expect(history.history.loss.length).toBe(3); expect(history.history.loss[0]).toBeCloseTo(1.5441135168075562); expect(history.history.loss[1]).toBeCloseTo(3.209195613861084); expect(history.history.loss[2]).toBeCloseTo(3.7930736541748047); }); /** * batch_size = 4 * sequence_len = 2 * data_size = 5 * data_channel = 1 * * filters = 3 * kernel_size = 3 * padding = "same" * * kwargs = {'filters': filters, 'kernel_size': kernel_size, 'padding': * padding, 'batch_input_shape': [batch_size, sequence_len, data_size, * data_size, data_channel]} * * model = keras.Sequential() * * model.add(keras.layers.ConvLSTM2D(kernel_initializer='ones', * bias_initializer="ones", recurrent_initializer='ones', **kwargs)) * * model.add(keras.layers.Flatten()) * * model.add(keras.layers.Dense(units=1, kernel_initializer='zeros', * use_bias=False)) * * model.compile(loss='mean_squared_error', optimizer='sgd') * * xs_1 = np.ones([batch_size, sequence_len, data_size, data_size, * data_channel]) * xs_2 = np.zeros([batch_size, sequence_len, data_size, * data_size, data_channel]) * xs = np.concatenate([xs_1, xs_2], 0) * * ys = np.array([[1], [1], [1], [1], [0], [0], [0], [0]]) * * history = model.fit(xs, ys, batch_size=batch_size, shuffle=False, epochs=3) * print(history.history) */ it('for normal BPTT', async () => { const model = tfl.sequential(); model.add(tfl.layers.convLstm2d({ filters, kernelSize, padding, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'ones', batchInputShape: inputShape })); model.add(tfl.layers.flatten()); model.add(tfl.layers.dense( {units: 1, kernelInitializer: 'zeros', useBias: false})); model.compile({loss: 'meanSquaredError', optimizer: 'sgd'}); const input = tfc.concat([tfc.ones(inputShape), tfc.zeros(inputShape)], 0); const output = tfc.tensor([1, 1, 1, 1, 0, 0, 0, 0]); const history = await model.fit(input, output, {batchSize, shuffle: false, epochs: 3}); expect(history.history.loss.length).toBe(3); expect(history.history.loss[0]).toBeCloseTo(1.367607831954956); expect(history.history.loss[1]).toBeCloseTo(1.9423290491104126); expect(history.history.loss[2]).toBeCloseTo(2.00433349609375); }); /** * batch_size = 4 * sequence_len = 2 * data_size = 5 * data_channel = 1 * * filters = 3 * kernel_size = 3 * padding = "same" * * kwargs = {'filters': filters, 'kernel_size': kernel_size, 'padding': * padding, 'batch_input_shape': [batch_size, sequence_len, data_size, * data_size, data_channel]} * * model = keras.Sequential() * * model.add(keras.layers.ConvLSTM2D(kernel_initializer='ones', * bias_initializer="ones", recurrent_initializer='ones', **kwargs)) * * model.add(keras.layers.Flatten()) * * model.add(keras.layers.Dense(units=1, kernel_initializer='zeros', * use_bias=False)) * * model.compile(loss='mean_squared_error', optimizer='sgd') * * xs_1 = np.ones([batch_size, sequence_len, data_size, data_size, * data_channel]) * xs_2 = np.zeros([batch_size, sequence_len, data_size, * data_size, data_channel]) * xs = np.concatenate([xs_1, xs_2], 0) * * ys = np.array([[1], [1], [1], [1], [0], [0], [0], [0]]) * * model.fit(xs, ys, batch_size=batch_size, shuffle=False, epochs=2) * * history = model.fit(xs, ys, batch_size=batch_size, shuffle=False, epochs=3) * print(history.history) */ it('with no leak', async () => { const model = tfl.sequential(); model.add(tfl.layers.convLstm2d({ filters, kernelSize, padding, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'ones', batchInputShape: inputShape })); model.add(tfl.layers.flatten()); model.add(tfl.layers.dense( {units: 1, kernelInitializer: 'zeros', useBias: false})); model.compile({loss: 'meanSquaredError', optimizer: 'sgd'}); const input = tfc.concat([tfc.ones(inputShape), tfc.zeros(inputShape)], 0); const output = tfc.tensor([1, 1, 1, 1, 0, 0, 0, 0]); // Serves as burn-in call for subsequent tracking of memory leak. await model.fit(input, output, {epochs: 2, batchSize, shuffle: false}); const numTensors0 = tfc.memory().numTensors; const history = await model.fit(input, output, {epochs: 3, batchSize, shuffle: false}); const numTensors1 = tfc.memory().numTensors; // Assert no memory leak. expect(numTensors1).toEqual(numTensors0); expect(history.history.loss.length).toEqual(3); expect(history.history.loss[0]).toBeCloseTo(2.00433349609375); expect(history.history.loss[1]).toBeCloseTo(2.0098776817321777); expect(history.history.loss[2]).toBeCloseTo(2.0099055767059326); }); }); describeMathCPU('ConvLSTM2D Serialization and Deserialization', () => { const cellConfig: ConvLSTM2DCellArgs = { filters: 32, kernelSize: 3, dataFormat: 'channelsLast', dilationRate: 2, padding: 'same', strides: 2, activation: 'tanh', recurrentActivation: 'tanh', useBias: true, kernelInitializer: 'glorotUniform', recurrentInitializer: 'heUniform', biasInitializer: 'ones', kernelRegularizer: 'l1l2', recurrentRegularizer: 'l1l2', biasRegularizer: 'l1l2', kernelConstraint: 'unitNorm', recurrentConstraint: 'unitNorm', biasConstraint: 'nonNeg', dropout: 0.1, recurrentDropout: 0.2, name: 'cell_1', batchSize: 12, batchInputShape: [12, 8, 8], inputShape: [8, 8], dtype: 'int32', inputDType: 'int32', trainable: true, implementation: 1, unitForgetBias: true, }; const expectedCellConfigPrime = { name: 'cell_1', trainable: true, batchInputShape: [12, 8, 8], dtype: 'int32', filters: 32, kernelSize: [3, 3], dataFormat: 'channelsLast', dilationRate: [2, 2], padding: 'same', strides: [2, 2], activation: serializeActivation(new Tanh()), recurrentActivation: serializeActivation(new Tanh()), useBias: true, kernelInitializer: serializeInitializer(new GlorotUniform()), recurrentInitializer: serializeInitializer(new HeUniform()), biasInitializer: serializeInitializer(new Ones()), kernelRegularizer: serializeRegularizer(new L1L2()), recurrentRegularizer: serializeRegularizer(new L1L2()), biasRegularizer: serializeRegularizer(new L1L2()), activityRegularizer: serializeRegularizer(null), kernelConstraint: serializeConstraint(new UnitNorm({})), recurrentConstraint: serializeConstraint(new UnitNorm({})), biasConstraint: serializeConstraint(new NonNeg()), implementation: 1, unitForgetBias: true, }; describe('ConvLSTM2DCell.getConfig', () => { it('should return the expected values', () => { const cell = tfl.layers.convLstm2dCell(cellConfig); const {dropout, recurrentDropout, ...configPrime} = cell.getConfig(); expect(configPrime).toEqual(expectedCellConfigPrime); expect(dropout).toBeCloseTo(0.1); expect(recurrentDropout).toBeCloseTo(0.2); }); }); describe('ConvLSTM2D.getConfig', () => { it('should return the expected values', () => { const config: ConvLSTM2DArgs = { ...cellConfig, name: 'layer_1', ...{ returnSequences: true, returnState: true, stateful: true, unroll: false, goBackwards: true, inputDim: 8, inputLength: 8, } as Omit<ConvLSTM2DArgs, keyof ConvLSTM2DCellArgs> }; const cell = tfl.layers.convLstm2d(config); const {dropout, recurrentDropout, ...configPrime} = cell.getConfig(); expect(configPrime).toEqual({ ...expectedCellConfigPrime, name: 'layer_1', returnSequences: true, returnState: true, stateful: true, unroll: false, goBackwards: true, }); expect(dropout).toBeCloseTo(0.1); expect(recurrentDropout).toBeCloseTo(0.2); }); }); it('should return equal outputs before and after', async () => { const model = sequential(); const batchSize = 8; const sequenceLength = 1; const inputSize = 8; const channels = 3; const filters = 5; const kernelSize = 3; const layer = tfl.layers.convLstm2d({ filters, kernelSize, kernelInitializer: 'ones', recurrentInitializer: 'ones', returnSequences: true, dataFormat: 'channelsFirst', inputShape: [sequenceLength, channels, inputSize, inputSize] }); model.add(layer); const x = tfc.ones([batchSize, sequenceLength, channels, inputSize, inputSize]); const y = model.predict(x) as tfc.Tensor; const json = model.toJSON(null, false); const modelPrime = await modelFromJSON({modelTopology: json}); const yPrime = modelPrime.predict(x) as tfc.Tensor; expectTensorsClose(yPrime, y); }); });
the_stack
import {OasValidationRule} from "./common.rule" import {Oas20Parameter} from "../../models/2.0/parameter.model"; import {Oas20Document} from "../../models/2.0/document.model"; import {Oas20Operation} from "../../models/2.0/operation.model"; import {Oas20XML} from "../../models/2.0/xml.model"; import {Oas20PathItem} from "../../models/2.0/path-item.model"; import {Oas20Schema} from "../../models/2.0/schema.model"; import {Oas20Scopes} from "../../models/2.0/scopes.model"; import {OasValidationRuleUtil, PathSegment} from "../validation" import {OasOperation} from "../../models/common/operation.model"; import {Oas30Parameter, Oas30ParameterDefinition} from "../../models/3.0/parameter.model"; import {Oas20Items} from "../../models/2.0/items.model"; import {Oas20Header} from "../../models/2.0/header.model"; import {Oas20SecurityScheme} from "../../models/2.0/security-scheme.model"; import {Oas30SecurityScheme} from "../../models/3.0/security-scheme.model"; import {Oas20SecurityRequirement} from "../../models/2.0/security-requirement.model"; import {Oas20SecurityDefinitions} from "../../models/2.0/security-definitions.model"; import {Oas30XML} from "../../models/3.0/xml.model"; import {Oas30Schema} from "../../models/3.0/schema.model"; import {Oas30Operation} from "../../models/3.0/operation.model"; import {Oas30Encoding} from "../../models/3.0/encoding.model"; import {Oas30MediaType} from "../../models/3.0/media-type.model"; import {Oas30Header, Oas30HeaderDefinition} from "../../models/3.0/header.model"; import {Oas30Link, Oas30LinkDefinition} from "../../models/3.0/link.model"; import {OasVisitorUtil} from "../../visitors/visitor.utils"; import {Oas30PathItem} from "../../models/3.0/path-item.model"; import {ReferenceUtil} from "../../util"; import {Oas30Responses} from "../../models/3.0/responses.model"; import {Oas30Discriminator} from "../../models/3.0/discriminator.model"; import {Oas30SecurityRequirement} from "../../models/3.0/security-requirement.model"; import {Oas30ServerVariable} from "../../models/3.0/server-variable.model"; import {Oas30Server} from "../../models/3.0/server.model"; import {OasDocument} from "../../models/document.model"; import {Oas30Document} from "../../models/3.0/document.model"; import {Oas30NodeVisitorAdapter} from "../../visitors/visitor.base"; /** * Used to find an operation with a given operation id. */ export class Oas30OperationFinder extends Oas30NodeVisitorAdapter { private foundOp: Oas30Operation; constructor(private operationId: string) { super(); } public visitOperation(node: Oas30Operation): void { if (node.operationId === this.operationId) { this.foundOp = node; } } public isFound(): boolean { return OasValidationRuleUtil.hasValue(this.foundOp); } } /** * Base class for all Invalid Property Value rules. */ export abstract class OasInvalidPropertyValueRule extends OasValidationRule { /** * Returns true if the given media type name is multipart/* or application/x-www-form-urlencoded * @param {string} typeName * @return {boolean} */ protected isValidMultipartType(typeName: string): boolean { return typeName === "application/x-www-form-urlencoded" || typeName.indexOf("multipart") === 0; } /** * Merges all parameters applicable for an operation - those defined within the operation and those defined at the pathItem level. * Resolves parameters that are not defined inline but are referenced from the components/parameters section. * @param {Oas30Operation} - Operation for which to merge parameters. * @return {Oas30Parameter[]} - array of merged paramters. */ protected mergeParameters(node: Oas30Operation): Oas30Parameter[] { const paramsKey = {}; const parentNode = <Oas30PathItem>node.parent(); // Get the parameters from pathItem if (this.hasValue(parentNode.parameters)) { parentNode.parameters.forEach(param => { const resolutionResult: Oas30Parameter = <Oas30Parameter>ReferenceUtil.resolveNodeRef(param); if (resolutionResult) { const key: string = `${resolutionResult.in}-${resolutionResult.name}`; paramsKey[key] = resolutionResult; } }); } // Overwrite parameters from parent if (this.hasValue(node.parameters)) { node.parameters.forEach(param => { const resolutionResult: Oas30Parameter = <Oas30Parameter>ReferenceUtil.resolveNodeRef(param); if (resolutionResult) { const key: string = `${resolutionResult.in}-${resolutionResult.name}`; paramsKey[key] = resolutionResult; } }); } const mergedParameters:Oas30Parameter[] = [] for(let key in paramsKey) { mergedParameters.push(paramsKey[key]); } return mergedParameters; } } /** * Implements the XXX rule. */ export class OasInvalidApiSchemeRule extends OasInvalidPropertyValueRule { public visitDocument(node: Oas20Document): void { if (this.hasValue(node.schemes)) { node.schemes.forEach(scheme => { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(scheme, ["http", "https", "ws", "wss"]), node, "schemes", { scheme: scheme }); }); } } } /** * Implements the Invalid API 'Consumes' Mime-Type rule. */ export class OasInvalidApiConsumesMTRule extends OasInvalidPropertyValueRule { public visitDocument(node: Oas20Document): void { if (this.hasValue(node.consumes)) { this.reportIfInvalid(OasValidationRuleUtil.isValidMimeType(node.consumes), node, "consumes"); } } } /** * Implements the Invalid API 'Produces' Mime-Type rule. */ export class OasInvalidApiProducesMTRule extends OasInvalidPropertyValueRule { public visitDocument(node: Oas20Document): void { if (this.hasValue(node.produces)) { this.reportIfInvalid(OasValidationRuleUtil.isValidMimeType(node.produces), node, "produces"); } } } /** * Implements the Operation Summary Too Long rule. */ export class OasOperationSummaryTooLongRule extends OasInvalidPropertyValueRule { public visitOperation(node: OasOperation): void { if (this.hasValue(node.summary)) { this.reportIfInvalid(node.summary.length < 120, node, "summary"); } } } /** * Implements the Invalid Operation ID rule. */ export class OasInvalidOperationIdRule extends OasInvalidPropertyValueRule { /** * Returns true if the given value is a valid operationId. * @param id */ protected isValidOperationId(id: string): boolean { // TODO implement a regex for this? should be something like camelCase return true; } public visitOperation(node: Oas20Operation): void { if (this.hasValue(node.operationId)) { this.reportIfInvalid(this.isValidOperationId(node.operationId), node, "operationId"); } } } /** * Implements the Invalid Operation Scheme rule. */ export class OasInvalidOperationSchemeRule extends OasInvalidPropertyValueRule { public visitOperation(node: Oas20Operation): void { if (this.hasValue(node.schemes)) { node.schemes.forEach( scheme => { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(scheme, ["http", "https", "ws", "wss"]), node, "schemes", { scheme: scheme }); }); } } } /** * Implements the Path Parameter Not Found rule. */ export class OasPathParamNotFoundRule extends OasInvalidPropertyValueRule { public visitParameter(node: Oas20Parameter | Oas30Parameter): void { let resolvedParam: Oas20Parameter | Oas30Parameter = <Oas20Parameter | Oas30Parameter>ReferenceUtil.resolveNodeRef(node); if (this.hasValue(resolvedParam) && resolvedParam.in === "path") { // Note: parent may be an operation *or* a path-item. let pathItem: Oas20PathItem; if (node.parent()["_path"]) { pathItem = node.parent() as Oas20PathItem; } else { pathItem = node.parent().parent() as Oas20PathItem; } let path: string = pathItem.path(); let pathSegs: PathSegment[] = this.getPathSegments(path); this.reportIfInvalid(pathSegs.filter(pathSeg => pathSeg.formalName === resolvedParam.name).length > 0, node, "name", { name: resolvedParam.name }); } } } /** * Implements the Form Data Parameter Not Allowed rule. */ export class OasFormDataParamNotAllowedRule extends OasInvalidPropertyValueRule { public visitParameter(node: Oas20Parameter): void { if (node.in === "formData") { let consumes: string[] = (node.ownerDocument() as Oas20Document).consumes; if (!node.parent()["_path"]) { let operation: Oas20Operation = (node.parent() as Oas20Operation); if (this.hasValue(operation.consumes)) { consumes = operation.consumes; } } if (!this.hasValue(consumes)) { consumes = []; } let valid: boolean = consumes.indexOf("application/x-www-form-urlencoded") >= 0 || consumes.indexOf("multipart/form-data") >= 0; this.reportIfInvalid(valid, node, "consumes"); } } } /** * Implements the Unknown Parameter Location rule. */ export class OasUnknownParamLocationRule extends OasInvalidPropertyValueRule { public visitParameter(node: Oas20Parameter | Oas30Parameter): void { if (this.hasValue(node.in)) { if (node.ownerDocument().is2xDocument()) { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.in, [ "query", "header", "path", "formData", "body" ]), node, "in", { options: "query, header, path, formData, body" }); } else { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.in, [ "query", "header", "path", "cookie" ]), node, "in", { options: "query, header, path, cookie" }); } } } } /** * Implements the Unknown Parameter Type rule. */ export class OasUnknownParamTypeRule extends OasInvalidPropertyValueRule { public visitParameter(node: Oas20Parameter): void { if (this.hasValue(node.type)) { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.type, [ "string", "number", "integer", "boolean", "array", "file" ]), node, "type"); } } } /** * Implements the Unknown Parameter Format rule. */ export class OasUnknownParamFormatRule extends OasInvalidPropertyValueRule { public visitParameter(node: Oas20Parameter): void { if (this.hasValue(node.format)) { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.format, [ "int32", "int64", "float", "double", "byte", "binary", "date", "date-time", "password" ]), node, "format"); } } } /** * Implements the Unexpected Parameter Usage of 'allowEmptyValue' rule. */ export class OasUnexpectedParamAllowEmptyValueRule extends OasInvalidPropertyValueRule { public visitParameter(node: Oas20Parameter | Oas30Parameter): void { if (this.hasValue(node.allowEmptyValue)) { if (node.ownerDocument().is2xDocument()) { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.in, [ "query", "formData" ]), node, "allowEmptyValue", { options: "Query and Form Data" }); } else { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.in, [ "query" ]), node, "allowEmptyValue", { options: "Query" }); } } } } /** * Implements the Unexpected Parameter Usage of 'collectionFormat' rule. */ export class OasUnexpectedParamCollectionFormatRule extends OasInvalidPropertyValueRule { public visitParameter(node: Oas20Parameter): void { if (this.hasValue(node.collectionFormat)) { this.reportIfInvalid(node.type === "array", node, "collectionFormat"); } } } /** * Implements the Unknown Parameter Collection Format rule. */ export class OasUnknownParamCollectionFormatRule extends OasInvalidPropertyValueRule { public visitParameter(node: Oas20Parameter): void { if (this.hasValue(node.collectionFormat)) { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.collectionFormat, [ "csv", "ssv", "tsv", "pipes", "multi" ]), node, "collectionFormat"); } } } /** * Implements the Unexpected Parameter Usage of 'multi' rule. */ export class OasUnexpectedParamMultiRule extends OasInvalidPropertyValueRule { public visitParameter(node: Oas20Parameter): void { if (node.collectionFormat === "multi") { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.in, [ "query", "formData" ]), node, "collectionFormat"); } } } /** * Implements the Required Parameter With Default Value rule. */ export class OasRequiredParamWithDefaultValueRule extends OasInvalidPropertyValueRule { public visitParameter(node: Oas20Parameter): void { if (this.hasValue(node.default)) { this.reportIfInvalid(node.required === undefined || node.required === null || node.required === false, node, "default"); } } } /** * Implements the Unknown Array Type rule. */ export class OasUnknownArrayTypeRule extends OasInvalidPropertyValueRule { public visitItems(node: Oas20Items): void { if (this.hasValue(node.type)) { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.type, [ "string", "number", "integer", "boolean", "array" ]), node, "type"); } } } /** * Implements the Unknown Array Format rule. */ export class OasUnknownArrayFormatRule extends OasInvalidPropertyValueRule { public visitItems(node: Oas20Items): void { if (this.hasValue(node.format)) { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.format, [ "int32", "int64", "float", "double", "byte", "binary", "date", "date-time", "password" ]), node, "format"); } } } /** * Implements the Unknown Array Collection Format rule. */ export class OasUnknownArrayCollectionFormatRule extends OasInvalidPropertyValueRule { public visitItems(node: Oas20Items): void { if (this.hasValue(node.collectionFormat)) { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.collectionFormat, [ "csv", "ssv", "tsv", "pipes" ]), node, "collectionFormat"); } } } /** * Implements the Unexpected Array Usage of 'collectionFormat' rule. */ export class OasUnexpectedArrayCollectionFormatRule extends OasInvalidPropertyValueRule { public visitItems(node: Oas20Items): void { if (this.hasValue(node.collectionFormat)) { this.reportIfInvalid(node.type === "array", node, "collectionFormat"); } } } /** * Implements the Unknown Header Type rule. */ export class OasUnknownHeaderTypeRule extends OasInvalidPropertyValueRule { public visitHeader(node: Oas20Header): void { if (this.hasValue(node.type)) { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.type, [ "string", "number", "integer", "boolean", "array" ]), node, "type"); } } } /** * Implements the Unknown Header Format rule. */ export class OasUnknownHeaderFormatRule extends OasInvalidPropertyValueRule { public visitHeader(node: Oas20Header): void { if (this.hasValue(node.format)) { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.format, [ "int32", "int64", "float", "double", "byte", "binary", "date", "date-time", "password" ]), node, "format"); } } } /** * Implements the Unexpected Header Usage of 'collectionFormat' rule. */ export class OasUnexpectedHeaderCollectionFormatRule extends OasInvalidPropertyValueRule { public visitHeader(node: Oas20Header): void { if (this.hasValue(node.collectionFormat)) { this.reportIfInvalid(node.type === "array", node, "collectionFormat"); } } } /** * Implements the Unknown Header Collection Format rule. */ export class OasUnknownHeaderCollectionFormatRule extends OasInvalidPropertyValueRule { public visitHeader(node: Oas20Header): void { if (this.hasValue(node.collectionFormat)) { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.collectionFormat, [ "csv", "ssv", "tsv", "pipes" ]), node, "collectionFormat"); } } } /** * Implements the Unexpected XML Wrapping rule. */ export class OasUnexpectedXmlWrappingRule extends OasInvalidPropertyValueRule { /** * Returns true if it's OK to use "wrapped" in the XML node. It's only OK to do this if * the type being defined is an 'array' type. * @param xml * @return {boolean} */ protected isWrappedOK(xml: Oas20XML | Oas30XML): boolean { let schema: Oas20Schema | Oas30Schema = xml.parent() as Oas20Schema | Oas30Schema; return schema.type === "array"; } public visitXML(node: Oas20XML): void { if (this.hasValue(node.wrapped)) { this.reportIfInvalid(this.isWrappedOK(node), node, "wrapped"); } } } /** * Implements the Unknown Security Scheme Type rule. */ export class OasUnknownSecuritySchemeTypeRule extends OasInvalidPropertyValueRule { public visitSecurityScheme(node: Oas20SecurityScheme | Oas30SecurityScheme): void { if (this.hasValue(node.type)) { if (node.ownerDocument().is2xDocument()) { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.type, [ "apiKey", "basic", "oauth2" ]), node, "type", { options: "basic, apiKey, oauth2" }); } else { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.type, [ "apiKey", "http", "oauth2", "openIdConnect" ]), node, "type", { options: "http, apiKey, oauth2, openIdConnect" }); } } } } /** * Implements the Unknown API-Key Location rule. */ export class OasUnknownApiKeyLocationRule extends OasInvalidPropertyValueRule { public visitSecurityScheme(node: Oas20SecurityScheme | Oas30SecurityScheme): void { if (this.hasValue(node.in)) { if (node.ownerDocument().is2xDocument()) { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.in, [ "query", "header" ]), node, "in", { options: "query, header" }); } else { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.in, [ "query", "header", "cookie" ]), node, "in", { options: "query, header, cookie" }); } } } } /** * Implements the Unknown OAuth Flow Type rule. */ export class OasUnknownOauthFlowTypeRule extends OasInvalidPropertyValueRule { public visitSecurityScheme(node: Oas20SecurityScheme): void { if (this.hasValue(node.flow)) { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.flow, [ "implicit", "password", "application", "accessCode" ]), node, "flow"); } } } /** * Implements the Security Requirement Scopes Must Be Empty rule. */ export class OasSecurityRequirementScopesMustBeEmptyRule extends OasInvalidPropertyValueRule { private findSecurityScheme(document: OasDocument, schemeName: string): Oas20SecurityScheme | Oas30SecurityScheme { if (document.is2xDocument()) { let doc20: Oas20Document = <Oas20Document>document; if (this.hasValue(doc20.securityDefinitions)) { return doc20.securityDefinitions.securityScheme(schemeName); } } else { let doc30: Oas30Document = <Oas30Document>document; if (this.hasValue(doc30.components)) { return doc30.components.getSecurityScheme(schemeName); } } return null; } public visitSecurityRequirement(node: Oas20SecurityRequirement | Oas30SecurityRequirement): void { let allowedTypes: string[] = [ "oauth2" ]; let options: string = `"oauth2"`; if (node.ownerDocument().is3xDocument()) { allowedTypes.push("openIdConnect"); options = `"oauth2" or "openIdConnect"`; } let snames: string[] = node.securityRequirementNames(); snames.forEach( sname => { let scheme: Oas20SecurityScheme | Oas30SecurityScheme = this.findSecurityScheme(node.ownerDocument(), sname); if (this.hasValue(scheme)) { if (allowedTypes.indexOf(scheme.type) === -1) { let scopes: string[] = node.scopes(sname); this.reportIfInvalid(this.hasValue(scopes) && scopes.length === 0, node, null, { sname: sname, options: options }); } } }); } } /** * Implements the Unexpected Security Requirement Scope(s) rule. */ export class OasUnexpectedSecurityRequirementScopesRule extends OasInvalidPropertyValueRule { /** * Returns true if the given required scopes are all actually defined by the security definition. * @param requiredScopes * @param definedScopes */ protected isValidScopes(requiredScopes: string[], definedScopes: Oas20Scopes) { let rval: boolean = true; let dscopes: string[] = []; if (definedScopes) { dscopes = definedScopes.scopes(); } requiredScopes.forEach( requiredScope => { if (dscopes.indexOf(requiredScope) === -1) { rval = false; } }); return rval; } public visitSecurityRequirement(node: Oas20SecurityRequirement): void { let snames: string[] = node.securityRequirementNames(); snames.forEach( sname => { let sdefs: Oas20SecurityDefinitions = (node.ownerDocument() as Oas20Document).securityDefinitions; if (this.hasValue(sdefs)) { let scheme: Oas20SecurityScheme = (node.ownerDocument() as Oas20Document).securityDefinitions.securityScheme(sname); if (this.hasValue(scheme)) { if (scheme.type === "oauth2") { let definedScopes: Oas20Scopes = scheme.scopes; let requiredScopes: string[] = node.scopes(sname); this.reportIfInvalid(this.isValidScopes(requiredScopes, definedScopes), node, null, { sname: sname }); } } } }); } } /** * Implements the Unexpected Header Usage rule. */ export class OasUnexpectedHeaderUsageRule extends OasInvalidPropertyValueRule { public visitEncoding(node: Oas30Encoding): void { if (node.getHeaders().length > 0) { let mediaType: Oas30MediaType = node.parent() as Oas30MediaType; this.reportIfInvalid(mediaType.name().indexOf("multipart") === 0, node, "headers", { name: mediaType.name() }); } } } /** * Implements the Encoding Style Not Allowed rule. */ export class OasEncodingStyleNotAllowedRule extends OasInvalidPropertyValueRule { public visitEncoding(node: Oas30Encoding): void { if (this.hasValue(node.style)) { let mediaType: Oas30MediaType = node.parent() as Oas30MediaType; this.reportIfInvalid(mediaType.name().indexOf("application/x-www-form-urlencoded") === 0, node, "style", { name: mediaType.name() }); } } } /** * Implements the Explode Not Allowed rule. */ export class OasExplodeNotAllowedRule extends OasInvalidPropertyValueRule { public visitEncoding(node: Oas30Encoding): void { if (this.hasValue(node.explode)) { let mediaType: Oas30MediaType = node.parent() as Oas30MediaType; this.reportIf(mediaType.name() !== "application/x-www-form-urlencoded", node, "explode", { name: mediaType.name() }); } } } /** * Implements the Allow Reserved Not Allowed rule. */ export class OasAllowReservedNotAllowedRule extends OasInvalidPropertyValueRule { public visitEncoding(node: Oas30Encoding): void { if (this.hasValue(node.allowReserved)) { let mediaType: Oas30MediaType = node.parent() as Oas30MediaType; this.reportIf(mediaType.name() !== "application/x-www-form-urlencoded", node, "allowReserved", { name: mediaType.name() }); } } } /** * Implements the Unknown Encoding Style rule. */ export class OasUnknownEncodingStyleRule extends OasInvalidPropertyValueRule { public visitEncoding(node: Oas30Encoding): void { if (this.hasValue(node.style)) { let valid = OasValidationRuleUtil.isValidEnumItem(node.style, ["form", "spaceDelimited", "pipeDelimited", "deepObject"]); this.reportIfInvalid(valid, node, "style"); } } } export class OasInvalidHeaderStyleRule extends OasInvalidPropertyValueRule { public visitHeader(node: Oas30Header): void { if (this.hasValue(node.style)) { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.style, ["simple"]), node, "style"); } } public visitHeaderDefinition(node: Oas30HeaderDefinition): void { this.visitHeader(node); } } export class OasUnexpectedNumberOfHeaderMTsRule extends OasInvalidPropertyValueRule { public visitHeader(node: Oas30Header): void { this.reportIfInvalid(node.getMediaTypes().length < 2, node, "content"); } public visitHeaderDefinition(node: Oas30HeaderDefinition): void { this.visitHeader(node); } } export class OasInvalidLinkOperationIdRule extends OasInvalidPropertyValueRule { // TODO move this to the invalid reference section public visitLink(node: Oas30Link): void { if (this.hasValue(node.operationId)) { let opFinder: Oas30OperationFinder = new Oas30OperationFinder(node.operationId); OasVisitorUtil.visitTree(node.ownerDocument(), opFinder); this.reportIfInvalid(opFinder.isFound(), node, "operationId"); } } public visitLinkDefinition(node: Oas30LinkDefinition): void { this.visitLink(node); } } export class OasInvalidEncodingForMPMTRule extends OasInvalidPropertyValueRule { public visitMediaType(node: Oas30MediaType): void { if (node.getEncodings().length > 0) { this.reportIfInvalid(this.isValidMultipartType(node.name()), node, "encoding", { name: node.name() }); } } } export class OasUnexpectedRequestBodyRule extends OasInvalidPropertyValueRule { /** * Returns true if the given operation is one of: POST, PUT, OPTIONS * @param {Oas30Operation} operation * @return {boolean} */ protected isValidRequestBodyOperation(operation: Oas30Operation): boolean { let method: string = operation.method(); return method === "put" || method === "post" || method === "options" || method === "patch"; } public visitOperation(node: Oas30Operation): void { if (this.hasValue(node.requestBody)) { this.reportIfInvalid(this.isValidRequestBodyOperation(node), node, "requestBody", { method: node.method().toUpperCase() }); } } } export class OasMissingPathParamDefinitionRule extends OasInvalidPropertyValueRule { private pathItemsWithError: string[] = []; public visitPathItem(node: Oas30PathItem): void { if (!this.isPathWellFormed(node.path())) { this.pathItemsWithError.push(node.path()); } } public visitOperation(node: Oas30Operation): void { // Perform operation level checks only if there are no issues at the pathItem level. if (this.pathItemsWithError.indexOf((<Oas30PathItem>node.parent()).path()) !== -1) { return; } // Check parameters are unique within operation const mergedParameters = this.mergeParameters(node); let pathItem: Oas30PathItem = node.parent() as Oas30PathItem; let path: string = pathItem.path(); let pathSegs: PathSegment[] = this.getPathSegments(path); // Report all the path segments that don't have an associated parameter definition pathSegs.filter(pathSeg => { return pathSeg.formalName !== undefined; }).forEach(pathSeg => { let valid: boolean = mergedParameters.filter((param) => { return pathSeg.formalName === param.name && param.in === 'path'; }).length > 0; this.reportIfInvalid(valid, node,null, { param: pathSeg.formalName, path: path, method: node.method().toUpperCase() }); }); } } export class OasMissingResponseForOperationRule extends OasInvalidPropertyValueRule { public visitResponses(node: Oas30Responses): void { this.reportIfInvalid(node.responses().length > 0, node.parent(), null); } } export class OasUnknownParamStyleRule extends OasInvalidPropertyValueRule { public visitParameter(node: Oas30Parameter): void { if (this.hasValue(node.style)) { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.style, ["matrix", "label", "form", "simple", "spaceDelimited", "pipeDelimited", "deepObject"]), node, "style", { style: node.style }); } } public visitParameterDefinition(node: Oas30ParameterDefinition): void { this.visitParameter(node); } } export class OasUnknownQueryParamStyleRule extends OasInvalidPropertyValueRule { public visitParameter(node: Oas30Parameter): void { if (this.hasValue(node.style)) { if (node.in === "query") { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.style, ["form", "spaceDelimited", "pipeDelimited", "deepObject"]), node, "style", { style: node.style }); } } } public visitParameterDefinition(node: Oas30ParameterDefinition): void { this.visitParameter(node); } } export class OasUnknownCookieParamStyleRule extends OasInvalidPropertyValueRule { public visitParameter(node: Oas30Parameter): void { if (this.hasValue(node.style)) { if (node.in === "cookie") { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.style, ["form"]), node, "style", { style: node.style }); } } } public visitParameterDefinition(node: Oas30ParameterDefinition): void { this.visitParameter(node); } } export class OasUnknownHeaderParamStyleRule extends OasInvalidPropertyValueRule { public visitParameter(node: Oas30Parameter): void { if (this.hasValue(node.style)) { if (node.in === "header") { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.style, ["simple"]), node, "style", { style: node.style }); } } } public visitParameterDefinition(node: Oas30ParameterDefinition): void { this.visitParameter(node); } } export class OasUnknownPathParamStyleRule extends OasInvalidPropertyValueRule { public visitParameter(node: Oas30Parameter): void { if (node.in === "path") { if (this.hasValue(node.style)) { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.style, ["matrix", "label", "simple"]), node, "style", { style: node.style }); } } } public visitParameterDefinition(node: Oas30ParameterDefinition): void { this.visitParameter(node); } } export class OasAllowReservedNotAllowedForParamRule extends OasInvalidPropertyValueRule { public visitParameter(node: Oas30Parameter): void { if (this.hasValue(node.allowReserved)) { this.reportIfInvalid(node.in === "query", node, "allowReserved"); } } public visitParameterDefinition(node: Oas30ParameterDefinition): void { this.visitParameter(node); } } export class OasUnexpectedNumOfParamMTsRule extends OasInvalidPropertyValueRule { public visitParameter(node: Oas30Parameter): void { if (this.hasValue(node.content)) { this.reportIfInvalid(node.getMediaTypes().length < 2, node, "content"); } } public visitParameterDefinition(node: Oas30ParameterDefinition): void { this.visitParameter(node); } } export class OasUnexpectedUsageOfDiscriminatorRule extends OasInvalidPropertyValueRule { public visitDiscriminator(node: Oas30Discriminator): void { let schema: Oas30Schema = node.parent() as Oas30Schema; let valid: boolean = this.hasValue(schema.oneOf) || this.hasValue(schema.anyOf) || this.hasValue(schema.allOf); this.reportIfInvalid(valid, node, "discriminator"); } } export class OasInvalidHttpSecuritySchemeTypeRule extends OasInvalidPropertyValueRule { public visitSecurityScheme(node: Oas30SecurityScheme): void { if (this.hasValue(node.scheme)) { this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(node.scheme, ["basic", "bearer", "digest", "hoba", "mutual", "negotiate", "oauth", "vapid", "scram-sha-1", "scram-sha-256"]), node, "scheme", { scheme: node.scheme }); } } } export class OasUnexpectedUsageOfBearerTokenRule extends OasInvalidPropertyValueRule { public visitSecurityScheme(node: Oas30SecurityScheme): void { if (this.hasValue(node.bearerFormat)) { this.reportIfInvalid(node.type === "http" && node.scheme === "bearer", node, "bearerFormat"); } } } export class OasInvalidSecurityReqScopesRule extends OasInvalidPropertyValueRule { public visitSecurityRequirement(node: Oas30SecurityRequirement): void { let snames: string[] = node.securityRequirementNames(); snames.forEach( sname => { let scopes: string[] = node.scopes(sname); this.reportIfInvalid(this.hasValue(scopes) && Array.isArray(scopes), node, sname, { name: sname }); }); } } export class OasServerVarNotFoundInTemplateRule extends OasInvalidPropertyValueRule { /** * Parses the given server template for variable names. For example, a server template might be * * https://{username}.gigantic-server.com:{port}/{basePath} * * In this case, this method will return [ "username", "port", "basePath" ] * * @param serverTemplate * @return {Array} */ private parseServerTemplate(serverTemplate: string): string[] { if (!this.hasValue(serverTemplate)) { return []; } let vars: string[] = []; let startIdx: number = serverTemplate.indexOf('{'); let endIdx: number = -1; while (startIdx !== -1) { endIdx = serverTemplate.indexOf('}', startIdx); if (endIdx !== -1) { vars.push(serverTemplate.substring(startIdx + 1, endIdx)); startIdx = serverTemplate.indexOf('{', endIdx); } else { startIdx = -1; } } return vars; } public visitServerVariable(node: Oas30ServerVariable): void { let varName: string = node.name(); let server: Oas30Server = node.parent() as Oas30Server; let vars: string[] = this.parseServerTemplate(server.url); this.reportIfInvalid(OasValidationRuleUtil.isValidEnumItem(varName, vars), node, null, { name: varName }); } }
the_stack
import { isNil, isFunction, assign } from '@antv/util'; import { Tag, Word } from '../../plots/word-cloud/types'; type FontWeight = number | 'normal' | 'bold' | 'bolder' | 'lighter'; export interface Options { size: [number, number]; font?: string | ((row: Word, index?: number, words?: Word[]) => string); fontSize?: number | ((row: Word, index?: number, words?: Word[]) => number); fontWeight?: FontWeight | ((row: Word, index?: number, words?: Word[]) => FontWeight); rotate?: number | ((row: Word, index?: number, words?: Word[]) => number); padding?: number | ((row: Word, index?: number, words?: Word[]) => number); spiral?: 'archimedean' | 'rectangular' | ((size: [number, number]) => (t: number) => number[]); random?: number | (() => number); timeInterval?: number; imageMask?: HTMLImageElement; } const DEFAULT_OPTIONS: Options = { font: () => 'serif', padding: 1, size: [500, 500], spiral: 'archimedean', // 'archimedean' || 'rectangular' || {function} // timeInterval: Infinity // max execute time timeInterval: 3000, // max execute time // imageMask: '', // instance of Image, must be loaded }; /** * 根据对应的数据对象,计算每个 * 词语在画布中的渲染位置,并返回 * 计算后的数据对象 * @param words * @param options */ export function wordCloud(words: Word[], options?: Partial<Options>): Tag[] { // 混入默认配置 options = assign({} as Options, DEFAULT_OPTIONS, options); return transform(words, options as Options); } /** * 抛出没有混入默认配置的方法,用于测试。 * @param words * @param options */ export function transform(words: Word[], options: Options) { // 布局对象 const layout = tagCloud(); ['font', 'fontSize', 'fontWeight', 'padding', 'rotate', 'size', 'spiral', 'timeInterval', 'random'].forEach( (key: string) => { if (!isNil(options[key])) { layout[key](options[key]); } } ); layout.words(words); if (options.imageMask) { layout.createMask(options.imageMask); } const result = layout.start(); const tags: any[] = result._tags; tags.forEach((tag) => { tag.x += options.size[0] / 2; tag.y += options.size[1] / 2; }); const [w, h] = options.size; // 添加两个参照数据,分别表示左上角和右下角。 // 不添加的话不会按照真实的坐标渲染,而是以 // 数据中的边界坐标为边界进行拉伸,以铺满画布。 // 这样的后果会导致词语之间的重叠。 tags.push({ text: '', value: 0, x: 0, y: 0, opacity: 0, }); tags.push({ text: '', value: 0, x: w, y: h, opacity: 0, }); return tags; } /* * Synchronous version of d3-cloud */ // Word cloud layout by Jason Davies, https://www.jasondavies.com/wordcloud/ // Algorithm due to Jonathan Feinberg, http://static.mrfeinberg.com/bv_ch03.pdf /* eslint-disable no-return-assign, no-cond-assign */ interface Item { value: number; text: string; sprite: boolean; } const cloudRadians = Math.PI / 180, cw = (1 << 11) >> 5, ch = 1 << 11; function cloudText(d: Item) { return d.text; } function cloudFont() { return 'serif'; } function cloudFontNormal() { return 'normal'; } function cloudFontSize(d: Item) { return d.value; } function cloudRotate() { return ~~(Math.random() * 2) * 90; } function cloudPadding() { return 1; } // Fetches a monochrome sprite bitmap for the specified text. // Load in batches for speed. function cloudSprite(contextAndRatio, d, data, di) { if (d.sprite) return; const c = contextAndRatio.context, ratio = contextAndRatio.ratio; c.clearRect(0, 0, (cw << 5) / ratio, ch / ratio); let x = 0, y = 0, maxh = 0; const n = data.length; --di; while (++di < n) { d = data[di]; c.save(); c.font = d.style + ' ' + d.weight + ' ' + ~~((d.size + 1) / ratio) + 'px ' + d.font; let w = c.measureText(d.text + 'm').width * ratio, h = d.size << 1; if (d.rotate) { const sr = Math.sin(d.rotate * cloudRadians), cr = Math.cos(d.rotate * cloudRadians), wcr = w * cr, wsr = w * sr, hcr = h * cr, hsr = h * sr; w = ((Math.max(Math.abs(wcr + hsr), Math.abs(wcr - hsr)) + 0x1f) >> 5) << 5; h = ~~Math.max(Math.abs(wsr + hcr), Math.abs(wsr - hcr)); } else { w = ((w + 0x1f) >> 5) << 5; } if (h > maxh) maxh = h; if (x + w >= cw << 5) { x = 0; y += maxh; maxh = 0; } if (y + h >= ch) break; c.translate((x + (w >> 1)) / ratio, (y + (h >> 1)) / ratio); if (d.rotate) c.rotate(d.rotate * cloudRadians); c.fillText(d.text, 0, 0); if (d.padding) { c.lineWidth = 2 * d.padding; c.strokeText(d.text, 0, 0); } c.restore(); d.width = w; d.height = h; d.xoff = x; d.yoff = y; d.x1 = w >> 1; d.y1 = h >> 1; d.x0 = -d.x1; d.y0 = -d.y1; d.hasText = true; x += w; } const pixels = c.getImageData(0, 0, (cw << 5) / ratio, ch / ratio).data, sprite = []; while (--di >= 0) { d = data[di]; if (!d.hasText) continue; const w = d.width, w32 = w >> 5; let h = d.y1 - d.y0; // Zero the buffer for (let i = 0; i < h * w32; i++) sprite[i] = 0; x = d.xoff; if (x == null) return; y = d.yoff; let seen = 0, seenRow = -1; for (let j = 0; j < h; j++) { for (let i = 0; i < w; i++) { const k = w32 * j + (i >> 5), m = pixels[((y + j) * (cw << 5) + (x + i)) << 2] ? 1 << (31 - (i % 32)) : 0; sprite[k] |= m; seen |= m; } if (seen) seenRow = j; else { d.y0++; h--; j--; y++; } } d.y1 = d.y0 + seenRow; d.sprite = sprite.slice(0, (d.y1 - d.y0) * w32); } } // Use mask-based collision detection. function cloudCollide(tag, board, sw) { sw >>= 5; const sprite = tag.sprite, w = tag.width >> 5, lx = tag.x - (w << 4), sx = lx & 0x7f, msx = 32 - sx, h = tag.y1 - tag.y0; let x = (tag.y + tag.y0) * sw + (lx >> 5), last; for (let j = 0; j < h; j++) { last = 0; for (let i = 0; i <= w; i++) { if (((last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0)) & board[x + i]) return true; } x += sw; } return false; } function cloudBounds(bounds, d) { const b0 = bounds[0], b1 = bounds[1]; if (d.x + d.x0 < b0.x) b0.x = d.x + d.x0; if (d.y + d.y0 < b0.y) b0.y = d.y + d.y0; if (d.x + d.x1 > b1.x) b1.x = d.x + d.x1; if (d.y + d.y1 > b1.y) b1.y = d.y + d.y1; } function collideRects(a, b) { return a.x + a.x1 > b[0].x && a.x + a.x0 < b[1].x && a.y + a.y1 > b[0].y && a.y + a.y0 < b[1].y; } function archimedeanSpiral(size) { const e = size[0] / size[1]; return function (t) { return [e * (t *= 0.1) * Math.cos(t), t * Math.sin(t)]; }; } function rectangularSpiral(size) { const dy = 4, dx = (dy * size[0]) / size[1]; let x = 0, y = 0; return function (t) { const sign = t < 0 ? -1 : 1; // See triangular numbers: T_n = n * (n + 1) / 2. switch ((Math.sqrt(1 + 4 * sign * t) - sign) & 3) { case 0: x += dx; break; case 1: y += dy; break; case 2: x -= dx; break; default: y -= dy; break; } return [x, y]; }; } // TODO reuse arrays? function zeroArray(n) { const a = []; let i = -1; while (++i < n) a[i] = 0; return a; } function cloudCanvas() { return document.createElement('canvas'); } export function functor(d) { return isFunction(d) ? d : function () { return d; }; } const spirals = { archimedean: archimedeanSpiral, rectangular: rectangularSpiral, }; function tagCloud() { let size = [256, 256], font = cloudFont, fontSize = cloudFontSize, fontWeight = cloudFontNormal, rotate = cloudRotate, padding = cloudPadding, spiral = archimedeanSpiral, random = Math.random, words = [], timeInterval = Infinity; const text = cloudText; const fontStyle = cloudFontNormal; const canvas = cloudCanvas; const cloud: any = {}; cloud.start = function () { const [width, height] = size; const contextAndRatio = getContext(canvas()), board = cloud.board ? cloud.board : zeroArray((size[0] >> 5) * size[1]), n = words.length, tags = [], data = words .map(function (d, i, data) { d.text = text.call(this, d, i, data); d.font = font.call(this, d, i, data); d.style = fontStyle.call(this, d, i, data); d.weight = fontWeight.call(this, d, i, data); d.rotate = rotate.call(this, d, i, data); d.size = ~~fontSize.call(this, d, i, data); d.padding = padding.call(this, d, i, data); return d; }) .sort(function (a, b) { return b.size - a.size; }); let i = -1, bounds = !cloud.board ? null : [ { x: 0, y: 0, }, { x: width, y: height, }, ]; step(); function step() { const start = Date.now(); while (Date.now() - start < timeInterval && ++i < n) { const d = data[i]; d.x = (width * (random() + 0.5)) >> 1; d.y = (height * (random() + 0.5)) >> 1; cloudSprite(contextAndRatio, d, data, i); if (d.hasText && place(board, d, bounds)) { tags.push(d); if (bounds) { if (!cloud.hasImage) { // update bounds if image mask not set cloudBounds(bounds, d); } } else { bounds = [ { x: d.x + d.x0, y: d.y + d.y0 }, { x: d.x + d.x1, y: d.y + d.y1 }, ]; } // Temporary hack d.x -= size[0] >> 1; d.y -= size[1] >> 1; } } cloud._tags = tags; cloud._bounds = bounds; } return cloud; }; function getContext(canvas: HTMLCanvasElement) { canvas.width = canvas.height = 1; const ratio = Math.sqrt(canvas.getContext('2d')!.getImageData(0, 0, 1, 1).data.length >> 2); canvas.width = (cw << 5) / ratio; canvas.height = ch / ratio; const context = canvas.getContext('2d') as CanvasRenderingContext2D; context.fillStyle = context.strokeStyle = 'red'; context.textAlign = 'center'; return { context, ratio }; } function place(board, tag, bounds) { // const perimeter = [{ x: 0, y: 0 }, { x: size[0], y: size[1] }], const startX = tag.x, startY = tag.y, maxDelta = Math.sqrt(size[0] * size[0] + size[1] * size[1]), s = spiral(size), dt = random() < 0.5 ? 1 : -1; let dxdy, t = -dt, dx, dy; while ((dxdy = s((t += dt)))) { dx = ~~dxdy[0]; dy = ~~dxdy[1]; if (Math.min(Math.abs(dx), Math.abs(dy)) >= maxDelta) break; tag.x = startX + dx; tag.y = startY + dy; if (tag.x + tag.x0 < 0 || tag.y + tag.y0 < 0 || tag.x + tag.x1 > size[0] || tag.y + tag.y1 > size[1]) continue; // TODO only check for collisions within current bounds. if (!bounds || !cloudCollide(tag, board, size[0])) { if (!bounds || collideRects(tag, bounds)) { const sprite = tag.sprite, w = tag.width >> 5, sw = size[0] >> 5, lx = tag.x - (w << 4), sx = lx & 0x7f, msx = 32 - sx, h = tag.y1 - tag.y0; let last, x = (tag.y + tag.y0) * sw + (lx >> 5); for (let j = 0; j < h; j++) { last = 0; for (let i = 0; i <= w; i++) { board[x + i] |= (last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0); } x += sw; } delete tag.sprite; return true; } } } return false; } cloud.createMask = (img: HTMLImageElement) => { const can: HTMLCanvasElement = document.createElement('canvas'); const [width, height] = size; // 当 width 或 height 为 0 时,调用 cxt.getImageData 会报错 if (!width || !height) { return; } const w32 = width >> 5; const board = zeroArray((width >> 5) * height); can.width = width; can.height = height; const cxt = can.getContext('2d') as CanvasRenderingContext2D; cxt.drawImage(img, 0, 0, img.width, img.height, 0, 0, width, height); const imageData = cxt.getImageData(0, 0, width, height).data; for (let j = 0; j < height; j++) { for (let i = 0; i < width; i++) { const k = w32 * j + (i >> 5); const tmp = (j * width + i) << 2; const flag = imageData[tmp] >= 250 && imageData[tmp + 1] >= 250 && imageData[tmp + 2] >= 250; const m = flag ? 1 << (31 - (i % 32)) : 0; board[k] |= m; } } cloud.board = board; cloud.hasImage = true; }; cloud.timeInterval = function (_) { timeInterval = _ == null ? Infinity : _; }; cloud.words = function (_) { words = _; }; cloud.size = function (_) { size = [+_[0], +_[1]]; }; cloud.font = function (_) { font = functor(_); }; cloud.fontWeight = function (_) { fontWeight = functor(_); }; cloud.rotate = function (_) { rotate = functor(_); }; cloud.spiral = function (_) { spiral = spirals[_] || _; }; cloud.fontSize = function (_) { fontSize = functor(_); }; cloud.padding = function (_) { padding = functor(_); }; cloud.random = function (_) { random = functor(_); }; return cloud; }
the_stack
import { parseAndGetTestState } from './harness/fourslash/testState'; import { testMoveSymbolAtPosition } from './renameModuleTestUtils'; test('move symbol to another file - simple from import', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// from [|{|"r":"moved"|}test|] import foo `; testFromCode(code); }); test('move symbol to another file - nested file', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: nested/moved.py //// [|/*dest*/|] // @filename: used.py //// from [|{|"r":"nested.moved"|}test|] import foo `; testFromCode(code); }); test('move symbol to another file - parent file', () => { const code = ` // @filename: nested/test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// from [|{|"r":"moved"|}nested.test|] import foo `; testFromCode(code); }); test('move symbol to another file - multiple import', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// //// def stay(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// [|{|"r":"from moved import foo!n!"|}|]from test import [|{|"r":""|}foo, |]stay `; testFromCode(code); }); test('move symbol to another file - multiple import with submodules', () => { const code = ` // @filename: nested/__init__.py //// def [|/*marker*/foo|](): pass // @filename: nested/test.py //// # empty // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// [|{|"r":"from moved import foo!n!"|}|]from nested import [|{|"r":""|}foo, |]test `; testFromCode(code); }); test('move symbol to another file - no merge with existing imports', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] //// def stay(): pass // @filename: used.py //// from [|{|"r":"moved"|}test|] import foo //// from moved import stay `; testFromCode(code); }); test('move symbol to another file - merge with existing imports', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] //// def stay(): pass // @filename: used.py //// from test import bar[|{|"r":""|}, foo|] //// from moved import [|{|"r":"foo, "|}|]stay `; testFromCode(code); }); test('move symbol to another file - multiple import - nested folder', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// //// def stay(): pass // @filename: nested/moved.py //// [|/*dest*/|] // @filename: used.py //// [|{|"r":"from nested.moved import foo!n!"|}|]from test import [|{|"r":""|}foo, |]stay `; testFromCode(code); }); test('move symbol to another file - multiple import with submodules - parent folder', () => { const code = ` // @filename: nested/__init__.py //// def [|/*marker*/foo|](): pass // @filename: nested/test.py //// # empty // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// [|{|"r":"from moved import foo!n!"|}|]from nested import [|{|"r":""|}foo, |]test `; testFromCode(code); }); test('move symbol to another file - no merge with existing imports - nested folder', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: nested/moved.py //// [|/*dest*/|] //// def stay(): pass // @filename: used.py //// from [|{|"r":"nested.moved"|}test|] import foo //// from nested.moved import stay `; testFromCode(code); }); test('move symbol to another file - merge with existing imports - nested folder', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: nested/moved.py //// [|/*dest*/|] //// def stay(): pass // @filename: used.py //// from test import bar[|{|"r":""|}, foo|] //// from nested.moved import [|{|"r":"foo, "|}|]stay `; testFromCode(code); }); test('move symbol to another file - multiple import - parent folder', () => { const code = ` // @filename: nested/test.py //// def [|/*marker*/foo|](): pass //// //// def stay(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// [|{|"r":"from moved import foo!n!"|}|]from nested.test import [|{|"r":""|}foo, |]stay `; testFromCode(code); }); test('move symbol to another file - multiple import with submodules - sibling folder', () => { const code = ` // @filename: nested/__init__.py //// def [|/*marker*/foo|](): pass // @filename: nested/test.py //// # empty // @filename: nested/moved.py //// [|/*dest*/|] // @filename: used.py //// from nested import [|{|"r":""|}foo, |]test[|{|"r":"!n!from nested.moved import foo"|}|] `; testFromCode(code); }); test('move symbol to another file - no merge with existing imports - parent folder', () => { const code = ` // @filename: nested/test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] //// def stay(): pass // @filename: used.py //// from [|{|"r":"moved"|}nested.test|] import foo //// from moved import stay `; testFromCode(code); }); test('move symbol to another file - merge with existing imports - parent folder', () => { const code = ` // @filename: nested/test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] //// def stay(): pass // @filename: used.py //// from nested.test import bar[|{|"r":""|}, foo|] //// from moved import [|{|"r":"foo, "|}|]stay `; testFromCode(code); }); test('move symbol to another file - simple from import - relative path', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// from [|{|"r":".moved"|}.test|] import foo `; testFromCode(code); }); test('move symbol to another file - nested file - relative path', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: nested/moved.py //// [|/*dest*/|] // @filename: nested/used.py //// from [|{|"r":".moved"|}..test|] import foo `; testFromCode(code); }); test('move symbol to another file - parent file - relative path', () => { const code = ` // @filename: nested/test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// from [|{|"r":".moved"|}.nested.test|] import foo `; testFromCode(code); }); test('move symbol to another file - multiple import - relative path', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// //// def stay(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: nested/used.py //// [|{|"r":"from ..moved import foo!n!"|}|]from ..test import [|{|"r":""|}foo, |]stay `; testFromCode(code); }); test('move symbol to another file - multiple import with submodules - relative path', () => { const code = ` // @filename: nested/__init__.py //// def [|/*marker*/foo|](): pass // @filename: nested/test.py //// # empty // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// [|{|"r":"from .moved import foo!n!"|}|]from .nested import [|{|"r":""|}foo, |]test `; testFromCode(code); }); test('move symbol to another file - no merge with existing imports - relative path', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] //// def stay(): pass // @filename: used.py //// from [|{|"r":".moved"|}.test|] import foo //// from moved import stay `; testFromCode(code); }); test('move symbol to another file - merge with existing imports - relative path', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] //// def stay(): pass // @filename: used.py //// from .test import bar[|{|"r":""|}, foo|] //// from .moved import [|{|"r":"foo, "|}|]stay `; testFromCode(code); }); test('member off import', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// import [|{|"r":"moved"|}test|] //// [|{|"r":"moved"|}test|].foo() `; testFromCode(code); }); test('member off import with existing import', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// [|{|"r":""|}import test //// |]import moved //// [|{|"r":"moved"|}test|].foo() `; testFromCode(code); }); test('member off import with existing import with alias', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// [|{|"r":""|}import test //// |]import moved as m //// [|{|"r":"m"|}test|].foo() `; testFromCode(code); }); test('member off import with existing import - multiple imports', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// import moved[|{|"r":""|}, test|] //// [|{|"r":"moved"|}test|].foo() `; testFromCode(code); }); test('member off import with existing import - multiple imports with alias', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// import moved as m[|{|"r":""|}, test|] //// [|{|"r":"m"|}test|].foo() `; testFromCode(code); }); test('member off from import with existing import', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// [|{|"r":""|}from . import test //// |]import moved //// [|{|"r":"moved"|}test|].foo() `; testFromCode(code); }); test('member off from import with existing import with alias', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// [|{|"r":""|}from . import test //// |]import moved as m //// [|{|"r":"m"|}test|].foo() `; testFromCode(code); }); test('member off from import with existing from import', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// [|{|"r":""|}from . import test //// |]from . import moved //// [|{|"r":"moved"|}test|].foo() `; testFromCode(code); }); test('member off from import with existing from import with alias', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// [|{|"r":""|}from . import test //// |]from . import moved as m //// [|{|"r":"m"|}test|].foo() `; testFromCode(code); }); test('member off from import with existing import - multiple imports', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// from . import moved[|{|"r":""|}, test|] //// [|{|"r":"moved"|}test|].foo() `; testFromCode(code); }); test('member off from import with existing import - multiple imports with alias', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// from . import moved as m[|{|"r":""|}, test|] //// [|{|"r":"m"|}test|].foo() `; testFromCode(code); }); test('member off submodule', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// from . import [|{|"r":"moved"|}test|] //// [|{|"r":"moved"|}test|].foo() `; testFromCode(code); }); test('member off import - dotted name', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: nested/moved.py //// [|/*dest*/|] // @filename: used.py //// import [|{|"r":"nested.moved"|}test|] //// [|{|"r":"nested.moved"|}test|].foo() `; testFromCode(code); }); test('member off submodule - dotted name', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: nested/moved.py //// [|/*dest*/|] // @filename: used.py //// from [|{|"r":".nested"|}.|] import [|{|"r":"moved"|}test|] //// [|{|"r":"moved"|}test|].foo() `; testFromCode(code); }); test('member off import with alias', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// import [|{|"r":"moved"|}test|] as t //// t.foo() `; testFromCode(code); }); test('member off submodule with alias', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// from . import [|{|"r":"moved"|}test|] as test //// test.foo() `; testFromCode(code); }); test('member off import with alias - dotted name', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: nested/moved.py //// [|/*dest*/|] // @filename: used.py //// import [|{|"r":"nested.moved"|}test|] as t //// t.foo() `; testFromCode(code); }); test('member off submodule with alias - dotted name', () => { const code = ` // @filename: nested/test.py //// def [|/*marker*/foo|](): pass // @filename: sub/moved.py //// [|/*dest*/|] // @filename: used.py //// from [|{|"r":"sub"|}nested|] import [|{|"r":"moved"|}test|] as test //// test.foo() `; testFromCode(code); }); test('member off import - multiple symbols', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// [|{|"r":"import moved!n!"|}|]import test //// [|{|"r":"moved"|}test|].foo() //// test.bar() `; testFromCode(code); }); test('member off import - multiple symbols - existing import', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// import moved //// import test //// //// [|{|"r":"moved"|}test|].foo() //// test.bar() `; testFromCode(code); }); test('member off import - multiple symbols - existing import with alias', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// import moved as m //// import test //// //// [|{|"r":"m"|}test|].foo() //// test.bar() `; testFromCode(code); }); test('member off import - multiple symbols with alias - existing import', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// import moved //// import test as t //// //// [|{|"r":"moved"|}t|].foo() //// t.bar() `; testFromCode(code); }); test('member off import - multiple symbols with alias - new import', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// [|{|"r":"import moved!n!"|}|]import test as t //// //// [|{|"r":"moved"|}t|].foo() //// t.bar() `; testFromCode(code); }); test('member off import - multiple symbols with alias - existing import with alias', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// import moved as m //// import test as t //// //// [|{|"r":"m"|}t|].foo() //// t.bar() `; testFromCode(code); }); test('member off import - multiple symbols - existing from import', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// from . import moved //// import test //// //// [|{|"r":"moved"|}test|].foo() //// test.bar() `; testFromCode(code); }); test('member off import - multiple symbols - existing from import with alias', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// from . import moved as m //// import test //// //// [|{|"r":"m"|}test|].foo() //// test.bar() `; testFromCode(code); }); test('member off import - multiple symbols - existing from import', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// from . import moved //// import test //// //// [|{|"r":"moved"|}test|].foo() //// test.bar() `; testFromCode(code); }); test('member off import - multiple symbols - existing from import with alias', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// from . import moved as m //// import test //// //// [|{|"r":"m"|}test|].foo() //// test.bar() `; testFromCode(code); }); test('member off from import - multiple symbols', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// [|{|"r":"import moved!n!"|}|]from . import test //// [|{|"r":"moved"|}test|].foo() //// test.bar() `; testFromCode(code); }); test('member off from import - multiple symbols - existing import', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// import moved //// from . import test //// //// [|{|"r":"moved"|}test|].foo() //// test.bar() `; testFromCode(code); }); test('member off from import - multiple symbols - existing import with alias', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// import moved as m //// from . import test //// //// [|{|"r":"m"|}test|].foo() //// test.bar() `; testFromCode(code); }); test('member off from import - multiple symbols with alias - existing import', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// import moved //// from . import test as t //// //// [|{|"r":"moved"|}t|].foo() //// t.bar() `; testFromCode(code); }); test('member off from import - multiple symbols with alias - new import', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// [|{|"r":"import moved!n!"|}|]from . import test as t //// //// [|{|"r":"moved"|}t|].foo() //// t.bar() `; testFromCode(code); }); test('member off from import - multiple symbols with alias - existing import with alias', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// import moved as m //// from . import test as t //// //// [|{|"r":"m"|}t|].foo() //// t.bar() `; testFromCode(code); }); test('member off from import - multiple symbols - existing from import', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// from . import moved //// from . import test //// //// [|{|"r":"moved"|}test|].foo() //// test.bar() `; testFromCode(code); }); test('member off from import - multiple symbols - existing from import with alias', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass //// def bar(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// from . import moved as m //// from . import test //// //// [|{|"r":"m"|}test|].foo() //// test.bar() `; testFromCode(code); }); test('member off import - error case that we dont touch - function return module', () => { // We could put import in test so test module still has symbol "foo" but // for now, we won't handle such corner case. const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: test2.py //// def foo(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// from test //// from test2 //// def getTestModule(a): //// return test if a > 0 else test2 //// //// getTestModule(1).foo() `; testFromCode(code); }); test('member off import - error case that we dont touch - field return module', () => { // We could put import in test so test module still has symbol "foo" but // for now, we won't handle such corner case. const code = ` // @filename: test.py //// def [|/*marker*/foo|](): pass // @filename: test2.py //// def foo(): pass // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// from test //// from test2 //// module = test if a > 0 else test2 //// //// module.foo() `; testFromCode(code); }); test('simple symbol reference', () => { const code = ` // @filename: test.py //// def [|/*marker*/foo|](): //// return 1 // @filename: moved.py //// [|/*dest*/|] // @filename: used.py //// from [|{|"r":"moved"|}test|] import foo //// //// foo() //// b = foo().real `; testFromCode(code); }); function testFromCode(code: string) { const state = parseAndGetTestState(code).state; testMoveSymbolAtPosition( state, state.getMarkerByName('marker').fileName, state.getMarkerByName('dest').fileName, state.getPositionRange('marker').start ); }
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * Base resource object. */ export interface Resource extends BaseResource { /** * ID of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Name of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Type of Resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * The entity tag used for optimistic concurrency when modifying the resource. */ etag?: string; } /** * Base resource object. */ export interface TrackedResource extends BaseResource { /** * ID of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Name of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Type of Resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * Custom tags for the resource. */ tags?: { [propertyName: string]: string }; /** * The entity tag used for optimistic concurrency when modifying the resource. */ etag?: string; } /** * Contains the localized display information for this particular operation or action. */ export interface Display { /** * The localized, friendly version of the resource provider name. */ provider?: string; /** * The localized, friendly version of the resource type related to this action or operation; the * resource type should match the public documentation for the resource provider. */ resource?: string; /** * The localized, friendly name for the operation. Use the name as it will displayed to the user. */ operation?: string; /** * The localized, friendly description for the operation. The description will be displayed to * the user. It should be thorough and concise for used in both tooltips and detailed views. */ description?: string; } /** * Describes the supported REST operation. */ export interface Operation { /** * The name of the operation being performed on this particular object. */ name?: string; /** * Contains the localized display information for this particular operation or action. */ display?: Display; /** * The intended executor of the operation. */ origin?: string; } /** * The details of the error. */ export interface ErrorDetails { /** * Error code. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly code?: string; /** * Error message indicating why the operation failed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly message?: string; /** * The target of the particular error. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly target?: string; } /** * Error response indicates that the service is not able to process the incoming request. The * reason is provided in the error message. */ export interface ErrorResponse { /** * The details of the error. */ error?: ErrorDetails; } /** * OS disk image. */ export interface OsDiskImage { /** * OS operating system type. Possible values include: 'None', 'Windows', 'Linux' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly operatingSystem?: OperatingSystem; /** * SAS key for source blob. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly sourceBlobSasUri?: string; } /** * Data disk image. */ export interface DataDiskImage { /** * The LUN. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly lun?: number; /** * SAS key for source blob. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly sourceBlobSasUri?: string; } /** * Extended description about the product required for installing it into Azure Stack. */ export interface ExtendedProduct { /** * The URI to the .azpkg file that provides information required for showing product in the * gallery. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly galleryPackageBlobSasUri?: string; /** * Specifies the kind of the product (virtualMachine or virtualMachineExtension). * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly productKind?: string; /** * Specifies kind of compute role included in the package. Possible values include: 'None', * 'IaaS', 'PaaS' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly computeRole?: ComputeRole; /** * Specifies if product is a Virtual Machine Extension. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly isSystemExtension?: boolean; /** * The URI. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly uri?: string; /** * Indicates if specified product supports multiple extensions. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly supportMultipleExtensions?: boolean; /** * Specifies product version. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly version?: string; /** * Specifies operating system used by the product. Possible values include: 'None', 'Windows', * 'Linux' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly vmOsType?: OperatingSystem; /** * Indicates if virtual machine Scale Set is enabled in the specified product. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly vmScaleSetEnabled?: boolean; /** * OS disk image used by product. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly osDiskImage?: OsDiskImage; /** * List of attached data disks. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly dataDiskImages?: DataDiskImage[]; } /** * Product information. */ export interface VirtualMachineExtensionProductProperties { /** * Specifies kind of compute role included in the package. Possible values include: 'None', * 'IaaS', 'PaaS' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly computeRole?: ComputeRole; /** * Specifies if product is a Virtual Machine Extension. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly isSystemExtension?: boolean; /** * The URI. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly uri?: string; /** * Indicates if specified product supports multiple extensions. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly supportMultipleExtensions?: boolean; /** * Specifies product version. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly version?: string; /** * Specifies operating system used by the product. Possible values include: 'None', 'Windows', * 'Linux' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly vmOsType?: OperatingSystem; /** * Indicates if virtual machine Scale Set is enabled in the specified product. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly vmScaleSetEnabled?: boolean; } /** * Product information. */ export interface VirtualMachineProductProperties { /** * Specifies product version. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly version?: string; /** * OS disk image used by product. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly osDiskImage?: OsDiskImage; /** * List of attached data disks. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly dataDiskImages?: DataDiskImage[]; } /** * Links to product icons. */ export interface IconUris { /** * URI to large icon. */ large?: string; /** * URI to wide icon. */ wide?: string; /** * URI to medium icon. */ medium?: string; /** * URI to small icon. */ small?: string; /** * URI to hero icon. */ hero?: string; } /** * Link with additional information about a product. */ export interface ProductLink { /** * The description of the link. */ displayName?: string; /** * The URI corresponding to the link. */ uri?: string; } /** * Additional properties of the product */ export interface ProductProperties { /** * The version. */ version?: string; } /** * Product compatibility */ export interface Compatibility { /** * Tells if product is compatible with current device */ isCompatible?: boolean; /** * Short error message if any compatibility issues are found */ message?: string; /** * Full error message if any compatibility issues are found */ description?: string; /** * List of all issues found */ issues?: CompatibilityIssue[]; } /** * Product information. */ export interface Product extends Resource { /** * The display name of the product. */ displayName?: string; /** * The description of the product. */ description?: string; /** * The user-friendly name of the product publisher. */ publisherDisplayName?: string; /** * Publisher identifier. */ publisherIdentifier?: string; /** * The offer representing the product. */ offer?: string; /** * The version of the product offer. */ offerVersion?: string; /** * The product SKU. */ sku?: string; /** * The part number used for billing purposes. */ billingPartNumber?: string; /** * The type of the Virtual Machine Extension. */ vmExtensionType?: string; /** * The identifier of the gallery item corresponding to the product. */ galleryItemIdentity?: string; /** * Additional links available for this product. */ iconUris?: IconUris; /** * Additional links available for this product. */ links?: ProductLink[]; /** * The legal terms. */ legalTerms?: string; /** * The privacy policy. */ privacyPolicy?: string; /** * The length of product content. */ payloadLength?: number; /** * The kind of the product (virtualMachine or virtualMachineExtension) */ productKind?: string; /** * Additional properties for the product. */ productProperties?: ProductProperties; /** * Product compatibility with current device. */ compatibility?: Compatibility; } /** * Device Configuration. */ export interface DeviceConfiguration { /** * Version of the device. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly deviceVersion?: string; /** * Identity system of the device. Possible values include: 'AzureAD', 'ADFS' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly identitySystem?: Category; } /** * Update details for product log. */ export interface MarketplaceProductLogUpdate { /** * Operation to log. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly operation?: string; /** * Operation status to log. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly status?: string; /** * Error related to the operation. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly error?: string; /** * Error details related to operation. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly details?: string; } /** * Product action log. */ export interface ProductLog { /** * Log ID. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * Logged product ID. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly productId?: string; /** * Logged subscription ID. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly subscriptionId?: string; /** * Logged registration name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly registrationName?: string; /** * Logged resource group name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly resourceGroupName?: string; /** * Logged operation. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly operation?: string; /** * Operation start datetime. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly startDate?: string; /** * Operation end datetime. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly endDate?: string; /** * Operation status. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly status?: string; /** * Operation error data. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly error?: string; /** * Operation error details. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly details?: string; } /** * Registration information. */ export interface Registration extends TrackedResource { /** * The object identifier associated with the Azure Stack connecting to Azure. */ objectId?: string; /** * The identifier of the registered Azure Stack. */ cloudId?: string; /** * Specifies the billing mode for the Azure Stack registration. */ billingModel?: string; } /** * The resource containing the Azure Stack activation key. */ export interface ActivationKeyResult { /** * Azure Stack activation key. */ activationKey?: string; } /** * Registration resource */ export interface RegistrationParameter { /** * The token identifying registered Azure Stack */ registrationToken: string; /** * Location of the resource. Possible values include: 'global' */ location?: Location; } /** * Customer subscription. */ export interface CustomerSubscription extends Resource { /** * Tenant Id. */ tenantId?: string; } /** * An interface representing AzureStackManagementClientOptions. */ export interface AzureStackManagementClientOptions extends AzureServiceClientOptions { baseUri?: string; } /** * @interface * List of Operations * @extends Array<Operation> */ export interface OperationList extends Array<Operation> { /** * URI to the next page of operations. */ nextLink?: string; } /** * @interface * Pageable list of products. * @extends Array<Product> */ export interface ProductList extends Array<Product> { /** * URI to the next page. */ nextLink?: string; } /** * @interface * Pageable list of registrations. * @extends Array<Registration> */ export interface RegistrationList extends Array<Registration> { /** * URI to the next page. */ nextLink?: string; } /** * @interface * Pageable list of customer subscriptions. * @extends Array<CustomerSubscription> */ export interface CustomerSubscriptionList extends Array<CustomerSubscription> { /** * URI to the next page. */ nextLink?: string; } /** * Defines values for ProvisioningState. * Possible values include: 'Creating', 'Failed', 'Succeeded', 'Canceled' * @readonly * @enum {string} */ export type ProvisioningState = 'Creating' | 'Failed' | 'Succeeded' | 'Canceled'; /** * Defines values for ComputeRole. * Possible values include: 'None', 'IaaS', 'PaaS' * @readonly * @enum {string} */ export type ComputeRole = 'None' | 'IaaS' | 'PaaS'; /** * Defines values for OperatingSystem. * Possible values include: 'None', 'Windows', 'Linux' * @readonly * @enum {string} */ export type OperatingSystem = 'None' | 'Windows' | 'Linux'; /** * Defines values for CompatibilityIssue. * Possible values include: 'HigherDeviceVersionRequired', 'LowerDeviceVersionRequired', * 'CapacityBillingModelRequired', 'PayAsYouGoBillingModelRequired', * 'DevelopmentBillingModelRequired', 'AzureADIdentitySystemRequired', * 'ADFSIdentitySystemRequired', 'ConnectionToInternetRequired', 'ConnectionToAzureRequired', * 'DisconnectedEnvironmentRequired' * @readonly * @enum {string} */ export type CompatibilityIssue = 'HigherDeviceVersionRequired' | 'LowerDeviceVersionRequired' | 'CapacityBillingModelRequired' | 'PayAsYouGoBillingModelRequired' | 'DevelopmentBillingModelRequired' | 'AzureADIdentitySystemRequired' | 'ADFSIdentitySystemRequired' | 'ConnectionToInternetRequired' | 'ConnectionToAzureRequired' | 'DisconnectedEnvironmentRequired'; /** * Defines values for Category. * Possible values include: 'AzureAD', 'ADFS' * @readonly * @enum {string} */ export type Category = 'AzureAD' | 'ADFS'; /** * Defines values for Location. * Possible values include: 'global' * @readonly * @enum {string} */ export type Location = 'global'; /** * Contains response data for the list operation. */ export type OperationsListResponse = OperationList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationList; }; }; /** * Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationList; }; }; /** * Contains response data for the list operation. */ export type ProductsListResponse = ProductList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProductList; }; }; /** * Contains response data for the get operation. */ export type ProductsGetResponse = Product & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Product; }; }; /** * Contains response data for the listDetails operation. */ export type ProductsListDetailsResponse = ExtendedProduct & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ExtendedProduct; }; }; /** * Contains response data for the getProducts operation. */ export type ProductsGetProductsResponse = ProductList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProductList; }; }; /** * Contains response data for the getProduct operation. */ export type ProductsGetProductResponse = Product & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Product; }; }; /** * Contains response data for the uploadLog operation. */ export type ProductsUploadLogResponse = ProductLog & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProductLog; }; }; /** * Contains response data for the listNext operation. */ export type ProductsListNextResponse = ProductList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProductList; }; }; /** * Contains response data for the list operation. */ export type RegistrationsListResponse = RegistrationList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RegistrationList; }; }; /** * Contains response data for the get operation. */ export type RegistrationsGetResponse = Registration & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Registration; }; }; /** * Contains response data for the createOrUpdate operation. */ export type RegistrationsCreateOrUpdateResponse = Registration & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Registration; }; }; /** * Contains response data for the update operation. */ export type RegistrationsUpdateResponse = Registration & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Registration; }; }; /** * Contains response data for the getActivationKey operation. */ export type RegistrationsGetActivationKeyResponse = ActivationKeyResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ActivationKeyResult; }; }; /** * Contains response data for the listNext operation. */ export type RegistrationsListNextResponse = RegistrationList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RegistrationList; }; }; /** * Contains response data for the list operation. */ export type CustomerSubscriptionsListResponse = CustomerSubscriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CustomerSubscriptionList; }; }; /** * Contains response data for the get operation. */ export type CustomerSubscriptionsGetResponse = CustomerSubscription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CustomerSubscription; }; }; /** * Contains response data for the create operation. */ export type CustomerSubscriptionsCreateResponse = CustomerSubscription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CustomerSubscription; }; }; /** * Contains response data for the listNext operation. */ export type CustomerSubscriptionsListNextResponse = CustomerSubscriptionList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CustomerSubscriptionList; }; };
the_stack
import {ExportNs} from '../../esl-utils/environment/export-ns'; import {ESLBaseElement, attr, boolAttr} from '../../esl-base-element/core'; import {bind} from '../../esl-utils/decorators/bind'; import {ready} from '../../esl-utils/decorators/ready'; import {rafDecorator} from '../../esl-utils/async/raf'; import {EventUtils} from '../../esl-utils/dom/events'; import {isRelativeNode} from '../../esl-utils/dom/traversing'; import {TraversingQuery} from '../../esl-traversing-query/core'; import {RTLUtils} from '../../esl-utils/dom/rtl'; /** * ESLScrollbar is a reusable web component that replaces the browser's default scrollbar with * a custom scrollbar implementation. * * @author Yuliya Adamskaya */ @ExportNs('Scrollbar') export class ESLScrollbar extends ESLBaseElement { public static is = 'esl-scrollbar'; /** Horizontal scroll orientation marker */ @boolAttr() public horizontal: boolean; /** Target element {@link TraversingQuery} selector. Parent element by default */ @attr({defaultValue: '::parent'}) public target: string; /** Custom class for thumb element. 'scrollbar-thumb' by default */ @attr({defaultValue: 'scrollbar-thumb'}) public thumbClass: string; /** Custom class for track element area. 'scrollbar-track' by default */ @attr({defaultValue: 'scrollbar-track'}) public trackClass: string; /** @readonly Dragging state marker */ @boolAttr({readonly: true}) public dragging: boolean; /** @readonly Inactive state marker */ @boolAttr({readonly: true}) public inactive: boolean; /** @readonly Indicates that the scroll is at the beginning */ @boolAttr({readonly: true}) public atStart: boolean; /** @readonly Indicates that the scroll is at the end */ @boolAttr({readonly: true}) public atEnd: boolean; protected $scrollbarThumb: HTMLElement; protected $scrollbarTrack: HTMLElement; protected _$target: HTMLElement | null; protected _initialPosition: number; protected _initialMousePosition: number; protected deferredRefresh = rafDecorator(() => this.refresh()); protected _resizeObserver = new ResizeObserver(this.deferredRefresh); protected _mutationObserver = new MutationObserver((rec) => this.updateContentObserve(rec)); static get observedAttributes() { return ['target', 'horizontal']; } @ready protected connectedCallback() { super.connectedCallback(); this.findTarget(); this.render(); this.bindEvents(); } @ready protected disconnectedCallback() { this.unbindEvents(); } protected attributeChangedCallback(attrName: string, oldVal: string, newVal: string) { if (!this.connected && oldVal === newVal) return; if (attrName === 'target') this.findTarget(); if (attrName === 'horizontal') this.refresh(); } protected findTarget() { this.$target = this.target ? TraversingQuery.first(this.target, this) as HTMLElement : null; } /** Target element to observe and scroll */ public get $target() { return this._$target || null; } public set $target(content: HTMLElement | null) { this.unbindTargetEvents(); this._$target = content; this.bindTargetEvents(); this.deferredRefresh(); } protected render() { this.innerHTML = ''; this.$scrollbarTrack = document.createElement('div'); this.$scrollbarTrack.className = this.trackClass; this.$scrollbarThumb = document.createElement('div'); this.$scrollbarThumb.className = this.thumbClass; this.$scrollbarTrack.appendChild(this.$scrollbarThumb); this.appendChild(this.$scrollbarTrack); } protected bindEvents() { this.addEventListener('click', this._onClick); this.$scrollbarThumb.addEventListener('mousedown', this._onMouseDown); window.addEventListener('esl:refresh', this._onRefresh); } protected bindTargetEvents() { if (!this.$target) return; if (document.documentElement === this.$target) { window.addEventListener('resize', this._onRefresh, {passive: true}); window.addEventListener('scroll', this._onRefresh, {passive: true}); } else { this._resizeObserver.observe(this.$target); this._mutationObserver.observe(this.$target, {childList: true}); Array.from(this.$target.children).forEach((el) => this._resizeObserver.observe(el)); this.$target.addEventListener('scroll', this._onRefresh, {passive: true}); } } protected updateContentObserve(recs: MutationRecord[] = []) { if (!this.$target) return; const contentChanges = recs.filter((rec) => rec.type === 'childList'); contentChanges.forEach((rec) => { Array.from(rec.addedNodes) .filter((el) => el instanceof Element) .forEach((el: Element) => this._resizeObserver.observe(el)); Array.from(rec.removedNodes) .filter((el) => el instanceof Element) .forEach((el: Element) => this._resizeObserver.unobserve(el)); }); if (contentChanges.length) this.deferredRefresh(); } protected unbindEvents() { this.removeEventListener('click', this._onClick); this.$scrollbarThumb.removeEventListener('mousedown', this._onMouseDown); this.unbindTargetEvents(); window.removeEventListener('esl:refresh', this._onRefresh); } protected unbindTargetEvents() { if (!this.$target) return; if (document.documentElement === this.$target) { window.removeEventListener('resize', this._onRefresh); window.removeEventListener('scroll', this._onRefresh); } else { this._resizeObserver.disconnect(); this._mutationObserver.disconnect(); this.$target.removeEventListener('scroll', this._onRefresh); } } /** @readonly Scrollable distance size value (px) */ public get scrollableSize() { if (!this.$target) return 0; return this.horizontal ? this.$target.scrollWidth - this.$target.clientWidth : this.$target.scrollHeight - this.$target.clientHeight; } /** @readonly Track size value (px) */ public get trackOffset() { return this.horizontal ? this.$scrollbarTrack.offsetWidth : this.$scrollbarTrack.offsetHeight; } /** @readonly Thumb size value (px) */ public get thumbOffset() { return this.horizontal ? this.$scrollbarThumb.offsetWidth : this.$scrollbarThumb.offsetHeight; } /** @readonly Relative thumb size value (between 0.0 and 1.0) */ public get thumbSize() { // behave as native scroll if (!this.$target || !this.$target.scrollWidth || !this.$target.scrollHeight) return 1; const areaSize = this.horizontal ? this.$target.clientWidth : this.$target.clientHeight; const scrollSize = this.horizontal ? this.$target.scrollWidth : this.$target.scrollHeight; return Math.min((areaSize + 1) / scrollSize, 1); } /** Relative position value (between 0.0 and 1.0) */ public get position() { if (!this.$target) return 0; const scrollOffset = this.horizontal ? RTLUtils.normalizeScrollLeft(this.$target) : this.$target.scrollTop; return this.scrollableSize ? (scrollOffset / this.scrollableSize) : 0; } public set position(position) { this.scrollTargetTo(this.scrollableSize * this.normalizePosition(position)); this.update(); } /** Normalize position value (between 0.0 and 1.0) */ protected normalizePosition(position: number) { const relativePosition = Math.min(1, Math.max(0, position)); if (this.$target && !RTLUtils.isRtl(this.$target)) return relativePosition; return RTLUtils.scrollType === 'negative' ? (relativePosition - 1) : (1 - relativePosition); } /** Scroll target element to passed position */ protected scrollTargetTo(pos: number) { if (!this.$target) return; this.$target.scrollTo({ [this.horizontal ? 'left' : 'top']: pos, behavior: this.dragging ? 'auto' : 'smooth' }); } /** Update thumb size and position */ public update() { this.$$fire('change:scroll', {bubbles: false}); if (!this.$scrollbarThumb || !this.$scrollbarTrack) return; const thumbSize = this.trackOffset * this.thumbSize; const thumbPosition = (this.trackOffset - thumbSize) * this.position; const style = { [this.horizontal ? 'left' : 'top']: `${thumbPosition}px`, [this.horizontal ? 'width' : 'height']: `${thumbSize}px` }; Object.assign(this.$scrollbarThumb.style, style); } /** Update auxiliary markers */ public updateMarkers() { const {position, thumbSize} = this; this.toggleAttribute('at-start', thumbSize < 1 && position <= 0); this.toggleAttribute('at-end', thumbSize < 1 && position >= 1); this.toggleAttribute('inactive', thumbSize >= 1); } /** Refresh scroll state and position */ public refresh() { this.update(); this.updateMarkers(); } // Event listeners /** `mousedown` event to track thumb drag start */ @bind protected _onMouseDown(event: MouseEvent) { this.toggleAttribute('dragging', true); this.$target?.style.setProperty('scroll-behavior', 'auto'); this._initialPosition = this.position; this._initialMousePosition = this.horizontal ? event.clientX : event.clientY; // Attach drag listeners window.addEventListener('mousemove', this._onMouseMove); window.addEventListener('mouseup', this._onMouseUp); window.addEventListener('click', this._onBodyClick, {capture: true}); // Prevents default text selection, etc. event.preventDefault(); } /** Set position on drug */ protected _dragToCoordinate(mousePosition: number) { const positionChange = mousePosition - this._initialMousePosition; const scrollableAreaHeight = this.trackOffset - this.thumbOffset; const absChange = scrollableAreaHeight ? (positionChange / scrollableAreaHeight) : 0; this.position = this._initialPosition + absChange; this.updateMarkers(); } protected _deferredDragToCoordinate = rafDecorator(this._dragToCoordinate); /** `mousemove` document handler for thumb drag event. Active only if drag action is active */ @bind protected _onMouseMove(event: MouseEvent) { if (!this.dragging) return; // Request position update this._deferredDragToCoordinate(this.horizontal ? event.clientX : event.clientY); // Prevents default text selection, etc. event.preventDefault(); event.stopPropagation(); } /** `mouseup` short-time document handler for drag end action */ @bind protected _onMouseUp() { this.toggleAttribute('dragging', false); this.$target?.style.removeProperty('scroll-behavior'); // Unbind drag listeners window.removeEventListener('mousemove', this._onMouseMove); window.removeEventListener('mouseup', this._onMouseUp); } /** Body `click` short-time handler to prevent clicks event on thumb drag. Handles capture phase */ @bind protected _onBodyClick(event: MouseEvent) { event.stopImmediatePropagation(); window.removeEventListener('click', this._onBodyClick, {capture: true}); } /** Handler for track clicks. Move scroll to selected position */ @bind protected _onClick(event: MouseEvent) { if (event.target !== this.$scrollbarTrack && event.target !== this) return; const clickCoordinates = EventUtils.normalizeCoordinates(event, this.$scrollbarTrack); const clickPosition = this.horizontal ? clickCoordinates.x : clickCoordinates.y; const freeTrackArea = this.trackOffset - this.thumbOffset; // px const clickPositionNoOffset = clickPosition - this.thumbOffset / 2; const newPosition = clickPositionNoOffset / freeTrackArea; // abs % to track this.position = Math.min(this.position + this.thumbSize, Math.max(this.position - this.thumbSize, newPosition)); } /** * Handler for refresh events to update the scroll. * @param event - instance of 'resize' or 'scroll' or 'esl:refresh' event. */ @bind protected _onRefresh(event: Event) { const target = event.target as HTMLElement; if (event.type === 'scroll' && this.dragging) return; if (event.type === 'esl:refresh' && !isRelativeNode(target.parentNode, this.$target)) return; this.deferredRefresh(); } } declare global { export interface ESLLibrary { Scrollbar: typeof ESLScrollbar; } export interface HTMLElementTagNameMap { 'esl-scrollbar': ESLScrollbar; } }
the_stack
import { isFunction, isString } from "../interfaces.js"; import { Binding, ChildContext, ExecutionContext, ItemContext, } from "../observation/observable.js"; import { bind, HTMLBindingDirective, oneTime } from "./binding.js"; import { Compiler } from "./compiler.js"; import { AddViewBehaviorFactory, Aspect, Aspected, HTMLDirective, HTMLDirectiveDefinition, ViewBehaviorFactory, } from "./html-directive.js"; import { nextId } from "./markup.js"; import type { ElementView, HTMLView, SyntheticView } from "./view.js"; /** * A template capable of creating views specifically for rendering custom elements. * @public */ export interface ElementViewTemplate<TSource = any, TParent = any> { /** * Used for TypeScript purposes only. * Do not use. */ type: "element"; /** * Creates an ElementView instance based on this template definition. * @param hostBindingTarget - The element that host behaviors will be bound to. */ create(hostBindingTarget: Element): ElementView<TSource, TParent>; /** * Creates an HTMLView from this template, binds it to the source, and then appends it to the host. * @param source - The data source to bind the template to. * @param host - The Element where the template will be rendered. * @param hostBindingTarget - An HTML element to target the host bindings at if different from the * host that the template is being attached to. */ render( source: TSource, host: Node, hostBindingTarget?: Element ): ElementView<TSource, TParent>; } /** * A template capable of rendering views not specifically connected to custom elements. * @public */ export interface SyntheticViewTemplate< TSource = any, TParent = any, TContext extends ExecutionContext<TParent> = ExecutionContext<TParent> > { /** * Used for TypeScript purposes only. * Do not use. */ type: string; /** * Creates a SyntheticView instance based on this template definition. */ create(): SyntheticView<TSource, TParent, TContext>; } /** * A template capable of rendering child views not specifically connected to custom elements. * @public */ export interface ChildViewTemplate<TSource = any, TParent = any> { /** * Used for TypeScript purposes only. * Do not use. */ type: "child"; /** * Creates a SyntheticView instance based on this template definition. */ create(): SyntheticView<TSource, TParent, ChildContext<TParent>>; } /** * A template capable of rendering item views not specifically connected to custom elements. * @public */ export interface ItemViewTemplate<TSource = any, TParent = any> { /** * Used for TypeScript purposes only. * Do not use. */ type: "item"; /** * Creates a SyntheticView instance based on this template definition. */ create(): SyntheticView<TSource, TParent, ItemContext<TParent>>; } /** * The result of a template compilation operation. * @public */ export interface HTMLTemplateCompilationResult< TSource = any, TParent = any, TContext extends ExecutionContext<TParent> = ExecutionContext<TParent> > { /** * Creates a view instance. * @param hostBindingTarget - The host binding target for the view. */ createView(hostBindingTarget?: Element): HTMLView<TSource, TParent, TContext>; } /** * A template capable of creating HTMLView instances or rendering directly to DOM. * @public */ export class ViewTemplate< TSource = any, TParent = any, TContext extends ExecutionContext<TParent> = ExecutionContext > implements ElementViewTemplate<TSource, TParent>, SyntheticViewTemplate<TSource, TParent, TContext> { private result: HTMLTemplateCompilationResult< TSource, TParent, TContext > | null = null; /** * Used for TypeScript purposes only. * Do not use. */ type: any; /** * The html representing what this template will * instantiate, including placeholders for directives. */ public readonly html: string | HTMLTemplateElement; /** * The directives that will be connected to placeholders in the html. */ public readonly factories: Record<string, ViewBehaviorFactory>; /** * Creates an instance of ViewTemplate. * @param html - The html representing what this template will instantiate, including placeholders for directives. * @param factories - The directives that will be connected to placeholders in the html. */ public constructor( html: string | HTMLTemplateElement, factories: Record<string, ViewBehaviorFactory> ) { this.html = html; this.factories = factories; } /** * Creates an HTMLView instance based on this template definition. * @param hostBindingTarget - The element that host behaviors will be bound to. */ public create(hostBindingTarget?: Element): HTMLView<TSource, TParent, TContext> { if (this.result === null) { this.result = Compiler.compile<TSource, TParent, TContext>( this.html, this.factories ); } return this.result!.createView(hostBindingTarget); } /** * Creates an HTMLView from this template, binds it to the source, and then appends it to the host. * @param source - The data source to bind the template to. * @param host - The Element where the template will be rendered. * @param hostBindingTarget - An HTML element to target the host bindings at if different from the * host that the template is being attached to. */ public render( source: TSource, host: Node, hostBindingTarget?: Element, context?: TContext ): HTMLView<TSource, TParent, TContext> { const view = this.create(hostBindingTarget ?? (host as any)); view.bind(source, context ?? (ExecutionContext.default as TContext)); view.appendTo(host); return view; } } // Much thanks to LitHTML for working this out! const lastAttributeNameRegex = /* eslint-disable-next-line no-control-regex */ /([ \x09\x0a\x0c\x0d])([^\0-\x1F\x7F-\x9F "'>=/]+)([ \x09\x0a\x0c\x0d]*=[ \x09\x0a\x0c\x0d]*(?:[^ \x09\x0a\x0c\x0d"'`<>=]*|"[^"]*|'[^']*))$/; /** * A marker interface used to capture types when interpolating Directive helpers * into templates. * @public */ /* eslint-disable-next-line */ export interface CaptureType<TSource> {} /** * Represents the types of values that can be interpolated into a template. * @public */ export type TemplateValue< TSource, TParent = any, TContext extends ExecutionContext<TParent> = ExecutionContext<TParent> > = Binding<TSource, any, TContext> | HTMLDirective | CaptureType<TSource>; function createAspectedHTML( value: HTMLDirective & Aspected, prevString: string, add: AddViewBehaviorFactory ): string { const match = lastAttributeNameRegex.exec(prevString); if (match !== null) { Aspect.assign(value as Aspected, match[2]); } return value.createHTML(add); } /** * Transforms a template literal string into a ViewTemplate. * @param strings - The string fragments that are interpolated with the values. * @param values - The values that are interpolated with the string fragments. * @remarks * The html helper supports interpolation of strings, numbers, binding expressions, * other template instances, and Directive instances. * @public */ export function html< TSource = any, TParent = any, TContext extends ExecutionContext<TParent> = ExecutionContext<TParent> >( strings: TemplateStringsArray, ...values: TemplateValue<TSource, TParent, TContext>[] ): ViewTemplate<TSource, TParent> { let html = ""; const factories: Record<string, ViewBehaviorFactory> = Object.create(null); const add = (factory: ViewBehaviorFactory): string => { const id = factory.id ?? (factory.id = nextId()); factories[id] = factory; return id; }; for (let i = 0, ii = strings.length - 1; i < ii; ++i) { const currentString = strings[i]; const currentValue = values[i]; let definition: HTMLDirectiveDefinition | undefined; html += currentString; if (isFunction(currentValue)) { html += createAspectedHTML( bind(currentValue) as HTMLBindingDirective, currentString, add ); } else if (isString(currentValue)) { const match = lastAttributeNameRegex.exec(currentString); if (match !== null) { const directive = bind( () => currentValue, oneTime ) as HTMLBindingDirective; Aspect.assign(directive, match[2]); html += directive.createHTML(add); } else { html += currentValue; } } else if ((definition = HTMLDirective.getForInstance(currentValue)) === void 0) { html += createAspectedHTML( bind(() => currentValue, oneTime) as HTMLBindingDirective, currentString, add ); } else { if (definition.aspected) { html += createAspectedHTML( currentValue as HTMLDirective & Aspected, currentString, add ); } else { html += (currentValue as HTMLDirective).createHTML(add); } } } return new ViewTemplate<TSource, TParent, any>( html + strings[strings.length - 1], factories ); } /** * Transforms a template literal string into a ChildViewTemplate. * @param strings - The string fragments that are interpolated with the values. * @param values - The values that are interpolated with the string fragments. * @remarks * The html helper supports interpolation of strings, numbers, binding expressions, * other template instances, and Directive instances. * @public */ export const child: <TChild = any, TParent = any>( strings: TemplateStringsArray, ...values: TemplateValue<TChild, TParent, ChildContext<TParent>>[] ) => ChildViewTemplate<TChild, TParent> = html as any; /** * Transforms a template literal string into an ItemViewTemplate. * @param strings - The string fragments that are interpolated with the values. * @param values - The values that are interpolated with the string fragments. * @remarks * The html helper supports interpolation of strings, numbers, binding expressions, * other template instances, and Directive instances. * @public */ export const item: <TItem = any, TParent = any>( strings: TemplateStringsArray, ...values: TemplateValue<TItem, TParent, ItemContext<TParent>>[] ) => ItemViewTemplate<TItem, TParent> = html as any;
the_stack
import * as cxschema from '@aws-cdk/cloud-assembly-schema'; import * as aws from 'aws-sdk'; import * as AWS from 'aws-sdk-mock'; import { LoadBalancerListenerContextProviderPlugin, LoadBalancerContextProviderPlugin, tagsMatch, describeListenersByLoadBalancerArn, describeTags, describeLoadBalancers } from '../../lib/context-providers/load-balancers'; import { MockSdkProvider } from '../util/mock-sdk'; AWS.setSDK(require.resolve('aws-sdk')); const mockSDK = new MockSdkProvider(); type AwsCallback<T> = (err: Error | null, val: T) => void; afterEach(done => { AWS.restore(); done(); }); describe('utilities', () => { test('describeTags yields tags by chunk', async () => { const resourceTags: Record<string, aws.ELBv2.TagDescription> = {}; for (const resourceArn of [...Array(100)].map((_, i) => `arn:load-balancer-${i}`)) { resourceTags[resourceArn] = { ResourceArn: resourceArn, Tags: [ { Key: 'name', Value: resourceArn }, ], }; }; AWS.mock('ELBv2', 'describeTags', (_params: aws.ELBv2.DescribeTagsInput, cb: AwsCallback<aws.ELBv2.DescribeTagsOutput>) => { expect(_params.ResourceArns.length).toBeLessThanOrEqual(20); cb(null, { TagDescriptions: _params.ResourceArns.map(resourceArn => ({ ResourceArn: resourceArn, Tags: [ { Key: 'name', Value: resourceArn }, ], })), }); }); const elbv2 = (await mockSDK.forEnvironment()).sdk.elbv2(); const resourceTagsOut: Record<string, aws.ELBv2.TagDescription> = {}; for await (const tagDescription of describeTags(elbv2, Object.keys(resourceTags))) { resourceTagsOut[tagDescription.ResourceArn!] = tagDescription; } expect(resourceTagsOut).toEqual(resourceTags); }); test('describeListenersByLoadBalancerArn traverses pages', async () => { // arn:listener-0, arn:listener-1, ..., arn:listener-99 const listenerArns = [...Array(100)].map((_, i) => `arn:listener-${i}`); expect(listenerArns[0]).toEqual('arn:listener-0'); AWS.mock('ELBv2', 'describeListeners', (_params: aws.ELBv2.DescribeListenersInput, cb: AwsCallback<aws.ELBv2.DescribeListenersOutput>) => { const start = parseInt(_params.Marker ?? '0'); const end = start + 10; const slice = listenerArns.slice(start, end); cb(null, { Listeners: slice.map(arn => ({ ListenerArn: arn, })), NextMarker: end < listenerArns.length ? end.toString() : undefined, }); }); const elbv2 = (await mockSDK.forEnvironment()).sdk.elbv2(); const listenerArnsFromPages = Array<string>(); for await (const listener of describeListenersByLoadBalancerArn(elbv2, ['arn:load-balancer'])) { listenerArnsFromPages.push(listener.ListenerArn!); } expect(listenerArnsFromPages).toEqual(listenerArns); }); test('describeLoadBalancers traverses pages', async () => { const loadBalancerArns = [...Array(100)].map((_, i) => `arn:load-balancer-${i}`); expect(loadBalancerArns[0]).toEqual('arn:load-balancer-0'); AWS.mock('ELBv2', 'describeLoadBalancers', (_params: aws.ELBv2.DescribeLoadBalancersInput, cb: AwsCallback<aws.ELBv2.DescribeLoadBalancersOutput>) => { const start = parseInt(_params.Marker ?? '0'); const end = start + 10; const slice = loadBalancerArns.slice(start, end); cb(null, { LoadBalancers: slice.map(loadBalancerArn => ({ LoadBalancerArn: loadBalancerArn, })), NextMarker: end < loadBalancerArns.length ? end.toString() : undefined, }); }); const elbv2 = (await mockSDK.forEnvironment()).sdk.elbv2(); const loadBalancerArnsFromPages = (await describeLoadBalancers(elbv2, {})).map(l => l.LoadBalancerArn!); expect(loadBalancerArnsFromPages).toEqual(loadBalancerArns); }); describe('tagsMatch', () => { test('all tags match', () => { const tagDescription = { ResourceArn: 'arn:whatever', Tags: [{ Key: 'some', Value: 'tag' }], }; const requiredTags = [ { key: 'some', value: 'tag' }, ]; expect(tagsMatch(tagDescription, requiredTags)).toEqual(true); }); test('extra tags match', () => { const tagDescription = { ResourceArn: 'arn:whatever', Tags: [ { Key: 'some', Value: 'tag' }, { Key: 'other', Value: 'tag2' }, ], }; const requiredTags = [ { key: 'some', value: 'tag' }, ]; expect(tagsMatch(tagDescription, requiredTags)).toEqual(true); }); test('no tags matches no tags', () => { const tagDescription = { ResourceArn: 'arn:whatever', Tags: [], }; expect(tagsMatch(tagDescription, [])).toEqual(true); }); test('one tag matches of several', () => { const tagDescription = { ResourceArn: 'arn:whatever', Tags: [{ Key: 'some', Value: 'tag' }], }; const requiredTags = [ { key: 'some', value: 'tag' }, { key: 'other', value: 'value' }, ]; expect(tagsMatch(tagDescription, requiredTags)).toEqual(false); }); test('undefined tag does not error', () => { const tagDescription = { ResourceArn: 'arn:whatever', Tags: [{ Key: 'some' }], }; const requiredTags = [ { key: 'some', value: 'tag' }, { key: 'other', value: 'value' }, ]; expect(tagsMatch(tagDescription, requiredTags)).toEqual(false); }); }); }); describe('load balancer context provider plugin', () => { test('errors when no matches are found', async () => { // GIVEN const provider = new LoadBalancerContextProviderPlugin(mockSDK); mockALBLookup({ loadBalancers: [], }); // WHEN await expect( provider.getValue({ account: '1234', region: 'us-east-1', loadBalancerType: cxschema.LoadBalancerType.APPLICATION, loadBalancerArn: 'arn:load-balancer1', }), ).rejects.toThrow(/No load balancers found/i); }); test('errors when multiple load balancers match', async () => { // GIVEN const provider = new LoadBalancerContextProviderPlugin(mockSDK); mockALBLookup({ loadBalancers: [ { IpAddressType: 'ipv4', LoadBalancerArn: 'arn:load-balancer1', DNSName: 'dns1.example.com', CanonicalHostedZoneId: 'Z1234', SecurityGroups: ['sg-1234'], VpcId: 'vpc-1234', Type: 'application', }, { IpAddressType: 'ipv4', LoadBalancerArn: 'arn:load-balancer2', DNSName: 'dns2.example.com', CanonicalHostedZoneId: 'Z1234', SecurityGroups: ['sg-1234'], VpcId: 'vpc-1234', Type: 'application', }, ], describeTagsExpected: { ResourceArns: ['arn:load-balancer1', 'arn:load-balancer2'] }, tagDescriptions: [ { ResourceArn: 'arn:load-balancer1', Tags: [ { Key: 'some', Value: 'tag' }, ], }, { ResourceArn: 'arn:load-balancer2', Tags: [ { Key: 'some', Value: 'tag' }, ], }, ], }); // WHEN await expect( provider.getValue({ account: '1234', region: 'us-east-1', loadBalancerType: cxschema.LoadBalancerType.APPLICATION, loadBalancerTags: [ { key: 'some', value: 'tag' }, ], }), ).rejects.toThrow(/Multiple load balancers found/i); }); test('looks up by arn', async () => { // GIVEN const provider = new LoadBalancerContextProviderPlugin(mockSDK); mockALBLookup({ describeLoadBalancersExpected: { LoadBalancerArns: ['arn:load-balancer1'] }, loadBalancers: [ { IpAddressType: 'ipv4', LoadBalancerArn: 'arn:load-balancer1', DNSName: 'dns.example.com', CanonicalHostedZoneId: 'Z1234', SecurityGroups: ['sg-1234'], VpcId: 'vpc-1234', Type: 'application', }, ], }); // WHEN const result = await provider.getValue({ account: '1234', region: 'us-east-1', loadBalancerType: cxschema.LoadBalancerType.APPLICATION, loadBalancerArn: 'arn:load-balancer1', }); // THEN expect(result.ipAddressType).toEqual('ipv4'); expect(result.loadBalancerArn).toEqual('arn:load-balancer1'); expect(result.loadBalancerCanonicalHostedZoneId).toEqual('Z1234'); expect(result.loadBalancerDnsName).toEqual('dns.example.com'); expect(result.securityGroupIds).toEqual(['sg-1234']); expect(result.vpcId).toEqual('vpc-1234'); }); test('looks up by tags', async() => { // GIVEN const provider = new LoadBalancerContextProviderPlugin(mockSDK); mockALBLookup({ loadBalancers: [ { IpAddressType: 'ipv4', LoadBalancerArn: 'arn:load-balancer1', DNSName: 'dns1.example.com', CanonicalHostedZoneId: 'Z1234', SecurityGroups: ['sg-1234'], VpcId: 'vpc-1234', Type: 'application', }, { IpAddressType: 'ipv4', LoadBalancerArn: 'arn:load-balancer2', DNSName: 'dns2.example.com', CanonicalHostedZoneId: 'Z1234', SecurityGroups: ['sg-1234'], VpcId: 'vpc-1234', Type: 'application', }, ], describeTagsExpected: { ResourceArns: ['arn:load-balancer1', 'arn:load-balancer2'] }, tagDescriptions: [ { ResourceArn: 'arn:load-balancer1', Tags: [ { Key: 'some', Value: 'tag' }, ], }, { ResourceArn: 'arn:load-balancer2', Tags: [ { Key: 'some', Value: 'tag' }, { Key: 'second', Value: 'tag2' }, ], }, ], }); // WHEN const result = await provider.getValue({ account: '1234', region: 'us-east-1', loadBalancerType: cxschema.LoadBalancerType.APPLICATION, loadBalancerTags: [ { key: 'some', value: 'tag' }, { key: 'second', value: 'tag2' }, ], }); expect(result.loadBalancerArn).toEqual('arn:load-balancer2'); }); test('filters by type', async () => { // GIVEN const provider = new LoadBalancerContextProviderPlugin(mockSDK); mockALBLookup({ loadBalancers: [ { IpAddressType: 'ipv4', Type: 'network', LoadBalancerArn: 'arn:load-balancer1', DNSName: 'dns1.example.com', CanonicalHostedZoneId: 'Z1234', SecurityGroups: ['sg-1234'], VpcId: 'vpc-1234', }, { IpAddressType: 'ipv4', Type: 'application', LoadBalancerArn: 'arn:load-balancer2', DNSName: 'dns2.example.com', CanonicalHostedZoneId: 'Z1234', SecurityGroups: ['sg-1234'], VpcId: 'vpc-1234', }, ], tagDescriptions: [ { ResourceArn: 'arn:load-balancer1', Tags: [{ Key: 'some', Value: 'tag' }], }, { ResourceArn: 'arn:load-balancer2', Tags: [{ Key: 'some', Value: 'tag' }], }, ], }); // WHEN const loadBalancer = await provider.getValue({ account: '1234', region: 'us-east-1', loadBalancerTags: [{ key: 'some', value: 'tag' }], loadBalancerType: cxschema.LoadBalancerType.APPLICATION, }); expect(loadBalancer.loadBalancerArn).toEqual('arn:load-balancer2'); }); }); describe('load balancer listener context provider plugin', () => { test('errors when no associated load balancers match', async () => { // GIVEN const provider = new LoadBalancerListenerContextProviderPlugin(mockSDK); mockALBLookup({ loadBalancers: [], }); // WHEN await expect( provider.getValue({ account: '1234', region: 'us-east-1', loadBalancerType: cxschema.LoadBalancerType.APPLICATION, loadBalancerTags: [{ key: 'some', value: 'tag' }], }), ).rejects.toThrow(/No associated load balancers found/i); }); test('errors when no listeners match', async () => { // GIVEN const provider = new LoadBalancerListenerContextProviderPlugin(mockSDK); mockALBLookup({ loadBalancers: [ { LoadBalancerArn: 'arn:load-balancer', Type: 'application', }, ], listeners: [ { LoadBalancerArn: 'arn:load-balancer', ListenerArn: 'arn:listener', Port: 80, Protocol: 'HTTP', }, ], }); // WHEN await expect( provider.getValue({ account: '1234', region: 'us-east-1', loadBalancerType: cxschema.LoadBalancerType.APPLICATION, loadBalancerArn: 'arn:load-balancer', listenerPort: 443, listenerProtocol: cxschema.LoadBalancerListenerProtocol.HTTPS, }), ).rejects.toThrow(/No load balancer listeners found/i); }); test('errors when multiple listeners match', async () => { // GIVEN const provider = new LoadBalancerListenerContextProviderPlugin(mockSDK); mockALBLookup({ loadBalancers: [ { LoadBalancerArn: 'arn:load-balancer', Type: 'application', }, { LoadBalancerArn: 'arn:load-balancer2', Type: 'application', }, ], tagDescriptions: [ { ResourceArn: 'arn:load-balancer', Tags: [{ Key: 'some', Value: 'tag' }], }, { ResourceArn: 'arn:load-balancer2', Tags: [{ Key: 'some', Value: 'tag' }], }, ], listeners: [ { LoadBalancerArn: 'arn:load-balancer', ListenerArn: 'arn:listener', Port: 80, Protocol: 'HTTP', }, { LoadBalancerArn: 'arn:load-balancer2', ListenerArn: 'arn:listener2', Port: 80, Protocol: 'HTTP', }, ], }); // WHEN await expect( provider.getValue({ account: '1234', region: 'us-east-1', loadBalancerType: cxschema.LoadBalancerType.APPLICATION, loadBalancerTags: [{ key: 'some', value: 'tag' }], listenerPort: 80, listenerProtocol: cxschema.LoadBalancerListenerProtocol.HTTP, }), ).rejects.toThrow(/Multiple load balancer listeners/i); }); test('looks up by listener arn', async () => { // GIVEN const provider = new LoadBalancerListenerContextProviderPlugin(mockSDK); mockALBLookup({ describeListenersExpected: { ListenerArns: ['arn:listener-arn'] }, listeners: [ { ListenerArn: 'arn:listener-arn', LoadBalancerArn: 'arn:load-balancer-arn', Port: 999, }, ], describeLoadBalancersExpected: { LoadBalancerArns: ['arn:load-balancer-arn'] }, loadBalancers: [ { LoadBalancerArn: 'arn:load-balancer-arn', SecurityGroups: ['sg-1234', 'sg-2345'], Type: 'application', }, ], }); // WHEN const listener = await provider.getValue({ account: '1234', region: 'us-east-1', loadBalancerType: cxschema.LoadBalancerType.APPLICATION, listenerArn: 'arn:listener-arn', }); // THEN expect(listener.listenerArn).toEqual('arn:listener-arn'); expect(listener.listenerPort).toEqual(999); expect(listener.securityGroupIds).toEqual(['sg-1234', 'sg-2345']); }); test('looks up by associated load balancer arn', async () => { // GIVEN const provider = new LoadBalancerListenerContextProviderPlugin(mockSDK); mockALBLookup({ describeLoadBalancersExpected: { LoadBalancerArns: ['arn:load-balancer-arn1'] }, loadBalancers: [ { LoadBalancerArn: 'arn:load-balancer-arn1', SecurityGroups: ['sg-1234'], Type: 'application', }, ], describeListenersExpected: { LoadBalancerArn: 'arn:load-balancer-arn1' }, listeners: [ { // This one ListenerArn: 'arn:listener-arn1', LoadBalancerArn: 'arn:load-balancer-arn1', Port: 80, }, ], }); // WHEN const listener = await provider.getValue({ account: '1234', region: 'us-east-1', loadBalancerType: cxschema.LoadBalancerType.APPLICATION, loadBalancerArn: 'arn:load-balancer-arn1', }); // THEN expect(listener.listenerArn).toEqual('arn:listener-arn1'); expect(listener.listenerPort).toEqual(80); expect(listener.securityGroupIds).toEqual(['sg-1234']); }); test('looks up by associated load balancer tags', async () => { // GIVEN const provider = new LoadBalancerListenerContextProviderPlugin(mockSDK); mockALBLookup({ describeLoadBalancersExpected: { LoadBalancerArns: undefined }, loadBalancers: [ { // This one should have the wrong tags LoadBalancerArn: 'arn:load-balancer-arn1', SecurityGroups: ['sg-1234', 'sg-2345'], Type: 'application', }, { // Expecting this one LoadBalancerArn: 'arn:load-balancer-arn2', SecurityGroups: ['sg-3456', 'sg-4567'], Type: 'application', }, ], describeTagsExpected: { ResourceArns: ['arn:load-balancer-arn1', 'arn:load-balancer-arn2'] }, tagDescriptions: [ { ResourceArn: 'arn:load-balancer-arn1', Tags: [], }, { // Expecting this one ResourceArn: 'arn:load-balancer-arn2', Tags: [ { Key: 'some', Value: 'tag' }, ], }, ], describeListenersExpected: { LoadBalancerArn: 'arn:load-balancer-arn2' }, listeners: [ { // This one ListenerArn: 'arn:listener-arn1', LoadBalancerArn: 'arn:load-balancer-arn2', Port: 80, }, { ListenerArn: 'arn:listener-arn2', LoadBalancerArn: 'arn:load-balancer-arn2', Port: 999, }, ], }); // WHEN const listener = await provider.getValue({ account: '1234', region: 'us-east-1', loadBalancerType: cxschema.LoadBalancerType.APPLICATION, loadBalancerTags: [ { key: 'some', value: 'tag' }, ], listenerPort: 999, }); // THEN expect(listener.listenerArn).toEqual('arn:listener-arn2'); expect(listener.listenerPort).toEqual(999); expect(listener.securityGroupIds).toEqual(['sg-3456', 'sg-4567']); }); test('looks up by listener port and proto', async () => { // GIVEN const provider = new LoadBalancerListenerContextProviderPlugin(mockSDK); AWS.mock('ELBv2', 'describeLoadBalancers', (_params: aws.ELBv2.DescribeLoadBalancersInput, cb: AwsCallback<aws.ELBv2.DescribeLoadBalancersOutput>) => { expect(_params).toEqual({}); cb(null, { LoadBalancers: [ { // Shouldn't have any matching listeners IpAddressType: 'ipv4', LoadBalancerArn: 'arn:load-balancer1', DNSName: 'dns1.example.com', CanonicalHostedZoneId: 'Z1234', SecurityGroups: ['sg-1234'], VpcId: 'vpc-1234', Type: 'application', }, { // Should have a matching listener IpAddressType: 'ipv4', LoadBalancerArn: 'arn:load-balancer2', DNSName: 'dns2.example.com', CanonicalHostedZoneId: 'Z1234', SecurityGroups: ['sg-2345'], VpcId: 'vpc-1234', Type: 'application', }, ], }); }); AWS.mock('ELBv2', 'describeTags', (_params: aws.ELBv2.DescribeTagsInput, cb: AwsCallback<aws.ELBv2.DescribeTagsOutput>) => { cb(null, { TagDescriptions: [ { ResourceArn: 'arn:load-balancer1', Tags: [{ Key: 'some', Value: 'tag' }], }, { ResourceArn: 'arn:load-balancer2', Tags: [{ Key: 'some', Value: 'tag' }], }, ], }); }); AWS.mock('ELBv2', 'describeListeners', (params: aws.ELBv2.DescribeListenersInput, cb: AwsCallback<aws.ELBv2.DescribeListenersOutput>) => { if (params.LoadBalancerArn === 'arn:load-balancer1') { cb(null, { Listeners: [ { // Wrong port, wrong protocol => no match ListenerArn: 'arn:listener-arn1', LoadBalancerArn: 'arn:load-balancer1', Protocol: 'HTTP', Port: 80, }, { // Wrong protocol, right port => no match ListenerArn: 'arn:listener-arn3', LoadBalancerArn: 'arn:load-balancer1', Protocol: 'HTTPS', Port: 443, }, { // Wrong port, right protocol => no match ListenerArn: 'arn:listener-arn4', LoadBalancerArn: 'arn:load-balancer1', Protocol: 'TCP', Port: 999, }, ], }); } else if (params.LoadBalancerArn === 'arn:load-balancer2') { cb(null, { Listeners: [ { // Wrong port, wrong protocol => no match ListenerArn: 'arn:listener-arn5', LoadBalancerArn: 'arn:load-balancer2', Protocol: 'HTTP', Port: 80, }, { // Right port, right protocol => match ListenerArn: 'arn:listener-arn6', LoadBalancerArn: 'arn:load-balancer2', Port: 443, Protocol: 'TCP', }, ], }); } else { cb(new Error(`Unexpected request: ${JSON.stringify(params)}'`), {}); } }); // WHEN const listener = await provider.getValue({ account: '1234', region: 'us-east-1', loadBalancerType: cxschema.LoadBalancerType.APPLICATION, loadBalancerTags: [{ key: 'some', value: 'tag' }], listenerProtocol: cxschema.LoadBalancerListenerProtocol.TCP, listenerPort: 443, }); // THEN expect(listener.listenerArn).toEqual('arn:listener-arn6'); expect(listener.listenerPort).toEqual(443); expect(listener.securityGroupIds).toEqual(['sg-2345']); }); test('filters by associated load balancer type', async () => { // GIVEN const provider = new LoadBalancerListenerContextProviderPlugin(mockSDK); mockALBLookup({ describeLoadBalancersExpected: { LoadBalancerArns: undefined }, loadBalancers: [ { // This one has wrong type => no match LoadBalancerArn: 'arn:load-balancer-arn1', SecurityGroups: [], Type: 'application', }, { // Right type => match LoadBalancerArn: 'arn:load-balancer-arn2', SecurityGroups: [], Type: 'network', }, ], tagDescriptions: [ { ResourceArn: 'arn:load-balancer-arn1', Tags: [{ Key: 'some', Value: 'tag' }], }, { ResourceArn: 'arn:load-balancer-arn2', Tags: [{ Key: 'some', Value: 'tag' }], }, ], describeListenersExpected: { LoadBalancerArn: 'arn:load-balancer-arn2' }, listeners: [ { ListenerArn: 'arn:listener-arn2', LoadBalancerArn: 'arn:load-balancer-arn2', Port: 443, }, ], }); // WHEN const listener = await provider.getValue({ account: '1234', region: 'us-east-1', loadBalancerType: cxschema.LoadBalancerType.NETWORK, loadBalancerTags: [{ key: 'some', value: 'tag' }], listenerPort: 443, }); // THEN expect(listener.listenerArn).toEqual('arn:listener-arn2'); expect(listener.listenerPort).toEqual(443); }); test('errors when associated load balancer is wrong type', async () => { // GIVEN const provider = new LoadBalancerListenerContextProviderPlugin(mockSDK); mockALBLookup({ describeListenersExpected: { ListenerArns: ['arn:listener-arn1'] }, listeners: [ { ListenerArn: 'arn:listener-arn1', LoadBalancerArn: 'arn:load-balancer-arn1', Port: 443, }, ], describeLoadBalancersExpected: { LoadBalancerArns: ['arn:load-balancer-arn1'] }, loadBalancers: [ { // This one has wrong type => no match LoadBalancerArn: 'arn:load-balancer-arn1', SecurityGroups: [], Type: 'application', }, ], }); // WHEN await expect( provider.getValue({ account: '1234', region: 'us-east-1', loadBalancerType: cxschema.LoadBalancerType.NETWORK, listenerArn: 'arn:listener-arn1', }), ).rejects.toThrow(/no associated load balancer found/i); }); }); interface ALBLookupOptions { describeLoadBalancersExpected?: any; loadBalancers?: aws.ELBv2.LoadBalancers; describeTagsExpected?: any; tagDescriptions?: aws.ELBv2.TagDescriptions; describeListenersExpected?: any; listeners?: aws.ELBv2.Listeners; } function mockALBLookup(options: ALBLookupOptions) { AWS.mock('ELBv2', 'describeLoadBalancers', (_params: aws.ELBv2.DescribeLoadBalancersInput, cb: AwsCallback<aws.ELBv2.DescribeLoadBalancersOutput>) => { if (options.describeLoadBalancersExpected !== undefined) { expect(_params).toEqual(options.describeLoadBalancersExpected); } cb(null, { LoadBalancers: options.loadBalancers }); }); AWS.mock('ELBv2', 'describeTags', (_params: aws.ELBv2.DescribeTagsInput, cb: AwsCallback<aws.ELBv2.DescribeTagsOutput>) => { if (options.describeTagsExpected !== undefined) { expect(_params).toEqual(options.describeTagsExpected); } cb(null, { TagDescriptions: options.tagDescriptions }); }); AWS.mock('ELBv2', 'describeListeners', (_params: aws.ELBv2.DescribeListenersInput, cb: AwsCallback<aws.ELBv2.DescribeListenersOutput>) => { if (options.describeListenersExpected !== undefined) { expect(_params).toEqual(options.describeListenersExpected); } cb(null, { Listeners: options.listeners }); }); }
the_stack
import { pluck, distinctUntilChanged, map, filter } from "rxjs/operators" import { Ref } from "@nuxtjs/composition-api" import DispatchingStore, { defineDispatchers } from "./DispatchingStore" import { FormDataKeyValue, HoppRESTHeader, HoppRESTParam, HoppRESTReqBody, HoppRESTRequest, RESTReqSchemaVersion, } from "~/helpers/types/HoppRESTRequest" import { HoppRESTResponse } from "~/helpers/types/HoppRESTResponse" import { useStream } from "~/helpers/utils/composables" import { HoppTestResult } from "~/helpers/types/HoppTestResult" import { HoppRESTAuth } from "~/helpers/types/HoppRESTAuth" import { ValidContentTypes } from "~/helpers/utils/contenttypes" import { HoppRequestSaveContext } from "~/helpers/types/HoppRequestSaveContext" type RESTSession = { request: HoppRESTRequest response: HoppRESTResponse | null testResults: HoppTestResult | null saveContext: HoppRequestSaveContext | null } export const defaultRESTRequest: HoppRESTRequest = { v: RESTReqSchemaVersion, endpoint: "https://echo.hoppscotch.io", name: "Untitled request", params: [{ key: "", value: "", active: true }], headers: [{ key: "", value: "", active: true }], method: "GET", auth: { authType: "none", authActive: true, }, preRequestScript: "", testScript: "", body: { contentType: null, body: null, }, } const defaultRESTSession: RESTSession = { request: defaultRESTRequest, response: null, testResults: null, saveContext: null, } const dispatchers = defineDispatchers({ setRequest(_: RESTSession, { req }: { req: HoppRESTRequest }) { return { request: req, } }, setRequestName(curr: RESTSession, { newName }: { newName: string }) { return { request: { ...curr.request, name: newName, }, } }, setEndpoint(curr: RESTSession, { newEndpoint }: { newEndpoint: string }) { return { request: { ...curr.request, endpoint: newEndpoint, }, } }, setParams(curr: RESTSession, { entries }: { entries: HoppRESTParam[] }) { return { request: { ...curr.request, params: entries, }, } }, addParam(curr: RESTSession, { newParam }: { newParam: HoppRESTParam }) { return { request: { ...curr.request, params: [...curr.request.params, newParam], }, } }, updateParam( curr: RESTSession, { index, updatedParam }: { index: number; updatedParam: HoppRESTParam } ) { const newParams = curr.request.params.map((param, i) => { if (i === index) return updatedParam else return param }) return { request: { ...curr.request, params: newParams, }, } }, deleteParam(curr: RESTSession, { index }: { index: number }) { const newParams = curr.request.params.filter((_x, i) => i !== index) return { request: { ...curr.request, params: newParams, }, } }, deleteAllParams(curr: RESTSession) { return { request: { ...curr.request, params: [], }, } }, updateMethod(curr: RESTSession, { newMethod }: { newMethod: string }) { return { request: { ...curr.request, method: newMethod, }, } }, setHeaders(curr: RESTSession, { entries }: { entries: HoppRESTHeader[] }) { return { request: { ...curr.request, headers: entries, }, } }, addHeader(curr: RESTSession, { entry }: { entry: HoppRESTHeader }) { return { request: { ...curr.request, headers: [...curr.request.headers, entry], }, } }, updateHeader( curr: RESTSession, { index, updatedEntry }: { index: number; updatedEntry: HoppRESTHeader } ) { return { request: { ...curr.request, headers: curr.request.headers.map((header, i) => { if (i === index) return updatedEntry else return header }), }, } }, deleteHeader(curr: RESTSession, { index }: { index: number }) { return { request: { ...curr.request, headers: curr.request.headers.filter((_, i) => i !== index), }, } }, deleteAllHeaders(curr: RESTSession) { return { request: { ...curr.request, headers: [], }, } }, setAuth(curr: RESTSession, { newAuth }: { newAuth: HoppRESTAuth }) { return { request: { ...curr.request, auth: newAuth, }, } }, setPreRequestScript(curr: RESTSession, { newScript }: { newScript: string }) { return { request: { ...curr.request, preRequestScript: newScript, }, } }, setTestScript(curr: RESTSession, { newScript }: { newScript: string }) { return { request: { ...curr.request, testScript: newScript, }, } }, setContentType( curr: RESTSession, { newContentType }: { newContentType: ValidContentTypes | null } ) { // TODO: persist body evenafter switching content typees if (curr.request.body.contentType !== "multipart/form-data") { if (newContentType === "multipart/form-data") { // Going from non-formdata to form-data, discard contents and set empty array as body return { request: { ...curr.request, body: <HoppRESTReqBody>{ contentType: "multipart/form-data", body: [], }, }, } } else { // non-formdata to non-formdata, keep body and set content type return { request: { ...curr.request, body: <HoppRESTReqBody>{ contentType: newContentType, body: newContentType === null ? null : (curr.request.body as any)?.body ?? "", }, }, } } } else if (newContentType !== "multipart/form-data") { // Going from formdata to non-formdata, discard contents and set empty string return { request: { ...curr.request, body: <HoppRESTReqBody>{ contentType: newContentType, body: "", }, }, } } else { // form-data to form-data ? just set the content type ¯\_(ツ)_/¯ return { request: { ...curr.request, body: <HoppRESTReqBody>{ contentType: newContentType, body: curr.request.body.body, }, }, } } }, addFormDataEntry(curr: RESTSession, { entry }: { entry: FormDataKeyValue }) { // Only perform update if the current content-type is formdata if (curr.request.body.contentType !== "multipart/form-data") return {} return { request: { ...curr.request, body: <HoppRESTReqBody>{ contentType: "multipart/form-data", body: [...curr.request.body.body, entry], }, }, } }, deleteFormDataEntry(curr: RESTSession, { index }: { index: number }) { // Only perform update if the current content-type is formdata if (curr.request.body.contentType !== "multipart/form-data") return {} return { request: { ...curr.request, body: <HoppRESTReqBody>{ contentType: "multipart/form-data", body: curr.request.body.body.filter((_, i) => i !== index), }, }, } }, updateFormDataEntry( curr: RESTSession, { index, entry }: { index: number; entry: FormDataKeyValue } ) { // Only perform update if the current content-type is formdata if (curr.request.body.contentType !== "multipart/form-data") return {} return { request: { ...curr.request, body: <HoppRESTReqBody>{ contentType: "multipart/form-data", body: curr.request.body.body.map((x, i) => (i !== index ? x : entry)), }, }, } }, deleteAllFormDataEntries(curr: RESTSession) { // Only perform update if the current content-type is formdata if (curr.request.body.contentType !== "multipart/form-data") return {} return { request: { ...curr.request, body: <HoppRESTReqBody>{ contentType: "multipart/form-data", body: [], }, }, } }, setRequestBody(curr: RESTSession, { newBody }: { newBody: HoppRESTReqBody }) { return { request: { ...curr.request, body: newBody, }, } }, updateResponse( _curr: RESTSession, { updatedRes }: { updatedRes: HoppRESTResponse | null } ) { return { response: updatedRes, } }, clearResponse(_curr: RESTSession) { return { response: null, } }, setTestResults( _curr: RESTSession, { newResults }: { newResults: HoppTestResult | null } ) { return { testResults: newResults, } }, setSaveContext( _, { newContext }: { newContext: HoppRequestSaveContext | null } ) { return { saveContext: newContext, } }, }) const restSessionStore = new DispatchingStore(defaultRESTSession, dispatchers) export function getRESTRequest() { return restSessionStore.subject$.value.request } export function setRESTRequest( req: HoppRESTRequest, saveContext?: HoppRequestSaveContext | null ) { restSessionStore.dispatch({ dispatcher: "setRequest", payload: { req, }, }) if (saveContext) setRESTSaveContext(saveContext) } export function setRESTSaveContext(saveContext: HoppRequestSaveContext | null) { restSessionStore.dispatch({ dispatcher: "setSaveContext", payload: { newContext: saveContext, }, }) } export function getRESTSaveContext() { return restSessionStore.value.saveContext } export function resetRESTRequest() { setRESTRequest(defaultRESTRequest) } export function setRESTEndpoint(newEndpoint: string) { restSessionStore.dispatch({ dispatcher: "setEndpoint", payload: { newEndpoint, }, }) } export function setRESTRequestName(newName: string) { restSessionStore.dispatch({ dispatcher: "setRequestName", payload: { newName, }, }) } export function setRESTParams(entries: HoppRESTParam[]) { restSessionStore.dispatch({ dispatcher: "setParams", payload: { entries, }, }) } export function addRESTParam(newParam: HoppRESTParam) { restSessionStore.dispatch({ dispatcher: "addParam", payload: { newParam, }, }) } export function updateRESTParam(index: number, updatedParam: HoppRESTParam) { restSessionStore.dispatch({ dispatcher: "updateParam", payload: { updatedParam, index, }, }) } export function deleteRESTParam(index: number) { restSessionStore.dispatch({ dispatcher: "deleteParam", payload: { index, }, }) } export function deleteAllRESTParams() { restSessionStore.dispatch({ dispatcher: "deleteAllParams", payload: {}, }) } export function updateRESTMethod(newMethod: string) { restSessionStore.dispatch({ dispatcher: "updateMethod", payload: { newMethod, }, }) } export function setRESTHeaders(entries: HoppRESTHeader[]) { restSessionStore.dispatch({ dispatcher: "setHeaders", payload: { entries, }, }) } export function addRESTHeader(entry: HoppRESTHeader) { restSessionStore.dispatch({ dispatcher: "addHeader", payload: { entry, }, }) } export function updateRESTHeader(index: number, updatedEntry: HoppRESTHeader) { restSessionStore.dispatch({ dispatcher: "updateHeader", payload: { index, updatedEntry, }, }) } export function deleteRESTHeader(index: number) { restSessionStore.dispatch({ dispatcher: "deleteHeader", payload: { index, }, }) } export function deleteAllRESTHeaders() { restSessionStore.dispatch({ dispatcher: "deleteAllHeaders", payload: {}, }) } export function setRESTAuth(newAuth: HoppRESTAuth) { restSessionStore.dispatch({ dispatcher: "setAuth", payload: { newAuth, }, }) } export function setRESTPreRequestScript(newScript: string) { restSessionStore.dispatch({ dispatcher: "setPreRequestScript", payload: { newScript, }, }) } export function setRESTTestScript(newScript: string) { restSessionStore.dispatch({ dispatcher: "setTestScript", payload: { newScript, }, }) } export function setRESTReqBody(newBody: HoppRESTReqBody | null) { restSessionStore.dispatch({ dispatcher: "setRequestBody", payload: { newBody, }, }) } export function updateRESTResponse(updatedRes: HoppRESTResponse | null) { restSessionStore.dispatch({ dispatcher: "updateResponse", payload: { updatedRes, }, }) } export function clearRESTResponse() { restSessionStore.dispatch({ dispatcher: "clearResponse", payload: {}, }) } export function setRESTTestResults(newResults: HoppTestResult | null) { restSessionStore.dispatch({ dispatcher: "setTestResults", payload: { newResults, }, }) } export function addFormDataEntry(entry: FormDataKeyValue) { restSessionStore.dispatch({ dispatcher: "addFormDataEntry", payload: { entry, }, }) } export function deleteFormDataEntry(index: number) { restSessionStore.dispatch({ dispatcher: "deleteFormDataEntry", payload: { index, }, }) } export function updateFormDataEntry(index: number, entry: FormDataKeyValue) { restSessionStore.dispatch({ dispatcher: "updateFormDataEntry", payload: { index, entry, }, }) } export function setRESTContentType(newContentType: ValidContentTypes | null) { restSessionStore.dispatch({ dispatcher: "setContentType", payload: { newContentType, }, }) } export function deleteAllFormDataEntries() { restSessionStore.dispatch({ dispatcher: "deleteAllFormDataEntries", payload: {}, }) } export const restSaveContext$ = restSessionStore.subject$.pipe( pluck("saveContext"), distinctUntilChanged() ) export const restRequest$ = restSessionStore.subject$.pipe( pluck("request"), distinctUntilChanged() ) export const restRequestName$ = restRequest$.pipe( pluck("name"), distinctUntilChanged() ) export const restEndpoint$ = restSessionStore.subject$.pipe( pluck("request", "endpoint"), distinctUntilChanged() ) export const restParams$ = restSessionStore.subject$.pipe( pluck("request", "params"), distinctUntilChanged() ) export const restActiveParamsCount$ = restParams$.pipe( map( (params) => params.filter((x) => x.active && (x.key !== "" || x.value !== "")).length ) ) export const restMethod$ = restSessionStore.subject$.pipe( pluck("request", "method"), distinctUntilChanged() ) export const restHeaders$ = restSessionStore.subject$.pipe( pluck("request", "headers"), distinctUntilChanged() ) export const restActiveHeadersCount$ = restHeaders$.pipe( map( (params) => params.filter((x) => x.active && (x.key !== "" || x.value !== "")).length ) ) export const restAuth$ = restRequest$.pipe(pluck("auth")) export const restPreRequestScript$ = restSessionStore.subject$.pipe( pluck("request", "preRequestScript"), distinctUntilChanged() ) export const restContentType$ = restRequest$.pipe( pluck("body", "contentType"), distinctUntilChanged() ) export const restTestScript$ = restSessionStore.subject$.pipe( pluck("request", "testScript"), distinctUntilChanged() ) export const restReqBody$ = restSessionStore.subject$.pipe( pluck("request", "body"), distinctUntilChanged() ) export const restResponse$ = restSessionStore.subject$.pipe( pluck("response"), distinctUntilChanged() ) export const completedRESTResponse$ = restResponse$.pipe( filter( (res) => res !== null && res.type !== "loading" && res.type !== "network_fail" ) ) export const restTestResults$ = restSessionStore.subject$.pipe( pluck("testResults"), distinctUntilChanged() ) /** * A Vue 3 composable function that gives access to a ref * which is updated to the preRequestScript value in the store. * The ref value is kept in sync with the store and all writes * to the ref are dispatched to the store as `setPreRequestScript` * dispatches. */ export function usePreRequestScript(): Ref<string> { return useStream( restPreRequestScript$, restSessionStore.value.request.preRequestScript, (value) => { setRESTPreRequestScript(value) } ) } /** * A Vue 3 composable function that gives access to a ref * which is updated to the testScript value in the store. * The ref value is kept in sync with the store and all writes * to the ref are dispatched to the store as `setTestScript` * dispatches. */ export function useTestScript(): Ref<string> { return useStream( restTestScript$, restSessionStore.value.request.testScript, (value) => { setRESTTestScript(value) } ) } export function useRESTRequestBody(): Ref<HoppRESTReqBody> { return useStream( restReqBody$, restSessionStore.value.request.body, setRESTReqBody ) } export function useRESTRequestName(): Ref<string> { return useStream( restRequestName$, restSessionStore.value.request.name, setRESTRequestName ) }
the_stack
import * as os from "os"; import * as vscode from "vscode"; import * as fs from "fs-plus"; import * as path from "path"; import request = require("request-promise"); import * as utils from "../utils"; import { FileNames, ConfigKey, ScaffoldType, OSPlatform } from "../constants"; import { TelemetryContext } from "../telemetry"; import { DigitalTwinConstants } from "./DigitalTwinConstants"; import { CodeGenProjectType, DeviceConnectionType, CodeGenLanguage, DeviceSdkReferenceType, CodeGenExecutionItem } from "./DigitalTwinCodeGen/Interfaces/CodeGenerator"; import { AnsiCCodeGeneratorFactory } from "./DigitalTwinCodeGen/AnsiCCodeGeneratorFactory"; import { ConfigHandler } from "../configHandler"; import { PnpDeviceConnection, CodeGenProjectTemplate, DeviceSdkReference } from "../Models/Interfaces/ProjectTemplate"; import { DialogResponses } from "../DialogResponses"; import { RemoteExtension } from "../Models/RemoteExtension"; import { DigitalTwinUtility } from "./DigitalTwinUtility"; import { CodeGenUtility } from "./DigitalTwinCodeGen/CodeGenUtility"; import { FileUtility } from "../FileUtility"; import { OperationCanceledError } from "../common/Error/OperationCanceledError"; import { Utility } from "./pnp/src/common/utility"; import { OperationFailedError } from "../common/Error/OperationFailedErrors/OperationFailedError"; import { SystemResourceNotFoundError } from "../common/Error/SystemErrors/SystemResourceNotFoundError"; import { TypeNotSupportedError } from "../common/Error/SystemErrors/TypeNotSupportedError"; import { WorkspaceNotOpenError } from "../common/Error/OperationFailedErrors/WorkspaceNotOpenError"; interface CodeGeneratorDownloadLocation { win32Md5: string; win32PackageUrl: string; macOSMd5: string; macOSPackageUrl: string; ubuntuMd5: string; ubuntuPackageUrl: string; } interface CodeGeneratorConfigItem { codeGeneratorVersion: string; iotWorkbenchMinimalVersion: string; codeGeneratorLocation: CodeGeneratorDownloadLocation; } interface CodeGeneratorConfig { codeGeneratorConfigItems: CodeGeneratorConfigItem[]; } interface CodeGenExecutions { codeGenExecutionItems: CodeGenExecutionItem[]; } enum CodeGenCliOperation { None = 0, Install, Upgrade } enum ReGenResult { Succeeded, Skipped } function compareVersion(verion1: string, verion2: string): 1 | -1 | 0 { const ver1 = verion1.split("."); const ver2 = verion2.split("."); let i = 0; let v1: number, v2: number; /* default is 0, version format should be 1.1.0 */ while (i < 3) { v1 = Number(ver1[i]); v2 = Number(ver2[i]); if (v1 > v2) return 1; if (v1 < v2) return -1; i++; } return 0; } function localCodeGenCliPath(): string { return path.join(os.homedir(), DigitalTwinConstants.codeGenCliFolder); } export class CodeGeneratorCore { async generateDeviceCodeStub( context: vscode.ExtensionContext, channel: vscode.OutputChannel, telemetryContext: TelemetryContext ): Promise<void> { RemoteExtension.ensureLocalBeforeRunCommand("generate device code stub", context); const rootPath = utils.getProjectDeviceRootPath(); if (!rootPath) { throw new WorkspaceNotOpenError("generate device code stub"); } // Check installation of Codegen CLI and update its bits if a new version is // found if (!(await this.installOrUpgradeCodeGenCli(context, channel))) { return; } // Select Capability Model const capabilityModelFilePath: string = await DigitalTwinUtility.selectCapabilityModel(); // Prompt if old project exists for the same Capability Model file const regenResult = await this.regenCode(rootPath, capabilityModelFilePath, context, channel, telemetryContext); if (regenResult === ReGenResult.Succeeded) { return; } // Specify project name const codeGenProjectName = await this.getCodeGenProjectName(channel, rootPath); // Select language const codeGenLanguage = await this.selectLanguage(channel); // Read CodeGen options configuration JSON const codeGenOptions = this.readCodeGenOptionsConfiguration(context); // Select device connection string type const connectionType = await this.selectConnectionType(channel, codeGenOptions); // Select project template const codeGenProjectType = await this.selectProjectTemplate(channel, codeGenLanguage, codeGenOptions); // Select Device SDK reference type for CMake project const sdkReferenceType = await this.selectDeviceSdkReferenceType(channel, codeGenProjectType, codeGenOptions); // Download dependent interface of capability model if (!(await DigitalTwinUtility.downloadDependentInterface(rootPath, capabilityModelFilePath))) { throw new OperationFailedError( "download dependent interface", "", "Check out error message in the output channel." ); } const codeGenExecutionInfo: CodeGenExecutionItem = { outputDirectory: path.join(rootPath, codeGenProjectName), capabilityModelFilePath, interfaceDirecoty: rootPath, projectName: codeGenProjectName, languageLabel: CodeGenLanguage.ANSIC, codeGenProjectType, deviceSdkReferenceType: sdkReferenceType, deviceConnectionType: connectionType }; const scaffoldType = ScaffoldType.Local; await this.saveCodeGenConfig(scaffoldType, rootPath, capabilityModelFilePath, codeGenExecutionInfo); await this.generateDeviceCodeCore(codeGenExecutionInfo, context, channel, telemetryContext); } private async regenCode( rootPath: string, capabilityModelFilePath: string, context: vscode.ExtensionContext, channel: vscode.OutputChannel, telemetryContext: TelemetryContext ): Promise<ReGenResult> { const codeGenConfigPath = path.join( rootPath, FileNames.vscodeSettingsFolderName, DigitalTwinConstants.codeGenConfigFileName ); let codeGenExecutionItem: CodeGenExecutionItem | undefined; // CodeGen configuration file not found, no need to regenerate code if (!fs.existsSync(codeGenConfigPath)) { return ReGenResult.Skipped; } try { const codeGenExecutions: CodeGenExecutions = JSON.parse(fs.readFileSync(codeGenConfigPath, "utf8")); if (codeGenExecutions) { codeGenExecutionItem = codeGenExecutions.codeGenExecutionItems.find( item => item.capabilityModelFilePath === capabilityModelFilePath ); } } catch { // just skip this if read file failed. } if (codeGenExecutionItem) { const regenOptions: vscode.QuickPickItem[] = []; // select the target of the code stub regenOptions.push( { label: `Re-generate code for ${codeGenExecutionItem.projectName}`, description: "" }, { label: "Create new project", description: "" } ); const regenSelection = await vscode.window.showQuickPick(regenOptions, { ignoreFocusOut: true, placeHolder: "Please select an option:" }); if (!regenSelection) { throw new OperationCanceledError("Re-generate code selection cancelled."); } // User select regenerate code if (regenSelection.label !== "Create new project") { if (!(await DigitalTwinUtility.downloadDependentInterface(rootPath, capabilityModelFilePath))) { return ReGenResult.Skipped; } utils.channelShowAndAppendLine( channel, `${DigitalTwinConstants.dtPrefix} Regenerate device code using an existing CodeGen configure:` ); CodeGenUtility.printCodeGenConfig(codeGenExecutionItem, channel); await this.generateDeviceCodeCore(codeGenExecutionItem, context, channel, telemetryContext); return ReGenResult.Succeeded; } else { return ReGenResult.Skipped; } } else { return ReGenResult.Skipped; } } private async getCodeGenProjectName(channel: vscode.OutputChannel, rootPath: string): Promise<string> { // select the project name for code gen const codeGenProjectName = await vscode.window.showInputBox({ placeHolder: "Please input the project name here.", ignoreFocusOut: true, validateInput: (projectName: string) => { if (!projectName || projectName.length === 0) { return `The project name can't be empty.`; } if (!DigitalTwinConstants.codegenProjectNameRegex.test(projectName)) { return `Project name can only contain ${DigitalTwinConstants.codegenProjectNameRegexDescription}.`; } return; } }); if (!codeGenProjectName) { throw new OperationCanceledError(`Project name is not specified, cancelled.`); } const projectPath = path.join(rootPath, codeGenProjectName); if (fs.isDirectorySync(projectPath)) { const messge = `The folder ${projectPath} already exists. Do you want to overwrite the contents in this folder?`; const choice = await vscode.window.showWarningMessage(messge, DialogResponses.yes, DialogResponses.no); if (choice !== DialogResponses.yes) { throw new OperationCanceledError(`Valid project name is not specified, cancelled.`); } } utils.channelShowAndAppendLine(channel, `Input project name: ${codeGenProjectName}`); return codeGenProjectName; } private readCodeGenOptionsConfiguration( context: vscode.ExtensionContext // eslint-disable-next-line @typescript-eslint/no-explicit-any ): any { // Load CodeGen configuration file which defines the available CodeGen // options in VS Code command palette const codeGenConfigFilePath: string = context.asAbsolutePath( path.join(FileNames.resourcesFolderName, FileNames.templatesFolderName, FileNames.codeGenOptionsFileName) ); return JSON.parse(fs.readFileSync(codeGenConfigFilePath, "utf8")); } private async selectLanguage(channel: vscode.OutputChannel): Promise<string> { const languageItems: vscode.QuickPickItem[] = []; languageItems.push({ label: CodeGenLanguage.ANSIC, description: "" }); const languageSelection = await vscode.window.showQuickPick(languageItems, { ignoreFocusOut: true, placeHolder: "Select the language for generated code:" }); if (!languageSelection) { throw new OperationCanceledError("CodeGen language selection cancelled."); } utils.channelShowAndAppendLine(channel, `Selected CodeGen language: ${languageSelection.label}`); return languageSelection.label; } private async selectConnectionType( channel: vscode.OutputChannel, // eslint-disable-next-line @typescript-eslint/no-explicit-any codegenOptionsConfig: any ): Promise<DeviceConnectionType> { // Load available Azure IoT connection types from JSON configuration const connectionTypeItems: vscode.QuickPickItem[] = []; codegenOptionsConfig.connectionTypes.forEach((element: PnpDeviceConnection) => { connectionTypeItems.push({ label: element.name, detail: element.detail }); }); const deviceConnectionSelection = await vscode.window.showQuickPick(connectionTypeItems, { ignoreFocusOut: true, placeHolder: "How will device connect to Azure IoT?" }); if (!deviceConnectionSelection) { throw new OperationCanceledError("Connection type selection cancelled."); } const deviceConnection = codegenOptionsConfig.connectionTypes.find((connectionType: PnpDeviceConnection) => { return connectionType.name === deviceConnectionSelection.label; }); if (!deviceConnection) { throw new SystemResourceNotFoundError( "device connection type", `${deviceConnectionSelection.label} connection type`, "CodeGen configuration" ); } const connectionType: DeviceConnectionType = DeviceConnectionType[deviceConnection.type as keyof typeof DeviceConnectionType]; if (!connectionType) { throw new TypeNotSupportedError("device connection type", `${deviceConnection.type}`); } utils.channelShowAndAppendLine(channel, `Selected device connection type: ${connectionType}`); return connectionType; } private async selectProjectTemplate( channel: vscode.OutputChannel, language: string, // eslint-disable-next-line @typescript-eslint/no-explicit-any codegenOptionsConfig: any ): Promise<CodeGenProjectType> { // Load available project templates from JSON configuration const projectTemplates = codegenOptionsConfig.projectTemplates.filter((projectTemplate: CodeGenProjectTemplate) => { return projectTemplate.enabled && projectTemplate.language === language; }); const projectTemplateItems: vscode.QuickPickItem[] = []; projectTemplates.forEach((element: CodeGenProjectTemplate) => { projectTemplateItems.push({ label: element.name, detail: element.detail }); }); if (!projectTemplateItems) { throw new SystemResourceNotFoundError("project template", `${language} language`, "CodeGen configuration"); } const projectTemplateSelection = await vscode.window.showQuickPick(projectTemplateItems, { ignoreFocusOut: true, placeHolder: "Select project template:" }); if (!projectTemplateSelection) { throw new OperationCanceledError("CodeGen project template selection cancelled."); } const projectTemplate = projectTemplates.find((projectType: CodeGenProjectTemplate) => { return projectType.name === projectTemplateSelection.label; }); if (!projectTemplate) { throw new SystemResourceNotFoundError( "project template", `${projectTemplateSelection.label} project template name`, "CodeGen configuration" ); } const codeGenProjectType: CodeGenProjectType = CodeGenProjectType[projectTemplate.type as keyof typeof CodeGenProjectType]; if (!codeGenProjectType) { throw new TypeNotSupportedError("CodeGen project type", `${projectTemplate.type}`); } utils.channelShowAndAppendLine(channel, `Selected CodeGen project type: ${codeGenProjectType}`); return codeGenProjectType; } private async selectDeviceSdkReferenceType( channel: vscode.OutputChannel, projectType: CodeGenProjectType, // eslint-disable-next-line @typescript-eslint/no-explicit-any codegenOptionsConfig: any ): Promise<DeviceSdkReferenceType> { let deviceSdkReferenceType = undefined; switch (projectType) { case CodeGenProjectType.IoTDevKit: deviceSdkReferenceType = DeviceSdkReferenceType.DevKitSDK; break; case CodeGenProjectType.CMakeWindows: case CodeGenProjectType.CMakeLinux: { // Load available Azure IoT connection types from JSON configuration const sdkReferenceTypeItems: vscode.QuickPickItem[] = []; codegenOptionsConfig.deviceSdkReferenceTypes.forEach((element: DeviceSdkReference) => { sdkReferenceTypeItems.push({ label: element.name, detail: element.detail }); }); const deviceConnectionSelection = await vscode.window.showQuickPick(sdkReferenceTypeItems, { ignoreFocusOut: true, placeHolder: "How will CMake include the Azure IoT Device SDK?" }); if (!deviceConnectionSelection) { throw new OperationCanceledError("IoT Device SDK reference type selection cancelled."); } // Map selection to a DeviceSdkReferenceType enum const sdkReference = codegenOptionsConfig.deviceSdkReferenceTypes.find((sdkReference: DeviceSdkReference) => { return sdkReference.name === deviceConnectionSelection.label; }); if (!sdkReference) { throw new SystemResourceNotFoundError( "SDK reference", `${deviceConnectionSelection.label} IoT Device SDK reference type`, "CodeGen configuration" ); } const sdkReferenceType: DeviceSdkReferenceType = DeviceSdkReferenceType[sdkReference.type as keyof typeof DeviceSdkReferenceType]; if (!sdkReferenceType) { throw new TypeNotSupportedError("SDK reference type", `${sdkReference.type}`); } deviceSdkReferenceType = sdkReferenceType; break; } default: throw new TypeNotSupportedError("project type", `${projectType}`); } utils.channelShowAndAppendLine(channel, `Selected device SDK reference type: ${deviceSdkReferenceType}`); return deviceSdkReferenceType; } private async generateDeviceCodeCore( codeGenExecutionInfo: CodeGenExecutionItem, context: vscode.ExtensionContext, channel: vscode.OutputChannel, telemetryContext: TelemetryContext ): Promise<boolean> { // We only support Ansi C const codeGenFactory = new AnsiCCodeGeneratorFactory(context, channel, telemetryContext); const codeGenerator = codeGenFactory.createCodeGeneratorImpl(codeGenExecutionInfo.languageLabel); if (!codeGenerator) { return false; } // Parse capabilityModel name from id const capabilityModel = await Utility.getJsonContent(codeGenExecutionInfo.capabilityModelFilePath); const capabilityModelId = capabilityModel["@id"]; await vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, title: `Generate PnP device code for ${capabilityModelId} ...` }, async () => { const result = await codeGenerator.generateCode(codeGenExecutionInfo); if (result) { vscode.window.showInformationMessage(`Generate PnP device code for ${capabilityModelId} completed`); } } ); return true; } private async saveCodeGenConfig( type: ScaffoldType, rootPath: string, capabilityModelFilePath: string, codeGenExecutionInfo: CodeGenExecutionItem ): Promise<void> { const codeGenConfigPath = path.join( rootPath, FileNames.vscodeSettingsFolderName, DigitalTwinConstants.codeGenConfigFileName ); try { let codeGenExecutions: CodeGenExecutions; if (await FileUtility.fileExists(type, codeGenConfigPath)) { const codeGenConfig = await FileUtility.readFile(type, codeGenConfigPath, "utf8"); codeGenExecutions = JSON.parse(codeGenConfig as string); if (codeGenExecutions) { codeGenExecutions.codeGenExecutionItems = codeGenExecutions.codeGenExecutionItems.filter( item => item.capabilityModelFilePath !== capabilityModelFilePath ); codeGenExecutions.codeGenExecutionItems.push(codeGenExecutionInfo); } } else { codeGenExecutions = { codeGenExecutionItems: [codeGenExecutionInfo] }; } if (codeGenExecutions) { await FileUtility.writeJsonFile(type, codeGenConfigPath, codeGenExecutions); } } catch (error) { // save config failure should not impact code gen. console.log(error); } } private async getCodeGenCliPackageInfo( context: vscode.ExtensionContext, channel: vscode.OutputChannel ): Promise<CodeGeneratorConfigItem | null> { const extensionPackage = await Utility.getJsonContent(context.asAbsolutePath("./package.json")); const extensionVersion = extensionPackage.version; // Download the config file for CodeGen cli const options: request.OptionsWithUri = { method: "GET", uri: extensionPackage.codeGenConfigUrl, encoding: "utf8", json: true }; let targetConfigItem: CodeGeneratorConfigItem | null = null; const codeGenConfig: CodeGeneratorConfig = await request(options).promise(); if (codeGenConfig) { codeGenConfig.codeGeneratorConfigItems.sort((configItem1, configItem2) => { return compareVersion(configItem2.codeGeneratorVersion, configItem1.codeGeneratorVersion); // reverse order }); // if this is a RC build, always use the latest version of code generator. if (!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(extensionVersion)) { targetConfigItem = codeGenConfig.codeGeneratorConfigItems[0]; } else { for (const item of codeGenConfig.codeGeneratorConfigItems) { if (compareVersion(extensionVersion, item.iotWorkbenchMinimalVersion) >= 0) { targetConfigItem = item; break; } } } } if (!targetConfigItem) { const message = `${DigitalTwinConstants.dtPrefix} \ Failed to get download information for ${DigitalTwinConstants.codeGenCli}.`; utils.channelShowAndAppendLine(channel, message); } return targetConfigItem; } private async checkLocalCodeGenCli(): Promise<string | null> { // Check version of existing CodeGen CLI const platform = os.platform(); const currentVersion = ConfigHandler.get<string>(ConfigKey.codeGeneratorVersion); let codeGenCliAppPath = path.join(localCodeGenCliPath(), DigitalTwinConstants.codeGenCliApp); if (platform === OSPlatform.WIN32) { codeGenCliAppPath += ".exe"; } if (!fs.isFileSync(codeGenCliAppPath) || currentVersion == null) { // Doen't exist return null; } // TODO: should check the integrity of the CodeGen CLI return currentVersion; } private async downloadAndInstallCodeGenCli( channel: vscode.OutputChannel, targetConfigItem: CodeGeneratorConfigItem, installOrUpgrade: number, newVersion: string ): Promise<boolean> { let packageUri: string; let md5value: string; const platform = os.platform(); if (platform === OSPlatform.WIN32) { packageUri = targetConfigItem.codeGeneratorLocation.win32PackageUrl; md5value = targetConfigItem.codeGeneratorLocation.win32Md5; } else if (platform === OSPlatform.DARWIN) { packageUri = targetConfigItem.codeGeneratorLocation.macOSPackageUrl; md5value = targetConfigItem.codeGeneratorLocation.macOSMd5; } else { packageUri = targetConfigItem.codeGeneratorLocation.ubuntuPackageUrl; md5value = targetConfigItem.codeGeneratorLocation.ubuntuMd5; } // Download utils.channelShowAndAppend( channel, `Step 1: Downloading ${DigitalTwinConstants.codeGenCli} v${newVersion} package ...` ); const downloadOption: request.OptionsWithUri = { method: "GET", uri: packageUri, encoding: null }; const zipData = await request(downloadOption).promise(); const tempPath = path.join(os.tmpdir(), FileNames.iotworkbenchTempFolder); const filePath = path.join(tempPath, `${md5value}.zip`); fs.writeFileSync(filePath, zipData); utils.channelShowAndAppendLine(channel, " download complete."); // Verify // Validate hash code utils.channelShowAndAppend(channel, "Step 2: Validating hash code for the package ..."); const hashvalue = await FileUtility.getFileHash(filePath); if (hashvalue !== md5value) { utils.channelShowAndAppendLine( channel, `the downloaded ${DigitalTwinConstants.codeGenCli} v${newVersion} package has been corrupted.` ); if (installOrUpgrade === CodeGenCliOperation.Install) { utils.channelShowAndAppendLine(channel, `${DigitalTwinConstants.dtPrefix} Abort generating device code stub.`); return false; } else { utils.channelShowAndAppendLine( channel, ` Abort the installation and continue generating device code stub.` ); return true; } } else { utils.channelShowAndAppendLine(channel, " passed."); } // Extract files const codeGenCommandPath = localCodeGenCliPath(); utils.channelShowAndAppend(channel, `Step 3: Extracting files ...`); await FileUtility.extractZipFile(filePath, codeGenCommandPath); utils.channelShowAndAppendLine(channel, " done."); // Update the config await ConfigHandler.update(ConfigKey.codeGeneratorVersion, newVersion, vscode.ConfigurationTarget.Global); utils.channelShowAndAppendLine( channel, `${DigitalTwinConstants.dtPrefix} The ${DigitalTwinConstants.codeGenCli} v${newVersion} is ready to use.` ); return true; } private async installOrUpgradeCodeGenCli( context: vscode.ExtensionContext, channel: vscode.OutputChannel ): Promise<boolean> { utils.channelShowAndAppend( channel, `${DigitalTwinConstants.dtPrefix} Check ${DigitalTwinConstants.codeGenCli} ...` ); const targetConfigItem = await this.getCodeGenCliPackageInfo(context, channel); if (targetConfigItem === null) { return false; } // Check version of existing CodeGen CLI let installOrUpgrade: CodeGenCliOperation = CodeGenCliOperation.None; const currentVersion = await this.checkLocalCodeGenCli(); if (currentVersion == null) { installOrUpgrade = CodeGenCliOperation.Install; } else { // Compare version if (compareVersion(targetConfigItem.codeGeneratorVersion, currentVersion) > 0) { // Upgrade installOrUpgrade = CodeGenCliOperation.Upgrade; } } if (installOrUpgrade === CodeGenCliOperation.None) { // Already exists utils.channelShowAndAppendLine(channel, `CodeGen CLI v${currentVersion} is installed and ready to use.`); return true; } const newVersion = targetConfigItem.codeGeneratorVersion; const processTitle = installOrUpgrade === CodeGenCliOperation.Install ? `Installing ${DigitalTwinConstants.codeGenCli}` : `Upgrading ${DigitalTwinConstants.codeGenCli}`; const message = installOrUpgrade === CodeGenCliOperation.Install ? ` not installed, start installing:` : ` new version detected, start upgrading from ${currentVersion} to ${newVersion}:`; utils.channelShowAndAppendLine(channel, message); // Start donwloading let result = false; await vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, title: processTitle }, async progress => { progress.report({ increment: 0 }); setTimeout(() => { progress.report({ increment: 10, message: `still going...` }); }, 1000); setTimeout(() => { progress.report({ increment: 40, message: `still going...` }); }, 5000); setTimeout(() => { progress.report({ increment: 50, message: `almost done...` }); }, 10000); result = await this.downloadAndInstallCodeGenCli( channel, targetConfigItem as CodeGeneratorConfigItem, installOrUpgrade, newVersion ); } ); return result; } }
the_stack
import * as tsModule from "typescript"; import { Declaration, Node, Signature, SignatureDeclaration, Symbol as ESSymbol, Type, TypeChecker } from "typescript"; import { inspect } from "util"; import { DEFAULT_TYPE_CACHE } from "../constants"; import { isSimpleType, SimpleType, SimpleTypeAlias, SimpleTypeEnumMember, SimpleTypeFunction, SimpleTypeFunctionParameter, SimpleTypeGenericParameter, SimpleTypeInterface, SimpleTypeLiteral, SimpleTypeMemberNamed, SimpleTypeMethod, SimpleTypeObject } from "../simple-type"; import { getTypescriptModule } from "../ts-module"; import { simplifySimpleTypes } from "../utils/simple-type-util"; import { getDeclaration, getModifiersFromDeclaration, getTypeArguments, isArray, isBigInt, isBigIntLiteral, isBoolean, isBooleanLiteral, isDate, isEnum, isESSymbolLike, isFunction, isImplicitGeneric, isLiteral, isMethod, isMethodSignature, isNever, isNode, isNonPrimitive, isNull, isNumber, isObject, isObjectTypeReference, isPromise, isString, isSymbol, isThisType, isTupleTypeReference, isUndefined, isUniqueESSymbol, isUnknown, isVoid } from "../utils/ts-util"; export interface ToSimpleTypeOptions { eager?: boolean; cache?: WeakMap<Type, SimpleType>; } interface ToSimpleTypeInternalOptions { cache: WeakMap<Type, SimpleType>; checker: TypeChecker; ts: typeof tsModule; eager?: boolean; } /** * Converts a Typescript type to a "SimpleType" * @param type The type to convert. * @param checker * @param options */ export function toSimpleType(type: SimpleType, checker?: TypeChecker, options?: ToSimpleTypeOptions): SimpleType; export function toSimpleType(type: Node, checker: TypeChecker, options?: ToSimpleTypeOptions): SimpleType; export function toSimpleType(type: Type, checker: TypeChecker, options?: ToSimpleTypeOptions): SimpleType; export function toSimpleType(type: Type | Node | SimpleType, checker: TypeChecker, options?: ToSimpleTypeOptions): SimpleType; export function toSimpleType(type: Type | Node | SimpleType, checker?: TypeChecker, options: ToSimpleTypeOptions = {}): SimpleType { if (isSimpleType(type)) { return type; } checker = checker!; if (isNode(type)) { // "type" is a "Node", convert it to a "Type" and continue. return toSimpleType(checker.getTypeAtLocation(type), checker); } return toSimpleTypeCached(type, { checker, eager: options.eager, cache: options.cache || DEFAULT_TYPE_CACHE, ts: getTypescriptModule() }); } function toSimpleTypeCached(type: Type, options: ToSimpleTypeInternalOptions): SimpleType { if (options.cache.has(type)) { return options.cache.get(type)!; } // This function will resolve the type and assign the content to "target". // This way we can cache "target" before calling "toSimpleTypeInternal" recursively const resolveType = (target: SimpleType): void => { // Construct the simple type recursively //const simpleTypeOverwrite = options.cache.has(type) ? options.cache.get(type)! : toSimpleTypeInternal(type, options); const simpleTypeOverwrite = toSimpleTypeInternal(type, options); // Strip undefined keys to make the output cleaner Object.entries(simpleTypeOverwrite).forEach(([k, v]) => { if (v == null) delete simpleTypeOverwrite[k as keyof typeof simpleTypeOverwrite]; }); // Transfer properties on the simpleType to the placeholder // This makes it possible to keep on using the reference "placeholder". Object.assign(target, simpleTypeOverwrite); }; if (options.eager === true) { // Make and cache placeholder const placeholder = {} as SimpleType; options.cache.set(type, placeholder); // Resolve type into placeholder resolveType(placeholder); Object.freeze(placeholder); return placeholder; } else { const placeholder = {} as SimpleType; // A function that only resolves the type once let didResolve = false; const ensureResolved = () => { if (!didResolve) { resolveType(placeholder); didResolve = true; } }; // Use "toStringTag" as a hook into resolving the type. // If we don't have this hook, console.log would always print "{}" because the type hasn't been resolved Object.defineProperty(placeholder, Symbol.toStringTag, { get(): string { resolveType(placeholder); // Don't return any tag. Only use this function as a hook for calling "resolveType" return undefined as never; } }); // Return a proxy with the purpose of resolving the type lazy const proxy = new Proxy(placeholder, { ownKeys(target: SimpleType) { ensureResolved(); return [...Object.getOwnPropertyNames(target), ...Object.getOwnPropertySymbols(target)]; }, has(target: SimpleType, p: PropertyKey) { // Always return true if we test for "kind", but don't resolve the type // This way "isSimpleType" (which checks for "kind") will succeed without resolving the type if (p === "kind") { return true; } ensureResolved(); return p in target; }, getOwnPropertyDescriptor(target: SimpleType, p: keyof SimpleType) { ensureResolved(); return Object.getOwnPropertyDescriptor(target, p); }, get: (target: SimpleType, p: keyof SimpleType) => { ensureResolved(); return target[p]; }, set: (target: SimpleType, p: keyof SimpleType) => { throw new TypeError(`Cannot assign to read only property '${p}'`); } }); options.cache.set(type, proxy); return proxy; } } /** * Tries to lift a potential generic type and wrap the result in a "GENERIC_ARGUMENTS" simple type and/or "ALIAS" type. * Returns the "simpleType" otherwise. * @param simpleType * @param type * @param options */ function liftGenericType(type: Type, options: ToSimpleTypeInternalOptions): { generic: (target: SimpleType) => SimpleType; target: Type } | undefined { // Check for alias reference if (type.aliasSymbol != null) { const aliasDeclaration = getDeclaration(type.aliasSymbol, options.ts); const typeParameters = getTypeParameters(aliasDeclaration, options); return { target: type, generic: target => { // Lift the simple type to an ALIAS type. const aliasType: SimpleTypeAlias = { kind: "ALIAS", name: type.aliasSymbol!.getName() || "", target, typeParameters }; // Lift the alias type if it uses generic arguments. if (type.aliasTypeArguments != null) { const typeArguments = Array.from(type.aliasTypeArguments || []).map(t => toSimpleTypeCached(t, options)); return { kind: "GENERIC_ARGUMENTS", target: aliasType, typeArguments }; } return target; } }; } // Check if the type is a generic interface/class reference and lift it. else if (isObject(type, options.ts) && isObjectTypeReference(type, options.ts) && type.typeArguments != null && type.typeArguments.length > 0) { // Special case for array, tuple and promise, they are generic in themselves if (isImplicitGeneric(type, options.checker, options.ts)) { return undefined; } return { target: type.target, generic: target => { const typeArguments = Array.from(type.typeArguments || []).map(t => toSimpleTypeCached(t, options)); return { kind: "GENERIC_ARGUMENTS", target, typeArguments }; } }; } return undefined; } function toSimpleTypeInternal(type: Type, options: ToSimpleTypeInternalOptions): SimpleType { const { checker, ts } = options; const symbol: ESSymbol | undefined = type.getSymbol(); const name = symbol != null ? getRealSymbolName(symbol, ts) : undefined; let simpleType: SimpleType | undefined; const generic = liftGenericType(type, options); if (generic != null) { type = generic.target; } if (isLiteral(type, ts)) { const literalSimpleType = primitiveLiteralToSimpleType(type, checker, ts); if (literalSimpleType != null) { // Enum members if (symbol != null && symbol.flags & ts.SymbolFlags.EnumMember) { const parentSymbol = (symbol as ESSymbol & { parent: ESSymbol | undefined }).parent; if (parentSymbol != null) { return { name: name || "", fullName: `${parentSymbol.name}.${name}`, kind: "ENUM_MEMBER", type: literalSimpleType }; } } // Literals types return literalSimpleType; } } // Primitive types else if (isString(type, ts)) { simpleType = { kind: "STRING", name }; } else if (isNumber(type, ts)) { simpleType = { kind: "NUMBER", name }; } else if (isBoolean(type, ts)) { simpleType = { kind: "BOOLEAN", name }; } else if (isBigInt(type, ts)) { simpleType = { kind: "BIG_INT", name }; } else if (isESSymbolLike(type, ts)) { simpleType = { kind: "ES_SYMBOL", name }; } else if (isUndefined(type, ts)) { simpleType = { kind: "UNDEFINED", name }; } else if (isNull(type, ts)) { simpleType = { kind: "NULL", name }; } else if (isUnknown(type, ts)) { simpleType = { kind: "UNKNOWN", name }; } else if (isVoid(type, ts)) { simpleType = { kind: "VOID", name }; } else if (isNever(type, ts)) { simpleType = { kind: "NEVER", name }; } // Enum else if (isEnum(type, ts) && type.isUnion()) { simpleType = { name: name || "", kind: "ENUM", types: type.types.map(t => toSimpleTypeCached(t, options) as SimpleTypeEnumMember) }; } // Promise else if (isPromise(type, checker, ts)) { simpleType = { kind: "PROMISE", name, type: toSimpleTypeCached(getTypeArguments(type, checker, ts)[0], options) }; } // Unions and intersections else if (type.isUnion()) { simpleType = { kind: "UNION", types: simplifySimpleTypes(type.types.map(t => toSimpleTypeCached(t, options))), name }; } else if (type.isIntersection()) { simpleType = { kind: "INTERSECTION", types: simplifySimpleTypes(type.types.map(t => toSimpleTypeCached(t, options))), name }; } // Date else if (isDate(type, ts)) { simpleType = { kind: "DATE", name }; } // Array else if (isArray(type, checker, ts)) { simpleType = { kind: "ARRAY", type: toSimpleTypeCached(getTypeArguments(type, checker, ts)[0], options), name }; } else if (isTupleTypeReference(type, ts)) { const types = getTypeArguments(type, checker, ts); const minLength = type.target.minLength; simpleType = { kind: "TUPLE", rest: type.target.hasRestElement || false, members: types.map((childType, i) => { return { optional: i >= minLength, type: toSimpleTypeCached(childType, options) }; }), name }; } // Method signatures else if (isMethodSignature(type, ts)) { const callSignatures = type.getCallSignatures(); simpleType = getSimpleFunctionFromCallSignatures(callSignatures, options); } // Class else if (type.isClass() && symbol != null) { const classDecl = getDeclaration(symbol, ts); if (classDecl != null && ts.isClassDeclaration(classDecl)) { const ctor = (() => { const ctorSymbol = symbol != null && symbol.members != null ? symbol.members.get("__constructor" as never) : undefined; if (ctorSymbol != null && symbol != null) { const ctorDecl = ctorSymbol.declarations !== undefined && ctorSymbol.declarations?.length > 0 ? ctorSymbol.declarations[0] : ctorSymbol.valueDeclaration; if (ctorDecl != null && ts.isConstructorDeclaration(ctorDecl)) { return getSimpleFunctionFromSignatureDeclaration(ctorDecl, options) as SimpleTypeFunction; } } })(); const call = getSimpleFunctionFromCallSignatures(type.getCallSignatures(), options) as SimpleTypeFunction; const members = checker .getPropertiesOfType(type) .map(symbol => { const declaration = getDeclaration(symbol, ts); // Some instance properties may have an undefined declaration. // Since we can't do too much without a declaration, filtering // these out seems like the best strategy for the moment. // // See https://github.com/runem/web-component-analyzer/issues/60 for // more info. if (declaration == null) return null; return { name: symbol.name, optional: (symbol.flags & ts.SymbolFlags.Optional) !== 0, modifiers: getModifiersFromDeclaration(declaration, ts), type: toSimpleTypeCached(checker.getTypeAtLocation(declaration), options) } as SimpleTypeMemberNamed; }) .filter((member): member is NonNullable<typeof member> => member != null); const typeParameters = getTypeParameters(getDeclaration(symbol, ts), options); simpleType = { kind: "CLASS", name, call, ctor, typeParameters, members }; } } // Interface else if ((type.isClassOrInterface() || isObject(type, ts)) && !(symbol?.name === "Function")) { // Handle the empty object if (isObject(type, ts) && symbol?.name === "Object") { return { kind: "OBJECT" }; } const members = type.getProperties().map(symbol => { const declaration = getDeclaration(symbol, ts); return { name: symbol.name, optional: (symbol.flags & ts.SymbolFlags.Optional) !== 0, modifiers: declaration != null ? getModifiersFromDeclaration(declaration, ts) : [], type: toSimpleTypeCached(checker.getTypeAtLocation(symbol.valueDeclaration!), options) }; }); const ctor = getSimpleFunctionFromCallSignatures(type.getConstructSignatures(), options) as SimpleTypeFunction; const call = getSimpleFunctionFromCallSignatures(type.getCallSignatures(), options) as SimpleTypeFunction; const typeParameters = (type.isClassOrInterface() && type.typeParameters != null ? type.typeParameters.map(t => toSimpleTypeCached(t, options) as SimpleTypeGenericParameter) : undefined) || (symbol != null ? getTypeParameters(getDeclaration(symbol, ts), options) : undefined); let indexType: SimpleTypeInterface["indexType"] = {}; if (type.getStringIndexType()) { indexType["STRING"] = toSimpleTypeCached(type.getStringIndexType()!, options); } if (type.getNumberIndexType()) { indexType["NUMBER"] = toSimpleTypeCached(type.getNumberIndexType()!, options); } if (Object.keys(indexType).length === 0) { indexType = undefined; } // Simplify: if there is only a single "call" signature and nothing else, just return the call signature /*if (call != null && members.length === 0 && ctor == null && indexType == null) { return { ...call, name, typeParameters }; }*/ simpleType = { kind: type.isClassOrInterface() ? "INTERFACE" : "OBJECT", typeParameters, ctor, members, name, indexType, call } as SimpleTypeInterface | SimpleTypeObject; } // Handle "object" type else if (isNonPrimitive(type, ts)) { return { kind: "NON_PRIMITIVE" }; } // Function else if (symbol != null && (isFunction(type, ts) || isMethod(type, ts))) { simpleType = getSimpleFunctionFromCallSignatures(type.getCallSignatures(), options, name); if (simpleType == null) { simpleType = { kind: "FUNCTION", name }; } } // Type Parameter else if (type.isTypeParameter() && symbol != null) { // This type if (isThisType(type, ts) && symbol.valueDeclaration != null) { return toSimpleTypeCached(checker.getTypeAtLocation(symbol.valueDeclaration), options); } const defaultType = type.getDefault(); const defaultSimpleType = defaultType != null ? toSimpleTypeCached(defaultType, options) : undefined; simpleType = { kind: "GENERIC_PARAMETER", name: symbol.getName(), default: defaultSimpleType } as SimpleTypeGenericParameter; } // If no type was found, return "ANY" if (simpleType == null) { simpleType = { kind: "ANY", name }; } // Lift generic types and aliases if possible if (generic != null) { return generic.generic(simpleType); } return simpleType; } function primitiveLiteralToSimpleType(type: Type, checker: TypeChecker, ts: typeof tsModule): SimpleTypeLiteral | undefined { if (type.isNumberLiteral()) { return { kind: "NUMBER_LITERAL", value: type.value }; } else if (type.isStringLiteral()) { return { kind: "STRING_LITERAL", value: type.value }; } else if (isBooleanLiteral(type, ts)) { // See https://github.com/Microsoft/TypeScript/issues/22269 for more information return { kind: "BOOLEAN_LITERAL", value: checker.typeToString(type) === "true" }; } else if (isBigIntLiteral(type, ts)) { return { kind: "BIG_INT_LITERAL", /* global BigInt */ value: BigInt(`${type.value.negative ? "-" : ""}${type.value.base10Value}`) }; } else if (isUniqueESSymbol(type, ts)) { return { kind: "ES_SYMBOL_UNIQUE", value: String(type.escapedName) || Math.floor(Math.random() * 100000000).toString() }; } } function getSimpleFunctionFromCallSignatures(signatures: readonly Signature[], options: ToSimpleTypeInternalOptions, fallbackName?: string): SimpleTypeFunction | SimpleTypeMethod | undefined { if (signatures.length === 0) { return undefined; } const signature = signatures[signatures.length - 1]; const signatureDeclaration = signature.getDeclaration(); return getSimpleFunctionFromSignatureDeclaration(signatureDeclaration, options, fallbackName); } function getSimpleFunctionFromSignatureDeclaration( signatureDeclaration: SignatureDeclaration, options: ToSimpleTypeInternalOptions, fallbackName?: string ): SimpleTypeFunction | SimpleTypeMethod | undefined { const { checker } = options; const symbol = checker.getSymbolAtLocation(signatureDeclaration); const parameters = signatureDeclaration.parameters.map(parameterDecl => { const argType = checker.getTypeAtLocation(parameterDecl); return { name: parameterDecl.name.getText() || fallbackName, optional: parameterDecl.questionToken != null, type: toSimpleTypeCached(argType, options), rest: parameterDecl.dotDotDotToken != null, initializer: parameterDecl.initializer != null } as SimpleTypeFunctionParameter; }); const name = symbol != null ? symbol.getName() : undefined; const type = checker.getTypeAtLocation(signatureDeclaration); const kind = isMethod(type, options.ts) ? "METHOD" : "FUNCTION"; const signature = checker.getSignatureFromDeclaration(signatureDeclaration); const returnType = signature == null ? undefined : toSimpleTypeCached(checker.getReturnTypeOfSignature(signature), options); const typeParameters = getTypeParameters(signatureDeclaration, options); return { name, kind, returnType, parameters, typeParameters } as SimpleTypeFunction | SimpleTypeMethod; } function getRealSymbolName(symbol: ESSymbol, ts: typeof tsModule): string | undefined { const name = symbol.getName(); if (name != null && [ts.InternalSymbolName.Type, ts.InternalSymbolName.Object, ts.InternalSymbolName.Function].includes(name as never)) { return undefined; } return name; } function getTypeParameters(obj: ESSymbol | Declaration | undefined, options: ToSimpleTypeInternalOptions): SimpleTypeGenericParameter[] | undefined { if (obj == null) return undefined; if (isSymbol(obj)) { const decl = getDeclaration(obj, options.ts); return getTypeParameters(decl, options); } if ( options.ts.isClassDeclaration(obj) || options.ts.isFunctionDeclaration(obj) || options.ts.isFunctionTypeNode(obj) || options.ts.isTypeAliasDeclaration(obj) || options.ts.isMethodDeclaration(obj) || options.ts.isMethodSignature(obj) ) { return obj.typeParameters == null ? undefined : Array.from(obj.typeParameters) .map(td => options.checker.getTypeAtLocation(td)) .map(t => toSimpleTypeCached(t, options) as SimpleTypeGenericParameter); } return undefined; } // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore function log(input: unknown, d = 3) { const str = inspect(input, { depth: d, colors: true }); // eslint-disable-next-line no-console console.log(str.replace(/checker: {[\s\S]*?}/g, "")); }
the_stack
import { CoreConstants } from '@/core/constants'; import { asyncInstance } from '@/core/utils/async-instance'; import { Injectable } from '@angular/core'; import { CoreCancellablePromise } from '@classes/cancellable-promise'; import { CoreDatabaseTable } from '@classes/database/database-table'; import { CoreDatabaseCachingStrategy, CoreDatabaseTableProxy } from '@classes/database/database-table-proxy'; import { CoreApp } from '@services/app'; import { CoreUtils } from '@services/utils/utils'; import { AngularFrameworkDelegate, makeSingleton } from '@singletons'; import { CoreComponentsRegistry } from '@singletons/components-registry'; import { CoreDom } from '@singletons/dom'; import { CoreSubscriptions } from '@singletons/subscriptions'; import { CoreUserToursUserTourComponent } from '../components/user-tour/user-tour'; import { APP_SCHEMA, CoreUserToursDBEntry, USER_TOURS_TABLE_NAME } from './database/user-tours'; /** * Service to manage User Tours. */ @Injectable({ providedIn: 'root' }) export class CoreUserToursService { protected table = asyncInstance<CoreDatabaseTable<CoreUserToursDBEntry>>(); protected tours: { component: CoreUserToursUserTourComponent; visible: boolean }[] = []; /** * Initialize database. */ async initializeDatabase(): Promise<void> { await CoreUtils.ignoreErrors(CoreApp.createTablesFromSchema(APP_SCHEMA)); this.table.setLazyConstructor(async () => { const table = new CoreDatabaseTableProxy<CoreUserToursDBEntry>( { cachingStrategy: CoreDatabaseCachingStrategy.Eager }, CoreApp.getDB(), USER_TOURS_TABLE_NAME, ['id'], ); await table.initialize(); return table; }); } /** * Check whether a User Tour is pending or not. * * @param id User Tour id. * @returns Whether the User Tour is pending or not. */ async isPending(id: string): Promise<boolean> { if (this.isDisabled(id)) { return false; } const isAcknowledged = await this.table.hasAnyByPrimaryKey({ id }); return !isAcknowledged; } /** * Confirm that a User Tour has been seen by the user. * * @param id User Tour id. */ async acknowledge(id: string): Promise<void> { await this.table.insert({ id, acknowledgedTime: Date.now() }); } /** * Show a User Tour if it's pending. * * @param options User Tour options. * @returns User tour controller, if any. */ async showIfPending(options: CoreUserToursBasicOptions): Promise<CoreUserToursUserTour | null>; async showIfPending(options: CoreUserToursFocusedOptions): Promise<CoreUserToursUserTour | null>; async showIfPending( options: CoreUserToursBasicOptions | CoreUserToursFocusedOptions, ): Promise<CoreUserToursUserTour | null> { const isPending = await CoreUserTours.isPending(options.id); if (!isPending) { return null; } return this.show(options); } /** * Show a User Tour. * * @param options User Tour options. * @returns User tour controller. */ protected async show(options: CoreUserToursBasicOptions): Promise<CoreUserToursUserTour>; protected async show(options: CoreUserToursFocusedOptions): Promise<CoreUserToursUserTour>; protected async show(options: CoreUserToursBasicOptions | CoreUserToursFocusedOptions): Promise<CoreUserToursUserTour> { const { delay, ...componentOptions } = options; await CoreUtils.wait(delay ?? 200); const container = document.querySelector('ion-app') ?? document.body; const element = await AngularFrameworkDelegate.attachViewToDom( container, CoreUserToursUserTourComponent, { ...componentOptions, container }, ); const tour = CoreComponentsRegistry.require(element, CoreUserToursUserTourComponent); return this.startTour(tour, options.watch ?? (options as CoreUserToursFocusedOptions).focus); } /** * Dismiss the active User Tour, if any. * * @param acknowledge Whether to acknowledge that the user has seen this User Tour or not. */ async dismiss(acknowledge: boolean = true): Promise<void> { await this.getForegroundTour()?.dismiss(acknowledge); } /** * Activate a tour component and bind its lifecycle to an element if provided. * * @param tour User tour. * @param watchElement Element to watch in order to update tour lifecycle. * @returns User tour controller. */ protected startTour(tour: CoreUserToursUserTourComponent, watchElement?: HTMLElement | false): CoreUserToursUserTour { if (!watchElement) { this.activateTour(tour); return { cancel: () => tour.dismiss(false), }; } let unsubscribeVisible: (() => void) | undefined; let visiblePromise: CoreCancellablePromise | undefined = CoreDom.waitToBeInViewport(watchElement); // eslint-disable-next-line promise/catch-or-return, promise/always-return visiblePromise.then(() => { visiblePromise = undefined; this.activateTour(tour); unsubscribeVisible = CoreDom.watchElementInViewport( watchElement, visible => visible ? this.activateTour(tour) : this.deactivateTour(tour), ); CoreSubscriptions.once(tour.beforeDismiss, () => { unsubscribeVisible?.(); visiblePromise = undefined; unsubscribeVisible = undefined; }); }); return { cancel: async () => { visiblePromise?.cancel(); if (!unsubscribeVisible) { return; } unsubscribeVisible(); await tour.dismiss(false); }, }; } /** * Activate the given user tour. * * @param tour User tour. */ protected activateTour(tour: CoreUserToursUserTourComponent): void { // Handle show/dismiss lifecycle. CoreSubscriptions.once(tour.beforeDismiss, () => { const index = this.getTourIndex(tour); if (index === -1) { return; } this.tours.splice(index, 1); this.getForegroundTour()?.show(); }); // Add to existing tours and show it if it's on top. const index = this.getTourIndex(tour); const previousForegroundTour = this.getForegroundTour(); if (previousForegroundTour?.id === tour.id) { // Already activated. return; } if (index !== -1) { this.tours[index].visible = true; } else { this.tours.push({ visible: true, component: tour, }); } if (this.getForegroundTour()?.id !== tour.id) { // Another tour is in use. return; } tour.show(); } /** * Returns the first visible tour in the stack. * * @return foreground tour if found or undefined. */ protected getForegroundTour(): CoreUserToursUserTourComponent | undefined { return this.tours.find(({ visible }) => visible)?.component; } /** * Returns the tour index in the stack. * * @return Tour index if found or -1 otherwise. */ protected getTourIndex(tour: CoreUserToursUserTourComponent): number { return this.tours.findIndex(({ component }) => component === tour); } /** * Hide User Tour if visible. * * @param tour User tour. */ protected deactivateTour(tour: CoreUserToursUserTourComponent): void { const index = this.getTourIndex(tour); if (index === -1) { return; } const foregroundTour = this.getForegroundTour(); this.tours[index].visible = false; if (foregroundTour?.id !== tour.id) { // Another tour is in use. return; } tour.hide(); } /** * Is user Tour disabled? * * @param tourId Tour Id or undefined to check all user tours. * @return Wether a particular or all user tours are disabled. */ isDisabled(tourId?: string): boolean { if (CoreConstants.CONFIG.disableUserTours) { return true; } return !!tourId && !!CoreConstants.CONFIG.disabledUserTours?.includes(tourId); } /** * It will reset all user tours. */ async resetTours(): Promise<void> { if (this.isDisabled()) { return; } await this.table.delete(); } } export const CoreUserTours = makeSingleton(CoreUserToursService); /** * User Tour controller. */ export interface CoreUserToursUserTour { /** * Cancelling a User Tours removed it from the queue if it was pending or dimisses it without * acknowledging if it existed. */ cancel(): Promise<void>; } /** * User Tour side. */ export const enum CoreUserToursSide { Top = 'top', Bottom = 'bottom', Right = 'right', Left = 'left', Start = 'start', End = 'end', } /** * User Tour alignment. */ export const enum CoreUserToursAlignment { Start = 'start', Center = 'center', End = 'end', } /** * Basic options to create a User Tour. */ export interface CoreUserToursBasicOptions { /** * Unique identifier. */ id: string; /** * User Tour component. */ component: unknown; /** * Properties to pass to the User Tour component. */ componentProps?: Record<string, unknown>; /** * Milliseconds to wait until the User Tour is shown. * * Defaults to 200ms. */ delay?: number; /** * Whether to watch an element to bind the User Tour lifecycle. Whenever this element appears or * leaves the screen, the user tour will do it as well. Focused user tours do it by default with * the focused element, but it can be disabled by explicitly using `false` here. */ watch?: HTMLElement | false; } /** * Options to create a focused User Tour. */ export interface CoreUserToursFocusedOptions extends CoreUserToursBasicOptions { /** * Element to focus. */ focus: HTMLElement; /** * Position relative to the focused element. */ side: CoreUserToursSide; /** * Alignment relative to the focused element. */ alignment: CoreUserToursAlignment; }
the_stack
import * as i18n from '../../core/i18n/i18n.js'; const UIStrings = { /** *@description Text to indicate something is not enabled */ disabled: 'Disabled', /** *@description Tooltip text that appears when hovering over the 'Disabled' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ ifTrueThisElementCurrentlyCannot: 'If true, this element currently cannot be interacted with.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ invalidUserEntry: 'Invalid user entry', /** *@description Tooltip text that appears when hovering over the 'Invalid user entry' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ ifTrueThisElementsUserentered: 'If true, this element\'s user-entered value does not conform to validation requirement.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ editable: 'Editable', /** *@description Tooltip text that appears when hovering over the 'Editable' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ ifAndHowThisElementCanBeEdited: 'If and how this element can be edited.', /** *@description Adjective. Describes whether the currently selected HTML element of the page can receive focus at all (e.g. can the selected element receive user keyboard input). * Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ focusable: 'Focusable', /** *@description Tooltip text that appears when hovering over the 'Focusable' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ ifTrueThisElementCanReceiveFocus: 'If true, this element can receive focus.', /** *@description Adjective. Describes whether the currently selected HTML element of the page is focused (e.g. the selected element receives user keyboard input). * Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane. */ focused: 'Focused', /** *@description Tooltip text that appears when hovering over the 'Focused' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ ifTrueThisElementCurrentlyHas: 'If `true`, this element currently has focus.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ canSetValue: 'Can set value', /** *@description Tooltip text that appears when hovering over the 'Can set value' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ whetherTheValueOfThisElementCan: 'Whether the value of this element can be set.', /** * @description Accessibility attribute name that appears under the Computed Properties section in * the Accessibility pane of the Elements panel. A live region is an area of the webpage which is * dynamic and changes frequently. */ liveRegion: 'Live region', /** *@description Tooltip text that appears when hovering over the 'Live region' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ whetherAndWhatPriorityOfLive: 'Whether and what priority of live updates may be expected for this element.', /** * @description Accessibility attribute name that appears under the Computed Properties section in * the Accessibility pane of the Elements panel when inspecting an element with aria-relevant set. */ atomicLiveRegions: 'Atomic (live regions)', /** * @description Tooltip text that appears when hovering over the 'Atomic (live regions)' attribute * name under the Computed Properties section in the Accessibility pane of the Elements panel. When * a node within a live region changes, the entire live region can be presented to the user, or * just the nodes within the region that actually changed. */ ifThisElementMayReceiveLive: 'If this element may receive live updates, whether the entire live region should be presented to the user on changes, or only changed nodes.', /** * @description Accessibility attribute name that appears under the Computed Properties section in * the Accessibility pane of the Elements panel when inspecting an element with aria-relevant set. */ relevantLiveRegions: 'Relevant (live regions)', /** *@description Tooltip text that appears when hovering over the 'Relevant (live regions)' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ ifThisElementMayReceiveLiveUpdates: 'If this element may receive live updates, what type of updates should trigger a notification.', /** * @description Accessibility attribute name that appears under the Computed Properties section in * the Accessibility pane of the Elements pane. Indicates that the aria-busy attribute is set for * the element, which means the element is being modified and assistive technologies like screen * readers may want to wait until the area is no longer live/busy before exposing it to the user. */ busyLiveRegions: '`Busy` (live regions)', /** *@description Tooltip text that appears when hovering over the 'Busy (live regions)' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ whetherThisElementOrItsSubtree: 'Whether this element or its subtree are currently being updated (and thus may be in an inconsistent state).', /** * @description Accessibility attribute name that appears under the Computed Properties section in * the Accessibility pane of the Elements panel. A live region is a section of the DOM graph which * is dynamic in nature and will change regularly. The live region root is the node in the graph * which is a parent of all nodes in the live region. * https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions */ liveRegionRoot: 'Live region root', /** *@description Tooltip text that appears when hovering over the 'Live region root' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ ifThisElementMayReceiveLiveUpdatesThe: 'If this element may receive live updates, the root element of the containing live region.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ hasAutocomplete: 'Has autocomplete', /** *@description Tooltip text that appears when hovering over the 'Has autocomplete' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ whetherAndWhatTypeOfAutocomplete: 'Whether and what type of autocomplete suggestions are currently provided by this element.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ hasPopup: 'Has popup', /** *@description Tooltip text that appears when hovering over the 'Has popup' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ whetherThisElementHasCausedSome: 'Whether this element has caused some kind of pop-up (such as a menu) to appear.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ level: 'Level', /** *@description Tooltip text that appears when hovering over the 'Level' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ theHierarchicalLevelOfThis: 'The hierarchical level of this element.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ multiselectable: 'Multi-selectable', /** *@description Tooltip text that appears when hovering over the 'Multi-selectable' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ whetherAUserMaySelectMoreThanOne: 'Whether a user may select more than one option from this widget.', /** *@description Text for the orientation of something */ orientation: 'Orientation', /** *@description Tooltip text that appears when hovering over the 'Orientation' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ whetherThisLinearElements: 'Whether this linear element\'s orientation is horizontal or vertical.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ multiline: 'Multi-line', /** *@description Tooltip text that appears when hovering over the 'Multi-line' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ whetherThisTextBoxMayHaveMore: 'Whether this text box may have more than one line.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ readonlyString: 'Read-only', /** *@description Tooltip text that appears when hovering over the 'Read-only' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ ifTrueThisElementMayBeInteracted: 'If true, this element may be interacted with, but its value cannot be changed.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ requiredString: 'Required', /** *@description Tooltip text that appears when hovering over the 'Required' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ whetherThisElementIsARequired: 'Whether this element is a required field in a form.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ minimumValue: 'Minimum value', /** *@description Tooltip text that appears when hovering over the 'Minimum value' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ forARangeWidgetTheMinimumAllowed: 'For a range widget, the minimum allowed value.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ maximumValue: 'Maximum value', /** *@description Tooltip text that appears when hovering over the 'Maximum value' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ forARangeWidgetTheMaximumAllowed: 'For a range widget, the maximum allowed value.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ valueDescription: 'Value description', /** *@description Tooltip text that appears when hovering over the 'Value description' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ aHumanreadableVersionOfTheValue: 'A human-readable version of the value of a range widget (where necessary).', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ checked: 'Checked', /** *@description Tooltip text that appears when hovering over the 'Checked' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ whetherThisCheckboxRadioButtonOr: 'Whether this checkbox, radio button or tree item is checked, unchecked, or mixed (e.g. has both checked and un-checked children).', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ expanded: 'Expanded', /** *@description Tooltip text that appears when hovering over the 'Expanded' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ whetherThisElementOrAnother: 'Whether this element, or another grouping element it controls, is expanded.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ pressed: 'Pressed', /** *@description Tooltip text that appears when hovering over the 'Pressed' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ whetherThisToggleButtonIs: 'Whether this toggle button is currently in a pressed state.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ selectedString: 'Selected', /** *@description Tooltip text that appears when hovering over the 'Selected' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ whetherTheOptionRepresentedBy: 'Whether the option represented by this element is currently selected.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ activeDescendant: 'Active descendant', /** *@description Tooltip text that appears when hovering over the 'Active descendant' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ theDescendantOfThisElementWhich: 'The descendant of this element which is active; i.e. the element to which focus should be delegated.', /** *@description Tooltip text that appears when hovering over the 'Flows to' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ elementToWhichTheUserMayChooseTo: 'Element to which the user may choose to navigate after this one, instead of the next element in the DOM order.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ controls: 'Controls', /** *@description Tooltip text that appears when hovering over the 'Controls' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ elementOrElementsWhoseContentOr: 'Element or elements whose content or presence is/are controlled by this widget.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ describedBy: 'Described by', /** *@description Tooltip text that appears when hovering over the 'Described by' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ elementOrElementsWhichFormThe: 'Element or elements which form the description of this element.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ labeledBy: 'Labeled by', /** *@description Tooltip text that appears when hovering over the 'Labeled by' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ elementOrElementsWhichMayFormThe: 'Element or elements which may form the name of this element.', /** *@description Tooltip text that appears when hovering over the 'Owns' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ elementOrElementsWhichShouldBe: 'Element or elements which should be considered descendants of this element, despite not being descendants in the DOM.', /** *@description Tooltip text that appears when hovering over the 'Name' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ theComputedNameOfThisElement: 'The computed name of this element.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ role: 'Role', /** *@description Tooltip text that appears when hovering over the 'Role' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ indicatesThePurposeOfThisElement: 'Indicates the purpose of this element, such as a user interface idiom for a widget, or structural role within a document.', /** *@description Text for the value of something */ value: 'Value', /** *@description Tooltip text that appears when hovering over the 'Value' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ theValueOfThisElementThisMayBe: 'The value of this element; this may be user-provided or developer-provided, depending on the element.', /** *@description Text for the viewing the help options */ help: 'Help', /** *@description Tooltip text that appears when hovering over the 'Help' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ theComputedHelpTextForThis: 'The computed help text for this element.', /** *@description Text for the description of something */ description: 'Description', /** *@description Tooltip text that appears when hovering over the 'Description' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ theAccessibleDescriptionForThis: 'The accessible description for this element.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ fromAttribute: 'From attribute', /** *@description Tooltip text that appears when hovering over the 'From attribute' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ valueFromAttribute: 'Value from attribute.', /** * @description The source of an accessibility attribute that appears under the Computed Properties * section in the Accessibility pane of the Elements panel. If the source is implicit, that means * it was never specified by the user but instead is present because it is the default value. */ implicit: 'Implicit', /** *@description Tooltip text that appears when hovering over the 'Implicit' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ implicitValue: 'Implicit value.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ fromStyle: 'From style', /** *@description Tooltip text that appears when hovering over the 'From style' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ valueFromStyle: 'Value from style.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ contents: 'Contents', /** *@description Tooltip text that appears when hovering over the 'Contents' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ valueFromElementContents: 'Value from element contents.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ fromPlaceholderAttribute: 'From placeholder attribute', /** *@description Tooltip text that appears when hovering over the 'From placeholder attribute' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ valueFromPlaceholderAttribute: 'Value from placeholder attribute.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ relatedElement: 'Related element', /** *@description Tooltip text that appears when hovering over the 'Related element' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ valueFromRelatedElement: 'Value from related element.', /** * @description Accessibility attribute name that appears under the Computed Properties section in * the Accessibility pane of the Elements pane. Indicates that this element got assigned this * attribute because there is a related caption, hence it received it from the caption. 'caption' * is part of the ARIA API and should not be translated. */ fromCaption: 'From `caption`', /** *@description Tooltip text that appears when hovering over the 'From caption' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ valueFromFigcaptionElement: 'Value from `figcaption` element.', /** * @description Accessibility attribute name that appears under the Computed Properties section in * the Accessibility pane of the Elements pane. Indicates that this element got assigned this * attribute because there is a related description, hence it received it from the description. * 'description' is part of the ARIA API and should not be translated. */ fromDescription: 'From `description`', /** *@description Tooltip text that appears when hovering over the 'From description' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ valueFromDescriptionElement: 'Value from `description` element.', /** * @description Accessibility attribute name that appears under the Computed Properties section in * the Accessibility pane of the Elements pane. Indicates that this element got assigned this * attribute because there is a related label, hence it received it from the label. 'label' * is part of the ARIA API and should not be translated. */ fromLabel: 'From `label`', /** *@description Tooltip text that appears when hovering over the 'From label' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ valueFromLabelElement: 'Value from `label` element.', /** * @description Accessibility attribute name that appears under the Computed Properties section in * the Accessibility pane of the Elements pane. Indicates that this element got assigned this * attribute because there is a related label, hence it received it from the label. 'label (for)' * is part of the ARIA API and should not be translated. label (for) is just a different type of * label. */ fromLabelFor: 'From `label` (`for=` attribute)', /** *@description Tooltip text that appears when hovering over the 'From label (for)' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ valueFromLabelElementWithFor: 'Value from `label` element with `for=` attribute.', /** * @description Accessibility attribute name that appears under the Computed Properties section in * the Accessibility pane of the Elements pane. Indicates that this element got assigned this * attribute because there is a related label which wraps (encompasses, surrounds) this element, * hence it received it from the label. 'wrapped' is not part of the ARIA API, and should be * translated. */ fromLabelWrapped: 'From `label` (wrapped)', /** * @description Tooltip text that appears when hovering over the 'From label (wrapped)' attribute * name under the Computed Properties section in the Accessibility pane of the Elements pane. * Indicates that there is a label element wrapping (surrounding) this element. */ valueFromLabelElementWrapped: 'Value from a wrapping `label` element.', /** * @description Accessibility attribute name that appears under the Computed Properties section in * the Accessibility pane of the Elements pane. Indicates that this element got assigned this * attribute because there is a related legend, hence it received it from the legend. 'legend' is * part of the ARIA API and should not be translated. */ fromLegend: 'From `legend`', /** *@description Tooltip text that appears when hovering over the 'From legend' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ valueFromLegendElement: 'Value from `legend` element.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ fromRubyAnnotation: 'From ruby annotation', /** *@description Tooltip text that appears when hovering over the 'From ruby annotation' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane. Indicates that the value was taken from a plain HTML ruby tag (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ruby). */ valueFromNativeHtmlRuby: 'Value from plain HTML ruby annotation.', /** *@description Tooltip text that appears when hovering over the 'From caption' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ valueFromTableCaption: 'Value from `table` `caption`.', /** * @description Accessibility attribute name that appears under the Computed Properties section in * the Accessibility pane of the Elements panel. */ fromTitle: 'From title', /** *@description Tooltip text that appears when hovering over the 'From title' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ valueFromTitleAttribute: 'Value from title attribute.', /** *@description Accessibility attribute name that appears under the Computed Properties section in the Accessibility pane of the Elements pane */ fromNativeHtml: 'From native HTML', /** *@description Tooltip text that appears when hovering over the 'From native HTML' attribute name under the Computed Properties section in the Accessibility pane of the Elements pane */ valueFromNativeHtmlUnknownSource: 'Value from native HTML (unknown source).', }; const str_ = i18n.i18n.registerUIStrings('panels/accessibility/AccessibilityStrings.ts', UIStrings); const i18nLazyString = i18n.i18n.getLazilyComputedLocalizedString.bind(undefined, str_); export const AXAttributes = { 'disabled': { name: i18nLazyString(UIStrings.disabled), description: i18nLazyString(UIStrings.ifTrueThisElementCurrentlyCannot), group: 'AXGlobalStates', }, 'invalid': { name: i18nLazyString(UIStrings.invalidUserEntry), description: i18nLazyString(UIStrings.ifTrueThisElementsUserentered), group: 'AXGlobalStates', }, 'editable': {name: i18nLazyString(UIStrings.editable), description: i18nLazyString(UIStrings.ifAndHowThisElementCanBeEdited)}, 'focusable': { name: i18nLazyString(UIStrings.focusable), description: i18nLazyString(UIStrings.ifTrueThisElementCanReceiveFocus), }, 'focused': {name: i18nLazyString(UIStrings.focused), description: i18nLazyString(UIStrings.ifTrueThisElementCurrentlyHas)}, 'settable': { name: i18nLazyString(UIStrings.canSetValue), description: i18nLazyString(UIStrings.whetherTheValueOfThisElementCan), }, 'live': { name: i18nLazyString(UIStrings.liveRegion), description: i18nLazyString(UIStrings.whetherAndWhatPriorityOfLive), group: 'AXLiveRegionAttributes', }, 'atomic': { name: i18nLazyString(UIStrings.atomicLiveRegions), description: i18nLazyString(UIStrings.ifThisElementMayReceiveLive), group: 'AXLiveRegionAttributes', }, 'relevant': { name: i18nLazyString(UIStrings.relevantLiveRegions), description: i18nLazyString(UIStrings.ifThisElementMayReceiveLiveUpdates), group: 'AXLiveRegionAttributes', }, 'busy': { name: i18nLazyString(UIStrings.busyLiveRegions), description: i18nLazyString(UIStrings.whetherThisElementOrItsSubtree), group: 'AXLiveRegionAttributes', }, 'root': { name: i18nLazyString(UIStrings.liveRegionRoot), description: i18nLazyString(UIStrings.ifThisElementMayReceiveLiveUpdatesThe), group: 'AXLiveRegionAttributes', }, 'autocomplete': { name: i18nLazyString(UIStrings.hasAutocomplete), description: i18nLazyString(UIStrings.whetherAndWhatTypeOfAutocomplete), group: 'AXWidgetAttributes', }, 'haspopup': { name: i18nLazyString(UIStrings.hasPopup), description: i18nLazyString(UIStrings.whetherThisElementHasCausedSome), group: 'AXWidgetAttributes', }, 'level': { name: i18nLazyString(UIStrings.level), description: i18nLazyString(UIStrings.theHierarchicalLevelOfThis), group: 'AXWidgetAttributes', }, 'multiselectable': { name: i18nLazyString(UIStrings.multiselectable), description: i18nLazyString(UIStrings.whetherAUserMaySelectMoreThanOne), group: 'AXWidgetAttributes', }, 'orientation': { name: i18nLazyString(UIStrings.orientation), description: i18nLazyString(UIStrings.whetherThisLinearElements), group: 'AXWidgetAttributes', }, 'multiline': { name: i18nLazyString(UIStrings.multiline), description: i18nLazyString(UIStrings.whetherThisTextBoxMayHaveMore), group: 'AXWidgetAttributes', }, 'readonly': { name: i18nLazyString(UIStrings.readonlyString), description: i18nLazyString(UIStrings.ifTrueThisElementMayBeInteracted), group: 'AXWidgetAttributes', }, 'required': { name: i18nLazyString(UIStrings.requiredString), description: i18nLazyString(UIStrings.whetherThisElementIsARequired), group: 'AXWidgetAttributes', }, 'valuemin': { name: i18nLazyString(UIStrings.minimumValue), description: i18nLazyString(UIStrings.forARangeWidgetTheMinimumAllowed), group: 'AXWidgetAttributes', }, 'valuemax': { name: i18nLazyString(UIStrings.maximumValue), description: i18nLazyString(UIStrings.forARangeWidgetTheMaximumAllowed), group: 'AXWidgetAttributes', }, 'valuetext': { name: i18nLazyString(UIStrings.valueDescription), description: i18nLazyString(UIStrings.aHumanreadableVersionOfTheValue), group: 'AXWidgetAttributes', }, 'checked': { name: i18nLazyString(UIStrings.checked), description: i18nLazyString(UIStrings.whetherThisCheckboxRadioButtonOr), group: 'AXWidgetStates', }, 'expanded': { name: i18nLazyString(UIStrings.expanded), description: i18nLazyString(UIStrings.whetherThisElementOrAnother), group: 'AXWidgetStates', }, 'pressed': { name: i18nLazyString(UIStrings.pressed), description: i18nLazyString(UIStrings.whetherThisToggleButtonIs), group: 'AXWidgetStates', }, 'selected': { name: i18nLazyString(UIStrings.selectedString), description: i18nLazyString(UIStrings.whetherTheOptionRepresentedBy), group: 'AXWidgetStates', }, 'activedescendant': { name: i18nLazyString(UIStrings.activeDescendant), description: i18nLazyString(UIStrings.theDescendantOfThisElementWhich), group: 'AXRelationshipAttributes', }, 'flowto': { name: i18n.i18n.lockedLazyString('Flows to'), description: i18nLazyString(UIStrings.elementToWhichTheUserMayChooseTo), group: 'AXRelationshipAttributes', }, 'controls': { name: i18nLazyString(UIStrings.controls), description: i18nLazyString(UIStrings.elementOrElementsWhoseContentOr), group: 'AXRelationshipAttributes', }, 'describedby': { name: i18nLazyString(UIStrings.describedBy), description: i18nLazyString(UIStrings.elementOrElementsWhichFormThe), group: 'AXRelationshipAttributes', }, 'labelledby': { name: i18nLazyString(UIStrings.labeledBy), description: i18nLazyString(UIStrings.elementOrElementsWhichMayFormThe), group: 'AXRelationshipAttributes', }, 'owns': { name: i18n.i18n.lockedLazyString('Owns'), description: i18nLazyString(UIStrings.elementOrElementsWhichShouldBe), group: 'AXRelationshipAttributes', }, 'name': { name: i18n.i18n.lockedLazyString('Name'), description: i18nLazyString(UIStrings.theComputedNameOfThisElement), group: 'Default', }, 'role': { name: i18nLazyString(UIStrings.role), description: i18nLazyString(UIStrings.indicatesThePurposeOfThisElement), group: 'Default', }, 'value': { name: i18nLazyString(UIStrings.value), description: i18nLazyString(UIStrings.theValueOfThisElementThisMayBe), group: 'Default', }, 'help': { name: i18nLazyString(UIStrings.help), description: i18nLazyString(UIStrings.theComputedHelpTextForThis), group: 'Default', }, 'description': { name: i18nLazyString(UIStrings.description), description: i18nLazyString(UIStrings.theAccessibleDescriptionForThis), group: 'Default', }, }; export const AXSourceTypes = { 'attribute': {name: i18nLazyString(UIStrings.fromAttribute), description: i18nLazyString(UIStrings.valueFromAttribute)}, 'implicit': { name: i18nLazyString(UIStrings.implicit), description: i18nLazyString(UIStrings.implicitValue), }, 'style': {name: i18nLazyString(UIStrings.fromStyle), description: i18nLazyString(UIStrings.valueFromStyle)}, 'contents': {name: i18nLazyString(UIStrings.contents), description: i18nLazyString(UIStrings.valueFromElementContents)}, 'placeholder': { name: i18nLazyString(UIStrings.fromPlaceholderAttribute), description: i18nLazyString(UIStrings.valueFromPlaceholderAttribute), }, 'relatedElement': {name: i18nLazyString(UIStrings.relatedElement), description: i18nLazyString(UIStrings.valueFromRelatedElement)}, }; export const AXNativeSourceTypes = { 'description': { name: i18nLazyString(UIStrings.fromDescription), description: i18nLazyString(UIStrings.valueFromDescriptionElement), }, 'figcaption': {name: i18nLazyString(UIStrings.fromCaption), description: i18nLazyString(UIStrings.valueFromFigcaptionElement)}, 'label': {name: i18nLazyString(UIStrings.fromLabel), description: i18nLazyString(UIStrings.valueFromLabelElement)}, 'labelfor': { name: i18nLazyString(UIStrings.fromLabelFor), description: i18nLazyString(UIStrings.valueFromLabelElementWithFor), }, 'labelwrapped': { name: i18nLazyString(UIStrings.fromLabelWrapped), description: i18nLazyString(UIStrings.valueFromLabelElementWrapped), }, 'legend': {name: i18nLazyString(UIStrings.fromLegend), description: i18nLazyString(UIStrings.valueFromLegendElement)}, 'rubyannotation': { name: i18nLazyString(UIStrings.fromRubyAnnotation), description: i18nLazyString(UIStrings.valueFromNativeHtmlRuby), }, 'tablecaption': {name: i18nLazyString(UIStrings.fromCaption), description: i18nLazyString(UIStrings.valueFromTableCaption)}, 'title': {name: i18nLazyString(UIStrings.fromTitle), description: i18nLazyString(UIStrings.valueFromTitleAttribute)}, 'other': { name: i18nLazyString(UIStrings.fromNativeHtml), description: i18nLazyString(UIStrings.valueFromNativeHtmlUnknownSource), }, };
the_stack
declare class TOActivityCroppedImageProvider extends UIActivityItemProvider { static alloc(): TOActivityCroppedImageProvider; // inherited from NSObject static new(): TOActivityCroppedImageProvider; // inherited from NSObject readonly angle: number; readonly circular: boolean; readonly cropFrame: CGRect; readonly image: UIImage; constructor(o: { image: UIImage; cropFrame: CGRect; angle: number; circular: boolean; }); initWithImageCropFrameAngleCircular(image: UIImage, cropFrame: CGRect, angle: number, circular: boolean): this; } declare class TOCropOverlayView extends UIView { static alloc(): TOCropOverlayView; // inherited from NSObject static appearance(): TOCropOverlayView; // inherited from UIAppearance static appearanceForTraitCollection(trait: UITraitCollection): TOCropOverlayView; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TOCropOverlayView; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): TOCropOverlayView; // inherited from UIAppearance static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TOCropOverlayView; // inherited from UIAppearance static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): TOCropOverlayView; // inherited from UIAppearance static new(): TOCropOverlayView; // inherited from NSObject displayHorizontalGridLines: boolean; displayVerticalGridLines: boolean; gridHidden: boolean; setGridHiddenAnimated(hidden: boolean, animated: boolean): void; } declare class TOCropScrollView extends UIScrollView { static alloc(): TOCropScrollView; // inherited from NSObject static appearance(): TOCropScrollView; // inherited from UIAppearance static appearanceForTraitCollection(trait: UITraitCollection): TOCropScrollView; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TOCropScrollView; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): TOCropScrollView; // inherited from UIAppearance static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TOCropScrollView; // inherited from UIAppearance static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): TOCropScrollView; // inherited from UIAppearance static new(): TOCropScrollView; // inherited from NSObject touchesBegan: () => void; touchesCancelled: () => void; touchesEnded: () => void; } declare class TOCropToolbar extends UIView { static alloc(): TOCropToolbar; // inherited from NSObject static appearance(): TOCropToolbar; // inherited from UIAppearance static appearanceForTraitCollection(trait: UITraitCollection): TOCropToolbar; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TOCropToolbar; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): TOCropToolbar; // inherited from UIAppearance static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TOCropToolbar; // inherited from UIAppearance static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): TOCropToolbar; // inherited from UIAppearance static new(): TOCropToolbar; // inherited from NSObject backgroundViewOutsets: UIEdgeInsets; cancelButtonTapped: () => void; readonly cancelIconButton: UIButton; readonly cancelTextButton: UIButton; cancelTextButtonTitle: string; readonly clampButton: UIButton; readonly clampButtonFrame: CGRect; clampButtonGlowing: boolean; clampButtonHidden: boolean; clampButtonTapped: () => void; readonly doneButtonFrame: CGRect; doneButtonTapped: () => void; readonly doneIconButton: UIButton; readonly doneTextButton: UIButton; doneTextButtonTitle: string; readonly resetButton: UIButton; resetButtonEnabled: boolean; resetButtonHidden: boolean; resetButtonTapped: () => void; readonly rotateButton: UIButton; readonly rotateClockwiseButton: UIButton; rotateClockwiseButtonHidden: boolean; rotateClockwiseButtonTapped: () => void; readonly rotateCounterclockwiseButton: UIButton; rotateCounterclockwiseButtonHidden: boolean; rotateCounterclockwiseButtonTapped: () => void; statusBarHeightInset: number; } declare class TOCropView extends UIView { static alloc(): TOCropView; // inherited from NSObject static appearance(): TOCropView; // inherited from UIAppearance static appearanceForTraitCollection(trait: UITraitCollection): TOCropView; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TOCropView; // inherited from UIAppearance static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): TOCropView; // inherited from UIAppearance static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TOCropView; // inherited from UIAppearance static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject> | typeof NSObject[]): TOCropView; // inherited from UIAppearance static new(): TOCropView; // inherited from NSObject alwaysShowCroppingGrid: boolean; angle: number; aspectRatio: CGSize; aspectRatioLockDimensionSwapEnabled: boolean; aspectRatioLockEnabled: boolean; readonly canBeReset: boolean; cropAdjustingDelay: number; readonly cropBoxAspectRatioIsPortrait: boolean; readonly cropBoxFrame: CGRect; cropBoxResizeEnabled: boolean; cropRegionInsets: UIEdgeInsets; cropViewPadding: number; readonly croppingStyle: TOCropViewCroppingStyle; croppingViewsHidden: boolean; delegate: TOCropViewDelegate; readonly foregroundContainerView: UIView; gridOverlayHidden: boolean; readonly gridOverlayView: TOCropOverlayView; readonly image: UIImage; imageCropFrame: CGRect; readonly imageViewFrame: CGRect; internalLayoutDisabled: boolean; maximumZoomScale: number; minimumAspectRatio: number; resetAspectRatioEnabled: boolean; simpleRenderMode: boolean; translucencyAlwaysHidden: boolean; constructor(o: { croppingStyle: TOCropViewCroppingStyle; image: UIImage; }); constructor(o: { image: UIImage; }); initWithCroppingStyleImage(style: TOCropViewCroppingStyle, image: UIImage): this; initWithImage(image: UIImage): this; moveCroppedContentToCenterAnimated(animated: boolean): void; performInitialSetup(): void; performRelayoutForRotation(): void; prepareforRotation(): void; resetLayoutToDefaultAnimated(animated: boolean): void; rotateImageNinetyDegreesAnimated(animated: boolean): void; rotateImageNinetyDegreesAnimatedClockwise(animated: boolean, clockwise: boolean): void; setAspectRatioAnimated(aspectRatio: CGSize, animated: boolean): void; setBackgroundImageViewHiddenAnimated(hidden: boolean, animated: boolean): void; setCroppingViewsHiddenAnimated(hidden: boolean, animated: boolean): void; setGridOverlayHiddenAnimated(gridOverlayHidden: boolean, animated: boolean): void; setSimpleRenderModeAnimated(simpleMode: boolean, animated: boolean): void; } declare class TOCropViewController extends UIViewController { static alloc(): TOCropViewController; // inherited from NSObject static new(): TOCropViewController; // inherited from NSObject activityItems: NSArray<any>; allowedAspectRatios: NSArray<number>; angle: number; applicationActivities: NSArray<UIActivity>; aspectRatioLockDimensionSwapEnabled: boolean; aspectRatioLockEnabled: boolean; aspectRatioPickerButtonHidden: boolean; aspectRatioPreset: TOCropViewControllerAspectRatioPreset; cancelButtonTitle: string; readonly cropView: TOCropView; readonly croppingStyle: TOCropViewCroppingStyle; customAspectRatio: CGSize; customAspectRatioName: string; delegate: TOCropViewControllerDelegate; doneButtonTitle: string; excludedActivityTypes: NSArray<string>; hidesNavigationBar: boolean; readonly image: UIImage; imageCropFrame: CGRect; minimumAspectRatio: number; onDidCropImageToRect: (p1: CGRect, p2: number) => void; onDidCropToCircleImage: (p1: UIImage, p2: CGRect, p3: number) => void; onDidCropToRect: (p1: UIImage, p2: CGRect, p3: number) => void; onDidFinishCancelled: (p1: boolean) => void; resetAspectRatioEnabled: boolean; resetButtonHidden: boolean; rotateButtonsHidden: boolean; rotateClockwiseButtonHidden: boolean; showActivitySheetOnDone: boolean; showCancelConfirmationDialog: boolean; readonly titleLabel: UILabel; readonly toolbar: TOCropToolbar; toolbarPosition: TOCropViewControllerToolbarPosition; constructor(o: { croppingStyle: TOCropViewCroppingStyle; image: UIImage; }); constructor(o: { image: UIImage; }); dismissAnimatedFromParentViewControllerToViewToFrameSetupCompletion(viewController: UIViewController, toView: UIView, frame: CGRect, setup: () => void, completion: () => void): void; dismissAnimatedFromParentViewControllerWithCroppedImageToViewToFrameSetupCompletion(viewController: UIViewController, image: UIImage, toView: UIView, frame: CGRect, setup: () => void, completion: () => void): void; initWithCroppingStyleImage(style: TOCropViewCroppingStyle, image: UIImage): this; initWithImage(image: UIImage): this; presentAnimatedFromParentViewControllerFromImageFromViewFromFrameAngleToImageFrameSetupCompletion(viewController: UIViewController, image: UIImage, fromView: UIView, fromFrame: CGRect, angle: number, toFrame: CGRect, setup: () => void, completion: () => void): void; presentAnimatedFromParentViewControllerFromViewFromFrameSetupCompletion(viewController: UIViewController, fromView: UIView, fromFrame: CGRect, setup: () => void, completion: () => void): void; resetCropViewLayout(): void; setAspectRatioPresetAnimated(aspectRatioPreset: TOCropViewControllerAspectRatioPreset, animated: boolean): void; } declare const enum TOCropViewControllerAspectRatioPreset { PresetOriginal = 0, PresetSquare = 1, Preset3x2 = 2, Preset5x3 = 3, Preset4x3 = 4, Preset5x4 = 5, Preset7x5 = 6, Preset16x9 = 7, PresetCustom = 8 } interface TOCropViewControllerDelegate extends NSObjectProtocol { cropViewControllerDidCropImageToRectAngle?(cropViewController: TOCropViewController, cropRect: CGRect, angle: number): void; cropViewControllerDidCropToCircularImageWithRectAngle?(cropViewController: TOCropViewController, image: UIImage, cropRect: CGRect, angle: number): void; cropViewControllerDidCropToImageWithRectAngle?(cropViewController: TOCropViewController, image: UIImage, cropRect: CGRect, angle: number): void; cropViewControllerDidFinishCancelled?(cropViewController: TOCropViewController, cancelled: boolean): void; } declare var TOCropViewControllerDelegate: { prototype: TOCropViewControllerDelegate; }; declare const enum TOCropViewControllerToolbarPosition { Bottom = 0, Top = 1 } declare class TOCropViewControllerTransitioning extends NSObject implements UIViewControllerAnimatedTransitioning { static alloc(): TOCropViewControllerTransitioning; // inherited from NSObject static new(): TOCropViewControllerTransitioning; // inherited from NSObject fromFrame: CGRect; fromView: UIView; image: UIImage; isDismissing: boolean; prepareForTransitionHandler: () => void; toFrame: CGRect; toView: UIView; readonly debugDescription: string; // inherited from NSObjectProtocol readonly description: string; // inherited from NSObjectProtocol readonly hash: number; // inherited from NSObjectProtocol readonly isProxy: boolean; // inherited from NSObjectProtocol readonly superclass: typeof NSObject; // inherited from NSObjectProtocol readonly // inherited from NSObjectProtocol animateTransition(transitionContext: UIViewControllerContextTransitioning): void; animationEnded(transitionCompleted: boolean): void; class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; interruptibleAnimatorForTransition(transitionContext: UIViewControllerContextTransitioning): UIViewImplicitlyAnimating; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; performSelector(aSelector: string): any; performSelectorWithObject(aSelector: string, object: any): any; performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any; reset(): void; respondsToSelector(aSelector: string): boolean; retainCount(): number; self(): this; transitionDuration(transitionContext: UIViewControllerContextTransitioning): number; } declare var TOCropViewControllerVersionNumber: number; declare var TOCropViewControllerVersionString: interop.Reference<number>; declare const enum TOCropViewCroppingStyle { Default = 0, Circular = 1 } interface TOCropViewDelegate extends NSObjectProtocol { cropViewDidBecomeNonResettable(cropView: TOCropView): void; cropViewDidBecomeResettable(cropView: TOCropView): void; } declare var TOCropViewDelegate: { prototype: TOCropViewDelegate; }; declare class TOCroppedImageAttributes extends NSObject { static alloc(): TOCroppedImageAttributes; // inherited from NSObject static new(): TOCroppedImageAttributes; // inherited from NSObject readonly angle: number; readonly croppedFrame: CGRect; readonly originalImageSize: CGSize; constructor(o: { croppedFrame: CGRect; angle: number; originalImageSize: CGSize; }); initWithCroppedFrameAngleOriginalImageSize(croppedFrame: CGRect, angle: number, originalSize: CGSize): this; }
the_stack
// deno-lint-ignore-file no-explicit-any import { Cookie, createElement, decodeBase64, deleteCookie, getCookies, green, isFormFile, MultipartReader, parseYml, red, renderToString, Response, serve, Server, ServerRequest, setCookie, yellow, } from "../deps.ts"; import { react, root } from "../template/react.ts"; import { CONTAINER, CONTENT_TYPE, CONTROLLER_FILE, DENO_ENV, DEV_ENV, FASTRO_VERSION, HOSTNAME, MAX_MEMORY, MIDDLEWARE_DIR, MODULE_DIR, NO_CONFIG, NO_DEPS, NO_MIDDLEWARE, NO_SERVICE, NO_STATIC_FILE, NO_TEMPLATE, NOT_FOUND, PAGE_FILE, PORT, REACT_ROOT, RUNNING_TEXT, STATIC_DIR, TEMPLATE_DIR, TEMPLATE_FILE, TEST_ENV, } from "./constant.ts"; import { Controller, Cookies, DynamicController, DynamicPage, Middleware, MultiPartData, Page, Query, Schema, ServerOptions, } from "./types.ts"; import { Data, HandlerOptions, HttpMethod } from "./types.ts"; import { createError, getErrorTime, replaceAll, validateObject, } from "./utils.ts"; /** * You have to create a `Fastro` class instance. * This will load all of your controller file automatically. * * const server = new Fastro(); * * With server options, you can change default service folder, add prefix, or enable cors. * * const serverOptions = { * cors: true, * prefix: "api", * moduleDir: "api", * staticFile: true, * }; * const server = new Fastro(serverOptions); */ export class Fastro { private appStatus!: string; private corsEnabled!: boolean; private cwd = Deno.cwd(); private dynamicController: DynamicController[] = []; private dynamicPage: DynamicPage[] = []; private hostname = HOSTNAME; private middlewares = new Map<string, Middleware>(); private pages = new Map<string, Page>(); private port = PORT; private prefix!: string; private server!: Server; private moduleDir = MODULE_DIR; private staticDir = STATIC_DIR; private controller = new Map<string, Controller>(); private staticFiles = new Map<string, any>(); private templateFiles = new Map<string, any>(); private container: any = undefined; constructor(options?: ServerOptions) { if (options && options.cors) this.corsEnabled = options.cors; if (options && options.hostname) this.hostname = options.hostname; if (options && options.prefix) this.prefix = options.prefix; if (options && options.port) this.port = options.port; if (options && options.serviceDir) this.moduleDir = options.serviceDir; if (options && options.staticDir) this.staticDir = options.staticDir; this.initApp(); } private handleRoot(request: Request) { const index = this.staticFiles.get("/index.html"); if (!index) return request.send(`Fastro v${FASTRO_VERSION}`); request.send(index); } private send<T>( payload: string | T, status: number | undefined = 200, headers: Headers | undefined = new Headers(), req: Request, ) { try { let body: string | Uint8Array | Deno.Reader | undefined; if ( typeof payload === "string" || payload instanceof Uint8Array ) { body = payload; } else if (typeof payload === "undefined") body = "undefined"; else if (Array.isArray(payload)) body = JSON.stringify(payload); else if ( typeof payload === "number" || typeof payload === "boolean" || typeof payload === "bigint" || typeof payload === "function" || typeof payload === "symbol" ) { body = payload.toString(); } else body = JSON.stringify(payload); const date = new Date().toUTCString(); const cookie = req.response.headers?.get("set-cookie"); if (cookie) headers.set("Set-Cookie", cookie); headers.set("Connection", "keep-alive"); headers.set("Date", date); headers.set("x-powered-by", this.appStatus); if (this.corsEnabled) { headers.set("Access-Control-Allow-Origin", "*"); headers.set("Access-Control-Allow-Headers", "*"); headers.set("Access-Control-Allow-Methods", "*"); } req.respond({ headers, status, body }); } catch (error) { error.message = "SEND_ERROR: " + error.message; console.error(error); } } private getCookiesByName(name: string, request: Request) { const cookies = request.headers.get("cookie")?.split(";"); const results = cookies?.map((v: any) => { const [n, value] = v.split("="); const name = n.trim(); return { name, value }; }) .filter((c: any) => c.name === name); if (!results || results.length < 1) return ""; const [c] = results; return c.value; } private handleRedirect(url: string, status: number, request: ServerRequest) { const headers = new Headers(); headers.set("Location", url); request.respond({ status, headers }); } private async handleFormUrlEncoded(req: ServerRequest, contentType: string) { try { const d = new TextDecoder(); const bodyString = d.decode(await Deno.readAll(req.body)); const body = bodyString .replace(contentType, "") .split("&"); const data: Data[] = []; body.forEach((i: string) => { if (i.includes("=")) { const [key, value] = i.split("="); const decodedV = decodeURIComponent(value); const decodedK = decodeURIComponent(key); const obj: Data = {}; obj[decodedK] = decodedV; data.push(obj); } else { const obj = JSON.parse(i); data.push(obj); } }); if (data.length > 1) return data; if (data.length === 1) { const [d] = data; return d; } } catch (error) { error.message = "HANDLE_FORM_URL_ENCODED_ERROR: " + error.message; throw error; } } private async handleMultipart(req: ServerRequest, contentType: string) { try { const decode = new TextDecoder().decode; const boundaries = contentType?.match(/boundary=([^\s]+)/); let boundary; const multiPartArray: MultiPartData[] = []; if (boundaries && boundaries?.length > 0) [, boundary] = boundaries; if (boundary) { const reader = new MultipartReader(req.body, boundary); const form = await reader.readForm(MAX_MEMORY); const map = new Map(form.entries()); map.forEach((v, key) => { const content = form.file(key); if (isFormFile(content)) { const v = decode(content.content); multiPartArray.push({ key, value: v, filename: content.filename }); } else { multiPartArray.push({ key, value: v }); } }); await form.removeAll(); } return multiPartArray; } catch (error) { error.message = "HANDLE_MULTIPART_ERROR: " + error.message; throw error; } } private validateJsonPayload(payload: Data, url: string) { try { const controller = this.controller.get(url); if ( controller && controller.options.validationSchema && controller.options.validationSchema.body ) { const schema = controller.options.validationSchema.body as Schema; validateObject(payload, schema); } } catch (error) { error.message = "VALIDATE_JSON_PAYLOAD_ERROR: " + error.message; throw error; } } private async getPayload(requestServer: ServerRequest) { try { const d = new TextDecoder(); const contentType = requestServer.headers.get(CONTENT_TYPE); if (contentType?.includes("multipart/form-data")) { return this.handleMultipart(requestServer, contentType); } else if ( contentType?.includes("application/x-www-form-urlencoded") ) { return this.handleFormUrlEncoded(requestServer, contentType); } else if ( contentType?.includes("application/json") ) { const payloadString = d.decode(await Deno.readAll(requestServer.body)); const payload = JSON.parse(payloadString); this.validateJsonPayload(payload, requestServer.url); return payload; } else { const payload = d.decode(await Deno.readAll(requestServer.body)); return payload; } } catch (error) { error.message = "GET_PAYLOAD_ERROR: " + error.message; throw error; } } private validateParams(params: Data, url: string) { try { const [handler] = this.dynamicController.filter((val) => val.url === url); if ( handler && handler.controller.options.validationSchema && handler.controller.options.validationSchema.params ) { const schema = handler.controller.options.validationSchema .params as Schema; validateObject(params, schema); } } catch (error) { error.message = "VALIDATE_PARAMS_ERROR: " + error.message; throw error; } } private getParams(incoming: string) { try { const incomingSplit = incoming.substr(1, incoming.length).split("/"); const params: string[] = []; incomingSplit .map((path, idx) => { return { path, idx }; }) .forEach((value) => params.push(incomingSplit[value.idx])); this.validateParams(params, incoming); return params; } catch (error) { error.message = "GET_PARAMS_ERROR: " + error.message; throw error; } } private validateQuery(query: Data, url: string) { try { const [handler] = this.dynamicController.filter((val) => url.includes(val.url) ); if ( handler && handler.controller.options.validationSchema && handler.controller.options.validationSchema.params ) { const schema = handler.controller.options.validationSchema .querystring as Schema; validateObject(query, schema); } } catch (error) { error.message = "VALIDATE_QUERY_ERROR: " + error.message; throw error; } } private getQuery(key?: string, url?: string) { try { if (!url) throw new Error("Url empty"); const [, query] = url.split("?"); if (!query) throw new Error("Query not found"); const queryPair = query.split("&"); const obj: Query = {}; queryPair.forEach((q) => { const [key, value] = q.split("="); obj[key] = value; }); this.validateQuery(obj, url); if (key) { const singleQuery: Query = {}; singleQuery[key] = obj[key]; return singleQuery; } return obj; } catch (error) { error.message = "GET_QUERY_ERROR: " + error.message; throw error; } } private async proxy(url: string, request: Request) { try { const resp = await fetch(url, { method: request.method, }); request.send(new Uint8Array(await resp.arrayBuffer())); } catch (error) { error.message = "PROXY_ERROR: " + error.message; throw error; } } private view(template: string, options?: Data, request?: Request) { try { let html = this.templateFiles.get(template); if (html) { for (const key in options) { const value = options[key]; html = replaceAll(html, `{{${key}}}`, value); } } if (request) request.send(html); } catch (error) { error.message = "VIEW_ERROR" + error.message; throw error; } } private transformRequest(serverRequest: ServerRequest, container: any) { try { const request = serverRequest as unknown as Request; request.container = container; request.response = {}; request.response.headers = new Headers(); request.proxy = (url) => this.proxy(url, request); request.view = (template, options) => this.view(template, options, request); request.redirect = (url, status = 302) => this.handleRedirect(url, status, serverRequest); request.getQuery = (key) => this.getQuery(key, serverRequest.url); request.getParams = () => this.getParams(serverRequest.url); request.getPayload = () => this.getPayload(serverRequest); request.setCookie = (cookie: Cookie) => { setCookie(request.response, cookie); return request; }; request.clearCookie = (name) => deleteCookie(request.response, name); request.getCookies = () => { return getCookies({ headers: serverRequest.headers }); }; request.getCookie = (name) => this.getCookiesByName(name, request); request.json = (payload) => { const headers = new Headers(); headers.set(CONTENT_TYPE, "application/json"); this.send(payload, request.httpStatus, headers, request); }; request.type = (contentType: string) => { request.contentType = contentType; return request; }; request.status = (status: number) => { request.httpStatus = status; return request; }; request.send = (payload, status, headers) => { status = request.httpStatus ? request.httpStatus : 200; if (request.contentType) { headers = new Headers(); headers.set(CONTENT_TYPE, request.contentType); } this.send(payload, status, headers, request); }; return request; } catch (error) { error.message = "TRANSFORM_REQUEST_ERROR: " + error.message; console.error( `ERROR: ${getErrorTime()}, url: ${serverRequest.url},`, error, ); } } private handleStaticFile(request: Request) { try { const url = request.url; const staticFile = this.staticFiles.get(url); if (!staticFile) throw new Error(NOT_FOUND); const header = new Headers(); if (url.includes(".svg")) header.set(CONTENT_TYPE, "image/svg+xml"); else if (url.includes(".png")) header.set(CONTENT_TYPE, "image/png"); else if (url.includes(".jpeg")) header.set(CONTENT_TYPE, "image/jpeg"); else if (url.includes(".css")) header.set(CONTENT_TYPE, "text/css"); else if (url.includes(".html")) header.set(CONTENT_TYPE, "text/html"); else if (url.includes(".json")) { header.set(CONTENT_TYPE, "application/json"); } else if (url.includes("favicon.ico")) { header.set(CONTENT_TYPE, "image/ico"); } request.send(staticFile, 200, header); } catch (error) { throw createError("HANDLE_STATIC_FILE_ERROR", error); } } private handleDynamicParams(request: Request) { try { const [handlerFile] = this.dynamicController.filter((controller) => { return request.url.includes(controller.url); }); if (!handlerFile) return this.handlePage(request); const options: HandlerOptions = handlerFile.controller.options ? handlerFile.controller.options : undefined; if ( options && options.methods && !options.methods.includes(request.method as HttpMethod) ) { throw new Error(NOT_FOUND); } if ( options && options.validationSchema && options.validationSchema.headers ) { const schema = options.validationSchema.headers as Schema; this.validateHeaders(request.headers, schema); } handlerFile.controller.default(request); } catch (error) { throw createError("HANDLE_DYNAMIC_PARAMS_ERROR", error); } } private handleMiddleware(request: Request) { try { this.middlewares.forEach((middleware, key) => { if ( middleware.options && middleware.options.methods && !middleware.options.methods.includes(request.method) ) { throw new Error(NOT_FOUND); } if ( middleware.options && middleware.options.validationSchema ) { const schema = middleware.options.validationSchema.headers as Schema; this.validateHeaders(request.headers, schema); } middleware.default(request, (err: Error) => { if (err) { if (!err.message) err.message = `Middleware error: ${key}`; throw err; } this.handleRoute(request); }); }); } catch (error) { throw createError("HANDLE_MIDDLEWARE_ERROR", error); } } private validateHeaders(headers: Headers, schema: Schema) { try { const target: Data = {}; const { properties } = schema; for (const key in properties) target[key] = headers.get(key); validateObject(target, schema); } catch (error) { error.message = "VALIDATE_HEADERS_ERROR: " + error.message; throw error; } } private renderComponent( page: Page, props: any, template?: string, ) { const rendered = renderToString(createElement(page.default, props)); let reactRoot = root.replace("{{root}}", `${rendered}`); reactRoot = reactRoot.replace("{{element}}", `${page.default}`); reactRoot = reactRoot.replace("{{props}}", JSON.stringify(props)); let html = template ? template.replace(REACT_ROOT, reactRoot) : react.replace(REACT_ROOT, reactRoot); if (page.options && page.options.title) { html = html.replace("{{title}}", page.options.title); } else { html = html.replace("{{title}}", "Hello"); } return html; } private async sendHTML(page: Page, request: Request) { try { let html; let props; if (page.props && typeof page.props === "function") { props = await page.props(request); } else if (page.props) { props = page.props; props.url = request.url; props.params = request.getParams(); props.cookie = request.getCookies(); } if (page.options && page.options.template) { const template = this.templateFiles.get(page.options.template); html = this.renderComponent(page, props, template); } else html = this.renderComponent(page, props); request.type("text/html").send(html); } catch (error) { throw createError("SEND_HTML_ERROR", error); } } private handlePage(request: Request) { const page = this.pages.get(request.url); if (!page) return this.handleDynamicPage(request); this.sendHTML(page, request); } private handleDynamicPage(request: Request) { const [page] = this.dynamicPage.filter((page) => request.url.includes(page.url) ); if (!page) return this.handleStaticFile(request); this.sendHTML(page.page, request); } private handleRoute(request: Request) { try { const controller = this.controller.get(request.url); const options = controller && controller.options ? controller.options : undefined; if (!controller) return this.handleDynamicParams(request); if ( options && options.methods && !options.methods.includes(request.method as HttpMethod) ) { throw new Error(NOT_FOUND); } if ( options && options.validationSchema && options.validationSchema.headers ) { const schema = options.validationSchema.headers as Schema; this.validateHeaders(request.headers, schema); } controller.default(request); } catch (error) { throw createError("HANDLE_ROUTE_ERROR", error); } } private handleRequestError(error: Error, serverRequest: ServerRequest) { const err = createError("HANDLE_REQUEST_ERROR", error); let status = 500; if (error.message.includes(NOT_FOUND)) status = 404; if (error.message.includes("VALIDATE")) status = 400; const message = JSON.stringify({ error: true, message: error.message }); const headers = new Headers(); headers.set(CONTENT_TYPE, "application/json"); serverRequest.respond({ status, body: message, headers }); console.error( `ERROR: ${getErrorTime()}, url: ${serverRequest.url},`, err, ); } private handleRequest(serverRequest: ServerRequest, container: any) { try { const request = this.transformRequest(serverRequest, container); if (!request) throw new Error("handle request error"); if (serverRequest.url === "/") return this.handleRoot(request); if (this.middlewares.size > 0) return this.handleMiddleware(request); this.handleRoute(request); } catch (error) { this.handleRequestError(error, serverRequest); } } private async readHtmlTemplate(target: string) { try { const templateFolder = `${this.cwd}/${target}`; const decoder = new TextDecoder("utf-8"); for await (const dirEntry of Deno.readDir(templateFolder)) { if (dirEntry.isFile && dirEntry.name.includes(TEMPLATE_FILE)) { const filePath = templateFolder + "/" + dirEntry.name; const file = await Deno.readFile(filePath); this.templateFiles.set(dirEntry.name, decoder.decode(file)); } else if (dirEntry.isDirectory) { this.readHtmlTemplate(target + "/" + dirEntry.name); } } } catch (error) { console.info(yellow(NO_TEMPLATE)); } } private isTxtFile(file: string) { const extension = [ ".html", ".json", ".css", ".xml", ".txt", ".ts", ".js", ".md", ]; const result = extension.filter((ext) => file.includes(ext)); return result.length > 0; } private async readStaticFiles(target: string) { try { const staticFolder = `${this.cwd}/${target}`; const decoder = new TextDecoder("utf-8"); for await (const dirEntry of Deno.readDir(staticFolder)) { if (dirEntry.isFile) { const filePath = staticFolder + "/" + dirEntry.name; const [, fileKey] = filePath.split(staticFolder); const file = await Deno.readFile(filePath); if (this.isTxtFile(dirEntry.name)) { this.staticFiles.set(fileKey, decoder.decode(file)); } else this.staticFiles.set(fileKey, file); } else if (dirEntry.isDirectory) { this.readStaticFiles(target + "/" + dirEntry.name); } } } catch (error) { if (Deno.env.get(DENO_ENV) !== TEST_ENV) { console.info(yellow(NO_STATIC_FILE)); } } } private async importMiddleware(target: string) { try { const middlewareFolder = `${this.cwd}/${target}`; for await (const dirEntry of Deno.readDir(middlewareFolder)) { if (dirEntry.isFile) { const filePath = middlewareFolder + "/" + dirEntry.name; const fileImport = Deno.env.get(DENO_ENV) === DEV_ENV ? `file:${filePath}#${new Date().getTime()}` : `file:${filePath}`; import(fileImport).then((middleware) => { this.middlewares.set(dirEntry.name, middleware); }); } else if (dirEntry.isDirectory) { this.importMiddleware(target + "/" + dirEntry.name); } } } catch (error) { if (Deno.env.get(DENO_ENV) !== TEST_ENV) { console.info(yellow(NO_MIDDLEWARE)); } } } private importContainer() { try { const container = `${this.cwd}/${CONTAINER}`; const fileImport = Deno.env.get(DENO_ENV) === DEV_ENV ? `file:${container}#${new Date().getTime()}` : `file:${container}`; import(fileImport).then((c) => { this.container = c.default; }); } catch (error) { if (Deno.env.get(DENO_ENV) !== TEST_ENV) { console.info(yellow(NO_DEPS)); } } } private async importController(target: string) { try { const servicesFolder = `${this.cwd}/${target}`; for await (const dirEntry of Deno.readDir(servicesFolder)) { if (dirEntry.isDirectory) { this.importController(target + "/" + dirEntry.name); } else if ( dirEntry.isFile && (dirEntry.name.includes(CONTROLLER_FILE) || dirEntry.name.includes(PAGE_FILE)) ) { const filePath = servicesFolder + "/" + dirEntry.name; const [, splittedFilePath] = filePath.split(this.moduleDir); const [splittedWithDot] = splittedFilePath.split("."); const finalPath = Deno.env.get(DENO_ENV) === DEV_ENV ? `file:${filePath}#${new Date().getTime()}` : `file:${filePath}`; const fileKey = this.prefix ? `/${this.prefix}${splittedWithDot}` : `${splittedWithDot}`; const isPage = dirEntry.name.includes(PAGE_FILE); this.nativeImport(finalPath, fileKey, isPage); } } } catch (error) { if (Deno.env.get(DENO_ENV) !== TEST_ENV) { console.info(yellow(NO_SERVICE)); } } } private nativeImport(filePath: string, fileKey: string, isPage: boolean) { import(filePath) .then((importedFile) => { const options = importedFile.options as HandlerOptions; fileKey = options && options.prefix ? `/${options.prefix}${fileKey}` : fileKey; if (options && options.params) { if (isPage) { this.dynamicPage.push({ url: fileKey, page: importedFile }); } else { this.dynamicController.push({ url: fileKey, controller: importedFile, }); } return; } if (isPage) this.pages.set(fileKey, importedFile); else this.controller.set(fileKey, importedFile); }); } private getAppStatus() { const decoded = this.regid ? decodeBase64("cmVnaXN0ZXJlZA==") : decodeBase64("VU5SRUdJU1RFUkVE"); const text = new TextDecoder().decode(decoded); const version = `Fastro/${FASTRO_VERSION} (${text})`; return version; } private async readConfig() { try { const configFile = await Deno.readTextFile("config.yml"); const parsedConfig = parseYml(configFile); if (configFile && parsedConfig) { const { email, regid } = <{ email: string; regid: string; }> parsedConfig; this.regid = regid; this.email = email; } } catch (error) { if (Deno.env.get(DENO_ENV) !== TEST_ENV) { console.info(yellow(NO_CONFIG)); } } } private regid!: string; private email!: string; initApp() { this.readConfig() .then(() => this.appStatus = this.getAppStatus()) .then(() => this.importMiddleware(MIDDLEWARE_DIR)) .then(() => this.readHtmlTemplate(TEMPLATE_DIR)) .then(() => this.importController(this.moduleDir)) .then(() => this.readStaticFiles(this.staticDir)) .then(() => this.importContainer()) .then(() => this.listen()); } /** * Close server * * server.close() */ public close() { if (this.server) this.server.close(); } private async listen() { try { if (Deno.env.get(DENO_ENV) !== TEST_ENV) { const addr = `http://${this.hostname}:${this.port}`; const runningText = `${RUNNING_TEXT}: ${addr}`; if (!this.regid) { console.info(red(this.getAppStatus())); console.info(green(runningText)); } else { console.info(green(this.getAppStatus())); console.info(green(runningText)); } } this.server = serve({ hostname: this.hostname, port: this.port }); for await (const request of this.server) { this.handleRequest(request, this.container); } } catch (error) { error.message = "LISTEN_ERROR: " + error.message; console.error(red(`ERROR: ${getErrorTime()}`), error); Deno.exit(1); } } } export class Request extends ServerRequest { response!: Response; contentType!: string; httpStatus!: number; /** * Set content type before send * * request.type("text/html").send("hello"); */ type!: { (contentType: string): Request; }; /** * Set HTTP Status * * request.status(404).send("not found"); */ status!: { (httpStatus: number): Request; }; /** * Get all cookies * * const cookies = request.getCookies(); */ getCookies!: { (): Cookies; }; /** * Get cookie by name * * const cookie = request.getCookie("my-cookie"); */ getCookie!: { (name: string): string; }; /** * Set cookie * * import { Cookie } from "../mod.ts"; * const cookie: Cookie = { name: "hello", value: "pram" }; * request.setCookie(cookie); */ setCookie!: { (cookie: Cookie): Request; }; /** * Clear cookie by name * * request.clearCookie("hello") */ clearCookie!: { (name: string): void; }; /** * Redirect to the specified url, the status code is optional (default to 302) * * request.redirect("/", 302) */ redirect!: { (url: string, status?: number): void; }; /** * Sends the payload to the user, could be a plain text, a buffer, JSON, stream, or an Error object. * * request.send("hello"); */ send!: { <T>(payload: string | T, status?: number, headers?: Headers): void; }; /** * Sends json object. * * request.send({ message: "hello" }); */ json!: { (payload: any): void; }; /** * Get url parameters * * * const params = request.getParams(); */ getParams!: { (): string[]; }; /** * Get payload. Could be plain text, json, multipart, or url-encoded * * * const payload = await request.getPayload(); */ getPayload!: { (): Promise<any>; }; /** * Get query * * const query = await request.getQuery() */ getQuery!: { (name?: string): Query; }; /** * URL proxy * * request.proxy("https://github.com/fastrodev/fastro"); */ proxy!: { (url: string): void; }; /** * Render html template * * request.view("index.template.html", { title: "Hello" }); */ view!: { (template: string, options?: any): void; }; /** * You can access container that defined on server creation * * request.container; */ container!: any; [key: string]: any }
the_stack
import { SkillBuilders } from 'ask-sdk-core'; import { ControlInput, ControlResponseBuilder, ControlResult, NumberControl } from '../../../src'; import { MultiValueListControl } from '../../../src/commonControls/multiValueListControl/MultiValueListControl'; import { MultiValueListControlComponentAPLBuiltIns } from '../../../src/commonControls/multiValueListControl/MultiValueListControlAPL'; import { ComponentModeControlManager } from '../../../src/controls/ComponentModeControlManager'; import { Control } from '../../../src/controls/Control'; import { ControlHandler } from '../../../src/runtime/ControlHandler'; import { DemoRootControl } from '../../Common/src/DemoRootControl'; /** * Demonstrates the composition of visual-aspects of multiple controls */ export namespace ComponentModeDemo { export class DemoControlManager extends ComponentModeControlManager { ageControl: NumberControl; guestsControl: NumberControl; partyThemeControl: MultiValueListControl; createControlTree(): Control { const rootControl = new DemoRootControl({ id: 'root' }); rootControl.addChild( (this.ageControl = new NumberControl({ id: 'age', interactionModel: { targets: ['builtin_it', 'age'], }, prompts: { requestValue: 'How old will you be?', valueSet: (act, input) => `${act.payload.renderedValue} is a great age!`, }, })), ); rootControl.addChild( (this.guestsControl = new NumberControl({ id: 'guests', interactionModel: { targets: ['builtin_it', 'guests'], }, validation: (state) => state.value <= 10 || { renderedReason: 'Ten guests is the most we can accommodate.' }, prompts: { requestValue: 'How many guests are coming?', valueSet: (act, input) => `${act.payload.value > 3 ? 'Awesome' : 'OK'}. I have you down for ${ act.payload.renderedValue } guests.`, }, apl: { validationFailedMessage: 'Maximum: 10', }, })), ); rootControl.addChild( (this.partyThemeControl = new MultiValueListControl({ id: 'partyThemeControl', listItemIDs: ['pirate', 'cartoon', 'fairy', 'monster'], slotType: 'PartyTheme', interactionModel: { targets: ['builtin_choice', 'builtin_it', 'theme'], }, apl: { renderComponent: MultiValueListControlComponentAPLBuiltIns.CheckBoxRenderer.default, }, })), ); return rootControl; } async renderAPL( result: ControlResult, input: ControlInput, controlResponseBuilder: ControlResponseBuilder, ): Promise<void> { controlResponseBuilder.addAPLDocumentStyle('ComponentPlaceholderStyle', { values: [ { borderColor: 'white', borderWidth: '2px', padding: '0', }, ], }); controlResponseBuilder.addAPLDocumentStyle('LabelStyle', { values: [ { fontSize: '24dp', }, ], }); // TODO: change to a more responsive layout rather than absolute positioning const aplDoc = { type: 'APL', version: '1.5', import: [ { name: 'alexa-layouts', version: '1.2.0', }, ], styles: {}, //placeholder layouts: {}, //placeholder mainTemplate: { parameters: ['wrapper'], item: { id: 'root', type: 'Container', width: '100vw', height: '100vh', bind: [ { name: 'disableContent', value: false, type: 'boolean', }, ], items: [ { id: 'label1', type: 'Text', style: 'LabelStyle', position: 'absolute', top: '150px', left: '50px', width: '200px', height: '100px', text: 'Your age:', }, { id: 'ageComponent', type: 'Frame', position: 'absolute', style: 'ComponentPlaceholderStyle', top: '200px', left: '50px', width: '200px', height: '100px', items: [ await this.ageControl.renderAPLComponent(input, controlResponseBuilder), ], }, { id: 'label2', type: 'Text', style: 'LabelStyle', position: 'absolute', top: '350px', left: '50px', width: '200px', height: '100px', text: 'Number of guests:', }, { id: 'guestsComponent', type: 'Frame', position: 'absolute', style: 'ComponentPlaceholderStyle', top: '400px', left: '50px', width: '200px', height: '100px', items: [ await this.guestsControl.renderAPLComponent( input, controlResponseBuilder, ), ], }, { id: 'label3', type: 'Text', style: 'LabelStyle', position: 'absolute', top: '150px', left: '300px', width: '200px', height: '100px', text: 'Theme:', }, { id: 'birthdayThemeComponent', type: 'Frame', position: 'absolute', style: 'ComponentPlaceholderStyle', top: '200px', left: '300px', width: '700px', height: '360px', items: [ await this.partyThemeControl.renderAPLComponent( input, controlResponseBuilder, ), ], }, { type: 'AlexaHeader', style: 'ComponentPlaceholderStyle', backgroundColor: '#557755', id: 'heading1', headerDivider: true, headerBackButton: '${wrapper.general.headerBackButton}', headerBackButtonCommand: { type: 'SendEvent', arguments: ['goBack'], }, headerTitle: 'Chucky Cheese', headerSubtitle: 'Birthday booking', }, { type: 'AlexaButton', id: 'nextButton', disabled: '${disableContent}', buttonText: '${wrapper.general.nextButtonText}', position: 'absolute', top: '10', right: '10', primaryAction: { type: 'Sequential', commands: [ { type: 'SetValue', componentId: 'debugText', property: 'text', value: 'Complete', }, { type: 'SetValue', componentId: 'root', property: 'disableContent', value: true, }, { type: 'SendEvent', arguments: ['${wrapper.general.controlId}', 'complete'], }, ], }, }, ], }, }, }; aplDoc.layouts = controlResponseBuilder.aplDocumentLayouts; aplDoc.styles = controlResponseBuilder.aplDocumentStyles; //TODO: factor out the adding of context.style / context.dataSources / templates controlResponseBuilder.addAPLRenderDocumentDirective( 'token', aplDoc, controlResponseBuilder.aplDocumentDataSources, ); } } } export const handler = SkillBuilders.custom() .addRequestHandlers(new ControlHandler(new ComponentModeDemo.DemoControlManager())) .lambda();
the_stack
declare namespace vips { // Allow single pixels/images as input. type Array<T> = T | T[]; type Enum = string | number; type Flag = string | number; type Blob = string | ArrayBuffer | Uint8Array | Uint8ClampedArray | Int8Array; type ArrayConstant = Array<number>; type ArrayImage = Array<Image> | Vector<Image>; /** * Get the major, minor or patch version number of the libvips library. * When the flag is omitted, the entire version number is returned as a string. * @param flag 0 to get the major version number, 1 to get minor, 2 to get patch. * @return The version number of libvips. */ function version(flag?: number): string | number; /** * Returns a string identifying the Emscripten version used for compiling wasm-vips. * @return The version number of Emscripten. */ function emscriptenVersion(): string; /** * Get detailed information about the installation of libvips. * @return Information about how libvips is configured. */ function config(): string; /** * Gets or, when a parameter is provided, sets the number of worker threads libvips' should create to * process each image. * @param concurrency The number of worker threads. * @return The number of worker threads libvips uses for image evaluation. */ function concurrency(concurrency?: number): void | number; /** * Call this to shutdown libvips and the runtime of Emscripten. * This is only needed on Node.js, as the thread pool of * Emscripten prevents the event loop from exiting. */ function shutdown(): void; /** * A sequence container representing an array that can change in size. */ export interface Vector<T> { /** * Adds a new element at the end of the vector, after its current last element. * @param val The value to be appended at the end of the container. */ push_back(val: T): void; /** * Resizes the container so that it contains n elements. * @param n New size of the container. * @param val The value to initialize the new elements with. */ resize(n: number, val: T): void; /** * Returns the number of elements in the container. * @return The number of elements in the container. */ size(): number; /** * Access a specified element with bounds checking. * @param pos Position of the element to return. * @return The requested element or `undefined`. */ get(pos: number): T | undefined; /** * Update a specified element at a certain position. * @param pos Position of the element to update. * @param val Value to be stored at the specified position. * @return `true` if successfully updated. */ set(pos: number, val: T): boolean; } /** * A class around libvips' operation cache. */ export class Cache { /** * Gets or, when a parameter is provided, sets the maximum number of operations libvips keeps in cache. * @param max Maximum number of operations. * @return The maximum number of operations libvips keeps in cache. */ static max(max?: number): void | number; /** * Gets or, when a parameter is provided, sets the maximum amount of tracked memory allowed. * @param mem Maximum amount of tracked memory. * @return The maximum amount of tracked memory libvips allows. */ static maxMem(mem?: number): void | number; /** * Gets or, when a parameter is provided, sets the maximum amount of tracked files allowed. * @param maxFiles Maximum amount of tracked files. * @return The maximum amount of tracked files libvips allows. */ static maxFiles(maxFiles?: number): void | number; /** * Get the current number of operations in cache. * @return The current number of operations in cache. */ static size(): number; } /** * A class that provides the statistics of memory usage and opened files. * libvips watches the total amount of live tracked memory and * uses this information to decide when to trim caches. */ export class Stats { /** * Get the number of active allocations. * @return The number of active allocations. */ static allocations(): number; /** * Get the number of bytes currently allocated `vips_malloc()` and friends. * libvips uses this figure to decide when to start dropping cache. * @return The number of bytes currently allocated. */ static mem(): number; /** * Get the largest number of bytes simultaneously allocated via `vips_tracked_malloc()`. * Handy for estimating max memory requirements for a program. * @return The largest number of currently allocated bytes. */ static memHighwater(): number; /** * Get the number of open files. * @return The number of open files. */ static files(): number; } /** * A class for error messages and error handling. */ export class Error { /** * Get the error buffer as a string. * @return The error buffer as a string. */ static buffer(): string; /** * Clear and reset the error buffer. * This is typically called after presenting an error to the user. */ static clear(): void; } /** * Handy utilities. */ export class Utils { /** * Get the GType for a name. * Looks up the GType for a nickname. Types below basename in the type hierarchy are searched. * @param basename Name of base class. * @param nickname Search for a class with this nickname. * @return The GType of the class, or `0` if the class is not found. */ static typeFind(basename: string, nickname: string): number; /** * Make a temporary file name. The format parameter is something like `"%s.jpg"` * and will be expanded to something like `"/tmp/vips-12-34587.jpg"`. * @param format The filename format. */ static tempName(format: string): string; } /** * The abstract base Connection class. */ export class Connection { /** * Get the filename associated with a connection. */ readonly filename: string; /** * Make a human-readable name for a connection suitable for error messages. */ readonly nick: string; } /** * An input connection. */ export class Source extends Connection { /** * Make a new source from a file. * * Make a new source that is attached to the named file. For example: * ```js * const source = vips.Source.newFromFile('myfile.jpg'); * ``` * You can pass this source to (for example) [[Image.newFromSource]]. * @param filename The file. * @return A new source. */ static newFromFile(filename: string): Source; /** * Make a new source from a memory object. * * Make a new source that is attached to the memory object. For example: * ```js * const data = image.writeToBuffer('.jpg'); * const source = vips.Source.newFromMemory(data); * ``` * You can pass this source to (for example) [[Image.newFromSource]]. * @param memory The memory object. * @return A new source. */ static newFromMemory(memory: Blob): Source; } /** * A source that can be attached to callbacks to implement behavior. */ export class SourceCustom extends Source { /** * Attach a read handler. * @param ptr A pointer to an array of bytes where the read content is stored. * @param size The maximum number of bytes to be read. * @return The total number of bytes read into the buffer. */ onRead: (ptr: number, size: number) => number; /** * Attach a seek handler. * Seek handlers are optional. If you do not set one, your source will be * treated as unseekable and libvips will do extra caching. * @param offset A byte offset relative to the whence parameter. * @param size A value indicating the reference point used to obtain the new position. * @return The new position within the current source. */ onSeek: (offset: number, whence: number) => number; } /** * An output connection. */ export class Target extends Connection { /** * Make a new target to write to a file. * * Make a new target that will write to the named file. For example:: * ```js * const target = vips.Target.newToFile('myfile.jpg'); * ``` * You can pass this target to (for example) [[image.writeToTarget]]. * @param filename Write to this this file. * @return A new target. */ static newToFile(filename: string): Target; /** * Make a new target to write to an area of memory. * * Make a new target that will write to memory. For example: * ```js * const target = vips.Target.newToMemory(); * ``` * You can pass this target to (for example) [[image.writeToTarget]]. * * After writing to the target, fetch the bytes from the target object with [[getBlob]]. * @return A new target. */ static newToMemory(): Target; /** * Fetch the typed array of 8-bit unsigned integer values * from the target object. * * @return A typed array of 8-bit unsigned integer values. */ getBlob(): Uint8Array; } /** * A target that can be attached to callbacks to implement behavior. */ export class TargetCustom extends Target { /** * Attach a write handler. * @param ptr A pointer to an array of bytes which will be written to. * @param length The number of bytes to write. * @return The number of bytes that were written. */ onWrite: (ptr: number, size: number) => number; /** * Attach a finish handler. * This optional handler is called at the end of write. It should do any * cleaning up, if necessary. */ onFinish: () => void; } /** * A class to build various interpolators. * For e.g. nearest, bilinear, and some non-linear. */ export class Interpolate { /** * Look up an interpolator from a nickname and make one. * @param nickname Nickname for interpolator. * @return An interpolator. */ static newFromName(nickname: string): Interpolate; } /** * An image class. */ export class Image extends ImageAutoGen { /** * Image width in pixels. */ readonly width: number; /** * Image height in pixels. */ readonly height: number; /** * Number of bands in image. */ readonly bands: number; /** * Pixel format in image. */ readonly format: string; /** * Pixel coding. */ readonly coding: string; /** * Pixel interpretation. */ readonly interpretation: string; /** * Horizontal offset of origin. */ readonly xoffset: number; /** * Vertical offset of origin. */ readonly yoffset: number; /** * Horizontal resolution in pixels/mm. */ readonly xres: number; /** * Vertical resolution in pixels/mm. */ readonly yres: number; /** * Image filename. */ readonly filename: string; // constructors /** * Creates a new image which, when written to, will create a memory image. * @return A new image. */ static newMemory(): Image; /** * Make a new temporary image. * * Returns an image backed by a temporary file. When written to with * [[write]], a temporary file will be created on disc in the * specified format. When the image is closed, the file will be deleted * automatically. * * The file is created in the temporary directory. This is set with * the environment variable `TMPDIR`. If this is not set, vips will * default to `/tmp`. * * libvips uses `g_mkstemp()` to make the temporary filename. They * generally look something like `"vips-12-EJKJFGH.v"`. * @param format The format for the temp file, defaults to a vips * format file (`"%s.v"`). The `%s` is substituted by the file path. * @return A new image. */ static newTempFile(format?: string): Image; /** * Load an image from a file. * * This method can load images in any format supported by libvips. The * filename can include load options, for example: * ```js * const image = vips.Image.newFromFile('fred.jpg[shrink=2]'); * ``` * You can also supply options as keyword arguments, for example: * ```js * const image = vips.Image.newFromFile('fred.jpg', { * shrink: 2 * }); * ``` * The full set of options available depend upon the load operation that * will be executed. Try something like: * ```bash * $ vips jpegload * ``` * at the command-line to see a summary of the available options for the * JPEG loader. * * Loading is fast: only enough of the image is loaded to be able to fill * out the header. Pixels will only be decompressed when they are needed. * @param vipsFilename The file to load the image from, with optional appended arguments. * @param options Optional options that depend on the load operation. * @return A new image. */ static newFromFile(vipsFilename: string, options?: { /** * Force open via memory. */ memory?: boolean /** * Hint the expected access pattern for the image */ access?: Access | Enum /** * Fail on first error. */ fail?: boolean }): Image; /** * Wrap an image around a memory array. * * Wraps an Image around an area of memory containing a C-style array. For * example, if the `data` memory array contains four bytes with the * values 1, 2, 3, 4, you can make a one-band, 2x2 uchar image from * it like this: * ```js * const data = new Uint8Array([1, 2, 3, 4]); * const image = vips.Image.newFromMemory(data, 2, 2, 1, vips.BandFormat.uchar); * ``` * The data object will internally be copied from JavaScript to WASM. * * This method is useful for efficiently transferring images from WebGL into * libvips. * * See [[writeToMemory]] for the opposite operation. * Use [[copy]] to set other image attributes. * @param data A C-style JavaScript array. * @param width Image width in pixels. * @param height Image height in pixels. * @param bands Number of bands. * @param format Band format. * @return A new image. */ static newFromMemory(data: Blob, width: number, height: number, bands: number, format: BandFormat): Image; /** * Wrap an image around a pointer. * * This behaves exactly as [[newFromMemory]], but the image is * loaded from a pointer rather than from a JavaScript array. * @param ptr A memory address. * @param size Length of memory area. * @param width Image width in pixels. * @param height Image height in pixels. * @param bands Number of bands. * @param format Band format. * @return A new image. */ static newFromMemory(ptr: number, size: number, width: number, height: number, bands: number, format: BandFormat): Image; /** * Load a formatted image from memory. * * This behaves exactly as [[newFromFile]], but the image is * loaded from the memory object rather than from a file. The * memory object can be a string or buffer. * @param data The memory object to load the image from. * @param strOptions Load options as a string. * @param options Optional options that depend on the load operation. * @return A new image. */ static newFromBuffer(data: Blob, strOptions?: string, options?: { /** * Hint the expected access pattern for the image */ access?: Access | Enum /** * Fail on first error. */ fail?: boolean }): Image; /** * Load a formatted image from a source. * * This behaves exactly as [[newFromFile]], but the image is * loaded from a source rather than from a file. * @param source The source to load the image from. * @param strOptions Load options as a string. * @param options Optional options that depend on the load operation. * @return A new image. */ static newFromSource(source: Source, strOptions?: string, options?: { /** * Hint the expected access pattern for the image */ access?: Access | Enum /** * Fail on first error. */ fail?: boolean }): Image; /** * Create an image from a 1D array. * * A new one-band image with [[BandFormat.double]] pixels is * created from the array. These image are useful with the libvips * convolution operator [[conv]]. * @param width Image width. * @param height Image height. * @param array Create the image from these values. * @return A new image. */ static newMatrix(width: number, height: number, array?: ArrayConstant): Image; /** * Create an image from a 2D array. * * A new one-band image with [[BandFormat.double]] pixels is * created from the array. These image are useful with the libvips * convolution operator [[conv]]. * @param array Create the image from these values. * @param scale Default to 1.0. What to divide each pixel by after * convolution. Useful for integer convolution masks. * @param offset Default to 0.0. What to subtract from each pixel * after convolution. Useful for integer convolution masks. * @return A new image. */ static newFromArray(array: ArrayConstant, scale?: number, offset?: number): Image; /** * Make a new image from an existing one. * * A new image is created which has the same size, format, interpretation * and resolution as itself, but with every pixel set to `value`. * @param value The value for the pixels. Use a single number to make a * one-band image; use an array constant to make a many-band image. * @return A new image. */ newFromImage(value: ArrayConstant): Image; /** * Copy an image to memory. * * A large area of memory is allocated, the image is rendered to that * memory area, and a new image is returned which wraps that large memory * area. * @return A new image. */ copyMemory(): Image; // writers /** * Write an image to another image. * * This function writes itself to another image. Use something like * [[newTempFile]] to make an image that can be written to. * @param other The image to write to. * @return A new image. */ write(other: Image): Image; /** * Write an image to a file. * * This method can save images in any format supported by libvips. The format * is selected from the filename suffix. The filename can include embedded * save options, see [[newFromFile]]. * * For example: * ```js * image.writeToFile('fred.jpg[Q=95]'); * ``` * You can also supply options as keyword arguments, for example: * ```js * image.writeToFile('.fred.jpg', { * Q: 95 * }); * ``` * The full set of options available depend upon the save operation that * will be executed. Try something like: * ```bash * $ vips jpegsave * ``` * at the command-line to see a summary of the available options for the * JPEG saver. * @param vipsFilename The file to save the image to, with optional appended arguments. * @param options Optional options that depend on the save operation. */ writeToFile(vipsFilename: string, options?: {}): void; /** * Write an image to a typed array of 8-bit unsigned integer values. * * This method can save images in any format supported by libvips. The format * is selected from the suffix in the format string. This can include * embedded save options, see [[newFromFile]]. * * For example: * ```js * const data = image.writeToBuffer('.jpg[Q=95]'); * ``` * You can also supply options as keyword arguments, for example: * ```js * const data = image.writeToBuffer('.jpg', { * Q: 85 * }); * ``` * The full set of options available depend upon the load operation that * will be executed. Try something like: * ```bash * $ vips jpegsave_buffer * ``` * at the command-line to see a summary of the available options for the * JPEG saver. * @param formatString The suffix, plus any string-form arguments. * @param options Optional options that depend on the save operation. * @return A typed array of 8-bit unsigned integer values. */ writeToBuffer(formatString: string, options?: {}): Uint8Array; /** * Write an image to a target. * * This behaves exactly as [[writeToFile]], but the image is * written to a target rather than a file. * @param target Write to this target. * @param formatString The suffix, plus any string-form arguments. * @param options Optional options that depend on the save operation. */ writeToTarget(target: Target, formatString: string, options?: {}): void; /** * Write the image to a large memory array. * * A large area of memory is allocated, the image is rendered to that * memory array, and the array is returned as a typed array. * * For example, if you have a 2x2 uchar image containing the bytes 1, 2, * 3, 4, read left-to-right, top-to-bottom, then: * ```js * const array = Uint8Array.of(1, 2, 3, 4); * const im = vips.Image.newFromMemory(array, 2, 2, 1, 'uchar'); * const buf = im.writeToMemory(); * ``` * will return a four byte typed array containing the values 1, 2, 3, 4. * @return A typed array of 8-bit unsigned integer values. */ writeToMemory(): Uint8Array; // get/set metadata /** * Set an integer on an image as metadata. * @param name The name of the piece of metadata to set the value of. * @param value The metadata value. */ setInt(name: string, value: number): void; /** * Set an integer array on an image as metadata. * @param name The name of the piece of metadata to set the value of. * @param value The metadata value. */ setArrayInt(name: string, value: ArrayConstant): void; /** * Set an double array on an image as metadata. * @param name The name of the piece of metadata to set the value of. * @param value The metadata value. */ setArrayDouble(name: string, value: ArrayConstant): void; /** * Set an double on an image as metadata. * @param name The name of the piece of metadata to set the value of. * @param value The metadata value. */ setDouble(name: string, value: number): void; /** * Set an string on an image as metadata. * @param name The name of the piece of metadata to set the value of. * @param value The metadata value. */ setString(name: string, value: string): void; /** * Set an blob on an image as metadata. * The value will internally be copied from JavaScript to WASM. * @param name The name of the piece of metadata to set the value of. * @param value The metadata value. */ setBlob(name: string, value: Blob): void; /** * Set an blob pointer on an image as metadata. * @param name The name of the piece of metadata to set the value of. * @param ptr The metadata value as memory address. * @param size Length of blob. */ setBlob(name: string, ptr: number, size: number): void; /** * Get the GType of an item of metadata. * Fetch the GType of a piece of metadata, or 0 if the named item does not exist. * @param name The name of the piece of metadata to get the type of. * @return The GType, or `0` if not found. */ getTypeof(name: string): number; /** * Get an integer from an image. * @param name The name of the piece of metadata to get. * @return The metadata item as an integer. */ getInt(name: string): number; /** * Get an integer array from an image. * @param name The name of the piece of metadata to get. * @return The metadata item as an integer array. */ getArrayInt(name: string): number[]; /** * Get an double array from an image. * @param name The name of the piece of metadata to get. * @return The metadata item as an double array. */ getArrayDouble(name: string): number[]; /** * Get an double from an image. * @param name The name of the piece of metadata to get. * @return The metadata item as an double. */ getDouble(name: string): number; /** * Get an string from an image. * @param name The name of the piece of metadata to get. * @return The metadata item as an string. */ getString(name: string): string; /** * Get an blob from an image. * @param name The name of the piece of metadata to get. * @return The metadata item as an typed array of 8-bit unsigned integer values. */ getBlob(name: string): Uint8Array; /** * Get a list of all the metadata fields on an image. * @return All metadata fields as string vector. */ getFields(): Vector<string>; /** * Remove an item of metadata. * @param name The name of the piece of metadata to remove. * @return `true` if successfully removed. */ remove(name: string): string; // handwritten functions /** * Does this image have an alpha channel? * @return `true` if this image has an alpha channel. */ hasAlpha(): boolean; /** * Sets the `delete_on_close` flag for the image. * If this flag is set, when image is finalized, the filename held in * [[image.filename]] at the time of this call is deleted. * This function is clearly extremely dangerous, use with great caution. */ setDeleteOnClose(flag: boolean): void; /** * Search an image for non-edge areas. * @param options Optional options. * @return The bounding box of the non-background area. */ findTrim(options?: { /** * Object threshold. */ threshold?: number /** * Color for background pixels. */ background?: ArrayConstant }): { /** * Output left edge. */ left: number /** * Output top edge. */ top: number /** * Output width. */ width: number /** * Output width. */ height: number }; /** * Find image profiles. * @return First non-zero pixel in column/row. */ profile(): { /** * Distances from top edge. */ columns: Image /** * Distances from left edge. */ rows: Image }; /** * Find image projections. * @return Sums of columns/rows. */ project(): { /** * Sums of columns. */ columns: Image /** * Sums of rows. */ rows: Image }; /** * Split an n-band image into n separate images. * @return Vector of output images. */ bandsplit(): Vector<Image>; /** * Append a set of images or constants bandwise * @param _in Array of input images. * @return Output image. */ bandjoin(_in: ArrayImage | ArrayConstant): Image; /** * Band-wise rank filter a set of images or constants. * @param _in Array of input images. * @param options Optional options. * @return Output image. */ bandrank(_in: ArrayImage | ArrayConstant, options?: { /** * Select this band element from sorted list. */ index?: number }): Image; /** * Composite a set of images with a set of blend modes. * @param _in Images to composite. * @param mode Blend modes to use. * @param options Optional options. * @return Blended image. */ static composite(_in: ArrayImage, mode: Array<Enum>, options?: { /** * Array of x coordinates to join at. */ x?: ArrayConstant /** * Array of y coordinates to join at. */ y?: ArrayConstant /** * Composite images in this colour space. */ compositing_space?: Interpretation | Enum /** * Images have premultiplied alpha. */ premultiplied?: boolean }): Image; /** * Composite a set of images with a set of blend modes. * @param overlay Images to composite. * @param mode Blend modes to use. * @param options Optional options. * @return Blended image. */ composite(overlay: ArrayImage, mode: Array<Enum>, options?: { /** * Array of x coordinates to join at. */ x?: ArrayConstant /** * Array of y coordinates to join at. */ y?: ArrayConstant /** * Composite images in this colour space. */ compositing_space?: Interpretation | Enum /** * Images have premultiplied alpha. */ premultiplied?: boolean }): Image; /** * Return the coordinates of the image maximum. * @return Array of output values. */ maxPos(): number[]; /** * Return the coordinates of the image minimum. * @return Array of output values. */ minPos(): number[]; /** * Flip an image horizontally. * @return Output image. */ flipHor(): Image; /** * Flip an image vertically. * @return Output image. */ flipVer(): Image; /** * Rotate an image 90 degrees clockwise. * @return Output image. */ rot90(): Image; /** * Rotate an image 180 degrees. * @return Output image. */ rot180(): Image; /** * Rotate an image 270 degrees clockwise. * @return Output image. */ rot270(): Image; /** * size x size median filter. * @param size The size of the median filter, defaults to 3. * @return Output image. */ median(size?: number): Image; /** * Return the largest integral value not greater than the argument. * @return Output image. */ floor(): Image; /** * Return the smallest integral value not less than the argument. * @return Output image. */ ceil(): Image; /** * Return the nearest integral value. * @return Output image. */ rint(): Image; /** * AND image bands together. * @return Output image. */ bandand(): Image; /** * OR image bands together. * @return Output image. */ bandor(): Image; /** * EOR image bands together. * @return Output image. */ bandeor(): Image; /** * Return the real part of a complex image. * @return Output image. */ real(): Image; /** * Return the imaginary part of a complex image. * @return Output image. */ imag(): Image; /** * Return an image converted to polar coordinates. * @return Output image. */ polar(): Image; /** * Return an image converted to rectangular coordinates. * @return Output image. */ rect(): Image; /** * Return the complex conjugate of an image. * @return Output image. */ conj(): Image; /** * Return the sine of an image in degrees. * @return Output image. */ sin(): Image; /** * Return the cosine of an image in degrees. * @return Output image. */ cos(): Image; /** * Return the tangent of an image in degrees. * @return Output image. */ tan(): Image; /** * Return the inverse sine of an image in degrees. * @return Output image. */ asin(): Image; /** * Return the inverse cosine of an image in degrees. * @return Output image. */ acos(): Image; /** * Return the inverse tangent of an image in degrees. * @return Output image. */ atan(): Image; /** * Return the natural log of an image. * @return Output image. */ log(): Image; /** * Return the log base 10 of an image. * @return Output image. */ log10(): Image; /** * Return e ** pixel. * @return Output image. */ exp(): Image; /** * Return 10 ** pixel. * @return Output image. */ exp10(): Image; /** * Erode with a structuring element. * @param mask Input matrix image. * @return Output image. */ erode(mask: Image | ArrayConstant): Image; /** * Dilate with a structuring element. * @param mask Input matrix image. * @return Output image. */ dilate(mask: Image | ArrayConstant): Image; /** * Raise to power of an image or constant. * @param right To the power of this. * @return Output image. */ pow(right: Image | ArrayConstant): Image; /** * Raise to power of an image, but with the arguments reversed. * @param right To the power of this. * @return Output image. */ wop(right: Image | ArrayConstant): Image; /** * Performs a bitwise left shift operation (<<). * @param right Right operand. * @return Output image. */ lshift(right: Image | ArrayConstant): Image; /** * Performs a bitwise right shift operation (>>). * @param right Right operand. * @return Output image. */ rshift(right: Image | ArrayConstant): Image; /** * Performs a bitwise AND operation (&). * @param right Right operand. * @return Output image. */ and(right: Image | ArrayConstant): Image; /** * Performs a bitwise OR operation (|) . * @param right Right operand. * @return Output image. */ or(right: Image | ArrayConstant): Image; /** * Performs a bitwise exclusive-OR operation (^). * @param right Right operand. * @return Output image. */ eor(right: Image | ArrayConstant): Image; /** * Performs a relational greater than operation (>). * @param right Right operand. * @return Output image. */ more(right: Image | ArrayConstant): Image; /** * Performs a relational greater than or equal operation (>=). * @param right Right operand. * @return Output image. */ moreEq(right: Image | ArrayConstant): Image; /** * Performs a relational less than operation (<). * @param right Right operand. * @return Output image. */ less(right: Image | ArrayConstant): Image; /** * Performs a relational less than or equal operation (<=). * @param right Right operand. * @return Output image. */ lessEq(right: Image | ArrayConstant): Image; /** * Performs a relational equality operation (==). * @param right Right operand. * @return Output image. */ equal(right: Image | ArrayConstant): Image; /** * Performs a relational inequality operation (!=). * @param right Right operand. * @return Output image. */ notEq(right: Image | ArrayConstant): Image; }
the_stack
import { bisectLeft, extent, histogram as d3Histogram, ticks } from 'd3-array'; import Decimal from 'decimal.js'; import { isMatch, isValid, parse, parseISO } from 'date-fns'; import { get } from 'lodash'; export const ONE_SECOND = 1000; export const ONE_MINUTE = ONE_SECOND * 60; export const ONE_HOUR = ONE_MINUTE * 60; export const ONE_DAY = ONE_HOUR * 24; export const ONE_YEAR = ONE_DAY * 365; export type Millisecond = number; export const StepMap = [ { max: 0.001, step: 0.00001 }, { max: 0.01, step: 0.0001 }, { max: 0.1, step: 0.001 }, { max: 1, step: 0.01 }, { max: 10, step: 0.1 }, { max: 100, step: 1 }, { max: 1000, step: 10 }, { max: 10000, step: 100 }, { max: 100000, step: 1000 }, { max: Number.POSITIVE_INFINITY, step: 10000 }, ]; /** * whether null or undefined * * @param {any} input * @returns {boolean} boolean */ export const notNullorUndefined = (d: any): boolean => { return d !== undefined && d !== null; }; /** * Get unique values of an array * * @param {any[]} values * @returns {any[]} unique values */ export const unique = (values: any[]): any[] => { const results: any[] = []; values.forEach((v) => { if (!results.includes(v) && notNullorUndefined(v)) { results.push(v); } }); return results; }; export type Accessor = { (data: any[]): any; }; export type Sort = { (a: any, b: any): any; }; /** * Return quantile domain for an array of data * * @param {any[]} data * @param {Accessor} valueAccessor function to access data * @param {Sort} sortFunc function to sort * @returns {number[]} domain of data */ export const getQuantileDomain = ( data: any[], valueAccessor?: Accessor, sortFunc?: Sort, ): number[] => { const values = typeof valueAccessor === 'function' ? data.map(valueAccessor) : data; return values.filter(notNullorUndefined).sort(sortFunc); }; /** * Return ordinal domain for an array of data i.e. unique values which are non null or undefined * * @param {any[]} data * @param {Accessor} valueAccessor function to access data * @returns {string[]} domain of data */ export const getOrdinalDomain = ( data: any[], valueAccessor?: Accessor, ): string[] => { const values = typeof valueAccessor === 'function' ? data.map(valueAccessor) : data; return unique(values).filter(notNullorUndefined).sort(); }; /** * Return linear domain for an array of data * * @param {any[]} data * @param {Accessor} [valueAccessor] function to access data * @returns {[number, number]} domain of data */ export const getLinearDomain = ( data: any[], valueAccessor?: Accessor, ): [number, number] => { const range = typeof valueAccessor === 'function' ? extent(data, valueAccessor) : extent(data); // @ts-ignore return range.map((d, i) => (d === undefined ? i : Number(d))); }; /** * Return linear domain for an array of data. A log scale domain cannot contain 0 * * @param {any[]} data * @param {Accessor} [valueAccessor] function to access data * @returns {[number, number]} domain of data */ export const getLogDomain = ( data: any[], valueAccessor?: Accessor, ): [number, number] => { const [d0, d1] = getLinearDomain(data, valueAccessor); return [d0 === 0 ? 1e-5 : d0, d1]; }; export type HistogramBin = { x0: number | undefined; x1: number | undefined; count: number; }; export type TimeRangeFieldDomain = { domain: [number, number]; step: number; histogram: HistogramBin[]; enlargedHistogram: HistogramBin[]; mappedValue: (Millisecond | null)[]; }; /** * Helper function to parse string date and convert to unix millisecond. * * @param value - date string or timestamp * @param {('DATETIME' | 'DATE' | 'TIME')} type * @param format - datetime format to be parsed * @return {*} */ export const unixTimeConverter = ( value: string | number, type: 'DATETIME' | 'DATE' | 'TIME', format: string, ) => { if (type === 'TIME') { return parseISO( `${new Date().toISOString().slice(0, 10)} ${value}`, ).getTime(); } // DATETIME | DATE const unixTimestampFormat = 'x'; const msUnixTimestampFormat = 'X'; if (format === msUnixTimestampFormat || format === unixTimestampFormat) { return value as number; } const dateString = value as string; const parsedDate = parseISO(dateString).getTime(); const isValidDate = isValid(parsedDate); if (isValidDate) return parsedDate; // Prevent use capital D and Y to format dates // https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md const dateFormat = format.replace(/D/gi, 'd').replace(/Y/gi, 'y'); const isDateFormatMatch: boolean = isMatch(dateString, dateFormat); if (isDateFormatMatch === false) { return null; } return parse(dateString, dateFormat, new Date()).getTime(); }; export const removeInvalidData = (data: any[]) => { return data.filter((data: any) => { const invalidValue = ['', null, undefined]; const isInvalidData = invalidValue.includes(data); return isInvalidData === false; }); }; /** * Calculate timestamp domain and suitable step * * @param {any[]} data * @param {Accessor} [valueAccessor] function to access data * @param {string} type * @param {string} format * @returns {TimeRangeFieldDomain} Object with domain, step, mappedValue, histogram and enlargedHistogram */ export const getFieldDomain = ( data: any[], valueAccessor?: Accessor, type?: string, format?: string, ): TimeRangeFieldDomain | false => { // to avoid converting string format time to epoch // every time we compare we store a value mapped to int in filter domain const accessedValues = data.map(valueAccessor); let mappedValue: any = []; if (Array.isArray(accessedValues[0])) { // Grouped edges for (const d of accessedValues) { const cleanedData = removeInvalidData(d); mappedValue = mappedValue.concat(cleanedData); } } else { mappedValue = removeInvalidData(accessedValues); } // mapped value is undefined and empty, do not proceed. if (mappedValue.length === 0) return false; if (type === 'DATETIME' || type === 'DATE' || type === 'TIME') { mappedValue = mappedValue.map((dt: string) => unixTimeConverter(dt, type, format), ); } let domain = getLinearDomain(mappedValue); const [minRange, maxRange] = domain; let step = 0.01; const diff = maxRange - minRange; const entry = StepMap.find((f) => f.max >= diff); if (entry) { step = entry.step; } // if minRange and maxRange are equals, modify the boundaries if (minRange === maxRange) { if (type === 'INT' || type === 'FLOAT' || type === 'NUMBER') { domain = [minRange - 1, maxRange + 1]; } if (type === 'DATETIME' || type === 'DATE' || type === 'TIME') { if (format !== 'X') { const HOURS_IN_MILLISECONDS: number = 60 * 60 * 1000; const newMinRange: number = minRange - HOURS_IN_MILLISECONDS; const newMaxRange: number = maxRange + HOURS_IN_MILLISECONDS; step = newMaxRange - newMinRange; domain = [newMinRange, newMaxRange]; } if (format === 'X') { const HOURS_IN_MILLISECONDS: number = 60 * 60 * 1000 * 1000; const newMinRange: number = minRange - HOURS_IN_MILLISECONDS; const newMaxRange: number = maxRange + HOURS_IN_MILLISECONDS; step = newMaxRange - newMinRange; domain = [newMinRange, newMaxRange]; } } } // eslint-disable-next-line @typescript-eslint/no-use-before-define const { histogram, enlargedHistogram } = getHistogram(domain, mappedValue); return { domain, step, mappedValue, histogram, enlargedHistogram }; }; /** * Construct histogram bins based on given domain, values and bins * * @param {[number, number]} domain * @param {((Millisecond | null | number)[])} values * @param {number} [bins=30] * @returns {HistogramBin[]} */ export const histogramConstruct = ( domain: [number, number], values: (Millisecond | null | number)[], bins = 30, ): HistogramBin[] => { return d3Histogram() .thresholds(ticks(domain[0], domain[1], bins)) .domain(domain)(values) .map((bin) => ({ count: bin.length, x0: bin.x0, x1: bin.x1, })); }; /** * Calculate histogram from domain and array of values * * @param {[number, number]} domain * @param {((Millisecond | null | number)[])} values * @returns {{histogram: HistogramBin[]; enlargedHistogram: HistogramBin[]}} */ export const getHistogram = ( domain: [number, number], values: (Millisecond | null | number)[], ): { histogram: HistogramBin[]; enlargedHistogram: HistogramBin[] } => { const histogram = histogramConstruct(domain, values, 30); const enlargedHistogram = histogramConstruct(domain, values, 100); return { histogram, enlargedHistogram }; }; /** * Returns a number whose value is limited to the given range * * @param {number} value * @param {number} min * @param {number} max * @return {*} */ export const clamp = (value: number, min: number, max: number) => { return Math.min(Math.max(value, min), max); }; /** * round number with exact number of decimals * return as a string * * @param {number} num * @param {number} decimals * * @return {string} */ export function preciseRound(num: number, decimals: number): string { const t = 10 ** decimals; return ( Math.round( num * t + (decimals > 0 ? 1 : 0) * (Math.sign(num) * (10 / 100 ** decimals)), ) / t ).toFixed(decimals); } /** * get number of decimals to round to for slider from step * @param {number} step * @returns {number} - number of decimal */ export function getRoundingDecimalFromStep(step: number) { const splitZero = step.toString().split('.'); if (splitZero.length === 1) { return 0; } return splitZero[1].length; } /** * Use in slider, given a number and an array of numbers, return the nears number from the array * * @param value * @param marks */ export function snapToMarks(value: number, marks: number[]) { // always use bin x0 const i = bisectLeft(marks, value); if (i === 0) { return marks[i]; } if (i === marks.length) { return marks[i - 1]; } const idx = marks[i] - value < value - marks[i - 1] ? i : i - 1; return marks[idx]; } /** * If marks is provided, snap to marks, if not normalize to step * @type {typeof import('./data-utils').normalizeSliderValue} * @param val * @param minValue * @param step * @param marks */ export function normalizeSliderValue( val: number, minValue: number, step: number, marks?: number[], ) { if (marks && marks.length) { return snapToMarks(val, marks); } return roundValToStep(minValue, step, val); } /** * round the value to step for the slider * @param minValue * @param step * @param val * @returns - rounded number */ export function roundValToStep(minValue: number, step: number, val: number) { if (!Number.isFinite(step) || !Number.isFinite(minValue)) { return val; } const decimal = getRoundingDecimalFromStep(step); const steps = Math.floor((val - minValue) / step); let remain = val - (steps * step + minValue); // has to round because javascript turns 0.1 into 0.9999999999999987 remain = Number(preciseRound(remain, 8)); let closest; if (remain === 0) { closest = val; } else if (remain < step / 2) { closest = steps * step + minValue; } else { closest = (steps + 1) * step + minValue; } // precise round return a string rounded to the defined decimal const rounded = preciseRound(closest, decimal); return Number(rounded); } /** * Obtain the decimal precision of given numeric values * * @param float - provided interger * @return {number} */ export const getDecimalPrecisionCount = (float: number): number => { const decimal = new Decimal(float); return decimal.e; }; /** * Eliminate alphabet in string and remain integer * - Specific radix in 10 as we want to convert string begins with other value to number. * * @reference * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#description * * @param {string} value * @return {number} */ export const extractIntegerFromString = (value: string): number => { return parseInt(value.replace(/\D/g, ''), 10); }; /** * Remove empty value from an object * * @param {Record<string, any>}object * * @return {void} */ export const removeEmptyValueInObject = (object: Record<string, any>): void => { Object.entries(object).forEach((property) => { const [key, value] = property; const isEmptyArray: boolean = Array.isArray(value) && value.length === 0; const isObj: boolean = typeof value === 'object' && value !== null; const isGraphinPosition: boolean = key === 'x' || key === 'y'; if (isEmptyArray || isObj || isGraphinPosition) { // eslint-disable-next-line no-param-reassign delete object[key]; } }); }; /** * Obtain the collection of values with given fields. * * 1. Eliminates undefined values * 2. Convert edge list to field collection * * Attempt to perform Step 1. and 2. with single loop * for performance optimization. * * @param collections * @param field * @return {any[]} */ export const mapCollectionFields = ( collections: any[], field: string, ): any[] => { const fieldsValues: any[] = collections.reduce( (acc: any[], collection: any) => { const property = get(collection, field); if (property !== undefined) { acc.push(property); } return acc; }, [], ); return fieldsValues; };
the_stack