text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
/// <reference types="node" />
import * as mqtt from "mqtt";
import * as WebSocket from "ws";
import { EventEmitter } from 'events';
export interface DeviceOptions extends mqtt.IClientOptions {
/** the AWS IoT region you will operate in (default "us-east-1") */
region?: string | undefined;
/** the client ID you will use to connect to AWS IoT */
clientId?: string | undefined;
/**
* path of the client certificate file path of the private key file
* associated with the client certificate
*/
certPath?: string | undefined;
/** path of the private key file associated with the client certificate */
keyPath?: string | undefined;
/** path of your CA certificate file */
caPath?: string | undefined;
/**
* same as certPath, but can also accept a buffer containing client
* certificate data
*/
clientCert?: string | Buffer | undefined;
/**
* same as keyPath, but can also accept a buffer containing private key
* data
*/
privateKey?: string | Buffer | undefined;
/**
* same as caPath, but can also accept a buffer containing CA certificate
* data
*/
caCert?: string | Buffer | undefined;
/**
* set to "true" to automatically re-subscribe to topics after
* reconnection (default "true")
*/
autoResubscribe?: boolean | undefined;
/** set to "true" to automatically queue published messages while
* offline (default "true")
*/
offlineQueueing?: boolean | undefined;
/**
* enforce a maximum size for the offline message queue
* (default 0, e.g. no maximum)
*/
offlineQueueMaxSize?: number | undefined;
/**
* set to "oldest" or "newest" to define drop behavior on a full
* queue when offlineQueueMaxSize > 0
*/
offlineQueueDropBehavior?: "oldest" | "newest" | undefined;
/**
* the minimum time in milliseconds between publishes when draining
* after reconnection (default 250)
*/
drainTimeMs?: number | undefined;
/** the base reconnection time in milliseconds (default 1000) */
baseReconnectTimeMs?: number | undefined;
/** the maximum reconnection time in milliseconds (default 128000) */
maximumReconnectTimeMs?: number | undefined;
/**
* the minimum time in milliseconds that a connection must be maintained
* in order to be considered stable (default 20000)
*/
minimumConnectionTimeMs?: number | undefined;
/**
* the connection type, either "mqtts" (default) or "wss" (WebSocket/TLS).
* Note that when set to "wss", values must be provided for the
* Access Key ID and Secret Key in either the following options or in
* environment variables as specified in WebSocket Configuration[1].
*
* 1. https://github.com/aws/aws-iot-device-sdk-js#websockets
*/
protocol?: "mqtts" | "wss" | undefined;
/**
* if protocol is set to "wss", you can use this parameter to pass
* additional options to the underlying WebSocket object;
* these options are documented here.
*/
websocketOptions?: WebSocket.ClientOptions | undefined;
/**
* used to specify the Access Key ID when protocol is set to "wss".
* Overrides the environment variable AWS_ACCESS_KEY_ID if set.
*/
accessKeyId?: string | undefined;
/**
* used to specify the Secret Key when protocol is set to "wss".
* Overrides the environment variable AWS_SECRET_ACCESS_KEY if set.
*/
secretKey?: string | undefined;
/**
* (required when authenticating via Cognito, optional otherwise) used
* to specify the Session Token when protocol is set to "wss". Overrides
* the environment variable AWS_SESSION_TOKEN if set.
*/
sessionToken?: string | undefined;
/**
* optional hostname, if not specified a hostname will be constructed
* from the region option
*/
// NB Not documented but present in examples, see
// https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b468d/device/index.js#L376
// https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b468d/device/index.js#L149
host?: string | undefined;
/** optional port, will be appended to hostname if present and not 443 */
// NB Not documented but present in examples, see
// https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b468d/device/index.js#L154
port?: number | undefined;
/** enable console logging, default false */
// NB Not documented but present in examples, see
// https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b468d/device/index.js#L436
debug?: boolean | undefined;
}
export class device extends EventEmitter {
/**
* Returns a wrapper for the mqtt.Client() class, configured for a TLS
* connection with the AWS IoT platform and with arguments as specified
* in options.
*/
constructor(options?: DeviceOptions);
/**
* Update the credentials set used to authenticate via WebSocket/SigV4.
*
* This method is designed to be invoked during the callback of the
* getCredentialsForIdentity method in the AWS SDK for JavaScript.
*/
updateWebSocketCredentials(accessKeyId: string, secretKey: string, sessionToken: string, expiration: Date): void;
on(event: "connect" | "close" | "reconnect" | "offline", listener: () => void): this;
// Error | string comes from:
// https://github.com/aws/aws-iot-device-sdk-js/blob/97b0b46/device/index.js#L744
// Remove when https://github.com/aws/aws-iot-device-sdk-js/issues/95 is fixed
on(event: "error", listener: (error: Error | string) => void): this;
/** Emitted when a message is received on a topic not related to any Thing Shadows */
on(event: "message", listener: (topic: string, payload: any) => void): this;
// The following publish, subscribe, unsubscribe and end Definitions
// are derived from the mqtt definition as they are re-surfaced through
// thingShadow
// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/e7772769fab8c206449ce9673cac417370330aa9/mqtt/mqtt.d.ts#L199
/**
* Publish a message to a topic
*
* @param topic to publish to
* @param message to publish
* @param publish options
* @param called when publish succeeds or fails
*/
publish(topic: string, message: Buffer | string, options?: mqtt.IClientPublishOptions, callback?: (error?: Error) => void): mqtt.Client;
/**
* Subscribe to a topic or topics
* @param topic to subscribe to or an Array of topics to subscribe to. It can also be an object.
* @param the options to subscribe with
* @param callback fired on suback
*/
subscribe(topic: string | string[], options?: mqtt.IClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;
/**
* Unsubscribe from a topic or topics
*
* @param topic is a String topic or an array of topics to unsubscribe from
* @param callback fired on unsuback
*/
unsubscribe(topic: string | string[], callback?: mqtt.PacketCallback): mqtt.Client;
/**
* end - close connection
*
* @param force passing it to true will close the client right away, without waiting for the in-flight messages to be acked.
* This parameter is optional.
* @param callback
*/
end(force?: boolean, callback?: Function): mqtt.Client;
}
export interface ThingShadowOptions extends DeviceOptions {
/** the timeout for thing operations (default 10 seconds) */
operationTimeout?: number | undefined;
}
export interface RegisterOptions {
/**
* set to true to not subscribe to the delta sub-topic for this
* Thing Shadow; used in cases where the application is not interested in
* changes (e.g. update only.) (default false)
*/
ignoreDeltas?: boolean | undefined;
/**
* set to false to unsubscribe from all operation sub-topics while not
* performing an operation (default true)
*/
persistentSubscribe?: boolean | undefined;
/**
* set to false to allow receiving messages with old version
* numbers (default true)
*/
discardStale?: boolean | undefined;
/** set to true to send version numbers with shadow updates (default true) */
enableVersioning?: boolean | undefined;
}
/**
* The thingShadow class wraps an instance of the device class with
* additional functionality to operate on Thing Shadows via the AWS IoT API.
*/
export class thingShadow extends EventEmitter {
constructor(options?: ThingShadowOptions);
/**
* Register interest in the Thing Shadow named thingName.
*
* The thingShadow class will subscribe to any applicable topics, and will
* fire events for the Thing Shadow until awsIot.thingShadow#unregister()
* is called with thingName
*
* If the callback parameter is provided, it will be invoked after
* registration is complete (i.e., when subscription ACKs have been received
* for all shadow topics). Applications should wait until shadow
* registration is complete before performing update/get/delete operations.
*/
register(thingName: string, options?: RegisterOptions, callback?: (error: Error, failedTopics: mqtt.ISubscriptionGrant[]) => void): void
/**
* Unregister interest in the Thing Shadow named thingName.
*
* The thingShadow class will unsubscribe from all applicable topics
* and no more events will be fired for thingName.
*/
unregister(thingName: string): void
/**
* Update the Thing Shadow named thingName with the state specified in the
* JavaScript object stateObject. thingName must have been previously
* registered using awsIot.thingShadow#register().
*
* The thingShadow class will subscribe to all applicable topics and
* publish stateObject on the update sub-topic.
*
* This function returns a clientToken, which is a unique value associated
* with the update operation. When a "status" or "timeout" event is emitted,
* the clientToken will be supplied as one of the parameters, allowing the
* application to keep track of the status of each operation. The caller may
* create their own clientToken value; if stateObject contains a clientToken
* property, that will be used rather than the internally generated value.
* Note that it should be of atomic type (i.e. numeric or string).
* This function returns "null" if an operation is already in progress.
*/
update(thingName: string, stateObject: any): string | null;
/**
* Get the current state of the Thing Shadow named thingName, which must
* have been previously registered using awsIot.thingShadow#register().
* The thingShadow class will subscribe to all applicable topics and
* publish on the get sub-topic.
*
* This function returns a clientToken, which is a unique value
* associated with the get operation. When a "status or "timeout" event
* is emitted, the clientToken will be supplied as one of the parameters,
* allowing the application to keep track of the status of each operation.
* The caller may supply their own clientToken value (optional); if
* supplied, the value of clientToken will be used rather than the
* internally generated value. Note that this value should be of atomic
* type (i.e. numeric or string). This function returns "null" if an
* operation is already in progress.
*/
get(thingName: string, clientToken?: string): string | null;
/**
* Delete the Thing Shadow named thingName, which must have been previously
* registered using awsIot.thingShadow#register(). The thingShadow class
* will subscribe to all applicable topics and publish on the delete sub-topic.
*
* This function returns a clientToken, which is a unique value associated
* with the delete operation. When a "status" or "timeout" event is
* emitted, the clientToken will be supplied as one of the parameters,
* allowing the application to keep track of the status of each operation.
* The caller may supply their own clientToken value (optional); if
* supplied, the value of clientToken will be used rather than the
* internally generated value. Note that this value should be of atomic
* type (i.e. numeric or string). This function returns "null" if an
* operation is already in progress.
*/
delete(thingName: string, clientToken?: string): string | null;
// The following publish, subscribe, unsubscribe and end Definitions
// are copied from the mqtt definition as they are re-surfaced through
// thingShadow
// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/e7772769fab8c206449ce9673cac417370330aa9/mqtt/mqtt.d.ts#L199
/**
* Publish a message to a topic
*
* @param topic
* @param message
* @param options
* @param callback
*/
publish(topic: string, message: Buffer | string, options?: mqtt.IClientPublishOptions, callback?: Function): mqtt.Client;
/**
* Subscribe to a topic or topics
* @param topic to subscribe to or an Array of topics to subscribe to. It can also be an object.
* @param the options to subscribe with
* @param callback fired on suback
*/
subscribe(topic: string | string[], options?: { qos: 0 | 1 }, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;
/**
* Unsubscribe from a topic or topics
*
* @param topic is a String topic or an array of topics to unsubscribe from
* @param options
* @param callback fired on unsuback
*/
unsubscribe(topic: string | string[], options?: mqtt.IClientSubscribeOptions, callback?: mqtt.ClientSubscribeCallback): mqtt.Client;
/**
* end - close connection
*
* @param force passing it to true will close the client right away, without waiting for the in-flight messages to be acked.
* This parameter is optional.
* @param callback
*/
end(force?: boolean, callback?: Function): mqtt.Client;
on(event: "connect" | "close" | "reconnect" | "offline", listener: () => void): this;
on(event: "error", listener: (error: Error) => void): this;
/** Emitted when a message is received on a topic not related to any Thing Shadows */
on(event: "message", listener: (topic: string, payload: any) => void): this;
/**
* Emitted when an operation update|get|delete completes.
*
* thingName - name of the Thing Shadow for which the operation has completed
* stat - status of the operation accepted|rejected
* clientToken - the operation"s clientToken
* stateObject - the stateObject returned for the operation
*
* Applications can use clientToken values to correlate status events with
* the operations that they are associated with by saving the clientTokens
* returned from each operation.
*/
on(event: "status", listener: (thingName: string, operationStatus: "accepted" | "rejected", clientToken: string, stateObject: any) => void): this;
/** Emitted when an operation update|get|delete has timed out. */
on(event: "timeout", listener: (thingName: string, clientToken: string) => void): this;
/** Emitted when a delta has been received for a registered Thing Shadow. */
on(event: "delta", listener: (thingName: string, stateObject: any) => void): this;
/** Emitted when a different client"s update or delete operation is accepted on the shadow. */
on(event: "foreignStateChange", listener: (thingName: string, operation: "update" | "delete", stateObject: any) => void): this;
}
export interface statusDetails {
progress: string;
}
export interface jobStatus {
status: string;
statusDetails: statusDetails;
}
export interface jobDocument {
[key: string]: any
}
export interface job {
/** Object that contains job execution information and functions for updating job execution status. */
/** Returns the job id. */
id: string;
/**
* The JSON document describing details of the job to be executed eg.
* {
* "operation": "install",
* "otherProperty": "value",
* ...
* }
*/
document: jobDocument;
/**
* Returns the job operation from the job document. Eg. 'install', 'reboot', etc.
*/
operation: string;
/**
* Returns the current job status according to AWS Orchestra.
*/
status: jobStatus;
/**
* Update the status of the job execution to be IN_PROGRESS for the thing associated with the job.
*
* @param statusDetails - optional document describing the status details of the in progress job
* @param callback - function(err) optional callback for when the operation completes, err is null if no error occurred
*/
inProgress(statusDetails?: statusDetails, callback?: (err: Error) => void): void;
/**
* Update the status of the job execution to be FAILED for the thing associated with the job.
*
* @param statusDetails - optional document describing the status details of the in progress job e.g.
* @param callback - function(err) optional callback for when the operation completes, err is null if no error occurred
*/
failed(statusDetails?: statusDetails, callback?: (err: Error) => void): void;
/**
* Update the status of the job execution to be SUCCESS for the thing associated with the job.
*
* @param statusDetails - optional document describing the status details of the in progress job e.g.
* @param callback - function(err) optional callback for when the operation completes, err is null if no error occurred
*/
succeeded(statusDetails?: statusDetails, callback?: (err: Error) => void): void;
}
export class jobs extends device {
/**
* The `jobs` class wraps an instance of the `device` class with additional functionality to
* handle job execution management through the AWS IoT Jobs platform. Arguments in `deviceOptions`
* are the same as those in the device class and the `jobs` class supports all of the
* same events and functions as the `device` class.
*/
constructor(options?: DeviceOptions);
/**
* Subscribes to job execution notifications for the thing named `thingName`. If
* `operationName` is specified then the callback will only be called when a job
* ready for execution contains a property called `operation` in its job document with
* a value matching `operationName`. If `operationName` is omitted then the callback
* will be called for every job ready for execution that does not match another
* `subscribeToJobs` subscription.
*
* @param thingName - name of the Thing to receive job execution notifications
* @param operationName - optionally filter job execution notifications to jobs with a value
* for the `operation` property that matches `operationName
* @param callback - function (err, job) callback for when a job execution is ready for processing or an error occurs
* - `err` a subscription error or an error that occurs when client is disconnecting
* - `job` an object that contains job execution information and functions for updating job execution status.
*/
subscribeToJobs(thingName: string, operationName: string, callback?: (err: Error, job: job) => void): void;
/**
* Causes any existing queued job executions for the given thing to be published
* to the appropriate subscribeToJobs handler. Only needs to be called once per thing.
*
* @param thingName - name of the Thing to cancel job execution notifications for
* @param callback - function (err) callback for when the startJobNotifications operation completes
*/
startJobNotifications(thingName: string, callback: (error: Error) => void): mqtt.Client;
/**
* Unsubscribes from job execution notifications for the thing named `thingName` having
* operations with a value of the given `operationName`. If `operationName` is omitted then
* the default handler for the thing with the given name is unsubscribed.
*
* @param thingName - name of the Thing to cancel job execution notifications for
* @param operationName - optional name of previously subscribed operation names
* @param callback - function (err) callback for when the unsubscribe operation completes
*/
unsubscribeFromJobs(thingName: string, operationName: string, callback: (err: Error) => void): void;
} | the_stack |
import { Dictionary } from '../../base/dictionary';
import { WList } from '../list/list';
import { WAbstractList } from '../list/abstract-list';
import { WListLevel } from '../list/list-level';
import { Selection } from '../index';
import { TextPosition } from '../selection/selection-helper';
import { DocumentEditor } from '../../document-editor';
import { Action } from '../../index';
import { LayoutViewer } from '../index';
import { isNullOrUndefined } from '@syncfusion/ej2-base';
import { BaseHistoryInfo } from './base-history-info';
import { ModifiedParagraphFormat, ModifiedLevel, RowHistoryFormat, TableHistoryInfo, CellHistoryFormat } from './history-helper';
import { HistoryInfo } from './history-info';
import { WParagraphFormat } from '../format/paragraph-format';
import { ParagraphWidget, TableRowWidget, TableWidget } from '../viewer/page';
import { Point, HelperMethods } from '../editor/editor-helper';
import { TableResizer } from '../editor/table-resizer';
import { DocumentHelper } from '../viewer';
/**
* `EditorHistory` Module class is used to handle history preservation
*/
export class EditorHistory {
private undoLimitIn: number;
private redoLimitIn: number;
//Fields
private undoStackIn: BaseHistoryInfo[] = [];
private redoStackIn: BaseHistoryInfo[] = [];
private historyInfoStack: HistoryInfo[] = [];
private owner: DocumentEditor;
/**
* @private
*/
public isUndoing: boolean = false;
/**
* @private
*/
public isRedoing: boolean = false;
/**
* @private
*/
public currentBaseHistoryInfo: BaseHistoryInfo;
/**
* @private
* @returns {HistoryInfo} - Returns the history info.
*/
public get currentHistoryInfo(): HistoryInfo {
return this.historyInfoStack && this.historyInfoStack.length > 0 ?
this.historyInfoStack[this.historyInfoStack.length - 1] : undefined;
}
/**
* @private
* @param {HistoryInfo} value - Specified the value.
*/
public set currentHistoryInfo(value: HistoryInfo) {
if (value instanceof HistoryInfo) {
this.historyInfoStack.push(value);
} else {
this.historyInfoStack.pop();
}
}
/**
* @private
*/
public modifiedParaFormats: Dictionary<BaseHistoryInfo, ModifiedParagraphFormat[]>;
public documentHelper: DocumentHelper;
//Properties
/**
* gets undo stack
*
* @private
* @returns {BaseHistoryInfo[]} - Returns the undo stack.
*/
public get undoStack(): BaseHistoryInfo[] {
return this.undoStackIn;
}
/**
* gets redo stack
*
* @private
* @returns {BaseHistoryInfo[]} - Returns the redo stack.
*/
public get redoStack(): BaseHistoryInfo[] {
return this.redoStackIn;
}
/**
* Gets or Sets the limit of undo operations can be done.
*
* @aspType int
* @returns {number} - Returns the redo limit
*/
public get undoLimit(): number {
return isNullOrUndefined(this.undoLimitIn) ? 0 : this.undoLimitIn;
}
/**
* Sets the limit of undo operations can be done.
*
* @aspType int
* @param {number} value - Specified the value.
*/
public set undoLimit(value: number) {
if (value < 0) {
throw new Error('The limit should be greater than or equal to zero.');
}
this.undoLimitIn = value;
}
/**
* Gets or Sets the limit of redo operations can be done.
*
* @aspType int
* @returns {number} - Returns the redo limit
*/
public get redoLimit(): number {
return isNullOrUndefined(this.redoLimitIn) ? 0 : this.redoLimitIn;
}
/**
* Gets or Sets the limit of redo operations can be done.
*
* @aspType int
* @param {number} value - Specified the value.
*/
public set redoLimit(value: number) {
if (value < 0) {
throw new Error('The limit should be greater than or equal to zero.');
}
this.redoLimitIn = value;
}
/**
* @param {DocumentEditor} node - Specified the document editor.
* @private
*/
public constructor(node: DocumentEditor) {
this.owner = node;
this.documentHelper = node.documentHelper;
this.modifiedParaFormats = new Dictionary<BaseHistoryInfo, ModifiedParagraphFormat[]>();
this.undoLimitIn = 500;
this.redoLimitIn = 500;
}
private get viewer(): LayoutViewer {
return this.owner.viewer;
}
private getModuleName(): string {
return 'EditorHistory';
}
/**
* Determines whether undo operation can be done.
*
* @returns {boolean} - Returns the canUndo.
*/
public canUndo(): boolean {
return !isNullOrUndefined(this.undoStack) && this.undoStack.length > 0;
}
/**
* Determines whether redo operation can be done.
*
* @returns {boolean} - Returns the canRedo.
*/
public canRedo(): boolean {
return !isNullOrUndefined(this.redoStack) && this.redoStack.length > 0;
}
//EditorHistory Initialization
/**
* initialize EditorHistory
*
* @private
* @param {Action} action - Specifies the action.
* @returns {void}
*/
public initializeHistory(action: Action): void {
this.currentBaseHistoryInfo = new BaseHistoryInfo(this.owner);
this.currentBaseHistoryInfo.action = action;
this.currentBaseHistoryInfo.updateSelection();
}
/**
* Initialize complex history
*
* @private
* @param {Selection} selection - Specifies the selection.
* @param {Action} action - Specifies the action.
* @returns {void}
*/
public initComplexHistory(selection: Selection, action: Action): void {
this.currentHistoryInfo = new HistoryInfo(selection.owner, !isNullOrUndefined(this.currentHistoryInfo));
this.currentHistoryInfo.action = action;
this.currentHistoryInfo.updateSelection();
}
/**
* @private
* @param {Point} startingPoint - Specifies the start point.
* @param {TableResizer} tableResize - Spcifies the table resizer.
* @returns {void}
*/
public initResizingHistory(startingPoint: Point, tableResize: TableResizer): void {
if (tableResize.resizeNode === 1) {
this.initializeHistory('RowResizing');
if (!isNullOrUndefined(this.currentBaseHistoryInfo)) {
/* eslint-disable-next-line max-len */
this.currentBaseHistoryInfo.modifiedProperties.push(new RowHistoryFormat(startingPoint, (tableResize.currentResizingTable.childWidgets[tableResize.resizerPosition] as TableRowWidget).rowFormat));
}
} else {
this.initializeHistory('CellResizing');
if (this.currentBaseHistoryInfo) {
tableResize.currentResizingTable = tableResize.currentResizingTable.combineWidget(this.viewer) as TableWidget;
const tableHistoryInfo: TableHistoryInfo = new TableHistoryInfo(tableResize.currentResizingTable, this.owner);
tableHistoryInfo.startingPoint = startingPoint;
this.currentBaseHistoryInfo.modifiedProperties.push(tableHistoryInfo);
}
}
}
/**
* Update resizing history
*
* @private
* @param {Point} point - Specifies the point.
* @param {TableResizer} tableResize - Specifies the table resizer.
* @returns {void}
*/
public updateResizingHistory(point: Point, tableResize: TableResizer): void {
if (tableResize.resizeNode === 1) {
if (!isNullOrUndefined(this.currentBaseHistoryInfo)) {
const rowHistoryFormat: RowHistoryFormat = this.currentBaseHistoryInfo.modifiedProperties[0] as RowHistoryFormat;
if (rowHistoryFormat.startingPoint.y === point.y) {
this.currentBaseHistoryInfo.modifiedProperties.length = 0;
} else {
rowHistoryFormat.displacement = HelperMethods.convertPixelToPoint(point.y - rowHistoryFormat.startingPoint.y);
this.recordChanges(this.currentBaseHistoryInfo);
this.currentBaseHistoryInfo = undefined;
}
}
} else {
if (!isNullOrUndefined(this.currentBaseHistoryInfo)) {
const cellHistoryFormat: CellHistoryFormat = this.currentBaseHistoryInfo.modifiedProperties[0] as CellHistoryFormat;
if (cellHistoryFormat.startingPoint.x === point.x) {
this.currentBaseHistoryInfo.modifiedProperties.length = 0;
} else {
cellHistoryFormat.displacement = HelperMethods.convertPixelToPoint(point.x - cellHistoryFormat.startingPoint.x);
cellHistoryFormat.endIndex = tableResize.getCellReSizerPosition(point);
this.owner.editorHistory.recordChanges(this.currentBaseHistoryInfo);
this.currentBaseHistoryInfo = undefined;
}
}
}
}
/**
* Record the changes
*
* @private
* @param {BaseHistoryInfo} baseHistoryInfo - Specified the base history info.
* @returns {void}
*/
public recordChanges(baseHistoryInfo: BaseHistoryInfo): void {
if (!this.owner.enableHistoryMode) {
return;
}
if (this.isUndoing) {
if (isNullOrUndefined(this.redoStack)) {
this.redoStackIn = [];
}
if (this.redoStack.length === this.redoLimit && this.redoLimit > 0) {
const count: number = this.undoLimit > 20 ? 10 : 1;
this.redoStackIn.splice(0, count);
}
if (this.redoStack.length < this.redoLimit) {
this.redoStack.push(baseHistoryInfo);
}
} else {
if (!this.isRedoing) {
this.clearRedoStack();
}
if (isNullOrUndefined(this.undoStack)) {
this.undoStackIn = [];
}
if (this.undoStack.length === this.undoLimit && this.undoLimit > 0) {
const count: number = this.undoLimit > 20 ? 10 : 1;
this.undoStackIn.splice(0, count);
}
if (this.undoStack.length < this.undoLimit) {
this.undoStackIn.push(baseHistoryInfo);
}
}
}
/**
* update EditorHistory
*
* @private
* @returns {void}
*/
public updateHistory(): void {
if (this.documentHelper.owner.enableHistoryMode && !isNullOrUndefined(this.currentBaseHistoryInfo)) {
//Updates the current end position
if (!isNullOrUndefined(this.currentBaseHistoryInfo)
&& isNullOrUndefined(this.currentBaseHistoryInfo.endPosition)) {
this.currentBaseHistoryInfo.endPosition = this.currentBaseHistoryInfo.insertPosition;
}
if (!isNullOrUndefined(this.currentHistoryInfo)) {
this.currentHistoryInfo.addModifiedAction(this.currentBaseHistoryInfo);
} else {
this.recordChanges(this.currentBaseHistoryInfo);
}
this.currentBaseHistoryInfo = undefined;
}
}
/**
* @private
* @returns {boolean} -Returns isHandleComplexHistory
*/
public isHandledComplexHistory(): boolean {
let isHandledComplexHistory: boolean = false;
if (!(this.isUndoing || this.isRedoing)) {
isHandledComplexHistory = this.owner.editorModule.insertRemoveBookMarkElements();
}
if (this.documentHelper.owner.enableHistoryMode && !isNullOrUndefined(this.currentHistoryInfo)) {
this.updateHistory();
isHandledComplexHistory = true;
} else if (this.owner.editorModule.isHandledComplex) {
isHandledComplexHistory = true;
}
return isHandledComplexHistory;
}
/**
* Update complex history
*
* @private
* @returns {void}
*/
public updateComplexHistory(): void {
const selection: Selection = this.documentHelper.selection;
if (this.currentHistoryInfo.hasAction) {
if (this.currentHistoryInfo.action === 'AutoFormatHyperlink' || this.currentHistoryInfo.action === 'SkipCommentInline'
|| this.currentHistoryInfo.action === 'DeleteCommentInline' || this.currentHistoryInfo.action === 'RemoveComment') {
// this.reLayoutParagraph(startPosition.paragraph, 0);
if (selection.owner.editorHistory.isUndoing) {
this.owner.editorModule.setPositionForCurrentIndex(selection.start, this.currentHistoryInfo.selectionStart);
this.owner.editorModule.setPositionForCurrentIndex(selection.end, this.currentHistoryInfo.selectionEnd);
} else {
this.owner.editorModule.setPositionForCurrentIndex(selection.start, this.currentHistoryInfo.endPosition);
this.owner.editorModule.setPositionForCurrentIndex(selection.end, this.currentHistoryInfo.endPosition);
}
}
if (this.currentHistoryInfo.action === 'InsertHyperlink') {
const startPosition: TextPosition = new TextPosition(selection.owner);
this.owner.editorModule.setPositionForCurrentIndex(startPosition, this.currentHistoryInfo.insertPosition);
const endPosition: TextPosition = new TextPosition(selection.owner);
this.owner.editorModule.setPositionForCurrentIndex(endPosition, this.currentHistoryInfo.endPosition);
this.documentHelper.layout.reLayoutParagraph(startPosition.paragraph, 0, 0);
if (endPosition.paragraph !== startPosition.paragraph) {
this.documentHelper.layout.reLayoutParagraph(endPosition.paragraph, 0, 0);
}
}
if (this.currentHistoryInfo.action === 'ReplaceAll') {
this.owner.editorModule.layoutWholeDocument();
} else if (selection.owner.isShiftingEnabled) {
this.documentHelper.layout.shiftLayoutedItems(false);
if (this.owner.enableHeaderAndFooter) {
this.owner.editorModule.updateHeaderFooterWidget();
}
this.documentHelper.removeEmptyPages();
}
}
if (this.owner.showRevisions) {
this.owner.trackChangesPane.updateTrackChanges();
}
selection.owner.isShiftingEnabled = false;
selection.owner.isLayoutEnabled = true;
// // selection.addMultipleSelectionRanges();
if (this.currentHistoryInfo.action === 'ApplyStyle') {
this.owner.editor.getOffsetValue(selection);
} else {
selection.start.updatePhysicalPosition(true);
if (selection.isEmpty) {
selection.end.setPositionInternal(selection.start);
} else {
selection.end.updatePhysicalPosition(true);
}
}
selection.upDownSelectionLength = selection.end.location.x;
this.documentHelper.isScrollHandler = true;
this.viewer.updateScrollBars();
selection.fireSelectionChanged(true);
this.documentHelper.isScrollHandler = false;
this.documentHelper.updateFocus();
this.updateComplexHistoryInternal();
this.owner.editorModule.fireContentChange();
}
/**
* @private
*
* @returns {void}
*/
public updateComplexHistoryInternal(): void {
if (!isNullOrUndefined(this.currentHistoryInfo)) {
//Updates the current end position
if (isNullOrUndefined(this.currentHistoryInfo.endPosition)) {
this.currentHistoryInfo.endPosition = this.currentHistoryInfo.insertPosition;
}
if (this.historyInfoStack.length > 1) {
const historyInfo: HistoryInfo = this.historyInfoStack[this.historyInfoStack.length - 2];
historyInfo.addModifiedAction(this.currentHistoryInfo);
} else {
this.recordChanges(this.currentHistoryInfo);
}
this.currentHistoryInfo = undefined;
}
}
//List history preservation undo API
/**
* update list changes for history preservation
*
* @private
* @param {WAbstractList} currentAbstractList - Specfies the abstractlist.
* @param {WList} list - Specifies the list.
* @returns {Dictionary<number, ModifiedLevel>} - Returns the modified action.
*/
public updateListChangesInHistory(currentAbstractList: WAbstractList, list: WList): Dictionary<number, ModifiedLevel> {
this.currentBaseHistoryInfo = new BaseHistoryInfo(this.documentHelper.owner);
this.currentBaseHistoryInfo.action = 'List';
this.currentBaseHistoryInfo.updateSelection();
const collection: Dictionary<number, ModifiedLevel> = new Dictionary<number, ModifiedLevel>();
for (let i: number = 0; i < currentAbstractList.levels.length; i++) {
const levels: WListLevel = this.documentHelper.getAbstractListById(list.abstractListId).levels[i];
this.currentBaseHistoryInfo.addModifiedPropertiesForList(levels);
const modifiedLevel: ModifiedLevel = new ModifiedLevel(levels, currentAbstractList.levels[i]);
if (!isNullOrUndefined(levels)) {
this.documentHelper.owner.editorModule.copyListLevel(levels, (currentAbstractList.levels[i] as WListLevel));
}
collection.add(i, modifiedLevel);
}
return collection;
}
/**
* Apply list changes
*
* @private
* @param {Selection} selection - Specifies the selection.
* @param {Dictionary<number, ModifiedLevel>} modifiedLevelsInternal - Specifies the modified levels.
* @returns {void}
*/
public applyListChanges(selection: Selection, modifiedLevelsInternal: Dictionary<number, ModifiedLevel>): void {
if (isNullOrUndefined(this.modifiedParaFormats)) {
this.modifiedParaFormats = new Dictionary<BaseHistoryInfo, ModifiedParagraphFormat[]>();
}
const collection: ModifiedParagraphFormat[] = [];
for (let i: number = 0; i < this.documentHelper.listParagraphs.length; i++) {
const paragraph: ParagraphWidget = this.documentHelper.listParagraphs[i];
const paraFormat: WParagraphFormat = paragraph.paragraphFormat;
const currentList: WList = this.documentHelper.getListById(paraFormat.listFormat.listId);
const listLevel: WListLevel = this.documentHelper.layout.getListLevel(currentList, paraFormat.listFormat.listLevelNumber);
if (modifiedLevelsInternal.containsKey(paraFormat.listFormat.listLevelNumber)
&& modifiedLevelsInternal.get(paraFormat.listFormat.listLevelNumber).ownerListLevel === listLevel) {
const modifiedFormat: WParagraphFormat = new WParagraphFormat(null);
modifiedFormat.leftIndent = paraFormat.leftIndent;
modifiedFormat.firstLineIndent = paraFormat.firstLineIndent;
const modified: ModifiedParagraphFormat = new ModifiedParagraphFormat(paraFormat, modifiedFormat);
collection.push(modified);
this.owner.editorModule.copyFromListLevelParagraphFormat(paraFormat, listLevel.paragraphFormat);
}
}
this.modifiedParaFormats.add(this.currentBaseHistoryInfo, collection);
}
/**
* Update list changes
*
* @private
* @param {Dictionary<number, ModifiedLevel>} modifiedCollection - Specifies the modified colection.
* @returns {void }
*/
public updateListChanges(modifiedCollection: Dictionary<number, ModifiedLevel>): void {
this.documentHelper.owner.isLayoutEnabled = false;
this.owner.editorModule.updateListParagraphs();
for (let i: number = 0; i < modifiedCollection.keys.length; i++) {
const levelNumber: number = modifiedCollection.keys[0];
let modifiedLevel: ModifiedLevel = modifiedCollection.get(levelNumber);
if (!isNullOrUndefined(this.currentBaseHistoryInfo)) {
modifiedLevel = this.currentBaseHistoryInfo.addModifiedPropertiesForList(modifiedLevel.ownerListLevel) as ModifiedLevel;
}
this.owner.editorModule.copyListLevel(modifiedLevel.ownerListLevel, modifiedLevel.modifiedListLevel);
}
this.revertListChanges();
this.documentHelper.owner.isLayoutEnabled = true;
this.documentHelper.renderedLists.clear();
this.documentHelper.renderedLevelOverrides = [];
this.documentHelper.pages = [];
this.documentHelper.layout.layout();
const selection: Selection = this.documentHelper.selection;
selection.start.updatePhysicalPosition(true);
if (selection.isEmpty) {
selection.end.setPositionInternal(selection.start);
} else {
selection.end.updatePhysicalPosition(true);
}
selection.upDownSelectionLength = selection.end.location.x;
selection.fireSelectionChanged(false);
this.updateHistory();
}
/**
* Revert list changes
*
* @returns {void}
*/
private revertListChanges(): void {
if (!isNullOrUndefined(this.currentBaseHistoryInfo)
&& this.documentHelper.owner.editorHistory.modifiedParaFormats.containsKey(this.currentBaseHistoryInfo)) {
const collection: ModifiedParagraphFormat[] = this.modifiedParaFormats.get(this.currentBaseHistoryInfo);
for (let i: number = 0; i < collection.length; i++) {
const modified: WParagraphFormat = new WParagraphFormat(null);
modified.leftIndent = collection[i].ownerFormat.leftIndent;
modified.firstLineIndent = collection[i].ownerFormat.firstLineIndent;
collection[i].ownerFormat.copyFormat(collection[i].modifiedFormat);
collection[i].modifiedFormat.leftIndent = modified.leftIndent;
collection[i].modifiedFormat.firstLineIndent = modified.firstLineIndent;
}
}
}
/**
* Reverts the last editing action.
*
* @returns {void}
*/
public undo(): void {
if ((this.owner.isReadOnlyMode && !this.owner.documentHelper.isCommentOnlyMode &&
(this.owner.documentHelper.protectionType !== 'FormFieldsOnly')) ||
!this.canUndo() || !this.owner.enableHistoryMode) {
return;
}
//this.owner.ClearTextSearchResults();
const historyInfo: BaseHistoryInfo = this.undoStack.pop();
this.isUndoing = true;
historyInfo.revert();
this.isUndoing = false;
this.owner.selection.checkForCursorVisibility();
this.owner.editorModule.isBordersAndShadingDialog = false;
}
/**
* Performs the last reverted action.
*
* @returns {void}
*/
public redo(): void {
if ((this.owner.isReadOnlyMode && !this.owner.documentHelper.isCommentOnlyMode &&
(this.owner.documentHelper.protectionType !== 'FormFieldsOnly'))
|| !this.canRedo() || !this.owner.enableHistoryMode) {
return;
}
//this.owner.ClearTextSearchResults();
const historyInfo: BaseHistoryInfo = this.redoStack.pop();
if (historyInfo.action === 'BordersAndShading') {
this.owner.editorModule.isBordersAndShadingDialog = true;
}
this.isRedoing = true;
historyInfo.revert();
this.isRedoing = false;
this.owner.selection.checkForCursorVisibility();
this.owner.editorModule.isBordersAndShadingDialog = false;
}
/**
* @private
* @returns {void}
*/
public destroy(): void {
this.clearHistory();
this.undoStackIn = undefined;
this.redoStackIn = undefined;
}
/**
* @private
* @returns {void}
*/
public clearHistory(): void {
this.clearUndoStack();
this.clearRedoStack();
}
private clearUndoStack(): void {
if (this.canUndo()) {
while (this.undoStack.length > 0) {
let historyInfo: BaseHistoryInfo = this.undoStack.pop();
historyInfo.destroy();
historyInfo = undefined;
}
}
}
private clearRedoStack(): void {
if (this.canRedo()) {
while (this.redoStack.length > 0) {
let historyInfo: BaseHistoryInfo = this.redoStack.pop();
historyInfo.destroy();
historyInfo = undefined;
}
}
}
} | the_stack |
// See state defs from inflate.js
const BAD = 30; /* got a data error -- remain here until reset */
const TYPE = 12; /* i: waiting for type bits, including last-flag bit */
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state.mode === LEN
strm.avail_in >= 6
strm.avail_out >= 258
start >= strm.avail_out
state.bits < 8
On return, state.mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm.avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm.avail_out >= 258 for each loop to avoid checking for
output space.
*/
export default function inflate_fast(strm: any, start: number) {
let state;
let _in; /* local strm.input */
let last; /* have enough input while in < last */
let _out; /* local strm.output */
let beg; /* inflate()'s initial strm.output */
let end; /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
let dmax; /* maximum distance from zlib header */
//#endif
let wsize; /* window size or zero if not using window */
let whave; /* valid bytes in the window */
let wnext; /* window write index */
// Use `s_window` instead `window`, avoid conflict with instrumentation tools
let s_window; /* allocated sliding window, if wsize != 0 */
let hold; /* local strm.hold */
let bits; /* local strm.bits */
let lcode; /* local strm.lencode */
let dcode; /* local strm.distcode */
let lmask; /* mask for first level of length codes */
let dmask; /* mask for first level of distance codes */
let here; /* retrieved table entry */
let op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
let len; /* match length, unused bytes */
let dist; /* match distance */
let from; /* where to copy match from */
let from_source;
let input, output; // JS specific, because we have no pointers
/* copy state to local variables */
state = strm.state;
//here = state.here;
_in = strm.next_in;
input = strm.input;
last = _in + (strm.avail_in - 5);
_out = strm.next_out;
output = strm.output;
beg = _out - (start - strm.avail_out);
end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
dmax = state.dmax;
//#endif
wsize = state.wsize;
whave = state.whave;
wnext = state.wnext;
s_window = state.window;
hold = state.hold;
bits = state.bits;
lcode = state.lencode;
dcode = state.distcode;
lmask = (1 << state.lenbits) - 1;
dmask = (1 << state.distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
top:
do {
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
for (;;) { // Goto emulation
op = here >>> 24 /*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff /*here.op*/;
if (op === 0) {
/* literal */
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
output[_out++] = here & 0xffff /*here.val*/;
} else if (op & 16) {
/* length base */
len = here & 0xffff /*here.val*/;
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
len += hold & ((1 << op) - 1);
hold >>>= op;
bits -= op;
}
//Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
for (;;) { // goto emulation
op = here >>> 24 /*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff /*here.op*/;
if (op & 16) {
/* distance base */
dist = here & 0xffff /*here.val*/;
op &= 15; /* number of extra bits */
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
}
dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
if (dist > dmax) {
strm.msg = "invalid distance too far back";
state.mode = BAD;
break top;
}
//#endif
hold >>>= op;
bits -= op;
//Tracevv((stderr, "inflate: distance %u\n", dist));
op = _out - beg; /* max distance in output */
if (dist > op) {
/* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state.sane) {
strm.msg = "invalid distance too far back";
state.mode = BAD;
break top;
}
// (!) This block is disabled in zlib defaults,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// if (len <= op - whave) {
// do {
// output[_out++] = 0;
// } while (--len);
// continue top;
// }
// len -= op - whave;
// do {
// output[_out++] = 0;
// } while (--op > whave);
// if (op === 0) {
// from = _out - dist;
// do {
// output[_out++] = output[from++];
// } while (--len);
// continue top;
// }
//#endif
}
from = 0; // window index
from_source = s_window;
if (wnext === 0) {
/* very common case */
from += wsize - op;
if (op < len) {
/* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
} else if (wnext < op) {
/* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) {
/* some from end of window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = 0;
if (wnext < len) {
/* some from start of window */
op = wnext;
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
} else {
/* contiguous in window */
from += wnext - op;
if (op < len) {
/* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
while (len > 2) {
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
len -= 3;
}
if (len) {
output[_out++] = from_source[from++];
if (len > 1) {
output[_out++] = from_source[from++];
}
}
} else {
from = _out - dist; /* copy direct from output */
do {
/* minimum length is three */
output[_out++] = output[from++];
output[_out++] = output[from++];
output[_out++] = output[from++];
len -= 3;
} while (len > 2);
if (len) {
output[_out++] = output[from++];
if (len > 1) {
output[_out++] = output[from++];
}
}
}
} else if ((op & 64) === 0) {
/* 2nd level distance code */
here =
dcode[(here & 0xffff) /*here.val*/ + (hold & ((1 << op) - 1))];
continue dodist;
} else {
strm.msg = "invalid distance code";
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
} else if ((op & 64) === 0) {
/* 2nd level length code */
here = lcode[(here & 0xffff) /*here.val*/ + (hold & ((1 << op) - 1))];
continue dolen;
} else if (op & 32) {
/* end-of-block */
//Tracevv((stderr, "inflate: end of block\n"));
state.mode = TYPE;
break top;
} else {
strm.msg = "invalid literal/length code";
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
} while (_in < last && _out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
_in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
/* update state and return */
strm.next_in = _in;
strm.next_out = _out;
strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
state.hold = hold;
state.bits = bits;
return;
} | the_stack |
import { format, IConnection } from "mysql";
import BaseDAO from "./BaseDAO";
import DeploymentDAO from "./DeploymentDAO";
import HistoryDAO from "./HistoryDAO";
import { PackageDTO, QueryOkPacketDTO } from "../dto";
import {
ClientRatioQueries,
DeploymentPackageQueries,
PackageContentQueries,
PackageDiffQueries,
PackageQueries,
PackageTagQueries,
} from "../queries";
import { difference, find } from "lodash";
import { connect } from "net";
import * as semver from "semver";
import Encryptor from "../Encryptor";
export default class PackageDAO extends BaseDAO {
public static async packageById(connection: IConnection, packageId: number): Promise<PackageDTO> {
const results = await PackageDAO.query(connection, PackageQueries.getPackageById, [packageId]);
if (!results || results.length === 0) {
throw new Error("Not found. No package found for id [" + packageId + "]");
}
const result = results[0];
const pkg = new PackageDTO();
pkg.id = result.id;
pkg.packageHash = result.package_hash;
pkg.appVersion = result.app_version;
pkg.blobUrl = result.blob_url;
pkg.created_ = result.create_time;
pkg.description = result.description;
pkg.isDisabled = (result.is_disabled === 1);
pkg.isMandatory = (result.is_mandatory === 1);
pkg.label = result.label;
pkg.manifestBlobUrl = result.manifest_blob_url;
pkg.originalDeployment = result.original_deployment_name;
pkg.originalLabel = result.original_label;
pkg.releasedBy = result.released_by;
pkg.releaseMethod = result.release_method;
pkg.rollout = result.rollout;
pkg.size = result.size;
pkg.uploadTime = result.upload_time;
Encryptor.instance.decryptDTO(pkg);
pkg.diffPackageMap = await PackageDAO.getPackageDiffs(connection, pkg.id)
.then(PackageDAO.transformOutgoingPackageDiffs);
const tagResults = await PackageDAO.getPackageTags(connection, pkg.id);
if (tagResults && tagResults.length > 0) {
pkg.tags = tagResults.map((tagResult: any) => tagResult.tag_name);
}
return pkg;
}
public static async getNewestApplicablePackage(connection: IConnection, deploymentKey: string,
tags: string[] | undefined, appVersion: string | undefined): Promise<PackageDTO | void> {
const deployment = await DeploymentDAO.deploymentForKey(connection, deploymentKey);
const deploymentId = deployment.id;
const isTagsRequested = tags && tags.length > 0;
const key = isTagsRequested ? "tags" : "notags";
const allQueries:{[key:string]: string;} = {
"tags": PackageQueries.getMostRecentPackageIdByDeploymentAndTags,
"notags": PackageQueries.getMostRecentPackageIdByDeploymentNoTags
}
const allParams:{[key:string]:any} = {
"tags": [deploymentId, tags, deploymentId],
"notags": [deploymentId]
}
const packages = await PackageDAO.query(connection, allQueries[key], allParams[key]);
if (packages && packages.length > 0) {
if (appVersion) {
for (let i = 0; i < packages.length; i++) {
if (semver.satisfies(appVersion, packages[i].app_version)) {
return await PackageDAO.packageById(connection, packages[i].package_id);
}
}
}
// always return latest release if version doesn't matches
return await PackageDAO.packageById(connection, packages[0].package_id);
}
return undefined;
}
public static async getNewestApplicablePackageByNonSemver(connection: IConnection, deploymentKey: string,
tags: string[] | undefined, appVersion: string | undefined): Promise<PackageDTO | void> {
const deployment = await DeploymentDAO.deploymentForKey(connection, deploymentKey);
const deploymentId = deployment.id;
const useTags = tags && tags.length > 0 ? "tags" : "notags";
const useVersion = appVersion !== undefined ? "version" : "noversion";
const allQueries:{[key:string]: string;} = {
"tags-noversion": PackageQueries.getMostRecentPackageIdByDeploymentAndTags,
"notags-noversion": PackageQueries.getMostRecentPackageIdByDeploymentNoTags,
"tags-version": PackageQueries.getMostRecentPackageIdByDeploymentAndTagsAndVersion,
"notags-version": PackageQueries.getMostRecentPackageIdByDeploymentNoTagsAndVersion
}
const allParams:{[key:string]:any} = {
"tags-noversion": [deploymentId, tags, deploymentId],
"notags-noversion": [deploymentId],
"tags-version": [deploymentId, appVersion, tags, deploymentId, appVersion],
"notags-version": [deploymentId, appVersion]
}
const key = `${useTags}-${useVersion}`;
const result = await PackageDAO.query(connection, allQueries[key], allParams[key]);
if (result && result.length > 0) {
return await PackageDAO.packageById(connection, result[0].package_id);
}
return undefined;
}
public static async getMostRecentlyPromotedVersions(connection: IConnection, deploymentId: number): Promise<any> {
const result = await PackageDAO.query(connection, PackageQueries.getMostRecentlyPromotedVersions, [deploymentId]);
if (result && result.length > 0) {
return result.map((pack: any) => pack.app_version);
}
return [];
}
public static async addPackage(connection: IConnection, deploymentKey: string,
packageInfo: PackageDTO): Promise<PackageDTO> {
const deployment = await DeploymentDAO.deploymentForKey(connection, deploymentKey);
await PackageDAO.beginTransaction(connection);
const insertResult = await PackageDAO.insertPackaage(connection, packageInfo);
const pkgId = insertResult.insertId;
await HistoryDAO.addHistory(connection, deployment.id, pkgId);
if (packageInfo.tags && packageInfo.tags.length) {
await PackageDAO.addPackageTags(connection, pkgId, packageInfo.tags);
}
await PackageDAO.commit(connection);
return await PackageDAO.packageById(connection, pkgId);
}
public static async addPackageDiffMap(connection: IConnection, deploymentKey: string,
packageInfo: PackageDTO, packageHash: string): Promise<any> {
let pkgId = packageInfo.id;
const newDiffs = [
{
packageHash,
size: packageInfo.diffPackageMap[packageHash].size,
url: packageInfo.diffPackageMap[packageHash].url,
}
];
return await PackageDAO.addPackageDiffs(connection, pkgId, newDiffs);
}
public static async updatePackage(connection: IConnection, deploymentKey: string,
packageInfo: any, label: string): Promise<PackageDTO> {
const deployment = await DeploymentDAO.deploymentForKey(connection, deploymentKey);
let pkgId = packageInfo.id;
if (!pkgId) {
const history = await HistoryDAO.historyForDeployment(connection, deployment.id);
if (!history || history.length === 0) {
throw new Error("Not found. no deployment-package history for deployment key [" + deploymentKey + "]");
}
pkgId = history[0].package_id;
if (label) {
const found = history.find((h: any) => h.label === label);
if (found) {
pkgId = found.package_id;
}
}
}
const existing = await PackageDAO.packageById(connection, pkgId);
await PackageDAO.beginTransaction(connection);
// check if diffs changed
if (packageInfo.diffPackageMap) {
// newDiffKeys will be a list of packageHash's for diffs that need to be added
const newDiffKeys = difference(Object.keys(packageInfo.diffPackageMap),
Object.keys(existing.diffPackageMap));
if (newDiffKeys.length > 0) {
const newDiffs = newDiffKeys.map((packageHash) => {
return {
packageHash,
size: packageInfo.diffPackageMap[packageHash].size,
url: packageInfo.diffPackageMap[packageHash].url,
};
});
await PackageDAO.addPackageDiffs(connection, pkgId, newDiffs);
}
// remDiffKeys will be a list of packageHash's that need to be removed
const remDiffKeys = difference(Object.keys(existing.diffPackageMap),
Object.keys(packageInfo.diffPackageMap));
if (remDiffKeys.length > 0) {
await PackageDAO.removePackageDiffs(connection, pkgId, remDiffKeys);
}
}
// check if tags changed
if (packageInfo.tags) {
const newTags = difference(packageInfo.tags, existing.tags || []);
if (newTags.length > 0) {
await PackageDAO.addPackageTags(connection, pkgId, newTags);
await PackageDAO.updatePackageTime(connection, pkgId);
}
if (existing.tags) {
const removeTags = difference(existing.tags, packageInfo.tags);
if (removeTags.length > 0) {
await PackageDAO.removePackageTags(connection, pkgId, removeTags);
await PackageDAO.updatePackageTime(connection, pkgId);
}
}
}
// check these properties we care about
let changed = false;
["isDisabled", "isMandatory", "rollout", "appVersion", "description"].forEach((prop) => {
const existingVal = (existing as any)[prop];
if (packageInfo[prop] !== undefined &&
packageInfo[prop] !== null &&
packageInfo[prop] !== existingVal) {
// if the value is different from what is in the db, mark changed as true
// and update the property on existing. Will use "existing" as data when passing to update function
changed = true;
(existing as any)[prop] = packageInfo[prop];
}
});
if (changed) {
await PackageDAO.updatePackageDB(connection, pkgId, existing);
}
await PackageDAO.commit(connection);
return await PackageDAO.packageById(connection, pkgId);
}
public static async savePackageContent(connection: IConnection, packageHash: string,
content: Buffer): Promise<any> {
const contentResult = await PackageDAO.getPackageContentFromDB(connection, packageHash);
if (contentResult && contentResult.length > 0) {
return PackageDAO.transformOkPacket({});
}
const result = await PackageDAO.insertPackageContent(connection, packageHash, content);
return PackageDAO.transformOkPacket(result);
}
public static async getPackageContent(connection: IConnection, packageHash: string): Promise<Buffer> {
const contentResult = await PackageDAO.getPackageContentFromDB(connection, packageHash);
if (contentResult && contentResult.length > 0) {
return contentResult[0].content;
} else {
throw new Error("No package content found for packageHash " + packageHash);
}
}
// public, but used internal to data layer
public static async removePackage(connection: IConnection, pkgId: number): Promise<void> {
// these can run in parallel
await Promise.all([
// delete client_ratio
PackageDAO.query(connection, ClientRatioQueries.deleteClientRatioByPackageId, [pkgId]),
// delete tags
PackageDAO.query(connection, PackageTagQueries.deletePackageTagsByPackageId, [pkgId]),
// delete package content
PackageDAO.query(connection, PackageContentQueries.deletePackageContentByPkgId, [pkgId]),
// delete package_diff
PackageDAO.query(connection, PackageDiffQueries.deletePackageDiffByLeftPkgId, [pkgId]),
PackageDAO.query(connection, PackageDiffQueries.deletePackageDiffByRightPkgId, [pkgId]),
// delete deployment_package_history
PackageDAO.query(connection, DeploymentPackageQueries.deleteDeploymentPackageByPackageId,
[pkgId]),
]);
// delete package
await PackageDAO.query(connection, PackageQueries.deletePackage, [pkgId]);
}
// only used in DAO
public static async getLatestPackageForDeployment(connection: IConnection,
deploymentId: number): Promise<PackageDTO | undefined> {
const results = await PackageDAO.query(connection, DeploymentPackageQueries.getHistoryByDeploymentId,
[deploymentId]);
if (results && results.length > 0) {
// newest package should be first in the list according to query result ordering
return await PackageDAO.packageById(connection, results[0].package_id);
}
return undefined;
}
private static async getPackageByHash(connection: IConnection, pkgHash: string): Promise<any> {
return PackageDAO.query(connection, PackageQueries.getPackageByHash, [pkgHash]);
}
private static async insertPackaage(connection: IConnection, pkg: PackageDTO): Promise<any> {
/*
app_version, blob_url, description,
is_disabled, is_mandatory, label,
manifest_blob_url, original_deployment_name, original_label,
package_hash, release_method, released_by,
rollout, size, upload_time
*/
return PackageDAO.query(connection, PackageQueries.insertPackage,
[pkg.appVersion, pkg.blobUrl, pkg.description,
pkg.isDisabled, pkg.isMandatory, pkg.label,
pkg.manifestBlobUrl, pkg.originalDeployment, pkg.originalLabel,
pkg.packageHash, pkg.releaseMethod, Encryptor.instance.encrypt("package.released_by", pkg.releasedBy),
pkg.rollout, pkg.size]);
}
private static async updatePackageDB(connection: IConnection, pkgId: number,
updateInfo: PackageDTO): Promise<any> {
/*
SET is_disabled = ?,
is_mandatory = ?,
rollout = ?,
app_version = ?,
description = ?
WHERE id = ?`
*/
return PackageDAO.query(connection, PackageQueries.updatePackage,
[updateInfo.isDisabled, updateInfo.isMandatory, updateInfo.rollout,
updateInfo.appVersion, updateInfo.description, pkgId]);
}
private static async updatePackageTime(connection: IConnection, pkgId: number) {
return PackageDAO.query(connection, PackageQueries.updatePackageTime, [pkgId]);
}
private static async addPackageDiffs(connection: IConnection, pkgId: number, pkgDiffs: any[]): Promise<any> {
return Promise.all(pkgDiffs.map((pkgDiff) => {
return PackageDAO.getPackageByHash(connection, pkgDiff.packageHash).then((pkgResults) => {
const rightPkgId = pkgResults[0].id;
return PackageDAO.insertPackageDiff(connection, pkgId, rightPkgId, pkgDiff.size, pkgDiff.url);
});
}));
}
private static async removePackageDiffs(connection: IConnection, pkgId: number, pkgHashes: string[]): Promise<any> {
return Promise.all(pkgHashes.map((pkgHash) => {
return PackageDAO.getPackageByHash(connection, pkgHash).then((pkgResults) => {
const rightPkgId = pkgResults[0].id;
return PackageDAO.deletePackageDiff(connection, pkgId, rightPkgId);
});
}));
}
private static async addPackageTags(connection: IConnection, pkgId: number, tags: string[]): Promise<any> {
return Promise.all(tags.map((tag) => {
return PackageDAO.insertPackageTag(connection, pkgId, tag);
}));
}
private static async removePackageTags(connection: IConnection, pkgId: number, tags: string[]): Promise<any> {
return Promise.all(tags.map((tag) => {
return PackageDAO.deletePackageTag(connection, pkgId, tag);
}));
}
private static async insertPackageDiff(connection: IConnection, leftPkgId: number,
rightPkgId: number, size: number, url: string): Promise<any> {
return PackageDAO.query(connection, PackageDiffQueries.insertPackageDiff,
[leftPkgId, rightPkgId, size, url]);
}
private static async deletePackageDiff(connection: IConnection, leftPkgId: number,
rightPkgId: number): Promise<any> {
return PackageDAO.query(connection, PackageDiffQueries.deletePackageDiff, [leftPkgId, rightPkgId]);
}
private static async getPackageDiffs(connection: IConnection, pkgId: number): Promise<any> {
return PackageDAO.query(connection, PackageDiffQueries.getPackageDiffsForLeftPkgId, [pkgId]);
}
private static async deletePackageTag(connection: IConnection, pkgId: number, tag: string): Promise<any> {
return PackageDAO.query(connection, PackageTagQueries.deletePackageTag, [pkgId, tag]);
}
private static async insertPackageTag(connection: IConnection, pkgId: number, tag: string): Promise<any> {
return PackageDAO.query(connection, PackageTagQueries.insertPackageTag, [pkgId, tag]);
}
private static async getPackageTags(connection: IConnection, pkgId: number): Promise<any> {
return PackageDAO.query(connection, PackageTagQueries.getTagsForPackage, [pkgId]);
}
private static async insertPackageContent(connection: IConnection, pkgHash: string, content: Buffer): Promise<void> {
return PackageDAO.query(connection, PackageContentQueries.insertPackageContent, [pkgHash, content]);
}
private static async getPackageContentFromDB(connection: IConnection, pkgHash: string): Promise<any> {
return PackageDAO.query(connection, PackageContentQueries.getPackageContentByPkgHash, [pkgHash]);
}
private static transformOutgoingPackageDiffs(pkgDiffs: any[]): any {
return pkgDiffs.reduce((obj, pkgDiff) => {
obj[pkgDiff.package_hash] = {
size: pkgDiff.size,
url: pkgDiff.url,
};
return obj;
}, {} as any);
}
private static transformOkPacket(result: any): QueryOkPacketDTO {
const okPacket = new QueryOkPacketDTO();
okPacket.fieldCount = 0;
okPacket.affectedRows = 0;
okPacket.insertId = 0;
okPacket.serverStatus = 2;
okPacket.warningCount = 0;
okPacket.message = "";
okPacket.protocol41 = true;
okPacket.changedRows = 0;
return Object.assign(okPacket, result);
}
} | the_stack |
import themisContext from "./context";
import { ThemisError, ThemisErrorCode } from "./themis_error";
import {
coerceToBytes,
heapFree,
heapGetArray,
heapPutArray,
heapAlloc,
passphraseBytes,
} from "./utils";
const cryptosystem_name = "SecureCellSeal";
export class SecureCellSeal {
protected masterKey: Uint8Array;
constructor(masterKey: Uint8Array) {
masterKey = coerceToBytes(masterKey);
if (masterKey.length == 0) {
throw new ThemisError(
cryptosystem_name,
ThemisErrorCode.INVALID_PARAMETER,
"master key must be not empty"
);
}
this.masterKey = masterKey;
}
/**
* Makes a new Secure Cell in Seal mode with given master key.
*
* @param masterKey non-empty array of master key bytes (Buffer or Uint8Array)
*
* @returns a new instance of SecureCellSeal.
*
* @throws TypeError if the master key is not a byte buffer.
* @throws ThemisError if the master key is empty.
*/
static withKey(masterKey: Uint8Array) {
return new SecureCellSeal(masterKey);
}
/**
* Makes a new Secure Cell in Seal mode with given passphrase.
*
* @param passphrase non-empty string with passphrase,
* or a non-empty raw byte array (Buffer or Uint8Array)
*
* @returns a new instance of SecureCellSeal.
*
* @throws TypeError if the passphrase is not a string or a byte buffer.
* @throws ThemisError if the passphrase is empty.
*/
static withPassphrase(passphrase: string) {
return new SecureCellSealWithPassphrase(passphrase);
}
encrypt(message: Uint8Array) {
message = coerceToBytes(message);
if (message.length == 0) {
throw new ThemisError(
cryptosystem_name,
ThemisErrorCode.INVALID_PARAMETER,
"message must be not empty"
);
}
let context;
if (arguments.length > 1 && arguments[1] !== null) {
context = coerceToBytes(arguments[1]);
} else {
context = new Uint8Array();
}
let status;
/// C API uses "size_t" for lengths, it's defined as "i32" in Emscripten
let result_length_ptr = themisContext.libthemis!!.allocate(
new ArrayBuffer(4),
themisContext.libthemis!!.ALLOC_STACK
);
let master_key_ptr, message_ptr, context_ptr, result_ptr, result_length;
try {
master_key_ptr = heapAlloc(this.masterKey.length);
message_ptr = heapAlloc(message.length);
context_ptr = heapAlloc(context.length);
if (!master_key_ptr || !message_ptr || !context_ptr) {
throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY);
}
heapPutArray(this.masterKey, master_key_ptr);
heapPutArray(message, message_ptr);
heapPutArray(context, context_ptr);
status = themisContext.libthemis!!._themis_secure_cell_encrypt_seal(
master_key_ptr,
this.masterKey.length,
context_ptr,
context.length,
message_ptr,
message.length,
null,
result_length_ptr
);
if (status != ThemisErrorCode.BUFFER_TOO_SMALL) {
throw new ThemisError(cryptosystem_name, status);
}
result_length = themisContext.libthemis!!.getValue(
result_length_ptr,
"i32"
);
result_ptr = heapAlloc(result_length);
if (!result_ptr) {
throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY);
}
status = themisContext.libthemis!!._themis_secure_cell_encrypt_seal(
master_key_ptr,
this.masterKey.length,
context_ptr,
context.length,
message_ptr,
message.length,
result_ptr,
result_length_ptr
);
if (status != ThemisErrorCode.SUCCESS) {
throw new ThemisError(cryptosystem_name, status);
}
result_length = themisContext.libthemis!!.getValue(
result_length_ptr,
"i32"
);
return heapGetArray(result_ptr, result_length);
} finally {
heapFree(master_key_ptr, this.masterKey.length);
heapFree(message_ptr, message.length);
heapFree(context_ptr, context.length);
heapFree(result_ptr, result_length);
}
}
decrypt(message: Uint8Array, context: Uint8Array = new Uint8Array()) {
message = coerceToBytes(message);
if (message.length == 0) {
throw new ThemisError(
cryptosystem_name,
ThemisErrorCode.INVALID_PARAMETER,
"message must be not empty"
);
}
context = coerceToBytes(context);
let status;
/// C API uses "size_t" for lengths, it's defined as "i32" in Emscripten
let result_length_ptr = themisContext.libthemis!!.allocate(
new ArrayBuffer(4),
themisContext.libthemis!!.ALLOC_STACK
);
let master_key_ptr, message_ptr, context_ptr, result_ptr, result_length;
try {
master_key_ptr = heapAlloc(this.masterKey.length);
message_ptr = heapAlloc(message.length);
context_ptr = heapAlloc(context.length);
if (!master_key_ptr || !message_ptr || !context_ptr) {
throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY);
}
heapPutArray(this.masterKey, master_key_ptr);
heapPutArray(message, message_ptr);
heapPutArray(context, context_ptr);
status = themisContext.libthemis!!._themis_secure_cell_decrypt_seal(
master_key_ptr,
this.masterKey.length,
context_ptr,
context.length,
message_ptr,
message.length,
null,
result_length_ptr
);
if (status != ThemisErrorCode.BUFFER_TOO_SMALL) {
throw new ThemisError(cryptosystem_name, status);
}
result_length = themisContext.libthemis!!.getValue(
result_length_ptr,
"i32"
);
result_ptr = heapAlloc(result_length);
if (!result_ptr) {
throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY);
}
status = themisContext.libthemis!!._themis_secure_cell_decrypt_seal(
master_key_ptr,
this.masterKey.length,
context_ptr,
context.length,
message_ptr,
message.length,
result_ptr,
result_length_ptr
);
if (status != ThemisErrorCode.SUCCESS) {
throw new ThemisError(cryptosystem_name, status);
}
result_length = themisContext.libthemis!!.getValue(
result_length_ptr,
"i32"
);
return heapGetArray(result_ptr, result_length);
} finally {
heapFree(master_key_ptr, this.masterKey.length);
heapFree(message_ptr, message.length);
heapFree(context_ptr, context.length);
heapFree(result_ptr, result_length);
}
}
}
class SecureCellSealWithPassphrase extends SecureCellSeal {
constructor(passphrase: string) {
super(passphraseBytes(passphrase));
}
encrypt(message: Uint8Array) {
message = coerceToBytes(message);
if (message.length == 0) {
throw new ThemisError(
cryptosystem_name,
ThemisErrorCode.INVALID_PARAMETER,
"message must be not empty"
);
}
let context;
if (arguments.length > 1 && arguments[1] !== null) {
context = coerceToBytes(arguments[1]);
} else {
context = new Uint8Array();
}
let status;
/// C API uses "size_t" for lengths, it's defined as "i32" in Emscripten
let result_length_ptr = themisContext.libthemis!!.allocate(
new ArrayBuffer(4),
themisContext.libthemis!!.ALLOC_STACK
);
let master_key_ptr, message_ptr, context_ptr, result_ptr, result_length;
try {
master_key_ptr = heapAlloc(this.masterKey.length);
message_ptr = heapAlloc(message.length);
context_ptr = heapAlloc(context.length);
if (!master_key_ptr || !message_ptr || !context_ptr) {
throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY);
}
heapPutArray(this.masterKey, master_key_ptr);
heapPutArray(message, message_ptr);
heapPutArray(context, context_ptr);
status = themisContext.libthemis!!._themis_secure_cell_encrypt_seal_with_passphrase(
master_key_ptr,
this.masterKey.length,
context_ptr,
context.length,
message_ptr,
message.length,
null,
result_length_ptr
);
if (status != ThemisErrorCode.BUFFER_TOO_SMALL) {
throw new ThemisError(cryptosystem_name, status);
}
result_length = themisContext.libthemis!!.getValue(
result_length_ptr,
"i32"
);
result_ptr = heapAlloc(result_length);
if (!result_ptr) {
throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY);
}
status = themisContext.libthemis!!._themis_secure_cell_encrypt_seal_with_passphrase(
master_key_ptr,
this.masterKey.length,
context_ptr,
context.length,
message_ptr,
message.length,
result_ptr,
result_length_ptr
);
if (status != ThemisErrorCode.SUCCESS) {
throw new ThemisError(cryptosystem_name, status);
}
result_length = themisContext.libthemis!!.getValue(
result_length_ptr,
"i32"
);
return heapGetArray(result_ptr, result_length);
} finally {
heapFree(master_key_ptr, this.masterKey.length);
heapFree(message_ptr, message.length);
heapFree(context_ptr, context.length);
heapFree(result_ptr, result_length);
}
}
decrypt(message: Uint8Array) {
message = coerceToBytes(message);
if (message.length == 0) {
throw new ThemisError(
cryptosystem_name,
ThemisErrorCode.INVALID_PARAMETER,
"message must be not empty"
);
}
let context;
if (arguments.length > 1 && arguments[1] !== null) {
context = coerceToBytes(arguments[1]);
} else {
context = new Uint8Array();
}
let status;
/// C API uses "size_t" for lengths, it's defined as "i32" in Emscripten
let result_length_ptr = themisContext.libthemis!!.allocate(
new ArrayBuffer(4),
themisContext.libthemis!!.ALLOC_STACK
);
let master_key_ptr, message_ptr, context_ptr, result_ptr, result_length;
try {
master_key_ptr = heapAlloc(this.masterKey.length);
message_ptr = heapAlloc(message.length);
context_ptr = heapAlloc(context.length);
if (!master_key_ptr || !message_ptr || !context_ptr) {
throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY);
}
heapPutArray(this.masterKey, master_key_ptr);
heapPutArray(message, message_ptr);
heapPutArray(context, context_ptr);
status = themisContext.libthemis!!._themis_secure_cell_decrypt_seal_with_passphrase(
master_key_ptr,
this.masterKey.length,
context_ptr,
context.length,
message_ptr,
message.length,
null,
result_length_ptr
);
if (status != ThemisErrorCode.BUFFER_TOO_SMALL) {
throw new ThemisError(cryptosystem_name, status);
}
result_length = themisContext.libthemis!!.getValue(
result_length_ptr,
"i32"
);
result_ptr = heapAlloc(result_length);
if (!result_ptr) {
throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY);
}
status = themisContext.libthemis!!._themis_secure_cell_decrypt_seal_with_passphrase(
master_key_ptr,
this.masterKey.length,
context_ptr,
context.length,
message_ptr,
message.length,
result_ptr,
result_length_ptr
);
if (status != ThemisErrorCode.SUCCESS) {
throw new ThemisError(cryptosystem_name, status);
}
result_length = themisContext.libthemis!!.getValue(
result_length_ptr,
"i32"
);
return heapGetArray(result_ptr, result_length);
} finally {
heapFree(master_key_ptr, this.masterKey.length);
heapFree(message_ptr, message.length);
heapFree(context_ptr, context.length);
heapFree(result_ptr, result_length);
}
}
} | the_stack |
import { expect } from "chai";
import { Guid, Id64, Id64String } from "@itwin/core-bentley";
import { Box, Point3d, Range3d, Vector3d, YawPitchRollAngles } from "@itwin/core-geometry";
import {
BatchType, Code, ColorDef, defaultTileOptions, GeometryStreamBuilder, IModel, iModelTileTreeIdToString, PhysicalElementProps, PrimaryTileTreeId,
RenderSchedule,
} from "@itwin/core-common";
import {
GenericSchema, IModelDb, PhysicalModel, PhysicalObject, PhysicalPartition, RenderTimeline, SnapshotDb, SpatialCategory,
SubjectOwnsPartitionElements,
} from "../../core-backend";
import { IModelTestUtils } from "../IModelTestUtils";
let uniqueId = 0;
const defaultExtents = Range3d.fromJSON({
low: { x: -500, y: -200, z: -50 },
high: { x: 500, y: 200, z: 50 },
});
// Tile tree range is scaled+offset a bit.
function scaleSpatialRange(range: Range3d): Range3d {
const loScale = 1.0001;
const hiScale = 1.0002;
const fLo = 0.5 * (1.0 + loScale);
const fHi = 0.5 * (1.0 + hiScale);
const result = new Range3d();
range.high.interpolate(fLo, range.low, result.low);
range.low.interpolate(fHi, range.high, result.high);
return result;
}
// The tile tree range is equal to the scaled+skewed project extents translated to align with the origin of the model range.
function almostEqualRange(a: Range3d, b: Range3d): boolean {
return a.diagonal().isAlmostEqual(b.diagonal());
}
function insertPhysicalModel(db: IModelDb): Id64String {
GenericSchema.registerSchema();
const partitionProps = {
classFullName: PhysicalPartition.classFullName,
model: IModel.repositoryModelId,
parent: new SubjectOwnsPartitionElements(IModel.rootSubjectId),
code: PhysicalPartition.createCode(db, IModel.rootSubjectId, `PhysicalPartition_${(++uniqueId)}`),
};
const partitionId = db.elements.insertElement(partitionProps);
expect(Id64.isValidId64(partitionId)).to.be.true;
const model = db.models.createModel({
classFullName: PhysicalModel.classFullName,
modeledElement: { id: partitionId },
});
expect(model instanceof PhysicalModel).to.be.true;
const modelId = db.models.insertModel(model);
expect(Id64.isValidId64(modelId)).to.be.true;
return modelId;
}
function scaleProjectExtents(db: IModelDb, scale: number): Range3d {
const range = db.projectExtents.clone();
range.scaleAboutCenterInPlace(scale);
db.updateProjectExtents(range);
db.saveChanges();
return scaleSpatialRange(range);
}
describe("tile tree", () => {
let db: SnapshotDb;
let modelId: string;
let spatialElementId: string;
let renderTimelineId: string;
function makeScript(buildTimeline: (timeline: RenderSchedule.ElementTimelineBuilder) => void): RenderSchedule.ScriptProps {
const scriptBuilder = new RenderSchedule.ScriptBuilder();
const modelBuilder = scriptBuilder.addModelTimeline(modelId);
const elemBuilder = modelBuilder.addElementTimeline(spatialElementId);
buildTimeline(elemBuilder);
return scriptBuilder.finish();
}
before(() => {
const props = {
rootSubject: { name: "TileTreeTest", description: "Test purgeTileTrees" },
client: "TileTree",
globalOrigin: { x: 0, y: 0 },
projectExtents: defaultExtents,
guid: Guid.createValue(),
};
const name = `Test_${(++uniqueId)}.bim`;
db = SnapshotDb.createEmpty(IModelTestUtils.prepareOutputFile("TileTree", name), props);
modelId = insertPhysicalModel(db);
// NB: The model needs to contain at least one element with a range - otherwise tile tree will have null range.
const geomBuilder = new GeometryStreamBuilder();
geomBuilder.appendGeometry(Box.createDgnBox(Point3d.createZero(), Vector3d.unitX(), Vector3d.unitY(), new Point3d(0, 0, 2), 2, 2, 2, 2, true)!);
const category = SpatialCategory.insert(db, IModel.dictionaryId, "kittycat", { color: ColorDef.white.toJSON(), transp: 0, invisible: false });
const elemProps: PhysicalElementProps = {
classFullName: PhysicalObject.classFullName,
model: modelId,
category,
code: Code.createEmpty(),
userLabel: "blah",
geom: geomBuilder.geometryStream,
placement: {
origin: Point3d.create(1, 1, 1),
angles: YawPitchRollAngles.createDegrees(0, 0, 0),
},
};
spatialElementId = db.elements.insertElement(elemProps);
const script = makeScript((timeline) => timeline.addVisibility(1234, 0.5));
const renderTimeline = RenderTimeline.fromJSON({
script: JSON.stringify(script),
classFullName: RenderTimeline.classFullName,
model: IModel.dictionaryId,
code: Code.createEmpty(),
}, db);
renderTimelineId = db.elements.insertElement(renderTimeline);
expect(Id64.isValid(renderTimelineId)).to.be.true;
});
after(() => {
db.close();
});
afterEach(() => {
db.nativeDb.purgeTileTrees(undefined);
});
it("should update after changing project extents and purging", async () => {
// "_x-" holds the flags - 0 = don't use project extents as basis of tile tree range; 1 = use them.
let treeId = `8_0-${modelId}`;
let tree = await db.tiles.requestTileTreeProps(treeId);
expect(tree).not.to.be.undefined;
expect(tree.id).to.equal(treeId);
expect(tree.contentIdQualifier).to.be.undefined;
const skewedDefaultExtents = scaleSpatialRange(defaultExtents);
let range = Range3d.fromJSON(tree.rootTile.range);
expect(almostEqualRange(range, skewedDefaultExtents)).to.be.false;
treeId = `8_1-${modelId}`;
tree = await db.tiles.requestTileTreeProps(treeId);
range = Range3d.fromJSON(tree.rootTile.range);
expect(range.isNull).to.be.false;
expect(almostEqualRange(range, skewedDefaultExtents)).to.be.true;
expect(tree.contentRange).not.to.be.undefined;
expect(tree.rootTile.contentRange).to.be.undefined;
expect(tree.rootTile.isLeaf).to.be.false;
expect(tree.contentIdQualifier).not.to.be.undefined;
let prevQualifier = tree.contentIdQualifier;
// Change the project extents - nothing should change - we haven't yet purged our model's tile tree.
let newExtents = scaleProjectExtents(db, 2.0);
tree = await db.tiles.requestTileTreeProps(treeId);
expect(tree).not.to.be.undefined;
expect(tree.id).to.equal(treeId);
expect(tree.contentIdQualifier).to.equal(prevQualifier);
range = Range3d.fromJSON(tree.rootTile.range);
expect(range.isNull).to.be.false;
expect(almostEqualRange(range, skewedDefaultExtents)).to.be.true;
expect(almostEqualRange(range, newExtents)).to.be.false;
expect(tree.contentRange).not.to.be.undefined;
expect(tree.rootTile.contentRange).to.be.undefined;
expect(tree.rootTile.isLeaf).to.be.false;
// Purge tile trees for a specific (non-existent) model - still nothing should change for our model.
db.nativeDb.purgeTileTrees(["0x123abc"]);
tree = await db.tiles.requestTileTreeProps(treeId);
expect(tree).not.to.be.undefined;
expect(tree.id).to.equal(treeId);
expect(tree.contentIdQualifier).to.equal(prevQualifier);
range = Range3d.fromJSON(tree.rootTile.range);
expect(range.isNull).to.be.false;
expect(almostEqualRange(range, skewedDefaultExtents)).to.be.true;
expect(almostEqualRange(range, newExtents)).to.be.false;
expect(tree.contentRange).not.to.be.undefined;
expect(tree.rootTile.contentRange).to.be.undefined;
expect(tree.rootTile.isLeaf).to.be.false;
// Purge tile trees for our model - now we should get updated tile tree props.
db.nativeDb.purgeTileTrees([modelId]);
tree = await db.tiles.requestTileTreeProps(treeId);
expect(tree).not.to.be.undefined;
expect(tree.id).to.equal(treeId);
range = Range3d.fromJSON(tree.rootTile.range);
expect(range.isNull).to.be.false;
expect(almostEqualRange(range, skewedDefaultExtents)).to.be.false;
expect(almostEqualRange(range, newExtents)).to.be.true;
expect(tree.contentRange).not.to.be.undefined;
expect(tree.rootTile.contentRange).to.be.undefined;
expect(tree.rootTile.isLeaf).to.be.false;
expect(tree.contentIdQualifier).not.to.equal(prevQualifier);
expect(tree.contentIdQualifier).not.to.be.undefined;
prevQualifier = tree.contentIdQualifier;
// Change extents again and purge tile trees for all loaded models (by passing `undefined` for model Ids).
newExtents = scaleProjectExtents(db, 0.75);
db.nativeDb.purgeTileTrees(undefined);
tree = await db.tiles.requestTileTreeProps(treeId);
expect(tree).not.to.be.undefined;
expect(tree.id).to.equal(treeId);
range = Range3d.fromJSON(tree.rootTile.range);
expect(range.isNull).to.be.false;
expect(almostEqualRange(range, skewedDefaultExtents)).to.be.false;
expect(almostEqualRange(range, newExtents)).to.be.true;
expect(tree.contentRange).not.to.be.undefined;
expect(tree.rootTile.contentRange).to.be.undefined;
expect(tree.rootTile.isLeaf).to.be.false;
expect(tree.contentIdQualifier).not.to.equal(prevQualifier);
expect(tree.contentIdQualifier).not.to.be.undefined;
});
it("should include checksum on schedule script contents", async () => {
const treeId: PrimaryTileTreeId = {
type: BatchType.Primary,
edgesRequired: false,
};
const options = { ...defaultTileOptions };
options.useProjectExtents = false;
const loadTree = async () => db.tiles.requestTileTreeProps(iModelTileTreeIdToString(modelId, treeId, options));
let tree = await loadTree();
expect(tree.contentIdQualifier).to.be.undefined;
options.useProjectExtents = true;
tree = await loadTree();
const extentsChecksum = tree.contentIdQualifier!;
expect(extentsChecksum).not.to.be.undefined;
expect(extentsChecksum.length).least(1);
options.useProjectExtents = false;
treeId.animationId = renderTimelineId;
tree = await loadTree();
const scriptChecksum = tree.contentIdQualifier!;
expect(scriptChecksum).not.to.be.undefined;
expect(scriptChecksum.length).least(1);
options.useProjectExtents = true;
tree = await loadTree();
expect(tree.contentIdQualifier).to.equal(`${scriptChecksum}${extentsChecksum}`);
});
it("should update checksum after purge when schedule script contents change", async () => {
const treeId: PrimaryTileTreeId = {
type: BatchType.Primary,
edgesRequired: false,
animationId: renderTimelineId,
};
const options = { ...defaultTileOptions };
options.useProjectExtents = false;
const tree1 = await db.tiles.requestTileTreeProps(iModelTileTreeIdToString(modelId, treeId, options));
const checksum1 = tree1.contentIdQualifier!;
expect(checksum1.length).least(1);
const renderTimeline = db.elements.getElement<RenderTimeline>(renderTimelineId);
const props = renderTimeline.toJSON();
props.script = JSON.stringify(makeScript((timeline) => timeline.addVisibility(4321, 0.25)));
db.elements.updateElement(props);
const tree2 = await db.tiles.requestTileTreeProps(iModelTileTreeIdToString(modelId, treeId, options));
expect(tree2).not.to.equal(tree1);
expect(tree2).to.deep.equal(tree1);
db.nativeDb.purgeTileTrees(undefined);
const tree3 = await db.tiles.requestTileTreeProps(iModelTileTreeIdToString(modelId, treeId, options));
expect(tree3).not.to.equal(tree2);
expect(tree3).not.to.equal(tree1);
expect(tree3.contentIdQualifier).not.to.equal(tree1.contentIdQualifier);
expect(tree3.contentIdQualifier!.length).least(1);
});
}); | the_stack |
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import 'rxjs/add/operator/toPromise';
import * as _ from 'lodash';
import { environment } from '../../environments/environment';
import { handleError, parseJson, packageForPost } from './http-helpers';
import { AdminService } from './admin.service';
import { Conference, TimeSlot } from './conference.model';
import { Session } from './session.model';
@Injectable()
export class SessionService {
baseUrl = environment.production ? '' : 'http://localhost:3000';
// All sessions with no filtering
sessionsUnfiltered: BehaviorSubject<Session[]> = new BehaviorSubject([]);
// All sessions filtered by association with current active conf (aka active sessions)
sessionsActive: BehaviorSubject<Session[]> = new BehaviorSubject([]);
// Active sessions filtered by completion
sessionsCompleted: BehaviorSubject<Session[]> = new BehaviorSubject([]);
sessionsNotDone: BehaviorSubject<Session[]> = new BehaviorSubject([]);
// Completed active sessions filtered by approval
sessionsPending: BehaviorSubject<Session[]> = new BehaviorSubject([]);
sessionsApproved: BehaviorSubject<Session[]> = new BehaviorSubject([]);
sessionsDenied: BehaviorSubject<Session[]> = new BehaviorSubject([]);
// Approved session filters
sessionsApprovedUnscheduled: BehaviorSubject<Session[]> = new BehaviorSubject([]);
constructor(private http: Http,
private adminService: AdminService) {
// Trigger session update when requested
this.adminService.triggerSessionUpdate.subscribe(e => {
this.getAllSessions();
});
}
getAllSessions() {
return this.http
.get(this.baseUrl + '/api/getallsessions')
.toPromise()
.then(parseJson)
.then(allSessions => {
this.sessionsUnfiltered.next(allSessions);
this.setFilterAndSort();
})
.catch(handleError);
}
getSpeakerSessions(speakerId) {
return _.filter(this.sessionsUnfiltered.getValue(), session => {
if (!session.speakers) {
return false;
}
if (session.speakers.mainPresenter === speakerId) {
return true;
}
if (session.speakers.coPresenters) {
for (let i = 0; i < session.speakers.coPresenters.length; i++) {
if (session.speakers.coPresenters[i] === speakerId) {
return true;
}
}
}
return false;
});
}
/** Update session display filters */
setFilterAndSort() {
let unfilteredCopy = this.sessionsUnfiltered.getValue();
let sortedUnfiltered: Session[];
sortedUnfiltered = _.sortBy(unfilteredCopy, session => session.title);
let defaultConf = this.adminService.defaultConference.getValue().title;
this.sessionsActive.next(_.filter(sortedUnfiltered, session => session.associatedConf === defaultConf && session.approval !== 'denied'));
this.sessionsDenied.next(_.filter(sortedUnfiltered, session => session.associatedConf === defaultConf && session.approval === 'denied'));
this.sessionsCompleted.next(_.filter(this.sessionsActive.getValue(), session => session.sessionComplete));
this.sessionsNotDone.next(_.filter(this.sessionsActive.getValue(), session => !session.sessionComplete));
this.sessionsPending.next(_.filter(this.sessionsCompleted.getValue(), session => session.approval === 'pending'));
this.sessionsApproved.next(_.filter(this.sessionsCompleted.getValue(), session => session.approval === 'approved'));
this.sessionsApprovedUnscheduled.next(_.filter(this.sessionsApproved.getValue(), session => session.statusTimeLocation.length < 1));
this.sessionsUnfiltered.next(sortedUnfiltered);
}
/** Find the session assigned to room and timeslot, if any
* @returns The session and which part for 2-parters
*/
findSession(slot: TimeSlot, room: string) {
if (!slot._id) {
return;
}
let part = '';
let session = _.find(this.sessionsUnfiltered.getValue(), session => {
// Skip sessions that haven't been assigned
if (!session.statusTimeLocation || session.statusTimeLocation.length < 1) {
return false;
}
let sameSlotAndRoom = false;
session.statusTimeLocation.forEach(sessionOccurence => {
if (sessionOccurence.timeSlot === slot._id
&& sessionOccurence.room === room) {
sameSlotAndRoom = true;
part = sessionOccurence.part;
}
});
return sameSlotAndRoom;
});
return {session: session, part: part};
}
/** Get the session with a known id */
getSession(sessionId: string) {
return _.find(this.sessionsUnfiltered.getValue(), session => session._id === sessionId );
}
/** Assign a session to a slot and room and remove overlap if needed */
setSession(slot: TimeSlot, room: string, sessionId: string, part: string) {
let session = this.getSession(sessionId);
// Active conf is the conference schedule being viewed in calendar.
let activeConf = this.adminService.activeConference.getValue();
// Default conf is the current year conference that can be modified.
let defaultConf = this.adminService.defaultConference.getValue();
// Can't change a conference schedule from an old year
if (activeConf.title !== defaultConf.title) {
return Promise.resolve({ errMsg: 'Can\'t change a historic conference.' });
}
// Check for sessions already in requested slot before adding new
let slotOccupied = this.isSlotOccupied(slot, room);
if (slotOccupied) {
return Promise.resolve({occupied: true});
} else {
if (!session.statusTimeLocation) {
session.statusTimeLocation = [];
}
if (this.isSessionInTimeslot(slot, session)) {
return Promise.resolve({alreadyScheduled: true});
}
let newOccurence = {
conferenceTitle: defaultConf.title,
timeSlot: slot._id,
part: part,
room: room
};
session.statusTimeLocation.push(newOccurence);
return this.updateSession(session, 'slots');
}
}
isSlotOccupied(slot: TimeSlot, room: string) {
let sessionInRequestedSlot = this.findSession(slot, room).session;
return typeof sessionInRequestedSlot !== 'undefined';
}
/** Returns true if session is already scheduled for a room in a timeslot */
isSessionInTimeslot(slot: TimeSlot, session: Session) {
let isInSlot = false;
session.statusTimeLocation.forEach(occurrence => {
if (occurrence.timeSlot === slot._id) {
isInSlot = true;
}
});
return isInSlot;
}
/** Unschedule a session from a time/room slot
*/
clearSlot(slot: TimeSlot, room: string) {
let session = this.findSession(slot, room).session;
// Active conf is the conference schedule being viewed in calendar.
let activeConf = this.adminService.activeConference.getValue();
// Default conf is the current year conference that can be modified.
let defaultConf = this.adminService.defaultConference.getValue();
// Can't change a conference schedule from an old year
if (activeConf.title !== defaultConf.title) {
return Promise.resolve({errMsg: 'Can\'t change a historic conference.'});
}
if (typeof session !== 'undefined' && session) {
let occurenceToRemoveIndex;
session.statusTimeLocation.forEach((sessionOccurence, index, arr) => {
if (sessionOccurence.timeSlot === slot._id && sessionOccurence.room === room) {
occurenceToRemoveIndex = index;
}
});
session.statusTimeLocation.splice(occurenceToRemoveIndex, 1);
return this.updateSession(session, 'slots');
} else {
return Promise.resolve('No scheduled session');
}
}
/** Unschedule a session from a time/room slot
*/
clearSlotSession(slot: TimeSlot, room: string) {
let session = this.findSession(slot, room).session;
if (typeof session !== 'undefined' && session) {
let occurenceToRemoveIndex;
session.statusTimeLocation.forEach((sessionOccurence, index, arr) => {
if (sessionOccurence.timeSlot === slot._id && sessionOccurence.room === room) {
occurenceToRemoveIndex = index;
}
});
session.statusTimeLocation.splice(occurenceToRemoveIndex, 1);
return this.updateSession(session, 'slots');
} else {
return Promise.resolve('No scheduled session');
}
}
assignSpeaker(speakerId: string, isLead: boolean, sessionId) {
let session = this.getSession(sessionId);
if (session.speakers) {
if (isLead) {
session.speakers.mainPresenter = speakerId;
} else {
let duplicate = false;
session.speakers.coPresenters.forEach(coPresId => {
if (coPresId === speakerId) {
duplicate = true;
}
});
if (!duplicate) {
session.speakers.coPresenters.push(speakerId);
} else {
return Promise.resolve({message: 'duplicate'});
}
}
} else {
session.speakers = {
mainPresenter: '',
coPresenters: []
};
if (isLead) {
session.speakers.mainPresenter = speakerId;
} else {
session.speakers.coPresenters.push(speakerId);
}
}
return this.updateSession(session, 'speakers');
}
removeSpeaker(speakerId: string, sessionId: string) {
let session = this.getSession(sessionId);
if (session.speakers.mainPresenter === speakerId) {
session.speakers.mainPresenter = '';
} else {
let coPresenters = session.speakers.coPresenters;
for (let i = 0; i < coPresenters.length; i++) {
if (coPresenters[i] === speakerId) {
session.speakers.coPresenters.splice(i, 1);
break;
}
}
}
return this.updateSession(session, 'speakers');
}
deleteTimeSlot(date: string, confTitle: string, slot: TimeSlot) {
let conf = _.find(this.adminService.allConferences, conf => conf.title === confTitle);
let confDate = _.find(conf.days, day => day.date === date);
// Sync front end
let slotIndex = _.findIndex(confDate.timeSlots, existSlot => existSlot._id === slot._id);
if (this.slotHasScheduledSessions(conf, confDate, slotIndex)) {
return Promise.resolve({message: 'slot has sessions'});
}
confDate.timeSlots.splice(slotIndex, 1);
let pkg = packageForPost(conf);
return this.http
.post(this.baseUrl + '/api/deletetimeslot', pkg.body, pkg.opts)
.toPromise()
.then(parseJson)
.catch(handleError);
}
slotHasScheduledSessions(conf: Conference,
confDate: {date: string, timeSlots: TimeSlot[]},
slotIndex: number): boolean {
let slot = confDate.timeSlots[slotIndex];
let sessions = this.sessionsUnfiltered.getValue();
let hasScheduledSession = false;
sessions.forEach(session => {
session.statusTimeLocation.forEach(occurrence => {
if (occurrence.timeSlot === slot._id) {
hasScheduledSession = true;
}
});
});
return hasScheduledSession;
}
deleteRoom(conferenceTitle: string, room: string) {
let conf = _.find(this.adminService.allConferences, conf => conf.title === conferenceTitle);
if (this.roomHasScheduledSessions(conf, room)) {
return Promise.resolve({message: 'room has sessions'});
}
conf.rooms.splice(conf.rooms.indexOf(room), 1);
let pkg = packageForPost(conf);
return this.http
.post(this.baseUrl + '/api/deleteRoom', pkg.body, pkg.opts)
.toPromise()
.then(parseJson)
.catch(handleError);
}
roomHasScheduledSessions(conf: Conference, room: string): boolean {
let sessions = this.sessionsUnfiltered.getValue();
let hasScheduledSession = false;
sessions.forEach(session => {
session.statusTimeLocation.forEach(occurrence => {
if (occurrence.room === room) {
hasScheduledSession = true;
}
});
});
return hasScheduledSession;
}
// approval: string, // pending (default), approved, denied (by brooke)
changeApproval(session: Session, approval: string) {
session.approval = approval;
return this.updateSession(session, null, 'approval');
}
changeAssociatedConf(session: Session, conferenceTitle: string) {
session.associatedConf = conferenceTitle;
return this.updateSession(session);
}
deleteSession(session: Session) {
const serverUrl = this.baseUrl + '/api/deletesession';
const pkg = packageForPost(session);
return this.http
.post(serverUrl, pkg.body, pkg.opts)
.toPromise()
.then(parseJson)
.catch(handleError);
}
/** Update new session on server and sync response with front end
* @updateType Different server endpoints for speaker and slot updates
*/
updateSession(session: Session, updateType?: string, alert?: string) {
let serverUrl = this.baseUrl + '/api/updatesession';
if (updateType) {
serverUrl += updateType;
}
let pkg = packageForPost(session);
return this.http
.post(serverUrl, pkg.body, pkg.opts)
.toPromise()
.then(parseJson)
.then(serverSession => {
let newSessions = this.sessionsUnfiltered.getValue();
let existingSession = _.find(newSessions, exSession => exSession._id === serverSession._id);
if (typeof existingSession === 'undefined') {
newSessions.push(serverSession);
} else {
existingSession = serverSession;
}
this.sessionsUnfiltered.next(newSessions);
this.setFilterAndSort();
if (alert) {
if (alert === 'approval') {
this.adminService.triggerSpeakerUpdate.emit('update');
}
}
return serverSession;
})
.catch(handleError);
}
} | the_stack |
import { Config } from "../index";
import {
CLASS_DRAG_IMAGE, CLASS_DRAG_OPERATION_ICON, CLASS_PREFIX, DROP_EFFECT, DROP_EFFECTS
} from "./constants";
import {
addDocumentListener, applyDragImageSnapback, extractTransformStyles, isDOMElement,
isTouchIdentifierContainedInTouchEvent, Point, removeDocumentListener, translateElementToPoint,
updateCentroidCoordinatesOfTouchesIn
} from "./dom-utils";
import { DataTransfer, DragDataStore, DragDataStoreMode } from "./drag-data-store";
import { determineDragOperation, determineDropEffect, dispatchDragEvent } from "./drag-utils";
/**
* For tracking the different states of a drag operation.
*/
export const enum DragOperationState {
// initial state of a controller, if no movement is detected the operation ends with this state
POTENTIAL,
// after movement is detected the drag operation starts and keeps this state until it ends
STARTED,
// when the drag operation ended normally
ENDED,
// when the drag operation ended with a cancelled input event
CANCELLED
}
/**
* Aims to implement the HTML5 d'n'd spec (https://html.spec.whatwg.org/multipage/interaction.html#dnd) as close as it can get.
* Note that all props that are private should start with an underscore to enable better minification.
*
* TODO remove lengthy spec comments in favor of short references to the spec
*/
export class DragOperationController {
private _dragOperationState:DragOperationState = DragOperationState.POTENTIAL;
private _dragImage:HTMLElement;
private _dragImageTransforms:string[];
private _dragImagePageCoordinates:Point; // the current page coordinates of the dragImage
private _dragImageOffset:Point; // offset of the drag image relative to the coordinates
private _currentHotspotCoordinates:Point; // the point relative to viewport for determining the immediate user selection
private _immediateUserSelection:HTMLElement = null; // the element the user currently hovers while dragging
private _currentDropTarget:HTMLElement = null; // the element that was selected as a valid drop target by the d'n'd operation
private _dragDataStore:DragDataStore;
private _dataTransfer:DataTransfer;
private _currentDragOperation:string; // the current drag operation set according to the d'n'd processing model
private _initialTouch:Touch; // the identifier for the touch that initiated the drag operation
private _touchMoveHandler:EventListener;
private _touchEndOrCancelHandler:EventListener;
private _lastTouchEvent:TouchEvent;
private _iterationLock:boolean;
private _iterationIntervalId:number;
constructor( private _initialEvent:TouchEvent,
private _config:Config,
private _sourceNode:HTMLElement,
private _dragOperationEndedCb:( config:Config, event:TouchEvent, state:DragOperationState ) => void ) {
console.log( "dnd-poly: setting up potential drag operation.." );
this._lastTouchEvent = _initialEvent;
this._initialTouch = _initialEvent.changedTouches[ 0 ];
// create bound event listeners
this._touchMoveHandler = this._onTouchMove.bind( this );
this._touchEndOrCancelHandler = this._onTouchEndOrCancel.bind( this );
addDocumentListener( "touchmove", this._touchMoveHandler, false );
addDocumentListener( "touchend", this._touchEndOrCancelHandler, false );
addDocumentListener( "touchcancel", this._touchEndOrCancelHandler, false );
// the only thing we do is setup the touch listeners. if drag will really start is decided in touch move handler.
//<spec>
// THIS IS SKIPPED SINCE SUPPORT IS ONLY AVAILABLE FOR DOM ELEMENTS
// 3. Establish which DOM node is the source node, as follows:
// If it is a selection that is being dragged, then the source node is the text node that the user started the drag on (typically the text node
// that the user originally clicked). If the user did not specify a particular node, for example if the user just told the user agent to begin
// a drag of "the selection", then the source node is the first text node containing a part of the selection. Otherwise, if it is an element
// that is being dragged, then the source node is the element that is being dragged. Otherwise, the source node is part of another document or
// application. When this specification requires that an event be dispatched at the source node in this case, the user agent must instead
// follow the platform-specific conventions relevant to that situation.
// THIS IS SKIPPED SINCE SUPPORT IS ONLY AVAILABLE FOR DOM ELEMENTS
// 4. Determine the list of dragged nodes, as follows:
// If it is a selection that is being dragged, then the list of dragged nodes contains, in tree order, every node that is partially or
// completely included in the selection (including all their ancestors).
// Otherwise, the list of dragged nodes contains only the source node, if any.
// THIS IS SKIPPED SINCE SUPPORT IS ONLY AVAILABLE FOR DOM ELEMENTS
// 5. If it is a selection that is being dragged, then add an item to the drag data store item list, with its properties set as follows:
//The drag data item type string
//"text/plain"
//The drag data item kind
//Plain Unicode string
//The actual data
//The text of the selection
//Otherwise, if any files are being dragged, then add one item per file to the drag data store item list, with their properties set as follows:
//
//The drag data item type string
//The MIME type of the file, if known, or "application/octet-stream" otherwise.
// The drag data item kind
//File
//The actual data
//The file's contents and name.
//Dragging files can currently only happen from outside a browsing context, for example from a file system manager application.
//
// If the drag initiated outside of the application, the user agent must add items to the drag data store item list as appropriate for the data
// being dragged, honoring platform conventions where appropriate; however, if the platform conventions do not use MIME types to label dragged
// data, the user agent must make a best-effort attempt to map the types to MIME types, and, in any case, all the drag data item type strings must
// be converted to ASCII lowercase. Perform drag-and-drop initialization steps defined in any other applicable specifications.
//</spec>
}
//<editor-fold desc="setup/teardown">
/**
* Setup dragImage, input listeners and the drag
* and drop process model iteration interval.
*/
private _setup():boolean {
console.log( "dnd-poly: starting drag and drop operation" );
this._dragOperationState = DragOperationState.STARTED;
this._currentDragOperation = DROP_EFFECTS[ DROP_EFFECT.NONE ];
this._dragDataStore = {
data: {},
effectAllowed: undefined,
mode: DragDataStoreMode.PROTECTED,
types: [],
};
this._currentHotspotCoordinates = {
x: null,
y: null
};
this._dragImagePageCoordinates = {
x: null,
y: null
};
let dragImageSrc:HTMLElement = this._sourceNode;
this._dataTransfer = new DataTransfer( this._dragDataStore, ( element:HTMLElement, x:number, y:number ) => {
dragImageSrc = element;
if( typeof x === "number" || typeof y === "number" ) {
this._dragImageOffset = {
x: x || 0,
y: y || 0
};
}
} );
// 9. Fire a DND event named dragstart at the source node.
this._dragDataStore.mode = DragDataStoreMode.READWRITE;
this._dataTransfer.dropEffect = DROP_EFFECTS[ DROP_EFFECT.NONE ];
if( dispatchDragEvent( "dragstart", this._sourceNode, this._lastTouchEvent, this._dragDataStore, this._dataTransfer ) ) {
console.log( "dnd-poly: dragstart cancelled" );
// dragstart has been prevented -> cancel d'n'd
this._dragOperationState = DragOperationState.CANCELLED;
this._cleanup();
return false;
}
updateCentroidCoordinatesOfTouchesIn( "page", this._lastTouchEvent, this._dragImagePageCoordinates );
const dragImage = this._config.dragImageSetup( dragImageSrc );
this._dragImageTransforms = extractTransformStyles( dragImage );
// set layout styles for freely moving it around
dragImage.style.position = "absolute";
dragImage.style.left = "0px";
dragImage.style.top = "0px";
// on top of all
dragImage.style.zIndex = "999999";
// add polyfill class for default styling
dragImage.classList.add( CLASS_DRAG_IMAGE );
dragImage.classList.add( CLASS_DRAG_OPERATION_ICON );
this._dragImage = dragImage;
if( !this._dragImageOffset ) {
// apply specific offset
if( this._config.dragImageOffset ) {
this._dragImageOffset = {
x: this._config.dragImageOffset.x,
y: this._config.dragImageOffset.y
};
}
// center drag image on touch coordinates
else if( this._config.dragImageCenterOnTouch ) {
const cs = getComputedStyle( dragImageSrc );
this._dragImageOffset = {
x: 0 - parseInt( cs.marginLeft, 10 ),
y: 0 - parseInt( cs.marginTop, 10 )
};
}
// by default initialize drag image offset the same as desktop
else {
const targetRect = dragImageSrc.getBoundingClientRect();
const cs = getComputedStyle( dragImageSrc );
this._dragImageOffset = {
x: targetRect.left - this._initialTouch.clientX - parseInt( cs.marginLeft, 10 ) + targetRect.width / 2,
y: targetRect.top - this._initialTouch.clientY - parseInt( cs.marginTop, 10 ) + targetRect.height / 2
};
}
}
translateElementToPoint( this._dragImage, this._dragImagePageCoordinates, this._dragImageTransforms, this._dragImageOffset, this._config.dragImageCenterOnTouch );
document.body.appendChild( this._dragImage );
// 10. Initiate the drag-and-drop operation in a manner consistent with platform conventions, and as described below.
this._iterationIntervalId = window.setInterval( () => {
// If the user agent is still performing the previous iteration of the sequence (if any) when the next iteration becomes due,
// abort these steps for this iteration (effectively "skipping missed frames" of the drag-and-drop operation).
if( this._iterationLock ) {
console.log( "dnd-poly: iteration skipped because previous iteration hast not yet finished." );
return;
}
this._iterationLock = true;
this._dragAndDropProcessModelIteration();
this._iterationLock = false;
}, this._config.iterationInterval );
return true;
}
private _cleanup() {
console.log( "dnd-poly: cleanup" );
if( this._iterationIntervalId ) {
clearInterval( this._iterationIntervalId );
this._iterationIntervalId = null;
}
removeDocumentListener( "touchmove", this._touchMoveHandler );
removeDocumentListener( "touchend", this._touchEndOrCancelHandler );
removeDocumentListener( "touchcancel", this._touchEndOrCancelHandler );
if( this._dragImage ) {
this._dragImage.parentNode.removeChild( this._dragImage );
this._dragImage = null;
}
this._dragOperationEndedCb( this._config, this._lastTouchEvent, this._dragOperationState );
}
//</editor-fold>
//<editor-fold desc="touch handlers">
private _onTouchMove( event:TouchEvent ) {
// filter unrelated touches
if( isTouchIdentifierContainedInTouchEvent( event, this._initialTouch.identifier ) === false ) {
return;
}
// update the reference to the last received touch event
this._lastTouchEvent = event;
// drag operation did not start yet but on movement it should start
if( this._dragOperationState === DragOperationState.POTENTIAL ) {
let startDrag:boolean;
// is a lifecycle hook present?
if( this._config.dragStartConditionOverride ) {
try {
startDrag = this._config.dragStartConditionOverride( event );
}
catch( e ) {
console.error( "dnd-poly: error in dragStartConditionOverride hook: " + e );
startDrag = false;
}
}
else {
// by default only allow a single moving finger to initiate a drag operation
startDrag = (event.touches.length === 1);
}
if( !startDrag ) {
this._cleanup();
return;
}
// setup will return true when drag operation starts
if( this._setup() === true ) {
// prevent scrolling when drag operation starts
this._initialEvent.preventDefault();
event.preventDefault();
}
return;
}
console.log( "dnd-poly: moving draggable.." );
// we emulate d'n'd so we dont want any defaults to apply
event.preventDefault();
// populate shared coordinates from touch event
updateCentroidCoordinatesOfTouchesIn( "client", event, this._currentHotspotCoordinates );
updateCentroidCoordinatesOfTouchesIn( "page", event, this._dragImagePageCoordinates );
if( this._config.dragImageTranslateOverride ) {
try {
let handledDragImageTranslate = false;
this._config.dragImageTranslateOverride(
event,
{
x: this._currentHotspotCoordinates.x,
y: this._currentHotspotCoordinates.y
},
this._immediateUserSelection,
( offsetX:number, offsetY:number ) => {
// preventing translation of drag image when there was a drag operation cleanup meanwhile
if( !this._dragImage ) {
return;
}
handledDragImageTranslate = true;
this._currentHotspotCoordinates.x += offsetX;
this._currentHotspotCoordinates.y += offsetY;
this._dragImagePageCoordinates.x += offsetX;
this._dragImagePageCoordinates.y += offsetY;
translateElementToPoint(
this._dragImage,
this._dragImagePageCoordinates,
this._dragImageTransforms,
this._dragImageOffset,
this._config.dragImageCenterOnTouch
);
}
);
if( handledDragImageTranslate ) {
return;
}
}
catch( e ) {
console.log( "dnd-poly: error in dragImageTranslateOverride hook: " + e );
}
}
translateElementToPoint( this._dragImage, this._dragImagePageCoordinates, this._dragImageTransforms, this._dragImageOffset, this._config.dragImageCenterOnTouch );
}
private _onTouchEndOrCancel( event:TouchEvent ) {
// filter unrelated touches
if( isTouchIdentifierContainedInTouchEvent( event, this._initialTouch.identifier ) === false ) {
return;
}
// let the dragImageTranslateOverride know that its over
if( this._config.dragImageTranslateOverride ) {
try {
/* tslint:disable */
this._config.dragImageTranslateOverride( undefined, undefined, undefined, function() {
} );
}
catch( e ) {
console.log( "dnd-poly: error in dragImageTranslateOverride hook: " + e );
}
}
// drag operation did not even start
if( this._dragOperationState === DragOperationState.POTENTIAL ) {
this._cleanup();
return;
}
// we emulate d'n'd so we dont want any defaults to apply
event.preventDefault();
this._dragOperationState = (event.type === "touchcancel") ? DragOperationState.CANCELLED : DragOperationState.ENDED;
}
//</editor-fold>
//<editor-fold desc="dnd spec logic">
/**
* according to https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model
*/
private _dragAndDropProcessModelIteration():void {
// if( DEBUG ) {
// var debug_class = CLASS_PREFIX + "debug",
// debug_class_user_selection = CLASS_PREFIX + "immediate-user-selection",
// debug_class_drop_target = CLASS_PREFIX + "current-drop-target";
// }
const previousDragOperation = this._currentDragOperation;
// Fire a DND event named drag event at the source node.
this._dragDataStore.mode = DragDataStoreMode.PROTECTED;
this._dataTransfer.dropEffect = DROP_EFFECTS[ DROP_EFFECT.NONE ];
const dragCancelled = dispatchDragEvent( "drag", this._sourceNode, this._lastTouchEvent, this._dragDataStore, this._dataTransfer );
if( dragCancelled ) {
console.log( "dnd-poly: drag event cancelled." );
// If this event is canceled, the user agent must set the current drag operation to "none" (no drag operation).
this._currentDragOperation = DROP_EFFECTS[ DROP_EFFECT.NONE ];
}
// Otherwise, if the user ended the drag-and-drop operation (e.g. by releasing the mouse button in a mouse-driven drag-and-drop interface),
// or if the drag event was canceled, then this will be the last iteration.
if( dragCancelled || this._dragOperationState === DragOperationState.ENDED || this._dragOperationState === DragOperationState.CANCELLED ) {
const dragFailed = this._dragOperationEnded( this._dragOperationState );
// if drag failed transition snap back
if( dragFailed ) {
applyDragImageSnapback( this._sourceNode, this._dragImage, this._dragImageTransforms, () => {
this._finishDragOperation();
} );
return;
}
// Otherwise immediately
// Fire a DND event named dragend at the source node.
this._finishDragOperation();
return;
}
// If the drag event was not canceled and the user has not ended the drag-and-drop operation,
// check the state of the drag-and-drop operation, as follows:
const newUserSelection:HTMLElement = <HTMLElement>this._config.elementFromPoint( this._currentHotspotCoordinates.x, this._currentHotspotCoordinates.y );
console.log( "dnd-poly: new immediate user selection is: " + newUserSelection );
const previousTargetElement = this._currentDropTarget;
// If the user is indicating a different immediate user selection than during the last iteration (or if this is the first iteration),
// and if this immediate user selection is not the same as the current target element,
// then fire a DND event named dragexit at the current target element,
// and then update the current target element as follows:
if( newUserSelection !== this._immediateUserSelection && newUserSelection !== this._currentDropTarget ) {
// if( DEBUG ) {
//
// if( this._immediateUserSelection ) {
// this._immediateUserSelection.classList.remove( debug_class_user_selection );
// }
//
// if( newUserSelection ) {
// newUserSelection.classList.add( debug_class );
// newUserSelection.classList.add( debug_class_user_selection );
// }
// }
this._immediateUserSelection = newUserSelection;
if( this._currentDropTarget !== null ) {
this._dragDataStore.mode = DragDataStoreMode.PROTECTED;
this._dataTransfer.dropEffect = DROP_EFFECTS[ DROP_EFFECT.NONE ];
dispatchDragEvent( "dragexit", this._currentDropTarget, this._lastTouchEvent, this._dragDataStore, this._dataTransfer, false );
}
// If the new immediate user selection is null
if( this._immediateUserSelection === null ) {
//Set the current target element to null also.
this._currentDropTarget = this._immediateUserSelection;
console.log( "dnd-poly: current drop target changed to null" );
}
// THIS IS SKIPPED SINCE SUPPORT IS ONLY AVAILABLE FOR DOM ELEMENTS
// If the new immediate user selection is in a non-DOM document or application
// else if() {
// Set the current target element to the immediate user selection.
// this.currentDropTarget = this.immediateUserSelection;
// return;
// }
// Otherwise
else {
// Fire a DND event named dragenter at the immediate user selection.
//the polyfill cannot determine if a handler even exists as browsers do to silently
// allow drop when no listener existed, so this event MUST be handled by the client
this._dragDataStore.mode = DragDataStoreMode.PROTECTED;
this._dataTransfer.dropEffect = determineDropEffect( this._dragDataStore.effectAllowed, this._sourceNode );
if( dispatchDragEvent( "dragenter", this._immediateUserSelection, this._lastTouchEvent, this._dragDataStore, this._dataTransfer ) ) {
console.log( "dnd-poly: dragenter default prevented" );
// If the event is canceled, then set the current target element to the immediate user selection.
this._currentDropTarget = this._immediateUserSelection;
this._currentDragOperation = determineDragOperation( this._dataTransfer.effectAllowed, this._dataTransfer.dropEffect );
}
// Otherwise, run the appropriate step from the following list:
else {
// NO DROPZONE SUPPORT SINCE NATIVE IMPLEMENTATIONS IN BROWSERS ALSO DO NOT
//console.log( "dnd-poly: dragenter not prevented, searching for dropzone.." );
//var newTarget = DragOperationController.FindDropzoneElement( this.immediateUserSelection );
// THIS IS SKIPPED SINCE SUPPORT IS ONLY AVAILABLE FOR DOM ELEMENTS
// If the current target element is a text field (e.g. textarea, or an input element whose type attribute is in the Text state) or an
// editable element, and the drag data store item list has an item with the drag data item type string "text/plain" and the drag data
// item kind Plain Unicode string
//if( ElementIsTextDropzone( this.immediateUserSelection, this.dragDataStore ) ) {
//Set the current target element to the immediate user selection anyway.
//this.currentDropTarget = this.immediateUserSelection;
//}
//else
// If the current target element is an element with a dropzone attribute that matches the drag data store
//if( newTarget === this.immediateUserSelection &&
// DragOperationController.GetOperationForMatchingDropzone( this.immediateUserSelection, this.dragDataStore ) !== "none" ) {
// Set the current target element to the immediate user selection anyway.
// this.currentDropTarget = this.immediateUserSelection;
//}
// If the immediate user selection is an element that itself has an ancestor element
// with a dropzone attribute that matches the drag data store
// NO DROPZONE SUPPORT SINCE NATIVE IMPLEMENTATIONS IN BROWSERS ALSO DO NOT
//else if( newTarget !== null && DragOperationController.GetOperationForMatchingDropzone( newTarget, this.dragDataStore ) ) {
// If the immediate user selection is new target, then leave the current target element unchanged.
// Otherwise, fire a DND event named dragenter at new target, with the current target element
// as the specific related target. Then, set the current target element to new target,
// regardless of whether that event was canceled or not.
//this.dragenter( newTarget, this.currentDropTarget );
//this.currentDropTarget = newTarget;
//}
// If the current target element is not the body element
//else
if( this._immediateUserSelection !== document.body ) {
// Fire a DND event named dragenter at the body element, and set the current target element to the body element, regardless of
// whether that event was canceled or not.
// Note: If the body element is null, then the event will be fired at the Document object (as
// required by the definition of the body element), but the current target element would be set to null, not the Document object.
// We do not listen to what the spec says here because this results in doubled events on the body/document because if the first one
// was not cancelled it will have bubbled up to the body already ;)
// this.dragenter( window.document.body );
this._currentDropTarget = document.body;
}
// Otherwise
//else {
// leave the current drop target unchanged
//}
}
}
}
// If the previous step caused the current target element to change,
// and if the previous target element was not null or a part of a non-DOM document,
// then fire a DND event named dragleave at the previous target element.
if( previousTargetElement !== this._currentDropTarget && (isDOMElement( previousTargetElement )) ) {
// if( DEBUG ) {
// previousTargetElement.classList.remove( debug_class_drop_target );
// }
console.log( "dnd-poly: current drop target changed." );
this._dragDataStore.mode = DragDataStoreMode.PROTECTED;
this._dataTransfer.dropEffect = DROP_EFFECTS[ DROP_EFFECT.NONE ];
dispatchDragEvent( "dragleave", previousTargetElement, this._lastTouchEvent, this._dragDataStore, this._dataTransfer, false, this._currentDropTarget );
}
// If the current target element is a DOM element, then fire a DND event named dragover at this current target element.
if( isDOMElement( this._currentDropTarget ) ) {
// if( DEBUG ) {
// this._currentDropTarget.classList.add( debug_class );
// this._currentDropTarget.classList.add( debug_class_drop_target );
// }
// If the dragover event is not canceled, run the appropriate step from the following list:
this._dragDataStore.mode = DragDataStoreMode.PROTECTED;
this._dataTransfer.dropEffect = determineDropEffect( this._dragDataStore.effectAllowed, this._sourceNode );
if( dispatchDragEvent( "dragover", this._currentDropTarget, this._lastTouchEvent, this._dragDataStore, this._dataTransfer ) === false ) {
console.log( "dnd-poly: dragover not prevented on possible drop-target." );
// NO DROPZONE SUPPORT SINCE NATIVE IMPLEMENTATIONS IN BROWSERS ALSO DO NOT
// THIS IS SKIPPED SINCE SUPPORT IS ONLY AVAILABLE FOR DOM ELEMENTS
// If the current target element is a text field (e.g. textarea, or an input element whose type attribute is in the Text state) or
// an editable element, and the drag data store item list has an item with the drag data item type string "text/plain" and the drag
// data item kind Plain Unicode string
//if( ElementIsTextDropzone( this.currentDropTarget, this.dragDataStore ) ) {
// Set the current drag operation to either "copy" or "move", as appropriate given the platform conventions.
//this.currentDragOperation = "copy"; //or move. spec says its platform specific behaviour.
//}
//else {
// If the current target element is an element with a dropzone attribute that matches the drag data store
//this.currentDragOperation = DragOperationController.GetOperationForMatchingDropzone( this.currentDropTarget, this.dragDataStore );
//}
// when dragover is not prevented and no dropzones are there, no drag operation
this._currentDragOperation = DROP_EFFECTS[ DROP_EFFECT.NONE ];
}
// Otherwise (if the dragover event is canceled), set the current drag operation based on the values of the effectAllowed and
// dropEffect attributes of the DragEvent object's dataTransfer object as they stood after the event dispatch finished
else {
console.log( "dnd-poly: dragover prevented." );
this._currentDragOperation = determineDragOperation( this._dataTransfer.effectAllowed, this._dataTransfer.dropEffect );
}
}
console.log( "dnd-poly: d'n'd iteration ended. current drag operation: " + this._currentDragOperation );
// THIS IS SKIPPED SINCE SUPPORT IS ONLY AVAILABLE FOR DOM ELEMENTS
// Otherwise, if the current target element is not a DOM element, use platform-specific mechanisms to determine what drag operation is
// being performed (none, copy, link, or move), and set the current drag operation accordingly.
//Update the drag feedback (e.g. the mouse cursor) to match the current drag operation, as follows:
// ---------------------------------------------------------------------------------------------------------
// Drag operation | Feedback
// "copy" | Data will be copied if dropped here.
// "link" | Data will be linked if dropped here.
// "move" | Data will be moved if dropped here.
// "none" | No operation allowed, dropping here will cancel the drag-and-drop operation.
// ---------------------------------------------------------------------------------------------------------
if( previousDragOperation !== this._currentDragOperation ) {
this._dragImage.classList.remove( CLASS_PREFIX + previousDragOperation );
}
const currentDragOperationClass = CLASS_PREFIX + this._currentDragOperation;
this._dragImage.classList.add( currentDragOperationClass );
}
/**
* according to https://html.spec.whatwg.org/multipage/interaction.html#drag-and-drop-processing-model
*/
private _dragOperationEnded( state:DragOperationState ):boolean {
console.log( "dnd-poly: drag operation end detected with " + this._currentDragOperation );
// if( DEBUG ) {
//
// var debug_class_user_selection = CLASS_PREFIX + "immediate-user-selection",
// debug_class_drop_target = CLASS_PREFIX + "current-drop-target";
//
// if( this._currentDropTarget ) {
// this._currentDropTarget.classList.remove( debug_class_drop_target );
//
// }
// if( this._immediateUserSelection ) {
// this._immediateUserSelection.classList.remove( debug_class_user_selection );
// }
// }
//var dropped:boolean = undefined;
// Run the following steps, then stop the drag-and-drop operation:
// If the current drag operation is "none" (no drag operation), or,
// if the user ended the drag-and-drop operation by canceling it (e.g. by hitting the Escape key), or
// if the current target element is null, then the drag operation failed.
const dragFailed = (this._currentDragOperation === DROP_EFFECTS[ DROP_EFFECT.NONE ]
|| this._currentDropTarget === null
|| state === DragOperationState.CANCELLED);
if( dragFailed ) {
// Run these substeps:
// Let dropped be false.
//dropped = false;
// If the current target element is a DOM element, fire a DND event named dragleave at it;
if( isDOMElement( this._currentDropTarget ) ) {
this._dragDataStore.mode = DragDataStoreMode.PROTECTED;
this._dataTransfer.dropEffect = DROP_EFFECTS[ DROP_EFFECT.NONE ];
dispatchDragEvent( "dragleave", this._currentDropTarget, this._lastTouchEvent, this._dragDataStore, this._dataTransfer, false );
}
// THIS IS SKIPPED SINCE SUPPORT IS ONLY AVAILABLE FOR DOM ELEMENTS
// otherwise, if it is not null, use platform-specific conventions for drag cancellation.
//else if( this.currentDropTarget !== null ) {
//}
}
// Otherwise, the drag operation was as success; run these substeps:
else {
// Let dropped be true.
//dropped = true;
// If the current target element is a DOM element, fire a DND event named drop at it;
if( isDOMElement( this._currentDropTarget ) ) {
// If the event is canceled, set the current drag operation to the value of the dropEffect attribute of the
// DragEvent object's dataTransfer object as it stood after the event dispatch finished.
this._dragDataStore.mode = DragDataStoreMode.READONLY;
this._dataTransfer.dropEffect = this._currentDragOperation;
if( dispatchDragEvent( "drop", this._currentDropTarget, this._lastTouchEvent, this._dragDataStore, this._dataTransfer ) ===
true ) {
this._currentDragOperation = this._dataTransfer.dropEffect;
}
// Otherwise, the event is not canceled; perform the event's default action, which depends on the exact target as follows:
else {
// THIS IS SKIPPED SINCE SUPPORT IS ONLY AVAILABLE FOR DOM ELEMENTS
// If the current target element is a text field (e.g. textarea, or an input element whose type attribute is in the Text state)
// or an editable element,
// and the drag data store item list has an item with the drag data item type string "text/plain"
// and the drag data item kind Plain Unicode string
//if( ElementIsTextDropzone( this.currentDropTarget, this.dragDataStore ) ) {
// Insert the actual data of the first item in the drag data store item list to have a drag data item type string of
// "text/plain" and a drag data item kind that is Plain Unicode string into the text field or editable element in a manner
// consistent with platform-specific conventions (e.g. inserting it at the current mouse cursor position, or inserting it at
// the end of the field).
//}
// Otherwise
//else {
// Reset the current drag operation to "none".
this._currentDragOperation = DROP_EFFECTS[ DROP_EFFECT.NONE ];
//}
}
}
// THIS IS SKIPPED SINCE SUPPORT IS ONLY AVAILABLE FOR DOM ELEMENTS
// otherwise, use platform-specific conventions for indicating a drop.
//else {
//}
}
return dragFailed;
// THIS IS SKIPPED SINCE SUPPORT IS ONLY AVAILABLE FOR DOM ELEMENTS
//if( this.dragend( this.sourceNode ) ) {
// return;
//}
// Run the appropriate steps from the following list as the default action of the dragend event:
//if( !dropped ) {
// return;
//}
// dropped is true
//if( this.currentDragOperation !== "move" ) {
// return;
//}
//// drag operation is move
//
//if( ElementIsTextDropzone( this.currentDropTarget ) === false ) {
// return;
//}
//// element is textfield
//
//// and the source of the drag-and-drop operation is a selection in the DOM
//if( this.sourceNode.nodeType === 1 ) {
// // The user agent should delete the range representing the dragged selection from the DOM.
//}
//// and the source of the drag-and-drop operation is a selection in a text field
//else if( this.sourceNode.nodeType === 3 ) {
// // The user agent should delete the dragged selection from the relevant text field.
//}
//// Otherwise, The event has no default action.
}
// dispatch dragend event and cleanup drag operation
private _finishDragOperation():void {
console.log( "dnd-poly: dragimage snap back transition ended" );
// Fire a DND event named dragend at the source node.
this._dragDataStore.mode = DragDataStoreMode.PROTECTED;
this._dataTransfer.dropEffect = this._currentDragOperation;
dispatchDragEvent( "dragend", this._sourceNode, this._lastTouchEvent, this._dragDataStore, this._dataTransfer, false );
// drag operation over and out
this._dragOperationState = DragOperationState.ENDED;
this._cleanup();
}
//</editor-fold>
} | the_stack |
import {
checkFilesExist,
ensureNxProject,
readJson,
runNxCommandAsync,
uniq,
updateFile,
readFile
} from '@nrwl/nx-plugin/testing';
// default 5000 is not long enough for some of our tests.
jest.setTimeout(120000)
function expectedProjectFiles(root:string) {
return [
`${root}/src/index.ts`,
`${root}/package.json`,
`${root}/tsconfig.app.json`,
`${root}/tsconfig.json`,
`${root}/readme.md`,
`${root}/database.rules.json`,
`${root}/firestore.indexes.json`,
`${root}/firestore.rules`,
`${root}/storage.rules`,
]
}
function expectedTargetFiles(root:string) {
return [
`${root}/src/index.js`,
`${root}/package.json`,
`${root}/readme.md`,
]
}
describe('nxfirebase e2e', () => {
describe('nxfirebase plugin', () => {
it('should install correctly', async (done) => {
ensureNxProject('@simondotm/nx-firebase', 'dist/packages/nx-firebase');
done();
});
});
//-----------------------------------------------------------------------------------------------
// test init generator
//-----------------------------------------------------------------------------------------------
describe('nxfirebase init generator', () => {
it('should init nxfirebase plugin', async (done) => {
await runNxCommandAsync(
`generate @simondotm/nx-firebase:init`
);
done();
});
});
//-----------------------------------------------------------------------------------------------
// test application generator
//-----------------------------------------------------------------------------------------------
const appProject = 'nxfirebase-root-app' //uniq('nxfirebase-root-app');
describe('nxfirebase application generator', () => {
describe('firebase app', () => {
it('should create nxfirebase:application', async (done) => {
//ensureNxProject('@simondotm/nx-firebase', 'dist/packages/nx-firebase');
await runNxCommandAsync(
`generate @simondotm/nx-firebase:application ${appProject}`
);
done();
});
it('should create files in the specified application directory', async (done) => {
expect(() =>
checkFilesExist(...expectedProjectFiles(`apps/${appProject}`)),
).not.toThrow();
done();
});
it('should create a project firebase config in the workspace root directory', async (done) => {
expect(() =>
checkFilesExist(
`firebase.${appProject}.json`,
`.firebaserc`,
`firebase.json`,
),
).not.toThrow();
done();
});
it('should build nxfirebase:app', async (done) => {
const result = await runNxCommandAsync(`build ${appProject}`);
expect(result.stdout).toContain('Done compiling TypeScript files');
done();
});
it('should compile files to the specified dist directory', async (done) => {
expect(() =>
checkFilesExist(...expectedTargetFiles(`dist/apps/${appProject}`)),
).not.toThrow();
done();
});
});
describe('--directory', () => {
it('should create files in the specified application directory', async (done) => {
const plugin = 'nxfirebase-subdir-app' //uniq('nxfirebase-subdir-app');
//ensureNxProject('@simondotm/nx-firebase', 'dist/packages/nx-firebase');
const result = await runNxCommandAsync(
`generate @simondotm/nx-firebase:application ${plugin} --directory subdir`
);
expect(() =>
checkFilesExist(...expectedProjectFiles(`apps/subdir/${plugin}`)),
).not.toThrow();
// creating the second firebase app should not overwrite the existing .firebaserc and firebase.json files
expect(result.stdout).toContain('firebase.json already exists in this workspace');
expect(result.stdout).toContain('.firebaserc already exists in this workspace');
done();
});
});
describe('--tags', () => {
it('should add tags to nx.json', async (done) => {
const plugin = 'nxfirebase-root-app-tags' //uniq('nxfirebase-root-app-tags');
//ensureNxProject('-', 'dist/packages/nx-firebase');
const result = await runNxCommandAsync(
`generate @simondotm/nx-firebase:application ${plugin} --tags e2etag,e2ePackage`
);
const nxJson = readJson('nx.json');
expect(nxJson.projects[plugin].tags).toEqual(['e2etag', 'e2ePackage']);
// creating the third firebase app should also not overwrite the existing .firebaserc and firebase.json files
expect(result.stdout).toContain('firebase.json already exists in this workspace');
expect(result.stdout).toContain('.firebaserc already exists in this workspace');
done();
});
});
})
//-----------------------------------------------------------------------------------------------
// test library integrations
//-----------------------------------------------------------------------------------------------
describe('nxfirebase library tests', () => {
const indexTs = `apps/${appProject}/src/index.ts`
const indexTsFile = readFile(indexTs)
let latestWorkingIndexTsFile = indexTsFile
const importMatch = `import * as functions from 'firebase-functions';`
/**
* Replace content in the application `index.ts` that matches `importMatch` with `importAddition`
* @param match - string to match in the index.ts
* @param addition - string to add after the matched line in the index.ts
*/
function addContentToIndexTs(match:string, addition:string) {
updateFile(indexTs, (content:string) => {
const replaced = content.replace(
importMatch,
`${match}\n${addition}`);
return replaced
});
}
/**
* Restore the application index.ts to initial state
*/
function resetIndexTs() {
updateFile(indexTs, (content:string) => {
return latestWorkingIndexTsFile;
});
}
//-----------------------------------------------------------------------------------------------
// test we can import a library in the workspace
//-----------------------------------------------------------------------------------------------
describe('nxfirebase generate nodelibrary', () => {
const libProject = 'nodelib' //uniq('nxfirebase-functions-app');
it('should create nodelib', async (done) => {
await runNxCommandAsync(
`generate @nrwl/node:lib ${libProject} --buildable`
);
done();
});
// add our new nodelib as an imported dependency
it('should add nodelib as an index.ts dependency', async (done) => {
const importAddition = `import * as c from '@proj/${libProject}'\nconsole.log(c.nodelib())\n`
expect(indexTsFile).toContain(importMatch);
addContentToIndexTs(importMatch, importAddition);
expect(readFile(indexTs)).toContain(importAddition);
done();
});
// rebuild app with deps
it('should build nxfirebase:app', async (done) => {
const result = await runNxCommandAsync(`build ${appProject} --with-deps`);
expect(result.stdout).toContain('Done compiling TypeScript files');
done();
});
});
//-----------------------------------------------------------------------------------------------
// test that application can import a library from a subdir in the workspace
// this uses --importPath
//-----------------------------------------------------------------------------------------------
describe('nxfirebase generate subdir nodelibrary using --importPath', () => {
const libProject = 'nodelib' //uniq('nxfirebase-functions-app');
const subDir = 'subdir'
it('should create subdir-nodelib', async (done) => {
await runNxCommandAsync(
`generate @nrwl/node:lib ${libProject} --directory ${subDir} --buildable --importPath='@proj/${subDir}-${libProject}'`
);
done();
});
// add our new subdir-nodelib as an imported dependency
it('should add subdir-nodelib as an index.ts dependency', async (done) => {
const importAddition = `import * as d from '@proj/${subDir}-${libProject}'\nconsole.log(d.subdirNodelib())\n`
const inFile = readFile(indexTs)
expect(inFile).toContain(importMatch);
latestWorkingIndexTsFile = inFile
addContentToIndexTs(importMatch, importAddition);
expect(readFile(indexTs)).toContain(importAddition);
done();
});
// rebuild app with deps
it('should build nxfirebase:app', async (done) => {
const result = await runNxCommandAsync(`build ${appProject} --with-deps`);
expect(result.stdout).toContain('Done compiling TypeScript files');
done();
});
});
//-----------------------------------------------------------------------------------------------
// test that application can import a library from a 2nd subdir in the workspace
// this uses --importPath
//-----------------------------------------------------------------------------------------------
describe('nxfirebase generate 2nd subdir nodelibrary using --importPath', () => {
const libProject = 'nodelib' //uniq('nxfirebase-functions-app');
const subDir = 'subdir'
it('should create subdir-subdir-nodelib', async (done) => {
await runNxCommandAsync(
`generate @nrwl/node:lib ${libProject} --directory ${subDir}/${subDir} --buildable --importPath='@proj/${subDir}-${subDir}-${libProject}'`
);
done();
});
// add our new subdir-subdir-nodelib as an imported dependency
it('should add subdir-subdir-nodelib as an index.ts dependency', async (done) => {
const importAddition = `import * as g from '@proj/${subDir}-${subDir}-${libProject}'\nconsole.log(g.subdirSubdirNodelib())\n`
const inFile = readFile(indexTs)
expect(inFile).toContain(importMatch);
latestWorkingIndexTsFile = inFile
addContentToIndexTs(importMatch, importAddition);
expect(readFile(indexTs)).toContain(importAddition);
done();
});
// rebuild app with deps
it('should build nxfirebase:app', async (done) => {
const result = await runNxCommandAsync(`build ${appProject} --with-deps`);
expect(result.stdout).toContain('Done compiling TypeScript files');
done();
});
});
//-----------------------------------------------------------------------------------------------
// test that the builder detects non-buildable libraries
//-----------------------------------------------------------------------------------------------
describe('nxfirebase generate non-buildable nodelibrary', () => {
const libProject = 'nonbuildablenodelib' //uniq('nxfirebase-functions-app');
it('should create nonbuildablenodelib', async (done) => {
await runNxCommandAsync(
`generate @nrwl/node:lib ${libProject}`
);
done();
});
// add our new nonbuildablenodelib as an imported dependency
it('should add nonbuildablenodelib as an index.ts dependency', async (done) => {
const importAddition = `import * as e from '@proj/${libProject}'\nconsole.log(e.nonbuildablenodelib())\n`
const inFile = readFile(indexTs)
expect(inFile).toContain(importMatch);
addContentToIndexTs(importMatch, importAddition);
expect(readFile(indexTs)).toContain(importAddition);
done();
});
// rebuild app with deps - should throw an error because the library is not buildable
it('should not build nxfirebase:app due to non buildable library', async (done) => {
const result = await runNxCommandAsync(`build ${appProject} --with-deps`, { silenceError: true });
expect(result.stderr).toContain('ERROR: Found non-buildable library');
expect(result.stderr).toContain('Firebase Application contains references to non-buildable');
done();
});
});
//-----------------------------------------------------------------------------------------------
// reset the build to be buildable again
//-----------------------------------------------------------------------------------------------
/*
describe('reset application to last working buildable state', () => {
it('should reset index.ts', async (done) => {
resetIndexTs();
expect(readFile(indexTs)).toEqual(latestWorkingIndexTsFile);
done();
});
});
*/
//-----------------------------------------------------------------------------------------------
// now try and create a subdir library without --importPath
// the app builder should warning about this
//-----------------------------------------------------------------------------------------------
describe('nxfirebase generate subdir nodelibrary without --importPath', () => {
const libProject = 'nodelib2'
const subDir = 'subdir'
it('should create subdir-nodelib2', async (done) => {
await runNxCommandAsync(
`generate @nrwl/node:lib ${libProject} --directory ${subDir} --buildable`
);
done();
});
// add our new subdir-nodelib2 as an imported dependency
it('should add subdir-nodelib2 as an index.ts dependency', async (done) => {
const importAddition = `import * as f from '@proj/${subDir}/${libProject}'\nconsole.log(f.subdirNodelib2())\n`
const inFile = readFile(indexTs)
expect(inFile).toContain(importMatch);
addContentToIndexTs(importMatch, importAddition);
expect(readFile(indexTs)).toContain(importAddition);
done();
});
// rebuild app with deps
// should throw an error because the nested library is incompatible
it('should not build nxfirebase:app due to incompatible nested library', async (done) => {
const result = await runNxCommandAsync(`build ${appProject} --with-deps`, { silenceError: true });
expect(result.stderr).toContain('ERROR: Found incompatible nested library');
expect(result.stderr).toContain('Firebase Application contains references to non-buildable');
done();
});
});
})
// test functions generator
/*
describe('nxfirebase functions generator', () => {
describe('functions schema', () => {
const plugin = uniq('nxfirebase-functions-app');
it('should create nxfirebase:functions', async (done) => {
//ensureNxProject('@simondotm/nx-firebase', 'dist/packages/nx-firebase');
await runNxCommandAsync(
`generate @simondotm/nx-firebase:functions ${plugin}`
);
done();
});
it('should build nxfirebase:functions', async (done) => {
const result = await runNxCommandAsync(`build ${plugin}`);
expect(result.stdout).toContain('Done compiling TypeScript files for library');
done();
});
});
describe('--directory', () => {
it('should create src/index.ts & package.json in the specified functions directory', async (done) => {
const plugin = uniq('nxfirebase-functions-app');
//ensureNxProject('@simondotm/nx-firebase', 'dist/packages/nx-firebase');
await runNxCommandAsync(
`generate @simondotm/nx-firebase:functions ${plugin} --directory subdir`
);
expect(() =>
checkFilesExist(`apps/subdir/${plugin}/src/index.ts`, `apps/subdir/${plugin}/package.json`),
).not.toThrow();
done();
});
});
describe('--tags', () => {
it('should add tags to nx.json', async (done) => {
const plugin = uniq('nxfirebase');
//ensureNxProject('@simondotm/nx-firebase', 'dist/packages/nx-firebase');
await runNxCommandAsync(
`generate @simondotm/nx-firebase:functions ${plugin} --tags e2etag,e2ePackage`
);
const nxJson = readJson('nx.json');
expect(nxJson.projects[plugin].tags).toEqual(['e2etag', 'e2ePackage']);
done();
});
});
});
*/
}); | the_stack |
import * as R from 'ramda';
import pickNonNil from '../util/pickNonNil';
import { logger } from '../loggers/logger';
import UserRepresentation from 'keycloak-admin/lib/defs/userRepresentation';
import { Group, isRoleSubgroup } from './group';
export interface User {
email: string;
username: string;
id?: string;
firstName?: string;
lastName?: string;
comment?: string;
gitlabId?: string;
}
interface UserEdit {
id: string;
email?: string;
username?: string;
firstName?: string;
lastName?: string;
comment?: string;
gitlabId?: string;
}
interface UserModel {
loadAllUsers: () => Promise<User[]>;
loadUserById: (id: string) => Promise<User>;
loadUserByUsername: (username: string) => Promise<User>;
loadUserByIdOrUsername: (userInput: UserEdit) => Promise<User>;
getAllGroupsForUser: (userInput: User) => Promise<Group[]>;
getAllProjectsIdsForUser: (userInput: User) => Promise<number[]>;
getUserRolesForProject: (
userInput: User,
projectId: number
) => Promise<string[]>;
addUser: (userInput: User) => Promise<User>;
updateUser: (userInput: UserEdit) => Promise<User>;
deleteUser: (id: string) => Promise<void>;
}
export class UsernameExistsError extends Error {
constructor(message: string) {
super(message);
this.name = 'UsernameExistsError';
}
}
export class UserNotFoundError extends Error {
constructor(message: string) {
super(message);
this.name = 'UserNotFoundError';
}
}
const attrLens = R.lensPath(['attributes']);
const commentLens = R.lensPath(['comment']);
const attrCommentLens = R.compose(
// @ts-ignore
attrLens,
commentLens,
R.lensPath([0])
);
export const User = (clients: {
keycloakAdminClient: any;
redisClient: any;
sqlClientPool: any;
esClient: any;
}): UserModel => {
const { keycloakAdminClient, redisClient } = clients;
const fetchGitlabId = async (user: User): Promise<string> => {
const identities = await keycloakAdminClient.users.listFederatedIdentities({
id: user.id
});
const gitlabIdentity = R.find(
R.propEq('identityProvider', 'gitlab'),
identities
);
// @ts-ignore
return R.defaultTo('', R.prop('userId', gitlabIdentity));
};
const transformKeycloakUsers = async (
keycloakUsers: UserRepresentation[]
): Promise<User[]> => {
// Map from keycloak object to user object
const users = keycloakUsers.map(
(keycloakUser: UserRepresentation): User =>
// @ts-ignore
R.pipe(
R.pick(['id', 'email', 'username', 'firstName', 'lastName']),
// @ts-ignore
R.set(commentLens, R.view(attrCommentLens, keycloakUser))
)(keycloakUser)
);
let usersWithGitlabIdFetch = [];
for (const user of users) {
usersWithGitlabIdFetch.push({
...user,
gitlabId: await fetchGitlabId(user)
});
}
return usersWithGitlabIdFetch;
};
const linkUserToGitlab = async (
user: User,
gitlabUserId: string
): Promise<void> => {
try {
// Add Gitlab Federated Identity to User
await keycloakAdminClient.users.addToFederatedIdentity({
id: user.id,
federatedIdentityId: 'gitlab',
federatedIdentity: {
identityProvider: 'gitlab',
userId: gitlabUserId,
userName: gitlabUserId // we don't map the username, instead just use the UID again
}
});
} catch (err) {
throw new Error(
`Error linking user "${user.email}" to Gitlab Federated Identity: ${err}`
);
}
};
const unlinkUserFromGitlab = async (user: User): Promise<void> => {
try {
// Remove Gitlab Federated Identity from User
await keycloakAdminClient.users.delFromFederatedIdentity({
id: user.id,
federatedIdentityId: 'gitlab'
});
} catch (err) {
if (err.response.status && err.response.status === 404) {
// No-op
} else {
throw new Error(
`Error unlinking user "${user.email}" from Gitlab Federated Identity: ${err}`
);
}
}
};
const loadUserById = async (id: string): Promise<User> => {
const keycloakUser = await keycloakAdminClient.users.findOne({
id
});
if (R.isNil(keycloakUser)) {
throw new UserNotFoundError(`User not found: ${id}`);
}
const users = await transformKeycloakUsers([keycloakUser]);
return users[0];
};
const loadUserByUsername = async (username: string): Promise<User> => {
const keycloakUsers = await keycloakAdminClient.users.find({
username
});
if (R.isEmpty(keycloakUsers)) {
throw new UserNotFoundError(`User not found: ${username}`);
}
const userId = R.pipe(
R.filter(R.propEq('username', username)),
R.path(['0', 'id'])
)(keycloakUsers);
if (R.isNil(userId)) {
throw new UserNotFoundError(`User not found: ${username}`);
}
// @ts-ignore
return await loadUserById(userId);
};
const loadUserByIdOrUsername = async (userInput: UserEdit): Promise<User> => {
if (R.prop('id', userInput)) {
return loadUserById(R.prop('id', userInput));
}
if (R.prop('username', userInput)) {
return loadUserByUsername(R.prop('username', userInput));
}
throw new Error('You must provide a user id or username');
};
const loadAllUsers = async (): Promise<User[]> => {
const keycloakUsers = await keycloakAdminClient.users.find({
max: -1
});
const users = await transformKeycloakUsers(keycloakUsers);
return users;
};
const getAllGroupsForUser = async (userInput: User): Promise<Group[]> => {
const GroupModel = Group(clients);
let groups = [];
const roleSubgroups = await keycloakAdminClient.users.listGroups({
id: userInput.id
});
for (const roleSubgroup of roleSubgroups) {
const fullRoleSubgroup = await GroupModel.loadGroupById(roleSubgroup.id);
if (!isRoleSubgroup(fullRoleSubgroup)) {
continue;
}
const roleSubgroupParent = await GroupModel.loadParentGroup(
fullRoleSubgroup
);
groups.push(roleSubgroupParent);
}
return groups;
};
const getAllProjectsIdsForUser = async (
userInput: User
): Promise<number[]> => {
const GroupModel = Group(clients);
let projects = [];
const userGroups = await getAllGroupsForUser(userInput);
for (const group of userGroups) {
const projectIds = await GroupModel.getProjectsFromGroupAndSubgroups(
group
);
projects = [...projects, ...projectIds];
}
return R.uniq(projects);
};
const getUserRolesForProject = async (
userInput: User,
projectId: number
): Promise<string[]> => {
const GroupModel = Group(clients);
const userGroups = await getAllGroupsForUser(userInput);
let roles = [];
for (const group of userGroups) {
const projectIds = await GroupModel.getProjectsFromGroupAndSubgroups(
group
);
if (projectIds.includes(projectId)) {
const groupRoles = R.pipe(
R.filter(membership =>
R.pathEq(['user', 'id'], userInput.id, membership)
),
R.pluck('role')
)(group.members);
roles = [...roles, ...groupRoles];
}
}
return R.uniq(roles);
};
const addUser = async (userInput: User): Promise<User> => {
let response: { id: string };
try {
response = await keycloakAdminClient.users.create({
...pickNonNil(
['email', 'username', 'firstName', 'lastName'],
userInput
),
enabled: true,
attributes: {
comment: [R.defaultTo('', R.prop('comment', userInput))]
}
});
} catch (err) {
if (err.response.status && err.response.status === 409) {
throw new UsernameExistsError(
`Username ${R.prop('username', userInput)} exists`
);
} else {
throw new Error(`Error creating Keycloak user: ${err.message}`);
}
}
const user = await loadUserById(response.id);
// If user has been created with a gitlabid, we map that ID to the user in Keycloak
if (R.prop('gitlabId', userInput)) {
await linkUserToGitlab(user, R.prop('gitlabId', userInput));
}
return {
...user,
gitlabId: R.prop('gitlabId', userInput)
};
};
const updateUser = async (userInput: UserEdit): Promise<User> => {
try {
await keycloakAdminClient.users.update(
{
id: userInput.id
},
{
...pickNonNil(
['email', 'username', 'firstName', 'lastName'],
userInput
),
attributes: {
comment: [R.defaultTo('', R.prop('comment', userInput))]
}
}
);
} catch (err) {
if (err.response.status && err.response.status === 404) {
throw new UserNotFoundError(`User not found: ${userInput.id}`);
} else {
throw new Error(`Error updating Keycloak user: ${err.message}`);
}
}
const user = await loadUserById(userInput.id);
// If gitlabId was passed, assume it's changed
if (R.prop('gitlabId', userInput)) {
await unlinkUserFromGitlab(user);
await linkUserToGitlab(user, R.prop('gitlabId', userInput));
}
return {
...user,
gitlabId: R.prop('gitlabId', userInput)
};
};
const deleteUser = async (id: string): Promise<void> => {
try {
await keycloakAdminClient.users.del({ id });
} catch (err) {
if (err.response.status && err.response.status === 404) {
throw new UserNotFoundError(`User not found: ${id}`);
} else {
throw new Error(`Error deleting user ${id}: ${err}`);
}
}
try {
await redisClient.deleteRedisUserCache(id);
} catch (err) {
logger.error(`Error deleting user cache ${id}: ${err}`);
}
};
return {
loadAllUsers,
loadUserById,
loadUserByUsername,
loadUserByIdOrUsername,
getAllGroupsForUser,
getAllProjectsIdsForUser,
getUserRolesForProject,
addUser,
updateUser,
deleteUser
};
}; | the_stack |
import * as path from 'path';
import * as unist from '../unistHelpers';
import * as ngHelpers from '../ngHelpers';
const includedNodeTypes = [
'root', 'paragraph', 'inlineCode', 'list', 'listItem',
'table', 'tableRow', 'tableCell', 'emphasis', 'strong',
'link', 'text'
];
let externalNameLinks;
let linkOverrides;
let ignoreLinkWords: any[];
export function processDocs(mdCache, aggData) {
initPhase(aggData, mdCache);
const pathnames = Object.keys(mdCache);
pathnames.forEach(pathname => {
updateFile(mdCache[pathname].mdOutTree, pathname, aggData);
});
}
function initPhase(aggData, mdCache) {
externalNameLinks = aggData.config.externalNameLinks;
ignoreLinkWords = aggData.config.ignoreLinkWords;
linkOverrides = {};
aggData.config.linkOverrides.forEach(override => {
linkOverrides[override.toLowerCase()] = 1;
});
aggData.docFiles = {};
aggData.nameLookup = new SplitNameLookup();
const docFilePaths = Object.keys(mdCache);
docFilePaths.forEach(docFilePath => {
const relPath = docFilePath.substring(docFilePath.indexOf('docs') + 5).replace(/\\/g, '/');
const compName = path.basename(relPath, '.md');
aggData.docFiles[compName] = relPath;
});
const classNames = Object.keys(aggData.classInfo);
classNames.forEach(currClassName => {
if (currClassName.match(/(Component|Directive|Interface|Model|Pipe|Service|Widget)$/)) {
aggData.nameLookup.addName(currClassName);
}
});
}
function updateFile(tree, pathname, aggData) {
traverseMDTree(tree);
return true;
function traverseMDTree(node) {
if (!includedNodeTypes.includes(node.type)) {
return;
}
if (node.type === 'link') {
if (node.children[0] && (
(node.children[0].type === 'inlineCode') ||
(node.children[0].type === 'text')
)) {
if (!ignoreLinkWords.includes(node.children[0].value)) {
const link = resolveTypeLink(aggData, pathname, node.children[0].value);
if (link) {
convertNodeToTypeLink(node, node.children[0].value, link);
}
}
}
} else if ((node.children) && (node.type !== 'heading')) {
node.children.forEach((child, index) => {
if ((child.type === 'text') || (child.type === 'inlineCode')) {
const newNodes = handleLinksInBodyText(aggData, pathname, child.value, child.type === 'inlineCode');
node.children.splice(index, 1, ...newNodes);
} else {
traverseMDTree(child);
}
});
}
}
}
class SplitNameNode {
children: {};
constructor(public key: string = '', public value: string = '') {
this.children = {};
}
addChild(child: SplitNameNode) {
this.children[child.key] = child;
}
}
class SplitNameMatchElement {
constructor(public node: SplitNameNode, public textPos: number) {
}
}
class SplitNameMatchResult {
constructor(public value: string, public startPos: number) {
}
}
class SplitNameMatcher {
matches: SplitNameMatchElement[];
constructor(public root: SplitNameNode) {
this.reset();
}
/* Returns all names that match when this word is added. */
nextWord(word: string, textPos: number): SplitNameMatchResult[] {
const result = [];
this.matches.push(new SplitNameMatchElement(this.root, textPos));
for (let i = this.matches.length - 1; i >= 0; i--) {
if (this.matches[i].node.children) {
const child = this.matches[i].node.children[word];
if (child) {
if (child.value) {
/* Using unshift to add the match to the array means that
* the longest matches will appear first in the array.
* User can then just use the first array element if only
* the longest match is needed.
*/
result.unshift(new SplitNameMatchResult(child.value, this.matches[i].textPos));
this.matches.splice(i, 1);
} else {
this.matches[i] = new SplitNameMatchElement(child, this.matches[i].textPos);
}
} else {
this.matches.splice(i, 1);
}
} else {
this.matches.splice(i, 1);
}
}
if (result === []) {
return null;
} else {
return result;
}
}
reset() {
this.matches = [];
}
}
class SplitNameLookup {
root: SplitNameNode;
constructor() {
this.root = new SplitNameNode();
}
addName(name: string) {
const spacedName = name.replace(/([A-Z])/g, ' $1');
const segments = spacedName.trim().toLowerCase().split(' ');
let currNode = this.root;
segments.forEach((segment, index) => {
let value = '';
if (index === (segments.length - 1)) {
value = name;
}
let childNode = currNode.children[segment];
if (!childNode) {
childNode = new SplitNameNode(segment, value);
currNode.addChild(childNode);
}
currNode = childNode;
});
}
}
class WordScanner {
separators: string;
index: number;
nextSeparator: number;
current: string;
constructor(public text: string) {
this.separators = ' \n\r\t.;:<>[]&|';
this.index = 0;
this.nextSeparator = 0;
this.next();
}
finished() {
return this.index >= this.text.length;
}
next(): void {
this.advanceIndex();
this.advanceNextSeparator();
this.current = this.text.substring(this.index, this.nextSeparator);
}
advanceNextSeparator() {
for (let i = this.index; i < this.text.length; i++) {
if (this.separators.indexOf(this.text[i]) !== -1) {
this.nextSeparator = i;
return;
}
}
this.nextSeparator = this.text.length;
}
advanceIndex() {
for (let i = this.nextSeparator; i < this.text.length; i++) {
if (this.separators.indexOf(this.text[i]) === -1) {
this.index = i;
return;
}
}
this.index = this.text.length;
}
}
function handleLinksInBodyText(aggData, docFilePath: string, text: string, wrapInlineCode: boolean = false): Node[] {
const result = [];
let currTextStart = 0;
const matcher = new SplitNameMatcher(aggData.nameLookup.root);
for (const scanner = new WordScanner(text); !scanner.finished(); scanner.next()) {
const word = scanner.current
.replace(/'s$/, '')
.replace(/^[;:,\."']+/g, '')
.replace(/[;:,\."']+$/g, '');
if (!ignoreLinkWords.includes(word)) {
let link = resolveTypeLink(aggData, docFilePath, word);
let matchStart;
if (!link) {
const match = matcher.nextWord(word.toLowerCase(), scanner.index);
if (match && match[0]) {
link = resolveTypeLink(aggData, docFilePath, match[0].value);
matchStart = match[0].startPos;
}
} else {
matchStart = scanner.index;
}
if (link) {
const linkText = text.substring(matchStart, scanner.nextSeparator);
let linkTitle;
if (wrapInlineCode) {
linkTitle = unist.makeInlineCode(linkText);
} else {
linkTitle = unist.makeText(linkText);
}
const linkNode = unist.makeLink(linkTitle, link);
const prevText = text.substring(currTextStart, matchStart);
if (prevText) {
if (wrapInlineCode) {
result.push(unist.makeInlineCode(prevText));
} else {
result.push(unist.makeText(prevText));
}
}
result.push(linkNode);
currTextStart = scanner.nextSeparator;
matcher.reset();
}
}
}
const remainingText = text.substring(currTextStart, text.length);
if (remainingText) {
if (wrapInlineCode) {
result.push(unist.makeInlineCode(remainingText));
} else {
result.push(unist.makeText(remainingText));
}
}
return result;
}
function resolveTypeLink(aggData, docFilePath, text): string {
const possTypeName = cleanTypeName(text);
if (possTypeName === 'constructor') {
return '';
}
const classInfo = aggData.classInfo[possTypeName];
if (linkOverrides[possTypeName.toLowerCase()]) {
return '';
} else if (externalNameLinks[possTypeName]) {
return externalNameLinks[possTypeName];
} else if (classInfo) {
const kebabName = ngHelpers.kebabifyClassName(possTypeName);
const possDocFile = aggData.docFiles[kebabName];
let url = fixRelSrcUrl(docFilePath, classInfo.sourcePath);
if (possDocFile) {
url = fixRelDocUrl(docFilePath, possDocFile);
}
return url;
} else {
return '';
}
}
function fixRelSrcUrl(docPath: string, srcPath: string) {
const relDocPath = docPath.substring(docPath.indexOf('docs'));
const docPathSegments = relDocPath.split(/[\\\/]/);
let dotPathPart = '';
for (let i = 0; i < (docPathSegments.length - 1); i++) {
dotPathPart += '../';
}
return dotPathPart + srcPath;
}
function fixRelDocUrl(docPathFrom: string, docPathTo: string) {
const relDocPathFrom = docPathFrom.substring(docPathFrom.indexOf('docs'));
const docPathSegments = relDocPathFrom.split(/[\\\/]/);
let dotPathPart = '';
for (let i = 0; i < (docPathSegments.length - 2); i++) {
dotPathPart += '../';
}
return dotPathPart + docPathTo;
}
function cleanTypeName(text) {
const matches = text.match(/[a-zA-Z0-9_]+<([a-zA-Z0-9_]+)(\[\])?>/);
if (matches) {
return matches[1];
} else {
return text.replace(/\[\]$/, '');
}
}
function convertNodeToTypeLink(node, text, url, title = null) {
const linkDisplayText = unist.makeInlineCode(text);
node.type = 'link';
node.title = title;
node.url = url;
node.children = [linkDisplayText];
} | the_stack |
import PSI from '../combined_wasm_node'
import { ERROR_INSTANCE_DELETED } from '../implementation/constants'
import { PSILibrary } from 'src/implementation/psi'
import { Response, ServerSetup } from '../implementation/proto/psi_pb'
let psi: PSILibrary
beforeAll(async () => {
psi = await PSI()
})
describe('PSI Client', () => {
test('It should create from an existing key', async () => {
const client1 = psi.client!.createWithNewKey()
const key = client1.getPrivateKeyBytes()
const client2 = psi.client!.createFromKey(key)
expect(client2.getPrivateKeyBytes()).toEqual(key)
})
test('It should fail to create from an invalid key', async () => {
const key = Uint8Array.from({ length: 32 })
expect(() => psi.client!.createFromKey(key)).toThrow()
})
test('It should throw if deleted twice', async () => {
const client = psi.client!.createWithNewKey()
client.delete()
expect(client.delete).toThrowError(ERROR_INSTANCE_DELETED)
})
test('It should return the private key as a binary array', async () => {
const client = psi.client!.createWithNewKey()
const keyLength = 32
const key = client.getPrivateKeyBytes()
expect(key.length).toBe(keyLength)
})
test('It should fail return the private key as a binary array if deleted', async () => {
const client = psi.client!.createWithNewKey()
client.delete()
expect(client.getPrivateKeyBytes.bind(client)).toThrowError(
ERROR_INSTANCE_DELETED
)
})
test('It should create a request', async () => {
const client = psi.client!.createWithNewKey()
const numClientElements = 10
const clientInputs = Array.from(
{ length: numClientElements },
(_, i) => `Element ${i}`
)
const request = client.createRequest(clientInputs)
expect(request.getEncryptedElementsList().length).toStrictEqual(
numClientElements
)
})
test('It should throw if attempting to create a request after deletion', async () => {
const client = psi.client!.createWithNewKey()
const numClientElements = 100
const clientInputs = Array.from(
{ length: numClientElements },
(_, i) => `Element ${i}`
)
client.delete()
expect(client.createRequest.bind(client, clientInputs)).toThrowError(
ERROR_INSTANCE_DELETED
)
})
test('It should process a response (cardinality) [GCS]', async () => {
// prettier-ignore
const key = Uint8Array.from([
160, 193, 102, 5, 219, 141, 42, 183,
157, 180, 97, 194, 33, 176, 95, 191,
77, 185, 205, 139, 61, 124, 1, 178,
198, 110, 236, 127, 64, 242, 152, 15
])
const client = psi.client!.createFromKey(key)
// prettier-ignore
const serverSetup = ServerSetup.deserializeBinary(Uint8Array.from([
10, 6, 8, 9, 16, 160, 141, 6, 26, 145, 1, 156,
124, 83, 130, 180, 41, 13, 249, 1, 160, 66, 225, 180,
102, 13, 186, 232, 132, 241, 96, 160, 28, 76, 132, 180,
174, 0, 237, 108, 36, 157, 81, 137, 81, 127, 152, 70,
60, 101, 15, 115, 201, 88, 204, 220, 14, 190, 136, 164,
2, 51, 141, 245, 160, 62, 55, 221, 23, 64, 22, 143,
242, 126, 57, 222, 180, 110, 125, 196, 1, 162, 228, 13,
133, 2, 63, 225, 105, 72, 148, 234, 184, 79, 143, 204,
148, 80, 122, 239, 70, 226, 93, 105, 118, 117, 46, 120,
4, 12, 47, 87, 126, 245, 6, 135, 24, 21, 228, 145,
49, 194, 180, 50, 255, 21, 233, 166, 226, 140, 5, 77,
7, 131, 118, 88, 132, 233, 2, 147, 128, 83, 16, 242,
171, 197, 88, 9, 148, 22, 129, 12, 112, 149, 170, 1
]))
// prettier-ignore
const response = Response.deserializeBinary(Uint8Array.from([
10, 33, 3, 76, 217, 211, 215, 254, 176, 87, 33, 177,
111, 184, 131, 7, 251, 172, 119, 48, 58, 156, 152, 18,
186, 184, 140, 122, 119, 253, 134, 206, 216, 193, 5, 10,
33, 3, 153, 37, 67, 82, 212, 45, 237, 208, 191, 226,
31, 75, 233, 165, 62, 126, 69, 93, 227, 207, 61, 22,
84, 196, 196, 73, 96, 234, 110, 75, 170, 229, 10, 33,
3, 141, 219, 163, 220, 158, 79, 10, 77, 55, 211, 205,
67, 160, 141, 61, 149, 156, 88, 126, 72, 94, 213, 42,
126, 245, 177, 50, 34, 90, 129, 193, 165, 10, 33, 2,
78, 83, 208, 113, 10, 63, 19, 208, 30, 134, 222, 189,
84, 35, 204, 184, 42, 23, 60, 138, 236, 88, 161, 35,
156, 54, 227, 58, 86, 22, 232, 116, 10, 33, 3, 159,
214, 143, 126, 207, 205, 25, 47, 174, 247, 87, 223, 117,
48, 106, 60, 203, 131, 125, 78, 8, 249, 141, 91, 214,
249, 239, 171, 120, 178, 50, 59, 10, 33, 3, 52, 239,
62, 190, 198, 211, 210, 185, 126, 26, 167, 170, 51, 218,
14, 121, 114, 68, 0, 99, 25, 198, 74, 169, 235, 245,
13, 234, 188, 200, 24, 150, 10, 33, 2, 36, 121, 159,
69, 8, 220, 251, 171, 213, 97, 193, 228, 171, 161, 171,
186, 96, 145, 190, 8, 174, 33, 160, 163, 214, 69, 0,
165, 161, 92, 94, 165, 10, 33, 2, 196, 108, 146, 176,
132, 215, 102, 87, 221, 29, 248, 65, 53, 145, 120, 220,
34, 136, 76, 91, 188, 35, 117, 239, 171, 174, 132, 154,
125, 50, 254, 158, 10, 33, 2, 34, 245, 53, 64, 84,
70, 211, 155, 133, 221, 136, 142, 173, 212, 234, 129, 0,
88, 99, 234, 212, 131, 188, 129, 174, 168, 95, 42, 131,
108, 120, 197, 10, 33, 3, 231, 207, 242, 34, 77, 41,
49, 61, 155, 163, 188, 51, 90, 70, 1, 15, 189, 140,
231, 10, 53, 120, 90, 155, 163, 88, 209, 165, 234, 47,
4, 126
]))
const intersection = client.getIntersectionSize(serverSetup, response)
expect(intersection).toStrictEqual(0)
})
test('It should process a response (intersection)', async () => {
// prettier-ignore
const key = Uint8Array.from([
160, 193, 102, 5, 219, 141, 42, 183,
157, 180, 97, 194, 33, 176, 95, 191,
77, 185, 205, 139, 61, 124, 1, 178,
198, 110, 236, 127, 64, 242, 152, 15
])
const client = psi.client!.createFromKey(key, true)
// prettier-ignore
const serverSetup = ServerSetup.deserializeBinary(Uint8Array.from([
10, 6, 8, 9, 16, 160, 141, 6, 26, 145, 1, 156,
124, 83, 130, 180, 41, 13, 249, 1, 160, 66, 225, 180,
102, 13, 186, 232, 132, 241, 96, 160, 28, 76, 132, 180,
174, 0, 237, 108, 36, 157, 81, 137, 81, 127, 152, 70,
60, 101, 15, 115, 201, 88, 204, 220, 14, 190, 136, 164,
2, 51, 141, 245, 160, 62, 55, 221, 23, 64, 22, 143,
242, 126, 57, 222, 180, 110, 125, 196, 1, 162, 228, 13,
133, 2, 63, 225, 105, 72, 148, 234, 184, 79, 143, 204,
148, 80, 122, 239, 70, 226, 93, 105, 118, 117, 46, 120,
4, 12, 47, 87, 126, 245, 6, 135, 24, 21, 228, 145,
49, 194, 180, 50, 255, 21, 233, 166, 226, 140, 5, 77,
7, 131, 118, 88, 132, 233, 2, 147, 128, 83, 16, 242,
171, 197, 88, 9, 148, 22, 129, 12, 112, 149, 170, 1
]))
// prettier-ignore
const response = Response.deserializeBinary(Uint8Array.from([
10, 33, 3, 76, 217, 211, 215, 254, 176, 87, 33, 177,
111, 184, 131, 7, 251, 172, 119, 48, 58, 156, 152, 18,
186, 184, 140, 122, 119, 253, 134, 206, 216, 193, 5, 10,
33, 3, 153, 37, 67, 82, 212, 45, 237, 208, 191, 226,
31, 75, 233, 165, 62, 126, 69, 93, 227, 207, 61, 22,
84, 196, 196, 73, 96, 234, 110, 75, 170, 229, 10, 33,
3, 141, 219, 163, 220, 158, 79, 10, 77, 55, 211, 205,
67, 160, 141, 61, 149, 156, 88, 126, 72, 94, 213, 42,
126, 245, 177, 50, 34, 90, 129, 193, 165, 10, 33, 2,
78, 83, 208, 113, 10, 63, 19, 208, 30, 134, 222, 189,
84, 35, 204, 184, 42, 23, 60, 138, 236, 88, 161, 35,
156, 54, 227, 58, 86, 22, 232, 116, 10, 33, 3, 159,
214, 143, 126, 207, 205, 25, 47, 174, 247, 87, 223, 117,
48, 106, 60, 203, 131, 125, 78, 8, 249, 141, 91, 214,
249, 239, 171, 120, 178, 50, 59, 10, 33, 3, 52, 239,
62, 190, 198, 211, 210, 185, 126, 26, 167, 170, 51, 218,
14, 121, 114, 68, 0, 99, 25, 198, 74, 169, 235, 245,
13, 234, 188, 200, 24, 150, 10, 33, 2, 36, 121, 159,
69, 8, 220, 251, 171, 213, 97, 193, 228, 171, 161, 171,
186, 96, 145, 190, 8, 174, 33, 160, 163, 214, 69, 0,
165, 161, 92, 94, 165, 10, 33, 2, 196, 108, 146, 176,
132, 215, 102, 87, 221, 29, 248, 65, 53, 145, 120, 220,
34, 136, 76, 91, 188, 35, 117, 239, 171, 174, 132, 154,
125, 50, 254, 158, 10, 33, 2, 34, 245, 53, 64, 84,
70, 211, 155, 133, 221, 136, 142, 173, 212, 234, 129, 0,
88, 99, 234, 212, 131, 188, 129, 174, 168, 95, 42, 131,
108, 120, 197, 10, 33, 3, 231, 207, 242, 34, 77, 41,
49, 61, 155, 163, 188, 51, 90, 70, 1, 15, 189, 140,
231, 10, 53, 120, 90, 155, 163, 88, 209, 165, 234, 47,
4, 126
]))
const intersection = client.getIntersection(serverSetup, response)
expect(intersection).toStrictEqual([])
})
test('It should throw if attempting to process a response after deletion (cardinality)', async () => {
const client = psi.client!.createWithNewKey()
// prettier-ignore
const serverSetup = ServerSetup.deserializeBinary(Uint8Array.from([
10, 6, 8, 9, 16, 160, 141, 6, 26, 145, 1, 156,
124, 83, 130, 180, 41, 13, 249, 1, 160, 66, 225, 180,
102, 13, 186, 232, 132, 241, 96, 160, 28, 76, 132, 180,
174, 0, 237, 108, 36, 157, 81, 137, 81, 127, 152, 70,
60, 101, 15, 115, 201, 88, 204, 220, 14, 190, 136, 164,
2, 51, 141, 245, 160, 62, 55, 221, 23, 64, 22, 143,
242, 126, 57, 222, 180, 110, 125, 196, 1, 162, 228, 13,
133, 2, 63, 225, 105, 72, 148, 234, 184, 79, 143, 204,
148, 80, 122, 239, 70, 226, 93, 105, 118, 117, 46, 120,
4, 12, 47, 87, 126, 245, 6, 135, 24, 21, 228, 145,
49, 194, 180, 50, 255, 21, 233, 166, 226, 140, 5, 77,
7, 131, 118, 88, 132, 233, 2, 147, 128, 83, 16, 242,
171, 197, 88, 9, 148, 22, 129, 12, 112, 149, 170, 1
]))
// prettier-ignore
const response = Response.deserializeBinary(Uint8Array.from([
10, 33, 3, 76, 217, 211, 215, 254, 176, 87, 33, 177,
111, 184, 131, 7, 251, 172, 119, 48, 58, 156, 152, 18,
186, 184, 140, 122, 119, 253, 134, 206, 216, 193, 5, 10,
33, 3, 153, 37, 67, 82, 212, 45, 237, 208, 191, 226,
31, 75, 233, 165, 62, 126, 69, 93, 227, 207, 61, 22,
84, 196, 196, 73, 96, 234, 110, 75, 170, 229, 10, 33,
3, 141, 219, 163, 220, 158, 79, 10, 77, 55, 211, 205,
67, 160, 141, 61, 149, 156, 88, 126, 72, 94, 213, 42,
126, 245, 177, 50, 34, 90, 129, 193, 165, 10, 33, 2,
78, 83, 208, 113, 10, 63, 19, 208, 30, 134, 222, 189,
84, 35, 204, 184, 42, 23, 60, 138, 236, 88, 161, 35,
156, 54, 227, 58, 86, 22, 232, 116, 10, 33, 3, 159,
214, 143, 126, 207, 205, 25, 47, 174, 247, 87, 223, 117,
48, 106, 60, 203, 131, 125, 78, 8, 249, 141, 91, 214,
249, 239, 171, 120, 178, 50, 59, 10, 33, 3, 52, 239,
62, 190, 198, 211, 210, 185, 126, 26, 167, 170, 51, 218,
14, 121, 114, 68, 0, 99, 25, 198, 74, 169, 235, 245,
13, 234, 188, 200, 24, 150, 10, 33, 2, 36, 121, 159,
69, 8, 220, 251, 171, 213, 97, 193, 228, 171, 161, 171,
186, 96, 145, 190, 8, 174, 33, 160, 163, 214, 69, 0,
165, 161, 92, 94, 165, 10, 33, 2, 196, 108, 146, 176,
132, 215, 102, 87, 221, 29, 248, 65, 53, 145, 120, 220,
34, 136, 76, 91, 188, 35, 117, 239, 171, 174, 132, 154,
125, 50, 254, 158, 10, 33, 2, 34, 245, 53, 64, 84,
70, 211, 155, 133, 221, 136, 142, 173, 212, 234, 129, 0,
88, 99, 234, 212, 131, 188, 129, 174, 168, 95, 42, 131,
108, 120, 197, 10, 33, 3, 231, 207, 242, 34, 77, 41,
49, 61, 155, 163, 188, 51, 90, 70, 1, 15, 189, 140,
231, 10, 53, 120, 90, 155, 163, 88, 209, 165, 234, 47,
4, 126
]))
client.delete()
expect(
client.getIntersectionSize.bind(client, serverSetup, response)
).toThrowError(ERROR_INSTANCE_DELETED)
})
test('It should throw if attempting to process a response after deletion (intersection)', async () => {
const client = psi.client!.createWithNewKey(true)
// prettier-ignore
const serverSetup = ServerSetup.deserializeBinary(Uint8Array.from([
10, 6, 8, 9, 16, 160, 141, 6, 26, 145, 1, 156,
124, 83, 130, 180, 41, 13, 249, 1, 160, 66, 225, 180,
102, 13, 186, 232, 132, 241, 96, 160, 28, 76, 132, 180,
174, 0, 237, 108, 36, 157, 81, 137, 81, 127, 152, 70,
60, 101, 15, 115, 201, 88, 204, 220, 14, 190, 136, 164,
2, 51, 141, 245, 160, 62, 55, 221, 23, 64, 22, 143,
242, 126, 57, 222, 180, 110, 125, 196, 1, 162, 228, 13,
133, 2, 63, 225, 105, 72, 148, 234, 184, 79, 143, 204,
148, 80, 122, 239, 70, 226, 93, 105, 118, 117, 46, 120,
4, 12, 47, 87, 126, 245, 6, 135, 24, 21, 228, 145,
49, 194, 180, 50, 255, 21, 233, 166, 226, 140, 5, 77,
7, 131, 118, 88, 132, 233, 2, 147, 128, 83, 16, 242,
171, 197, 88, 9, 148, 22, 129, 12, 112, 149, 170, 1
]))
// prettier-ignore
const response = Response.deserializeBinary(Uint8Array.from([
10, 33, 3, 76, 217, 211, 215, 254, 176, 87, 33, 177,
111, 184, 131, 7, 251, 172, 119, 48, 58, 156, 152, 18,
186, 184, 140, 122, 119, 253, 134, 206, 216, 193, 5, 10,
33, 3, 153, 37, 67, 82, 212, 45, 237, 208, 191, 226,
31, 75, 233, 165, 62, 126, 69, 93, 227, 207, 61, 22,
84, 196, 196, 73, 96, 234, 110, 75, 170, 229, 10, 33,
3, 141, 219, 163, 220, 158, 79, 10, 77, 55, 211, 205,
67, 160, 141, 61, 149, 156, 88, 126, 72, 94, 213, 42,
126, 245, 177, 50, 34, 90, 129, 193, 165, 10, 33, 2,
78, 83, 208, 113, 10, 63, 19, 208, 30, 134, 222, 189,
84, 35, 204, 184, 42, 23, 60, 138, 236, 88, 161, 35,
156, 54, 227, 58, 86, 22, 232, 116, 10, 33, 3, 159,
214, 143, 126, 207, 205, 25, 47, 174, 247, 87, 223, 117,
48, 106, 60, 203, 131, 125, 78, 8, 249, 141, 91, 214,
249, 239, 171, 120, 178, 50, 59, 10, 33, 3, 52, 239,
62, 190, 198, 211, 210, 185, 126, 26, 167, 170, 51, 218,
14, 121, 114, 68, 0, 99, 25, 198, 74, 169, 235, 245,
13, 234, 188, 200, 24, 150, 10, 33, 2, 36, 121, 159,
69, 8, 220, 251, 171, 213, 97, 193, 228, 171, 161, 171,
186, 96, 145, 190, 8, 174, 33, 160, 163, 214, 69, 0,
165, 161, 92, 94, 165, 10, 33, 2, 196, 108, 146, 176,
132, 215, 102, 87, 221, 29, 248, 65, 53, 145, 120, 220,
34, 136, 76, 91, 188, 35, 117, 239, 171, 174, 132, 154,
125, 50, 254, 158, 10, 33, 2, 34, 245, 53, 64, 84,
70, 211, 155, 133, 221, 136, 142, 173, 212, 234, 129, 0,
88, 99, 234, 212, 131, 188, 129, 174, 168, 95, 42, 131,
108, 120, 197, 10, 33, 3, 231, 207, 242, 34, 77, 41,
49, 61, 155, 163, 188, 51, 90, 70, 1, 15, 189, 140,
231, 10, 53, 120, 90, 155, 163, 88, 209, 165, 234, 47,
4, 126
]))
client.delete()
expect(
client.getIntersection.bind(client, serverSetup, response)
).toThrowError(ERROR_INSTANCE_DELETED)
})
test('It should fail to process a response (cardinality)', async () => {
const client = psi.client!.createWithNewKey()
const serverSetup = new ServerSetup()
const serverResponse = new Response()
expect(
client.getIntersectionSize.bind(client, serverSetup, serverResponse)
).toThrow()
})
test('It should fail to process a response (intersection)', async () => {
const client = psi.client!.createWithNewKey(true)
const serverSetup = new ServerSetup()
const serverResponse = new Response()
expect(
client.getIntersection.bind(client, serverSetup, serverResponse)
).toThrow()
})
}) | the_stack |
import { Epsilon, Matrix, Scalar, Vector3 } from '.';
import { FloatArray } from './types';
/**
* Vector4 class created for EulerAngle class conversion to Quaternion
*/
export class Vector4 {
/**
* Creates a Vector4 object from the given floats.
* @param x x value of the vector
* @param y y value of the vector
* @param z z value of the vector
* @param w w value of the vector
*/
constructor(
/** x value of the vector */
public x: number,
/** y value of the vector */
public y: number,
/** z value of the vector */
public z: number,
/** w value of the vector */
public w: number
) { }
/**
* Returns the string with the Vector4 coordinates.
* @returns a string containing all the vector values
*/
public toString(): string {
return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
}
/**
* Returns a JSON representation of this vector. This is necessary due to the way
* Actors detect changes on components like the actor's transform. They do this by adding
* properties for observation, and we don't want these properties serialized.
*/
public toJSON() {
return {
x: this.x,
y: this.y,
z: this.z,
w: this.w,
};
}
/**
* Returns the string "Vector4".
* @returns "Vector4"
*/
public getClassName(): string {
return "Vector4";
}
/**
* Returns the Vector4 hash code.
* @returns a unique hash code
*/
public getHashCode(): number {
let hash = this.x || 0;
hash = (hash * 397) ^ (this.y || 0);
hash = (hash * 397) ^ (this.z || 0);
hash = (hash * 397) ^ (this.w || 0);
return hash;
}
// Operators
/**
* Returns a new array populated with 4 elements : the Vector4 coordinates.
* @returns the resulting array
*/
public asArray(): number[] {
const result = new Array<number>();
this.toArray(result, 0);
return result;
}
/**
* Populates the given array from the given index with the Vector4 coordinates.
* @param array array to populate
* @param index index of the array to start at (default: 0)
* @returns the Vector4.
*/
public toArray(array: FloatArray, index?: number): Vector4 {
if (index === undefined) {
index = 0;
}
array[index] = this.x;
array[index + 1] = this.y;
array[index + 2] = this.z;
array[index + 3] = this.w;
return this;
}
/**
* Adds the given vector to the current Vector4.
* @param otherVector the vector to add
* @returns the updated Vector4.
*/
public addInPlace(otherVector: Vector4): Vector4 {
this.x += otherVector.x;
this.y += otherVector.y;
this.z += otherVector.z;
this.w += otherVector.w;
return this;
}
/**
* Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
* @param otherVector the vector to add
* @returns the resulting vector
*/
public add(otherVector: Vector4): Vector4 {
return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
}
/**
* Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
* @param otherVector the vector to add
* @param result the vector to store the result
* @returns the current Vector4.
*/
public addToRef(otherVector: Vector4, result: Vector4): Vector4 {
result.x = this.x + otherVector.x;
result.y = this.y + otherVector.y;
result.z = this.z + otherVector.z;
result.w = this.w + otherVector.w;
return this;
}
/**
* Subtract in place the given vector from the current Vector4.
* @param otherVector the vector to subtract
* @returns the updated Vector4.
*/
public subtractInPlace(otherVector: Vector4): Vector4 {
this.x -= otherVector.x;
this.y -= otherVector.y;
this.z -= otherVector.z;
this.w -= otherVector.w;
return this;
}
/**
* Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
* @param otherVector the vector to add
* @returns the new vector with the result
*/
public subtract(otherVector: Vector4): Vector4 {
return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
}
/**
* Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
* @param otherVector the vector to subtract
* @param result the vector to store the result
* @returns the current Vector4.
*/
public subtractToRef(otherVector: Vector4, result: Vector4): Vector4 {
result.x = this.x - otherVector.x;
result.y = this.y - otherVector.y;
result.z = this.z - otherVector.z;
result.w = this.w - otherVector.w;
return this;
}
/**
* Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
*/
/**
* Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
* @param x value to subtract
* @param y value to subtract
* @param z value to subtract
* @param w value to subtract
* @returns new vector containing the result
*/
public subtractFromFloats(x: number, y: number, z: number, w: number): Vector4 {
return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
}
/**
* Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
* @param x value to subtract
* @param y value to subtract
* @param z value to subtract
* @param w value to subtract
* @param result the vector to store the result in
* @returns the current Vector4.
*/
public subtractFromFloatsToRef(x: number, y: number, z: number, w: number, result: Vector4): Vector4 {
result.x = this.x - x;
result.y = this.y - y;
result.z = this.z - z;
result.w = this.w - w;
return this;
}
/**
* Returns a new Vector4 set with the current Vector4 negated coordinates.
* @returns a new vector with the negated values
*/
public negate(): Vector4 {
return new Vector4(-this.x, -this.y, -this.z, -this.w);
}
/**
* Multiplies the current Vector4 coordinates by scale (float).
* @param scale the number to scale with
* @returns the updated Vector4.
*/
public scaleInPlace(scale: number): Vector4 {
this.x *= scale;
this.y *= scale;
this.z *= scale;
this.w *= scale;
return this;
}
/**
* Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
* @param scale the number to scale with
* @returns a new vector with the result
*/
public scale(scale: number): Vector4 {
return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
}
/**
* Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
* @param scale the number to scale with
* @param result a vector to store the result in
* @returns the current Vector4.
*/
public scaleToRef(scale: number, result: Vector4): Vector4 {
result.x = this.x * scale;
result.y = this.y * scale;
result.z = this.z * scale;
result.w = this.w * scale;
return this;
}
/**
* Scale the current Vector4 values by a factor and add the result to a given Vector4
* @param scale defines the scale factor
* @param result defines the Vector4 object where to store the result
* @returns the unmodified current Vector4
*/
public scaleAndAddToRef(scale: number, result: Vector4): Vector4 {
result.x += this.x * scale;
result.y += this.y * scale;
result.z += this.z * scale;
result.w += this.w * scale;
return this;
}
/**
* Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
* @param otherVector the vector to compare against
* @returns true if they are equal
*/
public equals(otherVector: Vector4): boolean {
return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
}
/**
* Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
* @param otherVector vector to compare against
* @param epsilon (Default: very small number)
* @returns true if they are equal
*/
public equalsWithEpsilon(otherVector: Vector4, epsilon: number = Epsilon): boolean {
return otherVector
&& Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
&& Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
&& Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
&& Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
}
/**
* Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
* @param x x value to compare against
* @param y y value to compare against
* @param z z value to compare against
* @param w w value to compare against
* @returns true if equal
*/
public equalsToFloats(x: number, y: number, z: number, w: number): boolean {
return this.x === x && this.y === y && this.z === z && this.w === w;
}
/**
* Multiplies in place the current Vector4 by the given one.
* @param otherVector vector to multiple with
* @returns the updated Vector4.
*/
public multiplyInPlace(otherVector: Vector4): Vector4 {
this.x *= otherVector.x;
this.y *= otherVector.y;
this.z *= otherVector.z;
this.w *= otherVector.w;
return this;
}
/**
* Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
* @param otherVector vector to multiple with
* @returns resulting new vector
*/
public multiply(otherVector: Vector4): Vector4 {
return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
}
/**
* Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
* @param otherVector vector to multiple with
* @param result vector to store the result
* @returns the current Vector4.
*/
public multiplyToRef(otherVector: Vector4, result: Vector4): Vector4 {
result.x = this.x * otherVector.x;
result.y = this.y * otherVector.y;
result.z = this.z * otherVector.z;
result.w = this.w * otherVector.w;
return this;
}
/**
* Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
* @param x x value multiply with
* @param y y value multiply with
* @param z z value multiply with
* @param w w value multiply with
* @returns resulting new vector
*/
public multiplyByFloats(x: number, y: number, z: number, w: number): Vector4 {
return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
}
/**
* Returns a new Vector4 set with the division result of the current Vector4 by the given one.
* @param otherVector vector to devide with
* @returns resulting new vector
*/
public divide(otherVector: Vector4): Vector4 {
return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
}
/**
* Updates the given vector "result" with the division result of the current Vector4 by the given one.
* @param otherVector vector to devide with
* @param result vector to store the result
* @returns the current Vector4.
*/
public divideToRef(otherVector: Vector4, result: Vector4): Vector4 {
result.x = this.x / otherVector.x;
result.y = this.y / otherVector.y;
result.z = this.z / otherVector.z;
result.w = this.w / otherVector.w;
return this;
}
/**
* Divides the current Vector3 coordinates by the given ones.
* @param otherVector vector to devide with
* @returns the updated Vector3.
*/
public divideInPlace(otherVector: Vector4): Vector4 {
return this.divideToRef(otherVector, this);
}
/**
* Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
* @param other defines the second operand
* @returns the current updated Vector4
*/
public minimizeInPlace(other: Vector4): Vector4 {
if (other.x < this.x) { this.x = other.x; }
if (other.y < this.y) { this.y = other.y; }
if (other.z < this.z) { this.z = other.z; }
if (other.w < this.w) { this.w = other.w; }
return this;
}
/**
* Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
* @param other defines the second operand
* @returns the current updated Vector4
*/
public maximizeInPlace(other: Vector4): Vector4 {
if (other.x > this.x) { this.x = other.x; }
if (other.y > this.y) { this.y = other.y; }
if (other.z > this.z) { this.z = other.z; }
if (other.w > this.w) { this.w = other.w; }
return this;
}
/**
* Gets a new Vector4 from current Vector4 floored values
* @returns a new Vector4
*/
public floor(): Vector4 {
return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
}
/**
* Gets a new Vector4 from current Vector3 floored values
* @returns a new Vector4
*/
public fract(): Vector4 {
return new Vector4(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z), this.w - Math.floor(this.w));
}
// Properties
/**
* Returns the Vector4 length (float).
* @returns the length
*/
public length(): number {
return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
}
/**
* Returns the Vector4 squared length (float).
* @returns the length squared
*/
public lengthSquared(): number {
return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
}
// Methods
/**
* Normalizes in place the Vector4.
* @returns the updated Vector4.
*/
public normalize(): Vector4 {
const len = this.length();
if (len === 0) {
return this;
}
return this.scaleInPlace(1.0 / len);
}
/**
* Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
* @returns this converted to a new vector3
*/
public toVector3(): Vector3 {
return new Vector3(this.x, this.y, this.z);
}
/**
* Returns a new Vector4 copied from the current one.
* @returns the new cloned vector
*/
public clone(): Vector4 {
return new Vector4(this.x, this.y, this.z, this.w);
}
/**
* Updates the current Vector4 with the given one coordinates.
* @param source the source vector to copy from
* @returns the updated Vector4.
*/
public copyFrom(source: Vector4): Vector4 {
this.x = source.x;
this.y = source.y;
this.z = source.z;
this.w = source.w;
return this;
}
/**
* Updates the current Vector4 coordinates with the given floats.
* @param x float to copy from
* @param y float to copy from
* @param z float to copy from
* @param w float to copy from
* @returns the updated Vector4.
*/
public copyFromFloats(x: number, y: number, z: number, w: number): Vector4 {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
return this;
}
/**
* Updates the current Vector4 coordinates with the given floats.
* @param x float to set from
* @param y float to set from
* @param z float to set from
* @param w float to set from
* @returns the updated Vector4.
*/
public set(x: number, y: number, z: number, w: number): Vector4 {
return this.copyFromFloats(x, y, z, w);
}
/**
* Copies the given float to the current Vector3 coordinates
* @param v defines the x, y, z and w coordinates of the operand
* @returns the current updated Vector3
*/
public setAll(v: number): Vector4 {
this.x = this.y = this.z = this.w = v;
return this;
}
// Statics
/**
* Returns a new Vector4 set from the starting index of the given array.
* @param array the array to pull values from
* @param offset the offset into the array to start at
* @returns the new vector
*/
public static FromArray(array: ArrayLike<number>, offset?: number): Vector4 {
if (!offset) {
offset = 0;
}
return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
}
/**
* Updates the given vector "result" from the starting index of the given array.
* @param array the array to pull values from
* @param offset the offset into the array to start at
* @param result the vector to store the result in
*/
public static FromArrayToRef(array: ArrayLike<number>, offset: number, result: Vector4): void {
result.x = array[offset];
result.y = array[offset + 1];
result.z = array[offset + 2];
result.w = array[offset + 3];
}
/**
* Updates the given vector "result" from the starting index of the given Float32Array.
* @param array the array to pull values from
* @param offset the offset into the array to start at
* @param result the vector to store the result in
*/
public static FromFloatArrayToRef(array: Float32Array, offset: number, result: Vector4): void {
Vector4.FromArrayToRef(array, offset, result);
}
/**
* Updates the given vector "result" coordinates from the given floats.
* @param x float to set from
* @param y float to set from
* @param z float to set from
* @param w float to set from
* @param result the vector to the floats in
*/
public static FromFloatsToRef(x: number, y: number, z: number, w: number, result: Vector4): void {
result.x = x;
result.y = y;
result.z = z;
result.w = w;
}
/**
* Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
* @returns the new vector
*/
public static Zero(): Vector4 {
return new Vector4(0.0, 0.0, 0.0, 0.0);
}
/**
* Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
* @returns the new vector
*/
public static One(): Vector4 {
return new Vector4(1.0, 1.0, 1.0, 1.0);
}
/**
* Returns a new normalized Vector4 from the given one.
* @param vector the vector to normalize
* @returns the vector
*/
public static Normalize(vector: Vector4): Vector4 {
const result = Vector4.Zero();
Vector4.NormalizeToRef(vector, result);
return result;
}
/**
* Updates the given vector "result" from the normalization of the given one.
* @param vector the vector to normalize
* @param result the vector to store the result in
*/
public static NormalizeToRef(vector: Vector4, result: Vector4): void {
result.copyFrom(vector);
result.normalize();
}
/**
* Returns a vector with the minimum values from the left and right vectors
* @param left left vector to minimize
* @param right right vector to minimize
* @returns a new vector with the minimum of the left and right vector values
*/
public static Minimize(left: Vector4, right: Vector4): Vector4 {
const min = left.clone();
min.minimizeInPlace(right);
return min;
}
/**
* Returns a vector with the maximum values from the left and right vectors
* @param left left vector to maximize
* @param right right vector to maximize
* @returns a new vector with the maximum of the left and right vector values
*/
public static Maximize(left: Vector4, right: Vector4): Vector4 {
const max = left.clone();
max.maximizeInPlace(right);
return max;
}
/**
* Returns the distance (float) between the vectors "value1" and "value2".
* @param value1 value to calulate the distance between
* @param value2 value to calulate the distance between
* @return the distance between the two vectors
*/
public static Distance(value1: Vector4, value2: Vector4): number {
return Math.sqrt(Vector4.DistanceSquared(value1, value2));
}
/**
* Returns the squared distance (float) between the vectors "value1" and "value2".
* @param value1 value to calulate the distance between
* @param value2 value to calulate the distance between
* @return the distance between the two vectors squared
*/
public static DistanceSquared(value1: Vector4, value2: Vector4): number {
const x = value1.x - value2.x;
const y = value1.y - value2.y;
const z = value1.z - value2.z;
const w = value1.w - value2.w;
return (x * x) + (y * y) + (z * z) + (w * w);
}
/**
* Returns a new Vector4 located at the center between the vectors "value1" and "value2".
* @param value1 value to calulate the center between
* @param value2 value to calulate the center between
* @return the center between the two vectors
*/
public static Center(value1: Vector4, value2: Vector4): Vector4 {
const center = value1.add(value2);
center.scaleInPlace(0.5);
return center;
}
/**
* Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
* This methods computes transformed normalized direction vectors only.
* @param vector the vector to transform
* @param transformation the transformation matrix to apply
* @returns the new vector
*/
public static TransformNormal(vector: Vector4, transformation: Matrix): Vector4 {
const result = Vector4.Zero();
Vector4.TransformNormalToRef(vector, transformation, result);
return result;
}
/**
* Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
* This methods computes transformed normalized direction vectors only.
* @param vector the vector to transform
* @param transformation the transformation matrix to apply
* @param result the vector to store the result in
*/
public static TransformNormalToRef(vector: Vector4, transformation: Matrix, result: Vector4): void {
const m = transformation.m;
const x = (vector.x * m[0]) + (vector.y * m[4]) + (vector.z * m[8]);
const y = (vector.x * m[1]) + (vector.y * m[5]) + (vector.z * m[9]);
const z = (vector.x * m[2]) + (vector.y * m[6]) + (vector.z * m[10]);
result.x = x;
result.y = y;
result.z = z;
result.w = vector.w;
}
/**
* Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
* This methods computes transformed normalized direction vectors only.
* @param x value to transform
* @param y value to transform
* @param z value to transform
* @param w value to transform
* @param transformation the transformation matrix to apply
* @param result the vector to store the results in
*/
public static TransformNormalFromFloatsToRef(x: number, y: number, z: number, w: number, transformation: Matrix, result: Vector4): void {
const m = transformation.m;
result.x = (x * m[0]) + (y * m[4]) + (z * m[8]);
result.y = (x * m[1]) + (y * m[5]) + (z * m[9]);
result.z = (x * m[2]) + (y * m[6]) + (z * m[10]);
result.w = w;
}
} | the_stack |
/**
* @author Christopher Cook
* @copyright Webprofusion Ltd http://webprofusion.com
*/
/// <reference path="OCM_CommonUI.ts" />
declare var bootbox: any;
module OCM {
export enum AppMode {
STANDARD,
LOCALDEV,
SANDBOXED
}
/** View Model for core functionality */
export class AppViewModel {
/** The current selected POI */
public selectedPOI: any;
/** The currently viewed set of POIs from latest search/favourites view */
public poiList: Array<any>;
/** last set of POIs from recent search */
public searchPOIList: Array<any>;
/** A set of POIs favourited by the user */
public favouritesList: Array<any>;
/** track changes in result set, avoiding duplicate processing (maps etc) */
public resultsBatchID: number;
public searchPosition: GeoPosition;
public isCachedResults: boolean;
constructor() {
this.selectedPOI = null;
this.poiList = null;
this.favouritesList = null;
this.searchPosition = null;
this.resultsBatchID = -1;
this.isCachedResults = false;
}
}
/** App configuration settings */
export class AppConfig {
public launchMapOnStartup: boolean;
public maxResults: number;
public baseURL: string;
public loginProviderRedirectBaseURL: string;
public loginProviderRedirectURL: string;
public autoRefreshMapResults: boolean;
public newsHomeUrl: string;
public searchTimeoutMS: number; //max time allowed before search considered timed out
public searchFrequencyMinMS: number; //min ms between search requests
public allowAnonymousSubmissions: boolean;
public enablePOIListView: boolean;
///
// if enabled map movement will perform constant querying, user search for a specific location will centre on that location
///
public enableLiveMapQuerying: boolean;
constructor() {
this.autoRefreshMapResults = false;
this.launchMapOnStartup = false;
this.maxResults = 100;
this.searchTimeoutMS = 20000;
this.searchFrequencyMinMS = 500;
this.allowAnonymousSubmissions = false;
this.enableLiveMapQuerying = false;
this.enablePOIListView = true;
}
}
/** App state settings*/
export class AppState {
public appMode: AppMode;
public isRunningUnderCordova: boolean;
public isEmbeddedAppMode: boolean;
public appInitialised: boolean;
public languageCode: string;
public isLocationEditMode: boolean;
public menuDisplayed: boolean;
public mapLaunched: boolean;
public enableCommentSubmit: boolean;
public isSearchInProgress: boolean;
public isSearchRequested: boolean;
public suppressSettingsSave: boolean;
public isSubmissionInProgress: boolean;
public _lastPageId: string;
public _appQuitRequestCount: number;
public _appPollForLogin: any;
public _appSearchTimer: any;
public _appSearchTimestamp: Date; //time of last search
constructor() {
this.appMode = AppMode.STANDARD;
this.isRunningUnderCordova = false;
this.isEmbeddedAppMode = false;
this.appInitialised = false;
this.languageCode = "en";
this.isLocationEditMode = false;
this.enableCommentSubmit = true;
this.isSearchInProgress = false;
this._appQuitRequestCount = 0;
}
}
/** Base for App Components */
export class AppBase extends Base {
geolocationManager: OCM.Geolocation;
apiClient: OCM.API;
mappingManager: OCM.Mapping;
viewModel: AppViewModel;
appState: AppState;
appConfig: AppConfig;
constructor() {
super();
this.appState = new AppState();
this.appConfig = new AppConfig();
this.apiClient = new OCM.API();
this.geolocationManager = new OCM.Geolocation(this.apiClient);
this.mappingManager = new OCM.Mapping();
this.viewModel = new AppViewModel();
}
logAnalyticsView(viewName: string) {
if (window.analytics) {
window.analytics.trackView(viewName);
}
}
logAnalyticsEvent(category: string, action: string, label: string = null, value: number = null) {
if (window.analytics) {
window.analytics.trackEvent(category, action, label, value);
}
}
logAnalyticsUserId(userId: string) {
if (window.analytics) {
window.analytics.setUserId(userId);
}
}
getLoggedInUserInfo() {
var userInfo = {
"Identifier": this.getCookie("Identifier"),
"Username": this.getCookie("Username"),
"SessionToken": this.getCookie("OCMSessionToken"),
"Permissions": this.getCookie("AccessPermissions")
};
if (userInfo.Identifier != null) {
this.logAnalyticsUserId(userInfo.Identifier);
}
return userInfo;
}
setLoggedInUserInfo(userInfo) {
this.setCookie("Identifier", userInfo.Identifier);
this.setCookie("Username", userInfo.Username);
this.setCookie("OCMSessionToken", userInfo.SessionToken);
this.setCookie("AccessPermissions", userInfo.AccessPermissions);
}
getCookie(c_name: string) {
if (this.appState.isRunningUnderCordova) {
return this.apiClient.getCachedDataObject("_pref_" + c_name);
} else {
//http://www.w3schools.com/js/js_cookies.asp
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
var val = unescape(y);
if (val == "null") val = null;
return val;
}
}
return null;
}
}
setCookie(c_name: string, value, exdays: number = 1) {
if (this.appState.isRunningUnderCordova) {
this.apiClient.setCachedDataObject("_pref_" + c_name, value);
} else {
if (exdays == null) exdays = 1;
//http://www.w3schools.com/js/js_cookies.asp
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + "; expires=" + exdate.toUTCString();
document.cookie = c_name + "=" + c_value;
}
}
clearCookie(c_name: string) {
if (this.appState.isRunningUnderCordova) {
this.apiClient.setCachedDataObject("_pref_" + c_name, null);
} else {
var expires = new Date();
expires.setUTCFullYear(expires.getUTCFullYear() - 1);
document.cookie = c_name + '=; expires=' + expires.toUTCString() + '; path=/';
}
}
getParameter(name: string) {
//Get a parameter value from the document url
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}
setDropdown(id, selectedValue) {
if (selectedValue == null) selectedValue = "";
var $dropdown = $("#" + id);
$dropdown.val(selectedValue);
}
populateDropdown(id: any, refDataList: any, selectedValue: any, defaultToUnspecified: boolean = null, useTitleAsValue: boolean = null, unspecifiedText: string = null) {
var $dropdown = $("#" + id);
$('option', $dropdown).remove();
if (defaultToUnspecified == true) {
if (unspecifiedText == null) unspecifiedText = "Unknown";
$dropdown.append($('<option > </option>').val("").html(unspecifiedText));
$dropdown.val("");
}
for (var i = 0; i < refDataList.length; i++) {
if (useTitleAsValue == true) {
$dropdown.append($('<option > </option>').val(refDataList[i].Title).html(refDataList[i].Title));
}
else {
$dropdown.append($('<option > </option>').val(refDataList[i].ID).html(refDataList[i].Title));
}
}
if (selectedValue != null) $dropdown.val(selectedValue);
}
getMultiSelectionAsArray($dropdown: JQuery, defaultVal: any) {
//convert multi select values to string array
if ($dropdown.val() != null) {
var selectedVals = $dropdown.val().toString();
return selectedVals.split(",");
} else {
return defaultVal;
}
}
showProgressIndicator() {
$("#progress-indicator").fadeIn('slow');
}
hideProgressIndicator() {
$("#progress-indicator").fadeOut();
}
setElementAction(elementSelector, actionHandler) {
$(elementSelector).unbind("click");
$(elementSelector).unbind("touchstart");
$(elementSelector).fastClick(function (event) {
event.preventDefault();
actionHandler();
});
}
isUserSignedIn() {
if (this.apiClient.hasAuthorizationError == true) {
return false;
}
var userInfo = this.getLoggedInUserInfo();
if (userInfo.Username !== null && userInfo.Username !== "" && userInfo.SessionToken !== null && userInfo.SessionToken !== "") {
return true;
}
else {
return false;
}
}
getParameterFromURL(name, url) {
var sval = "";
if (url.indexOf("?") >= 0) {
var params = url.substr(url.indexOf("?") + 1);
params = params.split("&");
var temp = "";
// split param and value into individual pieces
for (var i = 0; i < params.length; i++) {
temp = params[i].split("=");
if ([temp[0]] == name) {
sval = temp[1];
}
}
}
return sval;
}
showMessage(msg) {
if (this.appState.isRunningUnderCordova && navigator.notification) {
navigator.notification.alert(
msg, // message
function () { ;; }, // callback
'Open Charge Map', // title
'OK' // buttonName
);
} else {
bootbox.alert(msg, function () {
});
}
}
}
} | the_stack |
import {
ChangeDetectorRef,
Directive,
EventEmitter,
HostListener,
Input,
NgZone,
OnDestroy,
Optional,
Output,
Renderer2
} from "@angular/core";
import {HttpClient, HttpResponse} from "@angular/common/http";
import {TranslateService} from "@ngx-translate/core";
import {AbstractJigsawComponent} from '../../common';
import {CommonUtils} from '../../core/utils/common-utils';
import {TimeGr, TimeService} from '../../service/time.service';
import {IUploader, UploadFileInfo} from "./uploader-typings";
const maxConcurrencyUpload = 5;
@Directive()
export abstract class JigsawUploadBase extends AbstractJigsawComponent {
/**
* @NoMarkForCheckRequired
*/
@Input('uploadTargetUrl')
public targetUrl: string = '/rdk/service/common/upload';
/**
* @NoMarkForCheckRequired
*/
@Input('uploadFileType')
public fileType: string;
/**
* @NoMarkForCheckRequired
*/
@Input('uploadMultiple')
public multiple: boolean = true;
/**
* @NoMarkForCheckRequired
*/
@Input('uploadContentField')
public contentField: string = 'file';
/**
* @NoMarkForCheckRequired
*/
@Input('uploadFileNameField')
public fileNameField: string = 'filename';
/**
* @NoMarkForCheckRequired
*/
@Input('uploadFileVerify')
public fileVerify: string;
/**
* @NoMarkForCheckRequired
*/
@Input('uploadAdditionalFields')
public additionalFields: { [prop: string]: string };
protected _minSize: number;
/**
* @NoMarkForCheckRequired
*/
@Input('uploadMinSize')
public get minSize(): number {
return this._minSize;
}
public set minSize(value: number) {
value = parseInt(<any>value);
if (isNaN(value)) {
console.error('minSize property must be a number, please input a number or number string');
return;
}
this._minSize = value;
}
protected _maxSize: number;
/**
* @NoMarkForCheckRequired
*/
@Input('uploadMaxSize')
public get maxSize(): number {
return this._maxSize;
}
public set maxSize(value: number) {
value = parseInt(<any>value);
if (isNaN(value)) {
console.error('maxSize property must be a number, please input a number or number string');
return;
}
this._maxSize = value;
}
@Input('uploadImmediately')
public uploadImmediately: boolean = true;
/**
* 每个文件上传完成(无论成功还是失败)之后发出,此事件给出的进度为文件个数来计算
*/
@Output('uploadProgress')
public progress = new EventEmitter<UploadFileInfo>();
/**
* 每个文件上传过程,服务端接收到客户端发送的数据后发出此事件,此事件给出的进度为单文件数据上传进度
*/
@Output('uploadDataSendProgress')
public dataSendProgress = new EventEmitter<UploadFileInfo>();
@Output('uploadComplete')
public complete = new EventEmitter<UploadFileInfo[]>();
@Output('uploadStart')
public start = new EventEmitter<UploadFileInfo[]>();
@Output('uploadChange')
public change = new EventEmitter<UploadFileInfo[]>();
}
@Directive({
selector: '[j-upload], [jigsaw-upload]'
})
export class JigsawUploadDirective extends JigsawUploadBase implements IUploader, OnDestroy {
constructor(@Optional() private _http: HttpClient,
private _renderer: Renderer2,
@Optional() private _translateService: TranslateService,
private _cdr: ChangeDetectorRef,
// _zone给runAfterMicrotasks用的
protected _zone: NgZone) {
super();
}
public files: UploadFileInfo[] = [];
@HostListener('click', ['$event'])
onClick($event) {
this._selectFile($event);
}
private _fileInputElement: HTMLElement;
private _removeFileChangeEvent: Function;
public retryUpload(fileInfo: UploadFileInfo) {
if (!fileInfo || !fileInfo.file) {
console.error('invalid retry upload file:', fileInfo);
return;
}
if (!this.files.find(file => file === fileInfo)) {
console.error('invalid retry upload file: the file is in our file list, maybe it was removed from our file list:', fileInfo);
return;
}
if (!this._isFileUploaded(fileInfo)) {
console.error('invalid retry upload file, this file is still pending:', fileInfo);
return;
}
const uploadingCount = this.files.filter(file => file.state == 'loading').length;
if (uploadingCount < maxConcurrencyUpload) {
this._sequenceUpload(fileInfo);
} else {
// 排队,后面上传线程有空了,会再来上传它的。
fileInfo.state = 'pause';
fileInfo.message = this._translateService.instant(`upload.waiting`);
}
}
/**
* 清空所有已上传的文件
*/
public clear() {
this.files.splice(0, this.files.length);
this._cdr.markForCheck();
}
private _selectFile($event) {
$event.preventDefault();
$event.stopPropagation();
if (!this._http) {
console.error('Jigsaw upload pc-components must inject HttpClientModule, please import it to the module!');
return;
}
const e = document.createEvent("MouseEvent");
e.initEvent("click", true, true);
if (!this._fileInputElement) {
this._fileInputElement = document.createElement('input');
this._fileInputElement.setAttribute('type', 'file');
//指令模式动态创建的input不在dom中的时候,此处将其加入body中,设置其不可见
this._fileInputElement.style.display = 'none';
document.body.appendChild(this._fileInputElement);
}
if (this.multiple) {
this._fileInputElement.setAttribute('multiple', 'true');
} else {
this._fileInputElement.removeAttribute('multiple');
}
this._fileInputElement.setAttribute('accept', this.fileType);
this._removeFileChangeEvent = this._removeFileChangeEvent ? this._removeFileChangeEvent :
this._renderer.listen(this._fileInputElement, 'change', () => {
if (this.uploadImmediately) {
this.upload();
} else {
this._appendFiles();
}
});
this._fileInputElement.dispatchEvent(e);
}
private _appendFiles(): boolean {
const fileInput: any = this._fileInputElement;
if (!fileInput) {
return false;
}
const files = this._checkFiles(Array.from(fileInput.files || []));
if (!this.multiple) {
this.files.splice(0, this.files.length);
files.splice(1, files.length);
} else {
fileInput.value = null;
}
this.files.push(...files);
if (files.length > 0) {
this.change.emit(this.files);
}
return this.files.length > 0;
}
public appendFiles(fileList) {
const files = this._checkFiles(Array.from(fileList || []));
this.files.push(...files);
this.change.emit(this.files);
}
public upload() {
this.runAfterMicrotasks(() => {
this._zone.run(() => {
if (!this._appendFiles() && this.files.length === 0) {
return;
}
this.start.emit(this.files);
const pendingFiles = this.files.filter(file => file.state == 'pause');
if (pendingFiles.length == 0) {
this.complete.emit(this.files);
return;
}
for (let i = 0, len = Math.min(maxConcurrencyUpload, pendingFiles.length); i < len; i++) {
// 最多前maxConcurrencyUpload个文件同时上传给服务器
this._sequenceUpload(pendingFiles[i]);
}
})
});
}
private _testFileType(fileName: string, type: string): boolean {
if (type == '*') {
return true;
}
const re = new RegExp(`.+\\${type.trim()}$`, 'i');
return re.test(fileName);
}
private _checkFiles(files: File[]): UploadFileInfo[] {
const fileTypes = this.fileType ? this.fileType.trim().split(/\s*,\s*/) : ['*'];
return files.map(file => {
const fileInfo: UploadFileInfo = {
name: file.name, state: "error", url: "", file: file, progress: 0,
message: this._translateService.instant(`upload.unknownStatus`)
}
if (!fileTypes.find(type => this._testFileType(file.name, type))) {
fileInfo.message = this._translateService.instant(`upload.fileTypeError`);
this._statusLog(fileInfo, fileInfo.message);
return fileInfo;
}
if (!isNaN(this.minSize) && file.size < this.minSize * 1024 * 1024) {
fileInfo.message = this._translateService.instant(`upload.fileMinSizeError`);
this._statusLog(fileInfo, fileInfo.message);
return fileInfo;
}
if (!isNaN(this.maxSize) && file.size > this.maxSize * 1024 * 1024) {
fileInfo.message = this._translateService.instant(`upload.fileMaxSizeError`);
this._statusLog(fileInfo, fileInfo.message);
return fileInfo;
}
fileInfo.state = 'pause';
fileInfo.message = this._translateService.instant(`upload.waiting`);
this._statusLog(fileInfo, fileInfo.message);
return fileInfo;
});
}
private _isAllFilesUploaded(): boolean {
return !this.files.find(f => !this._isFileUploaded(f));
}
private _isFileUploaded(fileInfo: UploadFileInfo): boolean {
return fileInfo.state !== 'loading' && fileInfo.state !== 'pause'
}
private _sequenceUpload(fileInfo: UploadFileInfo) {
fileInfo.state = 'loading';
fileInfo.message = this._translateService.instant(`upload.uploading`);
this._statusLog(fileInfo, fileInfo.message);
const formData = new FormData();
formData.append(this.contentField, fileInfo.file);
this._appendAdditionalFields(formData, fileInfo.file.name);
this._http.post(this.targetUrl, formData,
{
responseType: 'text',
reportProgress: true,
observe: 'events'
}).subscribe((res: any) => {
if (res.type === 1) {
fileInfo.progress = res.loaded / res.total * 100;
this.dataSendProgress.emit(fileInfo);
return;
}
if (res.type === 3) {
fileInfo.url = res.partialText;
return;
}
if (res.type === 4) {
fileInfo.state = 'success';
fileInfo.message = '';
const resp: HttpResponse<string> = <HttpResponse<string>>res;
fileInfo.url = resp.body && typeof resp.body == 'string' ? resp.body : fileInfo.url;
this._statusLog(fileInfo, this._translateService.instant(`upload.done`));
this._afterCurFileUploaded(fileInfo);
}
}, (e) => {
fileInfo.state = 'error';
const message = this._translateService.instant(`upload.${e.statusText}`) || e.statusText;
this._statusLog(fileInfo, message);
fileInfo.message = message;
this._afterCurFileUploaded(fileInfo);
});
}
private _appendAdditionalFields(formData: FormData, fileName: string): void {
const additionalFields = CommonUtils.shallowCopy(this.additionalFields || {});
// 为了避免引入破坏性,这里按照顺序append
const fileNameField = this.fileNameField ? this.fileNameField.trim() : '';
if (fileNameField) {
formData.append(fileNameField, encodeURIComponent(fileName));
delete additionalFields[fileNameField];
}
const fileVerify = this.fileVerify ? this.fileVerify.trim() : '';
if (fileVerify) {
formData.append('file-verify', encodeURIComponent(fileVerify));
delete additionalFields['file-verify'];
}
for (let prop in this.additionalFields) {
formData.append(prop, encodeURIComponent(this.additionalFields[prop]));
}
}
private _afterCurFileUploaded(fileInfo: UploadFileInfo) {
this.progress.emit(fileInfo);
const waitingFile = this.files.find(f => f.state == 'pause');
if (waitingFile) {
this._sequenceUpload(waitingFile)
} else if (this._isAllFilesUploaded()) {
this.complete.emit(this.files);
}
this._cdr.markForCheck();
}
private _statusLog(fileInfo: UploadFileInfo, content: string) {
if (!fileInfo.log) {
fileInfo.log = [];
}
const log = {time: TimeService.convertValue(new Date(), TimeGr.second), content: content};
fileInfo.log.push(log);
}
ngOnDestroy() {
super.ngOnDestroy();
if (this._removeFileChangeEvent) {
this._removeFileChangeEvent();
this._removeFileChangeEvent = null;
}
if (CommonUtils.isDefined(this._fileInputElement)){
document.body.removeChild(this._fileInputElement);
this._fileInputElement = null;
}
}
} | the_stack |
import common from '../../util/common';
import options from '../../util/options';
import Settings from '../../Settings';
import Math from '../../common/Math';
import Vec2 from '../../common/Vec2';
import Vec3 from '../../common/Vec3';
import Mat22 from '../../common/Mat22';
import Mat33 from '../../common/Mat33';
import Rot from '../../common/Rot';
import Joint, { JointOpt, JointDef } from '../Joint';
import Body from '../Body';
import { TimeStep } from "../Solver";
const _ASSERT = typeof ASSERT === 'undefined' ? false : ASSERT;
const inactiveLimit = 0;
const atLowerLimit = 1;
const atUpperLimit = 2;
const equalLimits = 3;
/**
* Revolute joint definition. This requires defining an anchor point where the
* bodies are joined. The definition uses local anchor points so that the
* initial configuration can violate the constraint slightly. You also need to
* specify the initial relative angle for joint limits. This helps when saving
* and loading a game.
*
* The local anchor points are measured from the body's origin rather than the
* center of mass because: 1. you might not know where the center of mass will
* be. 2. if you add/remove shapes from a body and recompute the mass, the
* joints will be broken.
*/
export interface RevoluteJointOpt extends JointOpt {
/**
* The lower angle for the joint limit (radians).
*/
lowerAngle?: number;
/**
* The upper angle for the joint limit (radians).
*/
upperAngle?: number;
/**
* The maximum motor torque used to achieve the desired motor speed. Usually
* in N-m.
*/
maxMotorTorque?: number;
/**
* The desired motor speed. Usually in radians per second.
*/
motorSpeed?: number;
/**
* A flag to enable joint limits.
*/
enableLimit?: boolean;
/**
* A flag to enable the joint motor.
*/
enableMotor?: boolean;
}
/**
* Revolute joint definition. This requires defining an anchor point where the
* bodies are joined. The definition uses local anchor points so that the
* initial configuration can violate the constraint slightly. You also need to
* specify the initial relative angle for joint limits. This helps when saving
* and loading a game.
*
* The local anchor points are measured from the body's origin rather than the
* center of mass because: 1. you might not know where the center of mass will
* be. 2. if you add/remove shapes from a body and recompute the mass, the
* joints will be broken.
*/
export interface RevoluteJointDef extends JointDef, RevoluteJointOpt {
/**
* The local anchor point relative to bodyA's origin.
*/
localAnchorA: Vec2;
/**
* The local anchor point relative to bodyB's origin.
*/
localAnchorB: Vec2;
/**
* The bodyB angle minus bodyA angle in the reference state (radians).
*/
referenceAngle: number;
}
const DEFAULTS = {
lowerAngle : 0.0,
upperAngle : 0.0,
maxMotorTorque : 0.0,
motorSpeed : 0.0,
enableLimit : false,
enableMotor : false
};
/**
* A revolute joint constrains two bodies to share a common point while they are
* free to rotate about the point. The relative rotation about the shared point
* is the joint angle. You can limit the relative rotation with a joint limit
* that specifies a lower and upper angle. You can use a motor to drive the
* relative rotation about the shared point. A maximum motor torque is provided
* so that infinite forces are not generated.
*/
export default class RevoluteJoint extends Joint {
static TYPE: 'revolute-joint' = 'revolute-joint';
/** @internal */ m_type: 'revolute-joint';
/** @internal */ m_localAnchorA: Vec2;
/** @internal */ m_localAnchorB: Vec2;
/** @internal */ m_referenceAngle: number;
/** @internal */ m_impulse: Vec3;
/** @internal */ m_motorImpulse: number;
/** @internal */ m_lowerAngle: number;
/** @internal */ m_upperAngle: number;
/** @internal */ m_maxMotorTorque: number;
/** @internal */ m_motorSpeed: number;
/** @internal */ m_enableLimit: boolean;
/** @internal */ m_enableMotor: boolean;
// Solver temp
/** @internal */ m_rA: Vec2;
/** @internal */ m_rB: Vec2;
/** @internal */ m_localCenterA: Vec2;
/** @internal */ m_localCenterB: Vec2;
/** @internal */ m_invMassA: number;
/** @internal */ m_invMassB: number;
/** @internal */ m_invIA: number;
/** @internal */ m_invIB: number;
// effective mass for point-to-point constraint.
/** @internal */ m_mass: Mat33 = new Mat33();
// effective mass for motor/limit angular constraint.
/** @internal */ m_motorMass: number;
/** @internal */ m_limitState: number = inactiveLimit; // TODO enum
constructor(def: RevoluteJointDef);
constructor(def: RevoluteJointOpt, bodyA: Body, bodyB: Body, anchor: Vec2);
// @ts-ignore
constructor(def: RevoluteJointDef, bodyA?: Body, bodyB?: Body, anchor?: Vec2) {
// @ts-ignore
if (!(this instanceof RevoluteJoint)) {
return new RevoluteJoint(def, bodyA, bodyB, anchor);
}
def = options(def, DEFAULTS);
super(def, bodyA, bodyB);
bodyA = this.m_bodyA;
bodyB = this.m_bodyB;
this.m_type = RevoluteJoint.TYPE;
this.m_localAnchorA = Vec2.clone(anchor ? bodyA.getLocalPoint(anchor) : def.localAnchorA || Vec2.zero());
this.m_localAnchorB = Vec2.clone(anchor ? bodyB.getLocalPoint(anchor) : def.localAnchorB || Vec2.zero());
this.m_referenceAngle = Math.isFinite(def.referenceAngle) ? def.referenceAngle : bodyB.getAngle() - bodyA.getAngle();
this.m_impulse = new Vec3();
this.m_motorImpulse = 0.0;
this.m_lowerAngle = def.lowerAngle;
this.m_upperAngle = def.upperAngle;
this.m_maxMotorTorque = def.maxMotorTorque;
this.m_motorSpeed = def.motorSpeed;
this.m_enableLimit = def.enableLimit;
this.m_enableMotor = def.enableMotor;
// Point-to-point constraint
// C = p2 - p1
// Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
// J = [-I -r1_skew I r2_skew ]
// Identity used:
// w k % (rx i + ry j) = w * (-ry i + rx j)
// Motor constraint
// Cdot = w2 - w1
// J = [0 0 -1 0 0 1]
// K = invI1 + invI2
}
/** @internal */
_serialize(): object {
return {
type: this.m_type,
bodyA: this.m_bodyA,
bodyB: this.m_bodyB,
collideConnected: this.m_collideConnected,
lowerAngle: this.m_lowerAngle,
upperAngle: this.m_upperAngle,
maxMotorTorque: this.m_maxMotorTorque,
motorSpeed: this.m_motorSpeed,
enableLimit: this.m_enableLimit,
enableMotor: this.m_enableMotor,
localAnchorA: this.m_localAnchorA,
localAnchorB: this.m_localAnchorB,
referenceAngle: this.m_referenceAngle,
};
}
/** @internal */
static _deserialize(data: any, world: any, restore: any):RevoluteJoint {
data = {...data};
data.bodyA = restore(Body, data.bodyA, world);
data.bodyB = restore(Body, data.bodyB, world);
const joint = new RevoluteJoint(data);
return joint;
}
/** @internal */
_setAnchors(def: {
anchorA?: Vec2,
localAnchorA?: Vec2,
anchorB?: Vec2,
localAnchorB?: Vec2,
}): void {
if (def.anchorA) {
this.m_localAnchorA.set(this.m_bodyA.getLocalPoint(def.anchorA));
} else if (def.localAnchorA) {
this.m_localAnchorA.set(def.localAnchorA);
}
if (def.anchorB) {
this.m_localAnchorB.set(this.m_bodyB.getLocalPoint(def.anchorB));
} else if (def.localAnchorB) {
this.m_localAnchorB.set(def.localAnchorB);
}
}
/**
* The local anchor point relative to bodyA's origin.
*/
getLocalAnchorA(): Vec2 {
return this.m_localAnchorA;
}
/**
* The local anchor point relative to bodyB's origin.
*/
getLocalAnchorB(): Vec2 {
return this.m_localAnchorB;
}
/**
* Get the reference angle.
*/
getReferenceAngle(): number {
return this.m_referenceAngle;
}
/**
* Get the current joint angle in radians.
*/
getJointAngle(): number {
const bA = this.m_bodyA;
const bB = this.m_bodyB;
return bB.m_sweep.a - bA.m_sweep.a - this.m_referenceAngle;
}
/**
* Get the current joint angle speed in radians per second.
*/
getJointSpeed(): number {
const bA = this.m_bodyA;
const bB = this.m_bodyB;
return bB.m_angularVelocity - bA.m_angularVelocity;
}
/**
* Is the joint motor enabled?
*/
isMotorEnabled(): boolean {
return this.m_enableMotor;
}
/**
* Enable/disable the joint motor.
*/
enableMotor(flag: boolean): void {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_enableMotor = flag;
}
/**
* Get the current motor torque given the inverse time step. Unit is N*m.
*/
getMotorTorque(inv_dt: number): number {
return inv_dt * this.m_motorImpulse;
}
/**
* Set the motor speed in radians per second.
*/
setMotorSpeed(speed: number): void {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_motorSpeed = speed;
}
/**
* Get the motor speed in radians per second.
*/
getMotorSpeed(): number {
return this.m_motorSpeed;
}
/**
* Set the maximum motor torque, usually in N-m.
*/
setMaxMotorTorque(torque: number): void {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_maxMotorTorque = torque;
}
getMaxMotorTorque(): number {
return this.m_maxMotorTorque;
}
/**
* Is the joint limit enabled?
*/
isLimitEnabled(): boolean {
return this.m_enableLimit;
}
/**
* Enable/disable the joint limit.
*/
enableLimit(flag: boolean): void {
if (flag != this.m_enableLimit) {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_enableLimit = flag;
this.m_impulse.z = 0.0;
}
}
/**
* Get the lower joint limit in radians.
*/
getLowerLimit(): number {
return this.m_lowerAngle;
}
/**
* Get the upper joint limit in radians.
*/
getUpperLimit(): number {
return this.m_upperAngle;
}
/**
* Set the joint limits in radians.
*/
setLimits(lower: number, upper: number): void {
_ASSERT && common.assert(lower <= upper);
if (lower != this.m_lowerAngle || upper != this.m_upperAngle) {
this.m_bodyA.setAwake(true);
this.m_bodyB.setAwake(true);
this.m_impulse.z = 0.0;
this.m_lowerAngle = lower;
this.m_upperAngle = upper;
}
}
/**
* Get the anchor point on bodyA in world coordinates.
*/
getAnchorA(): Vec2 {
return this.m_bodyA.getWorldPoint(this.m_localAnchorA);
}
/**
* Get the anchor point on bodyB in world coordinates.
*/
getAnchorB(): Vec2 {
return this.m_bodyB.getWorldPoint(this.m_localAnchorB);
}
/**
* Get the reaction force given the inverse time step. Unit is N.
*/
getReactionForce(inv_dt: number): Vec2 {
return Vec2.neo(this.m_impulse.x, this.m_impulse.y).mul(inv_dt);
}
/**
* Get the reaction torque due to the joint limit given the inverse time step.
* Unit is N*m.
*/
getReactionTorque(inv_dt: number): number {
return inv_dt * this.m_impulse.z;
}
initVelocityConstraints(step: TimeStep): void {
this.m_localCenterA = this.m_bodyA.m_sweep.localCenter;
this.m_localCenterB = this.m_bodyB.m_sweep.localCenter;
this.m_invMassA = this.m_bodyA.m_invMass;
this.m_invMassB = this.m_bodyB.m_invMass;
this.m_invIA = this.m_bodyA.m_invI;
this.m_invIB = this.m_bodyB.m_invI;
const aA = this.m_bodyA.c_position.a;
const vA = this.m_bodyA.c_velocity.v;
let wA = this.m_bodyA.c_velocity.w;
const aB = this.m_bodyB.c_position.a;
const vB = this.m_bodyB.c_velocity.v;
let wB = this.m_bodyB.c_velocity.w;
const qA = Rot.neo(aA);
const qB = Rot.neo(aB);
this.m_rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA));
this.m_rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB));
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
const mA = this.m_invMassA;
const mB = this.m_invMassB; // float
const iA = this.m_invIA;
const iB = this.m_invIB; // float
const fixedRotation = (iA + iB === 0.0); // bool
this.m_mass.ex.x = mA + mB + this.m_rA.y * this.m_rA.y * iA + this.m_rB.y
* this.m_rB.y * iB;
this.m_mass.ey.x = -this.m_rA.y * this.m_rA.x * iA - this.m_rB.y
* this.m_rB.x * iB;
this.m_mass.ez.x = -this.m_rA.y * iA - this.m_rB.y * iB;
this.m_mass.ex.y = this.m_mass.ey.x;
this.m_mass.ey.y = mA + mB + this.m_rA.x * this.m_rA.x * iA + this.m_rB.x
* this.m_rB.x * iB;
this.m_mass.ez.y = this.m_rA.x * iA + this.m_rB.x * iB;
this.m_mass.ex.z = this.m_mass.ez.x;
this.m_mass.ey.z = this.m_mass.ez.y;
this.m_mass.ez.z = iA + iB;
this.m_motorMass = iA + iB;
if (this.m_motorMass > 0.0) {
this.m_motorMass = 1.0 / this.m_motorMass;
}
if (this.m_enableMotor == false || fixedRotation) {
this.m_motorImpulse = 0.0;
}
if (this.m_enableLimit && fixedRotation == false) {
const jointAngle = aB - aA - this.m_referenceAngle; // float
if (Math.abs(this.m_upperAngle - this.m_lowerAngle) < 2.0 * Settings.angularSlop) {
this.m_limitState = equalLimits;
} else if (jointAngle <= this.m_lowerAngle) {
if (this.m_limitState != atLowerLimit) {
this.m_impulse.z = 0.0;
}
this.m_limitState = atLowerLimit;
} else if (jointAngle >= this.m_upperAngle) {
if (this.m_limitState != atUpperLimit) {
this.m_impulse.z = 0.0;
}
this.m_limitState = atUpperLimit;
} else {
this.m_limitState = inactiveLimit;
this.m_impulse.z = 0.0;
}
} else {
this.m_limitState = inactiveLimit;
}
if (step.warmStarting) {
// Scale impulses to support a variable time step.
this.m_impulse.mul(step.dtRatio);
this.m_motorImpulse *= step.dtRatio;
const P = Vec2.neo(this.m_impulse.x, this.m_impulse.y);
vA.subMul(mA, P);
wA -= iA * (Vec2.cross(this.m_rA, P) + this.m_motorImpulse + this.m_impulse.z);
vB.addMul(mB, P);
wB += iB * (Vec2.cross(this.m_rB, P) + this.m_motorImpulse + this.m_impulse.z);
} else {
this.m_impulse.setZero();
this.m_motorImpulse = 0.0;
}
this.m_bodyA.c_velocity.v = vA;
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v = vB;
this.m_bodyB.c_velocity.w = wB;
}
solveVelocityConstraints(step: TimeStep): void {
const vA = this.m_bodyA.c_velocity.v;
let wA = this.m_bodyA.c_velocity.w;
const vB = this.m_bodyB.c_velocity.v;
let wB = this.m_bodyB.c_velocity.w;
const mA = this.m_invMassA;
const mB = this.m_invMassB; // float
const iA = this.m_invIA;
const iB = this.m_invIB; // float
const fixedRotation = (iA + iB === 0.0); // bool
// Solve motor constraint.
if (this.m_enableMotor && this.m_limitState != equalLimits
&& fixedRotation == false) {
const Cdot = wB - wA - this.m_motorSpeed; // float
let impulse = -this.m_motorMass * Cdot; // float
const oldImpulse = this.m_motorImpulse; // float
const maxImpulse = step.dt * this.m_maxMotorTorque; // float
this.m_motorImpulse = Math.clamp(this.m_motorImpulse + impulse,
-maxImpulse, maxImpulse);
impulse = this.m_motorImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
// Solve limit constraint.
if (this.m_enableLimit && this.m_limitState != inactiveLimit
&& fixedRotation == false) {
const Cdot1 = Vec2.zero();
Cdot1.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB));
Cdot1.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA));
const Cdot2 = wB - wA; // float
const Cdot = new Vec3(Cdot1.x, Cdot1.y, Cdot2);
const impulse = Vec3.neg(this.m_mass.solve33(Cdot)); // Vec3
if (this.m_limitState == equalLimits) {
this.m_impulse.add(impulse);
} else if (this.m_limitState == atLowerLimit) {
const newImpulse = this.m_impulse.z + impulse.z; // float
if (newImpulse < 0.0) {
const rhs = Vec2.combine(-1, Cdot1, this.m_impulse.z, Vec2.neo(this.m_mass.ez.x, this.m_mass.ez.y)); // Vec2
const reduced = this.m_mass.solve22(rhs); // Vec2
impulse.x = reduced.x;
impulse.y = reduced.y;
impulse.z = -this.m_impulse.z;
this.m_impulse.x += reduced.x;
this.m_impulse.y += reduced.y;
this.m_impulse.z = 0.0;
} else {
this.m_impulse.add(impulse);
}
} else if (this.m_limitState == atUpperLimit) {
const newImpulse = this.m_impulse.z + impulse.z; // float
if (newImpulse > 0.0) {
const rhs = Vec2.combine(-1, Cdot1, this.m_impulse.z, Vec2.neo(this.m_mass.ez.x, this.m_mass.ez.y)); // Vec2
const reduced = this.m_mass.solve22(rhs); // Vec2
impulse.x = reduced.x;
impulse.y = reduced.y;
impulse.z = -this.m_impulse.z;
this.m_impulse.x += reduced.x;
this.m_impulse.y += reduced.y;
this.m_impulse.z = 0.0;
} else {
this.m_impulse.add(impulse);
}
}
const P = Vec2.neo(impulse.x, impulse.y);
vA.subMul(mA, P);
wA -= iA * (Vec2.cross(this.m_rA, P) + impulse.z);
vB.addMul(mB, P);
wB += iB * (Vec2.cross(this.m_rB, P) + impulse.z);
} else {
// Solve point-to-point constraint
const Cdot = Vec2.zero();
Cdot.addCombine(1, vB, 1, Vec2.cross(wB, this.m_rB));
Cdot.subCombine(1, vA, 1, Vec2.cross(wA, this.m_rA));
const impulse = this.m_mass.solve22(Vec2.neg(Cdot)); // Vec2
this.m_impulse.x += impulse.x;
this.m_impulse.y += impulse.y;
vA.subMul(mA, impulse);
wA -= iA * Vec2.cross(this.m_rA, impulse);
vB.addMul(mB, impulse);
wB += iB * Vec2.cross(this.m_rB, impulse);
}
this.m_bodyA.c_velocity.v = vA;
this.m_bodyA.c_velocity.w = wA;
this.m_bodyB.c_velocity.v = vB;
this.m_bodyB.c_velocity.w = wB;
}
/**
* This returns true if the position errors are within tolerance.
*/
solvePositionConstraints(step: TimeStep): boolean {
const cA = this.m_bodyA.c_position.c;
let aA = this.m_bodyA.c_position.a;
const cB = this.m_bodyB.c_position.c;
let aB = this.m_bodyB.c_position.a;
const qA = Rot.neo(aA);
const qB = Rot.neo(aB);
let angularError = 0.0; // float
let positionError = 0.0; // float
const fixedRotation = (this.m_invIA + this.m_invIB == 0.0); // bool
// Solve angular limit constraint.
if (this.m_enableLimit && this.m_limitState != inactiveLimit
&& fixedRotation == false) {
const angle = aB - aA - this.m_referenceAngle; // float
let limitImpulse = 0.0; // float
if (this.m_limitState == equalLimits) {
// Prevent large angular corrections
const C = Math.clamp(angle - this.m_lowerAngle,
-Settings.maxAngularCorrection, Settings.maxAngularCorrection); // float
limitImpulse = -this.m_motorMass * C;
angularError = Math.abs(C);
} else if (this.m_limitState == atLowerLimit) {
let C = angle - this.m_lowerAngle; // float
angularError = -C;
// Prevent large angular corrections and allow some slop.
C = Math.clamp(C + Settings.angularSlop, -Settings.maxAngularCorrection,
0.0);
limitImpulse = -this.m_motorMass * C;
} else if (this.m_limitState == atUpperLimit) {
let C = angle - this.m_upperAngle; // float
angularError = C;
// Prevent large angular corrections and allow some slop.
C = Math.clamp(C - Settings.angularSlop, 0.0,
Settings.maxAngularCorrection);
limitImpulse = -this.m_motorMass * C;
}
aA -= this.m_invIA * limitImpulse;
aB += this.m_invIB * limitImpulse;
}
// Solve point-to-point constraint.
{
qA.set(aA);
qB.set(aB);
const rA = Rot.mulVec2(qA, Vec2.sub(this.m_localAnchorA, this.m_localCenterA)); // Vec2
const rB = Rot.mulVec2(qB, Vec2.sub(this.m_localAnchorB, this.m_localCenterB)); // Vec2
const C = Vec2.zero();
C.addCombine(1, cB, 1, rB);
C.subCombine(1, cA, 1, rA);
positionError = C.length();
const mA = this.m_invMassA;
const mB = this.m_invMassB; // float
const iA = this.m_invIA;
const iB = this.m_invIB; // float
const K = new Mat22();
K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y;
K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y;
K.ey.x = K.ex.y;
K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x;
const impulse = Vec2.neg(K.solve(C)); // Vec2
cA.subMul(mA, impulse);
aA -= iA * Vec2.cross(rA, impulse);
cB.addMul(mB, impulse);
aB += iB * Vec2.cross(rB, impulse);
}
this.m_bodyA.c_position.c.set(cA);
this.m_bodyA.c_position.a = aA;
this.m_bodyB.c_position.c.set(cB);
this.m_bodyB.c_position.a = aB;
return positionError <= Settings.linearSlop
&& angularError <= Settings.angularSlop;
}
} | the_stack |
import { Trans } from "@lingui/macro";
import { i18nMark, withI18n } from "@lingui/react";
import { Hooks } from "#SRC/js/plugin-bridge/PluginSDK";
import * as React from "react";
import { MountService } from "foundation-ui";
import FormErrorUtil from "#SRC/js/utils/FormErrorUtil";
import { findNestedPropertyInObject } from "#SRC/js/utils/Util";
import ErrorsAlert from "#SRC/js/components/ErrorsAlert";
import FluidGeminiScrollbar from "#SRC/js/components/FluidGeminiScrollbar";
import JSONEditorLoading from "#SRC/js/components/JSONEditorLoading";
import SplitPanel, {
PrimaryPanel,
SidePanel,
} from "#SRC/js/components/SplitPanel";
import TabButton from "#SRC/js/components/TabButton";
import TabButtonList from "#SRC/js/components/TabButtonList";
import Tabs from "#SRC/js/components/Tabs";
import TabView from "#SRC/js/components/TabView";
import TabViewList from "#SRC/js/components/TabViewList";
import {
FormError,
JobFormActionType,
Action,
JobSpec,
JobOutput,
} from "./form/helpers/JobFormData";
import GeneralFormSection from "./form/GeneralFormSection";
import ContainerFormSection from "./form/ContainerFormSection";
import EnvironmentFormSection from "./form/EnvironmentFormSection";
import RunConfigFormSection from "./form/RunConfigFormSection";
import ScheduleFormSection from "./form/ScheduleFormSection";
import VolumesFormSection from "./form/VolumesFormSection";
import PlacementSection from "./form/PlacementSection";
import {
jobSpecToOutputParser,
jobSpecToFormOutputParser,
} from "./form/helpers/JobParsers";
import { translateErrorMessages } from "./form/helpers/ErrorUtil";
import JobErrorTabPathRegexes from "../constants/JobErrorTabPathRegexes";
const ServiceErrorPathMapping: any[] = [];
const JSONEditor = React.lazy(
() =>
import(/* webpackChunkName: "jsoneditor" */ "#SRC/js/components/JSONEditor")
);
interface JobsFormProps {
onChange: (action: Action) => void;
jobSpec: JobSpec;
activeTab: string;
handleTabChange: (tab: string) => void;
errors: any[];
isJSONModeActive: boolean;
onErrorsChange: (errors: FormError[], type?: string) => void;
showAllErrors: boolean;
i18n: any;
isEdit: boolean;
}
interface JobsFormState {
editorWidth?: number;
}
interface NavigationItem {
id: string;
key: string;
label: string;
}
const getFormOutput = (jobSpec: JobSpec) =>
Hooks.applyFilter(
"jobSpecToFormOutputParser",
jobSpecToFormOutputParser(jobSpec),
jobSpec
);
class JobsForm extends React.Component<JobsFormProps, JobsFormState> {
public static readonly navigationItems: NavigationItem[] = [
{ id: "general", key: "general", label: i18nMark("General") },
{ id: "container", key: "container", label: i18nMark("Container Runtime") },
{ id: "schedule", key: "schedule", label: i18nMark("Schedule") },
{ id: "environment", key: "environment", label: i18nMark("Environment") },
{ id: "volumes", key: "volumes", label: i18nMark("Volumes") },
{ id: "placement", key: "placement", label: i18nMark("Placement") },
{ id: "runconfig", key: "runConfig", label: i18nMark("Run Configuration") },
];
state = { editorWidth: undefined };
constructor(props: Readonly<JobsFormProps>) {
super(props);
this.onInputChange = this.onInputChange.bind(this);
this.handleJSONChange = this.handleJSONChange.bind(this);
this.handleJSONErrorStateChange = this.handleJSONErrorStateChange.bind(
this
);
this.getJSONEditorData = this.getJSONEditorData.bind(this);
this.handleAddItem = this.handleAddItem.bind(this);
this.handleRemoveItem = this.handleRemoveItem.bind(this);
this.onEditorResize = this.onEditorResize.bind(this);
}
public getJSONEditorData(jobSpec: JobSpec): JobOutput {
const jobJSON = jobSpecToOutputParser(jobSpec);
if (jobJSON.hasOwnProperty("schedule") && jobJSON.schedules === undefined) {
// jobSpecToOutputParser returns object with `schedule: undefined` if there is no schedule present,
// but this triggers an update of the JSONEditor and leads to issues where the state of the JSON in the
// editor is replaced with old values.
delete jobJSON.schedules;
}
return jobJSON;
}
public onInputChange({ target: { value, name, type } }) {
const actionType =
type === "number" ? JobFormActionType.SetNum : JobFormActionType.Set;
this.props.onChange({ type: actionType, value, path: name });
}
public handleJSONChange(jobJSON: JobOutput) {
this.props.onChange({
path: "json",
type: JobFormActionType.Override,
value: jobJSON,
});
}
public handleJSONErrorStateChange(errorMessage: string | null) {
this.props.onErrorsChange(
errorMessage === null ? [] : [{ message: errorMessage, path: [] }]
);
}
public handleAddItem(path: string) {
return () => {
const { onChange } = this.props;
const action = {
type: JobFormActionType.AddArrayItem,
path,
value: null,
};
onChange(action);
};
}
public handleRemoveItem(path: string, index: number) {
return () => {
const { onChange } = this.props;
const action = {
type: JobFormActionType.RemoveArrayItem,
path,
value: index,
};
onChange(action);
};
}
public getTabContent() {
const { jobSpec, errors, showAllErrors, i18n, isEdit } = this.props;
const formOutput = getFormOutput(jobSpec);
const translatedErrors = translateErrorMessages(errors, i18n);
const pluginTabProps = {
errors: translatedErrors,
data: formOutput,
pathMapping: ServiceErrorPathMapping,
hideTopLevelErrors: !showAllErrors,
showErrors: showAllErrors,
onAddItem: this.handleAddItem,
onRemoveItem: this.handleRemoveItem,
};
const tabs = [
<TabView id="general" key="general">
<ErrorsAlert
errors={translatedErrors}
pathMapping={ServiceErrorPathMapping}
hideTopLevelErrors={!showAllErrors}
/>
<GeneralFormSection
formData={formOutput}
errors={translatedErrors}
showErrors={showAllErrors}
isEdit={isEdit}
onChange={this.props.onChange}
/>
</TabView>,
<TabView id="container" key="container">
<ErrorsAlert
errors={translatedErrors}
pathMapping={ServiceErrorPathMapping}
hideTopLevelErrors={!showAllErrors}
/>
<ContainerFormSection
formData={formOutput}
errors={translatedErrors}
showErrors={showAllErrors}
onAddItem={this.handleAddItem}
onRemoveItem={this.handleRemoveItem}
/>
</TabView>,
<TabView id="schedule" key="schedule">
<ErrorsAlert
errors={translatedErrors}
pathMapping={ServiceErrorPathMapping}
hideTopLevelErrors={!showAllErrors}
/>
<ScheduleFormSection
formData={formOutput}
errors={translatedErrors}
showErrors={showAllErrors}
/>
</TabView>,
<TabView id="environment" key="environment">
<ErrorsAlert
errors={translatedErrors}
pathMapping={ServiceErrorPathMapping}
hideTopLevelErrors={!showAllErrors}
/>
<EnvironmentFormSection
formData={formOutput}
errors={translatedErrors}
showErrors={showAllErrors}
onAddItem={this.handleAddItem}
onRemoveItem={this.handleRemoveItem}
/>
</TabView>,
<TabView id="volumes" key="volumes">
<ErrorsAlert
errors={translatedErrors}
pathMapping={ServiceErrorPathMapping}
hideTopLevelErrors={!showAllErrors}
/>
<VolumesFormSection
formData={formOutput}
errors={translatedErrors}
showErrors={showAllErrors}
onAddItem={this.handleAddItem}
onRemoveItem={this.handleRemoveItem}
/>
</TabView>,
<TabView id="placement" key="placement">
<ErrorsAlert
errors={translatedErrors}
pathMapping={ServiceErrorPathMapping}
hideTopLevelErrors={!showAllErrors}
/>
<MountService.Mount
type="CreateJob:PlacementSection"
formData={formOutput}
errors={translatedErrors}
showErrors={showAllErrors}
onAddItem={this.handleAddItem}
onRemoveItem={this.handleRemoveItem}
>
<PlacementSection
formData={formOutput}
errors={translatedErrors}
showErrors={showAllErrors}
onAddItem={this.handleAddItem}
onRemoveItem={this.handleRemoveItem}
/>
</MountService.Mount>
</TabView>,
<TabView id="runconfig" key="runconfig">
<ErrorsAlert
errors={translatedErrors}
pathMapping={ServiceErrorPathMapping}
hideTopLevelErrors={!showAllErrors}
/>
<RunConfigFormSection
formData={formOutput}
errors={translatedErrors}
showErrors={showAllErrors}
onAddItem={this.handleAddItem}
onRemoveItem={this.handleRemoveItem}
/>
</TabView>,
];
return Hooks.applyFilter("createJobTabViews", tabs, pluginTabProps);
}
public onEditorResize(newSize: number | undefined) {
this.setState({ editorWidth: newSize });
}
public render() {
const {
activeTab,
handleTabChange,
isJSONModeActive,
jobSpec,
errors,
i18n,
} = this.props;
const errorsByTab = FormErrorUtil.getTopLevelTabErrors(
errors,
JobErrorTabPathRegexes,
ServiceErrorPathMapping,
i18n
);
const jobJSON = this.getJSONEditorData(jobSpec);
const tabList = Hooks.applyFilter(
"createJobTabList",
JobsForm.navigationItems
).map((item: NavigationItem) => {
const issueCount = findNestedPropertyInObject(
errorsByTab,
`${item.id}.length`
);
return (
<TabButton
id={item.id}
label={<Trans render="span" id={item.label} />}
key={item.key}
count={issueCount}
showErrorBadge={Boolean(issueCount) && this.props.showAllErrors}
description={
// TODO: pluralize
<Trans render="span">{issueCount} issues need addressing</Trans>
}
/>
);
});
return (
<SplitPanel onResize={this.onEditorResize}>
<PrimaryPanel className="create-service-modal-form__scrollbar-container modal-body-offset gm-scrollbar-container-flex">
<FluidGeminiScrollbar>
<div className="modal-body-padding-surrogate create-service-modal-form-container">
<form
className="create-service-modal-form container"
onChange={this.onInputChange}
noValidate={true}
>
<Tabs
activeTab={activeTab}
handleTabChange={handleTabChange}
vertical={true}
>
<TabButtonList>{tabList}</TabButtonList>
<TabViewList>{this.getTabContent()}</TabViewList>
</Tabs>
</form>
</div>
</FluidGeminiScrollbar>
</PrimaryPanel>
<SidePanel isActive={isJSONModeActive} className="jsonEditorWrapper">
<React.Suspense fallback={<JSONEditorLoading isSidePanel={true} />}>
<JSONEditor
errors={errors}
onChange={this.handleJSONChange}
onErrorStateChange={this.handleJSONErrorStateChange}
showGutter={true}
showPrintMargin={false}
theme="monokai"
height="100%"
value={jobJSON}
width={
this.state.editorWidth ? `${this.state.editorWidth}px` : "100%"
}
/>
</React.Suspense>
</SidePanel>
</SplitPanel>
);
}
}
export default withI18n()(JobsForm); | the_stack |
import _, { groupBy, filter, map, sum, some, isUndefined, uniq, difference, flatMap, concat, mean, defaultTo, find, size, isNaN } from 'lodash';
import { isPresent } from '../utils';
import { DependencyGraph } from '../DependencyGraph';
import { GraphDataElement, IGraph, IGraphEdge, IGraphMetrics, IGraphNode, EGraphNodeType, GraphDataType, ExternalType } from '../types';
class GraphGenerator {
controller: DependencyGraph;
constructor(controller: DependencyGraph) {
this.controller = controller;
}
_createNode(dataElements: GraphDataElement[]): IGraphNode | undefined {
if (!dataElements || dataElements.length <= 0) {
return undefined;
}
console.log(dataElements)
// const sumMetrics = this.controller.props.options.sumTimings;
// const nodeName = dataElements[0].target;
// const internalNode = some(dataElements, ['type', GraphDataType.INTERNAL]) || some(dataElements, ['type', GraphDataType.EXTERNAL_IN]);
// const nodeType = internalNode ? EGraphNodeType.INTERNAL : EGraphNodeType.EXTERNAL;
// const metrics: IGraphMetrics = {};
// const node: IGraphNode = {
// name: nodeName,
// type: nodeType,
// metrics
// };
// const aggregationFunction = sumMetrics ? sum : mean;
// if (internalNode) {
// metrics.rate = sum(map(dataElements, element => element.data.rate_in));
// metrics.error_rate = sum(map(dataElements, element => element.data.error_rate_in));
// const response_timings = map(dataElements, element => element.data.response_time_in).filter(isPresent);
// if (response_timings.length > 0) {
// metrics.response_time = aggregationFunction(response_timings);
// }
// } else {
// metrics.rate = sum(map(dataElements, element => element.data.rate_out));
// metrics.error_rate = sum(map(dataElements, element => element.data.error_rate_out));
// const response_timings = map(dataElements, element => element.data.response_time_out).filter(isPresent);
// if (response_timings.length > 0) {
// metrics.response_time = aggregationFunction(response_timings);
// }
// const externalType = _(dataElements)
// .map(element => element.data.type)
// .uniq()
// .value();
// if (externalType.length == 1) {
// node.external_type = externalType[0];
// }
// }
// // metrics which are same for internal and external nodes
// metrics.threshold = _(dataElements)
// .map(element => element.data.threshold)
// .filter()
// .mean();
// if (sumMetrics) {
// const requestCount = defaultTo(metrics.rate, 0) + defaultTo(metrics.error_rate, 0);
// const response_time = defaultTo(metrics.response_time, -1);
// if (requestCount > 0 && response_time >= 0) {
// metrics.response_time = response_time / requestCount;
// }
// }
// const { rate, error_rate } = metrics;
// if (rate + error_rate > 0) {
// metrics.success_rate = 1.0 / (rate + error_rate) * rate;
// } else {
// metrics.success_rate = 1.0;
// }
// return node;
// }
// _createMissingNodes(data: GraphDataElement[], nodes: IGraphNode[]): IGraphNode[] {
// const existingNodeNames = map(nodes, node => node.name);
// const expectedNodeNames = uniq(flatMap(data, dataElement => [dataElement.source, dataElement.target])).filter(isPresent);
// const missingNodeNames = difference(expectedNodeNames, existingNodeNames);
// const missingNodes = map(missingNodeNames, name => {
// let nodeType: EGraphNodeType;
// let external_type: string | undefined;
// // derive node type
// let elementSrc = find(data, { source: name });
// let elementTrgt = find(data, { target: name });
// if (elementSrc && elementSrc.type == GraphDataType.EXTERNAL_IN) {
// nodeType = EGraphNodeType.EXTERNAL;
// external_type = elementSrc.data.type;
// } else if (elementTrgt && elementTrgt.type == GraphDataType.EXTERNAL_OUT) {
// nodeType = EGraphNodeType.EXTERNAL;
// external_type = elementTrgt.data.type
// } else {
// nodeType = EGraphNodeType.INTERNAL;
// }
// return <IGraphNode>{
// name,
// type: nodeType,
// external_type: external_type
// };
// });
// return missingNodes;
}
_createNodes(data: GraphDataElement[]): IGraphNode[] {
const filteredData = filter(data, dataElement => dataElement.source !== dataElement.target);
const sumMetrics = this.controller.props.options.sumTimings;
console.log(filteredData)
const nodesMap = {}
filteredData.forEach((e: GraphDataElement) => {
const sourceNode = nodesMap[e.source]
if (!sourceNode) {
nodesMap[e.source] = {
name: e.source,
type: e.externalType === ExternalType.SourceExternal ? EGraphNodeType.EXTERNAL : EGraphNodeType.INTERNAL
} as IGraphNode
}
const targetNode: IGraphNode = nodesMap[e.target]
if (!targetNode) {
nodesMap[e.target] = {
name: e.target,
type: e.externalType === ExternalType.TargetExternal ? EGraphNodeType.EXTERNAL : EGraphNodeType.INTERNAL,
metrics: {
requests: e.data.requests,
errors: e.data.errors,
errorRate: e.data.errors / e.data.requests,
responseTime: e.data.responseTime
}
} as IGraphNode
} else {
targetNode.metrics = {
requests: targetNode.metrics.requests + e.data.requests,
errors: targetNode.metrics.errors + e.data.errors,
errorRate: (targetNode.metrics.errors + e.data.errors) / (targetNode.metrics.requests + e.data.requests),
responseTime: targetNode.metrics.responseTime + e.data.responseTime
}
}
})
const nodes = []
_.forEach(nodesMap, (node: IGraphNode) => {
if (sumMetrics && node.metrics) {
const respTime = node.metrics.responseTime / node.metrics.requests
if (isNaN(respTime)) {
node.metrics.responseTime = 0
}
}
nodes.push(node)
})
return nodes
}
_createEdge(dataElement: GraphDataElement): IGraphEdge | undefined {
const { source, target } = dataElement;
if (source === undefined || target === undefined) {
console.error("source and target are necessary to create an edge", dataElement);
return undefined;
}
const metrics: IGraphMetrics = {
requests: 0,
errors: 0,
errorRate: 0,
responseTime: 0
};
const edge: IGraphEdge = {
source,
target,
metrics
};
const { requests, errors, responseTime } = dataElement.data;
if (!isUndefined(requests)) {
metrics.requests = requests;
}
if (!isUndefined(errors)) {
metrics.errors = errors
}
if (metrics.requests !== 0) {
metrics.errorRate = metrics.errors / metrics.requests
}
if (!isUndefined(responseTime)) {
const { sumTimings } = this.controller.props.options;
if (sumTimings && metrics.requests) {
metrics.responseTime = responseTime / metrics.requests;
} else {
metrics.responseTime = responseTime;
}
}
return edge;
}
_createEdges(data: GraphDataElement[]): IGraphEdge[] {
const filteredData = _(data)
.filter(e => !!e.source)
.filter(e => e.source !== e.target)
.value();
const edges = map(filteredData, element => this._createEdge(element));
return edges.filter(isPresent);
}
_filterData(graph: IGraph): IGraph {
const { filterEmptyConnections: filterData } = this.controller.props.options;
if (filterData) {
const filteredGraph: IGraph = {
nodes: [],
edges: []
};
// filter empty connections
filteredGraph.edges = filter(graph.edges, edge => size(edge.metrics) > 0);
filteredGraph.nodes = filter(graph.nodes, node => {
const name = node.name;
// don't filter connected elements
if (some(graph.edges, { 'source': name }) || some(graph.edges, { 'target': name })) {
return true;
}
const metrics = node.metrics;
if (!metrics) {
return false; // no metrics
}
// only if rate, error rate or response time is available
return defaultTo(metrics.requests, -1) >= 0
|| defaultTo(metrics.errors, -1) >= 0
|| defaultTo(metrics.responseTime, -1) >= 0;
});
return filteredGraph;
} else {
return graph;
}
}
generateGraph(graphData: GraphDataElement[]): IGraph {
//const filteredData = this._filterData(graphData);
const nodes = this._createNodes(graphData);
const edges = this._createEdges(graphData);
const graph: IGraph = {
nodes,
edges
};
const filteredGraph = this._filterData(graph);
console.groupCollapsed('Graph generated');
console.log('Input data:', graphData);
console.log('Nodes:', nodes);
console.log('Edges:', edges);
console.log('Filtered graph', filteredGraph);
console.groupEnd();
return filteredGraph;
}
}
export default GraphGenerator; | the_stack |
import React, { useMemo, useRef } from 'react';
import { defineMessages, FormattedMessage } from 'react-intl';
import { ColonyRole } from '@colony/colony-js';
import FriendlyName from '~core/FriendlyName';
import PermissionsLabel from '~core/PermissionsLabel';
import ActionsPageFeed, {
SystemInfo,
SystemMessage,
ActionsPageFeedType,
ActionsPageFeedItem,
ActionsPageFeedItemWithIPFS,
ActionsPageEvent,
EventValues,
FeedItemWithId,
ActionsPageSystemInfo,
ActionsPageSystemMessage,
} from '~dashboard/ActionsPageFeed';
import ActionsPageComment from '~dashboard/ActionsPageComment';
import {
useLoggedInUser,
Colony,
ColonyActionQuery,
TokenInfoQuery,
AnyUser,
useRecoveryEventsForSessionQuery,
useRecoverySystemMessagesForSessionQuery,
ParsedEvent,
TransactionMessageFragment,
} from '~data/index';
import { ColonyActions, ColonyAndExtensionsEvents } from '~types/index';
import MultisigWidget from '../MultisigWidget';
import InputStorageWidget from '../InputStorageWidget';
import DetailsWidget from '../DetailsWidget';
import ApproveExitWidget from '../ApproveExitWidget';
import styles from './DefaultAction.css';
import recoverySpecificStyles from './RecoveryAction.css';
const MSG = defineMessages({
recoveryTag: {
id: 'dashboard.ActionsPage.RecoveryAction.recovery',
defaultMessage: `Recovery`,
},
tip: {
id: 'dashboard.ActionsPage.RecoveryAction.tip',
defaultMessage: `{tipTitle} While in recovery mode the colony is disabled
and no actions may be taken.
A {role} permission holder may update storage slots to rectify the issue that
caused {user} to take this action.
A majority of {role} permission holders must satisfy themselves that this issue
has been overcome and the colony is secure, and sign a transaction to approve
exiting recovery mode, and then reactivate the colony.
Approvals are reset each time storage slots are updated.`,
},
tipTitle: {
id: 'dashboard.ActionsPage.RecoveryAction.tipTitle',
defaultMessage: 'Tip:',
},
newSlotValue: {
id: 'dashboard.ActionsPage.RecoveryAction.newSlotValue',
defaultMessage: 'New slot value',
},
previousSlotValue: {
id: 'dashboard.ActionsPage.RecoveryAction.previousSlotValue',
defaultMessage: 'Previous value: {slotValue}',
},
approvalResetNotice: {
id: 'dashboard.ActionsPage.RecoveryAction.approvalResetNotice',
defaultMessage: 'Approvals to exit recovery have been reset.',
},
});
const displayName = 'dashboard.ActionsPage.RecoveryAction';
interface Props {
colony: Colony;
colonyAction: ColonyActionQuery['colonyAction'];
token: TokenInfoQuery['tokenInfo'];
transactionHash: string;
recipient: AnyUser;
initiator: AnyUser;
}
const RecoveryAction = ({
colony,
colony: { colonyAddress },
colonyAction: {
events = [],
createdAt: actionCreatedAt,
actionType,
annotationHash,
colonyDisplayName,
blockNumber,
},
colonyAction,
transactionHash,
recipient,
initiator,
}: Props) => {
const bottomElementRef = useRef<HTMLInputElement>(null);
const { username: currentUserName, ethereal } = useLoggedInUser();
const fallbackStorageSlotValue = `0x${'0'.padStart(64, '0')}`;
const {
data: recoveryEvents,
loading: recoveryEventsLoading,
} = useRecoveryEventsForSessionQuery({
variables: {
blockNumber,
colonyAddress,
},
});
const {
data: recoverySystemMessages,
loading: recoverySystemMessagesLoading,
} = useRecoverySystemMessagesForSessionQuery({
variables: {
blockNumber,
colonyAddress,
},
});
const isInRecoveryMode = useMemo(() => {
if (recoveryEvents?.recoveryEventsForSession) {
return !recoveryEvents.recoveryEventsForSession.find(
({ name }) => name === ColonyAndExtensionsEvents.RecoveryModeExited,
);
}
return false;
}, [recoveryEvents]);
/*
* @NOTE We need to convert the action type name into a forced camel-case string
*
* This is because it might have a name that contains spaces, and ReactIntl really
* doesn't like that...
*/
const actionAndEventValues = {
actionType,
initiator: (
<span className={styles.titleDecoration}>
<FriendlyName user={initiator} autoShrinkAddress />
</span>
),
colonyName: (
<FriendlyName
colony={{
...colony,
...(colonyDisplayName ? { displayName: colonyDisplayName } : {}),
}}
autoShrinkAddress
/>
),
};
const recoveryModeSystemInfo: SystemInfo = {
type: ActionsPageFeedType.SystemInfo,
text: MSG.tip,
/*
* Position in the feed array
* This is because these can be inserted at any point the feed and are not
* affected by creation time / date
*/
position: 1,
textValues: {
tipTitle: (
<span className={recoverySpecificStyles.tipTitle}>
<FormattedMessage {...MSG.tipTitle} />
</span>
),
user: (
<span className={styles.titleDecoration}>
<FriendlyName user={initiator} autoShrinkAddress />
</span>
),
role: (
<PermissionsLabel
permission={ColonyRole.Recovery}
name={{ id: `role.${ColonyRole.Recovery}` }}
/>
),
},
appearance: { theme: 'recovery' },
};
return (
<div className={styles.main}>
<div className={styles.container}>
<p className={styles.recoveryTag}>
<FormattedMessage {...MSG.recoveryTag} />
</p>
</div>
<hr className={styles.dividerTop} />
<div className={styles.container}>
<div className={styles.content}>
{/*
* @NOTE Can't use `Heading` here since it uses `formmatedMessage` internally
* for message descriptors, and that doesn't support our complex text values
*/}
<h1 className={styles.heading}>
<FormattedMessage
id="action.title"
values={{
...actionAndEventValues,
}}
/>
</h1>
{annotationHash && (
<ActionsPageFeedItemWithIPFS
createdAt={actionCreatedAt}
user={initiator}
annotation
hash={annotationHash}
/>
)}
<ActionsPageFeed
actionType={actionType}
transactionHash={transactionHash as string}
networkEvents={[
...events,
...(recoveryEvents?.recoveryEventsForSession || []),
]}
systemInfos={[recoveryModeSystemInfo]}
systemMessages={
/*
* @NOTE Prettier is stupid, it keeps changing this line in a way that
* breaks it
*/
// eslint-disable-next-line prettier/prettier,max-len
recoverySystemMessages?.recoverySystemMessagesForSession as SystemMessage[]
}
values={actionAndEventValues}
actionData={colonyAction}
colony={colony}
loading={recoveryEventsLoading || recoverySystemMessagesLoading}
>
{(feedItems) =>
feedItems.map((item, index) => {
/*
* Event
*/
if (item.type === ActionsPageFeedType.NetworkEvent) {
const {
name,
createdAt,
emmitedBy,
uniqueId,
values: eventValues,
} = item as FeedItemWithId<ParsedEvent>;
return (
<ActionsPageEvent
key={uniqueId}
eventIndex={index}
createdAt={new Date(createdAt)}
transactionHash={transactionHash}
eventName={name}
actionData={colonyAction}
values={{
...((eventValues as unknown) as EventValues),
...actionAndEventValues,
}}
emmitedBy={emmitedBy}
colony={colony}
>
{name ===
ColonyAndExtensionsEvents.RecoveryStorageSlotSet && (
<div
className={recoverySpecificStyles.additionalEventInfo}
>
<div className={recoverySpecificStyles.storageSlot}>
<FormattedMessage
tagName="p"
{...MSG.newSlotValue}
/>
<div className={recoverySpecificStyles.slotValue}>
{((eventValues as unknown) as EventValues)
?.toValue || fallbackStorageSlotValue}
</div>
<p
className={
recoverySpecificStyles.previousSlotValue
}
>
<FormattedMessage
{...MSG.previousSlotValue}
values={{
slotValue: (
<span>
{((eventValues as unknown) as EventValues)
?.fromValue || fallbackStorageSlotValue}
</span>
),
}}
/>
</p>
</div>
<p
className={
recoverySpecificStyles.approvalResetNotice
}
>
<FormattedMessage {...MSG.approvalResetNotice} />
</p>
</div>
)}
</ActionsPageEvent>
);
}
/*
* Comment
*/
if (item.type === ActionsPageFeedType.ServerComment) {
const {
initiator: messageInitiator,
createdAt,
context: { message },
uniqueId,
} = (item as unknown) as FeedItemWithId<
TransactionMessageFragment
>;
return (
<ActionsPageFeedItem
key={uniqueId}
createdAt={createdAt}
comment={message}
user={messageInitiator}
/>
);
}
/*
* System Info
*/
if (item.type === ActionsPageFeedType.SystemInfo) {
const {
text,
textValues,
appearance,
uniqueId,
} = item as FeedItemWithId<SystemInfo>;
return (
<ActionsPageSystemInfo
key={uniqueId}
tip={text}
tipValues={textValues}
appearance={appearance}
/>
);
}
/*
* System Message
*/
if (item.type === ActionsPageFeedType.SystemMessage) {
const { uniqueId } = item as FeedItemWithId<SystemMessage>;
return (
<ActionsPageSystemMessage
key={uniqueId}
systemMessage={item as SystemMessage}
/>
);
}
return null;
})
}
</ActionsPageFeed>
{/*
* @NOTE A user can comment only if he has a wallet connected
* and a registered user profile
*/}
{currentUserName && !ethereal && (
<div ref={bottomElementRef}>
<ActionsPageComment
transactionHash={transactionHash}
colonyAddress={colonyAddress}
/>
</div>
)}
</div>
<div className={styles.details}>
{isInRecoveryMode && (
<>
<ApproveExitWidget
colony={colony}
startBlock={blockNumber}
scrollToRef={bottomElementRef}
/>
<InputStorageWidget
colony={colony}
startBlock={blockNumber}
scrollToRef={bottomElementRef}
/>
</>
)}
<MultisigWidget
colony={colony}
startBlock={blockNumber}
scrollToRef={bottomElementRef}
isInRecoveryMode={isInRecoveryMode}
/>
<DetailsWidget
actionType={actionType as ColonyActions}
recipient={recipient}
transactionHash={transactionHash}
values={actionAndEventValues}
colony={colony}
/>
</div>
</div>
</div>
);
};
RecoveryAction.displayName = displayName;
export default RecoveryAction; | the_stack |
import Event, { CHECK_SAPARATOR, DOM_EVENT_SAPARATOR, SAPARATOR, NAME_SAPARATOR, CHECK_DOM_EVENT_PATTERN } from "../Event";
import { Dom } from "../functions/Dom";
import { debounce, throttle, isNotUndefined, isFunction, splitMethodByKeyword } from "../functions/func";
import { DomElement, IDom, IDomEventObject, IDomEventObjectOption, IMultiCallback } from "../types";
import { BaseHandler } from "./BaseHandler";
const scrollBlockingEvents = {
'touchstart': true,
'touchmove': true,
'mousedown': true,
'mouseup': true,
'mousemove': true,
// wheel, mousewheel 은 prevent 를 해야한다. 그래서 scroll blocking 을 막아야 한다.
// 'wheel': true,
// 'mousewheel': true
}
const eventConverts = {
'doubletab': 'touchend'
}
const customEventNames = {
'doubletab': true
}
export class DomEventHandler extends BaseHandler {
_domEvents: any;
_bindings?: IDomEventObject[];
doubleTab: any;
initialize() {
this.destroy();
if (!this._domEvents) {
this._domEvents = this.context.filterProps(CHECK_DOM_EVENT_PATTERN)
}
this._domEvents.forEach((key: string) => this.parseDomEvent(key));
}
destroy() {
this.removeEventAll();
}
removeEventAll() {
this.getBindings()?.forEach((obj: IDomEventObject) => {
this.removeDomEvent(obj);
});
this.initBindings();
}
removeDomEvent({ eventName, dom, callback }: IDomEventObject) {
if (dom) {
Event.removeDomEvent(dom, eventName, callback as EventListenerOrEventListenerObject);
}
}
getBindings() {
if (!this._bindings) {
this.initBindings();
}
return this._bindings;
}
addBinding(obj: IDomEventObject) {
this.getBindings()?.push(obj);
}
initBindings() {
this._bindings = [];
}
matchPath (el: Element, selector: string): Element|null {
if (el) {
if (el.matches(selector)) {
return el;
}
return this.matchPath(el.parentElement as Element, selector);
}
return null;
}
hasDelegate (e: any, eventObject: IDomEventObject) {
return this.matchPath(e.target || e.srcElement, eventObject.delegate as string);
}
makeCallback (eventObject: IDomEventObject, callback: Function) {
if (eventObject.delegate) {
return this.makeDelegateCallback(eventObject, callback);
} else {
return this.makeDefaultCallback(eventObject, callback);
}
}
makeDefaultCallback (eventObject: IDomEventObject, callback: Function) {
return (e: any) => {
var returnValue = this.runEventCallback(e, eventObject, callback);
if (isNotUndefined(returnValue)) {
return returnValue;
}
};
}
makeDelegateCallback (eventObject: IDomEventObject, callback: Function) {
return (e: any) => {
const delegateTarget = this.hasDelegate(e, eventObject);
if (delegateTarget) {
// delegate target 이 있는 경우만 callback 실행
e.$dt = Dom.create(delegateTarget as DomElement);
var returnValue = this.runEventCallback(e, eventObject, callback);
if (isNotUndefined(returnValue)) {
return returnValue;
}
}
};
}
runEventCallback (e: any, eventObject: IDomEventObject, callback: Function) {
const context = this.context;
e.xy = Event.posXY(e);
if (eventObject.beforeMethods.length) {
eventObject.beforeMethods.every((before) => {
return context[before.target].call(context, e, before.param);
});
}
if (this.checkEventType(e, eventObject)) {
var returnValue = callback(e, e.$dt, e.xy);
if (returnValue !== false && eventObject.afterMethods.length) {
eventObject.afterMethods.forEach(after => {
return context[after.target].call(context, e, after.param)
});
}
return returnValue;
}
}
checkEventType (e: any, eventObject: IDomEventObject) {
const context = this.context;
// 특정 keycode 를 가지고 있는지 체크
var hasKeyCode = true;
if (eventObject.codes.length) {
hasKeyCode =
(e.code ? eventObject.codes.indexOf(e.code.toLowerCase()) > -1 : false) ||
(e.key ? eventObject.codes.indexOf(e.key.toLowerCase()) > -1 : false);
}
// 체크 메소드들은 모든 메소드를 다 적용해야한다.
var isAllCheck = true;
if (eventObject.checkMethodList.length) {
isAllCheck = eventObject.checkMethodList.every(field => {
var fieldValue = context[field];
if (isFunction(fieldValue) && fieldValue) {
// check method
return fieldValue.call(context, e);
} else if (isNotUndefined(fieldValue)) {
// check field value
return !!fieldValue;
}
return true;
});
}
return hasKeyCode && isAllCheck;
}
getDefaultDomElement(dom: Element|string) {
const context = this.context;
let el;
if (typeof dom === 'string' && dom) {
el = context.refs[dom] || context[dom] || window[dom];
} else {
el = context.el || context.$el || context.$root;
}
if (el instanceof Dom) {
return el.getElement();
}
return el;
};
getRealEventName (eventName: string) {
return eventConverts[eventName] || eventName;
}
getCustomEventName (eventName: string) {
return customEventNames[eventName] ? eventName: '';
}
/**
*
* doubletab -> touchend 로 바뀜
*/
getDefaultEventObject (eventName: string, checkMethodFilters: string[]): IDomEventObject {
const context = this.context;
let arr = checkMethodFilters;
// context 에 속한 변수나 메소드 리스트 체크
const checkMethodList = arr.filter(code => !!context[code]);
// 이벤트 정의 시점에 적용 되어야 하는 것들은 모두 method() 화 해서 정의한다.
const [afters, afterMethods] = splitMethodByKeyword(arr, "after");
const [befores, beforeMethods] = splitMethodByKeyword(arr, "before");
const [debounces, debounceMethods] = splitMethodByKeyword(arr, "debounce");
const [delays, delayMethods] = splitMethodByKeyword(arr, "delay");
const [throttles, throttleMethods] = splitMethodByKeyword(arr, "throttle");
const [captures] = splitMethodByKeyword(arr, "capture");
// 위의 5개 필터 이외에 있는 코드들은 keycode 로 인식한다.
const filteredList = [
...checkMethodList,
...afters,
...befores,
...delays,
...debounces,
...throttles,
...captures
];
var codes = arr
.filter(code => filteredList.indexOf(code) === -1)
.map(code => code.toLowerCase());
return {
eventName: this.getRealEventName(eventName),
customEventName: this.getCustomEventName(eventName),
codes,
captures,
afterMethods,
beforeMethods,
delayMethods,
debounceMethods,
throttleMethods,
checkMethodList
};
}
addDomEvent (eventObject: IDomEventObject, callback: Function) {
eventObject.callback = this.makeCallback(eventObject, callback);
this.addBinding(eventObject);
var options: boolean|IDomEventObjectOption = !!eventObject.captures.length
if (scrollBlockingEvents[eventObject.eventName]) {
options = {
passive: true,
capture: options
}
}
if (eventObject?.dom) {
Event.addDomEvent(
eventObject?.dom,
eventObject.eventName,
eventObject.callback,
options
);
}
}
makeCustomEventCallback (eventObject: IDomEventObject, callback: Function): IMultiCallback {
if (eventObject.customEventName === 'doubletab') {
var delay = 300;
if (eventObject.delayMethods.length) {
delay = +eventObject.delayMethods[0].target;
}
return (...args: any[]) => {
if (!this.doubleTab) {
this.doubleTab = {
time: performance.now(),
}
} else {
if (performance.now() - this.doubleTab.time < delay) {
callback(...args);
}
this.doubleTab = null;
}
}
}
return callback as IMultiCallback;
}
bindingDomEvent ( [eventName, dom, ...delegate]: string[], checkMethodFilters: string[], callback: IMultiCallback ) {
let eventObject = this.getDefaultEventObject(eventName, checkMethodFilters);
eventObject.dom = this.getDefaultDomElement(dom);
eventObject.delegate = delegate.join(SAPARATOR);
if (eventObject.debounceMethods.length) {
var debounceTime = +eventObject.debounceMethods[0].target;
callback = debounce(callback, debounceTime);
} else if (eventObject.throttleMethods.length) {
var throttleTime = +eventObject.throttleMethods[0].target;
callback = throttle(callback, throttleTime);
}
// custom event callback 만들기
callback = this.makeCustomEventCallback(eventObject, callback)
this.addDomEvent(eventObject, callback);
};
getEventNames (eventName: string) {
let results: string[] = [];
eventName.split(NAME_SAPARATOR).forEach(e => {
var arr = e.split(NAME_SAPARATOR);
results.push.apply(results, arr);
});
return results;
}
/**
* 이벤트 문자열 파싱하기
*
* @param {string} key
*/
parseDomEvent (key: string) {
const context = this.context;
let checkMethodFilters = key.split(CHECK_SAPARATOR).map(it => it.trim()).filter(Boolean);
var prefix = checkMethodFilters.shift()
var eventSelectorAndBehave = prefix?.split(DOM_EVENT_SAPARATOR)[1];
var arr = eventSelectorAndBehave?.split(SAPARATOR);
if (arr) {
var eventNames = this.getEventNames(arr[0]);
var callback = context[key].bind(context);
for(let i = 0, len = eventNames.length; i< len; i++) {
arr[0] = eventNames[i];
this.bindingDomEvent(arr, checkMethodFilters, callback);
}
}
}
} | the_stack |
import '@gravitee/ui-components/wc/gv-header';
import '@gravitee/ui-components/wc/gv-menu';
import '@gravitee/ui-components/wc/gv-message';
import '@gravitee/ui-components/wc/gv-nav';
import '@gravitee/ui-components/wc/gv-user-menu';
import '@gravitee/ui-components/wc/gv-theme';
import {
AfterViewInit,
ChangeDetectorRef,
Component,
ComponentFactoryResolver,
HostListener,
OnDestroy,
OnInit,
ViewChild,
} from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { Title } from '@angular/platform-browser';
import { marker as i18n } from '@biesbjerg/ngx-translate-extract-marker';
import { UserNotificationComponent } from './pages/user/user-notification/user-notification.component';
import { CurrentUserService } from './services/current-user.service';
import { NotificationService } from './services/notification.service';
import {
ActivatedRoute,
NavigationEnd,
NavigationStart,
PRIMARY_OUTLET,
Router,
RouterOutlet,
UrlSegmentGroup,
UrlTree,
} from '@angular/router';
import { INavRoute, NavRouteService } from './services/nav-route.service';
import { animation } from './route-animation';
import { Link, PortalService, User, UserService } from '../../projects/portal-webclient-sdk/src/lib';
import { Notification } from './model/notification';
import { GvMenuTopSlotDirective } from './directives/gv-menu-top-slot.directive';
import { GvMenuRightTransitionSlotDirective } from './directives/gv-menu-right-transition-slot.directive';
import { ConfigurationService } from './services/configuration.service';
import { FeatureEnum } from './model/feature.enum';
import { GvMenuRightSlotDirective } from './directives/gv-menu-right-slot.directive';
import { GvSlot } from './directives/gv-slot';
import { GoogleAnalyticsService } from './services/google-analytics.service';
import { EventService, GvEvent } from './services/event.service';
import { PreviewService } from './services/preview.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
animations: [animation],
})
export class AppComponent implements AfterViewInit, OnInit, OnDestroy {
static UPDATE_USER_AVATAR: ':gv-user:avatar';
public mainRoutes: Promise<INavRoute[]>;
public userRoutes: Promise<INavRoute[]>;
public menuRoutes: Promise<INavRoute[]>;
public currentUser: User;
public userPicture: string;
public notification: Notification;
public isPreview = false;
public isSticky = false;
public isHomepage = false;
public isStickyHomepage = false;
public links: any = {};
@ViewChild(GvMenuTopSlotDirective, { static: true }) appGvMenuTopSlot: GvMenuTopSlotDirective;
@ViewChild(GvMenuRightTransitionSlotDirective, { static: true }) appGvMenuRightTransitionSlot: GvMenuRightTransitionSlotDirective;
@ViewChild(GvMenuRightSlotDirective, { static: true }) appGvMenuRightSlot: GvMenuRightSlotDirective;
@ViewChild('homepageBackground', { static: true }) homepageBackground;
private slots: Array<GvSlot>;
private homepageBackgroundHeight: number;
private interval: any;
public numberOfPortalNotifications: any;
public homepageTitle: string;
constructor(
private titleService: Title,
private translateService: TranslateService,
private router: Router,
private currentUserService: CurrentUserService,
private navRouteService: NavRouteService,
private notificationService: NotificationService,
private activatedRoute: ActivatedRoute,
private componentFactoryResolver: ComponentFactoryResolver,
private configurationService: ConfigurationService,
private portalService: PortalService,
private userService: UserService,
private eventService: EventService,
private ref: ChangeDetectorRef,
private googleAnalyticsService: GoogleAnalyticsService,
private previewService: PreviewService,
) {
this.activatedRoute.queryParamMap.subscribe((params) => {
if (params.has('preview') && params.get('preview') === 'on') {
this.previewService.activate();
}
});
this.router.events.subscribe((event) => {
if (event instanceof NavigationStart) {
this.notificationService.reset();
if (!this.currentUserService.exist() && !this.isInLoginOrRegistration(event.url) && this.forceLogin()) {
const redirectUrl = event.url;
this.router.navigate(['/user/login'], { replaceUrl: true, queryParams: { redirectUrl } });
}
} else if (event instanceof NavigationEnd) {
const currentRoute: ActivatedRoute = this.navRouteService.findCurrentRoute(this.activatedRoute);
this._setBrowserTitle(currentRoute);
this.isPreview = previewService.isActive();
this._onNavigationEnd(event);
}
});
}
async ngOnInit() {
this.homepageTitle =
this.configurationService.get('portal.homepageTitle') || (await this.translateService.get(i18n('homepage.title')).toPromise());
this.googleAnalyticsService.load();
this.currentUserService.get().subscribe((newCurrentUser) => {
this.currentUser = newCurrentUser;
this.userRoutes = this.navRouteService.getUserNav();
if (this.currentUser) {
setTimeout(() => {
this.userPicture = this.currentUser._links ? this.currentUser._links.avatar : null;
});
this.loadNotifications();
this.interval = setInterval(() => {
this.loadNotifications();
}, this.configurationService.get('scheduler.notificationsInSeconds') * 1000);
} else {
this.userPicture = null;
clearInterval(this.interval);
}
});
this.notificationService.notification.subscribe((notification) => {
if (notification) {
this.translateService.get(notification.code, notification.parameters).subscribe((translatedMessage) => {
if (notification.code !== translatedMessage || !notification.message) {
notification.message = translatedMessage;
}
this.notification = notification;
});
} else {
delete this.notification;
}
this.ref.detectChanges();
});
}
private loadNotifications() {
this.userService
.getCurrentUserNotifications({ size: 1 })
.toPromise()
.then((response) => {
if (response.data && response.data[0]) {
const portalNotification = response.data[0];
const total = response.metadata.pagination ? response.metadata.pagination.total : 0;
if (this.numberOfPortalNotifications !== null && total > this.numberOfPortalNotifications) {
this.eventService.dispatch(new GvEvent(UserNotificationComponent.NEW));
const windowNotification = (window as any).Notification;
if (windowNotification) {
windowNotification.requestPermission().then((permission) => {
if (permission === 'granted') {
const n = new windowNotification(portalNotification.title, {
body: portalNotification.message,
});
}
});
}
}
this.numberOfPortalNotifications = total;
this.ref.detectChanges();
}
});
}
ngAfterViewInit() {
const loader = document.querySelector('#loader');
if (loader) {
loader.remove();
}
this.slots = [this.appGvMenuRightSlot, this.appGvMenuRightTransitionSlot, this.appGvMenuTopSlot];
this.eventService.subscribe((event) => {
if (event.type === UserNotificationComponent.REMOVE) {
this.loadNotifications();
} else if (event.type === AppComponent.UPDATE_USER_AVATAR) {
this.userPicture = event.details.data;
}
});
}
onCloseNotification() {
this.notificationService.reset();
}
@HostListener('window:beforeunload')
async ngOnDestroy() {
clearInterval(this.interval);
this.eventService.unsubscribe();
}
@HostListener(':gv-theme:error', ['$event.detail'])
onThemeError(detail) {
this.notificationService.error(detail.message);
}
@HostListener('window:scroll')
onScroll() {
this.computeMenuMode();
}
private computeMenuMode() {
const pageYOffset = window.pageYOffset;
window.requestAnimationFrame(() => {
if (this.isHomepage) {
this.isStickyHomepage = pageYOffset >= this.homepageBackgroundHeight - 70;
}
if (!this.isSticky) {
this.isSticky = pageYOffset > 50;
} else {
this.isSticky = !(pageYOffset === 0);
}
});
}
private computeHomepageHeight() {
if (this.isHomepage) {
setTimeout(() => {
if (this.homepageBackground.nativeElement) {
this.homepageBackgroundHeight = parseInt(window.getComputedStyle(this.homepageBackground.nativeElement).height, 10);
}
}, 0);
}
}
prepareRoute(outlet: RouterOutlet) {
return outlet && outlet.activatedRouteData && outlet.activatedRouteData.animation;
}
private _setBrowserTitle(currentRoute: ActivatedRoute) {
this.translateService.get(i18n('site.title')).subscribe((siteTitle) => {
const data = currentRoute.snapshot.data;
if (data && data.title) {
this.translateService.get(data.title).subscribe((title) => this.titleService.setTitle(`${title} | ${siteTitle}`));
} else {
this.titleService.setTitle(siteTitle);
}
});
}
_buildLinks(links: Link[]): INavRoute[] {
return links.map((element) => {
let path: string;
let target: string;
switch (element.resourceType) {
case Link.ResourceTypeEnum.External:
path = element.resourceRef;
if (path && path.toLowerCase().startsWith('http')) {
target = '_blank';
} else {
target = '_self';
}
break;
case Link.ResourceTypeEnum.Page:
if (element.folder) {
path = '/documentation';
if (element.resourceRef) {
path += '/' + element.resourceRef;
}
} else {
path = '/pages/' + element.resourceRef;
}
target = '_self';
break;
case Link.ResourceTypeEnum.Category:
path = '/catalog/categories/' + element.resourceRef;
target = '_self';
break;
}
const navRoute: INavRoute = {
active: this.router.isActive(path, false),
path,
target,
title: element.name,
};
return navRoute;
});
}
get userName() {
if (this.currentUser) {
if (this.currentUser.first_name && this.currentUser.last_name) {
const capitalizedFirstName = this.currentUser.first_name[0].toUpperCase() + this.currentUser.first_name.slice(1);
const shortLastName = this.currentUser.last_name[0].toUpperCase();
return `${capitalizedFirstName} ${shortLastName}.`;
} else {
return this.currentUser.display_name;
}
}
return null;
}
@HostListener(':gv-nav:click', ['$event.detail'])
@HostListener(':gv-link:click', ['$event.detail'])
onNavChange(route: INavRoute) {
if (route.target && route.target === '_blank') {
window.open(route.path, route.target);
} else {
const urlTree = this.router.parseUrl(route.path);
const path = urlTree.root.children[PRIMARY_OUTLET].segments.join('/');
this.router.navigate([path], { queryParams: urlTree.queryParams });
}
}
isHomepageUrl(url) {
const tree: UrlTree = this.router.parseUrl(url);
const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
if (g == null) {
return true;
}
return false;
}
private _onNavigationEnd(event: NavigationEnd) {
this.isHomepage = this.isHomepageUrl(event.url);
this.portalService.getPortalLinks().subscribe((portalLinks) => {
if (portalLinks.slots) {
this.mainRoutes = this.navRouteService.getChildrenNav({
data: { menu: true },
children: this.router.config.filter((route) => route.data && route.data.menu),
});
if (portalLinks.slots.header) {
const headerLinks = portalLinks.slots.header.find((catLinks) => catLinks.root);
if (headerLinks) {
const dynamicRoutes = this._buildLinks(headerLinks.links);
const hasDynamicRouteActive = dynamicRoutes.find((r) => r.active);
this.mainRoutes = this.mainRoutes.then((navRoutes) => {
if (hasDynamicRouteActive) {
const activeRoute = navRoutes.find((r) => r.active);
if (activeRoute) {
activeRoute.active = false;
}
}
return [...navRoutes, ...dynamicRoutes];
});
}
}
if (portalLinks.slots.footer) {
const footerLinks = portalLinks.slots.footer.find((catLinks) => catLinks.root);
if (footerLinks) {
this.links.footer = this._buildLinks(footerLinks.links);
}
}
if (portalLinks.slots.topfooter) {
this.links.topfooter = portalLinks.slots.topfooter
.filter((catLinks) => !catLinks.root)
.map((catLinks) => {
return {
title: catLinks.category,
links: this._buildLinks(catLinks.links),
};
});
}
}
});
const currentRoute: ActivatedRoute = this.navRouteService.findCurrentRoute(this.activatedRoute);
this.menuRoutes = this.navRouteService.getSiblingsNav(currentRoute);
if (this.menuRoutes) {
const menuOption = currentRoute.snapshot.data.menu;
if (typeof menuOption === 'object') {
const parentSlots = currentRoute.parent && currentRoute.parent.snapshot.data.menu && currentRoute.parent.snapshot.data.menu.slots;
this._injectMenuSlots({ ...menuOption.slots, ...parentSlots });
} else {
this._clearMenuSlots();
}
} else {
this._clearMenuSlots();
}
this.computeMenuMode();
this.computeHomepageHeight();
}
private _clearMenuSlots() {
this.slots.forEach((directive) => {
directive.clear();
});
}
private _injectMenuSlots(slots) {
this.slots.forEach((directive) => {
const name = directive.getName();
let slot = slots ? slots[name] : null;
if (slots && slots.expectedFeature && !this.configurationService.hasFeature(slots.expectedFeature)) {
slot = null;
}
if (slots && slots.expectedPermissions) {
const userPermissions = (this.currentUserService.get().getValue() && this.currentUserService.get().getValue().permissions) || {};
const expectedPermissions = slots.expectedPermissions;
const expectedPermissionsObject = {};
expectedPermissions.map((perm) => {
const splittedPerms = perm.split('-');
if (expectedPermissionsObject[splittedPerms[0]]) {
expectedPermissionsObject[splittedPerms[0]].push(splittedPerms[1]);
} else {
expectedPermissionsObject[splittedPerms[0]] = [splittedPerms[1]];
}
});
Object.keys(expectedPermissionsObject).forEach((perm) => {
const applicationRights = userPermissions[perm];
if (
slot !== null &&
(!applicationRights || (applicationRights && !this._includesAll(applicationRights, expectedPermissionsObject[perm])))
) {
slot = null;
}
});
}
this._updateSlot(slot, directive);
});
}
private _includesAll(applicationRights, expectedRights): boolean {
let includesAll = true;
expectedRights.forEach((r) => {
if (!applicationRights.includes(r)) {
includesAll = false;
}
});
return includesAll;
}
private _updateSlot(slot, directive) {
if (slot == null) {
directive.clear();
} else {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(slot);
directive.setComponent(componentFactory);
}
}
isAuthenticated(): boolean {
return this.currentUserService.get().getValue() !== null;
}
displaySignUp(): boolean {
return this.configurationService.hasFeature(FeatureEnum.userRegistration) && !this.isAuthenticated();
}
displayShadowNav(): boolean {
return this.isHomepage && !this.isAuthenticated();
}
goTo(path: string) {
this.router.navigate([path]);
}
isInLoginOrRegistration(url: string = this.router.routerState.snapshot.url): boolean {
return url.startsWith('/user/login') || url.startsWith('/user/registration') || url.startsWith('/user/resetPassword');
}
forceLogin(): boolean {
return this.configurationService.hasFeature(FeatureEnum.forceLogin);
}
} | the_stack |
import { CommonModule } from '@angular/common';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import {
ApplicationModule,
APP_INITIALIZER,
Component,
FactoryProvider,
InjectionToken,
Injector,
NgModule,
} from '@angular/core';
import {
async,
ComponentFixture,
TestBed,
} from '@angular/core/testing';
import { BrowserModule, By } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import coreReflectModuleResolve from '../common/core.reflect.module-resolve';
import ngMocksUniverse from '../common/ng-mocks-universe';
import { MockComponent } from '../mock-component/mock-component';
import { MockRender } from '../mock-render/mock-render';
import mockProvider from '../mock-service/mock-provider';
import { MockModule } from './mock-module';
import {
AppRoutingModule,
CustomWithServiceComponent,
ExampleComponent,
ExampleConsumerComponent,
LogicNestedModule,
LogicRootModule,
ModuleWithProvidersModule,
ParentModule,
SameImports1Module,
SameImports2Module,
WithServiceModule,
} from './mock-module.spec.fixtures';
@Component({
selector: 'component-subject',
template: `
<example-component></example-component>
<span example-directive></span>
{{ test | examplePipe }}
`,
})
class ComponentSubject {
public test = 'test';
}
@Component({
selector: 'same-imports',
template: `same imports`,
})
class SameImportsComponent {}
describe('MockModule', () => {
let fixture: ComponentFixture<ComponentSubject>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ComponentSubject],
imports: [
MockModule(ParentModule),
MockModule(ModuleWithProvidersModule),
],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(ComponentSubject);
fixture.detectChanges();
});
}));
it('should do stuff', () => {
const mockComponent = fixture.debugElement.query(
By.directive(MockComponent(ExampleComponent)),
).componentInstance as ExampleComponent;
expect(mockComponent).not.toBeNull();
});
});
describe('SameImportsModules', () => {
let fixture: ComponentFixture<SameImportsComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [SameImportsComponent],
imports: [
MockModule(SameImports1Module),
MockModule(SameImports2Module),
],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(SameImportsComponent);
fixture.detectChanges();
});
}));
it('should be imported correctly', () => {
expect(fixture.componentInstance).toEqual(
jasmine.any(SameImportsComponent),
);
expect(fixture.nativeElement.innerText).toEqual('same imports');
});
});
describe('NeverMockModules', () => {
let fixture: ComponentFixture<SameImportsComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [SameImportsComponent],
imports: [
MockModule(ApplicationModule),
MockModule(BrowserAnimationsModule),
MockModule(BrowserModule),
MockModule(CommonModule),
],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(SameImportsComponent);
fixture.detectChanges();
});
}));
it('should not fail when we pass them to MockModule', () => {
expect(fixture.componentInstance).toEqual(
jasmine.any(SameImportsComponent),
);
expect(fixture.nativeElement.innerText).toEqual('same imports');
});
});
describe('RouterModule', () => {
let fixture: ComponentFixture<ExampleComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ExampleComponent],
imports: [MockModule(AppRoutingModule)],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(ExampleComponent);
fixture.detectChanges();
});
}));
it('should not fail when we pass RouterModule to MockModule', () => {
expect(fixture.componentInstance).toEqual(
jasmine.any(ExampleComponent),
);
expect(fixture.nativeElement.innerText).toEqual('My Example');
});
});
// What we mock should always export own private imports and declarations to allow us to use it in TestBed.
// In this test we check that nested module from cache still provides own private things.
// See https://github.com/ike18t/ng-mocks/pull/35
describe('Usage of cached nested module', () => {
let fixture: ComponentFixture<ExampleConsumerComponent>;
describe('1st test for root', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ExampleConsumerComponent],
imports: [MockModule(LogicRootModule)],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(ExampleConsumerComponent);
fixture.detectChanges();
});
}));
it('should be able to find component', () => {
expect(fixture.componentInstance).toEqual(
jasmine.any(ExampleConsumerComponent),
);
});
});
describe('2nd test for nested', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ExampleConsumerComponent],
imports: [MockModule(LogicNestedModule)],
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(ExampleConsumerComponent);
fixture.detectChanges();
});
}));
it('should be able to find component', () => {
expect(fixture.componentInstance).toEqual(
jasmine.any(ExampleConsumerComponent),
);
});
});
});
describe('WithServiceModule', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [CustomWithServiceComponent],
imports: [MockModule(WithServiceModule)],
});
}));
it('should not throw an error of service method', () => {
const fixture = MockRender('<custom-service></custom-service>');
expect(fixture).toBeDefined();
});
});
describe('mockProvider', () => {
const CUSTOM_TOKEN = new InjectionToken('TOKEN');
@NgModule({
providers: [
{
multi: true,
provide: HTTP_INTERCEPTORS,
useValue: 'MY_CUSTOM_VALUE',
},
{
provide: CUSTOM_TOKEN,
useValue: 'MY_CUSTOM_VALUE',
},
],
})
class CustomTokenModule {}
it('should skip multi tokens in a mock module', () => {
const mock = MockModule(CustomTokenModule);
const def = coreReflectModuleResolve(mock);
expect(def.providers).toEqual([
{
deps: [Injector],
provide: CUSTOM_TOKEN,
useFactory: jasmine.anything(),
},
]);
const provider: any = !Array.isArray(def.providers?.[0])
? def.providers?.[0]
: undefined;
expect(provider?.useFactory()).toEqual('');
});
it('should return undefined on any token', () => {
const p1: any = mockProvider(CUSTOM_TOKEN, true);
expect(p1).toEqual({
deps: [Injector],
provide: CUSTOM_TOKEN,
useFactory: jasmine.anything(),
});
expect(p1.useFactory()).toEqual(undefined);
const p2: any = mockProvider(HTTP_INTERCEPTORS, true);
expect(p2).toEqual({
deps: [Injector],
provide: HTTP_INTERCEPTORS,
useFactory: jasmine.anything(),
});
expect(p2.useFactory()).toEqual(undefined);
expect(mockProvider(APP_INITIALIZER)).toBeUndefined();
});
it('should return default value on primitives', () => {
const p1: any = mockProvider({
provide: CUSTOM_TOKEN,
useValue: undefined,
});
expect(p1).toEqual({
deps: [Injector],
provide: CUSTOM_TOKEN,
useFactory: jasmine.anything(),
});
expect(p1.useFactory()).toEqual(undefined);
const p2: any = mockProvider({
provide: CUSTOM_TOKEN,
useValue: 123,
});
expect(p2).toEqual({
deps: [Injector],
provide: CUSTOM_TOKEN,
useFactory: jasmine.anything(),
});
expect(p2.useFactory()).toEqual(0);
const p3: any = mockProvider({
provide: CUSTOM_TOKEN,
useValue: true,
});
expect(p3).toEqual({
deps: [Injector],
provide: CUSTOM_TOKEN,
useFactory: jasmine.anything(),
});
expect(p3.useFactory()).toEqual(false);
const p4: any = mockProvider({
provide: CUSTOM_TOKEN,
useValue: 'true',
});
expect(p4).toEqual({
deps: [Injector],
provide: CUSTOM_TOKEN,
useFactory: jasmine.anything(),
});
expect(p4.useFactory()).toEqual('');
const p5: any = mockProvider({
provide: CUSTOM_TOKEN,
useValue: null,
});
expect(p5).toEqual({
deps: [Injector],
provide: CUSTOM_TOKEN,
useFactory: jasmine.anything(),
});
expect(p5.useFactory()).toEqual(null);
const mock: FactoryProvider = mockProvider({
provide: CUSTOM_TOKEN,
useValue: {
func: () => undefined,
test: 123,
},
}) as any;
expect(mock).toEqual({
deps: [Injector],
provide: CUSTOM_TOKEN,
useFactory: jasmine.anything(),
});
expect(mock.useFactory(null)).toEqual({
func: jasmine.anything(),
});
});
});
describe('MockModuleWithProviders', () => {
const TARGET_TOKEN = new InjectionToken('TOKEN');
@NgModule()
class TargetModule {}
it('returns the same object on zero change', () => {
const def = {
ngModule: TargetModule,
providers: [
{
provide: TARGET_TOKEN,
useValue: 1,
},
],
};
ngMocksUniverse.flags.add('skipMock');
const actual = MockModule(def);
ngMocksUniverse.flags.delete('skipMock');
expect(actual).toBe(def);
});
it('returns a mock ngModule with undefined providers', () => {
const def = {
ngModule: TargetModule,
};
const actual = MockModule(def);
expect(actual.ngModule).toBeDefined();
});
}); | the_stack |
import * as React from "react";
import { Listbox, Transition } from "@headlessui/react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCheck, faSort } from "@fortawesome/free-solid-svg-icons";
import {
PropertyTypes,
ConfigurationPropertyValue,
SelectOption,
ConfigurationProperty,
applyStringPropertyTransformations,
applyNumberPropertyTransformations,
} from "@codotype/core";
import Switch from "react-switch";
import classnames from "classnames";
import { RadioGroup } from "@headlessui/react";
// // // //
interface ConfigurationInputPrimitiveProps {
value: any;
property: ConfigurationProperty;
onChange: (updatedValue: ConfigurationPropertyValue) => void;
}
export default function DropdownMenu(props: ConfigurationInputPrimitiveProps) {
const { value, property, onChange } = props;
const { content } = property;
const selectedOption:
| undefined
| SelectOption = property.selectOptions.find(o => o.value === value);
return (
<Listbox value={value} onChange={onChange}>
{({ open }) => (
<div className="mt-1 relative">
<Listbox.Button className="bg-white dark:bg-gray-900 relative w-full border border-gray-300 dark:border-gray-700 rounded-md shadow-sm pl-3 pr-10 py-2 text-left cursor-default focus:outline-none focus:ring-1 focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
<span className="block truncate text-lg">
{selectedOption === undefined
? content.label
: selectedOption.label}
</span>
<span className="absolute inset-y-0 right-0 flex items-center pr-2 pointer-events-none">
<FontAwesomeIcon icon={faSort} />
</span>
</Listbox.Button>
<Transition
show={open}
as={React.Fragment}
leave="transition ease-in duration-100"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<Listbox.Options
static
className="absolute z-10 mt-1 w-full bg-white dark:bg-gray-900 shadow-lg max-h-60 rounded-md py-1 text-base ring-1 ring-black ring-opacity-5 overflow-auto focus:outline-none sm:text-sm"
>
{property.selectOptions.map(option => (
<Listbox.Option
key={option.value}
className={({ active }) =>
classnames(
"cursor-default text-lg select-none relative py-2 pl-3 pr-9",
{
"text-gray-900 dark:text-gray-300": !active,
"text-white dark:text-gray-200 bg-indigo-600": active,
},
)
}
value={option.value}
>
{({ selected, active }) => (
<>
<span
className={classnames(
"block truncate",
{
"font-semibold": selected,
"font-normal": !selected,
},
)}
>
{option.label}
</span>
{selected ? (
<span
className={classnames(
"absolute inset-y-0 right-0 flex items-center pr-4",
{
"text-white": active,
"text-indigo-600": !active,
},
)}
>
<FontAwesomeIcon
icon={faCheck}
/>
</span>
) : null}
</>
)}
</Listbox.Option>
))}
</Listbox.Options>
</Transition>
</div>
)}
</Listbox>
);
}
// // // //
export function RadioGroupInput(props: ConfigurationInputPrimitiveProps) {
const { value, property, onChange } = props;
const { content } = property;
return (
<RadioGroup value={value} onChange={onChange}>
<RadioGroup.Label className="sr-only">
{content.label}
</RadioGroup.Label>
<div className="space-y-4">
{property.selectOptions.map(option => (
<RadioGroup.Option
key={option.value}
value={option.value}
className={({ active }) =>
classnames(
"relative block rounded-lg border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-900 shadow-sm px-6 py-4 cursor-pointer hover:border-gray-400 sm:flex sm:justify-between focus:outline-none",
{
"ring-1 ring-indigo-500": active,
},
)
}
>
{({ checked }) => (
<>
<div className="flex items-center h-14">
{option.icon !== undefined &&
option.icon !== "" && (
<div>
<img
src={option.icon}
className="max-h-14 mr-4 p-1"
/>
</div>
)}
<div className="flex flex-col">
<div className="text-lg">
<RadioGroup.Label
as="p"
className="font-medium text-gray-900 dark:text-gray-200"
>
{option.label}
</RadioGroup.Label>
</div>
<div className="text-sm">
<RadioGroup.Description
as="div"
className="text-gray-500 dark:text-gray-300"
>
<p className="sm:inline">
{option.description}
</p>
</RadioGroup.Description>
</div>
</div>
</div>
<div
className={classnames(
"absolute -inset-px rounded-lg border-2 pointer-events-none",
{
"border-indigo-500": checked,
"border-transparent": !checked,
},
)}
aria-hidden="true"
/>
</>
)}
</RadioGroup.Option>
))}
</div>
</RadioGroup>
);
}
// // // //
export function ConfigurationInputPrimitive(
props: ConfigurationInputPrimitiveProps,
) {
const { property } = props;
function setValue(updatedValue: ConfigurationPropertyValue) {
if (property.allowDisable) {
props.onChange({
enabled: props.value.enabled,
value: updatedValue,
});
return;
}
props.onChange(updatedValue);
}
// Pulls value from props.value
let value = props.value;
if (property.allowDisable) {
value = props.value.value;
}
// // // //
// Handle PropertyTypes.STRING
if (property.type === PropertyTypes.STRING) {
return (
<input
className="form-control"
type="text"
name={property.identifier}
required={property.required}
placeholder={property.content.label}
autoComplete="none"
value={value}
onChange={e => {
setValue(e.currentTarget.value);
}}
onBlur={e => {
const value = e.currentTarget.value;
// Applies PropertyFilters from ConfigurationProperty
const filteredValue: string = applyStringPropertyTransformations(
{
value,
// @ts-ignore
filters: property.filters,
},
);
// Sets value with filtered version on blur
setValue(filteredValue);
}}
/>
);
}
// Handle PropertyTypes.NUMBER
if (property.type === PropertyTypes.NUMBER) {
return (
<input
className="form-control"
type="number"
placeholder={property.content.label}
value={value}
required={property.required}
onChange={e => {
setValue(e.currentTarget.value);
}}
onBlur={e => {
const value = parseFloat(e.currentTarget.value);
// Return if value is NaN for some reason
if (Number.isNaN(value)) {
return;
}
// Applies PropertyFilters from ConfigurationProperty
const filteredValue: number = applyNumberPropertyTransformations(
{
value,
// @ts-ignore
filters: property.filters,
},
);
// Sets value with filtered version on blur
setValue(filteredValue);
}}
/>
);
}
// Handle PropertyTypes.BOOLEAN
// TODO - replace with generic headless/ui component
// https://headlessui.dev/react/switch
if (property.type === PropertyTypes.BOOLEAN) {
return (
<Switch
height={22}
width={50}
// onHandleColor={}
// offHandleColor={}
offColor={"#888"}
onColor={"#6366F1"}
checkedIcon={false}
uncheckedIcon={false}
onChange={(updatedChecked: boolean) => {
setValue(updatedChecked);
}}
checked={value}
/>
);
}
// Handle PropertyTypes.DROPDOWN
if (property.type === PropertyTypes.DROPDOWN) {
return <DropdownMenu {...props} />;
}
// Handle PropertyTypes.RADIO_GROUP
if (property.type === PropertyTypes.RADIO_GROUP) {
return (
<div>
<RadioGroupInput {...props} />
</div>
);
}
// FEATURE - add support for MULTI_DROPDOWN
return null;
} | the_stack |
import {
CancellationToken,
ExtensionContext,
NotebookCell,
NotebookCellExecution,
NotebookController,
NotebookDocument,
Uri,
window,
workspace
} from 'vscode';
import { IDisposable } from '../types';
import * as getPort from 'get-port';
import * as WebSocket from 'ws';
import { CellExecutionState } from './types';
import * as path from 'path';
import { ChildProcess, spawn } from 'child_process';
import { createDeferred, Deferred, generateId, noop } from '../coreUtils';
import { ServerLogger } from '../serverLogger';
import { CellOutput as CellOutput } from './cellOutput';
import { getNotebookCwd } from '../utils';
import { TensorflowVisClient } from '../tfjsvis';
import { Compiler } from './compiler';
import { CodeObject, RequestType, ResponseType } from '../server/types';
import { getConfiguration, writeConfigurationToTempFile } from '../configuration';
import { quote } from 'shell-quote';
import { getNextExecutionOrder } from './executionOrder';
import { DebuggerFactory } from './debugger/debugFactory';
import { EOL } from 'os';
import { createConsoleOutputCompletedMarker } from '../const';
const kernels = new WeakMap<NotebookDocument, JavaScriptKernel>();
const usedPorts = new Set<number>();
let getPortsPromise: Promise<unknown> = Promise.resolve();
export class JavaScriptKernel implements IDisposable {
private static extensionDir: Uri;
private starting?: Promise<void>;
private server?: WebSocket.Server;
private webSocket = createDeferred<WebSocket>();
private serverProcess?: ChildProcess;
private startHandlingStreamOutput?: boolean;
private disposed?: boolean;
private initialized = createDeferred<void>();
private readonly _debugPort = createDeferred<number>();
public get debugPort(): Promise<number> {
return this._debugPort.promise;
}
private readonly mapOfCodeObjectsToCellIndex = new Map<string, number>();
private tasks = new Map<
number | string,
{
task: NotebookCellExecution;
requestId: string;
result: Deferred<CellExecutionState>;
stdOutput: CellOutput;
}
>();
private currentTask?: {
task: NotebookCellExecution;
requestId: string;
result: Deferred<CellExecutionState>;
stdOutput: CellOutput;
};
private lastStdOutput?: CellOutput;
private waitingForLastOutputMessage?: { expectedString: string; deferred: Deferred<void> };
private readonly cwd?: string;
constructor(private readonly notebook: NotebookDocument, private readonly controller: NotebookController) {
this.cwd = getNotebookCwd(notebook);
}
public static get(notebook: NotebookDocument) {
return kernels.get(notebook);
}
public static register(context: ExtensionContext) {
JavaScriptKernel.extensionDir = context.extensionUri;
}
public static broadcast(message: RequestType) {
workspace.notebookDocuments.forEach((notebook) => {
const kernel = JavaScriptKernel.get(notebook);
if (kernel) {
void kernel.sendMessage(message);
}
});
}
public static getOrCreate(notebook: NotebookDocument, controller: NotebookController) {
let kernel = kernels.get(notebook);
if (kernel) {
return kernel;
}
kernel = new JavaScriptKernel(notebook, controller);
kernels.set(notebook, kernel);
void kernel.start();
return kernel;
}
public dispose() {
if (this.disposed) {
return;
}
this.disposed = true;
Array.from(this.tasks.values()).forEach((item) => {
try {
item.stdOutput.end(undefined);
} catch (ex) {
//
}
});
this.tasks.clear();
kernels.delete(this.notebook);
this.serverProcess?.kill();
this.serverProcess = undefined;
}
/**
* We cannot stop execution of JS, hence ignore the cancellation token.
*/
public async runCell(
task: NotebookCellExecution,
// We cannot stop execution of JS, hence ignore the cancellation token.
_token: CancellationToken
): Promise<CellExecutionState> {
await this.initialized.promise;
task.start(Date.now());
// TODO: fix waiting on https://github.com/microsoft/vscode/issues/131123
await task.clearOutput();
if (JavaScriptKernel.isEmptyCell(task.cell)) {
task.end(undefined);
return CellExecutionState.notExecutedEmptyCell;
}
const requestId = generateId();
this.waitingForLastOutputMessage = {
expectedString: createConsoleOutputCompletedMarker(requestId),
deferred: createDeferred<void>()
};
const result = createDeferred<CellExecutionState>();
const stdOutput = CellOutput.getOrCreate(task, this.controller, requestId);
this.currentTask = { task, requestId, result, stdOutput };
this.lastStdOutput = stdOutput;
this.tasks.set(requestId, { task, requestId, result, stdOutput });
task.executionOrder = getNextExecutionOrder(task.cell.notebook);
let code: CodeObject;
try {
code = Compiler.getOrCreateCodeObject(task.cell);
} catch (ex: unknown) {
console.error(`Failed to generate code object`, ex);
const error = new Error(`Failed to generate code object, ${(ex as Partial<Error> | undefined)?.message}`);
error.stack = ''; // Don't show stack trace pointing to our internal code (its not useful & its ugly)
stdOutput.appendError(error);
stdOutput.end(false, Date.now());
return CellExecutionState.error;
}
this.mapOfCodeObjectsToCellIndex.set(code.sourceFilename, task.cell.index);
ServerLogger.appendLine(`Execute:`);
ServerLogger.appendLine(code.code);
await this.sendMessage({ type: 'cellExec', code, requestId });
return result.promise;
}
private static isEmptyCell(cell: NotebookCell) {
return cell.document.getText().trim().length === 0;
}
private async start() {
if (!this.starting) {
this.starting = this.startInternal();
}
return this.starting;
}
private async startInternal() {
const [port, debugPort, configFile] = await Promise.all([
this.getPort(),
this.getPort(),
writeConfigurationToTempFile()
]);
this.server = new WebSocket.Server({ port });
this.server.on('connection', (ws) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
ws.on('message', (message: any) => {
if (typeof message === 'string' && message.startsWith('{') && message.endsWith('}')) {
try {
const msg: ResponseType = JSON.parse(message);
this.onMessage(msg);
if (msg.type === 'initialized') {
this.startHandlingStreamOutput = true;
this._debugPort.resolve(debugPort);
this.initialized.resolve();
}
} catch (ex) {
ServerLogger.appendLine(`Failed to handle message ${message}`);
}
} else {
console.log('received: %s', message);
}
});
void this.sendMessage({ type: 'initialize', requestId: '' });
this.webSocket.resolve(ws);
});
this.server.on('listening', () => {
if (this.disposed) {
return;
}
const serverFile = path.join(
JavaScriptKernel.extensionDir.fsPath,
'out',
'extension',
'server',
'index.js'
);
ServerLogger.appendLine(`Starting node ${serverFile} & listening on ${debugPort} & websock on ${port}`);
this.serverProcess = spawn(
'node',
[`--inspect=${debugPort}`, serverFile, `--port=${port}`, `--config=${quote([configFile])}`],
{
// this.serverProcess = spawn('node', [serverFile, `--port=${port}`], {
cwd: this.cwd
}
);
this.serverProcess.on('close', (code: number) => {
ServerLogger.appendLine(`Server Exited, code = ${code}`);
});
this.serverProcess.on('error', (error) => {
ServerLogger.appendLine('Server Exited, error:', error);
});
this.serverProcess.stderr?.on('data', (data: Buffer | string) => {
if (this.startHandlingStreamOutput) {
const output = this.getCellOutput();
if (output) {
data = data.toString();
if (DebuggerFactory.isAttached(this.notebook)) {
data = DebuggerFactory.stripDebuggerMessages(data);
}
if (data.length > 0) {
output.appendStreamOutput(data, 'stderr');
}
}
} else {
ServerLogger.append(data.toString());
}
});
this.serverProcess.stdout?.on('data', (data: Buffer | string) => {
data = data.toString();
if (this.startHandlingStreamOutput) {
const output = this.getCellOutput();
if (output) {
if (
this.waitingForLastOutputMessage?.expectedString &&
data.includes(this.waitingForLastOutputMessage.expectedString)
) {
data = data.replace(`${this.waitingForLastOutputMessage.expectedString}${EOL}`, '');
data = data.replace(`${this.waitingForLastOutputMessage.expectedString}`, '');
this.waitingForLastOutputMessage.deferred.resolve();
}
output.appendStreamOutput(data, 'stdout');
}
} else {
ServerLogger.append(data);
}
});
});
}
private async sendMessage(message: RequestType) {
await this.start();
const ws = await this.webSocket.promise;
ws.send(JSON.stringify(message));
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private onMessage(message: ResponseType) {
console.info(`Ext got message ${message.type} with ${message}`);
switch (message.type) {
case 'pong':
break;
case 'logMessage': {
ServerLogger.appendLine(message.message);
break;
}
case 'initialized': {
this.startHandlingStreamOutput = true;
break;
}
case 'replRestarted': {
void window.showErrorMessage('JavaScript/TypeScript Notebook Kernel was restarted');
break;
}
case 'readlineRequest': {
window.showInputBox({ ignoreFocusOut: true, prompt: message.question }).then((result) => {
void this.sendMessage({ type: 'readlineResponse', answer: result, requestId: message.requestId });
}, noop);
break;
}
case 'tensorFlowVis': {
if (
getConfiguration().inlineTensorflowVisualizations &&
(message.request === 'history' ||
message.request === 'scatterplot' ||
message.request === 'linechart' ||
message.request === 'heatmap' ||
message.request === 'layer' ||
message.request === 'valuesdistribution' ||
// message.request === 'registerfitcallback' || // Disabled, as VSC is slow to display the output.
// message.request === 'fitcallback' || // Disabled, as VSC is slow to display the output.
message.request === 'table' ||
message.request === 'perclassaccuracy' ||
message.request === 'histogram' ||
message.request === 'barchart' ||
message.request === 'confusionmatrix' ||
message.request === 'modelsummary')
) {
const item = this.tasks.get(message.requestId)?.stdOutput || this.getCellOutput();
if (item) {
item.appendTensorflowVisOutput(message);
}
}
TensorflowVisClient.sendMessage(message);
break;
}
case 'cellExec': {
const item = this.tasks.get(message.requestId);
if (item) {
if (message.success == true && message.result) {
const result = message.result;
// Append output (like value of last expression in cell) after we've received all of the console outputs.
if (this.waitingForLastOutputMessage) {
this.waitingForLastOutputMessage?.deferred.promise.then(() =>
item.stdOutput.appendOutput(result)
);
} else {
item.stdOutput.appendOutput(result);
}
}
if (message.success === false && message.ex) {
const responseEx = message.ex as unknown as Partial<Error>;
const error = new Error(responseEx.message || 'unknown');
error.name = responseEx.name || error.name;
error.stack = responseEx.stack || error.stack;
// Append error after we've received all of the console outputs.
if (this.waitingForLastOutputMessage) {
this.waitingForLastOutputMessage?.deferred.promise.then(() =>
item.stdOutput.appendError(error)
);
} else {
item.stdOutput.appendError(error);
}
}
const state = message.success ? CellExecutionState.success : CellExecutionState.error;
if (this.currentTask?.task === item.task) {
item.stdOutput.end(message.success, message.end || Date.now());
item.result.resolve(state);
this.currentTask = undefined;
} else {
item.stdOutput.end(message.success, message.end || Date.now());
item.result.resolve(state);
}
}
this.tasks.delete(message.requestId ?? -1);
break;
}
case 'output': {
const item = this.tasks.get(message.requestId)?.stdOutput || this.getCellOutput();
if (item) {
if (message.data) {
item.appendOutput(message.data);
}
if (message.ex) {
item.appendError(message.ex as unknown as Error);
}
}
break;
}
default:
break;
}
}
private getCellOutput() {
return this.currentTask?.stdOutput || this.lastStdOutput;
}
private getPort() {
return new Promise<number>((resolve) => {
// Chain the promises, to avoid getting the same port when we expect two distinct ports.
getPortsPromise = getPortsPromise.then(async () => {
const port = await getPort();
if (usedPorts.has(port)) {
return this.getPort();
}
usedPorts.add(port);
resolve(port);
});
});
}
} | the_stack |
import { IgxDateTimeEditorDirective, IgxDateTimeEditorModule } from './date-time-editor.directive';
import { DatePart } from './date-time-editor.common';
import { DOCUMENT, formatDate } from '@angular/common';
import { Component, ViewChild, DebugElement, EventEmitter, Output, SimpleChange, SimpleChanges } from '@angular/core';
import { fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing';
import { FormsModule, FormGroup, FormBuilder, ReactiveFormsModule, Validators, NgControl } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { IgxInputGroupModule, IgxInputGroupComponent, IgxInputDirective } from '../../input-group/public_api';
import { configureTestSuite } from '../../test-utils/configure-suite';
import { ControlsFunction } from '../../test-utils/controls-functions.spec';
import { UIInteractions } from '../../test-utils/ui-interactions.spec';
describe('IgxDateTimeEditor', () => {
let dateTimeEditor: IgxDateTimeEditorDirective;
describe('Unit tests', () => {
const maskParsingService = jasmine.createSpyObj('MaskParsingService',
['parseMask', 'restoreValueFromMask', 'parseMaskValue', 'applyMask', 'parseValueFromMask']);
const renderer2 = jasmine.createSpyObj('Renderer2', ['setAttribute']);
const locale = 'en';
const _ngModel = {
control: { touched: false, dirty: false, validator: null, setValue: () => { } },
valid: false,
statusChanges: new EventEmitter(),
};
let elementRef = { nativeElement: null };
let inputFormat: string;
let inputDate: string;
const initializeDateTimeEditor = (_control?: NgControl) => {
// const injector = { get: () => control };
dateTimeEditor = new IgxDateTimeEditorDirective(renderer2, elementRef, maskParsingService, null, DOCUMENT, locale);
dateTimeEditor.inputFormat = inputFormat;
dateTimeEditor.ngOnInit();
const change: SimpleChange = new SimpleChange(undefined, inputFormat, true);
const changes: SimpleChanges = { inputFormat: change };
dateTimeEditor.ngOnChanges(changes);
};
describe('Properties & Events', () => {
it('should emit valueChange event on clear()', () => {
inputFormat = 'dd/M/yy';
inputDate = '6/6/2000';
elementRef = { nativeElement: { value: inputDate, setSelectionRange: () => { } } };
initializeDateTimeEditor();
const date = new Date(2000, 5, 6);
dateTimeEditor.value = date;
spyOn(dateTimeEditor.valueChange, 'emit');
spyOnProperty((dateTimeEditor as any), 'inputValue', 'get').and.returnValue(inputDate);
dateTimeEditor.clear();
expect(dateTimeEditor.value).toBeNull();
expect(dateTimeEditor.valueChange.emit).toHaveBeenCalledTimes(1);
expect(dateTimeEditor.valueChange.emit).toHaveBeenCalledWith(null);
});
it('should update mask according to the input format', () => {
inputFormat = 'd/M/yy';
inputDate = '';
elementRef = { nativeElement: { value: inputDate } };
initializeDateTimeEditor();
dateTimeEditor.inputFormat = inputFormat;
expect(dateTimeEditor.mask).toEqual('00/00/00');
dateTimeEditor.inputFormat = 'dd-MM-yyyy HH:mm:ss';
expect(dateTimeEditor.mask).toEqual('00-00-0000 00:00:00');
dateTimeEditor.inputFormat = 'H:m:s';
expect(dateTimeEditor.mask).toEqual('00:00:00');
});
});
describe('Date portions spinning', () => {
it('should correctly increment / decrement date portions with passed in DatePart', () => {
inputFormat = 'dd/M/yy';
inputDate = '12/10/2015';
elementRef = { nativeElement: { value: inputDate } };
initializeDateTimeEditor();
dateTimeEditor.value = new Date(2015, 11, 12);
spyOnProperty((dateTimeEditor as any), 'inputValue', 'get').and.returnValue(inputDate);
const date = dateTimeEditor.value.getDate();
const month = dateTimeEditor.value.getMonth();
dateTimeEditor.increment(DatePart.Date);
expect(dateTimeEditor.value.getDate()).toBeGreaterThan(date);
dateTimeEditor.decrement(DatePart.Month);
expect(dateTimeEditor.value.getMonth()).toBeLessThan(month);
});
it('should correctly increment / decrement date portions without passed in DatePart', () => {
inputFormat = 'dd/MM/yyyy';
inputDate = '12/10/2015';
elementRef = { nativeElement: { value: inputDate } };
initializeDateTimeEditor();
dateTimeEditor.value = new Date(2015, 11, 12);
spyOnProperty((dateTimeEditor as any), 'inputValue', 'get').and.returnValue(inputDate);
const date = dateTimeEditor.value.getDate();
dateTimeEditor.increment();
expect(dateTimeEditor.value.getDate()).toBeGreaterThan(date);
dateTimeEditor.decrement();
expect(dateTimeEditor.value.getDate()).toEqual(date);
});
it('should correctly increment / decrement date portions with passed in spinDelta', () => {
inputFormat = 'dd/MM/yyyy';
inputDate = '12/10/2015';
elementRef = { nativeElement: { value: inputDate } };
initializeDateTimeEditor();
const date = new Date(2015, 11, 12, 14, 35, 12);
dateTimeEditor.value = date;
dateTimeEditor.spinDelta = { date: 2, month: 2, year: 2, hours: 2, minutes: 2, seconds: 2 };
spyOnProperty((dateTimeEditor as any), 'inputValue', 'get').and.returnValue(inputDate);
dateTimeEditor.increment();
expect(dateTimeEditor.value.getDate()).toEqual(14);
dateTimeEditor.decrement();
expect(dateTimeEditor.value.getDate()).toEqual(12);
dateTimeEditor.increment(DatePart.Minutes);
expect(dateTimeEditor.value.getMinutes()).toEqual(date.getMinutes() + 2);
dateTimeEditor.decrement(DatePart.Hours);
expect(dateTimeEditor.value.getHours()).toEqual(date.getHours() - 2);
});
it('should not loop over to next month when incrementing date', () => {
inputFormat = 'dd/MM/yyyy';
inputDate = '29/02/2020';
elementRef = { nativeElement: { value: inputDate } };
initializeDateTimeEditor();
dateTimeEditor.value = new Date(2020, 1, 29);
spyOnProperty((dateTimeEditor as any), 'inputValue', 'get').and.returnValue(inputDate);
dateTimeEditor.increment();
expect(dateTimeEditor.value.getDate()).toEqual(1);
expect(dateTimeEditor.value.getMonth()).toEqual(1);
});
it('should not loop over to next year when incrementing month', () => {
inputFormat = 'dd/MM/yyyy';
inputDate = '29/12/2020';
elementRef = { nativeElement: { value: inputDate } };
initializeDateTimeEditor();
dateTimeEditor.value = new Date(2020, 11, 29);
spyOnProperty((dateTimeEditor as any), 'inputValue', 'get').and.returnValue(inputDate);
dateTimeEditor.increment(DatePart.Month);
expect(dateTimeEditor.value.getMonth()).toEqual(0);
expect(dateTimeEditor.value.getFullYear()).toEqual(2020);
});
it('should update date part if next/previous month\'s max date is less than the current one\'s', () => {
inputFormat = 'dd/MM/yyyy';
inputDate = '31/01/2020';
elementRef = { nativeElement: { value: inputDate } };
initializeDateTimeEditor();
dateTimeEditor.value = new Date(2020, 0, 31);
spyOnProperty((dateTimeEditor as any), 'inputValue', 'get').and.returnValue(inputDate);
dateTimeEditor.increment(DatePart.Month);
expect(dateTimeEditor.value.getDate()).toEqual(29);
expect(dateTimeEditor.value.getMonth()).toEqual(1);
});
it('should prioritize Date for spinning, if it is set in format', () => {
inputFormat = 'dd/M/yy HH:mm:ss tt';
inputDate = '11/03/2020 00:00:00 AM';
elementRef = { nativeElement: { value: inputDate } };
initializeDateTimeEditor();
dateTimeEditor.value = new Date(2020, 2, 11);
spyOnProperty((dateTimeEditor as any), 'inputValue', 'get').and.returnValue(inputDate);
dateTimeEditor.increment();
expect(dateTimeEditor.value.getDate()).toEqual(12);
dateTimeEditor.decrement();
expect(dateTimeEditor.value.getDate()).toEqual(11);
});
it('should not loop over when isSpinLoop is false', () => {
inputFormat = 'dd/MM/yyyy';
inputDate = '31/03/2020';
elementRef = { nativeElement: { value: inputDate } };
initializeDateTimeEditor();
dateTimeEditor.spinLoop = false;
dateTimeEditor.value = new Date(2020, 2, 31);
spyOnProperty((dateTimeEditor as any), 'inputValue', 'get').and.returnValue(inputDate);
dateTimeEditor.increment(DatePart.Date);
expect(dateTimeEditor.value.getDate()).toEqual(31);
dateTimeEditor.value = new Date(2020, 1, 31);
dateTimeEditor.decrement(DatePart.Month);
expect(dateTimeEditor.value.getMonth()).toEqual(1);
});
it('should loop over when isSpinLoop is true (default)', () => {
inputFormat = 'dd/MM/yyyy';
inputDate = '31/03/2020';
elementRef = { nativeElement: { value: inputDate } };
initializeDateTimeEditor();
dateTimeEditor.value = new Date(2020, 2, 31);
spyOnProperty((dateTimeEditor as any), 'inputValue', 'get').and.returnValue(inputDate);
dateTimeEditor.increment(DatePart.Date);
expect(dateTimeEditor.value.getDate()).toEqual(1);
dateTimeEditor.value = new Date(2020, 0, 31);
dateTimeEditor.decrement(DatePart.Month);
expect(dateTimeEditor.value.getMonth()).toEqual(11);
});
});
describe('Time portions spinning', () => {
it('should correctly increment / decrement time portions with passed in DatePart', () => {
inputFormat = 'dd/MM/yyyy HH:mm:ss';
inputDate = '10/10/2010 12:10:34';
elementRef = { nativeElement: { value: inputDate } };
initializeDateTimeEditor();
dateTimeEditor.value = new Date(2010, 11, 10, 12, 10, 34);
spyOnProperty((dateTimeEditor as any), 'inputValue', 'get').and.returnValue(inputDate);
const minutes = dateTimeEditor.value.getMinutes();
const seconds = dateTimeEditor.value.getSeconds();
dateTimeEditor.increment(DatePart.Minutes);
expect(dateTimeEditor.value.getMinutes()).toBeGreaterThan(minutes);
dateTimeEditor.decrement(DatePart.Seconds);
expect(dateTimeEditor.value.getSeconds()).toBeLessThan(seconds);
});
it('should correctly increment / decrement time portions without passed in DatePart', () => {
inputFormat = 'HH:mm:ss tt';
inputDate = '';
elementRef = { nativeElement: { value: inputDate } };
initializeDateTimeEditor();
/*
* format must be set because the editor will prioritize Date if Hours is not set
* and no DatePart is provided to increment / decrement
*/
dateTimeEditor.value = new Date();
spyOnProperty((dateTimeEditor as any), 'inputValue', 'get').and.returnValue(inputDate);
const hours = dateTimeEditor.value.getHours();
dateTimeEditor.increment();
expect(dateTimeEditor.value.getHours()).toBeGreaterThan(hours);
dateTimeEditor.decrement();
expect(dateTimeEditor.value.getHours()).toEqual(hours);
});
it('should not loop over to next minute when incrementing seconds', () => {
inputFormat = 'dd/MM/yyyy HH:mm:ss';
inputDate = '20/01/2019 20:05:59';
elementRef = { nativeElement: { value: inputDate } };
initializeDateTimeEditor();
dateTimeEditor.value = new Date(2019, 1, 20, 20, 5, 59);
spyOnProperty((dateTimeEditor as any), 'inputValue', 'get').and.returnValue(inputDate);
dateTimeEditor.increment(DatePart.Seconds);
expect(dateTimeEditor.value.getMinutes()).toEqual(5);
expect(dateTimeEditor.value.getSeconds()).toEqual(0);
});
it('should not loop over to next hour when incrementing minutes', () => {
inputFormat = 'dd/MM/yyyy HH:mm:ss';
inputDate = '20/01/2019 20:59:12';
elementRef = { nativeElement: { value: inputDate } };
initializeDateTimeEditor();
dateTimeEditor.value = new Date(2019, 1, 20, 20, 59, 12);
spyOnProperty((dateTimeEditor as any), 'inputValue', 'get').and.returnValue(inputDate);
dateTimeEditor.increment(DatePart.Minutes);
expect(dateTimeEditor.value.getHours()).toEqual(20);
expect(dateTimeEditor.value.getMinutes()).toEqual(0);
});
it('should not loop over to next day when incrementing hours', () => {
inputFormat = 'dd/MM/yyyy HH:mm:ss';
inputDate = '20/01/2019 23:13:12';
elementRef = { nativeElement: { value: inputDate } };
initializeDateTimeEditor();
dateTimeEditor.value = new Date(2019, 1, 20, 23, 13, 12);
spyOnProperty((dateTimeEditor as any), 'inputValue', 'get').and.returnValue(inputDate);
dateTimeEditor.increment(DatePart.Hours);
expect(dateTimeEditor.value.getDate()).toEqual(20);
expect(dateTimeEditor.value.getHours()).toEqual(0);
});
it('should not loop over when isSpinLoop is false', () => {
inputFormat = 'dd/MM/yyyy HH:mm:ss';
inputDate = '20/01/2019 23:13:12';
elementRef = { nativeElement: { value: inputDate } };
initializeDateTimeEditor();
dateTimeEditor.spinLoop = false;
dateTimeEditor.value = new Date(2019, 1, 20, 23, 0, 12);
spyOnProperty((dateTimeEditor as any), 'inputValue', 'get').and.returnValue(inputDate);
dateTimeEditor.increment(DatePart.Hours);
expect(dateTimeEditor.value.getHours()).toEqual(23);
dateTimeEditor.decrement(DatePart.Minutes);
expect(dateTimeEditor.value.getMinutes()).toEqual(0);
});
it('should loop over when isSpinLoop is true (default)', () => {
inputFormat = 'dd/MM/yyyy HH:mm:ss';
inputDate = '20/02/2019 23:15:12';
elementRef = { nativeElement: { value: inputDate } };
initializeDateTimeEditor();
dateTimeEditor.value = new Date(2019, 1, 20, 23, 15, 0);
spyOnProperty((dateTimeEditor as any), 'inputValue', 'get').and.returnValue(inputDate);
dateTimeEditor.increment(DatePart.Hours);
expect(dateTimeEditor.value.getHours()).toEqual(0);
dateTimeEditor.decrement(DatePart.Seconds);
expect(dateTimeEditor.value.getSeconds()).toEqual(59);
});
it('should properly parse AM/PM no matter where it is in the format', () => {
inputFormat = 'dd tt yyyy-MM mm-ss-hh';
inputDate = '12 AM 2020-06 14-15-11';
elementRef = { nativeElement: { value: inputDate } };
initializeDateTimeEditor();
dateTimeEditor.inputFormat = inputFormat;
expect(dateTimeEditor.mask).toEqual('00 LL 0000-00 00-00-00');
dateTimeEditor.value = new Date(2020, 5, 12, 11, 15, 14);
spyOnProperty((dateTimeEditor as any), 'inputValue', 'get').and.returnValue(inputDate);
dateTimeEditor.increment(DatePart.AmPm);
expect(dateTimeEditor.value).toEqual(new Date(2020, 5, 12, 23, 15, 14));
});
});
});
describe('Integration tests', () => {
const dateTimeOptions = {
day: '2-digit', month: '2-digit', year: 'numeric',
hour: 'numeric', minute: 'numeric', second: 'numeric'
};
let fixture;
let inputElement: DebugElement;
let dateTimeEditorDirective: IgxDateTimeEditorDirective;
describe('Key interaction tests', () => {
configureTestSuite();
beforeAll(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [
IgxDateTimeEditorSampleComponent,
IgxDateTimeEditorBaseTestComponent
],
imports: [IgxInputGroupModule, IgxDateTimeEditorModule, FormsModule, NoopAnimationsModule]
})
.compileComponents();
}));
beforeEach(async () => {
fixture = TestBed.createComponent(IgxDateTimeEditorSampleComponent);
fixture.detectChanges();
inputElement = fixture.debugElement.query(By.css('input'));
dateTimeEditorDirective = inputElement.injector.get(IgxDateTimeEditorDirective);
});
it('should properly update mask with inputFormat onInit', () => {
fixture = TestBed.createComponent(IgxDateTimeEditorBaseTestComponent);
fixture.detectChanges();
expect(fixture.componentInstance.dateEditor.elementRef.nativeElement.value).toEqual('09/11/2009');
});
it('should correctly display input format during user input', () => {
fixture.componentInstance.dateTimeFormat = 'dd/MM/yy';
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('1', inputElement);
expect(inputElement.nativeElement.value).toEqual('1_/__/__');
UIInteractions.simulateTyping('9', inputElement, 1, 1);
expect(inputElement.nativeElement.value).toEqual('19/__/__');
UIInteractions.simulateTyping('1', inputElement, 2, 2);
expect(inputElement.nativeElement.value).toEqual('19/1_/__');
UIInteractions.simulateTyping('2', inputElement, 4, 4);
expect(inputElement.nativeElement.value).toEqual('19/12/__');
UIInteractions.simulateTyping('0', inputElement, 5, 5);
expect(inputElement.nativeElement.value).toEqual('19/12/0_');
UIInteractions.simulateTyping('8', inputElement, 7, 7);
expect(inputElement.nativeElement.value).toEqual('19/12/08');
});
it('should not accept invalid date.', () => {
fixture.componentInstance.dateTimeFormat = 'dd/MM/yy';
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('333333', inputElement);
expect(inputElement.nativeElement.value).toEqual('33/33/33');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual('');
});
it('should autofill missing date/time segments on blur.', () => {
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('8', inputElement);
expect(inputElement.nativeElement.value).toEqual('8_/__/____ __:__:__');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
const date = new Date(2000, 0, 8, 0, 0, 0);
let result = ControlsFunction.formatDate(date, dateTimeOptions, 'en-GB').replace(/,/g, '');
expect(inputElement.nativeElement.value).toEqual(result);
dateTimeEditorDirective.clear();
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('5', inputElement, 7, 7);
expect(inputElement.nativeElement.value).toEqual('__/__/_5__ __:__:__');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
date.setFullYear(2005);
date.setDate(1);
result = ControlsFunction.formatDate(date, dateTimeOptions, 'en-GB').replace(/,/g, '');
expect(inputElement.nativeElement.value).toEqual(result);
dateTimeEditorDirective.clear();
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('3', inputElement, 11, 11);
expect(inputElement.nativeElement.value).toEqual('__/__/____ 3_:__:__');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
date.setFullYear(2000);
date.setHours(3);
result = ControlsFunction.formatDate(date, dateTimeOptions, 'en-GB').replace(/,/g, '');
expect(inputElement.nativeElement.value).toEqual(result);
});
it('should not accept invalid date and time parts.', () => {
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('63', inputElement);
expect(inputElement.nativeElement.value).toEqual('63/__/____ __:__:__');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual('');
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('63', inputElement, 3, 3);
expect(inputElement.nativeElement.value).toEqual('__/63/____ __:__:__');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual('');
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('25', inputElement, 11, 11);
expect(inputElement.nativeElement.value).toEqual('__/__/____ 25:__:__');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual('');
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('78', inputElement, 14, 14);
expect(inputElement.nativeElement.value).toEqual('__/__/____ __:78:__');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual('');
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('78', inputElement, 17, 17);
expect(inputElement.nativeElement.value).toEqual('__/__/____ __:__:78');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual('');
});
it('should correctly show year based on century threshold.', () => {
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('0000', inputElement, 6, 6);
expect(inputElement.nativeElement.value).toEqual('__/__/0000 __:__:__');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
const date = new Date(2000, 0, 1, 0, 0, 0);
let result = ControlsFunction.formatDate(date, dateTimeOptions, 'en-GB').replace(/,/g, '');
expect(inputElement.nativeElement.value).toEqual(result);
dateTimeEditorDirective.clear();
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('5', inputElement, 6, 6);
expect(inputElement.nativeElement.value).toEqual('__/__/5___ __:__:__');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
date.setFullYear(2005);
result = ControlsFunction.formatDate(date, dateTimeOptions, 'en-GB').replace(/,/g, '');
expect(inputElement.nativeElement.value).toEqual(result);
dateTimeEditorDirective.clear();
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('16', inputElement, 6, 6);
expect(inputElement.nativeElement.value).toEqual('__/__/16__ __:__:__');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
date.setFullYear(2016);
result = ControlsFunction.formatDate(date, dateTimeOptions, 'en-GB').replace(/,/g, '');
expect(inputElement.nativeElement.value).toEqual(result);
dateTimeEditorDirective.clear();
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('169', inputElement, 6, 6);
expect(inputElement.nativeElement.value).toEqual('__/__/169_ __:__:__');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
date.setFullYear(169);
result = ControlsFunction.formatDate(date, dateTimeOptions, 'en-GB').replace(/169,/g, '0169');
expect(inputElement.nativeElement.value).toEqual(result);
});
it('should support different display and input formats.', () => {
fixture.componentInstance.displayFormat = 'longDate';
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('9', inputElement);
expect(inputElement.nativeElement.value).toEqual('9_/__/____ __:__:__');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
let date = new Date(2000, 0, 9, 0, 0, 0);
const options = { month: 'long', day: 'numeric' };
let result = `${ControlsFunction.formatDate(date, options)}, ${date.getFullYear()}`;
expect(inputElement.nativeElement.value).toEqual(result);
dateTimeEditorDirective.clear();
fixture.detectChanges();
fixture.componentInstance.displayFormat = 'dd/MM/yyy';
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('169', inputElement, 6, 6);
expect(inputElement.nativeElement.value).toEqual('__/__/169_ __:__:__');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
date = new Date(169, 0, 1, 0, 0, 0);
const customOptions = { day: '2-digit', month: '2-digit', year: 'numeric' };
result = ControlsFunction.formatDate(date, customOptions);
expect(inputElement.nativeElement.value).toEqual(result);
});
it('should support long and short date formats', () => {
fixture.componentInstance.displayFormat = 'longDate';
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('9', inputElement);
expect(inputElement.nativeElement.value).toEqual('9_/__/____ __:__:__');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
let date = new Date(2000, 0, 9, 0, 0, 0);
const longDateOptions = { month: 'long', day: 'numeric' };
let result = `${ControlsFunction.formatDate(date, longDateOptions)}, ${date.getFullYear()}`;
expect(inputElement.nativeElement.value).toEqual(result);
dateTimeEditorDirective.clear();
fixture.detectChanges();
fixture.componentInstance.displayFormat = 'shortDate';
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('9', inputElement);
expect(inputElement.nativeElement.value).toEqual('9_/__/____ __:__:__');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
const shortDateOptions = { day: 'numeric', month: 'numeric', year: '2-digit' };
result = ControlsFunction.formatDate(date, shortDateOptions);
expect(inputElement.nativeElement.value).toEqual(result);
dateTimeEditorDirective.clear();
fixture.detectChanges();
fixture.componentInstance.displayFormat = 'fullDate';
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('9', inputElement);
expect(inputElement.nativeElement.value).toEqual('9_/__/____ __:__:__');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
const fullDateOptions = { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' };
result = ControlsFunction.formatDate(date, fullDateOptions);
expect(inputElement.nativeElement.value).toEqual(result);
dateTimeEditorDirective.clear();
fixture.detectChanges();
fixture.componentInstance.displayFormat = 'shortTime';
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('1', inputElement, 11, 11);
expect(inputElement.nativeElement.value).toEqual('__/__/____ 1_:__:__');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
date = new Date(0, 0, 0, 1, 0, 0);
const shortTimeOptions = { hour: 'numeric', minute: 'numeric', hour12: true };
result = ControlsFunction.formatDate(date, shortTimeOptions);
expect(inputElement.nativeElement.value).toEqual(result);
dateTimeEditorDirective.clear();
fixture.detectChanges();
fixture.componentInstance.displayFormat = 'longTime';
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('2', inputElement, 11, 11);
expect(inputElement.nativeElement.value).toEqual('__/__/____ 2_:__:__');
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
date = new Date(2010, 10, 10, 2, 0, 0);
result = formatDate(date, 'longTime', 'en-US');
expect(inputElement.nativeElement.value).toEqual(result);
});
it('should be able to apply custom display format.', fakeAsync(() => {
// default format
const date = new Date(2003, 3, 5, 0, 0, 0);
fixture.componentInstance.date = new Date(2003, 3, 5, 0, 0, 0);
fixture.detectChanges();
tick();
let result = ControlsFunction.formatDate(date, dateTimeOptions, 'en-GB').replace(/,/g, '');
expect(inputElement.nativeElement.value).toEqual(result);
// custom format
fixture.componentInstance.displayFormat = 'EEEE d MMMM y h:mm a';
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('1', inputElement);
date.setDate(15);
result = ControlsFunction.formatDate(date, dateTimeOptions, 'en-GB').replace(/,/g, '');
expect(inputElement.nativeElement.value).toEqual(result);
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
date.setMonth(3);
const shortTimeOptions = { hour: 'numeric', minute: 'numeric', hour12: true };
const dateOptions = { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' };
const resultDate = ControlsFunction.formatDate(date, dateOptions, 'en-GB').replace(/,/g, '');
result = `${resultDate} ${ControlsFunction.formatDate(date, shortTimeOptions)}`;
expect(inputElement.nativeElement.value).toEqual(result);
}));
it('should convert dates correctly on paste when different display and input formats are set.', () => {
// display format = input format
let date = new Date(2020, 10, 10, 10, 10, 10);
let inputDate = ControlsFunction.formatDate(date, dateTimeOptions, 'en-GB').replace(/,/g, '');
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulatePaste(inputDate, inputElement, 0, 19);
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual(inputDate);
// display format != input format
fixture.componentInstance.displayFormat = 'd/M/yy';
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulatePaste(inputDate, inputElement, 0, 19);
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
const shortDateOptions = { day: 'numeric', month: 'numeric', year: '2-digit' };
const result = ControlsFunction.formatDate(date, shortDateOptions, 'en-GB');
expect(inputElement.nativeElement.value).toEqual(result);
inputDate = '6/7/28';
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulatePaste(inputDate, inputElement, 0, 19);
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual('');
fixture.componentInstance.dateTimeFormat = 'd/M/yy';
fixture.detectChanges();
fixture.componentInstance.displayFormat = 'dd/MM/yyyy';
fixture.detectChanges();
// inputElement.triggerEventHandler('focus', {});
// fixture.detectChanges();
// UIInteractions.simulatePaste(inputDate, inputElement, 0, 19);
// fixture.detectChanges();
// inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
// fixture.detectChanges();
// expect(inputElement.nativeElement.value).toEqual('__/__/__');
date = new Date(2028, 7, 16, 0, 0, 0);
inputDate = '16/07/28';
const longDateOptions = { day: '2-digit', month: '2-digit', year: '2-digit' };
inputDate = ControlsFunction.formatDate(date, longDateOptions, 'en-GB');
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulatePaste(inputDate, inputElement, 0, 19);
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
longDateOptions.year = 'numeric';
inputDate = ControlsFunction.formatDate(date, longDateOptions, 'en-GB');
expect(inputElement.nativeElement.value).toEqual(inputDate);
});
it('should clear input date on clear()', fakeAsync(() => {
const date = new Date(2003, 3, 5);
fixture.componentInstance.date = date;
fixture.detectChanges();
tick();
const result = ControlsFunction.formatDate(date, dateTimeOptions, 'en-GB').replace(/,/g, '');
expect(inputElement.nativeElement.value).toEqual(result);
dateTimeEditorDirective.clear();
expect(inputElement.nativeElement.value).toEqual('');
}));
it('should move the caret to the start/end of the portion with CTRL + arrow left/right keys.', fakeAsync(() => {
const date = new Date(2003, 4, 5);
fixture.componentInstance.date = date;
fixture.detectChanges();
tick();
const result = ControlsFunction.formatDate(date, dateTimeOptions, 'en-GB').replace(/,/g, '');
expect(inputElement.nativeElement.value).toEqual(result);
const inputHTMLElement = inputElement.nativeElement as HTMLInputElement;
inputHTMLElement.setSelectionRange(0, 0);
fixture.detectChanges();
UIInteractions.triggerEventHandlerKeyDown('ArrowRight', inputElement, false, false, true);
fixture.detectChanges();
expect(inputHTMLElement.selectionStart).toEqual(2);
expect(inputHTMLElement.selectionEnd).toEqual(2);
UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', inputElement, false, false, true);
fixture.detectChanges();
expect(inputHTMLElement.selectionStart).toEqual(0);
expect(inputHTMLElement.selectionEnd).toEqual(0);
inputHTMLElement.setSelectionRange(8, 8);
fixture.detectChanges();
UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', inputElement, false, false, true);
fixture.detectChanges();
expect(inputHTMLElement.selectionStart).toEqual(6);
expect(inputHTMLElement.selectionEnd).toEqual(6);
UIInteractions.triggerEventHandlerKeyDown('ArrowRight', inputElement, false, false, true);
fixture.detectChanges();
expect(inputHTMLElement.selectionStart).toEqual(10);
expect(inputHTMLElement.selectionEnd).toEqual(10);
UIInteractions.triggerEventHandlerKeyDown('ArrowRight', inputElement, false, false, true);
fixture.detectChanges();
expect(inputHTMLElement.selectionStart).toEqual(13);
expect(inputHTMLElement.selectionEnd).toEqual(13);
inputHTMLElement.setSelectionRange(15, 15);
fixture.detectChanges();
UIInteractions.triggerEventHandlerKeyDown('ArrowRight', inputElement, false, false, true);
fixture.detectChanges();
expect(inputHTMLElement.selectionStart).toEqual(16);
expect(inputHTMLElement.selectionEnd).toEqual(16);
UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', inputElement, false, false, true);
fixture.detectChanges();
expect(inputHTMLElement.selectionStart).toEqual(14);
expect(inputHTMLElement.selectionEnd).toEqual(14);
UIInteractions.triggerEventHandlerKeyDown('ArrowRight', inputElement, false, false, true);
fixture.detectChanges();
expect(inputHTMLElement.selectionStart).toEqual(16);
expect(inputHTMLElement.selectionEnd).toEqual(16);
UIInteractions.triggerEventHandlerKeyDown('ArrowRight', inputElement, false, false, true);
fixture.detectChanges();
expect(inputHTMLElement.selectionStart).toEqual(19);
expect(inputHTMLElement.selectionEnd).toEqual(19);
UIInteractions.triggerEventHandlerKeyDown('ArrowLeft', inputElement, false, false, true);
fixture.detectChanges();
expect(inputHTMLElement.selectionStart).toEqual(17);
expect(inputHTMLElement.selectionEnd).toEqual(17);
}));
it('should not block the user from typing/pasting dates outside of min/max range', () => {
fixture.componentInstance.minDate = '01/01/2000';
fixture.componentInstance.maxDate = '31/12/2000';
fixture.detectChanges();
let date = new Date(2009, 10, 10, 10, 10, 10);
let inputDate = ControlsFunction.formatDate(date, dateTimeOptions, 'en-GB').replace(/,/g, '');
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulatePaste(inputDate, inputElement, 0, 19);
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual(inputDate);
dateTimeEditorDirective.clear();
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('27', inputElement, 8, 8);
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
date = new Date(2027, 0, 1, 0, 0, 0);
inputDate = ControlsFunction.formatDate(date, dateTimeOptions, 'en-GB').replace(/,/g, '');
expect(inputElement.nativeElement.value).toEqual(inputDate);
});
it('should be able to customize prompt char.', () => {
fixture.componentInstance.promptChar = '.';
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual('../../.... ..:..:..');
});
it('should be en/disabled when the input is en/disabled.', fakeAsync(() => {
spyOn(dateTimeEditorDirective, 'setDisabledState');
fixture.componentInstance.disabled = true;
fixture.detectChanges();
tick();
expect(dateTimeEditorDirective.setDisabledState).toHaveBeenCalledTimes(1);
expect(dateTimeEditorDirective.setDisabledState).toHaveBeenCalledWith(true);
fixture.componentInstance.disabled = false;
fixture.detectChanges();
tick();
expect(dateTimeEditorDirective.setDisabledState).toHaveBeenCalledTimes(2);
expect(dateTimeEditorDirective.setDisabledState).toHaveBeenCalledWith(false);
}));
it('should emit valueChange event on blur', () => {
const newDate = new Date(2004, 11, 18);
fixture.componentInstance.dateTimeFormat = 'dd/MM/yy';
fixture.detectChanges();
spyOn(dateTimeEditorDirective.valueChange, 'emit');
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('18124', inputElement);
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
const options = { day: '2-digit', month: '2-digit', year: '2-digit' };
const result = ControlsFunction.formatDate(newDate, options, 'en-GB');
expect(inputElement.nativeElement.value).toEqual(result);
expect(dateTimeEditorDirective.valueChange.emit).toHaveBeenCalledTimes(1);
expect(dateTimeEditorDirective.valueChange.emit).toHaveBeenCalledWith(newDate);
});
it('should emit valueChange event after input is complete', () => {
const newDate = new Date(2012, 11, 12);
fixture.componentInstance.dateTimeFormat = 'dd/MM/yy';
fixture.detectChanges();
spyOn(dateTimeEditorDirective.valueChange, 'emit');
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateTyping('121212', inputElement);
fixture.detectChanges();
expect(dateTimeEditorDirective.valueChange.emit).toHaveBeenCalledTimes(1);
expect(dateTimeEditorDirective.valueChange.emit).toHaveBeenCalledWith(newDate);
});
it('should fire validationFailed when input date is outside date range.', () => {
fixture.componentInstance.dateTimeFormat = 'dd-MM-yyyy';
fixture.componentInstance.minDate = new Date(2020, 1, 20);
fixture.componentInstance.maxDate = new Date(2020, 1, 25);
fixture.detectChanges();
spyOn(dateTimeEditorDirective.validationFailed, 'emit');
// date within the range
let inputDate = '22-02-2020';
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulatePaste(inputDate, inputElement, 0, 10);
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual(inputDate);
expect(dateTimeEditorDirective.validationFailed.emit).not.toHaveBeenCalled();
// date > maxValue
let oldDate = new Date(2020, 1, 22);
let newDate = new Date(2020, 1, 26);
inputDate = '26-02-2020';
let args = { oldValue: oldDate, newValue: newDate, userInput: inputDate };
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulatePaste(inputDate, inputElement, 0, 19);
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual(inputDate);
expect(dateTimeEditorDirective.validationFailed.emit).toHaveBeenCalledTimes(1);
expect(dateTimeEditorDirective.validationFailed.emit).toHaveBeenCalledWith(args);
// date < minValue
oldDate = newDate;
newDate = new Date(2020, 1, 12);
inputDate = '12-02-2020';
args = { oldValue: oldDate, newValue: newDate, userInput: inputDate };
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulatePaste(inputDate, inputElement, 0, 19);
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual(inputDate);
expect(dateTimeEditorDirective.validationFailed.emit).toHaveBeenCalledTimes(2);
expect(dateTimeEditorDirective.validationFailed.emit).toHaveBeenCalledWith(args);
});
it('should fire validationFailed when input date is invalid.', () => {
fixture.componentInstance.dateTimeFormat = 'dd-MM-yyyy';
fixture.componentInstance.minDate = new Date(2000, 1, 1);
fixture.componentInstance.maxDate = new Date(2050, 1, 25);
fixture.detectChanges();
spyOn(dateTimeEditorDirective.validationFailed, 'emit').and.callThrough();
// valid date
let inputDate = '22-02-2020';
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulatePaste(inputDate, inputElement, 0, 10);
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual(inputDate);
expect(dateTimeEditorDirective.validationFailed.emit).not.toHaveBeenCalled();
// invalid date
const oldDate = new Date(2020, 1, 22);
inputDate = '99-99-2020';
const args = { oldValue: oldDate, newValue: null, userInput: inputDate };
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulatePaste(inputDate, inputElement, 0, 10);
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual('');
expect(dateTimeEditorDirective.validationFailed.emit).toHaveBeenCalledTimes(1);
expect(dateTimeEditorDirective.validationFailed.emit).toHaveBeenCalledWith(args);
});
it('should properly increment/decrement date-time portions on wheel', fakeAsync(() => {
fixture.componentInstance.dateTimeFormat = 'dd-MM-yyyy';
fixture.detectChanges();
const today = new Date(2021, 12, 12);
dateTimeEditorDirective.value = today;
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
dateTimeEditorDirective.nativeElement.setSelectionRange(1, 1);
inputElement.triggerEventHandler('wheel', new WheelEvent('wheel', { deltaY: 1 }));
fixture.detectChanges();
expect(dateTimeEditorDirective.value.getDate()).toEqual(today.getDate() - 1);
}));
it('should properly set placeholder with inputFormat applied', () => {
fixture.componentInstance.placeholder = 'Date:';
fixture.detectChanges();
expect(dateTimeEditorDirective.nativeElement.placeholder).toEqual('Date:');
});
it('should be able to switch placeholders at runtime', () => {
let placeholder = 'Placeholder';
fixture.componentInstance.placeholder = placeholder;
fixture.detectChanges();
expect(dateTimeEditorDirective.nativeElement.placeholder).toEqual(placeholder);
placeholder = 'Placeholder1';
fixture.componentInstance.placeholder = placeholder;
fixture.detectChanges();
expect(dateTimeEditorDirective.nativeElement.placeholder).toEqual(placeholder);
// when an empty placeholder (incl. null, undefined) is provided, at run-time, we do not default to the inputFormat
placeholder = '';
fixture.componentInstance.placeholder = placeholder;
fixture.detectChanges();
expect(dateTimeEditorDirective.nativeElement.placeholder).toEqual(placeholder);
});
it('should convert correctly full-width characters after blur', () => {
const fullWidthText = '191208';
fixture.componentInstance.dateTimeFormat = 'dd/MM/yy';
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateCompositionEvent(fullWidthText, inputElement, 0, 8);
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual('19/12/08');
});
it('should convert correctly full-width characters after enter', () => {
const fullWidthText = '130948';
fixture.componentInstance.dateTimeFormat = 'dd/MM/yy';
fixture.detectChanges();
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulateCompositionEvent(fullWidthText, inputElement, 0, 8, false);
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual('13/09/48');
});
it('should convert correctly full-width characters on paste', () => {
fixture.componentInstance.dateTimeFormat = 'dd/MM/yy';
fixture.detectChanges();
const inputDate = '070520';
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulatePaste(inputDate, inputElement, 0, 8);
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual('07/05/20');
});
});
describe('Form control tests: ', () => {
let form: FormGroup;
configureTestSuite();
beforeAll(waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [
IgxDateTimeEditorFormComponent
],
imports: [
IgxInputGroupModule,
IgxDateTimeEditorModule,
NoopAnimationsModule,
ReactiveFormsModule,
FormsModule
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(IgxDateTimeEditorFormComponent);
fixture.detectChanges();
form = fixture.componentInstance.reactiveForm;
inputElement = fixture.debugElement.query(By.css('input'));
dateTimeEditorDirective = inputElement.injector.get(IgxDateTimeEditorDirective);
});
it('should validate properly when used as form control.', () => {
spyOn(dateTimeEditorDirective.validationFailed, 'emit').and.callThrough();
const dateEditor = form.controls['dateEditor'];
const inputDate = '99-99-9999';
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulatePaste(inputDate, inputElement, 0, 10);
fixture.detectChanges();
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual('');
expect(form.valid).toBeFalsy();
expect(dateEditor.valid).toBeFalsy();
expect(dateTimeEditorDirective.validationFailed.emit).toHaveBeenCalledTimes(1);
// expect(dateTimeEditorDirective.validationFailed.emit).toHaveBeenCalledWith(args);
});
it('should validate properly min/max value when used as form control.', () => {
fixture.componentInstance.minDate = new Date(2020, 2, 20);
fixture.componentInstance.maxDate = new Date(2020, 2, 25);
spyOn(dateTimeEditorDirective.validationFailed, 'emit');
const dateEditor = form.controls['dateEditor'];
let inputDate = '21-03-2020';
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulatePaste(inputDate, inputElement, 0, 10);
fixture.detectChanges();
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual(inputDate);
expect(form.valid).toBeTruthy();
expect(dateEditor.valid).toBeTruthy();
expect(dateTimeEditorDirective.validationFailed.emit).not.toHaveBeenCalled();
inputDate = '21-02-2020';
const args = { oldValue: new Date(2020, 2, 21), newValue: new Date(2020, 1, 21), userInput: inputDate };
inputElement.triggerEventHandler('focus', {});
fixture.detectChanges();
UIInteractions.simulatePaste(inputDate, inputElement, 0, 10);
fixture.detectChanges();
inputElement.triggerEventHandler('blur', { target: inputElement.nativeElement });
fixture.detectChanges();
expect(inputElement.nativeElement.value).toEqual(inputDate);
expect(form.valid).toBeFalsy();
expect(dateEditor.valid).toBeFalsy();
expect(dateTimeEditorDirective.validationFailed.emit).toHaveBeenCalledTimes(1);
expect(dateTimeEditorDirective.validationFailed.emit).toHaveBeenCalledWith(args);
});
it('should properly submit values when used as a form control', () => {
const inputDate = '09-04-2020';
expect(form.valid).toBeFalsy();
form.controls['dateEditor'].setValue(inputDate);
expect(form.valid).toBeTruthy();
let result: string;
fixture.componentInstance.submitted.subscribe((value) => result = value);
fixture.componentInstance.submit();
expect(result).toBe(inputDate);
});
it('should default to inputFormat as placeholder if none is provided', () => {
fixture.componentInstance.dateTimeFormat = 'dd/MM/yyyy';
fixture.detectChanges();
expect(dateTimeEditorDirective.nativeElement.placeholder).toEqual('dd/MM/yyyy');
});
});
});
});
@Component({
template: `
<igx-input-group>
<input igxInput [igxDateTimeEditor]="'dd/MM/yyyy'" [value]="date"/>
</igx-input-group>
`
})
export class IgxDateTimeEditorBaseTestComponent {
@ViewChild(IgxDateTimeEditorDirective)
public dateEditor: IgxDateTimeEditorDirective;
public date = new Date(2009, 10, 9);
}
@Component({
template: `
<igx-input-group #igxInputGroup>
<input type="text" igxInput [disabled]="disabled" [readonly]="readonly"
[igxDateTimeEditor]="dateTimeFormat" [displayFormat]="displayFormat" [placeholder]="placeholder"
[(ngModel)]="date" [minValue]="minDate" [maxValue]="maxDate" [promptChar]="promptChar"/>
</igx-input-group>
<input [(ngModel)]="placeholder" />
`
})
export class IgxDateTimeEditorSampleComponent {
@ViewChild('igxInputGroup', { static: true }) public igxInputGroup: IgxInputGroupComponent;
public date: Date;
public dateTimeFormat = 'dd/MM/yyyy HH:mm:ss';
public displayFormat: string;
public minDate: string | Date;
public maxDate: string | Date;
public promptChar = '_';
public disabled = false;
public readonly = false;
public placeholder = null;
}
@Component({
template: `
<form (ngSubmit)="submit()" [formGroup]="reactiveForm">
<igx-input-group>
<input formControlName="dateEditor" type="text"
igxInput [igxDateTimeEditor]="dateTimeFormat" [minValue]="minDate" [maxValue]="maxDate"/>
</igx-input-group>
</form>
`
})
class IgxDateTimeEditorFormComponent {
@ViewChild('dateEditor', { read: IgxInputDirective, static: true })
public formInput: IgxInputDirective;
@Output()
public submitted = new EventEmitter<any>();
public reactiveForm: FormGroup;
public dateTimeFormat = 'dd-MM-yyyy';
public minDate: Date;
public maxDate: Date;
constructor(fb: FormBuilder) {
this.reactiveForm = fb.group({
dateEditor: ['', Validators.required]
});
}
public submit() {
if (this.reactiveForm.valid) {
this.submitted.emit(this.reactiveForm.value.dateEditor);
}
}
} | the_stack |
import jsan, { Options } from 'jsan';
import throttle from 'lodash/throttle';
import serializeImmutable from '@redux-devtools/serialize/lib/immutable/serialize';
import { getActionsArray } from '@redux-devtools/utils';
import { getLocalFilter, isFiltered, PartialLiftedState } from './filters';
import importState from './importState';
import generateId from './generateInstanceId';
import { Config } from '../../browser/extension/inject/pageScript';
import { Action } from 'redux';
import {
EnhancedStore,
LiftedState,
PerformAction,
} from '@redux-devtools/instrument';
import { LibConfig } from '@redux-devtools/app/lib/actions';
import {
ContentScriptToPageScriptMessage,
ListenerMessage,
} from '../../browser/extension/inject/contentScript';
import { Position } from './openWindow';
const listeners: {
[instanceId: string]:
| ((message: ContentScriptToPageScriptMessage) => void)
| ((message: ContentScriptToPageScriptMessage) => void)[];
} = {};
export const source = '@devtools-page';
function windowReplacer(key: string, value: unknown) {
if (value && (value as Window).window === value) {
return '[WINDOW]';
}
return value;
}
function tryCatchStringify(obj: unknown) {
try {
return JSON.stringify(obj);
} catch (err) {
/* eslint-disable no-console */
if (process.env.NODE_ENV !== 'production') {
console.log('Failed to stringify', err);
}
/* eslint-enable no-console */
return jsan.stringify(obj, windowReplacer, undefined, {
circular: '[CIRCULAR]',
date: true,
});
}
}
let stringifyWarned: boolean;
function stringify(obj: unknown, serialize?: Serialize | undefined) {
const str =
typeof serialize === 'undefined'
? tryCatchStringify(obj)
: jsan.stringify(obj, serialize.replacer, undefined, serialize.options);
if (!stringifyWarned && str && str.length > 16 * 1024 * 1024) {
// 16 MB
/* eslint-disable no-console */
console.warn(
'Application state or actions payloads are too large making Redux DevTools serialization slow and consuming a lot of memory. See https://git.io/fpcP5 on how to configure it.'
);
/* eslint-enable no-console */
stringifyWarned = true;
}
return str;
}
export interface Serialize {
readonly replacer?: (key: string, value: unknown) => unknown;
readonly reviver?: (key: string, value: unknown) => unknown;
readonly options?: Options | boolean;
}
export function getSerializeParameter(
config: Config,
param?: 'serializeState' | 'serializeAction'
) {
const serialize = config.serialize;
if (serialize) {
if (serialize === true) return { options: true };
if (serialize.immutable) {
const immutableSerializer = serializeImmutable(
serialize.immutable,
serialize.refs,
serialize.replacer,
serialize.reviver
);
return {
replacer: immutableSerializer.replacer,
reviver: immutableSerializer.reviver,
options:
typeof serialize.options === 'object'
? { ...immutableSerializer.options, ...serialize.options }
: immutableSerializer.options,
};
}
if (!serialize.replacer && !serialize.reviver) {
return { options: serialize.options };
}
return {
replacer: serialize.replacer,
reviver: serialize.reviver,
options: serialize.options || true,
};
}
const value = config[param!];
if (typeof value === 'undefined') return undefined;
// eslint-disable-next-line no-console
console.warn(
`\`${param}\` parameter for Redux DevTools Extension is deprecated. Use \`serialize\` parameter instead: https://github.com/zalmoxisus/redux-devtools-extension/releases/tag/v2.12.1`
);
if (typeof value === 'boolean') return { options: value };
if (typeof value === 'function') return { replacer: value };
return value;
}
interface InitInstancePageScriptToContentScriptMessage {
readonly type: 'INIT_INSTANCE';
readonly instanceId: number;
readonly source: typeof source;
}
interface DisconnectMessage {
readonly type: 'DISCONNECT';
readonly source: typeof source;
}
interface InitMessage<S, A extends Action<unknown>> {
readonly type: 'INIT';
readonly payload: string;
readonly instanceId: number;
readonly source: typeof source;
action?: string;
name?: string | undefined;
liftedState?: LiftedState<S, A, unknown>;
libConfig?: LibConfig;
}
interface SerializedPartialLiftedState {
readonly stagedActionIds: readonly number[];
readonly currentStateIndex: number;
readonly nextActionId: number;
}
interface SerializedPartialStateMessage {
readonly type: 'PARTIAL_STATE';
readonly payload: SerializedPartialLiftedState;
readonly source: typeof source;
readonly instanceId: number;
readonly maxAge: number;
readonly actionsById: string;
readonly computedStates: string;
readonly committedState: boolean;
}
interface SerializedExportMessage {
readonly type: 'EXPORT';
readonly payload: string;
readonly committedState: string | undefined;
readonly source: typeof source;
readonly instanceId: number;
}
interface SerializedActionMessage {
readonly type: 'ACTION';
readonly payload: string;
readonly source: typeof source;
readonly instanceId: number;
readonly action: string;
readonly maxAge: number;
readonly nextActionId?: number;
}
interface SerializedStateMessage<S, A extends Action<unknown>> {
readonly type: 'STATE';
readonly payload: Omit<
LiftedState<S, A, unknown>,
'actionsById' | 'computedStates' | 'committedState'
>;
readonly source: typeof source;
readonly instanceId: number;
readonly libConfig?: LibConfig;
readonly actionsById: string;
readonly computedStates: string;
readonly committedState: boolean;
}
interface OpenMessage {
readonly source: typeof source;
readonly type: 'OPEN';
readonly position: Position;
}
export type PageScriptToContentScriptMessageForwardedToMonitors<
S,
A extends Action<unknown>
> =
| InitMessage<S, A>
| LiftedMessage
| SerializedPartialStateMessage
| SerializedExportMessage
| SerializedActionMessage
| SerializedStateMessage<S, A>;
export type PageScriptToContentScriptMessageWithoutDisconnectOrInitInstance<
S,
A extends Action<unknown>
> =
| PageScriptToContentScriptMessageForwardedToMonitors<S, A>
| ErrorMessage
| GetReportMessage
| StopMessage
| OpenMessage;
export type PageScriptToContentScriptMessageWithoutDisconnect<
S,
A extends Action<unknown>
> =
| PageScriptToContentScriptMessageWithoutDisconnectOrInitInstance<S, A>
| InitInstancePageScriptToContentScriptMessage
| InitInstanceMessage;
export type PageScriptToContentScriptMessage<S, A extends Action<unknown>> =
| PageScriptToContentScriptMessageWithoutDisconnect<S, A>
| DisconnectMessage;
function post<S, A extends Action<unknown>>(
message: PageScriptToContentScriptMessage<S, A>
) {
window.postMessage(message, '*');
}
function getStackTrace(
config: Config,
toExcludeFromTrace: Function | undefined
) {
if (!config.trace) return undefined;
if (typeof config.trace === 'function') return config.trace();
let stack;
let extraFrames = 0;
let prevStackTraceLimit;
const traceLimit = config.traceLimit;
const error = Error();
if (Error.captureStackTrace) {
if (Error.stackTraceLimit < traceLimit!) {
prevStackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = traceLimit!;
}
Error.captureStackTrace(error, toExcludeFromTrace);
} else {
extraFrames = 3;
}
stack = error.stack;
if (prevStackTraceLimit) Error.stackTraceLimit = prevStackTraceLimit;
if (
extraFrames ||
typeof Error.stackTraceLimit !== 'number' ||
Error.stackTraceLimit > traceLimit!
) {
const frames = stack!.split('\n');
if (frames.length > traceLimit!) {
stack = frames
.slice(0, traceLimit! + extraFrames + (frames[0] === 'Error' ? 1 : 0))
.join('\n');
}
}
return stack;
}
function amendActionType<A extends Action<unknown>>(
action:
| A
| StructuralPerformAction<A>
| StructuralPerformAction<A>[]
| string,
config: Config,
toExcludeFromTrace: Function | undefined
): StructuralPerformAction<A> {
let timestamp = Date.now();
let stack = getStackTrace(config, toExcludeFromTrace);
if (typeof action === 'string') {
return { action: { type: action } as A, timestamp, stack };
}
if (!(action as A).type)
return { action: { type: 'update' } as A, timestamp, stack };
if ((action as StructuralPerformAction<A>).action)
return (
stack ? { stack, ...action } : action
) as StructuralPerformAction<A>;
return { action, timestamp, stack } as StructuralPerformAction<A>;
}
interface LiftedMessage {
readonly type: 'LIFTED';
readonly liftedState: { readonly isPaused: boolean | undefined };
readonly instanceId: number;
readonly source: typeof source;
}
interface PartialStateMessage<S, A extends Action<unknown>> {
readonly type: 'PARTIAL_STATE';
readonly payload: PartialLiftedState<S, A>;
readonly source: typeof source;
readonly instanceId: number;
readonly maxAge: number;
}
interface ExportMessage<S, A extends Action<unknown>> {
readonly type: 'EXPORT';
readonly payload: readonly A[];
readonly committedState: S;
readonly source: typeof source;
readonly instanceId: number;
}
export interface StructuralPerformAction<A extends Action<unknown>> {
readonly action: A;
readonly timestamp?: number;
readonly stack?: string;
}
type SingleUserAction<A extends Action<unknown>> =
| PerformAction<A>
| StructuralPerformAction<A>
| A;
type UserAction<A extends Action<unknown>> =
| SingleUserAction<A>
| readonly SingleUserAction<A>[];
interface ActionMessage<S, A extends Action<unknown>> {
readonly type: 'ACTION';
readonly payload: S;
readonly source: typeof source;
readonly instanceId: number;
readonly action: UserAction<A>;
readonly maxAge: number;
readonly nextActionId?: number;
readonly name?: string;
}
interface StateMessage<S, A extends Action<unknown>> {
readonly type: 'STATE';
readonly payload: LiftedState<S, A, unknown>;
readonly source: typeof source;
readonly instanceId: number;
readonly libConfig?: LibConfig;
readonly action?: UserAction<A>;
readonly maxAge?: number;
readonly name?: string;
}
export interface ErrorMessage {
readonly type: 'ERROR';
readonly payload: string;
readonly source: typeof source;
readonly instanceId: number;
readonly message?: string | undefined;
}
interface InitInstanceMessage {
readonly type: 'INIT_INSTANCE';
readonly payload: undefined;
readonly source: typeof source;
readonly instanceId: number;
}
interface GetReportMessage {
readonly type: 'GET_REPORT';
readonly payload: string;
readonly source: typeof source;
readonly instanceId: number;
}
interface StopMessage {
readonly type: 'STOP';
readonly payload: undefined;
readonly source: typeof source;
readonly instanceId: number;
}
type ToContentScriptMessage<S, A extends Action<unknown>> =
| LiftedMessage
| PartialStateMessage<S, A>
| ExportMessage<S, A>
| ActionMessage<S, A>
| StateMessage<S, A>
| ErrorMessage
| InitInstanceMessage
| GetReportMessage
| StopMessage;
export function toContentScript<S, A extends Action<unknown>>(
message: ToContentScriptMessage<S, A>,
serializeState?: Serialize | undefined,
serializeAction?: Serialize | undefined
) {
if (message.type === 'ACTION') {
post({
...message,
action: stringify(message.action, serializeAction),
payload: stringify(message.payload, serializeState),
});
} else if (message.type === 'STATE') {
const { actionsById, computedStates, committedState, ...rest } =
message.payload;
post({
...message,
payload: rest,
actionsById: stringify(actionsById, serializeAction),
computedStates: stringify(computedStates, serializeState),
committedState: typeof committedState !== 'undefined',
});
} else if (message.type === 'PARTIAL_STATE') {
const { actionsById, computedStates, committedState, ...rest } =
message.payload;
post({
...message,
payload: rest,
actionsById: stringify(actionsById, serializeAction),
computedStates: stringify(computedStates, serializeState),
committedState: typeof committedState !== 'undefined',
});
} else if (message.type === 'EXPORT') {
post({
...message,
payload: stringify(message.payload, serializeAction),
committedState:
typeof message.committedState !== 'undefined'
? stringify(message.committedState, serializeState)
: (message.committedState as undefined),
});
} else {
post(message);
}
}
export function sendMessage<S, A extends Action<unknown>>(
action: StructuralPerformAction<A> | StructuralPerformAction<A>[],
state: LiftedState<S, A, unknown>,
config: Config,
instanceId?: number,
name?: string
) {
let amendedAction = action;
if (typeof config !== 'object') {
// Legacy: sending actions not from connected part
config = {}; // eslint-disable-line no-param-reassign
if (action) amendedAction = amendActionType(action, config, sendMessage);
}
if (action) {
toContentScript(
{
type: 'ACTION',
action: amendedAction,
payload: state,
maxAge: config.maxAge!,
source,
name: config.name || name,
instanceId: config.instanceId || instanceId || 1,
},
config.serialize as Serialize | undefined,
config.serialize as Serialize | undefined
);
} else {
toContentScript<S, A>(
{
type: 'STATE',
action: amendedAction,
payload: state,
maxAge: config.maxAge,
source,
name: config.name || name,
instanceId: config.instanceId || instanceId || 1,
},
config.serialize as Serialize | undefined,
config.serialize as Serialize | undefined
);
}
}
function handleMessages(event: MessageEvent<ContentScriptToPageScriptMessage>) {
if (process.env.BABEL_ENV !== 'test' && (!event || event.source !== window)) {
return;
}
const message = event.data;
if (!message || message.source !== '@devtools-extension') return;
Object.keys(listeners).forEach((id) => {
if (message.id && id !== message.id) return;
const listenersForId = listeners[id];
if (typeof listenersForId === 'function') listenersForId(message);
else {
listenersForId.forEach((fn) => {
fn(message);
});
}
});
}
export function setListener(
onMessage: (message: ContentScriptToPageScriptMessage) => void,
instanceId: number
) {
listeners[instanceId] = onMessage;
window.addEventListener('message', handleMessages, false);
}
const liftListener =
<S, A extends Action<unknown>>(
listener: (message: ListenerMessage<S, A>) => void,
config: Config
) =>
(message: ContentScriptToPageScriptMessage) => {
if (message.type === 'IMPORT') {
listener({
type: 'DISPATCH',
payload: {
type: 'IMPORT_STATE',
...importState<S, A>(message.state, config)!,
},
});
} else {
listener(message);
}
};
export function disconnect() {
window.removeEventListener('message', handleMessages);
post({ type: 'DISCONNECT', source });
}
export interface ConnectResponse {
init: <S, A extends Action<unknown>>(
state: S,
liftedData: LiftedState<S, A, unknown>
) => void;
subscribe: <S, A extends Action<unknown>>(
listener: (message: ListenerMessage<S, A>) => void
) => (() => void) | undefined;
unsubscribe: () => void;
send: <S, A extends Action<unknown>>(
action: A,
state: LiftedState<S, A, unknown>
) => void;
error: (payload: string) => void;
}
export function connect(preConfig: Config): ConnectResponse {
const config = preConfig || {};
const id = generateId(config.instanceId);
if (!config.instanceId) config.instanceId = id;
if (!config.name) {
config.name =
document.title && id === 1 ? document.title : `Instance ${id}`;
}
if (config.serialize) config.serialize = getSerializeParameter(config);
const actionCreators = config.actionCreators || {};
const latency = config.latency;
const predicate = config.predicate;
const localFilter = getLocalFilter(config);
const autoPause = config.autoPause;
let isPaused = autoPause;
let delayedActions: StructuralPerformAction<Action<unknown>>[] = [];
let delayedStates: LiftedState<unknown, Action<unknown>, unknown>[] = [];
const rootListener = (action: ContentScriptToPageScriptMessage) => {
if (autoPause) {
if (action.type === 'START') isPaused = false;
else if (action.type === 'STOP') isPaused = true;
}
if (action.type === 'DISPATCH') {
const payload = action.payload;
if (payload.type === 'PAUSE_RECORDING') {
isPaused = payload.status;
toContentScript({
type: 'LIFTED',
liftedState: { isPaused },
instanceId: id,
source,
});
}
}
};
listeners[id] = [rootListener];
const subscribe = <S, A extends Action<unknown>>(
listener: (message: ListenerMessage<S, A>) => void
) => {
if (!listener) return undefined;
const liftedListener = liftListener(listener, config);
const listenersForId = listeners[id] as ((
message: ContentScriptToPageScriptMessage
) => void)[];
listenersForId.push(liftedListener);
return function unsubscribe() {
const index = listenersForId.indexOf(liftedListener);
listenersForId.splice(index, 1);
};
};
const unsubscribe = () => {
delete listeners[id];
};
const sendDelayed = throttle(() => {
sendMessage(delayedActions, delayedStates as any, config);
delayedActions = [];
delayedStates = [];
}, latency);
const send = <S, A extends Action<unknown>>(
action: A,
state: LiftedState<S, A, unknown>
) => {
if (
isPaused ||
isFiltered(action, localFilter) ||
(predicate && !predicate(state, action))
) {
return;
}
let amendedAction: A | StructuralPerformAction<A> = action;
const amendedState = config.stateSanitizer
? config.stateSanitizer(state)
: state;
if (action) {
if (config.getActionType) {
amendedAction = config.getActionType(action);
if (typeof amendedAction !== 'object') {
amendedAction = {
action: { type: amendedAction },
timestamp: Date.now(),
} as unknown as A;
}
} else if (config.actionSanitizer) {
amendedAction = config.actionSanitizer(action);
}
amendedAction = amendActionType(amendedAction, config, send);
if (latency) {
delayedActions.push(amendedAction);
delayedStates.push(amendedState);
sendDelayed();
return;
}
}
sendMessage(
amendedAction as StructuralPerformAction<A>,
amendedState,
config
);
};
const init = <S, A extends Action<unknown>>(
state: S,
liftedData: LiftedState<S, A, unknown>
) => {
const message: InitMessage<S, A> = {
type: 'INIT',
payload: stringify(state, config.serialize as Serialize | undefined),
instanceId: id,
source,
};
if (liftedData && Array.isArray(liftedData)) {
// Legacy
message.action = stringify(liftedData);
message.name = config.name;
} else {
if (liftedData) {
message.liftedState = liftedData;
if (liftedData.isPaused) isPaused = true;
}
message.libConfig = {
actionCreators: JSON.stringify(getActionsArray(actionCreators)),
name: config.name || document.title,
features: config.features,
serialize: !!config.serialize,
type: config.type,
};
}
post(message);
};
const error = (payload: string) => {
post({ type: 'ERROR', payload, instanceId: id, source });
};
window.addEventListener('message', handleMessages, false);
post({ type: 'INIT_INSTANCE', instanceId: id, source });
return {
init,
subscribe,
unsubscribe,
send,
error,
};
}
export function updateStore<S, A extends Action<unknown>>(stores: {
[K in string | number]: EnhancedStore<S, A, unknown>;
}) {
return function (newStore: EnhancedStore<S, A, unknown>, instanceId: number) {
/* eslint-disable no-console */
console.warn(
'`__REDUX_DEVTOOLS_EXTENSION__.updateStore` is deprecated, remove it and just use ' +
"`__REDUX_DEVTOOLS_EXTENSION_COMPOSE__` instead of the extension's store enhancer: " +
'https://github.com/zalmoxisus/redux-devtools-extension#12-advanced-store-setup'
);
/* eslint-enable no-console */
const store = stores[instanceId || Object.keys(stores)[0]];
// Mutate the store in order to keep the reference
store.liftedStore = newStore.liftedStore;
store.getState = newStore.getState;
store.dispatch = newStore.dispatch;
};
}
export function isInIframe() {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
} | the_stack |
* Created by Dolkkok on 2017. 7. 17..
*/
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| Static Variable
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
export const CHART_STRING_DELIMITER: string = '―';
export const SPEC_VERSION: number = 2;
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| E-Chart 속성
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
export enum ChartType {
BAR = 'bar',
GRID = 'grid',
LINE = 'line',
SCATTER = 'scatter',
HEATMAP = 'heatmap',
PIE = 'pie',
MAP = 'map',
CONTROL = 'control',
LABEL = 'label',
LABEL2 = 'label2',
BOXPLOT = 'boxplot',
WATERFALL = 'waterfall',
WORDCLOUD = 'wordcloud',
COMBINE = 'combine',
TREEMAP = 'treemap',
RADAR = 'radar',
NETWORK = 'network',
SANKEY = 'sankey',
GAUGE = 'gauge'
}
/**
* 시리즈 타입
*/
export enum SeriesType {
BAR = 'bar',
LINE = 'line',
SCATTER = 'scatter',
HEATMAP = 'heatmap',
PIE = 'pie',
BOXPLOT = 'boxplot',
WORDCLOUD = 'wordCloud',
TREEMAP = 'treemap',
RADAR = 'radar',
GRAPH = 'graph',
SANKEY = 'sankey'
}
/**
* 위치값
*/
export enum Position {
AUTO = 'auto',
START = 'start',
END = 'end',
LEFT = 'left',
RIGHT = 'right',
CENTER = 'center',
TOP = 'top',
MIDDLE = 'middle',
BOTTOM = 'bottom',
INSIDE = 'inside',
INSIDETOP = 'insideTop',
INSIDELEFT = 'insideLeft',
INSIDERIGHT = 'insideRight',
INSIDEBOTTOM = 'insideBottom',
OUTSIDE = 'outside',
}
/**
* 축 타입
*/
export enum AxisType {
CATEGORY = 'category',
VALUE = 'value',
LOG = 'log',
X = 'xAxis',
Y = 'yAxis',
SUB = 'subAxis'
}
/**
* 라인 타입
*/
export enum LineType {
SOLID = 'solid',
DASHED = 'dashed',
DOTTED = 'dotted'
}
/**
* 심볼 타입
*/
export enum SymbolType {
POLYGON = 'polygon',
CIRCLE = 'circle',
RECT = 'rect',
ROUNDRECT = 'roundRect',
TRIANGLE = 'triangle',
DIAMOND = 'diamond',
PIN = 'pin',
ARROW = 'arrow'
}
/**
* 심볼 불투명/반투명 여부
*/
export enum SymbolFill {
SINGLE = 'single',
TRANSPARENT = 'transparent',
}
/**
* 폰트 스타일
*/
export enum FontStyle {
NORMAL = 'normal',
ITALIC = 'italic',
OBLIQUE = 'oblique'
}
/**
* 폰트
*/
export enum FontWeight {
NORMAL = 'normal',
BOLD = 'bold',
BOLDER = 'bolder',
LIGHTER = 'lighter'
}
/**
* 표현 방향
*/
export enum Orient {
VERTICAL = 'vertical',
HORIZONTAL = 'horizontal',
BOTH = 'both'
}
/**
* 축 단위 라벨 회전수치
*/
export enum AxisLabelRotate {
HORIZONTAL = 0,
VERTICAL = 90,
SLOPE = 45,
}
/**
* 툴팁 표현 기준
*/
export enum TriggerType {
ITEM = 'item',
AXIS = 'axis',
NONE = 'none'
}
/**
* 툴팁이 표현되는 기준 이벤트
*/
export enum TriggerAction {
MOUSEMOVE = 'mousemove',
CLICK = 'click',
NONE = 'none'
}
/**
* 이미지 포멧
*/
export enum ImageFormat {
PNG = 'png',
JPEG = 'jpeg'
}
/**
* 툴 박스 항목
*/
export enum ToolboxMagicType {
LINE = 'line',
BAR = 'bar',
STACK = 'stack',
TILED = 'tiled'
}
/**
*
*/
export enum ThrottleType {
DEBOUNCE = 'debounce',
fixrate = 'fixRate'
}
/**
* 브러쉬 타입
*/
export enum BrushType {
RECT = 'rect',
POLYGON = 'polygon',
LINEX = 'lineX',
LINEY = 'lineY',
KEEP = 'keep',
CLEAR = 'clear',
}
/**
* 브러쉬 모드
*/
export enum BrushMode {
SINGLE = 'single',
MULTIPLE = 'multiple'
}
/**
* 그래픽 객체 타입
*/
export enum GraphicType {
IMAGE = 'image',
TEXT = 'text',
CIRCLE = 'circle',
SECTOR = 'sector',
RING = 'ring',
POLYGON = 'polygon',
POLYLINE = 'polyline',
RECT = 'rect',
LINE = 'line',
BEZIERCURVE = 'bezierCurve',
ARC = 'arc',
GROUP = 'group'
}
/**
* 그래픽 객체 액션 타입
*/
export enum GraphicAction {
MERGE = 'merge',
REPLACE = 'replace',
REMOVE = 'remove'
}
/**
* VisualMap의 색상 대상 축 인덱스
*/
export enum VisualMapDimension {
X = 0,
Y = 1
}
/**
* 시리즈에 맵핑되는 축 인덱스 항목
*/
export enum AxisIndexType {
X = 'xAxisIndex',
Y = 'yAxisIndex'
}
/**
* graph 차트의 layout 타입
*/
export enum GraphLayoutType {
NONE = 'none',
FORCE = 'force',
CIRCULAR = 'circular',
}
/**
* KPI 차트의 layout 타입
*/
export enum LabelLayoutType {
HORIZONTAL = 'HORIZONTAL',
VERTICAL = 'VERTICAL'
}
/**
* KPI 차트의 Text 위치
*/
export enum LabelTextLocation {
HIDDEN = 'HIDDEN',
BEFORE = 'BEFORE',
AFTER = 'AFTER'
}
export enum LabelSecondaryIndicatorType {
PERIOD = 'PERIOD',
STANDARD = 'STANDARD'
}
export enum LabelSecondaryIndicatorPeriod {
HOUR = 'HOUR',
DAY = 'DAY',
WEEK = 'WEEK',
MONTH = 'MONTH',
QUARTER = 'QUARTER',
YEAR = 'YEAR'
}
export enum LabelSecondaryIndicatorMarkType {
PERCENTAGE = 'PERCENTAGE', // 퍼센테이지
INCREMENTAL = 'INCREMENTAL' // 증감분
}
export enum LabelStyle {
LINE = 'LINE',
SOLID = 'SOLID'
}
/**
* 폰트 크기
*/
export enum FontSize {
SMALL = 'SMALL',
NORMAL = 'NORMAL',
LARGE = 'LARGE'
}
/**
* 폰트 스타일
*/
export enum UIFontStyle {
BOLD = 'BOLD',
ITALIC = 'ITALIC'
}
/*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
| 속성 변경에 핋요한 외부(UI) 속성
|-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* 선반 타입
*/
export enum ShelveType {
COLUMNS = 'columns',
ROWS = 'rows',
AGGREGATIONS = 'aggregations',
}
/**
* 선반내 필드 타입
*/
export enum ShelveFieldType {
DIMENSION = 'dimension',
MEASURE = 'measure',
CALCULATED = 'calculated',
TIMESTAMP = 'timestamp'
}
/**
* 차트 Pivot 타입 Key
*/
export enum ChartPivotType {
COLS = 'cols',
ROWS = 'rows',
AGGS = 'aggs',
}
/**
* 차트 색상 기준
*/
export enum ChartColorType {
DIMENSION = 'dimension',
SERIES = 'series',
MEASURE = 'measure',
SINGLE = 'single'
}
/**
* 색상 컬러 프리셋
*/
export class ChartColorList {
// color by series / dimension 색
public static readonly SC1 = ['#3452b5', '#f28a00', '#2b9a9e', '#ffd200', '#c3c3c3', '#4a95cf', '#7c5ac1', '#e03c8f', '#83bf47', '#fda08c', '#7b7b7b', '#fc79ac'];
public static readonly SC2 = ['#6ed0e4', '#026e7f', '#72b235', '#fb7661', '#fbb700', '#c22a32', '#e03c8f', '#5d9f27', '#9b7fe4', '#6344ad', '#fee330', '#c3c3c3'];
public static readonly SC3 = ['#fb7661', '#fee330', '#4a95cf', '#75c4be', '#0c8691', '#fbb700', '#ad037c', '#e03c8f', '#8d6dd2', '#58b5da', '#b5d994', '#83bf47'];
public static readonly SC4 = ['#4a95cf', '#fc79ac', '#b099f0', '#cd2287', '#adadad', '#ffd200', '#6ed0e4', '#fda08c', '#54b2ae', '#f8533b', '#f6a300', '#fee330'];
public static readonly SC5 = ['#f8533b', '#d73631', '#fda08c', '#fb6e2c', '#e5342c', '#9a0b2c', '#fca0c3', '#c22a32', '#fda08c', '#f23a2c', '#fb7661', '#fbb700'];
public static readonly SC6 = ['#f28a00', '#fbb700', '#f8533b', '#f6f4b7', '#f27603', '#fda08c', '#fee330', '#fb6e2c', '#ffd200', '#f9f6a1', '#fb7661', '#f6a300'];
public static readonly SC7 = ['#4b8a21', '#54b2ae', '#026e7f', '#83bf47', '#39751d', '#b5d994', '#0c8691', '#015268', '#5d9f27', '#2d681a', '#97cb63', '#72b235'];
public static readonly SC8 = ['#6ed0e4', '#3f72c1', '#58b5da', '#026e7f', '#54b2ae', '#8adfe9', '#4a95cf', '#3452b5', '#015268', '#75c4be', '#3f72c1', '#6ed0e4'];
public static readonly SC9 = ['#7c5ac1', '#7d0071', '#cd2287', '#ee5398', '#4c006a', '#9b7fe4', '#4c309a', '#b099f0', '#ad037c', '#fca0c3', '#e03c8f', '#fc79ac'];
// color by measure
public static readonly VC1 = ['#ffcaba', '#fb7661', '#f23a2c', '#d73631', '#9a0b2c'];
public static readonly VC2 = ['#f6f4b7', '#fee330', '#fbb700', '#f28a00', '#fb6e2c'];
public static readonly VC3 = ['#d1e5c2', '#97cb63', '#72b235', '#4b8a21', '#2d681a'];
public static readonly VC4 = ['#b5e0e1', '#75c4be', '#2b9a9e', '#026e7f', '#064059'];
public static readonly VC5 = ['#c4eeed', '#8adfe9', '#58b5da', '#3f72c1', '#23399f'];
public static readonly VC6 = ['#efdffd', '#b099f0', '#8d6dd2', '#6344ad', '#391f8a'];
public static readonly VC7 = ['#fcc9dd', '#fc79ac', '#e03c8f', '#ad037c', '#4c006a'];
public static readonly VC8 = ['#ffcaba', '#fda08c', '#fb7661', '#f8533b', '#f23a2c', '#e5342c', '#d73631', '#c22a32', '#9a0b2c'];
public static readonly VC9 = ['#f6f4b7', '#f9f6a1', '#fee330', '#ffd200', '#fbb700', '#f6a300', '#f28a00', '#f27603', '#fb6e2c'];
public static readonly VC10 = ['#d1e5c2', '#b5d994', '#97cb63', '#83bf47', '#72b235', '#5d9f27', '#4b8a21', '#39751d', '#2d681a'];
public static readonly VC11 = ['#b5e0e1', '#9ad5d2', '#75c4be', '#54b2ae', '#2b9a9e', '#0c8691', '#026e7f', '#015268', '#064059'];
public static readonly VC12 = ['#c4eeed', '#a9e7eb', '#8adfe9', '#6ed0e4', '#58b5da', '#4a95cf', '#3f72c1', '#3452b5', '#23399f'];
public static readonly VC13 = ['#efdffd', '#cdbaf8', '#b099f0', '#9b7fe4', '#8d6dd2', '#7c5ac1', '#6344ad', '#4c309a', '#391f8a'];
public static readonly VC14 = ['#fcc9dd', '#fca0c3', '#fc79ac', '#ee5398', '#e03c8f', '#cd2287', '#ad037c', '#7d0071', '#4c006a'];
public static readonly VC15 = ['#c22a32', '#f23a2c', '#fb7661', '#ffcaba', '#ededed', '#b5e0e1', '#75c4be', '#2b9a9e', '#0c8691'];
public static readonly VC16 = ['#9a0b2c', '#d73631', '#f28a00', '#fbb700', '#f6f4b7', '#d1e5c2', '#75c4be', '#3f72c1', '#391f8a'];
public static readonly VC17 = ['#ad037c', '#e03c8f', '#fc79ac', '#fcc9dd', '#ededed', '#d1e5c2', '#97cb63', '#72b235', '#4b8a21'];
public static readonly VC18 = ['#fbb700', '#ffd200', '#fee330', '#f9f6a1', '#ededed', '#cdbaf8', '#b099f0', '#7c5ac1', '#4c309a'];
public static readonly VC19 = ['#f27603', '#f28a00', '#fbb700', '#fee330', '#f6f4b7', '#c4eeed', '#6ed0e4', '#4a95cf', '#3452b5'];
public static readonly RVC1 = Object.keys(ChartColorList.VC1).map(key => ChartColorList.VC1[key]).reverse();
public static readonly RVC2 = Object.keys(ChartColorList.VC2).map(key => ChartColorList.VC2[key]).reverse();
public static readonly RVC3 = Object.keys(ChartColorList.VC3).map(key => ChartColorList.VC3[key]).reverse();
public static readonly RVC4 = Object.keys(ChartColorList.VC4).map(key => ChartColorList.VC4[key]).reverse();
public static readonly RVC5 = Object.keys(ChartColorList.VC5).map(key => ChartColorList.VC5[key]).reverse();
public static readonly RVC6 = Object.keys(ChartColorList.VC6).map(key => ChartColorList.VC6[key]).reverse();
public static readonly RVC7 = Object.keys(ChartColorList.VC7).map(key => ChartColorList.VC7[key]).reverse();
public static readonly RVC8 = Object.keys(ChartColorList.VC8).map(key => ChartColorList.VC8[key]).reverse();
public static readonly RVC9 = Object.keys(ChartColorList.VC9).map(key => ChartColorList.VC9[key]).reverse();
public static readonly RVC10 = Object.keys(ChartColorList.VC10).map(key => ChartColorList.VC10[key]).reverse();
public static readonly RVC11 = Object.keys(ChartColorList.VC11).map(key => ChartColorList.VC11[key]).reverse();
public static readonly RVC12 = Object.keys(ChartColorList.VC12).map(key => ChartColorList.VC12[key]).reverse();
public static readonly RVC13 = Object.keys(ChartColorList.VC13).map(key => ChartColorList.VC13[key]).reverse();
public static readonly RVC14 = Object.keys(ChartColorList.VC14).map(key => ChartColorList.VC14[key]).reverse();
public static readonly RVC15 = Object.keys(ChartColorList.VC15).map(key => ChartColorList.VC15[key]).reverse();
public static readonly RVC16 = Object.keys(ChartColorList.VC16).map(key => ChartColorList.VC16[key]).reverse();
public static readonly RVC17 = Object.keys(ChartColorList.VC17).map(key => ChartColorList.VC17[key]).reverse();
public static readonly RVC18 = Object.keys(ChartColorList.VC18).map(key => ChartColorList.VC18[key]).reverse();
public static readonly RVC19 = Object.keys(ChartColorList.VC19).map(key => ChartColorList.VC19[key]).reverse();
}
/**
* waterfall 양수 / 음수 색상
*/
export enum WaterfallBarColor {
// 양수
POSITIVE = '#c23531',
// 음수
NEGATIVE = '#304554'
}
/**
* measure의 color range
*/
export enum MeasureColorRange {
// 범위를 벗어났을때 쓰이는 색상
OUTOF_RANGE = '#3c4950',
// 기본설정색상
DEFAULT = '#c94819'
}
/**
* 축관련 색상설정
*/
export enum AxisDefaultColor {
// 축라인 색상
AXIS_LINE_COLOR = '#bfbfbf',
// 축라벨 색상
LABEL_COLOR = '#8f96a0',
// 라인색상
LINE_COLOR = '#f2f2f2'
}
/**
* color range의 타입
*/
export enum ColorCustomMode {
NONE = 'NONE',
SECTION = 'SECTION',
GRADIENT = 'GRADIENT'
}
/**
* range내의 타입
*/
export enum ColorRangeType {
SECTION = 'section',
GRADIENT = 'gradient',
}
/**
* 옵션패널의 이벤트 타입
*/
export enum EventType {
// 초기 진입시
INIT = 'init',
// 누적모드
CUMULATIVE = 'cumulativeMode',
// 선반 변경시
CHANGE_PIVOT = 'changePivot',
// 맵차트 옵션 변경시
MAP_CHANGE_OPTION = 'mapChangeOption',
// 공간 분석 시
MAP_SPATIAL_ANALYSIS = 'spatialAnalysis',
MAP_SPATIAL_REANALYSIS = 'spatialReAnalysis',
// 그리드차트 피봇/원본
GRID_ORIGINAL = 'gridViewType',
// 바차트 병렬 / 중첩
SERIES_VIEW = 'barSeriesViewType',
// granularity 변경시
GRANULARITY = 'onChangeGranularity',
// aggregation 변경시
AGGREGATION = 'onChangeAggregationType',
// change chart type
CHART_TYPE = 'chartType',
// filter changed
FILTER = 'filter',
// change pivot alias
PIVOT_ALIAS = 'pivotAlias',
// change dashboard alias
DASHBOARD_ALIAS = 'dashboardAlias'
}
/**
* Grid 차트 한정 색상 프리셋
*
*/
export class GridCellColorList {
public static readonly LINE1 = [['#a1e1f8', '#89cdeb', '#59a4d2', '#418fc5', '#297bb8', '#246ea5', '#1e6191', '#19537e', '#13466b', '|',],
['#777', '#777', '#ffffff', '#ffffff', '#ffffff', '#ffffff', '#ffffff', '#ffffff', '#ffffff']];
public static readonly CONT1 = [['#253ba2', '#374daf', '#4668b5', '#567dbd', '#638fc0', '#85a6cc', '#a0bad7', '#cbd8e6', '#f9f9f9', '#f6d3d3', '#f1b8b8', '#eb9999', '#dc6e6e', '#cc4d4d', '#cc3333', '#b71414', '#990a00'],
['#fff', '#fff', '#fff', '#fff', '#fff', '#fff', '#fff', '#777', '#777', '#777', '#fff', '#fff', '#fff', '#fff', '#fff', '#fff', '#fff']
];
}
/**
* 차트 그래디언트 타입
*/
export enum ChartGradientType {
LINEAR = 'LINEAR',
CONTRAST = 'CONTRAST',
CUSTOM = 'CUSTOM'
}
/**
* grid 차트 색상 지정 대상
*/
export enum CellColorTarget {
BACKGROUND = 'BACKGROUND',
TEXT = 'TEXT'
}
/**
* grid 연산행 연산자
*/
export enum Operator {
SUM = 'SUM',
AVERAGE = 'AVERAGE',
MAX = 'MAX',
MIN = 'MIN',
COUNT = 'COUNT'
}
/**
* 차트 라벨 타입
*/
export enum AxisOrientType {
X = 'X',
Y = 'Y'
}
/**
* 차트 라벨 타입
*/
export enum AxisLabelType {
ROW = 'row',
COLUMN = 'column',
SUBROW = 'sub_row',
SUBCOLUMN = 'sub_column',
SIMPLE = 'simple',
AGGREGATION = 'aggregation',
}
/**
* 축 변경 타입
*/
export enum LabelConvertType {
NAME = 'name',
SHOWNAME = 'showName',
SHOWMARK = 'showMark',
MARK = 'mark',
SCALED = 'scaled',
SHOWVALUE = 'showValue',
SHOWLABEL = 'showLabel',
ALIGN = 'align',
AXISCONFIG = 'axisConfig'
}
/**
* 축 단위 라벨 회전
*/
export enum AxisLabelMark {
HORIZONTAL = 'HORIZONTAL',
VERTICAL = 'VERTICAL',
SLOPE = 'SLOPE'
}
/**
* 범례 변경 타입
*/
export enum LegendConvertType {
SHOW = 'show',
COUNT = 'count'
}
/**
* 미니맵 변경 타입
*/
export enum DataZoomConverType {
SHOW = 'show',
RANGE = 'range'
}
/**
* 차트 시리즈 표현 변경 타입
*/
export enum SeriesConvertType {
MARK = 'mark',
SHOW = 'show',
UNITTYPE = 'unitType',
ACCUMULATE = 'isAccumulate',
SHAPE = 'shape',
ALIGN = 'align',
VALIGN = 'valign',
LAYOUT = 'layout',
FORMAT = 'format',
DECIMAL = 'decimal',
BAR = 'bar',
LINE = 'line',
LABEL = 'label',
ROTATE = 'rotate'
}
/**
* 차트 mark 표현 타입
*/
export enum BarMarkType {
MULTIPLE = 'MULTIPLE',
STACKED = 'STACKED',
}
/**
* 차트 시리즈 데이터 표현 단위
*/
export enum DataUnit {
NONE = 'NONE',
PERCENT = 'PERCENT'
}
/**
* 라인차트 marktype
*/
export enum LineMarkType {
LINE = 'LINE', // 라인 표시
AREA = 'AREA' // 면적 표시
}
/**
* 라인차트 Corner Type
*/
export enum LineCornerType {
STRAIGHT = 'STRAIGHT', // 직선형
SMOOTH = 'SMOOTH' // 굴림형
}
/**
* 라인차트 공통 스타일
*/
export enum LineStyle {
POINT_LINE = 'POINT_LINE', // 포인트 라인 혼합
POINT = 'POINT', // 포인트만 표시
LINE = 'LINE' // 라인만 표시
}
/**
* 라인차트 기본 / 누계
*/
export enum LineMode {
NORMAL = 'NORMAL', // 기본
CUMULATIVE = 'CUMULATIVE' // 누계
}
/**
* 스케터차트 포인트 사이즈
*/
export enum PointSize {
NORMAL = 'NORMAL', // 보통
SMALL = 'SMALL', // 작게
LARGE = 'LARGE', // 크게
XLARGE = 'XLARGE', // 매우 크게
}
/**
* grid 차트 표현 타입
*/
export enum GridViewType {
PIVOT = 'PIVOT',
MASTER = 'MASTER',
}
/**
* grid 차트 annotation position
*/
export enum AnnotationPosition {
TOP_RIGHT = 'TOP_RIGHT',
TOP_LEFT = 'TOP_LEFT',
BOTTOM_RIGHT = 'BOTTOM_RIGHT',
BOTTOM_LEFT = 'BOTTOM_LEFT'
}
/**
* pie 차트 표현 타입
*/
export enum PieSeriesViewType {
SECTOR = 'SECTOR',
DONUT = 'DONUT',
}
/**
* 데이터 값 포멧
*/
export enum ValueFormat {
NUMBER = 'NUMBER',
TEXT = 'TEXT'
}
/**
* DataZoom Range 타입
*
*/
export enum DataZoomRangeType {
COUNT = 'COUNT',
PERCENT = 'PERCENT'
}
/**
* UILocation
*
*/
export enum AxisOrientType {
HORIZONTAL = 'HORIZONTAL',
VERTICAL = 'VERTICAL'
}
/**
* 마우스 커서
*/
export enum ChartMouseMode {
SINGLE = 'single',
MULTI = 'multi',
DRAGZOOMIN = 'dragzoomin',
ZOOMIN = 'zoomin',
ZOOMOUT = 'zoomout',
REVERT = 'revert'
}
/**
* 차트 선택모드
*/
export enum ChartSelectMode {
ADD = 'add',
SUBTRACT = 'subtract',
CLEAR = 'clear'
}
/**
* 위치값
*/
export enum UIPosition {
AUTO = 'AUTO',
LEFT = 'LEFT',
RIGHT = 'RIGHT',
CENTER = 'CENTER',
TOP = 'TOP',
MIDDLE = 'MIDDLE',
BOTTOM = 'BOTTOM',
RIGHT_BOTTOM = 'RIGHT_BOTTOM',
LEFT_BOTTOM = 'LEFT_BOTTOM',
RIGHT_TOP = 'RIGHT_TOP',
LEFT_TOP = 'LEFT_TOP'
}
/**
* 표시 레이블 선택
*/
export enum UIChartDataLabelDisplayType {
CATEGORY_NAME = 'CATEGORY_NAME',
CATEGORY_VALUE = 'CATEGORY_VALUE',
CATEGORY_PERCENT = 'CATEGORY_PERCENT',
SERIES_NAME = 'SERIES_NAME',
SERIES_VALUE = 'SERIES_VALUE',
SERIES_PERCENT = 'SERIES_PERCENT',
XAXIS_VALUE = 'XAXIS_VALUE',
YAXIS_VALUE = 'YAXIS_VALUE',
VALUE = 'VALUE',
NODE_NAME = 'NODE_NAME',
LINK_VALUE = 'LINK_VALUE',
NODE_VALUE = 'NODE_VALUE',
HIGH_VALUE = 'HIGH_VALUE',
THREE_Q_VALUE = 'THREE_Q_VALUE',
MEDIAN_VALUE = 'MEDIAN_VALUE',
FIRST_Q_VALUE = 'FIRST_Q_VALUE',
LOW_VALUE = 'LOW_VALUE',
LAYER_NAME = 'LAYER_NAME',
LOCATION_INFO = 'LOCATION_INFO',
DATA_VALUE = 'DATA_VALUE'
}
/**
* 표현 방향
*/
export enum UIOrient {
VERTICAL = 'VERTICAL',
HORIZONTAL = 'HORIZONTAL',
BOTH = 'BOTH'
}
/**
* 스케터 차트 심볼 타입
*/
export enum PointShape {
CIRCLE = 'CIRCLE', // 원
RECT = 'RECT', // 사각형(네모)
TRIANGLE = 'TRIANGLE', // 삼각형(세모)
DIAMOND = 'DIAMOND', // 마름모(다이아몬드)
PIN = 'PIN', // 십자
ARROW = 'ARROW' // 액스
}
/**
* 포맷 타입
*/
export enum UIFormatType {
NUMBER = 'number',
CURRENCY = 'currency',
PERCENT = 'percent',
EXPONENT10 = 'exponent10',
TIME_CONTINUOUS = 'time_continuous',
TIME_CUSTOM = 'time_custom'
}
/**
* 포맷 통화 심볼 타입
*/
export enum UIFormatCurrencyType {
KRW = 'KRW',
USD = 'USD',
USCENT = 'USCENT',
GBP = 'GBP',
JPY = 'JPY',
EUR = 'EUR',
CNY = 'CNY',
RUB = 'RUB'
}
/**
* 수치표기 약어 타입
*/
export enum UIFormatNumericAliasType {
NONE = 'NONE',
AUTO = 'AUTO',
KILO = 'KILO',
MEGA = 'MEGA',
GIGA = 'GIGA',
KILO_KOR = 'KILO_KOR',
MEGA_KOR = 'MEGA_KOR',
GIGA_KOR = 'GIGA_KOR'
}
/**
* 포맷 사용자 기호 위치
*/
export enum UIFormatSymbolPosition {
BEFORE = 'BEFORE',
AFTER = 'AFTER'
}
/**
* 폰트 사이즈
*/
export enum UIFontSize {
DEFAULT = 'default',
SMALLER = 'smaller',
LARGER = 'larger'
}
/**
* 축 눈금 관련 옵션
*/
export enum ChartAxisGridType {
TEXT = 'text',
NUMERIC = 'numeric',
DATETIME = 'datetime'
}
/**
* 축 Label 타입
*/
export enum ChartAxisLabelType {
VALUE = 'value',
CATEGORY = 'category'
}
/**
* 데이터라벨 위치
*/
export enum DataLabelPosition {
OUTSIDE_TOP = 'OUTSIDE_TOP',
INSIDE_TOP = 'INSIDE_TOP',
INSIDE_BOTTOM = 'INSIDE_BOTTOM',
CENTER = 'CENTER',
OUTSIDE_RIGHT = 'OUTSIDE_RIGHT',
INSIDE_RIGHT = 'INSIDE_RIGHT',
INSIDE_LEFT = 'INSIDE_LEFT',
TOP = 'TOP',
BOTTOM = 'BOTTOM',
RIGHT = 'RIGHT',
LEFT = 'LEFT'
}
/**
* 데이터레이블 text align
*/
export enum TextAlign {
DEFAULT = 'DEFAULT',
LEFT = 'LEFT',
CENTER = 'CENTER',
RIGHT = 'RIGHT'
}
/**
* shelf type
*/
export enum ShelfType {
PIVOT = 'pivot',
GRAPH = 'graph',
GEO = 'geo'
}
/**
* shelf layer view type
*/
export enum LayerViewType {
ORIGINAL = 'original',
HASH = 'hash',
CLUSTERING = 'clustering'
}
/**
* field format type
*/
export enum FormatType {
DEFAULT = 'default',
GEO = 'geo',
GEO_HASH = 'geo_hash',
GEO_BOUNDARY = 'geo_boundary',
GEO_JOIN = 'geo_join'
}
/**
* 기능 확인기
*/
export class FunctionValidator {
// 차트속성맵 - 선택 기능 사용
private _useSelection: ChartType[] = [
ChartType.BAR, ChartType.LINE, ChartType.GRID, ChartType.SCATTER, ChartType.HEATMAP, ChartType.PIE, ChartType.CONTROL,
ChartType.BOXPLOT, ChartType.WATERFALL, ChartType.WORDCLOUD, ChartType.COMBINE, ChartType.SANKEY, ChartType.GAUGE
];
// 차트속성맵 - 복수 선택툴 사용
private _useMultiSelection: ChartType[] = [
ChartType.BAR, ChartType.LINE, ChartType.SCATTER, ChartType.COMBINE
];
// 차트속성맵 - 확대툴 사용
private _useZoom: ChartType[] = [
ChartType.BAR, ChartType.LINE, ChartType.SCATTER, ChartType.HEATMAP, ChartType.CONTROL,
ChartType.BOXPLOT, ChartType.WATERFALL, ChartType.COMBINE
];
// 차트속성맵 - 범례 사용
private _useLegend: ChartType[] = [
ChartType.BAR, ChartType.LINE, ChartType.SCATTER, ChartType.HEATMAP, ChartType.PIE, ChartType.CONTROL,
ChartType.COMBINE, ChartType.RADAR, ChartType.NETWORK
];
// 차트속성맵 - 미니맵 사용
private _useMiniMap: ChartType[] = [
ChartType.BAR, ChartType.LINE, ChartType.SCATTER, ChartType.HEATMAP, ChartType.CONTROL,
ChartType.BOXPLOT, ChartType.WATERFALL, ChartType.COMBINE
];
/**
* 선택툴 사용 여부 판단
* @param {string} type
* @returns {boolean}
*/
public checkUseSelectionByTypeString(type:string): boolean {
return -1 < this._useSelection.indexOf(ChartType[type.toUpperCase()]);
} // function - checkUseSelectionByTypeString
/**
* 선택툴 사용 여부 판단
* @param {ChartType} type
* @returns {boolean}
*/
public checkUseSelectionByType(type:ChartType): boolean {
return -1 < this._useSelection.indexOf(type);
} // function - checkUseSelectionByType
/**
* 선택툴 사용 여부 판단
* @param {string} type
* @returns {boolean}
*/
public checkUseMultiSelectionByTypeString(type:string): boolean {
return -1 < this._useMultiSelection.indexOf(ChartType[type.toUpperCase()]);
} // function - checkUseMultiSelectionByTypeString
/**
* 선택툴 사용 여부 판단
* @param {ChartType} type
* @returns {boolean}
*/
public checkUseMultiSelectionByType(type:ChartType): boolean {
return -1 < this._useMultiSelection.indexOf(type);
} // function - checkUseMultiSelectionByType
/**
* 확대툴 사용 여부 판단
* @param {string} type
* @returns {boolean}
*/
public checkUseZoomByTypeString(type:string): boolean {
return -1 < this._useZoom.indexOf(ChartType[type.toUpperCase()]);
} // function - checkUseZoomByTypeString
/**
* 확대툴 사용 여부 판단
* @param {ChartType} type
* @returns {boolean}
*/
public checkUseZoomByType(type:ChartType): boolean {
return -1 < this._useZoom.indexOf(type);
} // function - checkUseZoomByType
/**
* 범례 사용 여부 판단
* @param {string} type
* @returns {boolean}
*/
public checkUseLegendByTypeString(type: string): boolean {
return -1 < this._useLegend.indexOf(ChartType[type.toUpperCase()]);
} // function - checkUseLegendByTypeString
/**
* 범례 사용 여부 판단
* @param {ChartType} type
* @returns {boolean}
*/
public checkUseLegendByType(type: ChartType): boolean {
return -1 < this._useLegend.indexOf(type);
} // function - checkUseLegendByType
/**
* 미니맵 사용 여부 판단
* @param {string} type
* @returns {boolean}
*/
public checkUseMiniMapByTypeString(type: string): boolean {
return -1 < this._useMiniMap.indexOf(ChartType[type.toUpperCase()]);
} // function - checkUseMiniMapByTypeString
/**
* 미니맵 사용 여부 판단
* @param {ChartType} type
* @returns {boolean}
*/
public checkUseMiniMapByType(type: ChartType): boolean {
return -1 < this._useMiniMap.indexOf(type);
} // function - checkUseMiniMapByTypeString
} | the_stack |
type DistributeKeys<T> = { [P in keyof T]: P }
/**
* Validate response
* @see https://dev.twitch.tv/docs/authentication#validating-requests
*/
export type ApiValidateResponse = {
client_id: string
login: string
scopes: string[]
user_id: string
expires_in: number
}
/**
* @see https://dev.twitch.tv/docs/irc/guide#twitch-irc-capabilities
*/
export enum Capabilities {
'tags' = 'twitch.tv/tags',
'commands' = 'twitch.tv/commands',
'membership' = 'twitch.tv/membership',
}
/**
* @see https://dev.twitch.tv/docs/irc/membership
*/
export enum MembershipCommands {
JOIN = 'JOIN',
MODE = 'MODE',
PART = 'PART',
NAMES = '353',
NAMES_END = '366',
}
/**
* @see https://dev.twitch.tv/docs/irc/tags
*/
export enum TagCommands {
CLEAR_CHAT = 'CLEARCHAT',
GLOBALUSERSTATE = 'GLOBALUSERSTATE',
PRIVATE_MESSAGE = 'PRIVMSG',
ROOM_STATE = 'ROOMSTATE',
USER_NOTICE = 'USERNOTICE',
USER_STATE = 'USERSTATE',
}
export enum OtherCommands {
WELCOME = '001',
PING = 'PING',
PONG = 'PONG',
WHISPER = 'WHISPER',
}
/**
* @see https://dev.twitch.tv/docs/irc/commands
*/
export enum BaseCommands {
CLEAR_CHAT = 'CLEARCHAT',
CLEAR_MESSAGE = 'CLEARMSG',
HOST_TARGET = 'HOSTTARGET',
NOTICE = 'NOTICE',
RECONNECT = 'RECONNECT',
ROOM_STATE = 'ROOMSTATE',
USER_NOTICE = 'USERNOTICE',
USER_STATE = 'USERSTATE',
}
export enum Commands {
WELCOME = '001',
PING = 'PING',
PONG = 'PONG',
RECONNECT = 'RECONNECT',
WHISPER = 'PRIVMSG #jtv',
JOIN = 'JOIN',
MODE = 'MODE',
PART = 'PART',
NAMES = '353',
NAMES_END = '366',
CLEAR_CHAT = 'CLEARCHAT',
CLEAR_MESSAGE = 'CLEARMSG',
GLOBALUSERSTATE = 'GLOBALUSERSTATE',
HOST_TARGET = 'HOSTTARGET',
NOTICE = 'NOTICE',
PRIVATE_MESSAGE = 'PRIVMSG',
ROOM_STATE = 'ROOMSTATE',
USER_NOTICE = 'USERNOTICE',
USER_STATE = 'USERSTATE',
}
export enum ChatEvents {
RAW = 'RAW',
ALL = '*',
CONNECTED = 'CONNECTED',
DISCONNECTED = 'DISCONNECTED',
RECONNECT = 'RECONNECT',
AUTHENTICATED = 'AUTHENTICATED',
AUTHENTICATION_FAILED = 'AUTHENTICATION_FAILED',
GLOBALUSERSTATE = 'GLOBALUSERSTATE',
ERROR_ENCOUNTERED = 'ERROR_ENCOUNTERED',
PARSE_ERROR_ENCOUNTERED = 'PARSE_ERROR_ENCOUNTERED',
ANON_GIFT_PAID_UPGRADE = 'ANON_GIFT_PAID_UPGRADE',
GIFT_PAID_UPGRADE = 'GIFT_PAID_UPGRADE',
RAID = 'RAID',
RESUBSCRIPTION = 'RESUBSCRIPTION',
RITUAL = 'RITUAL',
SUBSCRIPTION = 'SUBSCRIPTION',
SUBSCRIPTION_GIFT = 'SUBSCRIPTION_GIFT',
SUBSCRIPTION_GIFT_COMMUNITY = 'SUBSCRIPTION_GIFT_COMMUNITY',
ROOM_MODS = 'ROOM_MODS',
MOD_GAINED = 'MOD_GAINED',
MOD_LOST = 'MOD_LOST',
USER_BANNED = 'USER_BANNED',
CHEER = 'CHEER',
HOST_ON = 'HOST_ON',
HOST_OFF = 'HOST_OFF',
HOSTED = 'HOSTED',
HOSTED_WITHOUT_VIEWERS = 'HOSTED/WITHOUT_VIEWERS',
HOSTED_WITH_VIEWERS = 'HOSTED/WITH_VIEWERS',
HOSTED_AUTO = 'HOSTED/AUTO',
}
/**
* @see https://help.twitch.tv/customer/en/portal/articles/659095-chat-moderation-commands
*/
export enum ChatCommands {
BAN = 'ban',
BLOCK = 'block',
CLEAR = 'clear',
COLOR = 'color',
COMMERCIAL = 'commercial',
// DISCONNECTED = 'disconnect',
DELETE = 'delete',
EMOTE_ONLY = 'emoteonly',
EMOTE_ONLY_OFF = 'emoteonlyoff',
FOLLOWERS_ONLY = 'followers',
FOLLOWERS_ONLY_OFF = 'followersoff',
HELP = 'help',
HOST = 'host',
MARKER = 'marker',
ME = 'me',
MOD = 'mod',
MODS = 'mods',
// PART = 'part',
R9K = 'r9kbeta',
R9K_OFF = 'r9kbetaoff',
RAID = 'raid',
SLOW = 'slow',
SLOW_OFF = 'slowoff',
SUBSCRIBERS = 'subscribers',
SUBSCRIBERS_OFF = 'subscribersoff',
TIMEOUT = 'timeout',
UNBAN = 'unban',
UNBLOCK = 'unblock',
UNHOST = 'unhost',
UNMOD = 'unmod',
UNRAID = 'unraid',
UNVIP = 'unvip',
VIP = 'vip',
VIPS = 'vips',
WHISPER = 'w',
}
export enum KnownNoticeMessageIds {
ALREADY_BANNED = 'already_banned',
ALREADY_EMOTE_ONLY_OFF = 'already_emote_only_off',
ALREADY_EMOTE_ONLY_ON = 'already_emote_only_on',
ALREADY_R9K_OFF = 'already_r9k_off',
ALREADY_R9K_ON = 'already_r9k_on',
ALREADY_SUBS_OFF = 'already_subs_off',
ALREADY_SUBS_ON = 'already_subs_on',
BAD_HOST_HOSTING = 'bad_host_hosting',
BAD_MOD_MOD = 'bad_mod_mod',
BAN_SUCCESS = 'ban_success',
BAD_UNBAN_NO_BAN = 'bad_unban_no_ban',
COLOR_CHANGED = 'color_changed',
CMDS_AVAILABLE = 'cmds_available',
COMMERCIAL_SUCCESS = 'commercial_success',
EMOTE_ONLY_OFF = 'emote_only_off',
EMOTE_ONLY_ON = 'emote_only_on',
FOLLOWERS_OFF = 'followers_off',
FOLLOWERS_ON = 'followers_on',
FOLLOWERS_ONZERO = 'followers_onzero',
HOST_OFF = 'host_off',
HOST_ON = 'host_on',
HOSTS_REMAINING = 'hosts_remaining',
MSG_CHANNEL_SUSPENDED = 'msg_channel_suspended',
MOD_SUCCESS = 'mod_success',
NOT_HOSTING = 'not_hosting',
R9K_OFF = 'r9k_off',
R9K_ON = 'r9k_on',
ROOM_MODS = 'room_mods',
SLOW_OFF = 'slow_off',
SLOW_ON = 'slow_on',
SUBS_OFF = 'subs_off',
SUBS_ON = 'subs_on',
TIMEOUT_SUCCESS = 'timeout_success',
UNBAN_SUCCESS = 'unban_success',
UNMOD_SUCCESS = 'unmod_success',
UNRAID_SUCCESS = 'unraid_success',
UNRECOGNIZED_CMD = 'unrecognized_cmd',
}
export const KnownNoticeMessageIdsUpperCase = Object.entries(
KnownNoticeMessageIds,
).reduce(
(uppercase, [key, value]) => ({ ...uppercase, [key]: value.toUpperCase() }),
{} as Record<keyof typeof KnownNoticeMessageIds, string>,
)
export const NoticeEvents = Object.keys(KnownNoticeMessageIds).reduce(
(events, event) => ({
...events,
[event]: event,
[`${Commands.NOTICE}/${event.toUpperCase()}`]: event,
}),
{} as DistributeKeys<typeof KnownNoticeMessageIds>,
)
export type NoticeEvents = keyof typeof NoticeEvents
export enum PrivateMessageEvents {
CHEER = 'CHEER',
HOSTED_WITHOUT_VIEWERS = 'HOSTED_WITHOUT_VIEWERS',
HOSTED_WITH_VIEWERS = 'HOSTED_WITH_VIEWERS',
HOSTED_AUTO = 'HOSTED_AUTO',
}
/**
* @see https://dev.twitch.tv/docs/irc/tags#usernotice-twitch-tags
*/
export enum KnownUserNoticeMessageIds {
ANON_GIFT_PAID_UPGRADE = 'anongiftpaidupgrade',
GIFT_PAID_UPGRADE = 'giftpaidupgrade',
RAID = 'raid',
RESUBSCRIPTION = 'resub',
RITUAL = 'ritual',
SUBSCRIPTION = 'sub',
SUBSCRIPTION_GIFT = 'subgift',
SUBSCRIPTION_GIFT_COMMUNITY = 'submysterygift',
}
export const UserNoticeEvents = Object.keys(KnownUserNoticeMessageIds).reduce(
(events, event) => ({
...events,
[event]: event,
[`${Commands.USER_NOTICE}/${event}`]: event,
}),
{} as DistributeKeys<typeof KnownUserNoticeMessageIds>,
)
export type UserNoticeEvents = keyof typeof UserNoticeEvents
export const Events = {
...MembershipCommands,
...TagCommands,
...OtherCommands,
...BaseCommands,
...ChatEvents,
...NoticeEvents,
...PrivateMessageEvents,
...UserNoticeEvents,
}
export type Events = keyof DistributeKeys<typeof Events>
export enum BooleanBadges {
'admin',
'broadcaster',
'globalMod',
'moderator',
'partner',
'premium',
'staff',
'subGifter',
'turbo',
'vip',
}
export enum NumberBadges {
'bits',
'bitsLeader',
'subscriber',
}
export type Badges =
| {
// Booleans
admin: boolean
broadcaster: boolean
globalMod: boolean
moderator: boolean
partner: boolean
premium: boolean
staff: boolean
subGifter: boolean
turbo: boolean
vip: boolean
// Numbers
bits: number
bitsLeader: number
subscriber: number
}
| {
[key: string]: string
}
export type EmoteTag = {
id: string
start: number
end: number
}
/**
* Tags
*/
export interface BaseTags {
[key: string]: any
}
/**
* CLEARCHAT tags
* @see https://dev.twitch.tv/docs/irc/tags#clearchat-twitch-tags
*/
export interface ClearChatTags extends BaseTags {
banReason?: string
banDuration?: number
}
/**
* CLEARMSG tags
* @see https://dev.twitch.tv/docs/irc/tags#clearmsg-twitch-tags
*/
export interface ClearMessageTags extends BaseTags {
login: string
targetMsgId: string
}
/**
* GLOBALUSERSTATE tags
* @see https://dev.twitch.tv/docs/irc/tags#globaluserstate-twitch-tags
*/
export interface GlobalUserStateTags extends BaseTags {
emoteSets: string[]
userType?: string
username: string
}
/**
* ROOMSTATE Tag
* @see https://dev.twitch.tv/docs/irc/tags#roomstate-twitch-tags
*/
export interface RoomStateTags extends BaseTags {
followersOnly?: number | boolean
broadcasterLang?: string
slow?: number
emoteOnly?: boolean
r9k?: boolean
subsOnly?: boolean
}
export interface NoticeTags extends BaseTags {
msgId: KnownNoticeMessageIds
}
/**
* USERSTATE tags
* @see https://dev.twitch.tv/docs/irc/tags#userstate-twitch-tags
*/
export interface UserStateTags extends BaseTags {
badges: Partial<Badges>
color: string
displayName: string
emotes: EmoteTag[]
emoteSets: string[]
mod?: string
subscriber?: string
turbo?: string
userType?: string
username: string
isModerator: boolean
}
/**
* PRIVMSG tags
* @see https://dev.twitch.tv/docs/irc/tags#privmsg-twitch-tags
*/
export interface PrivateMessageTags extends UserStateTags {
bits?: string
}
/**
* USERNOTICE tags
* @see https://dev.twitch.tv/docs/irc/tags#usernotice-twitch-tags
*/
export interface UserNoticeTags extends UserStateTags {
id: string
login: string
msgId: KnownUserNoticeMessageIds
roomId: string
systemMsg: string
tmiSentTs: string
}
export type Tags =
| ClearChatTags
| GlobalUserStateTags
| RoomStateTags
| UserStateTags
| PrivateMessageTags
| NoticeTags
| UserNoticeTags
/**
* Messages
*/
/* Base message parsed from Twitch */
export interface Message {
_raw: string
timestamp: Date
channel: string
username: string
command: string
event: string
isSelf: boolean
message: string
tags: { [key: string]: any }
parameters?: { [key: string]: string | number | boolean }
}
export interface BaseMessage extends Message {
_raw: string
timestamp: Date
channel: string
username: string
command: string
event: string
isSelf: boolean
message: string
tags: { [key: string]: any }
}
/**
* Join a channel.
* @see https://dev.twitch.tv/docs/irc/membership/#join-twitch-membership
*/
export interface JoinMessage extends Omit<BaseMessage, 'message'> {
command: Commands.JOIN
event: Commands.JOIN
}
/**
* Depart from a channel.
* @see https://dev.twitch.tv/docs/irc/membership/#part-twitch-membership
*/
export interface PartMessage extends Omit<BaseMessage, 'message'> {
command: Commands.PART
event: Commands.PART
}
/**
* Gain/lose moderator (operator) status in a channel.
* @see https://dev.twitch.tv/docs/irc/membership/#mode-twitch-membership
*/
export interface ModeModGainedMessage extends BaseMessage {
command: Commands.MODE
event: ChatEvents.MOD_GAINED
message: '+o'
isModerator: true
}
export interface ModeModLostMessage extends BaseMessage {
command: Commands.MODE
event: ChatEvents.MOD_LOST
message: '-o'
isModerator: false
}
export type ModeMessages = ModeModGainedMessage | ModeModLostMessage
/**
* List current chatters in a channel.
* @see https://dev.twitch.tv/docs/irc/membership/#names-twitch-membership
*/
export interface NamesMessage extends Omit<BaseMessage, 'message'> {
command: Commands.NAMES
event: Commands.NAMES
usernames: string[]
}
/**
* End of list current chatters in a channel.
* @see https://dev.twitch.tv/docs/irc/membership/#names-twitch-membership
*/
export interface NamesEndMessage extends Omit<BaseMessage, 'message'> {
command: Commands.NAMES_END
event: Commands.NAMES_END
}
/**
* GLOBALUSERSTATE message
* @see https://dev.twitch.tv/docs/irc/tags#globaluserstate-twitch-tags
*/
export interface GlobalUserStateMessage extends BaseMessage {
command: Commands.GLOBALUSERSTATE
event: Commands.GLOBALUSERSTATE
tags: GlobalUserStateTags
}
/**
* Temporary or permanent ban on a channel.
* @see https://dev.twitch.tv/docs/irc/commands/#clearchat-twitch-commands
* @see https://dev.twitch.tv/docs/irc/tags/#clearchat-twitch-tags
*/
export interface ClearChatUserBannedMessage
extends Omit<BaseMessage, 'message'> {
command: Commands.CLEAR_CHAT
event: ChatEvents.USER_BANNED
tags: ClearChatTags
}
/**
* All chat is cleared (deleted).
* @see https://dev.twitch.tv/docs/irc/commands/#clearchat-twitch-commands
* @see https://dev.twitch.tv/docs/irc/tags/#clearchat-twitch-tags
*/
export interface ClearChatMessage
extends Omit<BaseMessage, 'tags' | 'username' | 'message'> {
command: Commands.CLEAR_CHAT
event: Commands.CLEAR_CHAT
}
export type ClearChatMessages = ClearChatMessage | ClearChatUserBannedMessage
/**
* Single message removal on a channel.
* @see https://dev.twitch.tv/docs/irc/commands#clearmsg-twitch-commands
* @see https://dev.twitch.tv/docs/irc/tags#clearmsg-twitch-tags
*/
export interface ClearMessageMessage extends Omit<BaseMessage, 'message'> {
command: Commands.CLEAR_MESSAGE
event: Commands.CLEAR_MESSAGE
tags: ClearMessageTags
targetMessageId: string
}
/**
* Host starts or stops a message.
* @see https://dev.twitch.tv/docs/irc/commands/#hosttarget-twitch-commands
*/
export interface HostTargetMessage extends Omit<BaseMessage, 'message'> {
command: Commands.HOST_TARGET
event: ChatEvents.HOST_ON | ChatEvents.HOST_OFF
numberOfViewers?: number
}
/**
* When a user joins a channel or a room setting is changed.
* @see https://dev.twitch.tv/docs/irc/tags#roomstate-twitch-tags
*/
export interface RoomStateMessage extends BaseMessage {
command: Commands.ROOM_STATE
event: Commands.ROOM_STATE
tags: RoomStateTags
}
/**
* Base NOTICE message
*/
export interface NoticeMessage extends Omit<BaseMessage, 'event'> {
command: Commands.NOTICE
event: Exclude<NoticeEvents, typeof NoticeEvents.ROOM_MODS>
tags: NoticeTags
username: 'tmi.twitch.tv' | string
}
/**
* NOTICE/ROOM_MODS message
*/
export interface NoticeRoomModsMessage extends Omit<NoticeMessage, 'event'> {
event: typeof NoticeEvents.ROOM_MODS
/** The moderators of this channel. */
mods: string[]
}
/**
* NOTICE message
* @see https://dev.twitch.tv/docs/irc/commands/#msg-id-tags-for-the-notice-commands-capability
*/
export type NoticeMessages = NoticeMessage | NoticeRoomModsMessage
/**
* USERSTATE message
*/
export interface UserStateMessage extends BaseMessage {
command: Commands.USER_STATE
event: Commands.USER_STATE
tags: UserStateTags
}
/**
* PRIVMSG messages
*/
interface BasePrivateMessage
extends Omit<UserStateMessage, 'command' | 'event'> {
command: Commands.PRIVATE_MESSAGE
}
/**
* When a user joins a channel or sends a PRIVMSG to a channel.
*/
export interface PrivateMessage extends BasePrivateMessage {
event: Commands.PRIVATE_MESSAGE
}
export interface PrivateMessageWithBits extends BasePrivateMessage {
event: ChatEvents.CHEER
bits: number
}
interface BaseHostingPrivateMessage extends Omit<BasePrivateMessage, 'tags'> {}
/**
* When a user hosts your channel while connected as broadcaster.
*/
export interface HostingPrivateMessage extends BaseHostingPrivateMessage {
event: ChatEvents.HOSTED_WITHOUT_VIEWERS
tags: { displayName: string }
}
export interface HostingWithViewersPrivateMessage
extends BaseHostingPrivateMessage {
event: ChatEvents.HOSTED_WITH_VIEWERS
tags: { displayName: string }
numberOfViewers?: number
}
export interface HostingAutoPrivateMessage extends BaseHostingPrivateMessage {
event: ChatEvents.HOSTED_AUTO
tags: { displayName: string }
numberOfViewers?: number
}
export type PrivateMessages =
| PrivateMessage
| PrivateMessageWithBits
| HostingPrivateMessage
| HostingWithViewersPrivateMessage
| HostingAutoPrivateMessage
export interface MessageParameters {
[key: string]: string | number | boolean | Date | undefined
}
export interface AnonymousGiftPaidUpgradeParameters extends MessageParameters {}
export interface GiftPaidUpgradeParameters extends MessageParameters {
promoGiftTotal: number
promoName: string
senderLogin: string
senderName: string
}
export interface RaidParameters extends MessageParameters {
displayName: string
login: string
viewerCount: number
}
export interface ResubscriptionParameters extends MessageParameters {
months: number
subPlan: string
subPlanName: string
}
export interface RitualParameters extends MessageParameters {
ritualName: string
}
export interface SubscriptionGiftCommunityParameters extends MessageParameters {
massGiftCount: number
senderCount: number
subPlan: number
}
export interface SubscriptionGiftParameters extends MessageParameters {
months: number
subPlan: string
subPlanName: string
recipientDisplayName: string
recipientId: string
recipientName: string
}
export interface SubscriptionParameters extends MessageParameters {
months: 1
subPlan: string
subPlanName: string
}
export type UserNoticeMessageParameters =
| AnonymousGiftPaidUpgradeParameters
| GiftPaidUpgradeParameters
| RaidParameters
| ResubscriptionParameters
| RitualParameters
| SubscriptionGiftCommunityParameters
| SubscriptionGiftParameters
| SubscriptionParameters
export interface UserNoticeMessage
extends Omit<BaseMessage, 'event' | 'parameters'> {
command: Commands.USER_NOTICE
event: UserNoticeEvents
tags: UserNoticeTags
parameters: MessageParameters
systemMessage: string
}
/**
* On anonymous gifted subscription paid upgrade to a channel.
*/
export interface UserNoticeAnonymousGiftPaidUpgradeMessage
extends UserNoticeMessage {
command: Commands.USER_NOTICE
event: typeof UserNoticeEvents.ANON_GIFT_PAID_UPGRADE
parameters: AnonymousGiftPaidUpgradeParameters
}
/**
* On gifted subscription paid upgrade to a channel.
*/
export interface UserNoticeGiftPaidUpgradeMessage
extends Omit<UserNoticeMessage, 'parameters'> {
event: typeof UserNoticeEvents.GIFT_PAID_UPGRADE
parameters: {
promoGiftTotal: number
promoName: string
senderLogin: string
senderName: string
}
}
/**
* On channel raid.
*/
export interface UserNoticeRaidMessage
extends Omit<UserNoticeMessage, 'parameters'> {
event: typeof UserNoticeEvents.RAID
parameters: {
displayName: string
login: string
viewerCount: number
}
}
/**
* On resubscription (subsequent months) to a channel.
*/
export interface UserNoticeResubscriptionMessage
extends Omit<UserNoticeMessage, 'parameters'> {
event: typeof UserNoticeEvents.RESUBSCRIPTION
parameters: {
months: number
subPlan: string
subPlanName: string
}
}
/**
* On channel ritual.
*/
export interface UserNoticeRitualMessage
extends Omit<UserNoticeMessage, 'parameters'> {
event: typeof UserNoticeEvents.RITUAL
parameters: {
ritualName: string
}
}
/**
* On subscription gift to a channel community.
*/
export interface UserNoticeSubscriptionGiftCommunityMessage
extends Omit<UserNoticeMessage, 'parameters'> {
event: typeof UserNoticeEvents.SUBSCRIPTION_GIFT_COMMUNITY
parameters: {
massGiftCount: number
senderCount: number
subPlan: number
}
}
/**
* On subscription gift to a channel.
*/
export interface UserNoticeSubscriptionGiftMessage
extends Omit<UserNoticeMessage, 'parameters'> {
event: typeof UserNoticeEvents.SUBSCRIPTION_GIFT
parameters: {
months: number
subPlan: string
subPlanName: string
recipientDisplayName: string
recipientId: string
recipientName: string
}
}
/**
* On subscription (first month) to a channel.
*/
export interface UserNoticeSubscriptionMessage
extends Omit<UserNoticeMessage, 'event' | 'parameters'> {
event: typeof UserNoticeEvents.SUBSCRIPTION
parameters: {
months: 1
subPlan: string
subPlanName: string
}
}
export type UserNoticeMessages =
| UserNoticeAnonymousGiftPaidUpgradeMessage
| UserNoticeGiftPaidUpgradeMessage
| UserNoticeRaidMessage
| UserNoticeResubscriptionMessage
| UserNoticeRitualMessage
| UserNoticeSubscriptionGiftCommunityMessage
| UserNoticeSubscriptionGiftMessage
| UserNoticeSubscriptionMessage
export type Messages =
| BaseMessage
| JoinMessage
| PartMessage
| ModeMessages
| NamesMessage
| NamesEndMessage
| GlobalUserStateMessage
| ClearChatMessages
| ClearMessageMessage
| HostTargetMessage
| RoomStateMessage
| NoticeMessages
| UserStateMessage
| PrivateMessages
| UserNoticeMessages | the_stack |
namespace Linqer {
/**
* wrapper class over iterable instances that exposes the methods usually found in .NET LINQ
*
* @export
* @class Enumerable
* @implements {Iterable<any>}
* @implements {IUsesQuickSort}
*/
export class Enumerable implements Iterable<any>, IUsesQuickSort {
_src: IterableType;
_generator: () => Iterator<any>;
_useQuickSort: boolean;
// indicates that count and elementAt functions will not cause iterating the enumerable
_canSeek: boolean;
_count: null | (() => number);
_tryGetAt: null | ((index: number) => { value: any } | null);
// true if the enumerable was iterated at least once
_wasIterated: boolean;
/**
* sort an array in place using the Enumerable sort algorithm (Quicksort)
*
* @static
* @memberof Enumerable
*/
static sort: (arr: any[], comparer?: IComparer) => any[];
/**
* You should never use this. Instead use Enumerable.from
* @param {IterableType} src
* @memberof Enumerable
*/
constructor(src: IterableType) {
_ensureIterable(src);
this._src = src;
const iteratorFunction: (() => Iterator<any>) = (src as Iterable<any>)[Symbol.iterator];
// the generator is either the iterator of the source enumerable
// or the generator function that was provided as the source itself
if (iteratorFunction) {
this._generator = iteratorFunction.bind(src);
} else {
this._generator = src as (() => Iterator<any>);
}
// set sorting method on an enumerable and all the derived ones should inherit it
// TODO: a better method of doing this
this._useQuickSort = (src as IUsesQuickSort)._useQuickSort !== undefined
? (src as IUsesQuickSort)._useQuickSort
: true;
this._canSeek = false;
this._count = null;
this._tryGetAt = null;
this._wasIterated = false;
}
/**
* Wraps an iterable item into an Enumerable if it's not already one
*
* @static
* @param {IterableType} iterable
* @returns {Enumerable}
* @memberof Enumerable
*/
static from(iterable: IterableType): Enumerable {
if (iterable instanceof Enumerable) return iterable;
return new Enumerable(iterable);
}
/**
* the Enumerable instance exposes the same iterator as the wrapped iterable or generator function
*
* @returns {Iterator<any>}
* @memberof Enumerable
*/
[Symbol.iterator](): Iterator<any> {
this._wasIterated = true;
return this._generator();
}
/**
* returns an empty Enumerable
*
* @static
* @returns {Enumerable}
* @memberof Enumerable
*/
static empty(): Enumerable {
const result = new Enumerable([]);
result._count = () => 0;
result._tryGetAt = (index: number) => null;
result._canSeek = true;
return result;
}
/**
* generates a sequence of integer numbers within a specified range.
*
* @static
* @param {number} start
* @param {number} count
* @returns {Enumerable}
* @memberof Enumerable
*/
static range(start: number, count: number): Enumerable {
const gen = function* () {
for (let i = 0; i < count; i++) {
yield start + i;
}
};
const result = new Enumerable(gen);
result._count = () => count;
result._tryGetAt = index => {
if (index >= 0 && index < count) return { value: start + index };
return null;
};
result._canSeek = true;
return result;
}
/**
* Generates a sequence that contains one repeated value.
*
* @static
* @param {*} item
* @param {number} count
* @returns {Enumerable}
* @memberof Enumerable
*/
static repeat(item: any, count: number): Enumerable {
const gen = function* () {
for (let i = 0; i < count; i++) {
yield item;
}
};
const result = new Enumerable(gen);
result._count = () => count;
result._tryGetAt = index => {
if (index >= 0 && index < count) return { value: item };
return null;
};
result._canSeek = true;
return result;
}
/**
* Same value as count(), but will throw an Error if enumerable is not seekable and has to be iterated to get the length
*/
get length():number {
_ensureInternalTryGetAt(this);
if (!this._canSeek) throw new Error('Calling length on this enumerable will iterate it. Use count()');
return this.count();
}
/**
* Concatenates two sequences by appending iterable to the existing one.
*
* @param {IterableType} iterable
* @returns {Enumerable}
* @memberof Enumerable
*/
concat(iterable: IterableType): Enumerable {
_ensureIterable(iterable);
const self: Enumerable = this;
// the generator will iterate the enumerable first, then the iterable that was given as a parameter
// this will be able to seek if both the original and the iterable derived enumerable can seek
// the indexing function will get items from the first and then second enumerable without iteration
const gen = function* () {
for (const item of self) {
yield item;
}
for (const item of Enumerable.from(iterable)) {
yield item;
}
};
const result = new Enumerable(gen);
const other = Enumerable.from(iterable);
result._count = () => self.count() + other.count();
_ensureInternalTryGetAt(this);
_ensureInternalTryGetAt(other);
result._canSeek = self._canSeek && other._canSeek;
if (self._canSeek) {
result._tryGetAt = index => {
return self._tryGetAt!(index) || other._tryGetAt!(index - self.count());
};
}
return result;
}
/**
* Returns the number of elements in a sequence.
*
* @returns {number}
* @memberof Enumerable
*/
count(): number {
_ensureInternalCount(this);
return this._count!();
}
/**
* Returns distinct elements from a sequence.
* WARNING: using a comparer makes this slower. Not specifying it uses a Set to determine distinctiveness.
*
* @param {IEqualityComparer} [equalityComparer=EqualityComparer.default]
* @returns {Enumerable}
* @memberof Enumerable
*/
distinct(equalityComparer: IEqualityComparer = EqualityComparer.default): Enumerable {
const self: Enumerable = this;
// if the comparer function is not provided, a Set will be used to quickly determine distinctiveness
const gen = equalityComparer === EqualityComparer.default
? function* () {
const distinctValues = new Set();
for (const item of self) {
const size = distinctValues.size;
distinctValues.add(item);
if (size < distinctValues.size) {
yield item;
}
}
}
// otherwise values will be compared with previous values ( O(n^2) )
// use distinctByHash in Linqer.extra to use a hashing function ( O(n log n) )
: function* () {
const values = [];
for (const item of self) {
let unique = true;
for (let i=0; i<values.length; i++) {
if (equalityComparer(item, values[i])) {
unique = false;
break;
}
}
if (unique) yield item;
values.push(item);
}
};
return new Enumerable(gen);
}
/**
* Returns the element at a specified index in a sequence.
*
* @param {number} index
* @returns {*}
* @memberof Enumerable
*/
elementAt(index: number): any {
_ensureInternalTryGetAt(this);
const result = this._tryGetAt!(index);
if (!result) throw new Error('Index out of range');
return result.value;
}
/**
* Returns the element at a specified index in a sequence or undefined if the index is out of range.
*
* @param {number} index
* @returns {(any | undefined)}
* @memberof Enumerable
*/
elementAtOrDefault(index: number): any | undefined {
_ensureInternalTryGetAt(this);
const result = this._tryGetAt!(index);
if (!result) return undefined;
return result.value;
}
/**
* Returns the first element of a sequence.
*
* @returns {*}
* @memberof Enumerable
*/
first(): any {
return this.elementAt(0);
}
/**
* Returns the first element of a sequence, or a default value if no element is found.
*
* @returns {(any | undefined)}
* @memberof Enumerable
*/
firstOrDefault(): any | undefined {
return this.elementAtOrDefault(0);
}
/**
* Returns the last element of a sequence.
*
* @returns {*}
* @memberof Enumerable
*/
last(): any {
_ensureInternalTryGetAt(this);
// if this cannot seek, getting the last element requires iterating the whole thing
if (!this._canSeek) {
let result = null;
let found = false;
for (const item of this) {
result = item;
found = true;
}
if (found) return result;
throw new Error('The enumeration is empty');
}
// if this can seek, then just go directly at the last element
const count = this.count();
return this.elementAt(count - 1);
}
/**
* Returns the last element of a sequence, or undefined if no element is found.
*
* @returns {(any | undefined)}
* @memberof Enumerable
*/
lastOrDefault(): any | undefined {
_ensureInternalTryGetAt(this);
if (!this._canSeek) {
let result = undefined;
for (const item of this) {
result = item;
}
return result;
}
const count = this.count();
return this.elementAtOrDefault(count - 1);
}
/**
* Returns the count, minimum and maximum value in a sequence of values.
* A custom function can be used to establish order (the result 0 means equal, 1 means larger, -1 means smaller)
*
* @param {IComparer} [comparer]
* @returns {{ count: number, min: any, max: any }}
* @memberof Enumerable
*/
stats(comparer?: IComparer): { count: number, min: any, max: any } {
if (comparer) {
_ensureFunction(comparer);
} else {
comparer = _defaultComparer;
}
const agg = {
count: 0,
min: undefined,
max: undefined
};
for (const item of this) {
if (typeof agg.min === 'undefined' || comparer(item, agg.min) < 0) agg.min = item;
if (typeof agg.max === 'undefined' || comparer(item, agg.max) > 0) agg.max = item;
agg.count++;
}
return agg;
}
/**
* Returns the minimum value in a sequence of values.
* A custom function can be used to establish order (the result 0 means equal, 1 means larger, -1 means smaller)
*
* @param {IComparer} [comparer]
* @returns {*}
* @memberof Enumerable
*/
min(comparer?: IComparer): any {
const stats = this.stats(comparer);
return stats.count === 0
? undefined
: stats.min;
}
/**
* Returns the maximum value in a sequence of values.
* A custom function can be used to establish order (the result 0 means equal, 1 means larger, -1 means smaller)
*
* @param {IComparer} [comparer]
* @returns {*}
* @memberof Enumerable
*/
max(comparer?: IComparer): any {
const stats = this.stats(comparer);
return stats.count === 0
? undefined
: stats.max;
}
/**
* Projects each element of a sequence into a new form.
*
* @param {ISelector} selector
* @returns {Enumerable}
* @memberof Enumerable
*/
select(selector: ISelector): Enumerable {
_ensureFunction(selector);
const self: Enumerable = this;
// the generator is applying the selector on all the items of the enumerable
// the count of the resulting enumerable is the same as the original's
// the indexer is the same as that of the original, with the selector applied on the value
const gen = function* () {
let index = 0;
for (const item of self) {
yield selector(item, index);
index++;
}
};
const result = new Enumerable(gen);
_ensureInternalCount(this);
result._count = this._count;
_ensureInternalTryGetAt(self);
result._canSeek = self._canSeek;
result._tryGetAt = index => {
const res = self._tryGetAt!(index);
if (!res) return res;
return { value: selector(res.value) };
};
return result;
}
/**
* Bypasses a specified number of elements in a sequence and then returns the remaining elements.
*
* @param {number} nr
* @returns {Enumerable}
* @memberof Enumerable
*/
skip(nr: number): Enumerable {
const self: Enumerable = this;
// the generator just enumerates the first nr numbers then starts yielding values
// the count is the same as the original enumerable, minus the skipped items and at least 0
// the indexer is the same as for the original, with an offset
const gen = function* () {
let nrLeft = nr;
for (const item of self) {
if (nrLeft > 0) {
nrLeft--;
} else {
yield item;
}
}
};
const result = new Enumerable(gen);
result._count = () => Math.max(0, self.count() - nr);
_ensureInternalTryGetAt(this);
result._canSeek = this._canSeek;
result._tryGetAt = index => self._tryGetAt!(index + nr);
return result;
}
/**
* Takes start elements, ignores howmany elements, continues with the new items and continues with the original enumerable
* Equivalent to the value of an array after performing splice on it with the same parameters
* @param start
* @param howmany
* @param items
* @returns splice
*/
splice(start: number, howmany: number, ...newItems:any[]) : Enumerable {
// tried to define length and splice so that this is seen as an Array-like object,
// but it doesn't work on properties. length needs to be a field.
return this.take(start).concat(newItems).concat(this.skip(start+howmany));
}
/**
* Computes the sum of a sequence of numeric values.
*
* @returns {(number | undefined)}
* @memberof Enumerable
*/
sum(): number | undefined {
const stats = this.sumAndCount();
return stats.count === 0
? undefined
: stats.sum;
}
/**
* Computes the sum and count of a sequence of numeric values.
*
* @returns {{ sum: number, count: number }}
* @memberof Enumerable
*/
sumAndCount(): { sum: number, count: number } {
const agg = {
count: 0,
sum: 0
};
for (const item of this) {
agg.sum = agg.count === 0
? _toNumber(item)
: agg.sum + _toNumber(item);
agg.count++;
}
return agg;
}
/**
* Returns a specified number of contiguous elements from the start of a sequence.
*
* @param {number} nr
* @returns {Enumerable}
* @memberof Enumerable
*/
take(nr: number): Enumerable {
const self: Enumerable = this;
// the generator will stop after nr items yielded
// the count is the maximum between the total count and nr
// the indexer is the same, as long as it's not higher than nr
const gen = function* () {
let nrLeft = nr;
for (const item of self) {
if (nrLeft > 0) {
yield item;
nrLeft--;
}
if (nrLeft <= 0) {
break;
}
}
};
const result = new Enumerable(gen);
result._count = () => Math.min(nr, self.count());
_ensureInternalTryGetAt(this);
result._canSeek = self._canSeek;
if (self._canSeek) {
result._tryGetAt = index => {
if (index >= nr) return null;
return self._tryGetAt!(index);
};
}
return result;
}
/**
* creates an array from an Enumerable
*
* @returns {any[]}
* @memberof Enumerable
*/
toArray(): any[] {
_ensureInternalTryGetAt(this);
// this should be faster than Array.from(this)
if (this._canSeek) {
const arr = new Array(this.count());
for (let i = 0; i < arr.length; i++) {
arr[i] = this._tryGetAt!(i)?.value;
}
return arr;
}
// try to optimize the array growth by increasing it
// by 64 every time it is needed
const minIncrease = 64;
let size = 0;
const arr = [];
for (const item of this) {
if (size === arr.length) {
arr.length += minIncrease;
}
arr[size] = item;
size++;
}
arr.length = size;
return arr;
}
/**
* similar to toArray, but returns a seekable Enumerable (itself if already seekable) that can do count and elementAt without iterating
*
* @returns {Enumerable}
* @memberof Enumerable
*/
toList(): Enumerable {
_ensureInternalTryGetAt(this);
if (this._canSeek) return this;
return Enumerable.from(this.toArray());
}
/**
* Filters a sequence of values based on a predicate.
*
* @param {IFilter} condition
* @returns {Enumerable}
* @memberof Enumerable
*/
where(condition: IFilter): Enumerable {
_ensureFunction(condition);
const self: Enumerable = this;
// cannot imply the count or indexer from the condition
// where will have to iterate through the whole thing
const gen = function* () {
let index = 0;
for (const item of self) {
if (condition(item, index)) {
yield item;
}
index++;
}
};
return new Enumerable(gen);
}
}
// throw if src is not a generator function or an iteratable
export function _ensureIterable(src: IterableType): void {
if (src) {
if ((src as Iterable<any>)[Symbol.iterator]) return;
if (typeof src === 'function' && (src as Function).constructor.name === 'GeneratorFunction') return;
}
throw new Error('the argument must be iterable!');
}
// throw if f is not a function
export function _ensureFunction(f: Function): void {
if (!f || typeof f !== 'function') throw new Error('the argument needs to be a function!');
}
// return Nan if this is not a number
// different from Number(obj), which would cast strings to numbers
function _toNumber(obj: any): number {
return typeof obj === 'number'
? obj
: Number.NaN;
}
// return the iterable if already an array or use Array.from to create one
export function _toArray(iterable: IterableType) {
if (!iterable) return [];
if (Array.isArray(iterable)) return iterable;
return Array.from(iterable);
}
// if the internal count function is not defined, set it to the most appropriate one
export function _ensureInternalCount(enumerable: Enumerable) {
if (enumerable._count) return;
if (enumerable._src instanceof Enumerable) {
// the count is the same as the underlying enumerable
const innerEnumerable = enumerable._src as Enumerable;
_ensureInternalCount(innerEnumerable);
enumerable._count = () => innerEnumerable._count!();
return;
}
const src = enumerable._src as any;
// this could cause false positives, but if it has a numeric length or size, use it
if (typeof src !== 'function' && typeof src.length === 'number') {
enumerable._count = () => src.length;
return;
}
if (typeof src.size === 'number') {
enumerable._count = () => src.size;
return;
}
// otherwise iterate the whole thing and count all items
enumerable._count = () => {
let x = 0;
for (const item of enumerable) x++;
return x;
};
}
// ensure there is an internal indexer function adequate for this enumerable
// this also determines if the enumerable can seek
export function _ensureInternalTryGetAt(enumerable: Enumerable) {
if (enumerable._tryGetAt) return;
enumerable._canSeek = true;
if (enumerable._src instanceof Enumerable) {
// indexer and seekability is the same as for the underlying enumerable
const innerEnumerable = enumerable._src as Enumerable;
_ensureInternalTryGetAt(innerEnumerable);
enumerable._tryGetAt = index => innerEnumerable._tryGetAt!(index);
enumerable._canSeek = innerEnumerable._canSeek;
return;
}
if (typeof enumerable._src === 'string') {
// a string can be accessed by index
enumerable._tryGetAt = index => {
if (index < (enumerable._src as string).length) {
return { value: (enumerable._src as string).charAt(index) };
}
return null;
};
return;
}
if (Array.isArray(enumerable._src)) {
// an array can be accessed by index
enumerable._tryGetAt = index => {
if (index >= 0 && index < (enumerable._src as any[]).length) {
return { value: (enumerable._src as any[])[index] };
}
return null;
};
return;
}
const src = enumerable._src as any;
if (typeof enumerable._src !== 'function' && typeof src.length === 'number') {
// try to access an object with a defined numeric length by indexing it
// might cause false positives
enumerable._tryGetAt = index => {
if (index < src.length && typeof src[index] !== 'undefined') {
return { value: src[index] };
}
return null;
};
return;
}
enumerable._canSeek = false;
// TODO other specialized types? objects, maps, sets?
enumerable._tryGetAt = index => {
let x = 0;
for (const item of enumerable) {
if (index === x) return { value: item };
x++;
}
return null;
}
}
/**
* an extended iterable type that also supports generator functions
*/
export type IterableType = Iterable<any> | (() => Iterator<any>) | Enumerable;
/**
* A comparer function to be used in sorting
*/
export type IComparer = (item1: any, item2: any) => -1 | 0 | 1;
/**
* A selector function to be used in mapping
*/
export type ISelector<T = any> = (item: any, index?: number) => T;
/**
* A filter function
*/
export type IFilter = ISelector<boolean>;
/**
* The default comparer function between two items
* @param item1
* @param item2
*/
export const _defaultComparer: IComparer = (item1, item2) => {
if (item1 > item2) return 1;
if (item1 < item2) return -1;
return 0;
};
/**
* Interface for an equality comparer
*/
export type IEqualityComparer = (item1: any, item2: any) => boolean;
/**
* Predefined equality comparers
* default is the equivalent of ==
* exact is the equivalent of ===
*/
export const EqualityComparer = {
default: (item1: any, item2: any) => item1 == item2,
exact: (item1: any, item2: any) => item1 === item2,
};
// used to access the variable determining if
// an enumerable should be ordered using Quicksort or not
interface IUsesQuickSort {
_useQuickSort: boolean;
}
} | the_stack |
import { NewExpression, Identifier, TemplateString, ArrayLiteral, CastExpression, BooleanLiteral, StringLiteral, NumericLiteral, CharacterLiteral, PropertyAccessExpression, Expression, ElementAccessExpression, BinaryExpression, UnresolvedCallExpression, ConditionalExpression, InstanceOfExpression, ParenthesizedExpression, RegexLiteral, UnaryExpression, UnaryType, MapLiteral, NullLiteral, AwaitExpression, UnresolvedNewExpression, UnresolvedMethodCallExpression, InstanceMethodCallExpression, NullCoalesceExpression, GlobalFunctionCallExpression, StaticMethodCallExpression, LambdaCallExpression, IMethodCallExpression } from "../One/Ast/Expressions";
import { Statement, ReturnStatement, UnsetStatement, ThrowStatement, ExpressionStatement, VariableDeclaration, BreakStatement, ForeachStatement, IfStatement, WhileStatement, ForStatement, DoStatement, ContinueStatement, TryStatement, Block } from "../One/Ast/Statements";
import { Class, SourceFile, IVariable, Lambda, Interface, IInterface, MethodParameter, IVariableWithInitializer, Visibility, Package, IHasAttributesAndTrivia } from "../One/Ast/Types";
import { VoidType, ClassType, InterfaceType, EnumType, AnyType, LambdaType, NullType, GenericsType } from "../One/Ast/AstTypes";
import { ThisReference, EnumReference, ClassReference, MethodParameterReference, VariableDeclarationReference, ForVariableReference, ForeachVariableReference, SuperReference, StaticFieldReference, StaticPropertyReference, InstanceFieldReference, InstancePropertyReference, EnumMemberReference, CatchVariableReference, GlobalFunctionReference, StaticThisReference, VariableReference } from "../One/Ast/References";
import { GeneratedFile } from "./GeneratedFile";
import { NameUtils } from "./NameUtils";
import { IGenerator } from "./IGenerator";
import { IExpression, IType } from "../One/Ast/Interfaces";
import { ITransformer } from "../One/ITransformer";
import { IGeneratorPlugin } from "./IGeneratorPlugin";
import { TemplateFileGeneratorPlugin } from "./TemplateFileGeneratorPlugin";
export class CsharpGenerator implements IGenerator {
usings: Set<string>;
currentClass: IInterface;
reservedWords = ["object", "else", "operator", "class", "enum", "void", "string", "implicit", "Type", "Enum", "params", "using", "throw", "ref", "base", "virtual", "interface", "int", "const"];
fieldToMethodHack = ["length", "size"];
instanceOfIds: { [name: string]: number } = {};
plugins: IGeneratorPlugin[] = [];
getLangName(): string { return "CSharp"; }
getExtension(): string { return "cs"; }
getTransforms(): ITransformer[] { return []; }
addInclude(include: string): void { this.usings.add(include); }
addPlugin(plugin: IGeneratorPlugin) {
this.plugins.push(plugin);
// TODO: hack?
if (plugin instanceof TemplateFileGeneratorPlugin) {
// ...
}
}
name_(name: string) {
if (this.reservedWords.includes(name)) name += "_";
if (this.fieldToMethodHack.includes(name)) name += "()";
const nameParts = name.split(/-/g);
for (let i = 1; i < nameParts.length; i++)
nameParts[i] = nameParts[i][0].toUpperCase() + nameParts[i].substr(1);
name = nameParts.join('');
return name;
}
leading(item: Statement) {
let result = "";
if (item.leadingTrivia !== null && item.leadingTrivia.length > 0)
result += item.leadingTrivia;
//if (item.attributes !== null)
// result += Object.keys(item.attributes).map(x => `// @${x} ${item.attributes[x]}\n`).join("");
return result;
}
preArr(prefix: string, value: string[]) {
return value.length > 0 ? `${prefix}${value.join(", ")}` : "";
}
preIf(prefix: string, condition: boolean) {
return condition ? prefix : "";
}
pre(prefix: string, value: string) {
return value !== null ? `${prefix}${value}` : "";
}
typeArgs(args: string[]): string { return args !== null && args.length > 0 ? `<${args.join(", ")}>` : ""; }
typeArgs2(args: IType[]): string { return this.typeArgs(args.map(x => this.type(x))); }
type(t: IType, mutates = true): string {
if (t instanceof ClassType) {
const typeArgs = this.typeArgs(t.typeArguments.map(x => this.type(x)));
if (t.decl.name === "TsString")
return "string";
else if (t.decl.name === "TsBoolean")
return "bool";
else if (t.decl.name === "TsNumber")
return "int";
else if (t.decl.name === "TsArray") {
if (mutates) {
this.usings.add("System.Collections.Generic");
return `List<${this.type(t.typeArguments[0])}>`;
} else
return `${this.type(t.typeArguments[0])}[]`;
} else if (t.decl.name === "Promise") {
this.usings.add("System.Threading.Tasks");
return t.typeArguments[0] instanceof VoidType ? "Task" : `Task${typeArgs}`;
} else if (t.decl.name === "Object") {
this.usings.add("System");
return `object`;
} else if (t.decl.name === "TsMap") {
this.usings.add("System.Collections.Generic");
return `Dictionary<string, ${this.type(t.typeArguments[0])}>`;
}
return this.name_(t.decl.name) + typeArgs;
} else if (t instanceof InterfaceType)
return `${this.name_(t.decl.name)}${this.typeArgs(t.typeArguments.map(x => this.type(x)))}`;
else if (t instanceof VoidType)
return "void";
else if (t instanceof EnumType)
return `${this.name_(t.decl.name)}`;
else if (t instanceof AnyType)
return `object`;
else if (t instanceof NullType)
return `null`;
else if (t instanceof GenericsType)
return `${t.typeVarName}`;
else if (t instanceof LambdaType) {
const isFunc = !(t.returnType instanceof VoidType);
const paramTypes = t.parameters.map(x => this.type(x.type, false));
if (isFunc)
paramTypes.push(this.type(t.returnType, false));
this.usings.add("System");
return `${isFunc ? "Func" : "Action"}<${paramTypes.join(", ")}>`;
} else if (t === null) {
return "/* TODO */ object";
} else {
debugger;
return "/* MISSING */";
}
}
isTsArray(type: IType) { return type instanceof ClassType && type.decl.name == "TsArray"; }
vis(v: Visibility) {
return v === Visibility.Private ? "private" :
v === Visibility.Protected ? "protected" :
v === Visibility.Public ? "public" :
"/* TODO: not set */public";
}
varWoInit(v: IVariable, attr: IHasAttributesAndTrivia) {
let type: string;
if (attr !== null && attr.attributes !== null && "csharp-type" in attr.attributes)
type = attr.attributes["csharp-type"];
else if (v.type instanceof ClassType && v.type.decl.name === "TsArray") {
if (v.mutability.mutated) {
this.usings.add("System.Collections.Generic");
type = `List<${this.type(v.type.typeArguments[0])}>`;
} else {
type = `${this.type(v.type.typeArguments[0])}[]`;
}
} else {
type = this.type(v.type);
}
return `${type} ${this.name_(v.name)}`;
}
var(v: IVariableWithInitializer, attrs: IHasAttributesAndTrivia) {
return this.varWoInit(v, attrs) + (v.initializer !== null ? ` = ${this.expr(v.initializer)}` : "");
}
exprCall(typeArgs: IType[], args: Expression[]) {
return this.typeArgs2(typeArgs) + `(${args.map(x => this.expr(x)).join(", ")})`;
}
mutateArg(arg: Expression, shouldBeMutable: boolean) {
if (this.isTsArray(arg.actualType)) {
if (arg instanceof ArrayLiteral && !shouldBeMutable) {
const itemType = (<ClassType>arg.actualType).typeArguments[0];
return arg.items.length === 0 && !this.isTsArray(itemType) ? `new ${this.type(itemType)}[0]` :
`new ${this.type(itemType)}[] { ${arg.items.map(x => this.expr(x)).join(', ')} }`;
}
let currentlyMutable = shouldBeMutable;
if (arg instanceof VariableReference)
currentlyMutable = arg.getVariable().mutability.mutated;
else if (arg instanceof InstanceMethodCallExpression || arg instanceof StaticMethodCallExpression)
currentlyMutable = false;
if (currentlyMutable && !shouldBeMutable)
return `${this.expr(arg)}.ToArray()`;
else if (!currentlyMutable && shouldBeMutable) {
this.usings.add("System.Linq");
return `${this.expr(arg)}.ToList()`;
}
}
return this.expr(arg);
}
mutatedExpr(expr: Expression, toWhere: Expression) {
if (toWhere instanceof VariableReference) {
const v = toWhere.getVariable();
if (this.isTsArray(v.type))
return this.mutateArg(expr, v.mutability.mutated);
}
return this.expr(expr);
}
callParams(args: Expression[], params: MethodParameter[]) {
const argReprs: string[] = [];
for (let i = 0; i < args.length; i++)
argReprs.push(this.isTsArray(params[i].type) ? this.mutateArg(args[i], params[i].mutability.mutated) : this.expr(args[i]));
return `(${argReprs.join(", ")})`;
}
methodCall(expr: IMethodCallExpression) {
return this.name_(expr.method.name) + this.typeArgs2(expr.typeArgs) + this.callParams(expr.args, expr.method.parameters);
}
inferExprNameForType(type: IType): string {
if (type instanceof ClassType && type.typeArguments.every((x,_) => x instanceof ClassType)) {
const fullName = type.typeArguments.map(x => (<ClassType>x).decl.name).join('') + type.decl.name;
return NameUtils.shortName(fullName);
}
return null;
}
expr(expr: IExpression): string {
for (const plugin of this.plugins) {
const result = plugin.expr(expr);
if (result !== null)
return result;
}
let res = "UNKNOWN-EXPR";
if (expr instanceof NewExpression) {
res = `new ${this.type(expr.cls)}${this.callParams(expr.args, expr.cls.decl.constructor_ !== null ? expr.cls.decl.constructor_.parameters : [])}`;
} else if (expr instanceof UnresolvedNewExpression) {
res = `/* TODO: UnresolvedNewExpression */ new ${this.type(expr.cls)}(${expr.args.map(x => this.expr(x)).join(", ")})`;
} else if (expr instanceof Identifier) {
res = `/* TODO: Identifier */ ${expr.text}`;
} else if (expr instanceof PropertyAccessExpression) {
res = `/* TODO: PropertyAccessExpression */ ${this.expr(expr.object)}.${expr.propertyName}`;
} else if (expr instanceof UnresolvedCallExpression) {
res = `/* TODO: UnresolvedCallExpression */ ${this.expr(expr.func)}${this.exprCall(expr.typeArgs, expr.args)}`;
} else if (expr instanceof UnresolvedMethodCallExpression) {
res = `/* TODO: UnresolvedMethodCallExpression */ ${this.expr(expr.object)}.${expr.methodName}${this.exprCall(expr.typeArgs, expr.args)}`;
} else if (expr instanceof InstanceMethodCallExpression) {
res = `${this.expr(expr.object)}.${this.methodCall(expr)}`;
} else if (expr instanceof StaticMethodCallExpression) {
res = `${this.name_(expr.method.parentInterface.name)}.${this.methodCall(expr)}`;
} else if (expr instanceof GlobalFunctionCallExpression) {
res = `Global.${this.name_(expr.func.name)}${this.exprCall([], expr.args)}`;
} else if (expr instanceof LambdaCallExpression) {
res = `${this.expr(expr.method)}(${expr.args.map(x => this.expr(x)).join(", ")})`;
} else if (expr instanceof BooleanLiteral) {
res = `${expr.boolValue ? "true" : "false"}`;
} else if (expr instanceof StringLiteral) {
res = `${JSON.stringify(expr.stringValue)}`;
} else if (expr instanceof NumericLiteral) {
res = `${expr.valueAsText}`;
} else if (expr instanceof CharacterLiteral) {
res = `'${expr.charValue}'`;
} else if (expr instanceof ElementAccessExpression) {
res = `${this.expr(expr.object)}[${this.expr(expr.elementExpr)}]`;
} else if (expr instanceof TemplateString) {
const parts: string[] = [];
for (const part of expr.parts) {
// parts.push(part.literalText.replace(new RegExp("\\n"), $"\\n").replace(new RegExp("\\r"), $"\\r").replace(new RegExp("\\t"), $"\\t").replace(new RegExp("{"), "{{").replace(new RegExp("}"), "}}").replace(new RegExp("\""), $"\\\""));
if (part.isLiteral) {
let lit = "";
for (let i = 0; i < part.literalText.length; i++) {
const chr = part.literalText[i];
if (chr === '\n') lit += "\\n";
else if (chr === '\r') lit += "\\r";
else if (chr === '\t') lit += "\\t";
else if (chr === '\\') lit += "\\\\";
else if (chr === '"') lit += '\\"';
else if (chr === '{') lit += "{{";
else if (chr === '}') lit += "}}";
else {
const chrCode = chr.charCodeAt(0);
if (32 <= chrCode && chrCode <= 126)
lit += chr;
else
throw new Error(`invalid char in template string (code=${chrCode})`);
}
}
parts.push(lit);
}
else {
const repr = this.expr(part.expression);
parts.push(part.expression instanceof ConditionalExpression ? `{(${repr})}` : `{${repr}}`);
}
}
res = `$"${parts.join('')}"`;
} else if (expr instanceof BinaryExpression) {
res = `${this.expr(expr.left)} ${expr.operator} ${this.mutatedExpr(expr.right, expr.operator === "=" ? expr.left : null)}`;
} else if (expr instanceof ArrayLiteral) {
if (expr.items.length === 0) {
res = `new ${this.type(expr.actualType)}()`;
} else
res = `new ${this.type(expr.actualType)} { ${expr.items.map(x => this.expr(x)).join(', ')} }`;
} else if (expr instanceof CastExpression) {
if (expr.instanceOfCast !== null && expr.instanceOfCast.alias !== null)
res = this.name_(expr.instanceOfCast.alias);
else
res = `((${this.type(expr.newType)})${this.expr(expr.expression)})`;
} else if (expr instanceof ConditionalExpression) {
res = `${this.expr(expr.condition)} ? ${this.expr(expr.whenTrue)} : ${this.mutatedExpr(expr.whenFalse, expr.whenTrue)}`;
} else if (expr instanceof InstanceOfExpression) {
if (expr.implicitCasts !== null && expr.implicitCasts.length > 0) {
let aliasPrefix = this.inferExprNameForType(expr.checkType);
if (aliasPrefix === null)
aliasPrefix = expr.expr instanceof VariableReference ? expr.expr.getVariable().name : "obj";
const id = aliasPrefix in this.instanceOfIds ? this.instanceOfIds[aliasPrefix] : 1;
this.instanceOfIds[aliasPrefix] = id + 1;
expr.alias = aliasPrefix + (id === 1 ? "" : `${id}`);
}
res = `${this.expr(expr.expr)} is ${this.type(expr.checkType)}${expr.alias !== null ? ` ${this.name_(expr.alias)}` : ""}`;
} else if (expr instanceof ParenthesizedExpression) {
res = `(${this.expr(expr.expression)})`;
} else if (expr instanceof RegexLiteral) {
res = `new RegExp(${JSON.stringify(expr.pattern)})`;
} else if (expr instanceof Lambda) {
let body: string;
if (expr.body.statements.length === 1 && expr.body.statements[0] instanceof ReturnStatement)
body = this.expr((<ReturnStatement>expr.body.statements[0]).expression);
else
body = `{ ${this.rawBlock(expr.body)} }`;
const params = expr.parameters.map(x => this.name_(x.name));
res = `${params.length === 1 ? params[0] : `(${params.join(", ")})`} => ${body}`;
} else if (expr instanceof UnaryExpression && expr.unaryType === UnaryType.Prefix) {
res = `${expr.operator}${this.expr(expr.operand)}`;
} else if (expr instanceof UnaryExpression && expr.unaryType === UnaryType.Postfix) {
res = `${this.expr(expr.operand)}${expr.operator}`;
} else if (expr instanceof MapLiteral) {
const repr = expr.items.map(item => `[${JSON.stringify(item.key)}] = ${this.expr(item.value)}`).join(",\n");
res = `new ${this.type(expr.actualType)} ` + (repr === "" ? "{}" : repr.includes("\n") ? `{\n${this.pad(repr)}\n}` : `{ ${repr} }`);
} else if (expr instanceof NullLiteral) {
res = `null`;
} else if (expr instanceof AwaitExpression) {
res = `await ${this.expr(expr.expr)}`;
} else if (expr instanceof ThisReference) {
res = `this`;
} else if (expr instanceof StaticThisReference) {
res = `${this.currentClass.name}`;
} else if (expr instanceof EnumReference) {
res = `${this.name_(expr.decl.name)}`;
} else if (expr instanceof ClassReference) {
res = `${this.name_(expr.decl.name)}`;
} else if (expr instanceof MethodParameterReference) {
res = `${this.name_(expr.decl.name)}`;
} else if (expr instanceof VariableDeclarationReference) {
res = `${this.name_(expr.decl.name)}`;
} else if (expr instanceof ForVariableReference) {
res = `${this.name_(expr.decl.name)}`;
} else if (expr instanceof ForeachVariableReference) {
res = `${this.name_(expr.decl.name)}`;
} else if (expr instanceof CatchVariableReference) {
res = `${this.name_(expr.decl.name)}`;
} else if (expr instanceof GlobalFunctionReference) {
res = `${this.name_(expr.decl.name)}`;
} else if (expr instanceof SuperReference) {
res = `base`;
} else if (expr instanceof StaticFieldReference) {
res = `${this.name_(expr.decl.parentInterface.name)}.${this.name_(expr.decl.name)}`;
} else if (expr instanceof StaticPropertyReference) {
res = `${this.name_(expr.decl.parentClass.name)}.${this.name_(expr.decl.name)}`;
} else if (expr instanceof InstanceFieldReference) {
res = `${this.expr(expr.object)}.${this.name_(expr.field.name)}`;
} else if (expr instanceof InstancePropertyReference) {
res = `${this.expr(expr.object)}.${this.name_(expr.property.name)}`;
} else if (expr instanceof EnumMemberReference) {
res = `${this.name_(expr.decl.parentEnum.name)}.${this.name_(expr.decl.name)}`;
} else if (expr instanceof NullCoalesceExpression) {
res = `${this.expr(expr.defaultExpr)} ?? ${this.mutatedExpr(expr.exprIfNull, expr.defaultExpr)}`;
} else debugger;
return res;
}
block(block: Block, allowOneLiner = true): string {
const stmtLen = block.statements.length;
return stmtLen === 0 ? " { }" : allowOneLiner && stmtLen === 1 && !(block.statements[0] instanceof IfStatement) ?
`\n${this.pad(this.rawBlock(block))}` : ` {\n${this.pad(this.rawBlock(block))}\n}`;
}
stmt(stmt: Statement): string {
let res = "UNKNOWN-STATEMENT";
if (stmt.attributes !== null && "csharp" in stmt.attributes) {
res = stmt.attributes["csharp"];
} else if (stmt instanceof BreakStatement) {
res = "break;";
} else if (stmt instanceof ReturnStatement) {
res = stmt.expression === null ? "return;" : `return ${this.mutateArg(stmt.expression, false)};`;
} else if (stmt instanceof UnsetStatement) {
res = `/* unset ${this.expr(stmt.expression)}; */`;
} else if (stmt instanceof ThrowStatement) {
res = `throw ${this.expr(stmt.expression)};`;
} else if (stmt instanceof ExpressionStatement) {
res = `${this.expr(stmt.expression)};`;
} else if (stmt instanceof VariableDeclaration) {
if (stmt.initializer instanceof NullLiteral)
res = `${this.type(stmt.type, stmt.mutability.mutated)} ${this.name_(stmt.name)} = null;`;
else if (stmt.initializer !== null)
res = `var ${this.name_(stmt.name)} = ${this.mutateArg(stmt.initializer, stmt.mutability.mutated)};`;
else
res = `${this.type(stmt.type)} ${this.name_(stmt.name)};`;
} else if (stmt instanceof ForeachStatement) {
res = `foreach (var ${this.name_(stmt.itemVar.name)} in ${this.expr(stmt.items)})` + this.block(stmt.body);
} else if (stmt instanceof IfStatement) {
const elseIf = stmt.else_ !== null && stmt.else_.statements.length === 1 && stmt.else_.statements[0] instanceof IfStatement;
res = `if (${this.expr(stmt.condition)})${this.block(stmt.then)}`;
res += (elseIf ? `\nelse ${this.stmt(stmt.else_.statements[0])}` : "") +
(!elseIf && stmt.else_ !== null ? `\nelse` + this.block(stmt.else_) : "");
} else if (stmt instanceof WhileStatement) {
res = `while (${this.expr(stmt.condition)})` + this.block(stmt.body);
} else if (stmt instanceof ForStatement) {
res = `for (${stmt.itemVar !== null ? this.var(stmt.itemVar, null) : ""}; ${this.expr(stmt.condition)}; ${this.expr(stmt.incrementor)})` + this.block(stmt.body);
} else if (stmt instanceof DoStatement) {
res = `do${this.block(stmt.body)} while (${this.expr(stmt.condition)});`;
} else if (stmt instanceof TryStatement) {
res = "try" + this.block(stmt.tryBody, false);
if (stmt.catchBody !== null) {
this.usings.add("System");
res += ` catch (Exception ${this.name_(stmt.catchVar.name)}) ${this.block(stmt.catchBody, false)}`;
}
if (stmt.finallyBody !== null)
res += "finally" + this.block(stmt.finallyBody);
} else if (stmt instanceof ContinueStatement) {
res = `continue;`;
} else debugger;
return this.leading(stmt) + res;
}
stmts(stmts: Statement[]): string { return stmts.map(stmt => this.stmt(stmt)).join("\n"); }
rawBlock(block: Block): string { return this.stmts(block.statements); }
classLike(cls: IInterface) {
this.currentClass = cls;
const resList: string[] = [];
const staticConstructorStmts: Statement[] = [];
const complexFieldInits: Statement[] = [];
if (cls instanceof Class) {
const fieldReprs: string[] = [];
for (const field of cls.fields) {
const isInitializerComplex = field.initializer !== null &&
!(field.initializer instanceof StringLiteral) &&
!(field.initializer instanceof BooleanLiteral) &&
!(field.initializer instanceof NumericLiteral);
const prefix = `${this.vis(field.visibility)} ${this.preIf("static ", field.isStatic)}`;
if (field.interfaceDeclarations.length > 0) {
const init = field.initializer !== null ? ` = ${this.expr(field.initializer)};` : "";
fieldReprs.push(`${prefix}${this.varWoInit(field, field)} { get; set; }${init}`);
} else if (isInitializerComplex) {
if (field.isStatic)
staticConstructorStmts.push(new ExpressionStatement(new BinaryExpression(new StaticFieldReference(field), "=", field.initializer)));
else
complexFieldInits.push(new ExpressionStatement(new BinaryExpression(new InstanceFieldReference(new ThisReference(cls), field), "=", field.initializer)));
fieldReprs.push(`${prefix}${this.varWoInit(field, field)};`);
} else
fieldReprs.push(`${prefix}${this.var(field, field)};`);
}
resList.push(fieldReprs.join("\n"));
resList.push(cls.properties.map(prop => {
return `${this.vis(prop.visibility)} ${this.preIf("static ", prop.isStatic)}` +
this.varWoInit(prop, prop) +
(prop.getter !== null ? ` {\n get {\n${this.pad(this.block(prop.getter))}\n }\n}` : "") +
(prop.setter !== null ? ` {\n set {\n${this.pad(this.block(prop.setter))}\n }\n}` : "");
}).join("\n"));
if (staticConstructorStmts.length > 0)
resList.push(`static ${this.name_(cls.name)}()\n{\n${this.pad(this.stmts(staticConstructorStmts))}\n}`);
if (cls.constructor_ !== null) {
const constrFieldInits: Statement[] = [];
for (const field of cls.fields.filter(x => x.constructorParam !== null)) {
const fieldRef = new InstanceFieldReference(new ThisReference(cls), field);
const mpRef = new MethodParameterReference(field.constructorParam);
// TODO: decide what to do with "after-TypeEngine" transformations
mpRef.setActualType(field.type, false, false);
constrFieldInits.push(new ExpressionStatement(new BinaryExpression(fieldRef, "=", mpRef)));
}
// @java var stmts = Stream.concat(Stream.concat(constrFieldInits.stream(), complexFieldInits.stream()), ((Class)cls).constructor_.getBody().statements.stream()).toArray(Statement[]::new);
// @java-import java.util.stream.Stream
const stmts = constrFieldInits.concat(complexFieldInits).concat(cls.constructor_.body.statements);
resList.push(
"public " +
this.preIf("/* throws */ ", cls.constructor_.throws) +
this.name_(cls.name) +
`(${cls.constructor_.parameters.map(p => this.var(p, p)).join(", ")})` +
(cls.constructor_.superCallArgs !== null ? `: base(${cls.constructor_.superCallArgs.map(x => this.expr(x)).join(", ")})` : "") +
`\n{\n${this.pad(this.stmts(stmts))}\n}`);
} else if (complexFieldInits.length > 0)
resList.push(`public ${this.name_(cls.name)}()\n{\n${this.pad(this.stmts(complexFieldInits))}\n}`);
} else if (cls instanceof Interface) {
resList.push(cls.fields.map(field => `${this.varWoInit(field, field)} { get; set; }`).join("\n"));
}
const methods: string[] = [];
for (const method of cls.methods) {
if (cls instanceof Class && method.body === null) continue; // declaration only
methods.push(
(method.parentInterface instanceof Interface ? "" : this.vis(method.visibility) + " ") +
this.preIf("static ", method.isStatic) +
this.preIf("virtual ", method.overrides === null && method.overriddenBy.length > 0) +
this.preIf("override ", method.overrides !== null) +
this.preIf("async ", method.async) +
this.preIf("/* throws */ ", method.throws) +
`${this.type(method.returns, false)} ` +
this.name_(method.name) + this.typeArgs(method.typeArguments) +
`(${method.parameters.map(p => this.var(p, null)).join(", ")})` +
(method.body !== null ? `\n{\n${this.pad(this.stmts(method.body.statements))}\n}` : ";"));
}
resList.push(methods.join("\n\n"));
return this.pad(resList.filter(x => x !== "").join("\n\n"));
}
pad(str: string): string { return str.split(/\n/g).map(x => ` ${x}`).join('\n'); }
pathToNs(path: string): string {
// Generator/ExprLang/ExprLangAst.ts -> Generator.ExprLang
const parts = path.split(/\//g);
parts.pop();
return parts.join('.');
}
genFile(sourceFile: SourceFile): string {
this.instanceOfIds = {};
this.usings = new Set<string>();
const enums = sourceFile.enums.map(enum_ => `public enum ${this.name_(enum_.name)} { ${enum_.values.map(x => this.name_(x.name)).join(", ")} }`);
const intfs = sourceFile.interfaces.map(intf => `public interface ${this.name_(intf.name)}${this.typeArgs(intf.typeArguments)}`+
`${this.preArr(" : ", intf.baseInterfaces.map(x => this.type(x)))} {\n${this.classLike(intf)}\n}`);
const classes: string[] = [];
for (const cls of sourceFile.classes) {
const baseClasses: IType[] = [];
if (cls.baseClass !== null)
baseClasses.push(cls.baseClass);
for (const intf of cls.baseInterfaces)
baseClasses.push(intf);
classes.push(`public class ${this.name_(cls.name)}${this.typeArgs(cls.typeArguments)}${this.preArr(" : ", baseClasses.map(x => this.type(x)))}\n{\n${this.classLike(cls)}\n}`);
}
const main = sourceFile.mainBlock.statements.length > 0 ?
`public class Program\n{\n static void Main(string[] args)\n {\n${this.pad(this.rawBlock(sourceFile.mainBlock))}\n }\n}` : "";
// @java var usingsSet = new LinkedHashSet<String>(Arrays.stream(sourceFile.imports).map(x -> this.pathToNs(x.exportScope.scopeName)).filter(x -> x != "").collect(Collectors.toList()));
// @java-import java.util.LinkedHashSet
const usingsSet = new Set<string>(sourceFile.imports.map(x => this.pathToNs(x.exportScope.scopeName)).filter(x => x !== ""));
for (const using of this.usings.values())
usingsSet.add(using);
const usings: string[] = [];
for (const using of usingsSet.values())
usings.push(`using ${using};`);
usings.sort();
let result = [enums.join("\n"), intfs.join("\n\n"), classes.join("\n\n"), main].filter(x => x !== "").join("\n\n");
const nl = "\n"; // Python fix
result = `${usings.join(nl)}\n\nnamespace ${this.pathToNs(sourceFile.sourcePath.path)}\n{\n${this.pad(result)}\n}`;
return result;
}
generate(pkg: Package): GeneratedFile[] {
const result: GeneratedFile[] = [];
for (const path of Object.keys(pkg.files))
result.push(new GeneratedFile(`${path}.cs`, this.genFile(pkg.files[path])));
return result;
}
} | the_stack |
import { DATEPICKER_DIALOG_NAME, DATEPICKER_NAME } from '../../constants.js';
import { KEY_CODES_MAP } from '../../custom_typings.js';
import type { DatepickerDialog } from '../../datepicker-dialog.js';
import type { Datepicker } from '../../datepicker.js';
import { APP_INDEX_URL } from '../constants.js';
import { cleanHtml } from '../helpers/clean-html.js';
import { prettyHtml } from '../helpers/pretty-html.js';
import { toSelector } from '../helpers/to-selector.js';
import {
allStrictEqual,
deepStrictEqual,
ok,
strictEqual,
} from '../helpers/typed-assert.js';
describe(`${DATEPICKER_DIALOG_NAME}::keyboards`, () => {
const focusElement = async (selector: string, inDialog: boolean = false) => {
return browser.executeAsync(async (a, b, c, d, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
const n3 = (d ? n : n2).shadowRoot!.querySelector<HTMLElement>(c)!;
n3.focus();
await n.updateComplete;
await new Promise(y => setTimeout(() => y(n3.focus())));
await n.updateComplete;
done();
}, DATEPICKER_DIALOG_NAME, DATEPICKER_NAME, selector, inDialog);
};
const tapElements = async (
selectors: string[],
keys: string[]
): Promise<void> => {
for (const s of selectors) {
await focusElement(s);
await browser.keys(keys);
}
};
before(async () => {
await browser.url(APP_INDEX_URL);
});
beforeEach(async () => {
await browser.executeAsync(async (a, done) => {
const el: DatepickerDialog = document.createElement(a);
el.locale = 'en-US';
// Reset `min` and `value` here before running tests
el.min = '2000-01-01';
el.value = '2020-02-20';
document.body.appendChild(el);
await el.open();
await el.updateComplete;
done();
}, DATEPICKER_DIALOG_NAME);
});
afterEach(async () => {
await browser.executeAsync((a, done) => {
const el = document.body.querySelector<DatepickerDialog>(a);
if (el) document.body.removeChild(el);
done();
}, DATEPICKER_DIALOG_NAME);
});
it(`switches to year list view`, async () => {
await tapElements(['.btn__year-selector'], ['Space']);
const hasYearListView: boolean = await browser.executeAsync(async (a, b, c, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
const yearListView = n2.shadowRoot!.querySelector<HTMLDivElement>(c)!;
done(yearListView != null);
}, DATEPICKER_DIALOG_NAME, DATEPICKER_NAME, '.datepicker-body__year-list-view');
ok(hasYearListView);
});
it(`switches to calendar view`, async () => {
await browser.executeAsync(async (a, done) => {
const n = document.body.querySelector<Datepicker>(a)!;
n.startView = 'yearList';
await n.updateComplete;
done();
}, DATEPICKER_DIALOG_NAME);
await tapElements(['.btn__calendar-selector'], ['Space']);
const hasCalendarView: boolean = await browser.executeAsync(async (a, b, c, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
const yearListView = n2.shadowRoot!.querySelector<HTMLDivElement>(c)!;
done(yearListView != null);
}, DATEPICKER_DIALOG_NAME, DATEPICKER_NAME, '.datepicker-body__calendar-view');
ok(hasCalendarView);
});
it(`focuses date after navigating away when switching to calendar view`, async () => {
type A = [boolean, string];
await tapElements([
`.btn__month-selector[aria-label="Next month"]`,
`.btn__year-selector`,
], ['Space']);
const hasYearListView: boolean = await browser.executeAsync(async (a, b, c, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
const yearListView = n2.shadowRoot!.querySelector<HTMLDivElement>(c)!;
done(yearListView != null);
}, DATEPICKER_DIALOG_NAME, DATEPICKER_NAME, '.datepicker-body__year-list-view');
await tapElements([`.btn__calendar-selector`], ['Space']);
const [
hasCalendarView,
focusedDateContent,
]: A = await browser.executeAsync(async (a, b, c, d, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
const root = n2.shadowRoot!;
const yearListView = root.querySelector<HTMLDivElement>(c)!;
const focusedDate = root.querySelector<HTMLTableCellElement>(d)!;
done([
yearListView != null,
focusedDate.outerHTML,
] as A);
},
DATEPICKER_DIALOG_NAME,
DATEPICKER_NAME,
'.datepicker-body__calendar-view',
toSelector('.day--focused'));
allStrictEqual([hasCalendarView, hasYearListView], true);
strictEqual(cleanHtml(focusedDateContent), prettyHtml`
<td class="full-calendar__day day--focused" aria-disabled="false" aria-label="Feb 20, 2020" aria-selected="true">
<div class="calendar-day">20</div>
</td>
`);
});
it(`switches back to calendar view when new year is selected`, async () => {
type A = [string, string];
type B = [string, string, string, string, string[]];
const [
prop,
prop2,
]: A = await browser.executeAsync(async (a, b, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
done([
n.value,
n2.value,
] as A);
}, DATEPICKER_DIALOG_NAME, DATEPICKER_NAME);
await tapElements([
'.btn__year-selector',
[
`.year-list-view__list-item.year--selected`,
`+ .year-list-view__list-item`,
`+ .year-list-view__list-item`,
].join(' '),
], ['Space']);
const [
prop3,
prop4,
yearSelectorButtonContent,
calendarLabelContent,
calendarDaysContents,
]: B = await browser.executeAsync(async (a, b, c, d, e, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
const root = n2.shadowRoot!;
const yearSelectorButton = root.querySelector<HTMLButtonElement>(c)!;
const calendarLabel = root.querySelector<HTMLDivElement>(d)!;
const calendarDays = Array.from(
root.querySelectorAll<HTMLTableCellElement>(e), o => o.textContent);
done([
n.value,
n2.value,
yearSelectorButton.outerHTML,
calendarLabel.outerHTML,
calendarDays,
] as B);
},
DATEPICKER_DIALOG_NAME,
DATEPICKER_NAME,
'.btn__year-selector',
toSelector('.calendar-label'),
toSelector('.full-calendar__day'));
allStrictEqual([prop, prop2, prop3], '2020-02-20');
strictEqual(prop4, '2022-02-20');
strictEqual(cleanHtml(yearSelectorButtonContent), prettyHtml`
<button class="btn__year-selector" data-view="yearList">2022</button>
`);
strictEqual(cleanHtml(calendarLabelContent), prettyHtml`
<div class="calendar-label">February 2022</div>
`);
deepStrictEqual(calendarDaysContents.map(n => cleanHtml(n.trim())), [
'', '', 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26,
27, 28, '', '', '', '', '',
'', '', '', '', '', '', '',
].map(String));
});
it(`closes dialog when dismiss button is tapped`, async () => {
type A = [string, string];
await focusElement(`.actions-container > mwc-button[dialog-dismiss]`, true);
await browser.keys(['Space']);
// Wait for dialog closes
await (await $(DATEPICKER_DIALOG_NAME)).waitForDisplayed(undefined, true);
const [
cssDisplay,
ariaHiddenAttr,
]: A = await browser.executeAsync(async (a, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
await n.updateComplete;
done([
getComputedStyle(n).display,
n.getAttribute('aria-hidden'),
] as A);
}, DATEPICKER_DIALOG_NAME);
strictEqual(cssDisplay, 'none');
strictEqual(ariaHiddenAttr, 'true');
});
it(`closes dialog with new focused date when confirm button is tapped`, async () => {
type A = [string, string, string];
type B = [string, string, string];
// FIXME: Using keyboard to select new focused date is tedious and inconsistent.
// Here updates via `value` property.
const [
prop,
prop2,
focusedDateContent,
]: C = await browser.executeAsync(async (a, b, c, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
n2.value = '2020-02-13';
await n2.updateComplete;
const focusedDate = n2.shadowRoot!.querySelector<HTMLTableCellElement>(c)!;
done([
n.value,
n2.value,
focusedDate.outerHTML,
] as A);
}, DATEPICKER_DIALOG_NAME, DATEPICKER_NAME, toSelector('.day--focused'));
await focusElement(`.actions-container > mwc-button[dialog-confirm]`, true);
await browser.keys(['Space']);
await (await $(DATEPICKER_DIALOG_NAME)).waitForDisplayed(undefined, true);
const [
prop3,
cssDisplay,
ariaHiddenAttr,
]: B = await browser.executeAsync(async (a, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
await n.updateComplete;
done([
n.value,
getComputedStyle(n).display,
n.getAttribute('aria-hidden'),
// === '2020-02-13'
] as B);
}, DATEPICKER_DIALOG_NAME);
strictEqual(prop, '2020-02-20');
allStrictEqual([prop2, prop3], '2020-02-13');
strictEqual(cssDisplay, 'none');
strictEqual(ariaHiddenAttr, 'true');
strictEqual(cleanHtml(focusedDateContent), prettyHtml`
<td class="full-calendar__day day--focused" aria-disabled="false" aria-label="Feb 13, 2020" aria-selected="true">
<div class="calendar-day">13</div>
</td>
`);
});
it(`reset value when clear button is tapped`, async () => {
type A = [string, string];
type B = string;
const [
initialVal,
todayValue,
]: A = await browser.executeAsync(async (a, b, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
const padStart = (v: number) => `0${v}`.slice(-2);
const today = new Date();
const fy = today.getFullYear();
const m = today.getMonth();
const d = today.getDate();
const todayVal = [`${fy}`].concat([1 + m, d].map(padStart)).join('-');
n.min = `${fy - 10}-01-01`;
n2.value = `${fy - 1}-01-01`;
n.max = `${fy + 10}-01-01`;
await n2.updateComplete;
await n.updateComplete;
done([n2.value, todayVal] as A);
}, DATEPICKER_DIALOG_NAME, DATEPICKER_NAME);
await focusElement('mwc-button.clear', true);
await browser.keys(['Space']);
const prop: B = await browser.executeAsync(async (a, b, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
done(n2.value as B);
}, DATEPICKER_DIALOG_NAME, DATEPICKER_NAME);
strictEqual(initialVal, `${Number(todayValue.slice(0, 4)) - 1}-01-01`);
strictEqual(prop, todayValue);
});
// region helpers
type C = [string, string, string];
const focusCalendarsContainer = async (): Promise<string> => {
return await browser.executeAsync(async (a, b, c, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
const n3 = n2.shadowRoot!.querySelector<HTMLElement>(c)!;
n3.focus();
await n.updateComplete;
await new Promise(y => setTimeout(() => y(n3.focus())));
await n.updateComplete;
let activeElement = document.activeElement;
while (activeElement?.shadowRoot) {
activeElement = activeElement.shadowRoot.activeElement;
}
done(
`.${Array.from(activeElement?.classList.values() ?? []).join('.')}`
);
}, DATEPICKER_DIALOG_NAME, DATEPICKER_NAME, '.calendars-container');
};
// FIXME: Helper as a workaround until `browser.keys()` supports Alt
// on all browsers on local and CI.
const browserKeys = async (keyCode: number, altKey: boolean = false) => {
await focusCalendarsContainer();
return browser.executeAsync(async (a, b, c, d, e, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
const n3 = n2.shadowRoot!.querySelector<HTMLDivElement>(c)!;
const opt: any = { keyCode: d, altKey: e };
const ev = new CustomEvent('keyup', opt);
Object.keys(opt).forEach((o) => {
Object.defineProperty(ev, o, { value: opt[o] });
});
n3.dispatchEvent(ev);
done();
}, DATEPICKER_DIALOG_NAME, DATEPICKER_NAME, '.calendars-container', keyCode, altKey);
};
const getValuesAfterKeys = async (
key: number,
altKey: boolean = false
): Promise<C> => {
await focusCalendarsContainer();
await browserKeys(key, altKey);
const [prop, prop2, content]: C = await browser.executeAsync(async (a, b, c, done) => {
const n = document.body.querySelector<DatepickerDialog>(a)!;
const n2 = n.shadowRoot!.querySelector<Datepicker>(b)!;
const focusedDate = n2.shadowRoot!.querySelector<HTMLTableCellElement>(c)!;
done([
n.value,
n2.value,
focusedDate.outerHTML,
] as C);
}, DATEPICKER_DIALOG_NAME, DATEPICKER_NAME, toSelector('.day--focused'));
return [prop, prop2, cleanHtml(content)];
};
// #endregion helpers
it(`focuses date (ArrowLeft)`, async () => {
const [
prop,
prop2,
focusedDateContent,
]: C = await getValuesAfterKeys(KEY_CODES_MAP.ARROW_LEFT);
strictEqual(prop, '2020-02-20');
strictEqual(prop2, '2020-02-19');
strictEqual(focusedDateContent, prettyHtml`
<td class="full-calendar__day day--focused" aria-disabled="false" aria-label="Feb 19, 2020" aria-selected="true">
<div class="calendar-day">19</div>
</td>
`);
});
it(`focuses date (ArrowRight)`, async () => {
const [
prop,
prop2,
focusedDateContent,
]: C = await getValuesAfterKeys(KEY_CODES_MAP.ARROW_RIGHT);
strictEqual(prop, '2020-02-20');
strictEqual(prop2, '2020-02-21');
strictEqual(focusedDateContent, prettyHtml`
<td class="full-calendar__day day--focused" aria-disabled="false" aria-label="Feb 21, 2020" aria-selected="true">
<div class="calendar-day">21</div>
</td>
`);
});
it(`focuses date (ArrowUp)`, async () => {
const [
prop,
prop2,
focusedDateContent,
]: C = await getValuesAfterKeys(KEY_CODES_MAP.ARROW_UP);
strictEqual(prop, '2020-02-20');
strictEqual(prop2, `2020-02-13`);
strictEqual(focusedDateContent, prettyHtml`
<td class="full-calendar__day day--focused" aria-disabled="false" aria-label="Feb 13, 2020" aria-selected="true">
<div class="calendar-day">13</div>
</td>
`);
});
it(`focuses date (ArrowDown)`, async () => {
const [
prop,
prop2,
focusedDateContent,
]: C = await getValuesAfterKeys(KEY_CODES_MAP.ARROW_DOWN);
strictEqual(prop, '2020-02-20');
strictEqual(prop2, '2020-02-27');
strictEqual(focusedDateContent, prettyHtml`
<td class="full-calendar__day day--focused" aria-disabled="false" aria-label="Feb 27, 2020" aria-selected="true">
<div class="calendar-day">27</div>
</td>
`);
});
it(`focuses date (PageUp)`, async () => {
const [
prop,
prop2,
focusedDateContent,
]: C = await getValuesAfterKeys(KEY_CODES_MAP.PAGE_UP);
strictEqual(prop, '2020-02-20');
strictEqual(prop2, '2020-01-20');
strictEqual(focusedDateContent, prettyHtml`
<td class="full-calendar__day day--focused" aria-disabled="false" aria-label="Jan 20, 2020" aria-selected="true">
<div class="calendar-day">20</div>
</td>
`);
});
it(`focuses date (PageDown)`, async () => {
const [
prop,
prop2,
focusedDateContent,
]: C = await getValuesAfterKeys(KEY_CODES_MAP.PAGE_DOWN);
strictEqual(prop, '2020-02-20');
strictEqual(prop2, '2020-03-20');
strictEqual(focusedDateContent, prettyHtml`
<td class="full-calendar__day day--focused" aria-disabled="false" aria-label="Mar 20, 2020" aria-selected="true">
<div class="calendar-day">20</div>
</td>
`);
});
it(`focuses date (Home)`, async () => {
const [
prop,
prop2,
focusedDateContent,
]: C = await getValuesAfterKeys(KEY_CODES_MAP.HOME);
strictEqual(prop, '2020-02-20');
strictEqual(prop2, '2020-02-01');
strictEqual(focusedDateContent, prettyHtml`
<td class="full-calendar__day day--focused" aria-disabled="false" aria-label="Feb 1, 2020" aria-selected="true">
<div class="calendar-day">1</div>
</td>
`);
});
it(`focuses date (End)`, async () => {
const [
prop,
prop2,
focusedDateContent,
]: C = await getValuesAfterKeys(KEY_CODES_MAP.END);
strictEqual(prop, '2020-02-20');
strictEqual(prop2, '2020-02-29');
strictEqual(focusedDateContent, prettyHtml`
<td class="full-calendar__day day--focused" aria-disabled="false" aria-label="Feb 29, 2020" aria-selected="true">
<div class="calendar-day">29</div>
</td>
`);
});
it(`focuses date (Alt + PageUp)`, async () => {
const [
prop,
prop2,
focusedDateContent,
]: C = await getValuesAfterKeys(KEY_CODES_MAP.PAGE_UP, true);
strictEqual(prop, '2020-02-20');
strictEqual(prop2, '2019-02-20');
strictEqual(focusedDateContent, prettyHtml`
<td class="full-calendar__day day--focused" aria-disabled="false" aria-label="Feb 20, 2019" aria-selected="true">
<div class="calendar-day">20</div>
</td>
`);
});
it(`focuses date (Alt + PageDown)`, async () => {
const [
prop,
prop2,
focusedDateContent,
]: C = await getValuesAfterKeys(KEY_CODES_MAP.PAGE_DOWN, true);
strictEqual(prop, '2020-02-20');
strictEqual(prop2, '2021-02-20');
strictEqual(focusedDateContent, prettyHtml`
<td class="full-calendar__day day--focused" aria-disabled="false" aria-label="Feb 20, 2021" aria-selected="true">
<div class="calendar-day">20</div>
</td>
`);
});
}); | the_stack |
import { TestBed } from '@angular/core/testing';
import { CalendarPeriodRelativityEnum } from './enums/calendar-period-relativity.enum';
// temporary fix for https://github.com/ng-packagr/ng-packagr/issues/217#issuecomment-360176759
import * as momentNs from 'moment';
const moment = momentNs;
import { CalendarManagerService } from './calendar-manager.service';
let previouslySelectedYear;
function getYearList(start: momentNs.Moment, margin: number = 19): number[] {
let yearIterator;
let endYear;
if (start) {
previouslySelectedYear = start.clone();
}
if (margin < 0) {
endYear = moment(previouslySelectedYear).add(margin, 'years');
yearIterator = moment(endYear).add(margin, 'years');
} else {
yearIterator = moment(previouslySelectedYear);
endYear = moment(yearIterator).add(margin, 'years');
}
const yearList = [];
while (yearIterator.isSameOrBefore(endYear)) {
yearList.push(yearIterator.clone().year());
yearIterator.add(1, 'year');
}
previouslySelectedYear = yearIterator.subtract(1, 'year').clone();
return yearList;
}
describe('CalendarManagerService', () => {
beforeEach(() => TestBed.configureTestingModule({
providers: [
CalendarManagerService
]
}));
it('should be created', () => {
const service: CalendarManagerService = TestBed.inject(CalendarManagerService);
expect(service).toBeTruthy();
});
it('should create a calendar month table correctly', () => {
const service: CalendarManagerService = TestBed.inject(CalendarManagerService);
const startDate = moment().startOf('month');
const isStartOfTable = startDate.weekday() === 0;
if (!isStartOfTable) {
let daysToGoBack = startDate.weekday();
daysToGoBack = (daysToGoBack === 0) ? 1 : daysToGoBack;
startDate.subtract(daysToGoBack, 'days');
}
// the calendar should be 6 rows x 7 days
const endDate = moment(startDate).add(41, 'days');
const calendar = service.generateCalendarForMonth(moment(), moment(), [], { minDate: null, maxDate: null });
const firstCalendarDay = calendar[0][0];
const lastCalendarDay = calendar[calendar.length - 1][calendar[calendar.length - 1].length - 1];
const firstDayIsCorrect = firstCalendarDay.momentObj.isSame(startDate, 'day');
const lastDayIsCorrect = lastCalendarDay.momentObj.isSame(endDate, 'day');
const everyRowHas7Days = calendar.every((row) => {
return row.length === 7;
});
expect(firstDayIsCorrect && lastDayIsCorrect && calendar.length === 6 && everyRowHas7Days)
.toBe(true, 'table should be 6 rows x 7 days and the starting day should be adjusted if needed');
});
it('should find a date from month calendar correctly', () => {
const service: CalendarManagerService = TestBed.inject(CalendarManagerService);
const dayToFind = moment();
const calendar = service.generateCalendarForMonth(moment(), moment(), [], { minDate: null, maxDate: null });
const searchResult = service.findADateFromCalendar(dayToFind, calendar);
expect((searchResult.momentObj).isSame(dayToFind, 'day'))
.toBe(true, 'the search date and the result date should be the same month and day');
});
it('should disable calendar dates that are outside the [min, max] range', () => {
const service: CalendarManagerService = TestBed.inject(CalendarManagerService);
const minDate = moment().startOf('month').add(3, 'days');
const maxDate = moment(minDate).add(7, 'days');
const calendar = service.generateCalendarForMonth(moment(), moment(), [], { minDate: minDate, maxDate: maxDate });
const dayBeforeMin = service.findADateFromCalendar(moment(minDate).subtract(1, 'day'), calendar);
const dayAfterMax = service.findADateFromCalendar(moment(maxDate).add(1, 'day'), calendar);
expect(dayBeforeMin.isDisabled && dayAfterMax.isDisabled)
.toBe(true, 'the date before minDate and the date after maxDate should be disabled');
});
it('should generate a list of years with a given margin correctly', () => {
const service: CalendarManagerService = TestBed.inject(CalendarManagerService);
const margin = 40;
const startDate = moment();
const endDate = moment(startDate).add(margin, 'years');
const yearsList = service.getYearList(startDate, margin);
expect(yearsList.length === margin + 1 &&
yearsList[0] === startDate.year() &&
yearsList[yearsList.length - 1] === endDate.year())
.toBe(true, `the start date and the end date should be ${margin} years apart`);
});
it('should generate a month calendar with preselected dates', () => {
const service: CalendarManagerService = TestBed.inject(CalendarManagerService);
const preselectedDates = [moment(), moment().add(1, 'day')];
const calendar = service.generateCalendarForMonth(moment(), moment(), preselectedDates, { minDate: null, maxDate: null });
const preselectedDate1 = service.findADateFromCalendar(preselectedDates[0], calendar);
const preselectedDate2 = service.findADateFromCalendar(preselectedDates[1], calendar);
expect(preselectedDate1.isSelected && preselectedDate2.isSelected)
.toBe(true, 'the preselected dates should be marked as selected in the calendar');
});
it('should generate a list of months correctly', () => {
const service: CalendarManagerService = TestBed.inject(CalendarManagerService);
const momentMonthsLong = moment.months();
const monthsListLong = service.getMonths(false);
const momentMonthsShort = moment.monthsShort();
const monthsListShort = service.getMonths();
const longMonthsCorrect = monthsListLong.every((month, index) => {
return month === momentMonthsLong[index];
});
const shortMonthsCorrect = momentMonthsShort.every((month, index) => {
return month === monthsListShort[index];
});
expect(longMonthsCorrect && shortMonthsCorrect)
.toBe(true, 'moment and service long and short months lists match');
});
it('should generate a list of weekdays correctly', () => {
const service: CalendarManagerService = TestBed.inject(CalendarManagerService);
const momentWeekdaysLong = moment.weekdays();
const weekdaysListLong = service.getWeekdays(false);
const momentWeekdaysShort = moment.weekdaysShort();
const weekdaysListShort = service.getWeekdays();
const longWeekdaysCorrect = weekdaysListLong.every((month, index) => {
return month === momentWeekdaysLong[index];
});
const shortWeekdaysCorrect = weekdaysListShort.every((month, index) => {
return month === momentWeekdaysShort[index];
});
expect(longWeekdaysCorrect && shortWeekdaysCorrect)
.toBe(true, 'moment and service long and short weekdays lists match');
});
it('should determine date relativity correctly', () => {
const service: CalendarManagerService = TestBed.inject(CalendarManagerService);
const beforeCurrentMonthDate = moment().subtract(1, 'month');
const afterCurrentMonthDate = moment().add(1, 'month');
const beforeDateIsCorrectlyMarked = service.determineDateRelativityToCurrentMonth(beforeCurrentMonthDate, moment());
const afterDateIsCorrectlyMarked = service.determineDateRelativityToCurrentMonth(afterCurrentMonthDate, moment());
const currentDateIsCorrectlyMarked = service.determineDateRelativityToCurrentMonth(moment(), moment());
expect(beforeDateIsCorrectlyMarked === CalendarPeriodRelativityEnum.Before &&
afterDateIsCorrectlyMarked === CalendarPeriodRelativityEnum.After &&
currentDateIsCorrectlyMarked === CalendarPeriodRelativityEnum.Current)
.toBe(true, 'the dates are correctly marked relatively to the current month');
});
it('should generate a month picker correctly', () => {
const service: CalendarManagerService = TestBed.inject(CalendarManagerService);
const momentMonthsShort = moment.monthsShort();
const dateRange = {
minDate: moment().add(1, 'month'),
maxDate: moment().add(2, 'months')
};
const expectedPickerItems = momentMonthsShort.map((monthName, index) => {
const date = moment().year(moment().year()).month(index);
return {
displayName: monthName,
momentObj: date,
isDisabled: service.determineIfDateIsDisabled(date, dateRange.minDate, dateRange.maxDate)
};
});
const actualPickerItems = service.generateMonthPickerCollection(moment().year(), dateRange);
const arePickerItemsCorrect = actualPickerItems.every((pickerItem, index) => {
const isDisplayNameOK = pickerItem.displayName === expectedPickerItems[index].displayName;
const isMomentObjOK = pickerItem.momentObj.isSame(expectedPickerItems[index].momentObj, 'day');
const isDisabledOK = pickerItem.isDisabled === expectedPickerItems[index].isDisabled;
return isDisplayNameOK && isMomentObjOK && isDisabledOK;
});
expect(arePickerItemsCorrect)
.toBe(true, 'month picker items are correctly generated');
});
it('should generate a year picker correctly', () => {
const service: CalendarManagerService = TestBed.inject(CalendarManagerService);
const margin = 20;
const testYearsList = getYearList(moment(), margin);
const dateRange = {
minDate: moment().add(1, 'year'),
maxDate: moment().add(2, 'years')
};
const expectedPickerItems = testYearsList.map((year) => {
const date = moment().year(year);
return {
displayName: year.toString(),
momentObj: date,
isDisabled: service.determineIfDateIsDisabled(date, dateRange.minDate, dateRange.maxDate)
};
});
const actualPickerItems = service.generateYearPickerCollection(moment(), margin, dateRange);
const arePickerItemsCorrect = actualPickerItems.every((pickerItem, index) => {
const isDisplayNameOK = pickerItem.displayName === expectedPickerItems[index].displayName;
const isMomentObjOK = pickerItem.momentObj.isSame(expectedPickerItems[index].momentObj, 'day');
const isDisabledOK = pickerItem.isDisabled === expectedPickerItems[index].isDisabled;
return isDisplayNameOK && isMomentObjOK && isDisabledOK;
});
expect(arePickerItemsCorrect)
.toBe(true, 'year picker items are correctly generated');
});
it('should find the index of a selected date correctly', () => {
const service: CalendarManagerService = TestBed.inject(CalendarManagerService);
const preselectedDates = [moment().add(1, 'day'), moment(), moment().add(1, 'month'), moment().add(1, 'year')];
const dateToFind = moment().add(1, 'month');
const expectedIndex = preselectedDates.findIndex((selectedDate) => {
return moment(selectedDate).isSame(dateToFind, 'day');
});
const actualIndex = service.getSelectedItemIndex(dateToFind, preselectedDates);
expect(expectedIndex === actualIndex)
.toBe(true, 'the returned date index is correct');
});
}); | the_stack |
import * as PIXI from 'pixi.js'
import FD from '../core/factorioData'
import G from '../common/globals'
import util from '../common/util'
import { Entity } from '../core/Entity'
import F from './controls/functions'
import { Panel } from './controls/Panel'
import { styles } from './style'
function template(strings: TemplateStringsArray, ...keys: (number | string)[]) {
return (...values: (unknown | Record<string, unknown>)[]) => {
const result = [strings[0].replace('\n', '')]
keys.forEach((key, i) => {
result.push(
typeof key === 'number'
? (values as string[])[key]
: (values[0] as Record<string, string>)[key],
strings[i + 1]
)
})
return result.join('')
}
}
const entityInfoTemplate = template`
Crafting speed: ${'craftingSpeed'} ${'speedMultiplier'}
Power consumption: ${'energyUsage'} kW ${'energyMultiplier'}`
const SIZE_OF_ITEM_ON_BELT = 0.25
const getBeltSpeed = (beltSpeed: number): number => beltSpeed * 60 * (1 / SIZE_OF_ITEM_ON_BELT) * 2
const containerToContainer = (rotationSpeed: number, n: number): number => rotationSpeed * 60 * n
/**
nr of items to ignore the time it takes to place them on a belt
because: first item is being placed instantly and also in front so
this also reduces the time it takes to put down the second item by about 75%
*/
const NR_OF_ITEMS_TO_IGNORE = 1.75
const containerToBelt = (rotationSpeed: number, beltSpeed: number, n: number): number => {
const armTime = 1 / (rotationSpeed * 60)
const itemTime = (1 / (beltSpeed * 60)) * SIZE_OF_ITEM_ON_BELT
return n / (armTime + itemTime * Math.max(n - NR_OF_ITEMS_TO_IGNORE, 0))
}
// TODO: add beltToContainer
const roundToTwo = (n: number): number => Math.round(n * 100) / 100
const roundToFour = (n: number): number => Math.round(n * 10000) / 10000
/**
* This class creates a panel to show detailed informations about each entity (as the original game and maybe more).
* @function updateVisualization (Update informations and show/hide panel)
* @function setPosition (top right corner of the screen)
* @extends /controls/panel (extends PIXI.Container)
* @see instantiation in /index.ts - event in /containers/entity.ts
*/
export class EntityInfoPanel extends Panel {
private title: PIXI.Text
private m_EntityName: PIXI.Text
private m_entityInfo: PIXI.Text
private m_RecipeContainer: PIXI.Container
private m_RecipeIOContainer: PIXI.Container
public constructor() {
super(270, 270)
this.interactive = false
this.visible = false
this.title = new PIXI.Text('Information', styles.dialog.title)
this.title.anchor.set(0.5, 0)
this.title.position.set(super.width / 2, 2)
this.addChild(this.title)
this.m_EntityName = new PIXI.Text('', styles.dialog.label)
this.m_entityInfo = new PIXI.Text('', styles.dialog.label)
this.m_RecipeContainer = new PIXI.Container()
this.m_RecipeIOContainer = new PIXI.Container()
this.addChild(
this.m_EntityName,
this.m_entityInfo,
this.m_RecipeContainer,
this.m_RecipeIOContainer
)
}
public updateVisualization(entity?: Entity): void {
this.m_RecipeContainer.removeChildren()
this.m_RecipeIOContainer.removeChildren()
if (!entity) {
this.visible = false
this.m_EntityName.text = ''
this.m_entityInfo.text = ''
return
}
this.visible = true
let nextY = this.title.position.y + this.title.height + 10
this.m_EntityName.text = `Name: ${FD.entities[entity.name].localised_name}`
this.m_EntityName.position.set(10, nextY)
nextY = this.m_EntityName.position.y + this.m_EntityName.height + 10
if (entity.entityData.type === 'assembling_machine') {
// Details for assembling machines with or without recipe
let productivity = 0
let consumption = 0
// let pollution = 0
let speed = 0
if (entity.modules.length > 0) {
for (const module of entity.modules) {
const moduleData = FD.items[module]
if (moduleData.effect.productivity) {
productivity += moduleData.effect.productivity.bonus
}
if (moduleData.effect.consumption) {
consumption += moduleData.effect.consumption.bonus
}
// if (moduleData.effect.pollution) {
// pollution += moduleData.effect.pollution.bonus
// }
if (moduleData.effect.speed) {
speed += moduleData.effect.speed.bonus
}
}
}
for (const beacon of this.findNearbyBeacons(entity)) {
for (const module of beacon.modules) {
if (FD.items[module].effect.productivity) {
productivity +=
FD.items[module].effect.productivity.bonus *
beacon.entityData.distribution_effectivity
}
if (FD.items[module].effect.consumption) {
consumption +=
FD.items[module].effect.consumption.bonus *
beacon.entityData.distribution_effectivity
}
// if (FD.items[module].effect.pollution) {
// pollution += FD.items[module].effect.pollution.bonus * beacon.entityData.distribution_effectivity
// }
if (FD.items[module].effect.speed) {
speed +=
FD.items[module].effect.speed.bonus *
beacon.entityData.distribution_effectivity
}
}
}
consumption = consumption < -0.8 ? -0.8 : consumption
const newCraftingSpeed = entity.entityData.crafting_speed * (1 + speed)
const newEnergyUsage =
parseInt(entity.entityData.energy_usage.slice(0, -2)) * (1 + consumption)
const fmt = (n: number): string =>
`(${Math.sign(n) === 1 ? '+' : '-'}${roundToTwo(Math.abs(n) * 100)}%)`
// Show modules effect and some others informations
this.m_entityInfo.text = entityInfoTemplate({
craftingSpeed: roundToFour(newCraftingSpeed),
speedMultiplier: speed ? fmt(speed) : '',
energyUsage: roundToTwo(newEnergyUsage),
energyMultiplier: consumption ? fmt(consumption) : '',
})
this.m_entityInfo.position.set(10, nextY)
nextY = this.m_entityInfo.position.y + this.m_entityInfo.height + 10
if (!entity.recipe) return
// Details for assembling machines with recipe
this.m_RecipeContainer.removeChildren()
const recipe = FD.recipes[entity.recipe]
if (recipe === undefined) return
// Show the original recipe
this.m_RecipeContainer.addChild(new PIXI.Text('Recipe:', styles.dialog.label))
F.CreateRecipe(
this.m_RecipeContainer,
0,
20,
recipe.ingredients,
recipe.results,
recipe.time
)
this.m_RecipeContainer.position.set(10, nextY)
nextY = this.m_RecipeContainer.position.y + this.m_RecipeContainer.height + 20
// Show recipe that takes entity effects into account
this.m_RecipeIOContainer.addChild(
new PIXI.Text('Recipe (takes entity effects into account):', styles.dialog.label)
)
F.CreateRecipe(
this.m_RecipeIOContainer,
0,
20,
recipe.ingredients.map(i => ({
name: i.name,
amount: roundToTwo((i.amount * newCraftingSpeed) / recipe.time),
})),
recipe.results.map(r => ({
name: r.name,
amount: roundToTwo(
((r.amount * newCraftingSpeed) / recipe.time) * (1 + productivity)
),
})),
1
)
this.m_RecipeIOContainer.position.set(10, nextY)
nextY = this.m_RecipeIOContainer.position.y + this.m_RecipeIOContainer.height + 20
}
const isBelt = (e: Entity): boolean =>
e.entityData.type === 'transport_belt' ||
e.entityData.type === 'underground_belt' ||
e.entityData.type === 'splitter' ||
e.entityData.type === 'loader'
if (entity.entityData.type === 'inserter') {
// Details for inserters
let speed = containerToContainer(
entity.entityData.rotation_speed,
entity.inserterStackSize
)
const tiles = entity.name === 'long_handed_inserter' ? 2 : 1
// const fromP = util.rotatePointBasedOnDir([0, -tiles], entity.direction)
const toP = util.rotatePointBasedOnDir([0, tiles], entity.direction)
// const from = G.bp.entities.get(
// G.bp.entityPositionGrid.getCellAtPosition({
// x: entity.position.x + fromP.x,
// y: entity.position.y + fromP.y
// })
// )
const to = G.bp.entityPositionGrid.getEntityAtPosition(
entity.position.x + toP.x,
entity.position.y + toP.y
)
if (to && isBelt(to)) {
speed = containerToBelt(
entity.entityData.rotation_speed,
to.entityData.speed,
entity.inserterStackSize
)
}
this.m_entityInfo.text = `Speed: ${roundToTwo(
speed
)} items/s\n> changes if inserter unloads to a belt`
this.m_entityInfo.position.set(10, nextY)
nextY = this.m_entityInfo.position.y + this.m_entityInfo.height + 20
}
if (isBelt(entity)) {
// Details for belts
this.m_entityInfo.text = `Speed: ${roundToTwo(
getBeltSpeed(entity.entityData.speed)
)} items/s`
this.m_entityInfo.position.set(10, nextY)
nextY = this.m_entityInfo.position.y + this.m_entityInfo.height + 20
}
}
protected setPosition(): void {
this.position.set(G.app.screen.width - this.width + 1, 0)
}
private findNearbyBeacons(entity: Entity): Entity[] {
const entityRect = new PIXI.Rectangle(entity.position.x, entity.position.y)
entityRect.pad(entity.size.x / 2, entity.size.y / 2)
return entity.Blueprint.entities.filter((beacon: Entity): boolean => {
if (beacon.type !== 'beacon') {
return false
}
const beaconAura = new PIXI.Rectangle(beacon.position.x, beacon.position.y, 1, 1)
beaconAura.pad(FD.entities.beacon.supply_area_distance)
return (
beaconAura.contains(entityRect.left, entityRect.top) ||
beaconAura.contains(entityRect.right, entityRect.top) ||
beaconAura.contains(entityRect.left, entityRect.bottom) ||
beaconAura.contains(entityRect.right, entityRect.bottom)
)
})
}
} | the_stack |
import { Dict } from "lang"
const dict: Dict = {
module: {
ohmymn: {
link: "https://www.notion.so/huangkewei/Gesture-2d43552645f3433da3c9beece0990f73",
option: {
profile: "Profile",
has_title_then: ["As Comments", "As Title Link", "Override"],
panel_position: ["Auto", "Left", "Center", "Right"],
panel_height: ["Higher", "Standard", "Lower"],
panle_control: [
"Double Click Logo Open Panel",
"Double Click Panel to Close",
"Close Panel after Action"
],
detect_update: [
"Never",
"Everyday",
"Every Monday",
"Everyday for Signed Vers.",
"Every Monday for Signed Vers."
]
},
label: {
has_title_then: "Excerpt While Title Exist",
quick_switch: "Quick Switch",
profile: "Choose Profile",
detect_update: "Auto Detect Update",
panel_position: "Panel Position",
panel_height: "Panel Height",
panle_control: "Panel ON and OFF",
screen_always_on: "Keep Screen Always On",
lock_excerpt: "Lock Excerpt Text",
auto_correct: "Is Auto-Correct Enabled?"
},
help: {
profile:
"[Current Document Takes Effect]\nCan be used in different scenarios",
has_title_then: "If can be turned into a title, then",
auto_correct:
"[Current Document Takes Effect]\nAfter opening, it will be processed after auto-correction"
},
detect_update: {
tip: (time: string, version: string, signed: boolean) =>
`${time} update,version: ${version}\n whether signed: ${
signed ? "Yes" : "No"
}`,
check_update: "Check for updates"
}
},
gesture: {
intro: "Custom Gestures to Trigger Actions",
link: "https://www.notion.so/huangkewei/Gesture-2d43552645f3433da3c9beece0990f73",
singleBar: "Single-select Toolbar",
muiltBar: "Multi-select Toolbar"
},
anotherautodef: {
intro:
"Extract the defined terms and any other content as title or title link\nDefinition = Defined Term + Connective of Definition + Definiens\n", //Question:有待商议
link: "https://huangkewei.notion.site/AnotherAutoDef-1852d4876891455681a90864ea35c828", //Todo:修改英文版Notion
label: {
only_desc: "Only Keep Definiens",
to_title_link: "Convert Alias To Title Link",
custom_split: "Customize alias participle, click for specific format",
preset: "Select Presets",
custom_def_link:
"Customize connective of definition, click for the specific format",
custom_extract_title:
"Customize extract content, click for specific format",
extract_title: "Extract Title From Card"
},
option: {
preset: [
"Custom Extraction",
"Custom Connective of Definition",
"xxx : yyy",
"xxx —— yyy",
"xxx ,是(指) yyy",
"xxx 是(指),yyy",
"xxx 是指 yyy",
"yyy,___称(之)为 xxx",
"yyy(被)称(之)为 xxx"
],
extract_title: ["Use AutoDef Configuration", "Confirm"]
}
},
magicaction: {
intro:
"Please note that the following functions are used after selecting the card.\nClick for specific usage and precautions",
link: "https://www.notion.so/huangkewei/MagicAction-79afa352bad141f58075841614ded734", //Todo:修改英文版Notion
option: {
filter_cards: ["Filter Only Title", "Filter Entire Card"],
merge_text: ["Merged as Excerpt", "Merged as Comment"],
merge_cards: ["Merge Title Simultaneously", "Do not Merge Titles"],
manage_profile: ["Read Configuration", "Write Configuration"]
},
help: {
filter_cards:
"Please see the help document for more precautions and specific input format",
merge_text:
"input delimiter. Please read the reference guide at the top for precautions and specific input formats.",
rename_title:
"Reference guide for precuations and specific input formats is at the top.",
manage_profile:
"It is forbidden to directly modify the configuration information, and the existing configuration will be overwritten after reading"
},
label: {
filter_cards: "Filter Cards",
merge_cards: "Merge Multiple Cards",
merge_text: "Merge Text in Cards",
rename_title: "Rename Titles",
manage_profile: "Configuration Management"
},
hud: {
is_clicked: "The card is selected, please continue",
none_card: "No matching cards found"
}
},
autostandardize: {
intro: "Optimize the typography and formatting of excerpts & titles",
link: "https://www.notion.so/huangkewei/AutoStandrize-ec4986eff67744d4b2a045a283267b99",
option: {
preset: [
"Customization",
"Delete All Spaces",
"Half Width To Double Width",
"Add Space Between Chinese&English", // Todo: 是否需要修改
"Remove Multiple Spaces"
],
standardize_selected: [
"Optimize All",
"Only Optimize Title",
"Only Optimize Excerption"
]
},
help: {
standardize_title: "Click for specific specifications"
},
label: {
standardize_selected: "Optimize Typography",
standardize_title: " Normalize English Title",
custom_standardize: "Customize. Click for specific formats",
preset: "Select Presets"
}
},
autoreplace: {
intro: "Automatically replace errors in excerpts",
link: "https://www.notion.so/huangkewei/AutoReplace-1cf1399ed90e4fc7a3e16843d37f2a56", //Todo:修改英文版Notion
option: {
preset: ["Customization"],
replace_selected: ["Use AutoReplace Configuration", "Confirm"]
},
help: {
replace_selected:
"For the specific input format, see the reference guide at the top"
},
label: {
preset: "Select Presets",
replace_selected: "Replace Excerptions",
custom_replace: "Customize. Click for specific formats"
}
},
autolist: {
intro:
"For sequence text, automatic line wrapping, preset only for Chinese", //Todo: 需要修改
link: "https://www.notion.so/huangkewei/AutoList-e56366855c4a4a6e9c80364d7cca0882", //Todo:修改英文版Notion
option: {
preset: [
"Customization",
"Multiple Choice",
"Number at the beginning of the sentence",
"Semicolon at the end of the sentence",
"Period at the end of the Sentence"
], //Todo:需要修改
list_selected: ["Use AutoList Configuration", "Confirm"]
},
help: {
list_selected:
"For the specific input format, see the reference guide at the top"
},
label: {
preset: "Select Presets",
custom_list: "Customize. Click for specific formats",
list_selected: "Sequence Excerption Wrapping"
}
},
autocomplete: {
intro: "Complete word form. Only support verbs and nouns",
link: "https://www.notion.so/huangkewei/AutoComplete-3b9b27baef8f414cb86c454a6128b608", //Todo:修改英文版Notion
label: {
custom_complete:
"Custom excerption filling template, click for support variables",
complete_selected: "Complete Word Form"
},
option: {
complete_selected: [
"Only complete word form",
"Fill the word information as well"
]
},
error: {
not_find_word: "No matching words found",
forbid:
"To reduce server pressure, it is forbidden to process more than 5 cards at the same time"
}
},
anotherautotitle: {
intro: "More powerful Autotitle",
link: "https://www.notion.so/huangkewei/AnotherAutoTitle-bdd09b713c844a82aeea1c0d3bd4cb48", //Todo:修改英文版Notion
option: {
preset: ["Customization", "Word Count Limit", "Do not Contain Dots"],
switch_title: ["Switch to Another", "Swap Titles and Excerpts"]
},
label: {
change_title_no_limit: "Title Always Be Title",
preset: "Select Presets",
custom_be_title: "Customize. Click for specific formats",
switch_title: "Switch Excerption or Title",
word_count:
"[number of Chinese words, number of English words ], if not exceeded, then set the excerpt text as the title"
},
help: {
switch_title: "Use [Swap Title and Excerpt] when both are present」",
change_title_no_limit:
"Broaden the title excerpt selection, always turn to the title"
}
},
autotag: {
intro: "Auto Add Tags",
link: "https://www.notion.so/huangkewei/AutoTag-9e0bb2106d984ded8c29e781b53a1c23",
option: {
preset: ["Customization"],
tag_selected: ["Use AutoTag Configuration", "Confirm"]
},
label: {
preset: "Select Presets",
custom_tag: "Customize. Click for specific formats",
tag_selected: "Tag Cards"
}
},
autostyle: {
link: "https://www.notion.so/huangkewei/AutoStyle-16971d7c0fb048bd828d97373a035bc2",
intro: "Auto modify excerpt colors and styles",
area: "Aera",
label: {
preset: "Select Presets",
change_style: "Modify Excerpt Style",
change_color: "Modify Excerpt Color",
show_area: "Show Excerpt Area",
default_text_excerpt_color: "Default Text Excerpt Color",
default_pic_excerpt_color: "Default Pic Excerpt Color",
default_text_excerpt_style: "Default Text Excerpt Style",
default_pic_excerpt_style: "Default Pic Excerpt Style",
word_count_area:
"[number of Chinese words, number of English words, area], if it exceeds, set the excerpt style to wireframe, otherwise the default.\n"
},
help: {
change_color: "Enter the color index, 1 to 16"
},
option: {
change_style: [
"Use AutoStyle Configuration",
"Wireframe+Fill",
"Fill",
"Wireframe"
],
change_color: ["Use AutoStyle Configuration", "Confirm"],
preset: [
"Style is determined by word count or area",
"color follow card",
"Color follows frist child node",
"Color follows parent node"
],
style: ["None", "Wireframe+Fill", "Fill", "Wireframe"],
color: [
"None",
"Light Yellow",
"Light Green",
"Light Blue",
"light red",
"Yellow",
"Green",
"Blue",
"Red",
"Orange",
"Dark Green",
"Dark Blue",
"Dark Red",
"White",
"Light Grey",
"Dark Grey",
"Purple"
]
}
},
more: {
donate:
"If you want to help me out, please click and go directly to the QR code.",
github:
"ohmymn is completely open source, easy to extend, welcome to participate in development. Click to go directly to Github and view the source code.",
feishu:
"Click to join the Feishu Group to exchange ohmymn usage skills. I will solve your questions from time to time."
}
},
handle_received_event: {
input_saved: "Input Saved",
input_clear: "Input Clear",
auto_correct:
"Please select the switch according to the actual situation. It is not recommended to turn on automatic correction without brain.",
lock_excerpt:
"Locking excerpts is not recommended and auto-correction is turned on at the same time"
},
magic_action_handler: {
not_selected: "None card is selected",
smart_select: {
option: [
"Process only selected cards",
"Process all child nodes",
"Process child nodes and seected cards"
],
card_with_children: "Detect only one selected card has child nodes",
cards_with_children:
"Detect all selected cards of the same level have child nodes"
}
},
switch_panel: {
better_with_mindmap: "OhMyMN is more compatible with mindmap"
},
handle_user_action: {
sure: "Confirm",
input_error: "Input errors, please re-enter",
gesture: {
alert:
"When it is turned on, OhMyMN will monitor swipes on the mindmap nodes single and multiple selection toolbars and triggers the actions you set.\nThis feature is provided by OhMyMN and is not related to MarginNote. Have you read the doc and are aware of the specific gesture monitoring areas and the risks associated with their use?",
option: ["Not sure, check the doc", "Sure, I know"],
doc: "https://www.notion.so/huangkewei/Gesture-2d43552645f3433da3c9beece0990f73"
}
},
implement_datasource_method: {
none: "None",
open_panel: "Open the control panel"
},
addon_life_cycle: {
remove: "OhMyMN deactivated, configuration reset"
},
profile_manage: {
success: "Configuration read successfully",
fail: "Configuration read fail",
not_find: "Configuration information not found",
prohibit: "[OhMyMN] configuration (no direct modification is allowed)"
},
other: {
cancel: "Cancel"
}
}
export default dict | the_stack |
import * as React from 'react';
import { Label } from 'office-ui-fabric-react/lib/Label';
import { IChoiceGroupOption } from 'office-ui-fabric-react/lib/ChoiceGroup';
import { Spinner, SpinnerSize, SpinnerType } from 'office-ui-fabric-react/lib/Spinner';
import { Async } from 'office-ui-fabric-react/lib/Utilities';
import { Checkbox } from 'office-ui-fabric-react/lib/Checkbox';
import { IPropertyFieldColumnMultiPickerHostProps, IPropertyFieldColumnMultiPickerHostState } from './IPropertyFieldColumnMultiPickerHost';
import { ISPColumns, ISPColumn } from '.';
import { SPColumnPickerService } from '../../services/SPColumnPickerService';
import FieldErrorMessage from '../errorMessage/FieldErrorMessage';
import * as telemetry from '../../common/telemetry';
import { setPropertyValue } from '../../helpers/GeneralHelper';
/**
* Renders the controls for PropertyFieldSPColumnMultiplePicker component
*/
export default class PropertyFieldColumnMultiPickerHost extends React.Component<IPropertyFieldColumnMultiPickerHostProps, IPropertyFieldColumnMultiPickerHostState> {
private loaded: boolean = false;
private async: Async;
private delayedValidate: (value: string[]) => void;
/**
* Constructor
*/
constructor(props: IPropertyFieldColumnMultiPickerHostProps) {
super(props);
telemetry.track('PropertyFieldColumnMultiPicker', {
disabled: props.disabled
});
this.onChanged = this.onChanged.bind(this);
this.onSelectAllChanged = this.onSelectAllChanged.bind(this);
this.state = {
loadedColumns: {
value: []
},
results: [],
selectedKeys: [],
loaded: this.loaded,
errorMessage: ''
};
this.async = new Async(this);
this.validate = this.validate.bind(this);
this.notifyAfterValidate = this.notifyAfterValidate.bind(this);
this.delayedValidate = this.async.debounce(this.validate, this.props.deferredValidationTime);
}
public componentDidMount() {
this.loadColumns();
}
public componentDidUpdate(prevProps: IPropertyFieldColumnMultiPickerHostProps, prevState: IPropertyFieldColumnMultiPickerHostState): void {
if (this.props.listId !== prevProps.listId ||
this.props.webAbsoluteUrl !== prevProps.webAbsoluteUrl) {
this.loadColumns();
}
}
private loadColumns(): void {
const { context, selectedColumns, columnReturnProperty, displayHiddenColumns } = this.props;
const columnService: SPColumnPickerService = new SPColumnPickerService(this.props, this.props.context);
const columnsToExclude: string[] = this.props.columnsToExclude || [];
const options: IChoiceGroupOption[] = [];
const selectedKeys: string[] = [];
let selectedColumnsKeys: string[] = [];
if (selectedColumns && selectedColumns.length) {
const firstItem = selectedColumns[0];
if (typeof firstItem === 'string') {
selectedColumnsKeys = selectedColumns as string[];
}
else {
selectedColumnsKeys = (selectedColumns as string[]).map((o: any) => (columnReturnProperty ? o[columnReturnProperty] : o.Id));
}
}
columnService.getColumns(displayHiddenColumns).then((response: ISPColumns) => {
// Start mapping the Columns that are selected
response.value.forEach((column: ISPColumn) => {
let isSelected: boolean = false;
let indexInExisting: number = -1;
let colPropsToCheck = columnReturnProperty ? column[columnReturnProperty] : column.Id;
// Defines if the current list must be selected by default
if (selectedColumnsKeys) {
indexInExisting = selectedColumnsKeys.indexOf(colPropsToCheck);
}
if (indexInExisting > -1) {
isSelected = true;
selectedKeys.push(colPropsToCheck);
}
// Make sure that the current column is NOT in the 'columnsToExclude' array
if (columnsToExclude.indexOf(column.Title) === -1 && columnsToExclude.indexOf(column.Id) === -1) {
options.push({
key: colPropsToCheck,
text: column.Title,
checked: isSelected
});
}
});
this.loaded = true;
this.setState({
loadedColumns: response,
results: options,
selectedKeys: selectedKeys,
loaded: true
});
});
}
/**
* Raises when a column has been selected
*/
private onChanged(element: React.FormEvent<HTMLElement>, isChecked: boolean): void {
if (element) {
const value: string = (element.currentTarget as any).value;
let selectedKeys = this.state.selectedKeys;
// Check if the element is selected
if (isChecked === false) {
// Remove the unselected item
selectedKeys = selectedKeys.filter(s => s !== value);
} else {
// Add the selected item and filter out the doubles
selectedKeys.push(value);
selectedKeys = selectedKeys.filter((item, pos, self) => {
return self.indexOf(item) === pos;
});
}
// Update the state and validate
this.setState({
selectedKeys: selectedKeys
});
this.delayedValidate(selectedKeys);
}
}
/**
* Raises when the select all checkbox is changed
*/
private onSelectAllChanged(element: React.FormEvent<HTMLElement>, isChecked: boolean): void {
if (element) {
let selectedKeys = new Array<string>();
const {
results
} = this.state;
if (isChecked === true) {
results.forEach((value: IChoiceGroupOption) => {
selectedKeys.push(value.key);
});
}
this.setState({
selectedKeys: selectedKeys
});
this.delayedValidate(selectedKeys);
}
}
/**
* Validates the new custom field value
*/
private validate(value: string[]): void {
if (this.props.onGetErrorMessage === null || typeof this.props.onGetErrorMessage === 'undefined') {
this.notifyAfterValidate(value);
return;
}
const errResult: string | PromiseLike<string> = this.props.onGetErrorMessage(value || []);
if (typeof errResult !== 'undefined') {
if (typeof errResult === 'string') {
if (errResult === '') {
this.notifyAfterValidate(value);
}
this.setState({
errorMessage: errResult
});
} else {
errResult.then((errorMessage: string) => {
if (typeof errorMessage === 'undefined' || errorMessage === '') {
this.notifyAfterValidate(value);
}
this.setState({
errorMessage: errorMessage
});
});
}
} else {
this.notifyAfterValidate(value);
}
}
/**
* Notifies the parent Web Part of a property value change
*/
private notifyAfterValidate(newValue: string[]) {
const {
onPropertyChange,
onChange,
selectedColumn,
targetProperty,
properties
} = this.props;
const {
loadedColumns
} = this.state;
let propValue: string[] | ISPColumn | undefined;
if (!newValue || !newValue.length) {
propValue = [];
}
else {
propValue = [...newValue];
}
if (onPropertyChange && newValue !== null) {
setPropertyValue(properties, targetProperty, propValue);
onPropertyChange(targetProperty, selectedColumn, propValue);
// Trigger the apply button
if (typeof onChange !== 'undefined' && onChange !== null) {
onChange(targetProperty, propValue);
}
}
}
/**
* Called when the component will unmount
*/
public componentWillUnmount() {
this.async.dispose();
}
/**
* Renders the SPColumnMultiplePicker controls with Office UI Fabric
*/
public render(): JSX.Element {
const {
selectedKeys,
results,
errorMessage
} = this.state;
const {
label,
disabled,
targetProperty
} = this.props;
if (this.loaded === false) {
return (
<div>
<Label>{label}</Label>
<Spinner size={SpinnerSize.medium} />
</div>
);
} else {
const styleOfLabel: any = {
color: disabled === true ? '#A6A6A6' : 'auto'
};
// Renders content
return (
<div>
{this.props.label && <Label>{this.props.label}</Label>}
{results && results.length > 0 ? (
<>
{
results.map((item: IChoiceGroupOption, index: number) => {
const uniqueKey = targetProperty + '-' + item.key;
return (
<div style={{ marginBottom: '5px' }} className='ms-ChoiceField' key={uniqueKey}>
<Checkbox
checked={selectedKeys.indexOf(item.key.toString()) >= 0}
disabled={disabled}
label={item.text}
onChange={this.onChanged}
inputProps={{ value: item.key }}
/>
</div>
);
})
}
</>
) : (
<FieldErrorMessage errorMessage={"List ID not provided!"} />
)
}
<FieldErrorMessage errorMessage={errorMessage} />
</div>
);
}
}
} | the_stack |
import {
XInputBoolean,
XBoolean,
XDataConvert,
XData,
XInputNumber,
XNumber,
XSort,
XQuery,
XWithConfig,
XFilter,
XSize
} from '@ng-nest/ui/core';
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { XTableColumn, XTableRow } from '@ng-nest/ui/table';
import { XTreeNode } from '@ng-nest/ui/tree';
import { XControlValueAccessor, XFormOption } from '@ng-nest/ui/base-form';
/**
* Find
* @selector x-find
* @decorator component
*/
export const XFindPrefix = 'x-find';
const X_CONFIG_NAME = 'find';
export interface XFindSearchOption extends XFilter {
label?: string;
button?: string;
}
/**
* Find Property
*/
@Component({ template: '' })
export class XFindProperty extends XControlValueAccessor<any | any[]> implements XFindOption {
/**
* @zh_CN 尺寸
* @en_US Size
*/
@Input() @XWithConfig<XSize>(X_CONFIG_NAME, 'medium') override size!: XSize;
/**
* @zh_CN 显示边框
* @en_US Display Border
*/
@Input() @XInputBoolean() @XWithConfig<XBoolean>(X_CONFIG_NAME, true) bordered!: XBoolean;
/**
* @zh_CN 多选
* @en_US Multiple choice
*/
@Input() @XInputBoolean() multiple: XBoolean = false;
/**
* @zh_CN 选中 label 名称字段
* @en_US Check the label name field
*/
@Input() @XWithConfig<string>(X_CONFIG_NAME, 'label') columnLabel!: string;
/**
* @zh_CN 弹框标题
* @en_US Bullet title
*/
@Input() @XWithConfig<string>(X_CONFIG_NAME, '查找选择') dialogTitle!: string;
/**
* @zh_CN 弹框宽度
* @en_US Bullet frame width
*/
@Input() dialogWidth?: string;
/**
* @zh_CN 弹框高度
* @en_US Height of bullet frame
*/
@Input() dialogHeight?: string;
/**
* @zh_CN 弹框显示,隐藏
* @en_US Bullet box display, hide
*/
@Input() @XInputBoolean() dialogVisible: boolean = false;
/**
* @zh_CN 弹框显示,隐藏
* @en_US Bullet box display, hide
*/
@Output() dialogVisibleChange = new EventEmitter<boolean>();
/**
* @zh_CN 按钮居中
* @en_US Button centered
*/
@Input() @XWithConfig<XBoolean>(X_CONFIG_NAME) @XInputBoolean() dialogButtonsCenter?: XBoolean;
/**
* @zh_CN 表格行数据
* @en_US Table row data
*/
@Input() tableData: XData<XTableRow> = [];
/**
* @zh_CN 表格页码
* @en_US Table page number
*/
@Input() @XWithConfig<number>(X_CONFIG_NAME, 1) tableIndex!: number;
/**
* @zh_CN 表每页数据条数
* @en_US Number of data items per page
*/
@Input() @XWithConfig<number>(X_CONFIG_NAME, 10) tableSize!: number;
/**
* @zh_CN 表每页数据条数
* @en_US Number of data items per page
*/
@Input() tableQuery: XQuery = {};
/**
* @zh_CN 表格数据总条数
* @en_US Total number of table data
*/
@Input() tableTotal: number = 0;
/**
* @zh_CN 页码变化的事件
* @en_US Page number change event
*/
@Output() tableIndexChange = new EventEmitter<number>();
/**
* @zh_CN 每页显示条数变化的事件
* @en_US Show the number of events on each page
*/
@Output() tableSizeChange = new EventEmitter<number>();
/**
* @zh_CN 排序点击的事件
* @en_US Sort click events
*/
@Output() tableSortChange = new EventEmitter<XSort[]>();
/**
* @zh_CN 表格列参数
* @en_US Table column parameters
*/
@Input() tableColumns: XTableColumn[] = [];
/**
* @zh_CN 当前选中行数据
* @en_US Currently selected row data
*/
@Input() tableActivatedRow?: any;
/**
* @zh_CN 表格行点击事件
* @en_US Table row click event
*/
@Output() tableRowEmit = new EventEmitter<any>();
/**
* @zh_CN 表格行点击事件
* @en_US Table row click event
*/
@Input() tableCheckedRow: { [property: string]: any[] } = {};
/**
* @zh_CN 是否启用加载 loading
* @en_US Whether to enable loading loading
*/
@Input() @XWithConfig<XBoolean>(X_CONFIG_NAME, false) @XInputBoolean() tableLoading!: XBoolean;
/**
* @zh_CN 表格开启虚拟滚动
* @en_US Table opens virtual scrolling
*/
@Input() @XWithConfig<boolean>(X_CONFIG_NAME, false) @XInputBoolean() tableVirtualScroll!: boolean;
/**
* @zh_CN 表格 body 数据高度
* @en_US Table body data height
*/
@Input() @XInputNumber() tableBodyHeight?: number;
/**
* @zh_CN 表格超出可视窗口缓冲区的最小值,对应 cdk scroll 中的参数
* @en_US The table exceeds the minimum value of the visible window buffer, corresponding to the parameters in cdk scroll
*/
@Input() tableMinBufferPx: number = 100;
/**
* @zh_CN 表格渲染新数据缓冲区的像素,对应 cdk scroll 中的参数
* @en_US The pixels of the new data buffer for the table rendering, corresponding to the parameters in cdk scroll
*/
@Input() tableMaxBufferPx: number = 200;
/**
* @zh_CN 表格自适应高度,table 高度等于屏幕高度减掉此处设置的数值
* @en_US Table adaptive height, table height is equal to the screen height minus the value set here
*/
@Input() @XInputNumber() tableAdaptionHeight?: XNumber;
/**
* @zh_CN 表格文档高度百分比,弹窗百分比高度用到
* @en_US Table document height percentage, used for pop-up window percentage height
*/
@Input() @XInputNumber() tableDocPercent: XNumber = 1;
/**
* @zh_CN 表格行高度,单位 px
* @en_US Table row height, unit px
*/
@Input() @XWithConfig<number>(X_CONFIG_NAME, 42) @XInputNumber() tableRowHeight!: number;
/**
* @zh_CN 树节点数据
* @en_US Tree node data
*/
@Input() @XDataConvert() treeData: XData<XTreeNode> = [];
/**
* @zh_CN 树当前点击选中的节点变化的事件
* @en_US The event of the tree currently clicked on the selected node change
*/
@Output() treeActivatedChange = new EventEmitter<XTreeNode>();
/**
* @zh_CN 树当前激活的节点 Id
* @en_US Id of the currently active node of the tree
*/
@Input() treeActivatedId: any;
/**
* @zh_CN 树默认展开的层级
* @en_US The level of the tree expanded by default
*/
@Input() @XWithConfig<XNumber>(X_CONFIG_NAME, 0) @XInputNumber() treeExpandedLevel!: XNumber;
/**
* @zh_CN 树 checkbox 选中的节点
* @en_US Tree checkbox selected node
*/
@Input() treeChecked: any[] = [];
/**
* @zh_CN 树显示多选框
* @en_US Tree display checkbox
*/
@Input() @XInputBoolean() treeCheckbox?: XBoolean;
/**
* @zh_CN 树和表格同时存在的时候,树节点 id 对应表格的属性,用来做表格数据过滤
* @en_US When the tree and the table exist at the same time, the tree node id corresponds to the attribute of the table, which is used to filter the table data
*/
@Input() treeTableConnect: any;
/**
* @zh_CN 数据查询过滤表单
* @en_US form for data filter
*/
@Input() search!: XFindSearchOption;
}
/**
* Find Option
* @undocument true
*/
export interface XFindOption extends XFormOption {
/**
* @zh_CN 尺寸
* @en_US Size
*/
size?: XSize;
/**
* @zh_CN 显示边框
* @en_US Display Border
*/
bordered?: XBoolean;
/**
* @zh_CN 多选
* @en_US Multiple select
*/
multiple?: XBoolean;
/**
* @zh_CN 选中 label 名称字段
* @en_US Check the label name field
*/
columnLabel?: string;
/**
* @zh_CN 弹框标题
* @en_US Bullet title
*/
dialogTitle?: string;
/**
* @zh_CN 弹框宽度
* @en_US Bullet frame width
*/
dialogWidth?: string;
/**
* @zh_CN 弹框高度
* @en_US Height of bullet frame
*/
dialogHeight?: string;
/**
* @zh_CN 弹框显示,隐藏
* @en_US Bullet box show, hide
*/
dialogVisible?: boolean;
/**
* @zh_CN 弹框显示,隐藏
* @en_US Bullet box show, hide
*/
// dialogVisibleChange = new EventEmitter<boolean>();
/**
* @zh_CN 按钮居中
* @en_US Button center
*/
dialogButtonsCenter?: XBoolean;
/**
* @zh_CN 表格行数据
* @en_US Table row data
*/
tableData?: XData<XTableRow>;
/**
* @zh_CN 表格页码
* @en_US Table page number
*/
tableIndex?: number;
/**
* @zh_CN 表每页数据条数
* @en_US Number of data items per page
*/
tableSize?: number;
/**
* @zh_CN 表格数据总条数
* @en_US Total number of table data
*/
tableTotal?: number;
/**
* @zh_CN 页码变化的事件
* @en_US Page number change event
*/
// tableIndexChange = new EventEmitter<number>();
/**
* @zh_CN 每页显示条数变化的事件
* @en_US Show the number of events on each page
*/
// tableSizeChange = new EventEmitter<number>();
/**
* @zh_CN 排序点击的事件
* @en_US Sort click events
*/
// tableSortChange = new EventEmitter<XSort[]>();
/**
* @zh_CN 表格列参数
* @en_US Table column parameters
*/
tableColumns?: XTableColumn[];
/**
* @zh_CN 当前选中行数据
* @en_US Currently selected row data
*/
tableActivatedRow?: any;
/**
* @zh_CN 表格行点击事件
* @en_US Table row click event
*/
// tableRowEmit = new EventEmitter<any>();
/**
* @zh_CN 表格行点击事件
* @en_US Table row click event
*/
tableCheckedRow?: { [property: string]: any[] };
/**
* @zh_CN 是否启用加载 loading
* @en_US Whether to enable loading
*/
tableLoading?: XBoolean;
/**
* @zh_CN 表格开启虚拟滚动
* @en_US Table opens virtual scrolling
*/
tableVirtualScroll?: boolean;
/**
* @zh_CN 表格 body 数据高度
* @en_US Table body data height
*/
tableBodyHeight?: number;
/**
* @zh_CN 表格超出可视窗口缓冲区的最小值,对应 cdk scroll 中的参数
* @en_US The table exceeds the minimum value of the visible window buffer, corresponding to the parameters in cdk scroll
*/
tableMinBufferPx?: number;
/**
* @zh_CN 表格渲染新数据缓冲区的像素,对应 cdk scroll 中的参数
* @en_US The pixels of the new data buffer for the table rendering, corresponding to the parameters in cdk scroll
*/
tableMaxBufferPx?: number;
/**
* @zh_CN 表格自适应高度,table 高度等于屏幕高度减掉此处设置的数值
* @en_US Table adaptive height, table height is equal to the screen height minus the value set here
*/
tableAdaptionHeight?: XNumber;
/**
* @zh_CN 表格文档高度百分比,弹窗百分比高度用到
* @en_US Table document height percentage, used for pop-up window percentage height
*/
tableDocPercent?: XNumber;
/**
* @zh_CN 表格行高度,单位 px
* @en_US Table row height, unit px
*/
tableRowHeight?: XNumber;
/**
* @zh_CN 树节点数据
* @en_US Tree node data
*/
treeData?: XData<XTreeNode>;
/**
* @zh_CN 树当前点击选中的节点变化的事件
* @en_US The event of the tree currently clicked on the selected node change
*/
// treeActivatedChange = new EventEmitter<XTreeNode>();
/**
* @zh_CN 树当前激活的节点 Id
* @en_US Id of the currently active node of the tree
*/
treeActivatedId?: any;
/**
* @zh_CN 树默认展开的层级
* @en_US The level of the tree expanded by default
*/
treeExpandedLevel?: XNumber;
/**
* @zh_CN 树 checkbox 选中的节点
* @en_US Tree checkbox selected node
*/
treeChecked?: any[];
/**
* @zh_CN 树显示多选框
* @en_US Tree display checkbox
*/
treeCheckbox?: XBoolean;
/**
* @zh_CN 树和表格同时存在的时候,树节点 id 对应表格的属性,用来做表格数据过滤
* @en_US When the tree and the table exist at the same time, the tree node id corresponds to the attribute of the table, which is used to filter the table data
*/
treeTableConnect?: any;
/**
* @zh_CN 数据查询过滤表单
* @en_US form for data filter
*/
search?: XFindSearchOption;
} | the_stack |
import { assert } from "chai";
import * as Plottable from "../../src";
import * as Mocks from "../mocks";
import * as TestMethods from "../testMethods";
describe("Tables", () => {
function assertTableRows(table: Plottable.Components.Table, expectedRows: Plottable.Component[][], message: string) {
expectedRows.forEach((row, rowIndex) => {
row.forEach((component, columnIndex) => {
assert.strictEqual(table.componentAt(rowIndex, columnIndex), component,
`${message} contains the correct entry at [${rowIndex}, ${columnIndex}]`);
});
});
}
describe("constructor behavior", () => {
it("adds the \"table\" CSS class", () => {
const table = new Plottable.Components.Table();
assert.isTrue(table.hasClass("table"));
});
it("can take a 2-D array of Components in the constructor", () => {
const c00 = new Plottable.Component();
const c11 = new Plottable.Component();
const rows = [
[c00, null],
[null, c11],
];
const table = new Plottable.Components.Table(rows);
assertTableRows(table, rows, "constructor initialized Table correctly");
});
});
describe("checking Table contents", () => {
it("can check if a given Component is in the Table", () => {
const c0 = new Plottable.Component();
const table = new Plottable.Components.Table([[c0]]);
assert.isTrue(table.has(c0), "correctly checks that Component is in the Table");
table.remove(c0);
assert.isFalse(table.has(c0), "correctly checks that Component is no longer in the Table");
table.add(c0, 1, 1);
assert.isTrue(table.has(c0), "correctly checks that Component is in the Table again");
});
it("can retrieve the Component at a given row, column index", () => {
const c00 = new Plottable.Component();
const c01 = new Plottable.Component();
const c10 = new Plottable.Component();
const c11 = new Plottable.Component();
const table = new Plottable.Components.Table([
[c00, c01],
[c10, c11],
]);
assert.strictEqual(table.componentAt(0, 0), c00, "retrieves the Component at [0, 0]");
assert.strictEqual(table.componentAt(0, 1), c01, "retrieves the Component at [0, 1]");
assert.strictEqual(table.componentAt(1, 0), c10, "retrieves the Component at [1, 0]");
assert.strictEqual(table.componentAt(1, 1), c11, "retrieves the Component at [1, 1]");
});
it("returns null when no Component exists at the specified row, column index", () => {
const c00 = new Plottable.Component();
const c11 = new Plottable.Component();
const table = new Plottable.Components.Table();
table.add(c00, 0, 0);
table.add(c11, 1, 1);
assert.isNull(table.componentAt(0, 1), "returns null if an empty cell is queried");
assert.isNull(table.componentAt(-1, 0), "returns null if a negative row index is passed in");
assert.isNull(table.componentAt(0, -1), "returns null if a negative column index is passed in");
assert.isNull(table.componentAt(9001, 0), "returns null if a row index larger than the number of rows is passed in");
assert.isNull(table.componentAt(0, 9001), "returns null if a column index larger than the number of columns is passed in");
});
});
describe("adding Components", () => {
it("adds the Component and pads out other empty cells with null", () => {
const table = new Plottable.Components.Table();
const c11 = new Plottable.Component();
table.add(c11, 1, 1);
assert.strictEqual(table.componentAt(1, 1), c11, "Component was added at the correct position");
assert.isNull(table.componentAt(0, 0), "Table padded [0, 0] with null");
assert.isNull(table.componentAt(0, 1), "Table padded [0, 1] with null");
assert.isNull(table.componentAt(1, 0), "Table padded [1, 0] with null");
});
it("throws an Error on trying to add a Component to an occupied cell", () => {
const c1 = new Plottable.Component();
const table = new Plottable.Components.Table([[c1]]);
const c2 = new Plottable.Component();
assert.throws(() => table.add(c2, 0, 0), Error, "occupied");
});
it("throws an Error on trying to add null to the Table", () => {
const table = new Plottable.Components.Table();
assert.throws(() => table.add(null, 0, 0), "Cannot add null to a table cell");
});
it("detaches a Component from its previous location before adding it", () => {
const component = new Plottable.Component();
const div = TestMethods.generateDiv();
component.renderTo(div);
const table = new Plottable.Components.Table();
table.add(component, 0, 0);
assert.isFalse((<Node> div.node()).hasChildNodes(), "Component was detach()-ed");
div.remove();
});
});
describe("removing Components", () => {
let c00: Plottable.Component;
let c01: Plottable.Component;
let c10: Plottable.Component;
let c11: Plottable.Component;
let table: Plottable.Components.Table;
beforeEach(() => {
c00 = new Plottable.Component();
c01 = new Plottable.Component();
c10 = new Plottable.Component();
c11 = new Plottable.Component();
});
it("removes the specified Component", () => {
const tableRows = [
[c00, c01],
[c10, c11],
];
table = new Plottable.Components.Table(tableRows);
table.remove(c11);
const expectedRows = [
[c00, c01],
[c10, null],
];
assertTableRows(table, expectedRows, "the requested element was removed");
assert.isNull(c11.parent(), "Component disconnected from the Table");
});
it("does nothing when component is not found", () => {
const tableRows = [
[c00, c01],
[c10, c11],
];
table = new Plottable.Components.Table(tableRows);
const expectedRows = tableRows;
const notInTable = new Plottable.Component();
table.remove(notInTable);
assertTableRows(table, expectedRows, "removing a nonexistent Component does not affect the table");
});
it("has no further effect when called a second time with the same Component", () => {
const tableRows = [
[c00, c01],
[c10, c11],
];
table = new Plottable.Components.Table(tableRows);
const expectedRows = [
[null, c01],
[c10, c11],
];
table.remove(c00);
assertTableRows(table, expectedRows, "Component was removed");
table.remove(c00);
assertTableRows(table, expectedRows, "removing Component again has no further effect");
});
it("removes a Component from the Table if the Component becomes detached", () => {
table = new Plottable.Components.Table([[c00]]);
c00.detach();
assert.isNull(table.componentAt(0, 0), "calling detach() on the Component removes it from the Table");
assert.isNull(c00.parent(), "Component disconnected from the Table");
});
});
describe("requesting space", () => {
it("is fixed-width if all columns contain only fixed-width Components, non-fixed otherwise", () => {
const fixedNullsTable = new Plottable.Components.Table([
[new Mocks.FixedSizeComponent(), null],
[null, new Mocks.FixedSizeComponent()],
]);
assert.isTrue(fixedNullsTable.fixedWidth(), "width is fixed if all columns contain fixed-width Components or null");
const notAllFixedTable = new Plottable.Components.Table([
[new Mocks.FixedSizeComponent(), new Mocks.FixedSizeComponent()],
[new Plottable.Component(), null],
]);
assert.isFalse(notAllFixedTable.fixedWidth(), "width is not fixed if any column contains a non-fixed-width Component");
});
it("is fixed-height if all rows contain only fixed-height Components, non-fixed otherwise", () => {
const fixedNullsTable = new Plottable.Components.Table([
[new Mocks.FixedSizeComponent(), null],
[null, new Mocks.FixedSizeComponent()],
]);
assert.isTrue(fixedNullsTable.fixedHeight(), "height is fixed if all columns contain fixed-height Components or null");
const notAllFixedTable = new Plottable.Components.Table([
[new Mocks.FixedSizeComponent(), new Plottable.Component()],
[new Mocks.FixedSizeComponent(), null],
]);
assert.isFalse(notAllFixedTable.fixedHeight(), "height is not fixed if any row contains a non-fixed-height Component");
});
it("requests enough space for largest fixed-size Component in each row and column", () => {
const BIG_COMPONENT_SIZE = 50;
const SMALL_COMPONENT_SIZE = 20;
const unfixedComponent = new Plottable.Component();
const bigFixedComponent01 = new Mocks.FixedSizeComponent(BIG_COMPONENT_SIZE, BIG_COMPONENT_SIZE);
const bigFixedComponent10 = new Mocks.FixedSizeComponent(BIG_COMPONENT_SIZE, BIG_COMPONENT_SIZE);
const smallFixedComponent = new Mocks.FixedSizeComponent(SMALL_COMPONENT_SIZE, SMALL_COMPONENT_SIZE);
const table = new Plottable.Components.Table([
[unfixedComponent, bigFixedComponent01],
[bigFixedComponent10, smallFixedComponent],
]);
const expectedMinWidth = 2 * BIG_COMPONENT_SIZE;
const expectedMinHeight = 2 * BIG_COMPONENT_SIZE;
const constrainedSpaceRequest = table.requestedSpace(0, 0);
TestMethods.verifySpaceRequest(constrainedSpaceRequest, expectedMinWidth, expectedMinHeight,
"requests enough space for all fixed-size Components when space is constrained");
const exactlyEnoughSpaceRequest = table.requestedSpace(expectedMinWidth, expectedMinHeight);
TestMethods.verifySpaceRequest(exactlyEnoughSpaceRequest, expectedMinWidth, expectedMinHeight,
"requests enough space for all fixed-size Components when given exactly enough space");
const extraSpaceRequest = table.requestedSpace(2 * expectedMinWidth, 2 * expectedMinHeight);
TestMethods.verifySpaceRequest(extraSpaceRequest, expectedMinWidth, expectedMinHeight,
"requests enough space for all fixed-size Components when given extra space");
});
});
describe("error checking on padding and weights", () => {
let table: Plottable.Components.Table;
beforeEach(() => {
table = new Plottable.Components.Table([
[new Plottable.Component(), new Plottable.Component()],
[new Plottable.Component(), new Plottable.Component()],
]);
});
afterEach(() => {
table.destroy();
});
it("rejects invalid input to rowPadding", () => {
// HACKHACK #2661: Cannot assert errors being thrown with description
(<any> assert).throws(() => table.rowPadding(-1), Error,
"rowPadding must be a non-negative finite value", "rowPadding rejects negative numbers");
(<any> assert).throws(() => table.rowPadding(Infinity), Error,
"rowPadding must be a non-negative finite value", "rowPadding rejects Infinity");
(<any> assert).throws(() => table.rowPadding(NaN), Error,
"rowPadding must be a non-negative finite value", "rowPadding rejects NaN");
(<any> assert).throws(() => table.rowPadding(<any> "4"), Error,
"rowPadding must be a non-negative finite value", "rowPadding rejects string numbers");
});
it("rejects invalid input to columnPadding", () => {
// HACKHACK #2661: Cannot assert errors being thrown with description
(<any> assert).throws(() => table.columnPadding(-1), Error,
"columnPadding must be a non-negative finite value", "columnPadding rejects negative numbers");
(<any> assert).throws(() => table.columnPadding(Infinity), Error,
"columnPadding must be a non-negative finite value", "columnPadding rejects Infinity");
(<any> assert).throws(() => table.columnPadding(NaN), Error,
"columnPadding must be a non-negative finite value", "columnPadding rejects NaN");
(<any> assert).throws(() => table.columnPadding(<any> "4"), Error,
"columnPadding must be a non-negative finite value", "columnPadding rejects string numbers");
});
it("rejects invalid input to rowWeight", () => {
// HACKHACK #2661: Cannot assert errors being thrown with description
(<any> assert).throws(() => table.rowWeight(0, -1), Error,
"rowWeight must be a non-negative finite value", "rowWeight rejects negative numbers");
(<any> assert).throws(() => table.rowWeight(1, Infinity), Error,
"rowWeight must be a non-negative finite value", "rowWeight rejects Infinity");
(<any> assert).throws(() => table.rowWeight(0, NaN), Error,
"rowWeight must be a non-negative finite value", "rowWeight rejects NaN");
(<any> assert).throws(() => table.rowWeight(1, <any> "4"), Error,
"rowWeight must be a non-negative finite value", "rowWeight rejects string numbers");
});
it("rejects invalid input to columnWeight", () => {
// HACKHACK #2661: Cannot assert errors being thrown with description
(<any> assert).throws(() => table.columnWeight(1, -1), Error,
"columnWeight must be a non-negative finite value", "columnWeight rejects negative numbers");
(<any> assert).throws(() => table.columnWeight(0, Infinity), Error,
"columnWeight must be a non-negative finite value", "columnWeight rejects Infinity");
(<any> assert).throws(() => table.columnWeight(1, NaN), Error,
"columnWeight must be a non-negative finite value", "columnWeight rejects NaN");
(<any> assert).throws(() => table.columnWeight(0, <any> "4"), Error,
"columnWeight must be a non-negative finite value", "columnWeight rejects string numbers");
});
});
describe("layout of constituent Components", () => {
const FIXED_COMPONENT_SIZE = 50;
function verifyOrigins(rows: Plottable.Component[][], rowPadding = 0, columnPadding = 0) {
const expectedOrigin = {
x: 0,
y: 0,
};
rows.forEach((row, r) => {
let maxHeight = 0;
expectedOrigin.x = 0;
row.forEach((component, c) => {
TestMethods.assertPointsClose(component.origin(), expectedOrigin, 0, `Component at [${r}, ${c}] has the correct origin`);
expectedOrigin.x += component.width() + columnPadding;
maxHeight = maxHeight > component.height() ? maxHeight : component.height();
});
expectedOrigin.y += maxHeight + rowPadding;
});
}
it("divides available width evenly between non-fixed-width Components", () => {
const div = TestMethods.generateDiv();
const component1 = new Plottable.Component();
const component2 = new Plottable.Component();
const tableRows = [[component1, component2]];
const table = new Plottable.Components.Table(tableRows);
table.renderTo(div);
const twoColumnExpectedWidth = Plottable.Utils.DOM.elementWidth(div) / 2;
assert.strictEqual(component1.width(), twoColumnExpectedWidth, "first Component received half the available width");
assert.strictEqual(component2.width(), twoColumnExpectedWidth, "second Component received half the available width");
verifyOrigins(tableRows);
const component3 = new Plottable.Component();
table.add(component3, 0, 2);
tableRows[0].push(component3);
const threeColumnExpectedWidth = Plottable.Utils.DOM.elementWidth(div) / 3;
assert.strictEqual(component1.width(), threeColumnExpectedWidth, "first Component received one-third of the available width");
assert.strictEqual(component2.width(), threeColumnExpectedWidth, "second Component received one-third of the available width");
assert.strictEqual(component3.width(), threeColumnExpectedWidth, "third Component received one-third of the available width");
verifyOrigins(tableRows);
table.destroy();
div.remove();
});
it("gives width to fixed-width Components, then divides remainder between non-fixed-width Components", () => {
const div = TestMethods.generateDiv();
const fixedSizeComponent = new Mocks.FixedSizeComponent(FIXED_COMPONENT_SIZE, FIXED_COMPONENT_SIZE);
const unfixedComponent1 = new Plottable.Component();
const unfixedComponent2 = new Plottable.Component();
const table = new Plottable.Components.Table([[fixedSizeComponent, unfixedComponent1, unfixedComponent2]]);
table.renderTo(div);
const expectedUnfixedWidth = (Plottable.Utils.DOM.elementWidth(div) - FIXED_COMPONENT_SIZE) / 2;
assert.strictEqual(unfixedComponent1.width(), expectedUnfixedWidth,
"first non-fixed-width Component received half the remaining width");
assert.strictEqual(unfixedComponent2.width(), expectedUnfixedWidth,
"second non-fixed-width Component received half the remaining width");
table.destroy();
div.remove();
});
it("divides available height evenly between non-fixed-height Components", () => {
const div = TestMethods.generateDiv();
const component1 = new Plottable.Component();
const component2 = new Plottable.Component();
const tableRows = [
[component1],
[component2],
];
const table = new Plottable.Components.Table(tableRows);
table.renderTo(div);
const twoRowExpectedHeight = Plottable.Utils.DOM.elementHeight(div) / 2;
assert.strictEqual(component1.height(), twoRowExpectedHeight, "first Component received half the available height");
assert.strictEqual(component2.height(), twoRowExpectedHeight, "second Component received half the available height");
verifyOrigins(tableRows);
const component3 = new Plottable.Component();
table.add(component3, 2, 0);
tableRows.push([component3]);
const threeRowExpectedHeight = Plottable.Utils.DOM.elementHeight(div) / 3;
assert.strictEqual(component1.height(), threeRowExpectedHeight, "first Component received one-third of the available height");
assert.strictEqual(component2.height(), threeRowExpectedHeight, "second Component received one-third of the available height");
assert.strictEqual(component3.height(), threeRowExpectedHeight, "third Component received one-third of the available height");
verifyOrigins(tableRows);
table.destroy();
div.remove();
});
it("gives height to fixed-height Components, then divides remainder between non-fixed-height Components", () => {
const div = TestMethods.generateDiv();
const fixedSizeComponent = new Mocks.FixedSizeComponent(FIXED_COMPONENT_SIZE, FIXED_COMPONENT_SIZE);
const unfixedComponent1 = new Plottable.Component();
const unfixedComponent2 = new Plottable.Component();
const table = new Plottable.Components.Table([
[fixedSizeComponent],
[unfixedComponent1],
[unfixedComponent2],
]);
table.renderTo(div);
const expectedUnfixedHeight = (Plottable.Utils.DOM.elementHeight(div) - FIXED_COMPONENT_SIZE) / 2;
assert.strictEqual(unfixedComponent1.height(), expectedUnfixedHeight,
"first non-fixed-height Component received half the remaining height");
assert.strictEqual(unfixedComponent2.height(), expectedUnfixedHeight,
"second non-fixed-height Component received half the remaining height");
table.destroy();
div.remove();
});
it("divides width evenly if there isn't enough width to go around", () => {
const div = TestMethods.generateDiv(FIXED_COMPONENT_SIZE, FIXED_COMPONENT_SIZE);
const fixedComponent1 = new Mocks.FixedSizeComponent(FIXED_COMPONENT_SIZE, FIXED_COMPONENT_SIZE);
const fixedComponent2 = new Mocks.FixedSizeComponent(FIXED_COMPONENT_SIZE, FIXED_COMPONENT_SIZE);
const tableRows = [[fixedComponent1, fixedComponent2]];
const table = new Plottable.Components.Table(tableRows);
table.renderTo(div);
const expectedWidth = FIXED_COMPONENT_SIZE / 2;
assert.strictEqual(fixedComponent1.width(), expectedWidth, "first fixed-width Component received half the available width");
assert.strictEqual(fixedComponent2.width(), expectedWidth, "second fixed-width Component received half the available width");
verifyOrigins(tableRows);
table.destroy();
div.remove();
});
it("divides height evenly if there isn't enough hieght to go around", () => {
const div = TestMethods.generateDiv(FIXED_COMPONENT_SIZE, FIXED_COMPONENT_SIZE);
const fixedComponent1 = new Mocks.FixedSizeComponent(FIXED_COMPONENT_SIZE, FIXED_COMPONENT_SIZE);
const fixedComponent2 = new Mocks.FixedSizeComponent(FIXED_COMPONENT_SIZE, FIXED_COMPONENT_SIZE);
const tableRows = [
[fixedComponent1],
[fixedComponent2],
];
const table = new Plottable.Components.Table(tableRows);
table.renderTo(div);
const expectedHeight = FIXED_COMPONENT_SIZE / 2;
assert.strictEqual(fixedComponent1.height(), expectedHeight, "first fixed-height Component received half the available height");
assert.strictEqual(fixedComponent2.height(), expectedHeight, "second fixed-height Component received half the available height");
verifyOrigins(tableRows);
table.destroy();
div.remove();
});
describe("layout with padding and weights", () => {
it("adds row padding between rows", () => {
const div = TestMethods.generateDiv();
const component1 = new Plottable.Component();
const component2 = new Plottable.Component();
const tableRows = [
[component1],
[component2],
];
const table = new Plottable.Components.Table(tableRows);
const rowPadding = 10;
table.rowPadding(rowPadding);
table.renderTo(div);
const expectedHeight = (Plottable.Utils.DOM.elementHeight(div) - rowPadding) / 2;
assert.strictEqual(component1.height(), expectedHeight, "first non-fixed-height Component received half the remaining height");
assert.strictEqual(component2.height(), expectedHeight, "second non-fixed-height Component received half the remaining height");
verifyOrigins(tableRows, rowPadding, 0);
table.destroy();
div.remove();
});
it("adds column padding between columns", () => {
const div = TestMethods.generateDiv();
const component1 = new Plottable.Component();
const component2 = new Plottable.Component();
const tableRows = [[component1, component2]];
const table = new Plottable.Components.Table(tableRows);
const columnPadding = 10;
table.columnPadding(columnPadding);
table.renderTo(div);
const expectedWidth = (Plottable.Utils.DOM.elementHeight(div) - columnPadding) / 2;
assert.strictEqual(component1.width(), expectedWidth, "first non-fixed-width Component received half the remaining width");
assert.strictEqual(component2.width(), expectedWidth, "second non-fixed-width Component received half the remaining width");
verifyOrigins(tableRows, 0, columnPadding);
table.destroy();
div.remove();
});
it("allocates height to unfixed rows according to row weights", () => {
const div = TestMethods.generateDiv();
const component0 = new Plottable.Component();
const component1 = new Plottable.Component();
const table = new Plottable.Components.Table([
[component0],
[component1],
]);
const row0Weight = 1;
table.rowWeight(0, row0Weight);
const row1Weight = 2;
table.rowWeight(1, row1Weight);
const totalRowWeight = row0Weight + row1Weight;
table.renderTo(div);
assert.strictEqual(component0.height(), Plottable.Utils.DOM.elementWidth(div) * row0Weight / totalRowWeight,
"row 0 received height according to its weight");
assert.strictEqual(component1.height(), Plottable.Utils.DOM.elementWidth(div) * row1Weight / totalRowWeight,
"row 1 received height according to its weight");
table.destroy();
div.remove();
});
it("allocates width to unfixed columns according to column weights", () => {
const div = TestMethods.generateDiv();
const component0 = new Plottable.Component();
const component1 = new Plottable.Component();
const table = new Plottable.Components.Table([[component0, component1]]);
const column0Weight = 1;
table.columnWeight(0, column0Weight);
const column1Weight = 2;
table.columnWeight(1, column1Weight);
const totalColumnWeight = column0Weight + column1Weight;
table.renderTo(div);
assert.strictEqual(component0.width(), Plottable.Utils.DOM.elementWidth(div) * column0Weight / totalColumnWeight,
"column 0 received width according to its weight");
assert.strictEqual(component1.width(), Plottable.Utils.DOM.elementWidth(div) * column1Weight / totalColumnWeight,
"column 1 received width according to its weight");
table.destroy();
div.remove();
});
});
});
}); | the_stack |
import { Component, Inject } from 'vue-property-decorator';
import { getAbsoluteLink } from '../../../../../../utils/router';
import AppAdWidget from '../../../../../../_common/ad/widget/widget.vue';
import { Api } from '../../../../../../_common/api/api.service';
import AppCard from '../../../../../../_common/card/card.vue';
import { Clipboard } from '../../../../../../_common/clipboard/clipboard-service';
import AppCommentAddButton from '../../../../../../_common/comment/add-button/add-button.vue';
import { canCommentOnModel, Comment } from '../../../../../../_common/comment/comment-model';
import {
CommentStoreManager,
CommentStoreManagerKey,
getCommentStore,
} from '../../../../../../_common/comment/comment-store';
import { CommentModal } from '../../../../../../_common/comment/modal/modal.service';
import {
CommentThreadModal,
CommentThreadModalPermalinkDeregister,
} from '../../../../../../_common/comment/thread/modal.service';
import AppContentViewer from '../../../../../../_common/content/content-viewer/content-viewer.vue';
import { Environment } from '../../../../../../_common/environment/environment.service';
import AppFadeCollapse from '../../../../../../_common/fade-collapse/fade-collapse.vue';
import { number } from '../../../../../../_common/filters/number';
import { FiresidePost } from '../../../../../../_common/fireside/post/post-model';
import AppGameExternalPackageCard from '../../../../../../_common/game/external-package/card/card.vue';
import { Game } from '../../../../../../_common/game/game.model';
import AppGameMediaBar from '../../../../../../_common/game/media-bar/media-bar.vue';
import AppGamePackageCard from '../../../../../../_common/game/package/card/card.vue';
import AppGameSoundtrackCard from '../../../../../../_common/game/soundtrack/card/card.vue';
import { HistoryTick } from '../../../../../../_common/history-tick/history-tick-service';
import { AppLazyPlaceholder } from '../../../../../../_common/lazy/placeholder/placeholder';
import { Meta } from '../../../../../../_common/meta/meta-service';
import { PartnerReferral } from '../../../../../../_common/partner-referral/partner-referral-service';
import { BaseRouteComponent, RouteResolver } from '../../../../../../_common/route/route-component';
import { Screen } from '../../../../../../_common/screen/screen-service';
import AppShareCard from '../../../../../../_common/share/card/card.vue';
import { ActivityFeedService } from '../../../../../components/activity/feed/feed-service';
import AppActivityFeedPlaceholder from '../../../../../components/activity/feed/placeholder/placeholder.vue';
import { ActivityFeedView } from '../../../../../components/activity/feed/view';
import AppCommentOverview from '../../../../../components/comment/overview/overview.vue';
import AppGameCommunityBadge from '../../../../../components/game/community-badge/community-badge.vue';
import AppGameOgrs from '../../../../../components/game/ogrs/ogrs.vue';
import { AppGamePerms } from '../../../../../components/game/perms/perms';
import { AppActivityFeedLazy } from '../../../../../components/lazy';
import AppPageContainer from '../../../../../components/page-container/page-container.vue';
import AppPostAddButton from '../../../../../components/post/add-button/add-button.vue';
import AppRatingWidget from '../../../../../components/rating/widget/widget.vue';
import AppUserKnownFollowers from '../../../../../components/user/known-followers/known-followers.vue';
import { RouteStore, routeStore, RouteStoreModule } from '../view.store';
import AppDiscoverGamesViewOverviewDetails from './_details/details.vue';
import AppDiscoverGamesViewOverviewRecommended from './_recommended/recommended.vue';
import AppDiscoverGamesViewOverviewStatbar from './_statbar/statbar.vue';
import AppDiscoverGamesViewOverviewSupporters from './_supporters/supporters.vue';
@Component({
name: 'RouteDiscoverGamesViewOverview',
components: {
AppPageContainer,
AppDiscoverGamesViewOverviewDetails,
AppDiscoverGamesViewOverviewRecommended,
AppDiscoverGamesViewOverviewSupporters,
AppDiscoverGamesViewOverviewStatbar,
AppGameCommunityBadge,
AppAdWidget,
AppRatingWidget,
AppCard,
AppFadeCollapse,
AppLazyPlaceholder,
AppGameOgrs,
AppGameExternalPackageCard,
AppGamePackageCard,
AppGameSoundtrackCard,
AppGameMediaBar,
AppCommentAddButton,
AppCommentOverview,
AppActivityFeed: AppActivityFeedLazy,
AppActivityFeedPlaceholder,
AppPostAddButton,
AppGamePerms,
AppContentViewer,
AppUserKnownFollowers,
AppShareCard,
},
filters: {
number,
},
})
@RouteResolver({
lazy: true,
cache: true,
deps: { query: ['feed_last_id'] },
resolver({ route }) {
const gameId = parseInt(route.params.id, 10);
HistoryTick.sendBeacon('game-view', gameId, {
sourceResource: 'Game',
sourceResourceId: gameId,
});
// If we have a tracked partner "ref" in the URL, we want to pass that along
// when gathering the payload.
let apiOverviewUrl = '/web/discover/games/overview/' + route.params.id;
const ref = PartnerReferral.getReferrer('Game', parseInt(route.params.id, 10));
if (ref) {
apiOverviewUrl += '?ref=' + ref;
}
return Api.sendRequest(ActivityFeedService.makeFeedUrl(route, apiOverviewUrl));
},
resolveStore({ payload, fromCache }) {
routeStore.commit('processOverviewPayload', { payload, fromCache });
},
})
export default class RouteDiscoverGamesViewOverview extends BaseRouteComponent {
@Inject(CommentStoreManagerKey) commentManager!: CommentStoreManager;
@RouteStoreModule.State
isOverviewLoaded!: RouteStore['isOverviewLoaded'];
@RouteStoreModule.State
game!: RouteStore['game'];
@RouteStoreModule.State
mediaItems!: RouteStore['mediaItems'];
@RouteStoreModule.State
overviewComments!: RouteStore['overviewComments'];
@RouteStoreModule.State
userRating!: RouteStore['userRating'];
@RouteStoreModule.State
songs!: RouteStore['songs'];
@RouteStoreModule.State
userPartnerKey!: RouteStore['userPartnerKey'];
@RouteStoreModule.State
partnerLink!: RouteStore['partnerLink'];
@RouteStoreModule.State
partner!: RouteStore['partner'];
@RouteStoreModule.State
partnerKey!: RouteStore['partnerKey'];
@RouteStoreModule.State
supporters!: RouteStore['supporters'];
@RouteStoreModule.State
supporterCount!: RouteStore['supporterCount'];
@RouteStoreModule.State
shouldShowMultiplePackagesMessage!: RouteStore['shouldShowMultiplePackagesMessage'];
@RouteStoreModule.State
postsCount!: RouteStore['postsCount'];
@RouteStoreModule.State
packages!: RouteStore['packages'];
@RouteStoreModule.State
externalPackages!: RouteStore['externalPackages'];
@RouteStoreModule.State
hasReleasesSection!: RouteStore['hasReleasesSection'];
@RouteStoreModule.State
customGameMessages!: RouteStore['customGameMessages'];
@RouteStoreModule.Mutation
processOverviewPayload!: RouteStore['processOverviewPayload'];
@RouteStoreModule.State
showDetails!: RouteStore['showDetails'];
@RouteStoreModule.Mutation
toggleDetails!: RouteStore['toggleDetails'];
@RouteStoreModule.Mutation
setCanToggleDescription!: RouteStore['setCanToggleDescription'];
@RouteStoreModule.Mutation
setOverviewComments!: RouteStore['setOverviewComments'];
@RouteStoreModule.State
browserBuilds!: RouteStore['browserBuilds'];
@RouteStoreModule.State
knownFollowers!: RouteStore['knownFollowers'];
@RouteStoreModule.State
knownFollowerCount!: RouteStore['knownFollowerCount'];
feed: ActivityFeedView | null = null;
permalinkWatchDeregister?: CommentThreadModalPermalinkDeregister;
readonly Screen = Screen;
readonly Environment = Environment;
get routeTitle() {
if (this.game) {
let title = this.$gettextInterpolate('%{ gameTitle } by %{ user }', {
gameTitle: this.game.title,
user: this.game.developer.display_name,
});
if (this.browserBuilds.length) {
title += ' - ' + this.$gettext('Play Online');
}
return title;
}
return null;
}
get hasAnyPerms() {
return this.game.hasPerms();
}
get hasDevlogPerms() {
return this.game.hasPerms('devlogs');
}
get hasPartnerControls() {
return this.game.referrals_enabled && this.userPartnerKey && this.packages.length;
}
get commentsCount() {
if (this.game) {
const store = getCommentStore(this.commentManager, 'Game', this.game.id);
return store ? store.totalCount : 0;
}
return 0;
}
get shouldShowAds() {
return this.$ad.shouldShow;
}
get shouldShowCommentAdd() {
return canCommentOnModel(this.game);
}
get shareLink() {
return getAbsoluteLink(this.$router, this.game.getUrl());
}
routeCreated() {
this.feed = ActivityFeedService.routeInit(this);
}
routeResolved($payload: any, fromCache: boolean) {
Meta.description = $payload.metaDescription;
Meta.fb = $payload.fb;
Meta.twitter = $payload.twitter;
if ($payload.microdata) {
Meta.microdata = $payload.microdata;
}
if (this.game) {
CommentThreadModal.showFromPermalink(this.$router, this.game, 'comments');
this.permalinkWatchDeregister = CommentThreadModal.watchForPermalink(
this.$router,
this.game,
'comments'
);
}
this.feed = ActivityFeedService.routed(
this.feed,
{
type: 'EventItem',
name: 'game-devlog',
url: `/web/posts/fetch/game/${this.game.id}`,
hideGameInfo: true,
itemsPerPage: $payload.perPage,
},
$payload.posts,
fromCache
);
}
destroyed() {
if (this.permalinkWatchDeregister) {
this.permalinkWatchDeregister();
this.permalinkWatchDeregister = undefined;
}
}
copyPartnerLink() {
if (this.partnerLink) {
Clipboard.copy(this.partnerLink);
}
}
showComments() {
CommentModal.show({ model: this.game, displayMode: 'comments' });
}
onPostAdded(post: FiresidePost) {
ActivityFeedService.onPostAdded(this.feed!, post, this);
}
async reloadPreviewComments() {
if (this.game instanceof Game) {
const $payload = await Api.sendRequest(
'/web/discover/games/comment-overview/' + this.game.id
);
this.setOverviewComments(Comment.populate($payload.comments));
}
}
} | the_stack |
import { Asset, CommonOffset, StorageLoadError } from "@akashic/pdi-types";
import { Trigger } from "@akashic/trigger";
import { AssetAccessor } from "./AssetAccessor";
import { AssetHolder } from "./AssetHolder";
import { AssetLoadFailureInfo } from "./AssetLoadFailureInfo";
import { Camera } from "./Camera";
import { Camera2D } from "./Camera2D";
import { DynamicAssetConfiguration } from "./DynamicAssetConfiguration";
import { E, PointDownEvent, PointMoveEvent, PointSource, PointUpEvent } from "./entities/E";
import { MessageEvent, OperationEvent } from "./Event";
import { ExceptionFactory } from "./ExceptionFactory";
import { Game } from "./Game";
import { LocalTickModeString } from "./LocalTickModeString";
import { StorageLoader, StorageLoaderHandler, StorageReadKey, StorageValueStore, StorageValueStoreSerialization } from "./Storage";
import { TickGenerationModeString } from "./TickGenerationModeString";
import { Timer } from "./Timer";
import { TimerIdentifier, TimerManager } from "./TimerManager";
export type SceneRequestAssetHandler = () => void;
/**
* `Scene` のコンストラクタに渡すことができるパラメータ。
* 説明のない各メンバの詳細は `Scene` の同名メンバの説明を参照すること。
*/
export interface SceneParameterObject {
/**
* このシーンの属するゲーム。
*/
game: Game;
/**
* このシーンで用いるアセットIDの配列。
*
* アセットIDとは、 game.jsonのassetsオブジェクトの各プロパティのキー文字列である。
* アセットIDでなくパスで指定したい場合は `assetPaths` を利用できる。両方指定してもよい。
*
* @default undefined
*/
assetIds?: (string | DynamicAssetConfiguration)[];
/**
* このシーンで用いるアセットのファイルパスの配列。
*
* 各要素は `/` から始まる絶対パスでなければならない。
* ここでルートディレクトリ `/` はgame.json のあるディレクトリを指す。
* ただしオーディオアセットに限り、拡張子を含まないパスであること。
* (e.g. `/image/character01.png`, `/audio/bgm01`)
*
* パスでなくアセットIDで指定したい場合は `assetIds` を利用できる。両方指定してもよい。
* game.jsonのassetsに定義がないアセット(ダイナミックアセット)は指定できない。
*
* @default undefined
*/
assetPaths?: string[];
/**
* このシーンで用いるストレージのキーを表す `StorageReadKey` の配列。
* @default undefined
*/
storageKeys?: StorageReadKey[];
/**
* このシーンのローカルティック消化ポリシー。
*
* * `"full-local"` が与えられた場合、このシーンはローカルシーンと呼ばれる。
* ローカルシーンでは、他プレイヤーと独立な時間進行処理(ローカルティックの消化)が行われる。
* * `"non-local"` が与えられた場合、このシーンは非ローカルシーンと呼ばれる。
* 非ローカルシーンでは、他プレイヤーと共通の時間進行処理((非ローカル)ティックの消化)が行われる(onUpdateがfireされる)。
* ローカルティックを消化することはない。
* * `"interpolate-local"` が与えられた場合、このシーンはローカルティック補間シーンと呼ばれる。
* ローカルティック補間シーンでは、非ローカルシーン同様にティックを消化するが、
* 消化すべき非ローカルティックがない場合にローカルティックが補間され消化される。
*
* ローカルシーンに属するエンティティは、すべてローカルである(強制的にローカルエンティティとして生成される)。
* ローカルシーンは特にアセットロード中のような、他プレイヤーと同期すべきでないシーンのために存在する機能である。
*
* `LocalTickModeString` の代わりに `boolean` を与えることもできる。
* 偽は `"non-local"` 、 真は `"full-local"` と解釈される。
* @default "non-local"
*/
local?: boolean | LocalTickModeString;
/**
* このシーンの識別用の名前。
* @default undefined
*/
name?: string;
/**
* このシーンで復元するストレージデータ。
*
* falsyでない場合、 `Scene#serializeStorageValues()` の戻り値でなければならない。
* この値を指定した場合、 `storageValues` の値は `serializeStorageValues()` を呼び出したシーン(元シーン)の持っていた値を再現したものになる。
* この時、 `storageKeys` の値は元シーンと同じでなければならない。
* @default undefined
*/
storageValuesSerialization?: StorageValueStoreSerialization;
/**
* 時間経過の契機(ティック)をどのように生成するか。
*
* 省略された場合、 `"by-clock"` 。
* `Manual` を指定した場合、 `Game#raiseTick()` を呼び出さない限りティックが生成されない(時間経過しない)。
* ただしローカルティック(ローカルシーンの間などの「各プレイヤー間で独立な時間経過処理」)はこの値の影響を受けない。
* またこのシーンへの遷移直後、一度だけこの値に関わらずティックが生成される。
*/
tickGenerationMode?: TickGenerationModeString;
}
/**
* そのSceneの状態を表す列挙子。
*
* - "destroyed": すでに破棄されているシーンで、再利用が不可能になっている状態を表す
* - "standby": 初期化された状態のシーンで、シーンスタックへ追加されることを待っている状態を表す
* - "active": シーンスタックの一番上にいるシーンで、ゲームのカレントシーンとして活性化されている状態を表す
* - "deactive": シーンスタックにいるが一番上ではないシーンで、裏側で非活性状態になっていることを表す
* - "before-destroyed": これから破棄されるシーンで、再利用が不可能になっている状態を表す
*/
export type SceneStateString = "destroyed" | "standby" | "active" | "deactive" | "before-destroyed";
export type SceneLoadStateString = "initial" | "ready" | "ready-fired" | "loaded-fired";
/**
* シーンを表すクラス。
*/
export class Scene implements StorageLoaderHandler {
/**
* このシーンの子エンティティ。
*
* エンティティは `Scene#append()` によって追加され、 `Scene#remove()` によって削除される。
*/
children: E[];
/**
* このシーンで利用できるアセット。
*
* アセットID をkeyに、対応するアセットのインスタンスを得ることができる。
* keyはこのシーンの生成時、コンストラクタの第二引数 `assetIds` に渡された配列に含まれる文字列でなければならない。
*/
assets: { [key: string]: Asset };
/**
* このシーンで利用できるアセットへのアクセッサ。
*
* 歴史的経緯による `assets` との違いに注意。
* `assets` は「このシーンの生成時に読み込んだアセット」に「アセットIDをキーにして」アクセスするテーブルである。
* 他方この `asset` は `getImageById()`, `getAllTexts()` などのメソッドを持つオブジェクトである。
* アセットIDだけでなくパスでのアクセスや、複数アセットの一括取得ができる点で異なる。
*/
asset: AssetAccessor;
/**
* このシーンの属するゲーム。
*/
game: Game;
/**
* このシーンのローカルティック消化ポリシー。
*
* * `"non-local"` が与えられた場合、このシーンは非ローカルシーンと呼ばれる。
* 非ローカルシーンでは、他プレイヤーと共通の時間進行処理((非ローカル)ティックの消化)が行われる(onUpdateがfireされる)。
* * `"full-local"` が与えられた場合、このシーンはローカルシーンと呼ばれる。
* ローカルシーンでは、他プレイヤーと独立な時間進行処理(ローカルティックの消化)が行われる。
* * `"interpolate-local"` が与えられた場合、このシーンはローカルティック補間シーンと呼ばれる。
* ローカルティック補間シーンは、非ローカルシーン同様にティックを消化するが、
* 消化すべき非ローカルティックがない場合にローカルティックが補間され消化される。
*
* ローカルシーンとローカルティック補間シーンに属するエンティティは、
* すべてローカルである(強制的にローカルエンティティとして生成される)。
* ローカルシーンは特にアセットロード中のような、他プレイヤーと同期すべきでないシーンのために存在する機能である。
*
* この値は参照のためにのみ公開されている。ゲーム開発者はこの値を変更すべきではない。
*/
local: LocalTickModeString;
/**
* 時間経過の契機(ティック)をどのように生成するか。
* `"manual"` の場合、 `Game#raiseTick()` を呼び出さない限りティックが生成されない(時間経過しない)。
* ただしローカルティック(ローカルシーンの間などの「各プレイヤー間で独立な時間経過処理」)はこの値の影響を受けない。
* またこのシーンへの遷移直後、一度だけこの値に関わらずティックが生成される。
*
* この値は参照のためにのみ公開されている。ゲーム開発者はこの値を変更すべきではない。
*/
tickGenerationMode: TickGenerationModeString;
/**
* シーンの識別用の名前。
*/
name: string | undefined;
/**
* 時間経過イベント。本イベントの一度のfireにつき、常に1フレーム分の時間経過が起こる。
*/
onUpdate: Trigger<void>;
/**
* 読み込み完了イベント。
*
* このシーンの生成時に(コンストラクタで)指定されたすべてのアセットの読み込みが終了した後、一度だけfireされる。
* このシーンのアセットを利用するすべての処理は、このイベントのfire後に実行されなければならない。
*/
onLoad: Trigger<Scene>;
/**
* アセット読み込み成功イベント。
*
* このシーンのアセットが一つ読み込まれる度にfireされる。
* アセット読み込み中の動作をカスタマイズしたい場合に用いる。
*/
onAssetLoad: Trigger<Asset>;
/**
* アセット読み込み失敗イベント。
*
* このシーンのアセットが一つ読み込みに失敗する度にfireされる。
* アセット読み込み中の動作をカスタマイズしたい場合に用いる。
* このイベントをhandleする場合、ハンドラは `AssetLoadFailureInfo#cancelRetry` を真にすることでゲーム続行を断念することができる。
*/
onAssetLoadFailure: Trigger<AssetLoadFailureInfo>;
/**
* アセット読み込み完了イベント。
*
* このシーンのアセットが一つ読み込みに失敗または成功する度にfireされる。
* アセット読み込み中の動作をカスタマイズしたい場合に用いる。
*/
onAssetLoadComplete: Trigger<Asset>;
/**
* シーンの状態。
*/
state: SceneStateString;
/**
* シーンの状態変更イベント。
* 状態が初期化直後の `"standby"` 状態以外に変化するときfireされる。
*/
onStateChange: Trigger<SceneStateString>;
/**
* 汎用メッセージイベント。
*/
onMessage: Trigger<MessageEvent>;
/**
* シーン内でのpoint downイベント。
*
* このイベントは `E#onPointDown` とは独立にfireされる。
* すなわち、シーン内に同じ位置でのpoint downイベントに反応する `E` がある場合もない場合もこのイベントはfireされる。
*/
onPointDownCapture: Trigger<PointDownEvent>;
/**
* シーン内でのpoint moveイベント。
*
* このイベントは `E#onPointMove` とは独立にfireされる。
* すなわち、シーン内に同じ位置でのpoint moveイベントに反応する `E` がある場合もない場合もこのイベントはfireされる。
*/
onPointMoveCapture: Trigger<PointMoveEvent>;
/**
* シーン内でのpoint upイベント。
*
* このイベントは `E#onPointUp` とは独立にfireされる。
* すなわち、シーン内に同じ位置でのpoint upイベントに反応する `E` がある場合もない場合もこのイベントはfireされる。
*/
onPointUpCapture: Trigger<PointUpEvent>;
/**
* シーン内での操作イベント。
*/
onOperation: Trigger<OperationEvent>;
/**
* シーン内で利用可能なストレージの値を保持する `StorageValueStore`。
*/
storageValues: StorageValueStore | undefined;
/**
* 時間経過イベント。本イベントの一度のfireにつき、常に1フレーム分の時間経過が起こる。
* @deprecated 非推奨である。将来的に削除される。代わりに `onUpdate` を利用すること。
*/
update: Trigger<void>;
/**
* 読み込み完了イベント。
*
* このシーンの生成時に(コンストラクタで)指定されたすべてのアセットの読み込みが終了した後、一度だけfireされる。
* このシーンのアセットを利用するすべての処理は、このイベントのfire後に実行されなければならない。
* @deprecated 非推奨である。将来的に削除される。代わりに `onLoad` を利用すること。
*/
loaded: Trigger<Scene>;
/**
* アセット読み込み成功イベント。
*
* このシーンのアセットが一つ読み込まれる度にfireされる。
* アセット読み込み中の動作をカスタマイズしたい場合に用いる。
* @deprecated 非推奨である。将来的に削除される。代わりに `onAssetLoad` を利用すること。
*/
assetLoaded: Trigger<Asset>;
/**
* アセット読み込み失敗イベント。
*
* このシーンのアセットが一つ読み込みに失敗する度にfireされる。
* アセット読み込み中の動作をカスタマイズしたい場合に用いる。
* このイベントをhandleする場合、ハンドラは `AssetLoadFailureInfo#cancelRetry` を真にすることでゲーム続行を断念することができる。
* @deprecated 非推奨である。将来的に削除される。代わりに `onAssetLoadFailure` を利用すること。
*/
assetLoadFailed: Trigger<AssetLoadFailureInfo>;
/**
* アセット読み込み完了イベント。
*
* このシーンのアセットが一つ読み込みに失敗または成功する度にfireされる。
* アセット読み込み中の動作をカスタマイズしたい場合に用いる。
* @deprecated 非推奨である。将来的に削除される。代わりに `onAssetLoadComplete` を利用すること。
*/
assetLoadCompleted: Trigger<Asset>;
/**
* 汎用メッセージイベント。
* @deprecated 非推奨である。将来的に削除される。代わりに `onMessage` を利用すること。
*/
message: Trigger<MessageEvent>;
/**
* シーン内でのpoint downイベント。
*
* このイベントは `E#onPointDown` とは独立にfireされる。
* すなわち、シーン内に同じ位置でのpoint downイベントに反応する `E` がある場合もない場合もこのイベントはfireされる。
* @deprecated 非推奨である。将来的に削除される。代わりに `onPointDownCapture` を利用すること。
*/
pointDownCapture: Trigger<PointDownEvent>;
/**
* シーン内でのpoint moveイベント。
*
* このイベントは `E#onPointMove` とは独立にfireされる。
* すなわち、シーン内に同じ位置でのpoint moveイベントに反応する `E` がある場合もない場合もこのイベントはfireされる。
* @deprecated 非推奨である。将来的に削除される。代わりに `onPointMoveCapture` を利用すること。
*/
pointMoveCapture: Trigger<PointMoveEvent>;
/**
* シーン内でのpoint upイベント。
*
* このイベントは `E#onPointUp` とは独立にfireされる。
* すなわち、シーン内に同じ位置でのpoint upイベントに反応する `E` がある場合もない場合もこのイベントはfireされる。
* @deprecated 非推奨である。将来的に削除される。代わりに `onPointUpCapture` を利用すること。
*/
pointUpCapture: Trigger<PointUpEvent>;
/**
* シーン内での操作イベント。
* @deprecated 非推奨である。将来的に削除される。代わりに `onOperation` を利用すること。
*/
operation: Trigger<OperationEvent>;
/**
* @private
*/
_storageLoader: StorageLoader | undefined;
/**
* アセットとストレージの読み込みが終わったことを通知するTrigger。
* @private
*/
_onReady: Trigger<Scene>;
/**
* アセットとストレージの読み込みが終わったことを通知するTrigger。
* @private
* @deprecated 非推奨である。将来的に削除される。代わりに `_onReady` を利用すること。
*/
_ready: Trigger<Scene>;
/**
* 読み込みが開始されたか否か。
* すなわち、 `_load()` が呼び出された後か否か。
*
* 歴史的経緯により、このフラグの意味は「読み込みが終わった後」でも「onLoadがfireされた後」でもない点に注意。
* なお前者「(アセットとストレージの)読み込みが終わった後」は `_loadingState === "ready"` に与えられる。
*
* シーンの読み込みは概ね次の順で処理が進行する。
* * `_loaded` が真になる
* * 各種読み込みが完了する
* * `_loadingState` が `"ready"` になる
* * `_onReady` がfireされる
* * `_loadingState` が `"ready-fired"` になる
* * `onLoad` がfireされる
* * `_loadingState` が `"loaded-fired"` になる
* @private
*/
_loaded: boolean;
/**
* 先読みが要求されたか否か。
* すなわち、 `prefetch()` が呼び出された後か否か。
* @private
*/
_prefetchRequested: boolean;
/**
* アセットとストレージの読み込みが終わった後か否か。
* 「 `onLoad` がfireされた後」ではない点に注意。
* @private
*/
_loadingState: SceneLoadStateString;
/**
* タイマー。通常は本変数直接ではなく、createTimer/deleteTimer/setInterval/clearInterval等の機構を利用する。
* @private
*/
_timer: TimerManager;
/**
* シーンのアセットの保持者。
* @private
*/
_sceneAssetHolder: AssetHolder<SceneRequestAssetHandler>;
/**
* `Scene#requestAssets()` で動的に要求されたアセットの保持者。
* @private
*/
_assetHolders: AssetHolder<SceneRequestAssetHandler>[];
/**
* 各種パラメータを指定して `Scene` のインスタンスを生成する。
* @param param 初期化に用いるパラメータのオブジェクト
*/
constructor(param: SceneParameterObject) {
var game = param.game;
var local =
param.local === undefined
? "non-local"
: param.local === false
? "non-local"
: param.local === true
? "full-local"
: param.local;
var tickGenerationMode = param.tickGenerationMode !== undefined ? param.tickGenerationMode : "by-clock";
if (!param.storageKeys) {
this._storageLoader = undefined;
this.storageValues = undefined;
} else {
this._storageLoader = game.storage._createLoader(param.storageKeys, param.storageValuesSerialization);
this.storageValues = this._storageLoader._valueStore;
}
this.name = param.name;
this.game = game;
this.local = local;
this.tickGenerationMode = tickGenerationMode;
this.onLoad = new Trigger<Scene>();
this.loaded = this.onLoad;
this._onReady = new Trigger<Scene>();
this._ready = this._onReady;
this.assets = {};
this.asset = new AssetAccessor(game._assetManager);
this._loaded = false;
this._prefetchRequested = false;
this._loadingState = "initial";
this.onUpdate = new Trigger<void>();
this.update = this.onUpdate;
this._timer = new TimerManager(this.onUpdate, this.game.fps);
this.onAssetLoad = new Trigger<Asset>();
this.onAssetLoadFailure = new Trigger<AssetLoadFailureInfo>();
this.onAssetLoadComplete = new Trigger<Asset>();
this.assetLoaded = this.onAssetLoad;
this.assetLoadFailed = this.onAssetLoadFailure;
this.assetLoadCompleted = this.onAssetLoadComplete;
this.onMessage = new Trigger<MessageEvent>();
this.onPointDownCapture = new Trigger<PointDownEvent>();
this.onPointMoveCapture = new Trigger<PointMoveEvent>();
this.onPointUpCapture = new Trigger<PointUpEvent>();
this.onOperation = new Trigger<OperationEvent>();
this.message = this.onMessage;
this.pointDownCapture = this.onPointDownCapture;
this.pointMoveCapture = this.onPointMoveCapture;
this.pointUpCapture = this.onPointUpCapture;
this.operation = this.onOperation;
this.children = [];
this.state = "standby";
this.onStateChange = new Trigger<SceneStateString>();
this._assetHolders = [];
this._sceneAssetHolder = new AssetHolder<SceneRequestAssetHandler>({
assetManager: this.game._assetManager,
assetIds: param.assetIds,
assetPaths: param.assetPaths,
handlerSet: {
owner: this,
handleLoad: this._handleSceneAssetLoad,
handleLoadFailure: this._handleSceneAssetLoadFailure,
handleFinish: this._handleSceneAssetLoadFinish
},
userData: null
});
}
/**
* このシーンが変更されたことをエンジンに通知する。
*
* このメソッドは、このシーンに紐づいている `E` の `modified()` を呼び出すことで暗黙に呼び出される。
* 通常、ゲーム開発者がこのメソッドを呼び出す必要はない。
* @param isBubbling この関数をこのシーンの子の `modified()` から呼び出す場合、真を渡さなくてはならない。省略された場合、偽。
*/
modified(_isBubbling?: boolean): void {
this.game.modified();
}
/**
* このシーンを破棄する。
*
* 破棄処理の開始時に、このシーンの `onStateChange` が引数 `BeforeDestroyed` でfireされる。
* 破棄処理の終了時に、このシーンの `onStateChange` が引数 `Destroyed` でfireされる。
* このシーンに紐づいている全ての `E` と全てのTimerは破棄される。
* `Scene#setInterval()`, `Scene#setTimeout()` に渡された関数は呼び出されなくなる。
*
* このメソッドは `Scene#end` や `Game#popScene` などによって要求されたシーンの遷移時に暗黙に呼び出される。
* 通常、ゲーム開発者がこのメソッドを呼び出す必要はない。
*/
destroy(): void {
this.state = "before-destroyed";
this.onStateChange.fire(this.state);
// TODO: (GAMEDEV-483) Sceneスタックがそれなりの量になると重くなるのでScene#dbが必要かもしれない
var gameDb = this.game.db;
for (var p in gameDb) {
if (gameDb.hasOwnProperty(p) && gameDb[p].scene === this) gameDb[p].destroy();
}
var gameDb = this.game._localDb;
for (var p in gameDb) {
if (gameDb.hasOwnProperty(p) && gameDb[p].scene === this) gameDb[p].destroy();
}
this._timer.destroy();
this.onUpdate.destroy();
this.onMessage.destroy();
this.onPointDownCapture.destroy();
this.onPointMoveCapture.destroy();
this.onPointUpCapture.destroy();
this.onOperation.destroy();
this.onLoad.destroy();
this.onAssetLoad.destroy();
this.onAssetLoadFailure.destroy();
this.onAssetLoadComplete.destroy();
this.assets = {};
// アセットを参照しているEより先に解放しないよう最後に解放する
for (var i = 0; i < this._assetHolders.length; ++i) this._assetHolders[i].destroy();
this._sceneAssetHolder.destroy();
this._storageLoader = undefined;
this.game = undefined!;
this.state = "destroyed";
this.onStateChange.fire(this.state);
this.onStateChange.destroy();
}
/**
* 破棄済みであるかを返す。
*/
destroyed(): boolean {
return this.game === undefined;
}
/**
* 一定間隔で定期的に処理を実行するTimerを作成して返す。
*
* 戻り値は作成されたTimerである。
* 通常は `Scene#setInterval` を利用すればよく、ゲーム開発者がこのメソッドを呼び出す必要はない。
* `Timer` はフレーム経過処理(`Scene#onUpdate`)で実現される疑似的なタイマーである。実時間の影響は受けない。
* @param interval Timerの実行間隔(ミリ秒)
*/
createTimer(interval: number): Timer {
return this._timer.createTimer(interval);
}
/**
* Timerを削除する。
* @param timer 削除するTimer
*/
deleteTimer(timer: Timer): void {
this._timer.deleteTimer(timer);
}
/**
* 一定間隔で定期的に実行される処理を作成する。
*
* `interval` ミリ秒おきに `owner` を `this` として `handler` を呼び出す。
* 戻り値は `Scene#clearInterval` の引数に指定して定期実行を解除するために使える値である。
* このタイマーはフレーム経過処理(`Scene#onUpdate`)で実現される疑似的なタイマーである。実時間の影響は受けない。
* 関数は指定時間の経過直後ではなく、経過後最初のフレームで呼び出される。
* @param handler 処理
* @param interval 実行間隔(ミリ秒)
* @param owner handlerの所有者。省略された場合、null
*/
setInterval(handler: () => void, interval: number, owner?: any): TimerIdentifier {
return this._timer.setInterval(handler, interval, owner);
}
/**
* setIntervalで作成した定期処理を解除する。
* @param identifier 解除対象
*/
clearInterval(identifier: TimerIdentifier): void {
this._timer.clearInterval(identifier);
}
/**
* 一定時間後に一度だけ実行される処理を作成する。
*
* `milliseconds` ミリ秒後(以降)に、一度だけ `owner` を `this` として `handler` を呼び出す。
* 戻り値は `Scene#clearTimeout` の引数に指定して処理を削除するために使える値である。
*
* このタイマーはフレーム経過処理(`Scene#onUpdate`)で実現される疑似的なタイマーである。実時間の影響は受けない。
* 関数は指定時間の経過直後ではなく、経過後最初のフレームで呼び出される。
* (理想的なケースでは、30FPSなら50msのコールバックは66.6ms時点で呼び出される)
* 時間経過に対して厳密な処理を行う必要があれば、自力で `Scene#onUpdate` 通知を処理すること。
*
* @param handler 処理
* @param milliseconds 時間(ミリ秒)
* @param owner handlerの所有者。省略された場合、null
*/
setTimeout(handler: () => void, milliseconds: number, owner?: any): TimerIdentifier {
return this._timer.setTimeout(handler, milliseconds, owner);
}
/**
* setTimeoutで作成した処理を削除する。
* @param identifier 解除対象
*/
clearTimeout(identifier: TimerIdentifier): void {
this._timer.clearTimeout(identifier);
}
/**
* このシーンが現在のシーンであるかどうかを返す。
*/
isCurrentScene(): boolean {
return this.game.scene() === this;
}
/**
* 次のシーンへの遷移を要求する。
*
* このメソッドは、 `toPush` が真ならば `Game#pushScene()` の、でなければ `Game#replaceScene` のエイリアスである。
* このメソッドは要求を行うだけである。呼び出し直後にはシーン遷移は行われていないことに注意。
* このシーンが現在のシーンでない場合、 `AssertionError` がthrowされる。
* @param next 遷移後のシーン
* @param toPush 現在のシーンを残したままにするなら真、削除して遷移するなら偽を指定する。省略された場合偽
*/
gotoScene(next: Scene, toPush?: boolean): void {
if (!this.isCurrentScene()) throw ExceptionFactory.createAssertionError("Scene#gotoScene: this scene is not the current scene");
if (toPush) {
this.game.pushScene(next);
} else {
this.game.replaceScene(next);
}
}
/**
* このシーンの削除と、一つ前のシーンへの遷移を要求する。
*
* このメソッドは `Game#popScene()` のエイリアスである。
* このメソッドは要求を行うだけである。呼び出し直後にはシーン遷移は行われていないことに注意。
* このシーンが現在のシーンでない場合、 `AssertionError` がthrowされる。
*/
end(): void {
if (!this.isCurrentScene()) throw ExceptionFactory.createAssertionError("Scene#end: this scene is not the current scene");
this.game.popScene();
}
/**
* このSceneにエンティティを登録する。
*
* このメソッドは各エンティティに対して暗黙に呼び出される。ゲーム開発者がこのメソッドを明示的に呼び出す必要はない。
* @param e 登録するエンティティ
*/
register(e: E): void {
this.game.register(e);
e.scene = this;
}
/**
* このSceneからエンティティの登録を削除する。
*
* このメソッドは各エンティティに対して暗黙に呼び出される。ゲーム開発者がこのメソッドを明示的に呼び出す必要はない。
* @param e 登録を削除するエンティティ
*/
unregister(e: E): void {
// @ts-ignore
e.scene = undefined;
this.game.unregister(e);
}
/**
* 子エンティティを追加する。
*
* `this.children` の末尾に `e` を追加する(`e` はそれまでに追加されたすべての子エンティティより手前に表示される)。
*
* @param e 子エンティティとして追加するエンティティ
*/
append(e: E): void {
this.insertBefore(e, undefined);
}
/**
* 子エンティティを挿入する。
*
* `this.children` の`target`の位置に `e` を挿入する。
* `target` が`this` の子でない場合、`append(e)`と同じ動作となる。
*
* @param e 子エンティティとして追加するエンティティ
* @param target 挿入位置にある子エンティティ
*/
insertBefore(e: E, target: E | undefined): void {
if (e.parent) e.remove();
e.parent = this;
var index = -1;
if (target !== undefined && (index = this.children.indexOf(target)) > -1) {
this.children.splice(index, 0, e);
} else {
this.children.push(e);
}
this.modified(true);
}
/**
* 子エンティティを削除する。
* `this` の子から `e` を削除する。 `e` が `this` の子でない場合、何もしない。
* @param e 削除する子エンティティ
*/
remove(e: E): void {
var index = this.children.indexOf(e);
if (index === -1) return;
this.children[index].parent = undefined;
this.children.splice(index, 1);
this.modified(true);
}
/**
* シーン内でその座標に反応する `PointSource` を返す。
* @param point 対象の座標
* @param force touchable指定を無視する場合真を指定する。指定されなかった場合偽
* @param camera 対象のカメラ。指定されなかった場合undefined
*/
findPointSourceByPoint(point: CommonOffset, force?: boolean, camera?: Camera): PointSource {
const mayConsumeLocalTick = this.local !== "non-local";
const children = this.children;
const m = camera && camera instanceof Camera2D ? camera.getMatrix() : undefined;
for (var i = children.length - 1; i >= 0; --i) {
const ret = children[i].findPointSourceByPoint(point, m, force);
if (ret) {
ret.local = (ret.target && ret.target.local) || mayConsumeLocalTick;
return ret;
}
}
return { target: undefined, point: undefined, local: mayConsumeLocalTick };
}
/**
* アセットの先読みを要求する。
*
* `Scene` に必要なアセットは、通常、`Game#pushScene()` などによるシーン遷移にともなって暗黙に読み込みが開始される。
* ゲーム開発者はこのメソッドを呼び出すことで、シーン遷移前にアセット読み込みを開始する(先読みする)ことができる。
* 先読み開始後、シーン遷移時までに読み込みが完了していない場合、通常の読み込み処理同様にローディングシーンが表示される。
*
* このメソッドは `StorageLoader` についての先読み処理を行わない点に注意。
* ストレージの場合、書き込みが行われる可能性があるため、順序を無視して先読みすることはできない。
*/
prefetch(): void {
if (this._loaded) {
// _load() 呼び出し後に prefetch() する意味はない(先読みではない)。
return;
}
if (this._prefetchRequested) return;
this._prefetchRequested = true;
this._sceneAssetHolder.request();
}
/**
* シーンが読み込んだストレージの値をシリアライズする。
*
* `Scene#storageValues` の内容をシリアライズする。
*/
serializeStorageValues(): StorageValueStoreSerialization {
if (!this._storageLoader) return undefined;
return this._storageLoader._valueStoreSerialization;
}
requestAssets(assetIds: (string | DynamicAssetConfiguration)[], handler: SceneRequestAssetHandler): void {
if (this._loadingState !== "ready-fired" && this._loadingState !== "loaded-fired") {
// このメソッドは読み込み完了前には呼び出せない。これは実装上の制限である。
// やろうと思えば _load() で読み込む対象として加えることができる。が、その場合 `handler` を呼び出す方法が単純でないので対応を見送る。
throw ExceptionFactory.createAssertionError("Scene#requestAsset(): can be called after loaded.");
}
var holder = new AssetHolder<SceneRequestAssetHandler>({
assetManager: this.game._assetManager,
assetIds: assetIds,
handlerSet: {
owner: this,
handleLoad: this._handleSceneAssetLoad,
handleLoadFailure: this._handleSceneAssetLoadFailure,
handleFinish: this._handleSceneAssetLoadFinish
},
userData: () => {
// 不要なクロージャは避けたいが生存チェックのため不可避
if (!this.destroyed()) handler();
}
});
this._assetHolders.push(holder);
holder.request();
}
/**
* @private
*/
_activate(): void {
this.state = "active";
this.onStateChange.fire(this.state);
}
/**
* @private
*/
_deactivate(): void {
this.state = "deactive";
this.onStateChange.fire(this.state);
}
/**
* @private
*/
_needsLoading(): boolean {
return this._sceneAssetHolder.waitingAssetsCount > 0 || (!!this._storageLoader && !this._storageLoader._loaded);
}
/**
* @private
*/
_load(): void {
if (this._loaded) return;
this._loaded = true;
var needsWait = this._sceneAssetHolder.request();
if (this._storageLoader) {
this._storageLoader._load(this);
needsWait = true;
}
if (!needsWait) this._notifySceneReady();
}
/**
* @private
*/
_handleSceneAssetLoad(asset: Asset): void {
this.assets[asset.id] = asset;
this.onAssetLoad.fire(asset);
this.onAssetLoadComplete.fire(asset);
}
/**
* @private
*/
_handleSceneAssetLoadFailure(failureInfo: AssetLoadFailureInfo): void {
this.onAssetLoadFailure.fire(failureInfo);
this.onAssetLoadComplete.fire(failureInfo.asset);
}
/**
* @private
*/
_handleSceneAssetLoadFinish(holder: AssetHolder<SceneRequestAssetHandler>, succeed: boolean): void {
if (!succeed) {
this.game.terminateGame();
return;
}
// 動的アセット (`requestAssets()` 由来) の場合
if (holder.userData) {
this.game._pushPostTickTask(holder.userData, null);
return;
}
if (!this._loaded) {
// prefetch() で開始されたアセット読み込みを完了したが、_load() がまだ呼ばれていない。
// _notifySceneReady() は _load() 呼び出し後まで遅延する。
return;
}
if (this._storageLoader && !this._storageLoader._loaded) {
// アセット読み込みを完了したが、ストレージの読み込みが終わっていない。
// _notifySceneReady() は _onStorageLoaded() 呼び出し後まで遅延する。
return;
}
this._notifySceneReady();
}
/**
* @private
*/
_onStorageLoadError(_error: StorageLoadError): void {
this.game.terminateGame();
}
/**
* @private
*/
_onStorageLoaded(): void {
if (this._sceneAssetHolder.waitingAssetsCount === 0) this._notifySceneReady();
}
/**
* @private
*/
_notifySceneReady(): void {
// 即座に `_onReady` をfireすることはしない。tick()のタイミングで行うため、リクエストをgameに投げておく。
this._loadingState = "ready";
this.game._pushPostTickTask(this._fireReady, this);
}
/**
* @private
*/
_fireReady(): void {
if (this.destroyed()) return;
this._onReady.fire(this);
this._loadingState = "ready-fired";
}
/**
* @private
*/
_fireLoaded(): void {
if (this.destroyed()) return;
if (this._loadingState === "loaded-fired") return;
this.onLoad.fire(this);
this._loadingState = "loaded-fired";
}
} | the_stack |
import {ComplexFilter} from '../browser';
const {join} = require('path');
const assetDir = join(__dirname, '..', '..', 'assets');
export interface Testcase {
name: string;
assets: string[];
filters: ComplexFilter[];
}
const generateFontTests = (fontFile: string): Testcase[] => {
return [
{
name: `drawtext ${fontFile}`,
assets: [join(assetDir, 'servers.png')],
filters: [
{
name: 'drawtext',
args: {
fontfile: `./assets/${fontFile}`,
text: "it's not, me",
x: 0,
y: 10,
fontsize: '70',
fontcolor: 'black',
},
},
],
},
{
name: `drawtext-with-background ${fontFile}`,
assets: [join(assetDir, 'servers.png')],
filters: [
{
name: 'drawtext',
args: {
fontfile: `./assets/${fontFile}`,
text: "it's not, me",
x: 15,
y: 15,
fontsize: '70',
fontcolor: 'black',
box: 1,
boxcolor: 'pink',
boxborderw: 10,
},
},
],
},
];
};
export const testcases: Testcase[] = [
{
name: `drawtext-special-chars`,
assets: [join(assetDir, 'servers.png')],
filters: [
{
name: 'drawtext',
args: {
fontfile: `./assets/Verdana.ttf`,
text: "Jason's \"friend\": it's, not you/me; it's you",
x: 0,
y: 10,
fontsize: '18',
fontcolor: 'black',
},
},
],
},
{
name: 'drawbox-simple',
assets: [join(assetDir, 'image.jpg'), join(assetDir, 'servers.png')],
filters: [
{
inputs: ['0'],
name: 'drawbox',
args: {
x: 10,
y: 10,
w: 500,
h: 300,
color: 'pink',
t: 'fill',
},
},
],
},
{
name: 'drawbox-rotated',
assets: [join(assetDir, 'image.jpg'), join(assetDir, 'empty.png')],
filters: [
{
inputs: ['1'],
name: 'scale',
args: {
w: 500,
h: 300,
},
outputs: ['scaled'],
},
{
inputs: ['scaled'],
name: 'drawbox',
args: {
x: 0,
y: 0,
w: 500,
h: 300,
color: '#ffffff',
t: 'fill',
replace: 1, // required to draw on transparent png
},
outputs: ['box'],
},
{
inputs: ['box'],
name: 'rotate',
args: {
angle: 1,
fillcolor: '#00000000',
},
outputs: ['rotated'],
},
{
inputs: ['0', 'rotated'],
name: 'overlay',
args: {
format: 'rgb',
x: 40,
y: 40,
},
},
],
},
{
name: 'overlay-simple',
assets: [join(assetDir, 'image.jpg'), join(assetDir, 'servers.png')],
filters: [
{
inputs: ['0', '1'],
name: 'overlay',
args: {
format: 'rgb',
x: 0,
y: 0,
},
},
],
},
{
name: 'overlay-with-offset',
assets: [join(assetDir, 'image.jpg'), join(assetDir, 'servers.png')],
filters: [
{
inputs: ['0', '1'],
name: 'overlay',
args: {
format: 'rgb',
x: 50,
y: 50,
},
},
],
},
{
name: 'overlay-out-of-bounds',
assets: [join(assetDir, 'image.jpg'), join(assetDir, 'servers.png')],
filters: [
{
inputs: ['0', '1'],
name: 'overlay',
args: {
format: 'rgb',
x: -30,
y: -30,
},
},
],
},
{
name: 'overlay-multiple',
assets: [
join(assetDir, 'image.jpg'),
join(assetDir, 'servers.png'),
join(assetDir, 'servers.png'),
join(assetDir, 'servers.png'),
join(assetDir, 'servers.png'),
],
filters: [
{
inputs: ['0', '1'],
name: 'overlay',
args: {
format: 'rgb',
x: 50,
y: 50,
},
outputs: ['out1'],
},
{
inputs: ['out1', '2'],
name: 'overlay',
args: {
format: 'rgb',
x: 150,
y: 150,
},
outputs: ['out2'],
},
{
inputs: ['out2', '3'],
name: 'overlay',
args: {
format: 'rgb',
x: 250,
y: 250,
},
outputs: ['out3'],
},
{
inputs: ['out3', '4'],
name: 'overlay',
args: {
format: 'rgb',
x: 350,
y: 350,
},
},
],
},
{
name: 'scale-simple',
assets: [join(assetDir, 'image.jpg'), join(assetDir, 'servers.png')],
filters: [
{
inputs: ['1'],
name: 'scale',
args: {
w: 300,
h: 300,
},
outputs: ['scaled'],
},
{
inputs: ['0', 'scaled'],
name: 'overlay',
args: {
format: 'rgb',
x: 100,
y: 100,
},
},
],
},
{
name: 'scale-twice',
assets: [join(assetDir, 'image.jpg'), join(assetDir, 'servers.png')],
filters: [
{
inputs: ['1'],
name: 'scale',
args: {
w: 40,
h: 40,
},
outputs: ['scaled1'],
},
{
inputs: ['scaled1'],
name: 'scale',
args: {
w: 400,
h: 400,
},
outputs: ['scaled2'],
},
{
inputs: ['0', 'scaled2'],
name: 'overlay',
args: {
format: 'rgb',
x: 10,
y: 10,
},
},
],
},
{
name: 'rotate',
assets: [join(assetDir, 'image.jpg'), join(assetDir, 'servers.png')],
filters: [
{
inputs: ['1'],
name: 'rotate',
args: {
angle: 1,
},
outputs: ['rotated'],
},
{
inputs: ['0', 'rotated'],
name: 'overlay',
args: {
x: 0,
y: 0,
format: 'rgb',
},
},
],
},
{
name: 'rotate-with-positive-padding',
assets: [join(assetDir, 'image.jpg'), join(assetDir, 'servers.png')],
filters: [
{
inputs: ['1'],
name: 'rotate',
args: {
angle: 1,
out_w: 600,
out_h: 600,
},
outputs: ['rotated'],
},
{
inputs: ['0', 'rotated'],
name: 'overlay',
args: {
x: 0,
y: 0,
format: 'rgb',
},
},
],
},
{
name: 'rotate-with-negative-padding',
assets: [join(assetDir, 'image.jpg'), join(assetDir, 'servers.png')],
filters: [
{
inputs: ['1'],
name: 'rotate',
args: {
angle: 1,
out_w: 100,
out_h: 100,
},
outputs: ['rotated'],
},
{
inputs: ['0', 'rotated'],
name: 'overlay',
args: {
x: 0,
y: 0,
format: 'rgb',
},
},
],
},
{
name: 'rotate-transparent-bg',
assets: [join(assetDir, 'image.jpg'), join(assetDir, 'servers.png')],
filters: [
{
inputs: ['1'],
name: 'rotate',
args: {
angle: 1,
out_w: 600,
out_h: 600,
fillcolor: '#0077ff7f',
},
outputs: ['rotated'],
},
{
inputs: ['0', 'rotated'],
name: 'overlay',
args: {
x: 0,
y: 0,
format: 'rgb',
},
},
],
},
{
name: 'loop-noop',
assets: [join(assetDir, 'image.jpg'), join(assetDir, 'servers.png')],
filters: [
{
inputs: ['1'],
name: 'loop',
args: {
loop: 3,
},
outputs: ['looped'],
},
{
inputs: ['0', 'looped'],
name: 'overlay',
args: {
x: 0,
y: 0,
format: 'rgb',
},
},
],
},
{
name: 'pad-transparent-bg',
assets: [join(assetDir, 'image.jpg'), join(assetDir, 'servers.png')],
filters: [
{
inputs: ['1'],
name: 'pad',
args: {
w: 600,
h: 400,
x: 20,
y: 20,
color: '#00000000',
},
outputs: ['padded'],
},
{
inputs: ['0', 'padded'],
name: 'overlay',
args: {
x: 0,
y: 0,
format: 'rgb',
},
},
],
},
{
name: 'pad-default-bg',
assets: [join(assetDir, 'image.jpg'), join(assetDir, 'servers.png')],
filters: [
{
inputs: ['1'],
name: 'pad',
args: {
w: 600,
h: 400,
x: 20,
y: 20,
},
outputs: ['padded'],
},
{
inputs: ['0', 'padded'],
name: 'overlay',
args: {
x: 0,
y: 0,
format: 'rgb',
},
},
],
},
{
name: 'pad-red-bg',
assets: [join(assetDir, 'image.jpg'), join(assetDir, 'servers.png')],
filters: [
{
inputs: ['1'],
name: 'pad',
args: {
w: 600,
h: 400,
x: 20,
y: 20,
color: '#ff0000',
},
outputs: ['padded'],
},
{
inputs: ['0', 'padded'],
name: 'overlay',
args: {
x: 0,
y: 0,
format: 'rgb',
},
},
],
},
{
name: 'pad-transparent-png',
assets: [join(assetDir, 'image.jpg'), join(assetDir, 'threads-logo-gold.png')],
filters: [
{
inputs: ['1'],
name: 'pad',
args: {
w: 600,
h: 400,
x: 20,
y: 20,
color: '#0000ff',
},
outputs: ['padded'],
},
{
inputs: ['0', 'padded'],
name: 'overlay',
args: {
x: 0,
y: 0,
format: 'rgb',
},
},
],
},
...generateFontTests('Verdana.ttf'),
...generateFontTests('Notable-Regular.ttf'),
// failing because of font weight and letter spacing issues
// ...generateFontTests('Berthold Akzidenz Grotesk Bold Condensed.otf'),
// ...generateFontTests('DomaineDisplay-Regular.otf'),
{
name: 'drawtext-rotated',
assets: [join(assetDir, 'servers.png'), join(assetDir, 'empty.png')],
filters: [
{
inputs: ['1'],
name: 'scale',
args: {
w: 300,
h: 300,
},
outputs: ['scaled'],
},
{
inputs: ['scaled'],
name: 'drawtext',
args: {
fontfile: './assets/Verdana.ttf',
text: 'SOME TEXT',
x: 15,
y: 15,
fontsize: 70,
fontcolor: 'black',
box: 1,
boxcolor: 'pink',
boxborderw: 10,
},
outputs: ['txt'],
},
{
inputs: ['txt'],
name: 'drawbox',
args: {
x: 20,
y: 70,
w: 200,
h: 5,
color: '#000000',
t: 'fill',
replace: 1,
},
outputs: ['underline'],
},
{
inputs: ['underline'],
name: 'rotate',
args: {
angle: 1,
fillcolor: '#00000000',
},
outputs: ['rotated'],
},
{
inputs: ['0', 'rotated'],
name: 'overlay',
args: {
format: 'rgb',
x: 10,
y: 10,
},
},
],
},
{
name: 'drawtext-expr-tw',
assets: [join(assetDir, 'servers.png')],
filters: [
{
name: 'drawtext',
args: {
fontfile: './assets/Verdana.ttf',
text: 'SOME TEXT',
x: '(0 - tw / 2)',
y: '15',
fontsize: 70,
fontcolor: 'black',
box: 1,
boxcolor: 'pink',
boxborderw: 10,
},
},
],
},
{
name: 'drawtext-expr-th',
assets: [join(assetDir, 'servers.png')],
filters: [
{
name: 'drawtext',
args: {
fontfile: './assets/Verdana.ttf',
text: 'LOL - the bear is not a fox',
x: '15',
y: '(50 - th / 2)',
fontsize: 70,
fontcolor: 'black',
box: 1,
boxcolor: 'pink',
boxborderw: 10,
},
},
],
},
{
name: 'drawtext-center-at-origin',
assets: [join(assetDir, 'servers.png')],
filters: [
{
name: 'drawtext',
args: {
fontfile: './assets/Verdana.ttf',
text: 'O',
x: '(0 - tw / 2)',
y: '(0 - th / 2)',
fontsize: 100,
fontcolor: 'red',
},
},
{
name: 'drawtext',
args: {
fontfile: './assets/Verdana.ttf',
text: 'A',
x: '(33 - tw / 2)',
y: '(33 - th / 2)',
fontsize: 70,
fontcolor: 'green',
},
},
],
},
{
name: 'drawtext-with-rotation',
assets: [join(assetDir, 'servers.png'), join(assetDir, 'empty.png')],
filters: [
{
inputs: ['1'],
name: 'scale',
args: {
w: 70,
h: 70,
},
outputs: ['scaled'],
},
{
inputs: ['scaled'],
name: 'drawtext',
args: {
fontfile: './assets/Verdana.ttf',
text: 'M',
x: '(35 - tw / 2)',
y: '(35 - th / 2)',
fontsize: 70,
fontcolor: 'green',
},
outputs: ['txt'],
},
{
inputs: ['txt'],
name: 'rotate',
args: {
angle: Math.PI / 2,
fillcolor: '#00000000',
},
outputs: ['rotated'],
},
{
inputs: ['0', 'rotated'],
name: 'overlay',
args: {
format: 'rgb',
x: 0,
y: 0,
},
},
],
},
]; | the_stack |
import React, {
ReactNode,
useRef,
useState,
useCallback,
useEffect,
useContext,
useLayoutEffect,
} from 'react'
import cn from 'classnames'
import { useTabState, Tab, TabList, TabPanel } from 'reakit/Tab'
import { useWindowSize, useIsomorphicLayoutEffect } from 'react-use'
import {
Text,
Stack,
Box,
Button,
GridContainer,
GridRow,
GridColumn,
Link,
} from '@island.is/island-ui/core'
import { Slice as SliceType, richText } from '@island.is/island-ui/contentful'
import { deorphanize } from '@island.is/island-ui/utils'
import { useI18n } from '../../i18n'
import { helperStyles, theme } from '@island.is/island-ui/theme'
import { GlobalContext } from '@island.is/web/context'
import { useNamespace } from '@island.is/web/hooks'
import LottieLoader from './LottiePlayer/LottieLoader'
import { useLinkResolver } from '@island.is/web/hooks/useLinkResolver'
import * as styles from './FrontpageSlider.css'
import { FrontpageSlider as FrontpageSliderType } from '@island.is/web/graphql/schema'
import fetch from 'isomorphic-fetch'
export interface FrontpageSliderProps {
slides: FrontpageSliderType[]
searchContent: ReactNode
}
export interface TabBulletProps {
selected?: boolean
}
const TabBullet = ({ selected }: TabBulletProps) => {
return (
<span
className={cn(styles.tabBullet, {
[styles.tabBulletSelected]: selected,
})}
/>
)
}
export const FrontpageSlider = ({
slides,
searchContent,
}: FrontpageSliderProps) => {
const { globalNamespace } = useContext(GlobalContext)
const gn = useNamespace(globalNamespace)
const contentRef = useRef(null)
const [minHeight, setMinHeight] = useState<number>(0)
const itemRefs = useRef<Array<HTMLElement | null>>([])
const [selectedIndex, setSelectedIndex] = useState<number>(0)
const [animationData, setAnimationData] = useState([])
const timerRef = useRef(null)
const tab = useTabState({
baseId: 'frontpage-tab',
})
const { t } = useI18n()
const { width } = useWindowSize()
const isMobile = width < theme.breakpoints.md
useEffect(() => {
const newSelectedIndex = tab.items.findIndex((x) => x.id === tab.currentId)
setSelectedIndex(newSelectedIndex)
}, [tab])
const { linkResolver } = useLinkResolver()
const goTo = (direction: string) => {
switch (direction) {
case 'prev':
tab.previous()
break
case 'next':
tab.next()
break
default:
break
}
}
const generateUrls = (link: string) => {
if (link) {
const linkData = JSON.parse(link)
const contentId = linkData.sys?.contentType?.sys?.id
const slug = String(linkData.fields?.slug)
if (slug) {
// the need for this check is caused by miss match in cache typename and cms typename
// TODO: Make CMS get this content from cache to standardize type
let type
if (contentId === 'vidspyrna-frontpage') {
type = 'adgerdirfrontpage'
} else {
type = contentId
}
return linkResolver(type, [slug])
}
return null
}
}
useLayoutEffect(() => {
if (!isMobile && !animationData.length) {
const requests = slides.reduce((all, slide) => {
if (slide.animationJsonAsset && slide.animationJsonAsset.url) {
all.push(
fetch(slide.animationJsonAsset.url).then((res) => res.json()),
)
}
return all
}, [])
Promise.all(requests).then((res) => {
setAnimationData(res)
})
}
}, [isMobile, slides, animationData])
const onResize = useCallback(() => {
setMinHeight(0)
let height = 0
itemRefs.current.forEach((item) => {
if (item) {
height =
width < theme.breakpoints.md
? Math.min(height, item.offsetHeight)
: Math.max(height, item.offsetHeight)
}
})
setMinHeight(height)
}, [width, itemRefs])
useIsomorphicLayoutEffect(() => {
timerRef.current = setTimeout(onResize, 5000)
window.addEventListener('resize', onResize)
return () => {
clearTimeout(timerRef.current)
window.removeEventListener('resize', onResize)
}
}, [onResize])
useIsomorphicLayoutEffect(() => {
const el = itemRefs.current[selectedIndex]
if (el) {
const spans = el.getElementsByClassName(styles.textItem)
Array.prototype.forEach.call(spans, (span, index) => {
const ms = index * 100
span.style.transitionDelay = `${ms}ms`
})
}
}, [selectedIndex])
return (
<GridContainer>
<GridRow className={styles.tabPanelRow}>
<GridColumn hiddenBelow="lg" span="1/12" />
<GridColumn span={['12/12', '12/12', '7/12', '6/12']} position="static">
<Box ref={contentRef}>
<TabList
{...tab}
aria-label={t.carouselTitle}
className={styles.tabWrapper}
>
{slides.map(({ title = '' }, index) => {
return (
<Tab key={index} {...tab} className={styles.tabContainer}>
<TabBullet selected={selectedIndex === index} />
<span className={helperStyles.srOnly}>{title}</span>
</Tab>
)
})}
</TabList>
<Box className={styles.tabPanelWrapper}>
{slides.map(
({ title, subtitle, content, intro, link }, index) => {
const linkUrls = generateUrls(link)
// If none are found (during SSR) findIndex returns -1. We want 0 instead.
const currentIndex = Math.max(
tab.items.findIndex((x) => x.id === tab.currentId),
0,
)
const visible = currentIndex === index
const tabTitleId = 'frontpageTabTitle' + index
return (
<TabPanel
key={index}
{...tab}
style={{
display: 'block',
}}
tabIndex={visible ? 0 : -1}
className={cn(styles.tabPanel, {
[styles.tabPanelVisible]: visible,
})}
>
{visible && (
<Box
marginY={3}
ref={(el) => (itemRefs.current[index] = el)}
style={{ minHeight: `${minHeight}px` }}
>
<Stack space={3}>
<Text variant="eyebrow" color="purple400">
<span
className={cn(styles.textItem, {
[styles.textItemVisible]: visible,
})}
>
{subtitle}
</span>
</Text>
<Text variant="h1" as="h1" id={tabTitleId}>
<span
className={cn(styles.textItem, {
[styles.textItemVisible]: visible,
})}
>
{deorphanize(title)}
</span>
</Text>
{intro ? (
<Box marginBottom={4}>
{richText(
[
{
__typename: 'Html',
id: intro.id,
document: intro.document,
},
] as SliceType[],
undefined,
)}
</Box>
) : (
<Text>
<span
className={cn(styles.textItem, {
[styles.textItemVisible]: visible,
})}
>
{content}
</span>
</Text>
)}
{linkUrls?.href && visible ? (
<span
className={cn(styles.textItem, {
[styles.textItemVisible]: visible,
})}
>
<Link {...linkUrls} skipTab>
<Button
variant="text"
icon="arrowForward"
aria-labelledby={tabTitleId}
as="span"
>
{gn('seeMore')}
</Button>
</Link>
</span>
) : null}
</Stack>
</Box>
)}
</TabPanel>
)
},
)}
</Box>
</Box>
<GridColumn hiddenBelow="lg" position="static">
<Box
display="flex"
height="full"
alignItems="center"
className={styles.tabListArrowLeft}
>
<Button
circle
colorScheme="light"
icon="arrowBack"
iconType="filled"
aria-label={t.frontpageTabsPrevious}
onClick={() => goTo('prev')}
type="button"
variant="primary"
/>
</Box>
<Box
display="flex"
height="full"
justifyContent="flexEnd"
alignItems="center"
className={styles.tabListArrowRight}
>
<Button
circle
colorScheme="light"
icon="arrowForward"
iconType="filled"
aria-label={t.frontpageTabsNext}
onClick={() => goTo('next')}
type="button"
variant="primary"
/>
</Box>
</GridColumn>
<Box
display="inlineFlex"
alignItems="center"
width="full"
background="blue100"
paddingTop={[4, 4, 5]}
paddingBottom={4}
paddingX={[3, 3, 4]}
className={styles.searchContentContainer}
>
{searchContent}
</Box>
</GridColumn>
<GridColumn hiddenBelow="md" span={['0', '0', '5/12', '4/12']}>
<Box
display="flex"
flexDirection="column"
height="full"
justifyContent="center"
>
{!isMobile && animationData.length > 0 && (
<LottieLoader
animationData={animationData}
selectedIndex={selectedIndex}
/>
)}
</Box>
</GridColumn>
<GridColumn hiddenBelow="lg" span="1/12" />
</GridRow>
</GridContainer>
)
}
export default FrontpageSlider | the_stack |
import { getExt } from "./utils.files";
import {
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, oga, ogv, ogx, 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
} from "./IconFiles";
const DEF_GEN_MIME: string = "octet";
/**
*
* @param tailMime
* @returns
*/
export const audioSelector = (tailMime: string): string => {
switch (tailMime) {
case "aac": return "aac";
case "midi": return "midi";
case "x-midi": return "midi";
case "mpeg": return "mpeg";//mp3
case "ogg": return "oga";
case "opus": return "opus";
case "wav": return "wav";
case "webm": return "webm";
//case "3gpp": return "threegp";
//case "3gpp2": return "threegp";
//case "mp3": return "mp3";
case "wma": return "wma";
default: return DEF_GEN_MIME;
}
}
export const textSelector = (tailMime: string): string => {
switch (tailMime) {
case "css": return "css";
case "csv": return "csv";
case "html": return "html";
case "calendar": return "icalendar";
case "javascript": return "javascript";
case "x-javascript": return "javascript";
case "plain": return "text";
case "xml": return "xml";
default: return DEF_GEN_MIME;
}
}
export const imageSelector = (tailMime: string): string => {
switch (tailMime) {
case "bmp": return "bmp";
case "gif": return "gif";
// case "vnd.microsoft.icon": return "ico";
case "ico": return "ico";
case "jpg": return "jpeg";
case "jpeg": return "jpeg";
case "png": return "png";
//case "svg+xml": return "svg";
//case "svg": return "svg";
case "tiff": return "tiff";
case "webp": return "webp";
default: return DEF_GEN_MIME;
}
}
export const fontSelector = (tailMime: string): string => {
switch (tailMime) {
case "otf": return "otf";
case "ttf": return "ttf";
case "woff": return "woff";
case "woff2": return "woff";
default: return DEF_GEN_MIME;
}
}
export const videoSelector = (tailMime: string): string => {
switch (tailMime) {
case "x-msvideo": return "avi";
case "msvideo": return "avi";
case "avi": return "avi";
case "mp4": return "mp4";
case "mpeg": return "mpeg";
case "ogg": return "ogv";
case "mp2t": return "mp2t";
case "wmv": return "wmv";
case "webm": return "webm";
// case "3gpp": return "threegp";
// case "3gpp2": return "threegp2";
default: return DEF_GEN_MIME;
}
}
/**
*
* @param tailMime
* @returns
*/
export const applicationSelector = (tailMime: string): string => {
switch (tailMime) {
case "x-abiword": return "abw";
case "abiword": return "abw";
case "x-freearc": return "arc";
case "freearc": return "arc";
case "vnd.amazon.ebook": return "azw";
case "octet-stream": return "octet";
case "x-bzip": return "bz";
case "x-bzip2": return "bz2";
case "bzip": return "bz";
case "bzip2": return "bz2";
case "x-cdf": return "cda";
case "msaccess": return "accdb";
case "csh": return "csh";
case "x-csh": return "csh";
case "vnd.ms-fontobject": return "eot";
case "epub+zip": return "epub";
case "gzip": return "gzip";
case "java-archive": return "jar";
case "x-javascript": return "javascript";
case "json": return "json";
case "ld+json": return "jsonld";
case "vnd.apple.installer+xml": return "mpkg";
case "ogg": return "ogx";
case "vnd.rar": return "rar";
case "rtf": return "rtf";
case "x-sh": return "sh";
case "sh": return "sh";
case "x-shockwave-flash": return "swf";
case "x-tar": return "tar";
case "x-httpd-php": return "php";
case "vnd.visio": return "vsd";
case "xhtml+xml": return "xhtml";
case "xml": return "xml";
case "vnd.mozilla.xul+xml": return "xul";
case "vnd.openxmlformats-officedocument.wordprocessingml.document": return "docx";
case "msword": return "docx";
case "vnd.openxmlformats-officedocument.spreadsheetml.sheet": return "xlsx";
case "vnd.openxmlformats-officedocument.presentationml.presentation": return "pptx";
case "vnd.ms-powerpoint": return "pptx";
case "vnd.oasis.opendocument.presentation": return "odp";
case "vnd.oasis.opendocument.text": return "odt";
case "vnd.oasis.opendocument.spreadsheet": return "ods";
case "zip": return "zip";
case "x-zip-compressed": return "zip";
case "pdf": return "pdf";
default: return DEF_GEN_MIME;
}
}
/**
* Selects to wich mime type the mime type given belongs to
* @param mimeType mime type to be searched
* @returns the generic type,
if not found it return "octet" that means generic binary file
*/
export const mimeSelector = (mimeType?: string): string => {
// let genericMime: string | undefined = undefined;
if (!mimeType || !mimeType.includes("/")) {
return DEF_GEN_MIME;
}
let headerMime = mimeType.split("/")[0];
let tailMime = mimeType.split("/")[1];
/**
* Every mimetype that
* starts with: "application/...."
*/
switch (headerMime) {
case "application": return applicationSelector(tailMime);
case "audio": return audioSelector(tailMime);
case "video": return videoSelector(tailMime);
case "text": return textSelector(tailMime);
case "image": return imageSelector(tailMime);
case "font": return fontSelector(tailMime);
default: return DEF_GEN_MIME;
}
}
/**
* Selects to wich mapped extension
* the given exension belongs to
*
* @param extension
* @returns
*/
export const extensionSelector = (extension?: string): string => {
let genericMime: string = "octet";
if (extension && extension !== "") {
if (extension.includes("zip") || extension.includes("rar")) {
genericMime = "zip";
} else if (extension.includes("doc")) {
genericMime = "docx";
} else if (extension.includes("xls")) {
genericMime = "xlsx";
} else if (extension.includes("drawio")) {
genericMime = "drawio";
} else if (extension.includes("psd")) {
genericMime = "psd";
} else if (extension.includes("csv")) {
genericMime = "csv";
} else if (extension === "jsx") {
genericMime = "react";
} else if (extension === "py") {
genericMime = "python";
} else if (extension === "vue") {
genericMime = "vue";
} else if (extension === "java") {
genericMime = "java";
} else if (extension === "ts") {
genericMime = "ts";
} else if (extension === "sass" || extension === "scss") {
genericMime = "sass";
}
}
return genericMime;
}
/**
* Chack for extention whether the file is code os not
* @param extension
* @returns
*/
export const checkIsCode = (extension?: string): string => {
let genericMime = "text";
if (extension && extension !== "") {
if (extension === "jsx") {
genericMime = "react";
} else if (extension === "py") {
genericMime = "python";
} else if (extension === "vue") {
genericMime = "vue";
} else if (extension === "java") {
genericMime = "java";
} else if (extension === "ts" || extension === "tsx") {
genericMime = "typescript";
} else if (extension === "js") {
genericMime = "javascript";
} else if (extension === "xml") {
genericMime = "xml";
} else if (extension === "php") {
genericMime = "php";
}
}
return genericMime;
}
/**
* Looks for a suitable file icon
* @param props mime and extension from file to search
* @returns the result file ico, if not found, turns octet-stream url
*/
export const getURLFileIco = (file: File | undefined): ResultFileIco => {
let result = "";
//if not file, return octet
if (!file) {
result = DEF_GEN_MIME;
return { url: mimeUrlList[result], mimeResume: result };
} else {
result = mimeSelector(file.type);
}
//If plain text
const extention: string = getExt(file.name);
if (result === "text") {
result = checkIsCode(extention);
}
//If octet stream result, second chance: file extention
if (result === DEF_GEN_MIME) {
result = extensionSelector(extention);
}
return { url: mimeUrlList[result], mimeResume: result };
}
interface ResultFileIco {
url: string;
mimeResume: string;
}
/**
* set of registered mimes on MDN
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
*
*/
interface MimeSelector {
[mime: string]: string;
}
const mimeUrlList: MimeSelector = {
img: "https://ssl.gstatic.com/docs/doclist/images/mediatype/icon_1_image_x16.png",
video: "https://ssl.gstatic.com/docs/doclist/images/mediatype/icon_1_video_x16.png",
audio: "https://ssl.gstatic.com/docs/doclist/images/mediatype/icon_1_audio_x16.png",
aac: aac,
accdb: accdb,
abw: abw,
arc: freearc,
avi: avi,
azw: azw,
octet: octet,
bmp: bmp,
bz: bz,
bz2: bz2,
cda: cda,
csh: csh,
css: css,
csv: csv,
docx: docx,
drawio: drawio,
eot: eot,
epub: epub,
gzip: gzip,
gif: gif,
html: html,
//ico: ico,
icalendar: icalendar,
jar: jar,
jpeg: jpeg,
javascript: javascript,
json: json,
jsonld: jsonld,
midi: midi,
// js: js,
mp3: mp3,
mp4: mp4,
mpeg: mpeg,
mpkg: mpkg,
mp2t: octet,
odp: odp,
ods: ods,
odt: odt,
oga: oga,
ogv: ogv,
ogx: ogx,
opus: opus,
otf: otf,
png: png,
pdf: pdf,
php: php,
pptx: pptx,
psd: psd,
rar: rar,
rtf: rtf,
sass: sass,
sh: sh,
//svg: svg,
swf: swf,
tar: tar,
tiff: tiff,
ttf: ttf,
//ts: ts,
typescript: typescript,
text: text,
vsd: vsd,
wav: wav,
weba: weba,
webm: webm,
webp: webp,
woff: woff,
wma: wma,
wmv: wmv,
xhtml: html,
xlsx: xlsx,
xml: xml,
xul: xul,
zip: zip,
// threegp: threegp,
sevenzip: sevenzip,
python: python,
java: java,
react: react,
vue: vue,
}; | the_stack |
import Protocol from 'devtools-protocol';
import {
RequestMapping,
ResponseMapping,
MappedEvent,
EventMapping,
EventPredicate,
MappedRequestMethod
} from 'chrome-debugging-client';
import { RaceCancellation } from 'race-cancellation';
export interface VersionStatusIdentifier {
status: Protocol.ServiceWorker.ServiceWorkerVersionStatus;
version?: string;
runningStatus?: Protocol.ServiceWorker.ServiceWorkerVersionRunningStatus;
}
type SerializedStateIdentifier = string;
function identifierFromVersion(v: Protocol.ServiceWorker.ServiceWorkerVersion): VersionStatusIdentifier {
return {
version: v.versionId,
status: v.status,
runningStatus: v.runningStatus
};
}
function serializeStateIdentifier({ version, status, runningStatus }:
VersionStatusIdentifier): SerializedStateIdentifier {
const sanitizedVersion = version ? version : '';
const sanitizedRunningStatus = runningStatus ? runningStatus : '';
const id = `${sanitizedVersion}:${status}:${sanitizedRunningStatus}`;
return id;
}
function addTimeout<T>(promise: Promise<T>, msg: string, timeout: number = 6000): Promise<T> {
const timedOut: Promise<T> = new Promise((_resolve, reject) => {
setTimeout(() => {
reject(new Error(msg));
}, timeout);
});
return Promise.race([promise, timedOut]);
}
class StateIdMap<V> extends Map<any, V> {
get(key: VersionStatusIdentifier) {
return super.get(serializeStateIdentifier(key));
}
set(key: VersionStatusIdentifier, value: V) {
return super.set(serializeStateIdentifier(key), value);
}
}
class StateIdArrayMap<V> extends Map<any, V[]> {
get(key: VersionStatusIdentifier) {
const versionQuery = super.get(serializeStateIdentifier(key));
const eventQuery = super.get(serializeStateIdentifier({
status: key.status,
runningStatus: key.runningStatus
}));
if (!versionQuery && !eventQuery) {
return;
}
return (versionQuery || []).concat(eventQuery || []);
}
set(key: VersionStatusIdentifier, value: V[]) {
return super.set(serializeStateIdentifier(key), value);
}
}
/**
* Interface for ServiceWorker class, generated by chrome-debugging-client, that represents
* the raw API for the ServiceWorker DevTools protocl domain
* @public
*/
/*
export interface IServiceWorker {
skipWaiting: (params: Protocol.ServiceWorker.SkipWaitingRequest) => Promise<void>;
workerErrorReported: Protocol.ServiceWorker.WorkerErrorReportedEvent | null;
workerRegistrationUpdated: Protocol.ServiceWorker.WorkerRegistrationUpdatedEvent | null;
workerVersionUpdated: Protocol.ServiceWorker.WorkerVersionUpdatedEvent | null;
// Set all the other methods as optional until we actually start using them
deliverPushMessage?: (params: Protocol.ServiceWorker.DeliverPushMessageRequest) => Promise<void>;
disable?: () => Promise<void>;
dispatchSyncEvent?: (params: Protocol.ServiceWorker.DispatchSyncEventRequest) => Promise<void>;
enable?: () => Promise<void>;
inspectWorker?: (params: Protocol.ServiceWorker.InspectWorkerRequest) => Promise<void>;
setForceUpdateOnPageLoad?: (params: Protocol.ServiceWorker.SetForceUpdateOnPageLoadRequest) => Promise<void>;
startWorker?: (params: Protocol.ServiceWorker.StartWorkerRequest) => Promise<void>;
stopAllWorkers?: () => Promise<void>;
stopWorker?: (params: Protocol.ServiceWorker.StopWorkerRequest) => Promise<void>;
unregister?: (params: Protocol.ServiceWorker.UnregisterRequest) => Promise<void>;
updateRegistration?: (params: Protocol.ServiceWorker.UpdateRegistrationRequest) => Promise<void>;
}
*/
type VersionListener = (v: Protocol.ServiceWorker.ServiceWorkerVersion) => void;
/*
class ServiceWorkerProtocolSession {
private core: Promise<ServiceWorkerCore>;
constructor(public targetId: string, clientP: Promise<IDebuggingProtocolClient>) {
this.core = clientP.then(async (client) => {
const networkDomain = new Network(client);
await networkDomain.enable({});
return {
client,
networkDomain
};
});
}
public async emulateOffline(offline: boolean) {
await this.core;
throw new Error('Offline emulation not working. See https://bugs.chromium.org/p/chromium/issues/detail?id=852127');
}
}
*/
/**
* ServiceWorkerState config options
* @internal
*/
export interface IServiceWorkerStateOptions {
log?: boolean;
}
export type ServiceWorkerErrorCallback = (err: Protocol.ServiceWorker.ServiceWorkerErrorMessage) => void;
export interface IPage {
send<M extends MappedRequestMethod>(
method: M,
request: RequestMapping[M],
raceCancellation?: RaceCancellation,
): Promise<ResponseMapping[M]>;
on<E extends MappedEvent>(
event: E,
listener: (event: EventMapping[E]) => void,
): void;
until<E extends MappedEvent>(
event: E,
predicate?: EventPredicate<EventMapping[E]>,
raceCancellation?: RaceCancellation,
): Promise<EventMapping[E]>;
}
/**
* Models the state of Service Workers for a particular client
* @remarks
* Effectively a wrapper around the {@link https://chromedevtools.github.io/devtools-protocol/tot/ServiceWorker
* | ServiceWorker} domain of the Chrome DevTools Protocol.
* @internal
*/
export class ServiceWorkerState {
private versions: Map<number, Protocol.ServiceWorker.ServiceWorkerVersion>;
private active: Protocol.ServiceWorker.ServiceWorkerVersion;
private lastInstalled: Protocol.ServiceWorker.ServiceWorkerVersion;
private log: boolean;
private errors: Protocol.ServiceWorker.ServiceWorkerErrorMessage[];
private stateListeners: StateIdArrayMap<VersionListener>;
private stateHistory: StateIdMap<Protocol.ServiceWorker.ServiceWorkerVersion>;
private page: IPage;
// private targets: Map<string, ServiceWorkerProtocolSession>;
private errorCallbacks: ServiceWorkerErrorCallback[];
constructor(
page: IPage,
options: IServiceWorkerStateOptions = {}
) {
this.versions = new Map();
this.stateListeners = new StateIdArrayMap();
this.stateHistory = new StateIdMap();
this.log = !!options.log;
// this.targets = new Map();
this.errorCallbacks = [];
this.errors = [];
this.page = page;
// TODO: Somehow add ability to listen to network requests from the service worker
// The service worker might be its own client
page.on('ServiceWorker.workerVersionUpdated', ({ versions }) => {
for (let version of versions) {
this.recordVersion(version);
}
});
page.on('ServiceWorker.workerErrorReported', ({ errorMessage }) => {
this.errors.push(errorMessage);
});
}
public catchErrors(cb: ServiceWorkerErrorCallback) {
this.errorCallbacks.push(cb);
}
public getErrors() {
return this.errors;
}
public ensureNoErrors(handleError?: (err: Error) => void) {
const errors = this.errors;
this.errors = [];
const cbs = this.errorCallbacks.length;
if (errors.length) {
// If we are handling the errors via registered callbacks, delegate
if (cbs > 0) {
for (let i = 0; i < errors.length; i++) {
for (let x = 0; x < cbs; x++) {
this.errorCallbacks[x](errors[i]);
}
}
} else {
// Otherwise throw and log
// TODO: Better surface all the errors
const err = new Error(`Uncaught error thrown in Service Worker: ${errors[0].errorMessage}`);
if (handleError) {
handleError(err);
} else {
throw err;
}
}
}
}
private listen(id: VersionStatusIdentifier, listener: VersionListener) {
let listeners = this.stateListeners.get(id) || [];
listeners.push(listener);
this.stateListeners.set(id, listeners);
}
private recordVersion(version: Protocol.ServiceWorker.ServiceWorkerVersion) {
if (this.log) {
console.log('[sw]', version.status, version.runningStatus, version.versionId);
}
this.versions.set(Number(version.versionId), version);
const id = identifierFromVersion(version);
this.stateHistory.set(id, version);
/*
if (version.targetId && !this.targets.has(version.targetId)) {
const attach = this.session.attachToTarget(this.browserClient, version.targetId);
this.targets.set(version.targetId, new ServiceWorkerProtocolSession(version.targetId, attach));
}
*/
if (version.status === 'activated' && version.runningStatus === 'running') {
this.handleActivated(version);
} else if (version.status === 'installed' && version.runningStatus === 'running') {
this.handleInstalled(version);
}
const listeners = this.stateListeners.get(id);
if (listeners) {
listeners.forEach((listener) => {
listener(version);
});
}
}
public debug() {
this.log = true;
}
public waitForInstalled(version?: string) {
if (!version && this.lastInstalled) {
return Promise.resolve(this.lastInstalled);
}
return this.waitForState({
status: 'installed',
version
});
}
public waitForActivated(version?: string) {
if (!version && this.active) {
return Promise.resolve(this.active);
}
return this.waitForState({
status: 'activated',
version
});
}
public waitForActivation() {
return this.waitForState('activated');
}
public waitForInstallation() {
return this.waitForState('installed');
}
public waitForNextInstalled(version: Protocol.ServiceWorker.ServiceWorkerVersion) {
return this.page.until('ServiceWorker.workerVersionUpdated', ({ versions }) => {
for (let i = 0; i < versions.length; i++) {
const { versionId, status, runningStatus } = versions[i];
if (status === 'installed' && runningStatus === 'running' && versionId > version.versionId) {
return true;
}
}
return false;
});
}
public waitForVersionUpdate(predicate: (v: Protocol.ServiceWorker.ServiceWorkerVersion) => boolean,
label: string, timeout: number = 1000): Promise<Protocol.ServiceWorker.WorkerVersionUpdatedEvent> {
return Promise.race([
this.page.until('ServiceWorker.workerVersionUpdated', ({ versions }) => {
for (let i = 0; i < versions.length; i++) {
if (predicate(versions[i])) {
return true;
}
}
return false;
}),
new Promise((_r, reject) => {
setTimeout(() => {
reject(`Timeout waiting for service worker version update: ${label}`);
}, timeout);
})
]) as Promise<Protocol.ServiceWorker.WorkerVersionUpdatedEvent>;
}
// Potentially tricky behavior: If you specify a version in addition to a state, will resolve if event
// happened in the past. If you only provide a state, will NOT resolve if event happened in past
// TODO: Add tests for above ^^
// TODO: Need a more robust event listening engine now that we have 3 different properties on VersionStatusIdentifier
public waitForState(arg: VersionStatusIdentifier | Protocol.ServiceWorker.ServiceWorkerVersionStatus):
Promise<Protocol.ServiceWorker.ServiceWorkerVersion> {
const id: VersionStatusIdentifier = typeof arg === 'string' ? { status: arg } : arg;
if (!id.runningStatus) {
id.runningStatus = 'running';
}
const existingHistory = this.stateHistory.get(id);
if (existingHistory) {
return Promise.resolve(existingHistory);
}
return addTimeout(new Promise((resolve) => {
this.listen(id, (result) => {
// Wait until the next tick so that any state changes take effect first
// tslint:disable-next-line:no-floating-promises
Promise.resolve().then(() => {
resolve(result);
});
});
}), `Waiting for service worker version ${id.version} to be ${id.status} timed out`, 10000);
}
private handleActivated(version: Protocol.ServiceWorker.ServiceWorkerVersion) {
this.active = version;
}
private handleInstalled(version: Protocol.ServiceWorker.ServiceWorkerVersion) {
this.lastInstalled = version;
}
public getActive() {
if (!this.active) {
throw new Error('Error calling getActive(): There is no active worker yet. Try using waitForActivated()');
}
return this.active;
}
public getLastInstalled() {
return this.lastInstalled;
}
public skipWaiting() {
return this.page.send('ServiceWorker.skipWaiting', {
scopeURL: '/'
});
}
public emulateOffline(offline: boolean) {
throw new Error('Offline emulation not working. See https://bugs.chromium.org/p/chromium/issues/detail?id=852127');
/*
return Promise.all(Array.from(this.targets).map(([key, sw]) => {
return sw.emulateOffline(offline);
}));
*/
}
public close() {
// TODO: Once we move to using new BrowserContext per test, instead of an entire new ISession,
// we need to manually close all the ServiceWorkerProtocolSessions
this.versions.clear();
this.stateListeners.clear();
this.stateHistory.clear();
// this.targets.clear();
this.errorCallbacks = [];
}
} | the_stack |
import { BaseProxifiedProperty, PropertyProxy } from "@fluid-experimental/property-proxy";
import { ModalRoot } from '../src/ModalRoot';
import { ModalManager } from '../src/ModalManager';
import { ArrayProperty, BaseProperty, MapProperty, NodeProperty, PropertyFactory } from "@fluid-experimental/property-properties";
import { mount, MountRendererProps } from 'enzyme';
import * as React from 'react';
import { act } from 'react-dom/test-utils';
import { EditableValueCell } from '../src/EditableValueCell';
import { HashCalculator } from '../src/HashCalculator';
import {
handlePropertyDataCreation,
handlePropertyDataCreationOptionGeneration,
} from '../src/PropertyDataCreationHandlers';
import { InspectorTable } from '../src/InspectorTable';
import { search } from '../src/utils';
import {
IColumns, IInspectorSearchMatch, IInspectorSearchMatchMap, IInspectorRow,
IInspectorTableProps
} from '../src/InspectorTableTypes';
import {
constantsCustomType,
coordinateSystem3DSchema,
enumCasesSchema,
enumUnoDosTresSchema,
nonPrimitiveCollectionsSchema,
point3DSchema,
primitiveCollectionsSchema,
referenceCollectionsSchema,
sampleComplexConstsSchema,
sampleConstCollectionSchema,
sampleConstSchema,
typedReferencesSchema,
uint64CasesSchema,
} from './schemas';
export const uniqueIdentifier = 'uniqueIdentifier';
export const populateWorkspace = (workspace: MockWorkspace) => {
const schemas = [
point3DSchema,
coordinateSystem3DSchema,
primitiveCollectionsSchema,
nonPrimitiveCollectionsSchema,
referenceCollectionsSchema,
enumUnoDosTresSchema,
enumCasesSchema,
uint64CasesSchema,
sampleConstCollectionSchema,
sampleConstSchema,
constantsCustomType,
sampleComplexConstsSchema,
typedReferencesSchema,
];
schemas.forEach((schema) => { PropertyFactory.register(schema); });
workspace.root.insert('BooleanFalse', PropertyFactory.create('Bool', 'single', false) as BaseProperty);
workspace.root.insert('BooleanTrue', PropertyFactory.create('Bool', 'single', true) as BaseProperty);
workspace.root.insert('String',
PropertyFactory.create('String', 'single', 'Hello ') as BaseProperty);
workspace.root.insert('ValidReference',
PropertyFactory.create('Reference', 'single', 'String') as BaseProperty);
workspace.root.insert('InvalidReference',
PropertyFactory.create('Reference', 'single', 'someNonExisting') as BaseProperty);
workspace.root.insert('Point3D',
PropertyFactory.create(point3DSchema.typeid, 'single', { x: 1, y: 2, z: 3 }) as BaseProperty);
workspace.root.insert('CoordinateSystem3D',
PropertyFactory.create(coordinateSystem3DSchema.typeid) as BaseProperty);
workspace.root.insert('PrimitiveCollections',
PropertyFactory.create(primitiveCollectionsSchema.typeid) as BaseProperty);
workspace.root.insert('NonPrimitiveCollections',
PropertyFactory.create(nonPrimitiveCollectionsSchema.typeid) as BaseProperty);
workspace.get<MapProperty>(['NonPrimitiveCollections', 'map'])!.set(
'outlier', PropertyFactory.create(coordinateSystem3DSchema.typeid) as BaseProperty);
workspace.root.insert('ReferenceCollections',
PropertyFactory.create(referenceCollectionsSchema.typeid) as BaseProperty);
workspace.root.insert('EnumCases',
PropertyFactory.create(enumCasesSchema.typeid) as BaseProperty);
workspace.root.insert('Uint64Cases',
PropertyFactory.create(uint64CasesSchema.typeid) as BaseProperty);
workspace.root.insert('SampleConst',
PropertyFactory.create(sampleConstSchema.typeid) as BaseProperty);
workspace.root.insert('SampleCollectionConst',
PropertyFactory.create(sampleConstCollectionSchema.typeid) as BaseProperty);
workspace.root.insert('sampleComplexConst',
PropertyFactory.create(sampleComplexConstsSchema.typeid) as BaseProperty);
workspace.root.insert('typedReferences',
PropertyFactory.create(typedReferencesSchema.typeid) as BaseProperty);
const nodeProp = PropertyFactory.create<NodeProperty>('NodeProperty')!;
nodeProp.insert('nestedStr', PropertyFactory.create('String', 'single', 'nested test')!);
nodeProp.insert('int32', PropertyFactory.create('Int32', 'single', 2)!);
nodeProp.insert('cyclicReference', PropertyFactory.create('Reference', 'single', '../')!);
workspace.root.insert('nodeProp', nodeProp!);
workspace.root.insert(uniqueIdentifier, PropertyFactory.create('String', 'single', uniqueIdentifier)!);
const primitives = ['String', 'Int32', 'Int64', 'Float64', 'Uint64', 'Reference'];
const collections = ['Array', 'Map'];
for (const type of primitives) {
for (const context of collections) {
workspace.root.insert(
type.toLowerCase() + context, PropertyFactory.create(type, context.toLowerCase()) as BaseProperty);
}
}
workspace.get<ArrayProperty>('stringArray')!.push([0, 1, 2]);
workspace.get<ArrayProperty>('uint64Array')!.push([0, 1, 2]);
workspace.root.insert('ReferenceToUint64ArrayElement',
PropertyFactory.create('Reference', 'single', 'uint64Array[0]') as BaseProperty);
workspace.root.insert('ReferenceToReference',
PropertyFactory.create('Reference', 'single', 'ReferenceToArrayElement') as BaseProperty);
workspace.root.insert('ReferenceToElementOfArrayOfReferences',
PropertyFactory.create('Reference', 'single', '/ReferenceCollections.arrayOfReferences[0]') as BaseProperty);
workspace.root.insert('ReferenceToInvalidElementOfArrayOfReferences',
PropertyFactory.create('Reference', 'single', '/ReferenceCollections.arrayOfReferences[5]') as BaseProperty);
};
export function getAllMatchesFromRows(searchExpression: string, rows: IInspectorRow[], dataGetter, columns: IColumns[],
props, toTableRowOptions)
: Promise<{ matches: IInspectorSearchMatch[], matchesMap: IInspectorSearchMatchMap, childToParentMap: {} }> {
return new Promise((resolve) => {
let state;
const callback = (matches: IInspectorSearchMatch[], matchesMap, searchDone, childToParentMap) => {
if (searchDone) {
resolve({ matches, matchesMap, childToParentMap });
return;
}
state = search(searchExpression, rows, dataGetter, columns!, callback, props, toTableRowOptions, state).state;
};
state = search(searchExpression, rows, dataGetter, columns!, callback, props, toTableRowOptions, state).state;
});
};
export const getPopulateFunctionWithSerializedBranchData = (serializedBranchData: any) =>
(workspace: MockWorkspace) => {
if (!serializedBranchData) { return; }
const data = JSON.parse(serializedBranchData.data);
const changeSet = data.commits[0].changeSet;
Object.values(changeSet.insertTemplates).forEach((item: any) => {
try {
PropertyFactory.register(item);
} catch (error) {
// Often times, the error is due to a property already being registered
console.log(error);
}
});
const root = workspace.getRoot();
root.applyChangeSet(data.commits[0].changeSet);
workspace.commit();
};
/**
* This function is used to find a particular row from the react wrapper using either the name of the row or by
* a property id. Both the parameters are optional, however, if a `name` is given, it will return the row with a similar
* name, and not check for `propertyId`.
*
* @param wrapper A react wrapper in which the row needs to be searched.
* @param name Name of the row which is to be found. Encoded within `rowData.name`.
* @param propertyId An id by which the property is identified. The id is encoded into the `rowKey`.
*/
export const findTableRow = (wrapper, name = '', propertyId = '') => {
const tableRows = wrapper.find('TableRow');
return tableRows.filterWhere((row) => {
const rowKey = row.props().rowKey.split('/');
if (name && row.props().rowData.name === name.toString()) {
return true;
} else if (propertyId && rowKey.length >= 2 &&
rowKey[rowKey.length - 2] === getHash('/' + propertyId) &&
rowKey[rowKey.length - 1] === 'Add') {
return true;
}
});
};
/**
* This function is used to simulate a click to expand a row in the inspector table.
*
* @param wrapper A react wrapper in which the row needs to be searched
* @param name Name of the row which is to be found. Encoded within rowData.name
*/
export const expandRow = (wrapper, name) => {
const row = findTableRow(wrapper, name);
const expandIcon = row.find('ExpandIcon');
if (expandIcon.length > 0) {
expandIcon.simulate('click');
}
};
export const findRowMenuButton = (wrapper, name) => {
const row = findTableRow(wrapper, name);
const label = row.find('NameCell').childAt(0);
return label.find('ItemMenu');
};
export const mountInspectorTable = (
rootProxy: BaseProxifiedProperty | undefined,
inProps: Partial<IInspectorTableProps> = {},
options: MountRendererProps = {},
needModalManager = false,
) => {
const props = Object.assign({}, {
dataCreationHandler: handlePropertyDataCreation,
dataCreationOptionGenerationHandler: handlePropertyDataCreationOptionGeneration,
}, inProps);
const table = (
<InspectorTable
width={800}
height={600}
data={rootProxy}
columns={['name', 'value']}
expandColumnKey={'name'}
{...props}
/>
);
if (!needModalManager) {
return mount(
table,
options);
} else {
return mount(
<ModalManager>
<ModalRoot />
{table}
</ModalManager>,
options);
}
};
export const findAndClick = (wrapper, propertyId = '') => {
const row = propertyId ? findTableRow(wrapper, '', propertyId) : wrapper;
const addNewProp = row.find('NewDataRow');
if (addNewProp.length > 0) {
addNewProp.simulate('click');
}
};
export const addProperty = (wrapper, primitiveValue, contextValue, name?) => {
const dataForm = wrapper.find('NewDataForm');
if (name) {
const input = dataForm.findWhere(
(node) => node.props().placeholder && node.props().placeholder.startsWith('Name of the')).find('input');
input.simulate('change', { target: { value: name } });
}
const decoratedSelect = dataForm.find('DecoratedSelect');
const propertySelection = decoratedSelect.filterWhere((node) => node.props().id === 'propertyTypeSelector');
const contextSelection = decoratedSelect.filterWhere((node) => node.props().id === 'contextSelector');
const allOptions = propertySelection.props().options.reduce((acc, val) => acc.concat(val.options), []);
const newPropertyOption = allOptions.find((primitiveProperty) => primitiveProperty.label === primitiveValue);
const newContextOption = contextSelection.props().options.filter(
(context) => context.value === contextValue)[0];
propertySelection.props().onChange(newPropertyOption);
contextSelection.props().onChange(newContextOption);
// Calls creation
const createButton = dataForm.find('button').find({ id: 'createDataButton' });
createButton.simulate('click');
};
export const deleteProperty = (wrapper, menuButtonWrapper, isReference = false) => {
// click context menu button
menuButtonWrapper.find('button').simulate('click');
const position = isReference ? 2 : 1;
menuButtonWrapper.find('.MuiPaper-root').find('.MuiButtonBase-root').at(position).simulate('click');
// click delete button
wrapper.find('.MuiButton-label').at(1).simulate('click');
};
export class MockWorkspace {
public root: NodeProperty;
constructor() {
this.root = PropertyFactory.create('NodeProperty');
this.root.getWorkspace = () => this;
}
getRoot() { return this.root; }
commit() { return Promise.resolve() }
get<T>(...args) { return this.root.get<T>(...args) }
getIds() { return this.root.getIds() }
getEntriesReadOnly() { return this.root.getEntriesReadOnly() }
insert(in_id, in_property) { return this.root.insert(in_id, in_property) }
}
export const typeNewName = (wrapper, name) => {
const dataForm = wrapper.find('NewDataForm');
const input = dataForm.findWhere(
(node) => node.props().placeholder && node.props().placeholder.startsWith('Name of the')).find('input');
input.simulate('change', { target: { value: name } });
};
export const initializeWorkspace = async (populate = true) => {
const workspace = new MockWorkspace();
if (populate) {
await populateWorkspace(workspace);
}
const rootProxy = PropertyProxy.proxify(workspace.getRoot());
return { workspace, rootProxy };
};
export const findEditableCell = (wrapper, typeList: string[], name = '') => {
let editCell = wrapper.find(EditableValueCell);
editCell = (name || typeof name !== 'string')
? editCell.filterWhere((n) => n.props().rowData.name === name.toString()) : editCell;
return typeList.reduce((itemWrapper, search) => {
return itemWrapper.find(search);
}, editCell);
};
export const updateEditableValueCellValue = (wrapper, value, name = '') => {
const input = findEditableCell(wrapper, ['ForwardRef(InputBase)', 'input'], name);
input.instance().value = value;
input.find('input').simulate('blur', { currentTarget: { value } });
};
export const updateEditableValueCellSelectValue = (wrapper, value, name = '') => {
const item = findEditableCell(wrapper, ['ForwardRef(Select)'], name);
item.props().onChange({ target: { value } });
};
export const toggleEditableValueCellBoolSwitch = (wrapper, checked, name = '') => {
const item = findEditableCell(wrapper, ['ForwardRef(Switch)'], name);
item.props().onChange({ target: { checked } });
};
export const changeValue = (value, rootProxy) => {
const wrapper = mountInspectorTable(rootProxy);
updateEditableValueCellValue(wrapper, value);
};
export const changeBoolValue = (value, rootProxy, collectionKey = '') => {
const wrapper = mountInspectorTable(rootProxy);
toggleEditableValueCellBoolSwitch(wrapper, value, collectionKey);
};
export const generateRandomValidNumber = (typeid) => {
const randomFloat = +(Math.random() * 100).toFixed(2);
return typeid.startsWith('Float') ? randomFloat : Math.round(randomFloat);
};
export const findRow = (id: string, innerRows: IInspectorRow[]) => {
return innerRows.find((val) => (val.name === id))!;
};
/**
* This function is used to select a given option from the dropdown selector in the inspector table property creation.
* It triggers a state change, updates the wrapper and returns the context selector to check if it is correctly updated.
*
* @param wrapper React Wrapper containing the inspector table.
* @param selectorId Id of the dropdown selector to find and update.
* @param optionLabel Label of the option to select.
* @return Returns the updated wrapper containing context selector.
*/
const updateDropdown = (wrapper, selectorId, optionLabel) => {
const decoratedSelect = wrapper.find('NewDataForm').find('DecoratedSelect');
const selector = decoratedSelect.filterWhere((node) => node.props().id === selectorId);
let allOptions = selector.props().options;
if (selectorId === 'propertyTypeSelector') {
allOptions = selector.props().options.reduce((acc, val) => acc.concat(val.options), []);
}
const newOption = allOptions.find((option) => option.label === optionLabel);
act(() => {
selector.props().onChange(newOption);
});
wrapper.update();
return wrapper
.find('NewDataForm')
.find('DecoratedSelect')
.filterWhere((node) => node.props().id === 'contextSelector');
};
/**
* This function is used to test the dynamic updates of the dropdown options in the inspector table property creation.
* @param wrapper React Wrapper containing the inspector table.
* @return {boolean} Returns true if all check pass, false otherwise.
*/
export const testDynamicDropdown = (wrapper) => {
/* Step 1, property type is selected as `NodeProperty`. This will result in only 3 context options in dropdown */
let contextSelector = updateDropdown(wrapper, 'propertyTypeSelector', 'NodeProperty');
if (contextSelector.props().options.length !== 3) { // only 3 context options for NodeProperty
return false;
}
/* Step 2, property type is selected as `NamedNodeProperty`. This will result in 4 context options in dropdown */
contextSelector = updateDropdown(wrapper, 'propertyTypeSelector', 'NamedNodeProperty');
if (contextSelector.props().options.length !== 4) { // 4 context options for NamedNodeProperty, incl. Set
return false;
}
/* Step 3, Now we select `Set` as the context. This is possible as selected property is `NamedNodeProperty` */
updateDropdown(wrapper, 'contextSelector', 'Set');
/* Step 4, Update proprety to `NodeProperty`, and check if context has been unset. It should no longer be `set` */
contextSelector = updateDropdown(wrapper, 'propertyTypeSelector', 'NodeProperty');
if (contextSelector.props().value === 'set') { // unset context on change of property type
return false;
}
/* If all checks pass, return true */
return true;
};
export const getHash = (id) => {
const hash = new HashCalculator();
hash.pushString(id);
return hash.getHash();
};
export const getExpandedMap = (expanded) => {
return expanded.reduce(function(map, id) {
map[getHash(id)] = true;
return map;
}, {});
} | the_stack |
import { getInteraction } from '@antv/g2';
import InteractionContext from '@antv/g2/lib/interaction/context';
import { IGroup, IShape } from '@antv/g2/lib/dependents';
import { createDiv } from '../../../../utils/dom';
import { Treemap } from '../../../../../src';
import {
BREAD_CRUMB_NAME,
DrillDownAction as TreemapDrillDownAction,
} from '../../../../../src/interactions/actions/drill-down';
import { transformData } from '../../../../../src/plots/treemap/utils';
const data = {
name: 'root',
children: [
{
name: '欧洲',
children: [
{
name: '东欧',
children: [
{
name: '俄罗斯',
value: 6000,
},
{
name: '波兰',
value: 1000,
},
],
},
{
name: '西欧',
children: [
{
name: '英国',
value: 9000,
},
{
name: '德国',
value: 2000,
},
],
},
],
},
{
name: '亚洲',
children: [
{
name: '东亚',
children: [
{
name: '中国',
value: 4000,
},
{
name: '日本',
value: 2000,
},
],
},
],
},
],
};
describe('drill-down intera', () => {
it('drill-down is defined', () => {
const treemapInteraction = getInteraction('treemap-drill-down');
// 不再支持 treemap-drill-down,不过会兼容
expect(treemapInteraction).not.toBeDefined();
const interaction = getInteraction('drill-down');
expect(interaction).toBeDefined();
});
it.skip('action test', async () => {
const treemapPlot = new Treemap(createDiv(), {
data,
padding: 20,
colorField: 'name',
hierarchyConfig: {
tile: 'treemapDice',
},
interactions: [
{
type: 'treemap-drill-down',
},
],
legend: {
position: 'top-left',
},
});
treemapPlot.render();
// @ts-ignore
const context = new InteractionContext(treemapPlot.chart);
const drillDownAction = new TreemapDrillDownAction(context);
// @ts-ignore
expect(treemapPlot.chart.autoPadding.bottom).toBe(45);
// 模拟一次点击
context.event = {
type: 'custom',
data: {
data: data.children[0],
},
};
drillDownAction.click();
// 测试下钻显示数据
const nowData = treemapPlot.chart.getData();
expect(nowData.length).toBe(2);
expect(nowData[0].name).toBe('西欧');
expect(nowData[1].name).toBe('东欧');
expect(nowData[0].y).toEqual([1, 1, 0, 0]);
expect(nowData[1].y).toEqual([1, 1, 0, 0]);
// 再次模拟一次点击
context.event = {
type: 'custom',
data: {
data: {
data: transformData({
data: data.children[0].children[0],
hierarchyConfig: treemapPlot.options.hierarchyConfig,
colorField: treemapPlot.options.colorField,
enableDrillDown: true,
}),
},
},
};
drillDownAction.click();
// 测试面包屑显示
const breadCrumbGroup = treemapPlot.chart.foregroundGroup.findAllByName(BREAD_CRUMB_NAME)[0] as IGroup;
const breadCrumbGroupChildren = breadCrumbGroup.getChildren() as IShape[];
// 测试 面包屑位置
treemapPlot.changeSize(400, 600);
drillDownAction.resetPosition();
const chartHeight = treemapPlot.chart.height;
expect(breadCrumbGroup.getCanvasBBox().y).toBe(chartHeight - 20 - 20);
expect(breadCrumbGroupChildren.length).toBe(5);
const textArr = ['初始', '/', data.children[0].name, '/', data.children[0].children[0].name];
breadCrumbGroupChildren.forEach((shape, index) => {
expect(shape.cfg.type).toBe('text');
expect(shape.attr('text')).toBe(textArr[index]);
});
// 测试面包屑 hover 效果
breadCrumbGroupChildren[2].emit('mouseenter', {});
expect(breadCrumbGroupChildren[2].attr('fill')).toBe('#87B5FF');
breadCrumbGroupChildren[2].emit('mouseleave', {});
expect(breadCrumbGroupChildren[2].attr('fill')).toBe('rgba(0, 0, 0, 0.65)');
// 测试面包屑点击
breadCrumbGroup.getChildren()[4].emit('click', {});
const firstBreadData = treemapPlot.chart.getData();
expect(firstBreadData.length).toBe(2);
expect(firstBreadData[0].name).toBe('俄罗斯');
expect(firstBreadData[1].name).toBe('波兰');
// @ts-ignore
expect(drillDownAction.historyCache.length).toBe(3);
breadCrumbGroup.getChildren()[2].emit('click', {});
const secondBreadData = treemapPlot.chart.getData();
expect(secondBreadData.length).toBe(2);
expect(secondBreadData[0].name).toBe('西欧');
expect(secondBreadData[1].name).toBe('东欧');
// @ts-ignore
expect(drillDownAction.historyCache.length).toBe(2);
breadCrumbGroup.getChildren()[0].emit('click', {});
const thirdBreadData = treemapPlot.chart.getData();
expect(thirdBreadData.length).toBe(2);
expect(thirdBreadData[0].name).toBe('欧洲');
expect(thirdBreadData[1].name).toBe('亚洲');
// @ts-ignore
expect(drillDownAction.historyCache.length).toBe(1);
expect(breadCrumbGroup.cfg.visible).toBeFalsy();
treemapPlot.destroy();
});
it('interaction switch', async () => {
const treemapPlot = new Treemap(createDiv(), {
data,
padding: 20,
colorField: 'name',
interactions: [
{
type: 'treemap-drill-down',
},
],
legend: false,
});
treemapPlot.render();
const context = new InteractionContext(treemapPlot.chart);
const drillDownAction = new TreemapDrillDownAction(context);
context.event = {
type: 'custom',
data: {
// data: data.children[0],
data: {
data: transformData({
data: data.children[0],
hierarchyConfig: treemapPlot.options.hierarchyConfig,
colorField: treemapPlot.options.colorField,
enableDrillDown: true,
}),
},
},
};
drillDownAction.click();
treemapPlot.update({
interactions: [
{ type: 'view-zoom', enable: true },
{ type: 'treemap-drill-down', enable: false },
],
});
// 更换 interactions 后,padding 正常
// @ts-ignore
expect(treemapPlot.chart.autoPadding.bottom).toBe(20);
expect(treemapPlot.chart.getData().length).toBe(6);
treemapPlot.destroy();
});
it('interaction reset and destory', async () => {
const treemapPlot = new Treemap(createDiv(), {
data,
colorField: 'name',
interactions: [
{
type: 'treemap-drill-down',
},
],
legend: false,
});
treemapPlot.render();
const context = new InteractionContext(treemapPlot.chart);
const drillDownAction = new TreemapDrillDownAction(context);
// 模拟一次点击
context.event = {
type: 'custom',
data: {
// data: data.children[0],
data: {
data: transformData({
data: data.children[0],
hierarchyConfig: treemapPlot.options.hierarchyConfig,
colorField: treemapPlot.options.colorField,
enableDrillDown: true,
}),
},
},
};
drillDownAction.click();
drillDownAction.reset();
// @ts-ignore
expect(drillDownAction.historyCache).toEqual([]);
// @ts-ignore
expect(drillDownAction.breadCrumbGroup.cfg.visible).toBeFalsy();
expect(treemapPlot.chart.foregroundGroup.findAllByName(BREAD_CRUMB_NAME)[0].cfg.visible).toBe(false);
drillDownAction.click();
expect(treemapPlot.chart.foregroundGroup.findAllByName(BREAD_CRUMB_NAME).length).toBe(1);
drillDownAction.destroy();
expect(treemapPlot.chart.foregroundGroup.findAllByName(BREAD_CRUMB_NAME).length).toBe(0);
treemapPlot.destroy();
});
it('options: enableDrillDown', async () => {
const treemapPlot = new Treemap(createDiv(), {
data,
colorField: 'name',
drilldown: { enabled: true },
legend: false,
});
treemapPlot.render();
const context = new InteractionContext(treemapPlot.chart);
const drillDownAction = new TreemapDrillDownAction(context);
// 模拟一次点击
context.event = {
type: 'custom',
data: {
// data: data.children[0],
data: {
data: transformData({
data: data.children[0],
hierarchyConfig: treemapPlot.options.hierarchyConfig,
colorField: treemapPlot.options.colorField,
enableDrillDown: true,
}),
},
},
};
drillDownAction.click();
drillDownAction.reset();
// @ts-ignore
expect(drillDownAction.historyCache).toEqual([]);
// @ts-ignore
expect(drillDownAction.breadCrumbGroup.cfg.visible).toBeFalsy();
expect(treemapPlot.chart.foregroundGroup.findAllByName(BREAD_CRUMB_NAME)[0].cfg.visible).toBe(false);
drillDownAction.click();
expect(treemapPlot.chart.foregroundGroup.findAllByName(BREAD_CRUMB_NAME).length).toBe(1);
drillDownAction.destroy();
expect(treemapPlot.chart.foregroundGroup.findAllByName(BREAD_CRUMB_NAME).length).toBe(0);
treemapPlot.destroy();
});
it('options: drillDownConfig', async () => {
const treemapPlot = new Treemap(createDiv(), {
data,
colorField: 'name',
drilldown: {
enabled: true,
breadCrumb: { position: 'bottom-left', rootText: '面包根', textStyle: { fontSize: 28, fill: 'red' } },
},
legend: false,
});
treemapPlot.render();
const context = new InteractionContext(treemapPlot.chart);
const drillDownAction = new TreemapDrillDownAction(context, treemapPlot.options.drilldown.breadCrumb);
// 模拟一次点击
context.event = {
type: 'custom',
data: {
// data: data.children[0],
data: {
data: transformData({
data: data.children[0],
hierarchyConfig: treemapPlot.options.hierarchyConfig,
colorField: treemapPlot.options.colorField,
enableDrillDown: true,
}),
},
},
};
drillDownAction.click();
const treemapBreadCrumb = treemapPlot.chart.foregroundGroup.findAllByName(BREAD_CRUMB_NAME)[0];
// @ts-ignore
const breadCrumbRoot = treemapBreadCrumb.getChildByIndex(0);
expect(breadCrumbRoot.attr('text')).toBe('面包根');
expect(breadCrumbRoot.attr('fontSize')).toBe(28);
expect(breadCrumbRoot.attr('fill')).toBe('red');
drillDownAction.destroy();
expect(treemapPlot.chart.foregroundGroup.findAllByName(BREAD_CRUMB_NAME).length).toBe(0);
treemapPlot.destroy();
});
}); | the_stack |
import { GuidanceTag, guidanceTags } from 'common/guidance-links';
export interface GuidelineMetadata {
number: string;
axeTag: string;
name: string;
linkName: string;
linkTag: string;
link: string;
guidanceTags: GuidanceTag[];
}
// Maps from axe-core rule/result objects' tags property (eg, "wcag1411") to the guidance
// metadata used within our application, including the link tag (eg, WCAG_1_4_11)
//
// Note: it is intentional that not all axe tags map to metadata in our application! In particular:
// * cat.whatever are omitted (they are axe-specific and don't correspond to any official
// accessibility standard)
// * wcag2a, wcag2aa, wcag21a, wcag21aa are omitted in favor of the more specific links for
// individual wcag sections
// * experimental is omitted (we only show them at all in needs-review)
// * wcag123 tags for AAA requirements are omitted (to avoid user confusion about whether we support
// AAA assessments)
const axeTagToGuidelineKeyMap = {
wcag111: 'WCAG 1.1.1',
wcag121: 'WCAG 1.2.1',
wcag122: 'WCAG 1.2.2',
wcag123: 'WCAG 1.2.3',
wcag124: 'WCAG 1.2.4',
wcag125: 'WCAG 1.2.5',
wcag131: 'WCAG 1.3.1',
wcag132: 'WCAG 1.3.2',
wcag133: 'WCAG 1.3.3',
wcag134: 'WCAG 1.3.4',
wcag135: 'WCAG 1.3.5',
wcag141: 'WCAG 1.4.1',
wcag142: 'WCAG 1.4.2',
wcag143: 'WCAG 1.4.3',
wcag144: 'WCAG 1.4.4',
wcag145: 'WCAG 1.4.5',
wcag1410: 'WCAG 1.4.10',
wcag1411: 'WCAG 1.4.11',
wcag1412: 'WCAG 1.4.12',
wcag1413: 'WCAG 1.4.13',
wcag211: 'WCAG 2.1.1',
wcag212: 'WCAG 2.1.2',
wcag214: 'WCAG 2.1.4',
wcag221: 'WCAG 2.2.1',
wcag222: 'WCAG 2.2.2',
wcag231: 'WCAG 2.3.1',
wcag241: 'WCAG 2.4.1',
wcag242: 'WCAG 2.4.2',
wcag243: 'WCAG 2.4.3',
wcag244: 'WCAG 2.4.4',
wcag245: 'WCAG 2.4.5',
wcag246: 'WCAG 2.4.6',
wcag247: 'WCAG 2.4.7',
wcag251: 'WCAG 2.5.1',
wcag252: 'WCAG 2.5.2',
wcag253: 'WCAG 2.5.3',
wcag254: 'WCAG 2.5.4',
wcag255: 'WCAG 2.5.5',
wcag311: 'WCAG 3.1.1',
wcag312: 'WCAG 3.1.2',
wcag321: 'WCAG 3.2.1',
wcag322: 'WCAG 3.2.2',
wcag323: 'WCAG 3.2.3',
wcag324: 'WCAG 3.2.4',
wcag331: 'WCAG 3.3.1',
wcag332: 'WCAG 3.3.2',
wcag333: 'WCAG 3.3.3',
wcag334: 'WCAG 3.3.4',
wcag411: 'WCAG 4.1.1',
wcag412: 'WCAG 4.1.2',
wcag413: 'WCAG 4.1.3',
};
export const getGuidelineKeyByAxeTag = (axeTag: string): string => {
return axeTagToGuidelineKeyMap[axeTag];
};
export const guidelineMetadata = {
'WCAG 1.1.1': {
number: '1.1.1',
axeTag: 'wcag111',
name: 'Non-text Content',
linkName: 'WCAG 1.1.1',
linkTag: 'WCAG_1_1_1',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/non-text-content.html',
guidanceTags: [],
},
'WCAG 1.2.1': {
number: '1.2.1',
axeTag: 'wcag121',
name: 'Audio-only and Video-only (Prerecorded)',
linkName: 'WCAG 1.2.1',
linkTag: 'WCAG_1_2_1',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/audio-only-and-video-only-prerecorded',
guidanceTags: [],
},
'WCAG 1.2.2': {
number: '1.2.2',
axeTag: 'wcag122',
name: 'Captions (Prerecorded)',
linkName: 'WCAG 1.2.2',
linkTag: 'WCAG_1_2_2',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/captions-prerecorded.html',
guidanceTags: [],
},
'WCAG 1.2.3': {
number: '1.2.3',
axeTag: 'wcag123',
name: 'Audio Description or Media Alternative (Prerecorded)',
linkName: 'WCAG 1.2.3',
linkTag: 'WCAG_1_2_3',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/audio-description-or-media-alternative-prerecorded',
guidanceTags: [],
},
'WCAG 1.2.4': {
number: '1.2.4',
axeTag: 'wcag124',
name: 'Captions (Live)',
linkName: 'WCAG 1.2.4',
linkTag: 'WCAG_1_2_4',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/captions-live.html',
guidanceTags: [],
},
'WCAG 1.2.5': {
number: '1.2.5',
axeTag: 'wcag125',
name: 'Audio Description (Prerecorded)',
linkName: 'WCAG 1.2.5',
linkTag: 'WCAG_1_2_5',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/audio-description-prerecorded',
guidanceTags: [],
},
'WCAG 1.3.1': {
number: '1.3.1',
axeTag: 'wcag131',
name: 'Info and Relationships',
linkName: 'WCAG 1.3.1',
linkTag: 'WCAG_1_3_1',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/info-and-relationships',
guidanceTags: [],
},
'WCAG 1.3.2': {
number: '1.3.2',
axeTag: 'wcag132',
name: 'Meaningful Sequence',
linkName: 'WCAG 1.3.2',
linkTag: 'WCAG_1_3_2',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/meaningful-sequence.html',
guidanceTags: [],
},
'WCAG 1.3.3': {
number: '1.3.3',
axeTag: 'wcag133',
name: 'Sensory Characteristics',
linkName: 'WCAG 1.3.3',
linkTag: 'WCAG_1_3_3',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/sensory-characteristics.html',
guidanceTags: [],
},
'WCAG 1.3.4': {
number: '1.3.4',
axeTag: 'wcag134',
name: 'Orientation',
linkName: 'WCAG 1.3.4',
linkTag: 'WCAG_1_3_4',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/orientation.html',
guidanceTags: [guidanceTags.WCAG_2_1],
},
'WCAG 1.3.5': {
number: '1.3.5',
axeTag: 'wcag135',
name: 'Identify Input Purpose',
linkName: 'WCAG 1.3.5',
linkTag: 'WCAG_1_3_5',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/identify-input-purpose.html',
guidanceTags: [guidanceTags.WCAG_2_1],
},
'WCAG 1.4.1': {
number: '1.4.1',
axeTag: 'wcag141',
name: 'Use of Color',
linkName: 'WCAG 1.4.1',
linkTag: 'WCAG_1_4_1',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/use-of-color.html',
guidanceTags: [],
},
'WCAG 1.4.2': {
number: '1.4.2',
axeTag: 'wcag142',
name: 'Audio Control',
linkName: 'WCAG 1.4.2',
linkTag: 'WCAG_1_4_2',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/audio-control.html',
guidanceTags: [],
},
'WCAG 1.4.3': {
number: '1.4.3',
axeTag: 'wcag143',
name: 'Contrast (Minimum)',
linkName: 'WCAG 1.4.3',
linkTag: 'WCAG_1_4_3',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/contrast-minimum.html',
guidanceTags: [],
},
'WCAG 1.4.4': {
number: '1.4.4',
axeTag: 'wcag144',
name: 'Resize text',
linkName: 'WCAG 1.4.4',
linkTag: 'WCAG_1_4_4',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/resize-text.html',
guidanceTags: [],
},
'WCAG 1.4.5': {
number: '1.4.5',
axeTag: 'wcag145',
name: 'Images of Text',
linkName: 'WCAG 1.4.5',
linkTag: 'WCAG_1_4_5',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/images-of-text.html',
guidanceTags: [],
},
'WCAG 1.4.10': {
number: '1.4.10',
axeTag: 'wcag1410',
name: 'Reflow',
linkTag: 'WCAG_1_4_10',
linkName: 'WCAG 1.4.10',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/reflow.html',
guidanceTags: [guidanceTags.WCAG_2_1],
},
'WCAG 1.4.11': {
number: '1.4.11',
axeTag: 'wcag1411',
name: 'Non-text Contrast',
linkTag: 'WCAG_1_4_11',
linkName: 'WCAG 1.4.11',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/non-text-contrast.html',
guidanceTags: [guidanceTags.WCAG_2_1],
},
'WCAG 1.4.12': {
number: '1.4.12',
axeTag: 'wcag1412',
name: 'Text Spacing',
linkTag: 'WCAG_1_4_12',
linkName: 'WCAG 1.4.12',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/text-spacing.html',
guidanceTags: [guidanceTags.WCAG_2_1],
},
'WCAG 1.4.13': {
number: '1.4.13',
axeTag: 'wcag1413',
name: 'Content on Hover or Focus',
linkTag: 'WCAG_1_4_13',
linkName: 'WCAG 1.4.13',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/content-on-hover-or-focus.html',
guidanceTags: [guidanceTags.WCAG_2_1],
},
'WCAG 2.1.1': {
number: '2.1.1',
axeTag: 'wcag211',
name: 'Keyboard',
linkName: 'WCAG 2.1.1',
linkTag: 'WCAG_2_1_1',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/keyboard.html',
guidanceTags: [],
},
'WCAG 2.1.2': {
number: '2.1.2',
axeTag: 'wcag212',
name: 'No Keyboard Trap',
linkName: 'WCAG 2.1.2',
linkTag: 'WCAG_2_1_2',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/no-keyboard-trap.html',
guidanceTags: [],
},
'WCAG 2.1.4': {
number: '2.1.4',
axeTag: 'wcag214',
name: 'Character Key Shortcuts',
linkName: 'WCAG 2.1.4',
linkTag: 'WCAG_2_1_4',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/character-key-shortcuts.html',
guidanceTags: [guidanceTags.WCAG_2_1],
},
'WCAG 2.2.1': {
number: '2.2.1',
axeTag: 'wcag221',
name: 'Timing Adjustable',
linkName: 'WCAG 2.2.1',
linkTag: 'WCAG_2_2_1',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/timing-adjustable.html',
guidanceTags: [],
},
'WCAG 2.2.2': {
number: '2.2.2',
axeTag: 'wcag222',
name: 'Pause, Stop, Hide',
linkName: 'WCAG 2.2.2',
linkTag: 'WCAG_2_2_2',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/pause-stop-hide',
guidanceTags: [],
},
// wcag223: intentionally omitted, AAA
// wcag224: intentionally omitted, AAA
'WCAG 2.3.1': {
number: '2.3.1',
axeTag: 'wcag231',
name: 'Three Flashes or Below Threshold',
linkName: 'WCAG 2.3.1',
linkTag: 'WCAG_2_3_1',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/three-flashes-or-below-threshold.html',
guidanceTags: [],
},
'WCAG 2.4.1': {
number: '2.4.1',
axeTag: 'wcag241',
name: 'Bypass Blocks',
linkName: 'WCAG 2.4.1',
linkTag: 'WCAG_2_4_1',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/bypass-blocks',
guidanceTags: [],
},
'WCAG 2.4.2': {
number: '2.4.2',
axeTag: 'wcag242',
name: 'Page Titled',
linkName: 'WCAG 2.4.2',
linkTag: 'WCAG_2_4_2',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/page-titled.html',
guidanceTags: [],
},
'WCAG 2.4.3': {
number: '2.4.3',
axeTag: 'wcag243',
name: 'Focus Order',
linkName: 'WCAG 2.4.3',
linkTag: 'WCAG_2_4_3',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/focus-order.html',
guidanceTags: [],
},
'WCAG 2.4.4': {
number: '2.4.4',
axeTag: 'wcag244',
name: 'Link Purpose (In Context)',
linkName: 'WCAG 2.4.4',
linkTag: 'WCAG_2_4_4',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/link-purpose-in-context.html',
guidanceTags: [],
},
'WCAG 2.4.5': {
number: '2.4.5',
axeTag: 'wcag245',
name: 'Multiple Ways',
linkName: 'WCAG 2.4.5',
linkTag: 'WCAG_2_4_5',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/multiple-ways.html',
guidanceTags: [],
},
'WCAG 2.4.6': {
number: '2.4.6',
axeTag: 'wcag246',
name: 'Headings and Labels',
linkName: 'WCAG 2.4.6',
linkTag: 'WCAG_2_4_6',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/headings-and-labels',
guidanceTags: [],
},
'WCAG 2.4.7': {
number: '2.4.7',
axeTag: 'wcag247',
name: 'Focus Visible',
linkName: 'WCAG 2.4.7',
linkTag: 'WCAG_2_4_7',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/focus-visible.html',
guidanceTags: [],
},
// wcag248: intentionally omitted, AAA
// wcag249: intentionally omitted, AAA
'WCAG 2.5.1': {
number: '2.5.1',
axeTag: 'wcag251',
name: 'Pointer Gestures',
linkName: 'WCAG 2.5.1',
linkTag: 'WCAG_2_5_1',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/pointer-gestures.html',
guidanceTags: [guidanceTags.WCAG_2_1],
},
'WCAG 2.5.2': {
number: '2.5.2',
axeTag: 'wcag252',
name: 'Pointer Cancellation',
linkName: 'WCAG 2.5.2',
linkTag: 'WCAG_2_5_2',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/pointer-cancellation.html',
guidanceTags: [guidanceTags.WCAG_2_1],
},
'WCAG 2.5.3': {
number: '2.5.3',
axeTag: 'wcag253',
name: 'Label in Name',
linkName: 'WCAG 2.5.3',
linkTag: 'WCAG_2_5_3',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/label-in-name',
guidanceTags: [guidanceTags.WCAG_2_1],
},
'WCAG 2.5.4': {
number: '2.5.4',
axeTag: 'wcag254',
name: 'Motion Actuation',
linkName: 'WCAG 2.5.4',
linkTag: 'WCAG_2_5_4',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/motion-actuation.html',
guidanceTags: [guidanceTags.WCAG_2_1],
},
'WCAG 2.5.5': {
number: '2.5.5',
axeTag: 'wcag255',
name: 'Target Size',
linkName: 'WCAG 2.5.5',
linkTag: 'WCAG_2_5_5',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/target-size.html',
guidanceTags: [],
},
'WCAG 3.1.1': {
number: '3.1.1',
axeTag: 'wcag311',
name: 'Language of Page',
linkName: 'WCAG 3.1.1',
linkTag: 'WCAG_3_1_1',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/language-of-page.html',
guidanceTags: [],
},
'WCAG 3.1.2': {
number: '3.1.2',
axeTag: 'wcag312',
name: 'Language of Parts',
linkName: 'WCAG 3.1.2',
linkTag: 'WCAG_3_1_2',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/language-of-parts.html',
guidanceTags: [],
},
'WCAG 3.2.1': {
number: '3.2.1',
axeTag: 'wcag321',
name: 'On Focus',
linkName: 'WCAG 3.2.1',
linkTag: 'WCAG_3_2_1',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/on-focus.html',
guidanceTags: [],
},
'WCAG 3.2.2': {
number: '3.2.2',
axeTag: 'wcag322',
name: 'On Input',
linkName: 'WCAG 3.2.2',
linkTag: 'WCAG_3_2_2',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/on-input.html',
guidanceTags: [],
},
'WCAG 3.2.3': {
number: '3.2.3',
axeTag: 'wcag323',
name: 'Consistent Navigation',
linkName: 'WCAG 3.2.3',
linkTag: 'WCAG_3_2_3',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/consistent-navigation',
guidanceTags: [],
},
'WCAG 3.2.4': {
number: '3.2.4',
axeTag: 'wcag324',
name: 'Consistent Identification',
linkName: 'WCAG 3.2.4',
linkTag: 'WCAG_3_2_4',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/consistent-identification',
guidanceTags: [],
},
// wcag325: intentionally omitted, AAA
'WCAG 3.3.1': {
number: '3.3.1',
axeTag: 'wcag331',
name: 'Error Identification',
linkName: 'WCAG 3.3.1',
linkTag: 'WCAG_3_3_1',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/error-identification.html',
guidanceTags: [],
},
'WCAG 3.3.2': {
number: '3.3.2',
axeTag: 'wcag332',
name: 'Labels or Instructions',
linkName: 'WCAG 3.3.2',
linkTag: 'WCAG_3_3_2',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/labels-or-instructions.html',
guidanceTags: [],
},
'WCAG 3.3.3': {
number: '3.3.3',
axeTag: 'wcag333',
name: 'Error Suggestion',
linkName: 'WCAG 3.3.3',
linkTag: 'WCAG_3_3_3',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/error-suggestion.html',
guidanceTags: [],
},
'WCAG 3.3.4': {
number: '3.3.4',
axeTag: 'wcag334',
name: 'Error Prevention (Legal, Financial, Data)',
linkName: 'WCAG 3.3.4',
linkTag: 'WCAG_3_3_4',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/error-prevention-legal-financial-data.html',
guidanceTags: [],
},
'WCAG 4.1.1': {
number: '4.1.1',
axeTag: 'wcag411',
name: 'Parsing',
linkName: 'WCAG 4.1.1',
linkTag: 'WCAG_4_1_1',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/parsing.html',
guidanceTags: [],
},
'WCAG 4.1.2': {
number: '4.1.2',
axeTag: 'wcag412',
name: 'Name, Role, Value',
linkName: 'WCAG 4.1.2',
linkTag: 'WCAG_4_1_2',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/name-role-value.html',
guidanceTags: [],
},
'WCAG 4.1.3': {
number: '4.1.3',
axeTag: 'wcag413',
name: 'Status Messages',
linkName: 'WCAG 4.1.3',
linkTag: 'WCAG_4_1_3',
link: 'https://www.w3.org/WAI/WCAG21/Understanding/status-messages.html',
guidanceTags: [guidanceTags.WCAG_2_1],
},
}; | the_stack |
import { Vector3 } from './Vector3'
// import {Object3D} from '../core/Object3D'
// import {Sphere} from './Sphere'
// import {Plane} from './Plane'
import { Matrix4 } from './Matrix4'
const points: Vector3[] = [
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3(),
new Vector3(),
]
export class Box3 {
max: Vector3
min: Vector3
readonly isBox3: boolean = true
constructor(
min: Vector3 = new Vector3(+Infinity, +Infinity, +Infinity),
max: Vector3 = new Vector3(-Infinity, -Infinity, -Infinity)
) {
this.min = min
this.max = max
}
// expandByVector(vector: Vector3): this
// expandByObject(object: Object3D): this
// containsPoint(point: Vector3): boolean
// containsBox(box: Box3): boolean
// getParameter(point: Vector3): Vector3
// intersectsBox(box: Box3): boolean
// intersectsSphere(sphere: Sphere): boolean
// intersectsPlane(plane: Plane): boolean
// clampPoint(point: Vector3, target: Vector3): Vector3
// distanceToPoint(point: Vector3): f32
// getBoundingSphere(target: Sphere): Sphere
// intersect(box: Box3): this
// union(box: Box3): this
set(min: Vector3, max: Vector3): this {
this.min.copy(min)
this.max.copy(max)
return this
}
// setFromArray(array: ArrayLike<f32>): this {
// var minX = +Infinity
// var minY = +Infinity
// var minZ = +Infinity
// var maxX = -Infinity
// var maxY = -Infinity
// var maxZ = -Infinity
// for (var i = 0, l = array.length; i < l; i += 3) {
// var x = array[i]
// var y = array[i + 1]
// var z = array[i + 2]
// if (x < minX) minX = x
// if (y < minY) minY = y
// if (z < minZ) minZ = z
// if (x > maxX) maxX = x
// if (y > maxY) maxY = y
// if (z > maxZ) maxZ = z
// }
// this.min.set(minX, minY, minZ)
// this.max.set(maxX, maxY, maxZ)
// return this
// },
// setFromBufferAttribute: function(attribute) {
// var minX = +Infinity
// var minY = +Infinity
// var minZ = +Infinity
// var maxX = -Infinity
// var maxY = -Infinity
// var maxZ = -Infinity
// for (var i = 0, l = attribute.count; i < l; i++) {
// var x = attribute.getX(i)
// var y = attribute.getY(i)
// var z = attribute.getZ(i)
// if (x < minX) minX = x
// if (y < minY) minY = y
// if (z < minZ) minZ = z
// if (x > maxX) maxX = x
// if (y > maxY) maxY = y
// if (z > maxZ) maxZ = z
// }
// this.min.set(minX, minY, minZ)
// this.max.set(maxX, maxY, maxZ)
// return this
// },
setFromPoints(points: Vector3[]): this {
this.makeEmpty()
for (let i = 0, il = points.length; i < il; i++) {
this.expandByPoint(points[i])
}
return this
}
// setFromCenterAndSize(center: Vector3, size: Vector3): this
// setFromCenterAndSize: (function() {
// var v1 = new Vector3()
// return function setFromCenterAndSize(center, size) {
// var halfSize = v1.copy(size).multiplyScalar(0.5)
// this.min.copy(center).sub(halfSize)
// this.max.copy(center).add(halfSize)
// return this
// }
// })(),
// setFromObject(object: Object3D): this {
// this.makeEmpty()
// return this.expandByObject(object)
// },
clone(): Box3 {
const b = new Box3()
b.copy(this)
return b
}
copy(box: Box3): this {
this.min.copy(box.min)
this.max.copy(box.max)
return this
}
makeEmpty(): this {
this.min.x = this.min.y = this.min.z = +Infinity
this.max.x = this.max.y = this.max.z = -Infinity
return this
}
isEmpty(): boolean {
// this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z
}
getCenter(target: Vector3): Vector3 {
return this.isEmpty() ? target.set(0, 0, 0) : target.addVectors(this.min, this.max).multiplyScalar(0.5)
}
getSize(target: Vector3): Vector3 {
return this.isEmpty() ? target.set(0, 0, 0) : target.subVectors(this.max, this.min)
}
expandByPoint(point: Vector3): this {
this.min.min(point)
this.max.max(point)
return this
}
// expandByVector: function(vector) {
// this.min.sub(vector)
// this.max.add(vector)
// return this
// },
expandByScalar(scalar: f32): this {
this.min.addScalar(-scalar)
this.max.addScalar(scalar)
return this
}
// expandByObject: (function() {
// // Computes the world-axis-aligned bounding box of an object (including its children),
// // accounting for both the object's, and children's, world transforms
// var scope, i, l
// var v1 = new Vector3()
// function traverse(node) {
// var geometry = node.geometry
// if (geometry !== undefined) {
// if (geometry.isGeometry) {
// var vertices = geometry.vertices
// for (i = 0, l = vertices.length; i < l; i++) {
// v1.copy(vertices[i])
// v1.applyMatrix4(node.matrixWorld)
// scope.expandByPoint(v1)
// }
// } else if (geometry.isBufferGeometry) {
// var attribute = geometry.attributes.position
// if (attribute !== undefined) {
// for (i = 0, l = attribute.count; i < l; i++) {
// v1.fromBufferAttribute(attribute, i).applyMatrix4(node.matrixWorld)
// scope.expandByPoint(v1)
// }
// }
// }
// }
// }
// return function expandByObject(object) {
// scope = this
// object.updateMatrixWorld(true)
// object.traverse(traverse)
// return this
// }
// })(),
// containsPoint: function(point) {
// return point.x < this.min.x ||
// point.x > this.max.x ||
// point.y < this.min.y ||
// point.y > this.max.y ||
// point.z < this.min.z ||
// point.z > this.max.z
// ? false
// : true
// },
// containsBox: function(box) {
// return (
// this.min.x <= box.min.x &&
// box.max.x <= this.max.x &&
// this.min.y <= box.min.y &&
// box.max.y <= this.max.y &&
// this.min.z <= box.min.z &&
// box.max.z <= this.max.z
// )
// },
// getParameter: function(point, target) {
// // This can potentially have a divide by zero if the box
// // has a size dimension of 0.
// if (target === undefined) {
// console.warn('THREE.Box3: .getParameter() target is now required')
// target = new Vector3()
// }
// return target.set(
// (point.x - this.min.x) / (this.max.x - this.min.x),
// (point.y - this.min.y) / (this.max.y - this.min.y),
// (point.z - this.min.z) / (this.max.z - this.min.z)
// )
// },
// intersectsBox: function(box) {
// // using 6 splitting planes to rule out intersections.
// return box.max.x < this.min.x ||
// box.min.x > this.max.x ||
// box.max.y < this.min.y ||
// box.min.y > this.max.y ||
// box.max.z < this.min.z ||
// box.min.z > this.max.z
// ? false
// : true
// },
// intersectsSphere: (function() {
// var closestPoint = new Vector3()
// return function intersectsSphere(sphere) {
// // Find the point on the AABB closest to the sphere center.
// this.clampPoint(sphere.center, closestPoint)
// // If that point is inside the sphere, the AABB and sphere intersect.
// return closestPoint.distanceToSquared(sphere.center) <= sphere.radius * sphere.radius
// }
// })(),
// intersectsPlane: function(plane) {
// // We compute the minimum and maximum dot product values. If those values
// // are on the same side (back or front) of the plane, then there is no intersection.
// var min, max
// if (plane.normal.x > 0) {
// min = plane.normal.x * this.min.x
// max = plane.normal.x * this.max.x
// } else {
// min = plane.normal.x * this.max.x
// max = plane.normal.x * this.min.x
// }
// if (plane.normal.y > 0) {
// min += plane.normal.y * this.min.y
// max += plane.normal.y * this.max.y
// } else {
// min += plane.normal.y * this.max.y
// max += plane.normal.y * this.min.y
// }
// if (plane.normal.z > 0) {
// min += plane.normal.z * this.min.z
// max += plane.normal.z * this.max.z
// } else {
// min += plane.normal.z * this.max.z
// max += plane.normal.z * this.min.z
// }
// return min <= -plane.constant && max >= -plane.constant
// },
// intersectsTriangle: (function() {
// // triangle centered vertices
// var v0 = new Vector3()
// var v1 = new Vector3()
// var v2 = new Vector3()
// // triangle edge vectors
// var f0 = new Vector3()
// var f1 = new Vector3()
// var f2 = new Vector3()
// var testAxis = new Vector3()
// var center = new Vector3()
// var extents = new Vector3()
// var triangleNormal = new Vector3()
// function satForAxes(axes) {
// var i, j
// for (i = 0, j = axes.length - 3; i <= j; i += 3) {
// testAxis.fromArray(axes, i)
// // project the aabb onto the seperating axis
// var r =
// extents.x * Mathf.abs(testAxis.x) +
// extents.y * Mathf.abs(testAxis.y) +
// extents.z * Mathf.abs(testAxis.z)
// // project all 3 vertices of the triangle onto the seperating axis
// var p0 = v0.dot(testAxis)
// var p1 = v1.dot(testAxis)
// var p2 = v2.dot(testAxis)
// // actual test, basically see if either of the most extreme of the triangle points intersects r
// if (Mathf.max(-Mathf.max(p0, p1, p2), Mathf.min(p0, p1, p2)) > r) {
// // points of the projected triangle are outside the projected half-length of the aabb
// // the axis is seperating and we can exit
// return false
// }
// }
// return true
// }
// return function intersectsTriangle(triangle) {
// if (this.isEmpty()) {
// return false
// }
// // compute box center and extents
// this.getCenter(center)
// extents.subVectors(this.max, center)
// // translate triangle to aabb origin
// v0.subVectors(triangle.a, center)
// v1.subVectors(triangle.b, center)
// v2.subVectors(triangle.c, center)
// // compute edge vectors for triangle
// f0.subVectors(v1, v0)
// f1.subVectors(v2, v1)
// f2.subVectors(v0, v2)
// // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
// // make an axis testing of each of the 3 sides of the aabb against each of the 3 sides of the triangle = 9 axis of separation
// // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
// var axes = [
// 0,
// -f0.z,
// f0.y,
// 0,
// -f1.z,
// f1.y,
// 0,
// -f2.z,
// f2.y,
// f0.z,
// 0,
// -f0.x,
// f1.z,
// 0,
// -f1.x,
// f2.z,
// 0,
// -f2.x,
// -f0.y,
// f0.x,
// 0,
// -f1.y,
// f1.x,
// 0,
// -f2.y,
// f2.x,
// 0,
// ]
// if (!satForAxes(axes)) {
// return false
// }
// // test 3 face normals from the aabb
// axes = [1, 0, 0, 0, 1, 0, 0, 0, 1]
// if (!satForAxes(axes)) {
// return false
// }
// // finally testing the face normal of the triangle
// // use already existing triangle edge vectors here
// triangleNormal.crossVectors(f0, f1)
// axes = [triangleNormal.x, triangleNormal.y, triangleNormal.z]
// return satForAxes(axes)
// }
// })(),
// clampPoint: function(point, target) {
// if (target === undefined) {
// console.warn('THREE.Box3: .clampPoint() target is now required')
// target = new Vector3()
// }
// return target.copy(point).clamp(this.min, this.max)
// },
// distanceToPoint: (function() {
// var v1 = new Vector3()
// return function distanceToPoint(point) {
// var clampedPoint = v1.copy(point).clamp(this.min, this.max)
// return clampedPoint.sub(point).length()
// }
// })(),
// getBoundingSphere: (function() {
// var v1 = new Vector3()
// return function getBoundingSphere(target) {
// if (target === undefined) {
// console.error('THREE.Box3: .getBoundingSphere() target is now required')
// //target = new Sphere(); // removed to avoid cyclic dependency
// }
// this.getCenter(target.center)
// target.radius = this.getSize(v1).length() * 0.5
// return target
// }
// })(),
// intersect: function(box) {
// this.min.max(box.min)
// this.max.min(box.max)
// // ensure that if there is no overlap, the result is fully empty, not slightly empty with non-inf/+inf values that will cause subsequence intersects to erroneously return valid values.
// if (this.isEmpty()) this.makeEmpty()
// return this
// },
// union: function(box) {
// this.min.min(box.min)
// this.max.max(box.max)
// return this
// },
applyMatrix4(matrix: Matrix4): this {
// transform of empty box is an empty box.
if (this.isEmpty()) return this
// NOTE: I am using a binary pattern to specify all 2^3 combinations below
points[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(matrix) // 000
points[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(matrix) // 001
points[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(matrix) // 010
points[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(matrix) // 011
points[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(matrix) // 100
points[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(matrix) // 101
points[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(matrix) // 110
points[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(matrix) // 111
this.setFromPoints(points)
return this
}
translate(offset: Vector3): this {
this.min.add(offset)
this.max.add(offset)
return this
}
equals(box: Box3): boolean {
return box.min.equals(this.min) && box.max.equals(this.max)
}
}
export function compareBox(a: Box3, b: Box3, threshold: f32 = 0.0001): bool {
return a.min.distanceTo(b.min) < threshold && a.max.distanceTo(b.max) < threshold
} | the_stack |
import {equal, ok} from 'assert';
import {join} from 'path';
import {
command,
fail,
file,
handler,
path as toPath,
resource,
task,
template,
} from 'fig';
import Context from 'fig/Context.js';
import assert from 'fig/assert.js';
import {promises} from 'fig/fs.js';
import stat from 'fig/fs/stat.js';
import tempdir from 'fig/fs/tempdir.js';
function live() {
return !Context.currentOptions?.check;
}
const expect = {
equal(actual: any, expected: any, message?: string | Error | undefined) {
if (live()) {
equal(actual, expected, message);
}
},
ok(value: any, message?: string | Error | undefined) {
if (live()) {
ok(value, message);
}
},
};
const fs = {
async readFile(name: string, encoding: BufferEncoding) {
if (live()) {
return promises.readFile(name, encoding);
} else {
return '';
}
},
async stat(name: string) {
if (live()) {
return promises.stat(name);
} else {
return {
mtimeMs: 1000,
};
}
},
async utimes(path: string, atime: number, mtime: number) {
if (live()) {
await promises.utimes(path, atime, mtime);
}
},
};
const DEFAULT_STATS = {
mode: '0644',
target: undefined,
type: 'file',
};
task('copy a file', async () => {
//
// 1. Create a file for the first time.
//
let path = join(await tempdir('meta'), 'example.txt');
let {changed, failed, ok, skipped} = Context.counts;
// This time showing use of "src".
await file({
path,
src: resource.file('example.txt'),
state: 'file',
});
let contents = await fs.readFile(path, 'utf8');
expect.equal(contents, 'Some example content.\n');
expect.equal(Context.counts.changed, changed + 1);
expect.equal(Context.counts.failed, failed);
expect.equal(Context.counts.ok, ok);
expect.equal(Context.counts.skipped, skipped);
//
// 2. Overwrite an existing file.
//
({changed, failed, ok, skipped} = Context.counts);
// This time showing use of "contents".
await file({
contents: 'New content!\n',
path,
state: 'file',
});
contents = await fs.readFile(path, 'utf8');
expect.equal(contents, 'New content!\n');
expect.equal(Context.counts.changed, changed + 1);
expect.equal(Context.counts.failed, failed);
expect.equal(Context.counts.ok, ok);
expect.equal(Context.counts.skipped, skipped);
//
// 3. When no changes needed.
//
({changed, failed, ok, skipped} = Context.counts);
await file({
contents: 'New content!\n',
path,
state: 'file',
});
contents = await fs.readFile(path, 'utf8');
expect.equal(contents, 'New content!\n');
expect.equal(Context.counts.changed, changed);
expect.equal(Context.counts.failed, failed);
expect.equal(Context.counts.ok, ok + 1);
expect.equal(Context.counts.skipped, skipped);
//
// 4. Creating an empty file (no "src", no "content").
//
path = path.replace(/\.txt$/, '.txt.bak');
({changed, failed, ok, skipped} = Context.counts);
await file({
path,
state: 'file',
});
contents = await fs.readFile(path, 'utf8');
expect.equal(contents, '');
expect.equal(Context.counts.changed, changed + 1);
expect.equal(Context.counts.failed, failed);
expect.equal(Context.counts.ok, ok);
expect.equal(Context.counts.skipped, skipped);
});
task('create a directory', async () => {
//
// 1. Create a directory for the first time.
//
const path = join(await tempdir('meta'), 'a-directory');
let {changed, failed, ok, skipped} = Context.counts;
await file({
path,
state: 'directory',
});
let stats = live() ? await stat(path) : DEFAULT_STATS;
assert(stats && !(stats instanceof Error));
expect.equal(stats.type, 'directory');
expect.equal(Context.counts.changed, changed + 1);
expect.equal(Context.counts.failed, failed);
expect.equal(Context.counts.ok, ok);
expect.equal(Context.counts.skipped, skipped);
//
// 2. Changing mode of an existing directory.
//
({changed, failed, ok, skipped} = Context.counts);
await file({
mode: '0700',
path,
state: 'directory',
});
stats = live() ? await stat(path) : DEFAULT_STATS;
assert(stats && !(stats instanceof Error));
expect.equal(stats.mode, '0700');
expect.equal(Context.counts.changed, changed + 1);
expect.equal(Context.counts.failed, failed);
expect.equal(Context.counts.ok, ok);
expect.equal(Context.counts.skipped, skipped);
//
// 3. A no-op.
//
({changed, failed, ok, skipped} = Context.counts);
await file({
path,
state: 'directory',
});
stats = live() ? await stat(path) : DEFAULT_STATS;
assert(stats && !(stats instanceof Error));
expect.equal(stats.mode, '0700');
expect.equal(Context.counts.changed, changed);
expect.equal(Context.counts.failed, failed);
expect.equal(Context.counts.ok, ok + 1);
expect.equal(Context.counts.skipped, skipped);
});
task('manage a symbolic link', async () => {
//
// 1. Create a link.
//
let path = join(await tempdir('meta'), 'example.txt');
const src = resource.file('example.txt');
let {changed, failed, ok, skipped} = Context.counts;
await file({
path,
src,
state: 'link',
});
let contents = await fs.readFile(path, 'utf8');
expect.equal(contents, 'Some example content.\n');
let stats = live() ? await stat(path) : DEFAULT_STATS;
assert(stats && !(stats instanceof Error));
expect.equal(stats.type, 'link');
expect.equal(stats.target, toPath(src).resolve);
expect.equal(Context.counts.changed, changed + 1);
expect.equal(Context.counts.failed, failed);
expect.equal(Context.counts.ok, ok);
expect.equal(Context.counts.skipped, skipped);
});
task('template a file', async () => {
//
// 1. Create file from template.
//
const path = join(await tempdir('meta'), 'sample.txt');
let {changed, failed, ok, skipped} = Context.counts;
await template({
path,
src: resource.template('sample.txt.erb'),
variables: {
greeting: 'Hello',
names: ['Bob', 'Jane'],
},
});
let contents = await fs.readFile(path, 'utf8');
expect.equal(contents, 'Hello Bob, Jane!\n');
expect.equal(Context.counts.changed, changed + 1);
expect.equal(Context.counts.failed, failed);
expect.equal(Context.counts.ok, ok);
expect.equal(Context.counts.skipped, skipped);
//
// 2. Show that running again is a no-op.
//
({changed, failed, ok, skipped} = Context.counts);
await template({
path,
src: resource.template('sample.txt.erb'),
variables: {
greeting: 'Hello',
names: ['Bob', 'Jane'],
},
});
contents = await fs.readFile(path, 'utf8');
expect.equal(contents, 'Hello Bob, Jane!\n');
expect.equal(Context.counts.changed, changed);
expect.equal(Context.counts.failed, failed);
expect.equal(Context.counts.ok, ok + 1);
expect.equal(Context.counts.skipped, skipped);
//
// 3. Show that we can change an existing file if required.
//
// 3a. Just a content change.
//
({changed, failed, ok, skipped} = Context.counts);
await template({
path,
src: resource.template('sample.txt.erb'),
variables: {
greeting: 'Hi',
names: ['Jim', 'Mary', 'Carol'],
},
});
expect.equal(Context.counts.changed, changed + 1);
expect.equal(Context.counts.failed, failed);
expect.equal(Context.counts.ok, ok);
expect.equal(Context.counts.skipped, skipped);
contents = await fs.readFile(path, 'utf8');
expect.equal(contents, 'Hi Jim, Mary, Carol!\n');
//
// 3b. Just a mode change.
//
({changed, failed, ok, skipped} = Context.counts);
await template({
mode: '0600',
path,
src: resource.template('sample.txt.erb'),
variables: {
greeting: 'Hi',
names: ['Jim', 'Mary', 'Carol'],
},
});
expect.equal(Context.counts.changed, changed + 1);
expect.equal(Context.counts.failed, failed);
expect.equal(Context.counts.ok, ok);
expect.equal(Context.counts.skipped, skipped);
contents = await fs.readFile(path, 'utf8');
expect.equal(contents, 'Hi Jim, Mary, Carol!\n');
let stats = live() ? await stat(path) : DEFAULT_STATS;
assert(stats && !(stats instanceof Error));
expect.equal(stats.mode, '0600');
//
// 3c. A mode and a content change.
//
({changed, failed, ok, skipped} = Context.counts);
await template({
mode: '0644',
path,
src: resource.template('sample.txt.erb'),
variables: {
greeting: 'Yo',
names: ['Derek'],
},
});
expect.equal(Context.counts.changed, changed + 1);
expect.equal(Context.counts.failed, failed);
expect.equal(Context.counts.ok, ok);
expect.equal(Context.counts.skipped, skipped);
contents = await fs.readFile(path, 'utf8');
expect.equal(contents, 'Yo Derek!\n');
stats = live() ? await stat(path) : DEFAULT_STATS;
assert(stats && !(stats instanceof Error));
expect.equal(stats.mode, '0644');
});
task('touch an item', async () => {
//
// 1. Create a file for the first time.
//
let path = join(await tempdir('meta'), 'example.txt');
let {changed, failed, ok, skipped} = Context.counts;
await file({
path,
state: 'touch',
});
let contents = await fs.readFile(path, 'utf8');
expect.equal(contents, '');
expect.equal(Context.counts.changed, changed + 1);
expect.equal(Context.counts.failed, failed);
expect.equal(Context.counts.ok, ok);
expect.equal(Context.counts.skipped, skipped);
//
// 2. Touch an existing entity.
//
const now = Date.now();
const recent = now - 3_600_000; // An hour ago.
await fs.utimes(path, recent, recent);
({changed, failed, ok, skipped} = Context.counts);
await file({
path,
state: 'touch',
});
expect.equal(Context.counts.changed, changed + 1);
expect.equal(Context.counts.failed, failed);
expect.equal(Context.counts.ok, ok);
expect.equal(Context.counts.skipped, skipped);
const stats = await fs.stat(path);
// Assert that mtime is within 1 second, allowing some imprecision.
expect.ok(Math.abs(stats.mtimeMs - now) < 1_000);
});
task("don't notify a handler", async () => {
await command('mkdir', ['/etc'], {
creates: '/etc',
notify: 'should not to be called',
});
});
task('notify a handler', async () => {
await command('true', [], {
notify: 'handle command',
});
});
handler('should not to be called', async () => {
fail('handler fired');
});
handler('handle command', async () => {
await command('true', []);
}); | the_stack |
import * as os from 'os';
import * as im from 'immutable';
import * as ast from './ast';
import * as lexer from './lexer';
import * as lexical from './lexical';
// ---------------------------------------------------------------------------
type precedence = number;
const applyPrecedence: precedence = 2, // Function calls and indexing.
unaryPrecedence: precedence = 4, // Logical and bitwise negation, unary + -
maxPrecedence: precedence = 16; // Local, If, Import, Function, Error
var bopPrecedence = im.Map<ast.BinaryOp, precedence>({
"BopMult": 5,
"BopDiv": 5,
"BopPercent": 5,
"BopPlus": 6,
"BopMinus": 6,
"BopShiftL": 7,
"BopShiftR": 7,
"BopGreater": 8,
"BopGreaterEq": 8,
"BopLess": 8,
"BopLessEq": 8,
"BopManifestEqual": 9,
"BopManifestUnequal": 9,
"BopBitwiseAnd": 10,
"BopBitwiseXor": 11,
"BopBitwiseOr": 12,
"BopAnd": 13,
"BopOr": 14,
});
// ---------------------------------------------------------------------------
const makeUnexpectedError = (
t: lexer.Token, during: string
): lexical.StaticError => {
return lexical.MakeStaticError(
`Unexpected: ${t} while ${during}`,
t.loc);
}
const locFromTokens = (
begin: lexer.Token, end: lexer.Token
): lexical.LocationRange => {
return lexical.MakeLocationRange(begin.loc.fileName, begin.loc.begin, end.loc.end)
}
const locFromTokenAST = (
begin: lexer.Token, end: ast.Node
): lexical.LocationRange => {
return lexical.MakeLocationRange(
begin.loc.fileName, begin.loc.begin, end.loc.end)
}
// ---------------------------------------------------------------------------
class parser {
private currT: number = 0;
constructor(
readonly t: lexer.Tokens
) {}
public pop = (): lexer.Token => {
const t = this.t.get(this.currT);
this.currT++
return t
};
public popExpect = (
tk: lexer.TokenKind
): lexer.Token | lexical.StaticError => {
const t = this.pop();
if (t.kind !== tk) {
return lexical.MakeStaticError(
`Expected token ${lexer.TokenKindStrings.get(tk)} but got ${t}`,
t.loc);
}
return t;
};
public popExpectOp = (
op: string
): lexer.Token | lexical.StaticError => {
const t = this.pop();
if (t.kind !== "TokenOperator" || t.data != op) {
return lexical.MakeStaticError(
`Expected operator ${op} but got ${t}`, t.loc);
}
return t
};
public peek = (): lexer.Token => {
return this.t.get(this.currT);
};
// parseOptionalComments parses a block of comments if they exist at
// the current position in the token stream (as measured by
// `this.peek()`), and has no effect if they don't.
public parseOptionalComments = ()
: ast.CppComment | ast.CComment | ast.HashComment | null => {
const next = this.peek();
switch (next.kind) {
case "TokenCommentCpp": {
return this.parseCppCommentBlock();
}
case "TokenCommentC": {
return this.parseCComment();
}
case "TokenCommentHash": {
return this.parseHashCommentBlock();
}
default: {
return null;
}
}
};
public parseCppCommentBlock = ()
: ast.CppComment | ast.CComment | ast.HashComment | null => {
let lines = im.List<string>();
const first = this.peek();
let curr = this.peek();
while (true) {
curr = this.peek();
switch (curr.kind) {
case "TokenCommentCpp": {
if (curr.fodder != null) {
const anyNewlines = curr.fodder.filter(fodder =>
fodder.data.match(/^\n\s*\n/) != null);
if (anyNewlines.length) {
curr = this.pop();
lines = im.List<string>([curr.data]);
break;
}
}
curr = this.pop();
lines = lines.push(curr.data);
break;
}
case "TokenCommentC": {
return this.parseCComment();
}
case "TokenCommentHash": {
return this.parseHashCommentBlock();
}
default: {
return lines.count() == 0
? null
: new ast.CppComment(lines, locFromTokens(first, curr));
}
}
}
}
public parseCComment = ()
: ast.CppComment | ast.CComment | ast.HashComment | null => {
let lines = im.List<string>();
let next = this.peek();
while (true) {
next = this.peek();
switch (next.kind) {
case "TokenCommentCpp": {
return this.parseCppCommentBlock();
}
case "TokenCommentC": {
// NOTE: This does not trim the whitespace in the last line.
// For example, if a multi-line comment ends: ` */`, then
// the line will end with 3 space characters.
const processedLines = next.data
.split(os.EOL)
.map(line => {
const m = line.match(/^\s*\*/);
if (m == null) {
return line;
}
return line.slice(m[0].length);
});
next = this.pop();
lines = im.List<string>(processedLines);
break;
}
case "TokenCommentHash": {
return this.parseHashCommentBlock();
}
default: {
return lines.count() == 0
? null
: new ast.CComment(lines, next.loc);
}
}
}
}
public parseHashCommentBlock = ()
: ast.CppComment | ast.CComment | ast.HashComment | null => {
let lines = im.List<string>();
const first = this.peek();
let curr = this.peek();
while (true) {
curr = this.peek();
switch (curr.kind) {
case "TokenCommentCpp": {
return this.parseCppCommentBlock();
}
case "TokenCommentC": {
return this.parseCComment();
}
case "TokenCommentHash": {
if (curr.fodder != null) {
const anyNewlines = curr.fodder.filter(fodder =>
fodder.data.match(/^\n\s*\n/) != null);
if (anyNewlines.length) {
curr = this.pop();
lines = im.List<string>([curr.data]);
break;
}
}
curr = this.pop();
lines = lines.push(curr.data);
break;
}
default: {
return lines.count() == 0
? null
: new ast.HashComment(lines, locFromTokens(first, curr));
}
}
}
}
public parseCommaList = <T extends ast.Node>(
end: lexer.TokenKind, elementKind: string,
elementCallback: (e: ast.Node) => T | lexical.StaticError = (e) => <T>e,
): {next: lexer.Token, exprs: im.List<T>, gotComma: boolean} | lexical.StaticError => {
let exprs = im.List<T>();
let gotComma = false;
let first = true;
while (true) {
let next = this.peek();
if (!first && !gotComma) {
if (next.kind === "TokenComma") {
this.pop();
next = this.peek();
gotComma = true;
}
}
if (next.kind === end) {
// gotComma can be true or false here.
return {next: this.pop(), exprs: exprs, gotComma: gotComma};
}
if (!first && !gotComma) {
return lexical.MakeStaticError(
`Expected a comma before next ${elementKind}.`, next.loc);
}
const expr = this.parse(maxPrecedence, null);
if (lexical.isStaticError(expr)) {
return expr;
}
const mappedExpr = elementCallback(expr);
if (lexical.isStaticError(mappedExpr)) {
return mappedExpr;
}
exprs = exprs.push(mappedExpr);
gotComma = false;
first = false;
}
}
public parseArgsList = (
elementKind: string
): {next: lexer.Token, params: ast.Nodes, gotComma: boolean} | lexical.StaticError => {
const result = this.parseCommaList<ast.Node>(
"TokenParenR",
elementKind,
(expr): ast.Node | lexical.StaticError => {
const next = this.peek();
let rhs: ast.Node | null = null;
if (ast.isVar(expr) && next.kind === "TokenOperator" &&
next.data === "="
) {
this.pop();
const assignment = this.parse(maxPrecedence, null);
if (lexical.isStaticError(assignment)) {
return assignment;
}
return new ast.ApplyParamAssignment(
expr.id.name, assignment, expr.loc);
}
return expr;
});
if (lexical.isStaticError(result)) {
return result;
}
return {next: result.next, params: result.exprs, gotComma: result.gotComma};
}
public parseParamsList = (
elementKind: string
): {next: lexer.Token, params: ast.FunctionParams, gotComma: boolean} | lexical.StaticError => {
const result = this.parseCommaList<ast.FunctionParam>(
"TokenParenR",
elementKind,
(expr): ast.FunctionParam | lexical.StaticError => {
if (!ast.isVar(expr)) {
return lexical.MakeStaticError(
`Expected simple identifier but got a complex expression.`,
expr.loc);
}
const next = this.peek();
let rhs: ast.Node | null = null;
if (next.kind === "TokenOperator" && next.data === "=") {
this.pop();
const assignment = this.parse(maxPrecedence, null);
if (lexical.isStaticError(assignment)) {
return assignment;
}
rhs = assignment;
}
return new ast.FunctionParam(expr.id.name, rhs, expr.loc);
});
if (lexical.isStaticError(result)) {
return result;
}
return {next: result.next, params: result.exprs, gotComma: result.gotComma};
}
public parseBind = (
localToken: lexer.Token, binds: ast.LocalBinds
): ast.LocalBinds | lexical.StaticError => {
const varID = this.popExpect("TokenIdentifier");
if (lexical.isStaticError(varID)) {
return varID;
}
for (let b of binds.toArray()) {
if (b.variable.name === varID.data) {
return lexical.MakeStaticError(
`Duplicate local var: ${varID.data}`, varID.loc);
}
}
if (this.peek().kind === "TokenParenL") {
this.pop();
const result = this.parseParamsList("function parameter");
if (lexical.isStaticError(result)) {
return result;
}
const pop = this.popExpectOp("=")
if (lexical.isStaticError(pop)) {
return pop;
}
const body = this.parse(maxPrecedence, null);
if (lexical.isStaticError(body)) {
return body;
}
const id = new ast.Identifier(varID.data, varID.loc);
const {params: params, gotComma: gotComma} = result;
const location = locFromTokenAST(localToken, body);
const bind = new ast.LocalBind(
id, body, true, params, gotComma, location);
binds = binds.push(bind);
} else {
const pop = this.popExpectOp("=");
if (lexical.isStaticError(pop)) {
return pop;
}
const body = this.parse(maxPrecedence, null);
if (lexical.isStaticError(body)) {
return body;
}
const id = new ast.Identifier(varID.data, varID.loc);
const location = locFromTokenAST(localToken, body);
const bind = new ast.LocalBind(
id, body, false, im.List<ast.FunctionParam>(), false, location);
binds = binds.push(bind);
}
return binds;
};
public parseObjectAssignmentOp = (
): {plusSugar: boolean, hide: ast.ObjectFieldHide} | lexical.StaticError => {
let plusSugar = false;
let hide: ast.ObjectFieldHide | null = null;
const op = this.popExpect("TokenOperator");
if (lexical.isStaticError(op)) {
return op;
}
let opStr = op.data;
if (opStr[0] === '+') {
plusSugar = true;
opStr = opStr.slice(1);
}
let numColons = 0
while (opStr.length > 0) {
if (opStr[0] !== ':') {
return lexical.MakeStaticError(
`Expected one of :, ::, :::, +:, +::, +:::, got: ${op.data}`,
op.loc);
}
opStr = opStr.slice(1);
numColons++
}
switch (numColons) {
case 1:
hide = "ObjectFieldInherit";
break;
case 2:
hide = "ObjectFieldHidden"
break;
case 3:
hide = "ObjectFieldVisible"
break;
default:
return lexical.MakeStaticError(
`Expected one of :, ::, :::, +:, +::, +:::, got: ${op.data}`,
op.loc);
}
return {plusSugar: plusSugar, hide: hide};
};
// parseObjectCompRemainder parses the remainder of an object as an
// object comprehension. This function is meant to act in conjunction
// with `parseObjectCompRemainder`, and is meant to be called
// immediately after the `for` token is encountered, since this is
// typically the first indication that we are in an object
// comprehension. Partially to enforce this condition, this function
// takes as an argument the token representing the `for` keyword.
public parseObjectCompRemainder = (
first: lexer.Token, forTok: lexer.Token, gotComma: boolean,
fields: ast.ObjectFields,
): {comp: ast.Node, last: lexer.Token} | lexical.StaticError => {
let numFields = 0;
let numAsserts = 0;
let field = fields.first();
for (field of fields.toArray()) {
if (field.kind === "ObjectLocal") {
continue;
}
if (field.kind === "ObjectAssert") {
numAsserts++;
continue;
}
numFields++;
}
if (numAsserts > 0) {
return lexical.MakeStaticError(
"Object comprehension cannot have asserts.", forTok.loc);
}
if (numFields != 1) {
return lexical.MakeStaticError(
"Object comprehension can only have one field.", forTok.loc);
}
if (field.hide != "ObjectFieldInherit") {
return lexical.MakeStaticError(
"Object comprehensions cannot have hidden fields.", forTok.loc);
}
if (field.kind !== "ObjectFieldExpr") {
return lexical.MakeStaticError(
"Object comprehensions can only have [e] fields.", forTok.loc);
}
const result = this.parseCompSpecs("TokenBraceR");
if (lexical.isStaticError(result)) {
return result;
}
const comp = new ast.ObjectComp(
fields,
gotComma,
result.compSpecs,
locFromTokens(first, result.maybeIf),
);
return {comp: comp, last: result.maybeIf};
};
// parseObjectField will parse a single field in an object.
public parseObjectField = (
headingComments: ast.BindingComment, next: lexer.Token,
literalFields: im.Set<literalField>,
): {field: ast.ObjectField, literals: im.Set<literalField>} | lexical.StaticError => {
let kind: ast.ObjectFieldKind;
let expr1: ast.Node | null = null;
let id: ast.Identifier | null = null;
switch (next.kind) {
case "TokenIdentifier": {
kind = "ObjectFieldID";
id = new ast.Identifier(next.data, next.loc);
break;
}
case "TokenStringDouble": {
kind = "ObjectFieldStr";
expr1 = new ast.LiteralStringDouble(next.data, next.loc);
break;
}
case "TokenStringSingle": {
kind = "ObjectFieldStr";
expr1 = new ast.LiteralStringSingle(next.data, next.loc);
break;
}
case "TokenStringBlock": {
kind = "ObjectFieldStr"
expr1 = new ast.LiteralStringBlock(
next.data, next.stringBlockIndent, next.loc);
break;
}
default: {
kind = "ObjectFieldExpr"
const expr1 = this.parse(maxPrecedence, null);
if (lexical.isStaticError(expr1)) {
return expr1;
}
const pop = this.popExpect("TokenBracketR");
if (lexical.isStaticError(pop)) {
return pop;
}
break;
}
}
let isMethod = false;
let methComma = false;
let params = im.List<ast.FunctionParam>();
if (this.peek().kind === "TokenParenL") {
this.pop();
const result = this.parseParamsList("method parameter");
if (lexical.isStaticError(result)) {
return result;
}
params = result.params;
isMethod = true
}
const result = this.parseObjectAssignmentOp();
if (lexical.isStaticError(result)) {
return result;
}
if (result.plusSugar && isMethod) {
return lexical.MakeStaticError(
`Cannot use +: syntax sugar in a method: ${next.data}`, next.loc);
}
if (kind !== "ObjectFieldExpr") {
if (literalFields.contains(next.data)) {
return lexical.MakeStaticError(
`Duplicate field: ${next.data}`, next.loc);
}
literalFields = literalFields.add(next.data);
}
const body = this.parse(maxPrecedence, null);
if (lexical.isStaticError(body)) {
return body;
}
// TODO: The location range here is probably not quite correct.
// For example, in cases where `body` is a string literal, the
// location range will only reflect the string contents, not the
// ending quote.
return {
field: new ast.ObjectField(
kind,
result.hide,
result.plusSugar,
isMethod,
expr1,
id,
params,
methComma,
body,
null,
headingComments,
locFromTokenAST(next, body),
),
literals: literalFields
};
}
// parseObjectLocal parses a `local` definition that appears in an
// object, as an object field. `assertToken` is required to allow the
// object to create an appropriate location range for the field.
public parseObjectLocal = (
localToken: lexer.Token, binds: ast.IdentifierSet,
): {field: ast.ObjectField, binds: ast.IdentifierSet} | lexical.StaticError => {
const varID = this.popExpect("TokenIdentifier");
if (lexical.isStaticError(varID)) {
return varID;
}
const id = new ast.Identifier(varID.data, varID.loc);
if (binds.contains(id.name)) {
return lexical.MakeStaticError(
`Duplicate local var: ${id.name}`, varID.loc);
}
let isMethod = false;
let funcComma = false;
let params = im.List<ast.FunctionParam>();
if (this.peek().kind === "TokenParenL") {
this.pop();
const result = this.parseParamsList("function parameter");
if (lexical.isStaticError(result)) {
return result;
}
isMethod = true;
params = result.params;
}
const pop = this.popExpectOp("=");
if (lexical.isStaticError(pop)) {
return pop;
}
const body = this.parse(maxPrecedence, null);
if (lexical.isStaticError(body)) {
return body;
}
binds = binds.add(id.name);
return {
field: new ast.ObjectField(
"ObjectLocal",
"ObjectFieldVisible",
false,
isMethod,
null,
id,
params,
funcComma,
body,
null,
null,
locFromTokenAST(localToken, body),
),
binds: binds,
};
};
// parseObjectAssert parses an `assert` that appears as an object
// field. `localToken` is required to allow the object to create an
// appropriate location range for the field.
public parseObjectAssert = (
localToken: lexer.Token,
): ast.ObjectField | lexical.StaticError => {
const cond = this.parse(maxPrecedence, null)
if (lexical.isStaticError(cond)) {
return cond;
}
let msg: ast.Node | null = null;
if (this.peek().kind === "TokenOperator" && this.peek().data == ":") {
this.pop();
const result = this.parse(maxPrecedence, null);
if (lexical.isStaticError(result)) {
return result;
}
msg = result;
}
// Message is optional, so location range changes based on whether
// it's present.
const loc: lexical.LocationRange = msg == null
? locFromTokenAST(localToken, cond)
: locFromTokenAST(localToken, msg);
return new ast.ObjectField(
"ObjectAssert",
"ObjectFieldVisible",
false,
false,
null,
null,
im.List<ast.FunctionParam>(),
false,
cond,
msg,
null,
loc,
);
};
// parseObjectRemainder parses "the rest" of an object, typically
// immediately after we encounter the '{' character.
public parseObjectRemainder = (
tok: lexer.Token, heading: ast.BindingComment,
): {objRemainder: ast.Node, next: lexer.Token} | lexical.StaticError => {
let fields = im.List<ast.ObjectField>();
let literalFields = im.Set<literalField>();
let binds = im.Set<ast.IdentifierName>()
let gotComma = false
let first = true
while (true) {
// Comments for an object field are allowed to be of either of
// these forms:
//
// // Explains `foo`.
// foo: "bar",
//
// or (note the leading comma before the field):
//
// // Explains `foo`.
// , foo: "bar"
//
// To accomodate both styles, we attempt to parse comments
// before and after the comma. If there are comments after, that
// is becomes the heading comment for that field; if not, then
// we use any comments that happen after the line that contains
// the last field, but before the comma. So, for example, we
// ignore the following comment:
//
// , foo: "value1" // This comment is not a heading comment.
// // But this one is.
// , bar: "value2"
let headingComments = this.parseOptionalComments();
let next = this.peek();
if (!gotComma && !first) {
if (next.kind === "TokenComma") {
this.pop();
next = this.peek();
gotComma = true
}
}
const thisKind = this.peek().kind;
if (
thisKind === "TokenCommentCpp" || thisKind === "TokenCommentC" ||
thisKind === "TokenCommentHash"
) {
headingComments = this.parseOptionalComments();
}
next = this.pop();
// Done parsing the object. Return.
if (next.kind === "TokenBraceR") {
return {
objRemainder: new ast.ObjectNode(
fields, gotComma, heading, locFromTokens(tok, next)),
next: next
};
}
// Object comprehension.
if (next.kind === "TokenFor") {
const result = this.parseObjectCompRemainder(
tok, next, gotComma, fields)
if (lexical.isStaticError(result)) {
return result;
}
return {objRemainder: result.comp, next: result.last};
}
if (!gotComma && !first) {
return lexical.MakeStaticError(
"Expected a comma before next field.", next.loc);
}
first = false;
// Start to parse an object field. There are basically 3 valid
// cases:
// 1. An object field. The key is a string, an identifier, or a
// computed field.
// 2. A `local` definition.
// 3. An `assert`.
switch (next.kind) {
case "TokenBracketL":
case "TokenIdentifier":
case "TokenStringDouble":
case "TokenStringSingle":
case "TokenStringBlock": {
const result = this.parseObjectField(
headingComments, next, literalFields);
if (lexical.isStaticError(result)) {
return result;
}
literalFields = result.literals;
fields = fields.push(result.field);
break;
}
case "TokenLocal": {
const result = this.parseObjectLocal(next, binds);
if (lexical.isStaticError(result)) {
return result;
}
binds = result.binds;
fields = fields.push(result.field);
break;
}
case "TokenAssert": {
const field = this.parseObjectAssert(next);
if (lexical.isStaticError(field)) {
return field;
}
fields = fields.push(field);
break;
}
default: {
return makeUnexpectedError(next, "parsing field definition");
}
}
gotComma = false;
}
};
// parseCompSpecs parses expressions of the form (e.g.) `for x in expr
// for y in expr if expr for z in expr ...`
public parseCompSpecs = (
end: lexer.TokenKind
): {compSpecs: ast.CompSpecs, maybeIf: lexer.Token} | lexical.StaticError => {
let specs = im.List<ast.CompSpec>();
while (true) {
const varID = this.popExpect("TokenIdentifier");
if (lexical.isStaticError(varID)) {
return varID;
}
const id: ast.Identifier = new ast.Identifier(varID.data, varID.loc);
const pop = this.popExpect("TokenIn");
if (lexical.isStaticError(pop)) {
return pop;
}
const arr = this.parse(maxPrecedence, null);
if (lexical.isStaticError(arr)) {
return arr;
}
specs = specs.push(new ast.CompSpecFor(
id, arr, locFromTokenAST(varID, arr)));
let maybeIf = this.pop();
for (; maybeIf.kind === "TokenIf"; maybeIf = this.pop()) {
const cond = this.parse(maxPrecedence, null);
if (lexical.isStaticError(cond)) {
return cond;
}
specs = specs.push(new ast.CompSpecIf(
cond, locFromTokenAST(maybeIf, cond)));
}
if (maybeIf.kind === end) {
return {compSpecs: specs, maybeIf: maybeIf};
}
if (maybeIf.kind !== "TokenFor") {
const tokenKind = lexer.TokenKindStrings.get(end);
return lexical.MakeStaticError(
`Expected for, if or ${tokenKind} after for clause, got: ${maybeIf}`, maybeIf.loc);
}
}
};
// parseArrayRemainder parses "the rest" of an array literal,
// typically immediately after we encounter the '[' character.
public parseArrayRemainder = (
tok: lexer.Token
): ast.Node | lexical.StaticError => {
let next = this.peek();
if (next.kind === "TokenBracketR") {
this.pop();
return new ast.Array(
im.List<ast.Node>(), false, null, null, locFromTokens(tok, next));
}
const first = this.parse(maxPrecedence, null);
if (lexical.isStaticError(first)) {
return first;
}
let gotComma = false;
next = this.peek();
if (next.kind === "TokenComma") {
this.pop();
next = this.peek();
gotComma = true;
}
if (next.kind === "TokenFor") {
// It's a comprehension
this.pop();
const result = this.parseCompSpecs("TokenBracketR");
if (lexical.isStaticError(result)) {
return result;
}
return new ast.ArrayComp(
first, gotComma, result.compSpecs, locFromTokens(tok, result.maybeIf));
}
// Not a comprehension: It can have more elements.
let elements = im.List<ast.Node>([first]);
while (true) {
if (next.kind === "TokenBracketR") {
// TODO(dcunnin): SYNTAX SUGAR HERE (preserve comma)
this.pop();
break;
}
if (!gotComma) {
return lexical.MakeStaticError(
"Expected a comma before next array element.", next.loc);
}
const nextElem = this.parse(maxPrecedence, null);
if (lexical.isStaticError(nextElem)) {
return nextElem;
}
elements = elements.push(nextElem);
// Throw away comments before the comma.
this.parseOptionalComments();
next = this.peek();
if (next.kind === "TokenComma") {
this.pop();
next = this.peek();
gotComma = true;
} else {
gotComma = false;
}
// Throw away comments after the comma.
this.parseOptionalComments();
}
// TODO: Remove trailing whitespace here after we emit newlines
// from the lexer. If we don't do that, we might accidentally kill
// comments that correspond to, e.g., the next field of an object.
return new ast.Array(
elements, gotComma, null, null, locFromTokens(tok, next));
};
public parseTerminal = (
heading: ast.BindingComment,
): ast.Node | lexical.StaticError => {
let tok = this.pop();
switch (tok.kind) {
case "TokenAssert":
case "TokenBraceR":
case "TokenBracketR":
case "TokenComma":
case "TokenDot":
case "TokenElse":
case "TokenError":
case "TokenFor":
case "TokenFunction":
case "TokenIf":
case "TokenIn":
case "TokenImport":
case "TokenImportStr":
case "TokenLocal":
case "TokenOperator":
case "TokenParenR":
case "TokenSemicolon":
case "TokenTailStrict":
case "TokenThen":
return makeUnexpectedError(tok, "parsing terminal");
case "TokenEndOfFile":
return lexical.MakeStaticError("Unexpected end of file.", tok.loc);
case "TokenBraceL": {
const result = this.parseObjectRemainder(tok, heading);
if (lexical.isStaticError(result)) {
return result;
}
return result.objRemainder;
}
case "TokenBracketL":
return this.parseArrayRemainder(tok);
case "TokenParenL": {
const inner = this.parse(maxPrecedence, null);
if (lexical.isStaticError(inner)) {
return inner;
}
const pop = this.popExpect("TokenParenR");
if (lexical.isStaticError(pop)) {
return pop;
}
return inner;
}
// Literals
case "TokenNumber": {
// This shouldn't fail as the lexer should make sure we have
// good input but we handle the error regardless.
const num = Number(tok.data);
// TODO: Figure out whether this is correct.
if (isNaN(num) && tok.data !== "NaN") {
return lexical.MakeStaticError(
"Could not parse floating point number.", tok.loc);
}
return new ast.LiteralNumber(num, tok.data, tok.loc);
}
case "TokenStringSingle":
return new ast.LiteralStringSingle(tok.data, tok.loc);
case "TokenStringDouble":
return new ast.LiteralStringDouble(tok.data, tok.loc);
case "TokenStringBlock":
return new ast.LiteralStringBlock(
tok.data, tok.stringBlockIndent, tok.loc);
case "TokenFalse":
return new ast.LiteralBoolean(false, tok.loc);
case "TokenTrue":
return new ast.LiteralBoolean(true, tok.loc);
case "TokenNullLit":
return new ast.LiteralNull(tok.loc);
// Variables
case "TokenDollar":
return new ast.Dollar(tok.loc);
case "TokenIdentifier": {
const id = new ast.Identifier(tok.data, tok.loc);
return new ast.Var(id, tok.loc);
}
case "TokenSelf":
return new ast.Self(tok.loc);
case "TokenSuper": {
const next = this.pop();
let index: ast.Node | null = null;
let id: ast.Identifier | null = null;
switch (next.kind) {
case "TokenDot": {
const fieldID = this.popExpect("TokenIdentifier");
if (lexical.isStaticError(fieldID)) {
return fieldID;
}
id = new ast.Identifier(fieldID.data, fieldID.loc);
break;
}
case "TokenBracketL": {
let parseErr: lexical.StaticError | null;
const result = this.parse(maxPrecedence, null);
if (lexical.isStaticError(result)) {
return result;
}
index = result;
const pop = this.popExpect("TokenBracketR");
if (lexical.isStaticError(pop)) {
return pop;
}
break;
}
default:
return lexical.MakeStaticError(
"Expected . or [ after super.", tok.loc);
}
return new ast.SuperIndex(index, id, tok.loc);
}
}
return lexical.MakeStaticError(
`INTERNAL ERROR: Unknown tok kind: ${tok.kind}`, tok.loc);
}
// parse is the main parsing routine.
public parse = (
prec: precedence, heading: ast.BindingComment
): ast.Node | lexical.StaticError => {
let begin = this.peek();
// Consume heading comments if they exist.
heading = this.parseOptionalComments();
switch (begin.kind) {
// These cases have effectively maxPrecedence as the first call
// to parse will parse them.
case "TokenAssert": {
this.pop();
const cond = this.parse(maxPrecedence, null);
if (lexical.isStaticError(cond)) {
return cond;
}
let msg: ast.Node | null = null;
if (this.peek().kind === "TokenOperator" && this.peek().data === ":") {
this.pop();
const result = this.parse(maxPrecedence, null);
if (lexical.isStaticError(result)) {
return result;
}
msg = result;
}
const pop = this.popExpect("TokenSemicolon");
if (lexical.isStaticError(pop)) {
return pop;
}
const rest = this.parse(maxPrecedence, null);
if (lexical.isStaticError(rest)) {
return rest;
}
return new ast.Assert(cond, msg, rest, locFromTokenAST(begin, rest));
}
case "TokenError": {
this.pop();
const expr = this.parse(maxPrecedence, null);
if (lexical.isStaticError(expr)) {
return expr;
}
return new ast.ErrorNode(expr, locFromTokenAST(begin, expr));
}
case "TokenIf": {
this.pop();
const cond = this.parse(maxPrecedence, null);
if (lexical.isStaticError(cond)) {
return cond;
}
const pop = this.popExpect("TokenThen");
if (lexical.isStaticError(pop)) {
return pop;
}
const branchTrue = this.parse(maxPrecedence, null);
if (lexical.isStaticError(branchTrue)) {
return branchTrue;
}
let branchFalse: ast.Node | null = null;
let lr = locFromTokenAST(begin, branchTrue);
if (this.peek().kind === "TokenElse") {
this.pop();
const branchFalse = this.parse(maxPrecedence, null);
if (lexical.isStaticError(branchFalse)) {
return branchFalse;
}
lr = locFromTokenAST(begin, branchFalse)
}
return new ast.Conditional(cond, branchTrue, branchFalse, lr);
}
case "TokenFunction": {
this.pop();
const next = this.pop();
if (next.kind === "TokenParenL") {
const result = this.parseParamsList("function parameter");
if (lexical.isStaticError(result)) {
return result;
}
const body = this.parse(maxPrecedence, null);
if (lexical.isStaticError(body)) {
return body;
}
const fn = new ast.Function(
result.params,
result.gotComma,
body,
null,
im.List<ast.Comment>(),
locFromTokenAST(begin, body),
);
return fn;
}
return lexical.MakeStaticError(`Expected ( but got ${next}`, next.loc);
}
case "TokenImport": {
this.pop();
const body = this.parse(maxPrecedence, null);
if (lexical.isStaticError(body)) {
return body;
}
if (ast.isLiteralString(body)) {
return new ast.Import(body.value, locFromTokenAST(begin, body));
}
return lexical.MakeStaticError(
"Computed imports are not allowed", body.loc);
}
case "TokenImportStr": {
this.pop();
const body = this.parse(maxPrecedence, null);
if (lexical.isStaticError(body)) {
return body;
}
if (ast.isLiteralString(body)) {
return new ast.ImportStr(body.value, locFromTokenAST(begin, body));
}
return lexical.MakeStaticError(
"Computed imports are not allowed", body.loc);
}
case "TokenLocal": {
this.pop();
let binds = im.List<ast.LocalBind>();
while (true) {
const newBinds = this.parseBind(begin, binds);
if (lexical.isStaticError(newBinds)) {
return newBinds;
}
binds = newBinds;
const delim = this.pop();
if (delim.kind !== "TokenSemicolon" && delim.kind !== "TokenComma") {
const msg = `Expected , or ; but got ${delim}`;
const rest = restFromBinds(newBinds);
if (rest == null) {
return lexical.MakeStaticError(msg, delim.loc);
}
return lexical.MakeStaticErrorRest(
rest, msg, delim.loc);
}
if (delim.kind === "TokenSemicolon") {
break;
}
}
const body = this.parse(maxPrecedence, null);
if (lexical.isStaticError(body)) {
return body;
}
return new ast.Local(binds, body, locFromTokenAST(begin, body));
}
default: {
// Unary operator
if (begin.kind === "TokenOperator") {
const uop = ast.UopMap.get(begin.data);
if (uop == undefined) {
return lexical.MakeStaticError(
`Not a unary operator: ${begin.data}`, begin.loc);
}
if (prec == unaryPrecedence) {
const op = this.pop();
const expr = this.parse(prec, null);
if (lexical.isStaticError(expr)) {
return expr;
}
return new ast.Unary(uop, expr, locFromTokenAST(op, expr));
}
}
// Base case
if (prec == 0) {
return this.parseTerminal(heading);
}
let lhs = this.parse(prec-1, heading);
if (lexical.isStaticError(lhs)) {
return lhs;
}
while (true) {
// Then next token must be a binary operator.
let bop: ast.BinaryOp | null = null;
// Check precedence is correct for this level. If we're
// parsing operators with higher precedence, then return lhs
// and let lower levels deal with the operator.
switch (this.peek().kind) {
case "TokenOperator": {
// _ = "breakpoint"
if (this.peek().data === ":" || this.peek().data === "=") {
// Special case for the colons in assert. Since COLON
// is no-longer a special token, we have to make sure
// it does not trip the op_is_binary test below. It
// should terminate parsing of the expression here,
// returning control to the parsing of the actual
// assert AST.
return lhs;
}
bop = ast.BopMap.get(this.peek().data);
if (bop == undefined) {
return lexical.MakeStaticError(
`Not a binary operator: ${this.peek().data}`, this.peek().loc);
}
if (bopPrecedence.get(bop) != prec) {
return lhs;
}
break;
}
case "TokenDot":
case "TokenBracketL":
case "TokenParenL":
case "TokenBraceL": {
if (applyPrecedence != prec) {
return lhs;
}
break;
}
default:
return lhs;
}
const op = this.pop();
switch (op.kind) {
case "TokenBracketL": {
const index = this.parse(maxPrecedence, null);
if (lexical.isStaticError(index)) {
return index;
}
const end = this.popExpect("TokenBracketR");
if (lexical.isStaticError(end)) {
return end;
}
lhs = new ast.IndexSubscript(
lhs, index, locFromTokens(begin, end));
break;
}
case "TokenDot": {
const fieldID = this.popExpect("TokenIdentifier");
if (lexical.isStaticError(fieldID)) {
// After the user types a `.`, the document very
// likely doesn't parse. For autocomplete facilities,
// it's useful to return the AST that precedes the `.`
// character (typically a `Var` or `Index`
// expression), so that it is easier to discern what
// to complete.
return lexical.MakeStaticErrorRest(lhs, fieldID.msg, fieldID.loc);
}
const id = new ast.Identifier(fieldID.data, fieldID.loc);
lhs = new ast.IndexDot(lhs, id, locFromTokens(begin, fieldID));
break;
}
case "TokenParenL": {
const result = this.parseArgsList("function argument");
if (lexical.isStaticError(result)) {
return result;
}
const {next: end, params: args, gotComma: gotComma} = result;
let tailStrict = false
if (this.peek().kind === "TokenTailStrict") {
this.pop();
tailStrict = true;
}
lhs = new ast.Apply(
lhs, args, gotComma, tailStrict, locFromTokens(begin, end));
break;
}
case "TokenBraceL": {
const result = this.parseObjectRemainder(op, heading);
if (lexical.isStaticError(result)) {
return result;
}
lhs = new ast.ApplyBrace(
lhs, result.objRemainder, locFromTokens(begin, result.next));
break;
}
default: {
const rhs = this.parse(prec-1, null);
if (lexical.isStaticError(rhs)) {
return rhs;
}
if (bop == null) {
throw new Error(
"INTERNAL ERROR: `parse` can't return a null node unless an `error` is populated");
}
lhs = new ast.Binary(lhs, bop, rhs, locFromTokenAST(begin, rhs));
break;
}
}
}
}
}
}
}
type literalField = string;
// ---------------------------------------------------------------------------
const restFromBinds = (newBinds: ast.LocalBinds): ast.Var | null => {
if (newBinds.count() == 0) {
return null
}
const lastBody = newBinds.last().body;
if (ast.isBinary(lastBody) && lastBody.op === "BopPlus" &&
ast.isVar(lastBody.right)
) {
return lastBody.right;
} else if (ast.isVar(lastBody)) {
return lastBody;
}
return null;
}
// ---------------------------------------------------------------------------
export const Parse = (
t: lexer.Tokens
): ast.Node | lexical.StaticError => {
const p = new parser(t);
const expr = p.parse(maxPrecedence, null);
if (lexical.isStaticError(expr)) {
return expr;
}
// Get rid of any trailing comments.
p.parseOptionalComments();
if (p.peek().kind !== "TokenEndOfFile") {
return lexical.MakeStaticError(`Did not expect: ${p.peek()}`, p.peek().loc);
}
new ast.InitializingVisitor(expr).visit();
return expr;
} | the_stack |
import { createElement, L10n, remove, EmitType } from '@syncfusion/ej2-base';
import { HeatMap } from '../../src/heatmap/heatmap';
import { Title } from '../../src/heatmap/model/base';
import { ILoadedEventArgs, ICellEventArgs } from '../../src/heatmap/model/interface'
import { Adaptor } from '../../src/heatmap/index';
import { MouseEvents } from '../base/event.spec';
import { profile , inMB, getMemoryProfile } from '../../spec/common.spec';
HeatMap.Inject(Adaptor);
describe('Heatmap Control', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
describe('Heatmap series properties and its behavior', () => {
let heatmap: HeatMap;
let ele: HTMLElement;
let tempElement: HTMLElement;
let tooltipElement: HTMLElement;
let created: EmitType<Object>;
let trigger: MouseEvents = new MouseEvents();
let adaptorData: Object = {};
// let trigger: MouseEvents = new MouseEvents();
beforeAll((): void => {
ele = createElement('div', { id: 'container' });
document.body.appendChild(ele);
heatmap = new HeatMap({
width: "100%",
height: "300px",
xAxis: {
title: { text: "Weekdays" },
},
yAxis: {
title: { text: "YAxis" },
},
dataSource: [[10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]],
paletteSettings: {
palette: [{ 'value': 100, 'color': "rgb(255, 255, 153)" },
{ 'value': 50, 'color': "rgb(153, 255, 187)" },
{ 'value': 20, 'color': "rgb(153, 153, 255)" },
{ 'value': 0, 'color': "rgb(255, 159, 128)" },
],
type: "Fixed"
},
legendSettings: {
visible: false
},
});
});
afterAll((): void => {
heatmap.destroy();
});
it('Checking heatmap instance creation', (done: Function) => {
created = (args: Object): void => {
expect(heatmap != null).toBe(true);
done();
}
heatmap.created = created;
heatmap.appendTo('#container');
});
it('Change the xAxis in oposit position', () => {
heatmap.cellSettings.border.width = 2;
heatmap.cellSettings.border.radius = 2;
heatmap.yAxis.opposedPosition = true;
heatmap.dataBind();
tempElement = document.getElementById('container_HeatMapRect_0');
expect(tempElement.getAttribute('x') == '11' || tempElement.getAttribute('y') == '10').toBe(true);
});
it('Check enableCellHighlighting property', () => {
heatmap.cellSettings.enableCellHighlighting = false;
heatmap.refresh();
tempElement = document.getElementById('container_HeatMapRectLabels_0');
trigger.mousemoveEvent(tempElement, 0, 0, 5, 5, false);
tempElement = document.getElementById('container_HeatMapRect_0');
expect(tempElement.getAttribute('opacity')).toBe("1");
});
it('Check enableCellHighlighting property', () => {
heatmap.cellSettings.enableCellHighlighting = true;
heatmap.refresh();
tempElement = document.getElementById('container_HeatMapRectLabels_0');
trigger.mousemoveEvent(tempElement, 0, 0, 5, 5, false);
tempElement = document.getElementById('container_HeatMapRect_0');
expect(tempElement.getAttribute('opacity')).toBe("0.65");
});
it('Check format property', () => {
heatmap.cellSettings.format = "{value}$";
heatmap.refresh();
tempElement = document.getElementById('container_HeatMapRectLabels_0');
expect(tempElement.innerHTML == '100$').toBe(true);
});
it('Check showlable property', () => {
heatmap.cellSettings.showLabel = false;
heatmap.cellSettings.border.width = 0;
heatmap.refresh();
tempElement = document.getElementById('container_HeatMapRectLabels_0');
expect(tempElement).toBe(null);
});
it('Check cell color for a particular cell',() => {
heatmap.cellSettings.showLabel = true;
heatmap.cellRender = function (args: ICellEventArgs) {
if (args.xLabel == '0' && args.yLabel == '9') {
args.cellColor = '#898b2b';
}
}
heatmap.refresh();
tempElement = document.getElementById('container_HeatMapRect_0');
expect(tempElement.getAttribute('fill') == '#898b2b').toBe(true);
});
it('Check enableCanvasRendering property', () => {
heatmap.renderingMode = "Canvas";
heatmap.emptyPointColor = "blue";
heatmap.dataBind();
tempElement = document.getElementById('container_canvas');
expect(tempElement).not.toBe(null);
});
it('Check bubble type heatmap', (done: Function) => {
heatmap.renderingMode = "SVG";
heatmap.cellSettings.tileType = "Bubble";
heatmap.height = '100%';
heatmap.showTooltip = true;
heatmap.dataSource = [[10, 20, 30, 40],
[10, 20, 30, 40],
[10, 20, 30, 40]];
heatmap.cellSettings.showLabel = true;
heatmap.dataBind();
tempElement = document.getElementById('container_HeatMapRect_0');
trigger.mousemoveEvent(tempElement, 0, 0, 0, 20, false);
trigger.mousemoveEvent(tempElement, 0, 0, 60, 20, false);
expect(tempElement.getAttribute('opacity')).toBe("0.65");
tooltipElement = document.getElementById('containerCelltooltipcontainer_svg');
expect(tooltipElement).not.toBe(null);
setTimeout(done, 1600);
});
it('Check bubble(size) type heatmap', (done: Function) => {
heatmap.renderingMode = "SVG";
heatmap.cellSettings.tileType = "Bubble";
heatmap.cellSettings.bubbleType = "Size";
heatmap.showTooltip = true;
heatmap.dataBind();
tempElement = document.getElementById('container_HeatMapRect_0');
trigger.mousemoveEvent(tempElement, 0, 0, 0, 20, false);
trigger.mousemoveEvent(tempElement, 0, 0, 60, 20, false);
tooltipElement = document.getElementById('containerCelltooltipcontainer_svg');
expect(tooltipElement).not.toBe(null);
setTimeout(done, 1600);
});
it('Check minimum size option for bubble(size) type heatmap', (done: Function) => {
heatmap.renderingMode = "SVG";
heatmap.cellSettings.tileType = "Bubble";
heatmap.cellSettings.bubbleType = "Size";
heatmap.cellSettings.bubbleSize.minimum = "50%";
heatmap.showTooltip = true;
heatmap.dataBind();
tempElement = document.getElementById('container_HeatMapRect_0');
expect(tempElement.getAttribute('r') == "45.25" || tempElement.getAttribute('r') == "45.5");
setTimeout(done, 1600);
});
it('Check maximum size option for bubble(size) type heatmap', (done: Function) => {
heatmap.renderingMode = "SVG";
heatmap.cellSettings.tileType = "Bubble";
heatmap.cellSettings.bubbleType = "Size";
heatmap.cellSettings.bubbleSize.maximum = "80%";
heatmap.showTooltip = true;
heatmap.dataBind();
tempElement = document.getElementById('container_HeatMapRect_0');
expect(tempElement.getAttribute('r') == "36.2" || tempElement.getAttribute('r') == "36.4"); setTimeout(done, 1600);
});
it('Check minimum size(minimum value) option for bubble(size) type heatmap', (done: Function) => {
heatmap.renderingMode = "SVG";
heatmap.cellSettings.tileType = "Bubble";
heatmap.cellSettings.bubbleType = "Size";
heatmap.cellSettings.bubbleSize.minimum = "0%";
heatmap.showTooltip = true;
heatmap.dataBind();
tempElement = document.getElementById('container_HeatMapRect_0');
expect(tempElement.getAttribute('r') == "45.25" || tempElement.getAttribute('r') == "45.5");
setTimeout(done, 1600);
});
it('Check maximum size(maximum value) option for bubble(size) type heatmap', (done: Function) => {
heatmap.renderingMode = "SVG";
heatmap.cellSettings.tileType = "Bubble";
heatmap.cellSettings.bubbleType = "Size";
heatmap.cellSettings.bubbleSize.maximum = "100%";
heatmap.showTooltip = true;
heatmap.dataBind();
tempElement = document.getElementById('container_HeatMapRect_0');
expect(tempElement.getAttribute('r') == "36.2" || tempElement.getAttribute('r') == "36.4"); setTimeout(done, 1600);
});
it('Check bubble(sector) type heatmap', (done: Function) => {
heatmap.renderingMode = "SVG";
heatmap.cellSettings.tileType = "Bubble";
heatmap.cellSettings.bubbleType = "Sector";
heatmap.showTooltip = true;
heatmap.dataBind();
tempElement = document.getElementById('container_HeatMapRect_0');
trigger.mousemoveEvent(tempElement, 0, 0, 0, 20, false);
trigger.mousemoveEvent(tempElement, 0, 0, 60, 20, false);
tooltipElement = document.getElementById('containerCelltooltipcontainer_svg');
expect(tooltipElement).not.toBe(null);
tempElement = document.getElementById('container_HeatMapRectLabels_0');
expect(tempElement).toBe(null);
setTimeout(done, 1600);
});
it('Check bubble(sector) type heatmap in Canvas mode', (done: Function) => {
heatmap.renderingMode = "Canvas";
heatmap.dataBind();
tempElement = document.getElementById('container');
heatmap.heatMapMouseMove(<PointerEvent>trigger.onTouchStart(tempElement, null, null, null, null, 0, 80));
heatmap.heatMapMouseMove(<PointerEvent>trigger.onTouchStart(tempElement, null, null, null, null, 50, 80));
tempElement = document.getElementById('containerCelltooltipcontainer');
expect(tempElement.style.visibility).toBe("visible");
setTimeout(done, 1600);
});
it('Check bubble(size) type heatmap in Canvas mode', (done: Function) => {
heatmap.cellSettings.tileType = "Bubble";
heatmap.cellSettings.bubbleType = "Size";
heatmap.cellSettings.border.width = 1;
heatmap.cellSettings.border.color = 'red';
heatmap.dataBind();
tempElement = document.getElementById('container');
heatmap.heatMapMouseMove(<PointerEvent>trigger.onTouchStart(tempElement, null, null, null, null, 0, 80));
heatmap.heatMapMouseMove(<PointerEvent>trigger.onTouchStart(tempElement, null, null, null, null, 50, 80));
tempElement = document.getElementById('containerCelltooltipcontainer');
expect(tempElement.style.visibility).toBe("visible");
setTimeout(done, 1600);
});
it('Check bubble(size) type heatmap in Canvas mode', (done: Function) => {
heatmap.cellSettings.tileType = "Bubble";
heatmap.cellSettings.bubbleType = "Size";
heatmap.cellSettings.border.width = 1;
heatmap.cellSettings.border.color = 'red';
heatmap.dataBind();
tempElement = document.getElementById('container');
heatmap.heatMapMouseMove(<PointerEvent>trigger.onTouchStart(tempElement, null, null, null, null, 0, 80));
heatmap.heatMapMouseMove(<PointerEvent>trigger.onTouchStart(tempElement, null, null, null, null, 50, 80));
tempElement = document.getElementById('containerCelltooltipcontainer');
expect(tempElement.style.visibility).toBe("visible");
setTimeout(done, 1600);
});
it('Check bubble(color) type heatmap in Canvas mode', (done: Function) => {
heatmap.cellSettings.tileType = "Bubble";
heatmap.cellSettings.bubbleType = "Color";
heatmap.dataBind();
tempElement = document.getElementById('container');
heatmap.heatMapMouseMove(<PointerEvent>trigger.onTouchStart(tempElement, null, null, null, null, 0, 80));
heatmap.heatMapMouseMove(<PointerEvent>trigger.onTouchStart(tempElement, null, null, null, null, 50, 80));
tempElement = document.getElementById('containerCelltooltipcontainer');
expect(tempElement.style.visibility).toBe("visible");
setTimeout(done, 1600);
});
it('Check SizeAndColor type heatmap in Canvas mode', (done: Function) => {
heatmap.cellSettings.tileType = "Bubble";
heatmap.cellSettings.bubbleType = "SizeAndColor";
heatmap.dataSource = [
[[0, 320], [40, 360]],
[[80, 240, 40], [120, 280]],
[['', 240], [120, '']],
[[160, 160], [200, 200]],
[[160, null], ['', '']],
[[240, 80], [280, 120]],
[[null, 240], 120],
[[320, 40], [360, 0]],
[[null, null], [360, 0]]
];
heatmap.refresh();
tempElement = document.getElementById('container');
heatmap.heatMapMouseMove(<PointerEvent>trigger.onTouchStart(tempElement, null, null, null, null, 0, 80));
heatmap.heatMapMouseMove(<PointerEvent>trigger.onTouchStart(tempElement, null, null, null, null, 50, 80));
tempElement = document.getElementById('containerCelltooltipcontainer');
expect(tempElement.style.visibility).toBe("visible");
setTimeout(done, 1600);
});
it('Check SizeAndColor type heatmap in Canvas mode', (done: Function) => {
heatmap.renderingMode = "SVG";
heatmap.paletteSettings.type = 'Gradient';
heatmap.legendSettings.showGradientPointer = true;
heatmap.legendSettings.visible = true;
heatmap.refresh();
tempElement = document.getElementById('container');
tempElement = document.getElementById('container_HeatMapRect_0');
trigger.mousemoveEvent(tempElement, 0, 0, 0, 20, false);
trigger.mousemoveEvent(tempElement, 0, 0, 60, 20, false);
tooltipElement = document.getElementById('containerCelltooltipcontainer_svg');
expect(tooltipElement).not.toBe(null);
tempElement = document.getElementById('container_HeatMapRectLabels_0');
expect(tempElement).toBe(null);
setTimeout(done, 1600);
});
it('Check SizeAndColor type heatmap in cell dataSource with Json Cell dataSource', (done: Function) => {
let jsonCellData = [
{
"rowid": "TestX1",
"columnid": "Jan",
"value": "21",
"Men": "21",
"Women": "11"
},
{
"rowid": "Moutain",
"columnid": "Feb",
"value": "24",
"Men": null,
"Women": "41"
},
{
"rowid": "Moutain",
"columnid": "TestY2",
"value": "24",
"Men": "41",
"Women": "28"
},
{
"rowid": "TestX2",
"columnid": "Mar",
"value": "25"
},
{
"rowid": "Pacific",
"columnid": "Apr",
"value": "27",
"Men": "81",
"Women": "14"
},
{
"rowid": "Pacific",
"columnid": "TestY1",
"value": "27",
"Men": "",
"Women": null
},
{
"rowid": "TestX3",
"columnid": "May",
"value": "32",
"Men": "",
"Women": "19"
},
{
"rowid": "TestX3",
"columnid": "Jun",
"value": "34"
},
{
"rowid": "TestX1",
"columnid": "Jun",
"value": "34",
"Men": "50",
"Women": "13"
}
];
adaptorData = {
isJsonData: true,
adaptorType: "Cell",
xDataMapping: "rowid",
yDataMapping: "columnid",
valueMapping: "value",
bubbleDataMapping: { size: 'Men', color: 'Women' }
};
heatmap.xAxis.labels = ['TestX1', 'Pacific', 'TestX2', 'Moutain', 'TestX3'];
heatmap.yAxis.labels = ['TestY1', 'Jan', 'Feb', 'Mar', 'TestY2', 'Apr', 'May', 'Jun', 'TestY3'];
heatmap.dataSource = jsonCellData;
heatmap.dataSourceSettings = adaptorData;
heatmap.refresh();
tempElement = document.getElementById('container_HeatMapRect_0');
trigger.mousemoveEvent(tempElement, 0, 0, 0, 20, false);
trigger.mousemoveEvent(tempElement, 0, 0, 60, 20, false);
tooltipElement = document.getElementById('containerCelltooltipcontainer_svg');
expect(tooltipElement).not.toBe(null);
expect(heatmap.tooltipModule.tooltipObject.content[0]).toBe("Weekdays : TestX1<br/>YAxis : Jun<br/>Men : 50$<br/>Women : 13$");
setTimeout(done, 1600);
});
it('Checking cell rendering event', (done: Function) => {
heatmap.cellSettings = {
format: '',
bubbleType: 'Size',
},
heatmap.cellRender = function (args: ICellEventArgs) {
if (args.value >= 30) {
args.displayText = 'test'
}
},
heatmap.refresh();
tempElement = document.getElementById('container_HeatMapRectLabels_0');
expect(tempElement.textContent).toBe("test");
done();
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
}); | the_stack |
'use strict';
interface IDenqueOptions {
capacity?: number
}
/**
* Custom implementation of a double ended queue.
*/
export default class Denque<T> {
_head: number;
_tail: number;
_capacity: number | undefined;
_capacityMask: number;
_list: any[];
constructor(array?: T[], options?: IDenqueOptions) {
const thisOptions = options || {};
this._head = 0;
this._tail = 0;
this._capacity = thisOptions.capacity;
this._capacityMask = 0x3;
this._list = new Array(4);
if (Array.isArray(array)) {
this._fromArray(array);
}
}
/**
* Add an item to the bottom of the list.
* @param item
*/
push(item?: T): number {
if (item === undefined) return this.size();
const tail = this._tail;
this._list[tail] = item;
this._tail = (tail + 1) & this._capacityMask;
if (this._tail === this._head) {
this._growArray();
}
if (this._capacity && this.size() > this._capacity) {
this.shift();
}
if (this._head < this._tail) return this._tail - this._head;
else return this._capacityMask + 1 - (this._head - this._tail);
};
/**
* Add an item at the beginning of the list.
* @param item
*/
unshift(item?: T): number {
if (item === undefined) return this.size();
const len = this._list.length;
this._head = (this._head - 1 + len) & this._capacityMask;
this._list[this._head] = item;
if (this._tail === this._head) this._growArray();
if (this._capacity && this.size() > this._capacity) this.pop();
if (this._head < this._tail) return this._tail - this._head;
else return this._capacityMask + 1 - (this._head - this._tail);
};
/**
* Remove and return the last item on the list.
* Returns undefined if the list is empty.
* @returns {*}
*/
pop(): T | undefined {
const tail = this._tail;
if (tail === this._head) return undefined;
const len = this._list.length;
this._tail = (tail - 1 + len) & this._capacityMask;
const item = this._list[this._tail];
this._list[this._tail] = undefined;
if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray();
return item;
};
/**
* Returns the item that is at the back of the queue without removing it.
* Uses peekAt(-1)
*/
peekBack(): T | undefined {
return this.peekAt(-1);
}
/**
* Alias for peek()
* @returns {*}
*/
peekFront(): T | undefined {
return this.peek();
}
/**
* Returns the item at the specified index from the list.
* 0 is the first element, 1 is the second, and so on...
* Elements at negative values are that many from the end: -1 is one before the end
* (the last element), -2 is two before the end (one before last), etc.
* @param index
* @returns {*}
*/
peekAt(index: number): T | undefined {
let i = index;
// expect a number or return undefined
if ((i !== (i | 0))) {
return undefined;
}
const len = this.size();
if (i >= len || i < -len) return undefined;
if (i < 0) i += len;
i = (this._head + i) & this._capacityMask;
return this._list[i];
}
/**
* Alias for peekAt()
* @param i
* @returns {*}
*/
get(index: number): T | undefined {
return this.peekAt(index);
}
/**
* Remove number of items from the specified index from the list.
* Returns array of removed items.
* Returns undefined if the list is empty.
* @param index
* @param count
* @returns {array}
*/
remove(index: number, count: number): T[] | undefined {
let i = index;
let removed;
let delCount = count;
// expect a number or return undefined
if ((i !== (i | 0))) {
return undefined;
}
if (this._head === this._tail) return undefined;
const size = this.size();
const len = this._list.length;
if (i >= size || i < -size || count < 1) return undefined;
if (i < 0) i += size;
if (count === 1 || !count) {
removed = new Array(1);
removed[0] = this.removeOne(i);
return removed;
}
if (i === 0 && i + count >= size) {
removed = this.toArray();
this.clear();
return removed;
}
if (i + count > size) count = size - i;
let k;
removed = new Array(count);
for (k = 0; k < count; k++) {
removed[k] = this._list[(this._head + i + k) & this._capacityMask];
}
i = (this._head + i) & this._capacityMask;
if (index + count === size) {
this._tail = (this._tail - count + len) & this._capacityMask;
for (k = count; k > 0; k--) {
this._list[i = (i + 1 + len) & this._capacityMask] = undefined;
}
return removed;
}
if (index === 0) {
this._head = (this._head + count + len) & this._capacityMask;
for (k = count - 1; k > 0; k--) {
this._list[i = (i + 1 + len) & this._capacityMask] = undefined;
}
return removed;
}
if (i < size / 2) {
this._head = (this._head + index + count + len) & this._capacityMask;
for (k = index; k > 0; k--) {
this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]);
}
i = (this._head - 1 + len) & this._capacityMask;
while (delCount > 0) {
this._list[i = (i - 1 + len) & this._capacityMask] = undefined;
delCount--;
}
if (index < 0) this._tail = i;
} else {
this._tail = i;
i = (i + count + len) & this._capacityMask;
for (k = size - (count + index); k > 0; k--) {
this.push(this._list[i++]);
}
i = this._tail;
while (delCount > 0) {
this._list[i = (i + 1 + len) & this._capacityMask] = undefined;
delCount--;
}
}
if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray();
return removed;
};
/**
* Remove and return the item at the specified index from the list.
* Returns undefined if the list is empty.
* @param index
* @returns {*}
*/
removeOne(index: number): T | undefined {
let i = index;
// expect a number or return undefined
if ((i !== (i | 0))) {
return undefined;
}
if (this._head === this._tail) return undefined;
const size = this.size();
const len = this._list.length;
if (i >= size || i < -size) return undefined;
if (i < 0) i += size;
i = (this._head + i) & this._capacityMask;
const item = this._list[i];
let k;
if (index < size / 2) {
for (k = index; k > 0; k--) {
this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask];
}
this._list[i] = undefined;
this._head = (this._head + 1 + len) & this._capacityMask;
} else {
for (k = size - 1 - index; k > 0; k--) {
this._list[i] = this._list[i = (i + 1 + len) & this._capacityMask];
}
this._list[i] = undefined;
this._tail = (this._tail - 1 + len) & this._capacityMask;
}
return item;
};
/**
* Native splice implementation.
* Remove number of items from the specified index from the list and/or add new elements.
* Returns array of removed items or empty array if count == 0.
* Returns undefined if the list is empty.
*
* @param index
* @param count
* @param {...*} [elements]
* @returns {array}
*/
splice(index: number, count: number, ..._items: T[]): T[] | undefined {
let i = index;
// expect a number or return undefined
if ((i !== (i | 0))) {
return undefined;
}
const size = this.size();
if (i < 0) i += size;
if (i > size) return undefined;
if (arguments.length > 2) {
let k;
let temp;
let removed;
let argLen = arguments.length;
const len = this._list.length;
let argumentsIndex = 2;
if (!size || i < size / 2) {
temp = new Array(i);
for (k = 0; k < i; k++) {
temp[k] = this._list[(this._head + k) & this._capacityMask];
}
if (count === 0) {
removed = [];
if (i > 0) {
this._head = (this._head + i + len) & this._capacityMask;
}
} else {
removed = this.remove(i, count);
this._head = (this._head + i + len) & this._capacityMask;
}
while (argLen > argumentsIndex) {
this.unshift(arguments[--argLen]);
}
for (k = i; k > 0; k--) {
this.unshift(temp[k - 1]);
}
} else {
temp = new Array(size - (i + count));
const leng = temp.length;
for (k = 0; k < leng; k++) {
temp[k] = this._list[(this._head + i + count + k) & this._capacityMask];
}
if (count === 0) {
removed = [];
if (i !== size) {
this._tail = (this._head + i + len) & this._capacityMask;
}
} else {
removed = this.remove(i, count);
this._tail = (this._tail - leng + len) & this._capacityMask;
}
while (argumentsIndex < argLen) {
this.push(arguments[argumentsIndex++]);
}
for (k = 0; k < leng; k++) {
this.push(temp[k]);
}
}
return removed;
} else {
return this.remove(i, count);
}
};
/**
* Returns true or false whether the list is empty.
* @returns {boolean}
*/
isEmpty(): boolean {
return this._head === this._tail;
};
/**
* Soft clear - does not reset capacity.
*/
clear(): void {
this._head = 0;
this._tail = 0;
};
/**
* Returns an array of all queue items.
* @returns {Array}
*/
toArray(): T[] {
return this._copyArray(false);
};
peek(): T | undefined {
if (this._head === this._tail) return undefined;
return this._list[this._head];
};
/**
* Return the number of items on the list, or 0 if empty.
* @returns {number}
*/
get length(): number {
return this.size();
}
/**
* Return the number of items on the list, or 0 if empty.
* @returns {number}
*/
size() {
if (this._head === this._tail) return 0;
if (this._head < this._tail) return this._tail - this._head;
else return this._capacityMask + 1 - (this._head - this._tail);
};
/**
* Remove and return the first item on the list,
* Returns undefined if the list is empty.
* @returns {*}
*/
shift() {
const head = this._head;
if (head === this._tail) return undefined;
const item = this._list[head];
this._list[head] = undefined;
this._head = (head + 1) & this._capacityMask;
if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray();
return item;
};
/**
* Fills the queue with items from an array
* For use in the constructor
* @param array
* @private
*/
private _fromArray(array: T[]) {
for (let i = 0; i < array.length; i++) this.push(array[i]);
};
/**
*
* @param fullCopy
* @returns {Array}
* @private
*/
private _copyArray(fullCopy: boolean) {
const newArray = [];
const list = this._list;
const len = list.length;
let i;
if (fullCopy || this._head > this._tail) {
for (i = this._head; i < len; i++) newArray.push(list[i]);
for (i = 0; i < this._tail; i++) newArray.push(list[i]);
} else {
for (i = this._head; i < this._tail; i++) newArray.push(list[i]);
}
return newArray;
};
/**
* Grows the internal list array.
* @private
*/
private _growArray() {
if (this._head) {
// copy existing data, head to end, then beginning to tail.
this._list = this._copyArray(true);
this._head = 0;
}
// head is at 0 and array is now full, safe to extend
this._tail = this._list.length;
this._list.length *= 2;
this._capacityMask = (this._capacityMask << 1) | 1;
};
/**
* Shrinks the internal list array.
* @private
*/
private _shrinkArray() {
this._list.length >>>= 1;
this._capacityMask >>>= 1;
};
} | the_stack |
import type { Operation } from '@apollo/client/core';
import { expect } from '@open-wc/testing';
import { gql } from '@apollo/client/core';
import { hasAllVariables } from './has-all-variables';
function pass(description: string, operation: Partial<Operation>): Mocha.Suite {
return describe(description, function() {
return it('passes', function() {
expect(hasAllVariables(operation)).to.be.true;
});
});
}
function fail(description: string, operation: Partial<Operation>): Mocha.Suite {
return describe(description, function() {
return it('fails', function() {
expect(hasAllVariables(operation)).to.be.false;
});
});
}
describe('[lib] hasAllVariables', function() {
describe('for no variables', function() {
const query = gql`query NoVars { q { one } }`;
pass('without variables', { query });
pass('with variable', { query, variables: { one: '1' } });
pass('with null variable', { query, variables: { one: null } });
pass('without variable', { query, variables: {} });
});
describe('for one non-nullable variable', function() {
const query = gql`query NeedsOne($one: ID!) { q(one: $one) { one } }`;
pass('with variable', { query, variables: { one: '1' } });
fail('with null variable', { query, variables: { one: null } });
fail('without variable', { query, variables: {} });
});
describe('for one nullable variable', function() {
const query = gql`query OptOne($one: String) { q(one: $one) { one } }`;
pass('with no variable', { query, variables: {} });
pass('with variable', { query, variables: { one: '1' } });
pass('with null variable', { query, variables: { one: null } });
});
describe('for one nullable variable one level deep', function() {
const query = gql`query NeedsOne($one: ID) { q { one(one: $one) { id } } }`;
pass('with no variable', { query, variables: {} });
pass('with variable', { query, variables: { one: '1' } });
pass('with null variable', { query, variables: { one: null } });
});
describe('for one non-nullable variable one level deep', function() {
const query = gql`query NeedsOne($one: ID!) { q { one(one: $one) { id } } }`;
pass('with variable', { query, variables: { one: '1' } });
fail('with no variable', { query, variables: {} });
fail('with null variable', { query, variables: { one: null } });
});
describe('for two non-nullable variables', function() {
const query = gql`query NeedsTwo($one: ID!, $two: ID!) { q(one: $one, two: $two) { one two } }`;
pass('with both variables', { query, variables: { one: '1', two: '2' } });
fail('with no variables', { query, variables: {} });
fail('with both variables null', { query, variables: { one: null, two: null } });
fail('with first variable only', { query, variables: { one: '1' } });
fail('with first variable only null', { query, variables: { one: null } });
fail(`with first variable null and second variable`, { query, variables: { one: null, two: '1' } });
fail('with second variable only', { query, variables: { two: '1' } });
fail('with second variable only null', { query, variables: { two: null } });
fail(`with second variable null and first variable`, { query, variables: { one: '1', two: null } });
});
describe('for two nullable variables', function() {
const query = gql`query OptTwo($one: ID, $two: ID) { q(one: $one, two: $two) { one two } }`;
pass('with no variables', { query, variables: {} });
pass('with both variables', { query, variables: { one: '1', two: '2' } });
pass('with both variables null', { query, variables: { one: null, two: null } });
pass('with first variable only', { query, variables: { one: '1' } });
pass('with first variable only null', { query, variables: { one: null } });
pass(`with first variable null and second variable`, { query, variables: { one: null, two: '1' } });
pass('with second variable only', { query, variables: { two: '1' } });
pass('with second variable only null', { query, variables: { two: null } });
pass(`with second variable null and first variable`, { query, variables: { one: '1', two: null } });
});
describe('for one non-nullable and one nullable variable', function() {
const query = gql`query NeedsOneOptOne($one: ID!, $two: ID) { q(one: $one, two: $two) { one two } }`;
pass('with both variables', { query, variables: { one: '1', two: '2' } });
pass('with first variable only', { query, variables: { one: '1' } });
pass(`with first variable and second variable null`, { query, variables: { one: '1', two: null } });
fail('with no variables', { query, variables: {} });
fail('with both variables null', { query, variables: { one: null, two: null } });
fail('with first variable only null', { query, variables: { one: null } });
fail(`with first variable null and second variable`, { query, variables: { one: null, two: '1' } });
fail('with second variable only', { query, variables: { two: '1' } });
fail('with second variable only null', { query, variables: { two: null } });
});
describe('for one nullable and one non-nullable variable', function() {
const query = gql`query OptOneNeedsOne($one: ID, $two: ID!) { q(one: $one, two: $two) { one two } }`;
pass('with both variables', { query, variables: { one: '1', two: '2' } });
pass(`with first variable null and second variable`, { query, variables: { one: null, two: '1' } });
pass('with second variable only', { query, variables: { two: '1' } });
fail('with no variables', { query, variables: {} });
fail('with both variables null', { query, variables: { one: null, two: null } });
fail('with first variable only', { query, variables: { one: '1' } });
fail('with first variable only null', { query, variables: { one: null } });
fail('with second variable only null', { query, variables: { two: null } });
fail(`with second variable null and first variable`, { query, variables: { one: '1', two: null } });
});
describe('for two nullable and two non-nullable variables', function() {
const query = gql`query OptOneNeedsOne($one: ID, $two: ID, $three: ID!, $four: ID!) { q(one: $one, two: $two, three: $three, four: $four) { one two three four } }`;
pass('with al variables', { query, variables: { one: '1', two: '2', three: '3', four: '4' } });
pass(`with first two variable null and last two variables set`, { query, variables: { one: null, two: null, three: '3', four: '4' } });
pass('with last two variable only', { query, variables: { three: '3', four: '4' } });
fail('with no variables', { query, variables: {} });
fail('with first two variables null', { query, variables: { one: null, two: null } });
fail('with first variable only', { query, variables: { one: '1' } });
fail('with first variable only null', { query, variables: { one: null } });
fail('with second variable only null', { query, variables: { two: null } });
fail(`with second variable null and first variable`, { query, variables: { one: '1', two: null } });
fail('with third variable only', { query, variables: { three: '3' } });
});
it('handles weird input', function() {
// @ts-expect-error: testing weird input
expect(hasAllVariables(), 'no params').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables(void 0), 'void params').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables(null), 'null params').to.be.false;
expect(hasAllVariables({}), 'empty object params').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables([]), 'empty array params').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables(NaN), 'NaN params').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables(1), 'Number params').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables(true), 'Boolean params').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables('foo'), 'String params').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables((() => 'hmm')), 'Function params').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables(Promise.resolve()), 'Promise params').to.be.false;
const query = gql`query NeedsOne($one: ID!) { q(one: $one) { one } }`;
expect(hasAllVariables({ query }), 'missing variables').to.be.false;
expect(hasAllVariables({ query, variables: void 0 }), 'void variables').to.be.false;
expect(hasAllVariables({ query, variables: undefined }), 'undefined variables').to.be.false;
expect(hasAllVariables({ query, variables: [] }), 'empty array variables').to.be.false;
expect(hasAllVariables({ query, variables: [1] }), 'array variables').to.be.false;
expect(hasAllVariables({ query, variables: [1] }), 'array of object variables').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables({ query, variables: null }), 'null variables').to.be.false;
expect(hasAllVariables({ query, variables: { boo: 'foo' } }), 'weird variables').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables({ query, variables: NaN }), 'NaN variables').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables({ query, variables: '' }), 'Empty string variables').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables({ query, variables: 'foo' }), 'String variables').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables({ query, variables: 0 }), 'Number 0 variables').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables({ query, variables: 1 }), 'Number 1 variables').to.be.false;
expect(hasAllVariables({ variables: {} }), 'undefined query').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables({ query: null }), 'null query').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables({ query: NaN }), 'NaN query').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables({ query: '' }), 'Empty string query').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables({ query: 'foo' }), 'String query').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables({ query: 0 }), 'Number 0 query').to.be.false;
// @ts-expect-error: testing weird input
expect(hasAllVariables({ query: 1 }), 'Number 1 query').to.be.false;
});
}); | the_stack |
import * as React from 'react';
import {
Interactive,
createInteractive,
InteractiveProps,
InteractiveExtendableProps,
InteractiveState,
InteractiveStateChange,
} from 'react-interactive';
import { BrowserRouter, Link } from 'react-router-dom';
import { styled } from '../stitches.config';
////////////////////////////////////
// TS demos in this file:
//
// <DemoCreateInteractiveAs />
// <DemoOnStateChangeAndChildren />
// <DemoPropsForInteractive />
// <DemoWrapAsTagName />
// <DemoWrapAsComponent />
// <DemoWrapAsUnion />
////////////////////////////////////
////////////////////////////////////
// using createInteractive(as) to extend <Interactive>
// and predefined Interactive.Tagname components
const InteractiveNav = createInteractive('nav');
const InteractiveRouterLink = createInteractive(Link);
export const DemoCreateInteractiveAs: React.VFC = () => (
<>
<Interactive.Button
// as="button" // should error
type="submit" // button specific prop
ref={(element) => {}}
hoverStyle={{ fontWeight: 'bold' }}
// foo // should error
>
Interactive.Button
</Interactive.Button>
<Interactive.A
// as="a" // should error
href="https://rafgraph.dev"
ref={(element) => {}}
hoverStyle={{ fontWeight: 'bold' }}
>
Interactive.A
</Interactive.A>
<Interactive.Div
ref={(element) => {}}
hoverStyle={{ fontWeight: 'bold' }}
onStateChange={({ state, prevState }) => {}}
>
Interactive.Div
</Interactive.Div>
<InteractiveNav
// as="nav" // should error
ref={(element) => {}}
hoverStyle={{ fontWeight: 'bold' }}
onStateChange={({ state, prevState }) => {}}
>
InteractiveNav
</InteractiveNav>
<InteractiveRouterLink
// as={Link} // should error
to="/some-path"
ref={(element) => {}}
hoverStyle={{ fontWeight: 'bold' }}
onStateChange={({ state, prevState }) => {}}
>
InteractiveRouterLink
</InteractiveRouterLink>
</>
);
////////////////////////////////////
// typing onStateChange and children as a function
const DemoOnStateChangeAndChildren: React.VFC = () => {
// use the InteractiveStateChange type to type the argument
// passed to the onStateChange callback
const handleInteractiveStateChange = React.useCallback(
({ state, prevState }: InteractiveStateChange) => {
// your logic here...
},
[],
);
// use the InteractiveState type to type the argument
// passed to children (when children is a function)
const childrenAsAFunction = React.useCallback(
({ hover, active, focus }: InteractiveState) =>
`Current state - active: ${active}, hover: ${hover}, focus: ${focus}`,
[],
);
return (
<Interactive as="button" onStateChange={handleInteractiveStateChange}>
{childrenAsAFunction}
</Interactive>
);
};
////////////////////////////////////
// typing props passed to <Interactive>
// use type InteractiveProps
// props object passed to <Interactive>, InteractiveProps includes types for `as` and `ref`
const propsForInteractiveButton: InteractiveProps<'button'> = {
as: 'button',
type: 'submit', // button specific prop
children: 'propsForInteractiveButton',
ref: (element) => {},
hoverStyle: { fontWeight: 'bold' },
onStateChange: ({ state, prevState }) => {},
// foo: true, // should error
};
const propsForInteractiveRouterLink: InteractiveProps<typeof Link> = {
as: Link,
to: '/some-path', // Link specific prop
children: 'propsForInteractiveRouterLink',
ref: (element) => {},
hoverStyle: { fontWeight: 'bold' },
onStateChange: ({ state, prevState }) => {},
// foo: true, // should error
};
const DemoPropsForInteractive: React.VFC = () => (
<>
<Interactive {...propsForInteractiveButton} />
<Interactive {...propsForInteractiveRouterLink} />
<Interactive
as="button"
type="submit" // button specific prop
ref={(element: HTMLButtonElement | null) => {}} // element type is not inferred, see https://github.com/kripod/react-polymorphic-types/issues/5
hoverStyle={{ fontWeight: 'bold' }}
onStateChange={({ state, prevState }) => {}}
>
Interactive-as-button
</Interactive>
<Interactive
as={Link}
to="/some-path"
ref={(element: React.ElementRef<typeof Link> | null) => {}} // element type is not inferred, see https://github.com/kripod/react-polymorphic-types/issues/5
hoverStyle={{ fontWeight: 'bold' }}
onStateChange={({ state, prevState }) => {}}
>
Interactive-as-Link
</Interactive>
</>
);
////////////////////////////////////
// wrapping as="button" with pass through props
// use type InteractiveExtendableProps
// the same props interface is used for wrapping with and without forwardRef
// note that InteractiveExtendableProps doesn't include `as` or `ref` props
// when using forwardRef the ref type will be added by the forwardRef function
interface WrapAsTagNameProps extends InteractiveExtendableProps<'button'> {
additionalProp?: string;
}
// as="button" without ref
const WrapAsTagNameWithoutRef: React.VFC<WrapAsTagNameProps> = ({
additionalProp,
...props
}) => {
// component logic here...
return <Interactive {...props} as="button" />;
};
// as="button" with ref
const WrapAsTagNameWithRef = React.forwardRef<
HTMLButtonElement,
WrapAsTagNameProps
>(({ additionalProp, ...props }, ref) => {
// component logic here...
return <Interactive {...props} as="button" ref={ref} />;
});
// type for props with ref, use for typing props passed to WrapAsTagNameWithRef
type WrapAsTagNameWithRefProps = React.ComponentPropsWithRef<
typeof WrapAsTagNameWithRef
>;
const propsForWrapAsTagNameWithRef: WrapAsTagNameWithRefProps = {
additionalProp: 'something',
children: 'propsForWrapAsTagNameWithRef',
ref: () => {},
type: 'submit', // button specific prop
hoverStyle: { fontWeight: 'bold' },
};
const DemoWrapAsTagName: React.VFC = () => (
<>
<WrapAsTagNameWithoutRef
// as="button" // should error
// ref={(element) => {}} // should error
type="submit" // button specific prop
hoverStyle={{ fontWeight: 'bold' }}
>
WrapAsTagNameWithoutRef
</WrapAsTagNameWithoutRef>
<WrapAsTagNameWithRef
// as="button" // should error
ref={(element) => {}}
type="submit" // button specific prop
hoverStyle={{ fontWeight: 'bold' }}
>
WrapAsTagNameWithRef
</WrapAsTagNameWithRef>
<WrapAsTagNameWithRef {...propsForWrapAsTagNameWithRef} />
<Interactive
as="button"
// ref={(element: HTMLButtonElement | null) => {}}
ref={{ current: null }}
type="submit" // button specific prop
hoverStyle={{ fontWeight: 'bold' }}
>
Interactive-as-button
</Interactive>
</>
);
////////////////////////////////////
// wrapping as={Component} with pass through props
// use type InteractiveExtendableProps
// first create a composable component to use for the `as` prop
// (or use a component from a composable library such as React Router's <Link>)
// the composable component needs to pass through props and ref using React.forwardRef
interface MyComponentProps extends React.ComponentPropsWithoutRef<'button'> {
someMyComponentProp?: string;
}
const MyComponent = React.forwardRef<HTMLButtonElement, MyComponentProps>(
({ someMyComponentProp, ...props }, ref) => {
// component logic here...
return <button {...props} ref={ref} />;
},
);
// next create the interface for the component that wraps the <Interactive> component,
// the same props interface is used for wrapping with and without forwardRef
// note that InteractiveExtendableProps doesn't include `as` or `ref` props
// when using forwardRef the ref type will be added by the forwardRef function
interface WrapAsComponentProps
extends InteractiveExtendableProps<typeof MyComponent> {
additionalProp?: string;
}
// as={Component} without ref
const WrapAsComponentWithoutRef: React.VFC<WrapAsComponentProps> = ({
additionalProp,
...props
}) => {
// component logic here...
return <Interactive {...props} as={MyComponent} />;
};
// as={Component} with ref
const WrapAsComponentWithRef = React.forwardRef<
React.ElementRef<typeof MyComponent>,
WrapAsComponentProps
>(({ additionalProp, ...props }, ref) => {
// component logic here...
return <Interactive {...props} as={MyComponent} ref={ref} />;
});
// type for props with ref, use for typing props passed to WrapAsComponentWithRef
type WrapAsComponentWithRefProps = React.ComponentPropsWithRef<
typeof WrapAsComponentWithRef
>;
const propsForWrapAsComponentWithRef: WrapAsComponentWithRefProps = {
additionalProp: 'something',
someMyComponentProp: 'something else',
children: 'propsForWrapAsTagNameWithRef',
ref: () => {},
hoverStyle: { fontWeight: 'bold' },
};
const DemoWrapAsComponent: React.VFC = () => (
<>
<WrapAsComponentWithoutRef
additionalProp="something"
someMyComponentProp="something else"
// ref={(element) => {}} // should error
hoverStyle={{ fontWeight: 'bold' }}
>
WrapAsComponentWithoutRef
</WrapAsComponentWithoutRef>
<WrapAsComponentWithRef
additionalProp="something"
someMyComponentProp="something else"
ref={(element) => {}}
hoverStyle={{ fontWeight: 'bold' }}
>
WrapAsComponentWithRef
</WrapAsComponentWithRef>
<WrapAsComponentWithRef {...propsForWrapAsComponentWithRef} />
<Interactive
as={MyComponent}
someMyComponentProp="something else"
hoverStyle={{ fontWeight: 'bold' }}
ref={(element: React.ElementRef<typeof MyComponent> | null) => {}}
>
Interactive-as-MyComponent
</Interactive>
</>
);
////////////////////////////////////
// wrapping as a union with ref
// this example is a union of an Anchor element and React Router's <Link> component
// when an href prop is passed to the component, an Anchor element is rendered
// when a to prop is passed to the component, a <Link> component is rendered
type WrapAsUnionProps =
| (InteractiveExtendableProps<typeof Link> & { href?: never })
| (InteractiveExtendableProps<'a'> & { to?: never; replace?: never });
const WrapAsUnionWithRef = React.forwardRef<
HTMLAnchorElement,
WrapAsUnionProps
>((props, ref) => {
// React Router's <Link> component doesn't have a disabled state
// so when disabled always render as="a" and remove router specific props
const As = props.to && !props.disabled ? Link : 'a';
let passThroughProps = props;
if (props.disabled) {
const { to, replace, ...propsWithoutRouterProps } = props;
passThroughProps = propsWithoutRouterProps;
}
return <Interactive {...passThroughProps} as={As} ref={ref} />;
});
type WrapAsUnionWithRefProps = React.ComponentPropsWithRef<
typeof WrapAsUnionWithRef
>;
const propsForWrapAsUnionWithRef: WrapAsUnionWithRefProps = {
ref: (element) => {},
href: 'https://rafgraph.dev',
// to: '/some-path', // should error
children: 'propsForWrapAsUnionWithRef',
hoverStyle: { fontWeight: 'bold' },
};
const DemoWrapAsUnionWithRef: React.VFC = () => (
<>
<WrapAsUnionWithRef
to="/some-path"
replace // replace is a Router Link prop
// href="https://rafgraph.dev" // should error
ref={(element) => {}}
hoverStyle={{ fontWeight: 'bold' }}
>
WrapAsUnionWithRef-RouterLink
</WrapAsUnionWithRef>
<WrapAsUnionWithRef
disabled
to="/some-path"
replace // replace is a Router Link prop
ref={(element) => {}}
hoverStyle={{ fontWeight: 'bold' }}
disabledStyle={{ opacity: 0.5 }}
>
WrapAsUnionWithRef-RouterLink-disabled
</WrapAsUnionWithRef>
<WrapAsUnionWithRef
href="https://rafgraph.dev"
// to="/some-path" // should error b/c to is a Router Link prop
// replace // should error b/c replace is a Router Link prop
ref={(element) => {}}
hoverStyle={{ fontWeight: 'bold' }}
>
WrapAsUnionWithRef-AnchorLink
</WrapAsUnionWithRef>
<WrapAsUnionWithRef {...propsForWrapAsUnionWithRef} />
</>
);
////////////////////////////////////
const ContainerDiv = styled('div', {
'&>*': {
display: 'block',
},
'&>h1': {
fontSize: '20px',
},
});
export const TypeScriptExamples: React.VFC = () => (
<BrowserRouter>
<ContainerDiv>
<h1>TypeScript Examples</h1>
<DemoCreateInteractiveAs />
<DemoOnStateChangeAndChildren />
<DemoPropsForInteractive />
<DemoWrapAsTagName />
<DemoWrapAsComponent />
<DemoWrapAsUnionWithRef />
</ContainerDiv>
</BrowserRouter>
); | the_stack |
import {
parse,
GraphQLSchema,
DocumentNode,
GraphQLField,
GraphQLCompositeType,
isCompositeType,
getNamedType,
GraphQLType,
VariableDefinitionNode,
TypeNode,
OperationTypeNode,
GraphQLObjectType,
GraphQLEnumType,
DirectiveNode,
GraphQLInputObjectType,
GraphQLInputField,
GraphQLUnionType,
GraphQLNamedType,
FieldNode,
isAbstractType,
} from 'graphql';
import {
schemaFromInputs,
isList,
isNonNullable,
isEnum,
filterAndJoinArray,
} from '@gql2ts/util';
import {
GetChildSelectionsType,
IChildSelection,
IComplexTypeSignature,
IFromQueryOptions,
FromQuerySignature,
HandleNamedTypes,
HandleInputTypes,
ConvertToTypeSignature,
ITypeMap,
IFromQueryReturnValue,
} from '@gql2ts/types';
import {
DEFAULT_TYPE_MAP,
DEFAULT_OPTIONS,
} from '@gql2ts/language-typescript';
import {
GenerateSubtypeCache,
SubtypeNamerAndDedupe,
ISubtypeMetadata,
} from './subtype';
const doIt: FromQuerySignature = (schema, query, typeMap = {}, providedOptions = {}) => {
const enumDeclarations: Map<string, string> = new Map<string, string>();
const {
wrapList,
wrapPartial,
generateSubTypeInterfaceName,
printType,
formatInput,
generateFragmentName,
generateQueryName,
interfaceBuilder,
typeBuilder,
typeJoiner,
generateInterfaceDeclaration,
exportFunction,
postProcessor,
generateInputName,
addExtensionsToInterfaceName,
enumTypeBuilder,
formatEnum,
generateEnumName,
generateDocumentation,
typeMap: langTypeMap
}: IFromQueryOptions = { ...DEFAULT_OPTIONS, ...providedOptions };
const TypeMap: ITypeMap = {
...DEFAULT_TYPE_MAP,
...langTypeMap,
...typeMap,
};
const getSubtype: SubtypeNamerAndDedupe = GenerateSubtypeCache();
const parsedSchema: GraphQLSchema = schemaFromInputs(schema);
const parsedSelection: DocumentNode = parse(query);
const handleInputObject: (type: GraphQLInputObjectType, isNonNull: boolean) => string = (type, isNonNull) => {
const variables: GraphQLInputField[] = Object.keys(type.getFields()).map(k => type.getFields()[k]);
const variableDeclarations: string[] = variables.map(v => formatInput(v.name, true, convertToType(v.type)));
const builder: string = generateInterfaceDeclaration(variableDeclarations.map(v => v));
return printType(builder, isNonNull);
};
const handleEnum: (type: GraphQLEnumType, isNonNull: boolean) => string = (type, isNonNull) => {
const enumName: string = generateEnumName(type.name);
if (!enumDeclarations.has(type.name)) {
const enumDeclaration: string = enumTypeBuilder(enumName, formatEnum(type.getValues(), generateDocumentation));
enumDeclarations.set(type.name, enumDeclaration);
}
return printType(enumName, isNonNull);
};
const handleNamedTypeInput: (type: TypeNode, isNonNull: boolean) => string | undefined = (type, isNonNull) => {
if (type.kind === 'NamedType' && type.name.kind === 'Name' && type.name.value) {
const newType: GraphQLType = parsedSchema.getType(type.name.value);
if (newType instanceof GraphQLEnumType) {
return handleEnum(newType, isNonNull);
} else if (newType instanceof GraphQLInputObjectType) {
return handleInputObject(newType, isNonNull);
}
}
};
const handleRegularType: HandleNamedTypes = (type, isNonNull, replacement) => {
const typeValue: string = (typeof type.name === 'string') ? type.toString() : type.name.value;
const showValue: string = replacement || typeValue;
const show: string = TypeMap[showValue] || (replacement ? showValue : TypeMap.__DEFAULT);
return printType(show, isNonNull);
};
const convertVariable: HandleInputTypes = (type, isNonNull = false, replacement = null) => {
if (type.kind === 'ListType') {
return printType(wrapList(convertVariable(type.type, false, replacement)), isNonNull!);
} else if (type.kind === 'NonNullType') {
return convertVariable(type.type, true, replacement);
} else {
return handleNamedTypeInput(type, isNonNull!) || handleRegularType(type, isNonNull!, replacement!);
}
};
const convertToType: ConvertToTypeSignature = (type, isNonNull = false, replacement = null) => {
if (isList(type)) {
return printType(wrapList(convertToType(type.ofType, false, replacement)), isNonNull!);
} else if (isNonNullable(type)) {
return convertToType(type.ofType, true, replacement);
} else if (isEnum(type)) {
return handleEnum(type, isNonNull!);
} else {
return handleRegularType(type, isNonNull!, replacement!);
}
};
const UndefinedDirectives: Set<string> = new Set(['include', 'skip']);
const isUndefinedFromDirective: (directives: DirectiveNode[] | undefined) => boolean = directives => {
if (!directives || !directives.length) { return false; }
const badDirectives: DirectiveNode[] = directives.filter(d => !UndefinedDirectives.has(d.name.value));
const hasDirectives: boolean = directives.some(d => UndefinedDirectives.has(d.name.value));
if (badDirectives.length) {
console.error('Found some unknown directives:');
badDirectives.forEach(d => console.error(d.name.value));
}
return hasDirectives;
};
const getOperationFields: (operation: OperationTypeNode) => GraphQLObjectType | null | undefined = operation => {
switch (operation) {
case 'query':
return parsedSchema.getQueryType();
case 'mutation':
return parsedSchema.getMutationType();
case 'subscription':
return parsedSchema.getSubscriptionType();
default:
throw new Error('Unsupported Operation');
}
};
const wrapPossiblePartial: (possiblePartial: IChildSelection) => string = possiblePartial => {
if (possiblePartial.isPartial) {
return wrapPartial(possiblePartial.iface);
} else {
return possiblePartial.iface;
}
};
const flattenComplexTypes: (children: IChildSelection[]) => IComplexTypeSignature[] = children => (
children.reduce((acc, child) => { acc.push(...child.complexTypes); return acc; }, [] as IComplexTypeSignature[])
);
type GetField = (operation: OperationTypeNode, selection: FieldNode, parent?: GraphQLType) => GraphQLField<any, any>;
const getField: GetField = (operation, selection, parent) => {
if (parent && isCompositeType(parent)) {
if (parent instanceof GraphQLUnionType) {
return parent.getTypes().map(t => t.getFields()[selection.name.value]).find(z => !!z)!;
} else {
return parent.getFields()[selection.name.value];
}
} else {
const operationFields: GraphQLObjectType | null | undefined = getOperationFields(operation);
// operation is taken from the schema, so it should never be falsy
return operationFields!.getFields()[selection.name.value];
}
};
const rootIntrospectionTypes: Map<string, string> = new Map([[ '__schema', '__Schema' ], [ '__type', '__Type' ]]);
const getChildSelections: GetChildSelectionsType = (operation, selection, parent?, isUndefined = false): IChildSelection => {
let str: string = '';
let isFragment: boolean = false;
let isPartial: boolean = false;
let complexTypes: IComplexTypeSignature[] = [];
if (selection.kind === 'Field') {
const field: GraphQLField<any, any> = getField(operation, selection, parent);
const originalName: string = selection.name.value;
const selectionName: string = selection.alias ? selection.alias.value : originalName;
let childType: string | undefined;
isUndefined = isUndefined || isUndefinedFromDirective(selection.directives);
let resolvedType: string;
if (originalName === '__typename') {
if (!parent) {
resolvedType = TypeMap.String;
} else if (isAbstractType(parent)) {
const possibleTypes: GraphQLObjectType[] = parsedSchema.getPossibleTypes(parent);
/**
* @TODO break this OR logic out of here (and the other places) and put into a printer
* @TODO break out the string-literal type out of here as it probably isn't supported by other languages
*/
resolvedType = possibleTypes.map(({ name }) => `'${name}'`).join(' | ');
} else {
resolvedType = `'${parent.toString()}'`;
}
} else if (!!selection.selectionSet) {
let newParent: GraphQLCompositeType | undefined;
const fieldType: GraphQLNamedType = rootIntrospectionTypes.has(originalName) ? parsedSchema.getType(
rootIntrospectionTypes.get(originalName)!
) : getNamedType(field.type);
if (isCompositeType(fieldType)) {
newParent = fieldType;
}
const selections: IChildSelection[] =
selection.selectionSet.selections.map(sel => getChildSelections(operation, sel, newParent));
const nonFragments: IChildSelection[] = selections.filter(s => !s.isFragment);
const fragments: IChildSelection[] = selections.filter(s => s.isFragment);
const andOps: string[] = [];
complexTypes.push(...flattenComplexTypes(selections));
if (nonFragments.length) {
const nonPartialNonFragments: IChildSelection[] = nonFragments.filter(nf => !nf.isPartial);
const partialNonFragments: IChildSelection[] = nonFragments.filter(nf => nf.isPartial);
if (nonPartialNonFragments.length) {
const interfaceDeclaration: string = generateInterfaceDeclaration(nonPartialNonFragments.map(f => f.iface));
const subtypeInfo: ISubtypeMetadata | null = getSubtype(selection, interfaceDeclaration, generateSubTypeInterfaceName);
const newInterfaceName: string | null = subtypeInfo ? subtypeInfo.name : null;
andOps.push(newInterfaceName || interfaceDeclaration);
if (newInterfaceName && subtypeInfo && !subtypeInfo.dupe) {
complexTypes.push({ iface: interfaceDeclaration, isPartial: false, name: newInterfaceName });
}
}
if (partialNonFragments.length) {
const interfaceDeclaration: string =
wrapPartial(generateInterfaceDeclaration(partialNonFragments.map(f => f.iface)));
const subtypeInfo: ISubtypeMetadata | null = getSubtype(selection, interfaceDeclaration, generateSubTypeInterfaceName);
const newInterfaceName: string | null = subtypeInfo ? subtypeInfo.name : null;
andOps.push(newInterfaceName || interfaceDeclaration);
if (newInterfaceName && subtypeInfo && !subtypeInfo.dupe) {
complexTypes.push({ iface: interfaceDeclaration, isPartial: true, name: newInterfaceName });
}
}
}
andOps.push(...fragments.map(wrapPossiblePartial));
childType = typeJoiner(andOps);
resolvedType = convertToType(field ? field.type : fieldType, false, childType);
} else {
resolvedType = convertToType(field.type, false, childType);
}
str = formatInput(selectionName, isUndefined, resolvedType);
} else if (selection.kind === 'FragmentSpread') {
str = generateFragmentName(selection.name.value);
isFragment = true;
isPartial = isUndefinedFromDirective(selection.directives);
} else if (selection.kind === 'InlineFragment') {
const anon: boolean = !selection.typeCondition;
let fragName: string = '';
if (!anon && selection.typeCondition) {
const typeName: string = selection.typeCondition.name.value;
parent = parsedSchema.getType(typeName);
isFragment = true;
fragName = generateFragmentName(`SpreadOn${typeName}`);
}
const selections: IChildSelection[] =
selection.selectionSet.selections.map(sel => getChildSelections(operation, sel, parent, false));
const fragmentSelections: IChildSelection[] = selections.filter(({ isFragment: frag }) => frag);
const nonFragmentSelections: IChildSelection[] = selections.filter(({ isFragment: frag }) => !frag);
/**
* @TODO need to handle fragments of fragments better
* An example of a previously unsupported fragment can be found in the __tests__ directory
* `fragmentSelections.length` is definitely a hack and a proper solution should be investigated
* See: https://github.com/avantcredit/gql2ts/issues/76
*/
if (!fragmentSelections.length && anon) {
let joinSelections: string = filterAndJoinArray(selections.map(s => s.iface), '\n');
isPartial = isUndefinedFromDirective(selection.directives);
complexTypes.push(...flattenComplexTypes(selections));
return {
iface: joinSelections,
isFragment: false,
isPartial,
complexTypes,
};
} else {
let joinSelections: string[] = nonFragmentSelections.map(s => s.iface);
isPartial = isUndefinedFromDirective(selection.directives);
complexTypes.push(...flattenComplexTypes(selections));
const interfaces: string[] = fragmentSelections.map(({ iface }) => iface);
if (joinSelections.length) {
complexTypes.push({ name: fragName, iface: generateInterfaceDeclaration(joinSelections), isPartial: false });
interfaces.push(fragName);
}
return {
// Avoid Double Partial, i.e. Partial<Partial<IFragmentOnWhatever>>
iface: interfaces.length === 1 && isPartial ? interfaces[0] : typeJoiner(interfaces.map(wrapPartial)),
isFragment,
isPartial,
complexTypes,
};
}
}
return {
iface: str,
isFragment,
isPartial,
complexTypes,
};
};
const getVariables: (variables: VariableDefinitionNode[]) => string[] = variables => (
variables.map(v => {
const optional: boolean = v.type.kind !== 'NonNullType';
return formatInput(v.variable.name.value, optional, convertVariable(v.type));
})
);
const variablesToInterface: (operationName: string, variables: VariableDefinitionNode[] | undefined) => string = (opName, variables) => {
if (!variables || !variables.length) { return ''; }
const variableTypeDefs: string[] = getVariables(variables);
return postProcessor(exportFunction(interfaceBuilder(generateInputName(opName), generateInterfaceDeclaration(variableTypeDefs))));
};
const buildAdditionalTypes: (children: IChildSelection[]) => string[] = children => {
const subTypes: IComplexTypeSignature[] = flattenComplexTypes(children);
return subTypes.map(subtype => {
if (subtype.isPartial) {
return postProcessor(exportFunction(typeBuilder(subtype.name, subtype.iface)));
} else {
return postProcessor(exportFunction(interfaceBuilder(subtype.name, subtype.iface)));
}
});
};
const getEnums: () => string[] = () => [
...enumDeclarations.values()
].map(enumDecl => postProcessor(exportFunction(enumDecl)));
interface IOutputJoinInput {
variables: string;
interface: string;
additionalTypes: string[];
}
const joinOutputs: (output: IOutputJoinInput) => IFromQueryReturnValue = output => {
const { variables, additionalTypes, interface: iface } = output;
const result: string = postProcessor(filterAndJoinArray([variables, ...additionalTypes, iface], '\n\n'));
return {
...output,
result
};
};
return parsedSelection.definitions.map(def => {
if (def.kind === 'OperationDefinition') {
const ifaceName: string = generateQueryName(def);
const variableInterface: string = variablesToInterface(ifaceName, def.variableDefinitions);
const ret: IChildSelection[] = def.selectionSet.selections.map(sel => getChildSelections(def.operation, sel));
const fields: string[] = ret.map(x => x.iface);
const iface: string = postProcessor(exportFunction(interfaceBuilder(ifaceName, generateInterfaceDeclaration(fields))));
const additionalTypes: string[] = buildAdditionalTypes(ret);
return joinOutputs({
variables: variableInterface,
interface: iface,
additionalTypes,
});
} else if (def.kind === 'FragmentDefinition') {
const ifaceName: string = generateFragmentName(def.name.value);
// get the correct type
const onType: string = def.typeCondition.name.value;
const foundType: GraphQLType = parsedSchema.getType(onType);
const ret: IChildSelection[] = def.selectionSet.selections.map(sel => getChildSelections('query', sel, foundType));
const extensions: string[] = ret.filter(x => x.isFragment).map(x => x.iface);
const fields: string[] = ret.filter(x => !x.isFragment).map(x => x.iface);
const iface: string = postProcessor(
exportFunction(
interfaceBuilder(
addExtensionsToInterfaceName(ifaceName, extensions),
generateInterfaceDeclaration(fields)
)
)
);
const additionalTypes: string[] = buildAdditionalTypes(ret);
return joinOutputs({
interface: iface,
variables: '',
additionalTypes,
});
} else {
throw new Error(`Unsupported Definition ${def.kind}`);
}
}).concat(
enumDeclarations.size ? [
joinOutputs({
additionalTypes: getEnums(),
interface: '',
variables: ''
})
] : []
);
};
export default doIt; | the_stack |
import { Utils } from '../../lib/vulcan-lib/utils';
import { validateDocument, validateData, dataToModifier, modifierToData, } from './validation';
import { getSchema } from '../../lib/utils/getSchema';
import { throwError } from './errors';
import { Connectors } from './connectors';
import { getCollectionHooks, CollectionMutationCallbacks, CreateCallbackProperties, UpdateCallbackProperties, DeleteCallbackProperties } from '../mutationCallbacks';
import { logFieldChanges } from '../fieldChanges';
import { createAnonymousContext } from './query';
import clone from 'lodash/clone';
import isEmpty from 'lodash/isEmpty';
import { createError } from 'apollo-errors';
import pickBy from 'lodash/pickBy';
/**
* Create mutation
* Inserts an entry in a collection, and runs a bunch of callback functions to
* fill in its denormalized fields etc. Input is a Partial<T>, because some
* fields will be filled in by those callbacks; result is a T, but nothing
* in the type system ensures that everything actually gets filled in.
*/
export const createMutator = async <T extends DbObject>({
collection,
document,
data,
currentUser=null,
validate=true,
context,
}: {
collection: CollectionBase<T>,
document: Partial<DbInsertion<T>>,
data?: Partial<DbInsertion<T>>,
currentUser?: DbUser|null,
validate?: boolean,
context?: ResolverContext,
}): Promise<{
data: T
}> => {
// OpenCRUD backwards compatibility: accept either data or document
// we don't want to modify the original document
document = data || document;
// If no context is provided, create a new one (so that callbacks will have
// access to loaders)
if (!context)
context = createAnonymousContext();
const { collectionName } = collection;
const schema = getSchema(collection);
// Cast because the type system doesn't know that the collectionName on a
// collection object identifies the collection object type
const hooks = getCollectionHooks(collectionName) as unknown as CollectionMutationCallbacks<T>;
/*
Properties
Note: keep newDocument for backwards compatibility
*/
const properties: CreateCallbackProperties<T> = {
data: data as unknown as T, // Pretend this isn't Partial<T>
currentUser, collection, context,
document: document as unknown as T, // Pretend this isn't Partial<T>
newDocument: document as unknown as T, // Pretend this isn't Partial<T>
schema
};
/*
Validation
*/
if (validate) {
let validationErrors: Array<any> = [];
validationErrors = validationErrors.concat(validateDocument(document, collection, context));
// run validation callbacks
validationErrors = await hooks.createValidate.runCallbacks({
iterator: validationErrors,
properties: [properties],
ignoreExceptions: false,
});
// OpenCRUD backwards compatibility
document = await hooks.newValidate.runCallbacks({
iterator: document as DbInsertion<T>, // Pretend this isn't Partial<T>
properties: [currentUser, validationErrors],
ignoreExceptions: false,
});
if (validationErrors.length) {
console.log(validationErrors); // eslint-disable-line no-console
throwError({ id: 'app.validation_error', data: { break: true, errors: validationErrors } });
}
}
// userId
//
// If user is logged in, check if userId field is in the schema and add it to
// document if needed.
// FIXME: This is a horrible hack; there's no good reason for this not to be
// using the same callbacks as everything else.
if (currentUser) {
const userIdInSchema = Object.keys(schema).find(key => key === 'userId');
if (!!userIdInSchema && !(document as any).userId) {
(document as any).userId = currentUser._id;
}
}
/*
onCreate
note: cannot use forEach with async/await.
See https://stackoverflow.com/a/37576787/649299
note: clone arguments in case callbacks modify them
*/
for (let fieldName of Object.keys(schema)) {
let autoValue;
const schemaField = schema[fieldName];
if (schemaField.onCreate) {
// OpenCRUD backwards compatibility: keep both newDocument and data for now, but phase out newDocument eventually
// eslint-disable-next-line no-await-in-loop
autoValue = await schemaField.onCreate({...properties, fieldName} as any); // eslint-disable-line no-await-in-loop
} else if (schemaField.onInsert) {
// OpenCRUD backwards compatibility
autoValue = await schemaField.onInsert(clone(document) as any, currentUser); // eslint-disable-line no-await-in-loop
}
if (typeof autoValue !== 'undefined') {
document[fieldName] = autoValue;
}
}
// TODO: find that info in GraphQL mutations
// if (isServer && this.connection) {
// post.userIP = this.connection.clientAddress;
// post.userAgent = this.connection.httpHeaders['user-agent'];
// }
/*
Before
*/
document = await hooks.createBefore.runCallbacks({
iterator: document as unknown as T, // Pretend this isn't Partial<T>
properties: [properties],
}) as unknown as Partial<DbInsertion<T>>;
// OpenCRUD backwards compatibility
document = await hooks.newBefore.runCallbacks({
iterator: document as unknown as T, // Pretend this isn't Partial<T>
properties: [
currentUser
]
}) as unknown as Partial<DbInsertion<T>>;
document = await hooks.newSync.runCallbacks({
iterator: document as unknown as T, // Pretend this isn't Partial<T>
properties: [currentUser]
}) as unknown as Partial<DbInsertion<T>>;
/*
DB Operation
*/
(document as any)._id = await Connectors.create(collection, document as unknown as T);
/*
After
*/
// run any post-operation sync callbacks
document = await hooks.createAfter.runCallbacks({
iterator: document as unknown as T, // Pretend this isn't Partial<T>
properties: [properties],
}) as unknown as DbInsertion<T>;
// OpenCRUD backwards compatibility
document = await hooks.newAfter.runCallbacks({
iterator: document as unknown as T, // Pretend this isn't Partial<T>
properties: [currentUser]
}) as unknown as DbInsertion<T>;
// note: query for document to get fresh document with collection-hooks effects applied
let completedDocument: T = document as unknown as T;
const queryResult = await Connectors.get(collection, document._id);
if (queryResult)
completedDocument = queryResult;
/*
Async
*/
// note: make sure properties.document is up to date
await hooks.createAsync.runCallbacksAsync(
[{ ...properties, document: completedDocument as T }],
);
// OpenCRUD backwards compatibility
await hooks.newAsync.runCallbacksAsync([
completedDocument,
currentUser,
collection
]);
return { data: completedDocument };
};
/**
* Update mutation
* Updates a single database entry, and runs callbacks/etc to update its
* denormalized fields. The preferred way to do this is with a documentId;
* in theory you can use a selector, but you should only do this if you're sure
* there's only one matching document (eg, slug). Returns the modified document.
*/
export const updateMutator = async <T extends DbObject>({
collection,
documentId,
selector,
data: dataParam,
set = {},
unset = {},
currentUser=null,
validate=true,
context,
document: oldDocument,
}: {
collection: CollectionBase<T>,
documentId: string,
selector?: any,
data?: Partial<DbInsertion<T>>,
set?: Partial<DbInsertion<T>>,
unset?: any,
currentUser?: DbUser|null,
validate?: boolean,
context?: ResolverContext,
document?: T|null,
}): Promise<{
data: T
}> => {
const { collectionName } = collection;
const schema = getSchema(collection);
// If no context is provided, create a new one (so that callbacks will have
// access to loaders)
if (!context)
context = createAnonymousContext();
// OpenCRUD backwards compatibility
selector = selector || { _id: documentId };
let data = dataParam || modifierToData({ $set: set, $unset: unset });
// Save the original mutation (before callbacks add more changes to it) for
// logging in LWEvents
let origData = {...data};
// Cast because the type system doesn't know that the collectionName on a
// collection object identifies the collection object type
const hooks = getCollectionHooks(collectionName) as unknown as CollectionMutationCallbacks<T>;
if (isEmpty(selector)) {
throw new Error('Selector cannot be empty');
}
// get original document from database or arguments
oldDocument = oldDocument || (await Connectors.get(collection, selector));
if (!oldDocument) {
throw new Error(`Could not find document to update for selector: ${JSON.stringify(selector)}`);
}
// get a "preview" of the new document
let document: T = { ...oldDocument, ...data };
// FIXME: Filtering out null-valued fields here is a very sketchy, probably
// wrong thing to do. This originates from Vulcan, and it's not clear why it's
// doing it. Explicit cast to make it type-check anyways.
document = pickBy(document, f => f !== null) as any;
/*
Properties
*/
const properties: UpdateCallbackProperties<T> = {
data: data||{},
oldDocument,
document,
newDocument: document,
currentUser, collection, context, schema
};
/*
Validation
*/
if (validate) {
let validationErrors: any = [];
validationErrors = validationErrors.concat(validateData(data, document, collection, context));
validationErrors = await hooks.updateValidate.runCallbacks({
iterator: validationErrors,
properties: [properties],
ignoreExceptions: false,
});
// OpenCRUD backwards compatibility
data = modifierToData(
await hooks.editValidate.runCallbacks({
iterator: dataToModifier(data),
properties: [document, currentUser, validationErrors],
ignoreExceptions: false,
})
);
// LESSWRONG - added custom message (showing all validation errors instead of a generic message)
if (validationErrors.length) {
console.log('// validationErrors'); // eslint-disable-line no-console
console.log(validationErrors); // eslint-disable-line no-console
const EditDocumentValidationError = createError('app.validation_error', {message: JSON.stringify(validationErrors)});
throw new EditDocumentValidationError({data: { break: true, errors: validationErrors }});
}
}
/*
onUpdate
*/
for (let fieldName of Object.keys(schema)) {
let autoValue;
const schemaField = schema[fieldName];
if (schemaField.onUpdate) {
// eslint-disable-next-line no-await-in-loop
autoValue = await schemaField.onUpdate({...properties, fieldName});
} else if (schemaField.onEdit) {
// OpenCRUD backwards compatibility
// eslint-disable-next-line no-await-in-loop
autoValue = await schemaField.onEdit(
dataToModifier(clone(data)),
oldDocument,
currentUser,
document
);
}
if (typeof autoValue !== 'undefined') {
data![fieldName] = autoValue;
}
}
/*
Before
*/
data = await hooks.updateBefore.runCallbacks({
iterator: data,
properties: [properties],
});
// OpenCRUD backwards compatibility
data = modifierToData(
await hooks.editBefore.runCallbacks({
iterator: dataToModifier(data),
properties: [
oldDocument,
currentUser,
document
]
})
);
data = modifierToData(
await hooks.editSync.runCallbacks({
iterator: dataToModifier(data),
properties: [
oldDocument,
currentUser,
document
]
})
);
// update connector requires a modifier, so get it from data
const modifier = dataToModifier(data);
// remove empty modifiers
if (isEmpty(modifier.$set)) {
delete modifier.$set;
}
if (isEmpty(modifier.$unset)) {
delete modifier.$unset;
}
/*
DB Operation
*/
if (!isEmpty(modifier)) {
// update document
await Connectors.updateOne(collection, selector, modifier, { removeEmptyStrings: false });
// get fresh copy of document from db
const fetched = await Connectors.get(collection, selector);
if (!fetched)
throw new Error("Could not find updated document after applying update");
document = fetched;
// TODO: add support for caching by other indexes to Dataloader
// https://github.com/VulcanJS/Vulcan/issues/2000
// clear cache if needed
if (selector.documentId && context) {
context.loaders[collectionName].clear(selector.documentId);
}
}
/*
After
*/
document = await hooks.updateAfter.runCallbacks({
iterator: document,
properties: [properties],
});
// OpenCRUD backwards compatibility
document = await hooks.editAfter.runCallbacks({
iterator: document,
properties: [
oldDocument,
currentUser
]
});
/*
Async
*/
// run async callbacks
await hooks.updateAsync.runCallbacksAsync([properties]);
// OpenCRUD backwards compatibility
await hooks.editAsync.runCallbacksAsync([
document,
oldDocument,
currentUser,
collection
]);
void logFieldChanges({currentUser, collection, oldDocument, data: origData});
return { data: document };
};
//
// Delete mutation
// Deletes a single database entry, and runs any callbacks/etc that trigger on
// that. Returns the entry that was deleted.
//
export const deleteMutator = async <T extends DbObject>({
collection,
documentId,
selector,
currentUser=null,
validate=true,
context,
document,
}: {
collection: CollectionBase<T>,
documentId: string,
selector?: MongoSelector<T>,
currentUser?: DbUser|null,
validate?: boolean,
context?: ResolverContext,
document?: T|null,
}): Promise<{
data: T|null|undefined
}> => {
const { collectionName } = collection;
const schema = getSchema(collection);
// OpenCRUD backwards compatibility
selector = selector || { _id: documentId };
// Cast because the type system doesn't know that the collectionName on a
// collection object identifies the collection object type
const hooks = getCollectionHooks(collectionName) as unknown as CollectionMutationCallbacks<T>;
// If no context is provided, create a new one (so that callbacks will have
// access to loaders)
if (!context)
context = createAnonymousContext();
if (isEmpty(selector)) {
throw new Error('Selector cannot be empty');
}
document = document || (await Connectors.get(collection, selector));
if (!document) {
throw new Error(`Could not find document to delete for selector: ${JSON.stringify(selector)}`);
}
/*
Properties
*/
const properties: DeleteCallbackProperties<T> = { document, currentUser, collection, context, schema };
/*
Validation
*/
if (validate) {
let validationErrors: any = [];
validationErrors = await hooks.deleteValidate.runCallbacks({
iterator: validationErrors,
properties: [properties],
ignoreExceptions: false,
});
// OpenCRUD backwards compatibility
document = await hooks.removeValidate.runCallbacks({
iterator: document,
properties: [currentUser],
ignoreExceptions: false,
});
if (validationErrors.length) {
console.log(validationErrors); // eslint-disable-line no-console
throwError({ id: 'app.validation_error', data: { break: true, errors: validationErrors } });
}
}
/*
onDelete
*/
for (let fieldName of Object.keys(schema)) {
const onDelete = schema[fieldName].onDelete;
if (onDelete) {
await onDelete(properties); // eslint-disable-line no-await-in-loop
}
}
/*
Before
*/
await hooks.deleteBefore.runCallbacks({
iterator: document,
properties: [properties],
});
// OpenCRUD backwards compatibility
await hooks.removeBefore.runCallbacks({
iterator: document,
properties: [currentUser]
});
await hooks.removeSync.runCallbacks({
iterator: document,
properties: [currentUser]
});
/*
DB Operation
*/
await Connectors.delete(collection, selector);
// TODO: add support for caching by other indexes to Dataloader
// clear cache if needed
if (selector.documentId && context) {
context.loaders[collectionName].clear(selector.documentId);
}
/*
Async
*/
await hooks.deleteAsync.runCallbacksAsync([properties]);
// OpenCRUD backwards compatibility
await hooks.removeAsync.runCallbacksAsync([
document,
currentUser,
collection
]);
return { data: document };
};
Utils.createMutator = createMutator;
Utils.updateMutator = updateMutator;
Utils.deleteMutator = deleteMutator; | the_stack |
import {
all,
call,
put,
select,
takeEvery,
takeLatest
} from 'redux-saga/effects'
import { Name, PlaybackSource } from 'common/models/Analytics'
import { ID, UID } from 'common/models/Identifiers'
import Kind from 'common/models/Kind'
import { Track } from 'common/models/Track'
import { User } from 'common/models/User'
import { getUserId } from 'common/store/account/selectors'
import * as cacheActions from 'common/store/cache/actions'
import { getCollection } from 'common/store/cache/collections/selectors'
import { getId } from 'common/store/cache/selectors'
import { getTrack } from 'common/store/cache/tracks/selectors'
import { getUser } from 'common/store/cache/users/selectors'
import { makeUid, Uid } from 'common/utils/uid'
import { make } from 'store/analytics/actions'
import { getLineupSelectorForRoute } from 'store/lineup/lineupForRoute'
import {
getTrackId as getPlayerTrackId,
getUid as getPlayerUid
} from 'store/player/selectors'
import * as playerActions from 'store/player/slice'
import {
getId as getQueueTrackId,
getIndex,
getLength,
getOvershot,
getQueueAutoplay,
getRepeat,
getShuffle,
getSource,
getUid,
getUndershot
} from 'store/queue/selectors'
import {
add,
clear,
next,
pause,
play,
queueAutoplay,
persist,
previous,
remove
} from 'store/queue/slice'
import { RepeatMode, Source } from 'store/queue/types'
import { getRecommendedTracks } from '../recommendation/sagas'
import mobileSagas from './mobileSagas'
const NATIVE_MOBILE = process.env.REACT_APP_NATIVE_MOBILE
const QUEUE_SUBSCRIBER_NAME = 'QUEUE'
export function* getToQueue(prefix: string, entry: { kind: Kind; uid: UID }) {
if (entry.kind === Kind.COLLECTIONS) {
const collection = yield select(getCollection, { uid: entry.uid })
const {
playlist_contents: { track_ids: trackIds }
} = collection
// Replace the track uid source w/ the full source including collection source
// Replace the track count w/ it's index in the array
const collectionUid = Uid.fromString(entry.uid)
const collectionSource = collectionUid.source
return trackIds.map(
({ track, uid }: { track: ID; uid: UID }, idx: number) => {
const trackUid = Uid.fromString(uid)
trackUid.source = `${collectionSource}:${trackUid.source}`
trackUid.count = idx
return {
id: track,
uid: trackUid.toString(),
source: prefix
}
}
)
} else if (entry.kind === Kind.TRACKS) {
const track = yield select(getTrack, { uid: entry.uid })
if (!track) return {}
return {
id: track.track_id,
uid: entry.uid,
source: prefix
}
}
}
const flatten = (list: any[]): any[] =>
list.reduce((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), [])
function* handleQueueAutoplay({
skip,
ignoreSkip,
track
}: {
skip: boolean
ignoreSkip: boolean
track: any
}) {
const isQueueAutoplayEnabled = yield select(getQueueAutoplay)
const index = yield select(getIndex)
if (!isQueueAutoplayEnabled || index < 0) {
return
}
// Get recommended tracks if not in shuffle mode
// and not in repeat mode and
// - close to end of queue, or
// - playing first song of lineup and lineup has only one song
const length = yield select(getLength)
const shuffle = yield select(getShuffle)
const repeatMode = yield select(getRepeat)
const isCloseToEndOfQueue = index + 1 >= length
const isOnlySongInQueue = index === 0 && length === 1
const isNotRepeating =
repeatMode === RepeatMode.OFF ||
(repeatMode === RepeatMode.SINGLE && (skip || ignoreSkip))
if (
!shuffle &&
isNotRepeating &&
(isCloseToEndOfQueue || isOnlySongInQueue)
) {
const userId = yield select(getUserId)
yield put(
queueAutoplay({
genre: track?.genre,
exclusionList: track ? [track.track_id] : [],
currentUserId: userId
})
)
}
}
/**
* Play the queue. The side effects are slightly complicated, but can be summarzed in the following
* cases.
* 1. If the caller provided a uid, play that uid.
* 2. If no uid was provided and the queue is empty, find whatever lineup is on the page, queue it and play it.
* 3. If the queue is indexed onto a different uid than the player, play the queue's uid
* 4. Resume whatever was playing on the player
*/
export function* watchPlay() {
yield takeLatest(play.type, function* (action: ReturnType<typeof play>) {
// persist queue in mobile layer
yield put(persist({}))
const { uid, trackId } = action.payload
// Play a specific uid
const playerUid = yield select(getPlayerUid)
const playerTrackId: ID = yield select(getPlayerTrackId)
if (uid || trackId) {
const playActionTrack: Track = trackId
? yield select(getTrack, { id: trackId })
: yield select(getTrack, { uid })
yield call(handleQueueAutoplay, {
skip: false,
ignoreSkip: true,
track: playActionTrack
})
const user: User = playActionTrack
? yield select(getUser, { id: playActionTrack.owner_id })
: null
// Skip deleted tracks
if (
(playActionTrack && playActionTrack.is_delete) ||
user?.is_deactivated
) {
yield put(next({}))
return
}
// Make sure that we should actually play
const repeatMode = yield select(getRepeat)
const noTrackPlaying = !playerTrackId
const trackIsDifferent = playerTrackId !== playActionTrack.track_id
const trackIsSameButDifferentUid =
playerTrackId === playActionTrack.track_id && uid !== playerUid
const trackIsSameAndRepeatSingle =
playerTrackId === playActionTrack.track_id &&
repeatMode === RepeatMode.SINGLE
if (
noTrackPlaying ||
trackIsDifferent ||
trackIsSameButDifferentUid ||
trackIsSameAndRepeatSingle
) {
yield put(playerActions.stop({}))
yield put(
playerActions.play({
uid: uid,
trackId: playActionTrack.track_id,
onEnd: next
})
)
} else {
yield put(playerActions.play({}))
}
} else {
// If nothing is queued, grab the proper lineup, queue it and play it
const index = yield select(getIndex)
if (index === -1) {
const lineup = yield select(getLineupSelectorForRoute())
if (!lineup) return
if (lineup.entries.length > 0) {
yield put(clear({}))
const toQueue = yield all(
lineup.entries.map((e: { kind: Kind; uid: UID }) =>
call(getToQueue, lineup.prefix, e)
)
)
const flattenedQueue = flatten(toQueue)
yield put(add({ entries: flattenedQueue }))
const playTrack = yield select(getTrack, {
uid: flattenedQueue[0].uid
})
yield put(
play({
uid: flattenedQueue[0].uid,
trackId: playTrack.track_id,
source: lineup.prefix
})
)
}
} else {
const queueUid = yield select(getPlayerUid)
const playerTrackid = yield select(getPlayerTrackId)
if (queueUid !== playerUid) {
yield put(playerActions.stop({}))
yield put(
playerActions.play({ uid: queueUid, trackId: playerTrackid })
)
} else {
// Play whatever is/was playing
yield put(playerActions.play({}))
}
}
}
})
}
export function* watchPause() {
yield takeEvery(pause.type, function* (action: ReturnType<typeof pause>) {
yield put(playerActions.pause({}))
})
}
export function* watchNext() {
yield takeEvery(next.type, function* (action: ReturnType<typeof next>) {
const { skip } = action.payload
// If the queue has overshot the end, reset the song
const overshot = yield select(getOvershot)
if (overshot) {
yield put(playerActions.reset({ shouldAutoplay: false }))
return
}
const id: ID = yield select(getQueueTrackId)
const track: Track = yield select(getTrack, { id })
const user: User = yield select(getUser, { id: track?.owner_id })
// Skip deleted or owner deactivated track
if (track && (track.is_delete || user?.is_deactivated)) {
yield put(next({ skip }))
} else {
const uid = yield select(getUid)
const source = yield select(getSource)
yield call(handleQueueAutoplay, {
skip: !!skip,
ignoreSkip: false,
track
})
if (track) {
yield put(play({ uid, trackId: id, source }))
const event = make(Name.PLAYBACK_PLAY, {
id: `${id}`,
source: PlaybackSource.PASSIVE
})
yield put(event)
} else {
yield put(playerActions.stop({}))
}
}
})
}
export function* watchQueueAutoplay() {
yield takeEvery(queueAutoplay.type, function* (
action: ReturnType<typeof queueAutoplay>
) {
const { genre, exclusionList, currentUserId } = action.payload
const tracks: Track[] = yield call(
getRecommendedTracks,
genre,
exclusionList,
currentUserId
)
const recommendedTracks = tracks.map(({ track_id }) => ({
id: track_id,
uid: makeUid(Kind.TRACKS, track_id),
source: Source.RECOMMENDED_TRACKS
}))
yield put(add({ entries: recommendedTracks }))
})
}
export function* watchPrevious() {
yield takeEvery(previous.type, function* (
action: ReturnType<typeof previous>
) {
// If the queue has undershot the beginning, reset the song
const undershot = yield select(getUndershot)
if (undershot) {
yield put(playerActions.reset({ shouldAutoplay: false }))
return
}
const uid = yield select(getUid)
const id: ID = yield select(getQueueTrackId)
const track: Track = yield select(getTrack, { id })
const source = yield select(getSource)
const user: User = yield select(getUser, { id: track?.owner_id })
// If we move to a previous song that's been
// deleted, skip over it.
if (track && (track.is_delete || user?.is_deactivated)) {
yield put(previous({}))
} else {
const index = yield select(getIndex)
if (index >= 0) {
yield put(play({ uid, trackId: id, source }))
const event = make(Name.PLAYBACK_PLAY, {
id: `${id}`,
source: PlaybackSource.PASSIVE
})
yield put(event)
} else {
yield put(playerActions.stop({}))
}
}
})
}
export function* watchAdd() {
yield takeEvery(add.type, function* (action: ReturnType<typeof add>) {
const { entries } = action.payload
const subscribers = entries.map(entry => ({
uid: QUEUE_SUBSCRIBER_NAME,
id: entry.id
}))
yield put(cacheActions.subscribe(Kind.TRACKS, subscribers))
// persist queue in mobile layer
yield put(persist({}))
})
}
export function* watchRemove() {
yield takeEvery(remove.type, function* (action: ReturnType<typeof remove>) {
const { uid } = action.payload
const id = yield select(getId, { kind: Kind.TRACKS, uid })
yield put(
cacheActions.unsubscribe(Kind.TRACKS, [
{ uid: QUEUE_SUBSCRIBER_NAME, id }
])
)
})
}
const sagas = () => {
const sagas = [
watchPlay,
watchPause,
watchNext,
watchQueueAutoplay,
watchPrevious,
watchAdd,
watchRemove
]
return NATIVE_MOBILE ? sagas.concat(mobileSagas()) : sagas
}
export default sagas | the_stack |
// clang-format off
import {webUIListenerCallback} from 'chrome://resources/js/cr.m.js';
import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {AddSiteDialogElement, ContentSetting, ContentSettingsTypes, SettingsEditExceptionDialogElement, SITE_EXCEPTION_WILDCARD, SiteException, SiteListElement, SiteSettingSource, SiteSettingsPrefsBrowserProxyImpl} from 'chrome://settings/lazy_load.js';
import {CrSettingsPrefs, loadTimeData, Router} from 'chrome://settings/settings.js';
import {assertEquals, assertFalse, assertNotEquals, assertTrue} from 'chrome://webui-test/chai_assert.js';
import {eventToPromise, waitBeforeNextRender} from 'chrome://webui-test/test_util.js';
import {TestSiteSettingsPrefsBrowserProxy} from './test_site_settings_prefs_browser_proxy.js';
import {createContentSettingTypeToValuePair, createRawSiteException, createSiteSettingsPrefs, SiteSettingsPref} from './test_util.js';
// clang-format on
/**
* An example pref with 2 blocked location items and 2 allowed. This pref
* is also used for the All Sites category and therefore needs values for
* all types, even though some might be blank.
*/
let prefsGeolocation: SiteSettingsPref;
/**
* An example pref that is empty.
*/
let prefsGeolocationEmpty: SiteSettingsPref;
/**
* An example pref with mixed schemes (present and absent).
*/
let prefsMixedSchemes: SiteSettingsPref;
/**
* An example pref with exceptions with origins and patterns from
* different providers.
*/
let prefsMixedProvider: SiteSettingsPref;
/**
* An example pref with with and without embeddingOrigin.
*/
let prefsMixedEmbeddingOrigin: SiteSettingsPref;
/**
* An example pref with file system write
*/
let prefsFileSystemWrite: SiteSettingsPref;
/**
* An example pref with multiple categories and multiple allow/block
* state.
*/
let prefsVarious: SiteSettingsPref;
/**
* An example pref with 1 allowed location item.
*/
let prefsOneEnabled: SiteSettingsPref;
/**
* An example pref with 1 blocked location item.
*/
let prefsOneDisabled: SiteSettingsPref;
/**
* An example Cookies pref with 1 in each of the three categories.
*/
let prefsSessionOnly: SiteSettingsPref;
/**
* An example Cookies pref with mixed incognito and regular settings.
*/
let prefsIncognito: SiteSettingsPref;
/**
* An example Javascript pref with a chrome-extension:// scheme.
*/
let prefsChromeExtension: SiteSettingsPref;
/**
* An example pref with 1 embargoed location item.
*/
let prefsEmbargo: SiteSettingsPref;
/**
* Creates all the test |SiteSettingsPref|s that are needed for the tests in
* this file. They are populated after test setup in order to access the
* |settings| constants required.
*/
function populateTestExceptions() {
prefsGeolocation = createSiteSettingsPrefs([], [
createContentSettingTypeToValuePair(
ContentSettingsTypes.GEOLOCATION,
[
createRawSiteException('https://bar-allow.com:443'),
createRawSiteException('https://foo-allow.com:443'),
createRawSiteException('https://bar-block.com:443', {
setting: ContentSetting.BLOCK,
}),
createRawSiteException('https://foo-block.com:443', {
setting: ContentSetting.BLOCK,
})
]),
]);
prefsMixedSchemes = createSiteSettingsPrefs([], [
createContentSettingTypeToValuePair(
ContentSettingsTypes.GEOLOCATION,
[
createRawSiteException('https://foo-allow.com', {
source: SiteSettingSource.POLICY,
}),
createRawSiteException('bar-allow.com'),
]),
]);
prefsMixedProvider = createSiteSettingsPrefs([], [
createContentSettingTypeToValuePair(
ContentSettingsTypes.GEOLOCATION,
[
createRawSiteException('https://[*.]foo.com', {
setting: ContentSetting.BLOCK,
source: SiteSettingSource.POLICY,
}),
createRawSiteException('https://bar.foo.com', {
setting: ContentSetting.BLOCK,
source: SiteSettingSource.POLICY,
}),
createRawSiteException('https://[*.]foo.com', {
setting: ContentSetting.BLOCK,
source: SiteSettingSource.POLICY,
})
]),
]);
prefsMixedEmbeddingOrigin = createSiteSettingsPrefs([], [
createContentSettingTypeToValuePair(
ContentSettingsTypes.IMAGES,
[
createRawSiteException('https://foo.com', {
embeddingOrigin: 'https://example.com',
}),
createRawSiteException('https://bar.com', {
embeddingOrigin: '',
})
]),
]);
prefsVarious = createSiteSettingsPrefs([], [
createContentSettingTypeToValuePair(
ContentSettingsTypes.GEOLOCATION,
[
createRawSiteException('https://foo.com', {
embeddingOrigin: '',
}),
createRawSiteException('https://bar.com', {
embeddingOrigin: '',
})
]),
createContentSettingTypeToValuePair(
ContentSettingsTypes.NOTIFICATIONS,
[
createRawSiteException('https://google.com', {
embeddingOrigin: '',
}),
createRawSiteException('https://bar.com', {
embeddingOrigin: '',
}),
createRawSiteException('https://foo.com', {
embeddingOrigin: '',
})
]),
]);
prefsOneEnabled = createSiteSettingsPrefs([], [
createContentSettingTypeToValuePair(
ContentSettingsTypes.GEOLOCATION,
[createRawSiteException('https://foo-allow.com:443', {
embeddingOrigin: '',
})]),
]);
prefsOneDisabled = createSiteSettingsPrefs([], [
createContentSettingTypeToValuePair(
ContentSettingsTypes.GEOLOCATION,
[createRawSiteException('https://foo-block.com:443', {
embeddingOrigin: '',
setting: ContentSetting.BLOCK,
})]),
]);
prefsSessionOnly = createSiteSettingsPrefs([], [
createContentSettingTypeToValuePair(
ContentSettingsTypes.COOKIES,
[
createRawSiteException('http://foo-block.com', {
embeddingOrigin: '',
setting: ContentSetting.BLOCK,
}),
createRawSiteException('http://foo-allow.com', {
embeddingOrigin: '',
}),
createRawSiteException('http://foo-session.com', {
embeddingOrigin: '',
setting: ContentSetting.SESSION_ONLY,
})
]),
]);
prefsIncognito = createSiteSettingsPrefs([], [
createContentSettingTypeToValuePair(
ContentSettingsTypes.COOKIES,
[
// foo.com is blocked for regular sessions.
createRawSiteException('http://foo.com', {
embeddingOrigin: '',
setting: ContentSetting.BLOCK,
}),
// bar.com is an allowed incognito item.
createRawSiteException('http://bar.com', {
embeddingOrigin: '',
incognito: true,
}),
// foo.com is allowed in incognito (overridden).
createRawSiteException('http://foo.com', {
embeddingOrigin: '',
incognito: true,
})
]),
]);
prefsChromeExtension = createSiteSettingsPrefs([], [
createContentSettingTypeToValuePair(
ContentSettingsTypes.JAVASCRIPT,
[createRawSiteException(
'chrome-extension://cfhgfbfpcbnnbibfphagcjmgjfjmojfa/', {
embeddingOrigin: '',
setting: ContentSetting.BLOCK,
})]),
]);
prefsGeolocationEmpty = createSiteSettingsPrefs([], []);
prefsFileSystemWrite = createSiteSettingsPrefs(
[], [createContentSettingTypeToValuePair(
ContentSettingsTypes.FILE_SYSTEM_WRITE,
[createRawSiteException('http://foo.com', {
setting: ContentSetting.BLOCK,
})])]);
prefsEmbargo = createSiteSettingsPrefs([], [
createContentSettingTypeToValuePair(
ContentSettingsTypes.GEOLOCATION,
[createRawSiteException('https://foo-block.com:443', {
embeddingOrigin: '',
setting: ContentSetting.BLOCK,
isEmbargoed: true,
})]),
]);
}
suite('SiteListEmbargoedOrigin', function() {
/**
* A site list element created before each test.
*/
let testElement: SiteListElement;
/**
* The mock proxy object to use during test.
*/
let browserProxy: TestSiteSettingsPrefsBrowserProxy;
suiteSetup(function() {
CrSettingsPrefs.setInitialized();
});
suiteTeardown(function() {
CrSettingsPrefs.resetForTesting();
});
// Initialize a site-list before each test.
setup(function() {
populateTestExceptions();
browserProxy = new TestSiteSettingsPrefsBrowserProxy();
SiteSettingsPrefsBrowserProxyImpl.setInstance(browserProxy);
document.body.innerHTML = '';
testElement = document.createElement('site-list');
testElement.searchFilter = '';
document.body.appendChild(testElement);
});
teardown(function() {
// The code being tested changes the Route. Reset so that state is not
// leaked across tests.
Router.getInstance().resetRouteForTesting();
});
/**
* Configures the test element for a particular category.
* @param category The category to set up.
* @param subtype Type of list to use.
* @param prefs The prefs to use.
*/
function setUpCategory(
category: ContentSettingsTypes, subtype: ContentSetting,
prefs: SiteSettingsPref) {
browserProxy.setPrefs(prefs);
testElement.categorySubtype = subtype;
testElement.category = category;
}
test('embaroed origin site description', async function() {
const contentType = ContentSettingsTypes.GEOLOCATION;
setUpCategory(contentType, ContentSetting.BLOCK, prefsEmbargo);
const result = await browserProxy.whenCalled('getExceptionList');
flush();
assertEquals(contentType, result);
// Validate that the sites gets populated from pre-canned prefs.
assertEquals(1, testElement.sites.length);
assertEquals(
prefsEmbargo.exceptions[contentType][0]!.origin,
testElement.sites[0]!.origin);
assertTrue(testElement.sites[0]!.isEmbargoed);
// Validate that embargoed site has correct subtitle.
assertEquals(
loadTimeData.getString('siteSettingsSourceEmbargo'),
testElement.$.listContainer.querySelectorAll('site-list-entry')[0]!
.shadowRoot!.querySelector('#siteDescription')!.innerHTML);
});
});
suite('SiteList', function() {
/**
* A site list element created before each test.
*/
let testElement: SiteListElement;
/**
* The mock proxy object to use during test.
*/
let browserProxy: TestSiteSettingsPrefsBrowserProxy;
suiteSetup(function() {
// clang-format off
CrSettingsPrefs.setInitialized();
// clang-format on
});
suiteTeardown(function() {
CrSettingsPrefs.resetForTesting();
});
// Initialize a site-list before each test.
setup(function() {
populateTestExceptions();
browserProxy = new TestSiteSettingsPrefsBrowserProxy();
SiteSettingsPrefsBrowserProxyImpl.setInstance(browserProxy);
document.body.innerHTML = '';
testElement = document.createElement('site-list');
testElement.searchFilter = '';
document.body.appendChild(testElement);
});
teardown(function() {
closeActionMenu();
// The code being tested changes the Route. Reset so that state is not
// leaked across tests.
Router.getInstance().resetRouteForTesting();
});
/**
* Opens the action menu for a particular element in the list.
* @param index The index of the child element (which site) to
* open the action menu for.
*/
function openActionMenu(index: number) {
const actionMenuButton =
testElement.$.listContainer.querySelectorAll('site-list-entry')[index]!
.$.actionMenuButton;
actionMenuButton.click();
flush();
}
/** Closes the action menu. */
function closeActionMenu() {
const menu = testElement.shadowRoot!.querySelector('cr-action-menu')!;
if (menu.open) {
menu.close();
}
}
/**
* Asserts the menu looks as expected.
* @param items The items expected to show in the menu.
*/
function assertMenu(items: string[]) {
const menu = testElement.shadowRoot!.querySelector('cr-action-menu');
assertTrue(!!menu);
const menuItems = menu!.querySelectorAll('button:not([hidden])');
assertEquals(items.length, menuItems.length);
for (let i = 0; i < items.length; i++) {
assertEquals(items[i], menuItems[i]!.textContent!.trim());
}
}
/**
* Configures the test element for a particular category.
* @param category The category to set up.
* @param subtype Type of list to use.
* @param prefs The prefs to use.
*/
function setUpCategory(
category: ContentSettingsTypes, subtype: ContentSetting,
prefs: SiteSettingsPref) {
browserProxy.setPrefs(prefs);
testElement.categorySubtype = subtype;
testElement.category = category;
}
test('read-only attribute', function() {
setUpCategory(
ContentSettingsTypes.GEOLOCATION, ContentSetting.ALLOW, prefsVarious);
return browserProxy.whenCalled('getExceptionList').then(function() {
// Flush to be sure list container is populated.
flush();
const dotsMenu =
testElement.shadowRoot!.querySelector(
'site-list-entry')!.$.actionMenuButton;
assertFalse(dotsMenu.hidden);
testElement.toggleAttribute('read-only-list', true);
flush();
assertTrue(dotsMenu.hidden);
testElement.removeAttribute('read-only-list');
flush();
assertFalse(dotsMenu.hidden);
});
});
test('getExceptionList API used', function() {
setUpCategory(
ContentSettingsTypes.GEOLOCATION, ContentSetting.ALLOW,
prefsGeolocationEmpty);
return browserProxy.whenCalled('getExceptionList')
.then(function(contentType) {
assertEquals(ContentSettingsTypes.GEOLOCATION, contentType);
});
});
test('Empty list', function() {
setUpCategory(
ContentSettingsTypes.GEOLOCATION, ContentSetting.ALLOW,
prefsGeolocationEmpty);
return browserProxy.whenCalled('getExceptionList')
.then(function(contentType) {
assertEquals(ContentSettingsTypes.GEOLOCATION, contentType);
assertEquals(0, testElement.sites.length);
assertEquals(ContentSetting.ALLOW, testElement.categorySubtype);
assertFalse(testElement.$.category.hidden);
});
});
test('initial ALLOW state is correct', function() {
setUpCategory(
ContentSettingsTypes.GEOLOCATION, ContentSetting.ALLOW,
prefsGeolocation);
return browserProxy.whenCalled('getExceptionList')
.then(function(contentType: ContentSettingsTypes) {
assertEquals(ContentSettingsTypes.GEOLOCATION, contentType);
assertEquals(2, testElement.sites.length);
assertEquals(
prefsGeolocation.exceptions[contentType][0]!.origin,
testElement.sites[0]!.origin);
assertEquals(
prefsGeolocation.exceptions[contentType][1]!.origin,
testElement.sites[1]!.origin);
assertEquals(ContentSetting.ALLOW, testElement.categorySubtype);
flush(); // Populates action menu.
openActionMenu(0);
assertMenu(['Block', 'Edit', 'Remove']);
assertFalse(testElement.$.category.hidden);
});
});
test('action menu closes when list changes', function() {
setUpCategory(
ContentSettingsTypes.GEOLOCATION, ContentSetting.ALLOW,
prefsGeolocation);
const actionMenu = testElement.shadowRoot!.querySelector('cr-action-menu')!;
return browserProxy.whenCalled('getExceptionList')
.then(function() {
flush(); // Populates action menu.
openActionMenu(0);
assertTrue(actionMenu.open);
browserProxy.resetResolver('getExceptionList');
// Simulate a change in the underlying model.
webUIListenerCallback(
'contentSettingSitePermissionChanged',
ContentSettingsTypes.GEOLOCATION);
return browserProxy.whenCalled('getExceptionList');
})
.then(function() {
// Check that the action menu was closed.
assertFalse(actionMenu.open);
});
});
test('exceptions are not reordered in non-ALL_SITES', async function() {
setUpCategory(
ContentSettingsTypes.GEOLOCATION, ContentSetting.BLOCK,
prefsMixedProvider);
const contentType: ContentSettingsTypes =
await browserProxy.whenCalled('getExceptionList');
assertEquals(ContentSettingsTypes.GEOLOCATION, contentType);
assertEquals(3, testElement.sites.length);
for (let i = 0; i < testElement.sites.length; ++i) {
const exception = prefsMixedProvider.exceptions[contentType][i]!;
assertEquals(exception.origin, testElement.sites[i]!.origin);
let expectedControlledBy =
chrome.settingsPrivate.ControlledBy.PRIMARY_USER;
if (exception.source === SiteSettingSource.EXTENSION ||
exception.source === SiteSettingSource.HOSTED_APP) {
expectedControlledBy = chrome.settingsPrivate.ControlledBy.EXTENSION;
} else if (exception.source === SiteSettingSource.POLICY) {
expectedControlledBy = chrome.settingsPrivate.ControlledBy.USER_POLICY;
}
assertEquals(expectedControlledBy, testElement.sites[i]!.controlledBy);
}
});
test('initial BLOCK state is correct', function() {
const contentType = ContentSettingsTypes.GEOLOCATION;
const categorySubtype = ContentSetting.BLOCK;
setUpCategory(contentType, categorySubtype, prefsGeolocation);
return browserProxy.whenCalled('getExceptionList')
.then(function(actualContentType) {
assertEquals(contentType, actualContentType);
assertEquals(categorySubtype, testElement.categorySubtype);
assertEquals(2, testElement.sites.length);
assertEquals(
prefsGeolocation.exceptions[contentType][2]!.origin,
testElement.sites[0]!.origin);
assertEquals(
prefsGeolocation.exceptions[contentType][3]!.origin,
testElement.sites[1]!.origin);
flush(); // Populates action menu.
openActionMenu(0);
assertMenu(['Allow', 'Edit', 'Remove']);
assertFalse(testElement.$.category.hidden);
});
});
test('initial SESSION ONLY state is correct', function() {
const contentType = ContentSettingsTypes.COOKIES;
const categorySubtype = ContentSetting.SESSION_ONLY;
setUpCategory(contentType, categorySubtype, prefsSessionOnly);
return browserProxy.whenCalled('getExceptionList')
.then(function(actualContentType) {
assertEquals(contentType, actualContentType);
assertEquals(categorySubtype, testElement.categorySubtype);
assertEquals(1, testElement.sites.length);
assertEquals(
prefsSessionOnly.exceptions[contentType][2]!.origin,
testElement.sites[0]!.origin);
flush(); // Populates action menu.
openActionMenu(0);
assertMenu(['Allow', 'Block', 'Edit', 'Remove']);
assertFalse(testElement.$.category.hidden);
});
});
test('initial INCOGNITO BLOCK state is correct', function() {
const contentType = ContentSettingsTypes.COOKIES;
const categorySubtype = ContentSetting.BLOCK;
setUpCategory(contentType, categorySubtype, prefsIncognito);
return browserProxy.whenCalled('getExceptionList')
.then(function(actualContentType) {
assertEquals(contentType, actualContentType);
assertEquals(categorySubtype, testElement.categorySubtype);
assertEquals(1, testElement.sites.length);
assertEquals(
prefsIncognito.exceptions[contentType][0]!.origin,
testElement.sites[0]!.origin);
flush(); // Populates action menu.
openActionMenu(0);
// 'Clear on exit' is visible as this is not an incognito item.
assertMenu(['Allow', 'Clear on exit', 'Edit', 'Remove']);
// Select 'Remove' from menu.
const remove =
testElement.shadowRoot!.querySelector<HTMLElement>('#reset');
assertTrue(!!remove);
remove!.click();
return browserProxy.whenCalled('resetCategoryPermissionForPattern');
})
.then(function(args) {
assertEquals('http://foo.com', args[0]);
assertEquals('', args[1]);
assertEquals(contentType, args[2]);
assertFalse(args[3]); // Incognito.
});
});
test('initial INCOGNITO ALLOW state is correct', function() {
const contentType = ContentSettingsTypes.COOKIES;
const categorySubtype = ContentSetting.ALLOW;
setUpCategory(contentType, categorySubtype, prefsIncognito);
return browserProxy.whenCalled('getExceptionList')
.then(function(actualContentType) {
assertEquals(contentType, actualContentType);
assertEquals(categorySubtype, testElement.categorySubtype);
assertEquals(2, testElement.sites.length);
assertEquals(
prefsIncognito.exceptions[contentType][1]!.origin,
testElement.sites[0]!.origin);
assertEquals(
prefsIncognito.exceptions[contentType][2]!.origin,
testElement.sites[1]!.origin);
flush(); // Populates action menu.
openActionMenu(0);
// 'Clear on exit' is hidden for incognito items.
assertMenu(['Block', 'Edit', 'Remove']);
closeActionMenu();
// Select 'Remove' from menu on 'foo.com'.
openActionMenu(1);
const remove =
testElement.shadowRoot!.querySelector<HTMLElement>('#reset');
assertTrue(!!remove);
remove!.click();
return browserProxy.whenCalled('resetCategoryPermissionForPattern');
})
.then(function(args) {
assertEquals('http://foo.com', args[0]);
assertEquals('', args[1]);
assertEquals(contentType, args[2]);
assertTrue(args[3]); // Incognito.
});
});
test('reset button works for read-only content types', function() {
testElement.readOnlyList = true;
flush();
const contentType = ContentSettingsTypes.GEOLOCATION;
const categorySubtype = ContentSetting.ALLOW;
setUpCategory(contentType, categorySubtype, prefsOneEnabled);
return browserProxy.whenCalled('getExceptionList')
.then(function(actualContentType) {
assertEquals(contentType, actualContentType);
assertEquals(categorySubtype, testElement.categorySubtype);
assertEquals(1, testElement.sites.length);
assertEquals(
prefsOneEnabled.exceptions[contentType][0]!.origin,
testElement.sites[0]!.origin);
flush();
const item =
testElement.shadowRoot!.querySelector('site-list-entry')!;
// Assert action button is hidden.
const dots = item.$.actionMenuButton;
assertTrue(!!dots);
assertTrue(dots.hidden);
// Assert reset button is visible.
const resetButton =
item.shadowRoot!.querySelector<HTMLElement>('#resetSite');
assertTrue(!!resetButton);
assertFalse(resetButton!.hidden);
resetButton!.click();
return browserProxy.whenCalled('resetCategoryPermissionForPattern');
})
.then(function(args) {
assertEquals('https://foo-allow.com:443', args[0]);
assertEquals('', args[1]);
assertEquals(contentType, args[2]);
});
});
test('edit action menu opens edit exception dialog', function() {
setUpCategory(
ContentSettingsTypes.COOKIES, ContentSetting.SESSION_ONLY,
prefsSessionOnly);
return browserProxy.whenCalled('getExceptionList').then(function() {
flush(); // Populates action menu.
openActionMenu(0);
assertMenu(['Allow', 'Block', 'Edit', 'Remove']);
const menu = testElement.shadowRoot!.querySelector('cr-action-menu')!;
assertTrue(menu.open);
const edit = testElement.shadowRoot!.querySelector<HTMLElement>('#edit');
assertTrue(!!edit);
edit!.click();
flush();
assertFalse(menu.open);
assertTrue(!!testElement.shadowRoot!.querySelector(
'settings-edit-exception-dialog'));
});
});
test('edit dialog closes when incognito status changes', function() {
setUpCategory(
ContentSettingsTypes.COOKIES, ContentSetting.BLOCK, prefsSessionOnly);
return browserProxy.whenCalled('getExceptionList')
.then(function() {
flush(); // Populates action menu.
openActionMenu(0);
testElement.shadowRoot!.querySelector<HTMLElement>('#edit')!.click();
flush();
const dialog = testElement.shadowRoot!.querySelector(
'settings-edit-exception-dialog');
assertTrue(!!dialog);
const closeEventPromise = eventToPromise('close', dialog!);
browserProxy.setIncognito(true);
return closeEventPromise;
})
.then(() => {
assertFalse(!!testElement.shadowRoot!.querySelector(
'settings-edit-exception-dialog'));
});
});
test('list items shown and clickable when data is present', function() {
const contentType = ContentSettingsTypes.GEOLOCATION;
setUpCategory(contentType, ContentSetting.ALLOW, prefsGeolocation);
return browserProxy.whenCalled('getExceptionList')
.then(function(actualContentType) {
assertEquals(contentType, actualContentType);
// Required for firstItem to be found below.
flush();
// Validate that the sites gets populated from pre-canned prefs.
assertEquals(2, testElement.sites.length);
assertEquals(
prefsGeolocation.exceptions[contentType][0]!.origin,
testElement.sites[0]!.origin);
assertEquals(
prefsGeolocation.exceptions[contentType][1]!.origin,
testElement.sites[1]!.origin);
// Validate that the sites are shown in UI and can be selected.
const clickable =
testElement.shadowRoot!.querySelector('site-list-entry')!
.shadowRoot!.querySelector<HTMLElement>('.middle');
assertTrue(!!clickable);
clickable!.click();
assertEquals(
prefsGeolocation.exceptions[contentType][0]!.origin,
Router.getInstance().getQueryParameters().get('site'));
});
});
test('Block list open when Allow list is empty', function() {
// Prefs: One item in Block list, nothing in Allow list.
const contentType = ContentSettingsTypes.GEOLOCATION;
setUpCategory(contentType, ContentSetting.BLOCK, prefsOneDisabled);
return browserProxy.whenCalled('getExceptionList')
.then(function(actualContentType) {
assertEquals(contentType, actualContentType);
return waitBeforeNextRender(testElement);
})
.then(function() {
assertFalse(testElement.$.category.hidden);
assertNotEquals(0, testElement.$.listContainer.offsetHeight);
});
});
test('Block list open when Allow list is not empty', function() {
// Prefs: Items in both Block and Allow list.
const contentType = ContentSettingsTypes.GEOLOCATION;
setUpCategory(contentType, ContentSetting.BLOCK, prefsGeolocation);
return browserProxy.whenCalled('getExceptionList')
.then(function(actualContentType) {
assertEquals(contentType, actualContentType);
return waitBeforeNextRender(testElement);
})
.then(function() {
assertFalse(testElement.$.category.hidden);
assertNotEquals(0, testElement.$.listContainer.offsetHeight);
});
});
test('Allow list is always open (Block list empty)', function() {
// Prefs: One item in Allow list, nothing in Block list.
const contentType = ContentSettingsTypes.GEOLOCATION;
setUpCategory(contentType, ContentSetting.ALLOW, prefsOneEnabled);
return browserProxy.whenCalled('getExceptionList')
.then(function(actualContentType) {
assertEquals(contentType, actualContentType);
return waitBeforeNextRender(testElement);
})
.then(function() {
assertFalse(testElement.$.category.hidden);
assertNotEquals(0, testElement.$.listContainer.offsetHeight);
});
});
test('Allow list is always open (Block list non-empty)', function() {
// Prefs: Items in both Block and Allow list.
const contentType = ContentSettingsTypes.GEOLOCATION;
setUpCategory(contentType, ContentSetting.ALLOW, prefsGeolocation);
return browserProxy.whenCalled('getExceptionList')
.then(function(actualContentType) {
assertEquals(contentType, actualContentType);
return waitBeforeNextRender(testElement);
})
.then(function() {
assertFalse(testElement.$.category.hidden);
assertNotEquals(0, testElement.$.listContainer.offsetHeight);
});
});
test('Block list not hidden when empty', function() {
// Prefs: One item in Allow list, nothing in Block list.
const contentType = ContentSettingsTypes.GEOLOCATION;
setUpCategory(contentType, ContentSetting.BLOCK, prefsOneEnabled);
return browserProxy.whenCalled('getExceptionList')
.then(function(actualContentType) {
assertEquals(contentType, actualContentType);
assertFalse(testElement.$.category.hidden);
});
});
test('Allow list not hidden when empty', function() {
// Prefs: One item in Block list, nothing in Allow list.
const contentType = ContentSettingsTypes.GEOLOCATION;
setUpCategory(contentType, ContentSetting.ALLOW, prefsOneDisabled);
return browserProxy.whenCalled('getExceptionList')
.then(function(actualContentType) {
assertEquals(contentType, actualContentType);
assertFalse(testElement.$.category.hidden);
});
});
test('Mixed embeddingOrigin', function() {
setUpCategory(
ContentSettingsTypes.IMAGES, ContentSetting.ALLOW,
prefsMixedEmbeddingOrigin);
return browserProxy.whenCalled('getExceptionList').then(function() {
// Required for firstItem to be found below.
flush();
// Validate that embeddingOrigin sites cannot be edited.
const entries =
testElement.shadowRoot!.querySelectorAll('site-list-entry');
const firstItem = entries[0]!;
assertTrue(firstItem.$.actionMenuButton.hidden);
assertFalse(
firstItem.shadowRoot!.querySelector<HTMLElement>(
'#resetSite')!.hidden);
// Validate that non-embeddingOrigin sites can be edited.
const secondItem = entries[1]!;
assertFalse(secondItem.$.actionMenuButton.hidden);
assertTrue(
secondItem.shadowRoot!.querySelector<HTMLElement>(
'#resetSite')!.hidden);
});
});
test('Mixed schemes (present and absent)', function() {
// Prefs: One item with scheme and one without.
setUpCategory(
ContentSettingsTypes.GEOLOCATION, ContentSetting.ALLOW,
prefsMixedSchemes);
return browserProxy.whenCalled('getExceptionList').then(function() {
// No further checks needed. If this fails, it will hang the test.
});
});
test('Select menu item', function() {
// Test for error: "Cannot read property 'origin' of undefined".
setUpCategory(
ContentSettingsTypes.GEOLOCATION, ContentSetting.ALLOW,
prefsGeolocation);
return browserProxy.whenCalled('getExceptionList').then(function() {
flush();
openActionMenu(0);
const allow =
testElement.shadowRoot!.querySelector<HTMLElement>('#allow');
assertTrue(!!allow);
allow!.click();
return browserProxy.whenCalled('setCategoryPermissionForPattern');
});
});
test('Chrome Extension scheme', function() {
setUpCategory(
ContentSettingsTypes.JAVASCRIPT, ContentSetting.BLOCK,
prefsChromeExtension);
return browserProxy.whenCalled('getExceptionList')
.then(function() {
flush();
openActionMenu(0);
assertMenu(['Allow', 'Edit', 'Remove']);
const allow =
testElement.shadowRoot!.querySelector<HTMLElement>('#allow');
assertTrue(!!allow);
allow!.click();
return browserProxy.whenCalled('setCategoryPermissionForPattern');
})
.then(function(args) {
assertEquals(
'chrome-extension://cfhgfbfpcbnnbibfphagcjmgjfjmojfa/', args[0]);
assertEquals('', args[1]);
assertEquals(ContentSettingsTypes.JAVASCRIPT, args[2]);
assertEquals(ContentSetting.ALLOW, args[3]);
});
});
test('show-tooltip event fires on entry shows common tooltip', function() {
setUpCategory(
ContentSettingsTypes.GEOLOCATION, ContentSetting.ALLOW,
prefsGeolocation);
return browserProxy.whenCalled('getExceptionList').then(() => {
flush();
const entry =
testElement.$.listContainer.querySelector('site-list-entry')!;
const tooltip = testElement.$.tooltip;
const testsParams = [
['a', testElement, new MouseEvent('mouseleave')],
['b', testElement, new MouseEvent('click')],
['c', testElement, new Event('blur')],
['d', tooltip, new MouseEvent('mouseenter')],
];
testsParams.forEach(params => {
const text = params[0] as string;
const eventTarget = params[1] as HTMLElement;
const event = params[2] as MouseEvent;
entry.fire('show-tooltip', {target: testElement, text});
assertTrue(tooltip._showing);
assertEquals(text, tooltip.innerHTML.trim());
eventTarget.dispatchEvent(event);
assertFalse(tooltip._showing);
});
});
});
test(
'Add site button is hidden for content settings that don\'t allow it',
function() {
setUpCategory(
ContentSettingsTypes.FILE_SYSTEM_WRITE, ContentSetting.ALLOW,
prefsFileSystemWrite);
return browserProxy.whenCalled('getExceptionList').then(() => {
flush();
assertTrue(testElement.$.addSite.hidden);
});
});
});
suite('EditExceptionDialog', function() {
let dialog: SettingsEditExceptionDialogElement;
/**
* The dialog tests don't call |getExceptionList| so the exception needs to
* be processed as a |SiteException|.
*/
let cookieException: SiteException;
let browserProxy: TestSiteSettingsPrefsBrowserProxy;
setup(function() {
cookieException = {
category: ContentSettingsTypes.COOKIES,
embeddingOrigin: SITE_EXCEPTION_WILDCARD,
isEmbargoed: false,
incognito: false,
setting: ContentSetting.BLOCK,
enforcement: null,
controlledBy: chrome.settingsPrivate.ControlledBy.USER_POLICY,
displayName: 'foo.com',
origin: 'foo.com',
};
browserProxy = new TestSiteSettingsPrefsBrowserProxy();
SiteSettingsPrefsBrowserProxyImpl.setInstance(browserProxy);
document.body.innerHTML = '';
dialog = document.createElement('settings-edit-exception-dialog');
dialog.model = cookieException;
document.body.appendChild(dialog);
});
teardown(function() {
dialog.remove();
});
test('invalid input', function() {
const input = dialog.shadowRoot!.querySelector('cr-input');
assertTrue(!!input);
assertFalse(input!.invalid);
const actionButton = dialog.$.actionButton;
assertTrue(!!actionButton);
assertFalse(actionButton.disabled);
// Simulate user input of whitespace only text.
input!.value = ' ';
input!.fire('input');
flush();
assertTrue(actionButton.disabled);
assertTrue(input!.invalid);
// Simulate user input of invalid text.
browserProxy.setIsPatternValidForType(false);
const expectedPattern = '*';
input!.value = expectedPattern;
input!.fire('input');
return browserProxy.whenCalled('isPatternValidForType').then(function([
pattern, _category
]) {
assertEquals(expectedPattern, pattern);
assertTrue(actionButton.disabled);
assertTrue(input!.invalid);
});
});
test('action button calls proxy', function() {
const input = dialog.shadowRoot!.querySelector('cr-input');
assertTrue(!!input);
// Simulate user edit.
const newValue = input!.value + ':1234';
input!.value = newValue;
const actionButton = dialog.$.actionButton;
assertTrue(!!actionButton);
assertFalse(actionButton.disabled);
actionButton.click();
return browserProxy.whenCalled('resetCategoryPermissionForPattern')
.then(function(args) {
assertEquals(cookieException.origin, args[0]);
assertEquals(cookieException.embeddingOrigin, args[1]);
assertEquals(ContentSettingsTypes.COOKIES, args[2]);
assertEquals(cookieException.incognito, args[3]);
return browserProxy.whenCalled('setCategoryPermissionForPattern');
})
.then(function(args) {
assertEquals(newValue, args[0]);
assertEquals(SITE_EXCEPTION_WILDCARD, args[1]);
assertEquals(ContentSettingsTypes.COOKIES, args[2]);
assertEquals(cookieException.setting, args[3]);
assertEquals(cookieException.incognito, args[4]);
assertFalse(dialog.$.dialog.open);
});
});
});
suite('AddExceptionDialog', function() {
let dialog: AddSiteDialogElement;
let browserProxy: TestSiteSettingsPrefsBrowserProxy;
setup(function() {
populateTestExceptions();
browserProxy = new TestSiteSettingsPrefsBrowserProxy();
SiteSettingsPrefsBrowserProxyImpl.setInstance(browserProxy);
document.body.innerHTML = '';
dialog = document.createElement('add-site-dialog');
dialog.category = ContentSettingsTypes.GEOLOCATION;
dialog.contentSetting = ContentSetting.ALLOW;
dialog.hasIncognito = false;
document.body.appendChild(dialog);
});
teardown(function() {
dialog.remove();
});
test('incognito', function() {
dialog.set('hasIncognito', true);
flush();
assertFalse(dialog.$.incognito.checked);
dialog.$.incognito.checked = true;
// Changing the incognito status will reset the checkbox.
dialog.set('hasIncognito', false);
flush();
assertFalse(dialog.$.incognito.checked);
});
test('invalid input', function() {
// Initially the action button should be disabled, but the error warning
// should not be shown for an empty input.
const input = dialog.shadowRoot!.querySelector('cr-input');
assertTrue(!!input);
assertFalse(input!.invalid);
const actionButton = dialog.$.add;
assertTrue(!!actionButton);
assertTrue(actionButton.disabled);
// Simulate user input of invalid text.
browserProxy.setIsPatternValidForType(false);
const expectedPattern = 'foobarbaz';
input!.value = expectedPattern;
input!.fire('input');
return browserProxy.whenCalled('isPatternValidForType').then(function([
pattern, _category
]) {
assertEquals(expectedPattern, pattern);
assertTrue(actionButton.disabled);
assertTrue(input!.invalid);
});
});
}); | the_stack |
import { Either } from "../Either"
import { Internals } from "../Internals"
import { List } from "../List"
import { add } from "../Num"
import { Pair } from "../Tuple"
const { Just, Nothing, Left, Right } = Internals
// CONSTRUCTORS
test ("Right", () => {
expect (Right (3) .value) .toEqual (3)
expect (Right (3) .isRight) .toEqual (true)
expect (Right (3) .isLeft) .toEqual (false)
})
test ("Left", () => {
expect (Left (3) .value) .toEqual (3)
expect (Left (3) .isRight) .toEqual (false)
expect (Left (3) .isLeft) .toEqual (true)
})
// EITHER.EXTRA
test ("fromLeft", () => {
expect (Either.fromLeft (0) (Left (3)))
.toEqual (3)
expect (Either.fromLeft (0) (Right (3)))
.toEqual (0)
})
test ("fromRight", () => {
expect (Either.fromRight (0) (Right (3)))
.toEqual (3)
expect (Either.fromRight (0) (Left (3)))
.toEqual (0)
})
test ("fromEither", () => {
expect (Either.fromEither (Right (3)))
.toEqual (3)
expect (Either.fromEither (Left (0)))
.toEqual (0)
})
test ("fromLeft_", () => {
expect (Either.fromLeft_ (Left (3)))
.toEqual (3)
expect (() => Either.fromLeft_ (Right (3) as any))
.toThrow ()
})
test ("fromRight_", () => {
expect (Either.fromRight_ (Right (3)))
.toEqual (3)
expect (() => Either.fromRight_ (Left (3) as any))
.toThrow ()
})
test ("eitherToMaybe", () => {
expect (Either.eitherToMaybe (Left (3)))
.toEqual (Nothing)
expect (Either.eitherToMaybe (Right (3)))
.toEqual (Just (3))
})
test ("maybeToEither", () => {
expect (Either.maybeToEither ("test") (Just (3)))
.toEqual (Right (3))
expect (Either.maybeToEither ("test") (Nothing))
.toEqual (Left ("test"))
})
test ("maybeToEither_", () => {
expect (Either.maybeToEither_ (() => "test") (Just (3)))
.toEqual (Right (3))
expect (Either.maybeToEither_ (() => "test") (Nothing))
.toEqual (Left ("test"))
})
// BIFUNCTOR
test ("bimap", () => {
expect (Either.bimap (add (5)) (add (10)) (Left (3)))
.toEqual (Left (8))
expect (Either.bimap (add (5)) (add (10)) (Right (3)))
.toEqual (Right (13))
})
test ("first", () => {
expect (Either.first (add (5)) (Left (3)))
.toEqual (Left (8))
expect (Either.first (add (5)) (Right (3)))
.toEqual (Right (3))
})
test ("second", () => {
expect (Either.second (add (10)) (Left (3)))
.toEqual (Left (3))
expect (Either.second (add (10)) (Right (3)))
.toEqual (Right (13))
})
// APPLICATIVE
test ("pure", () => {
expect (Either.pure (2)) .toEqual (Right (2))
})
test ("ap", () => {
expect (Either.ap (Right ((x: number) => x * 2)) (Right (3)))
.toEqual (Right (6))
expect (Either.ap (Right ((x: number) => x * 2)) (Left ("b")))
.toEqual (Left ("b"))
expect (Either.ap (Left ("a")) (Right (3)))
.toEqual (Left ("a"))
expect (Either.ap (Left ("a")) (Left ("b")))
.toEqual (Left ("a"))
})
// MONAD
test ("bind", () => {
expect (Either.bind<number, number> (Left (3))
(x => Right (x * 2)))
.toEqual (Left (3))
expect (Either.bind (Right (2))
((x: number) => Right (x * 2)))
.toEqual (Right (4))
expect (Either.bind (Right (2))
((x: number) => Left (x * 2)))
.toEqual (Left (4))
})
test ("bindF", () => {
expect (Either.bindF ((x: number) => Right (x * 2))
(Left (3)))
.toEqual (Left (3))
expect (Either.bindF ((x: number) => Right (x * 2))
(Right (2)))
.toEqual (Right (4))
expect (Either.bindF ((x: number) => Left (x * 2))
(Right (2)))
.toEqual (Left (4))
})
test ("then", () => {
expect (Either.then (Right (3)) (Right (2)))
.toEqual (Right (2))
expect (Either.then (Left ("a")) (Right (2)))
.toEqual (Left ("a"))
expect (Either.then (Right (3)) (Left ("b")))
.toEqual (Left ("b"))
expect (Either.then (Left ("a")) (Left ("b")))
.toEqual (Left ("a"))
})
test ("kleisli", () => {
expect (Either.kleisli ((x: number) => x > 5 ? Left ("too large") : Right (x))
((x: number) => x < 0 ? Left ("too low") : Right (x))
(2))
.toEqual (Right (2))
expect (Either.kleisli ((x: number) => x > 5 ? Left ("too large") : Right (x))
((x: number) => x < 0 ? Left ("too low") : Right (x))
(6))
.toEqual (Left ("too large"))
expect (Either.kleisli ((x: number) => x > 5 ? Left ("too large") : Right (x))
((x: number) => x < 0 ? Left ("too low") : Right (x))
(-1))
.toEqual (Left ("too low"))
})
test ("join", () => {
expect (Either.join (Right (Right (3))))
.toEqual (Right (3))
expect (Either.join (Right (Left ("test"))))
.toEqual (Left ("test"))
expect (Either.join (Left (Left ("test"))))
.toEqual (Left (Left ("test")))
})
test ("mapM", () => {
expect (
Either.mapM ((x: number) => x === 2 ? Left ("test") : Right (x + 1))
(List.empty)
)
.toEqual (Right (List.empty))
expect (
Either.mapM ((x: number) => x === 2 ? Left ("test") : Right (x + 1))
(List (1, 3))
)
.toEqual (Right (List (2, 4)))
expect (
Either.mapM ((x: number) => x === 2 ? Left ("test") : Right (x + 1))
(List (1, 2, 3))
)
.toEqual (Left ("test"))
})
test ("liftM2", () => {
expect (Either.liftM2 ((x: number) => (y: number) => x + y) (Right (1)) (Right (2)))
.toEqual (Right (3))
expect (Either.liftM2 ((x: number) => (y: number) => x + y) (Left ("x")) (Right (2)))
.toEqual (Left ("x"))
expect (Either.liftM2 ((x: number) => (y: number) => x + y) (Right (1)) (Left ("y")))
.toEqual (Left ("y"))
expect (Either.liftM2 ((x: number) => (y: number) => x + y) (Left ("x")) (Left ("y")))
.toEqual (Left ("x"))
})
// FOLDABLE
test ("foldr", () => {
expect (Either.foldr ((x: number) => (acc: number) => x * 2 + acc) (2) (Right (3)))
.toEqual (8)
expect (Either.foldr ((x: number) => (acc: number) => x * 2 + acc) (2) (Left ("a")))
.toEqual (2)
})
test ("foldl", () => {
expect (Either.foldl ((acc: number) => (x: number) => x * 2 + acc) (2) (Right (3)))
.toEqual (8)
expect (Either.foldl ((acc: number) => (x: number) => x * 2 + acc) (2) (Left ("a")))
.toEqual (2)
})
test ("toList", () => {
expect (Either.toList (Right (3)))
.toEqual (List (3))
expect (Either.toList (Left ("a")))
.toEqual (List ())
})
test ("fnull", () => {
expect (Either.fnull (Right (3)))
.toEqual (false)
expect (Either.fnull (Left ("a")))
.toEqual (true)
})
test ("flength", () => {
expect (Either.flength (Right (3)))
.toEqual (1)
expect (Either.flength (Left ("a")))
.toEqual (0)
})
test ("elem", () => {
expect (Either.elem (3) (Left ("a")))
.toBeFalsy ()
expect (Either.elem (3) (Right (2)))
.toBeFalsy ()
expect (Either.elem (3) (Right (3)))
.toBeTruthy ()
})
test ("elemF", () => {
expect (Either.elemF<string | number> (Left ("a")) (3))
.toBeFalsy ()
expect (Either.elemF (Right (2)) (3))
.toBeFalsy ()
expect (Either.elemF (Right (3)) (3))
.toBeTruthy ()
})
test ("sum", () => {
expect (Either.sum (Right (3)))
.toEqual (3)
expect (Either.sum (Left ("a")))
.toEqual (0)
})
test ("product", () => {
expect (Either.product (Right (3)))
.toEqual (3)
expect (Either.product (Left ("a")))
.toEqual (1)
})
test ("concat", () => {
expect (Either.concat (Right (List (1, 2, 3))))
.toEqual (List (1, 2, 3))
expect (Either.concat (Left ("a")))
.toEqual (List ())
})
test ("concatMap", () => {
expect (Either.concatMap (e => List (e, e)) (Right (3)))
.toEqual (List (3, 3))
expect (Either.concatMap (e => List (e, e)) (Left ("a")))
.toEqual (List ())
})
test ("and", () => {
expect (Either.and (Right (true)))
.toEqual (true)
expect (Either.and (Right (false)))
.toEqual (false)
expect (Either.and (Left ("a")))
.toEqual (true)
})
test ("or", () => {
expect (Either.or (Right (true)))
.toEqual (true)
expect (Either.or (Right (false)))
.toEqual (false)
expect (Either.or (Left ("a")))
.toEqual (false)
})
test ("any", () => {
expect (Either.any ((e: number) => e > 3) (Right (5)))
.toEqual (true)
expect (Either.any ((e: number) => e > 3) (Right (3)))
.toEqual (false)
expect (Either.any ((e: number) => e > 3) (Left ("a")))
.toEqual (false)
})
test ("all", () => {
expect (Either.all ((e: number) => e > 3) (Right (5)))
.toEqual (true)
expect (Either.all ((e: number) => e > 3) (Right (3)))
.toEqual (false)
expect (Either.all ((e: number) => e > 3) (Left ("a")))
.toEqual (true)
})
test ("notElem", () => {
expect (Either.notElem (3) (Left ("a")))
.toBeTruthy ()
expect (Either.notElem (3) (Right (2)))
.toBeTruthy ()
expect (Either.notElem (3) (Right (3)))
.toBeFalsy ()
})
test ("find", () => {
expect (Either.find ((e: number) => e > 3) (Right (5)))
.toEqual (Just (5))
expect (Either.find ((e: number) => e > 3) (Right (3)))
.toEqual (Nothing)
expect (Either.find ((e: number) => e > 3) (Left ("a")))
.toEqual (Nothing)
})
// // EQ
// test ('equals', () => {
// expect (Either.equals (Right (3)) (Right (3)))
// .toBeTruthy ()
// expect (Either.equals (Left ('a')) (Left ('a')))
// .toBeTruthy ()
// expect (Either.equals (Right (3)) (Right (4)))
// .toBeFalsy ()
// expect (Either.equals (Left ('a')) (Left ('b')))
// .toBeFalsy ()
// expect (Either.equals (Left ('a')) (Right (4)))
// .toBeFalsy ()
// expect (Either.equals (Right (3)) (Left ('a')))
// .toBeFalsy ()
// })
// test ('notEquals', () => {
// expect (Either.notEquals (Right (3)) (Right (5)))
// .toBeTruthy ()
// expect (Either.notEquals (Left ('a')) (Left ('b')))
// .toBeTruthy ()
// expect (Either.notEquals (Left ('a')) (Right (5)))
// .toBeTruthy ()
// expect (Either.notEquals (Right (3)) (Left ('a')))
// .toBeTruthy ()
// expect (Either.notEquals (Right (2)) (Right (2)))
// .toBeFalsy ()
// expect (Either.notEquals (Left ('a')) (Left ('a')))
// .toBeFalsy ()
// })
// ORD
test ("gt", () => {
expect (Either.gt (Right (1)) (Right (2)))
.toBeTruthy ()
expect (Either.gt (Right (1)) (Right (1)))
.toBeFalsy ()
expect (Either.gt (Right (1)) (Left (1)))
.toBeFalsy ()
expect (Either.gt (Left (2)) (Right (2)))
.toBeTruthy ()
expect (Either.gt (Left (1)) (Left (2)))
.toBeTruthy ()
expect (Either.gt (Left (1)) (Left (1)))
.toBeFalsy ()
})
test ("lt", () => {
expect (Either.lt (Right (3)) (Right (2)))
.toBeTruthy ()
expect (Either.lt (Right (1)) (Right (1)))
.toBeFalsy ()
expect (Either.lt (Right (3)) (Left (3)))
.toBeTruthy ()
expect (Either.lt (Left (3)) (Right (2)))
.toBeFalsy ()
expect (Either.lt (Left (2)) (Left (1)))
.toBeTruthy ()
expect (Either.lt (Left (1)) (Left (1)))
.toBeFalsy ()
})
test ("gte", () => {
expect (Either.gte (Right (1)) (Right (2)))
.toBeTruthy ()
expect (Either.gte (Right (2)) (Right (2)))
.toBeTruthy ()
expect (Either.gte (Right (2)) (Right (1)))
.toBeFalsy ()
expect (Either.gte (Right (1)) (Left (1)))
.toBeFalsy ()
expect (Either.gte (Right (2)) (Left (1)))
.toBeFalsy ()
expect (Either.gte (Right (1)) (Left (2)))
.toBeFalsy ()
expect (Either.gte (Left (1)) (Right (2)))
.toBeTruthy ()
expect (Either.gte (Left (1)) (Right (1)))
.toBeTruthy ()
expect (Either.gte (Left (1)) (Right (0)))
.toBeTruthy ()
expect (Either.gte (Left (1)) (Left (2)))
.toBeTruthy ()
expect (Either.gte (Left (1)) (Left (1)))
.toBeTruthy ()
expect (Either.gte (Left (1)) (Left (0)))
.toBeFalsy ()
})
test ("lte", () => {
expect (Either.lte (Right (3)) (Right (2)))
.toBeTruthy ()
expect (Either.lte (Right (2)) (Right (2)))
.toBeTruthy ()
expect (Either.lte (Right (2)) (Right (3)))
.toBeFalsy ()
expect (Either.lte (Right (1)) (Left (2)))
.toBeTruthy ()
expect (Either.lte (Right (1)) (Left (1)))
.toBeTruthy ()
expect (Either.lte (Right (1)) (Left (0)))
.toBeTruthy ()
expect (Either.lte (Left (1)) (Right (2)))
.toBeFalsy ()
expect (Either.lte (Left (1)) (Right (1)))
.toBeFalsy ()
expect (Either.lte (Left (1)) (Right (0)))
.toBeFalsy ()
expect (Either.lte (Left (1)) (Left (2)))
.toBeFalsy ()
expect (Either.lte (Left (1)) (Left (1)))
.toBeTruthy ()
expect (Either.lte (Left (1)) (Left (0)))
.toBeTruthy ()
})
// SEMIGROUP
// test ('mappend', () => {
// expect(Just (List(3)).mappend(Just (List(2))))
// .toEqual(Just (List(3, 2)))
// expect(Just (List(3)).mappend(Nothing))
// .toEqual(Just (List(3)))
// expect(Nothing.mappend(Just (List(2))))
// .toEqual(Nothing)
// expect(Nothing.mappend(Nothing))
// .toEqual(Nothing)
// })
// EITHER FUNCTIONS
test ("isLeft", () => {
expect (Either.isLeft (Left (3)))
.toBeTruthy ()
expect (Either.isLeft (Right (3)))
.toBeFalsy ()
})
test ("isRight", () => {
expect (Either.isRight (Left (3)))
.toBeFalsy ()
expect (Either.isRight (Right (3)))
.toBeTruthy ()
})
test ("either", () => {
expect (Either.either (add (10)) (add (1)) (Right (3)))
.toEqual (4)
expect (Either.either (add (10)) (add (1)) (Left (3)))
.toEqual (13)
})
test ("lefts", () => {
expect (Either.lefts (List<Either<number, number>> (
Left (3),
Left (2),
Right (2),
Right (3),
Left (4),
Right (4)
)))
.toEqual (List (3, 2, 4))
})
test ("rights", () => {
expect (Either.rights (List<Either<number, number>> (
Left (3),
Left (2),
Right (2),
Right (3),
Left (4),
Right (4)
)))
.toEqual (List (2, 3, 4))
})
test ("partitionEithers", () => {
expect (Either.partitionEithers (List<Either<number, number>> (
Left (3),
Left (2),
Right (2),
Right (3),
Left (4),
Right (4)
)))
.toEqual (Pair (List (3, 2, 4), List (2, 3, 4)))
})
// CUSTOM EITHER FUNCTIONS
test ("isEither", () => {
expect (Either.isEither (4)) .toEqual (false)
expect (Either.isEither (Right (4))) .toEqual (true)
expect (Either.isEither (Left ("test"))) .toEqual (true)
})
test ("imapM", () => {
expect (
Either.imapM (i => (x: number) => x === 2 ? Left ("test") : Right (x + 1 + i))
(List.empty)
)
.toEqual (Right (List.empty))
expect (
Either.imapM (i => (x: number) => x === 2 ? Left ("test") : Right (x + 1 + i))
(List (1, 3))
)
.toEqual (Right (List (2, 5)))
expect (
Either.imapM (i => (x: number) => x === 2 ? Left ("test") : Right (x + 1 + i))
(List (1, 3, 4, 5))
)
.toEqual (Right (List (2, 5, 7, 9)))
expect (
Either.imapM (i => (x: number) => x === 2 ? Left ("test") : Right (x + 1 + i))
(List (1, 2, 3))
)
.toEqual (Left ("test"))
})
test ("invertEither", () => {
expect (Either.invertEither (Left ("test"))) .toEqual (Right ("test"))
expect (Either.invertEither (Right (4))) .toEqual (Left (4))
}) | the_stack |
import 'chrome://webui-test/mojo_webui_test_support.js';
import 'chrome://read-later.top-chrome/app.js';
import {ReadLaterAppElement} from 'chrome://read-later.top-chrome/app.js';
import {ReadLaterEntriesByStatus} from 'chrome://read-later.top-chrome/read_later.mojom-webui.js';
import {ReadLaterApiProxyImpl} from 'chrome://read-later.top-chrome/read_later_api_proxy.js';
import {ReadLaterItemElement} from 'chrome://read-later.top-chrome/read_later_item.js';
import {keyDownOn} from 'chrome://resources/polymer/v3_0/iron-test-helpers/mock-interactions.js';
import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js';
import {flushTasks} from 'chrome://webui-test/test_util.js';
import {TestReadLaterApiProxy} from './test_read_later_api_proxy.js';
suite('ReadLaterAppTest', () => {
let readLaterApp: ReadLaterAppElement;
let testProxy: TestReadLaterApiProxy;
function assertEntryURLs(items: NodeListOf<HTMLElement>, urls: string[]) {
assertEquals(urls.length, items.length);
items.forEach((item, index) => {
assertEquals(urls[index], item.dataset['url']);
});
}
function queryItems() {
return readLaterApp.shadowRoot!.querySelectorAll('read-later-item');
}
function clickItem(url: string) {
readLaterApp.shadowRoot!.querySelector<HTMLElement>(
`[data-url="${url}"]`)!.click();
}
function getSampleData(): ReadLaterEntriesByStatus {
const entries = {
unreadEntries: [
{
title: 'Google',
url: {url: 'https://www.google.com'},
displayUrl: 'google.com',
updateTime: 0n,
read: false,
displayTimeSinceUpdate: '2 minutes ago',
},
{
title: 'Apple',
url: {url: 'https://www.apple.com'},
displayUrl: 'apple.com',
updateTime: 0n,
read: false,
displayTimeSinceUpdate: '20 minutes ago',
},
],
readEntries: [
{
title: 'Bing',
url: {url: 'https://www.bing.com'},
displayUrl: 'bing.com',
updateTime: 0n,
read: true,
displayTimeSinceUpdate: '5 minutes ago',
},
{
title: 'Yahoo',
url: {url: 'https://www.yahoo.com'},
displayUrl: 'yahoo.com',
updateTime: 0n,
read: true,
displayTimeSinceUpdate: '7 minutes ago',
},
]
};
return entries;
}
setup(async () => {
testProxy = new TestReadLaterApiProxy();
ReadLaterApiProxyImpl.setInstance(testProxy);
testProxy.setEntries(getSampleData());
document.body.innerHTML = '';
readLaterApp = document.createElement('read-later-app');
document.body.appendChild(readLaterApp);
await flushTasks();
});
test('return all entries', async () => {
const urls = [
'https://www.google.com', 'https://www.apple.com', 'https://www.bing.com',
'https://www.yahoo.com'
];
assertEntryURLs(queryItems(), urls);
});
test('click on item passes correct url', async () => {
const expectedUrl = 'https://www.apple.com';
clickItem(expectedUrl);
const [url, updateReadStatus] = await testProxy.whenCalled('openURL');
assertEquals(url.url, expectedUrl);
assertTrue(updateReadStatus);
});
test('click on item passes event info', async () => {
const item = readLaterApp.shadowRoot!.querySelector(
`[data-url="https://www.apple.com"]`)!;
item.dispatchEvent(new MouseEvent('click'));
const [, , click] = await testProxy.whenCalled('openURL');
assertFalse(
click.middleButton || click.altKey || click.ctrlKey || click.metaKey ||
click.shiftKey);
testProxy.resetResolver('openURL');
// Middle mouse button click.
item.dispatchEvent(new MouseEvent('auxclick', {button: 1}));
const [, , auxClick] = await testProxy.whenCalled('openURL');
assertTrue(auxClick.middleButton);
assertFalse(
auxClick.altKey || auxClick.ctrlKey || auxClick.metaKey ||
auxClick.shiftKey);
testProxy.resetResolver('openURL');
// Modifier keys.
item.dispatchEvent(new MouseEvent('click', {
altKey: true,
ctrlKey: true,
metaKey: true,
shiftKey: true,
}));
const [, , modifiedClick] = await testProxy.whenCalled('openURL');
assertFalse(modifiedClick.middleButton);
assertTrue(
modifiedClick.altKey && modifiedClick.ctrlKey &&
modifiedClick.metaKey && modifiedClick.shiftKey);
});
test('Click on item mark as read button triggers actions', async () => {
const expectedUrl = 'https://www.apple.com';
const readLaterItem =
readLaterApp.shadowRoot!.querySelector<ReadLaterItemElement>(
`[data-url="${expectedUrl}"]`)!;
const readLaterItemUpdateStatusButton = readLaterItem.$.updateStatusButton;
readLaterItemUpdateStatusButton.click();
const [url, read] = await testProxy.whenCalled('updateReadStatus');
assertEquals(expectedUrl, url.url);
assertTrue(read);
});
test('Click on item mark as unread button triggers actions', async () => {
const expectedUrl = 'https://www.bing.com';
const readLaterItem =
readLaterApp.shadowRoot!.querySelector<ReadLaterItemElement>(
`[data-url="${expectedUrl}"]`)!;
const readLaterItemUpdateStatusButton = readLaterItem.$.updateStatusButton;
readLaterItemUpdateStatusButton.click();
const [url, read] = await testProxy.whenCalled('updateReadStatus');
assertEquals(expectedUrl, url.url);
assertFalse(read);
});
test('Click on item delete button triggers actions', async () => {
const expectedUrl = 'https://www.apple.com';
const readLaterItem =
readLaterApp.shadowRoot!.querySelector<ReadLaterItemElement>(
`[data-url="${expectedUrl}"]`)!;
const readLaterItemDeleteButton = readLaterItem.$.deleteButton;
readLaterItemDeleteButton.click();
const url = await testProxy.whenCalled('removeEntry');
assertEquals(expectedUrl, url.url);
});
test('Click on menu button triggers actions', async () => {
const readLaterCloseButton =
readLaterApp.shadowRoot!.querySelector<HTMLElement>('#closeButton')!;
readLaterCloseButton.click();
await testProxy.whenCalled('closeUI');
});
test('Enter key triggers action and passes correct url', async () => {
const expectedUrl = 'https://www.apple.com';
const readLaterItem =
readLaterApp.shadowRoot!.querySelector<ReadLaterItemElement>(
`[data-url="${expectedUrl}"]`)!;
keyDownOn(readLaterItem, 0, [], 'Enter');
const [url, updateReadStatus] = await testProxy.whenCalled('openURL');
assertEquals(url.url, expectedUrl);
assertTrue(updateReadStatus);
});
test('Space key triggers action and passes correct url', async () => {
const expectedUrl = 'https://www.apple.com';
const readLaterItem =
readLaterApp.shadowRoot!.querySelector<ReadLaterItemElement>(
`[data-url="${expectedUrl}"]`)!;
keyDownOn(readLaterItem, 0, [], ' ');
const [url, updateReadStatus] = await testProxy.whenCalled('openURL');
assertEquals(url.url, expectedUrl);
assertTrue(updateReadStatus);
});
test('Keyboard navigation abides by item list range boundaries', async () => {
const urls = [
'https://www.google.com', 'https://www.apple.com', 'https://www.bing.com',
'https://www.yahoo.com'
];
const selector = readLaterApp.shadowRoot!.querySelector('iron-selector')!;
// Select first item.
selector.selected =
readLaterApp.shadowRoot!.querySelector(
'read-later-item')!.dataset['url']!;
keyDownOn(selector, 0, [], 'ArrowUp');
assertEquals(urls[3], selector.selected);
keyDownOn(selector, 0, [], 'ArrowDown');
assertEquals(urls[0], selector.selected);
keyDownOn(selector, 0, [], 'ArrowDown');
assertEquals(urls[1], selector.selected);
keyDownOn(selector, 0, [], 'ArrowUp');
assertEquals(urls[0], selector.selected);
});
test(
'Keyboard navigation left/right cycles through list item elements',
async () => {
const firstItem =
readLaterApp.shadowRoot!.querySelector('read-later-item')!;
// Focus first item.
firstItem.focus();
keyDownOn(firstItem, 0, [], 'ArrowRight');
assertEquals(
firstItem.$.updateStatusButton,
firstItem.shadowRoot!.activeElement);
keyDownOn(firstItem, 0, [], 'ArrowRight');
assertEquals(
firstItem.$.deleteButton, firstItem.shadowRoot!.activeElement);
keyDownOn(firstItem, 0, [], 'ArrowRight');
assertEquals(firstItem, readLaterApp.shadowRoot!.activeElement);
keyDownOn(firstItem, 0, [], 'ArrowLeft');
assertEquals(
firstItem.$.deleteButton, firstItem.shadowRoot!.activeElement);
keyDownOn(firstItem, 0, [], 'ArrowLeft');
assertEquals(
firstItem.$.updateStatusButton,
firstItem.shadowRoot!.activeElement);
keyDownOn(firstItem, 0, [], 'ArrowLeft');
assertEquals(firstItem, readLaterApp.shadowRoot!.activeElement);
});
test('Favicons present in the dom', async () => {
const readLaterItems =
readLaterApp.shadowRoot!.querySelectorAll('read-later-item');
readLaterItems.forEach((readLaterItem) => {
assertTrue(!!readLaterItem.shadowRoot!.querySelector('.favicon'));
});
});
test('Verify visibilitychange triggers data fetch', async () => {
assertEquals(1, testProxy.getCallCount('getReadLaterEntries'));
// When hidden visibilitychange should not trigger the data callback.
Object.defineProperty(
document, 'visibilityState', {value: 'hidden', writable: true});
document.dispatchEvent(new Event('visibilitychange'));
await flushTasks();
assertEquals(1, testProxy.getCallCount('getReadLaterEntries'));
// When visible visibilitychange should trigger the data callback.
Object.defineProperty(
document, 'visibilityState', {value: 'visible', writable: true});
document.dispatchEvent(new Event('visibilitychange'));
await flushTasks();
assertEquals(2, testProxy.getCallCount('getReadLaterEntries'));
});
}); | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/locationsMappers";
import * as Parameters from "../models/parameters";
import { HDInsightManagementClientContext } from "../hDInsightManagementClientContext";
/** Class representing a Locations. */
export class Locations {
private readonly client: HDInsightManagementClientContext;
/**
* Create a Locations.
* @param {HDInsightManagementClientContext} client Reference to the service client.
*/
constructor(client: HDInsightManagementClientContext) {
this.client = client;
}
/**
* Gets the capabilities for the specified location.
* @param location The Azure location (region) for which to make the request.
* @param [options] The optional parameters
* @returns Promise<Models.LocationsGetCapabilitiesResponse>
*/
getCapabilities(
location: string,
options?: msRest.RequestOptionsBase
): Promise<Models.LocationsGetCapabilitiesResponse>;
/**
* @param location The Azure location (region) for which to make the request.
* @param callback The callback
*/
getCapabilities(
location: string,
callback: msRest.ServiceCallback<Models.CapabilitiesResult>
): void;
/**
* @param location The Azure location (region) for which to make the request.
* @param options The optional parameters
* @param callback The callback
*/
getCapabilities(
location: string,
options: msRest.RequestOptionsBase,
callback: msRest.ServiceCallback<Models.CapabilitiesResult>
): void;
getCapabilities(
location: string,
options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.CapabilitiesResult>,
callback?: msRest.ServiceCallback<Models.CapabilitiesResult>
): Promise<Models.LocationsGetCapabilitiesResponse> {
return this.client.sendOperationRequest(
{
location,
options
},
getCapabilitiesOperationSpec,
callback
) as Promise<Models.LocationsGetCapabilitiesResponse>;
}
/**
* Lists the usages for the specified location.
* @param location The Azure location (region) for which to make the request.
* @param [options] The optional parameters
* @returns Promise<Models.LocationsListUsagesResponse>
*/
listUsages(
location: string,
options?: msRest.RequestOptionsBase
): Promise<Models.LocationsListUsagesResponse>;
/**
* @param location The Azure location (region) for which to make the request.
* @param callback The callback
*/
listUsages(location: string, callback: msRest.ServiceCallback<Models.UsagesListResult>): void;
/**
* @param location The Azure location (region) for which to make the request.
* @param options The optional parameters
* @param callback The callback
*/
listUsages(
location: string,
options: msRest.RequestOptionsBase,
callback: msRest.ServiceCallback<Models.UsagesListResult>
): void;
listUsages(
location: string,
options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.UsagesListResult>,
callback?: msRest.ServiceCallback<Models.UsagesListResult>
): Promise<Models.LocationsListUsagesResponse> {
return this.client.sendOperationRequest(
{
location,
options
},
listUsagesOperationSpec,
callback
) as Promise<Models.LocationsListUsagesResponse>;
}
/**
* Lists the billingSpecs for the specified subscription and location.
* @param location The Azure location (region) for which to make the request.
* @param [options] The optional parameters
* @returns Promise<Models.LocationsListBillingSpecsResponse>
*/
listBillingSpecs(
location: string,
options?: msRest.RequestOptionsBase
): Promise<Models.LocationsListBillingSpecsResponse>;
/**
* @param location The Azure location (region) for which to make the request.
* @param callback The callback
*/
listBillingSpecs(
location: string,
callback: msRest.ServiceCallback<Models.BillingResponseListResult>
): void;
/**
* @param location The Azure location (region) for which to make the request.
* @param options The optional parameters
* @param callback The callback
*/
listBillingSpecs(
location: string,
options: msRest.RequestOptionsBase,
callback: msRest.ServiceCallback<Models.BillingResponseListResult>
): void;
listBillingSpecs(
location: string,
options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BillingResponseListResult>,
callback?: msRest.ServiceCallback<Models.BillingResponseListResult>
): Promise<Models.LocationsListBillingSpecsResponse> {
return this.client.sendOperationRequest(
{
location,
options
},
listBillingSpecsOperationSpec,
callback
) as Promise<Models.LocationsListBillingSpecsResponse>;
}
/**
* Get the async operation status.
* @param location The Azure location (region) for which to make the request.
* @param operationId The long running operation id.
* @param [options] The optional parameters
* @returns Promise<Models.LocationsGetAzureAsyncOperationStatusResponse>
*/
getAzureAsyncOperationStatus(
location: string,
operationId: string,
options?: msRest.RequestOptionsBase
): Promise<Models.LocationsGetAzureAsyncOperationStatusResponse>;
/**
* @param location The Azure location (region) for which to make the request.
* @param operationId The long running operation id.
* @param callback The callback
*/
getAzureAsyncOperationStatus(
location: string,
operationId: string,
callback: msRest.ServiceCallback<Models.AsyncOperationResult>
): void;
/**
* @param location The Azure location (region) for which to make the request.
* @param operationId The long running operation id.
* @param options The optional parameters
* @param callback The callback
*/
getAzureAsyncOperationStatus(
location: string,
operationId: string,
options: msRest.RequestOptionsBase,
callback: msRest.ServiceCallback<Models.AsyncOperationResult>
): void;
getAzureAsyncOperationStatus(
location: string,
operationId: string,
options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.AsyncOperationResult>,
callback?: msRest.ServiceCallback<Models.AsyncOperationResult>
): Promise<Models.LocationsGetAzureAsyncOperationStatusResponse> {
return this.client.sendOperationRequest(
{
location,
operationId,
options
},
getAzureAsyncOperationStatusOperationSpec,
callback
) as Promise<Models.LocationsGetAzureAsyncOperationStatusResponse>;
}
/**
* Check the cluster name is available or not.
* @param location The Azure location (region) for which to make the request.
* @param parameters
* @param [options] The optional parameters
* @returns Promise<Models.LocationsCheckNameAvailabilityResponse>
*/
checkNameAvailability(
location: string,
parameters: Models.NameAvailabilityCheckRequestParameters,
options?: msRest.RequestOptionsBase
): Promise<Models.LocationsCheckNameAvailabilityResponse>;
/**
* @param location The Azure location (region) for which to make the request.
* @param parameters
* @param callback The callback
*/
checkNameAvailability(
location: string,
parameters: Models.NameAvailabilityCheckRequestParameters,
callback: msRest.ServiceCallback<Models.NameAvailabilityCheckResult>
): void;
/**
* @param location The Azure location (region) for which to make the request.
* @param parameters
* @param options The optional parameters
* @param callback The callback
*/
checkNameAvailability(
location: string,
parameters: Models.NameAvailabilityCheckRequestParameters,
options: msRest.RequestOptionsBase,
callback: msRest.ServiceCallback<Models.NameAvailabilityCheckResult>
): void;
checkNameAvailability(
location: string,
parameters: Models.NameAvailabilityCheckRequestParameters,
options?:
| msRest.RequestOptionsBase
| msRest.ServiceCallback<Models.NameAvailabilityCheckResult>,
callback?: msRest.ServiceCallback<Models.NameAvailabilityCheckResult>
): Promise<Models.LocationsCheckNameAvailabilityResponse> {
return this.client.sendOperationRequest(
{
location,
parameters,
options
},
checkNameAvailabilityOperationSpec,
callback
) as Promise<Models.LocationsCheckNameAvailabilityResponse>;
}
/**
* Validate the cluster create request spec is valid or not.
* @param location The Azure location (region) for which to make the request.
* @param parameters
* @param [options] The optional parameters
* @returns Promise<Models.LocationsValidateClusterCreateRequestResponse>
*/
validateClusterCreateRequest(
location: string,
parameters: Models.ClusterCreateRequestValidationParameters,
options?: msRest.RequestOptionsBase
): Promise<Models.LocationsValidateClusterCreateRequestResponse>;
/**
* @param location The Azure location (region) for which to make the request.
* @param parameters
* @param callback The callback
*/
validateClusterCreateRequest(
location: string,
parameters: Models.ClusterCreateRequestValidationParameters,
callback: msRest.ServiceCallback<Models.ClusterCreateValidationResult>
): void;
/**
* @param location The Azure location (region) for which to make the request.
* @param parameters
* @param options The optional parameters
* @param callback The callback
*/
validateClusterCreateRequest(
location: string,
parameters: Models.ClusterCreateRequestValidationParameters,
options: msRest.RequestOptionsBase,
callback: msRest.ServiceCallback<Models.ClusterCreateValidationResult>
): void;
validateClusterCreateRequest(
location: string,
parameters: Models.ClusterCreateRequestValidationParameters,
options?:
| msRest.RequestOptionsBase
| msRest.ServiceCallback<Models.ClusterCreateValidationResult>,
callback?: msRest.ServiceCallback<Models.ClusterCreateValidationResult>
): Promise<Models.LocationsValidateClusterCreateRequestResponse> {
return this.client.sendOperationRequest(
{
location,
parameters,
options
},
validateClusterCreateRequestOperationSpec,
callback
) as Promise<Models.LocationsValidateClusterCreateRequestResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const getCapabilitiesOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path:
"subscriptions/{subscriptionId}/providers/Microsoft.HDInsight/locations/{location}/capabilities",
urlParameters: [Parameters.subscriptionId, Parameters.location],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {
bodyMapper: Mappers.CapabilitiesResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listUsagesOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.HDInsight/locations/{location}/usages",
urlParameters: [Parameters.subscriptionId, Parameters.location],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {
bodyMapper: Mappers.UsagesListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const listBillingSpecsOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path:
"subscriptions/{subscriptionId}/providers/Microsoft.HDInsight/locations/{location}/billingSpecs",
urlParameters: [Parameters.subscriptionId, Parameters.location],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {
bodyMapper: Mappers.BillingResponseListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const getAzureAsyncOperationStatusOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path:
"subscriptions/{subscriptionId}/providers/Microsoft.HDInsight/locations/{location}/azureasyncoperations/{operationId}",
urlParameters: [Parameters.subscriptionId, Parameters.location, Parameters.operationId],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
responses: {
200: {
bodyMapper: Mappers.AsyncOperationResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const checkNameAvailabilityOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path:
"subscriptions/{subscriptionId}/providers/Microsoft.HDInsight/locations/{location}/checkNameAvailability",
urlParameters: [Parameters.subscriptionId, Parameters.location],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.NameAvailabilityCheckRequestParameters,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.NameAvailabilityCheckResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
};
const validateClusterCreateRequestOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path:
"subscriptions/{subscriptionId}/providers/Microsoft.HDInsight/locations/{location}/validateCreateRequest",
urlParameters: [Parameters.subscriptionId, Parameters.location],
queryParameters: [Parameters.apiVersion],
headerParameters: [Parameters.acceptLanguage],
requestBody: {
parameterPath: "parameters",
mapper: {
...Mappers.ClusterCreateRequestValidationParameters,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.ClusterCreateValidationResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
serializer
}; | the_stack |
import * as React from "react";
import { WebPartTitle } from "@pnp/spfx-controls-react/lib/WebPartTitle";
import { IOrganizationChartProps } from "./IOrganizationChartProps";
import { escape } from "@microsoft/sp-lodash-subset";
import { Customizer } from "@uifabric/utilities/lib/";
import * as strings from "OrganizationChartWebPartStrings";
import {
IStyle,
mergeStyles,
Persona,
IPersonaSharedProps,
PersonaSize,
PersonaPresence,
DocumentCard,
IPersonaStyles,
mergeStyleSets,
IDocumentCardStyles,
Spinner,
SpinnerSize,
Stack,
IPersonaProps,
Label,
MessageBar,
MessageBarType,
} from "office-ui-fabric-react";
//import { AppContext } from "../../Entities/AppContext";
import { IAppContext } from "../../Entities/IAppContext";
import { IUserInfo } from "../../Entities/IUserInfo";
import { useState } from "react";
import { useGetUserProperties } from "../../hooks/useGetUserProperties";
import { IOrganizationChartState } from "./IOrganizationChartState";
// Persona Styles
const personaStyles: Partial<IPersonaStyles> = {
root: {},
primaryText: {
fontSize: 14,
fontWeight: 500,
},
};
// Maping presence status MSGraph to persona presence status
const presenceStatus: any[] = [];
presenceStatus["Available"] = PersonaPresence.online;
presenceStatus["AvailableIdle"] = PersonaPresence.online;
presenceStatus["Away"] = PersonaPresence.away;
presenceStatus["BeRightBack"] = PersonaPresence.away;
presenceStatus["Busy"] = PersonaPresence.busy;
presenceStatus["BusyIdle"] = PersonaPresence.busy;
presenceStatus["DoNotDisturb"] = PersonaPresence.dnd;
presenceStatus["Offline"] = PersonaPresence.offline;
presenceStatus["PresenceUnknown"] = PersonaPresence.none;
// Functional Component
export const OrganizationChart: React.FunctionComponent<IOrganizationChartProps> = (
props: IOrganizationChartProps
) => {
// Timer Id used by setInterval
let _timerId:number = 0;
// Application Context (React.Context)
const applicationContext: IAppContext = {
currentUser: props.currentUser,
context: props.context,
};
// State
const [state, setState] = useState<IOrganizationChartState>({
isloading: true,
hasError: false,
errorMessage: "",
managerList: [],
userProfile: undefined,
reportsList: [],
});
// Global Compoment Styles
const stylesComponent = mergeStyleSets({
container: {
minWidth: 257,
display: "block",
maxWidth: 300,
maxHeight: 620,
overflow: "auto",
padding: 10,
paddingBottom: 20,
},
managerList: {
display: "block",
marginLeft: 30,
marginRight: 10,
height: "auto",
paddingBottom: 40,
borderLeftStyle: "solid",
borderLeftWidth: 2,
borderLeftColor: props.themeVariant.palette.neutralQuaternary,
borderBottomColor: props.themeVariant.palette.neutralQuaternary,
borderBottomStyle: "solid",
borderBottomWidth: 2,
},
currentUser: {
marginLeft: 75,
height: "auto",
marginRight: 10,
borderLeftStyle: state.reportsList.length > 0 ? "solid" : "none",
borderLeftWidth: state.reportsList.length > 0 ? 2 : 0,
borderLeftColor: props.themeVariant.palette.neutralQuaternary,
borderBottomColor: props.themeVariant.palette.neutralQuaternary,
},
directReportList: {
marginLeft: 85,
height: "auto",
marginRight: 10,
},
directReportInfo: {
width: "70%",
padding: 5,
height: "auto",
backgroundColor: props.themeVariant.palette.neutralLight,
marginLeft: 1,
marginTop: 20,
},
webPartTile: {
paddingLeft: 30,
paddingTop: 20,
},
});
// Document Card Styles
const documentCardManagerStyles: Partial<IDocumentCardStyles> = {
root: {
marginLeft: -25,
marginTop: 15,
padding: 5,
paddingBottom: 5,
borderStyle: "none",
borderWidth: 0,
selectors: {
":hover": {
backgroundColor: props.themeVariant.palette.themeLighter,
},
":hover::after": {
borderWidth: 0,
borderStyle: "none",
},
},
},
};
const documentCardUserStyles: Partial<IDocumentCardStyles> = {
root: {
marginLeft: 0,
marginTop: 15,
padding: 5,
paddingBottom: 5,
borderStyle: "none",
borderWidth: 0,
selectors: {
":hover": {
backgroundColor: props.themeVariant.palette.themeLighter,
},
":hover::after": {
borderWidth: 0,
borderStyle: "none",
},
},
},
};
const documentCardCurrentUserStyles: Partial<IDocumentCardStyles> = {
root: {
marginLeft: -25,
padding: 5,
borderStyle: "none",
borderWidth: 0,
marginTop: state.managerList.length > 0 ? -25 : 15,
selectors: {
":hover": {
backgroundColor: props.themeVariant.palette.themeLighter,
},
":hover::after": {
borderWidth: 0,
borderStyle: "none",
},
},
},
};
const _onRenderCoin = (iconProps: IPersonaProps): JSX.Element => {
const { coinSize, imageAlt, imageUrl } = iconProps;
return (
<img
src={imageUrl}
alt={imageAlt}
width={coinSize}
height={coinSize}
style={{
display: "block",
background: "transparent",
border: `2px solid ${props.themeVariant.palette.neutralTertiary}`,
borderRadius: "50%",
}}
/>
);
};
const _userPersonaCard = (userInfo: IUserInfo): JSX.Element => {
return (
<>
<DocumentCard
styles={documentCardUserStyles}
onClickHref={userInfo.userUrl}
key={userInfo.email}
>
<Persona
styles={personaStyles}
imageUrl={userInfo.pictureUrl}
text={userInfo.displayName}
secondaryText={userInfo.title}
size={PersonaSize.size40}
coinSize={40}
onRenderCoin={_onRenderCoin}
presence={presenceStatus[userInfo.presence.availability]}
presenceTitle={userInfo.presence.activity}
/>
</DocumentCard>
</>
);
};
const _managerPersonaCard = (managerInfo: IUserInfo): JSX.Element => {
return (
<>
<DocumentCard
styles={documentCardManagerStyles}
onClickHref={managerInfo.userUrl}
key={managerInfo.email}
>
<Persona
styles={personaStyles}
imageUrl={managerInfo.pictureUrl}
text={managerInfo.displayName}
secondaryText={managerInfo.title}
size={PersonaSize.size40}
coinSize={40}
onRenderCoin={_onRenderCoin}
presence={presenceStatus[managerInfo.presence.availability]}
presenceTitle={managerInfo.presence.activity}
/>
</DocumentCard>
</>
);
};
React.useEffect(() => {
(async () => {
try {
let {
_managersList,
_currentUserProfile,
_reportsList,
getPresenceStatus,
} = await useGetUserProperties(
applicationContext.currentUser.loginName,
applicationContext.context
);
setState({
...state,
isloading: false,
managerList: _managersList,
reportsList: _reportsList,
userProfile: _currentUserProfile,
});
// Pooling status each x min ( value define as property in webpart)
// test if there are an Timer running if exist clear
if (_timerId) {
clearInterval(_timerId);
}
const _interval = props.refreshInterval * 60000;
_timerId = setInterval(async () => {
console.log("cheching new status... ", new Date());
const newPresenceStatus = await getPresenceStatus(
_managersList,
_reportsList,
_currentUserProfile
);
const {
managersList,
currentUserProfile,
reportsList,
} = newPresenceStatus;
setState({
...state,
isloading: false,
managerList: managersList,
reportsList: reportsList,
userProfile: currentUserProfile,
});
}, _interval);
//
} catch (error) {
setState({
...state,
isloading: false,
hasError: true,
errorMessage: `${strings.errorMessage} ${error.message}`,
});
}
})();
}, [props.title, props.refreshInterval]);
// Render component
return (
<>
<div className={stylesComponent.container}>
<WebPartTitle
displayMode={props.displayMode}
title={props.title}
updateProperty={props.updateProperty}
themeVariant={props.themeVariant}
/>
{state.isloading ? (
<Stack horizontal horizontalAlign={"center"}>
<Spinner size={SpinnerSize.small} label={"loading..."} />
</Stack>
) : state.hasError ? (
<MessageBar messageBarType={MessageBarType.error}>
{state.errorMessage}
</MessageBar>
) : (
<ol style={{ listStyle: "none", paddingLeft: 0 }}>
<li style={{ display: "list-item" }}>
{state.managerList.length > 0 ? (
<div className={stylesComponent.managerList} key={1}>
{state.managerList.map((manager, i) => {
return _managerPersonaCard(manager);
})}
</div>
) : null}
</li>
<li style={{ display: "list-item" }}>
{state.userProfile ? (
<div
className={stylesComponent.currentUser}
style={{
marginLeft: state.managerList.length > 0 ? 80 : 40,
}}
>
<DocumentCard
onClickHref={state.userProfile.UserUrl}
styles={documentCardCurrentUserStyles}
>
<Persona
styles={{
...personaStyles,
primaryText: { fontWeight: 700 },
}}
imageUrl={state.userProfile.PictureUrl}
text={state.userProfile.DisplayName}
secondaryText={state.userProfile.Title}
size={PersonaSize.size40}
coinSize={40}
onRenderCoin={_onRenderCoin}
presence={
presenceStatus[state.userProfile.presence.availability]
}
presenceTitle={state.userProfile.presence.activity}
// imageAlt={"Annie Linguist, status is away"}
/>
</DocumentCard>
{state.reportsList.length > 0 ? (
<div className={stylesComponent.directReportInfo}>
<Label style={{ fontWeight: 500, fontSize: 12 }}>
Direct Reports ({state.reportsList.length})
</Label>
</div>
) : null}
</div>
) : null}
<div
className={stylesComponent.directReportList}
style={{
marginLeft: state.managerList.length > 0 ? 80 : 40,
}}
>
{state.reportsList.length > 0
? state.reportsList.map((user, i) => {
return _userPersonaCard(user);
})
: null}
</div>
</li>
</ol>
)}
</div>
</>
);
}; | the_stack |
import React from 'react';
import { css, Global } from '@emotion/react';
import {
neutral,
brandBackground,
brandBorder,
from,
until,
} from '@guardian/source-foundations';
import { ArticleFormat, ArticleSpecial, ArticleDesign } from '@guardian/libs';
import { Footer } from '@root/src/web/components/Footer';
import { SubNav } from '@root/src/web/components/SubNav.importable';
import { ElementContainer } from '@root/src/web/components/ElementContainer';
import {
MobileStickyContainer,
AdSlot,
labelStyles as adLabelStyles,
adCollapseStyles,
} from '@root/src/web/components/AdSlot';
import { BannerWrapper } from '@root/src/web/layouts/lib/stickiness';
import { Lines } from '@guardian/source-react-components-development-kitchen';
import { interactiveGlobalStyles } from './lib/interactiveLegacyStyling';
import { ImmersiveHeader } from './headers/ImmersiveHeader';
import { renderElement } from '../lib/renderElement';
import { GridItem } from '../components/GridItem';
import { Hide } from '../components/Hide';
import { Border } from '../components/Border';
import { ArticleTitle } from '../components/ArticleTitle';
import { ArticleHeadline } from '../components/ArticleHeadline';
import { ArticleMeta } from '../components/ArticleMeta';
import { GuardianLabsLines } from '../components/GuardianLabsLines';
import { HeadlineByline } from '../components/HeadlineByline';
import { decideLineEffect, decideLineCount } from '../lib/layoutHelpers';
import { Standfirst } from '../components/Standfirst';
import { Caption } from '../components/Caption';
import { Island } from '../components/Island';
const InteractiveImmersiveGrid = ({
children,
}: {
children: React.ReactNode;
}) => (
<div
css={css`
/* IE Fallback */
display: flex;
flex-direction: column;
${until.leftCol} {
margin-left: 0px;
}
${from.leftCol} {
margin-left: 151px;
}
${from.wide} {
margin-left: 230px;
}
@supports (display: grid) {
display: grid;
width: 100%;
margin-left: 0;
/*
Explanation of each unit of grid-template-columns
Left Column (220 - 1px border)
Vertical grey border
Main content
Right Column
*/
${from.wide} {
grid-column-gap: 10px;
grid-template-columns: 219px 1px 1fr 300px;
grid-template-areas:
'caption border title right-column'
'. border headline right-column'
'. border standfirst right-column'
'. border byline right-column'
'. border lines right-column'
'. border meta right-column'
'. border body right-column'
'. border . right-column';
}
/*
Explanation of each unit of grid-template-columns
Left Column (220 - 1px border)
Vertical grey border
Main content
Right Column
*/
${until.wide} {
grid-column-gap: 10px;
grid-template-columns: 140px 1px 1fr 300px;
grid-template-areas:
'. border title right-column'
'. border headline right-column'
'. border standfirst right-column'
'. border byline right-column'
'. border lines right-column'
'. border meta right-column'
'. border body right-column'
'. border . right-column';
}
/*
Explanation of each unit of grid-template-columns
Main content
Right Column
*/
${until.leftCol} {
grid-template-columns: 1fr 300px;
grid-column-gap: 20px;
grid-template-areas:
'title right-column'
'headline right-column'
'standfirst right-column'
'byline right-column'
'caption right-column'
'lines right-column'
'meta right-column'
'body right-column';
}
${until.desktop} {
grid-column-gap: 0px;
grid-template-columns: 1fr; /* Main content */
grid-template-areas:
'title'
'headline'
'standfirst'
'byline'
'caption'
'lines'
'meta'
'body';
}
}
`}
>
{children}
</div>
);
const Renderer: React.FC<{
format: ArticleFormat;
palette: Palette;
elements: CAPIElement[];
host?: string;
pageId: string;
webTitle: string;
}> = ({ format, palette, elements, host, pageId, webTitle }) => {
// const cleanedElements = elements.map(element =>
// 'html' in element ? { ...element, html: clean(element.html) } : element,
// );
// ^^ Until we decide where to do the "isomorphism split" in this this code is not safe here.
// But should be soon.
const output = elements.map((element, index) => {
const [ok, el] = renderElement({
format,
palette,
element,
adTargeting: undefined,
host,
index,
isMainMedia: false,
pageId,
webTitle,
});
if (ok) {
switch (element._type) {
// Here we think it makes sense not to wrap every `p` inside a `figure`
case 'model.dotcomrendering.pageElements.InteractiveBlockElement':
case 'model.dotcomrendering.pageElements.TextBlockElement':
return el;
default:
return (
<figure
id={
'elementId' in element
? element.elementId
: undefined
}
key={index}
>
{el}
</figure>
);
}
}
return null;
});
const adStyles = css`
${adLabelStyles}
${adCollapseStyles}
${from.tablet} {
.mobile-only .ad-slot {
display: none;
}
}
${until.tablet} {
.hide-until-tablet .ad-slot {
display: none;
}
}
`;
return <div css={adStyles}>{output}</div>;
};
const decideCaption = (mainMedia: ImageBlockElement): string => {
const caption = [];
if (mainMedia && mainMedia.data && mainMedia.data.caption)
caption.push(mainMedia.data.caption);
if (
mainMedia &&
mainMedia.displayCredit &&
mainMedia.data &&
mainMedia.data.credit
)
caption.push(mainMedia.data.credit);
return caption.join(' ');
};
const maxWidth = css`
${from.desktop} {
max-width: 620px;
}
`;
const stretchLines = css`
${until.phablet} {
margin-left: -20px;
margin-right: -20px;
}
${until.mobileLandscape} {
margin-left: -10px;
margin-right: -10px;
}
`;
interface Props {
CAPI: CAPIType;
NAV: NavType;
format: ArticleFormat;
palette: Palette;
}
export const InteractiveImmersiveLayout = ({
CAPI,
NAV,
format,
palette,
}: Props) => {
const {
config: { host },
} = CAPI;
const mainMedia = CAPI.mainMediaElements[0] as ImageBlockElement;
const captionText = decideCaption(mainMedia);
const { branding } = CAPI.commercialProperties[CAPI.editionId];
return (
<>
{CAPI.isLegacyInteractive && (
<Global styles={interactiveGlobalStyles} />
)}
{CAPI.config.switches.surveys && (
<AdSlot position="survey" display={format.display} />
)}
<ImmersiveHeader
CAPI={CAPI}
NAV={NAV}
format={format}
palette={palette}
/>
<main>
<ElementContainer
showTopBorder={false}
showSideBorders={false}
backgroundColour={palette.background.article}
element="article"
>
<InteractiveImmersiveGrid>
{/* Above leftCol, the Caption is controled by ContainerLayout ^^ */}
<GridItem area="caption">
<Hide when="above" breakpoint="leftCol">
<Caption
palette={palette}
captionText={captionText}
format={format}
shouldLimitWidth={false}
/>
</Hide>
</GridItem>
<GridItem area="border">
{format.design === ArticleDesign.PhotoEssay ? (
<></>
) : (
<Border palette={palette} />
)}
</GridItem>
<GridItem area="title" element="aside">
<>
{!mainMedia && (
<div
css={css`
margin-top: -8px;
margin-left: -4px;
margin-bottom: 12px;
${until.tablet} {
margin-left: -20px;
}
`}
>
<ArticleTitle
format={format}
palette={palette}
tags={CAPI.tags}
sectionLabel={CAPI.sectionLabel}
sectionUrl={CAPI.sectionUrl}
guardianBaseURL={
CAPI.guardianBaseURL
}
badge={CAPI.badge}
/>
</div>
)}
</>
</GridItem>
<GridItem area="headline">
<>
{!mainMedia && (
<div css={maxWidth}>
<ArticleHeadline
format={format}
headlineString={CAPI.headline}
palette={palette}
tags={CAPI.tags}
byline={CAPI.author.byline}
/>
</div>
)}
</>
</GridItem>
<GridItem area="standfirst">
<Standfirst
format={format}
standfirst={CAPI.standfirst}
/>
</GridItem>
<GridItem area="byline">
<HeadlineByline
format={format}
tags={CAPI.tags}
byline={
CAPI.author.byline ? CAPI.author.byline : ''
}
/>
</GridItem>
<GridItem area="lines">
{format.design === ArticleDesign.PhotoEssay &&
format.theme !== ArticleSpecial.Labs ? (
<></>
) : (
<div css={maxWidth}>
<div css={stretchLines}>
{format.theme ===
ArticleSpecial.Labs ? (
<GuardianLabsLines />
) : (
<Lines
effect={decideLineEffect(
ArticleDesign.Standard,
format.theme,
)}
count={decideLineCount(
ArticleDesign.Standard,
)}
/>
)}
</div>
</div>
)}
</GridItem>
<GridItem area="meta" element="aside">
<div css={maxWidth}>
<ArticleMeta
branding={branding}
format={format}
palette={palette}
pageId={CAPI.pageId}
webTitle={CAPI.webTitle}
author={CAPI.author}
tags={CAPI.tags}
primaryDateline={
CAPI.webPublicationDateDisplay
}
secondaryDateline={
CAPI.webPublicationSecondaryDateDisplay
}
/>
</div>
</GridItem>
</InteractiveImmersiveGrid>
</ElementContainer>
<ElementContainer
showTopBorder={false}
showSideBorders={false}
shouldCenter={false}
padded={false}
backgroundColour={palette.background.article}
element="main"
>
<article>
<Renderer
format={format}
palette={palette}
elements={
CAPI.blocks[0] ? CAPI.blocks[0].elements : []
}
host={host}
pageId={CAPI.pageId}
webTitle={CAPI.webTitle}
/>
</article>
</ElementContainer>
</main>
{NAV.subNavSections && (
<ElementContainer
padded={false}
backgroundColour={neutral[100]}
element="aside"
>
<Island deferUntil="visible">
<SubNav
subNavSections={NAV.subNavSections}
currentNavLink={NAV.currentNavLink}
format={format}
/>
</Island>
</ElementContainer>
)}
<ElementContainer
padded={false}
backgroundColour={brandBackground.primary}
borderColour={brandBorder.primary}
showSideBorders={false}
element="footer"
>
<Footer
pageFooter={CAPI.pageFooter}
pillar={format.theme}
pillars={NAV.pillars}
/>
</ElementContainer>
<BannerWrapper />
<MobileStickyContainer />
</>
);
}; | the_stack |
import _ = require('underscore');
import Q = require('q');
import Utils = require('./Utils');
//var ObserveJs = require('observe-js');
var HashMap = require('hashmap').HashMap;
/**
* It represents API for business rules definition of the product, the contract, the form etc.
* It is not tight to HTML DOM or any other UI framework.
* It is **UI agnostic** and that is why it can be used as **an independent representation of business rules** of a product, contract, etc.
* The module itself contains the essential components for an validation engine to function.
*/
module Validation {
/**
* Custom message functions.
*/
export interface IErrorCustomMessage { (config:any, args:any):string;
}
/**
* It represents a property validator for atomic object.
*/
export interface IPropertyValidator {
isAcceptable(s:any): boolean;
customMessage?: IErrorCustomMessage;
tagName?:string;
}
/**
* It represents a property validator for simple string value.
*/
export interface IStringValidator extends IPropertyValidator {
isAcceptable(s:string): boolean;
}
/**
* It represents an async property validator for atomic object.
*/
export interface IAsyncPropertyValidator {
isAcceptable(s:any): Q.Promise<boolean>;
customMessage?: IErrorCustomMessage;
isAsync:boolean;
tagName?:string;
}
/**
* It represents an async property validator for simple string value.
*/
export interface IAsyncStringPropertyValidator extends IAsyncPropertyValidator {
isAcceptable(s:string): Q.Promise<boolean>;
}
/**
* It defines compare operators.
*/
export enum CompareOperator {
/**
* must be less than
*/
LessThan,
/**
* cannot be more than
*/
LessThanEqual,
/**
* must be the same as
*/
Equal,
/**
* must be different from
*/
NotEqual,
/**
* cannot be less than
*/
GreaterThanEqual,
/**
* must be more than
*/
GreaterThan
}
/**
* basic error structure
*/
export interface IError {
HasError: boolean;
ErrorMessage: string;
TranslateArgs?:IErrorTranslateArgs;
}
/**
* support for localization of error messages
*/
export interface IErrorTranslateArgs
{
TranslateId:string;
MessageArgs:any;
CustomMessage?:IErrorCustomMessage;
}
/**
* It defines conditional function.
*/
export interface IOptional { (): boolean; }
/**
* It represents the validation result.
*/
export interface IValidationFailure extends IError{
//Validator:IPropertyValidator
IsAsync:boolean;
Error:IError;
}
/**
* This class provides unit of information about error.
* Implements composite design pattern to enable nesting of error information.
*/
export interface IValidationResult extends Utils.IComponent {
/**
* The name of error collection.
*/
Name: string;
/**
* Add error information to child collection of errors.
* @param validationResult - error information to be added.
*/
Add(validationResult:IValidationResult): void;
/**
* Remove error information from child collection of errors.
* @param index - index of error information to be removed.
*/
Remove(index:number): void;
/**
* Return collections of child errors information.
*/
Children: Array<IValidationResult>;
/**
* Return true if there is any error.
*/
HasErrors: boolean;
/**
* Return true if there is any error and hasw dirty state.
*/
HasErrorsDirty: boolean;
/**
* Return error message, if there is no error, return empty string.
*/
ErrorMessage: string;
/**
* Return number of errors.
*/
ErrorCount: number;
/**
* It enables to have errors optional.
*/
Optional?: IOptional;
/**
* Occurs when the validation errors have changed for a property or for the entire entity.
*/
ErrorsChanged:Utils.ISignal<any>;
/**
* It enables support for localization of error messages.
*/
TranslateArgs?:Array<IErrorTranslateArgs>
}
/**
* It defines validation function.
*/
export interface IValidate { (args: IError): void; }
/**
* It defines async validation function.
*/
export interface IAsyncValidate { (args: IError): Q.Promise<any>; }
/**
* It represents named validation function. It used to define shared validation rules.
*/
export interface IValidatorFce {
/**
* Return name for shared validation rule.
*/
Name:string;
/**
* It defines validation function
*/
ValidationFce?: IValidate;
/**
* It defines async validation function.
*/
AsyncValidationFce?:IAsyncValidate;
}
/**
* This class represents custom validator. It used to create shared validation rules.
*/
export interface IValidator {
/**
* It executes sync validation rules using a validation context and returns a collection of Validation Failures.
*/
Validate(context:any): IValidationFailure;
/**
* It executes sync and async validation rules using a validation context and returns a collection of Validation Failures asynchronoulsy.
*/
ValidateAsync(context:any):Q.Promise<IValidationFailure>;
/**
* Return validation failures.
*/
Error: IError;
}
/**
* It represents abstract validator for type of <T>.
*/
export interface IAbstractValidator<T>{
/**
* Register property validator for property.
* @param prop name
* @param validator - property validator
*/
RuleFor(prop:string,validator:IPropertyValidator);
/**
* Register shared validation and assign property name as dependency on shared rule.
* Dependency = when the property is validated then the shared rule is validated also.
* @param prop name
* @param validatorFce name validation function
*/
ValidationFor(prop:string,validatorFce:IValidatorFce);
/**
* Register shared validation. There are no relationship to dependent property.
* Dependency = when the property is validated then the shared rule is validated also.
* @param validatorFce name validation function
*/
Validation(validatorFce:IValidatorFce);
/**
* Register child validator for property - composition of validators
* @param prop name
* @param validator child validator
* @param forList true if is array structure, otherwise false
*/
ValidatorFor<K>(prop:string,validator:IAbstractValidator<K>,forList?:boolean);
//Validators:{ [name: string]: Array<IPropertyValidator> ; };
/**
* It creates new concrete validation rule and assigned data context to this rule.
* @param name of the rule
* @constructor
*/
CreateRule(name:string):IAbstractValidationRule<any>;
CreateAbstractRule(name:string):IAbstractValidationRule<any>;
CreateAbstractListRule(name:string):IAbstractValidationRule<any>;
/**
* return true if this validation rule is intended for list of items, otherwise true
*/
ForList:boolean;
}
/**
* It represents concrete validation rule for type of <T>.
*/
export interface IAbstractValidationRule<T> extends Utils.IComponent {
/**
* It executes sync validation rules using a validation context and returns a collection of Validation Failures.
*/
Validate(context:T):IValidationResult
/**
* It executes async validation rules using a validation context and returns a collection of Validation Failures asynchronoulsy.
*/
ValidateAsync(context:T):Q.Promise<IValidationResult>
/**
* It executes sync and async validation rules using a validation context and returns a collection of Validation Failures asynchronoulsy.
*/
ValidateAll(context:T):Q.Promise<IValidationResult>;
/**
* It executes sync and async validation rules for the passed property using a validation context.
*/
ValidateProperty(context:T, propName:string):void;
/**
* Return validation results.
*/
ValidationResult: IValidationResult
/**
* Return property validation rules.
*/
Rules:{ [name: string]: IPropertyValidationRule<T> ; }
/**
* Return shared validation rules.
*/
Validators: { [name: string]: IValidator ; }
/**
* Return child validators.
*/
Children:{ [name: string]: IAbstractValidationRule<any> ; }
/**
* Return true if this validation rule is intended for list of items, otherwise true.
*/
ForList:boolean;
}
/**
* It represents concrete validation rule for list of type of <T>.
*/
export interface IAbstractListValidationRule<T> {
/**
* Return map of rows of validation rules for collection-based structures (arrays).
*/
RowsMap:HashMap<T,IAbstractValidationRule<T>>;
/**
* Return rows of validation rules for collection-based structures (arrays).
*
*/
Rows:Array<IAbstractValidationRule<T>>
/**
* Refresh (add or removes row from collection of validation rules based on passed data context).
* @param list collection-based structure data
*/
RefreshRows(context:Array<T>)
}
/**
* It represents property validation rule for type of <T>.
*/
export interface IPropertyValidationRule<T> extends IValidationResult {
/**
*The validators that are grouped under this rule.
*/
Validators:{[name:string]:any};
/**
* Performs validation using a validation context and returns a collection of Validation Failures.
*/
Validate(context:IValidationContext<T>):Array<IValidationFailure>;
/**
* Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy.
*/
ValidateAsync(context:IValidationContext<T>):Q.Promise<Array<IValidationFailure>>;
}
/**
* It represents a data context for validation rule.
*/
export interface IValidationContext<T> {
/**
* Return current value.
*/
Value:string;
/**
* Return property name for current data context.
*/
Key:string;
/**
* Data context for validation rule.
*/
Data:T
}
/**
* It enables to create your own visitors for definition of various validation results.
*/
export interface IValidationResultVisitor{
/**
* It creates (visits) validation result for validation rule for property.
* @param IPropertyValidationRule - property validation rule.
*/
AddRule(IPropertyValidationRule);
/**
* It creates (visits) validation result for child validation rule.
* @param IAbstractValidationRule - child validation rule
*/
AddValidator(IAbstractValidationRule);
/**
* It creates (visits) validation result for shared validation rule.
* @param IValidator - shared validation rule
*/
AddValidation(IValidator);
ValidationResult:IValidationResult;
}
/**
*
* @ngdoc object
* @name Error
* @module Validation
*
*
* @description
* It represents basic error structure.
*/
export class Error implements IError{
public HasError: boolean = false;
public ErrorMessage: string = "";
constructor() {
}
}
/**
*
* @ngdoc object
* @name ValidationFailure
* @module Validation
*
*
* @description
* It represents validation failure.
*/
export class ValidationFailure implements IError
{
constructor(public Error:IError, public IsAsync:boolean) {
}
public get HasError(): boolean {return this.Error.HasError;}
public get ErrorMessage(): string {return this.Error.ErrorMessage;}
public get TranslateArgs():IErrorTranslateArgs {return this.Error.TranslateArgs;}
}
/**
*
* @ngdoc object
* @name ValidationResult
* @module Validation
*
*
* @description
* It represents simple abstract error object.
*/
export class ValidationResult implements IValidationResult {
constructor(public Name: string) {}
public IsDirty:boolean;
public get Children(): Array<IValidationResult> {
return [];
}
public Add(error: IValidationResult) {
throw ("Cannot add to ValidationResult to leaf node.");
}
public Remove(index: number) {
throw ("Cannot remove ValidationResult from leaf node.");
}
public ErrorsChanged:Utils.ISignal<any> = new Utils.Signal();
public DispatchErrorsChanged(){
if (this.ErrorsChanged !== undefined) this.ErrorsChanged.dispatch(this);
}
public Optional: IOptional;
public TranslateArgs:Array<IErrorTranslateArgs>;
public get HasErrorsDirty():boolean {
return this.IsDirty && this.HasErrors;
}
public get HasErrors(): boolean {
return false;
}
public get ErrorCount(): number {
return 0;
}
public get ErrorMessage(): string {
return "";
}
add(child:Utils.IComponent):boolean {this.add(child); return true; }
remove(child:Utils.IComponent):boolean {this.remove(child); return true;}
getChildren():Utils.IComponent[] {return this.Children;}
getName():string {return this.Name}
isItem():boolean {return true;}
}
/**
*
* @ngdoc object
* @name CompositeValidationResult
* @module Validation
*
*
* @description
* It represents composite error object.
*/
export class CompositeValidationResult implements IValidationResult {
public Children: Array<IValidationResult> = [];
constructor(public Name: string) {
}
public Optional: IOptional;
public ErrorsChanged:Utils.ISignal<any> = new Utils.Signal();
public AddFirst(error: IValidationResult) {
this.Children.unshift(error);
}
public Add(error: IValidationResult) {
this.Children.push(error);
}
public Remove(index: number) {
this.Children.splice(index, 1);
}
public Clear(){
this.Children.splice(0,this.Children.length);
}
public get HasErrorsDirty():boolean {
if (this.Optional !== undefined && _.isFunction(this.Optional) && this.Optional()) return false;
return _.some(this.Children, function (error) {
return error.HasErrorsDirty;
});
}
get HasErrors(): boolean {
if (this.Optional !== undefined && _.isFunction(this.Optional) && this.Optional()) return false;
return _.some(this.Children, function (error) {
return error.HasErrors;
});
}
public get ErrorCount(): number {
if (!this.HasErrors) return 0;
return _.reduce(this.Children, function (memo, error:IValidationResult) {
return memo + error.ErrorCount;
}, 0);
//return _.filter(this.children, function (error) { return error.HasErrors; }).length;
}
public get ErrorMessage(): string {
if (!this.HasErrors) return "";
return _.reduce(this.Children, function (memo, error:IValidationResult) {
return memo + error.ErrorMessage;
}, "");
}
public get TranslateArgs():Array<IErrorTranslateArgs> {
if (!this.HasErrors) return [];
var newArgs = [];
_.each(this.Children, function (error:IValidationResult) {
newArgs = newArgs.concat(error.TranslateArgs);
});
return newArgs;
}
public LogErrors(headerMessage?:string) {
if (headerMessage === undefined) headerMessage = "Output";
console.log("---------------\n");
console.log("--- " + headerMessage + " ----\n");
console.log("---------------\n");
this.traverse(this, 1);
console.log("\n\n\n");
}
public get Errors():{[name:string]:IValidationResult}{
var map:{[name:string]:IValidationResult} = {};
_.each(this.Children,function (val){
map[val.Name] = val;
});
return map;
}
private get FlattenErros(): Array<IValidationResult> {
var errors = [];
this.flattenErrors(this, errors);
return errors;
}
public SetDirty(){
this.SetDirtyEx(this,true);
}
public SetPristine(){
this.SetDirtyEx(this,false);
}
private SetDirtyEx(node: IValidationResult, dirty:boolean){
if (node.Children.length === 0) {
node["IsDirty"] = dirty;
}
else {
for (var i = 0, len = node.Children.length; i < len; i++) {
//stop if there are no children with errors
this.SetDirtyEx(node.Children[i], dirty);
}
}
}
private flattenErrors(node: IValidationResult, errorCollection: Array<IValidationResult>) {
if (node.Children.length === 0) {
if (node.HasErrors) errorCollection.push(node);
}
else {
for (var i = 0, len = node.Children.length; i < len; i++) {
//stop if there are no children with errors
if (node.Children[i].HasErrors)
this.flattenErrors(node.Children[i], errorCollection);
}
}
}
// recursively traverse a (sub)tree
private traverse(node: IValidationResult, indent: number) {
console.log(Array(indent++).join("--") + node.Name + " (" + node.ErrorMessage + ")" + '\n\r');
for (var i = 0, len = node.Children.length; i < len; i++) {
this.traverse(node.Children[i], indent);
}
}
add(child:Utils.IComponent):boolean {this.add(child); return true; }
remove(child:Utils.IComponent):boolean {this.remove(child); return true;}
getChildren():Utils.IComponent[] {return this.Children;}
getName():string {return this.Name}
isItem():boolean {return false;}
}
/**
* It represents mixed validation rule for composite error object and property validation rule error.
*/
class MixedValidationResult extends CompositeValidationResult implements IValidationResult {
constructor(private Composite:IValidationResult,private PropRule:PropertyValidationRule<any>) {
super(Composite.Name);
}
public get Children() {return this.Composite.Children;}
public get ValidationFailures(){return this.PropRule.ValidationFailures;}
public get HasErrorsDirty():boolean {
if (this.Composite.HasErrorsDirty) return true;
if (this.PropRule !== undefined && this.PropRule.HasErrorsDirty) return true;
return false;
}
get HasErrors(): boolean {
if (this.Composite.HasErrors) return true;
if (this.PropRule !== undefined && this.PropRule.HasErrors) return true;
return false;
}
public get ErrorCount(): number {
if (!this.Composite.HasErrors && this.PropRule !== undefined && !this.PropRule.HasErrors) return 0;
return this.Composite.ErrorCount + (this.PropRule !== undefined ? this.PropRule.ErrorCount:0);
}
public get ErrorMessage(): string {
if (!this.Composite.HasErrors && this.PropRule !== undefined && !this.PropRule.HasErrors) return "";
this.Composite.ErrorMessage + this.PropRule !== undefined ?this.PropRule.ErrorMessage:"";
}
}
/**
*
* @ngdoc object
* @name AbstractValidator
* @module Validation
*
*
* @description
* It enables to create custom validator for your own abstract object (class) and to assign validation rules to its properties.
* You can assigned these rules
*
* + register property validation rules - use _RuleFor_ property
* + register property async validation rules - use _RuleFor_ property
* + register shared validation rules - use _Validation_ or _ValidationFor_ property
* + register custom object validator - use _ValidatorFor_ property - enables composition of child custom validators
*/
export class AbstractValidator<T> implements IAbstractValidator<T> {
public Validators:{ [name: string]: Array<IPropertyValidator> ; } = {};
public AbstractValidators:{ [name: string]: IAbstractValidator<any> ; } = {};
public ValidationFunctions:{[name:string]: Array<IValidatorFce>;} = {};
/**
* Register property validator for property.
* @param prop - property name
* @param validator - property validator
*/
public RuleFor(prop:string, validator:IPropertyValidator) {
if (this.Validators[prop] === undefined) {
this.Validators[prop] = [];
}
this.Validators[prop].push(validator);
}
/**
* Register shared validation and assign property name as dependency on shared rule.
* Dependency = when the property is validated then the shared rule is validated also.
* @param prop name
* @param fce name validation function
*/
public ValidationFor(prop:string,fce:IValidatorFce) {
if (this.ValidationFunctions[prop] === undefined) {
this.ValidationFunctions[prop] = [];
}
this.ValidationFunctions[prop].push(fce);
}
/**
* Register shared validation. There are no relationship to dependent property.
* Dependency = when the property is validated then the shared rule is validated also.
* @param fce name validation function
*/
public Validation(fce:IValidatorFce) {
if (fce.Name === undefined) throw 'argument must have property Name';
this.ValidationFor(fce.Name,fce);
}
/**
* Register child validator for property - composition of validators
* @param prop name
* @param validator child validator
* @param forList true if is array structure, otherwise false
*/
public ValidatorFor<K>(prop:string,validator:IAbstractValidator<K>, forList?:boolean) {
validator.ForList = forList;
this.AbstractValidators[prop] = validator;
}
public CreateAbstractRule(name:string) :IAbstractValidationRule<T> {
return new AbstractValidationRule<T>(name, this);
}
public CreateAbstractListRule(name:string) :IAbstractValidationRule<T>{
return new AbstractListValidationRule<T>(name, this);
}
public CreateRule(name:string): IAbstractValidationRule<T>{
return new AbstractValidationRule<T>(name, this);
}
/**
* Return true if this validation rule is intended for list of items, otherwise true.
*/
public ForList:boolean = false;
}
/**
*
* @ngdoc object
* @name AbstractValidationRule
* @module Validation
*
*
* @description
* It represents concreate validator for custom object. It enables to assign validation rules to custom object properties.
*/
class AbstractValidationRule<T> implements IAbstractValidationRule<T>{
public get ValidationResult():IValidationResult {return this.ValidationResultVisitor.ValidationResult;}
public set ValidationResult(value:IValidationResult) { this.ValidationResultVisitor.ValidationResult = value; }
public Rules:{ [name: string]: IPropertyValidationRule<T> ; } = {};
public Validators: { [name: string]: IValidator ; } = {};
public Children:{ [name: string]: IAbstractValidationRule<any> ; } = {};
public ValidationResultVisitor:IValidationResultVisitor;
public AcceptVisitor(visitor:IValidationResultVisitor){
visitor.AddValidator(this);
}
constructor(public Name:string,public validator:AbstractValidator<T>,public ForList?:boolean){
this.ValidationResultVisitor = new ValidationResultVisitor(new CompositeValidationResult(this.Name));
if (!this.ForList) {
_.each(this.validator.Validators, function (val, key) {
this.createRuleFor(key);
_.each(val, function (validator) {
this.Rules[key].AddValidator(validator);
}, this);
}, this);
_.each(this.validator.ValidationFunctions, function (val:Array<IValidatorFce>) {
_.each(val, function (validation) {
var validator = this.Validators[validation.Name];
if (validator === undefined) {
validator = new Validator(validation.Name, validation.ValidationFce, validation.AsyncValidationFce);
this.Validators[validation.Name] = validator;
validator.AcceptVisitor(this.ValidationResultVisitor);
//this.ValidationResult.Add(validator);
}
}, this)
}, this);
this.addChildren();
}
}
public addChildren(){
_.each(this.validator.AbstractValidators, function(val, key){
var validationRule;
if (val.ForList) {
validationRule = val.CreateAbstractListRule(key);
}
else {
validationRule = val.CreateAbstractRule(key);
}
this.Children[key] = validationRule;
validationRule.AcceptVisitor(this.ValidationResultVisitor);
//this.ValidationResult.Add(validationRule.ValidationResult);
},this);
}
public SetOptional(fce:IOptional){
this.ValidationResult.Optional = fce;
_.each(this.Rules, function(value:IValidationResult, key:string){value.Optional = fce;});
_.each(this.Validators, function(value:any, key:string){value.Optional = fce;});
_.each(this.Children, function(value:any, key:string){value.SetOptional(fce);});
}
private createRuleFor(prop:string){
var propValidationRule = new PropertyValidationRule(prop);
this.Rules[prop] = propValidationRule;
propValidationRule.AcceptVisitor(this.ValidationResultVisitor);
//this.ValidationResult.Add(propValidationRule);
}
/**
* Performs validation using a validation context and returns a collection of Validation Failures.
*/
public Validate(context:T):IValidationResult{
_.each(this.Children,function(val,key){
if (context[key] === undefined) context[key] = val.ForList?[]:{};
val.Validate(context[key]);
},this);
for (var propName in this.Rules){
var rule = this.Rules[propName];
rule.Validate(new ValidationContext(propName,context));
}
_.each (this.validator.ValidationFunctions, function (valFunctions:Array<IValidatorFce>) {
_.each(valFunctions, function (valFce) {
var validator = this.Validators[valFce.Name];
if (validator !== undefined) validator.Validate(context);
},this)
},this);
return this.ValidationResult;
}
/**
* Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy.
*/
public ValidateAsync(context:T):Q.Promise<IValidationResult>{
var deferred = Q.defer<IValidationResult>();
var promises = [];
_.each(this.Children,function(val,key){
promises.push(val.ValidateAsync(context[key]));
},this);
for (var propName in this.Rules){
var rule = this.Rules[propName];
promises.push(rule.ValidateAsync(new ValidationContext(propName,context)));
}
_.each (this.validator.ValidationFunctions, function (valFunctions:Array<IValidatorFce>) {
_.each(valFunctions, function (valFce) {
var validator = this.Validators[valFce.Name];
if (validator !== undefined) promises.push(validator.ValidateAsync(context));
},this)
},this);
var self = this;
Q.all(promises).then(function(result){deferred.resolve(self.ValidationResult);});
return deferred.promise;
}
ValidateAll(context:T):Q.Promise<IValidationResult>{
this.Validate(context);
return this.ValidateAsync(context);
}
ValidateProperty(context:T, propName:string){
var childRule = this.Children[propName];
if (childRule !== undefined) childRule.Validate(context[propName]);
var rule = this.Rules[propName];
if (rule !== undefined) {
var valContext = new ValidationContext(propName, context);
rule.Validate(valContext);
rule.ValidateAsync(valContext);
}
var validationFces = this.validator.ValidationFunctions[propName];
if (validationFces !== undefined) {
_.each(validationFces, function (valFce) {
var validator = this.Validators[valFce.Name];
if (validator !== undefined) validator.Validate(context);
}, this);
}
}
static id:number =0;
public add(child:IAbstractValidationRule<T>):boolean
{
throw "not implemented";
//return false;
}
public remove(child:IAbstractValidationRule<T>):boolean
{
throw "not implemented";
//return false;
}
public getChildren():IAbstractValidationRule<T>[]{
return _.map(this.Children, function (item) {
return item;
});
}
public getName():string{
return this.Name;
}
public isItem():boolean{
return this.getChildren().length === 0;
}
}
/**
* It represents visitor class that enables to separate validation result creation from validation execution.
* You can create your own Visitors for composing ValidationResults on your own.
*/
class ValidationResultVisitor implements IValidationResultVisitor{
constructor(public ValidationResult:IValidationResult){
}
public AddRule(rule:PropertyValidationRule<any>){
//if (this.ValidationResult.ErrorsChanged !== undefined) rule.ErrorsChanged = this.ValidationResult.ErrorsChanged;
this.ValidationResult.Add(rule);
}
public AddValidator(rule:IAbstractValidationRule<any>){
// mixed composite validation result with property validation error
//TODO: find better and more generic way how to solve mixed validation results with the same name
var error:any = _.find(this.ValidationResult.Children, function(item:IValidationResult) {return item.Name === rule.ValidationResult.Name});
if (error !== undefined){
//compose composite validation result with property validation result
this.ValidationResult.Add(new MixedValidationResult(rule.ValidationResult,error));
}
else {
this.ValidationResult.Add(rule.ValidationResult);
}
}
public AddValidation(validator:Validator){
this.ValidationResult.Add(validator);
}
}
/**
*
* @ngdoc object
* @name AbstractListValidationRule
* @module Validation
*
*
* @description
* It represents an validator for custom object. It enables to assign rules to custom object properties.
*/
class AbstractListValidationRule<T> extends AbstractValidationRule<T> implements IAbstractListValidationRule<T>{
public RowsMap = new HashMap<any,IAbstractValidationRule>();
//private RowsObserver;
constructor(public Name:string, public validator:AbstractValidator<T>) {
super(Name, validator, true);
}
/**
* Performs validation using a validation context and returns a collection of Validation Failures.
*/
public Validate(context:any):IValidationResult {
//super.Validate(context);
this.RefreshRows(context);
for (var i = 0; i != context.length; i++) {
var validationRule =this.RowsMap.get(context[i]);
if (validationRule !== undefined) validationRule.Validate(context[i]);
}
//this.ClearValidationResult(context);
return this.ValidationResult;
}
/**
* Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy.
*/
public ValidateAsync(context:any):Q.Promise<IValidationResult>{
var deferred = Q.defer<IValidationResult>();
var promises = [];
this.RefreshRows(context);
for (var i = 0; i != context.length; i++) {
var validationRule = this.RowsMap.get(context[i]);
if (validationRule !== undefined) promises.push(validationRule.ValidateAsync(context[i]));
}
var self = this;
Q.all(promises).then(function(result){
//self.ClearValidationResult(context);
deferred.resolve(self.ValidationResult);});
return deferred.promise;
}
public get Rows():Array<IAbstractValidationRule<any>> {
return this.RowsMap.values();
}
public RefreshRows(list:Array<any>) {
this.refreshList(list);
// var self = this;
// this.RowsObserver = new ObserveJs.ArrayObserver(list, function(splices) {
// // respond to changes to the elements of arr.
// splices.forEach(function(splice) {
// //var newContext = ObserveJs.ArrayObserver.applySplices(splice, context);
// var newList = list.splice.apply(list,[splice.index,splice.removed.length].concat(splice.added));
// self.refreshList(newList);
// });
// });
}
private ClearRows(list:Array<any>){
var keysToRemove = _.difference(this.RowsMap.keys(),list);
_.each(keysToRemove,function(key){
if (this.has(key)) this.remove(key);
},this.RowsMap);
}
private ClearValidationResult(list:Array<any>) {
this.ClearRows(list);
var results =
_.map( this.RowsMap.values(), function(item:IAbstractValidationRule<any>) {return item.ValidationResult;});
for (var i= this.ValidationResult.Children.length -1;i >= 0; i--){
var item = this.ValidationResult.Children[i];
if (item === undefined) continue;
if (results.indexOf(item) === -1){
this.ValidationResult.Remove(i);
}
}
}
private getValidationRule(key:any, name?:string):IAbstractValidationRule<any>
{
if (name === undefined) name = "Row";
var validationRule:IAbstractValidationRule<any>;
if (!this.RowsMap.has(key)) {
validationRule = this.validator.CreateAbstractRule(name);
this.ValidationResult.Add(validationRule.ValidationResult);
this.RowsMap.set(key,validationRule);
}
else{
validationRule = this.RowsMap.get(key)
}
return validationRule;
}
private refreshList(list:Array<any>){
this.ClearValidationResult(list);
_.each(list,function(item){ var rule = this.getValidationRule(item);},this)
}
}
/**
*
* @ngdoc object
* @name ValidationContext
* @module Validation
*
*
* @description
* It represents a data context for validation rule.
*/
class ValidationContext<T> implements IValidationContext<T> {
constructor(public Key:string, public Data: T) {
}
public get Value(): any {
return this.Data[this.Key];
}
}
export class MessageLocalization {
static customMsg = "Please, fix the field.";
static defaultMessages = {
"required": "This field is required.",
"remote": "Please fix the field.",
"email": "Please enter a valid email address.",
"url": "Please enter a valid URL.",
"date": "Please enter a valid date.",
"dateISO": "Please enter a valid date ( ISO ).",
"number": "Please enter a valid number.",
"digits": "Please enter only digits.",
"signedDigits": "Please enter only signed digits.",
"creditcard": "Please enter a valid credit card number.",
"equalTo": "Please enter the same value again.",
"maxlength": "Please enter no more than {MaxLength} characters.",
"minlength": "Please enter at least {MinLength} characters.",
"rangelength": "Please enter a value between {MinLength} and {MaxLength} characters long.",
"range": "Please enter a value between {Min} and {Max}.",
"max": "Please enter a value less than or equal to {Max}.",
"min": "Please enter a value greater than or equal to {Min}.",
"step": "Please enter a value with step {Step}.",
"contains": "Please enter a value from list of values. Attempted value '{AttemptedValue}'.",
"mask": "Please enter a value corresponding with {Mask}.",
minItems:"Please enter at least {Min} items.",
maxItems:"Please enter no more than {Max} items.",
uniqItems:"Please enter unique items.",
enum:"Please enter a value from list of permitted values.",
type:"Please enter a value of type '{Type}'.",
multipleOf:"Please enter a value that is multiple of {Divider}.",
"custom": MessageLocalization.customMsg
};
static ValidationMessages = MessageLocalization.defaultMessages;
static GetValidationMessage(validator:any) {
var msgText = MessageLocalization.ValidationMessages[validator.tagName];
if (msgText === undefined || msgText === "" || !_.isString(msgText)) {
msgText = MessageLocalization.customMsg;
}
return Utils.StringFce.format(msgText, validator);
}
}
/**
*
* @ngdoc object
* @name PropertyValidationRule
* @module Validation
*
*
* @description
* It represents a property validation rule. The property has assigned collection of property validators.
*/
class PropertyValidationRule<T> extends ValidationResult implements IPropertyValidationRule<T> {
public Validators:{[name:string]: any} = {};
public ValidationFailures:{[name:string]: IValidationFailure} = {};
//public AsyncValidationFailures:{[name:string]: IAsyncValidationFailure} = {};
public AcceptVisitor(visitor:IValidationResultVisitor){
visitor.AddRule(this);
}
constructor(public Name:string, validatorsToAdd?:Array<IPropertyValidator>) {
super(Name);
for (var index in validatorsToAdd) {
this.AddValidator(validatorsToAdd[index]);
}
}
public AddValidator(validator:any){
this.Validators[validator.tagName] = validator;
this.ValidationFailures[validator.tagName] = new ValidationFailure(new Error(),!!validator.isAsync);
}
public get Errors():{[name:string]: IValidationFailure} {
return this.ValidationFailures;
}
public get HasErrors():boolean {
if (this.Optional !== undefined && _.isFunction(this.Optional) && this.Optional()) return false;
return _.some(_.values(this.Errors), function (error) {
return error.HasError;
});
}
public get ErrorCount():number {
return this.HasErrors ? 1 : 0;
}
public get ErrorMessage():string {
if (!this.HasErrors) return "";
return _.reduce(_.values(this.Errors), function (memo, error:IError) {
return memo + error.ErrorMessage;
}, "");
}
public get TranslateArgs():Array<IErrorTranslateArgs>{
if (!this.HasErrors) return [];
var newArray = [];
_.each(_.values(this.Errors), function (error:IValidationFailure) {
if (error.HasError) newArray.push(error.Error.TranslateArgs);
});
return newArray;
}
/**
* Performs validation using a validation context and returns a collection of Validation Failures.
*/
Validate(context:IValidationContext<T>):Array<IValidationFailure> {
try {
return this.ValidateEx(context.Value);
} catch (e) {
//if (this.settings.debug && window.console) {
console.log("Exception occurred when checking element " + context.Key + ".", e);
//}
throw e;
}
}
ValidateEx(value:any):Array<IValidationFailure> {
var lastPriority:number = 0;
var shortCircuited:boolean = false;
var original = this.HasErrors;
for (var index in this.ValidationFailures) {
var validation:IValidationFailure = this.ValidationFailures[index];
if (validation.IsAsync) continue;
var validator:IPropertyValidator = this.Validators[index];
try {
var priority = 0;
if (shortCircuited && priority > lastPriority) {
validation.Error.HasError = false;
} else {
var hasError = ((value===undefined || value === null) && validator.tagName!="required")?false: !validator.isAcceptable(value);
validation.Error.HasError = hasError;
validation.Error.TranslateArgs = { TranslateId:validator.tagName, MessageArgs:_.extend(validator,{AttemptedValue: value}), CustomMessage: validator.customMessage};
validation.Error.ErrorMessage = hasError ? MessageLocalization.GetValidationMessage(validation.Error.TranslateArgs.MessageArgs) : "";
shortCircuited = hasError;
lastPriority = priority;
}
} catch (e) {
//if (this.settings.debug && window.console) {
console.log("Exception occurred when checking element'" + validator.tagName + "' method.", e);
//}
throw e;
}
}
if (original !== this.HasErrors) this.DispatchErrorsChanged();
return _.filter(this.ValidationFailures,function(item){return !item.IsAsync;});
}
/**
* Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy.
*/
ValidateAsync(context:IValidationContext<T>):Q.Promise<Array<IValidationFailure>> {
return this.ValidateAsyncEx(context.Value);
}
/**
* Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy.
*/
ValidateAsyncEx(value:string):Q.Promise<Array<IValidationFailure>> {
var deferred = Q.defer<Array<IValidationFailure>>();
var promises = [];
var original = this.HasErrors;
var setResultFce = function (result) {
var hasError = !result;
validation.Error.HasError = hasError;
validation.Error.TranslateArgs = { TranslateId: validator.tagName, MessageArgs: _.extend(validator, {AttemptedValue: value})};
validation.Error.ErrorMessage = hasError ? MessageLocalization.GetValidationMessage(validation.Error.TranslateArgs.MessageArgs) : "";
};
for (var index in this.ValidationFailures) {
var validation:IValidationFailure = this.ValidationFailures[index];
if (!validation.IsAsync) continue;
var validator:IAsyncPropertyValidator = this.Validators[index];
try {
var hasErrorPromise = ((value===undefined || value === null) && validator.tagName!="required")?Q.when(true):validator.isAcceptable(value);
hasErrorPromise.then(setResultFce);
promises.push(hasErrorPromise);
} catch (e) {
//if (this.settings.debug && window.console) {
console.log("Exception occurred when checking element'" + validator.tagName + "' method.", e);
//}
throw e;
}
}
var self = this;
Q.all(promises).then(function(result){
if (original !== self.HasErrors) self.DispatchErrorsChanged();
deferred.resolve(_.filter(self.ValidationFailures,function(item){return item.IsAsync;}))
});
return deferred.promise;
}
}
/**
*
* @ngdoc object
* @name Validator
* @module Validation
*
*
* @description
* It represents a custom validator. It enables to define your own shared validation rules
*/
class Validator extends ValidationResult implements IValidator {
public Error: IError = new Error();
public ValidationFailures:{[name:string]: IValidationFailure} = {};
constructor (public Name:string,private ValidateFce?: IValidate, private AsyncValidationFce?:IAsyncValidate) {
super(Name);
this.ValidationFailures[this.Name] = new ValidationFailure(this.Error,false);
}
public Optional:IOptional;
public Validate(context:any):IValidationFailure {
var original = this.Error.HasError;
if (this.ValidateFce !== undefined) this.ValidateFce.bind(context)(this.Error);
if (original !== this.Error.HasError) this.DispatchErrorsChanged();
return this.ValidationFailures[this.Name];
}
public ValidateAsync(context:any):Q.Promise<IValidationFailure>{
var deferred = Q.defer<IValidationFailure>();
if (this.AsyncValidationFce === undefined) {
deferred.resolve(this.ValidationFailures[this.Name]);
}
else {
var original = this.Error.HasError;
var self = this;
this.AsyncValidationFce.bind(context)(this.Error).then(function () {
if (original !== self.Error.HasError) self.DispatchErrorsChanged();
deferred.resolve(self.ValidationFailures[self.Name]);
});
}
return deferred.promise;
}
public get HasError():boolean{
return this.HasErrors;
}
public get Errors() {
return this.ValidationFailures;
}
public get HasErrors(): boolean {
if (this.Optional !== undefined && _.isFunction(this.Optional) && this.Optional()) return false;
return this.Error.HasError;
}
public get ErrorCount(): number {
return this.HasErrors ? 1 : 0;
}
public get ErrorMessage(): string {
if (!this.HasErrors) return "";
return this.Error.ErrorMessage;
}
public get TranslateArgs():Array<IErrorTranslateArgs> {
if (!this.HasErrors) return [];
var newArray = [];
newArray.push(this.Error.TranslateArgs);
return newArray;
}
public AcceptVisitor(visitor:IValidationResultVisitor){
visitor.AddValidation(this);
}
}
}
export = Validation; | the_stack |
import {CoreGraph} from '../../../../core/graph/CoreGraph';
import {MapUtils} from '../../../../core/MapUtils';
import {ShaderName} from './ShaderName';
import {TypedNode, BaseNodeType} from '../../_Base';
import {NodeContext, NetworkChildNodeType} from '../../../poly/NodeContext';
import {NodeTypeMap} from '../../../containers/utils/ContainerMap';
import {CoreGraphNodeId} from '../../../../core/graph/CoreGraph';
import {ArrayUtils} from '../../../../core/ArrayUtils';
// type NumberByString = Map<string, number>;
type NumberByCoreGraphNodeId = Map<CoreGraphNodeId, number>;
// type BaseNodeTypeByString = Map<string, BaseNodeType>;
// type BooleanByString = Map<string, boolean>;
type BooleanByCoreGraphNodeId = Map<CoreGraphNodeId, boolean>;
type BooleanByStringByShaderName = Map<ShaderName, BooleanByCoreGraphNodeId>;
type StringArrayByString = Map<CoreGraphNodeId, CoreGraphNodeId[]>;
type InputNamesByShaderNameMethod<NC extends NodeContext> = (
root_node: NodeTypeMap[NC],
shader_name: ShaderName
) => string[];
export class TypedNodeTraverser<NC extends NodeContext> {
private _leaves_graph_id: BooleanByStringByShaderName = new Map();
private _graph_ids_by_shader_name: BooleanByStringByShaderName = new Map();
private _outputs_by_graph_id: StringArrayByString = new Map();
private _depth_by_graph_id: NumberByCoreGraphNodeId = new Map();
private _graph_id_by_depth: Map<number, CoreGraphNodeId[]> = new Map();
private _graph: CoreGraph;
private _shader_name!: ShaderName;
// private _subnets_by_id: BaseNodeTypeByString = new Map();
constructor(
private _parent_node: TypedNode<NC, any>,
private _shader_names: ShaderName[],
private _input_names_for_shader_name_method: InputNamesByShaderNameMethod<NC>
) {
this._graph = this._parent_node.scene().graph;
}
private reset() {
this._leaves_graph_id.clear();
this._graph_ids_by_shader_name.clear();
this._outputs_by_graph_id.clear();
this._depth_by_graph_id.clear();
this._graph_id_by_depth.clear();
// this._subnets_by_id.clear();
this._shader_names.forEach((shader_name) => {
this._graph_ids_by_shader_name.set(shader_name, new Map());
});
}
shaderNames() {
return this._shader_names;
}
input_names_for_shader_name(root_node: NodeTypeMap[NC], shader_name: ShaderName) {
return this._input_names_for_shader_name_method(root_node, shader_name);
}
traverse(root_nodes: NodeTypeMap[NC][]) {
this.reset();
for (let shader_name of this.shaderNames()) {
this._leaves_graph_id.set(shader_name, new Map());
}
for (let shader_name of this.shaderNames()) {
this._shader_name = shader_name;
for (let root_node of root_nodes) {
this.find_leaves_from_root_node(root_node);
this.set_nodes_depth();
}
}
// graph_ids.forEach((graph_id) => {
this._depth_by_graph_id.forEach((depth: number, graph_id: CoreGraphNodeId) => {
if (depth != null) {
// this._graph_id_by_depth.set(depth, this._graph_id_by_depth.get(depth) || []);
// this._graph_id_by_depth.get(depth)?.push(graph_id);
MapUtils.pushOnArrayAtEntry(this._graph_id_by_depth, depth, graph_id);
}
});
}
leaves_from_nodes(nodes: NodeTypeMap[NC][]) {
this._shader_name = ShaderName.LEAVES_FROM_NODES_SHADER;
this._graph_ids_by_shader_name.set(this._shader_name, new Map());
this._leaves_graph_id.set(this._shader_name, new Map());
for (let node of nodes) {
this.find_leaves(node);
}
const node_ids: CoreGraphNodeId[] = [];
this._leaves_graph_id.get(this._shader_name)?.forEach((value: boolean, key: CoreGraphNodeId) => {
node_ids.push(key);
});
return this._graph.nodesFromIds(node_ids) as NodeTypeMap[NC][];
}
nodes_for_shader_name(shader_name: ShaderName) {
const depths: number[] = [];
this._graph_id_by_depth.forEach((value: CoreGraphNodeId[], key: number) => {
depths.push(key);
});
depths.sort((a, b) => a - b);
const nodes: NodeTypeMap[NC][] = [];
const node_id_used_state: Map<CoreGraphNodeId, boolean> = new Map();
depths.forEach((depth) => {
const graph_ids_for_depth = this._graph_id_by_depth.get(depth);
if (graph_ids_for_depth) {
graph_ids_for_depth.forEach((graph_id: CoreGraphNodeId) => {
const is_present = this._graph_ids_by_shader_name.get(shader_name)?.get(graph_id);
if (is_present) {
const node = this._graph.nodeFromId(graph_id) as NodeTypeMap[NC];
this.add_nodes_with_children(node, node_id_used_state, nodes, shader_name);
}
});
}
});
return nodes;
}
sorted_nodes() {
const depths: number[] = [];
this._graph_id_by_depth.forEach((ids: CoreGraphNodeId[], depth: number) => {
depths.push(depth);
});
depths.sort((a, b) => a - b);
const nodes: NodeTypeMap[NC][] = [];
const node_id_used_state: Map<CoreGraphNodeId, boolean> = new Map();
depths.forEach((depth) => {
const graph_ids_for_depth = this._graph_id_by_depth.get(depth);
if (graph_ids_for_depth) {
for (let graph_id of graph_ids_for_depth) {
const node = this._graph.nodeFromId(graph_id) as NodeTypeMap[NC];
if (node) {
this.add_nodes_with_children(node, node_id_used_state, nodes);
}
}
}
});
return nodes;
}
add_nodes_with_children(
node: NodeTypeMap[NC],
node_id_used_state: Map<CoreGraphNodeId, boolean>,
accumulated_nodes: NodeTypeMap[NC][],
shader_name?: ShaderName
) {
if (!node_id_used_state.get(node.graphNodeId())) {
accumulated_nodes.push(node);
node_id_used_state.set(node.graphNodeId(), true);
}
if (node.type() == NetworkChildNodeType.INPUT) {
const parent = node.parent();
if (parent) {
const nodes_with_same_parent_as_subnet_input = this.sorted_nodes_for_shader_name_for_parent(
parent,
shader_name
);
for (let child_node of nodes_with_same_parent_as_subnet_input) {
if (child_node.graphNodeId() != node.graphNodeId()) {
this.add_nodes_with_children(child_node, node_id_used_state, accumulated_nodes, shader_name);
}
}
}
}
}
sorted_nodes_for_shader_name_for_parent(parent: BaseNodeType, shader_name?: ShaderName) {
const depths: number[] = [];
this._graph_id_by_depth.forEach((value: CoreGraphNodeId[], key: number) => {
depths.push(key);
});
depths.sort((a, b) => a - b);
const nodes: NodeTypeMap[NC][] = [];
depths.forEach((depth) => {
const graph_ids_for_depth = this._graph_id_by_depth.get(depth);
if (graph_ids_for_depth) {
graph_ids_for_depth.forEach((graph_id: CoreGraphNodeId) => {
const is_present = shader_name
? this._graph_ids_by_shader_name.get(shader_name)?.get(graph_id)
: true;
if (is_present) {
const node = this._graph.nodeFromId(graph_id) as NodeTypeMap[NC];
if (node.parent() == parent) {
nodes.push(node);
}
}
});
}
});
const first_node = nodes[0];
if (parent.context() == first_node.context()) {
nodes.push(parent as NodeTypeMap[NC]);
}
return nodes;
}
private find_leaves_from_root_node(root_node: NodeTypeMap[NC]) {
this._graph_ids_by_shader_name.get(this._shader_name)?.set(root_node.graphNodeId(), true);
const input_names = this.input_names_for_shader_name(root_node, this._shader_name);
if (input_names) {
for (let input_name of input_names) {
const input = root_node.io.inputs.named_input(input_name) as NodeTypeMap[NC];
if (input) {
MapUtils.pushOnArrayAtEntry(
this._outputs_by_graph_id,
input.graphNodeId(),
root_node.graphNodeId()
);
this.find_leaves(input);
}
}
}
this._outputs_by_graph_id.forEach((outputs: CoreGraphNodeId[], graph_id: CoreGraphNodeId) => {
this._outputs_by_graph_id.set(graph_id, ArrayUtils.uniq(outputs));
});
}
private find_leaves(node: NodeTypeMap[NC]) {
this._graph_ids_by_shader_name.get(this._shader_name)?.set(node.graphNodeId(), true);
const inputs = this._find_inputs_or_children(node) as NodeTypeMap[NC][];
const compact_inputs: NodeTypeMap[NC][] = ArrayUtils.compact(inputs);
const input_graph_ids = ArrayUtils.uniq(compact_inputs.map((n) => n.graphNodeId()));
const unique_inputs = input_graph_ids.map((graph_id) => this._graph.nodeFromId(graph_id)) as NodeTypeMap[NC][];
if (unique_inputs.length > 0) {
for (let input of unique_inputs) {
MapUtils.pushOnArrayAtEntry(this._outputs_by_graph_id, input.graphNodeId(), node.graphNodeId());
this.find_leaves(input);
}
} else {
this._leaves_graph_id.get(this._shader_name)!.set(node.graphNodeId(), true);
}
}
private _find_inputs_or_children(node: NodeTypeMap[NC]) {
if (node.type() == NetworkChildNodeType.INPUT) {
return node.parent()?.io.inputs.inputs() || [];
} else {
if (node.childrenAllowed()) {
// this._subnets_by_id.set(node.graphNodeId(), node);
const output_node = node.childrenController?.output_node();
return [output_node];
} else {
return node.io.inputs.inputs();
}
}
}
private set_nodes_depth() {
this._leaves_graph_id.forEach((booleans_by_graph_id, shader_name) => {
booleans_by_graph_id.forEach((boolean, graph_id) => {
this.set_node_depth(graph_id);
});
});
}
private set_node_depth(graph_id: CoreGraphNodeId, depth: number = 0) {
/*
adjust graph depth by hierarchical depth
meaning that nodes inside a subnet should add their depth to the parent (and a multiplier)
so that nodes outside of a subnet do not have a depth that ends up between the depths of 2 subnet children.
*/
// let depth_offset = 0;
// const node = this._graph.node_from_id(graph_id) as BaseNodeType;
// if (node.type == NetworkChildNodeType.INPUT) {
// const parent = node.parent;
// if (parent) {
// depth_offset = parent.children().length * 10;
// }
// }
// depth += depth_offset;
/*
end hierarchical depth adjustment
*/
const current_depth = this._depth_by_graph_id.get(graph_id);
if (current_depth != null) {
this._depth_by_graph_id.set(graph_id, Math.max(current_depth, depth));
} else {
this._depth_by_graph_id.set(graph_id, depth);
}
const output_ids = this._outputs_by_graph_id.get(graph_id);
if (output_ids) {
output_ids.forEach((output_id) => {
this.set_node_depth(output_id, depth + 1);
});
}
}
} | the_stack |
import Ambrosia = require("ambrosia-node");
import { State } from "./PTI";
import IC = Ambrosia.IC;
import Utils = Ambrosia.Utils;
const _knownDestinations: string[] = []; // All previously used destination instances (the 'PTI' Ambrosia app/service can be running on multiple instances, potentially simultaneously); used by the postResultDispatcher (if any)
let _destinationInstanceName: string = ""; // The current destination instance
let _postTimeoutInMs: number = 8000; // -1 = Infinite
/**
* Sets the destination instance name that the API targets.\
* Must be called at least once (with the name of a registered Ambrosia instance that implements the 'PTI' API) before any other method in the API is used.
*/
export function setDestinationInstance(instanceName: string): void
{
_destinationInstanceName = instanceName.trim();
if (_destinationInstanceName && (_knownDestinations.indexOf(_destinationInstanceName) === -1))
{
_knownDestinations.push(_destinationInstanceName);
}
}
/** Returns the destination instance name that the API currently targets. */
export function getDestinationInstance(): string
{
return (_destinationInstanceName);
}
/** Throws if _destinationInstanceName has not been set. */
function checkDestinationSet(): void
{
if (!_destinationInstanceName)
{
throw new Error("setDestinationInstance() must be called to specify the target destination before the 'PTI' API can be used.");
}
}
/**
* Sets the post method timeout interval (in milliseconds), which is how long to wait for a post result from the destination instance before raising an error.\
* All post methods will use this timeout value. Specify -1 for no timeout.
*/
export function setPostTimeoutInMs(timeoutInMs: number): void
{
_postTimeoutInMs = Math.max(-1, timeoutInMs);
}
/**
* Returns the post method timeout interval (in milliseconds), which is how long to wait for a post result from the destination instance before raising an error.\
* A value of -1 means there is no timeout.
*/
export function getPostTimeoutInMs(): number
{
return (_postTimeoutInMs);
}
/** Namespace for the "client-side" published methods. */
export namespace ClientAPI
{
/**
* *Note: "_Fork" methods should **only** be called from deterministic events.*
*
* Builds a batch of messages (each of size 'numRPCBytes') until the batch contains at least State._appState.batchSizeCutoff bytes. The batch is then sent.\
* This continues until a total of State._appState.bytesPerRound have been sent.\
* With the round complete, numRPCBytes is adjusted, then the whole cycle repeats until State._appState.numRoundsLeft reaches 0.
*/
export function continueSendingMessages_Fork(numRPCBytes: number, iterationWithinRound: number, startTimeOfRound: number): void
{
checkDestinationSet();
IC.callFork(_destinationInstanceName, 4, { numRPCBytes: numRPCBytes, iterationWithinRound: iterationWithinRound, startTimeOfRound: startTimeOfRound });
}
/**
* *Note: "_Impulse" methods should **only** be called from non-deterministic events (UI events, timers, web service calls, etc).*
*
* Builds a batch of messages (each of size 'numRPCBytes') until the batch contains at least State._appState.batchSizeCutoff bytes. The batch is then sent.\
* This continues until a total of State._appState.bytesPerRound have been sent.\
* With the round complete, numRPCBytes is adjusted, then the whole cycle repeats until State._appState.numRoundsLeft reaches 0.
*/
export function continueSendingMessages_Impulse(numRPCBytes: number, iterationWithinRound: number, startTimeOfRound: number): void
{
checkDestinationSet();
IC.callImpulse(_destinationInstanceName, 4, { numRPCBytes: numRPCBytes, iterationWithinRound: iterationWithinRound, startTimeOfRound: startTimeOfRound });
}
/**
* *Note: "_EnqueueFork" methods should **only** be called from deterministic events, and will not be sent until IC.flushQueue() is called.*
*
* Builds a batch of messages (each of size 'numRPCBytes') until the batch contains at least State._appState.batchSizeCutoff bytes. The batch is then sent.\
* This continues until a total of State._appState.bytesPerRound have been sent.\
* With the round complete, numRPCBytes is adjusted, then the whole cycle repeats until State._appState.numRoundsLeft reaches 0.
*/
export function continueSendingMessages_EnqueueFork(numRPCBytes: number, iterationWithinRound: number, startTimeOfRound: number): void
{
checkDestinationSet();
IC.queueFork(_destinationInstanceName, 4, { numRPCBytes: numRPCBytes, iterationWithinRound: iterationWithinRound, startTimeOfRound: startTimeOfRound });
}
/**
* *Note: "_EnqueueImpulse" methods should **only** be called from non-deterministic events (UI events, timers, web service calls, etc), and will not be sent until IC.flushQueue() is called.*
*
* Builds a batch of messages (each of size 'numRPCBytes') until the batch contains at least State._appState.batchSizeCutoff bytes. The batch is then sent.\
* This continues until a total of State._appState.bytesPerRound have been sent.\
* With the round complete, numRPCBytes is adjusted, then the whole cycle repeats until State._appState.numRoundsLeft reaches 0.
*/
export function continueSendingMessages_EnqueueImpulse(numRPCBytes: number, iterationWithinRound: number, startTimeOfRound: number): void
{
checkDestinationSet();
IC.queueImpulse(_destinationInstanceName, 4, { numRPCBytes: numRPCBytes, iterationWithinRound: iterationWithinRound, startTimeOfRound: startTimeOfRound });
}
/**
* *Note: "_Fork" methods should **only** be called from deterministic events.*
*
* A client method whose purpose is simply to be called [by the server] as an "echo" of the doWork() call sent to the server [by the client].
* @param rawParams A custom serialized byte array of all method parameters.
*/
export function doWorkEcho_Fork(rawParams: Uint8Array): void
{
checkDestinationSet();
IC.callFork(_destinationInstanceName, 5, rawParams);
}
/**
* *Note: "_Impulse" methods should **only** be called from non-deterministic events (UI events, timers, web service calls, etc).*
*
* A client method whose purpose is simply to be called [by the server] as an "echo" of the doWork() call sent to the server [by the client].
* @param rawParams A custom serialized byte array of all method parameters.
*/
export function doWorkEcho_Impulse(rawParams: Uint8Array): void
{
checkDestinationSet();
IC.callImpulse(_destinationInstanceName, 5, rawParams);
}
/**
* *Note: "_EnqueueFork" methods should **only** be called from deterministic events, and will not be sent until IC.flushQueue() is called.*
*
* A client method whose purpose is simply to be called [by the server] as an "echo" of the doWork() call sent to the server [by the client].
* @param rawParams A custom serialized byte array of all method parameters.
*/
export function doWorkEcho_EnqueueFork(rawParams: Uint8Array): void
{
checkDestinationSet();
IC.queueFork(_destinationInstanceName, 5, rawParams);
}
/**
* *Note: "_EnqueueImpulse" methods should **only** be called from non-deterministic events (UI events, timers, web service calls, etc), and will not be sent until IC.flushQueue() is called.*
*
* A client method whose purpose is simply to be called [by the server] as an "echo" of the doWork() call sent to the server [by the client].
* @param rawParams A custom serialized byte array of all method parameters.
*/
export function doWorkEcho_EnqueueImpulse(rawParams: Uint8Array): void
{
checkDestinationSet();
IC.queueImpulse(_destinationInstanceName, 5, rawParams);
}
}
/** Namespace for the "server-side" published methods. */
export namespace ServerAPI
{
/**
* *Note: "_Fork" methods should **only** be called from deterministic events.*
*
* A method whose purpose is to update _appState with each call.
* @param rawParams A custom serialized byte array of all method parameters.
*/
export function doWork_Fork(rawParams: Uint8Array): void
{
checkDestinationSet();
IC.callFork(_destinationInstanceName, 1, rawParams);
}
/**
* *Note: "_Impulse" methods should **only** be called from non-deterministic events (UI events, timers, web service calls, etc).*
*
* A method whose purpose is to update _appState with each call.
* @param rawParams A custom serialized byte array of all method parameters.
*/
export function doWork_Impulse(rawParams: Uint8Array): void
{
checkDestinationSet();
IC.callImpulse(_destinationInstanceName, 1, rawParams);
}
/**
* *Note: "_EnqueueFork" methods should **only** be called from deterministic events, and will not be sent until IC.flushQueue() is called.*
*
* A method whose purpose is to update _appState with each call.
* @param rawParams A custom serialized byte array of all method parameters.
*/
export function doWork_EnqueueFork(rawParams: Uint8Array): void
{
checkDestinationSet();
IC.queueFork(_destinationInstanceName, 1, rawParams);
}
/**
* *Note: "_EnqueueImpulse" methods should **only** be called from non-deterministic events (UI events, timers, web service calls, etc), and will not be sent until IC.flushQueue() is called.*
*
* A method whose purpose is to update _appState with each call.
* @param rawParams A custom serialized byte array of all method parameters.
*/
export function doWork_EnqueueImpulse(rawParams: Uint8Array): void
{
checkDestinationSet();
IC.queueImpulse(_destinationInstanceName, 1, rawParams);
}
/**
* *Note: "_Fork" methods should **only** be called from deterministic events.*
*
* A method that reports (to the console) the current application state.
*/
export function reportState_Fork(isFinalState: boolean): void
{
checkDestinationSet();
IC.callFork(_destinationInstanceName, 2, { isFinalState: isFinalState });
}
/**
* *Note: "_Impulse" methods should **only** be called from non-deterministic events (UI events, timers, web service calls, etc).*
*
* A method that reports (to the console) the current application state.
*/
export function reportState_Impulse(isFinalState: boolean): void
{
checkDestinationSet();
IC.callImpulse(_destinationInstanceName, 2, { isFinalState: isFinalState });
}
/**
* *Note: "_EnqueueFork" methods should **only** be called from deterministic events, and will not be sent until IC.flushQueue() is called.*
*
* A method that reports (to the console) the current application state.
*/
export function reportState_EnqueueFork(isFinalState: boolean): void
{
checkDestinationSet();
IC.queueFork(_destinationInstanceName, 2, { isFinalState: isFinalState });
}
/**
* *Note: "_EnqueueImpulse" methods should **only** be called from non-deterministic events (UI events, timers, web service calls, etc), and will not be sent until IC.flushQueue() is called.*
*
* A method that reports (to the console) the current application state.
*/
export function reportState_EnqueueImpulse(isFinalState: boolean): void
{
checkDestinationSet();
IC.queueImpulse(_destinationInstanceName, 2, { isFinalState: isFinalState });
}
/**
* *Note: "_Fork" methods should **only** be called from deterministic events.*
*
* A method whose purpose is [mainly] to be a rapidly occurring Impulse method to test if this causes issues for recovery.\
* Also periodically (eg. every ~5 seconds) reports that the Server is still running.
*/
export function checkHealth_Fork(currentTime: number): void
{
checkDestinationSet();
IC.callFork(_destinationInstanceName, 3, { currentTime: currentTime });
}
/**
* *Note: "_Impulse" methods should **only** be called from non-deterministic events (UI events, timers, web service calls, etc).*
*
* A method whose purpose is [mainly] to be a rapidly occurring Impulse method to test if this causes issues for recovery.\
* Also periodically (eg. every ~5 seconds) reports that the Server is still running.
*/
export function checkHealth_Impulse(currentTime: number): void
{
checkDestinationSet();
IC.callImpulse(_destinationInstanceName, 3, { currentTime: currentTime });
}
/**
* *Note: "_EnqueueFork" methods should **only** be called from deterministic events, and will not be sent until IC.flushQueue() is called.*
*
* A method whose purpose is [mainly] to be a rapidly occurring Impulse method to test if this causes issues for recovery.\
* Also periodically (eg. every ~5 seconds) reports that the Server is still running.
*/
export function checkHealth_EnqueueFork(currentTime: number): void
{
checkDestinationSet();
IC.queueFork(_destinationInstanceName, 3, { currentTime: currentTime });
}
/**
* *Note: "_EnqueueImpulse" methods should **only** be called from non-deterministic events (UI events, timers, web service calls, etc), and will not be sent until IC.flushQueue() is called.*
*
* A method whose purpose is [mainly] to be a rapidly occurring Impulse method to test if this causes issues for recovery.\
* Also periodically (eg. every ~5 seconds) reports that the Server is still running.
*/
export function checkHealth_EnqueueImpulse(currentTime: number): void
{
checkDestinationSet();
IC.queueImpulse(_destinationInstanceName, 3, { currentTime: currentTime });
}
/**
* *Note: The result (number) produced by this post method is received via the PostResultDispatcher provided to IC.start(). Returns the post method callID.*
*
* *Note: "_Post" methods should **only** be called from deterministic events.*
*
* A simple post method. Returns the supplied value incremented by 1.
*/
export function incrementValue_Post(callContextData: any, value: number): number
{
checkDestinationSet();
const callID = IC.postFork(_destinationInstanceName, "incrementValue", 1, _postTimeoutInMs, callContextData, IC.arg("value", value));
return (callID);
}
/**
* *Note: The result (number) produced by this post method is received via the PostResultDispatcher provided to IC.start().*
*
* *Note: "_PostByImpulse" methods should **only** be called from non-deterministic events (UI events, timers, web service calls, etc).*
*
* A simple post method. Returns the supplied value incremented by 1.
*/
export function incrementValue_PostByImpulse(callContextData: any, value: number): void
{
checkDestinationSet();
IC.postByImpulse(_destinationInstanceName, "incrementValue", 1, _postTimeoutInMs, callContextData, IC.arg("value", value));
}
}
/**
* Handler for the results of previously called post methods (in Ambrosia, only 'post' methods return values). See Messages.PostResultDispatcher.\
* Must return true only if the result (or error) was handled.
*/
export function postResultDispatcher(senderInstanceName: string, methodName: string, methodVersion: number, callID: number, callContextData: any, result: any, errorMsg: string): boolean
{
const sender: string = IC.isSelf(senderInstanceName) ? "local" : `'${senderInstanceName}'`;
let handled: boolean = true;
if (_knownDestinations.indexOf(senderInstanceName) === -1)
{
return (false); // Not handled: this post result is from a different instance than the destination instance currently (or previously) targeted by the 'PTI' API
}
if (errorMsg)
{
switch (methodName)
{
case "incrementValue":
Utils.log(`Error: ${errorMsg}`);
break;
default:
handled = false;
break;
}
}
else
{
switch (methodName)
{
case "incrementValue":
const incrementValue_Result: number = result;
const expectedValue: number = callContextData;
if (incrementValue_Result !== expectedValue)
{
throw new Error(`The result of post method '${methodName}' (from ${sender}) is incorrect: expected ${expectedValue} but got ${incrementValue_Result}`);
}
if (incrementValue_Result !== State._appState.lastPostMethodResultValue + 1)
{
throw new Error(`The result of post method '${methodName}' (from ${sender}) is out of order: expected ${State._appState.lastPostMethodResultValue + 1} but got ${incrementValue_Result}`);
}
State._appState.postMethodResultCount++;
State._appState.lastPostMethodResultValue = incrementValue_Result;
break;
default:
handled = false;
break;
}
}
return (handled);
} | the_stack |
'use strict';
function gcd(a: any, b: any) {
let c;
if (a < 0) a = -a;
if (b < 0) b = -b;
while (b) {
c = b; b = a % b; a = c;
}
return a;
}
function lcm(a: any, b: any) {
if (!a && !b) return 0;
return Math.abs(a * b / gcd(a, b));
}
class RationalNumber {
a: any;
b: any;
constructor(a: any, b: any) {
if (b === 0) throw new Error("Denominator must not be zero");
if (typeof b === 'undefined') b = 1;
this.a = a;
this.b = b;
this.normalize();
}
normalize() {
let k = gcd(this.a, this.b);
if (k !== 1) {
this.a /= k;
this.b /= k;
}
if (this.b < 0) {
this.a = -this.a;
this.b = -this.b;
}
}
isZero() {
return this.a === 0;
}
plus(b: any) {
return new RationalNumber(this.a * b.b + b.a * this.b, this.b * b.b);
}
minus(b: any) {
return new RationalNumber(this.a * b.b - b.a * this.b, this.b * b.b);
}
multiply(b: any) {
return new RationalNumber(this.a * b.a, this.b * b.b);
}
divide(b: any) {
if (b.isZero()) throw new Error("Divisor must not be zero");
return new RationalNumber(this.a * b.b, this.b * b.a);
}
invert() {
return new RationalNumber(-this.a, this.b);
}
equal(b: any) {
return this.a * b.b === this.b * b.a;
}
toString() {
return this.b === 1 ? '' + this.a : this.a + '/' + this.b;
}
get value() {
return this.a / this.b;
}
}
class EquationSolveError extends Error {
constructor(info: any) {
super("Failed to solve the equation set.");
}
}
class Equation {
a: any;
x: any;
constructor(a: any, b: any) {
this.x = a.slice(0);
this.a = b;
}
}
class EquationSet {
a: any;
x: any;
constructor(n: any, arr: any) {
this.x = n;
this.a = arr.slice(0);
}
// @ts-expect-error ts-migrate(7023) FIXME: '_solve' implicitly has return type 'any' because ... Remove this comment to see the full error message
static _solve(set: any) {
// @ts-expect-error ts-migrate(2554) FIXME: Expected 1 arguments, but got 0.
if (set.a.length < set.x) throw new EquationSolveError();
if (set.x > 1) {
let src: any = null;
let arr: any = [];
set.a.forEach(function(b: any) {
if (b.x[0].isZero()) {
arr.push(new Equation(b.x.slice(1), b.a));
} else if (!src) {
src = b;
} else {
let tmp = [];
for (let i = 1; i < b.x.length; ++i) {
tmp.push(b.x[i].multiply(src.x[0]).minus(src.x[i].multiply(b.x[0])));
}
arr.push(new Equation(tmp, b.a.multiply(src.x[0]).minus(src.a.multiply(b.x[0]))));
}
});
// @ts-expect-error ts-migrate(2554) FIXME: Expected 1 arguments, but got 0.
if (!src) throw new EquationSolveError();
// @ts-expect-error ts-migrate(7022) FIXME: 'res' implicitly has type 'any' because it does no... Remove this comment to see the full error message
let res = [null].concat(EquationSet._solve(new EquationSet(set.x - 1, arr)));
let a = src.a, b = src.x[0];
for (let i = 1; i < set.x; ++i) {
a = a.plus(src.x[i].multiply(res[i]));
}
res[0] = a.divide(b).invert();
return res;
} else {
let res: any = null;
set.a.forEach(function(b: any) {
if (b.x[0].isZero()) {
if (!b.a.isZero()) {
// @ts-expect-error ts-migrate(2554) FIXME: Expected 1 arguments, but got 0.
throw new EquationSolveError();
}
} else {
let tmp = b.a.divide(b.x[0]).invert();
// @ts-expect-error ts-migrate(2554) FIXME: Expected 1 arguments, but got 0.
if (res && !res.equal(tmp)) throw new EquationSolveError();
res = tmp;
}
});
// @ts-expect-error ts-migrate(2554) FIXME: Expected 1 arguments, but got 0.
if (!res) throw new EquationSolveError();
return [res];
}
}
solve() {
return EquationSet._solve(this);
}
}
class CalcError extends Error {
// @ts-expect-error ts-migrate(7019) FIXME: Rest parameter 'arg' implicitly has an 'any[]' typ... Remove this comment to see the full error message
constructor(...arg) {
super(...arg);
}
}
class Chemical {
count: any;
str: any;
constructor(str: any, count: any) {
this.str = str;
this.count = count;
}
get(element: any) {
return this.count.has(element) ? this.count.get(element) : 0;
}
}
class ChemicalSet extends Array {
// @ts-expect-error ts-migrate(7019) FIXME: Rest parameter 'arg' implicitly has an 'any[]' typ... Remove this comment to see the full error message
constructor(...arg) {
super(...arg);
}
}
function init(_this: any, str: any) {
// let _this = this;
str.replace(/\s/g, '').split('+').forEach(function(s: any) {
if (!s) throw new CalcError("化学式不能为空");
let stack = [[]];
for (let i = 0; i < s.length; ) {
if (s[i] === '(') {
stack.push([]);
++i;
} else if (s[i] === ')') {
if (stack.length < 2) throw new CalcError("括号不匹配");
if (s[i - 1] === '(') throw new CalcError("括号内不能为空");
let tmp = s.slice(i + 1).match(/^[0-9]+/);
let count = 1;
if (tmp) {
count = parseInt(tmp[0]);
i += tmp[0].length;
}
let arr = stack.pop();
// @ts-expect-error ts-migrate(2532) FIXME: Object is possibly 'undefined'.
arr.forEach(function(o) {
stack[stack.length - 1].push({
// @ts-expect-error ts-migrate(2322) FIXME: Type 'any' is not assignable to type 'never'.
element: o.element,
// @ts-expect-error ts-migrate(2322) FIXME: Type 'number' is not assignable to type 'never'.
count: o.count * count
});
});
++i;
} else {
let tmp = s.slice(i).match(/^([A-Z][a-z]*)(\d*)/);
if (!tmp) throw new CalcError("化学式书写错误");
let element = tmp[1];
let count = parseInt(tmp[2] || 1);
stack[stack.length - 1].push({
// @ts-expect-error ts-migrate(2322) FIXME: Type 'any' is not assignable to type 'never'.
element: element,
// @ts-expect-error ts-migrate(2322) FIXME: Type 'number' is not assignable to type 'never'.
count: count
});
i += tmp[0].length;
}
}
if (stack.length > 1) throw new CalcError("括号不匹配");
let map = new Map();
stack[0].forEach(function(item) {
// @ts-expect-error ts-migrate(2339) FIXME: Property 'element' does not exist on type 'never'.
if (!map.has(item.element)) {
// @ts-expect-error ts-migrate(2339) FIXME: Property 'element' does not exist on type 'never'.
map.set(item.element, item.count);
} else {
// @ts-expect-error ts-migrate(2339) FIXME: Property 'element' does not exist on type 'never'.
map.set(item.element, map.get(item.element) + item.count);
}
});
console.log('_s', s)
console.log('map', map)
_this.push(new Chemical(s, map));
});
return _this
}
class ChemicalEquation {
elements: any;
l: any;
r: any;
constructor(l: any, r: any) {
// this.l = new ChemicalSet();
this.l = init([], l)
this.r = init([], r)
console.log('left', this.l)
// this.r.init(r);
}
balance() {
let _this = this;
this.elements = [];
[].concat(this.l, this.r).forEach(function(a) {
// @ts-expect-error ts-migrate(2339) FIXME: Property 'count' does not exist on type 'never'.
a.count.forEach(function(count: any, element: any) {
if (_this.elements.indexOf(element) === -1) {
_this.elements.push(element);
}
});
});
console.log('this.elements', this.elements)
let cntUnknowns = this.l.length + this.r.length - 1;
console.log('cntUnknowns', cntUnknowns)
let set = new EquationSet(cntUnknowns, this.elements.map(function(element: any) {
console.log('====element', element)
let a = [].concat(_this.l.slice(1).map(function(b: any) {
return b.get(element);
}), _this.r.map(function(b: any) {
return -b.get(element);
})).map(function(x) {
// @ts-expect-error ts-migrate(2554) FIXME: Expected 2 arguments, but got 1.
return new RationalNumber(x);
});
// @ts-expect-error ts-migrate(2554) FIXME: Expected 2 arguments, but got 1.
let b = new RationalNumber(_this.l[0].get(element));
console.log('a,b', a, b)
return new Equation(a, b);
}));
let res;
console.log('set', set)
let table = set.a.map((item: any) => {
return [item.a.a].concat(item.x.map((item: any) => item.a));
})
console.log('table', table)
try {
res = set.solve();
} catch (err) {
throw new CalcError("无法配平方程式");
}
console.log('方程解', res)
let k = 1;
for (let i = 0; i < res.length; ++i) {
if (res[i].a <= 0) throw new CalcError("无法配平方程式");
k = lcm(k, res[i].b);
}
let ans = [k];
for (let i = 0; i < res.length; ++i) {
ans.push(res[i].a * (k / res[i].b));
}
return {
ans,
table
}
}
}
function getResult(textl: any, textr: any) {
try {
let eq = new ChemicalEquation(textl, textr);
let {ans,table} = eq.balance();
console.log('ans', ans)
let res = '';
for (let i = 0; i < eq.l.length; ++i) {
if (i) res += '+';
if (ans[i] !== 1) res += ans[i];
res += eq.l[i].str.replace(/\d+/g, function(a: any) {
return '<sub>' + a + '</sub>';
});
}
for (let i = 0; i < eq.r.length; ++i) {
res += i ? '+' : '==';
if (ans[i + eq.l.length] !== 1) res += ans[i + eq.l.length];
res += eq.r[i].str.replace(/\d+/g, function(a: any) {
return '<sub>' + a + '</sub>';
});
}
console.log('res', res)
return {
ans,
exp: res,
table,
};
} catch (err) {
console.error('err', err)
if (err instanceof CalcError) {
return '<span class="error-info">' + err.message + '</span>';
} else {
return '<span class="error-info">' + err.stack + '</span>';
}
}
}
let table = [
[2, 0, -1, 0, 0],
[1, 0, 0, 0, -1],
[3, 0, 0, -1, -2],
[0, 1, 0, -2, 0],
[0, 1, -1, 0, 0]
]
function calTable(table: any) {
let set = new EquationSet(table[0].length - 1, table.map((row: any) => {
// @ts-expect-error ts-migrate(2554) FIXME: Expected 2 arguments, but got 1.
return new Equation(row.slice(1).map((item: any) => new RationalNumber(item)), new RationalNumber(row[0]));
}))
console.log('==set', set)
let res = set.solve()
let k = 1;
for (let i = 0; i < res.length; ++i) {
if (res[i].a <= 0) throw new CalcError("无法配平方程式");
k = lcm(k, res[i].b);
}
let ans = [k];
for (let i = 0; i < res.length; ++i) {
ans.push(res[i].a * (k / res[i].b));
}
return ans;
}
//console.log('==table', table)
console.log('==result', calTable(table))
//export { getResult }
export default calTable | the_stack |
import { IFilterInfo, SimpleFsStorageProvider } from "../../src";
import * as expect from "expect";
import * as tmp from "tmp";
tmp.setGracefulCleanup();
function createSimpleFsStorageProvider(inMemory = false, maxMemTransactions = 20) {
const tmpFile = tmp.fileSync();
const writeProvider = new SimpleFsStorageProvider(tmpFile.name, inMemory, maxMemTransactions);
const readProviderFn = () => new SimpleFsStorageProvider(tmpFile.name, inMemory, maxMemTransactions);
return {tmpFile, writeProvider, readProviderFn};
}
describe('SimpleFsStorageProvider', () => {
it('should return the right sync token', async () => {
const {writeProvider, readProviderFn} = createSimpleFsStorageProvider();
const value = "testing";
expect(await writeProvider.getSyncToken()).toBeFalsy();
await writeProvider.setSyncToken(value);
expect(await writeProvider.getSyncToken()).toEqual(value);
expect(await readProviderFn().getSyncToken()).toEqual(value);
});
it('should return the right filter object', async () => {
const {writeProvider, readProviderFn} = createSimpleFsStorageProvider();
const value: IFilterInfo = {id: 12, filter: {hello: "world"}};
expect(await writeProvider.getFilter()).toBeFalsy();
await writeProvider.setFilter(value);
expect(await writeProvider.getFilter()).toMatchObject(<any>value);
expect(await readProviderFn().getFilter()).toMatchObject(<any>value);
});
it('should track registered users', async () => {
const {writeProvider, readProviderFn} = createSimpleFsStorageProvider();
const userIdA = "@first:example.org";
const userIdB = "@second:example.org";
expect(await writeProvider.isUserRegistered(userIdA)).toBeFalsy();
expect(await writeProvider.isUserRegistered(userIdB)).toBeFalsy();
await writeProvider.addRegisteredUser(userIdA);
expect(await writeProvider.isUserRegistered(userIdA)).toBeTruthy();
expect(await writeProvider.isUserRegistered(userIdB)).toBeFalsy();
expect(await readProviderFn().isUserRegistered(userIdA)).toBeTruthy();
expect(await readProviderFn().isUserRegistered(userIdB)).toBeFalsy();
await writeProvider.addRegisteredUser(userIdA); // duplicated to make sure it is safe to do so
expect(await writeProvider.isUserRegistered(userIdA)).toBeTruthy();
expect(await writeProvider.isUserRegistered(userIdB)).toBeFalsy();
expect(await readProviderFn().isUserRegistered(userIdA)).toBeTruthy();
expect(await readProviderFn().isUserRegistered(userIdB)).toBeFalsy();
await writeProvider.addRegisteredUser(userIdB);
expect(await writeProvider.isUserRegistered(userIdA)).toBeTruthy();
expect(await writeProvider.isUserRegistered(userIdB)).toBeTruthy();
expect(await readProviderFn().isUserRegistered(userIdA)).toBeTruthy();
expect(await readProviderFn().isUserRegistered(userIdB)).toBeTruthy();
});
it('should track completed transactions', async () => {
const {writeProvider, readProviderFn} = createSimpleFsStorageProvider();
const txnA = "@first:example.org";
const txnB = "@second:example.org";
expect(await writeProvider.isTransactionCompleted(txnA)).toBeFalsy();
expect(await writeProvider.isTransactionCompleted(txnB)).toBeFalsy();
await writeProvider.setTransactionCompleted(txnA);
expect(await writeProvider.isTransactionCompleted(txnA)).toBeTruthy();
expect(await writeProvider.isTransactionCompleted(txnB)).toBeFalsy();
expect(await readProviderFn().isTransactionCompleted(txnA)).toBeTruthy();
expect(await readProviderFn().isTransactionCompleted(txnB)).toBeFalsy();
await writeProvider.setTransactionCompleted(txnA); // duplicated to make sure it is safe to do so
expect(await writeProvider.isTransactionCompleted(txnA)).toBeTruthy();
expect(await writeProvider.isTransactionCompleted(txnB)).toBeFalsy();
expect(await readProviderFn().isTransactionCompleted(txnA)).toBeTruthy();
expect(await readProviderFn().isTransactionCompleted(txnB)).toBeFalsy();
await writeProvider.setTransactionCompleted(txnB);
expect(await writeProvider.isTransactionCompleted(txnA)).toBeTruthy();
expect(await writeProvider.isTransactionCompleted(txnB)).toBeTruthy();
expect(await readProviderFn().isTransactionCompleted(txnA)).toBeTruthy();
expect(await readProviderFn().isTransactionCompleted(txnB)).toBeTruthy();
});
it('should track a limited number of completed transactions in memory', async () => {
const maxTransactions = 2;
const {writeProvider, readProviderFn} = createSimpleFsStorageProvider(true, maxTransactions);
const txnA = "@first:example.org";
const txnB = "@second:example.org";
const txnC = "@third:example.org";
// The read provider results should always be falsey because the write provider
// should not be writing to disk.
expect(await writeProvider.isTransactionCompleted(txnA)).toBeFalsy();
expect(await writeProvider.isTransactionCompleted(txnB)).toBeFalsy();
expect(await writeProvider.isTransactionCompleted(txnC)).toBeFalsy();
await writeProvider.setTransactionCompleted(txnA);
expect(await writeProvider.isTransactionCompleted(txnA)).toBeTruthy();
expect(await writeProvider.isTransactionCompleted(txnB)).toBeFalsy();
expect(await writeProvider.isTransactionCompleted(txnC)).toBeFalsy();
expect(await readProviderFn().isTransactionCompleted(txnA)).toBeFalsy();
expect(await readProviderFn().isTransactionCompleted(txnB)).toBeFalsy();
expect(await readProviderFn().isTransactionCompleted(txnC)).toBeFalsy();
await writeProvider.setTransactionCompleted(txnA); // duplicated to make sure it is safe to do so
expect(await writeProvider.isTransactionCompleted(txnA)).toBeTruthy();
expect(await writeProvider.isTransactionCompleted(txnB)).toBeFalsy();
expect(await writeProvider.isTransactionCompleted(txnC)).toBeFalsy();
expect(await readProviderFn().isTransactionCompleted(txnA)).toBeFalsy();
expect(await readProviderFn().isTransactionCompleted(txnB)).toBeFalsy();
expect(await readProviderFn().isTransactionCompleted(txnC)).toBeFalsy();
await writeProvider.setTransactionCompleted(txnB);
expect(await writeProvider.isTransactionCompleted(txnA)).toBeTruthy();
expect(await writeProvider.isTransactionCompleted(txnB)).toBeTruthy();
expect(await writeProvider.isTransactionCompleted(txnC)).toBeFalsy();
expect(await readProviderFn().isTransactionCompleted(txnA)).toBeFalsy();
expect(await readProviderFn().isTransactionCompleted(txnB)).toBeFalsy();
expect(await readProviderFn().isTransactionCompleted(txnC)).toBeFalsy();
await writeProvider.setTransactionCompleted(txnC);
expect(await writeProvider.isTransactionCompleted(txnA)).toBeFalsy(); // No longer in memory
expect(await writeProvider.isTransactionCompleted(txnB)).toBeTruthy();
expect(await writeProvider.isTransactionCompleted(txnC)).toBeTruthy();
expect(await readProviderFn().isTransactionCompleted(txnA)).toBeFalsy();
expect(await readProviderFn().isTransactionCompleted(txnB)).toBeFalsy();
expect(await readProviderFn().isTransactionCompleted(txnC)).toBeFalsy();
});
it('should track arbitrary key value pairs', async () => {
const {writeProvider, readProviderFn} = createSimpleFsStorageProvider();
const key = "test";
const value = "testing";
expect(writeProvider.readValue(key)).toBeFalsy();
writeProvider.storeValue(key, value);
expect(writeProvider.readValue(key)).toEqual(value);
expect(readProviderFn().readValue(key)).toEqual(value);
});
describe('namespacing', () => {
it('should return the right sync token', async () => {
const {writeProvider, readProviderFn} = createSimpleFsStorageProvider();
const value = "testing";
const namespace = "@user:example.org";
const nsWriter = writeProvider.storageForUser(namespace);
expect(nsWriter).toBeDefined();
expect(await writeProvider.getSyncToken()).toBeFalsy();
expect(await nsWriter.getSyncToken()).toBeFalsy();
await nsWriter.setSyncToken(value);
expect(await nsWriter.getSyncToken()).toEqual(value);
expect(await writeProvider.getSyncToken()).toBeFalsy();
expect(await readProviderFn().storageForUser(namespace).getSyncToken()).toEqual(value);
expect(await readProviderFn().getSyncToken()).toBeFalsy();
});
it('should return the right filter object', async () => {
const {writeProvider, readProviderFn} = createSimpleFsStorageProvider();
const value: IFilterInfo = {id: 12, filter: {hello: "world"}};
const namespace = "@user:example.org";
const nsWriter = writeProvider.storageForUser(namespace);
expect(nsWriter).toBeDefined();
expect(await writeProvider.getFilter()).toBeFalsy();
expect(await nsWriter.getFilter()).toBeFalsy();
await nsWriter.setFilter(value);
expect(await nsWriter.getFilter()).toMatchObject(<any>value);
expect(await writeProvider.getFilter()).toBeFalsy();
expect(await readProviderFn().storageForUser(namespace).getFilter()).toMatchObject(<any>value);
expect(await readProviderFn().getFilter()).toBeFalsy();
});
it('should track arbitrary key value pairs', async () => {
const { writeProvider, readProviderFn } = createSimpleFsStorageProvider();
const key = "test";
const value = "testing";
const namespace = "@user:example.org";
const nsKey = `${namespace}_kv_${key}`;
const nsWriter = writeProvider.storageForUser(namespace);
expect(nsWriter).toBeDefined();
expect(await nsWriter.readValue(key)).toBeFalsy();
expect(await writeProvider.readValue(nsKey)).toBeFalsy();
await nsWriter.storeValue(key, value);
expect(await nsWriter.readValue(key)).toEqual(value);
expect(await writeProvider.readValue(nsKey)).toEqual(value);
expect(await readProviderFn().storageForUser(namespace).readValue(key)).toEqual(value);
expect(await readProviderFn().readValue(nsKey)).toEqual(value);
});
});
}); | the_stack |
import { Commit } from 'vuex'
import * as types from '../mutation-types'
export interface ApmData {
[key: string]: any
}
export interface State {
captures: any[]
historys: any[]
defaultCapture: any
defaultHistory: any
reloadToggle: boolean
compareToggle: boolean
captureToggle: boolean
apmData: ApmData,
performanceMode: any,
performanceScoreSeed: any,
performanceScoreTextMap: any
}
const state: State = {
captures: [
'5000',
'8000',
'10000'
],
historys: [],
defaultCapture: 5000,
defaultHistory: '',
reloadToggle: true,
compareToggle: false,
captureToggle: false,
apmData: {},
performanceMode: {
wxRequestSourceTime: 'Weex请求资源耗时',
wxRenderBundleTime: 'Weex处理Bundle耗时',
wxJSAsyncDataTime: '前端异步请求时间',
wxJSDataPrefetchSuccess: '前端prefetch是否成功',
wxInteractionTime: '可交互时间总耗时',
wxRequestType: {
text: '请求类型, 2g/3g/4g/wifi/zcache/weex_cache/other',
tips: ['纯网络 2g、3g、4g、wifi', 'zcache', 'weex_cache']
},
wxBizID: '完整的业务ID',
wxBundleType: {
text: 'JS框架语言',
tips: ['主要为Vue, Rax, 也支持三方定制框架']
},
wxInstanceType: {
text: '实例类型',
tips: ['page - 普通weex页面', 'embed - weex模块']
},
wxContainerInfo: {
text: '运行容器名称',
tips: [
'一个容器可能会对应多个页面'
]
},
parentPage: {
text: 'Embed组件父级页面',
tips: [
'只有Embed页面内会报,Embed所在page的url'
]
},
wxBundleSize: {
text: '页面Bundle大小',
tips: [
'拖慢资源请求耗时',
'减少Bundle大小'
]
},
wxActualNetworkTime: '网络库打点的网络下载耗时',
wxInteractionComponentCreateTime: {
text: '可交互时间内,总共创建component耗时',
tips: ['调整渲染时序,屏幕外的组件会延后屏幕内的渲染时间']
},
wxInteractionComponentCreateCount: {
text: '可交互时间内,总共创建component个数',
tips: ['减少资源请求前预先打底的次数']
},
wxInteractionAllViewCount: {
text: '可交互时间内,屏幕(instance)内外,对应渲染 view 个数',
tips: ['减少打底view的总个数']
},
wxInteractionScreenViewCount: {
text: '可交互时间内,屏幕(instance)内 渲染 view 次数',
tips: [
'可交互时间内,屏幕内是否需要这么多view',
'减少不必要的屏幕内节点'
]
},
wxFSCallJsTotalTime: '首屏时间调用JS耗时',
wxFSCallJsTotalNum: '首屏时间调用js次数',
wxFSCallNativeTotalTime: {
text: '首屏时间调用Native module耗时',
tips: [
'减少native module的调用次数(重复的,不必要的)',
'使用devtool、analzyer排查纤细信息'
]
},
wxFSCallNativeTotalNum: '首屏时间调用Native次数',
wxFSCallEventTotalTime: '首屏时间调用CallEven耗时',
wxFSCallEventTotalNum: '首屏时间调用CallEven耗时次数',
wxFSRequestNum: '首屏调用Timer次数',
wxFSTimerCount: '首屏Tmer调用耗时',
memdiff: '进入退出内存水位变化',
wxLargeImgMaxCount: {
text: '大图个数(最多那次)',
tips: ['图片大小>1080*720', '减少大图的投放,内存占用大头']
},
wxWrongImgSizeCount: {
text: '图片和view大小不匹配个数',
tips: ['投放的图片尺寸大于实际view的的大小,建议图片进行裁剪,减少不必要的内存占用', '使用analyzer或者dev-tool有详细的url和尺寸提示']
},
wxImgUnRecycleCount: {
text: '未开启图片自动回收imgview的个数',
tips: ['imageview没有开启图片自动回收机制,内存非常容易oom']
},
wxCellDataUnRecycleCount: {
text: '内容不回收的cell组件个数',
tips: ['最好开启cell上数据的回收,不然内存会爆掉']
},
wxCellViewUnReUseCount: {
text: '没有开启复用cell的个数',
tips: ['没有开启cell的复用机制,大列表内存会爆炸']
},
wxScrollerCount: {
text: '使用scroller个数',
tips: ['scroller是没有view回收机制的,长列表内存容易oom','使用ListView、recycleView替代']
},
wxEmbedCount: {
text: 'embed 模块个数',
tips: ['embed不建议太多(3个)']
},
wxCellExceedNum: {
text: '超大cell个数',
tips: ['width >= screenWidth/2 && height >= screenHeight/2']
},
fps: {
text: '进入退出 平均fps',
tips: ['apm 提供']
},
wxMaxDeepVDomLayer: {
text: 'Dom结点最大层级',
tips: ['dom树的最大层级,不建议超过15层,会给渲染造成很大压力,并且在Android设备上容易crash']
},
wxMaxComponentCount: {
text: '组件个数(最多那次)',
tips: ['持有组件个数峰值,在布局时layout造成很大压力,对fps和可交互时间都有很大影响','和wxMaxDeepVDomLayer一起,是影响渲染速度的两大因素','减少不必要的节点数']
},
wxMaxDeepViewLayer: {
text: 'view最大层级',
tips: ['同dom结点最大层级,在设备上实际渲染的view最大层级']
},
wxTimerInBackCount: '后台执行Timer次数',
wxImgLoadCount: '所有图片加载数',
wxImgLoadSuccessCount: '成功加载的图片数',
wxImgLoadFailCount: 'weex提供',
wxNetworkRequestCount: 'weex提供',
wxNetworkRequestSuccessCount: 'weex提供',
wxNetworkRequestFailCoun: 'weex提供',
imgLoadCount: 'apm提供',
imgLoadSuccessCount: 'apm提供',
imgLoadFailCount: 'apm提供',
networkRequestCount: 'apm提供',
networkRequestSuccessCount: 'apm提供',
networkRequestFailCount: 'apm提供',
wxRecordStart: '埋点开始记录时间',
wxStartDownLoadBundle: '开始下载Bundle时间',
wxEndDownLoadBundle: '下载Bundle结束时间',
wxRenderTimeOrigin: '开始渲染时间点',
wxStartLoadBundle: '加载解析业务Bundle时间点',
wxEndLoadBundle: '加载解析业务Bundle完成时间点',
wxFsRender: '旧首屏时间点',
wxNewFsRender: '新首屏时间点',
wxFirstInteractionView: '屏幕内第一个View出现的时间点',
wxInteraction: '可交互时间点',
wxJSAsyncDataStart: '前端异步请求开始时间点',
wxJSAsyncDataEnd: '前端异步请求结束时间点',
wxJSLibVersion: 'JSFramework版本',
wxContainerName: '运行容器名称',
wxZCacheInfo: 'ZCache信息',
wxErrorCode: {
text: 'Weex错误代码',
tips: [
'查看文档:<a href="https://yuque.antfin-inc.com/weex/weexrobust/yrp25x" target="_blank">WEEX异常码含义</a>'
]
},
wxSDKVersion: 'Weex SDK版本',
wxDestroy: '页面销毁时间点',
wxBodyRatio: {
text: 'weex页面的屏占百分比,[0-100]',
tips: ['用来区分是否是card类型的页面, < 60%为card类型']
}
},
performanceScoreSeed: {
JSTemplateSize: {
type: 'number',
range: 250,
step: 20,
stepScore: -1,
maxScore: 20
},
JSDataPrefetch: {
type: 'boolean',
range: 'true',
stepScore: 5,
maxScore: 5
},
sourceRequestTime: {
type: 'number',
range: 100,
step: 50,
stepScore: -6,
maxScore: 12
},
interactionTime: {
type: 'number',
range: 1000,
step: 50,
stepScore: -6,
maxScore: 30
},
wxScrollerCount: {
type: 'number',
range: 1,
step: 1,
stepScore: -1,
maxScore: 5
},
wxCellExceedNum: {
type: 'number',
range: 1,
step: 1,
stepScore: -1,
maxScore: 5
},
wxMaxDeepVDomLayer: {
type: 'number',
range: 15,
step: 1,
stepScore: -2,
maxScore: 10
},
wxWrongImgSizeCount: {
type: 'number',
range: 0,
step: 1,
stepScore: -3,
maxScore: 15
},
wxEmbedCount: {
type: 'number',
range: 3,
step: 1,
stepScore: -3,
maxScore: 15
},
wxLargeImgMaxCount: {
type: 'number',
range: 0,
step: 1,
stepScore: -2,
maxScore: 10
},
wxImgUnRecycleCount: {
type: 'number',
range: 0,
step: 1,
stepScore: -2,
maxScore: 10
},
wxCellUnReUseCount: {
type: 'number',
range: 0,
step: 1,
stepScore: -2,
maxScore: 10
},
wxCellDataUnRecycleCount: {
type: 'number',
range: 0,
step: 1,
stepScore: -2,
maxScore: 10
},
wxMaxComponentCount: {
type: 'number',
range: 100,
step: 20,
stepScore: -1,
maxScore: 10
}
},
performanceScoreTextMap: {
JSTemplateSize: {
name: '渲染JSBundle大小 (wxBundleSize)',
tips: ['查看文档:<a href="http://mwpo.taobao.net/native-render/bundlesize.html" target="_blank">减少 bundleSize 大小</a>']
},
JSDataPrefetch: {
name: '业务JSBundle是否预加载 (wxJSDataPrefetchSuccess)',
tips: ['查看文档:<a href="http://h5.alibaba-inc.com/awp/StartPackageApp.html" target="_blank">使用预加载</a>']
},
sourceRequestTime: {
name: '请求资源耗时',
tips: ['暂无']
},
interactionTime: {
name: '可交互时间',
tips: ['暂无']
},
wxScrollerCount: {
name: '使用scroller个数 (wxScrollerCount)',
tips: ['scroller是没有view回收机制的,长列表内存容易oom', '使用ListView、recycleView替代']
},
wxCellExceedNum: {
name: '超大cell个数 (wxCellExceedNum)',
tips: ['超大cell一般指宽高均大于屏幕宽高1/2的cell,需控制数量']
},
wxMaxDeepVDomLayer: {
name: 'View最大层级 (wxMaxDeepVDomLayer)',
tips: ['同dom结点最大层级,在设备上实际渲染的view最大层级']
},
wxWrongImgSizeCount: {
name: '图片和view大小不匹配个数 (wxWrongImgSizeCount)',
tips: ['投放的图片尺寸大于实际view的的大小,建议图片进行裁剪,减少不必要的内存占用', '使用analyzer或者devtool有详细的url和尺寸提示']
},
wxEmbedCount: {
name: 'Embed 模块个数 (wxEmbedCount)',
tips: ['Embed不建议太多(3个)']
},
wxLargeImgMaxCount: {
name: '大图个数 (wxLargeImgMaxCount)',
tips: ['大图一般指图片大小>1080*720','减少大图的投放,能有效降低应用内存占用']
},
wxImgUnRecycleCount: {
name: '未开启图片自动回收imgview的个数 (wxImgUnRecycleCount)',
tips: ['Imageview没有开启图片自动回收机制,内存非常容易oom']
},
wxCellUnReUseCount: {
name: '没有开启复用cell的个数 (wxCellUnReUseCount)',
tips: ['暂无']
},
wxCellDataUnRecycleCount: {
name: '内容不回收的cell组件个数 (wxCellDataUnRecycleCount)',
tips: ['暂无']
},
wxMaxComponentCount: {
name: '组件个数(wxMaxComponentCount)',
tips: [
'持有组件个数峰值,在布局时layout造成很大压力,对fps和可交互时间都有很大影响',
'和wxMaxDeepVDomLayer一起,是影响渲染速度的两大因素',
'减少不必要的节点数'
]
}
}
}
const getters = {
}
const actions = {
updateToggle (context: { commit: Commit, state: State }, toggle: {value: boolean, name: string}) {
context.commit(types.UPDATE_ANALYZE_TOGGLE, toggle)
},
updateDefaultCapture (context: { commit: Commit, state: State }, value: any) {
context.commit(types.UPDATE_ANALYZE_DEFAULT_CAPTURE, value)
},
updateDefaultHistory (context: { commit: Commit, state: State }, value: any) {
context.commit(types.UPDATE_ANALYZE_DEFAULT_HISTORY, value)
},
updateCaptures (context: { commit: Commit, state: State }, value: any) {
context.commit(types.UPDATE_ANALYZE_CAPTURES, value)
},
updateHistorys (context: { commit: Commit, state: State }, value: any) {
context.commit(types.UPDATE_ANALYZE_HISTORYS, value)
},
updateApmData (context: { commit: Commit, state: State }, value: any) {
context.commit(types.UPDATE_ANALYZE_APMDATA, value)
}
}
const mutations = {
[types.UPDATE_ANALYZE_TOGGLE] (state: State, toggle: {value: boolean, name: string}) {
state[toggle.name] = toggle.value
},
[types.UPDATE_ANALYZE_DEFAULT_CAPTURE] (state: State, value: any) {
state.defaultCapture = value
},
[types.UPDATE_ANALYZE_DEFAULT_HISTORY] (state: State, value: any) {
state.defaultHistory = value
},
[types.UPDATE_ANALYZE_HISTORYS] (state: State, value: any) {
state.historys = value
},
[types.UPDATE_ANALYZE_CAPTURES] (state: State, value: any) {
state.captures = value
},
[types.UPDATE_ANALYZE_APMDATA] (state: State, data: any) {
state.apmData = data.value
let historyLen = state.historys.length
let replace = false
for (let instance in data.value) {
if (data.value[instance].properties.wxBizID) {
console.log('Add history', data.value[instance].properties.wxBizID)
for (let i = 0; i < historyLen; i++) {
if (state.historys[i].key === instance) {
replace = true
state.historys[i] = {
key: instance,
value: data.value[instance].properties.wxBizID,
data: Object.assign(data.value[instance], { device: data.device }),
time: data.time
}
break
}
}
if (!replace) {
state.historys.unshift({
key: instance,
value: data.value[instance].properties.wxBizID,
data: Object.assign(data.value[instance], { device: data.device }),
time: data.time
})
}
}
}
}
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
} | the_stack |
import { ExpectedConditions, browser, element, by } from 'protractor';
import { AddFile } from '../component/add-file';
import { BusyAlert } from '../component/alert';
import { Constants } from '../constants';
import { Deploy } from '../component/deploy';
import { Editor } from '../component/editor';
import { EditorFile } from '../component/editor-file';
import { Login } from '../component/login';
import { OperationsHelper } from '../utils/operations-helper';
import { Test } from '../component/test';
import { Identity } from '../component/identity';
import { IssueIdentity } from '../component/issue-identity';
import { IdentityIssued } from '../component/identity-issued';
import * as fs from 'fs';
import * as chai from 'chai';
import { constants } from 'zlib';
let expect = chai.expect;
describe('Identity', (() => {
let baseTiles: Array<string> = null;
let npmTiles: Array<string> = null;
let sampleOptions;
const networkDetails = Constants.basicSampleNetwork;
const profile = browser.params.profile;
const isFabricTest = (profile !== 'Web Browser');
// Navigate to Editor base page and move past welcome splash
beforeAll(() => {
// Important angular configuration and intial step passage to reach editor
browser.waitForAngularEnabled(false);
OperationsHelper.navigatePastWelcome();
});
afterAll(() => {
browser.waitForAngularEnabled(true);
browser.executeScript('window.sessionStorage.clear();');
browser.executeScript('window.localStorage.clear();');
});
describe('Creating a new business network', (() => {
it('should allow a user to select the basic-sample-network and deploy', () => {
// Click to deploy on desired profile
return Login.deployNewToProfile(profile)
.then(() => {
return Deploy.waitToAppear();
})
.then(() => {
return Deploy.waitToLoadDeployBasisOptions();
})
.then(() => {
return Deploy.selectDeployBasisOption(networkDetails.name);
})
.then(() => {
if (isFabricTest) {
return Deploy.selectUsernameAndSecret('admin', 'adminpw');
}
return;
})
.then(() => {
return Deploy.clickDeploy();
})
.then(() => {
return Deploy.waitToDisappear(isFabricTest);
})
.then(() => {
return BusyAlert.waitToDisappear();
})
.catch((err) => {
fail(err);
});
}, Constants.vlongwait);
}));
describe('Connecting to the business network', (() => {
it('should let the user connect to their sample network', (() => {
return Login.connectViaIdCard(profile, networkDetails.name)
.then(() => {
// Should now be on main editor page for the business network
return Editor.waitToAppear();
})
.then(() => {
// Should have the correct named busnet once loaded
return Editor.waitForProjectFilesToLoad()
.then(() => {
return Editor.retrieveDeployedPackageName();
})
.then((packageName) => {
expect(packageName).to.be.equal(networkDetails.name);
return Editor.retrieveNavigatorFileNames();
})
.then((filelist: any) => {
expect(filelist).to.be.an('array').lengthOf(4);
filelist.forEach((file) => {
expect(file).to.be.oneOf(networkDetails.files);
});
return Editor.retrieveUpdateBusinessNetworkButtons()
.then((buttonlist: any) => {
expect(buttonlist).to.be.an('array').lengthOf(2);
expect(buttonlist[1]).to.deep.equal({text: Constants.deployButtonLabel, enabled: true});
});
});
})
.catch((err) => {
fail(err);
});
}));
}));
describe('Creating a user to make an identity against', (() => {
it('should open the test page', (() => {
OperationsHelper.click(element(by.id('app_testbutton')))
.then(() => {
return Test.waitToAppear();
})
.then(() => {
return Test.retrieveHeader();
})
.then((header) => {
expect(header).deep.equal(networkDetails.registryHeaders.sampleParticipant);
})
.then(() => {
return Test.retrieveParticipantTypes();
})
.then((participants) => {
participants.forEach((participant) => {
expect(participant).to.be.oneOf(networkDetails.participants.map((el) => {
return el.type;
}));
});
})
.then(() => {
return Test.retrieveAssetTypes();
})
.then((assets) => {
assets.forEach((asset) => {
expect(asset).to.be.oneOf(networkDetails.assets.map((el) => {
return el.type;
}));
});
})
.catch((err) => {
fail(err);
});
}));
it('should create CONGA', (() => {
let conga = fs.readFileSync(networkDetails.participants[0].example, 'utf8').trim();
Test.selectRegistry('participants', networkDetails.participants[0].type)
.then(() => {
return Test.createRegistryItem(conga);
})
.then(() => {
browser.sleep(Constants.shortWait); // give page a second to add the new element
Test.retrieveRegistryItem()
.then((participants) => {
expect(participants).to.be.an('array').lengthOf(1);
let participant = participants[0];
expect(participant).to.have.deep.property('id', 'CONGA');
let data = JSON.parse(participant['data'].toString());
expect(data).to.deep.equal(JSON.parse(conga));
})
.catch((err) => {
fail(err);
});
})
.catch((err) => {
fail(err);
});
}));
}));
describe('Create an identity', () => {
it('should load the identity page', () => {
OperationsHelper.click(element(by.id('dropdownMenu1')))
.then(() => {
return OperationsHelper.click(element(by.id('content')));
})
.then(() => {
return Identity.waitToAppear();
})
.then(() => {
return Identity.getMyIds();
})
.then((myIDs) => {
expect(myIDs.length).to.deep.equal(1);
expect(myIDs[0].id).to.deep.equal('admin');
expect(myIDs[0].status).to.deep.equal(Constants.myIDsStatuses.selected);
})
.then(() => {
return Identity.getAllIds();
})
.then((allIDs) => {
expect(allIDs.length).to.deep.equal(1);
expect(allIDs[0].id).to.deep.equal('admin');
expect(allIDs[0].issued).to.deep.equal('admin (NetworkAdmin)');
expect(allIDs[0].status).to.deep.equal(Constants.allIDsStatuses.activated);
});
});
it('should use the issue identity popup', () => {
return OperationsHelper.click(element(by.id('issueID')))
.then(() => {
IssueIdentity.waitToAppear();
})
.then(() => {
IssueIdentity.inputUserId('king_conga');
})
.then(() => {
IssueIdentity.inputParticipant('CONGA');
})
.then(() => {
IssueIdentity.selectParticipantType('CONGA', networkDetails.participants[0].type);
})
.then(() => {
OperationsHelper.click((element(by.id('createNew'))));
})
.then(() => {
if (isFabricTest) {
return IdentityIssued.waitToAppear()
.then(() => {
IdentityIssued.addToWallet(null);
});
}
})
.then(() => {
OperationsHelper.processExpectedSuccess();
});
});
it('should have the identities issued', () => {
return Identity.getMyIds()
.then((myIDs) => {
expect(myIDs.length).to.deep.equal(2);
expect(myIDs[0].id).to.deep.equal('admin');
expect(myIDs[0].status).to.deep.equal(Constants.myIDsStatuses.selected);
expect(myIDs[1].id).to.deep.equal('king_conga');
expect(myIDs[1].status).to.deep.equal(Constants.myIDsStatuses.inWallet);
})
.then(() => {
return Identity.getAllIds();
})
.then((allIDs) => {
expect(allIDs.length).to.deep.equal(2);
expect(allIDs[0].id).to.deep.equal('admin');
expect(allIDs[0].issued).to.deep.equal('admin (NetworkAdmin)');
expect(allIDs[0].status).to.deep.equal(Constants.allIDsStatuses.activated);
expect(allIDs[1].id).to.deep.equal('king_conga');
expect(allIDs[1].issued).to.deep.equal(`CONGA (${networkDetails.participants[0].type})`);
expect(allIDs[1].status).to.deep.equal(Constants.allIDsStatuses.issued);
});
});
});
describe('Delete a participant related to an ID', () => {
it('should delete the participant', (() => {
OperationsHelper.click(element(by.id('app_testbutton')))
.then(() => {
Test.waitToAppear();
})
.then(() => {
return Test.deleteRegistryItem('CONGA');
});
}));
});
describe('Check that the identity warns that the participant is deleted', () => {
it('should load the identity page and check they are warned', () => {
OperationsHelper.click(element(by.id('dropdownMenu1')))
.then(() => {
return OperationsHelper.click(element(by.id('content')));
})
.then(() => {
return Identity.waitToAppear();
})
.then(() => {
return Identity.getMyIds();
})
.then((myIDs) => {
expect(myIDs.length).to.deep.equal(2);
expect(myIDs[0].id).to.deep.equal('admin');
expect(myIDs[0].status).to.deep.equal(Constants.myIDsStatuses.selected);
expect(myIDs[1].id).to.deep.equal('king_conga');
expect(myIDs[1].status).to.deep.equal(Constants.myIDsStatuses.participantNotFound);
})
.then(() => {
return Identity.getAllIds();
})
.then((allIDs) => {
expect(allIDs.length).to.deep.equal(2);
expect(allIDs[0].id).to.deep.equal('admin');
expect(allIDs[0].issued).to.deep.equal('admin (NetworkAdmin)');
expect(allIDs[0].status).to.deep.equal(Constants.allIDsStatuses.activated);
expect(allIDs[1].id).to.deep.equal('king_conga');
expect(allIDs[1].issued).to.deep.equal(`CONGA (${networkDetails.participants[0].type})`);
expect(allIDs[1].status).to.deep.equal(Constants.allIDsStatuses.participantNotFound);
});
});
});
})); | the_stack |
import { Gltf, GltfType, GltfPrimitive, GltfComponentType } from './gltfType';
import { Mesh } from './Mesh';
import { MeshView } from './meshView';
import { calculateMinMax, MinMax } from './calculateMinMax';
import {
createFloat32Buffer,
createUInt8Buffer,
createUInt16Buffer
} from './createByteBuffer';
import { calculateBufferPadding } from './calculateBufferPadding';
import { UINT16_SIZE_BYTES } from './typeSize';
import { rootMatrix } from './constants';
type AttributeData = {
minMax: MinMax;
buffer: Buffer;
count: number;
componentType: GltfComponentType;
type: GltfType;
target?: GLenum;
};
type ByteOffsetInfo = {
bufferIndex: number; // gltf.buffers index that each attribute refers to
byteLengths: number[]; // length of each attribute
byteOffsets: number[]; // offset of each attribute in the buffer
indexByteLength?: number; // length of the index buffer if available
indexByteOffset?: number; // offset of the index buffer if available
};
// note that these arrays are not always identical lengths!
// for the indices there is only 1 buffer view, but many accessors into the
// same bufferView
type BufferViewAccessorInfo = {
bufferViewIndex: number[];
accessorIndex: number[];
};
/**
* Mostly a copy of createGltf.js, but adds the provided mesh to an existing
* glTF asset instead of creating an entirely new one.
* @param gltf The glTF asset to modify
* @param mesh A single mesh to edit
* @param attributeSuffix Value to append to the name of consecutive
* TEXCOORD / COLOR
* @param relativeToCenter If the mesh should have its positions set relative
* to center or not.
*/
export function addBatchedMeshToGltf(
gltf: Gltf,
mesh: Mesh,
attributeSuffix = '_0',
relativeToCenter = false
) {
// If all the vertex colors are 0 then the mesh does not have vertex colors
const useVertexColors = !mesh.vertexColors.every((e) => e === 0);
if (relativeToCenter) {
mesh.setPositionsRelativeToCenter();
}
// create the buffers
const useUvs = shouldUseUv(mesh.views);
const positionsMinMax = calculateMinMax(mesh.positions, 3);
const positionsBuffer = createFloat32Buffer(mesh.positions);
const normalsMinMax = calculateMinMax(mesh.normals, 3);
const normalsBuffer = createFloat32Buffer(mesh.normals);
let uvsMinMax: MinMax;
let uvsBuffer: Buffer;
if (useUvs) {
uvsMinMax = calculateMinMax(mesh.uvs, 2);
uvsBuffer = createFloat32Buffer(mesh.uvs);
} else {
uvsBuffer = Buffer.alloc(0);
}
let vertexColorsMinMax: MinMax;
let vertexColorsBuffer: Buffer;
if (useVertexColors) {
vertexColorsMinMax = calculateMinMax(mesh.vertexColors, 4);
vertexColorsBuffer = createUInt8Buffer(mesh.vertexColors);
} else {
vertexColorsBuffer = Buffer.alloc(0);
}
const indexBuffer = createUInt16Buffer(mesh.indices);
const attributes: AttributeData[] = [];
attributes.push({
minMax: positionsMinMax,
buffer: positionsBuffer,
type: GltfType.VEC3,
count: mesh.positions.length / 3,
componentType: GltfComponentType.FLOAT
});
attributes.push({
minMax: normalsMinMax,
buffer: normalsBuffer,
type: GltfType.VEC3,
count: mesh.normals.length / 3,
componentType: GltfComponentType.FLOAT
});
if (useUvs) {
attributes.push({
minMax: uvsMinMax,
buffer: uvsBuffer,
type: GltfType.VEC2,
count: mesh.uvs.length / 2,
componentType: GltfComponentType.FLOAT
});
}
if (useVertexColors) {
attributes.push({
minMax: vertexColorsMinMax,
buffer: vertexColorsBuffer,
type: GltfType.VEC4,
count: mesh.vertexColors.length / 4,
componentType: GltfComponentType.UNSIGNED_BYTE
});
}
const byteInfo = addBufferToGltf(gltf, attributes, indexBuffer);
const indexBufferViewAccessorInfo = addIndexBufferViewAndAccessor(
gltf,
mesh,
byteInfo,
mesh.indices
);
const accessorBufferViewAccessorInfo = addAttributeBufferViewsAndAccessors(
gltf,
byteInfo,
attributes
);
addMaterialsToGltf(gltf, mesh);
// add aj new primitive
let primitives: GltfPrimitive[] = [];
for (let i = 0; i < mesh.views.length; ++i) {
let primitive = {
attributes: {
POSITION: accessorBufferViewAccessorInfo.accessorIndex[0],
NORMAL: accessorBufferViewAccessorInfo.accessorIndex[1]
},
material: i,
mode: 4,
indices: indexBufferViewAccessorInfo.accessorIndex[i]
};
// TODO: How do we detect if we should add a _0, _1, _2 suffix?
if (useUvs) {
primitive.attributes['TEXCOORD' + attributeSuffix] =
accessorBufferViewAccessorInfo.accessorIndex[2];
}
if (useVertexColors) {
primitive.attributes['COLOR' + attributeSuffix] =
accessorBufferViewAccessorInfo.accessorIndex[3];
}
primitives.push(primitive);
}
gltf.meshes.push({ primitives: primitives });
gltf.nodes.push({
matrix: rootMatrix,
mesh: gltf.meshes.length - 1
});
}
function shouldUseUv(views: MeshView[]): boolean {
let view;
let material;
for (let i = 0; i < views.length; ++i) {
view = views[i];
material = view.material;
// TODO: Avoid using string typing here, see Material.ts
if (typeof material.baseColor === 'string') {
return true;
}
}
return false;
}
/**
*
* @param gltf The glTF asset to modify
* @param pairs A list of AttributeData, for generating the buffer that will be
* inserted into the glTF asset.
* @param indexBuffer A byte buffer containing a list of indices, if provided
* it will be placed at the end of the generated buffer.
*/
function addBufferToGltf(
gltf: Gltf,
pairs: AttributeData[],
indexBuffer?: Buffer
): ByteOffsetInfo {
gltf.buffers = gltf.buffers == null ? [] : gltf.buffers;
let result: ByteOffsetInfo = {
bufferIndex: gltf.buffers.length,
byteLengths: [],
byteOffsets: []
};
let byteOffset = 0;
for (const pair of pairs) {
result.byteLengths.push(pair.buffer.length);
result.byteOffsets.push(byteOffset);
byteOffset += pair.buffer.length;
}
const vertexBuffer = calculateBufferPadding(
Buffer.concat(pairs.map((v) => v.buffer))
);
let buffer: Buffer;
if (indexBuffer == null) {
buffer = vertexBuffer;
} else {
result.indexByteOffset = vertexBuffer.length;
result.indexByteLength = indexBuffer.length;
buffer = calculateBufferPadding(
Buffer.concat([vertexBuffer, indexBuffer])
);
}
const bufferUri =
'data:application/octet-stream;base64,' + buffer.toString('base64');
gltf.buffers.push({
uri: bufferUri,
byteLength: buffer.length
});
// sanity check / assertion
if (result.byteLengths.length != pairs.length) {
throw new Error('result.byteLengths.length != pairs.length');
}
return result;
}
function addIndexBufferViewAndAccessor(
gltf: Gltf,
mesh: Mesh,
byteInfo: ByteOffsetInfo,
indices: number[]
): BufferViewAccessorInfo {
let result: BufferViewAccessorInfo = {
bufferViewIndex: [],
accessorIndex: []
};
gltf.bufferViews.push({
buffer: byteInfo.bufferIndex,
byteLength: byteInfo.indexByteLength,
byteOffset: byteInfo.indexByteOffset,
target: 34963 // ELEMENT_ARRAY_BUFFER
});
result.bufferViewIndex.push(gltf.bufferViews.length - 1);
for (let i = 0; i < mesh.views.length; ++i) {
const view = mesh.views[i];
const indicesMinMax = calculateMinMax(
indices,
1,
view.indexOffset,
view.indexCount
);
gltf.accessors.push({
bufferView: gltf.bufferViews.length - 1,
byteOffset: UINT16_SIZE_BYTES * view.indexOffset,
componentType: 5123, // UNSIGNED_SHORT
count: view.indexCount,
type: GltfType.SCALAR,
min: indicesMinMax.min,
max: indicesMinMax.max
});
result.accessorIndex.push(gltf.accessors.length - 1);
}
return result;
}
function addAttributeBufferViewsAndAccessors(
gltf: Gltf,
byteInfo: ByteOffsetInfo,
attributes: AttributeData[]
): BufferViewAccessorInfo {
const buffersIndex = byteInfo.bufferIndex;
let result: BufferViewAccessorInfo = {
bufferViewIndex: [],
accessorIndex: []
};
for (let i = 0; i < attributes.length; ++i) {
const attrib = attributes[i];
const byteLengths = byteInfo.byteLengths;
const byteOffsets = byteInfo.byteOffsets;
const target = attrib.target == null ? 34962 : attrib.target;
gltf.bufferViews.push({
buffer: buffersIndex,
byteLength: byteLengths[i],
byteOffset: byteOffsets[i],
target: target
});
gltf.accessors.push({
bufferView: gltf.bufferViews.length - 1,
byteOffset: 0,
componentType: attrib.componentType,
count: attrib.count,
type: attrib.type,
min: attrib.minMax.min,
max: attrib.minMax.max
});
result.bufferViewIndex.push(gltf.bufferViews.length - 1);
result.accessorIndex.push(gltf.accessors.length - 1);
}
return result;
}
function addMaterialsToGltf(gltf: Gltf, mesh: Mesh) {
for (const view of mesh.views) {
let transparent = false;
let material = view.material;
let baseColorFactor = material.baseColor;
// TODO: Avoid stringly typed code, see Material.ts / createGltf.js
// 'If the baseColor uri is a string pointing to a file'
if (typeof material.baseColor === 'string') {
baseColorFactor = [1.0, 1.0, 1.0, 1.0];
gltf.samplers.push({
magFilter: 9729, // LINEAR
minFilter: 9729, // LINEAR
wrapS: 10497, // REPEAT
wrapT: 10497 // REPEAT
});
gltf.images.push({ uri: material.baseColor });
gltf.textures.push({
sampler: 0,
source: gltf.images.length - 1
});
} else {
transparent = material.baseColor[3] < 1.0;
}
const alphaMode = transparent ? 'BLEND' : 'OPAQUE';
gltf.materials.push({
pbrMetallicRoughness: {
baseColorFactor: baseColorFactor,
roughnessFactor: 1.0,
metallicFactor: 0.0
},
alphaMode: alphaMode,
doubleSided: transparent
});
}
} | the_stack |
import * as db from '../util/db';
export type BatchStatus = 'created' | 'paraphrasing' | 'validating' | 'complete';
export interface Row {
id : number;
id_hash : string;
owner : number;
name : string;
language : string;
submissions_per_hit : number;
status : BatchStatus;
}
export type OptionalFields = 'language' | 'submissions_per_hit' | 'status';
export interface ParaphraseInputRow {
id : number;
batch : number;
hit_id : number;
thingtalk : string;
sentence : string;
}
export interface ParaphraseSubmissionRow {
example_id : number;
submission_id : string;
program_id : number;
target_count : number;
accept_count : number;
reject_count : number;
}
export type ParaphraseSubmissionOptionalFields = 'target_count' | 'accept_count' | 'reject_count';
export interface ValidationInputRow {
id : number;
batch : number;
hit_id : number;
type : 'real' | 'fake-same' | 'fake-different';
program_id : number;
example_id : number|null;
paraphrase : string|null;
}
export interface ValidationSubmissionRow {
validation_sentence_id : number;
submission_id : string;
answer : 'same' | 'different';
}
export async function create<T extends db.Optional<Row, OptionalFields>>(dbClient : db.Client, batch : db.WithoutID<T>) : Promise<db.WithID<T>> {
return db.insertOne(dbClient, 'insert into mturk_batch set ?', [batch]).then((id) => {
batch.id = id;
return batch as db.WithID<T>;
});
}
export async function updateBatch(dbClient : db.Client, batchId : number, batch : Partial<Row>) {
await db.query(dbClient, `update mturk_batch set ? where id = ?`, [batch, batchId]);
}
export type ValidationInputCreateRecord = [
ValidationInputRow['batch'],
ValidationInputRow['hit_id'],
ValidationInputRow['type'],
ValidationInputRow['program_id'],
ValidationInputRow['example_id'],
ValidationInputRow['paraphrase']
];
export async function createValidationHITs(dbClient : db.Client, hits : ValidationInputCreateRecord[]) {
await db.query(dbClient, `insert into mturk_validation_input(batch,hit_id,type,program_id,example_id,paraphrase) values ?`, [hits]);
}
export async function getHIT(dbClient : db.Client, batch : number, hitId : number) : Promise<ParaphraseInputRow[]> {
return db.selectAll(dbClient, 'select * from mturk_input where batch = ? and hit_id = ? order by id', [batch, hitId]);
}
export async function getBatch(dbClient : db.Client, batchId : number) : Promise<ParaphraseInputRow[]> {
return db.selectAll(dbClient, `select * from mturk_input where batch = ?`, [batchId]);
}
export async function getBatchDetails(dbClient : db.Client, batchIdHash : string) : Promise<Row> {
return db.selectOne(dbClient, `select * from mturk_batch where id_hash = ?`, [batchIdHash]);
}
export async function getBatchDetailsById(dbClient : db.Client, batchId : number) : Promise<Row> {
return db.selectOne(dbClient, `select * from mturk_batch where id = ?`, [batchId]);
}
export async function getValidationHIT(dbClient : db.Client, batch : number, hitId : number) : Promise<Array<ValidationInputRow & { synthetic : string }>> {
return db.selectAll(dbClient, `select mvi.*, mi.sentence as synthetic
from mturk_validation_input mvi, mturk_input mi
where mvi.batch = ? and mvi.hit_id = ? and mi.id = mvi.program_id
order by mvi.program_id, mvi.id`,
[batch, hitId]);
}
export async function logSubmission(dbClient : db.Client, token : string, batch : number, hit : number, worker : string) {
const log = [token, batch, hit, worker];
await db.insertOne(dbClient, 'insert into mturk_log(submission_id,batch,hit,worker) values (?)', [log]);
}
export async function logValidationSubmission(dbClient : db.Client, token : string, batch : number, hit : number, worker : string) {
const log = [token, batch, hit, worker];
await db.insertOne(dbClient, 'insert into mturk_validation_log(submission_id,batch,hit,worker) values (?)', [log]);
}
export async function getExistingValidationSubmission(dbClient : db.Client, batch : number, hit : number, worker : string) : Promise<Array<{ submission_id : string }>> {
return db.selectAll(dbClient, `select submission_id from mturk_validation_log
where batch = ? and hit = ? and worker = ? for update`,
[batch, hit, worker]);
}
export async function insertSubmission(dbClient : db.Client, submissions : Array<db.Optional<ParaphraseSubmissionRow, ParaphraseSubmissionOptionalFields>>) {
if (submissions.length === 0)
return;
const KEYS = ['submission_id', 'example_id', 'program_id', 'target_count', 'accept_count', 'reject_count'] as const;
const arrays : any[] = [];
submissions.forEach((ex) => {
const vals = KEYS.map((key) => ex[key]);
arrays.push(vals);
});
await db.insertOne(dbClient, 'insert into mturk_output(' + KEYS.join(',') + ') '
+ 'values ?', [arrays]);
}
export async function insertValidationSubmission(dbClient : db.Client, submissions : ValidationSubmissionRow[]) {
if (submissions.length === 0)
return Promise.resolve();
const KEYS = ['submission_id', 'validation_sentence_id', 'answer'] as const;
const arrays : any[] = [];
submissions.forEach((ex) => {
const vals = KEYS.map((key) => ex[key]);
arrays.push(vals);
});
return db.insertOne(dbClient, 'insert into mturk_validation_output(' + KEYS.join(',') + ') '
+ 'values ?', [arrays]);
}
export async function markSentencesGood(dbClient : db.Client, exampleIds : number[]) {
if (exampleIds.length === 0)
return;
await db.query(dbClient, `update mturk_output set accept_count = accept_count + 1
where example_id in (?)`, [exampleIds]);
await db.query(dbClient, `update example_utterances ex, mturk_output mo
set ex.flags = if(ex.flags = '', 'training', concat_ws(',', 'training', ex.flags))
where ex.id in (?) and ex.id = mo.example_id and mo.accept_count >= mo.target_count
and mo.reject_count = 0`, [exampleIds]);
}
export async function markSentencesBad(dbClient : db.Client, exampleIds : number[]) {
if (exampleIds.length === 0)
return;
await db.query(dbClient, `update mturk_output set reject_count = reject_count + 1
where example_id in (?)`, [exampleIds]);
await db.query(dbClient, `update example_utterances ex
set ex.flags = trim(both ',' from replace(concat(',', ex.flags, ','), ',training,', ','))
where ex.id in (?)`, [exampleIds]);
}
export interface UnvalidatedRow {
paraphrase_id : number;
utterance : string;
synthetic_id : number;
synthetic : string;
target_code : string;
}
export function streamUnvalidated(dbClient : db.Client, batch : number) {
return dbClient.query(`select
ex.id as paraphrase_id, ex.utterance,
m_in.id as synthetic_id, m_in.sentence as synthetic, m_in.thingtalk as target_code
from example_utterances ex, mturk_output mout, mturk_input m_in,
mturk_log log where log.batch = ? and mout.example_id = ex.id and
(mout.accept_count + mout.reject_count) < mout.target_count and
not find_in_set('training', ex.flags) and
mout.submission_id = log.submission_id and m_in.id = mout.program_id
order by m_in.id`, batch);
}
export async function autoApproveUnvalidated(dbClient : db.Client, batch : number) {
await db.query(dbClient, `update example_utterances ex, mturk_output mout,
set ex.flags = if(ex.flags = '', 'training', concat_ws(',', 'training', ex.flags))
where mout.batch = ? and mout.example_id = ex.id and
mout.reject_count = 0 and mout.submission_id = log.submission_id
and not find_in_set('training', ex.flags)`, [batch]);
}
type BatchRow = Pick<Row, "id"|"id_hash"|"owner"|"name"|"submissions_per_hit"|"status"> & {
owner_name : string;
input_count : number;
submissions : number;
validated : number;
};
export async function getBatches(dbClient : db.Client) : Promise<BatchRow[]> {
return db.selectAll(dbClient, `select mturk_batch.id, mturk_batch.id_hash, mturk_batch.owner, mturk_batch.name,
submissions_per_hit, status, organizations.name as owner_name,
(select count(*) from mturk_input where batch = mturk_batch.id) as input_count,
(select count(mout.example_id) from mturk_output mout,
mturk_log log where log.batch= mturk_batch.id
and mout.submission_id = log.submission_id) as submissions,
(select count(mout.example_id)
from mturk_output mout, mturk_log log where
log.batch= mturk_batch.id and (mout.accept_count + mout.reject_count) >= mout.target_count
and mout.submission_id = log.submission_id) as validated
from mturk_batch join organizations on mturk_batch.owner = organizations.id`);
}
export async function getBatchesForOwner(dbClient : db.Client, ownerId : number) : Promise<Array<Omit<BatchRow, "owner_name">>> {
return db.selectAll(dbClient, `select mturk_batch.id, mturk_batch.id_hash, mturk_batch.owner, mturk_batch.name,
submissions_per_hit, status,
(select count(*) from mturk_input where batch = mturk_batch.id) as input_count,
(select count(mout.example_id) from mturk_output mout,
mturk_log log where log.batch= mturk_batch.id
and mout.submission_id = log.submission_id) as submissions,
(select count(mout.example_id)
from mturk_output mout, mturk_log log where
log.batch= mturk_batch.id and (mout.accept_count + mout.reject_count) >= mout.target_count
and mout.submission_id = log.submission_id) as validated
from mturk_batch where owner = ?`, [ownerId]);
}
export function streamHITs(dbClient : db.Client, batch : number) {
return dbClient.query(`select hit_id from mturk_input where batch = ? group by hit_id`, batch);
}
export function streamValidationHITs(dbClient : db.Client, batch : number) {
return dbClient.query(`select hit_id from mturk_validation_input where batch = ? group by hit_id`, batch);
} | the_stack |
import { View, Action, EventCodeLanguage } from "../types";
import { getAdditionalBackgroundCode, setAdditionalBackgroundCode, getAudioSelectCode, setAudioSelectCode, _fixPotentiallyOldBoard, _makeDefaultBoard } from "../boards";
import * as React from "react";
import * as ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { updateWindowTitle } from "../utils/browser";
import { Editor } from "../renderer";
import { Details } from "../views/details";
import { Settings } from "../views/settings";
import { About } from "../views/about";
import { ModelViewer } from "../views/models";
import { EventsView } from "../views/eventsview";
import { CreateASMEventView } from "../views/createevent_asm";
import { CreateCEventView } from "../views/createevent_c";
import { StringsViewer } from "../views/strings";
import { GamesharkView } from "../views/gameshark";
import { BoardMenu } from "../boardmenu";
import { Notification, NotificationBar, NotificationButton, NotificationColor } from "../components/notifications";
import { Header } from "../header";
import { ToolWindow } from "../toolwindow";
import { Toolbar } from "../toolbar";
import { SpaceProperties } from "../spaceproperties";
import { BoardProperties } from "../boardproperties";
import "../utils/onbeforeunload";
import "../events/builtin/events.common";
import "../events/builtin/MP1/events.MP1";
import "../events/builtin/MP2/events.MP2";
import "../events/builtin/MP3/events.MP3";
import "file-saver";
import { DebugView } from "../views/debug";
import { AudioViewer } from "../views/audio";
import { BasicCodeEditorView } from "../views/basiccodeeditorview";
import { IDecisionTreeNode } from "../ai/aitrees";
import { DecisionTreeEditor } from "../ai/aieditor";
import { isElectron } from "../utils/electron";
import { blockUI, showMessage, changeDecisionTree, undo, redo, clearUndoHistory } from "./appControl";
import { Blocker } from "../components/blocker";
import { killEvent } from "../utils/react";
import { getDefaultAdditionalBgCode, testAdditionalBgCodeAllGames } from "../events/additionalbg";
import { getDefaultGetAudioCode, testGetAudioCodeAllGames } from "../events/getaudiochoice";
import { SpriteView } from "../views/sprites";
import { store } from "./store";
import { selectCurrentAction, selectCurrentView, selectNotifications, selectRomLoaded, selectUpdateExists, setHideUpdateNotification, setUpdateExistsAction } from "./appState";
import { useCallback } from "react";
import { useAppDispatch, useAppSelector } from "./hooks";
import { selectBlocked, selectConfirm, selectMessage, selectMessageHTML, selectOnBlockerFinished, selectPrompt } from "./blocker";
import { addEventToLibraryAction, selectBoards, selectCurrentBoard, setBoardsAction } from "./boardState";
import { BasicErrorBoundary } from "../components/BasicErrorBoundary";
import { useHotkeys } from "react-hotkeys-hook";
import { getSavedBoards, getSavedEvents } from "../utils/localstorage";
import { IEvent } from "../events/events";
import { createCustomEvent, ICustomEvent } from "../events/customevents";
/* eslint-disable jsx-a11y/anchor-is-valid */
interface IPP64AppState {
aiTree: IDecisionTreeNode[] | null;
error: Error | null;
errorInfo: React.ErrorInfo | null;
initialized: boolean;
}
export class PP64App extends React.Component<{}, IPP64AppState> {
state: IPP64AppState = {
aiTree: null,
error: null,
errorInfo: null,
initialized: false,
}
render() {
if (this.state.error) {
return (
<ErrorDisplay error={this.state.error} errorInfo={this.state.errorInfo}
onClearError={() => {
this.setState({ error: null, errorInfo: null });
blockUI(false);
}} />
);
}
if (!this.state.initialized) {
return null; // Init in componentDidMount
}
return <PP64AppInternal {...this.state} />;
}
componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
_onError(this, error, errorInfo);
}
componentDidMount() {
if (isElectron) {
try {
const ipcRenderer = (window as any).require("electron").ipcRenderer;
ipcRenderer.on("update-check-hasupdate", this._onUpdateCheckHasUpdate);
ipcRenderer.send("update-check-start");
}
catch (e) {
console.error("Auto update failed in componentDidMount: ", e);
}
}
if (!this.state.initialized) {
initializeState();
this.setState({ initialized: true });
}
}
componentWillUnmount() {
if (isElectron) {
try {
const ipcRenderer = (window as any).require("electron").ipcRenderer;
ipcRenderer.removeListener("update-check-hasupdate", this._onUpdateCheckHasUpdate);
}
catch (e) {
console.error("Auto update failed in componentWillUnmount: ", e);
}
}
}
_onUpdateCheckHasUpdate = () => {
store.dispatch(setUpdateExistsAction(true));
}
};
interface PP64AppInternalProps {
aiTree: IDecisionTreeNode[] | null;
error: Error | null;
errorInfo: React.ErrorInfo | null;
}
function PP64AppInternal(props: PP64AppInternalProps) {
const currentView = useAppSelector(selectCurrentView);
const blocked = useAppSelector(selectBlocked);
const boards = useAppSelector(selectBoards);
const currentBoard = useAppSelector(selectCurrentBoard);
const currentAction = useAppSelector(selectCurrentAction);
const romLoaded = useAppSelector(selectRomLoaded);
updateWindowTitle(currentBoard.name);
usePP64Hotkeys();
let mainView;
switch (currentView) {
case View.EDITOR:
mainView = <Editor />;
break;
case View.DETAILS:
mainView = <Details board={currentBoard} />;
break;
case View.SETTINGS:
mainView = <Settings />;
break;
case View.ABOUT:
mainView = <About />;
break;
case View.MODELS:
mainView = <ModelViewer />;
break;
case View.SPRITES:
mainView = <SpriteView />;
break;
case View.EVENTS:
mainView = (
<BasicErrorBoundary>
<EventsView />
</BasicErrorBoundary>
);
break;
case View.CREATEEVENT_ASM:
mainView = <CreateASMEventView />;
break;
case View.CREATEEVENT_C:
mainView = <CreateCEventView />;
break;
case View.STRINGS:
mainView = <StringsViewer />;
break;
case View.PATCHES:
mainView = <GamesharkView />;
break;
case View.DEBUG:
mainView = <DebugView />;
break;
case View.AUDIO:
mainView = <AudioViewer />;
break;
case View.ADDITIONAL_BGS:
mainView = <BasicCodeEditorView board={currentBoard}
title="Additional Background Configuration"
getExistingCode={() => getAdditionalBackgroundCode(currentBoard)}
getDefaultCode={lang => getDefaultAdditionalBgCode(lang)}
onSetCode={(code, lang) => setAdditionalBackgroundCode(code, lang)}
canSaveAndExit={(code, lang) => testAdditionalBgCodeAllGames(code, lang, currentBoard)} />;
break;
case View.AUDIO_SELECTION_CODE:
mainView = <BasicCodeEditorView board={currentBoard}
title="Background Music Selection Code"
getExistingCode={() => getAudioSelectCode(currentBoard)}
getDefaultCode={lang => getDefaultGetAudioCode(lang)}
onSetCode={(code, lang) => setAudioSelectCode(code, lang)}
canSaveAndExit={(code, lang) => testGetAudioCodeAllGames(code, lang, currentBoard)} />;
break;
}
let sidebar;
switch (currentView) {
case View.EDITOR:
case View.DETAILS:
case View.EVENTS:
sidebar = (
<div className="sidebar">
<BoardMenu
boards={boards} />
</div>
);
break;
}
let bodyClass = "body";
if (currentAction === Action.ERASE)
bodyClass += " eraser";
return (
<div className={bodyClass}>
<PP64NotificationBar />
<Header view={currentView} romLoaded={romLoaded} board={currentBoard} />
<div className="content"
onKeyDownCapture={blocked ? killEvent : undefined}>
{sidebar}
<div className="main">
{mainView}
<div className="mainOverlay">
<ToolWindow name="Toolbox" position="TopRight"
visible={currentView === View.EDITOR}>
<Toolbar currentAction={currentAction}
gameVersion={currentBoard.game}
boardType={currentBoard.type} />
</ToolWindow>
<ToolWindow name="Space Properties" position="BottomRight"
visible={currentView === View.EDITOR}>
<SpaceProperties
gameVersion={currentBoard.game}
boardType={currentBoard.type} />
</ToolWindow>
<ToolWindow name="Board Properties" position="BottomLeft"
visible={currentView === View.EDITOR}>
<BoardProperties currentBoard={currentBoard} />
</ToolWindow>
{props.aiTree &&
<ToolWindow name="AI Decision Tree" position="TopLeft"
visible={currentView === View.EDITOR}
canClose onCloseClick={() => changeDecisionTree(null)}>
<DecisionTreeEditor root={props.aiTree} />
</ToolWindow>
}
</div>
<div id="dragZone"></div>
</div>
</div>
<PP64Blocker />
</div>
);
}
function usePP64Hotkeys(): void {
const currentView = useAppSelector(selectCurrentView);
const blocked = useAppSelector(selectBlocked);
const allowUndoRedo = !blocked && currentView === View.EDITOR;
useHotkeys("ctrl+z", (event, handler) => {
undo();
}, {
enabled: allowUndoRedo,
enableOnTags: ["INPUT", "SELECT"],
});
useHotkeys("ctrl+y", (event, handler) => {
redo();
}, {
enabled: allowUndoRedo,
enableOnTags: ["INPUT", "SELECT"],
});
}
function PP64NotificationBar() {
const dispatch = useAppDispatch();
const onUpdateNotificationClosed = useCallback(() => {
dispatch(setHideUpdateNotification(true));
}, [dispatch]);
const onUpdateNotificationInstallClicked = useCallback(() => {
dispatch(setHideUpdateNotification(true));
blockUI(true);
if (isElectron) {
const ipcRenderer = (window as any).require("electron").ipcRenderer;
ipcRenderer.send("update-check-doupdate");
}
}, [dispatch]);
const updateHideNotification = useAppSelector(state => state.app.updateHideNotification);
const updateExists = useAppSelector(selectUpdateExists);
const notifications = useAppSelector(selectNotifications).slice();
if (updateExists && !updateHideNotification) {
notifications.push(
<Notification key="update"
color={NotificationColor.Blue}
onClose={onUpdateNotificationClosed}>
An update is available.
<NotificationButton onClick={onUpdateNotificationInstallClicked}>
Install
</NotificationButton>
</Notification>
);
}
return (
<NotificationBar>
{notifications}
</NotificationBar>
);
}
function PP64Blocker() {
const blocked = useAppSelector(selectBlocked);
const message = useAppSelector(selectMessage);
const messageHTML = useAppSelector(selectMessageHTML);
const prompt = useAppSelector(selectPrompt);
const confirm = useAppSelector(selectConfirm);
const onBlockerFinished = useAppSelector(selectOnBlockerFinished);
if (!blocked) {
return null;
}
return <Blocker
message={message}
messageHTML={messageHTML}
prompt={prompt}
confirm={confirm}
onAccept={(value?: string) => {
showMessage();
if (onBlockerFinished) {
onBlockerFinished(value);
}
}}
onCancel={() => {
showMessage();
if (onBlockerFinished) {
onBlockerFinished();
}
}}
onForceClose={() => blockUI(false)} />
}
// Capture errors that don't happen during rendering.
window.onerror = function (msg, url, lineNo, columnNo, error) {
const app = (window as any)._PP64instance;
if (error) {
if (app) {
_onError(app, error, null);
}
else { // Occurred during ReactDOM.render?
alert(error);
}
}
};
function initializeState(): void {
let boards;
const cachedBoards = getSavedBoards();
if (cachedBoards && cachedBoards.length) {
boards = cachedBoards.map(board => _fixPotentiallyOldBoard(board));
}
else {
boards = [ _makeDefaultBoard(1) ];
}
store.dispatch(setBoardsAction({ boards }));
const cachedEvents = getSavedEvents();
if (cachedEvents && cachedEvents.length) {
cachedEvents.forEach((eventObj: IEvent) => {
if (!eventObj || !(eventObj as ICustomEvent).asm)
return;
try {
const customEventObj = eventObj as ICustomEvent;
const customEvent = createCustomEvent(
customEventObj.language || EventCodeLanguage.MIPS,
customEventObj.asm
);
store.dispatch(addEventToLibraryAction({ event: customEvent }));
}
catch (e) {
// Just let the error slide, event format changed or something?
console.error("Error reading cached event: " + e.toString());
}
});
}
clearUndoHistory();
}
const body = document.getElementById("body");
ReactDOM.render(
<Provider store={store}>
<PP64App ref={app => (window as any)._PP64instance = app} />
</Provider>,
body
);
function _onError(app: PP64App, error: Error, errorInfo: React.ErrorInfo | null) {
app.setState({
error,
errorInfo,
});
console.error(error, errorInfo);
}
interface IErrorDisplayProps {
error: Error,
errorInfo: React.ErrorInfo | null,
onClearError(): void;
}
function ErrorDisplay(props: IErrorDisplayProps) {
const componentStack = props.errorInfo && props.errorInfo.componentStack;
return (
<div className="errorDiv selectable">
<h2>Hey, it seeems like something's wrong in
<span className="errorStrikeoutText">Mushroom Village</span>
PartyPlanner64.</h2>
<p>Please
<a href="https://github.com/PartyPlanner64/PartyPlanner64/issues" target="_blank" rel="noopener noreferrer">
file an issue
</a>
with the following details, and refresh the page. Or
<a href="#" onClick={props.onClearError}>click here</a>
to dismiss this error, but you may be in a bad state.
</p>
<pre>{props.error.toString()}</pre>
{props.error.stack ? <React.Fragment>
<div>Stack Error Details:</div>
<pre>{props.error.stack}</pre>
</React.Fragment>
: null
}
<div>Component Stack Error Details:</div>
<pre>{componentStack || "N/A"}</pre>
</div>
);
} | the_stack |
'use strict'
import * as path from 'path';
import * as fs from 'fs';
import { workspace, Uri, commands, WorkspaceFolder, Event, EventEmitter, Disposable, window } from 'vscode';
import { spawn } from 'child_process';
import { Tracer } from './tracer';
const EntrySeparator = '471a2a19-885e-47f8-bff3-db43a3cdfaed';
const FormatSeparator = 'e69fde18-a303-4529-963d-f5b63b7b1664';
function formatDate(timestamp: number): string {
return (new Date(timestamp * 1000)).toDateString();
}
export interface GitRepo {
root: string;
}
export enum GitRefType {
Head,
RemoteHead,
Tag
}
export interface GitRef {
type: GitRefType;
name?: string;
commit?: string;
}
export interface GitLogEntry {
subject: string;
hash: string;
ref: string;
author: string;
email: string;
date: string;
stat?: string;
lineInfo?: string;
}
export interface GitCommittedFile {
fileUri: Uri;
oldFileUri: Uri;
gitRelativePath: string;
gitRelativeOldPath: string;
status: string;
}
class GitCommittedFileImpl implements GitCommittedFile {
constructor(private _repo: GitRepo, readonly gitRelativePath: string, readonly gitRelativeOldPath: string, readonly status: string) {
}
get fileUri(): Uri {
return Uri.file(path.join(this._repo.root, this.gitRelativePath));
}
get oldFileUri(): Uri {
return Uri.file(path.join(this._repo.root, this.gitRelativeOldPath));
}
}
export interface GitBlameItem {
file: Uri;
line: number;
hash?: string;
subject?: string;
body?: string;
author?: string;
date?: string;
relativeDate?: string;
email?: string;
stat?: string
}
function singleLined(value: string): string {
return value.replace(/\r?\n|\r/g, ' ');
}
export class GitService {
private _gitRepos: GitRepo[] = [];
private _onDidChangeGitRepositories = new EventEmitter<GitRepo[]>();
private _disposables: Disposable[] = [];
private _gitPath: string = workspace.getConfiguration('git').get('path');
constructor() {
this._disposables.push(this._onDidChangeGitRepositories);
}
get onDidChangeGitRepositories(): Event<GitRepo[]> { return this._onDidChangeGitRepositories.event; }
dispose(): void {
this._disposables.forEach(d => d.dispose());
}
updateGitRoots(wsFolders: WorkspaceFolder[]): void {
// reset repos first. Should optimize it to avoid firing multiple events.
this._gitRepos = [];
commands.executeCommand('setContext', 'hasGitRepo', false);
this._onDidChangeGitRepositories.fire([]);
if (wsFolders) {
wsFolders.forEach(wsFolder => {
this.getGitRepo(wsFolder.uri);
const root = wsFolder.uri.fsPath;
this._scanSubFolders(root);
});
}
}
getGitRepos(): GitRepo[] {
return this._gitRepos;
}
async getGitRepo(uri: Uri): Promise<GitRepo> {
let fsPath = uri.fsPath;
if (fs.statSync(fsPath).isFile()) {
fsPath = path.dirname(fsPath);
}
const repo: GitRepo = this._gitRepos.find(r => fsPath.startsWith(r.root));
if (repo) {
return repo;
}
let root: string = (await this._exec(['rev-parse', '--show-toplevel'], fsPath)).trim();
if (root) {
root = path.normalize(root);
if (this._gitRepos.findIndex((value: GitRepo) => { return value.root == root; }) === -1) {
this._gitRepos.push({ root });
commands.executeCommand('setContext', 'hasGitRepo', true);
this._onDidChangeGitRepositories.fire(this.getGitRepos());
}
}
return root ? { root } : null;
}
async getGitRelativePath(file: Uri) {
const repo: GitRepo = await this.getGitRepo(file);
if (!repo) {
return;
}
let relative: string = path.relative(repo.root, file.fsPath).replace(/\\/g, '/');
return relative === '' ? '.' : relative;
}
async getCurrentBranch(repo: GitRepo): Promise<string> {
if (!repo) {
return null;
}
return (await this._exec(['rev-parse', '--abbrev-ref', 'HEAD'], repo.root)).trim();
}
async getCommitsCount(repo: GitRepo, file?: Uri, author?: string): Promise<number> {
if (!repo) {
return 0;
}
let args: string[] = ['rev-list', '--simplify-merges', '--count', 'HEAD'];
if (author) {
args.push(`--author=${author}`);
}
if (file) {
args.push(await this.getGitRelativePath(file));
}
return parseInt(await this._exec(args, repo.root));
}
async getRefs(repo: GitRepo): Promise<GitRef[]> {
if (!repo) {
return [];
}
const result = await this._exec(['for-each-ref', '--format', '%(refname) %(objectname:short)'], repo.root);
const fn = (line): GitRef | null => {
let match: RegExpExecArray | null;
if (match = /^refs\/heads\/([^ ]+) ([0-9a-f]+)$/.exec(line)) {
return { name: match[1], commit: match[2], type: GitRefType.Head };
} else if (match = /^refs\/remotes\/([^/]+)\/([^ ]+) ([0-9a-f]+)$/.exec(line)) {
return { name: `${match[1]}/${match[2]}`, commit: match[3], type: GitRefType.RemoteHead };
} else if (match = /^refs\/tags\/([^ ]+) ([0-9a-f]+)$/.exec(line)) {
return { name: match[1], commit: match[2], type: GitRefType.Tag };
}
return null;
};
return result.trim().split('\n')
.filter(line => !!line)
.map(fn)
.filter(ref => !!ref) as GitRef[];
}
async getCommittedFiles(repo: GitRepo, leftRef: string, rightRef: string, isStash: boolean): Promise<GitCommittedFile[]> {
if (!repo) {
return [];
}
let args = ['show', '--format=%h', '--name-status', rightRef];
if (leftRef) {
args = ['diff', '--name-status', `${leftRef}..${rightRef}`];
} else if (isStash) {
args.unshift('stash');
}
const result = await this._exec(args, repo.root);
let files: GitCommittedFile[] = [];
result.split(/\r?\n/g).forEach((value, index) => {
if (value) {
let info = value.split(/\t/g);
if (info.length < 2) {
return;
}
let gitRelativePath: string;
let gitRelativeOldPath: string;
const status: string = info[0][0].toLocaleUpperCase();
// A filename
// M filename
// D filename
// RXX file_old file_new
// CXX file_old file_new
switch (status) {
case 'M':
case 'A':
case 'D':
gitRelativeOldPath = info[1];
gitRelativePath = info[1];
break;
case 'R':
case 'C':
gitRelativeOldPath = info[1];
gitRelativePath = info[2];
break;
default:
throw new Error('Cannot parse ' + info);
}
files.push(new GitCommittedFileImpl(repo, gitRelativePath, gitRelativeOldPath, status));
}
});
return files;
}
async getLogEntries(repo: GitRepo, express: boolean, start: number, count: number, branch: string, isStash?: boolean,
file?: Uri, line?: number, author?: string): Promise<GitLogEntry[]> {
Tracer.info(`Get entries. repo: ${repo.root}, express: ${express}, start: ${start}, count: ${count}, branch: ${branch},` +
`isStash: ${isStash}, file: ${file ? file.fsPath : ''}, line: ${line}, author: ${author}`);
if (!repo) {
return [];
}
let format = `--format=${EntrySeparator}`;
if (isStash) {
format += '%gd: ';
}
format += `%s${FormatSeparator}%h${FormatSeparator}%d${FormatSeparator}%aN${FormatSeparator}%ae${FormatSeparator}%ct${FormatSeparator}%cr${FormatSeparator}`;
let args: string[] = [format];
if (!express || !!line) {
args.push('--shortstat');
}
if (isStash) {
args.unshift('stash', 'list');
} else {
args.unshift('log', `--skip=${start}`, `--max-count=${count}`, '--simplify-merges', branch);
if (author) {
args.push(`--author=${author}`);
}
if (file) {
const filePath: string = await this.getGitRelativePath(file);
if (line) {
args.push(`-L ${line},${line}:${filePath}`);
} else {
args.push('--follow', filePath);
}
}
}
const result = await this._exec(args, repo.root);
let entries: GitLogEntry[] = [];
result.split(EntrySeparator).forEach(entry => {
if (!entry) {
return;
}
let subject: string;
let hash: string;
let ref: string;
let author: string;
let email: string;
let date: string;
let stat: string;
let lineInfo: string;
entry.split(FormatSeparator).forEach((value, index) => {
switch (index % 8) {
case 0:
subject = singleLined(value);
break;
case 1:
hash = value;
break;
case 2:
ref = value;
break;
case 3:
author = value;
break;
case 4:
email = value;
break;
case 5:
date = formatDate(parseInt(value));
break;
case 6:
date += ` (${value})`;
break;
case 7:
if (!!line) {
lineInfo = value.trim();
} else {
stat = value.trim();
}
entries.push({ subject, hash, ref, author, email, date, stat, lineInfo });
break;
}
});
});
return entries;
}
async getCommitDetails(repo: GitRepo, ref: string, isStash: boolean): Promise<string> {
if (!repo) {
return null;
}
const format: string = isStash ?
`Stash: %H
Author: %aN <%aE>
AuthorDate: %ad
%s
` :
`Commit: %H
Author: %aN <%aE>
AuthorDate: %ad
Commit: %cN <%cE>
CommitDate: %cd
%s
`;
let details: string = await this._exec(['show', `--format=${format}`, '--no-patch', '--date=local', ref], repo.root);
const body = (await this._exec(['show', '--format=%b', '--no-patch', ref], repo.root)).trim();
if (body) {
details += body + '\r\n\r\n';
}
details += '-----------------------------\r\n\r\n'
details += await this._exec(['show', '--format=', '--stat', ref], repo.root);
return details;
}
async getAuthors(repo: GitRepo): Promise<{ name: string, email: string }[]> {
if (!repo) {
return null;
}
const result: string = (await this._exec(['shortlog', '-se', 'HEAD'], repo.root)).trim();
return result.split(/\r?\n/g).map(item => {
item = item.trim();
let start: number = item.search(/ |\t/);
item = item.substr(start + 1).trim();
start = item.indexOf('<');
const name: string = item.substring(0, start);
const email: string = item.substring(start + 1, item.length - 1);
return { name, email };
});
}
async getBlameItem(file: Uri, line: number): Promise<GitBlameItem> {
const repo: GitRepo = await this.getGitRepo(file);
if (!repo) {
return null;
}
const filePath = file.fsPath;
const result = await this._exec(['blame', `${filePath}`, '-L', `${line + 1},${line + 1}`, '--incremental', '--root'], repo.root);
let hash: string;
let subject: string;
let author: string;
let date: string;
let email: string;
result.split(/\r?\n/g).forEach((line, index) => {
if (index == 0) {
hash = line.split(' ')[0];
} else {
const infoName = line.split(' ')[0];
const info = line.substr(infoName.length).trim();
if (!info) {
return;
}
switch (infoName) {
case 'author':
author = info;
break;
case 'committer-time':
date = (new Date(parseInt(info) * 1000)).toLocaleDateString();
break;
case 'author-mail':
email = info;
break;
case 'summary':
subject = singleLined(info);
break;
default:
break;
}
}
});
if ([hash, subject, author, email, date].some(v => !v)) {
Tracer.warning(`Blame info missed. repo ${repo.root} file ${filePath}:${line} ${hash}` +
` author: ${author}, mail: ${email}, date: ${date}, summary: ${subject}`);
return null;
}
// get additional info: abbrev hash, relative date, body, stat
const addition: string = await this._exec(['show', `--format=%h${FormatSeparator}%cr${FormatSeparator}%b${FormatSeparator}`, '--stat', `${hash}`], repo.root);
//const firstLine = addition.split(/\r?\n/g)[0];
const items = addition.split(FormatSeparator);
hash = items[0];
const relativeDate = items[1];
const body = items[2] ? items[2].trim() : null;
const stat = ` ${items[3].trim()}`;
return { file, line, subject, body, hash, author, date, email, relativeDate, stat };
}
private _scanSubFolders(root: string): void {
const children = fs.readdirSync(root);
children.filter(child => child !== '.git').forEach(async (child) => {
const fullPath = path.join(root, child);
if (fs.statSync(fullPath).isDirectory()) {
if (fs.readdirSync(fullPath).find(v => v === '.git')) {
let gitRoot: string = (await this._exec(['rev-parse', '--show-toplevel'], fullPath)).trim();
if (gitRoot) {
gitRoot = path.normalize(gitRoot);
if (this._gitRepos.findIndex((value: GitRepo) => { return value.root == gitRoot; }) === -1) {
this._gitRepos.push({ root: gitRoot });
commands.executeCommand('setContext', 'hasGitRepo', true);
this._onDidChangeGitRepositories.fire(this.getGitRepos());
}
}
}
//this._scanSubFolders(fullPath);
}
});
}
private async _exec(args: string[], cwd: string): Promise<string> {
const start = Date.now();
let content: string = '';
let gitPath = this._gitPath;
if (!gitPath) {
gitPath = 'git';
}
let gitShow = spawn(gitPath, args, { cwd });
let out = gitShow.stdout;
out.setEncoding('utf8');
return new Promise<string>((resolve, reject) => {
out.on('data', data => content += data);
out.on('end', () => {
resolve(content);
Tracer.verbose(`git command: git ${args.join(' ')} (${Date.now() - start}ms)`);
});
out.on('error', err => {
reject(err);
Tracer.error(`git command failed: git ${args.join(' ')} (${Date.now() - start}ms) ${err.message}`);
});
});
}
} | the_stack |
import moment from 'moment'
import GanttBinarySearch from '../util/binarySearch.service'
import GanttColumnGenerator from './columnGenerator.service'
import {GanttColumnBuilder} from './columnBuilder.factory'
import {GanttColumn} from './column.factory'
import {GanttColumnHeader} from './columnHeader.factory'
import GanttHeadersGenerator from './headersGenerator.service'
import GanttLayout from '../../ui/util/layout.service'
import {Gantt} from '../gantt.factory'
import {IGanttFilterService} from '../../../index'
export class GanttColumnsManager {
static GanttColumnGenerator: GanttColumnGenerator
static GanttHeadersGenerator: GanttHeadersGenerator
static GanttColumnBuilder: { new(columnsManager: GanttColumnsManager): GanttColumnBuilder }
static ganttBinarySearch: GanttBinarySearch
static ganttLayout: GanttLayout
static $filter: IGanttFilterService
gantt: Gantt
from: moment.Moment
to: moment.Moment
columns: GanttColumn[]
visibleColumns: GanttColumn[]
previousColumns: GanttColumn[]
nextColumns: GanttColumn[]
headers: GanttColumnHeader[][]
visibleHeaders: GanttColumnHeader[][]
columnBuilder: GanttColumnBuilder
scrollAnchor: moment.Moment
defaultHeadersFormats = {
year: 'YYYY',
quarter: '[Q]Q YYYY',
month: 'MMMM YYYY',
week: 'w',
day: 'D',
hour: 'H',
minute: 'H:mm',
second: 'H:mm:ss',
millisecond: 'H:mm:ss:SSS'
}
defaultDayHeadersFormats = {day: 'LL', hour: 'H', minute: 'H:mm', second: 'H:mm:ss', millisecond: 'H:mm:ss:SSS'}
defaultYearHeadersFormats = {'year': 'YYYY', 'quarter': '[Q]Q', month: 'MMMM'}
constructor (gantt) {
this.gantt = gantt
this.from = undefined
this.to = undefined
this.columns = []
this.visibleColumns = []
this.previousColumns = []
this.nextColumns = []
this.headers = []
this.visibleHeaders = []
this.scrollAnchor = undefined
this.columnBuilder = new GanttColumnsManager.GanttColumnBuilder(this)
// Add a watcher if a view related setting changed from outside of the Gantt. Update the gantt accordingly if so.
// All those changes need a recalculation of the header columns
this.gantt.$scope.$watchGroup(['viewScale', 'columnWidth', 'timeFramesWorkingMode', 'timeFramesNonWorkingMode', 'fromDate', 'toDate', 'autoExpand', 'taskOutOfRange'], (newValues, oldValues) => {
if (newValues !== oldValues && this.gantt.rendered) {
this.generateColumns()
}
})
this.gantt.$scope.$watchCollection('headers', (newValues, oldValues) => {
if (newValues !== oldValues && this.gantt.rendered) {
this.generateColumns()
}
})
this.gantt.$scope.$watchCollection('headersFormats', (newValues, oldValues) => {
if (newValues !== oldValues && this.gantt.rendered) {
this.generateColumns()
}
})
this.gantt.$scope.$watchGroup(['ganttElementWidth', 'showSide', 'sideWidth', 'maxHeight', 'daily'], (newValues, oldValues) => {
if (newValues !== oldValues && this.gantt.rendered) {
this.updateColumnsMeta()
}
});
(this.gantt.api as any).data.on.load(this.gantt.$scope, () => {
if ((this.from === undefined || this.to === undefined ||
this.from > this.gantt.rowsManager.getDefaultFrom() ||
this.to < this.gantt.rowsManager.getDefaultTo()) && this.gantt.rendered) {
this.generateColumns()
}
this.gantt.rowsManager.sortRows()
});
(this.gantt.api as any).data.on.remove(this.gantt.$scope, () => {
this.gantt.rowsManager.sortRows()
})
this.gantt.api.registerMethod('columns', 'clear', this.clearColumns, this)
this.gantt.api.registerMethod('columns', 'generate', this.generateColumns, this)
this.gantt.api.registerMethod('columns', 'refresh', this.updateColumnsMeta, this)
this.gantt.api.registerMethod('columns', 'getColumnsWidth', this.getColumnsWidth, this)
this.gantt.api.registerMethod('columns', 'getColumnsWidthToFit', this.getColumnsWidthToFit, this)
this.gantt.api.registerMethod('columns', 'getDateRange', this.getDateRange, this)
this.gantt.api.registerEvent('columns', 'clear')
this.gantt.api.registerEvent('columns', 'generate')
this.gantt.api.registerEvent('columns', 'refresh')
}
setScrollAnchor () {
if (this.gantt.scroll.$element && this.columns.length > 0) {
let el = this.gantt.scroll.$element[0]
let center = el.scrollLeft + el.offsetWidth / 2
this.scrollAnchor = this.gantt.getDateByPosition(center)
}
}
scrollToScrollAnchor () {
if (this.columns.length > 0 && this.scrollAnchor !== undefined) {
// Ugly but prevents screen flickering (unlike $timeout)
this.gantt.$scope.$$postDigest(() => {
(this.gantt.api as any).scroll.toDate(this.scrollAnchor)
})
}
}
clearColumns () {
this.setScrollAnchor()
this.from = undefined
this.to = undefined
this.columns = []
this.visibleColumns = []
this.previousColumns = []
this.nextColumns = []
this.headers = []
this.visibleHeaders = [];
(this.gantt.api as any).columns.raise.clear()
}
generateColumns (from?: moment.Moment | Date, to?: moment.Moment | Date) {
if (!from) {
from = this.gantt.options.value('fromDate')
}
if (!to) {
to = this.gantt.options.value('toDate')
}
if (!from || (moment.isMoment(from) && !from.isValid())) {
from = this.gantt.rowsManager.getDefaultFrom()
if (!from) {
return false
}
}
if (!to || (moment.isMoment(to) && !to.isValid())) {
to = this.gantt.rowsManager.getDefaultTo()
if (!to) {
return false
}
}
if (from !== undefined && !moment.isMoment(from)) {
from = moment(from)
}
if (to !== undefined && !moment.isMoment(to)) {
to = moment(to)
}
if (this.gantt.options.value('taskOutOfRange') === 'expand') {
from = this.gantt.rowsManager.getExpandedFrom(from as moment.Moment)
to = this.gantt.rowsManager.getExpandedTo(to as moment.Moment)
}
this.setScrollAnchor()
this.from = from as moment.Moment
this.to = to as moment.Moment
this.previousColumns = []
this.nextColumns = []
this.columns = GanttColumnsManager.GanttColumnGenerator.generate(this.columnBuilder, this.from, this.to, this.gantt.options.value('viewScale'), this.getColumnsWidth())
this.headers = GanttColumnsManager.GanttHeadersGenerator.generate(this)
this.updateColumnsMeta()
this.scrollToScrollAnchor();
(this.gantt.api as any).columns.raise.generate(this.columns, this.headers)
}
updateColumnsMeta () {
this.gantt.isRefreshingColumns = true
let lastColumn = this.getLastColumn()
this.gantt.originalWidth = lastColumn !== undefined ? lastColumn.originalSize.left + lastColumn.originalSize.width : 0
let columnsWidthChanged = this.updateColumnsWidths(this.columns, this.headers, this.previousColumns, this.nextColumns)
this.gantt.width = lastColumn !== undefined ? lastColumn.left + lastColumn.width : 0
let showSide = this.gantt.options.value('showSide')
let sideShown = this.gantt.side.isShown()
let sideVisibilityChanged = showSide !== sideShown
if (sideVisibilityChanged && !showSide) {
// Prevent unnecessary v-scrollbar if side is hidden here
this.gantt.side.show(false)
}
this.gantt.rowsManager.updateTasksPosAndSize()
this.gantt.timespansManager.updateTimespansPosAndSize()
this.updateVisibleColumns(columnsWidthChanged)
this.gantt.rowsManager.updateVisibleObjects()
let currentDateValue = this.gantt.options.value('currentDateValue')
this.gantt.currentDateManager.setCurrentDate(currentDateValue)
if (sideVisibilityChanged && showSide) {
// Prevent unnecessary v-scrollbar if side is shown here
this.gantt.side.show(true)
}
this.gantt.isRefreshingColumns = false;
(this.gantt.api as any).columns.raise.refresh(this.columns, this.headers)
}
/**
* Returns the last Gantt column or undefined
* @param extended
* @returns {any}
*/
getLastColumn (extended = false) {
let columns = this.columns
if (extended) {
columns = this.nextColumns
}
if (columns && columns.length > 0) {
return columns[columns.length - 1]
} else {
return undefined
}
}
/**
* Returns the first Gantt column or undefined
*
* @param extended
* @returns {any}
*/
getFirstColumn (extended = false) {
let columns = this.columns
if (extended) {
columns = this.previousColumns
}
if (columns && columns.length > 0) {
return columns[0]
} else {
return undefined
}
}
/**
* Returns the column at the given or next possible date
*
* @param date
* @param disableExpand
* @returns {GanttColumn}
*/
getColumnByDate (date: moment.Moment, disableExpand?: boolean) {
if (!disableExpand) {
this.expandExtendedColumnsForDate(date)
}
let extendedColumns = this.previousColumns.concat(this.columns, this.nextColumns)
let columns = GanttColumnsManager.ganttBinarySearch.get(extendedColumns, date, function (c) {
return c.date
}, true)
return columns[0] === undefined ? columns[1] : columns[0]
}
/**
* Returns the column at the given position x (in em)
*
* @param x
* @param disableExpand
* @returns {GanttColumn}
*/
getColumnByPosition (x: number, disableExpand?: boolean) {
if (!disableExpand) {
this.expandExtendedColumnsForPosition(x)
}
let extendedColumns = this.previousColumns.concat(this.columns, this.nextColumns)
let columns = GanttColumnsManager.ganttBinarySearch.get(extendedColumns, x, function (c) {
return c.left
}, true)
return columns[0] === undefined ? columns[1] : columns[0]
}
updateColumnsWidths (columns, headers, previousColumns, nextColumns) {
let columnWidth: number = this.gantt.options.value('columnWidth')
let expandToFit: boolean = this.gantt.options.value('expandToFit')
let shrinkToFit: boolean = this.gantt.options.value('shrinkToFit')
if (columnWidth === undefined || expandToFit || shrinkToFit) {
let newWidth = this.gantt.getBodyAvailableWidth()
let lastColumn = this.gantt.columnsManager.getLastColumn(false)
if (lastColumn !== undefined) {
let currentWidth = lastColumn.originalSize.left + lastColumn.originalSize.width
if (expandToFit && currentWidth < newWidth ||
shrinkToFit && currentWidth > newWidth ||
columnWidth === undefined
) {
let widthFactor = newWidth / currentWidth
GanttColumnsManager.ganttLayout.setColumnsWidthFactor(columns, widthFactor)
for (let header of headers) {
GanttColumnsManager.ganttLayout.setColumnsWidthFactor(header, widthFactor)
}
// previous and next columns will be generated again on need.
previousColumns.splice(0, this.previousColumns.length)
nextColumns.splice(0, this.nextColumns.length)
return true
}
}
}
return false
}
getColumnsWidth () {
let columnWidth: number = this.gantt.options.value('columnWidth')
if (columnWidth === undefined) {
if (!this.gantt.width || this.gantt.width <= 0) {
columnWidth = 20
} else {
columnWidth = this.gantt.width / this.columns.length
}
}
return columnWidth
}
getColumnsWidthToFit () {
return this.gantt.getBodyAvailableWidth() / this.columns.length
}
expandExtendedColumnsForPosition (x) {
let viewScale
if (x < 0) {
let firstColumn = this.getFirstColumn()
let from = firstColumn.date
let firstExtendedColumn = this.getFirstColumn(true)
if (!firstExtendedColumn || firstExtendedColumn.left > x) {
viewScale = this.gantt.options.value('viewScale')
this.previousColumns = GanttColumnsManager.GanttColumnGenerator.generate(this.columnBuilder, from, undefined, viewScale, this.getColumnsWidth(), -x, 0, true)
}
return true
} else if (x > this.gantt.width) {
let lastColumn = this.getLastColumn()
let endDate = lastColumn.getDateByPosition(lastColumn.width)
let lastExtendedColumn = this.getLastColumn(true)
if (!lastExtendedColumn || lastExtendedColumn.left + lastExtendedColumn.width < x) {
viewScale = this.gantt.options.value('viewScale')
this.nextColumns = GanttColumnsManager.GanttColumnGenerator.generate(this.columnBuilder, endDate, undefined, viewScale, this.getColumnsWidth(), x - this.gantt.width, this.gantt.width, false)
}
return true
}
return false
}
expandExtendedColumnsForDate (date) {
let firstColumn = this.getFirstColumn()
let from
if (firstColumn) {
from = firstColumn.date
}
let lastColumn = this.getLastColumn()
let endDate
if (lastColumn) {
endDate = lastColumn.endDate
}
let viewScale
if (from && date < from) {
let firstExtendedColumn = this.getFirstColumn(true)
if (!firstExtendedColumn || firstExtendedColumn.date > date) {
viewScale = this.gantt.options.value('viewScale')
this.previousColumns = GanttColumnsManager.GanttColumnGenerator.generate(this.columnBuilder, from, date, viewScale, this.getColumnsWidth(), undefined, 0, true)
}
return true
} else if (endDate && date >= endDate) {
let lastExtendedColumn = this.getLastColumn(true)
if (!lastExtendedColumn || lastExtendedColumn.date < endDate) {
viewScale = this.gantt.options.value('viewScale')
this.nextColumns = GanttColumnsManager.GanttColumnGenerator.generate(this.columnBuilder, endDate, date, viewScale, this.getColumnsWidth(), undefined, this.gantt.width, false)
}
return true
}
return false
}
/**
* Returns the number of active headers
*
* @returns {number}
*/
getActiveHeadersCount () {
return this.headers.length
}
updateVisibleColumns (includeViews) {
let limitThreshold = this.gantt.options.value('columnLimitThreshold')
let i
if (limitThreshold === undefined || limitThreshold > 0 && this.columns.length >= limitThreshold) {
this.visibleColumns = GanttColumnsManager.$filter('ganttColumnLimit')(this.columns, this.gantt)
this.visibleHeaders = []
for (i = 0; i < this.headers.length; i++) {
this.visibleHeaders.push.apply(this.visibleHeaders, GanttColumnsManager.$filter('ganttColumnLimit')(this.headers[i], this.gantt))
}
} else {
this.visibleColumns = this.columns
this.visibleHeaders = this.headers
}
if (includeViews) {
for (i = 0; i < this.visibleColumns.length; i++) {
this.visibleColumns[i].updateView()
}
for (i = 0; i < this.visibleHeaders.length; i++) {
let headerRow = this.visibleHeaders[i]
for (let headerRowItem of headerRow) {
headerRowItem.updateView()
}
}
}
let currentDateValue = this.gantt.options.value('currentDateValue')
this.gantt.currentDateManager.setCurrentDate(currentDateValue)
}
getHeaderFormat (unit) {
let format
let headersFormats = this.gantt.options.value('headersFormats')
if (headersFormats !== undefined) {
format = headersFormats[unit]
}
if (format === undefined) {
let viewScale = this.gantt.options.value('viewScale')
viewScale = viewScale.trim()
if (viewScale.charAt(viewScale.length - 1) === 's') {
viewScale = viewScale.substring(0, viewScale.length - 1)
}
let viewScaleUnit
let splittedViewScale
if (viewScale) {
splittedViewScale = viewScale.split(' ')
}
if (splittedViewScale && splittedViewScale.length > 1) {
viewScaleUnit = splittedViewScale[splittedViewScale.length - 1]
} else {
viewScaleUnit = viewScale
}
if (['millisecond', 'second', 'minute', 'hour'].indexOf(viewScaleUnit) > -1) {
format = this.defaultDayHeadersFormats[unit]
} else if (['month', 'quarter', 'year'].indexOf(viewScaleUnit) > -1) {
format = this.defaultYearHeadersFormats[unit]
}
if (format === undefined) {
format = this.defaultHeadersFormats[unit]
}
}
return format
}
getHeaderScale (header) {
let scale
let headersScales = this.gantt.options.value('headersScales')
if (headersScales !== undefined) {
scale = headersScales[header]
}
if (scale === undefined) {
scale = header
}
if (['millisecond', 'second', 'minute', 'hour', 'day', 'week', 'month', 'quarter', 'year'].indexOf(scale) === -1) {
scale = 'day'
}
return scale
}
getDateRange (visibleOnly) {
let firstColumn
let lastColumn
if (visibleOnly) {
if (this.visibleColumns && this.visibleColumns.length > 0) {
firstColumn = this.visibleColumns[0]
lastColumn = this.visibleColumns[this.visibleColumns.length - 1]
}
} else {
firstColumn = this.getFirstColumn()
lastColumn = this.getLastColumn()
}
return firstColumn && lastColumn ? [firstColumn.date, lastColumn.endDate] : undefined
}
}
export default function (GanttColumnGenerator: GanttColumnGenerator,
GanttColumnBuilder: { new(columnsManager: GanttColumnsManager): GanttColumnBuilder },
GanttHeadersGenerator: GanttHeadersGenerator,
$filter: IGanttFilterService,
ganttLayout: GanttLayout,
ganttBinarySearch: GanttBinarySearch) {
'ngInject'
GanttColumnsManager.GanttColumnGenerator = GanttColumnGenerator
GanttColumnsManager.GanttHeadersGenerator = GanttHeadersGenerator
GanttColumnsManager.ganttBinarySearch = ganttBinarySearch
GanttColumnsManager.GanttColumnBuilder = GanttColumnBuilder
GanttColumnsManager.ganttLayout = ganttLayout
GanttColumnsManager.$filter = $filter
return GanttColumnsManager
} | the_stack |
import { render } from 'lit-html';
import EventManager from '../utils/event-manager';
import { forEach } from '../../src/globals/internal/collection-helpers';
import BXTabs from '../../src/components/tabs/tabs';
import BXTab from '../../src/components/tabs/tab';
import { Default } from '../../src/components/tabs/tabs-story';
const template = (props?) =>
Default({
'bx-tabs': props,
});
describe('bx-tabs', function() {
describe('Toggling', function() {
it('should toggle "open" attribute', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-tabs');
const inner = elem!.shadowRoot!.getElementById('trigger');
(inner as HTMLElement).click();
await Promise.resolve();
expect(inner!.classList.contains('bx--tabs-trigger--open')).toBe(true);
(inner as HTMLElement).click();
await Promise.resolve();
expect(inner!.classList.contains('bx--tabs-trigger--open')).toBe(false);
});
it('should always close dropdown when clicking document', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-tabs');
const inner = elem!.shadowRoot!.getElementById('trigger');
(inner as HTMLElement).click();
await Promise.resolve();
document.documentElement.click();
expect(elem!.classList.contains('bx--tabs-trigger--open')).toBe(false);
});
it('should close dropdown when clicking on an item', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-tabs');
const inner = elem!.shadowRoot!.getElementById('trigger');
(inner as HTMLElement).click();
await Promise.resolve();
(document.body.querySelector('bx-tab') as HTMLElement).click();
expect(elem!.classList.contains('bx--tabs-trigger--open')).toBe(false);
});
});
describe('Selecting an item', function() {
const events = new EventManager();
it('should add/remove "selected" attribute', async function() {
render(template(), document.body);
await Promise.resolve();
const itemNodes = document.body.querySelectorAll('bx-tab');
(itemNodes[2] as HTMLElement).click();
await Promise.resolve();
expect(itemNodes[0].hasAttribute('selected')).toBe(false);
expect(itemNodes[1].hasAttribute('selected')).toBe(false);
expect(itemNodes[2].hasAttribute('selected')).toBe(true);
expect(itemNodes[3].hasAttribute('selected')).toBe(false);
expect(itemNodes[4].hasAttribute('selected')).toBe(false);
});
it('should update text', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-tabs');
const itemNodes = document.body.querySelectorAll('bx-tab');
(itemNodes[2] as HTMLElement).click();
await Promise.resolve();
expect(elem!.shadowRoot!.getElementById('trigger-label')!.textContent!.trim()).toBe('Option 3');
});
it('should update value', async function() {
render(template(), document.body);
await Promise.resolve();
const itemNodes = document.body.querySelectorAll('bx-tab');
(itemNodes[2] as HTMLElement).click();
await Promise.resolve();
expect((document.body.querySelector('bx-tabs') as BXTabs).value).toBe('staging');
});
it('should provide a way to switch item with a value', async function() {
render(template(), document.body);
await Promise.resolve();
(document.body.querySelector('bx-tabs') as BXTabs).value = 'staging';
await Promise.resolve(); // Update cycle for `<bx-tabs>`
await Promise.resolve(); // Update cycle for `<bx-tab>`
const itemNodes = document.body.querySelectorAll('bx-tab');
expect(itemNodes[0].hasAttribute('selected')).toBe(false);
expect(itemNodes[1].hasAttribute('selected')).toBe(false);
expect(itemNodes[2].hasAttribute('selected')).toBe(true);
expect(itemNodes[3].hasAttribute('selected')).toBe(false);
expect(itemNodes[4].hasAttribute('selected')).toBe(false);
});
it('should provide a way to cancel switching item', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-tabs');
const itemNodes = document.body.querySelectorAll('bx-tab');
(document.body.querySelector('bx-tabs') as BXTabs).value = 'all';
await Promise.resolve();
events.on(elem!, 'bx-tabs-beingselected', (event: CustomEvent) => {
expect(event.detail.item).toBe(itemNodes[2]);
event.preventDefault();
});
(itemNodes[2] as HTMLElement).click();
await Promise.resolve();
expect(itemNodes[0].hasAttribute('selected')).toBe(true);
expect(itemNodes[1].hasAttribute('selected')).toBe(false);
expect(itemNodes[2].hasAttribute('selected')).toBe(false);
expect(itemNodes[3].hasAttribute('selected')).toBe(false);
expect(itemNodes[4].hasAttribute('selected')).toBe(false);
expect(elem!.shadowRoot!.getElementById('trigger-label')!.textContent!.trim()).toBe('Option 1');
});
afterEach(async function() {
events.reset();
});
});
describe('Focus style', function() {
it('should support setting focus style to child tabs', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-tabs');
const itemNodes = document.body.querySelectorAll('bx-tab');
const event = new CustomEvent('focusin', { bubbles: true });
(elem as HTMLElement).dispatchEvent(event);
expect(Array.prototype.every.call(itemNodes, item => (item as BXTab).inFocus)).toBe(true);
});
it('should support unsetting focus style to child tabs', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-tabs');
const itemNodes = document.body.querySelectorAll('bx-tab');
forEach(itemNodes, item => {
(item as BXTab).inFocus = true;
});
const event = new CustomEvent('focusout', { bubbles: true });
(elem as HTMLElement).dispatchEvent(event);
expect(Array.prototype.every.call(itemNodes, item => (item as BXTab).inFocus)).toBe(false);
});
});
describe('Keyboard navigation', function() {
it('should support closing narrow mode dropdown by ESC key', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-tabs');
(elem as any)._open = true;
elem!.dispatchEvent(
Object.assign(new CustomEvent('keydown', { bubbles: true }), {
key: 'Escape',
})
);
expect((elem as any)._open).toBe(false);
});
it('should support left key in non-narrow mode', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-tabs');
(elem as BXTabs).value = 'all';
await Promise.resolve(); // Update cycle for `<bx-tabs>`
await Promise.resolve(); // Update cycle for `<bx-tab>`
const triggerNode = elem!.shadowRoot!.getElementById('trigger');
spyOnProperty(triggerNode!, 'offsetParent').and.returnValue(null);
elem!.dispatchEvent(
Object.assign(new CustomEvent('keydown', { bubbles: true }), {
key: 'ArrowLeft',
})
);
await Promise.resolve();
const itemNodes = document.body.querySelectorAll('bx-tab');
expect(itemNodes[0].hasAttribute('selected')).toBe(false);
expect(itemNodes[1].hasAttribute('selected')).toBe(false);
expect(itemNodes[2].hasAttribute('selected')).toBe(false);
expect(itemNodes[3].hasAttribute('selected')).toBe(false);
expect(itemNodes[4].hasAttribute('selected')).toBe(true);
});
it('should support right key in non-narrow mode', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-tabs');
(elem as BXTabs).value = 'router';
await Promise.resolve(); // Update cycle for `<bx-tabs>`
await Promise.resolve(); // Update cycle for `<bx-tab>`
const triggerNode = elem!.shadowRoot!.getElementById('trigger');
spyOnProperty(triggerNode!, 'offsetParent').and.returnValue(null);
elem!.dispatchEvent(
Object.assign(new CustomEvent('keydown', { bubbles: true }), {
key: 'ArrowRight',
})
);
await Promise.resolve();
const itemNodes = document.body.querySelectorAll('bx-tab');
expect(itemNodes[0].hasAttribute('selected')).toBe(true);
expect(itemNodes[1].hasAttribute('selected')).toBe(false);
expect(itemNodes[2].hasAttribute('selected')).toBe(false);
expect(itemNodes[3].hasAttribute('selected')).toBe(false);
expect(itemNodes[4].hasAttribute('selected')).toBe(false);
});
it('should support up key in narrow mode', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-tabs');
(elem as BXTabs).value = 'all';
(elem as any)._open = true;
await Promise.resolve(); // Update cycle for `<bx-tabs>`
await Promise.resolve(); // Update cycle for `<bx-tab>`
const triggerNode = elem!.shadowRoot!.getElementById('trigger');
spyOnProperty(triggerNode!, 'offsetParent').and.returnValue({});
elem!.dispatchEvent(
Object.assign(new CustomEvent('keydown', { bubbles: true }), {
key: 'ArrowUp',
})
);
await Promise.resolve();
const itemNodes = document.body.querySelectorAll('bx-tab');
expect(itemNodes[0].hasAttribute('highlighted')).toBe(false);
expect(itemNodes[1].hasAttribute('highlighted')).toBe(false);
expect(itemNodes[2].hasAttribute('highlighted')).toBe(false);
expect(itemNodes[3].hasAttribute('highlighted')).toBe(false);
expect(itemNodes[4].hasAttribute('highlighted')).toBe(true);
});
it('should support down key in narrow mode', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-tabs');
(elem as BXTabs).value = 'router';
(elem as any)._open = true;
await Promise.resolve(); // Update cycle for `<bx-tabs>`
await Promise.resolve(); // Update cycle for `<bx-tab>`
const triggerNode = elem!.shadowRoot!.getElementById('trigger');
spyOnProperty(triggerNode!, 'offsetParent').and.returnValue({});
elem!.dispatchEvent(
Object.assign(new CustomEvent('keydown', { bubbles: true }), {
key: 'ArrowDown',
})
);
await Promise.resolve();
const itemNodes = document.body.querySelectorAll('bx-tab');
expect(itemNodes[0].hasAttribute('highlighted')).toBe(true);
expect(itemNodes[1].hasAttribute('highlighted')).toBe(false);
expect(itemNodes[2].hasAttribute('highlighted')).toBe(false);
expect(itemNodes[3].hasAttribute('highlighted')).toBe(false);
expect(itemNodes[4].hasAttribute('highlighted')).toBe(false);
});
it('should open the dropdown with down key in narrow mode', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-tabs');
(elem as BXTabs).value = 'all';
await Promise.resolve(); // Update cycle for `<bx-tabs>`
await Promise.resolve(); // Update cycle for `<bx-tab>`
const triggerNode = elem!.shadowRoot!.getElementById('trigger');
spyOnProperty(triggerNode!, 'offsetParent').and.returnValue({});
elem!.dispatchEvent(
Object.assign(new CustomEvent('keydown', { bubbles: true }), {
key: 'ArrowDown',
})
);
await Promise.resolve();
expect((elem as any)._open).toBe(true);
const itemNodes = document.body.querySelectorAll('bx-tab');
expect(itemNodes[0].hasAttribute('highlighted')).toBe(false);
expect(itemNodes[1].hasAttribute('highlighted')).toBe(false);
expect(itemNodes[2].hasAttribute('highlighted')).toBe(false);
expect(itemNodes[3].hasAttribute('highlighted')).toBe(false);
expect(itemNodes[4].hasAttribute('highlighted')).toBe(false);
});
it('should open the dropdown with up key in narrow mode', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-tabs');
(elem as BXTabs).value = 'all';
await Promise.resolve(); // Update cycle for `<bx-tabs>`
await Promise.resolve(); // Update cycle for `<bx-tab>`
const triggerNode = elem!.shadowRoot!.getElementById('trigger');
spyOnProperty(triggerNode!, 'offsetParent').and.returnValue({});
elem!.dispatchEvent(
Object.assign(new CustomEvent('keydown', { bubbles: true }), {
key: 'ArrowUp',
})
);
await Promise.resolve();
expect((elem as any)._open).toBe(true);
const itemNodes = document.body.querySelectorAll('bx-tab');
expect(itemNodes[0].hasAttribute('highlighted')).toBe(false);
expect(itemNodes[1].hasAttribute('highlighted')).toBe(false);
expect(itemNodes[2].hasAttribute('highlighted')).toBe(false);
expect(itemNodes[3].hasAttribute('highlighted')).toBe(false);
expect(itemNodes[4].hasAttribute('highlighted')).toBe(false);
});
it('should open the dropdown with space key in narrow mode', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-tabs');
const triggerNode = elem!.shadowRoot!.getElementById('trigger');
spyOnProperty(triggerNode!, 'offsetParent').and.returnValue({});
elem!.dispatchEvent(
Object.assign(new CustomEvent('keydown', { bubbles: true }), {
key: ' ',
})
);
expect((elem as any)._open).toBe(true);
});
it('should select the highlighted item with space key in narrow mode', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-tabs');
(elem as any)._open = true;
const itemNodes = document.body.querySelectorAll('bx-tab');
(itemNodes[2] as BXTab).highlighted = true;
await Promise.resolve();
const triggerNode = elem!.shadowRoot!.getElementById('trigger');
spyOnProperty(triggerNode!, 'offsetParent').and.returnValue({});
elem!.dispatchEvent(
Object.assign(new CustomEvent('keydown', { bubbles: true }), {
key: ' ',
})
);
await Promise.resolve();
expect((elem as any)._open).toBe(false);
expect((elem as BXTabs).value).toBe('staging');
});
it('should simply close the dropdown if user tries to choose the same selection in narrow mode', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-tabs');
(elem as BXTabs).value = 'staging';
(elem as any)._open = true;
const itemNodes = document.body.querySelectorAll('bx-tab');
(itemNodes[2] as BXTab).highlighted = true;
await Promise.resolve(); // Update cycle for `<bx-tabs>`
await Promise.resolve(); // Update cycle for `<bx-tab>`
const triggerNode = elem!.shadowRoot!.getElementById('trigger');
spyOnProperty(triggerNode!, 'offsetParent').and.returnValue({});
elem!.dispatchEvent(
Object.assign(new CustomEvent('keydown', { bubbles: true }), {
key: ' ',
})
);
expect((elem as any)._open).toBe(false);
});
it('should support closing the dropdown without an highlighted item in narrow mode', async function() {
render(template(), document.body);
await Promise.resolve();
const elem = document.body.querySelector('bx-tabs');
(elem as any)._open = true;
const triggerNode = elem!.shadowRoot!.getElementById('trigger');
spyOnProperty(triggerNode!, 'offsetParent').and.returnValue({});
elem!.dispatchEvent(
Object.assign(new CustomEvent('keydown', { bubbles: true }), {
key: ' ',
})
);
expect((elem as any)._open).toBe(false);
});
});
afterEach(async function() {
await render(undefined!, document.body);
});
}); | the_stack |
import { Disposable } from 'vs/base/common/lifecycle';
import { ExtHostContext, MainThreadTreeViewsShape, ExtHostTreeViewsShape, MainContext } from 'vs/workbench/api/common/extHost.protocol';
import { ITreeViewDataProvider, ITreeItem, IViewsService, ITreeView, IViewsRegistry, ITreeViewDescriptor, IRevealOptions, Extensions, ResolvableTreeItem, ITreeViewDragAndDropController, IViewBadge } from 'vs/workbench/common/views';
import { extHostNamedCustomer, IExtHostContext } from 'vs/workbench/services/extensions/common/extHostCustomers';
import { distinct } from 'vs/base/common/arrays';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { isUndefinedOrNull, isNumber } from 'vs/base/common/types';
import { Registry } from 'vs/platform/registry/common/platform';
import { IExtensionService } from 'vs/workbench/services/extensions/common/extensions';
import { ILogService } from 'vs/platform/log/common/log';
import { CancellationToken } from 'vs/base/common/cancellation';
import { createStringDataTransferItem, VSDataTransfer } from 'vs/base/common/dataTransfer';
import { VSBuffer } from 'vs/base/common/buffer';
import { DataTransferCache } from 'vs/workbench/api/common/shared/dataTransferCache';
import * as typeConvert from 'vs/workbench/api/common/extHostTypeConverters';
@extHostNamedCustomer(MainContext.MainThreadTreeViews)
export class MainThreadTreeViews extends Disposable implements MainThreadTreeViewsShape {
private readonly _proxy: ExtHostTreeViewsShape;
private readonly _dataProviders: Map<string, TreeViewDataProvider> = new Map<string, TreeViewDataProvider>();
private readonly _dndControllers = new Map<string, TreeViewDragAndDropController>();
constructor(
extHostContext: IExtHostContext,
@IViewsService private readonly viewsService: IViewsService,
@INotificationService private readonly notificationService: INotificationService,
@IExtensionService private readonly extensionService: IExtensionService,
@ILogService private readonly logService: ILogService
) {
super();
this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostTreeViews);
}
async $registerTreeViewDataProvider(treeViewId: string, options: { showCollapseAll: boolean; canSelectMany: boolean; dropMimeTypes: string[]; dragMimeTypes: string[]; hasHandleDrag: boolean; hasHandleDrop: boolean }): Promise<void> {
this.logService.trace('MainThreadTreeViews#$registerTreeViewDataProvider', treeViewId, options);
this.extensionService.whenInstalledExtensionsRegistered().then(() => {
const dataProvider = new TreeViewDataProvider(treeViewId, this._proxy, this.notificationService);
this._dataProviders.set(treeViewId, dataProvider);
const dndController = (options.hasHandleDrag || options.hasHandleDrop)
? new TreeViewDragAndDropController(treeViewId, options.dropMimeTypes, options.dragMimeTypes, options.hasHandleDrag, this._proxy) : undefined;
const viewer = this.getTreeView(treeViewId);
if (viewer) {
// Order is important here. The internal tree isn't created until the dataProvider is set.
// Set all other properties first!
viewer.showCollapseAllAction = !!options.showCollapseAll;
viewer.canSelectMany = !!options.canSelectMany;
viewer.dragAndDropController = dndController;
if (dndController) {
this._dndControllers.set(treeViewId, dndController);
}
viewer.dataProvider = dataProvider;
this.registerListeners(treeViewId, viewer);
this._proxy.$setVisible(treeViewId, viewer.visible);
} else {
this.notificationService.error('No view is registered with id: ' + treeViewId);
}
});
}
$reveal(treeViewId: string, itemInfo: { item: ITreeItem; parentChain: ITreeItem[] } | undefined, options: IRevealOptions): Promise<void> {
this.logService.trace('MainThreadTreeViews#$reveal', treeViewId, itemInfo?.item, itemInfo?.parentChain, options);
return this.viewsService.openView(treeViewId, options.focus)
.then(() => {
const viewer = this.getTreeView(treeViewId);
if (viewer && itemInfo) {
return this.reveal(viewer, this._dataProviders.get(treeViewId)!, itemInfo.item, itemInfo.parentChain, options);
}
return undefined;
});
}
$refresh(treeViewId: string, itemsToRefreshByHandle: { [treeItemHandle: string]: ITreeItem }): Promise<void> {
this.logService.trace('MainThreadTreeViews#$refresh', treeViewId, itemsToRefreshByHandle);
const viewer = this.getTreeView(treeViewId);
const dataProvider = this._dataProviders.get(treeViewId);
if (viewer && dataProvider) {
const itemsToRefresh = dataProvider.getItemsToRefresh(itemsToRefreshByHandle);
return viewer.refresh(itemsToRefresh.length ? itemsToRefresh : undefined);
}
return Promise.resolve();
}
$setMessage(treeViewId: string, message: string): void {
this.logService.trace('MainThreadTreeViews#$setMessage', treeViewId, message);
const viewer = this.getTreeView(treeViewId);
if (viewer) {
viewer.message = message;
}
}
$setTitle(treeViewId: string, title: string, description: string | undefined): void {
this.logService.trace('MainThreadTreeViews#$setTitle', treeViewId, title, description);
const viewer = this.getTreeView(treeViewId);
if (viewer) {
viewer.title = title;
viewer.description = description;
}
}
$setBadge(treeViewId: string, badge: IViewBadge | undefined): void {
this.logService.trace('MainThreadTreeViews#$setBadge', treeViewId, badge?.value, badge?.tooltip);
const viewer = this.getTreeView(treeViewId);
if (viewer) {
viewer.badge = badge;
}
}
$resolveDropFileData(destinationViewId: string, requestId: number, dataItemIndex: number): Promise<VSBuffer> {
const controller = this._dndControllers.get(destinationViewId);
if (!controller) {
throw new Error('Unknown tree');
}
return controller.resolveDropFileData(requestId, dataItemIndex);
}
private async reveal(treeView: ITreeView, dataProvider: TreeViewDataProvider, itemIn: ITreeItem, parentChain: ITreeItem[], options: IRevealOptions): Promise<void> {
options = options ? options : { select: false, focus: false };
const select = isUndefinedOrNull(options.select) ? false : options.select;
const focus = isUndefinedOrNull(options.focus) ? false : options.focus;
let expand = Math.min(isNumber(options.expand) ? options.expand : options.expand === true ? 1 : 0, 3);
if (dataProvider.isEmpty()) {
// Refresh if empty
await treeView.refresh();
}
for (const parent of parentChain) {
const parentItem = dataProvider.getItem(parent.handle);
if (parentItem) {
await treeView.expand(parentItem);
}
}
const item = dataProvider.getItem(itemIn.handle);
if (item) {
await treeView.reveal(item);
if (select) {
treeView.setSelection([item]);
}
if (focus) {
treeView.setFocus(item);
}
let itemsToExpand = [item];
for (; itemsToExpand.length > 0 && expand > 0; expand--) {
await treeView.expand(itemsToExpand);
itemsToExpand = itemsToExpand.reduce((result, itemValue) => {
const item = dataProvider.getItem(itemValue.handle);
if (item && item.children && item.children.length) {
result.push(...item.children);
}
return result;
}, [] as ITreeItem[]);
}
}
}
private registerListeners(treeViewId: string, treeView: ITreeView): void {
this._register(treeView.onDidExpandItem(item => this._proxy.$setExpanded(treeViewId, item.handle, true)));
this._register(treeView.onDidCollapseItem(item => this._proxy.$setExpanded(treeViewId, item.handle, false)));
this._register(treeView.onDidChangeSelection(items => this._proxy.$setSelection(treeViewId, items.map(({ handle }) => handle))));
this._register(treeView.onDidChangeVisibility(isVisible => this._proxy.$setVisible(treeViewId, isVisible)));
}
private getTreeView(treeViewId: string): ITreeView | null {
const viewDescriptor: ITreeViewDescriptor = <ITreeViewDescriptor>Registry.as<IViewsRegistry>(Extensions.ViewsRegistry).getView(treeViewId);
return viewDescriptor ? viewDescriptor.treeView : null;
}
override dispose(): void {
this._dataProviders.forEach((dataProvider, treeViewId) => {
const treeView = this.getTreeView(treeViewId);
if (treeView) {
treeView.dataProvider = undefined;
}
});
this._dataProviders.clear();
this._dndControllers.clear();
super.dispose();
}
}
type TreeItemHandle = string;
class TreeViewDragAndDropController implements ITreeViewDragAndDropController {
private readonly dataTransfersCache = new DataTransferCache();
constructor(private readonly treeViewId: string,
readonly dropMimeTypes: string[],
readonly dragMimeTypes: string[],
readonly hasWillDrop: boolean,
private readonly _proxy: ExtHostTreeViewsShape) { }
async handleDrop(dataTransfer: VSDataTransfer, targetTreeItem: ITreeItem | undefined, token: CancellationToken,
operationUuid?: string, sourceTreeId?: string, sourceTreeItemHandles?: string[]): Promise<void> {
const request = this.dataTransfersCache.add(dataTransfer);
try {
return await this._proxy.$handleDrop(this.treeViewId, request.id, await typeConvert.DataTransfer.toDataTransferDTO(dataTransfer), targetTreeItem?.handle, token, operationUuid, sourceTreeId, sourceTreeItemHandles);
} finally {
request.dispose();
}
}
async handleDrag(sourceTreeItemHandles: string[], operationUuid: string, token: CancellationToken): Promise<VSDataTransfer | undefined> {
if (!this.hasWillDrop) {
return;
}
const additionalDataTransferDTO = await this._proxy.$handleDrag(this.treeViewId, sourceTreeItemHandles, operationUuid, token);
if (!additionalDataTransferDTO) {
return;
}
const additionalDataTransfer = new VSDataTransfer();
additionalDataTransferDTO.items.forEach(([type, item]) => {
additionalDataTransfer.replace(type, createStringDataTransferItem(item.asString));
});
return additionalDataTransfer;
}
public resolveDropFileData(requestId: number, dataItemIndex: number): Promise<VSBuffer> {
return this.dataTransfersCache.resolveDropFileData(requestId, dataItemIndex);
}
}
class TreeViewDataProvider implements ITreeViewDataProvider {
private readonly itemsMap: Map<TreeItemHandle, ITreeItem> = new Map<TreeItemHandle, ITreeItem>();
private hasResolve: Promise<boolean>;
constructor(private readonly treeViewId: string,
private readonly _proxy: ExtHostTreeViewsShape,
private readonly notificationService: INotificationService
) {
this.hasResolve = this._proxy.$hasResolve(this.treeViewId);
}
getChildren(treeItem?: ITreeItem): Promise<ITreeItem[] | undefined> {
return this._proxy.$getChildren(this.treeViewId, treeItem ? treeItem.handle : undefined)
.then(
children => this.postGetChildren(children),
err => {
this.notificationService.error(err);
return [];
});
}
getItemsToRefresh(itemsToRefreshByHandle: { [treeItemHandle: string]: ITreeItem }): ITreeItem[] {
const itemsToRefresh: ITreeItem[] = [];
if (itemsToRefreshByHandle) {
for (const treeItemHandle of Object.keys(itemsToRefreshByHandle)) {
const currentTreeItem = this.getItem(treeItemHandle);
if (currentTreeItem) { // Refresh only if the item exists
const treeItem = itemsToRefreshByHandle[treeItemHandle];
// Update the current item with refreshed item
this.updateTreeItem(currentTreeItem, treeItem);
if (treeItemHandle === treeItem.handle) {
itemsToRefresh.push(currentTreeItem);
} else {
// Update maps when handle is changed and refresh parent
this.itemsMap.delete(treeItemHandle);
this.itemsMap.set(currentTreeItem.handle, currentTreeItem);
const parent = treeItem.parentHandle ? this.itemsMap.get(treeItem.parentHandle) : null;
if (parent) {
itemsToRefresh.push(parent);
}
}
}
}
}
return itemsToRefresh;
}
getItem(treeItemHandle: string): ITreeItem | undefined {
return this.itemsMap.get(treeItemHandle);
}
isEmpty(): boolean {
return this.itemsMap.size === 0;
}
private async postGetChildren(elements: ITreeItem[] | undefined): Promise<ResolvableTreeItem[] | undefined> {
if (elements === undefined) {
return undefined;
}
const result: ResolvableTreeItem[] = [];
const hasResolve = await this.hasResolve;
if (elements) {
for (const element of elements) {
const resolvable = new ResolvableTreeItem(element, hasResolve ? (token) => {
return this._proxy.$resolve(this.treeViewId, element.handle, token);
} : undefined);
this.itemsMap.set(element.handle, resolvable);
result.push(resolvable);
}
}
return result;
}
private updateTreeItem(current: ITreeItem, treeItem: ITreeItem): void {
treeItem.children = treeItem.children ? treeItem.children : undefined;
if (current) {
const properties = distinct([...Object.keys(current instanceof ResolvableTreeItem ? current.asTreeItem() : current),
...Object.keys(treeItem)]);
for (const property of properties) {
(<any>current)[property] = (<any>treeItem)[property];
}
if (current instanceof ResolvableTreeItem) {
current.resetResolve();
}
}
}
} | the_stack |
import * as Common from '../../core/common/common.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as Platform from '../../core/platform/platform.js';
import * as Root from '../../core/root/root.js';
import * as SDK from '../../core/sdk/sdk.js';
import * as Bindings from '../../models/bindings/bindings.js';
import * as Extensions from '../../models/extensions/extensions.js';
import * as TimelineModel from '../../models/timeline_model/timeline_model.js';
import type * as Protocol from '../../generated/protocol.js';
import {ExtensionTracingSession} from './ExtensionTracingSession.js';
import {PerformanceModel} from './PerformanceModel.js';
const UIStrings = {
/**
* @description Text in Timeline Controller of the Performance panel.
* A "CPU profile" is a recorded performance measurement how a specific target behaves.
* "Target" in this context can mean a web page, service or normal worker.
* "Not available" is used as there are multiple things that can go wrong, but we do not
* know what exactly, just that the CPU profile was not correctly recorded.
*/
cpuProfileForATargetIsNot: 'CPU profile for a target is not available.',
/**
*@description Text in Timeline Controller of the Performance panel indicating that the Performance Panel cannot
* record a performance trace because the type of target (where possible types are page, service worker and shared
* worker) doesn't support it.
*/
tracingNotSupported: 'Performance trace recording not supported for this type of target',
};
const str_ = i18n.i18n.registerUIStrings('panels/timeline/TimelineController.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
export class TimelineController implements SDK.TargetManager.SDKModelObserver<SDK.CPUProfilerModel.CPUProfilerModel>,
SDK.TracingManager.TracingManagerClient {
private readonly target: SDK.Target.Target;
private tracingManager: SDK.TracingManager.TracingManager|null;
private performanceModel: PerformanceModel;
private readonly client: Client;
private readonly tracingModel: SDK.TracingModel.TracingModel;
private extensionSessions: ExtensionTracingSession[];
private extensionTraceProviders?: Extensions.ExtensionTraceProvider.ExtensionTraceProvider[];
// TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private tracingCompleteCallback?: ((value: any) => void)|null;
private profiling?: boolean;
// TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private cpuProfiles?: Map<any, any>|null;
constructor(target: SDK.Target.Target, client: Client) {
this.target = target;
this.tracingManager = target.model(SDK.TracingManager.TracingManager);
this.performanceModel = new PerformanceModel();
this.performanceModel.setMainTarget(target);
this.client = client;
const backingStorage = new Bindings.TempFile.TempFileBackingStorage();
this.tracingModel = new SDK.TracingModel.TracingModel(backingStorage);
this.extensionSessions = [];
SDK.TargetManager.TargetManager.instance().observeModels(SDK.CPUProfilerModel.CPUProfilerModel, this);
}
dispose(): void {
SDK.TargetManager.TargetManager.instance().unobserveModels(SDK.CPUProfilerModel.CPUProfilerModel, this);
}
mainTarget(): SDK.Target.Target {
return this.target;
}
async startRecording(
options: RecordingOptions, providers: Extensions.ExtensionTraceProvider.ExtensionTraceProvider[]):
Promise<Protocol.ProtocolResponseWithError> {
this.extensionTraceProviders = Extensions.ExtensionServer.ExtensionServer.instance().traceProviders().slice();
function disabledByDefault(category: string): string {
return 'disabled-by-default-' + category;
}
const categoriesArray = [
'-*',
'devtools.timeline',
disabledByDefault('devtools.timeline'),
disabledByDefault('devtools.timeline.frame'),
'v8.execute',
disabledByDefault('v8.compile'),
TimelineModel.TimelineModel.TimelineModelImpl.Category.Console,
TimelineModel.TimelineModel.TimelineModelImpl.Category.UserTiming,
TimelineModel.TimelineModel.TimelineModelImpl.Category.Loading,
];
categoriesArray.push(TimelineModel.TimelineModel.TimelineModelImpl.Category.LatencyInfo);
if (Root.Runtime.experiments.isEnabled('timelineV8RuntimeCallStats') && options.enableJSSampling) {
categoriesArray.push(disabledByDefault('v8.runtime_stats_sampling'));
}
if (!Root.Runtime.Runtime.queryParam('timelineTracingJSProfileDisabled') && options.enableJSSampling) {
categoriesArray.push(disabledByDefault('v8.cpu_profiler'));
}
categoriesArray.push(disabledByDefault('devtools.timeline.stack'));
if (Root.Runtime.experiments.isEnabled('timelineInvalidationTracking')) {
categoriesArray.push(disabledByDefault('devtools.timeline.invalidationTracking'));
}
if (options.capturePictures) {
categoriesArray.push(
disabledByDefault('devtools.timeline.layers'), disabledByDefault('devtools.timeline.picture'),
disabledByDefault('blink.graphics_context_annotations'));
}
if (options.captureFilmStrip) {
categoriesArray.push(disabledByDefault('devtools.screenshot'));
}
this.extensionSessions = providers.map(provider => new ExtensionTracingSession(provider, this.performanceModel));
this.extensionSessions.forEach(session => session.start());
this.performanceModel.setRecordStartTime(Date.now());
const response = await this.startRecordingWithCategories(categoriesArray.join(','), options.enableJSSampling);
if (response.getError()) {
await this.waitForTracingToStop(false);
await SDK.TargetManager.TargetManager.instance().resumeAllTargets();
}
return response;
}
async stopRecording(): Promise<PerformanceModel> {
if (this.tracingManager) {
this.tracingManager.stop();
}
this.client.loadingStarted();
await this.waitForTracingToStop(true);
this.allSourcesFinished();
return this.performanceModel;
}
private async waitForTracingToStop(awaitTracingCompleteCallback: boolean): Promise<void> {
const tracingStoppedPromises = [];
if (this.tracingManager && awaitTracingCompleteCallback) {
tracingStoppedPromises.push(new Promise(resolve => {
this.tracingCompleteCallback = resolve;
}));
}
tracingStoppedPromises.push(this.stopProfilingOnAllModels());
const extensionCompletionPromises = this.extensionSessions.map(session => session.stop());
if (extensionCompletionPromises.length) {
tracingStoppedPromises.push(
Promise.race([Promise.all(extensionCompletionPromises), new Promise(r => setTimeout(r, 5000))]));
}
await Promise.all(tracingStoppedPromises);
}
modelAdded(cpuProfilerModel: SDK.CPUProfilerModel.CPUProfilerModel): void {
if (this.profiling) {
cpuProfilerModel.startRecording();
}
}
modelRemoved(_cpuProfilerModel: SDK.CPUProfilerModel.CPUProfilerModel): void {
// FIXME: We'd like to stop profiling on the target and retrieve a profile
// but it's too late. Backend connection is closed.
}
private async startProfilingOnAllModels(): Promise<void> {
this.profiling = true;
const models = SDK.TargetManager.TargetManager.instance().models(SDK.CPUProfilerModel.CPUProfilerModel);
await Promise.all(models.map(model => model.startRecording()));
}
private addCpuProfile(targetId: Protocol.Target.TargetID|'main', cpuProfile: Protocol.Profiler.Profile|null): void {
if (!cpuProfile) {
Common.Console.Console.instance().warn(i18nString(UIStrings.cpuProfileForATargetIsNot));
return;
}
if (!this.cpuProfiles) {
this.cpuProfiles = new Map();
}
this.cpuProfiles.set(targetId, cpuProfile);
}
private async stopProfilingOnAllModels(): Promise<void> {
const models =
this.profiling ? SDK.TargetManager.TargetManager.instance().models(SDK.CPUProfilerModel.CPUProfilerModel) : [];
this.profiling = false;
const promises = [];
for (const model of models) {
const targetId = model.target().id();
const modelPromise = model.stopRecording().then(this.addCpuProfile.bind(this, targetId));
promises.push(modelPromise);
}
await Promise.all(promises);
}
private async startRecordingWithCategories(categories: string, enableJSSampling?: boolean):
Promise<Protocol.ProtocolResponseWithError> {
if (!this.tracingManager) {
throw new Error(UIStrings.tracingNotSupported);
}
// There might be a significant delay in the beginning of timeline recording
// caused by starting CPU profiler, that needs to traverse JS heap to collect
// all the functions data.
await SDK.TargetManager.TargetManager.instance().suspendAllTargets('performance-timeline');
if (enableJSSampling && Root.Runtime.Runtime.queryParam('timelineTracingJSProfileDisabled')) {
await this.startProfilingOnAllModels();
}
return this.tracingManager.start(this, categories, '');
}
traceEventsCollected(events: SDK.TracingManager.EventPayload[]): void {
this.tracingModel.addEvents(events);
}
tracingComplete(): void {
if (!this.tracingCompleteCallback) {
return;
}
this.tracingCompleteCallback(undefined);
this.tracingCompleteCallback = null;
}
private allSourcesFinished(): void {
this.client.processingStarted();
setTimeout(() => this.finalizeTrace(), 0);
}
private async finalizeTrace(): Promise<void> {
this.injectCpuProfileEvents();
await SDK.TargetManager.TargetManager.instance().resumeAllTargets();
this.tracingModel.tracingComplete();
this.client.loadingComplete(this.tracingModel);
}
private injectCpuProfileEvent(pid: number, tid: number, cpuProfile: Protocol.Profiler.Profile|null): void {
if (!cpuProfile) {
return;
}
// TODO(crbug/1011811): This event type is not compatible with the SDK.TracingManager.EventPayload.
// EventPayload requires many properties to be defined but it's not clear if they will have
// any side effects.
const cpuProfileEvent = ({
cat: SDK.TracingModel.DevToolsMetadataEventCategory,
ph: SDK.TracingModel.Phase.Instant,
ts: this.tracingModel.maximumRecordTime() * 1000,
pid: pid,
tid: tid,
name: TimelineModel.TimelineModel.RecordType.CpuProfile,
args: {data: {cpuProfile: cpuProfile}},
// TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any);
this.tracingModel.addEvents([cpuProfileEvent]);
}
private buildTargetToProcessIdMap(): Map<string, number>|null {
const metadataEventTypes = TimelineModel.TimelineModel.TimelineModelImpl.DevToolsMetadataEvent;
const metadataEvents = this.tracingModel.devToolsMetadataEvents();
const browserMetaEvent = metadataEvents.find(e => e.name === metadataEventTypes.TracingStartedInBrowser);
if (!browserMetaEvent) {
return null;
}
const pseudoPidToFrames = new Platform.MapUtilities.Multimap<string, string>();
const targetIdToPid = new Map<string, number>();
// TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const frames: any[] = browserMetaEvent.args.data.frames;
for (const frameInfo of frames) {
targetIdToPid.set(frameInfo.frame, frameInfo.processId);
}
for (const event of metadataEvents) {
const data = event.args.data;
switch (event.name) {
case metadataEventTypes.FrameCommittedInBrowser:
if (data.processId) {
targetIdToPid.set(data.frame, data.processId);
} else {
pseudoPidToFrames.set(data.processPseudoId, data.frame);
}
break;
case metadataEventTypes.ProcessReadyInBrowser:
for (const frame of pseudoPidToFrames.get(data.processPseudoId) || []) {
targetIdToPid.set(frame, data.processId);
}
break;
}
}
const mainFrame = frames.find(frame => !frame.parent);
const mainRendererProcessId = mainFrame.processId;
const mainProcess = this.tracingModel.getProcessById(mainRendererProcessId);
if (mainProcess) {
const target = SDK.TargetManager.TargetManager.instance().mainTarget();
if (target) {
targetIdToPid.set(target.id(), mainProcess.id());
}
}
return targetIdToPid;
}
private injectCpuProfileEvents(): void {
if (!this.cpuProfiles) {
return;
}
const metadataEventTypes = TimelineModel.TimelineModel.TimelineModelImpl.DevToolsMetadataEvent;
const metadataEvents = this.tracingModel.devToolsMetadataEvents();
const targetIdToPid = this.buildTargetToProcessIdMap();
if (targetIdToPid) {
for (const [id, profile] of this.cpuProfiles) {
const pid = targetIdToPid.get(id);
if (!pid) {
continue;
}
const process = this.tracingModel.getProcessById(pid);
const thread =
process && process.threadByName(TimelineModel.TimelineModel.TimelineModelImpl.RendererMainThreadName);
if (thread) {
this.injectCpuProfileEvent(pid, thread.id(), profile);
}
}
} else {
// Legacy backends support.
const filteredEvents = metadataEvents.filter(event => event.name === metadataEventTypes.TracingStartedInPage);
const mainMetaEvent = filteredEvents[filteredEvents.length - 1];
if (mainMetaEvent) {
const pid = mainMetaEvent.thread.process().id();
if (this.tracingManager) {
const mainCpuProfile = this.cpuProfiles.get(this.tracingManager.target().id());
this.injectCpuProfileEvent(pid, mainMetaEvent.thread.id(), mainCpuProfile);
}
} else {
// Or there was no tracing manager in the main target at all, in this case build the model full
// of cpu profiles.
let tid = 0;
for (const pair of this.cpuProfiles) {
const target = SDK.TargetManager.TargetManager.instance().targetById(pair[0]);
const name = target && target.name();
this.tracingModel.addEvents(
TimelineModel.TimelineJSProfile.TimelineJSProfileProcessor.buildTraceProfileFromCpuProfile(
pair[1], ++tid, /* injectPageEvent */ tid === 1, name));
}
}
}
const workerMetaEvents =
metadataEvents.filter(event => event.name === metadataEventTypes.TracingSessionIdForWorker);
for (const metaEvent of workerMetaEvents) {
const workerId = metaEvent.args['data']['workerId'];
const cpuProfile = this.cpuProfiles.get(workerId);
this.injectCpuProfileEvent(metaEvent.thread.process().id(), metaEvent.args['data']['workerThreadId'], cpuProfile);
}
this.cpuProfiles = null;
}
tracingBufferUsage(usage: number): void {
this.client.recordingProgress(usage);
}
eventsRetrievalProgress(progress: number): void {
this.client.loadingProgress(progress);
}
}
export interface Client {
recordingProgress(usage: number): void;
loadingStarted(): void;
processingStarted(): void;
loadingProgress(progress?: number): void;
loadingComplete(tracingModel: SDK.TracingModel.TracingModel|null): void;
}
export interface RecordingOptions {
enableJSSampling?: boolean;
capturePictures?: boolean;
captureFilmStrip?: boolean;
startCoverage?: boolean;
} | the_stack |
import React, { useEffect, useRef, useState } from 'react';
import { ImShrink2 } from '@react-icons/all-files/im/ImShrink2';
import { FaRegHandPointer } from '@react-icons/all-files/fa/FaRegHandPointer';
import {
EnergyMap as EnergyMapType,
Seam,
OnIterationArgs,
ImageSize,
resizeImage,
ALPHA_DELETE_THRESHOLD,
MAX_WIDTH_LIMIT,
MAX_HEIGHT_LIMIT,
} from '../utils/contentAwareResizer';
import EnergyMap from './EnergyMap';
import Seams from './Seams';
import defaultImgSrc from '../assets/02.jpg';
import Button, { BUTTON_KIND_SECONDARY } from './Button';
import FileSelector from './FileSelector';
import Checkbox from './Checkbox';
import Progress from './Progress';
import Input from './Input';
import FadeIn from './FadeIn';
import Mask from './Mask';
import { Coordinate, getPixel, setPixel } from '../utils/image';
import { MdLayersClear } from '@react-icons/all-files/md/MdLayersClear';
const defaultWidthScale = 50;
const defaultHeightScale = 70;
const minScale = 1;
const maxScale = 100;
const maxWidthLimit = MAX_WIDTH_LIMIT;
const maxHeightLimit = MAX_HEIGHT_LIMIT;
type ImageResizerProps = {
withSeam?: boolean,
withEnergyMap?: boolean,
};
const ImageResizer = (props: ImageResizerProps): React.ReactElement => {
const {
withSeam = false,
withEnergyMap = false,
} = props;
const [imgAuthor, setImgAuthor] = useState<string | null>('ian dooley');
const [imgAuthorURL, setImgAuthorURL] = useState<string | null>(
'https://unsplash.com/@sadswim?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText',
);
const [useNaturalSize, setUseNaturalSize] = useState<boolean>(false);
const [imageSrc, setImageSrc] = useState<string>(defaultImgSrc);
const [resizedImgSrc, setResizedImgSrc] = useState<string | null>(null);
const [energyMap, setEnergyMap] = useState<EnergyMapType | null>(null);
const [originalImgSize, setOriginalImgSize] = useState<ImageSize | null>(null);
const [originalImgViewSize, setOriginalImgViewSize] = useState<ImageSize | null>(null);
const [workingImgSize, setWorkingImgSize] = useState<ImageSize | null>(null);
const [seams, setSeams] = useState<Seam[] | null>(null);
const [isResizing, setIsResizing] = useState<boolean>(false);
const [progress, setProgress] = useState<number>(0);
const [maskImgData, setMaskImgData] = useState<ImageData | null>(null);
const [maskRevision, setMaskRevision] = useState<number>(0);
const [toWidthScale, setToWidthScale] = useState<number>(defaultWidthScale);
const [toWidthScaleString, setToWidthScaleString] = useState<string | undefined>(`${defaultWidthScale}`);
const [toHeightScale, setToHeightScale] = useState<number>(defaultHeightScale);
const [toHeightScaleString, setToHeightScaleString] = useState<string | undefined>(`${defaultHeightScale}`);
const imgRef = useRef<HTMLImageElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const onUseOriginalSizeChange = (state: boolean): void => {
setUseNaturalSize(state);
};
const onReset = (): void => {
setResizedImgSrc(null);
setSeams(null);
setWorkingImgSize(null);
setEnergyMap(null);
setProgress(0);
setOriginalImgViewSize(null);
};
const onFileSelect = (files: FileList | null): void => {
if (!files || !files.length) {
return;
}
setImgAuthor(null);
setImgAuthorURL(null);
onReset();
const imageURL = URL.createObjectURL(files[0]);
setImageSrc(imageURL);
};
const onWidthSizeChange = (size: string | undefined): void => {
const radix = 10;
const scale = Math.max(Math.min(parseInt(size || '0', radix), maxScale), minScale);
if (size) {
setToWidthScaleString(`${scale}`);
} else {
setToWidthScaleString(size);
}
setToWidthScale(scale);
};
const onHeightSizeChange = (size: string | undefined): void => {
const radix = 10;
const scale = Math.max(Math.min(parseInt(size || '0', radix), maxScale), minScale);
if (size) {
setToHeightScaleString(`${scale}`);
} else {
setToHeightScaleString(size);
}
setToHeightScale(scale);
};
const onFinish = (): void => {
if (!canvasRef.current) {
return;
}
const imageType = 'image/png';
canvasRef.current.toBlob((blob: Blob | null): void => {
if (!blob) {
return;
}
const imgUrl = URL.createObjectURL(blob);
setResizedImgSrc(imgUrl);
setIsResizing(false);
}, imageType);
};
const onClearMask = (): void => {
setMaskRevision(maskRevision + 1);
};
const onMaskDrawEnd = (imgData: ImageData): void => {
setMaskImgData(imgData);
};
const applyMask = (img: ImageData): void => {
if (!maskImgData) {
return;
}
const wRatio = maskImgData.width / img.width;
const hRatio = maskImgData.height / img.height;
const imgXYtoMaskXY = ({ x: imgX, y: imgY }: Coordinate): Coordinate => {
return {
x: Math.floor(imgX * wRatio),
y: Math.floor(imgY * hRatio),
};
};
for (let y = 0; y < img.height; y += 1) {
for (let x = 0; x < img.width; x += 1) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [mR, mG, mB, mA] = getPixel(
maskImgData,
imgXYtoMaskXY({ x, y }),
);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [iR, iG, iB, iA] = getPixel(img, { x, y });
if (mA) {
setPixel(img, { x, y }, [iR, iG, iB, ALPHA_DELETE_THRESHOLD]);
}
}
}
};
const onIteration = async (args: OnIterationArgs): Promise<void> => {
const {
seam,
img,
energyMap: nrgMap,
size: { w, h },
step,
steps,
} = args;
const canvas: HTMLCanvasElement | null = canvasRef.current;
if (!canvas) {
return;
}
canvas.width = w;
canvas.height = h;
const ctx: CanvasRenderingContext2D | null = canvas.getContext('2d');
if (!ctx) {
return;
}
ctx.putImageData(img, 0, 0, 0, 0, w, h);
setEnergyMap(nrgMap);
setSeams([seam]);
setWorkingImgSize({ w, h });
setProgress(step / steps);
};
const onResize = (): void => {
const srcImg: HTMLImageElement | null = imgRef.current;
if (!srcImg) {
return;
}
const canvas: HTMLCanvasElement | null = canvasRef.current;
if (!canvas) {
return;
}
onReset();
setIsResizing(true);
let w = useNaturalSize ? srcImg.naturalWidth : srcImg.width;
let h = useNaturalSize ? srcImg.naturalHeight : srcImg.height;
const ratio = w / h;
setOriginalImgViewSize({
w: srcImg.width,
h: srcImg.height,
});
if (w > maxWidthLimit) {
w = maxWidthLimit;
h = Math.floor(w / ratio);
}
if (h > maxHeightLimit) {
h = maxHeightLimit;
w = Math.floor(h * ratio);
}
canvas.width = w;
canvas.height = h;
const ctx: CanvasRenderingContext2D | null = canvas.getContext('2d');
if (!ctx) {
return;
}
ctx.drawImage(srcImg, 0, 0, w, h);
const img: ImageData = ctx.getImageData(0, 0, w, h);
applyMask(img);
const toWidth = Math.floor((toWidthScale * w) / 100);
const toHeight = Math.floor((toHeightScale * h) / 100);
resizeImage({
img,
toWidth,
toHeight,
onIteration,
}).then(() => {
onFinish();
});
};
useEffect(() => {
const srcImg: HTMLImageElement | null = imgRef.current;
if (!srcImg) {
return;
}
srcImg.addEventListener('load', () => {
if (!imgRef.current) {
return;
}
setOriginalImgSize({
w: imgRef.current.naturalWidth,
h: imgRef.current.naturalHeight,
});
setOriginalImgViewSize({
w: imgRef.current.width,
h: imgRef.current.height,
});
});
}, []);
useEffect(() => {
function updateSize(): void {
if (!imgRef.current) {
return;
}
setOriginalImgViewSize({
w: imgRef.current.width,
h: imgRef.current.height,
});
}
window.addEventListener('resize', updateSize);
return (): void => {
window.removeEventListener('resize', updateSize);
};
}, []);
const imgAuthorLink = imgAuthor && imgAuthorURL ? (
<div className="text-xs text-gray-400 mt-2 flex justify-center items-center font-light">
<div className="mr-1">
Photo by
</div>
<a
href={imgAuthorURL}
style={{ color: '#aaa', fontWeight: 300 }}
target="_blank"
rel="noreferrer"
>
{imgAuthor}
</a>
</div>
) : null;
const seamsCanvas = withSeam && workingImgSize && seams ? (
<div style={{ marginTop: `-${workingImgSize.h}px` }}>
<Seams seams={seams} width={workingImgSize.w} height={workingImgSize.h} />
</div>
) : null;
const originalImageSizeText = originalImgSize ? (
<sup className="text-xs text-gray-400 whitespace-nowrap">
{`${originalImgSize.w} x ${originalImgSize.h} px`}
</sup>
) : null;
const maskControls = (
<div>
<Button
onClick={onClearMask}
disabled={isResizing || !maskImgData}
kind={BUTTON_KIND_SECONDARY}
title="Clear mask"
className="rounded-full"
style={{ padding: '8px 8px', border: 0, outline: 'none' }}
>
<MdLayersClear size={16} />
</Button>
</div>
);
const mask = originalImgViewSize ? (
<div className="flex flex-col" style={{ marginTop: `-${originalImgViewSize.h}px` }}>
<Mask
width={originalImgViewSize.w}
height={originalImgViewSize.h}
disabled={isResizing}
onDrawEnd={onMaskDrawEnd}
revision={maskRevision}
/>
<div className="flex flex-row justify-end" style={{ marginTop: '-36px', zIndex: 100 }}>
<div className="mr-1">
{maskControls}
</div>
</div>
</div>
) : null;
const originalImage = (
<FadeIn>
<div className="flex flex-row justify-center items-center mb-1 sm:mb-0">
<div className="flex-1 sm:flex sm:flex-row sm:items-center">
<div className="sm:flex-1">
<b>Original image</b> {originalImageSizeText}
</div>
<div className="text-xs text-gray-400 flex flex-row items-center justify-self-end">
<div className="mr-1">
<FaRegHandPointer size={12} />
</div>
<div>
Mask to remove
</div>
</div>
</div>
</div>
<img src={imageSrc} alt="Original" ref={imgRef} style={{ margin: 0 }} />
{mask}
{imgAuthorLink}
</FadeIn>
);
const workingImageScrollableText = (
workingImgSize?.w && originalImgViewSize?.w && workingImgSize.w > originalImgViewSize.w
) ? <span className="text-xs text-gray-400 ml-4">↔︎ scrollable</span> : null;
const workingImageSizeText = workingImgSize ? (
<sup className="text-xs text-gray-400 whitespace-nowrap">
{`${workingImgSize.w} x ${workingImgSize.h} px`}
</sup>
) : null;
const workingImage = (
<FadeIn className={`mb-6 ${resizedImgSrc || !energyMap ? 'hidden' : ''}`}>
<div><b>Resized image</b> {workingImageSizeText} {workingImageScrollableText}</div>
<div className="overflow-scroll">
<canvas ref={canvasRef} />
{seamsCanvas}
</div>
</FadeIn>
);
const resultImageSizeText = workingImgSize ? (
<sup className="text-xs text-gray-400 whitespace-nowrap">
{`${workingImgSize.w} x ${workingImgSize.h} px`}
</sup>
) : null;
const resultImage = workingImgSize && resizedImgSrc ? (
<FadeIn className="mb-6">
<div><b>Resized image</b> {resultImageSizeText}</div>
<img src={resizedImgSrc} width={workingImgSize.w} height={workingImgSize.h} alt="Resized" style={{ margin: 0 }} />
</FadeIn>
) : null;
const debugEnergyMap = withEnergyMap && workingImgSize ? (
<FadeIn className="mb-6">
<div><b>Energy map</b></div>
<EnergyMap energyMap={energyMap} width={workingImgSize.w} height={workingImgSize.h} />
{seamsCanvas}
</FadeIn>
) : null;
const resizerControls = (
<div className="flex flex-col justify-start items-start mb-1">
<div className="mb-3 flex flex-row">
<div className="mr-2">
<FileSelector
onSelect={onFileSelect}
disabled={isResizing}
accept="image/png,image/jpeg"
>
Choose image
</FileSelector>
</div>
<div>
<Button
onClick={onResize}
disabled={isResizing || !toWidthScaleString}
startEnhancer={<ImShrink2 size={14} />}
>
Resize
</Button>
</div>
</div>
<div className="flex flex-col sm:flex-row">
<div className="mb-2 mr-6 flex flex-row items-center">
<div className="text-xs mr-1">Width</div>
<Input
onChange={onWidthSizeChange}
disabled={isResizing}
// @ts-ignore
type="number"
min={minScale}
max={maxScale}
className="w-14 text-center"
value={toWidthScaleString}
/>
<div className="text-xs ml-1 mr-4">%</div>
<div className="text-xs mr-1">Height</div>
<Input
onChange={onHeightSizeChange}
disabled={isResizing}
// @ts-ignore
type="number"
min={minScale}
max={maxScale}
className="w-14 text-center"
value={toHeightScaleString}
/>
<div className="text-xs ml-1">%</div>
</div>
<div className="mb-2">
<Checkbox disabled={isResizing} onChange={onUseOriginalSizeChange}>
<span className="text-xs">
Higher quality <span className="text-gray-400">(takes longer)</span>
</span>
</Checkbox>
</div>
</div>
</div>
);
const progressBar = (
<div className="mb-6">
<Progress progress={progress} />
</div>
);
return (
<>
{resizerControls}
{progressBar}
{workingImage}
{resultImage}
{debugEnergyMap}
{originalImage}
</>
);
};
export default ImageResizer; | the_stack |
import type {ComponentType} from './component';
import type {Dispatcher} from './dispatcher';
import type {Plan} from './planner';
import type {System, SystemBox, SystemType} from './system';
export const now = typeof window !== 'undefined' && typeof window.performance !== 'undefined' ?
performance.now.bind(performance) : Date.now.bind(Date);
// TODO: support replicated systems
// TODO: support continuously executed systems
/**
* A fluent DSL for specifying a system's scheduling constraints.
*
* Any given pair of systems will be ordered by the first of the following rules that matches:
* 1. A system was explicitly placed `before` or `after` another.
* 2. A system was explicitly left unordered with respect to another using `inAnyOrderWith`.
* 3. A system was implicitly placed before or after another system based on the components the
* other system reads or writes, using `beforeReadsFrom`, `afterReadsFrom`, `beforeWritesTo` or
* `afterWritesTo`.
* 4. A system was implicitly placed after another because it reads a component that the other
* system writes.
*
* If there are multiple constraints at the same priority level they will conflict and create a
* cycle. If there are any cycles in the order graph (whether due to explicit conflicts or implicit
* circular dependencies), world creation will fail with an informative error and you'll need to
* break the cycles by adding scheduling constraints to the systems involved.
*/
export class ScheduleBuilder {
private __systems: SystemBox[];
private __dispatcher: Dispatcher;
constructor(
private readonly __callback: (s: ScheduleBuilder) => void,
private readonly __schedule: Schedule
) {}
__build(systems: SystemBox[], name: string): void {
try {
this.__systems = systems;
this.__dispatcher = systems[0].dispatcher;
this.__callback(this);
} catch (e: any) {
e.message = `Failed to build schedule in ${name}: ${e.message}`;
throw e;
}
}
/**
* Force this system to only execute on the main thread. This is needed for systems that interact
* with APIs only available in the main thread such as the DOM.
* @returns The builder for chaining calls.
*/
get onMainThread(): this {
CHECK: this.__checkNoLaneAssigned();
this.__dispatcher.planner.mainLane?.add(...this.__systems);
return this;
}
/**
* Execute this system consistently on a single thread. This is the default behavior to
* accommodate systems with internal state.
* @returns The builder for chaining calls.
*/
get onOneThread(): this {
CHECK: this.__checkNoLaneAssigned();
this.__dispatcher.planner.createLane().add(...this.__systems);
return this;
}
/**
* Replicate this system among multiple threads and execute it on any one of them, possibly a
* different one each time. This allows Becsy to better utilize available CPUs but requires the
* system to be stateless (except for queries and attached systems). Note that `prepare` and
* `initialize` will be called on each replicated instance of the system!
* @returns The builder for chaining calls.
*/
get onManyThreads(): this {
CHECK: this.__checkNoLaneAssigned();
this.__dispatcher.planner.replicatedLane?.add(...this.__systems);
for (const system of this.__systems) system.stateless = true;
return this;
}
private __checkNoLaneAssigned(): void {
if (this.__systems.some(system => system.lane)) {
throw new Error(`Threading semantics already specified`);
}
}
/**
* Schedule this system before all the given ones (highest priority).
* @param systemTypes The systems or groups that this one should precede.
* @returns The builder for chaining calls.
*/
before(...systemTypes: (SystemType<System> | SystemGroup)[]): this {
for (const type of systemTypes) {
for (const other of this.__dispatcher.getSystems(type)) {
for (const system of this.__systems) {
this.__dispatcher.planner.graph.addEdge(system, other, 4);
}
}
}
return this;
}
/**
* Schedule this system after all the given ones (highest priority).
* @param systemTypes The systems or groups that this one should follow.
* @returns The builder for chaining calls.
*/
after(...systemTypes: (SystemType<System> | SystemGroup)[]): this {
for (const type of systemTypes) {
for (const other of this.__dispatcher.getSystems(type)) {
for (const system of this.__systems) {
this.__dispatcher.planner.graph.addEdge(other, system, 4);
}
}
}
return this;
}
/**
* Schedule this system in any order relative to the given ones (high priority).
* @param systemTypes The systems or groups whose order doesn't matter relative to this one.
* @returns The builder for chaining calls.
*/
inAnyOrderWith(...systemTypes: (SystemType<System> | SystemGroup)[]): this {
for (const type of systemTypes) {
for (const other of this.__dispatcher.getSystems(type)) {
for (const system of this.__systems) {
this.__dispatcher.planner.graph.denyEdge(system, other, 3);
}
}
}
return this;
}
/**
* Schedule this system before all other systems that declared a read dependency on the given
* component types (medium priority).
* @param componentTypes The component types whose readers this system should precede.
* @returns The builder for chaining calls.
*/
beforeReadsFrom(...componentTypes: ComponentType<any>[]): this {
for (const componentType of componentTypes) {
for (const other of this.__dispatcher.planner.readers!.get(componentType)!) {
for (const system of this.__systems) {
this.__dispatcher.planner.graph.addEdge(system, other, 2);
}
}
}
return this;
}
/**
* Schedule this system after all other systems that declared a read dependency on the given
* component types (medium priority).
* @param componentTypes The component types whose readers this system should follow.
* @returns The builder for chaining calls.
*/
afterReadsFrom(...componentTypes: ComponentType<any>[]): this {
for (const componentType of componentTypes) {
for (const other of this.__dispatcher.planner.readers!.get(componentType)!) {
for (const system of this.__systems) {
this.__dispatcher.planner.graph.addEdge(other, system, 2);
}
}
}
return this;
}
/**
* Schedule this system before all other systems that declared a write dependency on the given
* component types (medium priority).
* @param componentTypes The component types whose writers this system should precede.
* @returns The builder for chaining calls.
*/
beforeWritesTo(...componentTypes: ComponentType<any>[]): this {
for (const componentType of componentTypes) {
for (const other of this.__dispatcher.planner.writers!.get(componentType)!) {
for (const system of this.__systems) {
this.__dispatcher.planner.graph.addEdge(system, other, 2);
}
}
}
return this;
}
/**
* Schedule this system after all other systems that declared a write dependency on the given
* component types (medium priority).
* @param componentTypes The component types whose writers this system should follow.
* @returns The builder for chaining calls.
*/
afterWritesTo(...componentTypes: ComponentType<any>[]): this {
for (const componentType of componentTypes) {
for (const other of this.__dispatcher.planner.writers!.get(componentType)!) {
for (const system of this.__systems) {
this.__dispatcher.planner.graph.addEdge(other, system, 2);
}
}
}
return this;
}
}
/**
* A placeholder object returned from {@link System.schedule} with no public API.
*/
export class Schedule {
}
export type GroupContentsArray = (SystemType<System> | Record<string, unknown> | SystemGroup)[];
export class SystemGroupImpl {
__plan: Plan;
__executed = false;
__systems: SystemBox[];
__scheduleBuilder: ScheduleBuilder | undefined | null;
constructor(readonly __contents: GroupContentsArray) { }
__collectSystems(dispatcher: Dispatcher): SystemBox[] {
if (!this.__systems) {
this.__systems = [];
for (const item of this.__contents) {
if (item instanceof Function && item.__system) {
this.__systems.push(dispatcher.systemsByClass.get(item)!);
} else if (item instanceof SystemGroupImpl) {
this.__systems.push(...item.__collectSystems(dispatcher));
}
}
}
return this.__systems;
}
__buildSchedule(): void {
this.__scheduleBuilder?.__build(this.__systems, `a group`);
this.__scheduleBuilder = null;
}
/**
* Creates scheduling constraints for all systems in the group; this works exactly as if the
* call was made individually to every {@link System.schedule}. Can be called at most once.
* @param buildCallback A function that constrains the schedule using a small DSL. See
* {@link ScheduleBuilder} for the API.
* @returns This group for chaining calls.
*/
schedule(buildCallback: (s: ScheduleBuilder) => void): this {
CHECK: if (this.__scheduleBuilder === null) {
throw new Error(`Attempt to define group schedule after world initialized`);
}
CHECK: if (this.__scheduleBuilder) {
throw new Error(`Attempt to define multiple schedules in a group`);
}
this.__scheduleBuilder = new ScheduleBuilder(buildCallback, new Schedule());
return this;
}
}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface SystemGroup extends SystemGroupImpl { }
export class FrameImpl {
private executing: boolean;
private time = now() / 1000;
private delta: number;
constructor(private readonly dispatcher: Dispatcher, private readonly groups: SystemGroup[]) {
CHECK: if (groups.length === 0) {
throw new Error('At least one system group needed');
}
CHECK: for (const group of groups) {
if (!dispatcher.systemGroups.includes(group)) {
throw new Error('Some groups in the frame are not parts of the world defs');
}
}
}
/**
* Indicates that execution of a frame has begun and locks in the default `time` and `delta`.
* Must be called once at the beginning of each frame, prior to any calls to `execute`. Must be
* bookended by a call to `end`.
*
* You cannot call `begin` while any other executors are running.
*/
begin(): void {
CHECK: if (this.executing) throw new Error('Frame already executing');
this.executing = true;
const lastTime = this.dispatcher.lastTime ?? this.time;
this.time = now() / 1000;
this.delta = this.time - lastTime;
this.dispatcher.startFrame(this.time);
}
/**
* Indicates that execution of a frame has completed. Must be called once at the end of each
* frame, after any calls to `execute`.
*/
end(): void {
CHECK: if (!this.executing) throw new Error('Frame not executing');
this.executing = false;
allExecuted: {
for (const group of this.groups) if (!group.__executed) break allExecuted;
for (const group of this.groups) group.__executed = false;
this.dispatcher.completeCycle();
}
this.dispatcher.completeFrame();
}
/**
* Executes a group of systems. If your world is single-threaded then execution is synchronous
* and you can ignore the returned promise.
*
* You cannot execute individual systems, unless you create a singleton group to hold them.
*
* @param group The group of systems to execute. Must be a member of the group list passed in
* when this executor was created.
*
* @param time The time of this frame's execution. This will be set on every system's `time`
* property and defaults to the time when `begin` was called. It's not used internally so you can
* pass in any numeric value that's expected by your systems.
*
* @param delta The duration since the last frame's execution. This will be set on every system's
* `delta` property and default to the duration since any previous frame's `begin` was called.
* It's not used internally so you can pass in any numeric value that's expected by your systems.
*/
execute(group: SystemGroup, time?: number, delta?: number): Promise<void> {
CHECK: if (!this.groups.includes(group)) throw new Error('Group not included in this frame');
CHECK: if (!this.executing) throw new Error('Frame not executing');
return group.__plan.execute(time ?? this.time, delta ?? this.delta);
}
}
/**
* A frame executor that lets you manually run system groups. You can create one by calling
* `world.createCustomExecutor`.
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface Frame extends FrameImpl { } | the_stack |
* @module Views
*/
import {
AxisOrder, ClipPlane, ConvexClipPlaneSet, Geometry, GrowableXYZArray, LowAndHighXY, LowAndHighXYZ, Map4d, Matrix3d, Plane3dByOriginAndUnitNormal, Point3d, Range3d, Transform, Vector3d, XYAndZ,
} from "@itwin/core-geometry";
/** The 8 corners of the [Normalized Plane Coordinate]($docs/learning/glossary.md#npc) cube.
* @public
*/
export enum Npc {
/** Left bottom rear */
_000 = 0,
/** Right bottom rear */
_100 = 1,
/** Left top rear */
_010 = 2,
/** Right top rear */
_110 = 3,
/** Left bottom front */
_001 = 4,
/** Right bottom front */
_101 = 5,
/** Left top front */
_011 = 6,
/** Right top front */
_111 = 7,
LeftBottomRear = 0,
RightBottomRear = 1,
LeftTopRear = 2,
RightTopRear = 3,
LeftBottomFront = 4,
RightBottomFront = 5,
LeftTopFront = 6,
RightTopFront = 7,
/** useful for sizing arrays */
CORNER_COUNT = 8,
}
/** The 8 corners of an [[Npc]] Frustum.
* @public
*/
export const NpcCorners = [ // eslint-disable-line @typescript-eslint/naming-convention
new Point3d(0.0, 0.0, 0.0),
new Point3d(1.0, 0.0, 0.0),
new Point3d(0.0, 1.0, 0.0),
new Point3d(1.0, 1.0, 0.0),
new Point3d(0.0, 0.0, 1.0),
new Point3d(1.0, 0.0, 1.0),
new Point3d(0.0, 1.0, 1.0),
new Point3d(1.0, 1.0, 1.0),
];
NpcCorners.forEach((corner) => Object.freeze(corner));
Object.freeze(NpcCorners);
/** The center point of the [Normalized Plane Coordinate]($docs/learning/glossary.md#npc) cube.
* @public
*/
export const NpcCenter = new Point3d(.5, .5, .5); // eslint-disable-line @typescript-eslint/naming-convention
Object.freeze(NpcCenter);
/** The region of physical (3d) space that appears in a view. It forms the field-of-view of a camera.
* It is stored as 8 points, in [[Npc]] order, that must define a truncated pyramid.
* @public
*/
export class Frustum {
/** Array of the 8 points of this Frustum. */
public readonly points: Point3d[] = [];
/** Constructor for Frustum. Members are initialized to the Npc cube. */
public constructor() { for (let i = 0; i < 8; ++i) this.points[i] = NpcCorners[i].clone(); }
/** Initialize this Frustum to the 8 corners of the NPC cube. */
public initNpc() { for (let i = 0; i < 8; ++i) Point3d.createFrom(NpcCorners[i], this.points[i]); return this; }
/** Get a corner Point from this Frustum. */
public getCorner(i: number) { return this.points[i]; }
/** Get the point at the center of this Frustum (halfway between RightTopFront and LeftBottomRear. */
public getCenter(): Point3d { return this.getCorner(Npc.RightTopFront).interpolate(0.5, this.getCorner(Npc.LeftBottomRear)); }
/** Get the distance between two corners of this Frustum. */
public distance(corner1: number, corner2: number): number { return this.getCorner(corner1).distance(this.getCorner(corner2)); }
/** Get the ratio of the length of the diagonal of the front plane to the diagonal of the back plane. */
public getFraction(): number { return Geometry.safeDivideFraction(this.distance(Npc.LeftTopFront, Npc.RightBottomFront), this.distance(Npc.LeftTopRear, Npc.RightBottomRear), 0); }
/** Multiply all the points of this Frustum by a Transform, in place. */
public multiply(trans: Transform): void { trans.multiplyPoint3dArrayInPlace(this.points); }
/** Offset all of the points of this Frustum by a vector. */
public translate(offset: XYAndZ): void { for (const pt of this.points) pt.plus(offset, pt); }
/** Transform all the points of this Frustum and return the result in another Frustum. */
public transformBy(trans: Transform, result?: Frustum): Frustum { result = result ? result : new Frustum(); trans.multiplyPoint3dArray(this.points, result.points); return result; }
/** Calculate a bounding range from the 8 points in this Frustum. */
public toRange(range?: Range3d): Range3d { range = range ? range : new Range3d(); Range3d.createArray(this.points, range); return range; }
/** Make a copy of this Frustum.
* @param result Optional Frustum for copy. If undefined allocate a new Frustum.
*/
public clone(result?: Frustum): Frustum { result = result ? result : new Frustum(); result.setFrom(this); return result; }
/** Set the points of this Frustum to be copies of the points in another Frustum. */
public setFrom(other: Frustum) { this.setFromCorners(other.points); }
/** Set the points of this frustum from array of corner points in NPC order. */
public setFromCorners(corners: Point3d[]) { for (let i = 0; i < 8; ++i) this.points[i].setFrom(corners[i]); }
/** Scale this Frustum, in place, about its center by a scale factor. */
public scaleAboutCenter(scale: number): void {
const orig = this.clone();
const f = 0.5 * (1.0 + scale);
orig.points[Npc._111].interpolate(f, orig.points[Npc._000], this.points[Npc._000]);
orig.points[Npc._011].interpolate(f, orig.points[Npc._100], this.points[Npc._100]);
orig.points[Npc._101].interpolate(f, orig.points[Npc._010], this.points[Npc._010]);
orig.points[Npc._001].interpolate(f, orig.points[Npc._110], this.points[Npc._110]);
orig.points[Npc._110].interpolate(f, orig.points[Npc._001], this.points[Npc._001]);
orig.points[Npc._010].interpolate(f, orig.points[Npc._101], this.points[Npc._101]);
orig.points[Npc._100].interpolate(f, orig.points[Npc._011], this.points[Npc._011]);
orig.points[Npc._000].interpolate(f, orig.points[Npc._111], this.points[Npc._111]);
}
/** The point at the center of the front face of this frustum */
public get frontCenter() { return this.getCorner(Npc.LeftBottomFront).interpolate(.5, this.getCorner(Npc.RightTopFront)); }
/** The point at the center of the rear face of this frustum */
public get rearCenter() { return this.getCorner(Npc.LeftBottomRear).interpolate(.5, this.getCorner(Npc.RightTopRear)); }
/** Scale this frustum's XY (viewing) plane about its center */
public scaleXYAboutCenter(scale: number) {
const frontCenter = this.frontCenter, rearCenter = this.rearCenter;
frontCenter.interpolate(scale, this.points[Npc.LeftTopFront], this.points[Npc.LeftTopFront]);
frontCenter.interpolate(scale, this.points[Npc.RightTopFront], this.points[Npc.RightTopFront]);
frontCenter.interpolate(scale, this.points[Npc.LeftBottomFront], this.points[Npc.LeftBottomFront]);
frontCenter.interpolate(scale, this.points[Npc.RightBottomFront], this.points[Npc.RightBottomFront]);
rearCenter.interpolate(scale, this.points[Npc.LeftTopRear], this.points[Npc.LeftTopRear]);
rearCenter.interpolate(scale, this.points[Npc.RightTopRear], this.points[Npc.RightTopRear]);
rearCenter.interpolate(scale, this.points[Npc.LeftBottomRear], this.points[Npc.LeftBottomRear]);
rearCenter.interpolate(scale, this.points[Npc.RightBottomRear], this.points[Npc.RightBottomRear]);
}
/** Create a Map4d that converts world coordinates to/from [[Npc]] coordinates of this Frustum. */
public toMap4d(): Map4d | undefined {
const org = this.getCorner(Npc.LeftBottomRear);
const xVec = org.vectorTo(this.getCorner(Npc.RightBottomRear));
const yVec = org.vectorTo(this.getCorner(Npc.LeftTopRear));
const zVec = org.vectorTo(this.getCorner(Npc.LeftBottomFront));
return Map4d.createVectorFrustum(org, xVec, yVec, zVec, this.getFraction());
}
/** Get the rotation matrix to the frame of this frustum. This is equivalent to the view rotation matrix. */
public getRotation(result?: Matrix3d): Matrix3d | undefined {
const org = this.getCorner(Npc.LeftBottomRear);
const xVec = org.vectorTo(this.getCorner(Npc.RightBottomRear));
const yVec = org.vectorTo(this.getCorner(Npc.LeftTopRear));
const matrix = Matrix3d.createRigidFromColumns(xVec, yVec, AxisOrder.XYZ, result);
if (matrix)
matrix.transposeInPlace();
return matrix;
}
/** Get the eye point - undefined if parallel projection */
public getEyePoint(result?: Point3d): Point3d | undefined {
const fraction = this.getFraction();
if (Math.abs(fraction - 1) < 1E-8)
return undefined; // Parallel.
const org = this.getCorner(Npc.LeftBottomRear);
const zVec = org.vectorTo(this.getCorner(Npc.LeftBottomFront));
return org.plusScaled(zVec, 1 / (1 - fraction), result);
}
/** Invalidate this Frustum by setting all 8 points to zero. */
public invalidate(): void { for (let i = 0; i < 8; ++i) this.points[i].set(0, 0, 0); }
/** Return true if this Frustum is equal to another Frustum */
public equals(rhs: Frustum): boolean {
for (let i = 0; i < 8; ++i) {
if (!this.points[i].isExactEqual(rhs.points[i]))
return false;
}
return true;
}
/** Return true if all of the points in this Frustum are *almost* the same as the points in another Frustum.
* @see [[equals]], [XYZ.isAlmostEqual]($geometry)
*/
public isSame(other: Frustum): boolean { for (let i = 0; i < 8; ++i) { if (!this.points[i].isAlmostEqual(other.points[i])) return false; } return true; }
/** Initialize this Frustum from a Range */
public initFromRange(range: LowAndHighXYZ | LowAndHighXY): void {
const getZ = (arg: any): number => arg.z !== undefined ? arg.z : 0;
const pts = this.points;
pts[0].x = pts[2].x = pts[4].x = pts[6].x = range.low.x;
pts[1].x = pts[3].x = pts[5].x = pts[7].x = range.high.x;
pts[0].y = pts[1].y = pts[4].y = pts[5].y = range.low.y;
pts[2].y = pts[3].y = pts[6].y = pts[7].y = range.high.y;
pts[0].z = pts[1].z = pts[2].z = pts[3].z = getZ(range.low);
pts[4].z = pts[5].z = pts[6].z = pts[7].z = getZ(range.high);
}
/** Create a new Frustum from a Range3d */
public static fromRange(range: LowAndHighXYZ | LowAndHighXY, out?: Frustum): Frustum {
const frustum = undefined !== out ? out : new Frustum();
frustum.initFromRange(range);
return frustum;
}
/** Return true if this Frustum has a mirror (is not in the correct order.) */
public get hasMirror(): boolean {
const pts = this.points;
const u = pts[Npc._000].vectorTo(pts[Npc._001]);
const v = pts[Npc._000].vectorTo(pts[Npc._010]);
const w = pts[Npc._000].vectorTo(pts[Npc._100]);
return (u.tripleProduct(v, w) > 0);
}
/** Make sure the frustum point order does not include mirroring. If so, reverse the order. */
public fixPointOrder(): void {
if (!this.hasMirror)
return;
// frustum has mirroring, reverse points
const pts = this.points;
for (let i = 0; i < 8; i += 2) {
const tmpPoint = pts[i];
pts[i] = pts[i + 1];
pts[i + 1] = tmpPoint;
}
}
/** Get a convex set of clipping planes bounding the region contained by this Frustum. */
public getRangePlanes(clipFront: boolean, clipBack: boolean, expandPlaneDistance: number): ConvexClipPlaneSet {
const convexSet = ConvexClipPlaneSet.createEmpty();
const scratchNormal = Vector3d.create();
Vector3d.createCrossProductToPoints(this.points[5], this.points[3], this.points[1], scratchNormal);
if (scratchNormal.normalizeInPlace())
convexSet.addPlaneToConvexSet(ClipPlane.createNormalAndDistance(scratchNormal, scratchNormal.dotProduct(this.points[1]) - expandPlaneDistance));
Vector3d.createCrossProductToPoints(this.points[2], this.points[4], this.points[0], scratchNormal);
if (scratchNormal.normalizeInPlace())
convexSet.addPlaneToConvexSet(ClipPlane.createNormalAndDistance(scratchNormal, scratchNormal.dotProduct(this.points[0]) - expandPlaneDistance));
Vector3d.createCrossProductToPoints(this.points[3], this.points[6], this.points[2], scratchNormal);
if (scratchNormal.normalizeInPlace())
convexSet.addPlaneToConvexSet(ClipPlane.createNormalAndDistance(scratchNormal, scratchNormal.dotProduct(this.points[2]) - expandPlaneDistance));
Vector3d.createCrossProductToPoints(this.points[4], this.points[1], this.points[0], scratchNormal);
if (scratchNormal.normalizeInPlace())
convexSet.addPlaneToConvexSet(ClipPlane.createNormalAndDistance(scratchNormal, scratchNormal.dotProduct(this.points[0]) - expandPlaneDistance));
if (clipBack) {
Vector3d.createCrossProductToPoints(this.points[1], this.points[2], this.points[0], scratchNormal);
if (scratchNormal.normalizeInPlace())
convexSet.addPlaneToConvexSet(ClipPlane.createNormalAndDistance(scratchNormal, scratchNormal.dotProduct(this.points[0]) - expandPlaneDistance));
}
if (clipFront) {
Vector3d.createCrossProductToPoints(this.points[6], this.points[5], this.points[4], scratchNormal);
if (scratchNormal.normalizeInPlace())
convexSet.addPlaneToConvexSet(ClipPlane.createNormalAndDistance(scratchNormal, scratchNormal.dotProduct(this.points[4]) - expandPlaneDistance));
}
return convexSet;
}
/** Get a (convex) polygon that represents the intersection of this frustum with a plane, or undefined if no intersection exists */
public getIntersectionWithPlane(plane: Plane3dByOriginAndUnitNormal): Point3d[] | undefined {
const clipPlane = ClipPlane.createPlane(plane);
const loopPoints = clipPlane.intersectRange(this.toRange(), true);
if (undefined === loopPoints)
return undefined;
const convexSet = this.getRangePlanes(false, false, 0);
const workPoints = new GrowableXYZArray();
const outPoints = new GrowableXYZArray();
convexSet.polygonClip(loopPoints, outPoints, workPoints);
return outPoints.length < 4 ? undefined : outPoints.getPoint3dArray();
}
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* A Google Cloud IoT Core device registry.
*
* To get more information about DeviceRegistry, see:
*
* * [API documentation](https://cloud.google.com/iot/docs/reference/cloudiot/rest/)
* * How-to Guides
* * [Official Documentation](https://cloud.google.com/iot/docs/)
*
* ## Example Usage
* ### Cloudiot Device Registry Basic
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const test_registry = new gcp.iot.Registry("test-registry", {});
* ```
* ### Cloudiot Device Registry Single Event Notification Configs
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const default_telemetry = new gcp.pubsub.Topic("default-telemetry", {});
* const test_registry = new gcp.iot.Registry("test-registry", {eventNotificationConfigs: [{
* pubsubTopicName: default_telemetry.id,
* subfolderMatches: "",
* }]});
* ```
* ### Cloudiot Device Registry Full
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
* import * from "fs";
*
* const default_devicestatus = new gcp.pubsub.Topic("default-devicestatus", {});
* const default_telemetry = new gcp.pubsub.Topic("default-telemetry", {});
* const additional_telemetry = new gcp.pubsub.Topic("additional-telemetry", {});
* const test_registry = new gcp.iot.Registry("test-registry", {
* eventNotificationConfigs: [
* {
* pubsubTopicName: additional_telemetry.id,
* subfolderMatches: "test/path",
* },
* {
* pubsubTopicName: default_telemetry.id,
* subfolderMatches: "",
* },
* ],
* stateNotificationConfig: {
* pubsub_topic_name: default_devicestatus.id,
* },
* mqttConfig: {
* mqtt_enabled_state: "MQTT_ENABLED",
* },
* httpConfig: {
* http_enabled_state: "HTTP_ENABLED",
* },
* logLevel: "INFO",
* credentials: [{
* publicKeyCertificate: {
* format: "X509_CERTIFICATE_PEM",
* certificate: fs.readFileSync("test-fixtures/rsa_cert.pem"),
* },
* }],
* });
* ```
*
* ## Import
*
* DeviceRegistry can be imported using any of these accepted formats
*
* ```sh
* $ pulumi import gcp:iot/registry:Registry default {{project}}/locations/{{region}}/registries/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:iot/registry:Registry default {{project}}/{{region}}/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:iot/registry:Registry default {{region}}/{{name}}
* ```
*
* ```sh
* $ pulumi import gcp:iot/registry:Registry default {{name}}
* ```
*/
export class Registry extends pulumi.CustomResource {
/**
* Get an existing Registry resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: RegistryState, opts?: pulumi.CustomResourceOptions): Registry {
return new Registry(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:iot/registry:Registry';
/**
* Returns true if the given object is an instance of Registry. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is Registry {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Registry.__pulumiType;
}
/**
* List of public key certificates to authenticate devices.
* The structure is documented below.
*/
public readonly credentials!: pulumi.Output<outputs.iot.RegistryCredential[] | undefined>;
/**
* List of configurations for event notifications, such as PubSub topics
* to publish device events to.
* Structure is documented below.
*/
public readonly eventNotificationConfigs!: pulumi.Output<outputs.iot.RegistryEventNotificationConfigItem[]>;
/**
* Activate or deactivate HTTP.
* The structure is documented below.
*/
public readonly httpConfig!: pulumi.Output<{[key: string]: any}>;
/**
* The default logging verbosity for activity from devices in this
* registry. Specifies which events should be written to logs. For
* example, if the LogLevel is ERROR, only events that terminate in
* errors will be logged. LogLevel is inclusive; enabling INFO logging
* will also enable ERROR logging.
* Default value is `NONE`.
* Possible values are `NONE`, `ERROR`, `INFO`, and `DEBUG`.
*/
public readonly logLevel!: pulumi.Output<string | undefined>;
/**
* Activate or deactivate MQTT.
* The structure is documented below.
*/
public readonly mqttConfig!: pulumi.Output<{[key: string]: any}>;
/**
* A unique name for the resource, required by device registry.
*/
public readonly name!: pulumi.Output<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
public readonly project!: pulumi.Output<string>;
/**
* The region in which the created registry should reside.
* If it is not provided, the provider region is used.
*/
public readonly region!: pulumi.Output<string>;
/**
* A PubSub topic to publish device state updates.
* The structure is documented below.
*/
public readonly stateNotificationConfig!: pulumi.Output<{[key: string]: any} | undefined>;
/**
* Create a Registry resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args?: RegistryArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: RegistryArgs | RegistryState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as RegistryState | undefined;
inputs["credentials"] = state ? state.credentials : undefined;
inputs["eventNotificationConfigs"] = state ? state.eventNotificationConfigs : undefined;
inputs["httpConfig"] = state ? state.httpConfig : undefined;
inputs["logLevel"] = state ? state.logLevel : undefined;
inputs["mqttConfig"] = state ? state.mqttConfig : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["project"] = state ? state.project : undefined;
inputs["region"] = state ? state.region : undefined;
inputs["stateNotificationConfig"] = state ? state.stateNotificationConfig : undefined;
} else {
const args = argsOrState as RegistryArgs | undefined;
inputs["credentials"] = args ? args.credentials : undefined;
inputs["eventNotificationConfigs"] = args ? args.eventNotificationConfigs : undefined;
inputs["httpConfig"] = args ? args.httpConfig : undefined;
inputs["logLevel"] = args ? args.logLevel : undefined;
inputs["mqttConfig"] = args ? args.mqttConfig : undefined;
inputs["name"] = args ? args.name : undefined;
inputs["project"] = args ? args.project : undefined;
inputs["region"] = args ? args.region : undefined;
inputs["stateNotificationConfig"] = args ? args.stateNotificationConfig : undefined;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
const aliasOpts = { aliases: [{ type: "gcp:kms/registry:Registry" }] };
opts = pulumi.mergeOptions(opts, aliasOpts);
super(Registry.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Registry resources.
*/
export interface RegistryState {
/**
* List of public key certificates to authenticate devices.
* The structure is documented below.
*/
credentials?: pulumi.Input<pulumi.Input<inputs.iot.RegistryCredential>[]>;
/**
* List of configurations for event notifications, such as PubSub topics
* to publish device events to.
* Structure is documented below.
*/
eventNotificationConfigs?: pulumi.Input<pulumi.Input<inputs.iot.RegistryEventNotificationConfigItem>[]>;
/**
* Activate or deactivate HTTP.
* The structure is documented below.
*/
httpConfig?: pulumi.Input<{[key: string]: any}>;
/**
* The default logging verbosity for activity from devices in this
* registry. Specifies which events should be written to logs. For
* example, if the LogLevel is ERROR, only events that terminate in
* errors will be logged. LogLevel is inclusive; enabling INFO logging
* will also enable ERROR logging.
* Default value is `NONE`.
* Possible values are `NONE`, `ERROR`, `INFO`, and `DEBUG`.
*/
logLevel?: pulumi.Input<string>;
/**
* Activate or deactivate MQTT.
* The structure is documented below.
*/
mqttConfig?: pulumi.Input<{[key: string]: any}>;
/**
* A unique name for the resource, required by device registry.
*/
name?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* The region in which the created registry should reside.
* If it is not provided, the provider region is used.
*/
region?: pulumi.Input<string>;
/**
* A PubSub topic to publish device state updates.
* The structure is documented below.
*/
stateNotificationConfig?: pulumi.Input<{[key: string]: any}>;
}
/**
* The set of arguments for constructing a Registry resource.
*/
export interface RegistryArgs {
/**
* List of public key certificates to authenticate devices.
* The structure is documented below.
*/
credentials?: pulumi.Input<pulumi.Input<inputs.iot.RegistryCredential>[]>;
/**
* List of configurations for event notifications, such as PubSub topics
* to publish device events to.
* Structure is documented below.
*/
eventNotificationConfigs?: pulumi.Input<pulumi.Input<inputs.iot.RegistryEventNotificationConfigItem>[]>;
/**
* Activate or deactivate HTTP.
* The structure is documented below.
*/
httpConfig?: pulumi.Input<{[key: string]: any}>;
/**
* The default logging verbosity for activity from devices in this
* registry. Specifies which events should be written to logs. For
* example, if the LogLevel is ERROR, only events that terminate in
* errors will be logged. LogLevel is inclusive; enabling INFO logging
* will also enable ERROR logging.
* Default value is `NONE`.
* Possible values are `NONE`, `ERROR`, `INFO`, and `DEBUG`.
*/
logLevel?: pulumi.Input<string>;
/**
* Activate or deactivate MQTT.
* The structure is documented below.
*/
mqttConfig?: pulumi.Input<{[key: string]: any}>;
/**
* A unique name for the resource, required by device registry.
*/
name?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* The region in which the created registry should reside.
* If it is not provided, the provider region is used.
*/
region?: pulumi.Input<string>;
/**
* A PubSub topic to publish device state updates.
* The structure is documented below.
*/
stateNotificationConfig?: pulumi.Input<{[key: string]: any}>;
} | the_stack |
* @author Kuitos
* @since 2020-3-31
*/
import { SandBox, SandBoxType } from '../interfaces';
import { nextTick, uniq } from '../utils';
import { attachDocProxySymbol, getTargetValue } from './common';
import { clearSystemJsProps, interceptSystemJsProps } from './noise/systemjs';
// zone.js will overwrite Object.defineProperty
const rawObjectDefineProperty = Object.defineProperty;
/*
variables who are impossible to be overwrite need to be escaped from proxy sandbox for performance reasons
*/
const unscopables = {
undefined: true,
Array: true,
Object: true,
String: true,
Boolean: true,
Math: true,
eval: true,
Number: true,
Symbol: true,
parseFloat: true,
Float32Array: true,
};
type SymbolTarget = 'target' | 'rawWindow';
type FakeWindow = Window & Record<PropertyKey, any>;
/**
* 拷贝全局对象上所有不可配置属性到 fakeWindow 对象,并将这些属性的属性描述符改为可配置的然后冻结
* 将启动具有 getter 属性的属性再存入 propertiesWithGetter map 中
* @param global 全局对象 => window
*/
function createFakeWindow(global: Window) {
// 记录 window 对象上的 getter 属性,原生的有:window、document、location、top,比如:Object.getOwnPropertyDescriptor(window, 'window') => {set: undefined, enumerable: true, configurable: false, get: ƒ}
// propertiesWithGetter = {"window" => true, "document" => true, "location" => true, "top" => true, "__VUE_DEVTOOLS_GLOBAL_HOOK__" => true}
const propertiesWithGetter = new Map<PropertyKey, boolean>();
// 存储 window 对象中所有不可配置的属性和值
const fakeWindow = {} as FakeWindow;
/*
copy the non-configurable property of global to fakeWindow
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/getOwnPropertyDescriptor
> A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object.
*/
Object.getOwnPropertyNames(global)
// 遍历出 window 对象所有不可配置属性
.filter(p => {
const descriptor = Object.getOwnPropertyDescriptor(global, p);
return !descriptor?.configurable;
})
.forEach(p => {
// 得到属性描述符
const descriptor = Object.getOwnPropertyDescriptor(global, p);
if (descriptor) {
// 获取其 get 属性
const hasGetter = Object.prototype.hasOwnProperty.call(descriptor, 'get');
/*
make top/self/window property configurable and writable, otherwise it will cause TypeError while get trap return.
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/get
> The value reported for a property must be the same as the value of the corresponding target object property if the target object property is a non-writable, non-configurable data property.
*/
if (
p === 'top' ||
p === 'parent' ||
p === 'self' ||
p === 'window' ||
(process.env.NODE_ENV === 'test' && (p === 'mockTop' || p === 'mockSafariTop'))
) {
// 将 top、parent、self、window 这几个属性由不可配置改为可配置
descriptor.configurable = true;
/*
The descriptor of window.window/window.top/window.self in Safari/FF are accessor descriptors, we need to avoid adding a data descriptor while it was
Example:
Safari/FF: Object.getOwnPropertyDescriptor(window, 'top') -> {get: function, set: undefined, enumerable: true, configurable: false}
Chrome: Object.getOwnPropertyDescriptor(window, 'top') -> {value: Window, writable: false, enumerable: true, configurable: false}
*/
if (!hasGetter) {
// 如果这几个属性没有 getter,则说明由 writeable 属性,将其设置为可写
descriptor.writable = true;
}
}
// 如果存在 getter,则以该属性为 key,true 为 value 存入 propertiesWithGetter map
if (hasGetter) propertiesWithGetter.set(p, true);
// 将属性和描述设置到 fakeWindow 对象,并且冻结属性描述符,不然有可能会被更改,比如 zone.js
// freeze the descriptor to avoid being modified by zone.js
// see https://github.com/angular/zone.js/blob/a5fe09b0fac27ac5df1fa746042f96f05ccb6a00/lib/browser/define-property.ts#L71
rawObjectDefineProperty(fakeWindow, p, Object.freeze(descriptor));
}
});
return {
fakeWindow,
propertiesWithGetter,
};
}
// 记录被激活的沙箱的数量
let activeSandboxCount = 0;
/**
* 基于 Proxy 实现的多例模式下的沙箱
* 通过 proxy 代理 fakeWindow 对象,所有的更改都是基于 fakeWindow,这点和单例不一样(很重要),
* 从而保证每个 ProxySandbox 实例之间属性互不影响
*/
export default class ProxySandbox implements SandBox {
/** window 值变更记录 */
private updatedValueSet = new Set<PropertyKey>();
name: string;
type: SandBoxType;
proxy: WindowProxy;
sandboxRunning = true;
// 激活
active() {
// 被激活的沙箱数 + 1
if (!this.sandboxRunning) activeSandboxCount++;
this.sandboxRunning = true;
}
// 失活
inactive() {
if (process.env.NODE_ENV === 'development') {
console.info(`[qiankun:sandbox] ${this.name} modified global properties restore...`, [
...this.updatedValueSet.keys(),
]);
}
// 被激活的沙箱数 - 1
clearSystemJsProps(this.proxy, --activeSandboxCount === 0);
this.sandboxRunning = false;
}
constructor(name: string) {
this.name = name;
this.type = SandBoxType.Proxy;
const { updatedValueSet } = this;
const self = this;
const rawWindow = window;
// 全局对象上所有不可配置属性都在 fakeWindow 中,且其中具有 getter 属性的属性还存在 propertesWithGetter map 中,value 为 true
const { fakeWindow, propertiesWithGetter } = createFakeWindow(rawWindow);
const descriptorTargetMap = new Map<PropertyKey, SymbolTarget>();
// 判断全局对象是否存在指定属性
const hasOwnProperty = (key: PropertyKey) => fakeWindow.hasOwnProperty(key) || rawWindow.hasOwnProperty(key);
const proxy = new Proxy(fakeWindow, {
set(target: FakeWindow, p: PropertyKey, value: any): boolean {
// 如果沙箱在运行,则更新属性值并记录被更改的属性
if (self.sandboxRunning) {
// 设置属性值
// @ts-ignore
target[p] = value;
// 记录被更改的属性
updatedValueSet.add(p);
// 不用管,和 systemJs 有关
interceptSystemJsProps(p, value);
return true;
}
if (process.env.NODE_ENV === 'development') {
console.warn(`[qiankun] Set window.${p.toString()} while sandbox destroyed or inactive in ${name}!`);
}
// 在 strict-mode 下,Proxy 的 handler.set 返回 false 会抛出 TypeError,在沙箱卸载的情况下应该忽略错误
return true;
},
// 获取执行属性的值
get(target: FakeWindow, p: PropertyKey): any {
if (p === Symbol.unscopables) return unscopables;
// avoid who using window.window or window.self to escape the sandbox environment to touch the really window
// see https://github.com/eligrey/FileSaver.js/blob/master/src/FileSaver.js#L13
if (p === 'window' || p === 'self') {
return proxy;
}
if (
p === 'top' ||
p === 'parent' ||
(process.env.NODE_ENV === 'test' && (p === 'mockTop' || p === 'mockSafariTop'))
) {
// if your master app in an iframe context, allow these props escape the sandbox
if (rawWindow === rawWindow.parent) {
return proxy;
}
return (rawWindow as any)[p];
}
// proxy.hasOwnProperty would invoke getter firstly, then its value represented as rawWindow.hasOwnProperty
if (p === 'hasOwnProperty') {
return hasOwnProperty;
}
// mark the symbol to document while accessing as document.createElement could know is invoked by which sandbox for dynamic append patcher
if (p === 'document') {
document[attachDocProxySymbol] = proxy;
// remove the mark in next tick, thus we can identify whether it in micro app or not
// this approach is just a workaround, it could not cover all the complex scenarios, such as the micro app runs in the same task context with master in som case
// fixme if you have any other good ideas
nextTick(() => delete document[attachDocProxySymbol]);
return document;
}
// 以上内容都是一些特殊属性的处理
// 获取特定属性,如果属性具有 getter,说明是原生对象的那几个属性,否则是 fakeWindow 对象上的属性(原生的或者用户设置的)
// eslint-disable-next-line no-bitwise
const value = propertiesWithGetter.has(p) ? (rawWindow as any)[p] : (target as any)[p] || (rawWindow as any)[p];
return getTargetValue(rawWindow, value);
},
// 判断是否存在指定属性
// see https://github.com/styled-components/styled-components/blob/master/packages/styled-components/src/constants.js#L12
has(target: FakeWindow, p: string | number | symbol): boolean {
return p in unscopables || p in target || p in rawWindow;
},
getOwnPropertyDescriptor(target: FakeWindow, p: string | number | symbol): PropertyDescriptor | undefined {
/*
as the descriptor of top/self/window/mockTop in raw window are configurable but not in proxy target, we need to get it from target to avoid TypeError
see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/getOwnPropertyDescriptor
> A property cannot be reported as non-configurable, if it does not exists as an own property of the target object or if it exists as a configurable own property of the target object.
*/
if (target.hasOwnProperty(p)) {
const descriptor = Object.getOwnPropertyDescriptor(target, p);
descriptorTargetMap.set(p, 'target');
return descriptor;
}
if (rawWindow.hasOwnProperty(p)) {
const descriptor = Object.getOwnPropertyDescriptor(rawWindow, p);
descriptorTargetMap.set(p, 'rawWindow');
// A property cannot be reported as non-configurable, if it does not exists as an own property of the target object
if (descriptor && !descriptor.configurable) {
descriptor.configurable = true;
}
return descriptor;
}
return undefined;
},
// trap to support iterator with sandbox
ownKeys(target: FakeWindow): PropertyKey[] {
return uniq(Reflect.ownKeys(rawWindow).concat(Reflect.ownKeys(target)));
},
defineProperty(target: Window, p: PropertyKey, attributes: PropertyDescriptor): boolean {
const from = descriptorTargetMap.get(p);
/*
Descriptor must be defined to native window while it comes from native window via Object.getOwnPropertyDescriptor(window, p),
otherwise it would cause a TypeError with illegal invocation.
*/
switch (from) {
case 'rawWindow':
return Reflect.defineProperty(rawWindow, p, attributes);
default:
return Reflect.defineProperty(target, p, attributes);
}
},
deleteProperty(target: FakeWindow, p: string | number | symbol): boolean {
if (target.hasOwnProperty(p)) {
// @ts-ignore
delete target[p];
updatedValueSet.delete(p);
return true;
}
return true;
},
});
this.proxy = proxy;
}
} | the_stack |
/// <reference types="node" />
import { EventEmitter } from 'events';
declare namespace Connection {
// The property names of these interfaces match the documentation (where type names were given).
export interface Config {
/** Username for plain-text authentication. */
user: string;
/** Password for plain-text authentication. */
password: string;
/** Base64-encoded OAuth token for OAuth authentication for servers that support it (See Andris Reinman's xoauth.js module to help generate this string). */
xoauth?: string;
/** Base64-encoded OAuth2 token for The SASL XOAUTH2 Mechanism for servers that support it (See Andris Reinman's xoauth2 module to help generate this string). */
xoauth2?: string;
/** Hostname or IP address of the IMAP server. Default: "localhost" */
host?: string;
/** Port number of the IMAP server. Default: 143 */
port?: number;
/** Perform implicit TLS connection? Default: false */
tls?: boolean;
/** Options object to pass to tls.connect() Default: (none) */
tlsOptions?: Object;
/** Set to 'always' to always attempt connection upgrades via STARTTLS, 'required' only if upgrading is required, or 'never' to never attempt upgrading. Default: 'never' */
autotls?: string;
/** Number of milliseconds to wait for a connection to be established. Default: 10000 */
connTimeout?: number;
/** Number of milliseconds to wait to be authenticated after a connection has been established. Default: 5000 */
authTimeout?: number;
/** Configures the keepalive mechanism. Set to true to enable keepalive with defaults or set to object to enable and configure keepalive behavior: Default: true */
keepalive?: any; /* boolean|KeepAlive */
/** If set, the function will be called with one argument, a string containing some debug info Default: (no debug output) */
debug?: Function;
}
export interface KeepAlive {
/** This is the interval (in milliseconds) at which NOOPs are sent and the interval at which idleInterval is checked. Default: 10000 */
interval?: number;
/** This is the interval (in milliseconds) at which an IDLE command (for servers that support IDLE) is re-sent. Default: 300000 (5 mins) */
idleInterval?: number;
/** Set to true to force use of NOOP keepalive on servers also support IDLE. Default: false */
forceNoop?: boolean;
}
// One of:
// - a single message identifier
// - a message identifier range (e.g. '2504:2507' or '*' or '2504:*')
// - an array of message identifiers
// - an array of message identifier ranges.
// type MessageSource = string | string[]
export interface Box {
/** The name of this mailbox. */
name: string;
/** True if this mailbox was opened in read-only mode. (Only available with openBox() calls) */
readOnly?: boolean;
/** True if new keywords can be added to messages in this mailbox. */
newKeywords: boolean;
/** A 32-bit number that can be used to determine if UIDs in this mailbox have changed since the last time this mailbox was opened. */
uidvalidity: number;
/** The uid that will be assigned to the next message that arrives at this mailbox. */
uidnext: number;
/** array - A list of system-defined flags applicable for this mailbox. Flags in this list but not in permFlags may be stored for the current session only. Additional server implementation-specific flags may also be available. */
flags: string[];
/** A list of flags that can be permanently added/removed to/from messages in this mailbox. */
permFlags: string[];
/** Whether or not this mailbox has persistent UIDs. This should almost always be true for modern mailboxes and should only be false for legacy mail stores where supporting persistent UIDs was not technically feasible. */
persistentUIDs: boolean;
/** Contains various message counts for this mailbox: */
messages: {
/** Total number of messages in this mailbox. */
total: number;
/** Number of messages in this mailbox having the Recent flag (this IMAP session is the first to see these messages). */
new: number;
/** (Only available with status() calls) Number of messages in this mailbox not having the Seen flag (marked as not having been read). */
unseen: number;
};
}
export interface ImapMessageBodyInfo {
/** The specifier for this body (e.g. 'TEXT', 'HEADER.FIELDS (TO FROM SUBJECT)', etc). */
which: string;
/** The size of this body in bytes. */
size: number;
}
export interface ImapMessageAttributes {
/** A 32-bit ID that uniquely identifies this message within its mailbox. */
uid: number;
/** A list of flags currently set on this message. */
flags: string[];
/** The internal server date for the message. */
date: Date;
/** The message's body structure (only set if requested with fetch()). */
struct?: any[];
/** The RFC822 message size (only set if requested with fetch()). */
size?: number;
}
/** Given in a 'message' event from ImapFetch */
export interface ImapMessage extends NodeJS.EventEmitter {
on(event: string, listener: Function): this;
on(event: 'body', listener: (stream: NodeJS.ReadableStream, info: ImapMessageBodyInfo) => void): this;
on(event: 'attributes', listener: (attrs: ImapMessageAttributes) => void): this;
on(event: 'end', listener: () => void): this;
}
export interface FetchOptions {
/** Mark message(s) as read when fetched. Default: false */
markSeen?: boolean;
/** Fetch the message structure. Default: false */
struct?: boolean;
/** Fetch the message envelope. Default: false */
envelope?: boolean;
/** Fetch the RFC822 size. Default: false */
size?: boolean;
/** Fetch modifiers defined by IMAP extensions. Default: (none) */
modifiers?: Object;
/** A string or Array of strings containing the body part section to fetch. Default: (none) Example sections: */
bodies?: string | string[];
}
/** Returned from fetch() */
export interface ImapFetch extends NodeJS.EventEmitter {
on(event: string, listener: Function): this;
on(event: 'message', listener: (message: ImapMessage, seqno: number) => void): this;
on(event: 'error', listener: (error: Error) => void): this;
once(event: string, listener: Function): this;
once(event: 'error', listener: (error: Error) => void): this;
}
export interface Folder {
/** mailbox attributes. An attribute of 'NOSELECT' indicates the mailbox cannot be opened */
attribs: string[];
/** hierarchy delimiter for accessing this mailbox's direct children. */
delimiter: string;
/** an object containing another structure similar in format to this top level, otherwise null if no children */
children: MailBoxes;
/** pointer to parent mailbox, null if at the top level */
parent: Folder;
}
export interface MailBoxes {
[name: string]: Folder;
}
export interface AppendOptions {
/** The name of the mailbox to append the message to. Default: the currently open mailbox */
mailbox?: string;
/** A single flag (e.g. 'Seen') or an array of flags (e.g. ['Seen', 'Flagged']) to append to the message. Default: (no flags) */
flags?: any; /* string|string[] */
/** What to use for message arrival date/time. Default: (current date/time) */
date?: Date;
}
export interface MessageFunctions {
/** Searches the currently open mailbox for messages using given criteria. criteria is a list describing what you want to find. For criteria types that require arguments, use an array instead of just the string criteria type name (e.g. ['FROM', 'foo@bar.com']). Prefix criteria types with an "!" to negate.
The following message flags are valid types that do not have arguments:
ALL: void; // All messages.
ANSWERED: void; // Messages with the Answered flag set.
DELETED: void; // Messages with the Deleted flag set.
DRAFT: void; // Messages with the Draft flag set.
FLAGGED: void; // Messages with the Flagged flag set.
NEW: void; // Messages that have the Recent flag set but not the Seen flag.
SEEN: void; // Messages that have the Seen flag set.
RECENT: void; // Messages that have the Recent flag set.
OLD: void; // Messages that do not have the Recent flag set. This is functionally equivalent to "!RECENT" (as opposed to "!NEW").
UNANSWERED: void; // Messages that do not have the Answered flag set.
UNDELETED: void; // Messages that do not have the Deleted flag set.
UNDRAFT: void; // Messages that do not have the Draft flag set.
UNFLAGGED: void; // Messages that do not have the Flagged flag set.
UNSEEN: void; // Messages that do not have the Seen flag set.
The following are valid types that require string value(s):
BCC: any; // Messages that contain the specified string in the BCC field.
CC: any; // Messages that contain the specified string in the CC field.
FROM: any; // Messages that contain the specified string in the FROM field.
SUBJECT: any; // Messages that contain the specified string in the SUBJECT field.
TO: any; // Messages that contain the specified string in the TO field.
BODY: any; // Messages that contain the specified string in the message body.
TEXT: any; // Messages that contain the specified string in the header OR the message body.
KEYWORD: any; // Messages with the specified keyword set.
HEADER: any; // Requires two string values, with the first being the header name and the second being the value to search for. If this second string is empty, all messages that contain the given header name will be returned.
The following are valid types that require a string parseable by JavaScripts Date object OR a Date instance:
BEFORE: any; // Messages whose internal date (disregarding time and timezone) is earlier than the specified date.
ON: any; // Messages whose internal date (disregarding time and timezone) is within the specified date.
SINCE: any; // Messages whose internal date (disregarding time and timezone) is within or later than the specified date.
SENTBEFORE: any; // Messages whose Date header (disregarding time and timezone) is earlier than the specified date.
SENTON: any; // Messages whose Date header (disregarding time and timezone) is within the specified date.
SENTSINCE: any; // Messages whose Date header (disregarding time and timezone) is within or later than the specified date.
The following are valid types that require one Integer value:
LARGER: number; // Messages with a size larger than the specified number of bytes.
SMALLER: number; // Messages with a size smaller than the specified number of bytes.
The following are valid criterion that require one or more Integer values:
UID: any; // Messages with UIDs corresponding to the specified UID set. Ranges are permitted (e.g. '2504:2507' or '*' or '2504:*').
*/
search(criteria: any[], callback: (error: Error, uids: number[]) => void): void;
/** Fetches message(s) in the currently open mailbox; source can be a single message identifier, a message identifier range (e.g. '2504:2507' or '*' or '2504:*'), an array of message identifiers, or an array of message identifier ranges. */
fetch(source: any /* MessageSource */, options: FetchOptions): ImapFetch;
/** Copies message(s) in the currently open mailbox to another mailbox. */
copy(source: any /* MessageSource */, mailboxName: string, callback: (error: Error) => void): void;
/** Moves message(s) in the currently open mailbox to another mailbox. Note: The message(s) in the destination mailbox will have a new message UID. */
move(source: any /* MessageSource */, mailboxName: string, callback: (error: Error) => void): void;
/** Adds flag(s) to message(s). */
addFlags(source: any /* MessageSource */, flags: any, callback: (error: Error) => void): void;
/** Removes flag(s) from message(s). */
delFlags(source: any /* MessageSource */, flags: any, callback: (error: Error) => void): void;
/** Sets the flag(s) for message(s). */
setFlags(source: any /* MessageSource */, flags: any, callback: (error: Error) => void): void;
/** Adds keyword(s) to message(s). keywords is either a single keyword or an array of keywords. */
addKeywords(source: any /* MessageSource */, keywords: any /* string|string[] */, callback: (error: Error) => void): void;
/** Removes keyword(s) from message(s). keywords is either a single keyword or an array of keywords. */
delKeywords(source: any /* MessageSource */, keywords: any /* string|string[] */, callback: (error: Error) => void): void;
/** Sets keyword(s) for message(s). keywords is either a single keyword or an array of keywords. */
setKeywords(source: any /* MessageSource */, keywords: any /* string|string[] */, callback: (error: Error) => void): void;
/** Checks if the server supports the specified capability. */
serverSupports(capability: string): boolean;
}
}
declare class Connection extends EventEmitter implements Connection.MessageFunctions {
/** @constructor */
constructor(config: Connection.Config);
// from NodeJS.EventEmitter
addListener(event: string, listener: Function): this;
on(event: string, listener: Function): this;
once(event: string, listener: Function): this;
removeListener(event: string, listener: Function): this;
removeAllListeners(event?: string): this;
setMaxListeners(n: number): this;
getMaxListeners(): number;
listeners(event: string): Function[];
emit(event: string, ...args: any[]): boolean;
listenerCount(type: string): number;
// from MessageFunctions
/** Searches the currently open mailbox for messages using given criteria. criteria is a list describing what you want to find. For criteria types that require arguments, use an array instead of just the string criteria type name (e.g. ['FROM', 'foo@bar.com']). Prefix criteria types with an "!" to negate. */
search(criteria: any[], callback: (error: Error, uids: number[]) => void): void;
/** Fetches message(s) in the currently open mailbox. */
fetch(source: any /* MessageSource */, options: Connection.FetchOptions): Connection.ImapFetch;
/** Copies message(s) in the currently open mailbox to another mailbox. */
copy(source: any /* MessageSource */, mailboxName: string, callback: (error: Error) => void): void;
/** Moves message(s) in the currently open mailbox to another mailbox. Note: The message(s) in the destination mailbox will have a new message UID. */
move(source: any /* MessageSource */, mailboxName: string, callback: (error: Error) => void): void;
/** Adds flag(s) to message(s). */
addFlags(source: any /* MessageSource */, flags: any, callback: (error: Error) => void): void;
/** Removes flag(s) from message(s). */
delFlags(source: any /* MessageSource */, flags: any, callback: (error: Error) => void): void;
/** Sets the flag(s) for message(s). */
setFlags(source: any /* MessageSource */, flags: any, callback: (error: Error) => void): void;
/** Adds keyword(s) to message(s). keywords is either a single keyword or an array of keywords. */
addKeywords(source: any /* MessageSource */, keywords: any /* string|string[] */, callback: (error: Error) => void): void;
/** Removes keyword(s) from message(s). keywords is either a single keyword or an array of keywords. */
delKeywords(source: any /* MessageSource */, keywords: any /* string|string[] */, callback: (error: Error) => void): void;
/** Sets keyword(s) for message(s). keywords is either a single keyword or an array of keywords. */
setKeywords(source: any /* MessageSource */, keywords: any /* string|string[] */, callback: (error: Error) => void): void;
/** Checks if the server supports the specified capability. */
serverSupports(capability: string): boolean;
/** Parses a raw header and returns an object keyed on header fields and the values are Arrays of header field values. Set disableAutoDecode to true to disable automatic decoding of MIME encoded-words that may exist in header field values. */
static parseHeader(rawHeader: string, disableAutoDecode?: boolean): {[index: string]: string[]};
/** The current state of the connection (e.g. 'disconnected', 'connected', 'authenticated'). */
state: string;
/** The (top-level) mailbox hierarchy delimiter. If the server does not support mailbox hierarchies and only a flat list, this value will be falsey. */
delimiter: string;
/** Contains information about each namespace type (if supported by the server) with the following properties: */
namespaces: {
/** Mailboxes that belong to the logged in user. */
personal: any[];
/** Mailboxes that belong to other users that the logged in user has access to. */
other: any[];
/** Mailboxes that are accessible by any logged in user. */
shared: any[];
};
/**
seq exposes the search() ... serverSupports() set of commands, but returns sequence number(s) instead of UIDs.
*/
seq: Connection.MessageFunctions;
/** Attempts to connect and authenticate with the IMAP server. */
connect(): void;
/** Closes the connection to the server after all requests in the queue have been sent. */
end(): void;
/** Immediately destroys the connection to the server. */
destroy(): void;
/** Opens a specific mailbox that exists on the server. mailboxName should include any necessary prefix/path. modifiers is used by IMAP extensions. */
openBox(mailboxName: string, callback: (error: Error, mailbox: Connection.Box) => void): void;
openBox(mailboxName: string, openReadOnly: boolean, callback: (error: Error, mailbox: Connection.Box) => void): void;
openBox(mailboxName: string, openReadOnly: boolean, modifiers: Object, callback: (error: Error, mailbox: Connection.Box) => void): void;
/** Closes the currently open mailbox. If autoExpunge is true, any messages marked as Deleted in the currently open mailbox will be removed if the mailbox was NOT opened in read-only mode. If autoExpunge is false, you disconnect, or you open another mailbox, messages marked as Deleted will NOT be removed from the currently open mailbox. */
closeBox(callback: (error: Error) => void): void;
closeBox(autoExpunge: boolean, callback: (error: Error) => void): void;
/** Creates a new mailbox on the server. mailboxName should include any necessary prefix/path. */
addBox(mailboxName: string, callback: (error: Error) => void): void;
/** Removes a specific mailbox that exists on the server. mailboxName should including any necessary prefix/path. */
delBox(mailboxName: string, callback: (error: Error) => void): void;
/** Renames a specific mailbox that exists on the server. Both oldMailboxName and newMailboxName should include any necessary prefix/path. Note: Renaming the 'INBOX' mailbox will instead cause all messages in 'INBOX' to be moved to the new mailbox. */
renameBox(oldMailboxName: string, newMailboxName: string, callback: (error: Error, mailbox: Connection.Box) => void): void;
/** Subscribes to a specific mailbox that exists on the server. mailboxName should include any necessary prefix/path. */
subscribeBox(mailboxName: string, callback: (error: Error) => void): void;
/** Unsubscribes from a specific mailbox that exists on the server. mailboxName should include any necessary prefix/path. */
unsubscribeBox(mailboxName: string, callback: (error: Error) => void): void;
/** Fetches information about a mailbox other than the one currently open. Note: There is no guarantee that this will be a fast operation on the server. Also, do not call this on the currently open mailbox. */
status(mailboxName: string, callback: (error: Error, mailbox: Connection.Box) => void): void;
/** Obtains the full list of mailboxes. If nsPrefix is not specified, the main personal namespace is used. */
getBoxes(callback: (error: Error, mailboxes: Connection.MailBoxes) => void): void;
getBoxes(nsPrefix: string, callback: (error: Error, mailboxes: Connection.MailBoxes) => void): void;
/** Obtains the full list of subscribed mailboxes. If nsPrefix is not specified, the main personal namespace is used. */
getSubscribedBoxes(callback: (error: Error, mailboxes: Connection.MailBoxes) => void): void;
getSubscribedBoxes(nsPrefix: string, callback: (error: Error, mailboxes: Connection.MailBoxes) => void): void;
/** Permanently removes all messages flagged as Deleted in the currently open mailbox. If the server supports the 'UIDPLUS' capability, uids can be supplied to only remove messages that both have their uid in uids and have the \Deleted flag set. Note: At least on Gmail, performing this operation with any currently open mailbox that is not the Spam or Trash mailbox will merely archive any messages marked as Deleted (by moving them to the 'All Mail' mailbox). */
expunge(callback: (error: Error) => void): void;
expunge(uids: any /* MessageSource */, callback: (error: Error) => void): void;
/** Appends a message to selected mailbox. msgData is a string or Buffer containing an RFC-822 compatible MIME message. Valid options properties are: */
append(msgData: any, callback: (error: Error) => void): void;
append(msgData: any, options: Connection.AppendOptions, callback: (error: Error) => void): void;
}
export = Connection; | the_stack |
import { getVoidLogger } from '@backstage/backend-common';
import { ObjectFetchParams } from '../types/types';
import { KubernetesFanOutHandler } from './KubernetesFanOutHandler';
const fetchObjectsForService = jest.fn();
const getClustersByServiceId = jest.fn();
const mockFetch = (mock: jest.Mock) => {
mock.mockImplementation((params: ObjectFetchParams) =>
Promise.resolve(
generateMockResourcesAndErrors(
params.serviceId,
params.clusterDetails.name,
),
),
);
};
function generateMockResourcesAndErrors(
serviceId: string,
clusterName: string,
) {
if (clusterName === 'empty-cluster') {
return {
errors: [],
responses: [
{
type: 'pods',
resources: [],
},
{
type: 'configmaps',
resources: [],
},
{
type: 'services',
resources: [],
},
],
};
} else if (clusterName === 'error-cluster') {
return {
errors: ['some random cluster error'],
responses: [
{
type: 'pods',
resources: [],
},
{
type: 'configmaps',
resources: [],
},
{
type: 'services',
resources: [],
},
],
};
}
return {
errors: [],
responses: [
{
type: 'pods',
resources: [
{
metadata: {
name: `my-pods-${serviceId}-${clusterName}`,
},
},
],
},
{
type: 'configmaps',
resources: [
{
metadata: {
name: `my-configmaps-${serviceId}-${clusterName}`,
},
},
],
},
{
type: 'services',
resources: [
{
metadata: {
name: `my-services-${serviceId}-${clusterName}`,
},
},
],
},
],
};
}
describe('handleGetKubernetesObjectsForService', () => {
beforeEach(() => {
jest.resetAllMocks();
});
it('retrieve objects for one cluster', async () => {
getClustersByServiceId.mockImplementation(() =>
Promise.resolve([
{
name: 'test-cluster',
authProvider: 'serviceAccount',
},
]),
);
mockFetch(fetchObjectsForService);
const sut = new KubernetesFanOutHandler({
logger: getVoidLogger(),
fetcher: {
fetchObjectsForService,
},
serviceLocator: {
getClustersByServiceId,
},
customResources: [],
});
const result = await sut.getKubernetesObjectsByEntity({
entity: {
apiVersion: 'backstage.io/v1beta1',
kind: 'Component',
metadata: {
name: 'test-component',
annotations: {
'backstage.io/kubernetes-labels-selector':
'backstage.io/test-label=test-component',
},
},
spec: {
type: 'service',
lifecycle: 'production',
owner: 'joe',
},
},
});
expect(getClustersByServiceId.mock.calls.length).toBe(1);
expect(fetchObjectsForService.mock.calls.length).toBe(1);
expect(result).toStrictEqual({
items: [
{
cluster: {
name: 'test-cluster',
},
errors: [],
resources: [
{
resources: [
{
metadata: {
name: 'my-pods-test-component-test-cluster',
},
},
],
type: 'pods',
},
{
resources: [
{
metadata: {
name: 'my-configmaps-test-component-test-cluster',
},
},
],
type: 'configmaps',
},
{
resources: [
{
metadata: {
name: 'my-services-test-component-test-cluster',
},
},
],
type: 'services',
},
],
},
],
});
});
it('retrieve objects for two clusters', async () => {
getClustersByServiceId.mockImplementation(() =>
Promise.resolve([
{
name: 'test-cluster',
authProvider: 'serviceAccount',
dashboardUrl: 'https://k8s.foo.coom',
},
{
name: 'other-cluster',
authProvider: 'google',
},
]),
);
mockFetch(fetchObjectsForService);
const sut = new KubernetesFanOutHandler({
logger: getVoidLogger(),
fetcher: {
fetchObjectsForService,
},
serviceLocator: {
getClustersByServiceId,
},
customResources: [],
});
const result = await sut.getKubernetesObjectsByEntity({
auth: {
google: 'google_token_123',
},
entity: {
apiVersion: 'backstage.io/v1beta1',
kind: 'Component',
metadata: {
name: 'test-component',
annotations: {
'backstage.io/kubernetes-labels-selector':
'backstage.io/test-label=test-component',
},
},
spec: {
type: 'service',
lifecycle: 'production',
owner: 'joe',
},
},
});
expect(getClustersByServiceId.mock.calls.length).toBe(1);
expect(fetchObjectsForService.mock.calls.length).toBe(2);
expect(result).toStrictEqual({
items: [
{
cluster: {
dashboardUrl: 'https://k8s.foo.coom',
name: 'test-cluster',
},
errors: [],
resources: [
{
resources: [
{
metadata: {
name: 'my-pods-test-component-test-cluster',
},
},
],
type: 'pods',
},
{
resources: [
{
metadata: {
name: 'my-configmaps-test-component-test-cluster',
},
},
],
type: 'configmaps',
},
{
resources: [
{
metadata: {
name: 'my-services-test-component-test-cluster',
},
},
],
type: 'services',
},
],
},
{
cluster: {
name: 'other-cluster',
},
errors: [],
resources: [
{
resources: [
{
metadata: {
name: 'my-pods-test-component-other-cluster',
},
},
],
type: 'pods',
},
{
resources: [
{
metadata: {
name: 'my-configmaps-test-component-other-cluster',
},
},
],
type: 'configmaps',
},
{
resources: [
{
metadata: {
name: 'my-services-test-component-other-cluster',
},
},
],
type: 'services',
},
],
},
],
});
});
it('retrieve objects for three clusters, only two have resources and show in ui', async () => {
getClustersByServiceId.mockImplementation(() =>
Promise.resolve([
{
name: 'test-cluster',
authProvider: 'serviceAccount',
},
{
name: 'other-cluster',
authProvider: 'google',
},
{
name: 'empty-cluster',
authProvider: 'google',
},
]),
);
mockFetch(fetchObjectsForService);
const sut = new KubernetesFanOutHandler({
logger: getVoidLogger(),
fetcher: {
fetchObjectsForService,
},
serviceLocator: {
getClustersByServiceId,
},
customResources: [],
});
const result = await sut.getKubernetesObjectsByEntity({
auth: {
google: 'google_token_123',
},
entity: {
apiVersion: 'backstage.io/v1beta1',
kind: 'Component',
metadata: {
name: 'test-component',
annotations: {
'backstage.io/kubernetes-labels-selector':
'backstage.io/test-label=test-component',
},
},
spec: {
type: 'service',
lifecycle: 'production',
owner: 'joe',
},
},
});
expect(getClustersByServiceId.mock.calls.length).toBe(1);
expect(fetchObjectsForService.mock.calls.length).toBe(3);
expect(result).toStrictEqual({
items: [
{
cluster: {
name: 'test-cluster',
},
errors: [],
resources: [
{
resources: [
{
metadata: {
name: 'my-pods-test-component-test-cluster',
},
},
],
type: 'pods',
},
{
resources: [
{
metadata: {
name: 'my-configmaps-test-component-test-cluster',
},
},
],
type: 'configmaps',
},
{
resources: [
{
metadata: {
name: 'my-services-test-component-test-cluster',
},
},
],
type: 'services',
},
],
},
{
cluster: {
name: 'other-cluster',
},
errors: [],
resources: [
{
resources: [
{
metadata: {
name: 'my-pods-test-component-other-cluster',
},
},
],
type: 'pods',
},
{
resources: [
{
metadata: {
name: 'my-configmaps-test-component-other-cluster',
},
},
],
type: 'configmaps',
},
{
resources: [
{
metadata: {
name: 'my-services-test-component-other-cluster',
},
},
],
type: 'services',
},
],
},
],
});
});
it('retrieve objects for four clusters, two have resources and one error cluster', async () => {
getClustersByServiceId.mockImplementation(() =>
Promise.resolve([
{
name: 'test-cluster',
authProvider: 'serviceAccount',
},
{
name: 'other-cluster',
authProvider: 'google',
},
{
name: 'empty-cluster',
authProvider: 'google',
},
{
name: 'error-cluster',
authProvider: 'google',
},
]),
);
mockFetch(fetchObjectsForService);
const sut = new KubernetesFanOutHandler({
logger: getVoidLogger(),
fetcher: {
fetchObjectsForService,
},
serviceLocator: {
getClustersByServiceId,
},
customResources: [],
});
const result = await sut.getKubernetesObjectsByEntity({
auth: {
google: 'google_token_123',
},
entity: {
apiVersion: 'backstage.io/v1beta1',
kind: 'Component',
metadata: {
name: 'test-component',
annotations: {
'backstage.io/kubernetes-labels-selector':
'backstage.io/test-label=test-component',
},
},
spec: {
type: 'service',
lifecycle: 'production',
owner: 'joe',
},
},
});
expect(getClustersByServiceId.mock.calls.length).toBe(1);
expect(fetchObjectsForService.mock.calls.length).toBe(4);
expect(result).toStrictEqual({
items: [
{
cluster: {
name: 'test-cluster',
},
errors: [],
resources: [
{
resources: [
{
metadata: {
name: 'my-pods-test-component-test-cluster',
},
},
],
type: 'pods',
},
{
resources: [
{
metadata: {
name: 'my-configmaps-test-component-test-cluster',
},
},
],
type: 'configmaps',
},
{
resources: [
{
metadata: {
name: 'my-services-test-component-test-cluster',
},
},
],
type: 'services',
},
],
},
{
cluster: {
name: 'other-cluster',
},
errors: [],
resources: [
{
resources: [
{
metadata: {
name: 'my-pods-test-component-other-cluster',
},
},
],
type: 'pods',
},
{
resources: [
{
metadata: {
name: 'my-configmaps-test-component-other-cluster',
},
},
],
type: 'configmaps',
},
{
resources: [
{
metadata: {
name: 'my-services-test-component-other-cluster',
},
},
],
type: 'services',
},
],
},
{
cluster: {
name: 'error-cluster',
},
errors: ['some random cluster error'],
resources: [
{
type: 'pods',
resources: [],
},
{
type: 'configmaps',
resources: [],
},
{
type: 'services',
resources: [],
},
],
},
],
});
});
}); | the_stack |
import INode, { INodeData } from './INode'
import Layout from './Layout'
import { Notice, Platform } from 'obsidian'
import SVG from 'svg.js'
import { MindMapView } from '../MindMapView'
import { frontMatterKey, basicFrontmatter } from '../constants';
import Exec from './Execute'
import {uuid} from '../MindMapView'
let deleteIcon = '<svg class="icon" width="16px" height="16.00px" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M799.2 874.4c0 34.4-28 62.4-62.368 62.4H287.2a62.496 62.496 0 0 1-62.4-62.4V212h574.4v662.4zM349.6 100c0-7.2 5.6-12.8 12.8-12.8h300c7.2 0 12.768 5.6 12.768 12.8v37.6H349.6V100z m636.8 37.6H749.6V100c0-48-39.2-87.2-87.2-87.2h-300a87.392 87.392 0 0 0-87.2 87.2v37.6H37.6C16.8 137.6 0 154.4 0 175.2s16.8 37.6 37.6 37.6h112v661.6A137.6 137.6 0 0 0 287.2 1012h449.6a137.6 137.6 0 0 0 137.6-137.6V212h112c20.8 0 37.6-16.8 37.6-37.6s-16.8-36.8-37.6-36.8zM512 824c20.8 0 37.6-16.8 37.6-37.6v-400c0-20.8-16.768-37.6-37.6-37.6-20.8 0-37.6 16.8-37.6 37.6v400c0 20.8 16.8 37.6 37.6 37.6m-175.2 0c20.8 0 37.6-16.8 37.6-37.6v-400c0-20.8-16.8-37.6-37.6-37.6s-37.6 16.8-37.6 37.6v400c0.8 20.8 17.6 37.6 37.6 37.6m350.4 0c20.8 0 37.632-16.8 37.632-37.6v-400c0-20.8-16.8-37.6-37.632-37.6-20.768 0-37.6 16.8-37.6 37.6v400c0 20.8 16.8 37.6 37.6 37.6" /></svg>';
let addIcon = '<svg class="icon" width="16px" height="16.00px" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"><path d="M512 1024C230.4 1024 0 793.6 0 512S230.4 0 512 0s512 230.4 512 512-230.4 512-512 512z m0-960C265.6 64 64 265.6 64 512s201.6 448 448 448 448-201.6 448-448S758.4 64 512 64z" /><path d="M800 544H224c-19.2 0-32-12.8-32-32s12.8-32 32-32h576c19.2 0 32 12.8 32 32s-12.8 32-32 32z" /><path d="M512 832c-19.2 0-32-12.8-32-32V224c0-19.2 12.8-32 32-32s32 12.8 32 32v576c0 19.2-12.8 32-32 32z" /></svg>';
interface Setting {
theme?: string;
canvasSize?: number;
background?: string;
fontSize?: number;
color?: string,
exportMdModel?: string,
headLevel: number,
layoutDirect: string,
strokeArray?:any[]
}
export default class MindMap {
root: INode;
status: string;
appEl: HTMLElement;
contentEL: HTMLElement;
containerEL: HTMLElement;
path?: string;
editNode?: INode;
selectNode?: INode;
setting: Setting;
data: INodeData;
drag?: boolean;
startX?: number;
startY?: number;
dx?: number;
dy?: number;
mmLayout?: Layout;
draw: any;
edgeGroup: any;
_nodeNum: number = 0;
_tempNum: number = 0;
view?: MindMapView;
colors: string[] = [];
_dragNode: INode;
exec: Exec;
scalePointer: number[] = [];
mindScale = 100;
timeOut: any = null;
_indicateDom:HTMLElement;
_menuDom:HTMLElement;
_dragType:string='';
_left:number;
_top:number;
constructor(data: INodeData, containerEL: HTMLElement, setting?: Setting) {
this.setting = Object.assign({
theme: 'default',
canvasSize: 8000,
fontSize: 16,
background: 'transparent',
color: 'inherit',
exportMdModel: 'default',
headLevel: 2,
layoutDirect: ''
}, setting || {});
this.data = data;
this.appEl = document.createElement('div');
this.appEl.classList.add('mm-mindmap');
this.appEl.classList.add(`mm-theme-${this.setting.theme}`);
this.appEl.style.overflow = "auto";
this.contentEL = document.createElement('div');
this.contentEL.style.position = "relative";
this.contentEL.style.width = "100%";
this.contentEL.style.height = "100%";
this.appEl.appendChild(this.contentEL);
this.draw = SVG(this.contentEL).size('100%', '100%');
this.setAppSetting();
containerEL.appendChild(this.appEl);
this.containerEL = containerEL;
//layout direct
this._indicateDom = document.createElement('div');
this._indicateDom.classList.add('mm-node-layout-indicate');
this._indicateDom.style.display='none';
//menu
this._menuDom = document.createElement('div');
this._menuDom.classList.add('mm-node-menu');
this._menuDom.style.display='none';
this.setMenuIcon();
this.contentEL.appendChild(this._indicateDom);
this.contentEL.appendChild(this._menuDom);
//history
this.exec = new Exec();
// link line
this.edgeGroup = this.draw.group();
this.appClickFn = this.appClickFn.bind(this);
this.appDragstart = this.appDragstart.bind(this);
this.appDragend = this.appDragend.bind(this);
this.appDragover = this.appDragover.bind(this);
this.appDblclickFn = this.appDblclickFn.bind(this);
this.appMouseOverFn = this.appMouseOverFn.bind(this);
this.appDrop = this.appDrop.bind(this);
this.appKeyup = this.appKeyup.bind(this);
this.appKeydown = this.appKeydown.bind(this);
this.appMousewheel = this.appMousewheel.bind(this);
this.appMouseMove = this.appMouseMove.bind(this);
this.appMouseDown = this.appMouseDown.bind(this);
this.appMouseUp = this.appMouseUp.bind(this);
//custom event
this.initNode = this.initNode.bind(this);
this.renderEditNode = this.renderEditNode.bind(this);
this.mindMapChange = this.mindMapChange.bind(this);
this.initEvent();
//this.center();
}
setMenuIcon(){
var addNodeDom = document.createElement('span');
var deleteNodeDom = document.createElement('span');
addNodeDom.classList.add('mm-icon-add-node');
deleteNodeDom.classList.add('mm-icon-delete-node');
addNodeDom.innerHTML = addIcon;
deleteNodeDom.innerHTML = deleteIcon;
this._menuDom.appendChild(addNodeDom);
this._menuDom.appendChild(deleteNodeDom);
}
setAppSetting() {
this.appEl.style.width = `${this.setting.canvasSize}px`;
this.appEl.style.height = `${this.setting.canvasSize}px`;
this.contentEL.style.width = `100%`;
this.contentEL.style.height = `100%`;
// this.contentEL.style.color=`${this.setting.color};`;
this.contentEL.style.background = `${this.setting.background}`;
this.contentEL.style.fontSize = `${this.setting.fontSize}px`;
}
//create node
init(collapsedIds?: string[]) {
var that = this;
var data = this.data;
var x = this.setting.canvasSize / 2 - 60;
var y = this.setting.canvasSize / 2 - 200;
function initNode(d: INodeData, isRoot: boolean, p?: INode) {
that._nodeNum++;
var n = new INode(d, that);
if (collapsedIds && collapsedIds.includes(n.getId())) {
n.isExpand = false;
}
if (p && (!p.isExpand || p.isHide)) {
n.isHide = true;
}
that.contentEL.appendChild(n.containEl);
if (isRoot) {
n.setPosition(x, y);
that.root = n;
n.isRoot = true;
} else {
n.setPosition(0, 0);
p.children.push(n);
n.parent = p;
}
n.refreshBox();
if (d.children && d.children.length) {
d.children.forEach((dd: INodeData) => {
initNode(dd, false, n);
});
}
}
initNode(data, true);
}
traverseBF(callback: Function, node?: INode) {
var array = [];
array.push(node || this.root);
var currentNode = array.shift();
while (currentNode) {
for (let i = 0, len = currentNode.children.length; i < len; i++) {
array.push(currentNode.children[i]);
}
callback(currentNode);
currentNode = array.shift();
}
}
traverseDF(callback: Function, node?: INode, cbFirst?: boolean) {
function recurse(currentNode: INode) {
if (currentNode) {
if (cbFirst) {
callback(currentNode);
}
if (currentNode.children) {
for (var i = 0, length = currentNode.children.length; i < length; i++) {
recurse(currentNode.children[i]);
}
}
if (!cbFirst) {
callback(currentNode);
}
}
}
recurse(node || this.root);
}
getNodeById(id: string) {
var snode: INode = null;
this.traverseDF((n: INode) => {
if (n.getId() == id) {
snode = n;
}
});
return snode;
}
clearSelectNode() {
if (this.selectNode) {
this.selectNode.unSelect();
this.selectNode = null
}
if (this.editNode) {
if(this.editNode.isEdit){
this.editNode.cancelEdit();
}
this.editNode = null;
}
}
initEvent() {
this.appEl.addEventListener('click', this.appClickFn);
this.appEl.addEventListener('mouseover', this.appMouseOverFn);
this.appEl.addEventListener('dblclick', this.appDblclickFn);
this.appEl.addEventListener('dragstart', this.appDragstart);
this.appEl.addEventListener('dragover', this.appDragover);
this.appEl.addEventListener('dragend', this.appDragend);
this.appEl.addEventListener('drop', this.appDrop);
document.addEventListener('keyup', this.appKeyup);
document.addEventListener('keydown', this.appKeydown);
document.body.addEventListener('mousewheel', this.appMousewheel);
if(Platform.isDesktop){
this.appEl.addEventListener('mousedown', this.appMouseDown);
this.appEl.addEventListener('mouseup', this.appMouseUp);
}
this.appEl.addEventListener('mousemove', this.appMouseMove);
//custom event
this.on('initNode', this.initNode);
this.on('renderEditNode', this.renderEditNode);
this.on('mindMapChange', this.mindMapChange);
}
removeEvent() {
this.appEl.removeEventListener('click', this.appClickFn);
this.appEl.removeEventListener('dragstart', this.appDragstart);
this.appEl.removeEventListener('dragover', this.appDragover);
this.appEl.removeEventListener('dragend', this.appDragend);
this.appEl.removeEventListener('dblClick', this.appDblclickFn);
this.appEl.removeEventListener('mouseover', this.appMouseOverFn);
this.appEl.removeEventListener('drop', this.appDrop);
document.removeEventListener('keyup', this.appKeyup);
document.removeEventListener('keydown', this.appKeydown);
document.body.removeEventListener('mousewheel', this.appMousewheel);
if(Platform.isDesktop){
this.appEl.removeEventListener('mousedown', this.appMouseDown);
this.appEl.removeEventListener('mouseup', this.appMouseUp);
}
this.appEl.removeEventListener('mousemove', this.appMouseMove);
this.off('initNode', this.initNode);
this.off('renderEditNode', this.renderEditNode);
this.off('mindMapChange', this.mindMapChange);
}
initNode(evt: CustomEvent) {
this._tempNum++;
//console.log(this._nodeNum,this._tempNum);
if (this._tempNum == this._nodeNum) {
this.refresh();
this.center();
}
}
renderEditNode(evt: CustomEvent) {
var node = evt.detail.node || null;
node?.clearCacheData();
this.refresh();
}
mindMapChange() {
//console.log(this.view)
this.view?.mindMapChange();
}
appKeydown(e: KeyboardEvent) {
var keyCode = e.keyCode || e.which || e.charCode;
var ctrlKey = e.ctrlKey || e.metaKey;
var shiftKey = e.shiftKey;
if (!ctrlKey && !shiftKey) {
// tab
if (keyCode == 9 || keyCode == 45) {
e.preventDefault();
e.stopPropagation();
}
if (keyCode == 32) {
var node = this.selectNode;
if (node && !node.isEdit) {
e.preventDefault();
e.stopPropagation();
node.edit();
this._menuDom.style.display = 'none';
}
}
}
if (ctrlKey && !shiftKey) {
//ctrl + y
if (keyCode == 89) {
e.preventDefault();
e.stopPropagation();
this.redo();
}
//ctrl + z
if (keyCode == 90) {
e.preventDefault();
e.stopPropagation();
this.undo();
}
}
}
appKeyup(e: KeyboardEvent) {
var keyCode = e.keyCode || e.which || e.charCode;
var ctrlKey = e.ctrlKey || e.metaKey;
var shiftKey = e.shiftKey;
if (!ctrlKey && !shiftKey) {
//enter
if (keyCode == 13 || e.key =='Enter') {
var node = this.selectNode;
if (node && !node.isEdit) {
e.preventDefault();
e.stopPropagation();
if (!node.isExpand) {
node.expand();
}
if (!node.parent) return;
node.mindmap.execute('addSiblingNode', {
parent: node.parent
});
this._menuDom.style.display='none';
}
}
//delete
if (keyCode == 46 || e.key == 'Delete' || e.key == 'Backspace') {
var node = this.selectNode;
if (node && !node.isEdit) {
e.preventDefault();
e.stopPropagation();
node.mindmap.execute("deleteNodeAndChild", { node });
this._menuDom.style.display='none';
}
}
//tab
if (keyCode == 9 || keyCode == 45 || e.key == 'Tab') {
e.preventDefault();
e.stopPropagation();
var node = this.selectNode;
if (node && !node.isEdit) {
if (!node.isExpand) {
node.expand();
}
node.mindmap.execute("addChildNode", { parent: node });
this._menuDom.style.display='none';
} else if (node && node.isEdit) {
node.cancelEdit();
node.select();
node.mindmap.editNode=null;
}
}
// up
if (keyCode == 38 || e.key == 'ArrowUp') {
var node = this.selectNode;
if (node && !node.isEdit) {
this._selectNode(node, "up");
}
}
if (keyCode == 40 || e.key == 'ArrowDown') {
var node = this.selectNode;
if (node && !node.isEdit) {
this._selectNode(node, "down");
}
}
if (keyCode == 39 || e.key == 'ArrowRight') {
var node = this.selectNode;
if (node && !node.isEdit) {
this._selectNode(node, "right");
}
}
if (keyCode == 37 || e.key == 'ArrowLeft') {
var node = this.selectNode;
if (node && !node.isEdit) {
this._selectNode(node, "left");
}
}
}
if (ctrlKey && !shiftKey) {
//ctr + / toggle expand node
if (keyCode == 191) {
var node = this.selectNode;
if (node && !node.isEdit) {
if (node.isExpand) {
node.mindmap.execute('collapseNode', {
node
})
} else {
node.mindmap.execute('expandNode', {
node
})
}
}
}
// ctrl + E center
if (keyCode == 69) {
this.center();
}
}
}
_selectNode(node: INode, direct: string) {
if (!node) {
return;
}
var minDis: number;
var waitNode: INode = null;
var pos = node.getPosition();
var mind = this;
mind.traverseDF((n: INode) => {
var p = n.getPosition();
var dx = Math.abs(p.x - pos.x);
var dy = Math.abs(p.y - pos.y);
var dis = Math.sqrt(dx * dx + dy * dy);
switch (direct) {
case "right":
if (p.x > pos.x) {
if (minDis) {
if (minDis > dis) {
minDis = dis;
waitNode = n;
}
} else {
minDis = dis;
waitNode = n;
}
}
break;
case "left":
if (p.x < pos.x) {
if (minDis) {
if (minDis > dis) {
minDis = dis;
waitNode = n;
}
} else {
minDis = dis;
waitNode = n;
}
}
break;
case "up":
if (p.y < pos.y) {
if (minDis) {
if (minDis > dis) {
minDis = dis;
waitNode = n;
}
} else {
minDis = dis;
waitNode = n;
}
}
break;
case "down":
if (p.y > pos.y) {
if (minDis) {
if (minDis > dis) {
minDis = dis;
waitNode = n;
}
} else {
minDis = dis;
waitNode = n;
}
}
break;
}
});
if (waitNode) {
mind.clearSelectNode();
waitNode.select();
}
}
appClickFn(evt: MouseEvent) {
var targetEl = evt.target as HTMLElement;
if (targetEl) {
if (targetEl.tagName == 'A' && targetEl.hasClass("internal-link")) {
evt.preventDefault();
var targetEl = evt.target as HTMLElement;
var href = targetEl.getAttr("href");
if(href){
this.view.app.workspace.openLinkText(
href,
this.view.file.path,
evt.ctrlKey || evt.metaKey
);
}
}
if (targetEl.hasClass('mm-node-bar')) {
evt.preventDefault();
evt.stopPropagation();
var id = targetEl.closest('.mm-node').getAttribute('data-id');
var node = this.getNodeById(id);
if (node.isExpand) {
node.mindmap.execute('collapseNode', {
node
});
} else {
node.mindmap.execute('expandNode', {
node
});
}
return
}
if(targetEl.closest('.mm-node-menu')){
if(targetEl.closest('.mm-icon-add-node')){
var selectNode = this.selectNode;
if(selectNode){
selectNode.mindmap.execute("addChildNode", { parent: selectNode });
this._menuDom.style.display='none';
}
}
if(targetEl.closest('.mm-icon-delete-node')){
var selectNode = this.selectNode;
if(selectNode){
selectNode.mindmap.execute("deleteNodeAndChild", { node: selectNode });
this._menuDom.style.display='none';
}
}
return;
}
if (targetEl.closest('.mm-node')) {
var id = targetEl.closest('.mm-node').getAttribute('data-id');
var node = this.getNodeById(id);
if (!node.isSelect) {
this.clearSelectNode();
this.selectNode = node;
this.selectNode?.select();
this._menuDom.style.display='block';
var box = this.selectNode.getBox();
this._menuDom.style.left = `${box.x + box.width + 10}px`;
this._menuDom.style.top = `${box.y + box.height/2 - 14}px`;
}
} else {
this.clearSelectNode();
this._menuDom.style.display='none';
}
}
}
appDragstart(evt: MouseEvent) {
evt.stopPropagation();
this.startX = evt.pageX;
this.startY = evt.pageY;
if (evt.target instanceof HTMLElement) {
if (evt.target.closest('.mm-node')) {
var id = evt.target.closest('.mm-node').getAttribute('data-id');
this._dragNode = this.getNodeById(id);
this.drag = true;
}
}
}
appDragend(evt: MouseEvent) {
this.drag = false;
this._indicateDom.style.display = 'none'
this._menuDom.style.display = 'none';
}
appDragover(evt: MouseEvent) {
evt.preventDefault();
evt.stopPropagation();
var target =evt.target as HTMLElement;
var x = evt.pageX;
var y = evt.pageY;
if (this.drag) {
this.dx = x - this.startX;
this.dx = y - this.startY;
}
if(target.closest('.mm-node')){
var nodeId =target.closest('.mm-node').getAttribute('data-id');
var node = this.getNodeById(nodeId);
var box = node.getBox();
this._dragType = this._getDragType(node, x, y);
this._indicateDom.style.display = 'block';
this._indicateDom.style.left = box.x + box.width / 2 - 40 / 2 + 'px';
this._indicateDom.style.top = box.y - 90 + 'px';
this._indicateDom.className = 'mm-node-layout-indicate';
if( this._dragType == 'top') {
this._indicateDom.classList.add('mm-arrow-top');
} else if ( this._dragType == 'down') {
this._indicateDom.classList.add('mm-arrow-down');
} else if ( this._dragType == 'left') {
this._indicateDom.classList.add('mm-arrow-left');
} else if ( this._dragType == 'right') {
this._indicateDom.classList.add('mm-arrow-right');
} else {
this._indicateDom.classList.add('drag-type');
var arr = this._dragType.split('-');
if (arr[1]) {
this._indicateDom.classList.add('mm-arrow-' + arr[1]);
} else {
this._indicateDom.classList.add('mm-arrow-right');
}
}
}else{
this._indicateDom.style.display = 'none';
}
}
_getDragType(node:INode, x:number, y:number) {
if (!node) return;
var box = node.contentEl.getBoundingClientRect();
box.x = box.x
box.y = box.y;
var direct = node.direct;
switch (direct) {
case 'right':
if (y < box.y + box.height / 2 && x < box.x + box.width / 4 * 3) {
return 'top'
}
if (y > box.y + box.height / 2 && x < box.x + box.width / 4 * 3) {
return 'down'
}
return 'child-right'
case 'left':
if (y < box.y + box.height / 2 && x > box.x + box.width / 4) {
return 'top'
}
if (y > box.y + box.height / 2 && x > box.x + box.width / 4) {
return 'down'
}
return 'child-left'
case 'top':
case 'up':
if (x < box.x + box.width / 4) {
return 'left'
}
if (x > box.x + box.width / 4 * 3) {
return 'right'
}
return 'child-top'
case 'down':
case 'bottom':
if (x < box.x + box.width / 4) {
return 'left'
}
if (x > box.x + box.width / 4 * 3) {
return 'right'
}
return 'child-down'
default:
return 'child';
}
}
appDrop(evt: MouseEvent) {
if (evt.target instanceof HTMLElement) {
if (evt.target.closest('.mm-node')) {
evt.preventDefault();
var dropNodeId = evt.target.closest('.mm-node').getAttribute('data-id');
var dropNode = this.getNodeById(dropNodeId);
if (this._dragNode.isRoot) {
} else {
this.moveNode(this._dragNode, dropNode,this._dragType);
}
}
}
this._indicateDom.style.display = 'none'
this._menuDom.style.display = 'none';
}
appMouseOverFn(evt: MouseEvent) {
const targetEl = evt.target as HTMLElement;
if (targetEl.tagName !== "A") return;
if (targetEl.hasClass("internal-link")) {
this.view.app.workspace.trigger("hover-link", {
event: evt,
source: frontMatterKey,
hoverParent: this.view,
targetEl,
linktext: targetEl.getAttr("href"),
sourcePath: this.view.file.path,
});
}
}
appMouseMove(evt: MouseEvent) {
const targetEl = evt.target as HTMLElement;
this.scalePointer = [];
this.scalePointer.push(evt.offsetX, evt.offsetY);
if (targetEl.closest('.mm-node')) {
var id = targetEl.closest('.mm-node').getAttribute('data-id');
var node = this.getNodeById(id);
if (node) {
var box = node.getBox();
this.scalePointer = [];
this.scalePointer.push(box.x + box.width / 2, box.y + box.height / 2);
}
}else{
if(this.drag){
this.containerEL.scrollLeft = this._left - (evt.pageX - this.startX);
this.containerEL.scrollTop = this._top - (evt.pageY - this.startY);
}
}
}
appMouseDown(evt:MouseEvent){
const targetEl = evt.target as HTMLElement;
if(!targetEl.closest('.mm-node')){
this.drag = true;
this.startX = evt.pageX;
this.startY = evt.pageY;
this._left = this.containerEL.scrollLeft;
this._top = this.containerEL.scrollTop;
}
}
appMouseUp(evt:MouseEvent){
this.drag = false;
}
appDblclickFn(evt: MouseEvent) {
if (evt.target instanceof HTMLElement) {
if (evt.target.hasClass('mm-node-bar')) {
evt.preventDefault();
evt.stopPropagation();
return;
}
if (evt.target.closest('.mm-node') instanceof HTMLElement) {
var id = evt.target.closest('.mm-node').getAttribute('data-id');
this.selectNode = this.getNodeById(id);
if (!this.editNode || (this.editNode && this.editNode != this.selectNode)) {
this.selectNode?.edit();
this.editNode = this.selectNode;
this._menuDom.style.display='none';
}
}
}
}
appMousewheel(evt: any) {
// if(!evt) evt = window.event;
var ctrlKey = evt.ctrlKey || evt.metaKey;
var delta;
if (evt.wheelDelta) {
//IE、chrome -120
delta = evt.wheelDelta / 120;
} else if (evt.detail) {
//FF 3
delta = -evt.detail / 3;
}
if (delta) {
if (delta < 0) {
if (ctrlKey) {
this.setScale("down");
}
} else {
if (ctrlKey) {
this.setScale("up");
}
}
}
}
clearNode() {
//delete node
this.traverseBF((n: INode) => {
this.contentEL.removeChild(n.containEl);
});
//delete line
if (this.mmLayout) {
this.mmLayout.svgDom?.clear();
}
}
clear() {
this.clearNode();
this.removeEvent();
this.draw?.clear();
}
//get node list rect point
getBoundingRect(list: INode[]) {
var box = {
x: 0,
y: 0,
width: 0,
height: 0,
right: 0,
bottom: 0
};
list.forEach((item, i) => {
var b = item.getBox();
// console.log(b.x,b.y);
if (i == 0) {
box.x = b.x;
box.y = b.y;
box.right = b.x + b.width;
box.bottom = b.y + b.height;
} else {
if (b.x < box.x) {
box.x = b.x
}
if (b.y < box.y) {
box.y = b.y
}
if (b.x + b.width > box.right) {
box.right = b.x + b.width;
}
if (b.y + b.height > box.bottom) {
box.bottom = b.y + b.height;
}
}
});
box.width = box.right - box.x;
box.height = box.bottom - box.y;
return box;
}
moveNode(dragNode: INode, dropNode: INode,type:string) {
if (dragNode == dropNode || dragNode.isRoot) {
return
}
var flag = false;
var p = dropNode.parent;
while (p) {
if (p == dragNode) {
flag = true;
break;
}
p = p.parent;
}
if (flag) { //parent can not change to child
return;
}
dropNode.clearCacheData();
dragNode.clearCacheData();
if (!dropNode.isExpand) {
dropNode.expand();
}
if (type == 'top' || type == 'left' ||type == 'down' || type == 'right') {
this.execute('moveNode', { type: 'siblings', node: dragNode, oldParent: dragNode.parent, dropNode, direct: type })
}
else if (type.indexOf('child') > -1) {
var typeArr = type.split('-');
if (typeArr[1]) {
this.execute('moveNode', { type: 'child', node: dragNode, oldParent: dragNode.parent, parent: dropNode, direct: typeArr[1] })
}
else {
this.execute('moveNode', { type: 'child', node: dragNode, oldParent: dragNode.parent, parent: dropNode });
}
}
// this.execute('moveNode', { type: 'child', node: dragNode, oldParent: dragNode.parent, parent: dropNode })
}
//execute cmd , store history
execute(name: string, data?: any) {
this.exec.execute(name, data);
}
undo() {
this.exec.undo();
}
redo() {
this.exec.redo();
}
addNode(node: INode, parent?: INode, index = -1) {
if (parent) {
parent.addChild(node, index);
if (parent.direct) {
node.direct = parent.direct;
}
this._addNodeDom(node);
node.clearCacheData();
}
}
_addNodeDom(node: INode) {
this.traverseBF((n: INode) => {
if (!this.contentEL.contains(n.containEl)) {
this.contentEL.appendChild(n.containEl);
}
}, node);
}
removeNode(node: INode) {
if (node.parent) {
var p = node.parent;
var i = node.parent.removeChild(node);
this._removeChildDom(node);
p.clearCacheData();
return i;
} else {
this._removeChildDom(node);
return -1;
}
}
_removeChildDom(node: INode) {
this.traverseBF((n: INode) => {
if (this.contentEL.contains(n.containEl)) {
this.contentEL.removeChild(n.containEl);
}
}, node);
}
//layout
layout() {
if (!this.mmLayout) {
this.mmLayout = new Layout(this.root, this.setting.layoutDirect||'mind map', this.colors);
return;
}
this.mmLayout.layout(this.root, this.setting.layoutDirect || this.mmLayout.direct || 'mind map');
}
refresh() {
this.layout();
}
emit(name: string, data?: any) {
var evt = new CustomEvent(name, {
detail: data || {}
});
this.appEl.dispatchEvent(evt);
}
on(name: string, fn: any) {
this.appEl.addEventListener(name, fn);
}
off(name: string, fn: any) {
if (name && fn) {
this.appEl.removeEventListener(name, fn);
}
}
center() {
this._setMindScalePointer();
var oldScale = this.mindScale;
this.scale(100);
var w = this.containerEL.clientWidth;
var h = this.containerEL.clientHeight;
this.containerEL.scrollTop = this.setting.canvasSize / 2 - h / 2 - 60;
this.containerEL.scrollLeft = this.setting.canvasSize / 2 - w / 2 + 30;
this.scale(oldScale);
}
_setMindScalePointer() {
this.scalePointer = [];
var root = this.root;
if (root) {
var rbox = root.getBox();
this.scalePointer.push(rbox.x + rbox.width / 2, rbox.y + rbox.height / 2);
}
}
getMarkdown() {
var md = '';
var level = this.setting.headLevel;
this.traverseDF((n: INode) => {
var l = n.getLevel() + 1;
var hPrefix = '', space = '';
if (l > 1) {
hPrefix = '\n';
}
const ending = n.isExpand ? '' : ` ^${n.getId()}`
if (n.getLevel() < level) {
for (let i = 0; i < l; i++) {
hPrefix += '#';
}
md += (hPrefix + ' ');
md += n.getData().text.trim() + ending + '\n';
} else {
for (var i = 0; i < n.getLevel() - level; i++) {
space += ' ';
}
var text = n.getData().text.trim();
if (text) {
var textArr = text.split('\n');
var lineLength = textArr.length;
if (lineLength == 1) {
md += `${space}- ${text}${ending}\n`;
} else if (lineLength > 1) {
//code
if (text.startsWith('```')) {
md+='\n'
md += `${space}-\n`;
textArr.forEach((t: string, i: number) => {
md += `${space} ${t.trim()}${i === textArr.length - 1 ? ending : '' }\n`
});
md+='\n'
} else {
//text
md += `${space}- `;
textArr.forEach((t: string, i: number) => {
if (i > 0) {
md += `${space} ${t.trim()}${i === textArr.length - 1 ? ending : '' }\n`
} else {
md += `${t.trim()}\n`
}
});
}
}
} else {
md += `-\n`;
}
}
}, this.root, true);
return md.trim();
}
scale(num: number) {
if (num < 20) {
num = 20;
}
if (num > 300) {
num = 300;
}
this.mindScale = num;
if (this.scalePointer.length) {
this.appEl.style.transformOrigin = `${this.scalePointer[0]}px ${this.scalePointer[1]}px`;
this.appEl.style.transform = "scale(" + this.mindScale / 100 + ")";
} else {
this.appEl.style.transform = "scale(" + this.mindScale / 100 + ")";
}
}
setScale(type: string) {
if (type == "up") {
var n = this.mindScale + 10;
} else {
var n = this.mindScale - 10;
}
this.scale(n);
if (this.timeOut) {
clearTimeout(this.timeOut)
}
this.timeOut = setTimeout(() => {
new Notice(`${n} %`);
}, 600);
}
copyNode(node?:any){
var n = node||this.selectNode;
if(n){
var data:any = [];
function copyNode(n:INode, pid:any) {
var d = n.getData();
d.id = uuid();
d.pid = pid;
data.push({
id:d.id,
text:d.text,
pid:pid,
isExpand:d.isExpand,
note:d.note
});
n.children.forEach((c) => {
copyNode(c, d.id);
});
}
copyNode(n,null)
var _data = {
type:'copyNode',
text:data
};
return JSON.stringify(_data);
}else{
return ''
}
}
pasteNode(text:string){
var node = this.selectNode;
if(text){
try{
var json =JSON.parse(text);
if(json.type&&json.type=='copyNode'){
var data = json.text;
if(!node.isExpand){
node.expand();
node.clearCacheData();
}
this.execute('pasteNode',{
node:node,
data:data
})
navigator.clipboard.writeText('');
}
}catch(err){
console.log(err)
}
}
}
} | the_stack |
import { ident } from "../Function"
import { Internals } from "../Internals"
import * as L from "../List"
import { Num } from "../Num"
import { OrderedMap } from "../OrderedMap"
import { fromDefault } from "../Record"
import { Pair } from "../Tuple"
const { List } = L
const { Just, Nothing } = Internals
// [Symbol.iterator]
test ("[Symbol.iterator]", () => {
expect ([ ...List () ]) .toEqual ([])
expect ([ ...List (1, 2, 3) ]) .toEqual ([ 1, 2, 3 ])
})
// APPLICATIVE
test ("pure", () => {
expect (List.pure (3)) .toEqual (List (3))
})
test ("ap", () => {
expect (List.ap (List ((x: number) => x * 3, (x: number) => x * 2))
(List (1, 2, 3, 4, 5)))
.toEqual (List (3, 6, 9, 12, 15, 2, 4, 6, 8, 10))
})
// ALTERNATIVE
test ("alt", () => {
expect (List.alt (List (3)) (List (2)))
.toEqual (List (3))
expect (List.alt (List (3)) (List ()))
.toEqual (List (3))
expect (List.alt (List ()) (List (2)))
.toEqual (List (2))
expect (List.alt (List ()) (List ()))
.toEqual (List ())
})
test ("altF", () => {
expect (List.altF (List (2)) (List (3)))
.toEqual (List (3))
expect (List.altF (List ()) (List (3)))
.toEqual (List (3))
expect (List.altF (List (2)) (List ()))
.toEqual (List (2))
expect (List.altF (List ()) (List ()))
.toEqual (List ())
})
test ("empty", () => {
expect (List.empty) .toEqual (List ())
})
test ("guard", () => {
expect (List.guard (true))
.toEqual (List (true))
expect (List.guard (false))
.toEqual (List ())
})
// MONAD
test ("bind", () => {
expect (List.bind (List (1, 2, 3, 4, 5))
(e => List (e, e)))
.toEqual (List (1, 1, 2, 2, 3, 3, 4, 4, 5, 5))
})
test ("bindF", () => {
expect (List.bindF (e => List (e, e))
(List (1, 2, 3, 4, 5)))
.toEqual (List (1, 1, 2, 2, 3, 3, 4, 4, 5, 5))
})
test ("then", () => {
expect (List.then (List (1, 2, 3, 4, 5))
(List ("a", "c")))
.toEqual (
List ("a", "c", "a", "c", "a", "c", "a", "c", "a", "c")
)
expect (List.then (List ()) (List ("a", "c")))
.toEqual (List ())
})
test ("kleisli", () => {
expect (List.kleisli ((e: number) => List (e, e))
(e => List (e, e * 2))
(2))
.toEqual (List (2, 4, 2, 4))
})
test ("join", () => {
expect (List.join (
List (
List (3),
List (2),
List (1)
)
))
.toEqual (List (3, 2, 1))
})
// FOLDABLE
test ("foldr", () => {
expect (List.foldr<string, string> (e => acc => e + acc) ("0") (List ("3", "2", "1")))
.toEqual ("3210")
})
test ("foldl", () => {
expect (List.foldl<string, string> (acc => e => acc + e) ("0") (List ("1", "2", "3")))
.toEqual ("0123")
})
test ("foldr1", () => {
expect (List.foldr1<number> (e => acc => e + acc) (List (3, 2, 1)))
.toEqual (6)
})
test ("foldl1", () => {
expect (List.foldl1<number> (acc => e => e + acc) (List (3, 2, 1)))
.toEqual (6)
})
test ("toList", () => {
expect (List.toList (List (3, 2, 1)))
.toEqual (List (3, 2, 1))
})
test ("fnull", () => {
expect (List.fnull (List (3, 2, 1))) .toBeFalsy ()
expect (List.fnull (List ())) .toBeTruthy ()
})
test ("fnullStr", () => {
expect (List.fnullStr ("List (3, 2, 1)")) .toBeFalsy ()
expect (List.fnullStr ("")) .toBeTruthy ()
})
test ("flength", () => {
expect (List.flength (List (3, 2, 1))) .toEqual (3)
expect (List.flength (List ())) .toEqual (0)
})
test ("flengthStr", () => {
expect (List.flengthStr ("List (3, 2, 1)")) .toEqual (14)
expect (List.flengthStr ("List ()")) .toEqual (7)
})
test ("elem", () => {
expect (List.elem (3) (List (1, 2, 3, 4, 5)))
.toBeTruthy ()
expect (List.elem (6) (List (1, 2, 3, 4, 5)))
.toBeFalsy ()
})
test ("elemF", () => {
expect (List.elemF (List (1, 2, 3, 4, 5)) (3))
.toBeTruthy ()
expect (List.elemF (List (1, 2, 3, 4, 5)) (6))
.toBeFalsy ()
})
test ("sum", () => {
expect (List.sum (List (3, 2, 1))) .toEqual (6)
})
test ("product", () => {
expect (List.product (List (3, 2, 2))) .toEqual (12)
})
test ("maximum", () => {
expect (List.maximum (List (3, 2, 1))) .toEqual (3)
expect (List.maximum (List ())) .toEqual (-Infinity)
})
test ("minimum", () => {
expect (List.minimum (List (3, 2, 1))) .toEqual (1)
expect (List.minimum (List ())) .toEqual (Infinity)
})
test ("concat", () => {
expect (List.concat (
List (
List (3),
List (2),
List (1)
)
))
.toEqual (List (3, 2, 1))
})
test ("concatMap", () => {
expect (List.concatMap (e => List (e, e))
(List (1, 2, 3, 4, 5)))
.toEqual (List (1, 1, 2, 2, 3, 3, 4, 4, 5, 5))
})
test ("and", () => {
expect (List.and (List (true, true, true)))
.toBeTruthy ()
expect (List.and (List (true, true, false)))
.toBeFalsy ()
expect (List.and (List (true, false, true)))
.toBeFalsy ()
})
test ("or", () => {
expect (List.or (List (true, true, true)))
.toBeTruthy ()
expect (List.or (List (true, true, false)))
.toBeTruthy ()
expect (List.or (List (false, false, false)))
.toBeFalsy ()
})
test ("any", () => {
expect (List.any ((x: number) => x > 2) (List (3, 2, 1)))
.toBeTruthy ()
expect (List.any ((x: number) => x > 3) (List (3, 2, 1)))
.toBeFalsy ()
})
test ("all", () => {
expect (List.all ((x: number) => x >= 1) (List (3, 2, 1)))
.toBeTruthy ()
expect (List.all ((x: number) => x >= 2) (List (3, 2, 1)))
.toBeFalsy ()
})
test ("notElem", () => {
expect (List.notElem (3) (List (1, 2, 3, 4, 5)))
.toBeFalsy ()
expect (List.notElem (6) (List (1, 2, 3, 4, 5)))
.toBeTruthy ()
})
test ("notElemF", () => {
expect (List.notElemF (List (1, 2, 3, 4, 5)) (3))
.toBeFalsy ()
expect (List.notElemF (List (1, 2, 3, 4, 5)) (6))
.toBeTruthy ()
})
test ("find", () => {
expect (List.find ((e: string) => e.includes ("t"))
(List ("one", "two", "three")))
.toEqual (Just ("two"))
expect (List.find ((e: string) => e.includes ("tr"))
(List ("one", "two", "three")))
.toEqual (Nothing)
})
// BASIC FUNCTIONS
test ("append", () => {
expect (List.append (List (3, 2, 1))
(List (3, 2, 1)))
.toEqual (List (3, 2, 1, 3, 2, 1))
})
test ("appendStr", () => {
expect (List.appendStr ("abc") ("def")) .toEqual ("abcdef")
})
test ("cons", () => {
expect (List.cons (List (3, 2, 1)) (4))
.toEqual (List (4, 3, 2, 1))
})
test ("head", () => {
expect (List.head (List (3, 2, 1) as L.Cons<number>)) .toEqual (3)
expect (() => List.head (List () as L.Cons<void>)) .toThrow ()
})
test ("last", () => {
expect (List.last (List (3, 2, 1) as L.Cons<number>)) .toEqual (1)
expect (() => List.last (List () as L.Cons<void>)) .toThrow ()
})
test ("lastS", () => {
expect (List.lastS (List (3, 2, 1))) .toEqual (Just (1))
expect (List.lastS (List ())) .toEqual (Nothing)
})
test ("tail", () => {
expect (List.tail (List (3, 2, 1) as L.Cons<number>))
.toEqual (List (2, 1))
expect (List.tail (List (1) as L.Cons<number>))
.toEqual (List ())
expect (() => List.tail (List () as L.Cons<void>)) .toThrow ()
})
test ("tailS", () => {
expect (List.tailS (List (3, 2, 1)))
.toEqual (Just (List (2, 1)))
expect (List.tailS (List (1)))
.toEqual (Just (List ()))
expect (List.tailS (List ())) .toEqual (Nothing)
})
test ("init", () => {
expect (List.init (List (3, 2, 1) as L.Cons<number>))
.toEqual (List (3, 2))
expect (List.init (List (1) as L.Cons<number>))
.toEqual (List ())
expect (() => List.init (List () as L.Cons<void>)) .toThrow ()
})
test ("initS", () => {
expect (List.initS (List (3, 2, 1)))
.toEqual (Just (List (3, 2)))
expect (List.initS (List (1)))
.toEqual (Just (List ()))
expect (List.initS (List ())) .toEqual (Nothing)
})
test ("uncons", () => {
expect (List.uncons (List (3, 2, 1)))
.toEqual (Just (Pair (3, List (2, 1))))
expect (List.uncons (List (1)))
.toEqual (Just (Pair (1, List ())))
expect (List.uncons (List ())) .toEqual (Nothing)
})
// LIST TRANSFORMATIONS
test ("map", () => {
expect (List.map ((x: number) => x * 2) (List (3, 2, 1)))
.toEqual (List (6, 4, 2))
})
test ("reverse", () => {
expect (List.reverse (List (3, 2, 1)))
.toEqual (List (1, 2, 3))
const original = List (3, 2, 1)
const result = List.reverse (original)
expect (original === result) .toBeFalsy ()
})
test ("intersperse", () => {
expect (List.intersperse (0) (List (3, 2, 1)))
.toEqual (List (3, 0, 2, 0, 1))
})
test ("intercalate", () => {
expect (List.intercalate (", ") (List (3, 2, 1)))
.toEqual ("3, 2, 1")
})
describe ("permutations", () => {
it ("returns an empty list if an empty list is given", () => {
expect (List.permutations (List ()))
.toEqual (List ())
})
it ("returns a singleton list if a singleton list is given", () => {
expect (List.permutations (List (1)))
.toEqual (List (List (1)))
})
it ("returns 2 permutations on input length 2", () => {
expect (List.permutations (List (1, 2)))
.toEqual (List (List (1, 2), List (2, 1)))
})
it ("returns 6 permutations on input length 3", () => {
expect (List.permutations (List (1, 2, 3)))
.toEqual (List (
List (1, 2, 3),
List (1, 3, 2),
List (2, 1, 3),
List (2, 3, 1),
List (3, 1, 2),
List (3, 2, 1)
))
})
it ("returns 24 permutations on input length 4", () => {
expect (List.permutations (List (1, 2, 3, 4)))
.toEqual (List (
List (1, 2, 3, 4),
List (1, 2, 4, 3),
List (1, 3, 2, 4),
List (1, 3, 4, 2),
List (1, 4, 2, 3),
List (1, 4, 3, 2),
List (2, 1, 3, 4),
List (2, 1, 4, 3),
List (2, 3, 1, 4),
List (2, 3, 4, 1),
List (2, 4, 1, 3),
List (2, 4, 3, 1),
List (3, 1, 2, 4),
List (3, 1, 4, 2),
List (3, 2, 1, 4),
List (3, 2, 4, 1),
List (3, 4, 1, 2),
List (3, 4, 2, 1),
List (4, 1, 2, 3),
List (4, 1, 3, 2),
List (4, 2, 1, 3),
List (4, 2, 3, 1),
List (4, 3, 1, 2),
List (4, 3, 2, 1),
))
})
})
// BUILDING LISTS
// SCANS
test ("scanl", () => {
expect (List.scanl<number, number> (acc => x => acc * x) (1) (List (2, 3, 4)))
.toEqual (List (1, 2, 6, 24))
})
// ACCUMULATING MAPS
test ("mapAccumL", () => {
expect (
List.mapAccumL ((acc: string) => (current: number) =>
Pair (acc + current.toString (10), current * 2))
("0")
(List (1, 2, 3))
)
.toEqual (Pair ("0123", List (2, 4, 6)))
})
test ("mapAccumR", () => {
expect (
List.mapAccumR ((acc: string) => (current: number) =>
Pair (acc + current.toString (10), current * 2))
("0")
(List (1, 2, 3))
)
.toEqual (Pair ("0321", List (2, 4, 6)))
})
// INFINITE LISTS
describe ("replicate", () => {
it ("creates a list with 0 elements", () => {
expect (List.replicate (0) ("test"))
.toEqual (List ())
})
it ("creates a list with 1 element", () => {
expect (List.replicate (1) ("test"))
.toEqual (List ("test"))
})
it ("creates a list with 3 elements", () => {
expect (List.replicate (3) ("test"))
.toEqual (List ("test", "test", "test"))
})
it ("creates a list with 5 elements", () => {
expect (List.replicate (5) ("test"))
.toEqual (List ("test", "test", "test", "test", "test"))
})
})
describe ("replicateR", () => {
it ("creates a list with 0 elements", () => {
expect (List.replicateR (0) (ident))
.toEqual (List ())
})
it ("creates a list with 1 element", () => {
expect (List.replicateR (1) (ident))
.toEqual (List (0))
})
it ("creates a list with 3 elements", () => {
expect (List.replicateR (3) (ident))
.toEqual (List (0, 1, 2))
})
it ("creates a list with 5 elements", () => {
expect (List.replicateR (5) (ident))
.toEqual (List (0, 1, 2, 3, 4))
})
})
// UNFOLDING
test ("unfoldr", () => {
expect (List.unfoldr ((x: number) => x < 11 ? Just (Pair (x, x + 1)) : Nothing)
(1))
.toEqual (List (1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
})
// EXTRACTING SUBLIST
test ("take", () => {
expect (List.take (3) (List (1, 2, 3, 4, 5)))
.toEqual (List (1, 2, 3))
expect (List.take (6) (List (1, 2, 3, 4, 5)))
.toEqual (List (1, 2, 3, 4, 5))
})
test ("drop", () => {
expect (List.drop (3) (List (1, 2, 3, 4, 5)))
.toEqual (List (4, 5))
expect (List.drop (6) (List (1, 2, 3, 4, 5)))
.toEqual (List ())
})
test ("splitAt", () => {
expect (List.splitAt (3) (List (1, 2, 3, 4, 5)))
.toEqual (Pair (List (1, 2, 3))
(List (4, 5)))
expect (List.splitAt (6) (List (1, 2, 3, 4, 5)))
.toEqual (Pair (List (1, 2, 3, 4, 5))
(List ()))
})
// PREDICATES
test ("isInfixOf", () => {
expect (List.isInfixOf ("test") ("das asd dsad ad teste f as"))
.toEqual (true)
expect (List.isInfixOf ("test") ("das asd dsad ad tese f as"))
.toEqual (false)
expect (List.isInfixOf ("") ("das asd dsad ad tese f as"))
.toEqual (true)
expect (List.isInfixOf ("") (""))
.toEqual (true)
})
// SEARCHING BY EQUALITY
test ("lookup", () => {
expect (List.lookup (1)
(List (Pair (1) ("a")
, Pair (2) ("b"))))
.toEqual (Just ("a"))
expect (List.lookup (3)
(List (Pair (1) ("a")
, Pair (2) ("b"))))
.toEqual (Nothing)
})
// SEARCHING WITH A PREDICATE
test ("filter", () => {
expect (List.filter ((x: number) => x > 2) (List (1, 2, 3, 4, 5)))
.toEqual (List (3, 4, 5))
})
test ("partition", () => {
expect (List.partition ((x: number) => x > 2) (List (1, 2, 3, 4, 5)))
.toEqual (Pair (List (3, 4, 5))
(List (1, 2)))
})
// INDEXING LISTS
test ("subscript", () => {
expect (List.subscript (List (3, 2, 1)) (2))
.toEqual (Just (1))
expect (List.subscript (List (3, 2, 1)) (4))
.toEqual (Nothing)
expect (List.subscript (List (3, 2, 1)) (-1))
.toEqual (Nothing)
})
test ("subscriptF", () => {
expect (List.subscriptF (2) (List (3, 2, 1)))
.toEqual (Just (1))
expect (List.subscriptF (4) (List (3, 2, 1)))
.toEqual (Nothing)
expect (List.subscriptF (-1) (List (3, 2, 1)))
.toEqual (Nothing)
})
test ("elemIndex", () => {
expect (List.elemIndex (3) (List (1, 2, 3, 4, 5)))
.toEqual (Just (2))
expect (List.elemIndex (8) (List (1, 2, 3, 4, 5)))
.toEqual (Nothing)
})
test ("elemIndices", () => {
expect (List.elemIndices (3) (List (1, 2, 3, 4, 5, 3)))
.toEqual (List (2, 5))
expect (List.elemIndices (4) (List (1, 2, 3, 4, 5, 3)))
.toEqual (List (3))
expect (List.elemIndices (8) (List (1, 2, 3, 4, 5, 3)))
.toEqual (List ())
})
test ("findIndex", () => {
expect (List.findIndex ((x: number) => x > 2) (List (1, 2, 3, 4, 5)))
.toEqual (Just (2))
expect (List.findIndex ((x: number) => x > 8) (List (1, 2, 3, 4, 5)))
.toEqual (Nothing)
})
test ("findIndices", () => {
expect (List.findIndices ((x: number) => x === 3)
(List (1, 2, 3, 4, 5, 3)))
.toEqual (List (2, 5))
expect (List.findIndices ((x: number) => x > 3) (List (1, 2, 3, 4, 5, 3)))
.toEqual (List (3, 4))
expect (List.findIndices ((x: number) => x > 8) (List (1, 2, 3, 4, 5, 3)))
.toEqual (List ())
})
// ZIPPING AND UNZIPPING LISTS
test ("zip", () => {
expect (List.zip (List ("A", "B", "C"))
(List (1, 2, 3)))
.toEqual (List (
Pair ("A") (1),
Pair ("B") (2),
Pair ("C") (3)
))
expect (List.zip (List ("A", "B", "C", "D"))
(List (1, 2, 3)))
.toEqual (List (
Pair ("A") (1),
Pair ("B") (2),
Pair ("C") (3)
))
expect (List.zip (List ("A", "B", "C"))
(List (1, 2, 3, 4)))
.toEqual (List (
Pair ("A") (1),
Pair ("B") (2),
Pair ("C") (3)
))
})
test ("zipWith", () => {
expect (List.zipWith (Pair)
(List ("A", "B", "C"))
(List (1, 2, 3)))
.toEqual (List (
Pair ("A") (1),
Pair ("B") (2),
Pair ("C") (3)
))
expect (List.zipWith (Pair)
(List ("A", "B", "C", "D"))
(List (1, 2, 3)))
.toEqual (List (
Pair ("A") (1),
Pair ("B") (2),
Pair ("C") (3)
))
expect (List.zipWith (Pair)
(List ("A", "B", "C"))
(List (1, 2, 3, 4)))
.toEqual (List (
Pair ("A") (1),
Pair ("B") (2),
Pair ("C") (3)
))
})
// SPECIAL LISTS
// Functions on strings
test ("lines", () => {
expect (List.lines (""))
.toEqual (List ())
expect (List.lines ("\n"))
.toEqual (List (""))
expect (List.lines ("one"))
.toEqual (List ("one"))
expect (List.lines ("one\n"))
.toEqual (List ("one"))
expect (List.lines ("one\n\n"))
.toEqual (List ("one", ""))
expect (List.lines ("one\ntwo"))
.toEqual (List ("one", "two"))
expect (List.lines ("one\ntwo\n"))
.toEqual (List ("one", "two"))
})
// "SET" OPERATIONS
test ("sdelete", () => {
expect (List.sdelete (3) (List (1, 2, 3, 4, 5)))
.toEqual (List (1, 2, 4, 5))
expect (List.sdelete (6) (List (1, 2, 3, 4, 5)))
.toEqual (List (1, 2, 3, 4, 5))
})
test ("intersect", () => {
expect (List.intersect (List (1, 2, 3, 4))
(List (2, 4, 6, 8)))
.toEqual (List (2, 4))
expect (List.intersect (List (1, 2, 2, 3, 4))
(List (6, 4, 4, 2)))
.toEqual (List (2, 2, 4))
})
// ORDERED LISTS
test ("sortBy", () => {
expect (List.sortBy (Num.compare) (List (2, 3, 1, 5, 4)))
.toEqual (List (1, 2, 3, 4, 5))
})
test ("maximumBy", () => {
expect (List.maximumBy (Num.compare) (List (2, 3, 1, 5, 4) as L.NonEmptyList<number>))
.toEqual (5)
})
test ("minimumBy", () => {
expect (List.minimumBy (Num.compare) (List (2, 3, 1, 5, 4) as L.NonEmptyList<number>))
.toEqual (1)
})
// LIST.INDEX
// Original functions
test ("indexed", () => {
expect (List.indexed (List ("a", "b")))
.toEqual (List (
Pair (0) ("a"),
Pair (1) ("b")
))
})
test ("deleteAt", () => {
expect (List.deleteAt (1) (List (1, 2, 3, 4, 5)))
.toEqual (List (1, 3, 4, 5))
})
test ("setAt", () => {
expect (List.setAt (2) (4) (List (1, 2, 3, 4, 5)))
.toEqual (List (1, 2, 4, 4, 5))
})
test ("modifyAt", () => {
expect (List.modifyAt (2) ((x: number) => x * 3) (List (1, 2, 3, 4, 5)))
.toEqual (List (1, 2, 9, 4, 5))
})
test ("updateAt", () => {
expect (List.updateAt (2) ((x: number) => Just (x * 3)) (List (1, 2, 3, 4, 5)))
.toEqual (List (1, 2, 9, 4, 5))
expect (List.updateAt (2) ((_: number) => Nothing) (List (1, 2, 3, 4, 5)))
.toEqual (List (1, 2, 4, 5))
})
test ("insertAt", () => {
expect (List.insertAt (2) (6) (List (1, 2, 3, 4, 5)))
.toEqual (List (1, 2, 6, 3, 4, 5))
})
// Maps
test ("imap", () => {
expect (List.imap (i => (x: number) => x * 2 + i) (List (3, 2, 1)))
.toEqual (List (6, 5, 4))
})
// Folds
test ("ifoldr", () => {
expect (List.ifoldr (i => (x: number) => (acc: number) => acc + x + i)
(0)
(List (3, 2, 1)))
.toEqual (9)
})
test ("ifoldl", () => {
expect (List.ifoldl ((acc: number) => i => (x: number) => acc + x + i)
(0)
(List (3, 2, 1)))
.toEqual (9)
})
test ("iall", () => {
expect (List.iall (i => (x: number) => x >= 1 && i < 5) (List (3, 2, 1)))
.toBeTruthy ()
expect (List.iall (i => (x: number) => x >= 2 && i < 5) (List (3, 2, 1)))
.toBeFalsy ()
expect (List.iall (i => (x: number) => x >= 1 && i > 0) (List (3, 2, 1)))
.toBeFalsy ()
})
test ("iany", () => {
expect (List.iany (i => (x: number) => x > 2 && i < 5) (List (3, 2, 1)))
.toBeTruthy ()
expect (List.iany (i => (x: number) => x > 3 && i < 5) (List (3, 2, 1)))
.toBeFalsy ()
expect (List.iany (i => (x: number) => x > 2 && i > 0) (List (3, 2, 1)))
.toBeFalsy ()
})
test ("iconcatMap", () => {
expect (List.iconcatMap (i => (e: number) => List (e, e + i))
(List (1, 2, 3, 4, 5)))
.toEqual (List (1, 1, 2, 3, 3, 5, 4, 7, 5, 9))
})
test ("ifilter", () => {
expect (List.ifilter (i => (x: number) => x > 2 || i === 0)
(List (1, 2, 3, 4, 5)))
.toEqual (List (1, 3, 4, 5))
})
test ("ipartition", () => {
expect (List.ipartition (i => (x: number) => x > 2 || i === 0)
(List (1, 2, 3, 4, 5)))
.toEqual (Pair (List (1, 3, 4, 5))
(List (2)))
})
// Search
test ("ifind", () => {
expect (List.ifind (i => (e: string) => e.includes ("t") || i === 2)
(List ("one", "two", "three")))
.toEqual (Just ("two"))
expect (List.ifind (i => (e: string) => e.includes ("tr") || i === 2)
(List ("one", "two", "three")))
.toEqual (Just ("three"))
expect (List.ifind (i => (e: string) => e.includes ("tr") || i === 5)
(List ("one", "two", "three")))
.toEqual (Nothing)
})
test ("ifindIndex", () => {
expect (List.ifindIndex (i => (x: number) => x > 2 && i > 2)
(List (1, 2, 3, 4, 5)))
.toEqual (Just (3))
expect (List.ifindIndex (i => (x: number) => x > 8 && i > 2)
(List (1, 2, 3, 4, 5)))
.toEqual (Nothing)
})
test ("ifindIndices", () => {
expect (List.ifindIndices (i => (x: number) => x === 3 && i > 2)
(List (1, 2, 3, 4, 5, 3)))
.toEqual (List (5))
expect (List.ifindIndices (i => (x: number) => x > 4 && i > 3)
(List (1, 2, 3, 4, 5, 3)))
.toEqual (List (4))
expect (List.ifindIndices (i => (x: number) => x > 8 && i > 2)
(List (1, 2, 3, 4, 5, 3)))
.toEqual (List ())
})
// LIST.EXTRA
// String operations
test ("lower", () => {
expect (List.lower ("Test")) .toEqual ("test")
expect (List.lower ("TEst")) .toEqual ("test")
})
test ("trimStart", () => {
expect (List.trimStart (" test\ntest2 ")) .toEqual ("test\ntest2 ")
})
test ("trimEnd", () => {
expect (List.trimEnd (" test\ntest2 ")) .toEqual (" test\ntest2")
})
// Splitting
test ("splitOn", () => {
expect (List.splitOn (";;") ("x;;y;;z;;"))
.toEqual (List ("x", "y", "z", ""))
})
// Basics
test ("notNull", () => {
expect (List.notNull (List (3, 2, 1))) .toEqual (true)
expect (List.notNull (List ())) .toEqual (false)
})
test ("notNullStr", () => {
expect (List.notNullStr ("1")) .toEqual (true)
expect (List.notNullStr ("")) .toEqual (false)
})
test ("list", () => {
expect (List.list (1) ((v: number) => _ => v - 2) (List (5, 6, 7)))
.toEqual (3)
expect (List.list (1) ((v: number) => _ => v - 2) (List ()))
.toEqual (1)
})
describe ("unsnoc", () => {
it ("returns Nothing on empty list", () => {
expect (List.unsnoc (List ())) .toEqual (Nothing)
})
it ("returns Just (Nil, x) on singleton list", () => {
expect (List.unsnoc (List (1))) .toEqual (Just (Pair (List (), 1)))
})
it ("returns Just (init, last) on list with more than one element", () => {
expect (List.unsnoc (List (1, 2, 3, 4))) .toEqual (Just (Pair (List (1, 2, 3), 4)))
})
})
test ("consF", () => {
expect (List.consF (4) (List (3, 2, 1)))
.toEqual (List (4, 3, 2, 1))
})
test ("snoc", () => {
expect (List.snoc (List (3, 2, 1)) (4))
.toEqual (List (3, 2, 1, 4))
})
test ("snocF", () => {
expect (List.snocF (4) (List (3, 2, 1)))
.toEqual (List (3, 2, 1, 4))
})
// List operations
test ("maximumOn", () => {
expect (List.maximumOn ((x: { a: number }) => x.a)
(List ({ a: 1 }, { a: 3 }, { a: 2 })))
.toEqual (Just ({ a: 3 }))
expect (List.maximumOn ((x: { a: number }) => x.a)
(List ()))
.toEqual (Nothing)
})
test ("minimumOn", () => {
expect (List.minimumOn ((x: { a: number }) => x.a)
(List ({ a: 1 }, { a: 3 }, { a: 2 })))
.toEqual (Just ({ a: 1 }))
expect (List.minimumOn ((x: { a: number }) => x.a)
(List ()))
.toEqual (Nothing)
})
test ("firstJust", () => {
expect (List.firstJust ((x: { a: number }) => x.a >= 2 ? Just (x.a) : Nothing)
(List ({ a: 1 }, { a: 3 }, { a: 2 })))
.toEqual (Just (3))
expect (List.firstJust ((x: { a: number }) => x.a >= 2 ? Just (x.a) : Nothing)
(List ()))
.toEqual (Nothing)
})
test ("replaceStr", () => {
expect (List.replaceStr ("{}") ("nice") ("Hello, this is a {} test! It's {}, huh?"))
.toEqual ("Hello, this is a nice test! It's nice, huh?")
})
// OWN METHODS
test ("unsafeIndex", () => {
expect (List.unsafeIndex (List (1, 2, 3, 4, 5)) (1))
.toEqual (2)
expect (() => List.unsafeIndex (List (1, 2, 3, 4, 5)) (5))
.toThrow ()
})
test ("fromArray", () => {
expect (List.fromArray ([ 3, 2, 1 ]))
.toEqual (List (3, 2, 1))
})
test ("toArray", () => {
expect (List.toArray (List (1, 2, 3, 4, 5)))
.toEqual ([ 1, 2, 3, 4, 5 ])
})
test ("isList", () => {
expect (List.isList (List (1, 2, 3, 4, 5)))
.toBeTruthy ()
expect (List.isList (4))
.toBeFalsy ()
})
test ("countWith", () => {
expect (List.countWith ((x: number) => x > 2) (List (1, 2, 3, 4, 5)))
.toEqual (3)
})
test ("countWithByKey", () => {
expect (List.countWithByKey ((x: number) => x % 2) (List (1, 2, 3, 4, 5)))
.toEqual (
OrderedMap.fromArray (
[
[ 1, 3 ],
[ 0, 2 ],
]
)
)
})
test ("countWithByKeyMaybe", () => {
expect (List.countWithByKeyMaybe ((x: number) => x > 3 ? Nothing : Just (x % 2))
(List (1, 2, 3, 4, 5)))
.toEqual (
OrderedMap.fromArray (
[
[ 1, 2 ],
[ 0, 1 ],
]
)
)
})
test ("maximumNonNegative", () => {
expect (List.maximumNonNegative (List (1, 2, 3, 4, 5)))
.toEqual (5)
expect (List.maximumNonNegative (List (-1, -2, -3, 4, 5)))
.toEqual (5)
expect (List.maximumNonNegative (List (-1, -2, -3, -4, -5)))
.toEqual (0)
expect (List.maximumNonNegative (List.empty))
.toEqual (0)
})
test ("groupByKey", () => {
expect (List.groupByKey ((x: number) => x % 2) (List (1, 2, 3, 4, 5)))
.toEqual (
OrderedMap.fromArray (
[
[ 1, List (1, 3, 5) ],
[ 0, List (2, 4) ],
]
)
)
})
test ("mapByIdKeyMap", () => {
const R = fromDefault ("R") ({ id: "" })
const m = OrderedMap.fromArray ([ [ "a", 1 ], [ "b", 2 ], [ "c", 3 ], [ "d", 4 ], [ "e", 5 ] ])
expect (List.mapByIdKeyMap (m)
(List (R ({ id: "d" }), R ({ id: "b" }), R ({ id: "a" }))))
.toEqual (List (4, 2, 1))
})
test ("intersecting", () => {
expect (List.intersecting (List (1, 2, 3)) (List (4, 5, 6))) .toEqual (false)
expect (List.intersecting (List (1, 2, 3)) (List (3, 5, 6))) .toEqual (true)
})
test ("filterMulti", () => {
expect (List.filterMulti (List ((a: number) => a > 2, (a: number) => a < 5))
(List (1, 2, 3, 4, 5)))
.toEqual (List (3, 4))
expect (List.filterMulti (List ((a: number) => a > 2, (a: number) => a < 5))
(List (2, 5, 6, 7)))
.toEqual (List ())
})
test ("lengthAtLeast", () => {
expect (List.lengthAtLeast (3) (List (1, 2, 3, 4, 5)))
.toEqual (true)
expect (List.lengthAtLeast (3) (List (1, 2, 3, 4)))
.toEqual (true)
expect (List.lengthAtLeast (3) (List (1, 2, 3)))
.toEqual (true)
expect (List.lengthAtLeast (3) (List (1, 2)))
.toEqual (false)
expect (() => List.lengthAtLeast (-1) (List (1, 2)))
.toThrow ()
})
test ("lengthAtMost", () => {
expect (List.lengthAtMost (3) (List (1)))
.toEqual (true)
expect (List.lengthAtMost (3) (List (1, 2)))
.toEqual (true)
expect (List.lengthAtMost (3) (List (1, 2, 3)))
.toEqual (true)
expect (List.lengthAtMost (3) (List (1, 2, 3, 4)))
.toEqual (false)
expect (() => List.lengthAtMost (-1) (List (1, 2)))
.toThrow ()
})
describe ("Unique", () => {
describe ("countElem", () => {
it ("counts 0 if there is no matching element", () => {
expect (L.countElem (5) (List (1, 2, 3, 4))) .toBe (0)
})
it ("counts 1 if there is one matching element", () => {
expect (L.countElem (2) (List (1, 2, 3, 4))) .toBe (1)
})
it ("counts 2 if there are two matching element", () => {
expect (L.countElem (2) (List (1, 2, 3, 4, 2))) .toBe (2)
})
it ("counts 3 if there are three matching element", () => {
expect (L.countElem (2) (List (1, 2, 3, 2, 4, 2))) .toBe (3)
})
})
}) | the_stack |
import { reactive, computed, watch } from '@hummer/tenon-vue'
import { storeKey } from './injectKey'
import ModuleCollection from './module/module-collection'
import { forEachValue, isObject, isPromise, assert, partial } from './util'
interface StoreOptions{
plugins?: Array<any>,
strict?: Boolean
}
export function createStore (options:StoreOptions) {
return new Store(options)
}
export class Store {
private _committing:Boolean
private _actions:any
private _actionSubscribers:Array<any>
private _mutations:any
public _wrappedGetters:any
private _modules:any
public _modulesNamespaceMap:any
private _subscribers:any
public _makeLocalGettersCache:any
public strict: Boolean
private _state: any
public getters: any
constructor (options:StoreOptions = {}) {
const {
plugins = [],
strict = false
} = options
// store internal state
this._committing = false
this._actions = Object.create(null)
this._actionSubscribers = []
this._mutations = Object.create(null)
this._wrappedGetters = Object.create(null)
this._modules = new ModuleCollection(options)
this._modulesNamespaceMap = Object.create(null)
this._subscribers = []
this._makeLocalGettersCache = Object.create(null)
// bind commit and dispatch to self
const store = this
const { dispatch, commit } = this
this.dispatch = function boundDispatch (type, payload) {
return dispatch.call(store, type, payload)
}
this.commit = function boundCommit (type, payload, options) {
return commit.call(store, type, payload, options)
}
// strict mode
this.strict = strict
const state = this._modules.root.state
// init root module.
// this also recursively registers all sub-modules
// and collects all module getters inside this._wrappedGetters
installModule(this, state, [], this._modules.root)
// initialize the store state, which is responsible for the reactivity
// (also registers _wrappedGetters as computed properties)
resetStoreState(this, state)
plugins.forEach(plugin => plugin(this))
}
install (app:any, injectKey:string) {
app.provide(injectKey || storeKey, this)
app.config.globalProperties.$store = this
}
get state () {
return this._state.data
}
set state (v) {
if (__DEV__) {
assert(false, `use store.replaceState() to explicit replace store state.`)
}
}
commit (_type:any, _payload:any, _options:any) {
// check object-style commit
const {
type,
payload,
options
} = unifyObjectStyle(_type, _payload, _options)
const mutation = { type, payload }
const entry = this._mutations[type]
if (!entry) {
if (__DEV__) {
console.error(`[vuex] unknown mutation type: ${type}`)
}
return
}
this._withCommit(() => {
entry.forEach(function commitIterator (handler:Function) {
handler(payload)
})
})
this._subscribers
.slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe
.forEach((sub:Function) => sub(mutation, this.state))
if (
__DEV__ &&
options && options.silent
) {
console.warn(
`[vuex] mutation type: ${type}. Silent option has been removed. ` +
'Use the filter functionality in the vue-devtools'
)
}
}
dispatch (_type:any, _payload:any) {
// check object-style dispatch
const {
type,
payload
} = unifyObjectStyle(_type, _payload)
const action = { type, payload }
const entry = this._actions[type]
if (!entry) {
if (__DEV__) {
console.error(`[vuex] unknown action type: ${type}`)
}
return
}
try {
this._actionSubscribers
.slice() // shallow copy to prevent iterator invalidation if subscriber synchronously calls unsubscribe
.filter(sub => sub.before)
.forEach(sub => sub.before(action, this.state))
} catch (e) {
if (__DEV__) {
console.warn(`[vuex] error in before action subscribers: `)
console.error(e)
}
}
const result = entry.length > 1
? Promise.all(entry.map((handler:Function) => handler(payload)))
: entry[0](payload)
return new Promise((resolve, reject) => {
result.then((res:any) => {
try {
this._actionSubscribers
.filter(sub => sub.after)
.forEach(sub => sub.after(action, this.state))
} catch (e) {
if (__DEV__) {
console.warn(`[vuex] error in after action subscribers: `)
console.error(e)
}
}
resolve(res)
}, (error:any) => {
try {
this._actionSubscribers
.filter(sub => sub.error)
.forEach(sub => sub.error(action, this.state, error))
} catch (e) {
if (__DEV__) {
console.warn(`[vuex] error in error action subscribers: `)
console.error(e)
}
}
reject(error)
})
})
}
subscribe (fn:any, options:any) {
return genericSubscribe(fn, this._subscribers, options)
}
subscribeAction (fn:any, options:any) {
const subs = typeof fn === 'function' ? { before: fn } : fn
return genericSubscribe(subs, this._actionSubscribers, options)
}
watch (getter:any, cb:any, options:any) {
if (__DEV__) {
assert(typeof getter === 'function', `store.watch only accepts a function.`)
}
return watch(() => getter(this.state, this.getters), cb, Object.assign({}, options))
}
replaceState (state:any) {
this._withCommit(() => {
console.log('replace State:', JSON.stringify(state))
this._state.data = state
})
}
registerModule (path:any, rawModule:any, options:any = {}) {
if (typeof path === 'string') path = [path]
if (__DEV__) {
assert(Array.isArray(path), `module path must be a string or an Array.`)
assert(path.length > 0, 'cannot register the root module by using registerModule.')
}
this._modules.register(path, rawModule)
installModule(this, this.state, path, this._modules.get(path), options.preserveState)
// reset store to update getters...
resetStoreState(this, this.state)
}
unregisterModule (path:any) {
if (typeof path === 'string') path = [path]
if (__DEV__) {
assert(Array.isArray(path), `module path must be a string or an Array.`)
}
this._modules.unregister(path)
this._withCommit(() => {
const parentState = getNestedState(this.state, path.slice(0, -1))
delete parentState[path[path.length - 1]]
})
resetStore(this)
}
hasModule (path:any) {
if (typeof path === 'string') path = [path]
if (__DEV__) {
assert(Array.isArray(path), `module path must be a string or an Array.`)
}
return this._modules.isRegistered(path)
}
hotUpdate (newOptions:any) {
this._modules.update(newOptions)
resetStore(this, true)
}
_withCommit (fn:Function) {
const committing = this._committing
this._committing = true
fn()
this._committing = committing
}
}
function genericSubscribe (fn:Function, subs:any, options?:any) {
if (subs.indexOf(fn) < 0) {
options && options.prepend
? subs.unshift(fn)
: subs.push(fn)
}
return () => {
const i = subs.indexOf(fn)
if (i > -1) {
subs.splice(i, 1)
}
}
}
function resetStore (store:any, hot?:any) {
store._actions = Object.create(null)
store._mutations = Object.create(null)
store._wrappedGetters = Object.create(null)
store._modulesNamespaceMap = Object.create(null)
const state = store.state
// init all modules
installModule(store, state, [], store._modules.root, true)
// reset state
resetStoreState(store, state, hot)
}
function resetStoreState (store:any, state:any, hot?:any) {
const oldState = store._state
// bind store public getters
store.getters = {}
// reset local getters cache
store._makeLocalGettersCache = Object.create(null)
const wrappedGetters = store._wrappedGetters
const computedObj:any = {}
forEachValue(wrappedGetters, (fn:any, key:any) => {
// use computed to leverage its lazy-caching mechanism
// direct inline function use will lead to closure preserving oldVm.
// using partial to return function with only arguments preserved in closure environment.
computedObj[key] = partial(fn, store)
Object.defineProperty(store.getters, key, {
get: () => computed(() => computedObj[key]()).value,
enumerable: true // for local getters
})
})
store._state = reactive({
data: state
})
// enable strict mode for new state
if (store.strict) {
enableStrictMode(store)
}
if (oldState) {
if (hot) {
// dispatch changes in all subscribed watchers
// to force getter re-evaluation for hot reloading.
store._withCommit(() => {
oldState.data = null
})
}
}
}
function installModule (store:any, rootState:any, path:any, module:any, hot?:any) {
const isRoot = !path.length
const namespace = store._modules.getNamespace(path)
// register in namespace map
if (module.namespaced) {
if (store._modulesNamespaceMap[namespace] && __DEV__) {
console.error(`[vuex] duplicate namespace ${namespace} for the namespaced module ${path.join('/')}`)
}
store._modulesNamespaceMap[namespace] = module
}
// set state
if (!isRoot && !hot) {
const parentState = getNestedState(rootState, path.slice(0, -1))
const moduleName = path[path.length - 1]
store._withCommit(() => {
if (__DEV__) {
if (moduleName in parentState) {
console.warn(
`[vuex] state field "${moduleName}" was overridden by a module with the same name at "${path.join('.')}"`
)
}
}
parentState[moduleName] = module.state
})
}
const local = module.context = makeLocalContext(store, namespace, path)
module.forEachMutation((mutation:any, key:any) => {
const namespacedType = namespace + key
registerMutation(store, namespacedType, mutation, local)
})
module.forEachAction((action:any, key:any) => {
const type = action.root ? key : namespace + key
const handler = action.handler || action
registerAction(store, type, handler, local)
})
module.forEachGetter((getter:any, key:any) => {
const namespacedType = namespace + key
registerGetter(store, namespacedType, getter, local)
})
module.forEachChild((child:any, key:any) => {
installModule(store, rootState, path.concat(key), child, hot)
})
}
/**
* make localized dispatch, commit, getters and state
* if there is no namespace, just use root ones
*/
function makeLocalContext (store:any, namespace:any, path:any) {
const noNamespace = namespace === ''
const local = {
dispatch: noNamespace ? store.dispatch : (_type:any, _payload:any, _options:any) => {
const args = unifyObjectStyle(_type, _payload, _options)
const { payload, options } = args
let { type } = args
if (!options || !options.root) {
type = namespace + type
if (__DEV__ && !store._actions[type]) {
console.error(`[vuex] unknown local action type: ${args.type}, global type: ${type}`)
return
}
}
return store.dispatch(type, payload)
},
commit: noNamespace ? store.commit : (_type:any, _payload:any, _options:any) => {
const args = unifyObjectStyle(_type, _payload, _options)
const { payload, options } = args
let { type } = args
if (!options || !options.root) {
type = namespace + type
if (__DEV__ && !store._mutations[type]) {
console.error(`[vuex] unknown local mutation type: ${args.type}, global type: ${type}`)
return
}
}
store.commit(type, payload, options)
}
}
// getters and state object must be gotten lazily
// because they will be changed by state update
Object.defineProperties(local, {
getters: {
get: noNamespace
? () => store.getters
: () => makeLocalGetters(store, namespace)
},
state: {
get: () => getNestedState(store.state, path)
}
})
return local
}
function makeLocalGetters (store:any, namespace:any) {
if (!store._makeLocalGettersCache[namespace]) {
const gettersProxy = {}
const splitPos = namespace.length
Object.keys(store.getters).forEach(type => {
// skip if the target getter is not match this namespace
if (type.slice(0, splitPos) !== namespace) return
// extract local getter type
const localType = type.slice(splitPos)
// Add a port to the getters proxy.
// Define as getter property because
// we do not want to evaluate the getters in this time.
Object.defineProperty(gettersProxy, localType, {
get: () => store.getters[type],
enumerable: true
})
})
store._makeLocalGettersCache[namespace] = gettersProxy
}
return store._makeLocalGettersCache[namespace]
}
function registerMutation (store:any, type:any, handler:any, local:any) {
const entry = store._mutations[type] || (store._mutations[type] = [])
entry.push(function wrappedMutationHandler (payload:any) {
handler.call(store, local.state, payload)
})
}
function registerAction (store:any, type:any, handler:any, local:any) {
const entry = store._actions[type] || (store._actions[type] = [])
entry.push(function wrappedActionHandler (payload:any) {
let res = handler.call(store, {
dispatch: local.dispatch,
commit: local.commit,
getters: local.getters,
state: local.state,
rootGetters: store.getters,
rootState: store.state
}, payload)
if (!isPromise(res)) {
res = Promise.resolve(res)
}
if (store._devtoolHook) {
return res.catch((err:any) => {
store._devtoolHook.emit('vuex:error', err)
throw err
})
} else {
return res
}
})
}
function registerGetter (store:any, type:any, rawGetter:any, local:any) {
if (store._wrappedGetters[type]) {
if (__DEV__) {
console.error(`[vuex] duplicate getter key: ${type}`)
}
return
}
store._wrappedGetters[type] = function wrappedGetter (store:any) {
return rawGetter(
local.state, // local state
local.getters, // local getters
store.state, // root state
store.getters // root getters
)
}
}
function enableStrictMode (store:any) {
watch(() => store._state.data, () => {
if (__DEV__) {
assert(store._committing, `do not mutate vuex store state outside mutation handlers.`)
}
}, { deep: true, flush: 'sync' })
}
function getNestedState (state:any, path:any) {
return path.reduce((state:any, key:string) => state[key], state)
}
function unifyObjectStyle (type:any, payload:any, options?:any) {
if (isObject(type) && type.type) {
options = payload
payload = type
type = type.type
}
if (__DEV__) {
assert(typeof type === 'string', `expects string as the type, but found ${typeof type}.`)
}
return { type, payload, options }
} | the_stack |
import React from 'react';
import styles from './index.less';
import StringUtil from "@/common/StringUtil";
import Logger from "@/common/Logger";
import {JarBootConst} from "@/common/JarBootConst";
import {ColorBasic, Color256, ColorBrightness} from "@/components/console/ColorTable";
interface ConsoleProps {
/** 是否显示 */
visible?: boolean;
/** 初始内容 */
content?: string;
/** 订阅发布 */
pubsub?: PublishSubmit;
/** 唯一id */
id: string;
/** 高度 */
height?: string | number;
/** 是否自动滚动到底部 */
autoScrollEnd?: boolean;
/** 文字超出边界时是否自动换行 */
wrap: boolean;
}
enum EventType {
/** Console一行 */
CONSOLE_EVENT,
/** Std标准输出 */
STD_PRINT_EVENT,
/** std退格 */
BACKSPACE_EVENT,
/** 清屏 */
CLEAR_EVENT
}
interface ConsoleEvent {
/** 是否显示 */
type: EventType,
/** 是否显示 */
text?: string,
/** 是否显示 */
backspaceNum?: number,
}
interface SgrOption {
/** 前景色 */
foregroundColor: string;
/** 背景色 */
backgroundColor: string;
/** 是否粗体 */
bold: boolean;
/** 是否弱化 */
weaken: boolean;
/** 是否因此 */
hide: boolean;
/** 反显,前景色和背景色掉换 */
exchange: boolean;
/** 倾斜 */
oblique: boolean;
/** 下划线 */
underline: boolean;
/** 上划线 */
overline: boolean;
/** 贯穿线 */
through: boolean;
/** 缓慢闪烁 */
slowBlink: boolean;
/** 快速闪烁 */
fastBlink: boolean;
}
//最大行数
const MAX_LINE = 16384;
//超出上限则移除最老的行数
const AUTO_CLEAN_LINE = 12000;
//渲染更新延迟
const MAX_UPDATE_DELAY = 128;
const MAX_FINISHED_DELAY = MAX_UPDATE_DELAY * 2;
const BEGIN = '[';
const DEFAULT_SGR_OPTION: SgrOption = {
backgroundColor: '',
exchange: false,
foregroundColor: '',
hide: false,
weaken: false,
bold: false,
oblique: false,
underline: false,
overline: false,
through: false,
slowBlink: false,
fastBlink: false,
};
enum CONSOLE_TOPIC {
APPEND_LINE,
STD_PRINT,
BACKSPACE,
FINISH_LOADING,
INSERT_TO_HEADER,
START_LOADING,
CLEAR_CONSOLE,
SCROLL_TO_END,
SCROLL_TO_TOP,
}
const Banner = (
<div className={styles.banner}>
<br/>
<p>
<span className={styles.red}><span> </span>,--.</span>
<span className={styles.green}><span> </span></span>
<span className={styles.yellow}> <span> </span></span>
<span className={styles.blue}>,--. <span> </span></span>
<span className={styles.magenta}><span> </span></span>
<span className={styles.cyan}> <span> </span></span>
<span className={styles.red}><span> </span>,--.<span> </span></span>
</p>
<p>
<span className={styles.red}><span> </span>|<span> </span>|</span>
<span className={styles.green}> ,--,--.</span>
<span className={styles.yellow}>,--.--.</span>
<span className={styles.blue}>|<span> </span>|-. </span>
<span className={styles.magenta}> ,---. </span>
<span className={styles.cyan}> ,---. </span>
<span className={styles.red}>,-'<span> </span>'-. </span>
</p>
<p>
<span className={styles.red}>,--. |<span> </span>|</span>
<span className={styles.green}>' ,-.<span> </span>|</span>
<span className={styles.yellow}>|<span> </span>.--'</span>
<span className={styles.blue}>| .-. '</span>
<span className={styles.magenta}>| .-. |</span>
<span className={styles.cyan}>| .-. |</span>
<span className={styles.red}>'-.<span> </span>.-' </span>
</p>
<p>
<span className={styles.red}>|<span> </span>'-'<span> </span>/</span>
<span className={styles.green}>\ '-'<span> </span>|</span>
<span className={styles.yellow}>|<span> </span>| </span>
<span className={styles.blue}> | `-' |</span>
<span className={styles.magenta}>' '-' '</span>
<span className={styles.cyan}>' '-' '</span>
<span className={styles.red}><span> </span>|<span> </span>|<span> </span></span>
</p>
<p>
<span className={styles.red}> `-----' </span>
<span className={styles.green}> `--`--'</span>
<span className={styles.yellow}>`--'<span> </span></span>
<span className={styles.blue}> `---' </span>
<span className={styles.magenta}> `---' </span>
<span className={styles.cyan}> `---' </span>
<span className={styles.red}><span> </span>`--'<span> </span></span>
</p>
<br/>
<br/>
<p>Jarboot console, docs: <span className={styles.cyan}>{JarBootConst.DOCS_URL}</span></p>
<p>Diagnose command, type ‘help’ and hit ‘ENTER’ to see.</p>
</div>
);
/**
* 控制台终端类
* @author majianzheng
*/
class Console extends React.PureComponent<ConsoleProps> {
private codeDom: Element | any = null;
private loading = document.createElement('p');
private isStartLoading = false;
private eventQueue = [] as ConsoleEvent[];
private lines = [] as HTMLElement[];
private intervalHandle: NodeJS.Timeout|null = null;
private finishHandle: NodeJS.Timeout|null = null;
private sgrOption: SgrOption = {...DEFAULT_SGR_OPTION};
componentDidMount() {
this.intervalHandle = null;
this.finishHandle = null;
this.eventQueue = [];
//初始化loading
let three1 = document.createElement('div');
let three2 = document.createElement('div');
let three3 = document.createElement('div');
three1.className= styles.three1;
three2.className= styles.three2;
three3.className= 'three3';
this.loading.append(three1);
this.loading.append(three2);
this.loading.append(three3);
this.loading.className = styles.loading;
const {pubsub, id, content} = this.props;
//初始化code dom
this.codeDom = document.querySelector(`code[id="id-console-${id}"]`) as Element;
if (content?.length) {
this.resetContent(this.props.content);
}
if (pubsub) {
//初始化事件订阅
pubsub.submit(id, CONSOLE_TOPIC.APPEND_LINE, this.onConsole);
pubsub.submit(id, CONSOLE_TOPIC.STD_PRINT, this.onStdPrint);
pubsub.submit(id, CONSOLE_TOPIC.BACKSPACE, this.onBackspace);
pubsub.submit(id, CONSOLE_TOPIC.START_LOADING, this.onStartLoading);
pubsub.submit(id, CONSOLE_TOPIC.FINISH_LOADING, this.onFinishLoading);
pubsub.submit(id, CONSOLE_TOPIC.CLEAR_CONSOLE, this.onClear);
pubsub.submit(id, CONSOLE_TOPIC.SCROLL_TO_END, this.scrollToEnd);
pubsub.submit(id, CONSOLE_TOPIC.SCROLL_TO_TOP, this.scrollToTop);
}
}
componentWillUnmount() {
this.intervalHandle = null;
const {pubsub, id} = this.props;
if (pubsub) {
pubsub.unSubmit(id, CONSOLE_TOPIC.APPEND_LINE, this.onConsole);
pubsub.unSubmit(id, CONSOLE_TOPIC.STD_PRINT, this.onStdPrint);
pubsub.unSubmit(id, CONSOLE_TOPIC.BACKSPACE, this.onBackspace);
pubsub.unSubmit(id, CONSOLE_TOPIC.START_LOADING, this.onStartLoading);
pubsub.unSubmit(id, CONSOLE_TOPIC.FINISH_LOADING, this.onFinishLoading);
pubsub.unSubmit(id, CONSOLE_TOPIC.CLEAR_CONSOLE, this.onClear);
pubsub.unSubmit(id, CONSOLE_TOPIC.SCROLL_TO_END, this.scrollToEnd);
pubsub.unSubmit(id, CONSOLE_TOPIC.SCROLL_TO_TOP, this.scrollToTop);
}
}
private resetContent = (text: string|undefined) => {
if (text?.length) {
this.codeDom && (this.codeDom.innerHTML = this.ansiCompile(text as string));
}
};
private onClear = () => {
if (!this.codeDom?.children?.length) {
return;
}
const initLength = this.isStartLoading ? 2 : 1;
if (this.codeDom.children.length <= initLength) {
return;
}
this.eventQueue.push({type: EventType.CLEAR_EVENT});
//异步延迟MAX_UPDATE_DELAY毫秒,统一插入
this.trigEvent();
};
private onStartLoading = () => {
if (this.isStartLoading) {
return;
}
try {
this.codeDom.append(this.loading);
this.isStartLoading = true;
} catch (e) {
Logger.error(e);
}
};
private onFinishLoading = (str?: string) => {
this.onConsole(str);
if (this.finishHandle) {
// 以最后一次生效,当前若存在则取消,重新计时
clearTimeout(this.finishHandle);
}
//延迟异步,停止转圈
this.finishHandle = setTimeout(() => {
this.finishHandle = null;
try {
this.codeDom.removeChild(this.loading);
} catch (error) {
//ignore
}
this.isStartLoading = false;
}, MAX_FINISHED_DELAY);
};
private onStdPrint = (text: string | undefined) => {
this.eventQueue.push({type: EventType.STD_PRINT_EVENT, text});
this.trigEvent();
};
private onConsole = (line: string | undefined) => {
if (StringUtil.isString(line)) {
this.eventQueue.push({type: EventType.CONSOLE_EVENT, text: line,});
//异步延迟MAX_UPDATE_DELAY毫秒,统一插入
this.trigEvent();
}
};
private onBackspace = (num: string) => {
let backspaceNum = parseInt(num);
if (!Number.isInteger(backspaceNum)) {
return;
}
this.eventQueue.push({type: EventType.BACKSPACE_EVENT, backspaceNum});
this.trigEvent();
};
/**
* 滚动到最后
*/
private scrollToEnd = () => {
this.codeDom.scrollTop = this.codeDom.scrollHeight;
};
/**
* 滚动到顶部
*/
private scrollToTop = () => {
this.codeDom.scrollTop = 0;
};
/**
* 触发事件
* @private
*/
private trigEvent() {
if (this.intervalHandle) {
//已经触发
return;
}
this.intervalHandle = setTimeout(this.eventLoop, MAX_UPDATE_DELAY);
}
/**
* 事件循环,将一段时间内的事件收集起来统一处理
*/
private eventLoop = () => {
this.intervalHandle = null;
try {
this.eventQueue.forEach(this.handleEvent);
if (this.lines.length) {
if (!this.isStartLoading) {
this.onStartLoading()
}
//使用虚拟节点将MAX_UPDATE_DELAY时间内的所有更新一块append渲染,减轻浏览器负担
const fragment = document.createDocumentFragment();
this.lines.forEach(l => fragment.append(l));
this.loading.before(fragment);
}
this.props.autoScrollEnd && this.scrollToEnd();
} catch (e) {
Logger.error(e);
} finally {
this.eventQueue = [];
this.lines = [];
//检查是否需要清理,如果超过最大行数则移除最老的行
const count = this.codeDom.children.length;
if (count > MAX_LINE) {
//超出的行数加上一次性清理的行
const waitDeleteLineCount = count - MAX_LINE + AUTO_CLEAN_LINE;
for (let i = 0; i < waitDeleteLineCount; ++i) {
this.codeDom.removeChild(this.codeDom.children[0]);
}
}
}
};
/**
* 事件处理
* @param event 事件
*/
private handleEvent = (event: ConsoleEvent) => {
try {
switch (event.type) {
case EventType.CONSOLE_EVENT:
this.handleConsole(event);
break;
case EventType.STD_PRINT_EVENT:
this.handleStdPrint(event);
break;
case EventType.BACKSPACE_EVENT:
this.handleBackspace(event);
break;
case EventType.CLEAR_EVENT:
this.handleClear();
break;
default:
break;
}
} catch (e) {
Logger.error(e);
}
};
/**
* 处理清屏事件
* @private
*/
private handleClear() {
if (this.isStartLoading) {
//如果处于加载中,则保留加载的动画
this.codeDom.innerHTML = "";
this.codeDom.append(this.loading);
} else {
this.codeDom.innerHTML = "";
}
}
/**
* 处理Console事件
* @param event 事件
* @private
*/
private handleConsole(event: ConsoleEvent) {
this.lines.push(this.createConsoleDiv(event));
}
/**
* 创建一行Console容器
* @param event 事件
* @private
*/
private createConsoleDiv(event: ConsoleEvent) {
if (event.text?.length) {
const text = this.ansiCompile(event.text as string);
const div = document.createElement('div');
div.innerHTML = text;
return div;
}
return document.createElement('br');
}
/**
* 处理STD print事件,STD核心算法
* @param event 事件
* @private
*/
private handleStdPrint(event: ConsoleEvent) {
if (!event.text?.length) {
return;
}
//先处理待添加的Console行
if (this.lines.length > 0) {
const fragment = document.createDocumentFragment();
this.lines.forEach(l => fragment.append(l));
if (!this.isStartLoading) {
this.onStartLoading();
}
this.loading.before(fragment);
this.lines = [];
}
let text = event.text;
let index = text.indexOf('\n');
if (-1 == index) {
//没有换行符时
this.updateStdPrint(text);
return;
}
//换行处理算法,解析字符串中的换行符,替换为p标签,行未结束为p标签,行结束标识为br
while (-1 !== index) {
let last = this.getLastLine() as HTMLElement;
//1、截断一行;2、去掉左右尖括号"<>";3、Ansi编译
const left = this.ansiCompile(this.rawText(text.substring(0, index)));
if (last) {
if ('BR' === last.nodeName) {
last.before(this.createNewLine(left));
} else if ('P' === last.nodeName) {
last.insertAdjacentHTML("beforeend", left);
last.insertAdjacentHTML('afterend', '<br/>');
} else {
//其它标签
last.insertAdjacentHTML("afterend", `<p>${left}</p><br/>`);
}
} else {
//当前为空时,插入新的p和br
this.codeDom.insertAdjacentHTML('afterbegin', `<p>${left}</p><br/>`);
}
//得到下一个待处理的子串
text = text.substring(index + 1);
index = text.indexOf('\n');
}
if (text.length) {
//换行符不在最后一位时,会剩下最后一个子字符串
this.updateStdPrint(text);
}
}
/**
* STD print更新最后一行内容
* @param text 内容
* @private
*/
private updateStdPrint(text: string) {
text = this.ansiCompile(this.rawText(text));
let last = this.getLastLine() as HTMLElement;
if (last) {
if ('BR' === last.nodeName) {
last.replaceWith(this.createNewLine(text));
}
if ('P' === last.nodeName) {
last.insertAdjacentHTML("beforeend", text);
} else {
last.after(this.createNewLine(text));
}
} else {
this.codeDom.insertAdjacentHTML('afterbegin', `<p>${text}</p>`);
}
}
/**
* 创建STD print一行
* @param content 内容
*/
private createNewLine = (content: string) => {
const line = document.createElement('p');
line.innerHTML = content;
return line;
};
/**
* 处理退格事件,退格核心算法入口
* @param event 事件
* @private
*/
private handleBackspace(event: ConsoleEvent) {
let last = this.getLastLine() as HTMLElement;
//backspace操作只会作用于最后一行,因此只认p标签
if (!last || 'P' !== last.nodeName) {
return;
}
let backspaceNum = event.backspaceNum as number;
if (backspaceNum > 0) {
const len = last.innerText.length - backspaceNum;
if (len > 0) {
//行内容未被全部删除时
this.removeDeleted(last, len);
} else {
//行内容被全部清除时,保留一个换行符
last.replaceWith(document.createElement('br'));
}
}
}
/**
* 退格删除算法,留下保留的长度,剩下的去除
* @param line p节点
* @param len 保留的长度
*/
private removeDeleted = (line: HTMLElement, len: number) => {
let html = '';
let nodes = line.childNodes;
for(let i = 0; i < nodes.length; ++i){
const node = nodes[i];
const isText = ('#text' === node.nodeName);
let text = isText ? (node.nodeValue || '') : ((node as HTMLElement).innerText);
const remained = len - text.length;
if (remained > 0) {
html += (isText ? text : ((node as HTMLElement).outerHTML));
len = remained;
} else {
text = (0 === remained) ? text : text.substring(0, len);
if (isText) {
html += text;
} else {
(node as HTMLElement).innerText = text;
html += ((node as HTMLElement).outerHTML);
}
break;
}
}
line.innerHTML = html;
};
/**
* 获取最后一行
* @private
*/
private getLastLine(): HTMLElement|null {
if (!this.codeDom.children?.length) {
return null;
}
const len = this.codeDom.children.length;
return this.isStartLoading ? this.codeDom.children[len - 2] : this.codeDom.children[len - 1];
}
/**
* Ansi核心算法入口
* @param content 待解析的内容
* @return {string} 解析后内容
* @private
*/
private ansiCompile(content: string): string {
//色彩支持: \033[31m 文字 \033[0m
let begin = content.indexOf(BEGIN);
let preIndex = 0;
let preBegin = -1;
while (-1 !== begin) {
const mBegin = begin + BEGIN.length;
const mIndex = content.indexOf('m', mBegin);
if (-1 == mIndex) {
break;
}
const preStyle = this.toStyle();
const termStyle = content.substring(mBegin, mIndex);
//格式控制
if (preStyle.length) {
const styled = this.styleText(content.substring(preIndex, begin), preStyle);
const text = (preIndex > 0 && -1 !== preBegin) ? (content.substring(0, preBegin) + styled) : styled;
content = (text + content.substring(mIndex + 1));
preIndex = text.length;
} else {
const text = content.substring(0, begin);
content = (text + content.substring(mIndex + 1));
preIndex = text.length;
}
//解析termStyle: 32m、 48;5;4m
if (!this.parseTermStyle(termStyle)) {
Logger.error('parseTermStyle failed.', termStyle, content);
}
preBegin = begin;
begin = content.indexOf(BEGIN, preIndex);
}
const style = this.toStyle();
if (style.length) {
if (preIndex > 0) {
content = (content.substring(0, preIndex) + this.styleText(content.substring(preIndex), style));
} else {
content = this.styleText(content, style);
}
}
return content;
}
/**
* 尖括号转义
* @param text 字符串
* @return {string}
*/
private rawText = (text: string): string => {
if (text.length) {
return text.replaceAll('<', '<').replaceAll('>', '>');
}
return text;
};
/**
* 样式包裹
* @param text 文本
* @param style 样式
*/
private styleText = (text: string, style: string): string => {
if (style.length) {
return `<span style="${style}">${this.rawText(text)}</span>`;
}
return text;
};
/**
* ig: \033[32m、 \033[48;5;4m
* @return 是否成功
* @param styles 以分号分隔的数字字符串
*/
private parseTermStyle(styles: string): boolean {
if (StringUtil.isEmpty(styles)) {
return false;
}
const sgrList: string[] = styles.split(';');
while (sgrList.length > 0) {
const sgr = sgrList.shift() as string;
const number = parseInt(sgr);
if (isNaN(number)) {
return false;
}
const index = (number % 10);
const type = Math.floor((number / 10));
switch (type) {
case 0:
//特殊格式控制
this.specCtl(index, true);
break;
case 1:
//字体控制,暂不支持
break;
case 2:
//特殊格式关闭
this.specCtl(index, false);
break;
case 3:
//前景色
this.setForeground(index, sgrList, true);
break;
case 4:
//背景色
this.setBackground(index, sgrList, true);
break;
case 5:
// 51: Framed、52: Encircled、53: 上划线、54: Not framed or encircled、55: 关闭上划线
switch (index) {
case 3:
// 53: 上划线
this.sgrOption.overline = true;
break;
case 5:
// 55: 关闭上划线
this.sgrOption.overline = false;
break;
default:
//其他暂不支持
break;
}
break;
case 6:
//表意文字,暂不支持
// 60: 表意文字下划线或右边线
// 61: 表意文字双下划线或双右边线
// 62: 表意文字上划线或左边线
// 63: 表意文字双上划线或双左边线
// 64: 表意文字着重标志
// 65: 表意文字属性关闭
break;
case 9:
//前景色,亮色系
this.setForeground(index, sgrList, false);
break;
case 10:
//背景色,亮色系
this.setBackground(index, sgrList, false);
break;
default:
//其他情况暂未支持
break;
}
}
return true;
}
/**
* 256色、24位色解析
* @param sgrList 颜色参数
* @return {string} color
*/
private parseSgr256Or24Color = (sgrList: string[]): string => {
//如果是2,则使用24位色彩格式,格式为:2;r;g;b
//如果是5,则使用256色彩索引表
const type = sgrList.shift();
let color = '';
switch (type) {
case '2':
//使用24位色彩格式,格式为:2;r;g;b
//依次取出r、g、b的值
const r = parseInt(sgrList.shift() as string);
if (isNaN(r)) {
return color;
}
const g = parseInt(sgrList.shift() as string);
if (isNaN(g)) {
return color;
}
const b = parseInt(sgrList.shift() as string);
if (isNaN(b)) {
return color;
}
color = `rgb(${r},${g},${b})`;
break;
case '5':
//使用256色彩索引表
const index = parseInt(sgrList.shift() as string);
if (isNaN(index)) {
return color;
}
color = Color256[index] || '';
break;
default:
break;
}
return color;
};
/**
* 特殊格式设置
* @param index {number} 类型
* @param value {boolean} 是否启用
* @private
*/
private specCtl(index: number, value: boolean) {
switch (index) {
case 0:
//关闭所有格式,还原为初始状态,轻拷贝
if (value) {
this.sgrOption = {...DEFAULT_SGR_OPTION};
}
break;
case 1:
//粗体/高亮显示
this.sgrOption.bold = value;
break;
case 2:
//弱化、模糊(※)
this.sgrOption.weaken = value;
break;
case 3:
//斜体(※)
this.sgrOption.oblique = value;
break;
case 4:
//下划线
this.sgrOption.underline = value;
break;
case 5:
//闪烁(慢)
this.sgrOption.slowBlink = value;
break;
case 6:
//闪烁(快)(※)
this.sgrOption.fastBlink = value;
break;
case 7:
//交换背景色与前景色
this.sgrOption.exchange = value;
break;
case 8:
//隐藏(伸手不见五指,啥也看不见)(※)
this.sgrOption.hide = value;
break;
case 9:
//划除
this.sgrOption.through = value;
break;
default:
break;
}
}
/**
* 前景色设置
* @param index {number} 类型
* @param sgrList {string[]} 颜色配置
* @param basic {boolean} 是否是基本色
* @private
*/
private setForeground(index: number, sgrList: string[], basic: boolean) {
switch (index) {
case 8:
//设置前景色
const color = this.parseSgr256Or24Color(sgrList);
this.sgrOption.foregroundColor = color;
break;
case 9:
//恢复默认
this.sgrOption.foregroundColor = '';
break;
default:
const fontColor = (basic ? ColorBasic[index] : ColorBrightness[index]) || '';
this.sgrOption.foregroundColor = fontColor;
break;
}
}
/**
* 背景色设置
* @param index {number} 类型
* @param sgrList {string[]} 颜色配置
* @param basic {boolean} 是否是基本色
* @private
*/
private setBackground(index: number, sgrList: string[], basic: boolean) {
switch (index) {
case 8:
const color = this.parseSgr256Or24Color(sgrList);
this.sgrOption.backgroundColor = color;
break;
case 9:
//恢复默认
this.sgrOption.backgroundColor = '';
break;
default:
const bgColor = (basic ? ColorBasic[index] : ColorBrightness[index]) || '';
this.sgrOption.backgroundColor = bgColor;
break;
}
}
/**
* 将Ansi的配置转换为css样式
* @private
*/
private toStyle(): string {
let style = '';
if (this.sgrOption.hide) {
//隐藏,但需要保留位置
style += `visibility:hidden;`;
}
if (this.sgrOption.exchange) {
//前景色、背景色掉换
const foregroundColor = StringUtil.isEmpty(this.sgrOption.backgroundColor) ? '#263238' : this.sgrOption.backgroundColor;
const backgroundColor = StringUtil.isEmpty(this.sgrOption.foregroundColor) ? 'seashell' : this.sgrOption.foregroundColor;
style += `color:${foregroundColor};background:${backgroundColor};`;
} else {
if (StringUtil.isNotEmpty(this.sgrOption.backgroundColor)) {
style += `background:${this.sgrOption.backgroundColor};`;
}
if (StringUtil.isNotEmpty(this.sgrOption.foregroundColor)) {
style += `color:${this.sgrOption.foregroundColor};`;
}
}
if (this.sgrOption.bold) {
style += `font-weight:bold;`;
}
if (this.sgrOption.oblique) {
style += `font-style:oblique;`;
}
let decorationLine = '';
if (this.sgrOption.underline) {
decorationLine += `underline `;
}
if (this.sgrOption.through) {
decorationLine += `line-through `;
}
if (this.sgrOption.overline) {
decorationLine += `overline `;
}
if (decorationLine.length) {
style += `text-decoration-line:${decorationLine.trim()};`
}
if (this.sgrOption.weaken) {
style += `opacity:.5;`;
}
let animation = '';
if (this.sgrOption.slowBlink) {
const blink = styles['blink'];
animation = `${blink} 800ms infinite `;
}
if (this.sgrOption.fastBlink) {
const blink = styles['blink'];
//同时存在慢闪烁和快闪烁时,使用快的
animation = `${blink} 200ms infinite `;
}
if (animation.length) {
style += `animation:${animation};-webkit-animation:${animation};`
}
return style;
}
render() {
const style: any = {display: false === this.props.visible ? 'none' : 'block'};
if (this.props.height) {
style.height = this.props.height;
}
if (this.props.wrap) {
style.whiteSpace = "pre-wrap";
}
return <code id={`id-console-${this.props.id}`}
style={style}
className={styles.console}>
{Banner}
</code>;
}
}
export {CONSOLE_TOPIC};
export default Console; | the_stack |
import {
EndpointsInputConfig,
EndpointsResolvedConfig,
RegionInputConfig,
RegionResolvedConfig,
resolveEndpointsConfig,
resolveRegionConfig,
} from "@aws-sdk/config-resolver";
import { getContentLengthPlugin } from "@aws-sdk/middleware-content-length";
import {
getHostHeaderPlugin,
HostHeaderInputConfig,
HostHeaderResolvedConfig,
resolveHostHeaderConfig,
} from "@aws-sdk/middleware-host-header";
import { getLoggerPlugin } from "@aws-sdk/middleware-logger";
import { getRetryPlugin, resolveRetryConfig, RetryInputConfig, RetryResolvedConfig } from "@aws-sdk/middleware-retry";
import {
AwsAuthInputConfig,
AwsAuthResolvedConfig,
getAwsAuthPlugin,
resolveAwsAuthConfig,
} from "@aws-sdk/middleware-signing";
import {
getUserAgentPlugin,
resolveUserAgentConfig,
UserAgentInputConfig,
UserAgentResolvedConfig,
} from "@aws-sdk/middleware-user-agent";
import { HttpHandler as __HttpHandler } from "@aws-sdk/protocol-http";
import {
Client as __Client,
SmithyConfiguration as __SmithyConfiguration,
SmithyResolvedConfiguration as __SmithyResolvedConfiguration,
} from "@aws-sdk/smithy-client";
import {
Credentials as __Credentials,
Decoder as __Decoder,
Encoder as __Encoder,
Hash as __Hash,
HashConstructor as __HashConstructor,
HttpHandlerOptions as __HttpHandlerOptions,
Logger as __Logger,
Provider as __Provider,
Provider,
RegionInfoProvider,
StreamCollector as __StreamCollector,
UrlParser as __UrlParser,
UserAgent as __UserAgent,
} from "@aws-sdk/types";
import {
ChangeServerLifeCycleStateCommandInput,
ChangeServerLifeCycleStateCommandOutput,
} from "./commands/ChangeServerLifeCycleStateCommand";
import {
CreateReplicationConfigurationTemplateCommandInput,
CreateReplicationConfigurationTemplateCommandOutput,
} from "./commands/CreateReplicationConfigurationTemplateCommand";
import { DeleteJobCommandInput, DeleteJobCommandOutput } from "./commands/DeleteJobCommand";
import {
DeleteReplicationConfigurationTemplateCommandInput,
DeleteReplicationConfigurationTemplateCommandOutput,
} from "./commands/DeleteReplicationConfigurationTemplateCommand";
import { DeleteSourceServerCommandInput, DeleteSourceServerCommandOutput } from "./commands/DeleteSourceServerCommand";
import {
DescribeJobLogItemsCommandInput,
DescribeJobLogItemsCommandOutput,
} from "./commands/DescribeJobLogItemsCommand";
import { DescribeJobsCommandInput, DescribeJobsCommandOutput } from "./commands/DescribeJobsCommand";
import {
DescribeReplicationConfigurationTemplatesCommandInput,
DescribeReplicationConfigurationTemplatesCommandOutput,
} from "./commands/DescribeReplicationConfigurationTemplatesCommand";
import {
DescribeSourceServersCommandInput,
DescribeSourceServersCommandOutput,
} from "./commands/DescribeSourceServersCommand";
import {
DisconnectFromServiceCommandInput,
DisconnectFromServiceCommandOutput,
} from "./commands/DisconnectFromServiceCommand";
import { FinalizeCutoverCommandInput, FinalizeCutoverCommandOutput } from "./commands/FinalizeCutoverCommand";
import {
GetLaunchConfigurationCommandInput,
GetLaunchConfigurationCommandOutput,
} from "./commands/GetLaunchConfigurationCommand";
import {
GetReplicationConfigurationCommandInput,
GetReplicationConfigurationCommandOutput,
} from "./commands/GetReplicationConfigurationCommand";
import { InitializeServiceCommandInput, InitializeServiceCommandOutput } from "./commands/InitializeServiceCommand";
import {
ListTagsForResourceCommandInput,
ListTagsForResourceCommandOutput,
} from "./commands/ListTagsForResourceCommand";
import { MarkAsArchivedCommandInput, MarkAsArchivedCommandOutput } from "./commands/MarkAsArchivedCommand";
import {
RetryDataReplicationCommandInput,
RetryDataReplicationCommandOutput,
} from "./commands/RetryDataReplicationCommand";
import { StartCutoverCommandInput, StartCutoverCommandOutput } from "./commands/StartCutoverCommand";
import { StartTestCommandInput, StartTestCommandOutput } from "./commands/StartTestCommand";
import { TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand";
import {
TerminateTargetInstancesCommandInput,
TerminateTargetInstancesCommandOutput,
} from "./commands/TerminateTargetInstancesCommand";
import { UntagResourceCommandInput, UntagResourceCommandOutput } from "./commands/UntagResourceCommand";
import {
UpdateLaunchConfigurationCommandInput,
UpdateLaunchConfigurationCommandOutput,
} from "./commands/UpdateLaunchConfigurationCommand";
import {
UpdateReplicationConfigurationCommandInput,
UpdateReplicationConfigurationCommandOutput,
} from "./commands/UpdateReplicationConfigurationCommand";
import {
UpdateReplicationConfigurationTemplateCommandInput,
UpdateReplicationConfigurationTemplateCommandOutput,
} from "./commands/UpdateReplicationConfigurationTemplateCommand";
import { getRuntimeConfig as __getRuntimeConfig } from "./runtimeConfig";
export type ServiceInputTypes =
| ChangeServerLifeCycleStateCommandInput
| CreateReplicationConfigurationTemplateCommandInput
| DeleteJobCommandInput
| DeleteReplicationConfigurationTemplateCommandInput
| DeleteSourceServerCommandInput
| DescribeJobLogItemsCommandInput
| DescribeJobsCommandInput
| DescribeReplicationConfigurationTemplatesCommandInput
| DescribeSourceServersCommandInput
| DisconnectFromServiceCommandInput
| FinalizeCutoverCommandInput
| GetLaunchConfigurationCommandInput
| GetReplicationConfigurationCommandInput
| InitializeServiceCommandInput
| ListTagsForResourceCommandInput
| MarkAsArchivedCommandInput
| RetryDataReplicationCommandInput
| StartCutoverCommandInput
| StartTestCommandInput
| TagResourceCommandInput
| TerminateTargetInstancesCommandInput
| UntagResourceCommandInput
| UpdateLaunchConfigurationCommandInput
| UpdateReplicationConfigurationCommandInput
| UpdateReplicationConfigurationTemplateCommandInput;
export type ServiceOutputTypes =
| ChangeServerLifeCycleStateCommandOutput
| CreateReplicationConfigurationTemplateCommandOutput
| DeleteJobCommandOutput
| DeleteReplicationConfigurationTemplateCommandOutput
| DeleteSourceServerCommandOutput
| DescribeJobLogItemsCommandOutput
| DescribeJobsCommandOutput
| DescribeReplicationConfigurationTemplatesCommandOutput
| DescribeSourceServersCommandOutput
| DisconnectFromServiceCommandOutput
| FinalizeCutoverCommandOutput
| GetLaunchConfigurationCommandOutput
| GetReplicationConfigurationCommandOutput
| InitializeServiceCommandOutput
| ListTagsForResourceCommandOutput
| MarkAsArchivedCommandOutput
| RetryDataReplicationCommandOutput
| StartCutoverCommandOutput
| StartTestCommandOutput
| TagResourceCommandOutput
| TerminateTargetInstancesCommandOutput
| UntagResourceCommandOutput
| UpdateLaunchConfigurationCommandOutput
| UpdateReplicationConfigurationCommandOutput
| UpdateReplicationConfigurationTemplateCommandOutput;
export interface ClientDefaults extends Partial<__SmithyResolvedConfiguration<__HttpHandlerOptions>> {
/**
* The HTTP handler to use. Fetch in browser and Https in Nodejs.
*/
requestHandler?: __HttpHandler;
/**
* A constructor for a class implementing the {@link __Hash} interface
* that computes the SHA-256 HMAC or checksum of a string or binary buffer.
* @internal
*/
sha256?: __HashConstructor;
/**
* The function that will be used to convert strings into HTTP endpoints.
* @internal
*/
urlParser?: __UrlParser;
/**
* A function that can calculate the length of a request body.
* @internal
*/
bodyLengthChecker?: (body: any) => number | undefined;
/**
* A function that converts a stream into an array of bytes.
* @internal
*/
streamCollector?: __StreamCollector;
/**
* The function that will be used to convert a base64-encoded string to a byte array.
* @internal
*/
base64Decoder?: __Decoder;
/**
* The function that will be used to convert binary data to a base64-encoded string.
* @internal
*/
base64Encoder?: __Encoder;
/**
* The function that will be used to convert a UTF8-encoded string to a byte array.
* @internal
*/
utf8Decoder?: __Decoder;
/**
* The function that will be used to convert binary data to a UTF-8 encoded string.
* @internal
*/
utf8Encoder?: __Encoder;
/**
* The runtime environment.
* @internal
*/
runtime?: string;
/**
* Disable dyanamically changing the endpoint of the client based on the hostPrefix
* trait of an operation.
*/
disableHostPrefix?: boolean;
/**
* Value for how many times a request will be made at most in case of retry.
*/
maxAttempts?: number | __Provider<number>;
/**
* Specifies which retry algorithm to use.
*/
retryMode?: string | __Provider<string>;
/**
* Optional logger for logging debug/info/warn/error.
*/
logger?: __Logger;
/**
* Unique service identifier.
* @internal
*/
serviceId?: string;
/**
* The AWS region to which this client will send requests
*/
region?: string | __Provider<string>;
/**
* Default credentials provider; Not available in browser runtime.
* @internal
*/
credentialDefaultProvider?: (input: any) => __Provider<__Credentials>;
/**
* Fetch related hostname, signing name or signing region with given region.
* @internal
*/
regionInfoProvider?: RegionInfoProvider;
/**
* The provider populating default tracking information to be sent with `user-agent`, `x-amz-user-agent` header
* @internal
*/
defaultUserAgentProvider?: Provider<__UserAgent>;
}
type MgnClientConfigType = Partial<__SmithyConfiguration<__HttpHandlerOptions>> &
ClientDefaults &
RegionInputConfig &
EndpointsInputConfig &
RetryInputConfig &
HostHeaderInputConfig &
AwsAuthInputConfig &
UserAgentInputConfig;
/**
* The configuration interface of MgnClient class constructor that set the region, credentials and other options.
*/
export interface MgnClientConfig extends MgnClientConfigType {}
type MgnClientResolvedConfigType = __SmithyResolvedConfiguration<__HttpHandlerOptions> &
Required<ClientDefaults> &
RegionResolvedConfig &
EndpointsResolvedConfig &
RetryResolvedConfig &
HostHeaderResolvedConfig &
AwsAuthResolvedConfig &
UserAgentResolvedConfig;
/**
* The resolved configuration interface of MgnClient class. This is resolved and normalized from the {@link MgnClientConfig | constructor configuration interface}.
*/
export interface MgnClientResolvedConfig extends MgnClientResolvedConfigType {}
/**
* <p>The Application Migration Service service.</p>
*/
export class MgnClient extends __Client<
__HttpHandlerOptions,
ServiceInputTypes,
ServiceOutputTypes,
MgnClientResolvedConfig
> {
/**
* The resolved configuration of MgnClient class. This is resolved and normalized from the {@link MgnClientConfig | constructor configuration interface}.
*/
readonly config: MgnClientResolvedConfig;
constructor(configuration: MgnClientConfig) {
const _config_0 = __getRuntimeConfig(configuration);
const _config_1 = resolveRegionConfig(_config_0);
const _config_2 = resolveEndpointsConfig(_config_1);
const _config_3 = resolveRetryConfig(_config_2);
const _config_4 = resolveHostHeaderConfig(_config_3);
const _config_5 = resolveAwsAuthConfig(_config_4);
const _config_6 = resolveUserAgentConfig(_config_5);
super(_config_6);
this.config = _config_6;
this.middlewareStack.use(getRetryPlugin(this.config));
this.middlewareStack.use(getContentLengthPlugin(this.config));
this.middlewareStack.use(getHostHeaderPlugin(this.config));
this.middlewareStack.use(getLoggerPlugin(this.config));
this.middlewareStack.use(getAwsAuthPlugin(this.config));
this.middlewareStack.use(getUserAgentPlugin(this.config));
}
/**
* Destroy underlying resources, like sockets. It's usually not necessary to do this.
* However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed.
* Otherwise, sockets might stay open for quite a long time before the server terminates them.
*/
destroy(): void {
super.destroy();
}
} | the_stack |
import { areChildrenOutOfBounds } from '../../../Common/redux/Helpers/areChildrenOutOfBounds';
import { getWorkItemsForLevel } from './workItemsForLevel';
import { IFeatureTimelineRawState } from '../store/types';
import { IIterationDuration, IterationDurationKind } from "../../../Common/redux/Contracts/IIterationDuration";
import { IWorkItemInfo, WorkItemLevel } from '../store/workitems/types';
import { WorkItem, WorkItemStateColor } from 'TFS/WorkItemTracking/Contracts';
import { compareIteration } from '../../../Common/redux/Helpers/iterationComparer';
import { getTeamIterations } from './teamIterations';
import { UIStatus, StateCategory } from '../../../Common/redux/Contracts/types';
import { IWorkItemDisplayDetails } from '../../../Common/redux/Contracts/GridViewContracts';
export enum FeatureFilter {
None,
InProgress,
WithoutIteration
}
export function getEpicHierarchy(projectId: string,
teamId: string,
uiStatus: UIStatus,
rawState: IFeatureTimelineRawState,
featureFilter: FeatureFilter): IWorkItemDisplayDetails[] {
if (uiStatus !== UIStatus.Default) {
return [];
}
const epics = getEpicHierarchyInternal(projectId, teamId, uiStatus, rawState)
const {
workItemsState
} = rawState;
const {
workItemInfos
} = workItemsState;
// include only InProgress work items
const inProgressFilter = (feature: IWorkItemDisplayDetails) => workItemInfos[feature.id].stateCategory === StateCategory.InProgress;
// include only features that have explicit iteration
const explicitIterationFilter = (feature: IWorkItemDisplayDetails) => feature.iterationDuration.kind !== IterationDurationKind.BacklogIteration;
let filter = (feature: IWorkItemDisplayDetails) => true;
if (featureFilter === FeatureFilter.InProgress) {
filter = inProgressFilter;
} else if (featureFilter === FeatureFilter.WithoutIteration) {
filter = explicitIterationFilter;
}
// Filter only inprogress features
epics.forEach(epic => epic.children = epic.children.filter(filter));
const compare = (w1: IWorkItemDisplayDetails, w2: IWorkItemDisplayDetails) => {
if (w1.order === w2.order) {
return w1.id - w2.id;
}
return w1.order - w2.order;
}
epics.forEach(epic => epic.children.sort(compare));
// Return only those epics that have one or more children
return epics.filter(e => e.children.length > 0);
}
function getEpicHierarchyInternal(
projectId: string,
teamId: string,
uiStatus: UIStatus,
input: IFeatureTimelineRawState): IWorkItemDisplayDetails[] {
if (uiStatus !== UIStatus.Default) {
return [];
}
const {
workItemsState
} = input;
// Fetch work items at parent level
const epicIds = getWorkItemsForLevel(workItemsState.workItemInfos, WorkItemLevel.Parent, null);
// Add unparent level as parent
epicIds.unshift(0);
return getWorkItemsDetails(projectId, teamId, epicIds, input, /* isRoot */ true);
}
function getWorkItemDetails(
projectId: string,
teamId: string,
id: number,
input: IFeatureTimelineRawState,
isRoot: boolean): IWorkItemDisplayDetails {
const {
workItemsState,
workItemMetadata
} = input;
const workItemInfo = id && workItemsState.workItemInfos[id];
const workItem = workItemInfo && workItemInfo.workItem;
let workItemType = null;
let workItemStateColor: WorkItemStateColor = null;
if (workItem) {
const workItemTypeName = workItem.fields["System.WorkItemType"];
const state = workItem.fields["System.State"].toLowerCase();
const metadata = workItemMetadata[projectId];
workItemType = metadata.workItemTypes.filter((wit) => wit.name.toLowerCase() === workItemTypeName.toLowerCase())[0];
if (metadata.workItemStateColors[workItemTypeName]) {
workItemStateColor = metadata.workItemStateColors[workItemTypeName].filter(sc => sc.name.toLowerCase() === state)[0];
}
}
const children = getWorkItemsDetails(projectId, teamId, getChildrenIds(workItemsState.workItemInfos, id), input, /* isRoot */ false);
// try getting start/end iteration from children
let iterationDuration = getWorkItemIterationDuration(children, projectId, teamId, input, id, workItem);
const orderFieldName = input.backlogConfiguration.backlogConfigurations[projectId][teamId].backlogFields.typeFields["Order"];
const effortFieldName = input.backlogConfiguration.backlogConfigurations[projectId][teamId].backlogFields.typeFields["Effort"];
const color = workItemType && workItemType.color ? "#" + (workItemType.color.length > 6 ? workItemType.color.substr(2) : workItemType.color) : "#c2c8d1";
const workItemDetails: IWorkItemDisplayDetails = {
id,
title: workItem ? workItem.fields["System.Title"] : "Unparented",
color,
order: workItem ? workItem.fields[orderFieldName] || Number.MAX_VALUE : Number.MAX_VALUE,
efforts: workItem ? workItem.fields[effortFieldName] || 0 : 0,
workItem,
iterationDuration,
children,
isRoot,
isComplete: workItemInfo && workItemInfo.stateCategory === StateCategory.Completed,
workItemStateColor,
childrenWithNoEfforts: children.filter(c => c.efforts === 0).length,
predecessors: [],
successors: [],
highlighteSuccessorIcon: false,
highlightPredecessorIcon: false
};
return workItemDetails;
}
function getWorkItemsDetails(
projectId: string,
teamId: string,
ids: number[],
input: IFeatureTimelineRawState,
isEpic: boolean): IWorkItemDisplayDetails[] {
return ids.map(id => getWorkItemDetails(projectId, teamId, id, input, isEpic));
}
function getWorkItemIterationDuration(
children: IWorkItemDisplayDetails[],
projectId: string,
teamId: string,
input: IFeatureTimelineRawState,
id: number,
workItem: WorkItem) {
let iterationDuration = getIterationDurationFromChildren(children);
const allIterations = getTeamIterations(projectId, teamId, UIStatus.Default, input);
const teamSettings = input.teamSetting.teamSetting[projectId][teamId];
// if the start/end iteration is overridden use that value
if (input.savedOverriddenIterations &&
input.savedOverriddenIterations[id]) {
const si = input.savedOverriddenIterations[id].startIterationId;
const ei = input.savedOverriddenIterations[id].endIterationId;
const overridedBy = input.savedOverriddenIterations[id].user;
const startIteration = allIterations.find(i => i.id === si);
const endIteration = allIterations.find(i => i.id === ei);
if (startIteration && endIteration) {
const childrenAreOutofBounds = areChildrenOutOfBounds(startIteration, endIteration, iterationDuration, allIterations);
let kindMessage = "User specified start and end iteration.";
iterationDuration = { startIteration, endIteration, kind: IterationDurationKind.UserOverridden, overridedBy, kindMessage, childrenAreOutofBounds };
}
}
// if null use workItems start/end iteration
if (workItem && (!iterationDuration.startIteration || !iterationDuration.endIteration)) {
const iterationPath = workItem.fields["System.IterationPath"];
const iteration = allIterations.find((i) => i.path === iterationPath);
iterationDuration.startIteration = iteration;
iterationDuration.endIteration = iteration;
iterationDuration.kind = IterationDurationKind.Self;
iterationDuration.kindMessage = "Work Items own iteration.";
}
// If still null take currentIteration
if (!iterationDuration.startIteration || !iterationDuration.endIteration) {
iterationDuration.startIteration = teamSettings.backlogIteration;
iterationDuration.endIteration = teamSettings.backlogIteration;
iterationDuration.kind = IterationDurationKind.BacklogIteration;
iterationDuration.kindMessage = "Using backlog iteration";
}
return iterationDuration;
}
function getIterationDurationFromChildren(
children: IWorkItemDisplayDetails[]): IIterationDuration {
return children.reduce((prev, child) => {
let {
startIteration,
endIteration
} = prev;
// Use child iteration only if it is explicit derived
if (child.iterationDuration.kind !== IterationDurationKind.BacklogIteration) {
if ((!startIteration || !endIteration)) {
startIteration = child.iterationDuration.startIteration;
endIteration = child.iterationDuration.endIteration;
} else {
if (compareIteration(child.iterationDuration.startIteration, startIteration) < 0) {
startIteration = child.iterationDuration.startIteration;
}
if (compareIteration(child.iterationDuration.endIteration, endIteration) > 0) {
endIteration = child.iterationDuration.endIteration;
}
}
}
return {
startIteration,
endIteration,
kind: !startIteration ? IterationDurationKind.BacklogIteration : IterationDurationKind.ChildRollup,
kindMessage: !startIteration ? "Using backlog iteration." : "Start and end iterations are based on iteration of the child work items.",
childrenAreOutofBounds: false,
}
}, { startIteration: null, endIteration: null, kind: IterationDurationKind.BacklogIteration, kindMessage: "Backlog iteration", childrenAreOutofBounds: false });
}
function getChildrenIds(
workItemInfos: IDictionaryNumberTo<IWorkItemInfo>,
parentId: number): number[] {
const workItem = workItemInfos[parentId];
if (workItem) {
return workItemInfos[parentId].children;
}
const childIds = [];
for (const key in workItemInfos) {
const workItem = workItemInfos[key];
if (!workItem) {
console.log(`Invalid workitem id: ${key}`);
}
if (workItem
&& workItem.parent === parentId
&& workItem.level !== WorkItemLevel.Parent) {
childIds.push(workItem.workItem.id);
}
}
return childIds;
} | the_stack |
import {ComponentFixture, TestBed, waitForAsync, fakeAsync, tick} from '@angular/core/testing';
import {
Component,
ViewChild,
ElementRef,
ViewChildren,
QueryList,
EventEmitter,
} from '@angular/core';
import {By} from '@angular/platform-browser';
import {
TAB,
RIGHT_ARROW,
LEFT_ARROW,
DOWN_ARROW,
UP_ARROW,
SPACE,
HOME,
END,
E,
D,
ESCAPE,
S,
H,
} from '@angular/cdk/keycodes';
import {
dispatchKeyboardEvent,
createKeyboardEvent,
dispatchEvent,
dispatchMouseEvent,
} from '../../cdk/testing/private';
import {CdkMenuBar} from './menu-bar';
import {CdkMenuModule} from './menu-module';
import {CdkMenuItemRadio} from './menu-item-radio';
import {CdkMenu} from './menu';
import {CdkMenuItem} from './menu-item';
import {CdkMenuItemCheckbox} from './menu-item-checkbox';
import {CdkMenuItemTrigger} from './menu-item-trigger';
import {CdkMenuGroup} from './menu-group';
describe('MenuBar', () => {
describe('as radio group', () => {
let fixture: ComponentFixture<MenuBarRadioGroup>;
let menuItems: CdkMenuItemRadio[];
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
imports: [CdkMenuModule],
declarations: [MenuBarRadioGroup],
}).compileComponents();
fixture = TestBed.createComponent(MenuBarRadioGroup);
fixture.detectChanges();
menuItems = fixture.debugElement
.queryAll(By.directive(CdkMenuItemRadio))
.map(element => element.injector.get(CdkMenuItemRadio));
}),
);
it('should toggle menuitemradio items', () => {
expect(menuItems[0].checked).toBeTrue();
expect(menuItems[1].checked).toBeFalse();
menuItems[1].trigger();
expect(menuItems[0].checked).toBeFalse();
expect(menuItems[1].checked).toBeTrue();
});
});
describe('radiogroup change events', () => {
let fixture: ComponentFixture<MenuBarRadioGroup>;
let menuItems: CdkMenuItemRadio[];
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
imports: [CdkMenuModule],
declarations: [MenuBarRadioGroup],
}).compileComponents();
fixture = TestBed.createComponent(MenuBarRadioGroup);
fixture.detectChanges();
menuItems = fixture.debugElement
.queryAll(By.directive(CdkMenuItemRadio))
.map(element => element.injector.get(CdkMenuItemRadio));
}),
);
it('should emit on click', () => {
const spy = jasmine.createSpy('cdkMenu change spy');
fixture.debugElement
.query(By.directive(CdkMenuBar))
.injector.get(CdkMenuBar)
.change.subscribe(spy);
menuItems[0].trigger();
expect(spy).toHaveBeenCalledTimes(1);
expect(spy).toHaveBeenCalledWith(menuItems[0]);
});
});
describe('Keyboard handling', () => {
describe('(with ltr layout)', () => {
let fixture: ComponentFixture<MultiMenuWithSubmenu>;
let nativeMenuBar: HTMLElement;
let nativeMenus: HTMLElement[];
let menuBarNativeItems: HTMLButtonElement[];
let fileMenuNativeItems: HTMLButtonElement[];
function grabElementsForTesting() {
nativeMenuBar = fixture.componentInstance.nativeMenuBar.nativeElement;
nativeMenus = fixture.componentInstance.nativeMenus.map(e => e.nativeElement);
menuBarNativeItems = fixture.componentInstance.nativeItems
.map(e => e.nativeElement)
.slice(0, 2); // menu bar has the first 2 menu items
fileMenuNativeItems = fixture.componentInstance.nativeItems
.map(e => e.nativeElement)
.slice(2, 5); // file menu has the next 3 menu items
}
/** Run change detection and extract then set the rendered elements. */
function detectChanges() {
fixture.detectChanges();
grabElementsForTesting();
}
/** Set focus to the MenuBar and run change detection. */
function focusMenuBar() {
dispatchKeyboardEvent(document, 'keydown', TAB);
nativeMenuBar.focus();
detectChanges();
}
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
imports: [CdkMenuModule],
declarations: [MultiMenuWithSubmenu],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(MultiMenuWithSubmenu);
detectChanges();
});
describe('for MenuBar', () => {
it('should focus the first menu item when the menubar gets tabbed in', () => {
focusMenuBar();
expect(document.activeElement).toEqual(menuBarNativeItems[0]);
});
it('should toggle the last/first menu item on end/home key press', () => {
focusMenuBar();
dispatchKeyboardEvent(nativeMenuBar, 'keydown', END);
detectChanges();
expect(document.activeElement).toEqual(menuBarNativeItems[menuBarNativeItems.length - 1]);
focusMenuBar();
dispatchKeyboardEvent(nativeMenuBar, 'keydown', HOME);
detectChanges();
expect(document.activeElement).toEqual(menuBarNativeItems[0]);
});
it('should not focus the last item when pressing end with modifier', () => {
focusMenuBar();
const event = createKeyboardEvent('keydown', END, '', {control: true});
dispatchEvent(nativeMenuBar, event);
detectChanges();
expect(document.activeElement).toEqual(menuBarNativeItems[0]);
});
it('should not focus the first item when pressing home with modifier', () => {
focusMenuBar();
dispatchKeyboardEvent(nativeMenuBar, 'keydown', END);
detectChanges();
let event = createKeyboardEvent('keydown', HOME, '', {control: true});
dispatchEvent(nativeMenuBar, event);
detectChanges();
expect(document.activeElement).toEqual(menuBarNativeItems[menuBarNativeItems.length - 1]);
});
it('should focus the edit MenuItem on E, D character keys', fakeAsync(() => {
focusMenuBar();
dispatchKeyboardEvent(nativeMenuBar, 'keydown', E);
dispatchKeyboardEvent(nativeMenuBar, 'keydown', D);
tick(500);
detectChanges();
expect(document.activeElement).toEqual(menuBarNativeItems[1]);
}));
it(
'should toggle and wrap when cycling the right/left arrow keys on menu bar ' +
'without toggling menus',
() => {
focusMenuBar();
dispatchKeyboardEvent(nativeMenuBar, 'keydown', RIGHT_ARROW);
detectChanges();
expect(document.activeElement).toEqual(menuBarNativeItems[1]);
dispatchKeyboardEvent(nativeMenuBar, 'keydown', RIGHT_ARROW);
detectChanges();
expect(document.activeElement).toEqual(menuBarNativeItems[0]);
dispatchKeyboardEvent(nativeMenuBar, 'keydown', LEFT_ARROW);
detectChanges();
expect(document.activeElement).toEqual(menuBarNativeItems[1]);
dispatchKeyboardEvent(nativeMenuBar, 'keydown', LEFT_ARROW);
detectChanges();
expect(document.activeElement).toEqual(menuBarNativeItems[0]);
expect(nativeMenus.length).toBe(0);
},
);
it('should toggle tabindex of menu bar items with left/right arrow keys', () => {
focusMenuBar();
dispatchKeyboardEvent(nativeMenuBar, 'keydown', RIGHT_ARROW);
detectChanges();
expect(menuBarNativeItems[0].tabIndex).toEqual(-1);
expect(menuBarNativeItems[1].tabIndex).toEqual(0);
dispatchKeyboardEvent(nativeMenuBar, 'keydown', RIGHT_ARROW);
detectChanges();
expect(menuBarNativeItems[0].tabIndex).toEqual(0);
expect(menuBarNativeItems[1].tabIndex).toEqual(-1);
dispatchKeyboardEvent(nativeMenuBar, 'keydown', LEFT_ARROW);
detectChanges();
expect(menuBarNativeItems[0].tabIndex).toEqual(-1);
expect(menuBarNativeItems[1].tabIndex).toEqual(0);
dispatchKeyboardEvent(nativeMenuBar, 'keydown', LEFT_ARROW);
detectChanges();
expect(menuBarNativeItems[0].tabIndex).toEqual(0);
expect(menuBarNativeItems[1].tabIndex).toEqual(-1);
expect(nativeMenus.length).toBe(0);
});
it(
"should open the focused menu item's menu and focus the first submenu" +
' item on the down key',
() => {
focusMenuBar();
dispatchKeyboardEvent(menuBarNativeItems[0], 'keydown', DOWN_ARROW);
detectChanges();
expect(document.activeElement).toEqual(fileMenuNativeItems[0]);
},
);
it(
"should open the focused menu item's menu and focus the last submenu" +
' item on the up key',
() => {
focusMenuBar();
dispatchKeyboardEvent(menuBarNativeItems[0], 'keydown', UP_ARROW);
detectChanges();
expect(document.activeElement).toEqual(
fileMenuNativeItems[fileMenuNativeItems.length - 1],
);
},
);
it('should open the focused menu items menu and focus first submenu item on space', () => {
focusMenuBar();
dispatchKeyboardEvent(menuBarNativeItems[0], 'keydown', SPACE);
detectChanges();
expect(document.activeElement).toEqual(fileMenuNativeItems[0]);
});
it(
'should set the tabindex to 0 on the active item and reset the previous active items ' +
'to -1 when navigating down to a submenu and within it using the arrow keys',
() => {
focusMenuBar();
expect(menuBarNativeItems[0].tabIndex).toEqual(0);
dispatchKeyboardEvent(menuBarNativeItems[0], 'keydown', SPACE);
detectChanges();
expect(menuBarNativeItems[0].tabIndex).toEqual(-1);
expect(fileMenuNativeItems[0].tabIndex).toEqual(0);
dispatchKeyboardEvent(fileMenuNativeItems[0], 'keydown', DOWN_ARROW);
detectChanges();
expect(fileMenuNativeItems[0].tabIndex).toEqual(-1);
expect(fileMenuNativeItems[1].tabIndex).toEqual(0);
},
);
});
describe('for Menu', () => {
function openFileMenu() {
focusMenuBar();
dispatchKeyboardEvent(menuBarNativeItems[0], 'keydown', SPACE);
detectChanges();
}
function openShareMenu() {
dispatchKeyboardEvent(nativeMenus[0], 'keydown', DOWN_ARROW);
dispatchKeyboardEvent(document.activeElement!, 'keydown', RIGHT_ARROW);
detectChanges();
}
it('should open the submenu with focus on item with menu on right arrow press', () => {
openFileMenu();
dispatchKeyboardEvent(nativeMenus[0], 'keydown', DOWN_ARROW);
dispatchKeyboardEvent(document.activeElement!, 'keydown', RIGHT_ARROW);
detectChanges();
expect(nativeMenus.length).withContext('menu bar, menu and submenu').toBe(2);
expect(nativeMenus[0].id).toBe('file_menu');
expect(nativeMenus[1].id).toBe('share_menu');
});
it('should cycle focus on down/up arrow without toggling menus', () => {
openFileMenu();
expect(document.activeElement).toEqual(fileMenuNativeItems[0]);
dispatchKeyboardEvent(nativeMenus[0], 'keydown', DOWN_ARROW);
expect(document.activeElement).toEqual(fileMenuNativeItems[1]);
dispatchKeyboardEvent(nativeMenus[0], 'keydown', DOWN_ARROW);
expect(document.activeElement).toEqual(fileMenuNativeItems[2]);
dispatchKeyboardEvent(nativeMenus[0], 'keydown', UP_ARROW);
expect(document.activeElement).toEqual(fileMenuNativeItems[1]);
dispatchKeyboardEvent(nativeMenus[0], 'keydown', UP_ARROW);
expect(document.activeElement).toEqual(fileMenuNativeItems[0]);
dispatchKeyboardEvent(nativeMenus[0], 'keydown', UP_ARROW);
expect(document.activeElement).toEqual(fileMenuNativeItems[2]);
dispatchKeyboardEvent(nativeMenus[0], 'keydown', DOWN_ARROW);
expect(document.activeElement).toEqual(fileMenuNativeItems[0]);
expect(nativeMenus.length).toBe(1);
});
it('should focus the first/last item on home/end keys', () => {
openFileMenu();
expect(document.activeElement).toEqual(fileMenuNativeItems[0]);
dispatchKeyboardEvent(nativeMenus[0], 'keydown', END);
expect(document.activeElement).toEqual(
fileMenuNativeItems[fileMenuNativeItems.length - 1],
);
dispatchKeyboardEvent(nativeMenus[0], 'keydown', HOME);
expect(document.activeElement).toEqual(fileMenuNativeItems[0]);
});
it('should not focus the last item when pressing end with modifier', () => {
openFileMenu();
const event = createKeyboardEvent('keydown', END, '', {control: true});
dispatchEvent(nativeMenus[0], event);
detectChanges();
expect(document.activeElement).toEqual(fileMenuNativeItems[0]);
});
it('should not focus the first item when pressing home with modifier', () => {
openFileMenu();
dispatchKeyboardEvent(nativeMenus[0], 'keydown', END);
detectChanges();
const event = createKeyboardEvent('keydown', HOME, '', {control: true});
dispatchEvent(nativeMenus[0], event);
detectChanges();
expect(document.activeElement).toEqual(
fileMenuNativeItems[fileMenuNativeItems.length - 1],
);
});
it(
'should call user defined function and close out menus on space key on a non-trigger ' +
'menu item',
() => {
openFileMenu();
openShareMenu();
const spy = jasmine.createSpy('user defined callback spy');
fixture.componentInstance.clickEmitter.subscribe(spy);
dispatchKeyboardEvent(document.activeElement!, 'keydown', SPACE);
detectChanges();
expect(nativeMenus.length).toBe(0);
expect(spy).toHaveBeenCalledTimes(1);
},
);
it('should close the submenu on left arrow and place focus back on its trigger', () => {
openFileMenu();
openShareMenu();
dispatchKeyboardEvent(document.activeElement!, 'keydown', LEFT_ARROW);
detectChanges();
expect(nativeMenus.length).toBe(1);
expect(nativeMenus[0].id).toBe('file_menu');
expect(document.activeElement).toEqual(fileMenuNativeItems[1]);
});
it(
'should close menu tree, focus next menu bar item and open its menu on right arrow ' +
"when currently focused item doesn't trigger a menu",
() => {
openFileMenu();
openShareMenu();
dispatchKeyboardEvent(document.activeElement!, 'keydown', RIGHT_ARROW);
detectChanges();
expect(nativeMenus.length).toBe(1);
expect(nativeMenus[0].id).toBe('edit_menu');
expect(document.activeElement).toEqual(menuBarNativeItems[1]);
},
);
it('should close first level menu and focus previous menubar item on left arrow', () => {
openFileMenu();
dispatchKeyboardEvent(document.activeElement!, 'keydown', LEFT_ARROW);
detectChanges();
expect(nativeMenus.length).toBe(1);
expect(nativeMenus[0].id).toBe('edit_menu');
expect(document.activeElement).toEqual(menuBarNativeItems[1]);
});
it('should close the open submenu and focus its trigger on escape press', () => {
openFileMenu();
openShareMenu();
dispatchKeyboardEvent(document.activeElement!, 'keydown', ESCAPE);
detectChanges();
expect(nativeMenus.length).toBe(1);
expect(nativeMenus[0].id).toBe('file_menu');
expect(document.activeElement)
.withContext('re-focus trigger')
.toEqual(fileMenuNativeItems[1]);
});
it('should not close submenu and focus parent on escape with modifier', () => {
openFileMenu();
openShareMenu();
const event = createKeyboardEvent('keydown', ESCAPE, '', {control: true});
dispatchEvent(nativeMenus[1], event);
detectChanges();
expect(nativeMenus.length).withContext('menu bar, file menu, share menu').toBe(2);
expect(nativeMenus[0].id).toBe('file_menu');
expect(nativeMenus[1].id).toBe('share_menu');
});
it('should close out all menus on tab', () => {
openFileMenu();
openShareMenu();
dispatchKeyboardEvent(document.activeElement!, 'keydown', TAB);
detectChanges();
expect(nativeMenus.length).toBe(0);
});
it('should focus share MenuItem on S, H character key press', fakeAsync(() => {
openFileMenu();
dispatchKeyboardEvent(nativeMenus[0], 'keydown', S);
dispatchKeyboardEvent(nativeMenus[0], 'keydown', H);
tick(500);
detectChanges();
expect(document.activeElement).toEqual(fileMenuNativeItems[1]);
}));
it('should handle keyboard actions if initial menu is opened programmatically', () => {
fixture.debugElement
.queryAll(By.directive(CdkMenuItem))[0]
.injector.get(CdkMenuItem)
.getMenuTrigger()!
.openMenu();
detectChanges();
fixture.debugElement
.queryAll(By.directive(CdkMenuItem))[2]
.injector.get(CdkMenuItem)
.getMenuTrigger()!
.openMenu();
detectChanges();
fileMenuNativeItems[0].focus();
dispatchKeyboardEvent(fileMenuNativeItems[0], 'keydown', TAB);
detectChanges();
expect(nativeMenus.length).toBe(0);
});
});
});
describe('(with rtl layout)', () => {
let fixture: ComponentFixture<MultiMenuWithSubmenu>;
let nativeMenuBar: HTMLElement;
let nativeMenus: HTMLElement[];
let menuBarNativeItems: HTMLButtonElement[];
let fileMenuNativeItems: HTMLButtonElement[];
function grabElementsForTesting() {
nativeMenuBar = fixture.componentInstance.nativeMenuBar.nativeElement;
nativeMenus = fixture.componentInstance.nativeMenus.map(e => e.nativeElement);
menuBarNativeItems = fixture.componentInstance.nativeItems
.map(e => e.nativeElement)
.slice(0, 2); // menu bar has the first 2 menu items
fileMenuNativeItems = fixture.componentInstance.nativeItems
.map(e => e.nativeElement)
.slice(2, 5); // file menu has the next 3 menu items
}
/** Run change detection and extract then set the rendered elements. */
function detectChanges() {
fixture.detectChanges();
grabElementsForTesting();
}
/** Place focus on the MenuBar and run change detection. */
function focusMenuBar() {
dispatchKeyboardEvent(document, 'keydown', TAB);
nativeMenuBar.focus();
detectChanges();
}
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
imports: [CdkMenuModule],
declarations: [MultiMenuWithSubmenu],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(MultiMenuWithSubmenu);
detectChanges();
});
beforeAll(() => {
document.dir = 'rtl';
});
afterAll(() => {
document.dir = 'ltr';
});
describe('for Menu', () => {
function openFileMenu() {
focusMenuBar();
dispatchKeyboardEvent(menuBarNativeItems[0], 'keydown', SPACE);
detectChanges();
}
function openShareMenu() {
dispatchKeyboardEvent(nativeMenus[0], 'keydown', DOWN_ARROW);
dispatchKeyboardEvent(document.activeElement!, 'keydown', LEFT_ARROW);
detectChanges();
}
it('should open the submenu for menu item with menu on left arrow', () => {
openFileMenu();
dispatchKeyboardEvent(nativeMenus[0], 'keydown', DOWN_ARROW);
dispatchKeyboardEvent(document.activeElement!, 'keydown', LEFT_ARROW);
detectChanges();
expect(nativeMenus.length).withContext('menu and submenu').toBe(2);
expect(nativeMenus[0].id).toBe('file_menu');
expect(nativeMenus[1].id).toBe('share_menu');
});
it('should close the submenu and focus its trigger on right arrow', () => {
openFileMenu();
openShareMenu();
dispatchKeyboardEvent(document.activeElement!, 'keydown', RIGHT_ARROW);
detectChanges();
expect(nativeMenus.length).toBe(1);
expect(nativeMenus[0].id).toBe('file_menu');
expect(document.activeElement).toEqual(fileMenuNativeItems[1]);
});
it(
'should close menu tree, focus next menu bar item and open its menu on left arrow when ' +
"focused item doesn't have a menu",
() => {
openFileMenu();
openShareMenu();
dispatchKeyboardEvent(document.activeElement!, 'keydown', LEFT_ARROW);
detectChanges();
expect(nativeMenus.length).toBe(1);
expect(nativeMenus[0].id).toBe('edit_menu');
expect(document.activeElement).toEqual(menuBarNativeItems[1]);
},
);
it(
'should close first level menu and focus the previous menubar item on right' +
' arrow press',
() => {
openFileMenu();
dispatchKeyboardEvent(document.activeElement!, 'keydown', RIGHT_ARROW);
detectChanges();
expect(nativeMenus.length).toBe(1);
expect(nativeMenus[0].id).toBe('edit_menu');
expect(document.activeElement).toEqual(menuBarNativeItems[1]);
},
);
});
});
describe('with menuitemcheckbox components', () => {
let fixture: ComponentFixture<MenuWithCheckboxes>;
let nativeMenuBar: HTMLElement;
let nativeMenus: HTMLElement[];
let menuBarNativeItems: HTMLButtonElement[];
let fontMenuItems: CdkMenuItemCheckbox[];
function grabElementsForTesting() {
nativeMenuBar = fixture.componentInstance.nativeMenuBar.nativeElement;
nativeMenus = fixture.componentInstance.nativeMenus.map(e => e.nativeElement);
menuBarNativeItems = fixture.componentInstance.nativeItems
.map(e => e.nativeElement)
.slice(0, 2); // menu bar has the first 2 menu items
fontMenuItems = fixture.componentInstance.checkboxItems.toArray();
}
/** Run change detection and extract then set the rendered elements. */
function detectChanges() {
fixture.detectChanges();
grabElementsForTesting();
}
/** Place focus on the menu bar and run change detection. */
function focusMenuBar() {
dispatchKeyboardEvent(document, 'keydown', TAB);
nativeMenuBar.focus();
detectChanges();
}
function openFontMenu() {
focusMenuBar();
dispatchKeyboardEvent(menuBarNativeItems[0], 'keydown', SPACE);
detectChanges();
}
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
imports: [CdkMenuModule],
declarations: [MenuWithCheckboxes],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(MenuWithCheckboxes);
detectChanges();
});
it(
'should set the checked state on the focused checkbox on space key and keep the' +
' menu open',
() => {
openFontMenu();
dispatchKeyboardEvent(document.activeElement!, 'keydown', SPACE);
detectChanges();
expect(fontMenuItems[0].checked).toBeTrue();
expect(nativeMenus.length).toBe(1);
expect(nativeMenus[0].id).toBe('font_menu');
},
);
});
describe('with menuitemradio components', () => {
let fixture: ComponentFixture<MenuWithRadioButtons>;
let nativeMenuBar: HTMLElement;
let nativeMenus: HTMLElement[];
let menuBarNativeItems: HTMLButtonElement[];
let fontMenuItems: CdkMenuItemRadio[];
function grabElementsForTesting() {
nativeMenuBar = fixture.componentInstance.nativeMenuBar.nativeElement;
nativeMenus = fixture.componentInstance.nativeMenus.map(e => e.nativeElement);
menuBarNativeItems = fixture.componentInstance.nativeItems
.map(e => e.nativeElement)
.slice(0, 1); // menu bar only has a single item
fontMenuItems = fixture.componentInstance.radioItems.toArray();
}
/** run change detection and, extract and set the rendered elements. */
function detectChanges() {
fixture.detectChanges();
grabElementsForTesting();
}
/** set focus the MenuBar and run change detection. */
function focusMenuBar() {
dispatchKeyboardEvent(document, 'keydown', TAB);
nativeMenuBar.focus();
detectChanges();
}
function openFontMenu() {
focusMenuBar();
dispatchKeyboardEvent(menuBarNativeItems[0], 'keydown', SPACE);
detectChanges();
}
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
imports: [CdkMenuModule],
declarations: [MenuWithRadioButtons],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(MenuWithRadioButtons);
detectChanges();
});
it(
'should set the checked state on the active radio button on space key and keep the' +
' menu open',
() => {
openFontMenu();
dispatchKeyboardEvent(nativeMenus[0], 'keydown', DOWN_ARROW);
dispatchKeyboardEvent(document.activeElement!, 'keydown', SPACE);
detectChanges();
expect(fontMenuItems[1].checked).toBeTrue();
expect(nativeMenus.length).toBe(1);
expect(nativeMenus[0].id).toBe('text_menu');
},
);
});
});
describe('background click closeout', () => {
let fixture: ComponentFixture<MenuBarWithMenusAndInlineMenu>;
let popoutMenus: CdkMenu[];
let triggers: CdkMenuItemTrigger[];
let nativeInlineMenuItem: HTMLElement;
/** open the attached menu. */
function openMenu() {
triggers[0].toggle();
detectChanges();
}
/** set the menus and triggers arrays. */
function grabElementsForTesting() {
popoutMenus = fixture.componentInstance.menus.toArray().filter(el => !el._isInline());
triggers = fixture.componentInstance.triggers.toArray();
nativeInlineMenuItem = fixture.componentInstance.nativeInlineMenuItem.nativeElement;
}
/** run change detection and, extract and set the rendered elements. */
function detectChanges() {
fixture.detectChanges();
grabElementsForTesting();
}
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
imports: [CdkMenuModule],
declarations: [MenuBarWithMenusAndInlineMenu],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(MenuBarWithMenusAndInlineMenu);
detectChanges();
});
it('should close out all open menus when clicked outside the menu tree', () => {
openMenu();
expect(popoutMenus.length).toBe(1);
fixture.debugElement.query(By.css('#container')).nativeElement.click();
detectChanges();
expect(popoutMenus.length).toBe(0);
});
it('should not close open menus when clicking on a menu group', () => {
openMenu();
expect(popoutMenus.length).toBe(1);
const menuGroups = fixture.debugElement.queryAll(By.directive(CdkMenuGroup));
menuGroups[2].nativeElement.click();
detectChanges();
expect(popoutMenus.length).toBe(1);
});
it('should not close open menus when clicking on a menu', () => {
openMenu();
expect(popoutMenus.length).toBe(1);
fixture.debugElement.query(By.directive(CdkMenu)).nativeElement.click();
detectChanges();
expect(popoutMenus.length).toBe(1);
});
it('should not close when clicking on a CdkMenuItemCheckbox element', () => {
openMenu();
expect(popoutMenus.length).toBe(1);
fixture.debugElement.query(By.directive(CdkMenuItemCheckbox)).nativeElement.click();
fixture.detectChanges();
expect(popoutMenus.length).toBe(1);
});
it('should not close when clicking on a non-menu element inside menu', () => {
openMenu();
expect(popoutMenus.length).toBe(1);
fixture.debugElement.query(By.css('#inner-element')).nativeElement.click();
detectChanges();
expect(popoutMenus.length)
.withContext('menu should stay open if clicking on an inner span element')
.toBe(1);
});
it('should close the open menu when clicking on an inline menu item', () => {
openMenu();
nativeInlineMenuItem.click();
detectChanges();
expect(popoutMenus.length).toBe(0);
});
});
describe('Mouse handling', () => {
let fixture: ComponentFixture<MultiMenuWithSubmenu>;
let nativeMenus: HTMLElement[];
let menuBarNativeItems: HTMLButtonElement[];
let fileMenuNativeItems: HTMLButtonElement[];
let shareMenuNativeItems: HTMLButtonElement[];
/** Get menus and items used for tests. */
function grabElementsForTesting() {
nativeMenus = fixture.componentInstance.nativeMenus.map(e => e.nativeElement);
menuBarNativeItems = fixture.componentInstance.nativeItems
.map(e => e.nativeElement)
.slice(0, 2); // menu bar has the first 2 menu items
fileMenuNativeItems = fixture.componentInstance.nativeItems
.map(e => e.nativeElement)
.slice(2, 5); // file menu has the next 3 menu items
shareMenuNativeItems = fixture.componentInstance.nativeItems
.map(e => e.nativeElement)
.slice(5, 7); // share menu has the next 2 menu items
}
/** Run change detection and extract then set the rendered elements. */
function detectChanges() {
fixture.detectChanges();
grabElementsForTesting();
}
/** Mock mouse events required to open the file menu. */
function openFileMenu() {
dispatchMouseEvent(menuBarNativeItems[0], 'mouseenter');
dispatchMouseEvent(menuBarNativeItems[0], 'click');
dispatchMouseEvent(menuBarNativeItems[0], 'mouseenter');
detectChanges();
}
/** Mock mouse events required to open the share menu. */
function openShareMenu() {
dispatchMouseEvent(fileMenuNativeItems[1], 'mouseenter');
detectChanges();
}
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
imports: [CdkMenuModule],
declarations: [MultiMenuWithSubmenu],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(MultiMenuWithSubmenu);
detectChanges();
});
it('should toggle menu from menu bar when clicked', () => {
openFileMenu();
expect(nativeMenus.length).toBe(1);
expect(nativeMenus[0].id).toBe('file_menu');
dispatchMouseEvent(menuBarNativeItems[0], 'click');
detectChanges();
expect(nativeMenus.length).toBe(0);
});
it('should not open menu when hovering over trigger in menu bar with no open siblings', () => {
dispatchMouseEvent(menuBarNativeItems[0], 'mouseenter');
detectChanges();
expect(nativeMenus.length).toBe(0);
});
it(
'should not change focused items when hovering over trigger in menu bar with no open ' +
'siblings',
() => {
dispatchMouseEvent(menuBarNativeItems[0], 'mouseenter');
detectChanges();
expect(document.querySelector(':focus')).not.toEqual(menuBarNativeItems[0]);
expect(document.querySelector(':focus')).not.toEqual(menuBarNativeItems[1]);
},
);
it(
'should toggle open menus in menu bar if sibling is open when mouse moves from one item ' +
'to the other',
() => {
openFileMenu();
dispatchMouseEvent(menuBarNativeItems[1], 'mouseenter');
detectChanges();
expect(nativeMenus.length).toBe(1);
expect(nativeMenus[0].id).toBe('edit_menu');
dispatchMouseEvent(menuBarNativeItems[0], 'mouseenter');
detectChanges();
expect(nativeMenus.length).toBe(1);
expect(nativeMenus[0].id).toBe('file_menu');
dispatchMouseEvent(menuBarNativeItems[1], 'mouseenter');
detectChanges();
expect(nativeMenus.length).toBe(1);
expect(nativeMenus[0].id).toBe('edit_menu');
},
);
it('should not close the menu when re-hovering the trigger', () => {
openFileMenu();
dispatchMouseEvent(menuBarNativeItems[0], 'mouseenter');
expect(nativeMenus.length).toBe(1);
expect(nativeMenus[0].id).toBe('file_menu');
});
it('should open a submenu when hovering over a trigger in a menu with no siblings open', () => {
openFileMenu();
openShareMenu();
expect(nativeMenus.length).toBe(2);
expect(nativeMenus[0].id).toBe('file_menu');
expect(nativeMenus[1].id).toBe('share_menu');
});
it('should close menu when hovering over non-triggering sibling menu item', () => {
openFileMenu();
openShareMenu();
dispatchMouseEvent(fileMenuNativeItems[0], 'mouseenter');
detectChanges();
expect(nativeMenus.length).toBe(1);
expect(nativeMenus[0].id).toBe('file_menu');
});
it('should retain open menus when hovering over root level trigger which opened them', () => {
openFileMenu();
openShareMenu();
dispatchMouseEvent(menuBarNativeItems[0], 'mouseenter');
detectChanges();
expect(nativeMenus.length).toBe(2);
});
it('should close out the menu tree when hovering over sibling item in menu bar', () => {
openFileMenu();
openShareMenu();
dispatchMouseEvent(menuBarNativeItems[1], 'mouseenter');
detectChanges();
expect(nativeMenus.length).toBe(1);
expect(nativeMenus[0].id).toBe('edit_menu');
});
it('should close out the menu tree when clicking a non-triggering menu item', () => {
openFileMenu();
openShareMenu();
dispatchMouseEvent(shareMenuNativeItems[0], 'mouseenter');
dispatchMouseEvent(shareMenuNativeItems[0], 'click');
detectChanges();
expect(nativeMenus.length).toBe(0);
});
it(
'should allow keyboard down arrow to focus next item after mouse sets focus to' +
' initial item',
() => {
openFileMenu();
dispatchMouseEvent(fileMenuNativeItems[0], 'mouseenter');
detectChanges();
dispatchKeyboardEvent(nativeMenus[0], 'keydown', DOWN_ARROW);
expect(document.querySelector(':focus')).toEqual(fileMenuNativeItems[1]);
},
);
it(
'should not re-open a menu when hovering over the trigger in the menubar after clicking to ' +
'open and then close it',
() => {
openFileMenu();
dispatchMouseEvent(menuBarNativeItems[0], 'click');
detectChanges();
dispatchMouseEvent(menuBarNativeItems[0], 'mouseenter');
detectChanges();
expect(nativeMenus.length).toBe(0);
},
);
it(
'should not set the tabindex when hovering over menubar item and there is no open' +
' sibling menu',
() => {
dispatchMouseEvent(menuBarNativeItems[0], 'mouseenter');
detectChanges();
expect(menuBarNativeItems[0].tabIndex).toBe(-1);
},
);
it(
'should set the tabindex of the opened trigger to 0 and toggle tabindex' +
' when hovering between items',
() => {
openFileMenu();
expect(menuBarNativeItems[0].tabIndex).toBe(0);
dispatchMouseEvent(menuBarNativeItems[1], 'mouseenter');
detectChanges();
expect(menuBarNativeItems[0].tabIndex).toBe(-1);
expect(menuBarNativeItems[1].tabIndex).toBe(0);
dispatchMouseEvent(menuBarNativeItems[0], 'mouseenter');
detectChanges();
expect(menuBarNativeItems[0].tabIndex).toBe(0);
expect(menuBarNativeItems[1].tabIndex).toBe(-1);
},
);
it(
'should set the tabindex to 0 on the active item and reset the previous active items ' +
'to -1 when navigating down to a submenu and within it using a mouse',
() => {
openFileMenu();
expect(menuBarNativeItems[0].tabIndex).toBe(0);
dispatchMouseEvent(fileMenuNativeItems[0], 'mouseenter');
dispatchMouseEvent(menuBarNativeItems[0], 'mouseout');
detectChanges();
expect(menuBarNativeItems[0].tabIndex).toBe(-1);
expect(fileMenuNativeItems[0].tabIndex).toBe(0);
dispatchMouseEvent(fileMenuNativeItems[1], 'mouseenter');
detectChanges();
expect(fileMenuNativeItems[0].tabIndex).toBe(-1);
expect(fileMenuNativeItems[1].tabIndex).toBe(0);
},
);
});
});
@Component({
template: `
<ul cdkMenuBar>
<li role="none">
<button checked="true" cdkMenuItemRadio>
first
</button>
</li>
<li role="none">
<button cdkMenuItemRadio>
second
</button>
</li>
</ul>
`,
})
class MenuBarRadioGroup {}
@Component({
template: `
<div>
<div cdkMenuBar id="menu_bar">
<button cdkMenuItem [cdkMenuTriggerFor]="file">File</button>
<button cdkMenuItem [cdkMenuTriggerFor]="edit">Edit</button>
</div>
<ng-template cdkMenuPanel #file="cdkMenuPanel">
<div cdkMenu id="file_menu" [cdkMenuPanel]="file">
<button cdkMenuItem>Save</button>
<button cdkMenuItem [cdkMenuTriggerFor]="share">Share</button>
<button cdkMenuItem>Open</button>
</div>
</ng-template>
<ng-template cdkMenuPanel #share="cdkMenuPanel">
<div cdkMenu id="share_menu" [cdkMenuPanel]="share">
<button (cdkMenuItemTriggered)="clickEmitter.next()" cdkMenuItem>Email</button>
<button cdkMenuItem>Chat</button>
</div>
</ng-template>
<ng-template cdkMenuPanel #edit="cdkMenuPanel">
<div cdkMenu id="edit_menu" [cdkMenuPanel]="edit">
<button cdkMenuItem>Undo</button>
<button cdkMenuItem>Redo</button>
</div>
</ng-template>
</div>
`,
})
class MultiMenuWithSubmenu {
clickEmitter = new EventEmitter<void>();
@ViewChild(CdkMenuBar, {read: ElementRef}) nativeMenuBar: ElementRef;
@ViewChildren(CdkMenu, {read: ElementRef}) nativeMenus: QueryList<ElementRef>;
@ViewChildren(CdkMenuItem, {read: ElementRef}) nativeItems: QueryList<ElementRef>;
}
@Component({
template: `
<div>
<div cdkMenuBar id="menu_bar">
<button cdkMenuItem [cdkMenuTriggerFor]="font">Font size</button>
</div>
<ng-template cdkMenuPanel #font="cdkMenuPanel">
<div cdkMenu id="font_menu" [cdkMenuPanel]="font">
<button cdkMenuItemCheckbox>Small</button>
<button cdkMenuItemCheckbox>Large</button>
</div>
</ng-template>
</div>
`,
})
class MenuWithCheckboxes {
@ViewChild(CdkMenuBar, {read: ElementRef}) nativeMenuBar: ElementRef;
@ViewChildren(CdkMenu, {read: ElementRef}) nativeMenus: QueryList<ElementRef>;
@ViewChildren(CdkMenuItem, {read: ElementRef}) nativeItems: QueryList<ElementRef>;
@ViewChildren(CdkMenuItemCheckbox) checkboxItems: QueryList<CdkMenuItemCheckbox>;
}
@Component({
template: `
<div>
<div cdkMenuBar id="menu_bar">
<button cdkMenuItem [cdkMenuTriggerFor]="text">Text</button>
</div>
<ng-template cdkMenuPanel #text="cdkMenuPanel">
<div cdkMenu id="text_menu" [cdkMenuPanel]="text">
<button cdkMenuItemRadio>Bold</button>
<button cdkMenuItemRadio>Italic</button>
</div>
</ng-template>
</div>
`,
})
class MenuWithRadioButtons {
@ViewChild(CdkMenuBar, {read: ElementRef}) nativeMenuBar: ElementRef;
@ViewChildren(CdkMenu, {read: ElementRef}) nativeMenus: QueryList<ElementRef>;
@ViewChildren(CdkMenuItem, {read: ElementRef}) nativeItems: QueryList<ElementRef>;
@ViewChildren(CdkMenuItemRadio) radioItems: QueryList<CdkMenuItemRadio>;
}
@Component({
template: `
<div id="container">
<div cdkMenuBar>
<button cdkMenuItem [cdkMenuTriggerFor]="sub1">Trigger</button>
</div>
<ng-template cdkMenuPanel #sub1="cdkMenuPanel">
<div cdkMenu [cdkMenuPanel]="sub1">
<div cdkMenuGroup>
<button cdkMenuItemCheckbox>Trigger</button>
<span id="inner-element">A nested non-menuitem element</span>
</div>
</div>
</ng-template>
</div>
<div cdkMenu>
<button #inline_menu_item cdkMenuItem></button>
</div>
`,
})
class MenuBarWithMenusAndInlineMenu {
@ViewChildren(CdkMenu) menus: QueryList<CdkMenu>;
@ViewChildren(CdkMenuItemTrigger) triggers: QueryList<CdkMenuItemTrigger>;
@ViewChild('inline_menu_item') nativeInlineMenuItem: ElementRef;
} | the_stack |
import * as DomUtil from '../common/dom_util';
import {SemanticAttr, SemanticFont, SemanticRole, SemanticType} from './semantic_attr';
import {SemanticHeuristics} from './semantic_heuristics';
import {SemanticNode} from './semantic_node';
import {SemanticNodeFactory} from './semantic_node_factory';
import * as SemanticPred from './semantic_pred';
import * as SemanticUtil from './semantic_util';
interface BoundsType {
type: SemanticType;
length: number;
accent?: boolean;
}
export default class SemanticProcessor {
private static readonly FENCE_TO_PUNCT_: {[key: string]: SemanticRole} = {
[SemanticRole.METRIC]: SemanticRole.METRIC,
[SemanticRole.NEUTRAL]: SemanticRole.VBAR,
[SemanticRole.OPEN]: SemanticRole.OPENFENCE,
[SemanticRole.CLOSE]: SemanticRole.CLOSEFENCE,
};
private static readonly MML_TO_LIMIT_: {[key: string]: BoundsType} = {
'MSUB': {type: SemanticType.LIMLOWER, length: 1},
'MUNDER': {type: SemanticType.LIMLOWER, length: 1},
'MSUP': {type: SemanticType.LIMUPPER, length: 1},
'MOVER': {type: SemanticType.LIMUPPER, length: 1},
'MSUBSUP': {type: SemanticType.LIMBOTH, length: 2},
'MUNDEROVER': {type: SemanticType.LIMBOTH, length: 2}
};
/**
* {Object.<{type: SemanticType,
* length: number, accent: boolean}>}
*
*/
private static readonly MML_TO_BOUNDS_: {[key: string]: BoundsType} = {
'MSUB': {type: SemanticType.SUBSCRIPT, length: 1, accent: false},
'MSUP': {type: SemanticType.SUPERSCRIPT, length: 1, accent: false},
'MSUBSUP': {type: SemanticType.SUBSCRIPT, length: 2, accent: false},
'MUNDER': {type: SemanticType.UNDERSCORE, length: 1, accent: true},
'MOVER': {type: SemanticType.OVERSCORE, length: 1, accent: true},
'MUNDEROVER': {type: SemanticType.UNDERSCORE, length: 2, accent: true}
};
private static readonly CLASSIFY_FUNCTION_: {[key: string]: string} = {
[SemanticRole.INTEGRAL]: 'integral',
[SemanticRole.SUM]: 'bigop',
[SemanticRole.PREFIXFUNC]: 'prefix',
[SemanticRole.LIMFUNC]: 'prefix',
[SemanticRole.SIMPLEFUNC]: 'prefix',
[SemanticRole.COMPFUNC]: 'prefix'
};
/**
* Maps mathjax font variants to semantic font names.
*/
private static readonly MATHJAX_FONTS: {[key: string]: SemanticFont} = {
'-tex-caligraphic': SemanticFont.CALIGRAPHIC,
'-tex-caligraphic-bold': SemanticFont.CALIGRAPHICBOLD,
'-tex-calligraphic': SemanticFont.CALIGRAPHIC,
'-tex-calligraphic-bold': SemanticFont.CALIGRAPHICBOLD,
'-tex-oldstyle': SemanticFont.OLDSTYLE,
'-tex-oldstyle-bold': SemanticFont.OLDSTYLEBOLD,
'-tex-mathit': SemanticFont.ITALIC
};
// TODO (TS): Keeping this as a singleton for the time being.
private static instance: SemanticProcessor;
/**
* Table for caching explicit function applications.
*/
public funcAppls: {[key: string]: SemanticNode} = {};
private factory_: SemanticNodeFactory;
/**
* @return The SemanticProcessor object.
*/
public static getInstance(): SemanticProcessor {
SemanticProcessor.instance = SemanticProcessor.instance ||
new SemanticProcessor();
return SemanticProcessor.instance;
}
/**
* Rewrites a table to multiline structure, simplifying it by getting rid of
* the cell hierarchy level.
* @param table The node to be rewritten a multiline.
*/
public static tableToMultiline(table: SemanticNode) {
if (!SemanticPred.tableIsMultiline(table)) {
SemanticProcessor.classifyTable(table);
return;
}
table.type = SemanticType.MULTILINE;
for (let i = 0, row; row = table.childNodes[i]; i++) {
SemanticProcessor.rowToLine_(row, SemanticRole.MULTILINE);
}
if (table.childNodes.length === 1 &&
SemanticPred.isFencedElement(table.childNodes[0].childNodes[0])) {
SemanticProcessor.tableToMatrixOrVector_(
SemanticProcessor.rewriteFencedLine_(table));
}
SemanticProcessor.binomialForm_(table);
SemanticProcessor.classifyMultiline(table);
}
/**
* Processes a number node and adapts its role and font if necessary.
* @param node The semantic tree node.
*/
public static number(node: SemanticNode) {
if (node.type === SemanticType.UNKNOWN ||
// In case of latin numbers etc.
node.type === SemanticType.IDENTIFIER) {
node.type = SemanticType.NUMBER;
}
SemanticProcessor.numberRole_(node);
SemanticProcessor.exprFont_(node);
}
/**
* Semantically classifies a multiline table in terms of equation system it
* might be.
* @param multiline A multiline expression.
*/
public static classifyMultiline(multiline: SemanticNode) {
let index = 0;
let length = multiline.childNodes.length;
let line;
while (index < length &&
(!(line = multiline.childNodes[index]) || !line.childNodes.length)) {
index++;
}
if (index >= length) {
return;
}
let firstRole = line.childNodes[0].role;
if (firstRole !== SemanticRole.UNKNOWN &&
multiline.childNodes.every(function(x) {
let cell = x.childNodes[0];
return !cell ||
cell.role === firstRole &&
(SemanticPred.isType(cell, SemanticType.RELATION) ||
SemanticPred.isType(cell, SemanticType.RELSEQ));
})) {
multiline.role = firstRole;
}
}
/**
* Semantically classifies a table in terms of equation system it might be.
* @param table The table node.
*/
public static classifyTable(table: SemanticNode) {
let columns = SemanticProcessor.computeColumns_(table);
SemanticProcessor.classifyByColumns_(
table, columns, SemanticRole.EQUALITY) ||
SemanticProcessor.classifyByColumns_(
table, columns, SemanticRole.INEQUALITY, [SemanticRole.EQUALITY]) ||
SemanticProcessor.classifyByColumns_(
table, columns, SemanticRole.ARROW) ||
SemanticProcessor.detectCaleyTable(table);
}
/**
* Classifies a Cayley table.
* @param table The table.
* @return True if it is a Cayley table.
*/
private static detectCaleyTable(table: SemanticNode) {
if (!table.mathmlTree) {
return false;
}
const tree = table.mathmlTree;
const cl = tree.getAttribute('columnlines');
const rl = tree.getAttribute('rowlines');
if (!cl || !rl) {
return false;
}
if (SemanticProcessor.cayleySpacing(cl) &&
SemanticProcessor.cayleySpacing(rl)) {
table.role = SemanticRole.CAYLEY;
return true;
}
return false;
}
/**
* Checks for the table if it has bars between first and second column and
* first and second row, only.
*
* @param lines The lines attribute string.
* @return True if the lines attribute indicate a Cayley table.
*/
private static cayleySpacing(lines: string): boolean {
const list = lines.split(' ');
return (list[0] === 'solid' || list[0] === 'dashed') &&
list.slice(1).every(x => x === 'none');
}
// Inference rules (Simons)
// This is top down parsing, so we have to keep the bottom-up processor
// available.
/**
* Parses a proof node.
* @param node The node.
* @param semantics Its semantics attribute value.
* @param parse The
* current semantic parser for list of nodes.
* @return The semantic node.
*/
public static proof(
node: Element, semantics: string,
parse: (p1: Element[]) => SemanticNode[]): SemanticNode {
let attrs = SemanticProcessor.separateSemantics(semantics);
return SemanticProcessor.getInstance().proof(node, attrs, parse);
}
// Utilities
// This one should be prefix specific!
/**
*
* @param node The mml node.
* @param attr The attribute name.
* @param opt_value The attribute value.
* @return True if the semantic attribute is in the node.
*/
public static findSemantics(node: Element, attr: string, opt_value?: string):
boolean {
let value = opt_value == null ? null : opt_value;
let semantics = SemanticProcessor.getSemantics(node);
if (!semantics) {
return false;
}
if (!semantics[attr]) {
return false;
}
return value == null ? true : semantics[attr] === value;
}
/**
* Retrieves the content of a semantic attribute in a node as an association
* list.
* @param node The mml node.
* @return The association list.
*/
public static getSemantics(node: Element): {[key: string]: string} {
let semantics = node.getAttribute('semantics');
if (!semantics) {
return null;
}
return SemanticProcessor.separateSemantics(semantics);
}
/**
* Removes prefix from a semantic attribute.
* @param name The semantic attribute.
* @return Name with prefix removed.
*/
public static removePrefix(name: string): string {
let [ , ...rest] = name.split('_');
return rest.join('_');
}
/**
* Separates a semantic attribute into it's components.
* @param attr Content of the semantic attribute.
* @return Association list of semantic attributes.
*/
public static separateSemantics(attr: string): {[key: string]: string} {
let result: {[key: string]: string} = {};
attr.split(';').forEach(function(x) {
let [name, value] = x.split(':');
result[SemanticProcessor.removePrefix(name)] = value;
});
return result;
}
/**
* Matches juxtaposition with existing spaces by adding the potentially nested
* space elements as mathmlTree elements. This has the effect that newly
* introduced invisible times operators will enrich the spaces rather than add
* new empty elements.
* @param nodes The operands.
* @param ops A list of invisible times operators.
*/
private static matchSpaces_(nodes: SemanticNode[], ops: SemanticNode[]) {
for (let i = 0, op; op = ops[i]; i++) {
let node = nodes[i];
let mt1 = node.mathmlTree;
let mt2 = nodes[i + 1].mathmlTree;
if (!mt1 || !mt2) {
continue;
}
let sibling = (mt1.nextSibling as Element);
if (!sibling || sibling === mt2) {
continue;
}
let spacer = SemanticProcessor.getSpacer_(sibling);
if (spacer) {
op.mathml.push(spacer);
op.mathmlTree = spacer;
op.role = SemanticRole.SPACE;
}
}
}
// TODO (TS): Make this optional conditions.
/**
* Recursively retrieves an embedded space element.
* @param node The mml element.
* @return The space element if it exists.
*/
private static getSpacer_(node: Element): Element {
if (DomUtil.tagName(node) === 'MSPACE') {
return node;
}
while (SemanticUtil.hasEmptyTag(node) && node.childNodes.length === 1) {
node = (node.childNodes[0] as Element);
if (DomUtil.tagName(node) === 'MSPACE') {
return node;
}
}
return null;
}
/**
* Rewrite fences into punctuation. This is done with any "leftover" fence.
* @param fence Fence.
*/
private static fenceToPunct_(fence: SemanticNode) {
let newRole = SemanticProcessor.FENCE_TO_PUNCT_[fence.role];
if (!newRole) {
return;
}
while (fence.embellished) {
fence.embellished = SemanticType.PUNCTUATION;
if (!(SemanticPred.isRole(fence, SemanticRole.SUBSUP) ||
SemanticPred.isRole(fence, SemanticRole.UNDEROVER))) {
fence.role = newRole;
}
fence = fence.childNodes[0];
}
fence.type = SemanticType.PUNCTUATION;
fence.role = newRole;
}
/**
* Classifies a function wrt. the heuristic that should be applied.
* @param funcNode The node to be classified.
* @param restNodes The remainder list of
* nodes. They can be useful to look ahead if there is an explicit
* function application. If there is one, it will be destructively removed!
* @return The string specifying the heuristic.
*/
private static classifyFunction_(
funcNode: SemanticNode, restNodes: SemanticNode[]): string {
// We do not allow double function application. This is not lambda
// calculus!
if (funcNode.type === SemanticType.APPL ||
funcNode.type === SemanticType.BIGOP ||
funcNode.type === SemanticType.INTEGRAL) {
return '';
}
// Find and remove explicit function applications.
// We now treat funcNode as a prefix function, regardless of what its actual
// content is.
if (restNodes[0] &&
restNodes[0].textContent === SemanticAttr.functionApplication()) {
// Store explicit function application to be reused later.
SemanticProcessor.getInstance().funcAppls[funcNode.id] =
restNodes.shift();
let role = SemanticRole.SIMPLEFUNC;
SemanticHeuristics.run('simple2prefix', funcNode);
if (funcNode.role === SemanticRole.PREFIXFUNC ||
funcNode.role === SemanticRole.LIMFUNC) {
role = funcNode.role;
}
SemanticProcessor.propagateFunctionRole_(funcNode, role);
return 'prefix';
}
let kind = SemanticProcessor.CLASSIFY_FUNCTION_[funcNode.role];
return kind ? kind :
SemanticPred.isSimpleFunctionHead(funcNode) ? 'simple' : '';
}
/**
* Propagates a function role in a node.
* @param funcNode The node whose role is to be
* rewritten.
* @param tag The function role to be inserted.
*/
private static propagateFunctionRole_(
funcNode: SemanticNode, tag: SemanticRole) {
if (funcNode) {
if (funcNode.type === SemanticType.INFIXOP) {
return;
}
if (!(SemanticPred.isRole(funcNode, SemanticRole.SUBSUP) ||
SemanticPred.isRole(funcNode, SemanticRole.UNDEROVER))) {
funcNode.role = tag;
}
SemanticProcessor.propagateFunctionRole_(funcNode.childNodes[0], tag);
}
}
/**
* Finds the function operator in a partial semantic tree if it exists.
* @param tree The partial tree.
* @param pred Predicate for the
* function operator.
* @return The function operator.
*/
private static getFunctionOp_(
tree: SemanticNode, pred: (p1: SemanticNode) => boolean): SemanticNode {
if (pred(tree)) {
return tree;
}
for (let i = 0, child; child = tree.childNodes[i]; i++) {
let op = SemanticProcessor.getFunctionOp_(child, pred);
if (op) {
return op;
}
}
return null;
}
/**
* Replaces a fenced node by a matrix or vector node and possibly specialises
* it's role.
* @param node The fenced node to be rewritten.
* @return The matrix or vector node.
*/
private static tableToMatrixOrVector_(node: SemanticNode): SemanticNode {
let matrix = node.childNodes[0];
SemanticPred.isType(matrix, SemanticType.MULTILINE) ?
SemanticProcessor.tableToVector_(node) :
SemanticProcessor.tableToMatrix_(node);
node.contentNodes.forEach(matrix.appendContentNode.bind(matrix));
for (let i = 0, row; row = matrix.childNodes[i]; i++) {
SemanticProcessor.assignRoleToRow_(
row, SemanticProcessor.getComponentRoles_(matrix));
}
matrix.parent = null;
return matrix;
}
/**
* Assigns a specialised roles to a vector node inside the given fenced node.
* @param node The fenced node containing the vector.
*/
private static tableToVector_(node: SemanticNode) {
let vector = node.childNodes[0];
vector.type = SemanticType.VECTOR;
if (vector.childNodes.length === 1) {
SemanticProcessor.tableToSquare_(node);
return;
}
SemanticProcessor.binomialForm_(vector);
}
/**
* Assigns a binomial role if a table consists of two lines only.
* @param node The table node.
*/
private static binomialForm_(node: SemanticNode) {
if (SemanticPred.isBinomial(node)) {
node.role = SemanticRole.BINOMIAL;
node.childNodes[0].role = SemanticRole.BINOMIAL;
node.childNodes[1].role = SemanticRole.BINOMIAL;
}
}
/**
* Assigns a specialised roles to a matrix node inside the given fenced node.
* @param node The fenced node containing the matrix.
*/
private static tableToMatrix_(node: SemanticNode) {
let matrix = node.childNodes[0];
matrix.type = SemanticType.MATRIX;
if (matrix.childNodes && matrix.childNodes.length > 0 &&
matrix.childNodes[0].childNodes &&
matrix.childNodes.length === matrix.childNodes[0].childNodes.length) {
SemanticProcessor.tableToSquare_(node);
return;
}
if (matrix.childNodes && matrix.childNodes.length === 1) {
matrix.role = SemanticRole.ROWVECTOR;
}
}
/**
* Assigns a role to a square, fenced table.
* @param node The fenced node containing a square
* table.
*/
private static tableToSquare_(node: SemanticNode) {
let matrix = node.childNodes[0];
if (SemanticPred.isNeutralFence(node)) {
matrix.role = SemanticRole.DETERMINANT;
return;
}
matrix.role = SemanticRole.SQUAREMATRIX;
}
/**
* Cmoputes the role for the components of a matrix. It is either the role of
* that matrix or its type.
* @param node The matrix or vector node.
* @return The role to be assigned to the components.
*/
private static getComponentRoles_(node: SemanticNode): SemanticRole {
let role = node.role;
if (role && role !== SemanticRole.UNKNOWN) {
return role;
}
return node.type.toLowerCase() as SemanticRole ||
SemanticRole.UNKNOWN;
}
/**
* Makes case node out of a table and a fence.
* @param table The table containing the cases.
* @param openFence The left delimiter of the case
* statement.
* @return The cases node.
*/
private static tableToCases_(table: SemanticNode, openFence: SemanticNode):
SemanticNode {
for (let i = 0, row; row = table.childNodes[i]; i++) {
SemanticProcessor.assignRoleToRow_(row, SemanticRole.CASES);
}
table.type = SemanticType.CASES;
table.appendContentNode(openFence);
if (SemanticPred.tableIsMultiline(table)) {
SemanticProcessor.binomialForm_(table);
}
return table;
}
// TODO: (Simons) Is this heuristic really what we want? Make it selectable?
/**
* Heuristic to rewrite a single fenced line in a table into a square matrix.
* @param table The node to be rewritten.
* @return The rewritten node.
*/
private static rewriteFencedLine_(table: SemanticNode): SemanticNode {
let line = table.childNodes[0];
let fenced = table.childNodes[0].childNodes[0];
let element = table.childNodes[0].childNodes[0].childNodes[0];
fenced.parent = table.parent;
table.parent = fenced;
element.parent = line;
fenced.childNodes = [table];
line.childNodes = [element];
return fenced;
}
/**
* Converts a row that only contains one cell into a single line.
* @param row The row to convert.
* @param opt_role The new role for the line.
*/
private static rowToLine_(row: SemanticNode, opt_role?: SemanticRole) {
let role = opt_role || SemanticRole.UNKNOWN;
if (SemanticPred.isType(row, SemanticType.ROW)) {
row.type = SemanticType.LINE;
row.role = role;
if (row.childNodes.length === 1 &&
SemanticPred.isType(row.childNodes[0], SemanticType.CELL)) {
row.childNodes = row.childNodes[0].childNodes;
row.childNodes.forEach(function(x) {
x.parent = row;
});
}
}
}
/**
* Assign a row and its contained cells a new role value.
* @param row The row to be updated.
* @param role The new role for the row and its cells.
*/
private static assignRoleToRow_(row: SemanticNode, role: SemanticRole) {
if (SemanticPred.isType(row, SemanticType.LINE)) {
row.role = role;
return;
}
if (SemanticPred.isType(row, SemanticType.ROW)) {
row.role = role;
row.childNodes.forEach(function(cell) {
if (SemanticPred.isType(cell, SemanticType.CELL)) {
cell.role = role;
}
});
}
}
/**
* Constructs a closure that returns separators for an MathML mfenced
* expression.
* Separators in MathML are represented by a list and used up one by one
* until the final element is used as the default.
* Example: a b c d e and separators [+,-,*]
* would result in a + b - c * d * e.
* @param separators String representing a list of mfenced separators.
* @return A closure that returns the next separator
* for an mfenced expression starting with the first node in nodes.
*/
private static nextSeparatorFunction_(separators: string):
(() => string)|null {
let sepList: string[];
if (separators) {
// Mathjax does not expand empty separators.
if (separators.match(/^\s+$/)) {
return null;
} else {
sepList =
separators.replace(/\s/g, '').split('').filter(function(x) {
return x;
});
}
} else {
// When no separator is given MathML uses comma as default.
sepList = [','];
}
return function() {
if (sepList.length > 1) {
return sepList.shift();
}
return sepList[0];
};
}
/**
* Compute the role of a number if it does not have one already.
* @param node The semantic tree node.
*/
private static numberRole_(node: SemanticNode) {
if (node.role !== SemanticRole.UNKNOWN) {
return;
}
let content = SemanticUtil.splitUnicode(node.textContent);
let meaning = content.map(SemanticAttr.lookupMeaning);
if (meaning.every(function(x) {
return x.type === SemanticType.NUMBER &&
x.role === SemanticRole.INTEGER ||
x.type === SemanticType.PUNCTUATION &&
x.role === SemanticRole.COMMA;
})) {
node.role = SemanticRole.INTEGER;
if (content[0] === '0') {
node.addAnnotation('general', 'basenumber');
}
return;
}
if (meaning.every(function(x) {
return x.type === SemanticType.NUMBER &&
x.role === SemanticRole.INTEGER ||
x.type === SemanticType.PUNCTUATION;
})) {
node.role = SemanticRole.FLOAT;
return;
}
node.role = SemanticRole.OTHERNUMBER;
}
/**
* Updates the font of a node if a single font can be determined.
* @param node The semantic tree node.
*/
private static exprFont_(node: SemanticNode) {
if (node.font !== SemanticFont.UNKNOWN) {
return;
}
let content = SemanticUtil.splitUnicode(node.textContent);
let meaning = content.map(SemanticAttr.lookupMeaning);
let singleFont = meaning.reduce(function(prev, curr) {
if (!prev || !curr.font || curr.font === SemanticFont.UNKNOWN ||
curr.font === prev) {
return prev;
}
if (prev === SemanticFont.UNKNOWN) {
return curr.font;
}
return null;
}, SemanticFont.UNKNOWN);
if (singleFont) {
node.font = singleFont;
}
}
/**
* Rewrites a fences partition to remove non-eligible embellished fences.
* It rewrites all other fences into punctuations.
* For eligibility see sre.SemanticPred.isElligibleEmbellishedFence
* @param {{rel: !Array.<sre.SemanticNode>,
* comp: !Array.<!Array.<sre.SemanticNode>>}} partition A partition
* for fences.
* @return {{rel: !Array.<sre.SemanticNode>,
* comp: !Array.<!Array.<sre.SemanticNode>>}} The cleansed
* partition.
*/
private static purgeFences_(partition: {
rel: SemanticNode[],
comp: SemanticNode[][]
}): {rel: SemanticNode[], comp: SemanticNode[][]} {
let rel = partition.rel;
let comp = partition.comp;
let newRel = [];
let newComp = [];
while (rel.length > 0) {
let currentRel = rel.shift();
let currentComp = comp.shift();
if (SemanticPred.isElligibleEmbellishedFence(currentRel)) {
newRel.push(currentRel);
newComp.push(currentComp);
continue;
}
SemanticProcessor.fenceToPunct_(currentRel);
currentComp.push(currentRel);
currentComp = currentComp.concat(comp.shift());
comp.unshift(currentComp);
}
newComp.push(comp.shift());
return {rel: newRel, comp: newComp};
}
/**
* Rewrites a fenced node by pulling some embellishments from fences to the
* outside.
* @param fenced The fenced node.
* @return The rewritten node.
*/
private static rewriteFencedNode_(fenced: SemanticNode): SemanticNode {
let ofence = (fenced.contentNodes[0] as SemanticNode);
let cfence = (fenced.contentNodes[1] as SemanticNode);
let rewritten = SemanticProcessor.rewriteFence_(fenced, ofence);
fenced.contentNodes[0] = rewritten.fence;
rewritten = SemanticProcessor.rewriteFence_(rewritten.node, cfence);
fenced.contentNodes[1] = rewritten.fence;
fenced.contentNodes[0].parent = fenced;
fenced.contentNodes[1].parent = fenced;
rewritten.node.parent = null;
return rewritten.node;
}
/**
* Rewrites a fence by removing embellishments and putting them around the
* node. The only embellishments that are not pulled out are overscore and
* underscore.
* @param node The original fenced node.
* @param fence The fence node.
* @return {{node: !sre.SemanticNode,
* fence: !sre.SemanticNode}} The rewritten node and fence.
*/
// TODO (sorge) Maybe remove the superfluous MathML element.
private static rewriteFence_(node: SemanticNode, fence: SemanticNode):
{node: SemanticNode, fence: SemanticNode} {
if (!fence.embellished) {
return {node: node, fence: fence};
}
let newFence = (fence.childNodes[0] as SemanticNode);
let rewritten = SemanticProcessor.rewriteFence_(node, newFence);
if (SemanticPred.isType(fence, SemanticType.SUPERSCRIPT) ||
SemanticPred.isType(fence, SemanticType.SUBSCRIPT) ||
SemanticPred.isType(fence, SemanticType.TENSOR)) {
// Fence is embellished and needs to be rewritten.
if (!SemanticPred.isRole(fence, SemanticRole.SUBSUP)) {
fence.role = node.role;
}
if (newFence !== rewritten.node) {
fence.replaceChild(newFence, rewritten.node);
newFence.parent = node;
}
SemanticProcessor.propagateFencePointer_(fence, newFence);
return {node: fence, fence: rewritten.fence};
}
fence.replaceChild(newFence, rewritten.fence);
if (fence.mathmlTree && fence.mathml.indexOf(fence.mathmlTree) === -1) {
fence.mathml.push(fence.mathmlTree);
}
return {node: rewritten.node, fence: fence};
}
/**
* Propagates the fence pointer, that is, the embellishing node links to the
* actual fence it embellishes. If the link is valid on the new node, the old
* node will point to that link as well. Note, that this fence might still be
* embellished itself, e.g. with under or overscore.
* @param oldNode The old embellished node.
* @param newNode The new embellished node.
*/
private static propagateFencePointer_(
oldNode: SemanticNode, newNode: SemanticNode) {
oldNode.fencePointer = newNode.fencePointer || newNode.id.toString();
oldNode.embellished = null;
}
/**
* Classifies table by columns and a given relation.
* @param table The table node.
* @param columns The columns.
* @param relation The main relation to classify.
* @param alternatives Alternative relations that are
* permitted in addition to the main relation.
* @return True if classification was successful.
*/
private static classifyByColumns_(
table: SemanticNode, columns: SemanticNode[][], relation: SemanticRole,
_alternatives?: SemanticRole[]): boolean {
// TODO: For more complex systems, work with permutations/alternations of
// column indices.
let test1 = (x: SemanticNode) => SemanticProcessor.isPureRelation_(x, relation);
let test2 = (x: SemanticNode) => SemanticProcessor.isEndRelation_(x, relation) ||
SemanticProcessor.isPureRelation_(x, relation);
let test3 = (x: SemanticNode) => SemanticProcessor.isEndRelation_(x, relation, true) ||
SemanticProcessor.isPureRelation_(x, relation);
if (columns.length === 3 &&
SemanticProcessor.testColumns_(columns, 1, test1) ||
columns.length === 2 &&
(SemanticProcessor.testColumns_(columns, 1, test2) ||
SemanticProcessor.testColumns_(columns, 0, test3))) {
table.role = relation;
return true;
}
return false;
}
/**
* Check for a particular end relations, i.e., either a sole relation symbols
* or the relation ends in an side.
* @param node The node.
* @param relation The relation to be tested.
* @param opt_right From the right side?
* @return True if the node is an end relation.
*/
private static isEndRelation_(node: SemanticNode, relation: SemanticRole,
opt_right?: boolean): boolean {
let position = opt_right ? node.childNodes.length - 1 : 0;
return SemanticPred.isType(node, SemanticType.RELSEQ) &&
SemanticPred.isRole(node, relation) &&
SemanticPred.isType(node.childNodes[position], SemanticType.EMPTY);
}
/**
* Check for a particular relations.
* @param node The node.
* @param relation The relation to be tested.
* @return True if the node is an end relation.
*/
private static isPureRelation_(node: SemanticNode, relation: SemanticRole):
boolean {
return SemanticPred.isType(node, SemanticType.RELATION) &&
SemanticPred.isRole(node, relation);
}
/**
* Computes columns from a table. Note that the columns are reduced, i.e.,
* empty cells are simply omitted. Consequently, rows are not preserved, i.e.,
* elements at the same index in different columns are not necessarily in the
* same row in the original table!
* @param table The table node.
* @return The columns.
*/
private static computeColumns_(table: SemanticNode): SemanticNode[][] {
let columns = [];
for (let i = 0, row; row = table.childNodes[i]; i++) {
for (let j = 0, cell; cell = row.childNodes[j]; j++) {
let column = columns[j];
column ? columns[j].push(cell) : columns[j] = [cell];
}
}
return columns;
}
/**
* Test if all elements in the i-th column have the same property.
* @param columns The columns.
* @param index The column to be tested.
* @param pred Predicate to test against.
* @return True if all elements of the given column satisfy pred.
*/
private static testColumns_(
columns: SemanticNode[][], index: number,
pred: (p1: SemanticNode) => boolean): boolean {
let column = columns[index];
return column ? column.some(function(cell) {
return cell.childNodes.length &&
pred((cell.childNodes[0] as SemanticNode));
}) && column.every(function(cell) {
return !cell.childNodes.length ||
pred((cell.childNodes[0] as SemanticNode));
}) :
false;
}
/**
* Sets the node factory the processor is using.
* @param factory New node factory.
*/
public setNodeFactory(factory: SemanticNodeFactory) {
SemanticProcessor.getInstance().factory_ = factory;
SemanticHeuristics.factory = SemanticProcessor.getInstance().factory_;
}
/**
* Getter for the node factory.
* @return The node factory.
*/
public getNodeFactory(): SemanticNodeFactory {
return SemanticProcessor.getInstance().factory_;
}
/**
* Processes an identifier node, with particular emphasis on font
* disambiguation.
* @param leaf The identifier node.
* @param font The original mml font for the
* identifier. Could be empty if not font was given.
* @param unit The class of the identifier which is important if it is
* a unit.
* @return The semantic identifier node.
*/
public identifierNode(leaf: SemanticNode, font: SemanticFont, unit: string):
SemanticNode {
if (unit === 'MathML-Unit') {
leaf.type = SemanticType.IDENTIFIER;
leaf.role = SemanticRole.UNIT;
} else if (
!font && leaf.textContent.length === 1 &&
(leaf.role === SemanticRole.INTEGER ||
leaf.role === SemanticRole.LATINLETTER ||
leaf.role === SemanticRole.GREEKLETTER) &&
leaf.font === SemanticFont.NORMAL) {
// If single letter or single integer and font normal but no mathvariant
// then this letter/number should be in italic font.
leaf.font = SemanticFont.ITALIC;
return SemanticHeuristics.run('simpleNamedFunction', leaf) as SemanticNode;
}
if (leaf.type === SemanticType.UNKNOWN) {
leaf.type = SemanticType.IDENTIFIER;
}
SemanticProcessor.exprFont_(leaf);
return SemanticHeuristics.run('simpleNamedFunction', leaf) as SemanticNode;
}
/**
* Process a list of nodes and create a node for implicit operations,
* currently assumed to be of multiplicative type. Determines mixed numbers
* and unit elements.
* @param nodes The operands.
* @return The new branch node.
*/
public implicitNode(nodes: SemanticNode[]): SemanticNode {
nodes = SemanticProcessor.getInstance().getMixedNumbers_(nodes);
nodes = SemanticProcessor.getInstance().combineUnits_(nodes);
if (nodes.length === 1) {
return nodes[0];
}
let node = SemanticProcessor.getInstance().implicitNode_(nodes);
return SemanticHeuristics.run('combine_juxtaposition', node) as SemanticNode;
}
/**
* Create an text node, keeping string notation correct.
* @param leaf The text node.
* @param type The type of the text node.
* @return The new semantic text node.
*/
public text(leaf: SemanticNode, type: string): SemanticNode {
// TODO (simons): Here check if there is already a type or if we can compute
// an interesting number role. Than use this.
SemanticProcessor.exprFont_(leaf);
leaf.type = SemanticType.TEXT;
if (type === 'MS') {
leaf.role = SemanticRole.STRING;
return leaf;
}
if (type === 'MSPACE' || leaf.textContent.match(/^\s*$/)) {
leaf.role = SemanticRole.SPACE;
return leaf;
}
// TODO (simons): Process single element in text. E.g., check if a text
// element represents a function or a single letter, number, etc.
return leaf;
}
/**
* Processes a list of nodes, combining expressions by delimiters, tables,
* punctuation sequences, function/big operator/integral applications to
* generate a syntax tree with relation and operator precedence.
*
* This is the main heuristic to rewrite a flat row of terms into a meaningful
* term tree.
* @param nodes The list of nodes.
* @return The root node of the syntax tree.
*/
public row(nodes: SemanticNode[]): SemanticNode {
nodes = nodes.filter(function(x) {
return !SemanticPred.isType(x, SemanticType.EMPTY);
});
if (nodes.length === 0) {
return SemanticProcessor.getInstance().factory_.makeEmptyNode();
}
nodes = SemanticProcessor.getInstance().getFencesInRow_(nodes);
nodes = SemanticProcessor.getInstance().tablesInRow(nodes);
nodes = SemanticProcessor.getInstance().getPunctuationInRow_(nodes);
nodes = SemanticProcessor.getInstance().getTextInRow_(nodes);
nodes = SemanticProcessor.getInstance().getFunctionsInRow_(nodes);
return SemanticProcessor.getInstance().relationsInRow_(nodes);
}
/**
* Creates a limit node from a sub/superscript or over/under node if the
* central element is a big operator. Otherwise it creates the standard
* elements.
* @param mmlTag The tag name of the original node.
* @param children The children of the
* original node.
* @return The newly created limit node.
*/
public limitNode(mmlTag: string, children: SemanticNode[]): SemanticNode {
if (!children.length) {
return SemanticProcessor.getInstance().factory_.makeEmptyNode();
}
let center = children[0];
let type = SemanticType.UNKNOWN;
if (!children[1]) {
return center;
}
let result: BoundsType;
if (SemanticPred.isLimitBase(center)) {
result = SemanticProcessor.MML_TO_LIMIT_[mmlTag];
let length = result.length;
type = result.type;
children = children.slice(0, result.length + 1);
// Heuristic to deal with accents around limit functions/operators.
if (length === 1 && SemanticPred.isAccent(children[1]) ||
length === 2 && SemanticPred.isAccent(children[1]) &&
SemanticPred.isAccent(children[2])) {
result = SemanticProcessor.MML_TO_BOUNDS_[mmlTag];
return SemanticProcessor.getInstance().accentNode_(
center, children, result.type, result.length, result.accent);
}
if (length === 2) {
if (SemanticPred.isAccent(children[1])) {
center = SemanticProcessor.getInstance().accentNode_(
center, [center, children[1]], {
'MSUBSUP': SemanticType.SUBSCRIPT,
'MUNDEROVER': SemanticType.UNDERSCORE
}[mmlTag],
1, true);
return !children[2] ? center :
SemanticProcessor.getInstance().makeLimitNode_(
center, [center, children[2]], null,
SemanticType.LIMUPPER);
}
if (children[2] && SemanticPred.isAccent(children[2])) {
center = SemanticProcessor.getInstance().accentNode_(
center, [center, children[2]], {
'MSUBSUP': SemanticType.SUPERSCRIPT,
'MUNDEROVER': SemanticType.OVERSCORE
}[mmlTag],
1, true);
return SemanticProcessor.getInstance().makeLimitNode_(
center, [center, children[1]], null, SemanticType.LIMLOWER);
}
// Limit nodes only the number of children has to be restricted.
if (!children[length]) {
type = SemanticType.LIMLOWER;
}
}
return SemanticProcessor.getInstance().makeLimitNode_(center, children, null, type);
}
// We either have an indexed, stacked or accented expression.
result = SemanticProcessor.MML_TO_BOUNDS_[mmlTag];
return SemanticProcessor.getInstance().accentNode_(
center, children, result.type, result.length, result.accent);
}
// Improve table recognition, multiline alignments for pausing.
// Maybe labels, interspersed text etc.
/**
* Rewrites tables into matrices or case statements in a list of nodes.
* @param nodes List of nodes to rewrite.
* @return The new list of nodes.
*/
public tablesInRow(nodes: SemanticNode[]): SemanticNode[] {
// First we process all matrices:
let partition = SemanticUtil.partitionNodes(
nodes, SemanticPred.tableIsMatrixOrVector);
let result: SemanticNode[] = [];
for (let i = 0, matrix; matrix = partition.rel[i]; i++) {
result = result.concat(partition.comp.shift());
result.push(SemanticProcessor.tableToMatrixOrVector_(matrix));
}
result = result.concat(partition.comp.shift());
// Process the remaining tables for cases.
partition = SemanticUtil.partitionNodes(
result, SemanticPred.isTableOrMultiline);
result = [];
for (let i = 0, table; table = partition.rel[i]; i++) {
let prevNodes = partition.comp.shift();
if (SemanticPred.tableIsCases(table, prevNodes)) {
SemanticProcessor.tableToCases_(
table, (prevNodes.pop() as SemanticNode));
}
result = result.concat(prevNodes);
result.push(table);
}
return result.concat(partition.comp.shift());
}
/**
* Process an fenced node, effectively given in an mfenced style.
* @param open Textual representation of the opening fence.
* @param close Textual representation of the closing fence.
* @param sepValue Textual representation of separators.
* @param children List of already translated
* children.
* @return The semantic node.
*/
public mfenced(
open: string|null, close: string|null, sepValue: string|null,
children: SemanticNode[]): SemanticNode {
if (sepValue && children.length > 0) {
let separators = SemanticProcessor.nextSeparatorFunction_(sepValue);
let newChildren = [children.shift()];
children.forEach((child) => {
newChildren.push(
SemanticProcessor.getInstance().factory_.makeContentNode(
separators()));
newChildren.push(child);
});
children = newChildren;
}
// If both open and close are given, we assume those elements to be fences,
// regardless of their initial semantic interpretation. However, if only one
// of the fences is given we do not explicitly interfere with the semantic
// interpretation. In other worde the mfence is ignored and the content is
// interpreted as usual. The only effect of the mfence node here is that the
// content will be interpreted into a single node.
if (open && close) {
return SemanticProcessor.getInstance().horizontalFencedNode_(
SemanticProcessor.getInstance().factory_.makeContentNode(open),
SemanticProcessor.getInstance().factory_.makeContentNode(close),
children);
}
if (open) {
children.unshift(
SemanticProcessor.getInstance().factory_.makeContentNode(open));
}
if (close) {
children.push(
SemanticProcessor.getInstance().factory_.makeContentNode(close));
}
return SemanticProcessor.getInstance().row(children);
}
/**
* Creates a fraction node with the appropriate role.
* @param denom The denominator node.
* @param enume The enumerator node.
* @param linethickness The line thickness attribute value.
* @param bevelled Is it a bevelled fraction?
* @return The new fraction node.
*/
public fractionLikeNode(
denom: SemanticNode, enume: SemanticNode, linethickness: string,
bevelled: boolean): SemanticNode {
// return sre.SemanticProcessor.getInstance().factory_.makeBranchNode(
// SemanticType.MULTILINE, [child0, child1], []);
let node;
if (!bevelled && SemanticUtil.isZeroLength(linethickness)) {
let child0 = SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.LINE, [denom], []);
let child1 = SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.LINE, [enume], []);
node = SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.MULTILINE, [child0, child1], []);
SemanticProcessor.binomialForm_(node);
SemanticProcessor.classifyMultiline(node);
return node;
} else {
node = SemanticProcessor.getInstance().fractionNode_(denom, enume);
if (bevelled) {
node.addAnnotation('general', 'bevelled');
}
return node;
}
}
/**
* Create a tensor node.
* @param base The base node.
* @param lsub The left subscripts.
* @param lsup The left superscripts.
* @param rsub The right subscripts.
* @param rsup The right superscripts.
* @return The semantic tensor node.
*/
public tensor(base: SemanticNode, lsub: SemanticNode[], lsup: SemanticNode[],
rsub: SemanticNode[], rsup: SemanticNode[]): SemanticNode {
let newNode = SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.TENSOR,
[
base,
SemanticProcessor.getInstance().scriptNode_(
lsub, SemanticRole.LEFTSUB),
SemanticProcessor.getInstance().scriptNode_(
lsup, SemanticRole.LEFTSUPER),
SemanticProcessor.getInstance().scriptNode_(
rsub, SemanticRole.RIGHTSUB),
SemanticProcessor.getInstance().scriptNode_(
rsup, SemanticRole.RIGHTSUPER)
],
[]);
newNode.role = base.role;
newNode.embellished = SemanticPred.isEmbellished(base);
return newNode;
}
/**
* Creates a limit node from an original mmultiscript node, that only has
* non-empty right sub and superscript elements.
* @param base The base node.
* @param sub The subscripts.
* @param sup The superscripts.
* @return The semantic tensor node.
*/
public pseudoTensor(base: SemanticNode, sub: SemanticNode[],
sup: SemanticNode[]): SemanticNode {
let isEmpty = (x: SemanticNode) => !SemanticPred.isType(x, SemanticType.EMPTY);
let nonEmptySub = sub.filter(isEmpty).length;
let nonEmptySup = sup.filter(isEmpty).length;
if (!nonEmptySub && !nonEmptySup) {
return base;
}
let mmlTag = nonEmptySub ? nonEmptySup ? 'MSUBSUP' : 'MSUB' : 'MSUP';
let mmlchild = [base];
if (nonEmptySub) {
mmlchild.push(SemanticProcessor.getInstance().scriptNode_(
sub, SemanticRole.RIGHTSUB, true));
}
if (nonEmptySup) {
mmlchild.push(SemanticProcessor.getInstance().scriptNode_(
sup, SemanticRole.RIGHTSUPER, true));
}
return SemanticProcessor.getInstance().limitNode(mmlTag, mmlchild);
}
/**
* Cleans font names of potential MathJax prefixes.
* @param font The font name.
* @return The clean name.
*/
public font(font: string): SemanticFont {
let mathjaxFont = SemanticProcessor.MATHJAX_FONTS[font];
return mathjaxFont ? mathjaxFont : (font as SemanticFont);
}
/**
* Parses a proof node.
* @param node The node.
* @param semantics Association of semantic keys to values.
* @param parse The
* current semantic parser for list of nodes.
* @return The semantic node for the proof.
*/
public proof(
node: Element, semantics: {[key: string]: string},
parse: (p1: Element[]) => SemanticNode[]): SemanticNode {
if (!semantics['inference'] && !semantics['axiom']) {
console.log('Noise');
}
// do some preprocessing!
// Put in an invisible comma!
// Axiom case!
if (semantics['axiom']) {
let cleaned = SemanticProcessor.getInstance().cleanInference(node.childNodes);
let axiom = cleaned.length ?
SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.INFERENCE, parse(cleaned), []) :
SemanticProcessor.getInstance().factory_.makeEmptyNode();
axiom.role = SemanticRole.AXIOM;
axiom.mathmlTree = node;
return axiom;
}
let inference = SemanticProcessor.getInstance().inference(node, semantics, parse);
if (semantics['proof']) {
inference.role = SemanticRole.PROOF;
inference.childNodes[0].role = SemanticRole.FINAL;
}
return inference;
}
/**
* Parses a single inference node.
* @param node The node.
* @param semantics Association of semantic keys to values.
* @param parse The
* current semantic parser for list of nodes.
* @return The semantic node for the inference.
*/
public inference(
node: Element, semantics: {[key: string]: string},
parse: (p1: Element[]) => SemanticNode[]): SemanticNode {
if (semantics['inferenceRule']) {
let formulas = SemanticProcessor.getInstance().getFormulas(node, [], parse);
let inference = SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.INFERENCE, [formulas.conclusion, formulas.premises],
[]);
// Setting role
return inference;
}
let label = semantics['labelledRule'];
let children = DomUtil.toArray(node.childNodes);
let content = [];
if (label === 'left' || label === 'both') {
content.push(
SemanticProcessor.getInstance().getLabel(node, children, parse, SemanticRole.LEFT));
}
if (label === 'right' || label === 'both') {
content.push(
SemanticProcessor.getInstance().getLabel(node, children, parse, SemanticRole.RIGHT));
}
let formulas = SemanticProcessor.getInstance().getFormulas(node, children, parse);
let inference = SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.INFERENCE, [formulas.conclusion, formulas.premises],
content);
// Setting role
inference.mathmlTree = node;
return inference;
}
/**
* Parses the label of an inference rule.
* @param node The inference node.
* @param children The node's children containing the label.
* @param parse The
* current semantic parser for list of nodes.
* @param side The side the label is on.
* @return The semantic node for the label.
*/
public getLabel(_node: Element, children: Element[],
parse: (p1: Element[]) => SemanticNode[], side: string): SemanticNode {
let label = SemanticProcessor.getInstance().findNestedRow(children, 'prooflabel', side);
let sem = SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.RULELABEL,
parse(DomUtil.toArray(label.childNodes)), []);
sem.role = (side as SemanticRole);
sem.mathmlTree = label;
return sem;
}
/**
* Retrieves and parses premises and conclusion of an inference rule.
* @param node The inference rule node.
* @param children The node's children containing.
* @param parse The
* current semantic parser for list of nodes.
* @return A pair
* of conclusion and premises.
*/
public getFormulas(
node: Element, children: Element[],
parse: (p1: Element[]) => SemanticNode[]):
{conclusion: SemanticNode, premises: SemanticNode} {
let inf =
children.length ? SemanticProcessor.getInstance().findNestedRow(children, 'inferenceRule') : node;
let up = SemanticProcessor.getSemantics(inf)['inferenceRule'] === 'up';
let premRow = up ? inf.childNodes[1] : inf.childNodes[0];
let concRow = up ? inf.childNodes[0] : inf.childNodes[1];
let premTable = premRow.childNodes[0].childNodes[0];
let topRow = DomUtil.toArray(premTable.childNodes[0].childNodes);
let premNodes = [];
let i = 1;
for (let cell of topRow) {
if (i % 2) {
premNodes.push(cell.childNodes[0]);
}
i++;
}
let premises = parse(premNodes);
let conclusion =
parse(DomUtil.toArray(concRow.childNodes[0].childNodes))[0];
let prem =
SemanticProcessor.getInstance().factory_.makeBranchNode(SemanticType.PREMISES, premises, []);
prem.mathmlTree = (premTable as Element);
let conc = SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.CONCLUSION, [conclusion], []);
conc.mathmlTree = (concRow.childNodes[0].childNodes[0] as Element);
return {conclusion: conc, premises: prem};
}
/**
* Find a inference element nested in a row.
* @param nodes A node list.
* @param semantic A semantic key.
* @param opt_value Optionally the semantic value.
* @return The first element in that row that contains the semantic
* key (and has its value if the latter is given.)
*/
public findNestedRow(nodes: Element[], semantic: string, opt_value?: string):
Element {
return SemanticProcessor.getInstance().findNestedRow_(nodes, semantic, 0, opt_value);
}
/**
* Removes mspaces in a row.
* @param nodes The list of nodes.
* @return The list with all space elements removed.
*/
public cleanInference(nodes: NodeList): Element[] {
return DomUtil.toArray(nodes).filter(function(x) {
return DomUtil.tagName(x) !== 'MSPACE';
});
}
/**
* Switches unknown to operator node and runs multioperator heuristics.
* @param node The node to retype.
* @return The node resulting from applying the heuristic.
*/
public operatorNode(node: SemanticNode): SemanticNode {
if (node.type === SemanticType.UNKNOWN) {
node.type = SemanticType.OPERATOR;
}
return SemanticHeuristics.run('multioperator', node) as SemanticNode;
}
/**
* Private constructor for singleton class.
*/
private constructor() {
this.factory_ = new SemanticNodeFactory();
SemanticHeuristics.factory = this.factory_;
}
/**
* Create a branching node for an implicit operation, currently assumed to be
* of multiplicative type.
* @param nodes The operands.
* @return The new branch node.
*/
private implicitNode_(nodes: SemanticNode[]): SemanticNode {
let operators =
SemanticProcessor.getInstance().factory_.makeMultipleContentNodes(
nodes.length - 1, SemanticAttr.invisibleTimes());
SemanticProcessor.matchSpaces_(nodes, operators);
// For now we assume this is a multiplication using invisible times.
let newNode = SemanticProcessor.getInstance().infixNode_(
nodes, (operators[0] as SemanticNode));
newNode.role = SemanticRole.IMPLICIT;
operators.forEach(function(op) {
op.parent = newNode;
});
newNode.contentNodes = operators;
return newNode;
}
/**
* Create a branching node for an infix operation.
* @param children The operands.
* @param opNode The operator.
* @return The new branch node.
*/
private infixNode_(children: SemanticNode[], opNode: SemanticNode):
SemanticNode {
let node = SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.INFIXOP, children, [opNode],
SemanticUtil.getEmbellishedInner(opNode).textContent);
node.role = opNode.role;
return SemanticHeuristics.run('propagateSimpleFunction', node) as SemanticNode;
}
/**
* Finds mixed numbers that are explicitly given with invisible plus.
* @param nodes The list of nodes.
* @return The new list of nodes.
*/
private explicitMixed_(nodes: SemanticNode[]): SemanticNode[] {
let partition = SemanticUtil.partitionNodes(nodes, function(x) {
return x.textContent === SemanticAttr.invisiblePlus();
});
if (!partition.rel.length) {
return nodes;
}
let result: SemanticNode[] = [];
for (let i = 0, rel; rel = partition.rel[i]; i++) {
let prev = partition.comp[i];
let next = partition.comp[i + 1];
let last = prev.length - 1;
if (prev[last] && next[0] &&
SemanticPred.isType(prev[last], SemanticType.NUMBER) &&
!SemanticPred.isRole(prev[last], SemanticRole.MIXED) &&
SemanticPred.isType(next[0], SemanticType.FRACTION)) {
let newNode = SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.NUMBER, [prev[last], next[0]], []);
newNode.role = SemanticRole.MIXED;
result = result.concat(prev.slice(0, last));
result.push(newNode);
next.shift();
} else {
result = result.concat(prev);
result.push(rel);
}
}
return result.concat(partition.comp[partition.comp.length - 1]);
}
/**
* Creates a node of the specified type by collapsing the given node list into
* one content (thereby concatenating the content of each node into a single
* content string) with the inner node as a child.
* @param inner The inner node.
* @param nodeList List of nodes.
* @param type The new type of the node.
* @return The new branch node.
*/
private concatNode_(
inner: SemanticNode, nodeList: SemanticNode[],
type: SemanticType): SemanticNode {
if (nodeList.length === 0) {
return inner;
}
let content =
nodeList
.map(function(x) {
return SemanticUtil.getEmbellishedInner(x).textContent;
})
.join(' ');
let newNode = SemanticProcessor.getInstance().factory_.makeBranchNode(
type, [inner], nodeList, content);
if (nodeList.length > 1) {
newNode.role = SemanticRole.MULTIOP;
}
return newNode;
}
// TODO: (Simons) Rewrite to group same operators.
// Currently the positive role is only given to the innermost single +
// prefix operator.
/**
* Wraps a node into prefix operators.
* Example: + - a becomes (+ (- (a)))
* Input: a [+, -] -> Output: content: '+ -', child: a
* @param node The inner node.
* @param prefixes Prefix operators
* from the outermost to the innermost.
* @return The new branch node.
*/
private prefixNode_(node: SemanticNode, prefixes: SemanticNode[]):
SemanticNode {
let negatives = SemanticUtil.partitionNodes(
prefixes, x => SemanticPred.isRole(x , SemanticRole.SUBTRACTION));
let newNode = SemanticProcessor.getInstance().concatNode_(
node, negatives.comp.pop(), SemanticType.PREFIXOP);
if (newNode.contentNodes.length === 1 &&
newNode.contentNodes[0].role === SemanticRole.ADDITION &&
newNode.contentNodes[0].textContent === '+') {
newNode.role = SemanticRole.POSITIVE;
}
while (negatives.rel.length > 0) {
newNode = SemanticProcessor.getInstance().concatNode_(
newNode, [negatives.rel.pop()], SemanticType.PREFIXOP);
newNode.role = SemanticRole.NEGATIVE;
newNode = SemanticProcessor.getInstance().concatNode_(
newNode, negatives.comp.pop(), SemanticType.PREFIXOP);
}
return newNode;
}
/**
* Wraps a node into postfix operators.
* Example: a - + becomes (((a) -) +)
* Input: a [-, +] -> Output: content: '- +', child: a
* @param node The inner node.
* @param postfixes Postfix operators from
* innermost to outermost.
* @return The new branch node.
*/
private postfixNode_(node: SemanticNode, postfixes: SemanticNode[]):
SemanticNode {
if (!postfixes.length) {
return node;
}
return SemanticProcessor.getInstance().concatNode_(
node, postfixes, SemanticType.POSTFIXOP);
}
/**
* Combines adjacent units in
* @param nodes The list of nodes.
* @return The new list of nodes.
*/
private combineUnits_(nodes: SemanticNode[]): SemanticNode[] {
let partition = SemanticUtil.partitionNodes(nodes, function(x) {
return !SemanticPred.isRole(x, SemanticRole.UNIT);
});
if (nodes.length === partition.rel.length) {
return partition.rel;
}
let result = [];
let rel: SemanticNode;
let last: SemanticNode;
do {
let comp = partition.comp.shift();
rel = partition.rel.shift();
let unitNode = null;
last = result.pop();
if (last) {
if (!comp.length || !SemanticPred.isUnitCounter(last)) {
result.push(last);
} else {
comp.unshift(last);
}
}
if (comp.length === 1) {
unitNode = comp.pop();
}
if (comp.length > 1) {
// For now we assume this is a multiplication using invisible times.
unitNode = SemanticProcessor.getInstance().implicitNode_(comp);
unitNode.role = SemanticRole.UNIT;
}
if (unitNode) {
result.push(unitNode);
}
if (rel) {
result.push(rel);
}
} while (rel);
return result;
}
/**
* Finds mixed numbers in a list of single nodes. A mixed number is an integer
* followed by a vulgar fraction.
* @param nodes The list of nodes.
* @return The new list of nodes.
*/
// Change that to compute mixed fractions.
private getMixedNumbers_(nodes: SemanticNode[]): SemanticNode[] {
let partition = SemanticUtil.partitionNodes(nodes, function(x) {
return SemanticPred.isType(x, SemanticType.FRACTION) &&
SemanticPred.isRole(x, SemanticRole.VULGAR);
});
if (!partition.rel.length) {
return nodes;
}
let result: SemanticNode[] = [];
for (let i = 0, rel; rel = partition.rel[i]; i++) {
let comp = partition.comp[i];
let last = comp.length - 1;
if (comp[last] &&
SemanticPred.isType(comp[last], SemanticType.NUMBER) &&
(SemanticPred.isRole(comp[last], SemanticRole.INTEGER) ||
SemanticPred.isRole(comp[last], SemanticRole.FLOAT))) {
let newNode = SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.NUMBER, [comp[last], rel], []);
newNode.role = SemanticRole.MIXED;
result = result.concat(comp.slice(0, last));
result.push(newNode);
} else {
result = result.concat(comp);
result.push(rel);
}
}
return result.concat(partition.comp[partition.comp.length - 1]);
}
/**
* Separates text from math content and combines them into a punctuated node,
* with dummy punctuation invisible comma.
* @param nodes The list of nodes.
* @return The new list of nodes.
*/
private getTextInRow_(nodes: SemanticNode[]): SemanticNode[] {
if (nodes.length <= 1) {
return nodes;
}
let partition = SemanticUtil.partitionNodes(
nodes, x => SemanticPred.isType(x , SemanticType.TEXT));
if (partition.rel.length === 0) {
return nodes;
}
let result = [];
let nextComp = partition.comp[0];
// TODO: Properly collate punctuation: Add start and end punctuation to
// become
// the punctuation content of the punctuated node. Consider spaces
// separately. This currently introduces too many invisible commas.
if (nextComp.length > 0) {
result.push(SemanticProcessor.getInstance().row(nextComp));
}
for (let i = 0, text; text = partition.rel[i]; i++) {
result.push(text);
nextComp = partition.comp[i + 1];
if (nextComp.length > 0) {
result.push(SemanticProcessor.getInstance().row(nextComp));
}
}
return [SemanticProcessor.getInstance().dummyNode_(result)];
}
/**
* Constructs a syntax tree with relation and operator precedence from a list
* of nodes.
* @param nodes The list of nodes.
* @return The root node of the syntax tree.
*/
private relationsInRow_(nodes: SemanticNode[]): SemanticNode {
let partition =
SemanticUtil.partitionNodes(nodes, SemanticPred.isRelation);
let firstRel = partition.rel[0];
if (!firstRel) {
return SemanticProcessor.getInstance().operationsInRow_(nodes);
}
if (nodes.length === 1) {
return nodes[0];
}
let children = partition.comp.map(
SemanticProcessor.getInstance().operationsInRow_);
let node: SemanticNode;
if (partition.rel.some(function(x) {
return !x.equals(firstRel);
})) {
node = SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.MULTIREL, children, partition.rel);
if (partition.rel.every(function(x) {
return x.role === firstRel.role;
})) {
node.role = firstRel.role;
}
return node;
}
node = SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.RELSEQ, children, partition.rel,
SemanticUtil.getEmbellishedInner(firstRel).textContent);
node.role = firstRel.role;
return node;
}
/**
* Constructs a syntax tree with operator precedence from a list nodes.
* @param nodes The list of nodes.
* @return The root node of the syntax tree.
*/
private operationsInRow_(nodes: SemanticNode[]): SemanticNode {
if (nodes.length === 0) {
return SemanticProcessor.getInstance().factory_.makeEmptyNode();
}
// Get explicitly given mixed numbers
nodes = SemanticProcessor.getInstance().explicitMixed_(nodes);
if (nodes.length === 1) {
return nodes[0];
}
let prefix = [];
while (nodes.length > 0 && SemanticPred.isOperator(nodes[0])) {
prefix.push(nodes.shift());
}
// Pathological case: only operators in row.
if (nodes.length === 0) {
return SemanticProcessor.getInstance().prefixNode_(prefix.pop(), prefix);
}
if (nodes.length === 1) {
return SemanticProcessor.getInstance().prefixNode_(nodes[0], prefix);
}
// Deal with explicit juxtaposition
nodes = SemanticHeuristics.run('convert_juxtaposition', nodes) as SemanticNode[];
let split = SemanticUtil.sliceNodes(nodes, SemanticPred.isOperator);
// At this point, we know that split.head is not empty!
let node = SemanticProcessor.getInstance().prefixNode_(
SemanticProcessor.getInstance().implicitNode(
(split.head as SemanticNode[])),
prefix);
if (!split.div) {
return node;
}
return SemanticProcessor.getInstance().operationsTree_(
split.tail, node, split.div);
}
/**
* Recursively constructs syntax tree with operator precedence from a list
* nodes given a initial root node.
* @param nodes The list of nodes.
* @param root Initial tree.
* @param lastop Last operator that has not been
* processed yet.
* @param opt_prefixes Operator nodes that
* will become prefix operation (or postfix in case they come after last
* operand).
* @return The root node of the syntax tree.
*/
private operationsTree_(
nodes: SemanticNode[], root: SemanticNode, lastop: SemanticNode,
opt_prefixes?: SemanticNode[]): SemanticNode {
let prefixes = opt_prefixes || [];
if (nodes.length === 0) {
// Left over prefixes become postfixes.
prefixes.unshift(lastop);
if (root.type === SemanticType.INFIXOP) {
// We assume prefixes bind stronger than postfixes.
let node = SemanticProcessor.getInstance().postfixNode_(
// Here we know that the childNodes are not empty!
(root.childNodes.pop() as SemanticNode), prefixes);
root.appendChild(node);
return root;
}
return SemanticProcessor.getInstance().postfixNode_(root, prefixes);
}
let split = SemanticUtil.sliceNodes(nodes, SemanticPred.isOperator);
if (split.head.length === 0) {
prefixes.push(split.div);
return SemanticProcessor.getInstance().operationsTree_(
split.tail, root, lastop, prefixes);
}
let node = SemanticProcessor.getInstance().prefixNode_(
SemanticProcessor.getInstance().implicitNode(split.head), prefixes);
let newNode =
SemanticProcessor.getInstance().appendOperand_(root, lastop, node);
if (!split.div) {
return newNode;
}
return SemanticProcessor.getInstance().operationsTree_(
split.tail, newNode, split.div, []);
}
// TODO (sorge) The following four functions could be combined into
// a single one. Currently it is clearer the way it is, though.
/**
* Appends an operand at the right place in an operator tree.
* @param root The operator tree.
* @param op The operator node.
* @param node The node to be added.
* @return The modified root node.
*/
private appendOperand_(
root: SemanticNode, op: SemanticNode, node: SemanticNode): SemanticNode {
// In general our operator tree will have the form that additions and
// subtractions are stacked, while multiplications are subordinate.
if (root.type !== SemanticType.INFIXOP) {
return SemanticProcessor.getInstance().infixNode_([root, node], op);
}
let division = SemanticProcessor.getInstance().appendDivisionOp_(root, op, node);
if (division) {
return division;
}
if (SemanticProcessor.getInstance().appendExistingOperator_(
root, op, node)) {
return root;
}
return op.role === SemanticRole.MULTIPLICATION ?
SemanticProcessor.getInstance().appendMultiplicativeOp_(
root, op, node) :
SemanticProcessor.getInstance().appendAdditiveOp_(root, op, node);
}
/**
* Appends an operand to a divsion operator.
* @param root The root node.
* @param op The operator node.
* @param node The operand node to be added.
* @return The modified root node or null.
*/
private appendDivisionOp_(
root: SemanticNode, op: SemanticNode, node: SemanticNode): SemanticNode {
if (op.role === SemanticRole.DIVISION) {
if (SemanticPred.isImplicit(root)) {
return SemanticProcessor.getInstance().infixNode_([root, node], op);
}
return SemanticProcessor.getInstance().appendLastOperand_(root, op, node);
}
return root.role === SemanticRole.DIVISION ?
SemanticProcessor.getInstance().infixNode_([root, node], op) :
null;
}
/**
* Appends an operand as rightmost child of an infix operator.
* @param root The root node.
* @param op The operator node.
* @param node The operand node to be added.
* @return The modified root node.
*/
private appendLastOperand_(
root: SemanticNode, op: SemanticNode, node: SemanticNode): SemanticNode {
let lastRoot = root;
let lastChild = root.childNodes[root.childNodes.length - 1];
while (lastChild && lastChild.type === SemanticType.INFIXOP &&
!SemanticPred.isImplicit(lastChild)) {
lastRoot = lastChild;
lastChild = lastRoot.childNodes[root.childNodes.length - 1];
}
let newNode = SemanticProcessor.getInstance().infixNode_(
[lastRoot.childNodes.pop(), node], op);
lastRoot.appendChild(newNode);
return root;
}
/**
* Appends a multiplicative operator and operand.
* @param root The root node.
* @param op The operator node.
* @param node The operand node to be added.
* @return The modified root node.
*/
private appendMultiplicativeOp_(
root: SemanticNode, op: SemanticNode, node: SemanticNode): SemanticNode {
// This ensures that implicit nodes stay together, which is probably what
// we want.
if (SemanticPred.isImplicit(root)) {
return SemanticProcessor.getInstance().infixNode_([root, node], op);
}
let lastRoot = root;
let lastChild = root.childNodes[root.childNodes.length - 1];
while (lastChild && lastChild.type === SemanticType.INFIXOP &&
!SemanticPred.isImplicit(lastChild)) {
lastRoot = lastChild;
lastChild = lastRoot.childNodes[root.childNodes.length - 1];
}
let newNode = SemanticProcessor.getInstance().infixNode_(
[lastRoot.childNodes.pop(), node], op);
lastRoot.appendChild(newNode);
return root;
}
/**
* Appends an additive/substractive operator and operand.
* @param root The old root node.
* @param op The operator node.
* @param node The operand node to be added.
* @return The new root node.
*/
private appendAdditiveOp_(
root: SemanticNode, op: SemanticNode, node: SemanticNode): SemanticNode {
return SemanticProcessor.getInstance().infixNode_([root, node], op);
}
/**
* Adds an operand to an operator node if it is the continuation of an
* existing operation.
* @param root The root node.
* @param op The operator node.
* @param node The operand node to be added.
* @return True if operator was successfully appended.
*/
private appendExistingOperator_(
root: SemanticNode, op: SemanticNode, node: SemanticNode): boolean {
if (!root || root.type !== SemanticType.INFIXOP ||
// This ensures that implicit nodes stay together, which is probably
// what we want.
SemanticPred.isImplicit(root)) {
return false;
}
if (root.contentNodes[0].equals(op)) {
root.appendContentNode(op);
root.appendChild(node);
return true;
}
return SemanticProcessor.getInstance().appendExistingOperator_(
// Again, if this is an INFIXOP node, we know it has a child!
(root.childNodes[root.childNodes.length - 1] as SemanticNode), op,
node);
}
// TODO (sorge) The following procedure needs a rational reconstruction. It
// contains a number of similar cases which should be combined.
/**
* Combines delimited expressions in a list of nodes.
*
* The basic idea of the heuristic is as follows:
* 1. Opening and closing delimiters are matched regardless of the actual
* shape of the fence. These are turned into fenced nodes.
* 2. Neutral fences are matched only with neutral fences of the same shape.
* 3. For a collection of unmatched neutral fences we try to get a maximum
* number of matching fences. E.g. || a|b || would be turned into a fenced
* node with fences || and content a|b.
* 4. Any remaining unmatched delimiters are turned into punctuation nodes.
* @param nodes The list of nodes.
* @return The new list of nodes.
*/
private getFencesInRow_(nodes: SemanticNode[]): SemanticNode[] {
let partition =
SemanticUtil.partitionNodes(nodes, SemanticPred.isFence);
partition = SemanticProcessor.purgeFences_(partition);
let felem = partition.comp.shift();
return SemanticProcessor.getInstance().fences_(
partition.rel, partition.comp, [], [felem]);
}
/**
* Recursively processes a list of nodes and combines all the fenced
* expressions into single nodes. It also processes singular fences, building
* expressions that are only fenced left or right.
* @param fences FIFO queue of fence nodes.
* @param content FIFO queue content
* between fences.
* @param openStack LIFO stack of open fences.
* @param contentStack LIFO stack of
* content between fences yet to be processed.
* @return A list of nodes with all fenced
* expressions processed.
*/
private fences_(
fences: SemanticNode[], content: SemanticNode[][],
openStack: SemanticNode[],
contentStack: SemanticNode[][]): SemanticNode[] {
// Base case 1: Everything is used up.
if (fences.length === 0 && openStack.length === 0) {
return contentStack[0];
}
let openPred =
(x: SemanticNode) => SemanticPred.isRole(x, SemanticRole.OPEN);
// Base case 2: Only open and neutral fences are left on the stack.
if (fences.length === 0) {
// Basic idea:
// - make punctuation nodes from open fences
// - combine as many neutral fences as possible, if the are not separated
// by
// open fences.
// The idea is to allow for things like case statements etc. and not bury
// them inside a neutral fenced expression.
// 0. We process the list from left to right. Hence the first element on
// the
// content stack are actually left most elements in the expression.
// 1. Slice at open fence.
// 2. On tail optimize for neutral fences.
// 3. Repeat until fence stack is exhausted.
// Push rightmost elements onto the result.
let result = contentStack.shift();
while (openStack.length > 0) {
if (openPred(openStack[0])) {
let firstOpen = openStack.shift();
SemanticProcessor.fenceToPunct_(firstOpen);
result.push(firstOpen);
} else {
let split = SemanticUtil.sliceNodes(openStack, openPred);
let cutLength = split.head.length - 1;
let innerNodes = SemanticProcessor.getInstance().neutralFences_(
split.head, contentStack.slice(0, cutLength));
contentStack = contentStack.slice(cutLength);
// var rightContent = contentStack.shift();
result.push.apply(result, innerNodes);
// result.push.apply(result, rightContent);
if (split.div) {
split.tail.unshift(split.div);
}
openStack = split.tail;
}
result.push.apply(result, contentStack.shift());
}
return result;
}
let lastOpen = openStack[openStack.length - 1];
let firstRole = fences[0].role;
// General opening case.
// Either we have an open fence.
if (firstRole === SemanticRole.OPEN ||
// Or we have a neutral fence that does not have a counter part.
SemanticPred.isNeutralFence(fences[0]) &&
!(lastOpen &&
SemanticPred.compareNeutralFences(fences[0], lastOpen))) {
openStack.push(fences.shift());
let cont = content.shift();
if (cont) {
contentStack.push(cont);
}
// contentStack.push(content.shift());
return SemanticProcessor.getInstance().fences_(
fences, content, openStack, contentStack);
}
// General closing case.
if (lastOpen &&
// Closing fence for some opening fence.
firstRole === SemanticRole.CLOSE &&
lastOpen.role === SemanticRole.OPEN) {
let fenced = SemanticProcessor.getInstance().horizontalFencedNode_(
openStack.pop(), fences.shift(), contentStack.pop());
contentStack.push(contentStack.pop().concat([fenced], content.shift()));
return SemanticProcessor.getInstance().fences_(
fences, content, openStack, contentStack);
}
if (lastOpen &&
// Neutral fence with exact counter part.
SemanticPred.compareNeutralFences(fences[0], lastOpen)) {
if (!SemanticPred.elligibleLeftNeutral(lastOpen) ||
!SemanticPred.elligibleRightNeutral(fences[0])) {
openStack.push(fences.shift());
let cont = content.shift();
if (cont) {
contentStack.push(cont);
}
return SemanticProcessor.getInstance().fences_(
fences, content, openStack, contentStack);
}
let fenced = SemanticProcessor.getInstance().horizontalFencedNode_(
openStack.pop(), fences.shift(), contentStack.pop());
contentStack.push(contentStack.pop().concat([fenced], content.shift()));
return SemanticProcessor.getInstance().fences_(
fences, content, openStack, contentStack);
}
// Closing with a neutral fence on the stack.
if (lastOpen && firstRole === SemanticRole.CLOSE &&
SemanticPred.isNeutralFence(lastOpen) &&
openStack.some(openPred)) {
// Steps of the algorithm:
// 1. Split list at right most opening bracket.
// 2. Cut content list at corresponding length.
// 3. Optimise the neutral fences.
// 4. Make fenced node.
// Careful, this reverses openStack!
let split = SemanticUtil.sliceNodes(openStack, openPred, true);
// We know that
// (a) div & tail exist,
// (b) all are combined in this step into a single fenced node,
// (c) head is the new openStack,
// (d) the new contentStack is remainder of contentStack + new fenced node
// + shift of content.
let rightContent = contentStack.pop();
let cutLength = contentStack.length - split.tail.length + 1;
let innerNodes = SemanticProcessor.getInstance().neutralFences_(
split.tail, contentStack.slice(cutLength));
contentStack = contentStack.slice(0, cutLength);
let fenced = SemanticProcessor.getInstance().horizontalFencedNode_(
split.div, fences.shift(),
contentStack.pop().concat(innerNodes, rightContent));
contentStack.push(contentStack.pop().concat([fenced], content.shift()));
return SemanticProcessor.getInstance().fences_(
fences, content, split.head, contentStack);
}
// Final Case: A singular closing fence.
// We turn the fence into a punctuation.
let fenced = fences.shift();
SemanticProcessor.fenceToPunct_(fenced);
contentStack.push(contentStack.pop().concat([fenced], content.shift()));
return SemanticProcessor.getInstance().fences_(
fences, content, openStack, contentStack);
}
// TODO (sorge) The following could be done with linear programming.
/**
* Trys to combine neutral fences as much as possible.
* @param fences A list of neutral fences.
* @param content Intermediate
* content. Observe that |content| = |fences| - 1
* @return List of node with fully fenced
* nodes.
*/
private neutralFences_(fences: SemanticNode[], content: SemanticNode[][]):
SemanticNode[] {
if (fences.length === 0) {
return fences;
}
if (fences.length === 1) {
SemanticProcessor.fenceToPunct_(fences[0]);
return fences;
}
let firstFence = fences.shift();
if (!SemanticPred.elligibleLeftNeutral(firstFence)) {
SemanticProcessor.fenceToPunct_(firstFence);
let restContent = content.shift();
restContent.unshift(firstFence);
return restContent.concat(
SemanticProcessor.getInstance().neutralFences_(fences, content));
}
let split = SemanticUtil.sliceNodes(fences, function(x) {
return SemanticPred.compareNeutralFences(x, firstFence);
});
if (!split.div) {
SemanticProcessor.fenceToPunct_(firstFence);
let restContent = content.shift();
restContent.unshift(firstFence);
return restContent.concat(
SemanticProcessor.getInstance().neutralFences_(fences, content));
}
// If the first right neutral is not elligible we ignore it.
if (!SemanticPred.elligibleRightNeutral(split.div)) {
SemanticProcessor.fenceToPunct_(split.div);
fences.unshift(firstFence);
return SemanticProcessor.getInstance().neutralFences_(fences, content);
}
let newContent = SemanticProcessor.getInstance().combineFencedContent_(
firstFence, split.div, split.head, content);
if (split.tail.length > 0) {
let leftContent = newContent.shift();
let result = SemanticProcessor.getInstance().neutralFences_(
split.tail, newContent);
return leftContent.concat(result);
}
return newContent[0];
}
/**
* Combines nodes framed by two matching fences using the given content.
* Example: leftFence: [, rightFence: ], midFences: |, |
* content: c1, c2, c3, c4, ... cn
* return: [c1 | c2 | c3 ], c4, ... cn
* @param leftFence The left fence.
* @param rightFence The right fence.
* @param midFences A list of intermediate
* fences.
* @param content Intermediate
* content. Observe that |content| = |fences| - 1 + k where k >= 0 is the
* remainder.
* @return List of content nodes
* where the first is the fully fenced node wrt. the given left and right
* fence.
*/
private combineFencedContent_(
leftFence: SemanticNode, rightFence: SemanticNode,
midFences: SemanticNode[], content: SemanticNode[][]): SemanticNode[][] {
if (midFences.length === 0) {
let fenced = SemanticProcessor.getInstance().horizontalFencedNode_(
leftFence, rightFence, content.shift());
if (content.length > 0) {
content[0].unshift(fenced);
} else {
content = [[fenced]];
}
return content;
}
let leftContent = content.shift();
let cutLength = midFences.length - 1;
let midContent = content.slice(0, cutLength);
content = content.slice(cutLength);
let rightContent = content.shift();
let innerNodes =
SemanticProcessor.getInstance().neutralFences_(midFences, midContent);
leftContent.push.apply(leftContent, innerNodes);
leftContent.push.apply(leftContent, rightContent);
let fenced = SemanticProcessor.getInstance().horizontalFencedNode_(
leftFence, rightFence, leftContent);
if (content.length > 0) {
content[0].unshift(fenced);
} else {
content = [[fenced]];
}
return content;
}
/**
* Create a fenced node.
* @param ofence Opening fence.
* @param cfence Closing fence.
* @param content The content
* between the fences.
* @return The new node.
*/
private horizontalFencedNode_(
ofence: SemanticNode, cfence: SemanticNode,
content: SemanticNode[]): SemanticNode {
let childNode = SemanticProcessor.getInstance().row(content);
let newNode = SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.FENCED, [childNode], [ofence, cfence]);
if (ofence.role === SemanticRole.OPEN) {
// newNode.role = SemanticRole.LEFTRIGHT;
SemanticProcessor.getInstance().classifyHorizontalFence_(newNode);
newNode = SemanticHeuristics.run('propagateComposedFunction', newNode) as SemanticNode;
} else {
newNode.role = ofence.role;
}
newNode = SemanticHeuristics.run('detect_cycle', newNode) as SemanticNode;
return SemanticProcessor.rewriteFencedNode_(newNode);
}
/**
* Classifies a horizontally fenced semantic node, using heuristics to
* determine certain set types, intervals etc.
* @param node A fenced semantic node.
*/
private classifyHorizontalFence_(node: SemanticNode) {
node.role = SemanticRole.LEFTRIGHT;
let children = node.childNodes;
if (!SemanticPred.isSetNode(node) || children.length > 1) {
return;
}
if (children.length === 0 || children[0].type === SemanticType.EMPTY) {
node.role = SemanticRole.SETEMPTY;
return;
}
let type = children[0].type;
if (children.length === 1 &&
SemanticPred.isSingletonSetContent(children[0])) {
node.role = SemanticRole.SETSINGLE;
return;
}
let role = children[0].role;
if (type !== SemanticType.PUNCTUATED ||
role !== SemanticRole.SEQUENCE) {
return;
}
if (children[0].contentNodes[0].role === SemanticRole.COMMA) {
node.role = SemanticRole.SETCOLLECT;
return;
}
if (children[0].contentNodes.length === 1 &&
(children[0].contentNodes[0].role === SemanticRole.VBAR ||
children[0].contentNodes[0].role === SemanticRole.COLON)) {
node.role = SemanticRole.SETEXT;
SemanticProcessor.getInstance().setExtension_(node);
return;
}
// TODO (sorge): Intervals after the Bra-Ket heuristic.
}
/**
* Classifies content in the extension part of a set. Only works if we have
* assured that a set is indeed and extended set.
* @param set A semantic node representing an extended set.
*/
private setExtension_(set: SemanticNode) {
let extender = set.childNodes[0].childNodes[0];
if (extender && extender.type === SemanticType.INFIXOP &&
extender.contentNodes.length === 1 &&
SemanticPred.isMembership(extender.contentNodes[0])) {
extender.addAnnotation('set', 'intensional');
extender.contentNodes[0].addAnnotation('set', 'intensional');
}
}
/**
* Combines sequences of punctuated expressions in a list of nodes.
* @param nodes The list of nodes.
* @return The new list of nodes.
*/
private getPunctuationInRow_(nodes: SemanticNode[]): SemanticNode[] {
// For now we just make a punctuation node with a particular role. This is
// similar to an mrow. The only exception are ellipses, which we assume to
// be in lieu of identifiers. In addition we keep the single punctuation
// nodes as content.
if (nodes.length <= 1) {
return nodes;
}
let allowedType = (x: SemanticNode) => {
let type = x.type;
return type === 'punctuation' || type === 'text' || type === 'operator' ||
type === 'relation';
};
// Partition with improved ellipses handling.
let partition = SemanticUtil.partitionNodes(nodes, function(x) {
if (!SemanticPred.isPunctuation(x)) {
return false;
}
if (SemanticPred.isPunctuation(x) &&
!SemanticPred.isRole(x, SemanticRole.ELLIPSIS)) {
return true;
}
let index = nodes.indexOf(x);
if (index === 0) {
if (nodes[1] && allowedType(nodes[1])) {
return false;
}
return true;
}
// We now know the previous element exists
let prev = nodes[index - 1];
if (index === nodes.length - 1) {
if (allowedType(prev)) {
return false;
}
return true;
}
// We now know the next element exists
let next = nodes[index + 1];
if (allowedType(prev) && allowedType(next)) {
return false;
}
return true;
});
if (partition.rel.length === 0) {
return nodes;
}
let newNodes = [];
let firstComp = partition.comp.shift();
if (firstComp.length > 0) {
newNodes.push(SemanticProcessor.getInstance().row(firstComp));
}
let relCounter = 0;
while (partition.comp.length > 0) {
newNodes.push(partition.rel[relCounter++]);
firstComp = partition.comp.shift();
if (firstComp.length > 0) {
newNodes.push(SemanticProcessor.getInstance().row(firstComp));
}
}
return [SemanticProcessor.getInstance().punctuatedNode_(
newNodes, partition.rel)];
}
// TODO: Refine roles to reflect same roles. Find sequences of punctuation
// elements and separate those out or at least rewrite ellipses.
/**
* Create a punctuated node.
* @param nodes List of all nodes separated
* by punctuations.
* @param punctuations List of all separating
* punctations. Observe that punctations is a subset of nodes.
*/
private punctuatedNode_(nodes: SemanticNode[], punctuations: SemanticNode[]):
SemanticNode {
let newNode = SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.PUNCTUATED, nodes, punctuations);
if (punctuations.length === nodes.length) {
let firstRole = punctuations[0].role;
if (firstRole !== SemanticRole.UNKNOWN &&
punctuations.every(function(punct) {
return punct.role === firstRole;
})) {
newNode.role = firstRole;
return newNode;
}
}
if (SemanticPred.singlePunctAtPosition(nodes, punctuations, 0)) {
newNode.role = SemanticRole.STARTPUNCT;
} else if (SemanticPred.singlePunctAtPosition(
nodes, punctuations, nodes.length - 1)) {
newNode.role = SemanticRole.ENDPUNCT;
} else if (punctuations.every(
x => SemanticPred.isRole(x, SemanticRole.DUMMY))) {
newNode.role = SemanticRole.TEXT;
} else if (punctuations.every(
x => SemanticPred.isRole(x, SemanticRole.SPACE))) {
newNode.role = SemanticRole.SPACE;
} else {
newNode.role = SemanticRole.SEQUENCE;
}
return newNode;
}
/**
* Create an dummy punctuated node.
* @param children The child nodes to be
* separated by invisible comma.
* @return The new node.
*/
private dummyNode_(children: SemanticNode[]): SemanticNode {
let commata =
SemanticProcessor.getInstance().factory_.makeMultipleContentNodes(
children.length - 1, SemanticAttr.invisibleComma());
commata.forEach(function(comma) {
comma.role = SemanticRole.DUMMY;
});
return SemanticProcessor.getInstance().punctuatedNode_(children, commata);
}
/**
* Checks if a node is legal accent in a stacked node and sets the accent role
* wrt. to the parent type.
* @param node The semantic node.
* @param type The semantic type of the parent node.
* @return True if node is a legal accent.
*/
private accentRole_(node: SemanticNode, type: SemanticType): boolean {
if (!SemanticPred.isAccent(node)) {
return false;
}
// We save the original role of the node as accent annotation.
let content = node.textContent;
let role = SemanticAttr.lookupSecondary('bar', content) ||
SemanticAttr.lookupSecondary('tilde', content) || node.role;
node.role = type === SemanticType.UNDERSCORE ?
SemanticRole.UNDERACCENT :
SemanticRole.OVERACCENT;
node.addAnnotation('accent', role);
return true;
}
/**
* Creates an accent style node or sub/superscript depending on the given
* type.
* @param center The inner center node.
* @param children All children, where center is first node.
* @param type The new node type.
* @param length The exact length for the given type. This is important
* in case not enough children exist, then the type has to be changed.
* @param accent Is this an accent node?
* @return The newly created node.
*/
private accentNode_(
center: SemanticNode, children: SemanticNode[], type: SemanticType,
length: number, accent: boolean): SemanticNode {
children = children.slice(0, length + 1);
let child1 = (children[1] as SemanticNode);
let child2 = children[2];
let innerNode: SemanticNode;
if (!accent && child2) {
// For indexed we only have to nest if we have two children.
innerNode = SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.SUBSCRIPT, [center, child1], []);
innerNode.role = SemanticRole.SUBSUP;
children = [innerNode, child2];
type = SemanticType.SUPERSCRIPT;
}
if (accent) {
// Check if we have stacked or accented expressions (or mix).
let underAccent = SemanticProcessor.getInstance().accentRole_(child1, type);
if (child2) {
let overAccent = SemanticProcessor.getInstance().accentRole_(child2, SemanticType.OVERSCORE);
if (overAccent && !underAccent) {
innerNode = SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.OVERSCORE, [center, child2], []);
children = [innerNode, child1];
type = SemanticType.UNDERSCORE;
} else {
innerNode = SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.UNDERSCORE, [center, child1], []);
children = [innerNode, child2];
type = SemanticType.OVERSCORE;
}
innerNode.role = SemanticRole.UNDEROVER;
}
}
return SemanticProcessor.getInstance().makeLimitNode_(center, children, innerNode, type);
}
/**
* Creates the actual limit node.
* @param center The inner center node.
* @param children All children, where center is
* first node.
* @param innerNode The innermost node if it
* exists.
* @param type The new node type.
* @return The newly created limit node.
*/
private makeLimitNode_(
center: SemanticNode, children: SemanticNode[],
innerNode: SemanticNode|undefined,
type: SemanticType): SemanticNode {
// These two conditions implement the limitboth heuristic, which works
// before a new node is created.
if (type === SemanticType.LIMUPPER &&
center.type === SemanticType.LIMLOWER) {
center.childNodes.push(children[1]);
children[1].parent = center;
center.type = SemanticType.LIMBOTH;
return center;
}
if (type === SemanticType.LIMLOWER &&
center.type === SemanticType.LIMUPPER) {
center.childNodes.splice(1, -1, children[1]);
children[1].parent = center;
center.type = SemanticType.LIMBOTH;
return center;
}
let newNode = SemanticProcessor.getInstance().factory_.makeBranchNode(
type, children, []);
let embellished = SemanticPred.isEmbellished(center);
if (innerNode) {
innerNode.embellished = embellished;
}
newNode.embellished = embellished;
newNode.role = center.role;
return newNode;
}
/**
* Recursive method to accumulate function expressions.
*
* The idea is to process functions in a row from left to right combining them
* with their arguments. Thereby we take the notion of a function rather
* broadly as a functional expressions that consists of a prefix and some
* arguments. In particular we distinguish four types of functional
* expressions:
* - integral: Integral expression.
* - bigop: A big operator expression like a sum.
* - prefix: A well defined prefix function such as sin, cos or a limit
* functions like lim, max.
* - simple: An expression consisting of letters that are potentially a
* function symbol. If we have an explicit function application symbol
* following the expression we turn into a prefix function.
* Otherwise we decide heuristically if we could have a function application.
* @param restNodes The remainder list of
* nodes.
* @param opt_result The result node list.
* @return The fully processed list.
*/
private getFunctionsInRow_(
restNodes: SemanticNode[], opt_result?: SemanticNode[]): SemanticNode[] {
let result = opt_result || [];
// Base case.
if (restNodes.length === 0) {
return result;
}
let firstNode = (restNodes.shift() as SemanticNode);
let heuristic = SemanticProcessor.classifyFunction_(firstNode, restNodes);
// First node is not a function node.
if (!heuristic) {
result.push(firstNode);
return SemanticProcessor.getInstance().getFunctionsInRow_(
restNodes, result);
}
// Combine functions in the rest of the row.
let processedRest =
SemanticProcessor.getInstance().getFunctionsInRow_(restNodes, []);
let newRest = SemanticProcessor.getInstance().getFunctionArgs_(
firstNode, processedRest, heuristic);
return result.concat(newRest);
}
/**
* Computes the arguments for a function from a list of nodes depending on the
* given heuristic.
* @param func A function node.
* @param rest List of nodes to choose
* arguments from.
* @param heuristic The heuristic to follow.
* @return The function and the remainder of
* the rest list.
*/
private getFunctionArgs_(func: SemanticNode, rest: SemanticNode[],
heuristic: string): SemanticNode[] {
let partition;
let arg;
switch (heuristic) {
case 'integral':
let components = SemanticProcessor.getInstance().getIntegralArgs_(rest);
if (!components.intvar && !components.integrand.length) {
components.rest.unshift(func);
return components.rest;
}
let integrand =
SemanticProcessor.getInstance().row(components.integrand);
let funcNode = SemanticProcessor.getInstance().integralNode_(
func, integrand, components.intvar);
components.rest.unshift(funcNode);
return components.rest;
break;
case 'prefix':
if (rest[0] && rest[0].type === SemanticType.FENCED) {
// TODO: (MS2.3|simons) This needs to be made more robust! Currently
// we
// reset to eliminate sets. Once we include bra-ket heuristics,
// this might be incorrect.
let arg = rest.shift();
if (!SemanticPred.isNeutralFence(arg)) {
arg.role = SemanticRole.LEFTRIGHT;
}
funcNode = SemanticProcessor.getInstance().functionNode_(
func, (arg as SemanticNode));
rest.unshift(funcNode);
return rest;
}
partition = SemanticUtil.sliceNodes(
rest, SemanticPred.isPrefixFunctionBoundary);
if (!partition.head.length) {
if (!partition.div ||
!SemanticPred.isType(partition.div, SemanticType.APPL)) {
rest.unshift(func);
return rest;
}
arg = partition.div;
} else {
arg = SemanticProcessor.getInstance().row(partition.head);
if (partition.div) {
partition.tail.unshift(partition.div);
}
}
// TODO: (simons) If we have a prefix/simple function or implicit with
// prefix/simple function children only (i.e., a function
// composition) then we combine them via a function
// composition. Function composition is currently implicit, but we
// might want to remember this a bit better.
funcNode = SemanticProcessor.getInstance().functionNode_(func, arg);
partition.tail.unshift(funcNode);
return partition.tail;
break;
case 'bigop':
partition =
SemanticUtil.sliceNodes(rest, SemanticPred.isBigOpBoundary);
if (!partition.head.length) {
rest.unshift(func);
return rest;
}
arg = SemanticProcessor.getInstance().row(partition.head);
funcNode = SemanticProcessor.getInstance().bigOpNode_(func, arg);
if (partition.div) {
partition.tail.unshift(partition.div);
}
partition.tail.unshift(funcNode);
return partition.tail;
break;
case 'simple':
default:
if (rest.length === 0) {
return [func];
}
let firstArg = rest[0];
if (firstArg.type === SemanticType.FENCED &&
!SemanticPred.isNeutralFence(firstArg) &&
SemanticPred.isSimpleFunctionScope(firstArg)) {
// TODO: (MS2.3|simons) This needs to be made more robust! Currently
// we
// reset to eliminate sets. Once we include bra-ket heuristics,
// this might be incorrect.
firstArg.role = SemanticRole.LEFTRIGHT;
SemanticProcessor.propagateFunctionRole_(
func, SemanticRole.SIMPLEFUNC);
funcNode = SemanticProcessor.getInstance().functionNode_(
func, (rest.shift() as SemanticNode));
rest.unshift(funcNode);
return rest;
}
rest.unshift(func);
return rest;
break;
}
}
/**
* Tail recursive function to obtain integral arguments.
* @param nodes List of nodes to take
* arguments from.
* @param opt_args List of integral arguments.
* @return {{integrand: !Array.<sre.SemanticNode>,
* intvar: sre.SemanticNode,
* rest: !Array.<sre.SemanticNode>}} Result split into integrand, integral
* variable and the remaining elements.
*/
private getIntegralArgs_(nodes: SemanticNode[], opt_args?: SemanticNode[]):
{integrand: SemanticNode[], intvar: SemanticNode, rest: SemanticNode[]} {
let args = opt_args || [];
if (nodes.length === 0) {
return {integrand: args, intvar: null, rest: nodes};
}
let firstNode = nodes[0];
if (SemanticPred.isGeneralFunctionBoundary(firstNode)) {
return {integrand: args, intvar: null, rest: nodes};
}
if (SemanticPred.isIntegralDxBoundarySingle(firstNode)) {
firstNode.role = SemanticRole.INTEGRAL;
return {integrand: args, intvar: firstNode, rest: nodes.slice(1)};
}
if (nodes[1] && SemanticPred.isIntegralDxBoundary(firstNode, nodes[1])) {
let intvar = SemanticProcessor.getInstance().prefixNode_(
(nodes[1] as SemanticNode), [firstNode]);
intvar.role = SemanticRole.INTEGRAL;
return {integrand: args, intvar: intvar, rest: nodes.slice(2)};
}
args.push(nodes.shift());
return SemanticProcessor.getInstance().getIntegralArgs_(nodes, args);
}
/**
* Create a function node.
* @param func The function operator.
* @param arg The argument.
* @return The new function node.
*/
private functionNode_(func: SemanticNode, arg: SemanticNode): SemanticNode {
let applNode = SemanticProcessor.getInstance().factory_.makeContentNode(
SemanticAttr.functionApplication());
let appl = SemanticProcessor.getInstance().funcAppls[func.id];
if (appl) {
// TODO: Work out why we cannot just take appl.
applNode.mathmlTree = appl.mathmlTree;
applNode.mathml = appl.mathml;
applNode.annotation = appl.annotation;
applNode.attributes = appl.attributes;
delete SemanticProcessor.getInstance().funcAppls[func.id];
}
applNode.type = SemanticType.PUNCTUATION;
applNode.role = SemanticRole.APPLICATION;
let funcop = SemanticProcessor.getFunctionOp_(func, function(node) {
return SemanticPred.isType(node, SemanticType.FUNCTION) ||
SemanticPred.isType(node, SemanticType.IDENTIFIER) &&
SemanticPred.isRole(node, SemanticRole.SIMPLEFUNC);
});
return SemanticProcessor.getInstance().functionalNode_(
SemanticType.APPL, [func, arg], funcop, [applNode]);
}
/**
* Create a big operator node.
* @param bigOp The big operator.
* @param arg The argument.
* @return The new big operator node.
*/
private bigOpNode_(bigOp: SemanticNode, arg: SemanticNode): SemanticNode {
let largeop = SemanticProcessor.getFunctionOp_(
bigOp, x => SemanticPred.isType(x, SemanticType.LARGEOP));
return SemanticProcessor.getInstance().functionalNode_(
SemanticType.BIGOP, [bigOp, arg], largeop, []);
}
/**
* Create an integral node. It has three children: integral, integrand and
* integration variable. The latter two can be omitted.
* @param integral The integral operator.
* @param integrand The integrand.
* @param intvar The integral variable.
* @return The new integral node.
*/
private integralNode_(
integral: SemanticNode, integrand: SemanticNode,
intvar: SemanticNode): SemanticNode {
integrand =
integrand || SemanticProcessor.getInstance().factory_.makeEmptyNode();
intvar = intvar || SemanticProcessor.getInstance().factory_.makeEmptyNode();
let largeop = SemanticProcessor.getFunctionOp_(
integral, x => SemanticPred.isType(x, SemanticType.LARGEOP));
return SemanticProcessor.getInstance().functionalNode_(
SemanticType.INTEGRAL, [integral, integrand, intvar], largeop, []);
}
/**
* Creates a functional node, i.e., integral, bigop, simple function. If the
* operator is given, it takes care that th eoperator is contained as a
* content node, and that the original parent pointer of the operator node is
* retained.
*
* Example: Function application sin^2(x). The pointer from sin should remain
* to the superscript node, although sin is given as a content node.
* @param type The type of the node.
* @param children The children of the
* functional node. The first child must be given is understood to be the
* functional operator.
* @param operator The innermost operator (e.g., in the
* case of embellished functions or operators with limits).
* @param content The list of additional
* content nodes.
* @return The new functional node.
*/
private functionalNode_(
type: SemanticType, children: SemanticNode[],
operator: SemanticNode|null, content: SemanticNode[]): SemanticNode {
let funcop = children[0];
let oldParent: SemanticNode;
if (operator) {
oldParent = operator.parent;
content.push(operator);
}
let newNode = SemanticProcessor.getInstance().factory_.makeBranchNode(
type, children, content);
newNode.role = funcop.role;
if (oldParent) {
operator.parent = oldParent;
}
return newNode;
}
/**
* Creates a fraction node with the appropriate role.
* @param denom The denominator node.
* @param enume The enumerator node.
* @return The new fraction node.
*/
private fractionNode_(denom: SemanticNode, enume: SemanticNode):
SemanticNode {
let newNode = SemanticProcessor.getInstance().factory_.makeBranchNode(
SemanticType.FRACTION, [denom, enume], []);
newNode.role = newNode.childNodes.every(function(x) {
return SemanticPred.isType(x, SemanticType.NUMBER) &&
SemanticPred.isRole(x, SemanticRole.INTEGER);
}) ?
SemanticRole.VULGAR :
newNode.childNodes.every(SemanticPred.isPureUnit) ?
SemanticRole.UNIT :
SemanticRole.DIVISION;
return SemanticHeuristics.run('propagateSimpleFunction', newNode) as SemanticNode;
}
/**
* Creates a script node for a tensor, which is effectively a dummy
* punctuation.
* @param nodes A list of unprocessed nodes for
* that script.
* @param role The role of the dummy node.
* @param opt_noSingle Flag indicating whether role should be set
* for a single node.
* @return The semantic tensor node.
*/
private scriptNode_(
nodes: SemanticNode[], role: SemanticRole,
opt_noSingle?: boolean): SemanticNode {
let newNode: SemanticNode;
switch (nodes.length) {
case 0:
newNode = SemanticProcessor.getInstance().factory_.makeEmptyNode();
break;
case 1:
newNode = nodes[0];
if (opt_noSingle) {
return newNode;
}
break;
default:
newNode = SemanticProcessor.getInstance().dummyNode_(nodes);
}
newNode.role = role;
return newNode;
}
/**
* Searches the given row of elements for first element with the given
* semantic key or key/value pair if a value is not null. Ignores space
* elements and descents at most 3 levels.
* @param nodes A node list.
* @param semantic A semantic key.
* @param level The maximum level to search.
* @param value Optionally the semantic value.
* @return The first matching element in the row.
*/
private findNestedRow_(
nodes: Element[], semantic: string, level: number,
value: string|undefined): Element {
if (level > 3) {
return null;
}
for (let i = 0, node; node = nodes[i]; i++) {
let tag = DomUtil.tagName(node);
if (tag !== 'MSPACE') {
if (tag === 'MROW') {
return SemanticProcessor.getInstance().findNestedRow_(
DomUtil.toArray(node.childNodes), semantic, level + 1, value);
}
if (SemanticProcessor.findSemantics(node, semantic, value)) {
return node;
}
}
}
return null;
}
} | the_stack |
import * as React from 'react';
import {
Animated,
View,
Modal,
Easing,
LayoutChangeEvent,
BackHandler,
KeyboardAvoidingView,
Keyboard,
ScrollView,
FlatList,
SectionList,
Platform,
StatusBar,
KeyboardEvent,
NativeSyntheticEvent,
NativeScrollEvent,
StyleSheet,
KeyboardAvoidingViewProps,
ViewStyle,
NativeEventSubscription,
EmitterSubscription,
} from 'react-native';
import {
PanGestureHandler,
NativeViewGestureHandler,
State,
TapGestureHandler,
PanGestureHandlerStateChangeEvent,
TapGestureHandlerStateChangeEvent,
} from 'react-native-gesture-handler';
import { IProps, TOpen, TClose, TStyle, IHandles, TPosition } from './options';
import { useDimensions } from './utils/use-dimensions';
import { getSpringConfig } from './utils/get-spring-config';
import { isIphoneX, isIos, isAndroid, isBelowRN65 } from './utils/devices';
import { invariant } from './utils/invariant';
import { composeRefs } from './utils/compose-refs';
import s from './styles';
const AnimatedKeyboardAvoidingView = Animated.createAnimatedComponent(KeyboardAvoidingView);
/**
* When scrolling, it happens than beginScrollYValue is not always equal to 0 (top of the ScrollView).
* Since we use this to trigger the swipe down gesture animation, we allow a small threshold to
* not dismiss Modalize when we are using the ScrollView and we don't want to dismiss.
*/
const SCROLL_THRESHOLD = -4;
const USE_NATIVE_DRIVER = true;
const ACTIVATED = 20;
const PAN_DURATION = 150;
const ModalizeBase = (
{
// Refs
contentRef,
// Renderers
children,
scrollViewProps,
flatListProps,
sectionListProps,
customRenderer,
// Styles
rootStyle,
modalStyle,
handleStyle,
overlayStyle,
childrenStyle,
// Layout
snapPoint,
modalHeight,
modalTopOffset = Platform.select({
ios: 0,
android: StatusBar.currentHeight || 0,
default: 0,
}),
alwaysOpen,
adjustToContentHeight = false,
// Options
handlePosition = 'outside',
disableScrollIfPossible = true,
avoidKeyboardLikeIOS = Platform.select({
ios: true,
android: false,
default: true,
}),
keyboardAvoidingBehavior = 'padding',
keyboardAvoidingOffset,
panGestureEnabled = true,
panGestureComponentEnabled = false,
tapGestureEnabled = true,
closeOnOverlayTap = true,
closeSnapPointStraightEnabled = true,
// Animations
openAnimationConfig = {
timing: { duration: 240, easing: Easing.ease },
spring: { speed: 14, bounciness: 4 },
},
closeAnimationConfig = {
timing: { duration: 240, easing: Easing.ease },
},
dragToss = 0.18,
threshold = 120,
velocity = 2800,
panGestureAnimatedValue,
useNativeDriver = true,
// Elements visibilities
withReactModal = false,
reactModalProps,
withHandle = true,
withOverlay = true,
// Additional components
HeaderComponent,
FooterComponent,
FloatingComponent,
// Callbacks
onOpen,
onOpened,
onClose,
onClosed,
onBackButtonPress,
onPositionChange,
onOverlayPress,
onLayout,
}: IProps,
ref: React.Ref<React.ReactNode>,
): JSX.Element | null => {
const { height: screenHeight } = useDimensions();
const isHandleOutside = handlePosition === 'outside';
const handleHeight = withHandle ? 20 : isHandleOutside ? 35 : 20;
const fullHeight = screenHeight - modalTopOffset;
const computedHeight = fullHeight - handleHeight - (isIphoneX ? 34 : 0);
const endHeight = modalHeight || computedHeight;
const adjustValue = adjustToContentHeight ? undefined : endHeight;
const snaps = snapPoint ? [0, endHeight - snapPoint, endHeight] : [0, endHeight];
const [modalHeightValue, setModalHeightValue] = React.useState(adjustValue);
const [lastSnap, setLastSnap] = React.useState(snapPoint ? endHeight - snapPoint : 0);
const [isVisible, setIsVisible] = React.useState(false);
const [showContent, setShowContent] = React.useState(true);
const [enableBounces, setEnableBounces] = React.useState(true);
const [keyboardToggle, setKeyboardToggle] = React.useState(false);
const [keyboardHeight, setKeyboardHeight] = React.useState(0);
const [disableScroll, setDisableScroll] = React.useState(
alwaysOpen || snapPoint ? true : undefined,
);
const [beginScrollYValue, setBeginScrollYValue] = React.useState(0);
const [modalPosition, setModalPosition] = React.useState<TPosition>('initial');
const [cancelClose, setCancelClose] = React.useState(false);
const [layouts, setLayouts] = React.useState<Map<string, number>>(new Map());
const cancelTranslateY = React.useRef(new Animated.Value(1)).current; // 1 by default to have the translateY animation running
const componentTranslateY = React.useRef(new Animated.Value(0)).current;
const overlay = React.useRef(new Animated.Value(0)).current;
const beginScrollY = React.useRef(new Animated.Value(0)).current;
const dragY = React.useRef(new Animated.Value(0)).current;
const translateY = React.useRef(new Animated.Value(screenHeight)).current;
const reverseBeginScrollY = React.useRef(Animated.multiply(new Animated.Value(-1), beginScrollY))
.current;
const tapGestureModalizeRef = React.useRef<TapGestureHandler>(null);
const panGestureChildrenRef = React.useRef<PanGestureHandler>(null);
const nativeViewChildrenRef = React.useRef<NativeViewGestureHandler>(null);
const contentViewRef = React.useRef<ScrollView | FlatList<any> | SectionList<any>>(null);
const tapGestureOverlayRef = React.useRef<TapGestureHandler>(null);
const backButtonListenerRef = React.useRef<NativeEventSubscription>(null);
// We diff and get the negative value only. It sometimes go above 0
// (e.g. 1.5) and creates the flickering on Modalize for a ms
const diffClamp = Animated.diffClamp(reverseBeginScrollY, -screenHeight, 0);
const componentDragEnabled = (componentTranslateY as any)._value === 1;
// When we have a scrolling happening in the ScrollView, we don't want to translate
// the modal down. We either multiply by 0 to cancel the animation, or 1 to proceed.
const dragValue = Animated.add(
Animated.multiply(dragY, componentDragEnabled ? 1 : cancelTranslateY),
diffClamp,
);
const value = Animated.add(
Animated.multiply(translateY, componentDragEnabled ? 1 : cancelTranslateY),
dragValue,
);
let willCloseModalize = false;
const handleBackPress = (): boolean => {
if (alwaysOpen) {
return false;
}
if (onBackButtonPress) {
return onBackButtonPress();
} else {
handleClose();
}
return true;
};
const handleKeyboardShow = (event: KeyboardEvent): void => {
const { height } = event.endCoordinates;
setKeyboardToggle(true);
setKeyboardHeight(height);
};
const handleKeyboardHide = (): void => {
setKeyboardToggle(false);
setKeyboardHeight(0);
};
const handleAnimateOpen = (
alwaysOpenValue: number | undefined,
dest: TOpen = 'default',
): void => {
const { timing, spring } = openAnimationConfig;
(backButtonListenerRef as any).current = BackHandler.addEventListener(
'hardwareBackPress',
handleBackPress,
);
let toValue = 0;
let toPanValue = 0;
let newPosition: TPosition;
if (dest === 'top') {
toValue = 0;
} else if (alwaysOpenValue) {
toValue = (modalHeightValue || 0) - alwaysOpenValue;
} else if (snapPoint) {
toValue = (modalHeightValue || 0) - snapPoint;
}
if (panGestureAnimatedValue && (alwaysOpenValue || snapPoint)) {
toPanValue = 0;
} else if (
panGestureAnimatedValue &&
!alwaysOpenValue &&
(dest === 'top' || dest === 'default')
) {
toPanValue = 1;
}
setIsVisible(true);
setShowContent(true);
if ((alwaysOpenValue && dest !== 'top') || (snapPoint && dest === 'default')) {
newPosition = 'initial';
} else {
newPosition = 'top';
}
Animated.parallel([
Animated.timing(overlay, {
toValue: alwaysOpenValue && dest === 'default' ? 0 : 1,
duration: timing.duration,
easing: Easing.ease,
useNativeDriver: USE_NATIVE_DRIVER,
}),
panGestureAnimatedValue
? Animated.timing(panGestureAnimatedValue, {
toValue: toPanValue,
duration: PAN_DURATION,
easing: Easing.ease,
useNativeDriver,
})
: Animated.delay(0),
spring
? Animated.spring(translateY, {
...getSpringConfig(spring),
toValue,
useNativeDriver: USE_NATIVE_DRIVER,
})
: Animated.timing(translateY, {
toValue,
duration: timing.duration,
easing: timing.easing,
useNativeDriver: USE_NATIVE_DRIVER,
}),
]).start(() => {
if (onOpened) {
onOpened();
}
setModalPosition(newPosition);
if (onPositionChange) {
onPositionChange(newPosition);
}
});
};
const handleAnimateClose = (dest: TClose = 'default', callback?: () => void): void => {
const { timing, spring } = closeAnimationConfig;
const lastSnapValue = snapPoint ? snaps[1] : 80;
const toInitialAlwaysOpen = dest === 'alwaysOpen' && Boolean(alwaysOpen);
const toValue =
toInitialAlwaysOpen && alwaysOpen ? (modalHeightValue || 0) - alwaysOpen : screenHeight;
backButtonListenerRef.current?.remove();
cancelTranslateY.setValue(1);
setBeginScrollYValue(0);
beginScrollY.setValue(0);
Animated.parallel([
Animated.timing(overlay, {
toValue: 0,
duration: timing.duration,
easing: Easing.ease,
useNativeDriver: USE_NATIVE_DRIVER,
}),
panGestureAnimatedValue
? Animated.timing(panGestureAnimatedValue, {
toValue: 0,
duration: PAN_DURATION,
easing: Easing.ease,
useNativeDriver,
})
: Animated.delay(0),
spring
? Animated.spring(translateY, {
...getSpringConfig(spring),
toValue,
useNativeDriver: USE_NATIVE_DRIVER,
})
: Animated.timing(translateY, {
duration: timing.duration,
easing: Easing.out(Easing.ease),
toValue,
useNativeDriver: USE_NATIVE_DRIVER,
}),
]).start(() => {
if (onClosed) {
onClosed();
}
if (callback) {
callback();
}
if (alwaysOpen && dest === 'alwaysOpen' && onPositionChange) {
onPositionChange('initial');
}
if (alwaysOpen && dest === 'alwaysOpen') {
setModalPosition('initial');
}
setShowContent(toInitialAlwaysOpen);
translateY.setValue(toValue);
dragY.setValue(0);
willCloseModalize = false;
setLastSnap(lastSnapValue);
setIsVisible(toInitialAlwaysOpen);
});
};
const handleModalizeContentLayout = ({ nativeEvent: { layout } }: LayoutChangeEvent): void => {
const value = Math.min(
layout.height + (!adjustToContentHeight || keyboardHeight ? layout.y : 0),
endHeight -
Platform.select({
ios: 0,
android: keyboardHeight,
default: 0,
}),
);
setModalHeightValue(value);
};
const handleBaseLayout = (
component: 'content' | 'header' | 'footer' | 'floating',
height: number,
): void => {
setLayouts(new Map(layouts.set(component, height)));
const max = Array.from(layouts).reduce((acc, cur) => acc + cur?.[1], 0);
const maxFixed = +max.toFixed(3);
const endHeightFixed = +endHeight.toFixed(3);
const shorterHeight = maxFixed < endHeightFixed;
setDisableScroll(shorterHeight && disableScrollIfPossible);
};
const handleContentLayout = ({ nativeEvent }: LayoutChangeEvent): void => {
if (onLayout) {
onLayout(nativeEvent);
}
if (alwaysOpen && adjustToContentHeight) {
const { height } = nativeEvent.layout;
return setModalHeightValue(height);
}
// We don't want to disable the scroll if we are not using adjustToContentHeight props
if (!adjustToContentHeight) {
return;
}
handleBaseLayout('content', nativeEvent.layout.height);
};
const handleComponentLayout = (
{ nativeEvent }: LayoutChangeEvent,
name: 'header' | 'footer' | 'floating',
absolute: boolean,
): void => {
/**
* We don't want to disable the scroll if we are not using adjustToContentHeight props.
* Also, if the component is in absolute positioning we don't want to take in
* account its dimensions, so we just skip.
*/
if (!adjustToContentHeight || absolute) {
return;
}
handleBaseLayout(name, nativeEvent.layout.height);
};
const handleClose = (dest?: TClose, callback?: () => void): void => {
if (onClose) {
onClose();
}
handleAnimateClose(dest, callback);
};
const handleChildren = (
{ nativeEvent }: PanGestureHandlerStateChangeEvent,
type?: 'component' | 'children',
): void => {
const { timing } = closeAnimationConfig;
const { velocityY, translationY } = nativeEvent;
const negativeReverseScroll =
modalPosition === 'top' &&
beginScrollYValue >= (snapPoint ? 0 : SCROLL_THRESHOLD) &&
translationY < 0;
const thresholdProps = translationY > threshold && beginScrollYValue === 0;
const closeThreshold = velocity
? (beginScrollYValue <= 20 && velocityY >= velocity) || thresholdProps
: thresholdProps;
let enableBouncesValue = true;
// We make sure to reset the value if we are dragging from the children
if (type !== 'component' && (cancelTranslateY as any)._value === 0) {
componentTranslateY.setValue(0);
}
/*
* When the pan gesture began we check the position of the ScrollView "cursor".
* We cancel the translation animation if the ScrollView is not scrolled to the top
*/
if (nativeEvent.oldState === State.BEGAN) {
setCancelClose(false);
if (
!closeSnapPointStraightEnabled && snapPoint
? beginScrollYValue > 0
: beginScrollYValue > 0 || negativeReverseScroll
) {
setCancelClose(true);
translateY.setValue(0);
dragY.setValue(0);
cancelTranslateY.setValue(0);
enableBouncesValue = true;
} else {
cancelTranslateY.setValue(1);
enableBouncesValue = false;
if (!tapGestureEnabled) {
setDisableScroll(
(Boolean(snapPoint) || Boolean(alwaysOpen)) && modalPosition === 'initial',
);
}
}
}
setEnableBounces(
isAndroid
? false
: alwaysOpen
? beginScrollYValue > 0 || translationY < 0
: enableBouncesValue,
);
if (nativeEvent.oldState === State.ACTIVE) {
const toValue = translationY - beginScrollYValue;
let destSnapPoint = 0;
if (snapPoint || alwaysOpen) {
const endOffsetY = lastSnap + toValue + dragToss * velocityY;
/**
* snapPoint and alwaysOpen use both an array of points to define the first open state and the final state.
*/
snaps.forEach((snap: number) => {
const distFromSnap = Math.abs(snap - endOffsetY);
const diffPoint = Math.abs(destSnapPoint - endOffsetY);
// For snapPoint
if (distFromSnap < diffPoint && !alwaysOpen) {
if (closeSnapPointStraightEnabled) {
if (modalPosition === 'initial' && negativeReverseScroll) {
destSnapPoint = snap;
willCloseModalize = false;
}
if (snap === endHeight) {
destSnapPoint = snap;
willCloseModalize = true;
handleClose();
}
} else {
destSnapPoint = snap;
willCloseModalize = false;
if (snap === endHeight) {
willCloseModalize = true;
handleClose();
}
}
}
// For alwaysOpen props
if (distFromSnap < diffPoint && alwaysOpen && beginScrollYValue <= 0) {
destSnapPoint = (modalHeightValue || 0) - alwaysOpen;
willCloseModalize = false;
}
});
} else if (closeThreshold && !alwaysOpen && !cancelClose) {
willCloseModalize = true;
handleClose();
}
if (willCloseModalize) {
return;
}
setLastSnap(destSnapPoint);
translateY.extractOffset();
translateY.setValue(toValue);
translateY.flattenOffset();
dragY.setValue(0);
if (alwaysOpen) {
Animated.timing(overlay, {
toValue: Number(destSnapPoint <= 0),
duration: timing.duration,
easing: Easing.ease,
useNativeDriver: USE_NATIVE_DRIVER,
}).start();
}
Animated.spring(translateY, {
tension: 50,
friction: 12,
velocity: velocityY,
toValue: destSnapPoint,
useNativeDriver: USE_NATIVE_DRIVER,
}).start();
if (beginScrollYValue <= 0) {
const modalPositionValue = destSnapPoint <= 0 ? 'top' : 'initial';
if (panGestureAnimatedValue) {
Animated.timing(panGestureAnimatedValue, {
toValue: Number(modalPositionValue === 'top'),
duration: PAN_DURATION,
easing: Easing.ease,
useNativeDriver,
}).start();
}
if (!adjustToContentHeight && modalPositionValue === 'top') {
setDisableScroll(false);
}
if (onPositionChange && modalPosition !== modalPositionValue) {
onPositionChange(modalPositionValue);
}
if (modalPosition !== modalPositionValue) {
setModalPosition(modalPositionValue);
}
}
}
};
const handleComponent = ({ nativeEvent }: PanGestureHandlerStateChangeEvent): void => {
// If we drag from the HeaderComponent/FooterComponent/FloatingComponent we allow the translation animation
if (nativeEvent.oldState === State.BEGAN) {
componentTranslateY.setValue(1);
beginScrollY.setValue(0);
}
handleChildren({ nativeEvent }, 'component');
};
const handleOverlay = ({ nativeEvent }: TapGestureHandlerStateChangeEvent): void => {
if (nativeEvent.oldState === State.ACTIVE && !willCloseModalize) {
if (onOverlayPress) {
onOverlayPress();
}
const dest = !!alwaysOpen ? 'alwaysOpen' : 'default';
handleClose(dest);
}
};
const handleGestureEvent = Animated.event([{ nativeEvent: { translationY: dragY } }], {
useNativeDriver: USE_NATIVE_DRIVER,
listener: ({ nativeEvent: { translationY } }: PanGestureHandlerStateChangeEvent) => {
if (panGestureAnimatedValue) {
const offset = alwaysOpen ?? snapPoint ?? 0;
const diff = Math.abs(translationY / (endHeight - offset));
const y = translationY <= 0 ? diff : 1 - diff;
let value: number;
if (modalPosition === 'initial' && translationY > 0) {
value = 0;
} else if (modalPosition === 'top' && translationY <= 0) {
value = 1;
} else {
value = y;
}
panGestureAnimatedValue.setValue(value);
}
},
});
const renderHandle = (): JSX.Element | null => {
const handleStyles: (TStyle | undefined)[] = [s.handle];
const shapeStyles: (TStyle | undefined)[] = [s.handle__shape, handleStyle];
if (!withHandle) {
return null;
}
if (!isHandleOutside) {
handleStyles.push(s.handleBottom);
shapeStyles.push(s.handle__shapeBottom, handleStyle);
}
return (
<PanGestureHandler
enabled={panGestureEnabled}
simultaneousHandlers={tapGestureModalizeRef}
shouldCancelWhenOutside={false}
onGestureEvent={handleGestureEvent}
onHandlerStateChange={handleComponent}
>
<Animated.View style={handleStyles}>
<View style={shapeStyles} />
</Animated.View>
</PanGestureHandler>
);
};
const renderElement = (Element: React.ReactNode): JSX.Element =>
typeof Element === 'function' ? Element() : Element;
const renderComponent = (
component: React.ReactNode,
name: 'header' | 'footer' | 'floating',
): JSX.Element | null => {
if (!component) {
return null;
}
const tag = renderElement(component);
/**
* Nesting Touchable/ScrollView components with RNGH PanGestureHandler cancels the inner events.
* Until a better solution lands in RNGH, I will disable the PanGestureHandler for Android only,
* so inner touchable/gestures are working from the custom components you can pass in.
*/
if (isAndroid && !panGestureComponentEnabled) {
return tag;
}
const obj: ViewStyle = StyleSheet.flatten(tag?.props?.style);
const absolute: boolean = obj?.position === 'absolute';
const zIndex: number | undefined = obj?.zIndex;
return (
<PanGestureHandler
enabled={panGestureEnabled}
shouldCancelWhenOutside={false}
onGestureEvent={handleGestureEvent}
onHandlerStateChange={handleComponent}
>
<Animated.View
style={{ zIndex }}
onLayout={(e: LayoutChangeEvent): void => handleComponentLayout(e, name, absolute)}
>
{tag}
</Animated.View>
</PanGestureHandler>
);
};
const renderContent = (): JSX.Element => {
const keyboardDismissMode:
| Animated.Value
| Animated.AnimatedInterpolation
| 'interactive'
| 'on-drag' = isIos ? 'interactive' : 'on-drag';
const passedOnProps = flatListProps ?? sectionListProps ?? scrollViewProps;
// We allow overwrites when the props (bounces, scrollEnabled) are set to false, when true we use Modalize's core behavior
const bounces =
passedOnProps?.bounces !== undefined && !passedOnProps?.bounces
? passedOnProps?.bounces
: enableBounces;
const scrollEnabled =
passedOnProps?.scrollEnabled !== undefined && !passedOnProps?.scrollEnabled
? passedOnProps?.scrollEnabled
: keyboardToggle || !disableScroll;
const scrollEventThrottle = passedOnProps?.scrollEventThrottle || 16;
const onScrollBeginDrag = passedOnProps?.onScrollBeginDrag as (
event: NativeSyntheticEvent<NativeScrollEvent>,
) => void | undefined;
const opts = {
ref: composeRefs(contentViewRef, contentRef) as React.RefObject<any>,
bounces,
onScrollBeginDrag: Animated.event([{ nativeEvent: { contentOffset: { y: beginScrollY } } }], {
useNativeDriver: USE_NATIVE_DRIVER,
listener: onScrollBeginDrag,
}),
scrollEventThrottle,
onLayout: handleContentLayout,
scrollEnabled,
keyboardDismissMode,
};
if (flatListProps) {
return <Animated.FlatList {...flatListProps} {...opts} />;
}
if (sectionListProps) {
return <Animated.SectionList {...sectionListProps} {...opts} />;
}
if (customRenderer) {
const tag = renderElement(customRenderer);
return React.cloneElement(tag, { ...opts });
}
return (
<Animated.ScrollView {...scrollViewProps} {...opts}>
{children}
</Animated.ScrollView>
);
};
const renderChildren = (): JSX.Element => {
const style = adjustToContentHeight ? s.content__adjustHeight : s.content__container;
return (
<PanGestureHandler
ref={panGestureChildrenRef}
enabled={panGestureEnabled}
simultaneousHandlers={[nativeViewChildrenRef, tapGestureModalizeRef]}
shouldCancelWhenOutside={false}
onGestureEvent={handleGestureEvent}
minDist={ACTIVATED}
activeOffsetY={ACTIVATED}
activeOffsetX={ACTIVATED}
onHandlerStateChange={handleChildren}
>
<Animated.View style={[style, childrenStyle]}>
<NativeViewGestureHandler
ref={nativeViewChildrenRef}
waitFor={tapGestureModalizeRef}
simultaneousHandlers={panGestureChildrenRef}
>
{renderContent()}
</NativeViewGestureHandler>
</Animated.View>
</PanGestureHandler>
);
};
const renderOverlay = (): JSX.Element => {
const pointerEvents =
alwaysOpen && (modalPosition === 'initial' || !modalPosition) ? 'box-none' : 'auto';
return (
<PanGestureHandler
enabled={panGestureEnabled}
simultaneousHandlers={tapGestureModalizeRef}
shouldCancelWhenOutside={false}
onGestureEvent={handleGestureEvent}
onHandlerStateChange={handleChildren}
>
<Animated.View style={s.overlay} pointerEvents={pointerEvents}>
{showContent && (
<TapGestureHandler
ref={tapGestureOverlayRef}
enabled={closeOnOverlayTap !== undefined ? closeOnOverlayTap : panGestureEnabled}
onHandlerStateChange={handleOverlay}
>
<Animated.View
style={[
s.overlay__background,
overlayStyle,
{
opacity: overlay.interpolate({
inputRange: [0, 1],
outputRange: [0, 1],
}),
},
]}
pointerEvents={pointerEvents}
/>
</TapGestureHandler>
)}
</Animated.View>
</PanGestureHandler>
);
};
React.useImperativeHandle(ref, () => ({
open(dest?: TOpen): void {
if (onOpen) {
onOpen();
}
handleAnimateOpen(alwaysOpen, dest);
},
close(dest?: TClose, callback?: () => void): void {
handleClose(dest, callback);
},
}));
React.useEffect(() => {
if (alwaysOpen && (modalHeightValue || adjustToContentHeight)) {
handleAnimateOpen(alwaysOpen);
}
}, [alwaysOpen, modalHeightValue]);
React.useEffect(() => {
invariant(
modalHeight && adjustToContentHeight,
`You can't use both 'modalHeight' and 'adjustToContentHeight' props at the same time. Only choose one of the two.`,
);
invariant(
(scrollViewProps || children) && flatListProps,
`You have defined 'flatListProps' along with 'scrollViewProps' or 'children' props. Remove 'scrollViewProps' or 'children' or 'flatListProps' to fix the error.`,
);
invariant(
(scrollViewProps || children) && sectionListProps,
`You have defined 'sectionListProps' along with 'scrollViewProps' or 'children' props. Remove 'scrollViewProps' or 'children' or 'sectionListProps' to fix the error.`,
);
}, [
modalHeight,
adjustToContentHeight,
scrollViewProps,
children,
flatListProps,
sectionListProps,
]);
React.useEffect(() => {
setModalHeightValue(adjustValue);
}, [adjustToContentHeight, modalHeight, screenHeight]);
React.useEffect(() => {
let keyboardShowListener: EmitterSubscription | null = null;
let keyboardHideListener: EmitterSubscription | null = null;
const beginScrollYListener = beginScrollY.addListener(({ value }) =>
setBeginScrollYValue(value),
);
if (isBelowRN65) {
Keyboard.addListener('keyboardDidShow', handleKeyboardShow);
Keyboard.addListener('keyboardDidHide', handleKeyboardHide);
} else {
keyboardShowListener = Keyboard.addListener('keyboardDidShow', handleKeyboardShow);
keyboardHideListener = Keyboard.addListener('keyboardDidHide', handleKeyboardHide);
}
return (): void => {
backButtonListenerRef.current?.remove();
beginScrollY.removeListener(beginScrollYListener);
if (isBelowRN65) {
Keyboard.removeListener('keyboardDidShow', handleKeyboardShow);
Keyboard.removeListener('keyboardDidHide', handleKeyboardHide);
} else {
keyboardShowListener?.remove();
keyboardHideListener?.remove();
}
};
}, []);
const keyboardAvoidingViewProps: Animated.AnimatedProps<KeyboardAvoidingViewProps> = {
keyboardVerticalOffset: keyboardAvoidingOffset,
behavior: keyboardAvoidingBehavior,
enabled: avoidKeyboardLikeIOS,
style: [
s.modalize__content,
modalStyle,
{
height: modalHeightValue,
maxHeight: endHeight,
transform: [
{
translateY: value.interpolate({
inputRange: [-40, 0, endHeight],
outputRange: [0, 0, endHeight],
extrapolate: 'clamp',
}),
},
],
},
],
};
if (!avoidKeyboardLikeIOS && !adjustToContentHeight) {
keyboardAvoidingViewProps.onLayout = handleModalizeContentLayout;
}
const renderModalize = (
<View
style={[s.modalize, rootStyle]}
pointerEvents={alwaysOpen || !withOverlay ? 'box-none' : 'auto'}
>
<TapGestureHandler
ref={tapGestureModalizeRef}
maxDurationMs={tapGestureEnabled ? 100000 : 50}
maxDeltaY={lastSnap}
enabled={panGestureEnabled}
>
<View style={s.modalize__wrapper} pointerEvents="box-none">
{showContent && (
<AnimatedKeyboardAvoidingView {...keyboardAvoidingViewProps}>
{renderHandle()}
{renderComponent(HeaderComponent, 'header')}
{renderChildren()}
{renderComponent(FooterComponent, 'footer')}
</AnimatedKeyboardAvoidingView>
)}
{withOverlay && renderOverlay()}
</View>
</TapGestureHandler>
{renderComponent(FloatingComponent, 'floating')}
</View>
);
const renderReactModal = (child: JSX.Element): JSX.Element => (
<Modal
{...reactModalProps}
supportedOrientations={['landscape', 'portrait', 'portrait-upside-down']}
onRequestClose={handleBackPress}
hardwareAccelerated={USE_NATIVE_DRIVER}
visible={isVisible}
transparent
>
{child}
</Modal>
);
if (!isVisible) {
return null;
}
if (withReactModal) {
return renderReactModal(renderModalize);
}
return renderModalize;
};
export type ModalizeProps = IProps;
export type Modalize = IHandles;
export const Modalize = React.forwardRef(ModalizeBase); | the_stack |
import { DOCUMENT } from '@angular/common';
import {
ChangeDetectorRef, Component, ElementRef, EventEmitter, HostBinding, HostListener, Inject, Input,
NgZone, OnChanges, OnDestroy, Output, Renderer2, SimpleChanges, TemplateRef
} from '@angular/core';
import { fromEvent, Observable, Subscription } from 'rxjs';
import { FilterConfig, SortDirection, SortEventArg } from '../../../data-table.model';
@Component({
/* eslint-disable-next-line @angular-eslint/component-selector*/
selector: '[dHeadCell]',
templateUrl: './th.component.html',
})
export class TableThComponent implements OnChanges, OnDestroy {
@HostBinding('class.resizeable') resizeEnabledClass = false;
@HostBinding('class.operable') operableClass = false;
@HostBinding('class.sort-active') sortActiveClass = false;
@HostBinding('class.filter-active') filterActiveClass = false;
@HostBinding('class.devui-sticky-left-cell') stickyLeftClass = false;
@HostBinding('class.devui-sticky-right-cell') stickyRightClass = false;
@HostBinding('style.left') stickyLeftStyle: string;
@HostBinding('style.right') stickyRightStyle: string;
@Input() resizeEnabled: boolean;
@Input() filterable: boolean;
@Input() beforeFilter: (value) => boolean | Promise<boolean> | Observable<boolean>;
@Input() customFilterTemplate: TemplateRef<any>;
@Input() extraFilterTemplate: TemplateRef<any>;
@Input() searchFn: (term: string) => Observable<Array<any>>;
@Input() showFilterIcon = false;
@Input() filterList: Array<FilterConfig>;
@Input() filterIconActive: boolean;
@Input() filterMultiple = true;
@Input() closeFilterWhenScroll: boolean;
@Input() filterBoxWidth: any;
@Input() filterBoxHeight: any;
@Output() filterChange = new EventEmitter<FilterConfig[]>();
@Input() sortable: boolean;
@Input() sortDirection: SortDirection;
@Input() showSortIcon = false;
@Output() sortDirectionChange = new EventEmitter<SortDirection>();
@Output() sortChange = new EventEmitter<SortEventArg>();
@Input() colDraggable: boolean;
@Input() nestedColumn: boolean;
@Input() iconFoldTable: string;
@Input() iconUnFoldTable: string;
resizeBarRefElement: HTMLElement;
@Input() tableViewRefElement: ElementRef;
@Output() resizeEndEvent: EventEmitter<any> = new EventEmitter<any>();
@Output() resizeStartEvent: EventEmitter<any> = new EventEmitter<any>();
@Output() resizingEvent: EventEmitter<any> = new EventEmitter<any>();
@Input() minWidth: string;
@Input() maxWidth: string;
@Input() fixedLeft: string;
@Input() fixedRight: string;
element: HTMLElement;
subscription: Subscription;
resizing = false;
resizeNodeEvent: any;
resizeOverlay: HTMLElement;
nextElement: any;
initialWidth: number;
totalWidth: number;
mouseDownScreenX: number;
resizeHandleElement: HTMLElement;
tableElement: HTMLElement;
@Input() childrenTableOpen: boolean;
@Output() toggleChildrenTableEvent = new EventEmitter<boolean>();
@Output() tapEvent = new EventEmitter<any>();
@Input() column: any; // 为配置column方式兼容自定义过滤模板context
document: Document;
constructor(element: ElementRef, private renderer2: Renderer2, private zone: NgZone, private cdr: ChangeDetectorRef,
@Inject(DOCUMENT) private doc: any) {
this.element = element.nativeElement;
this.document = this.doc;
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['resizeEnabled']) {
if (this.resizeEnabled) {
this.resizeEnabledClass = true;
if (!this.resizeHandleElement) {
this.resizeHandleElement = this.renderer2.createElement('span');
this.renderer2.addClass(this.resizeHandleElement, 'resize-handle');
this.renderer2.appendChild(this.element.firstChild, this.resizeHandleElement);
this.resizeNodeEvent = this.renderer2.listen(this.resizeHandleElement, 'click', (event) => event.stopPropagation());
}
} else {
this.resizeEnabledClass = false;
}
}
if (changes['filterable'] || changes['sortable'] || changes['resizeEnabled'] || changes['colDraggable']) {
if (this.filterable || this.sortable || this.resizeEnabled || this.colDraggable) {
this.operableClass = true;
} else {
this.operableClass = false;
}
}
if (changes['filterIconActive']) {
if (this.filterIconActive) {
this.filterActiveClass = true;
} else {
this.filterActiveClass = false;
}
}
if (changes['sortDirection']) {
if (this.sortDirection === SortDirection.ASC || this.sortDirection === SortDirection.DESC) {
this.sortActiveClass = true;
} else {
this.sortActiveClass = false;
}
}
if (changes['fixedLeft']) {
if (this.fixedLeft) {
this.stickyLeftClass = true;
this.stickyLeftStyle = this.fixedLeft;
} else {
this.stickyLeftClass = false;
this.stickyLeftStyle = null;
}
}
if (changes['fixedRight']) {
if (this.fixedRight) {
this.stickyRightClass = true;
this.stickyRightStyle = this.fixedRight;
} else {
this.stickyRightClass = false;
this.stickyRightStyle = null;
}
}
}
ngOnDestroy(): void {
this._destroySubscription();
if (this.resizeNodeEvent) {
this.resizeNodeEvent();
}
}
onFilterIconActive(active) {
this.filterActiveClass = active;
}
onTap(event) {
this.tapEvent.emit(event);
}
toggleChildrenTable() {
this.childrenTableOpen = !this.childrenTableOpen;
this.toggleChildrenTableEvent.emit(this.childrenTableOpen);
}
emitFilterData(filterData) {
this.filterChange.emit(filterData);
}
onSort(event: SortEventArg) {
this.sortDirection = event.direction;
if (event.direction === SortDirection.default) {
this.sortActiveClass = false;
} else {
this.sortActiveClass = true;
}
this.sortDirectionChange.emit(event.direction);
this.sortChange.emit({ ...event, th: this });
}
clearSortOrder() {
this.sortDirection = SortDirection.default;
this.sortActiveClass = false;
}
@HostListener('mousedown', ['$event'])
onMousedown(event: MouseEvent): void {
const isHandle = (<HTMLElement>event.target).classList.contains('resize-handle');
if (isHandle) {
this.resizeStartEvent.emit(event); // emit begin resize event
this.initialWidth = this.element.clientWidth;
const initialOffset = this.element.offsetLeft;
this.mouseDownScreenX = event.clientX;
event.stopPropagation();
this.nextElement = this.element.nextElementSibling;
this.resizing = true;
this.totalWidth = this.nextElement ? this.initialWidth + this.nextElement.clientWidth : this.initialWidth;
// create resizeOverlay
this.resizeOverlay = this.renderer2.createElement('div');
this.renderer2.appendChild(this.element.firstElementChild, this.resizeOverlay);
this.renderer2.addClass(this.resizeOverlay, 'resize-overlay');
this.renderer2.listen(this.resizeOverlay, 'click', (clickEvent: Event) => clickEvent.stopPropagation());
this.renderer2.addClass(this.tableViewRefElement.nativeElement, 'table-view-selector');
const resizeBar = this.renderer2.createElement('div');
this.renderer2.addClass(resizeBar, 'resize-bar');
this.tableElement = this.tableViewRefElement.nativeElement.querySelector('.devui-scrollbar table');
if (this.tableElement) {
this.renderer2.appendChild(this.tableElement, resizeBar);
this.renderer2.setStyle(resizeBar, 'display', 'block');
this.renderer2.setStyle(resizeBar, 'left', initialOffset + this.initialWidth + 'px');
this.resizeBarRefElement = resizeBar;
}
this.renderer2.addClass(this.element, 'hover-bg');
const mouseup = fromEvent(this.document, 'mouseup');
this.subscription = mouseup.subscribe((ev: MouseEvent) => this.onMouseup(ev));
this.zone.runOutsideAngular(() => {
this.document.addEventListener('mousemove', this.bindMousemove);
});
}
}
onMouseup(event: MouseEvent): void {
this.zone.run(() => {
const movementX = event.clientX - this.mouseDownScreenX;
const newWidth = this.initialWidth + movementX;
const finalWidth = this.getFinalWidth(newWidth);
this.resizing = false;
// destroy overlay
this.renderer2.removeChild(this.element, this.resizeOverlay);
this.renderer2.removeClass(this.tableViewRefElement.nativeElement, 'table-view-selector');
this.renderer2.removeClass(this.element, 'hover-bg');
if (this.tableElement) {
this.renderer2.removeChild(this.tableElement, this.resizeBarRefElement);
}
// this.width = finalWidth + 'px';
this.resizeEndEvent.emit({ width: finalWidth });
});
if (this.subscription && !this.subscription.closed) {
this._destroySubscription();
}
this.document.removeEventListener('mousemove', this.bindMousemove);
}
bindMousemove = (e) => {
this.move(e);
};
move(event: MouseEvent): void {
const movementX = event.clientX - this.mouseDownScreenX;
const newWidth = this.initialWidth + movementX;
const finalWidth = this.getFinalWidth(newWidth);
if (this.resizeBarRefElement) {
this.renderer2.setStyle(this.resizeBarRefElement, 'left', `${finalWidth + this.element.offsetLeft}px`);
}
this.resizingEvent.emit({ width: finalWidth });
}
private getFinalWidth(newWidth: number): number {
const minWidth = this.handleWidth(this.minWidth);
const maxWidth = this.handleWidth(this.maxWidth);
const overMinWidth = !this.minWidth || newWidth >= minWidth;
const underMaxWidth = !this.maxWidth || newWidth <= maxWidth;
const finalWidth = !overMinWidth ? minWidth : !underMaxWidth ? maxWidth : newWidth;
return finalWidth;
}
private handleWidth(width: string | number) {
if (!width) {
return;
}
if (typeof width === 'number') {
return width;
}
if (width.includes('%')) {
const tableWidth = this.tableViewRefElement.nativeElement.clientWidth;
return (tableWidth * parseInt(width, 10)) / 100;
}
return parseInt(width.replace(/[^\d]+/, ''), 10);
}
private _destroySubscription() {
if (this.subscription) {
this.subscription.unsubscribe();
this.subscription = undefined;
}
}
} | the_stack |
'use strict';
import {LanguageServiceDefaultsImpl} from './monaco.contribution';
import {VueWorker} from './vueWorker';
import * as ls from 'vscode-languageserver-types';
import Uri = monaco.Uri;
import Position = monaco.Position;
import Range = monaco.Range;
import Thenable = monaco.Thenable;
import Promise = monaco.Promise;
import CancellationToken = monaco.CancellationToken;
import IDisposable = monaco.IDisposable;
export interface WorkerAccessor {
(...more: Uri[]): Thenable<VueWorker>
}
// --- diagnostics --- ---
export class DiagnostcsAdapter {
private _disposables: IDisposable[] = [];
private _listener: { [uri: string]: IDisposable } = Object.create(null);
constructor(private _languageId: string, private _worker: WorkerAccessor) {
const onModelAdd = (model: monaco.editor.IModel): void => {
let modeId = model.getModeId();
if (modeId !== this._languageId) {
return;
}
let handle: number;
this._listener[model.uri.toString()] = model.onDidChangeContent(() => {
clearTimeout(handle);
handle = setTimeout(() => this._doValidate(model.uri, modeId), 500);
});
this._doValidate(model.uri, modeId);
};
const onModelRemoved = (model: monaco.editor.IModel): void => {
monaco.editor.setModelMarkers(model, this._languageId, []);
let uriStr = model.uri.toString();
let listener = this._listener[uriStr];
if (listener) {
listener.dispose();
delete this._listener[uriStr];
}
};
this._disposables.push(monaco.editor.onDidCreateModel(onModelAdd));
this._disposables.push(monaco.editor.onWillDisposeModel(model => {
onModelRemoved(model);
}));
this._disposables.push(monaco.editor.onDidChangeModelLanguage(event => {
onModelRemoved(event.model);
onModelAdd(event.model);
}));
this._disposables.push({
dispose: () => {
for (let key in this._listener) {
this._listener[key].dispose();
}
}
});
monaco.editor.getModels().forEach(onModelAdd);
}
public dispose(): void {
this._disposables.forEach(d => d && d.dispose());
this._disposables = [];
}
private _doValidate(resource: Uri, languageId: string): void {
this._worker(resource).then(worker => {
return worker.doValidation(resource.toString()).then(diagnostics => {
const markers = diagnostics.map(d => toDiagnostics(resource, d));
monaco.editor.setModelMarkers(monaco.editor.getModel(resource), languageId, markers);
});
}).then(undefined, err => {
console.error(err);
});
}
}
function toSeverity(lsSeverity: number): monaco.Severity {
switch (lsSeverity) {
case ls.DiagnosticSeverity.Error: return monaco.Severity.Error;
case ls.DiagnosticSeverity.Warning: return monaco.Severity.Warning;
case ls.DiagnosticSeverity.Information:
case ls.DiagnosticSeverity.Hint:
default:
return monaco.Severity.Info;
}
}
function toDiagnostics(resource: Uri, diag: ls.Diagnostic): monaco.editor.IMarkerData {
let code = typeof diag.code === 'number' ? String(diag.code) : <string>diag.code;
return {
severity: toSeverity(diag.severity),
startLineNumber: diag.range.start.line + 1,
startColumn: diag.range.start.character + 1,
endLineNumber: diag.range.end.line + 1,
endColumn: diag.range.end.character + 1,
message: diag.message,
code: code,
source: diag.source
};
}
// --- completion ------
function fromPosition(position: Position): ls.Position {
if (!position) {
return void 0;
}
return { character: position.column - 1, line: position.lineNumber - 1 };
}
function fromRange(range: Range): ls.Range {
if (!range) {
return void 0;
}
return { start: fromPosition(range.getStartPosition()), end: fromPosition(range.getEndPosition()) };
}
function toRange(range: ls.Range): Range {
if (!range) {
return void 0;
}
return new Range(range.start.line + 1, range.start.character + 1, range.end.line + 1, range.end.character + 1);
}
function toCompletionItemKind(kind: number): monaco.languages.CompletionItemKind {
let mItemKind = monaco.languages.CompletionItemKind;
switch (kind) {
case ls.CompletionItemKind.Text: return mItemKind.Text;
case ls.CompletionItemKind.Method: return mItemKind.Method;
case ls.CompletionItemKind.Function: return mItemKind.Function;
case ls.CompletionItemKind.Constructor: return mItemKind.Constructor;
case ls.CompletionItemKind.Field: return mItemKind.Field;
case ls.CompletionItemKind.Variable: return mItemKind.Variable;
case ls.CompletionItemKind.Class: return mItemKind.Class;
case ls.CompletionItemKind.Interface: return mItemKind.Interface;
case ls.CompletionItemKind.Module: return mItemKind.Module;
case ls.CompletionItemKind.Property: return mItemKind.Property;
case ls.CompletionItemKind.Unit: return mItemKind.Unit;
case ls.CompletionItemKind.Value: return mItemKind.Value;
case ls.CompletionItemKind.Enum: return mItemKind.Enum;
case ls.CompletionItemKind.Keyword: return mItemKind.Keyword;
case ls.CompletionItemKind.Snippet: return mItemKind.Snippet;
case ls.CompletionItemKind.Color: return mItemKind.Color;
case ls.CompletionItemKind.File: return mItemKind.File;
case ls.CompletionItemKind.Reference: return mItemKind.Reference;
}
return mItemKind.Property;
}
function fromCompletionItemKind(kind: monaco.languages.CompletionItemKind): ls.CompletionItemKind {
let mItemKind = monaco.languages.CompletionItemKind;
switch (kind) {
case mItemKind.Text: return ls.CompletionItemKind.Text;
case mItemKind.Method: return ls.CompletionItemKind.Method;
case mItemKind.Function: return ls.CompletionItemKind.Function;
case mItemKind.Constructor: return ls.CompletionItemKind.Constructor;
case mItemKind.Field: return ls.CompletionItemKind.Field;
case mItemKind.Variable: return ls.CompletionItemKind.Variable;
case mItemKind.Class: return ls.CompletionItemKind.Class;
case mItemKind.Interface: return ls.CompletionItemKind.Interface;
case mItemKind.Module: return ls.CompletionItemKind.Module;
case mItemKind.Property: return ls.CompletionItemKind.Property;
case mItemKind.Unit: return ls.CompletionItemKind.Unit;
case mItemKind.Value: return ls.CompletionItemKind.Value;
case mItemKind.Enum: return ls.CompletionItemKind.Enum;
case mItemKind.Keyword: return ls.CompletionItemKind.Keyword;
case mItemKind.Snippet: return ls.CompletionItemKind.Snippet;
case mItemKind.Color: return ls.CompletionItemKind.Color;
case mItemKind.File: return ls.CompletionItemKind.File;
case mItemKind.Reference: return ls.CompletionItemKind.Reference;
}
return ls.CompletionItemKind.Property;
}
function toTextEdit(textEdit: ls.TextEdit): monaco.editor.ISingleEditOperation {
if (!textEdit) {
return void 0;
}
return {
range: toRange(textEdit.range),
text: textEdit.newText
}
}
interface DataCompletionItem extends monaco.languages.CompletionItem {
data?: any;
}
function toCompletionItem(entry: ls.CompletionItem): DataCompletionItem {
return {
label: entry.label,
insertText: entry.insertText,
sortText: entry.sortText,
filterText: entry.filterText,
documentation: entry.documentation,
detail: entry.detail,
kind: toCompletionItemKind(entry.kind),
textEdit: toTextEdit(entry.textEdit),
data: entry.data
};
}
function fromCompletionItem(entry: DataCompletionItem): ls.CompletionItem {
let item : ls.CompletionItem = {
label: entry.label,
sortText: entry.sortText,
filterText: entry.filterText,
documentation: entry.documentation,
detail: entry.detail,
kind: fromCompletionItemKind(entry.kind),
data: entry.data
};
if (typeof entry.insertText === 'object' && typeof entry.insertText.value === 'string') {
item.insertText = entry.insertText.value;
item.insertTextFormat = ls.InsertTextFormat.Snippet
} else {
item.insertText = <string> entry.insertText;
}
if (entry.range) {
item.textEdit = ls.TextEdit.replace(fromRange(entry.range), item.insertText);
}
return item;
}
const emmetTriggerCharacters = ['!', '.', '}', ':', '*', '$', ']', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
export class CompletionAdapter implements monaco.languages.CompletionItemProvider {
constructor(private _worker: WorkerAccessor) {
}
public get triggerCharacters(): string[] {
return [...emmetTriggerCharacters, '.', ':', '<', '"', '=', '/'];
}
provideCompletionItems(model: monaco.editor.IReadOnlyModel, position: Position, token: CancellationToken): Thenable<monaco.languages.CompletionList> {
const wordInfo = model.getWordUntilPosition(position);
const resource = model.uri;
return wireCancellationToken(token, this._worker(resource).then(worker => {
return worker.doComplete(resource.toString(), fromPosition(position));
}).then(info => {
if (!info) {
return;
}
let items: monaco.languages.CompletionItem[] = info.items.map(entry => {
let item : monaco.languages.CompletionItem = {
label: entry.label,
insertText: entry.insertText,
sortText: entry.sortText,
filterText: entry.filterText,
documentation: entry.documentation,
detail: entry.detail,
kind: toCompletionItemKind(entry.kind),
};
if (entry.textEdit) {
item.range = toRange(entry.textEdit.range);
item.insertText = entry.textEdit.newText;
}
if (entry.insertTextFormat === ls.InsertTextFormat.Snippet) {
item.insertText = { value: <string> item.insertText };
}
return item;
});
return {
isIncomplete: info.isIncomplete,
items: items
};
}));
}
}
function toMarkedStringArray(contents: ls.MarkedString | ls.MarkedString[]): monaco.MarkedString[] {
if (!contents) {
return void 0;
}
if (Array.isArray(contents)) {
return (<ls.MarkedString[]>contents);
}
return [<ls.MarkedString>contents];
}
// --- definition ------
function toLocation(location: ls.Location): monaco.languages.Location {
return {
uri: Uri.parse(location.uri),
range: toRange(location.range)
};
}
// --- document symbols ------
function toSymbolKind(kind: ls.SymbolKind): monaco.languages.SymbolKind {
let mKind = monaco.languages.SymbolKind;
switch (kind) {
case ls.SymbolKind.File: return mKind.Array;
case ls.SymbolKind.Module: return mKind.Module;
case ls.SymbolKind.Namespace: return mKind.Namespace;
case ls.SymbolKind.Package: return mKind.Package;
case ls.SymbolKind.Class: return mKind.Class;
case ls.SymbolKind.Method: return mKind.Method;
case ls.SymbolKind.Property: return mKind.Property;
case ls.SymbolKind.Field: return mKind.Field;
case ls.SymbolKind.Constructor: return mKind.Constructor;
case ls.SymbolKind.Enum: return mKind.Enum;
case ls.SymbolKind.Interface: return mKind.Interface;
case ls.SymbolKind.Function: return mKind.Function;
case ls.SymbolKind.Variable: return mKind.Variable;
case ls.SymbolKind.Constant: return mKind.Constant;
case ls.SymbolKind.String: return mKind.String;
case ls.SymbolKind.Number: return mKind.Number;
case ls.SymbolKind.Boolean: return mKind.Boolean;
case ls.SymbolKind.Array: return mKind.Array;
}
return mKind.Function;
}
function toHighlighKind(kind: ls.DocumentHighlightKind): monaco.languages.DocumentHighlightKind {
let mKind = monaco.languages.DocumentHighlightKind;
switch (kind) {
case ls.DocumentHighlightKind.Read: return mKind.Read;
case ls.DocumentHighlightKind.Write: return mKind.Write;
case ls.DocumentHighlightKind.Text: return mKind.Text;
}
return mKind.Text;
}
export class DocumentHighlightAdapter implements monaco.languages.DocumentHighlightProvider {
constructor(private _worker: WorkerAccessor) {
}
public provideDocumentHighlights(model: monaco.editor.IReadOnlyModel, position: Position, token: CancellationToken): Thenable<monaco.languages.DocumentHighlight[]> {
const resource = model.uri;
return wireCancellationToken(token, this._worker(resource).then(worker => worker.findDocumentHighlights(resource.toString(), fromPosition(position))).then(items => {
if (!items) {
return;
}
return items.map(item => ({
range: toRange(item.range),
kind: toHighlighKind(item.kind)
}));
}));
}
}
export class DocumentLinkAdapter implements monaco.languages.LinkProvider {
constructor(private _worker: WorkerAccessor) {
}
public provideLinks(model: monaco.editor.IReadOnlyModel, token: CancellationToken): Thenable<monaco.languages.ILink[]> {
const resource = model.uri;
return wireCancellationToken(token, this._worker(resource).then(worker => worker.findDocumentLinks(resource.toString())).then(items => {
if (!items) {
return;
}
return items.map(item => ({
range: toRange(item.range),
url: item.target
}));
}));
}
}
function fromFormattingOptions(options: monaco.languages.FormattingOptions): ls.FormattingOptions {
return {
tabSize: options.tabSize,
insertSpaces: options.insertSpaces
};
}
export class DocumentFormattingEditProvider implements monaco.languages.DocumentFormattingEditProvider {
constructor(private _worker: WorkerAccessor) {
}
public provideDocumentFormattingEdits(model: monaco.editor.IReadOnlyModel, options: monaco.languages.FormattingOptions, token: CancellationToken): Thenable<monaco.editor.ISingleEditOperation[]> {
const resource = model.uri;
return wireCancellationToken(token, this._worker(resource).then(worker => {
return worker.format(resource.toString(), null, fromFormattingOptions(options)).then(edits => {
if (!edits || edits.length === 0) {
return;
}
return edits.map(toTextEdit);
});
}));
}
}
export class DocumentRangeFormattingEditProvider implements monaco.languages.DocumentRangeFormattingEditProvider {
constructor(private _worker: WorkerAccessor) {
}
public provideDocumentRangeFormattingEdits(model: monaco.editor.IReadOnlyModel, range: Range, options: monaco.languages.FormattingOptions, token: CancellationToken): Thenable<monaco.editor.ISingleEditOperation[]> {
const resource = model.uri;
return wireCancellationToken(token, this._worker(resource).then(worker => {
return worker.format(resource.toString(), fromRange(range), fromFormattingOptions(options)).then(edits => {
if (!edits || edits.length === 0) {
return;
}
return edits.map(toTextEdit);
});
}));
}
}
/**
* Hook a cancellation token to a WinJS Promise
*/
function wireCancellationToken<T>(token: CancellationToken, promise: Thenable<T>): Thenable<T> {
if ((<Promise<T>>promise).cancel) {
token.onCancellationRequested(() => (<Promise<T>>promise).cancel());
}
return promise;
} | the_stack |
/// <reference path="OCM_Base.ts" />
/// <reference path="OCM_CommonUI.ts" />
/// <reference path="OCM_MapProvider_GoogleMapsWeb.ts" />
/**
* @author Christopher Cook
* @copyright Webprofusion Ltd http://webprofusion.com
*/
module OCM {
export class GeoLatLng implements Coordinates {
//based on HTML Geolocation "Coordinates"
public altitudeAccuracy: number;
public longitude: number;
public latitude: number;
public speed: number;
public heading: number;
public altitude: number;
public accuracy: number;
constructor(lat: number = null, lng: number = null) {
this.latitude = lat;
this.longitude = lng;
}
}
export class GeoPosition {
//based on HTML Geolocation "Position"
public coords: GeoLatLng;
public timestamp: number;
public attribution: string;
constructor(lat: number = null, lng: number = null) {
this.coords = new GeoLatLng();
this.coords.latitude = lat;
this.coords.longitude = lng;
}
static fromPosition(pos: Position): GeoPosition {
return new GeoPosition(pos.coords.latitude, pos.coords.longitude);
}
}
export class MapOptions {
public enableClustering: boolean;
public resultBatchID: number;
public useMarkerIcons: boolean;
public useMarkerAnimation: boolean;
public enableTrackingMapCentre: boolean;
public enableSearchByWatchingLocation: boolean;
public mapCentre: GeoPosition;
public searchDistanceKM: number;
public iconSet: string;
public mapAPI: MappingAPI;
public mapMoveQueryRefreshMS: number; //time to wait before recognising map centre has changed
public requestSearchUpdate: boolean;
public enableSearchRadiusIndicator: boolean;
public mapType: string;
public minZoomLevel: number;
/** @constructor */
constructor() {
this.enableClustering = false;
this.resultBatchID = -1;
this.useMarkerIcons = true;
this.useMarkerAnimation = true;
this.enableTrackingMapCentre = false;
this.enableSearchByWatchingLocation = false;
this.mapCentre = null;
this.mapAPI = MappingAPI.GOOGLE_WEB;
this.mapType = "ROADMAP";
this.searchDistanceKM = 1000 * 100;
this.mapMoveQueryRefreshMS = 300;
this.enableSearchRadiusIndicator = false;
this.minZoomLevel = 2;
}
}
export enum MappingAPI {
GOOGLE_WEB,
GOOGLE_NATIVE,
LEAFLET
}
export interface IMapProvider {
mapAPIType: OCM.MappingAPI;
mapReady: boolean;
providerError: string;
initMap(mapCanvasID: string, mapConfig: MapOptions, mapManipulationCallback: any, mapManagerContext: Mapping);
refreshMapLayout();
renderMap(poiList: Array<any>, mapHeight: number, parentContext: App);
getMapZoom(): number;
setMapZoom(zoomLevel: number);
getMapCenter(): GeoPosition;
setMapCenter(pos: GeoPosition);
setMapType(mapType: string);
getMapBounds(): Array<GeoLatLng>;
}
/** Mapping - provides a way to render to various mapping APIs
* @module OCM.Mapping
*/
export class Mapping extends Base {
public map: any;
public mapCentreMarker: any;
public mapsInitialised: boolean; //initial map setup initiated
public mapAPIReady: boolean; //api loaded
public mapReady: boolean; //map ready for any api calls (initialisation completed)
public mapOptions: MapOptions;
public markerClusterer: any;
public markerList: Array<any>;
public searchMarker: any;
public errorMessage: string;
public parentAppContext: OCM.App;
private _mapMoveTimer: any;
private mapProvider: IMapProvider;
private debouncedMapPositionUpdate: any;
/** @constructor */
constructor() {
super();
this.mapOptions = new MapOptions();
this.mapAPIReady = false;
this.mapsInitialised = false;
this.mapReady = false;
this.setMapAPI(this.mapOptions.mapAPI);
var mapManagerContext = this;
this.debouncedMapPositionUpdate = OCM.Utils.debounce(function () {
mapManagerContext.log("signaling map position change:");
if (mapManagerContext.mapProvider.mapReady) {
//create new latlng from map centre so that values get normalised to 180/-180
var centerPos: GeoPosition = mapManagerContext.mapProvider.getMapCenter();
mapManagerContext.log("Map centre/zoom changed, updating search position:" + centerPos);
mapManagerContext.updateMapCentrePos(centerPos.coords.latitude, centerPos.coords.longitude, false);
}
}, 300, false);
}
setParentAppContext(context: any) {
this.parentAppContext = context;
}
setMapAPI(api: OCM.MappingAPI) {
this.mapOptions.mapAPI = api;
if (this.mapOptions.mapAPI == MappingAPI.GOOGLE_NATIVE) {
this.mapProvider = new (<any>OCM).MapProviders.GoogleMapsNative();
}
if (this.mapOptions.mapAPI == MappingAPI.GOOGLE_WEB) {
this.mapProvider = new (<any>OCM).MapProviders.GoogleMapsWeb();
}
}
isMapReady() {
if (this.mapProvider != null) {
return this.mapProvider.mapReady;
} else {
return false;
}
}
externalAPILoaded(mapAPI: OCM.MappingAPI) {
this.mapAPIReady = true;
this.log("Mapping API Loaded: " + OCM.MappingAPI[mapAPI]);
}
/**
* Performs one-time init of map object, detects cordova and chooses map api as appropriate
* @param mapcanvasID dom element for map canvas
*/
initMap(mapcanvasID: string) {
if (this.mapProvider != null) {
if (this.mapsInitialised) {
this.log("initMap: Map provider already initialised");
}
this.log("Mapping Manager: Init " + OCM.MappingAPI[this.mapProvider.mapAPIType]);
this.mapProvider.initMap(mapcanvasID, this.mapOptions, $.proxy(this.mapManipulationPerformed, this), this);
} else {
if (this.mapsInitialised) {
this.log("initMap: map already initialised");
return;
} else {
this.log("initMap: " + this.mapOptions.mapAPI)
}
}
}
updateSearchPosMarker(searchPos) {
//skip search marker if using live map viewport bounds querying
if (this.parentAppContext.appConfig.enableLiveMapQuerying) return;
var mapManagerContext = this;
if (this.mapProvider != null) {
//TODO:?
} else {
if (this.mapOptions.mapAPI == MappingAPI.GOOGLE_NATIVE) {
var map = this.map;
this.log("would add/update search pos marker");
if (mapManagerContext.mapCentreMarker != null) {
mapManagerContext.log("Updating search marker position");
mapManagerContext.mapCentreMarker.setPosition(searchPos);
if (this.mapReady) map.refreshLayout();
//mapManagerContext.mapCentreMarker.setMap(map);
} else {
if (this.mapReady) {
mapManagerContext.log("Adding search marker position");
map.addMarker({
'position': searchPos,
'draggable': true,
title: "Tap to Searching from here, Drag to change position.",
content: 'Your search position'
// icon: "images/icons/compass.png"
}, function (marker) {
mapManagerContext.mapCentreMarker = marker;
//marker click
marker.addEventListener(plugin.google.maps.event.MARKER_CLICK, function (marker) {
marker.getPosition(function (pos) {
mapManagerContext.log("Search marker tapped, requesting search from current position.");
mapManagerContext.updateMapCentrePos(pos.lat(), pos.lng(), false);
mapManagerContext.mapOptions.requestSearchUpdate = true;
});
});
//marker drag
marker.addEventListener(plugin.google.maps.event.MARKER_DRAG_END, function (marker) {
marker.getPosition(function (pos) {
mapManagerContext.updateMapCentrePos(pos.lat(), pos.lng(), false);
mapManagerContext.mapOptions.requestSearchUpdate = true;
});
});
});
}
}
}
if (this.mapOptions.mapAPI == MappingAPI.GOOGLE_WEB) {
var map = this.map;
if (mapManagerContext.mapCentreMarker != null) {
mapManagerContext.log("Updating search marker position");
mapManagerContext.mapCentreMarker.setPosition(searchPos);
mapManagerContext.mapCentreMarker.setMap(map);
} else {
mapManagerContext.log("Adding search marker position");
mapManagerContext.mapCentreMarker = new google.maps.Marker({
position: searchPos,
map: map,
draggable: true,
title: "Tap to Searching from here, Drag to change position.",
icon: "images/icons/compass.png"
});
var infowindow = new google.maps.InfoWindow({
content: "Tap marker to search from here, Drag marker to change search position."
});
infowindow.open(map, mapManagerContext.mapCentreMarker);
google.maps.event.addListener(mapManagerContext.mapCentreMarker, 'click', function () {
mapManagerContext.log("Search markers tapped, requesting search.");
var pos = mapManagerContext.mapCentreMarker.getPosition();
mapManagerContext.updateMapCentrePos(pos.lat(), pos.lng(), false);
mapManagerContext.mapOptions.requestSearchUpdate = true;
});
google.maps.event.addListener(mapManagerContext.mapCentreMarker, 'dragend', function () {
mapManagerContext.log("Search marker moved, requesting search.");
var pos = mapManagerContext.mapCentreMarker.getPosition();
mapManagerContext.updateMapCentrePos(pos.lat(), pos.lng(), false);
mapManagerContext.mapOptions.requestSearchUpdate = true;
});
}
}
}
}
/**
* Used by map provider as callback when a zoom or pan/drag has been performed
* @param manipulationType string name for event "zoom", "drag" etc
*/
mapManipulationPerformed(manipulationType: string) {
this.log("map manipulated:" + manipulationType);
var mapManagerContext = this;
if (manipulationType == "drag" || manipulationType == "zoom") {
//after the center of the map centre has stopped changing, update search centre pos
this.debouncedMapPositionUpdate();
}
}
initMapLeaflet(mapcanvasID, currentLat, currentLng, locateUser) {
if (this.map == null) {
this.map = this.createMapLeaflet(mapcanvasID, currentLat, currentLng, locateUser, 13);
this.mapReady = true;
}
}
showPOIListOnMapViewLeaflet(mapcanvasID, poiList, appcontext, anchorElement, resultBatchID) {
var map = this.map;
//if list has changes to results render new markers etc
if (this.mapOptions.resultBatchID != resultBatchID) {
this.mapOptions.resultBatchID = resultBatchID;
this.log("Setting up map markers:" + resultBatchID);
// Creates a red marker with the coffee icon
var unknownPowerMarker = L.AwesomeMarkers.icon({
icon: "bolt",
color: "darkpurple",
prefix: "fa"
});
var lowPowerMarker = L.AwesomeMarkers.icon({
icon: "bolt",
color: "darkblue",
spin: true,
prefix: "fa"
});
var mediumPowerMarker = L.AwesomeMarkers.icon({
icon: "bolt",
color: "green",
spin: true,
prefix: "fa"
});
var highPowerMarker = L.AwesomeMarkers.icon({
icon: "bolt",
color: "orange",
spin: true,
prefix: "fa"
});
if (this.mapOptions.enableClustering) {
var markerClusterGroup = new L.MarkerClusterGroup();
if (poiList != null) {
//render poi markers
var poiCount = poiList.length;
for (var i = 0; i < poiList.length; i++) {
if (poiList[i].AddressInfo != null) {
if (poiList[i].AddressInfo.Latitude != null && poiList[i].AddressInfo.Longitude != null) {
var poi = poiList[i];
var markerTitle = poi.AddressInfo.Title;
var powerTitle = "";
var usageTitle = "";
var poiLevel = OCM.Utils.getMaxLevelOfPOI(poi);
var markerIcon = unknownPowerMarker;
if (poiLevel == 0) {
powerTitle += "Power Level Unknown";
}
if (poiLevel == 1) {
markerIcon = lowPowerMarker;
powerTitle += "Low Power";
}
if (poiLevel == 2) {
markerIcon = mediumPowerMarker;
powerTitle += "Medium Power";
}
if (poiLevel == 3) {
markerIcon = highPowerMarker;
powerTitle += "High Power";
}
usageTitle = "Unknown Usage Restrictions";
if (poi.UsageType != null && poi.UsageType.ID != 0) {
usageTitle = poi.UsageType.Title;
}
markerTitle += " (" + powerTitle + ", " + usageTitle + ")";
var marker = <any>new (<any>L).Marker(new (<any>L).LatLng(poi.AddressInfo.Latitude, poi.AddressInfo.Longitude), { icon: markerIcon, title: markerTitle, draggable: false, clickable: true });
marker._isClicked = false; //workaround for double click event
marker.poi = poi;
marker.on('click',
function (e) {
if (this._isClicked == false) {
this._isClicked = true;
appcontext.showDetailsView(anchorElement, this.poi);
appcontext.showPage("locationdetails-page");
//workaround double click event by clearing clicked state after short time
var mk = this;
setTimeout(function () { mk._isClicked = false; }, 300);
}
});
markerClusterGroup.addLayer(marker);
}
}
}
}
map.addLayer(markerClusterGroup);
map.fitBounds(markerClusterGroup.getBounds());
//refresh map view
setTimeout(function () { map.invalidateSize(false); }, 300);
}
}
}
createMapLeaflet(mapcanvasID, currentLat, currentLng, locateUser, zoomLevel) {
// create a map in the "map" div, set the view to a given place and zoom
var map = new (<any>L).Map(mapcanvasID);
if (currentLat != null && currentLng != null) {
map.setView(new (<any>L).LatLng(currentLat, currentLng), zoomLevel, true);
}
map.setZoom(zoomLevel);
if (locateUser == true) {
map.locate({ setView: true, watch: true, enableHighAccuracy: true });
} else {
//use a default view
}
// add an OpenStreetMap tile layer
new (<any>L).TileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
return map;
};
isNativeMapsAvailable(): boolean {
if (plugin && plugin.google && plugin.google.maps) {
return true;
} else {
return false;
}
}
updateMapSize() {
if (this.mapProvider) {
if (this.mapProvider.mapReady) {
this.mapProvider.refreshMapLayout();
}
}
}
updateMapCentrePos(lat: number, lng: number, moveMap: boolean) {
//update record of map centre so search results can optionally be refreshed
if (moveMap) {
if (this.mapProvider != null) {
this.mapProvider.setMapCenter(new GeoPosition(lat, lng));
}
}
this.mapOptions.mapCentre = new GeoPosition(lat, lng);
};
refreshMapView(mapHeight: number, poiList: Array<any>, searchPos: any): boolean {
if (this.mapProvider != null) {
this.log("Mapping Manager: renderMap " + OCM.MappingAPI[this.mapProvider.mapAPIType]);
if (this.isMapReady()) {
this.mapProvider.renderMap(poiList, mapHeight, this.parentAppContext);
} else {
this.log("refreshMapView: map provider not initialised..");
}
} else {
this.log("Unsupported Map API: refreshMapView", LogLevel.ERROR);
/*
document.getElementById(mapCanvasID).style.height = mapHeight + "px";
if (this.mapOptions.mapAPI == MappingAPI.LEAFLET) {
//setup map view, tracking user pos, if not already initialised
//TODO: use last search pos as lat/lng, or first item in locationList
var centreLat = 50;
var centreLng = 50;
if (poiList != null && poiList.length > 0) {
centreLat = poiList[0].AddressInfo.Latitude;
centreLng = poiList[0].AddressInfo.Longitude;
}
this.initMapLeaflet(mapCanvasID, centreLat, centreLng, false);
if (this.mapReady) this.showPOIListOnMapViewLeaflet(mapCanvasID, poiList, this, document.getElementById(mapCanvasID), this.mapOptions.resultBatchID);
}
*/
}
return true;
}
setMapType(maptype: string) {
if (this.mapOptions.mapType == maptype) return;
this.mapOptions.mapType = maptype;
this.log("Changing map type:" + maptype);
if (this.isMapReady()) {
if (this.mapProvider != null) {
this.mapProvider.setMapType(maptype);
} else {
if (this.mapOptions.mapAPI == MappingAPI.GOOGLE_NATIVE) {
try {
this.map.setMapTypeId(eval("plugin.google.maps.MapTypeId." + maptype));
} catch (exception) {
this.log("Failed to set map type:" + maptype + " : " + exception.toString());
}
}
}
} else {
this.log("Map type set, maps not initialised yet.");
}
}
hideMap() {
if (this.mapOptions.mapAPI == MappingAPI.GOOGLE_NATIVE) {
this.log("Debug: Hiding Map");
if (this.map != null && this.mapReady) {
this.map.setVisible(false);
this.map.setClickable(false);
}
}
}
showMap() {
if (this.mapOptions.mapAPI == MappingAPI.GOOGLE_NATIVE) {
this.log("Debug: Showing Map");
if (this.map != null && this.mapReady) {
//show/reposition map
this.map.refreshLayout();
this.map.setVisible(true);
this.map.setClickable(true);
} else {
this.log("Map not available - check API?", LogLevel.ERROR);
}
}
}
unfocusMap() {
if (this.mapOptions.mapAPI == MappingAPI.GOOGLE_NATIVE && this.mapReady) {
this.map.setClickable(false);
}
}
focusMap() {
if (this.mapOptions.mapAPI == MappingAPI.GOOGLE_NATIVE && this.mapReady) {
this.map.setClickable(true);
}
}
getMapBounds(): Array<GeoLatLng> {
return this.mapProvider.getMapBounds();
}
getMapZoom(): number {
//TODO: normalize zoom between providers?
return this.mapProvider.getMapZoom();
}
showPOIOnStaticMap(mapcanvasID: string, poi, includeMapLink: boolean = false, isRunningUnderCordova: boolean = false, mapWidth: number = 200, mapHeight: number = 200) {
var mapCanvas = document.getElementById(mapcanvasID);
if (mapCanvas != null) {
var title = poi.AddressInfo.Title;
var lat = poi.AddressInfo.Latitude;
var lon = poi.AddressInfo.Longitude;
if (mapWidth > 640) mapWidth = 640;
if (mapHeight > 640) mapHeight = 640;
var width = mapWidth;
var height = mapHeight;
var mapImageURL = "https://maps.googleapis.com/maps/api/staticmap?center=" + lat + "," + lon + "&zoom=14&size=" + width + "x" + height + "&maptype=roadmap&markers=color:blue%7Clabel:A%7C" + lat + "," + lon + "&sensor=false";
var mapHTML = "";
if (includeMapLink == true) {
mapHTML += "<div>" + OCM.Utils.formatMapLink(poi, "<div><img width=\"" + width + "\" height=\"" + height + "\" src=\"" + mapImageURL + "\" /></div>", isRunningUnderCordova) + "</div>";
} else {
mapHTML += "<div><img width=\"" + width + "\" height=\"" + height + "\" src=\"" + mapImageURL + "\" /></div>";
}
mapCanvas.innerHTML = mapHTML;
}
}
}
} | the_stack |
import type * as hb from "homebridge";
import type * as hap from "hap-nodejs";
import { BasePropsType, CharacteristicConfig, GetMapFunc } from "./humidifier";
import { ValueOf } from "./utils";
import { HumidifierModel } from "./models";
export type AnyCharacteristicConfig<PropsType> = CharacteristicConfig<
PropsType,
keyof PropsType,
ValueOf<PropsType>
>;
export interface Features<PropsType extends BasePropsType> {
accessoryInfo(
name: string,
model: HumidifierModel,
deviceId: number,
): Array<AnyCharacteristicConfig<PropsType>>;
currentState<PropKey extends keyof PropsType>(
key: PropKey,
params: {
on: PropsType[PropKey];
off: PropsType[PropKey];
},
): AnyCharacteristicConfig<PropsType>;
targetState(): AnyCharacteristicConfig<PropsType>;
active<PropKey extends keyof PropsType>(
key: PropKey,
setCall: string,
params: {
on: PropsType[PropKey];
off: PropsType[PropKey];
},
): AnyCharacteristicConfig<PropsType>;
rotationSpeed<PropKey extends keyof PropsType>(
key: PropKey,
setCall: string,
params: {
modes: Array<PropsType[PropKey]>;
},
): AnyCharacteristicConfig<PropsType>;
humidity<PropKey extends keyof PropsType>(
key: PropKey,
): AnyCharacteristicConfig<PropsType>;
humidityThreshold<
PropKey extends keyof PropsType,
ModePropKey extends keyof PropsType
>(
key: PropKey,
setCall: string,
params: {
min: number;
max: number;
// Some humidifiers have special mode for reaching target humidity.
// Pass "key" and "value" for this mode to enable it automatically.
switchToMode?: {
key: ModePropKey;
call: string;
value: PropsType[ModePropKey];
};
},
): AnyCharacteristicConfig<PropsType>;
lockPhysicalControls<PropKey extends keyof PropsType>(
key: PropKey,
setCall: string,
params: {
on: PropsType[PropKey];
off: PropsType[PropKey];
},
): AnyCharacteristicConfig<PropsType>;
waterLevel<PropKey extends keyof PropsType>(
key: PropKey,
params: {
toChar: (it: PropsType[PropKey]) => hb.CharacteristicValue;
},
): AnyCharacteristicConfig<PropsType>;
swingMode<PropKey extends keyof PropsType>(
key: PropKey,
setCall: string,
params: {
on: PropsType[PropKey];
off: PropsType[PropKey];
},
): AnyCharacteristicConfig<PropsType>;
ledBulb<PropKey extends keyof PropsType>(
key: PropKey,
setCall: string,
params: {
name?: string;
modes: Array<PropsType[PropKey]>;
on: PropsType[PropKey];
off: PropsType[PropKey];
},
): Array<AnyCharacteristicConfig<PropsType>>;
buzzerSwitch<PropKey extends keyof PropsType>(
key: PropKey,
setCall: string,
params: {
name?: string;
on: PropsType[PropKey];
off: PropsType[PropKey];
},
): Array<AnyCharacteristicConfig<PropsType>>;
humiditySensor<PropKey extends keyof PropsType>(
key: PropKey,
params: {
name?: string;
},
): Array<AnyCharacteristicConfig<PropsType>>;
temperatureSensor<PropKey extends keyof PropsType>(
key: PropKey,
params: {
name?: string;
toChar?: (it: PropsType[PropKey]) => hb.CharacteristicValue;
},
): Array<AnyCharacteristicConfig<PropsType>>;
cleanModeSwitch<PropKey extends keyof PropsType>(
key: PropKey,
setCall: string,
params: {
name?: string;
on: PropsType[PropKey];
off: PropsType[PropKey];
},
): Array<AnyCharacteristicConfig<PropsType>>;
}
export function features<PropsType extends BasePropsType>(
Service: typeof hap.Service,
Characteristic: typeof hap.Characteristic,
log: hb.Logging,
): Features<PropsType> {
return {
accessoryInfo(name, model, deviceId) {
return [
{
service: Service.AccessoryInformation,
characteristic: Characteristic.Name,
value: name,
},
{
service: Service.AccessoryInformation,
characteristic: Characteristic.Manufacturer,
value: "Xiaomi",
},
{
service: Service.AccessoryInformation,
characteristic: Characteristic.Model,
value: model,
},
{
service: Service.AccessoryInformation,
characteristic: Characteristic.SerialNumber,
value: `${deviceId}`,
},
{
service: Service.AccessoryInformation,
characteristic: Characteristic.Identify,
value: (callback: hb.CharacteristicGetCallback) => {
log.info(`Identified device "${name}"`);
callback(null);
},
},
];
},
currentState(key, params) {
return {
service: Service.HumidifierDehumidifier,
characteristic: Characteristic.CurrentHumidifierDehumidifierState,
props: {
validValues: [
Characteristic.CurrentHumidifierDehumidifierState.INACTIVE,
Characteristic.CurrentHumidifierDehumidifierState.HUMIDIFYING,
],
},
key: key,
get: {
map: (it) =>
it === params.on
? Characteristic.CurrentHumidifierDehumidifierState.HUMIDIFYING
: Characteristic.CurrentHumidifierDehumidifierState.INACTIVE,
},
};
},
targetState() {
return {
service: Service.HumidifierDehumidifier,
characteristic: Characteristic.TargetHumidifierDehumidifierState,
props: {
validValues: [
Characteristic.TargetHumidifierDehumidifierState.HUMIDIFIER,
],
},
value: Characteristic.TargetHumidifierDehumidifierState.HUMIDIFIER,
};
},
active(key, setCall, params) {
return {
service: Service.HumidifierDehumidifier,
characteristic: Characteristic.Active,
key: key,
get: {
map: (it) =>
it === params.on
? Characteristic.Active.ACTIVE
: Characteristic.Active.INACTIVE,
},
set: {
call: setCall,
map: (it) =>
it === Characteristic.Active.ACTIVE ? params.on : params.off,
},
};
},
rotationSpeed(key, setCall, params) {
return {
service: Service.HumidifierDehumidifier,
characteristic: Characteristic.RotationSpeed,
props: {
// Home.app automatically sends power off command when
// rotation speed is set to 0, so to be able to set lowest speed
// we need to start from 1.
minValue: 0,
maxValue: params.modes.length,
},
key: key,
get: {
map: (it) => {
const index = params.modes.findIndex((mode) => mode === it);
return index > 0 ? index + 1 : 1;
},
},
set: {
call: setCall,
map: (it) =>
it >= 1 && it <= params.modes.length
? params.modes[(it as number) - 1]
: params.modes[0],
},
};
},
humidity<PropKey extends keyof PropsType>(
key: PropKey,
): AnyCharacteristicConfig<PropsType> {
return {
service: Service.HumidifierDehumidifier,
characteristic: Characteristic.CurrentRelativeHumidity,
key: key,
get: {
map: (it) => it,
},
};
},
humidityThreshold(key, setCall, params) {
return {
service: Service.HumidifierDehumidifier,
characteristic: Characteristic.RelativeHumidityHumidifierThreshold,
key: key,
get: {
map: (it) => it,
},
set: {
call: setCall,
map: (it) => {
if (it < params.min) {
it = params.min;
} else if (it > params.max) {
it = params.max;
}
return it as PropsType[typeof key];
},
beforeSet: async ({ protocol }) => {
if (params.switchToMode) {
const { key, call, value } = params.switchToMode;
await protocol.setProp(key, call, value);
}
},
afterSet: ({ characteristic, mappedValue }) => {
// Update characteristic immediately is not working, so
// update it after a small delay.
setTimeout(() => {
characteristic.updateValue(mappedValue);
}, 200);
},
},
};
},
lockPhysicalControls(key, setCall, params) {
return {
service: Service.HumidifierDehumidifier,
characteristic: Characteristic.LockPhysicalControls,
key: key,
get: {
map: (it) =>
it === params.on
? Characteristic.LockPhysicalControls.CONTROL_LOCK_ENABLED
: Characteristic.LockPhysicalControls.CONTROL_LOCK_DISABLED,
},
set: {
call: setCall,
map: (it) =>
it === Characteristic.LockPhysicalControls.CONTROL_LOCK_ENABLED
? params.on
: params.off,
},
};
},
waterLevel(key, params) {
return {
service: Service.HumidifierDehumidifier,
characteristic: Characteristic.WaterLevel,
key: key,
get: {
// Some humidifier models return special values for water level
// when water tank is detached, so we limit the value here.
map: (it) =>
Math.min(params.toChar(it as PropsType[typeof key]) as number, 100),
},
};
},
swingMode(key, setCall, params) {
return {
service: Service.HumidifierDehumidifier,
characteristic: Characteristic.SwingMode,
key: key,
get: {
map: (it) =>
it === params.on
? Characteristic.SwingMode.SWING_ENABLED
: Characteristic.SwingMode.SWING_DISABLED,
},
set: {
call: setCall,
map: (it) =>
it === Characteristic.SwingMode.SWING_ENABLED
? params.on
: params.off,
},
};
},
ledBulb(key, setCall, params) {
const result: Array<AnyCharacteristicConfig<PropsType>> = [];
result.push({
service: Service.Lightbulb,
characteristic: Characteristic.Name,
value: params.name || "Humidifier LED",
});
if (params.modes.length > 2) {
result.push({
service: Service.Lightbulb,
characteristic: Characteristic.Brightness,
props: {
minValue: 0,
maxValue: params.modes.length - 1,
},
key: key,
get: {
map: (it) => {
const index = params.modes.findIndex((mode) => mode === it);
return index > 0 ? index : 0;
},
},
set: {
call: setCall,
map: (it) =>
it >= 0 && it < params.modes.length
? params.modes[it as number]
: params.modes[0],
},
});
}
result.push({
service: Service.Lightbulb,
characteristic: Characteristic.On,
key: key,
get: {
map: (it) => it !== params.off,
},
set: {
call: setCall,
map: (it) => (it ? params.on : params.off),
beforeSet: ({ value, characteristic }) => {
// HomeKit trying to set "On" to true after changing brightness
// which cause switching brightness back to Dim.
// So skip set if bulb has already turned on.
return value === characteristic.value;
},
},
});
return result;
},
buzzerSwitch(key, setCall, params) {
const name = params.name || "Humidifier Buzzer";
return [
{
service: Service.Switch,
name: {
displayName: name,
subtype: "buzzer-switch",
},
characteristic: Characteristic.Name,
value: name,
},
{
service: Service.Switch,
name: {
displayName: name,
subtype: "buzzer-switch",
},
characteristic: Characteristic.On,
key: key,
get: {
map: (it) => it === params.on,
},
set: {
call: setCall,
map: (it) => (it ? params.on : params.off),
},
},
];
},
humiditySensor(key, params) {
return [
{
service: Service.HumiditySensor,
characteristic: Characteristic.Name,
value: params.name || "Humidifier Humidity",
},
{
service: Service.HumiditySensor,
characteristic: Characteristic.CurrentRelativeHumidity,
key: key,
},
];
},
temperatureSensor(key, params) {
return [
{
service: Service.TemperatureSensor,
characteristic: Characteristic.Name,
value: params.name || "Humidifier Temperature",
},
{
service: Service.TemperatureSensor,
characteristic: Characteristic.CurrentTemperature,
key: key,
get: {
map: params.toChar as GetMapFunc<PropsType>,
},
},
];
},
cleanModeSwitch(key, setCall, params) {
const name = params.name || "Humidifier Clean Mode";
return [
{
service: Service.Switch,
name: {
displayName: name,
subtype: "clean-mode-switch",
},
characteristic: Characteristic.Name,
value: name,
},
{
service: Service.Switch,
name: {
displayName: name,
subtype: "clean-mode-switch",
},
characteristic: Characteristic.On,
key: key,
get: {
map: (it) => it === params.on,
},
set: {
call: setCall,
map: (it) => (it ? params.on : params.off),
},
},
];
},
};
} | the_stack |
import { FieldDefinitionNode } from 'graphql';
import {
compoundExpression,
Expression,
obj,
printBlock,
and,
equals,
iff,
methodCall,
not,
ref,
str,
bool,
forEach,
list,
qref,
raw,
set,
ifElse,
nul,
notEquals,
parens,
} from 'graphql-mapping-template';
import {
getIdentityClaimExp,
getOwnerClaim,
apiKeyExpression,
iamExpression,
lambdaExpression,
emptyPayload,
setHasAuthExpression,
} from './helpers';
import {
COGNITO_AUTH_TYPE,
OIDC_AUTH_TYPE,
RoleDefinition,
splitRoles,
ConfiguredAuthProviders,
IS_AUTHORIZED_FLAG,
fieldIsList,
RelationalPrimaryMapConfig,
} from '../utils';
import { NONE_VALUE } from 'graphql-transformer-common';
const generateStaticRoleExpression = (roles: Array<RoleDefinition>): Array<Expression> => {
const staticRoleExpression: Array<Expression> = [];
let privateRoleIdx = roles.findIndex(r => r.strategy === 'private');
if (privateRoleIdx > -1) {
staticRoleExpression.push(set(ref(IS_AUTHORIZED_FLAG), bool(true)));
roles.splice(privateRoleIdx, 1);
}
if (roles.length > 0) {
staticRoleExpression.push(
iff(
not(ref(IS_AUTHORIZED_FLAG)),
compoundExpression([
set(ref('staticGroupRoles'), raw(JSON.stringify(roles.map(r => ({ claim: r.claim, entity: r.entity }))))),
forEach(ref('groupRole'), ref('staticGroupRoles'), [
set(ref('groupsInToken'), getIdentityClaimExp(ref('groupRole.claim'), list([]))),
iff(
methodCall(ref('groupsInToken.contains'), ref('groupRole.entity')),
compoundExpression([set(ref(IS_AUTHORIZED_FLAG), bool(true)), raw(`#break`)]),
),
]),
]),
),
);
}
return staticRoleExpression;
};
const generateAuthOnRelationalModelQueryExpression = (
roles: Array<RoleDefinition>,
primaryFieldMap: RelationalPrimaryMapConfig,
): Array<Expression> => {
const modelQueryExpression = new Array<Expression>();
const primaryRoles = roles.filter(r => primaryFieldMap.has(r.entity));
if (primaryRoles.length > 0) {
primaryRoles.forEach((role, idx) => {
const { claim, field } = primaryFieldMap.get(role.entity);
modelQueryExpression.push(
set(
ref(`primaryRole${idx}`),
role.strategy === 'owner' ? getOwnerClaim(role.claim!) : getIdentityClaimExp(str(role.claim!), str(NONE_VALUE)),
),
ifElse(
and([
parens(not(ref(`util.isNull($ctx.${claim}.${field})`))),
parens(equals(ref(`ctx.${claim}.${field}`), ref(`primaryRole${idx}`))),
]),
compoundExpression([set(ref(IS_AUTHORIZED_FLAG), bool(true)), qref(methodCall(ref('ctx.stash.put'), str('authFilter'), nul()))]),
iff(
and([not(ref(IS_AUTHORIZED_FLAG)), methodCall(ref('util.isNull'), ref('ctx.stash.authFilter'))]),
compoundExpression([
qref(methodCall(ref(`ctx.${claim}.put`), str(field), ref(`primaryRole${idx}`))),
set(ref(IS_AUTHORIZED_FLAG), bool(true)),
]),
),
),
);
});
return [iff(not(ref(IS_AUTHORIZED_FLAG)), compoundExpression(modelQueryExpression))];
}
return modelQueryExpression;
};
/**
* In the event that an owner/group field is the same as a primary field we can validate against the args if provided
* if the field is not in the args we include it in the KeyConditionExpression which is formed as a part of the query
* when it is formed as a part of the query we can consider the request authorized
*/
const generateAuthOnModelQueryExpression = (
roles: Array<RoleDefinition>,
primaryFields: Array<string>,
isIndexQuery = false,
): Array<Expression> => {
const modelQueryExpression = new Array<Expression>();
const primaryRoles = roles.filter(r => primaryFields.includes(r.entity));
if (primaryRoles.length > 0) {
if (isIndexQuery) {
for (let role of primaryRoles) {
const claimExpression =
role.strategy === 'owner' ? getOwnerClaim(role.claim!) : getIdentityClaimExp(str(role.claim!), str(NONE_VALUE));
modelQueryExpression.push(
ifElse(
not(ref(`util.isNull($ctx.args.${role.entity})`)),
compoundExpression([
set(ref(`${role.entity}Claim`), claimExpression),
ifElse(
ref(`util.isString($ctx.args.${role.entity})`),
set(ref(`${role.entity}Condition`), parens(equals(ref(`${role.entity}Claim`), ref(`ctx.args.${role.entity}`)))),
set(
ref(`${role.entity}Condition`),
parens(
equals(
ref(`${role.entity}Claim`),
methodCall(ref('util.defaultIfNull'), raw(`$ctx.args.${role.entity}.get("eq")`), str(NONE_VALUE)),
),
),
),
),
iff(
ref(`${role.entity}Condition`),
compoundExpression([
set(ref(IS_AUTHORIZED_FLAG), bool(true)),
qref(methodCall(ref('ctx.stash.put'), str('authFilter'), nul())),
]),
),
]),
qref(methodCall(ref('primaryFieldMap.put'), str(role.entity), claimExpression)),
),
);
}
modelQueryExpression.push(
iff(
and([
not(ref(IS_AUTHORIZED_FLAG)),
methodCall(ref('util.isNull'), ref('ctx.stash.authFilter')),
not(ref('primaryFieldMap.isEmpty()')),
]),
compoundExpression([
forEach(ref('entry'), ref('primaryFieldMap.entrySet()'), [
qref(methodCall(ref('ctx.args.put'), ref('entry.key'), ref('entry.value'))),
set(ref(IS_AUTHORIZED_FLAG), bool(true)),
]),
]),
),
);
} else {
for (let role of primaryRoles) {
const claimExpression =
role.strategy === 'owner' ? getOwnerClaim(role.claim!) : getIdentityClaimExp(str(role.claim!), str(NONE_VALUE));
modelQueryExpression.push(
ifElse(
not(ref(`util.isNull($ctx.args.${role.entity})`)),
compoundExpression([
set(ref(`${role.entity}Claim`), claimExpression),
ifElse(
ref(`util.isString($ctx.args.${role.entity})`),
set(ref(`${role.entity}Condition`), parens(equals(ref(`${role.entity}Claim`), ref(`ctx.args.${role.entity}`)))),
// this type is mainly applied on list queries with primaryKeys therefore we can use the get "eq" key
// to check if the dynamic role condition is met
set(
ref(`${role.entity}Condition`),
parens(
equals(
ref(`${role.entity}Claim`),
methodCall(ref('util.defaultIfNull'), raw(`$ctx.args.${role.entity}.get("eq")`), str(NONE_VALUE)),
),
),
),
),
iff(
ref(`${role.entity}Condition`),
compoundExpression([
set(ref(IS_AUTHORIZED_FLAG), bool(true)),
qref(methodCall(ref('ctx.stash.put'), str('authFilter'), nul())),
]),
),
]),
qref(methodCall(ref('primaryFieldMap.put'), str(role.entity), claimExpression)),
),
);
}
modelQueryExpression.push(
iff(
and([
not(ref(IS_AUTHORIZED_FLAG)),
methodCall(ref('util.isNull'), ref('ctx.stash.authFilter')),
not(ref('primaryFieldMap.isEmpty()')),
]),
compoundExpression([
set(
ref('modelQueryExpression'),
methodCall(
ref('util.defaultIfNull'),
ref('ctx.stash.modelQueryExpression'),
obj({ expression: str(''), expressionNames: obj({}), expressionValues: obj({}) }),
),
),
ifElse(
methodCall(ref('util.isNullOrBlank'), ref('modelQueryExpression.expression')),
set(ref('expressions'), list([])),
set(ref('expressions'), list([ref('modelQueryExpression.expression')])),
),
forEach(ref('entry'), ref('primaryFieldMap.entrySet()'), [
qref(ref('expressions.add("#${entry.key} = :${entry.value}")')),
qref(ref('modelQueryExpression.expressionNames.put("#${entry.key}", $entry.key)')),
qref(ref('modelQueryExpression.expressionValues.put(":${entry.value}", $util.dynamodb.toDynamoDB($entry.value))')),
]),
qref(ref('modelQueryExpression.put("expression", $expressions.join(\' AND \'))')),
qref(methodCall(ref('ctx.stash.put'), str('modelQueryExpression'), ref('modelQueryExpression'))),
set(ref(IS_AUTHORIZED_FLAG), bool(true)),
]),
),
);
}
return modelQueryExpression;
}
return [];
};
const generateAuthFilter = (roles: Array<RoleDefinition>, fields: ReadonlyArray<FieldDefinitionNode>): Array<Expression> => {
const authCollectionExp = new Array<Expression>();
const groupMap = new Map<string, Array<string>>();
const groupContainsExpression = new Array<Expression>();
if (!(roles.length > 0)) return [];
/**
* if ownerField is string
* ownerField: { eq: "cognito:owner" }
* if ownerField is a List
* ownerField: { contains: "cognito:owner"}
*
* if groupsField is a string
* groupsField: { in: "cognito:groups" }
* if groupsField is a list
* we create contains experession for each cognito group
* */
roles.forEach((role, idx) => {
const entityIsList = fieldIsList(fields, role.entity);
if (role.strategy === 'owner') {
const ownerCondition = entityIsList ? 'contains' : 'eq';
authCollectionExp.push(
...[
set(ref(`role${idx}`), getOwnerClaim(role.claim!)),
iff(
notEquals(ref(`role${idx}`), str(NONE_VALUE)),
qref(methodCall(ref('authFilter.add'), raw(`{"${role.entity}": { "${ownerCondition}": $role${idx} }}`))),
),
],
);
} else if (role.strategy === 'groups') {
// for fields where the group is a list and the token is a list we must add every group in the claim
if (entityIsList) {
if (groupMap.has(role.claim!)) {
groupMap.get(role.claim).push(role.entity);
} else {
groupMap.set(role.claim!, [role.entity]);
}
} else {
authCollectionExp.push(
...[
set(ref(`role${idx}`), getIdentityClaimExp(str(role.claim!), list([]))),
iff(
not(methodCall(ref(`role${idx}.isEmpty`))),
qref(methodCall(ref('authFilter.add'), raw(`{ "${role.entity}": { "in": $role${idx} } }`))),
),
],
);
}
}
});
for (let [groupClaim, fieldList] of groupMap) {
groupContainsExpression.push(
forEach(
ref('group'),
ref(`util.defaultIfNull($ctx.identity.claims.get("${groupClaim}"), [])`),
fieldList.map(field =>
iff(not(methodCall(ref(`group.isEmpty`))), qref(methodCall(ref('authFilter.add'), raw(`{"${field}": { "contains": $group }}`)))),
),
),
);
}
return [
iff(
not(ref(IS_AUTHORIZED_FLAG)),
compoundExpression([
set(ref('authFilter'), list([])),
...authCollectionExp,
...groupContainsExpression,
iff(
not(methodCall(ref('authFilter.isEmpty'))),
qref(methodCall(ref('ctx.stash.put'), str('authFilter'), raw('{ "or": $authFilter }'))),
),
]),
),
];
};
export const generateAuthExpressionForQueries = (
providers: ConfiguredAuthProviders,
roles: Array<RoleDefinition>,
fields: ReadonlyArray<FieldDefinitionNode>,
primaryFields: Array<string>,
isIndexQuery = false,
): string => {
const { cognitoStaticRoles, cognitoDynamicRoles, oidcStaticRoles, oidcDynamicRoles, apiKeyRoles, iamRoles, lambdaRoles } =
splitRoles(roles);
const getNonPrimaryFieldRoles = (roles: RoleDefinition[]) => roles.filter(roles => !primaryFields.includes(roles.entity));
const totalAuthExpressions: Array<Expression> = [
setHasAuthExpression,
set(ref(IS_AUTHORIZED_FLAG), bool(false)),
set(ref('primaryFieldMap'), obj({})),
];
if (providers.hasApiKey) {
totalAuthExpressions.push(apiKeyExpression(apiKeyRoles));
}
if (providers.hasLambda) {
totalAuthExpressions.push(lambdaExpression(lambdaRoles));
}
if (providers.hasIAM) {
totalAuthExpressions.push(iamExpression(iamRoles, providers.hasAdminRolesEnabled, providers.adminRoles, providers.identityPoolId));
}
if (providers.hasUserPools) {
totalAuthExpressions.push(
iff(
equals(ref('util.authType()'), str(COGNITO_AUTH_TYPE)),
compoundExpression([
...generateStaticRoleExpression(cognitoStaticRoles),
...generateAuthFilter(getNonPrimaryFieldRoles(cognitoDynamicRoles), fields),
...generateAuthOnModelQueryExpression(cognitoDynamicRoles, primaryFields, isIndexQuery),
]),
),
);
}
if (providers.hasOIDC) {
totalAuthExpressions.push(
iff(
equals(ref('util.authType()'), str(OIDC_AUTH_TYPE)),
compoundExpression([
...generateStaticRoleExpression(oidcStaticRoles),
...generateAuthFilter(getNonPrimaryFieldRoles(oidcDynamicRoles), fields),
...generateAuthOnModelQueryExpression(oidcDynamicRoles, primaryFields, isIndexQuery),
]),
),
);
}
totalAuthExpressions.push(
iff(and([not(ref(IS_AUTHORIZED_FLAG)), methodCall(ref('util.isNull'), ref('ctx.stash.authFilter'))]), ref('util.unauthorized()')),
);
return printBlock('Authorization Steps')(compoundExpression([...totalAuthExpressions, emptyPayload]));
};
export const generateAuthExpressionForRelationQuery = (
providers: ConfiguredAuthProviders,
roles: Array<RoleDefinition>,
fields: ReadonlyArray<FieldDefinitionNode>,
primaryFieldMap: RelationalPrimaryMapConfig,
) => {
const { cognitoStaticRoles, cognitoDynamicRoles, oidcStaticRoles, oidcDynamicRoles, apiKeyRoles, iamRoles, lambdaRoles } =
splitRoles(roles);
const getNonPrimaryFieldRoles = (roles: RoleDefinition[]) => roles.filter(roles => !primaryFieldMap.has(roles.entity));
const totalAuthExpressions: Array<Expression> = [setHasAuthExpression, set(ref(IS_AUTHORIZED_FLAG), bool(false))];
if (providers.hasApiKey) {
totalAuthExpressions.push(apiKeyExpression(apiKeyRoles));
}
if (providers.hasLambda) {
totalAuthExpressions.push(lambdaExpression(lambdaRoles));
}
if (providers.hasIAM) {
totalAuthExpressions.push(iamExpression(iamRoles, providers.hasAdminRolesEnabled, providers.adminRoles, providers.identityPoolId));
}
if (providers.hasUserPools) {
totalAuthExpressions.push(
iff(
equals(ref('util.authType()'), str(COGNITO_AUTH_TYPE)),
compoundExpression([
...generateStaticRoleExpression(cognitoStaticRoles),
...generateAuthFilter(getNonPrimaryFieldRoles(cognitoDynamicRoles), fields),
...generateAuthOnRelationalModelQueryExpression(cognitoDynamicRoles, primaryFieldMap),
]),
),
);
}
if (providers.hasOIDC) {
totalAuthExpressions.push(
iff(
equals(ref('util.authType()'), str(OIDC_AUTH_TYPE)),
compoundExpression([
...generateStaticRoleExpression(oidcStaticRoles),
...generateAuthFilter(getNonPrimaryFieldRoles(oidcDynamicRoles), fields),
...generateAuthOnRelationalModelQueryExpression(oidcDynamicRoles, primaryFieldMap),
]),
),
);
}
totalAuthExpressions.push(
iff(and([not(ref(IS_AUTHORIZED_FLAG)), methodCall(ref('util.isNull'), ref('ctx.stash.authFilter'))]), ref('util.unauthorized()')),
);
return printBlock('Authorization Steps')(compoundExpression([...totalAuthExpressions, emptyPayload]));
}; | the_stack |
import { Component, OnInit, Renderer2, ViewChild, ElementRef, Input } from '@angular/core';
import * as jp from 'jsplumb';
import { fromEvent } from 'rxjs';
import { WorkFlowFormControl, ControlTypeEnum } from '../model/workFlowFormControl';
import { ActivatedRoute } from '@angular/router';
import { WorkflowFormService } from 'src/app/business/workflow/workflow-form.service';
import { WorkFlowForm } from '../model/workflowForm';
import { NzMessageService } from 'ng-zorro-antd/message';
@Component({
selector: 'app-form-design',
templateUrl: './form-design.component.html',
styleUrls: ['./form-design.component.less']
})
export class FormDesignComponent implements OnInit {
@ViewChild('formArea', { static: true })
_formArea;
@ViewChild('label', { static: true })
_label;
@ViewChild('input', { static: true })
_input;
@ViewChild('select', { static: true })
_select;
@ViewChild('numberInput', { static: true })
_numberInput;
@ViewChild('datePicker', { static: true })
_datePicker;
@ViewChild('timePicker', { static: true })
_timePicker;
@ViewChild('multiLineInput', { static: true })
_multiLineInput;
isloading = false;
// 选中框
@ViewChild('selectedBorder', { static: true })
private _sborder: ElementRef;
// 节点数据
private _nodeDataList: WorkFlowFormControl[] = [];
// 表单设计数据
formData: WorkFlowForm = new WorkFlowForm();
// 选中节点的数据
checkedNodeData: WorkFlowFormControl = null;
private _jsPlumb = jp.jsPlumb;
private _jsPlumbInstance;
// 拖拽的节点类型key
private _draggedKey;
// 点击选中的节点
checkedNode = null;
// 字号
fontsize = [];
// 编辑select的选项
inputOption = null;
// 工作流ID
@Input()
workflowId = null;
@Input()
workflowName = null;
constructor(private _renderer: Renderer2,
private _route: ActivatedRoute,
private _formService: WorkflowFormService,
private _messageService: NzMessageService) { }
ngOnInit(): void {
this.initGraph();
this.initKeyboardListening();
this.initFormAreaClick();
this.initData();
for (let i = 1; i <= 32; i++) {
this.fontsize.push(i * 2);
}
}
// 初始化流程图
initGraph() {
this._jsPlumbInstance = this._jsPlumb.getInstance({
DragOptions: { cursor: 'move', zIndex: 2000 },
Container: 'formArea'
});
}
// 键盘事件
initKeyboardListening() {
fromEvent(window, 'keydown').subscribe((event: any) => {
if (this.checkedNode) {
if (event.key == 'ArrowDown') {
event.preventDefault();
let distance = Number.parseInt(this.checkedNode.style.top.replace('px', ''));
this._renderer.setStyle(this.checkedNode, 'top', `${distance + 3}px`);
this.checkedNodeData.top = distance + 3;
} else if (event.key == 'ArrowUp') {
event.preventDefault();
let distance = Number.parseInt(this.checkedNode.style.top.substring(0, this.checkedNode.style.top.length - 2));
this._renderer.setStyle(this.checkedNode, 'top', `${distance - 3}px`);
this.checkedNodeData.top = distance - 3;
} else if (event.key == 'ArrowLeft') {
event.preventDefault();
let distance = Number.parseInt(this.checkedNode.style.left.substring(0, this.checkedNode.style.left.length - 2));
this._renderer.setStyle(this.checkedNode, 'left', `${distance - 3}px`);
this.checkedNodeData.left = distance - 3;
} else if (event.key == 'ArrowRight') {
event.preventDefault();
let distance = Number.parseInt(this.checkedNode.style.left.substring(0, this.checkedNode.style.left.length - 2));
this._renderer.setStyle(this.checkedNode, 'left', `${distance + 3}px`);
this.checkedNodeData.left = distance + 3;
}
if (event.key == 'Delete') {
this._jsPlumbInstance.remove(this.checkedNode);
this._nodeDataList = this._nodeDataList.filter(data => data.domId != this.checkedNode.id);
this.checkedNode = null;
}
}
if (event.ctrlKey && event.key == 's') {
event.preventDefault();
this.save();
}
});
}
// 初始化流程图区域点击
initFormAreaClick() {
this._renderer.listen(this._formArea.nativeElement, 'mousedown', event => {
this.checkedNode = null;
this.checkedNodeData = null;
this._renderer.setStyle(this._sborder.nativeElement, 'display', 'none');
});
}
initData() {
this._formService.get(this.workflowId).subscribe((result: any) => {
this.formData = result.formResult;
this._nodeDataList = result.formControlResults;
if (!this.formData) {
this.formData = new WorkFlowForm();
this.formData.width = 595;
this.formData.height = 842;
this.formData.background = 'black';
}
// 初始化表单区域状态
this._renderer.setStyle(this._formArea.nativeElement, 'height', `${this.formData.height}px`);
this._renderer.setStyle(this._formArea.nativeElement, 'width', `${this.formData.width}px`);
this._renderer.setStyle(this._formArea.nativeElement, 'background-color', this.formData.background);
if (!this._nodeDataList) {
this._nodeDataList = new Array<WorkFlowFormControl>();
}
// 初始化各个元素状态
this.checkedNode = null;
for (let node of this._formArea.nativeElement.childNodes) {
this._renderer.removeChild(this._formArea.nativeElement, node);
}
this._nodeDataList.forEach(nodeData => {
this.initNode(nodeData);
});
});
}
// 根据数据绘制节点
initNode(node: WorkFlowFormControl) {
node.optionList = node.options ? node.options.split(',') : [];
let id = node.domId;
let ele;
switch (node.controlType) {
case 1:
ele = this._label;
break;
case 2:
ele = this._input;
break;
case 3:
ele = this._select;
break;
case 4:
ele = this._numberInput;
break;
case 5:
ele = this._datePicker;
break;
case 6:
ele = this._timePicker;
break;
case 7:
ele = this._multiLineInput;
this._renderer.setAttribute(ele.nativeElement.firstChild, 'rows', `${node.line}`);
break;
}
let newEle = ele.nativeElement.cloneNode(true);
this._renderer.setAttribute(newEle, 'id', id);
this._renderer.setStyle(newEle, 'z-index', '0');
this._renderer.setStyle(newEle, 'opacity', '1');
this._renderer.setStyle(newEle, 'top', `${node.top}px`);
this._renderer.setStyle(newEle, 'left', `${node.left}px`);
if (node.controlType != 1) {
this._renderer.setStyle(newEle.firstChild, 'width', `${node.width}px`);
this._renderer.setStyle(newEle, 'width', `${node.width}px`);
} else {
newEle.firstChild.innerText = node.content;
}
this._renderer.setStyle(newEle, 'font-size', `${node.fontSize}px`);
// 设置节点事件
this._renderer.listen(newEle, 'mousedown', event => {
this.checkedNode = newEle;
this.checkedNodeData = this._nodeDataList.find(data => data.domId == newEle.id);
let rect = newEle.getBoundingClientRect();
this._renderer.setStyle(this._sborder.nativeElement, 'width', `${rect.width}px`);
this._renderer.setStyle(this._sborder.nativeElement, 'height', `${rect.height}px`);
this._renderer.setStyle(this._sborder.nativeElement, 'display', 'block');
this._renderer.appendChild(newEle, this._sborder.nativeElement);
});
this._renderer.appendChild(this._formArea.nativeElement, newEle);
this._jsPlumbInstance.draggable(newEle, {
containment: true,
drag: (event) => {
this.checkedNodeData.top = Number.parseInt(event.el.style.top.replace('px', ''));
this.checkedNodeData.left = Number.parseInt(event.el.style.left.replace('px', ''));
}
});
}
onDragStart(event, key) {
this._draggedKey = key;
}
onDragOver(event) {
event.preventDefault();
}
// drop事件
dropZone(event) {
event.preventDefault();
let rect = event.currentTarget.getBoundingClientRect();
let x = event.clientX - rect.left;
let y = event.clientY - rect.top;
let id = `control${this.randomKey()}`;
let ele;
let control = new WorkFlowFormControl();
switch (this._draggedKey) {
case 1:
ele = this._label;
control.content = '标签';
break;
case 2:
ele = this._input;
break;
case 3:
ele = this._select;
control.optionList = [];
break;
case 4:
ele = this._numberInput;
break;
case 5:
ele = this._datePicker;
break;
case 6:
ele = this._timePicker;
break;
case 7:
ele = this._multiLineInput;
control.line = 4;
break;
}
let eleRect = ele.nativeElement.getBoundingClientRect();
let newEle = ele.nativeElement.cloneNode(true);
x = Math.floor(x - eleRect.width / 2);
y = Math.floor(y - eleRect.height / 2);
this._renderer.setAttribute(newEle, 'id', id);
this._renderer.setStyle(newEle, 'z-index', '0');
this._renderer.setStyle(newEle, 'opacity', '1');
this._renderer.setStyle(newEle, 'top', `${y}px`);
this._renderer.setStyle(newEle, 'left', `${x}px`);
// 设置节点事件
this._renderer.listen(newEle, 'mousedown', event => {
this.checkedNode = newEle;
// 把选项数据分割成list
this.checkedNodeData = this._nodeDataList.find(data => data.domId == newEle.id);
this.checkedNodeData.optionList = this.checkedNodeData.options ? this.checkedNodeData.options.split(',') : [];
// 点击选中的效果
let rect = newEle.getBoundingClientRect();
this._renderer.setStyle(this._sborder.nativeElement, 'width', `${rect.width}px`);
this._renderer.setStyle(this._sborder.nativeElement, 'height', `${rect.height}px`);
this._renderer.setStyle(this._sborder.nativeElement, 'display', 'block');
this._renderer.appendChild(newEle, this._sborder.nativeElement);
});
this._renderer.appendChild(this._formArea.nativeElement, newEle);
this._jsPlumbInstance.draggable(newEle, {
containment: true,
drag: (event) => {
this.checkedNodeData.top = Math.floor(event.el.style.top.replace('px', ''));
this.checkedNodeData.left = Math.floor(event.el.style.left.replace('px', ''));
}
});
control.domId = id;
control.controlType = this._draggedKey;
control.width = 200;
control.fontSize = 14;
control.left = x;
control.top = y;
this._nodeDataList.push(control);
}
formHeightChanged(event) {
this._renderer.setStyle(this._formArea.nativeElement, 'height', `${event}px`);
}
formWidthChanged(event) {
this._renderer.setStyle(this._formArea.nativeElement, 'width', `${event}px`);
}
reloadFormSize(event) {
this.formData.width = 595;
this.formData.height = 842;
this._renderer.setStyle(this._formArea.nativeElement, 'width', `${595}px`);
this._renderer.setStyle(this._formArea.nativeElement, 'height', `${842}px`);
}
formBackGroundChanged(event) {
this._renderer.setStyle(this._formArea.nativeElement, 'background-color', event);
}
fontSizeChange(event) {
this._renderer.setStyle(this.checkedNode.firstChild, 'font-size', `${event}px`);
setTimeout(() => {
let rect = this.checkedNode.getBoundingClientRect();
this._renderer.setStyle(this._sborder.nativeElement, 'height', `${rect.height}px`);
this._renderer.setStyle(this._sborder.nativeElement, 'width', `${rect.width}px`);
}, 300);
}
widthChanged(event) {
this._renderer.setStyle(this.checkedNode.firstChild, 'width', `${event}px`);
this._renderer.setStyle(this._sborder.nativeElement, 'width', `${event}px`);
}
topChanged(event) {
this._renderer.setStyle(this.checkedNode, 'top', `${event}px`);
}
leftChanged(event) {
this._renderer.setStyle(this.checkedNode, 'left', `${event}px`);
}
contentChanged(event) {
this.checkedNode.firstChild.innerText = event;
let rect = this.checkedNode.getBoundingClientRect();
this._renderer.setStyle(this._sborder.nativeElement, 'width', `${rect.width}px`);
}
lineChanged(event) {
this._renderer.setAttribute(this.checkedNode.firstChild, 'rows', event);
let rect = this.checkedNode.getBoundingClientRect();
this._renderer.setStyle(this._sborder.nativeElement, 'height', `${rect.height}px`);
}
optionEnter(event) {
this.checkedNodeData.optionList.push(this.inputOption);
this.inputOption = null;
}
removeOption(event) {
this.checkedNodeData.optionList = this.checkedNodeData.optionList.filter(item => item !== event.currentTarget.innerText);
}
setVertialPosition(flg) {
switch (flg) {
case 'left':
this.leftChanged(0);
this.checkedNodeData.left = 0;
break;
case 'middle':
let rect = this.checkedNode.getBoundingClientRect();
let left = Math.round((this.formData.width - rect.width) / 2);
this.leftChanged(left);
this.checkedNodeData.left = left;
break;
case 'right':
let rrect = this.checkedNode.getBoundingClientRect();
this.leftChanged((this.formData.width - rrect.width));
this.checkedNodeData.left = this.formData.width - rrect.width;
break;
}
}
back() {
history.go(-1);
}
save() {
this.isloading = true;
// 把选项list拼接成string
for (let data of this._nodeDataList) {
data.options = data.optionList?.join(',');
}
this._formService.addOrUpdate({
workFlowId: Number.parseInt(this.workflowId),
formViewModel: this.formData,
formControlViewModels: this._nodeDataList
}).subscribe(result => {
this._messageService.success('保存成功!');
this.initData();
this.isloading = false;
}, error => {
this.isloading = false;
});
}
formatterPiex = (value: number) => {
return `${value} px`
};
parserPiex = (value: string) => value.replace(' px', '');
randomKey(): number {
return Date.parse(new Date().toString()) + Math.floor(Math.random() * Math.floor(999));
}
} | the_stack |
import { createConnection, IConnection } from 'vscode-languageserver';
import * as fs from 'fs';
export class OracleConnection {
// Create a connection for the server. The connection uses Node's IPC as a transport.
// Also include all preview / proposed LSP features.
private static _connection: IConnection;
private static _oracleDB;
private static _oracleConnection;
private static _customID = 0;
private static _customConnections = {};
private static ORACLE_DB_VERSION = 'oracledb@"^3.0.0"';
public static init() {
this._connection = createConnection(/*ProposedFeatures.all*/);
[
{name: 'Oracle/install', fn: this.installOracle},
{name: 'Oracle/init', fn: this.initOracle},
{name: 'Oracle/connect', fn: this.connect},
{name: 'Oracle/disconnect', fn: this.disconnect},
{name: 'Oracle/execCommand', fn: this.execCommand}
].forEach(request => {
this._connection.onRequest(request.name, (params) => request.fn.call(this, params));
});
this._connection.listen();
}
private static createOracleDirectory() {
return new Promise<any>((resolve, reject) => {
const directory = '../node_modules/oracledb';
fs.stat(directory, (err, stats) => {
if (!err)
return resolve(false);
// Check if error defined and the error code is "not exists"
if (err.code === 'ENOENT') {
// Create the directory, call the callback.
fs.mkdir(directory, error => {
if (error)
return reject('OracleDB failed create directory '+error);
return resolve(true);
});
} else
return reject('OracleDB failed check directory '+err);
});
});
}
// private static installOracle(): Promise<any> {
// return new Promise<any>((resolve, reject) => {
// this.createOracleDirectory()
// .then((install) => {
// if (!install)
// return resolve('OracleDB already installed');
// // No warranty (http://abulletproofidea.com/questions/5157/puis-je-installer-un-paquet-npm-a-partir-de-javascript-execute-dans-node-js)
// // directory npm is deleted, why ???
// const npm = require('npm');
// npm.load({}, err => {
// if (err)
// return resolve({error: 'OracleDB - npm load failed ' + err});
// npm.commands.install([ORACLE_DB_VERSION], (err, data) => {
// if (err)
// return resolve({error: 'OracleDB - install failed '+ err});
// return resolve('OracleDB - install work '+JSON.stringify(data));
// })
// })
// })
// .catch(err => resolve({error: err}));
// });
// }
private static installOracle(): Promise<any> {
return new Promise<any>((resolve, reject) => {
this.createOracleDirectory()
.then(install => {
if (!install)
return resolve('OracleDB already installed');
this._connection.sendNotification('Oracle/install', `Start install ${OracleConnection.ORACLE_DB_VERSION}...`);
require('child_process').exec(`npm install ${OracleConnection.ORACLE_DB_VERSION}`,
(err, stdout, stderr) => {
this._connection.sendNotification('Oracle/install', `...End install ${OracleConnection.ORACLE_DB_VERSION}`);
if (err)
resolve({error: err});
if (stderr)
resolve({stderror: stderr});
resolve({install: stdout});
});
});
});
}
private static initOracle() {
return new Promise<any>((resolve, reject) => {
try {
this._oracleDB = require('oracledb');
this._oracleDB.fetchAsString = [this._oracleDB.CLOB];
return resolve('oracleDB work');
} catch (e) {
return resolve({error : 'oracleDB failed: '+e + 'ENV: '+process.env});
}
});
}
private static execCommand(params): Promise<any> {
return new Promise<any>((resolve, reject) => {
if (!this._oracleDB)
return resolve({error: 'OracleDB is missing'});
if ( !(params && params.connection) && !this._oracleConnection)
return resolve({error: 'Connection is missing'});
this.internalExecCommand(params)
.then(data => resolve(data))
.catch(err => resolve(err));
});
}
private static internalExecCommand(params): Promise<any> {
return new Promise<any>((resolve, reject) => {
const cmd = params.sql.trim().toLowerCase();
let internalConnection;
if (params.connection) {
internalConnection = this._customConnections[params.connection.customID];
if (!internalConnection)
return reject({ params: params, error: 'connection not found ', list: this._customConnections, connection: internalConnection });
} else
internalConnection = this._oracleConnection;
if (cmd === 'commit' || cmd === 'rollback')
internalConnection[cmd]()
.then(() => resolve({ data: cmd }))
.catch(err => reject({ error: this.formatOracleError(err) }));
else {
// this._connection.sendNotification('Oracle/debug', 'ExecCmd');
// if no params, don't add an arguments null !
params.params = params.params || {};
params.opt = params.opt || {};
internalConnection.execute(params.sql, params.params, params.opt)
.then(result => resolve({ params: params, data: result }))
.catch(err => reject({ params: params, error: this.formatOracleError(err) }));
}
});
}
private static connect(params): Promise<any> {
return new Promise<any>((resolve, reject) => {
if (!this._oracleDB)
return resolve({error: 'OracleDB is missing'});
const result: any = {};
Promise.resolve()
.then(() => {
if (params && !params.custom && this._oracleConnection)
return this.disconnect();
return;
})
.then((data) => {
// disconnect error
if (data && data.error)
result.disconnect = data;
return this.internalConnect(params);
})
.then(connection => {
if (params.custom) {
connection.customID = ++this._customID;
this._customConnections[connection.customID] = connection;
} else
this._oracleConnection = connection;
result.connection = connection;
result.connected = true;
if (params.schema)
result.schema = params.schema;
if (!params.loginScript)
return;
else
return this.internalExecConnectCommand(params);
})
.then(data => {
if (data)
result.loginScript = data;
return resolve(result);
})
.catch(err => {
result.error = err;
return resolve(result);
});
});
}
private static internalConnect(params): Promise<any> {
return new Promise<any>((resolve, reject) => {
if (!params)
return reject('No params !');
const connectParams = {
user: params.user || params.username,
password: params.password || params.username,
connectString: params.connectString || params.database,
privilege: this._oracleDB[params.privilege]
};
this._oracleDB.getConnection(connectParams, (err, connection) => {
if (err)
return reject({ error: this.formatOracleError(err), params: connectParams });
return resolve(connection);
});
});
}
private static internalExecConnectCommand(params): Promise<any> {
return new Promise<any>((resolve, reject) => {
this.internalExecCommand({sql: params.loginScript})
.then(data => resolve(data))
.catch(err => resolve(err)); // Not considered as connection error
});
}
private static disconnect(params?): Promise<any> {
return new Promise<any>((resolve, reject) => {
let internalConnection;
if (params && params.connection) {
internalConnection = this._customConnections[params.connection.customID];
if (!internalConnection)
return resolve({ params: params, error: 'connection not found' });
} else {
if (!this._oracleConnection)
return resolve(true);
internalConnection = this._oracleConnection;
}
internalConnection.close(err => {
if (err)
return resolve({error: err});
if (params && params.connection)
delete this._customConnections[params.connection.customID];
else
delete this._oracleConnection;
return resolve(true);
});
});
}
private static formatOracleError(error) {
// re-format oracle error to be able to stringify
return {
message: error.message,
num: error.errorNum,
offset: error.offset
};
}
}
{
OracleConnection.init();
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.