text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { Quantity, PromiEvent, Subscription, Api } from "@ganache/utils";
import Blockchain from "./blockchain";
import {
StartDealParams,
SerializedStartDealParams
} from "./things/start-deal-params";
import { SerializedRootCID, RootCID } from "./things/root-cid";
import { DealInfo, SerializedDealInfo } from "./things/deal-info";
import { SerializedTipset, Tipset } from "./things/tipset";
import { Address, AddressProtocol, SerializedAddress } from "./things/address";
import {
SerializedRetrievalOrder,
RetrievalOrder
} from "./things/retrieval-order";
import { SerializedQueryOffer } from "./things/query-offer";
import Emittery from "emittery";
import { HeadChange, HeadChangeType } from "./things/head-change";
import { SubscriptionMethod, SubscriptionId } from "./types/subscriptions";
import { FileRef, SerializedFileRef } from "./things/file-ref";
import { MinerPower, SerializedMinerPower } from "./things/miner-power";
import { PowerClaim } from "./things/power-claim";
import { MinerInfo, SerializedMinerInfo } from "./things/miner-info";
import { SerializedVersion, Version } from "./things/version";
import { Message, SerializedMessage } from "./things/message";
import {
MessageSendSpec,
SerializedMessageSendSpec
} from "./things/message-send-spec";
import {
SerializedSignedMessage,
SignedMessage
} from "./things/signed-message";
import { KeyType } from "./things/key-type";
import { KeyInfo, SerializedKeyInfo } from "./things/key-info";
import { SerializedSignature, Signature } from "./things/signature";
import { SigType } from "./things/sig-type";
import { SerializedBlockHeader } from "./things/block-header";
import { SerializedBlockMessages } from "./things/block-messages";
import { StorageDealStatus } from "./types/storage-deal-status";
export default class FilecoinApi implements Api {
readonly [index: string]: (...args: any) => Promise<any>;
readonly #getId = (id => () => Quantity.from(++id))(0);
readonly #subscriptions = new Map<string, Emittery.UnsubscribeFn>();
readonly #blockchain: Blockchain;
constructor(blockchain: Blockchain) {
this.#blockchain = blockchain;
}
async initialize() {
await this.#blockchain.initialize();
}
async stop(): Promise<void> {
return await this.#blockchain.stop();
}
/**
* Provides information about the provider.
*
* @returns A `Version` object with various version details
* and the current block interval.
*/
async "Filecoin.Version"(): Promise<SerializedVersion> {
return new Version({
blockDelay: BigInt(
this.#blockchain.minerEnabled
? this.#blockchain.options.miner.blockTime
: 0
)
}).serialize();
}
/**
* Returns the libp2p Peer ID. Since Filecoin-flavored Ganache
* does not connect to a network, it doesn't leverage libp2p.
* This method instead returns a hardcoded Peer ID based on
* the string "ganache".
*
* @returns `bafzkbzaced47iu7qygeshb3jamzkh2cqcmlxzcpxrnqsj6yoipuidor523jyg`
*/
async "Filecoin.ID"(): Promise<string> {
// This is calculated with the below code
// Hardcoded as there's no reason to recalculate each time
// mh = require("multihashing")(Buffer.from("ganache"), "blake2b-256");
// (new require("peer-id")(mh)).toString()
// Not sure what else to put here since we don't implement
// the Filecoin P2P network
return "bafzkbzaced47iu7qygeshb3jamzkh2cqcmlxzcpxrnqsj6yoipuidor523jyg";
}
/**
* Returns the genesis tipset (tipset.Height = 0).
*
* @returns The genesis tipset.
*/
async "Filecoin.ChainGetGenesis"(): Promise<SerializedTipset> {
const tipset = this.#blockchain.genesisTipset();
return tipset.serialize();
}
/**
* Returns the head of the blockchain, which is the latest tipset.
*
* @returns The latest tipset.
*/
async "Filecoin.ChainHead"(): Promise<SerializedTipset> {
const tipset = this.#blockchain.latestTipset();
return tipset.serialize();
}
/**
* Starts a subscription to receive the latest tipset once
* it has been mined.
*
* Reference implementation entry point: https://git.io/JtO3a
*
* @param rpcId - This parameter is not provided by the user, but
* injected by the internal system.
* @returns An object with the subscription ID and an unsubscribe
* function.
*/
"Filecoin.ChainNotify"(rpcId?: string): PromiEvent<Subscription> {
const subscriptionId = this.#getId();
let promiEvent: PromiEvent<Subscription>;
const currentHead = new HeadChange({
type: HeadChangeType.HCCurrent,
val: this.#blockchain.latestTipset()
});
const unsubscribeFromEmittery = this.#blockchain.on(
"tipset",
(tipset: Tipset) => {
// Ganache currently doesn't support Filecoin reorgs,
// so we'll always only have one tipset per head change
// See reference implementations here: https://git.io/JtOOk;
// other lines of interest are line 207 which shows only the chainstore only
// references the "hcnf" (head change notification function) in the
// reorgWorker function (lines 485-560)
// Ganache currently doesn't support Filecoin reverts,
// so we'll always use HCApply for now
const newHead = new HeadChange({
type: HeadChangeType.HCApply,
val: tipset
});
if (promiEvent) {
promiEvent.emit("message", {
type: SubscriptionMethod.ChannelUpdated,
data: [subscriptionId.toString(), [newHead.serialize()]]
});
}
}
);
const unsubscribe = (): void => {
unsubscribeFromEmittery();
// Per https://git.io/JtOc1 and https://git.io/JtO3H
// implementations, we're should cancel the subscription
// since the protocol technically supports multiple channels
// per subscription, but implementation seems to show that there's
// only one channel per subscription
if (rpcId) {
promiEvent.emit("message", {
type: SubscriptionMethod.SubscriptionCanceled,
data: [rpcId]
});
}
};
promiEvent = PromiEvent.resolve({
unsubscribe,
id: subscriptionId
});
// There currently isn't an unsubscribe method,
// but it would go here
this.#subscriptions.set(subscriptionId.toString()!, unsubscribe);
promiEvent.emit("message", {
type: SubscriptionMethod.ChannelUpdated,
data: [subscriptionId.toString(), [currentHead.serialize()]]
});
return promiEvent;
}
/**
* Receives the `xrpc.ch.close` method which cancels a
* subscription.
*
* @param subscriptionId - The subscription ID to cancel.
* @returns `false` if the subscription ID doesn't exist or
* if the subscription is already canceled, `true` otherwise.
*/
[SubscriptionMethod.ChannelClosed](
subscriptionId: SubscriptionId
): Promise<boolean> {
const subscriptions = this.#subscriptions;
const unsubscribe = this.#subscriptions.get(subscriptionId);
if (unsubscribe) {
subscriptions.delete(subscriptionId);
unsubscribe();
return Promise.resolve(true);
} else {
return Promise.resolve(false);
}
}
/**
* Returns the tipset for the provided tipset key.
*
* @param serializedTipsetKey - an array of the Block RootCIDs
* that are part of the tipset. Must be an exact match and
* must include exactly the same number of blocks that are
* actually in the tipset.
* @returns The matched tipset.
*/
async "Filecoin.ChainGetTipSet"(
serializedTipsetKey: Array<SerializedRootCID>
): Promise<SerializedTipset> {
await this.#blockchain.waitForReady();
const tipset = await this.#blockchain.getTipsetFromKey(
serializedTipsetKey.map(serializedCid => new RootCID(serializedCid))
);
return tipset.serialize();
}
/**
* Returns the tipset for the provided tipset height.
*
* @param height - A `number` which indicates the `tipset.Height`
* that you would like to retrieve.
* @param serializedTipsetKey - An optional tipset key, an array
* of the Block RootCIDs that are part of the tipset. Must be
* an exact match and must include exactly the same number of
* blocks that are actually in the tipset.
* @returns The matched tipset.
*/
async "Filecoin.ChainGetTipSetByHeight"(
height: number,
serializedTipsetKey?: Array<SerializedRootCID>
): Promise<SerializedTipset> {
await this.#blockchain.waitForReady();
let tipset: Tipset;
// we check if serializedTipsetKey is an array as well because
// of our voodoo json rpc ID gets appended to the args
if (serializedTipsetKey && Array.isArray(serializedTipsetKey)) {
tipset = await this.#blockchain.getTipsetByHeight(
height,
serializedTipsetKey.map(serializedCid => new RootCID(serializedCid))
);
} else {
tipset = await this.#blockchain.getTipsetByHeight(height);
}
return tipset.serialize();
}
/**
* Returns a block for the given RootCID.
*
* @param serializedBlockCid - The RootCID of the block.
* @returns The matched Block.
*/
async "Filecoin.ChainGetBlock"(
serializedBlockCid: SerializedRootCID
): Promise<SerializedBlockHeader> {
await this.#blockchain.waitForReady();
const blockCid = new RootCID(serializedBlockCid);
const blockHeader = await this.#blockchain.blockHeaderManager!.get(
blockCid.root.value
);
if (!blockHeader) {
throw new Error("Could not find a block for the provided CID");
}
return blockHeader.serialize();
}
/**
* Returns the BlockMessages object, or all of the messages
* that are part of a block, for a given block RootCID.
*
* @param serializedBlockCid - The RootCID of the block.
* @returns The matched BlockMessages object.
*/
async "Filecoin.ChainGetBlockMessages"(
serializedBlockCid: SerializedRootCID
): Promise<SerializedBlockMessages> {
await this.#blockchain.waitForReady();
const blockCid = new RootCID(serializedBlockCid);
const blockMessages = await this.#blockchain.blockMessagesManager!.getBlockMessages(
blockCid.root
);
if (!blockMessages) {
throw new Error("Could not find a block for the provided CID");
}
return blockMessages.serialize();
}
/**
* Returns a Message for a given RootCID.
*
* @param serializedMessageCid - The RootCID of the message.
* @returns The matched Message object.
*/
async "Filecoin.ChainGetMessage"(
serializedMessageCid: SerializedRootCID
): Promise<SerializedMessage> {
await this.#blockchain.waitForReady();
const blockMessageCid = new RootCID(serializedMessageCid);
const signedMessage = await this.#blockchain.signedMessagesManager!.get(
blockMessageCid.root.value
);
if (!signedMessage) {
throw new Error("Could not find a message for the provided CID");
}
return signedMessage.message.serialize();
}
/**
* Gets the next nonce of an address, including any pending
* messages in the current message pool.
*
* @param address - A `string` of the public address.
* @returns A `number` of the next nonce.
*/
async "Filecoin.MpoolGetNonce"(address: string): Promise<number> {
await this.#blockchain.waitForReady();
const account = await this.#blockchain.accountManager!.getAccount(address);
const pendingMessagesForAccount = this.#blockchain.messagePool.filter(
queuedMessage => queuedMessage.message.from === address
);
if (pendingMessagesForAccount.length === 0) {
// account.nonce already stores the "next nonce"
// don't add more to it
return account.nonce;
} else {
// in this case, we have messages in the pool with
// already incremented nonces (account.nonce only
// increments when the block is mined). this will
// generate a nonce greater than any other nonce
const nonceFromPendingMessages = pendingMessagesForAccount.reduce(
(nonce, m) => {
return Math.max(nonce, m.message.nonce);
},
account.nonce
);
return nonceFromPendingMessages + 1;
}
}
/**
* Submits a signed message to be added to the message
* pool.
*
* Only value transfers are supported (`Method = 0`).
*
* @param signedMessage - The SignedMessage object.
* @returns The RootCID of the signed message.
*/
async "Filecoin.MpoolPush"(
signedMessage: SerializedSignedMessage
): Promise<SerializedRootCID> {
const rootCid = await this.#blockchain.pushSigned(
new SignedMessage(signedMessage)
);
return rootCid.serialize();
}
/**
* Submits an array of signed messages to be added to
* the message pool.
*
* Messages are processed in index order of the array;
* if any of them are invalid for any reason, the valid
* messages up to that point are still added to the message
* pool. The invalid message, as well as following messages
* in the array, will not be processed or added to the
* message pool.
*
* Only value transfers are supported (`Method = 0`).
*
* Reference implementation: https://git.io/JtgeG
*
* @param signedMessages - The array of SignedMessage objects.
* @returns An array of RootCIDs for signed messages that
* were valid and added to the message pool. The order of the
* output array matches the order of the input array.
*/
async "Filecoin.MpoolBatchPush"(
signedMessages: Array<SerializedSignedMessage>
): Promise<Array<SerializedRootCID>> {
const cids: RootCID[] = [];
// The lotus code makes it seem like it tries to
// still send a response with the signed messages that
// succeeded if one of them fails (see line 195 in ref impl).
// However, after trying it on lotus-devnet, I only receive the
// error (if the second message is the one that errors).
// So just letting the error bubble up should do the trick here.
// The reference implementation also doesn't revert/clear the messages
// that did successfully get added.
for (const signedMessage of signedMessages) {
const cid = await this.#blockchain.pushSigned(
new SignedMessage(signedMessage)
);
cids.push(cid);
}
return cids.map(c => c.serialize());
}
/**
* Submits an unsigned message to be added to the message
* pool.
*
* The `From` address must be one of the addresses held
* in the wallet; see `Filecoin.WalletList` to retrieve
* a list of addresses currently in the wallet. The `Nonce`
* must be `0` and is filled in with the correct value in
* the response object. Gas-related parameters will be
* generated if not filled.
*
* Only value transfers are supported (`Method = 0`).
*
* @param message - The Message object.
* @param spec - The MessageSendSpec object which defines
* the MaxFee.
* @returns The corresponding SignedMessage that was added
* to the message pool.
*/
async "Filecoin.MpoolPushMessage"(
message: SerializedMessage,
spec: SerializedMessageSendSpec
): Promise<SerializedSignedMessage> {
const signedMessage = await this.#blockchain.push(
new Message(message),
new MessageSendSpec(spec)
);
return signedMessage.serialize();
}
/**
* Submits an array of unsigned messages to be added to
* the message pool.
*
* Messages are processed in index order of the array;
* if any of them are invalid for any reason, the valid
* messages up to that point are still added to the message
* pool. The invalid message, as well as following messages
* in the array, will not be processed or added to the
* message pool.
*
* The `From` address must be one of the addresses
* held in the wallet; see `Filecoin.WalletList` to retrieve
* a list of addresses currently in the wallet. The `Nonce`
* must be `0` and is filled in with the correct value in
* the response object. Gas-related parameters will be
* generated if not filled.
*
* Only value transfers are supported (`Method = 0`).
*
* Reference implementation: https://git.io/JtgeU
*
* @param messages - The array of Message objects.
* @param spec - The MessageSendSpec object which defines
* the MaxFee.
* @returns An array of SignedMessages that were valid and
* added to the message pool. The order of the output array
* matches the order of the input array.
*/
async "Filecoin.MpoolBatchPushMessage"(
messages: Array<SerializedMessage>,
spec: SerializedMessageSendSpec
): Promise<Array<SerializedSignedMessage>> {
const signedMessages: SignedMessage[] = [];
// The lotus code makes it seem like it tries to
// still send a response with the signed messages that
// succeeded if one of them fails (see line 219 in ref impl).
// However, after trying it on lotus-devnet, I only receive the
// error (if the second message is the one that errors).
// So just letting the error bubble up should do the trick here.
// The reference implementation also doesn't revert/clear the messages
// that did successfully get added.
for (const message of messages) {
const signedMessage = await this.#blockchain.push(
new Message(message),
new MessageSendSpec(spec)
);
signedMessages.push(signedMessage);
}
return signedMessages.map(sm => sm.serialize());
}
/**
* Clears the current pending message pool; any messages in
* the pool will not be processed in the next tipset/block
* mine.
*
* @param local - In a normal Lotus node, setting this to `true`
* will only clear local messages from the message pool. Since
* Filecoin-flavored Ganache doesn't have a network, all messages
* are local, and therefore all messages from the message pool
* will be removed regardless of the value of this flag.
*/
async "Filecoin.MpoolClear"(local: boolean): Promise<void> {
await this.#blockchain.mpoolClear(local);
}
/**
* Returns a list of messages in the current pending message
* pool.
*
* @param tipsetKey - A normal Lotus node accepts an optional single
* parameter of the TipsetKey to refer to the pending messages.
* However, with the design of Filecoin-flavored Ganache, this
* parameter is not used.
* @returns An array of SignedMessage objects that are in the message pool.
*/
async "Filecoin.MpoolPending"(
tipsetKey: Array<RootCID>
): Promise<Array<SerializedSignedMessage>> {
const signedMessages = await this.#blockchain.mpoolPending();
return signedMessages.map(signedMessage => signedMessage.serialize());
}
/**
* Returns a list of pending messages for inclusion in the next block.
* Since all messages in the message pool are included in the next
* block for Filecoin-flavored Ganache, this method returns the same
* result as `Filecoin.MpoolPending`.
*
* Reference implementation: https://git.io/Jt24C
*
* @param tipsetKey - A normal Lotus node accepts an optional
* parameter of the TipsetKey to refer to the pending messages.
* However, with the design of Filecoin-flavored Ganache, this
* parameter is not used in Ganache.
* @param ticketQuality - Since all messages are included in the next
* block in Ganache, this number is ignored. A normal Lotus node uses
* this number to help determine which messages are going to be included
* in the next block. This parameter is also not used in Ganache.
*
* @returns
*/
async "Filecoin.MpoolSelect"(
tipsetKey: Array<RootCID>,
ticketQuality: number
): Promise<Array<SerializedSignedMessage>> {
const signedMessages = await this.#blockchain.mpoolPending();
return signedMessages.map(signedMessage => signedMessage.serialize());
}
/**
* Returns the miner actor address for the Filecoin-flavored
* Ganache node. This value is always the same and doesn't change.
*
* @returns `t01000`
*/
async "Filecoin.ActorAddress"(): Promise<string> {
return this.#blockchain.miner.value;
}
/**
* Returns a list of the miner addresses for the
* Filecoin-flavored Ganache. Ganache always has
* the same single miner.
*
* @returns `[ "t01000" ]`
*/
async "Filecoin.StateListMiners"(): Promise<Array<string>> {
return [this.#blockchain.miner.value];
}
/**
* Returns the miner power of a given miner address.
*
* "A storage miner's storage power is a value roughly proportional
* to the amount of storage capacity they make available on behalf
* of the network via capacity commitments or storage deals."
* From: https://docs.filecoin.io/reference/glossary/#storage-power
*
* Since Ganache is currently only supporting 1 miner per Ganache
* instance, then it will have a raw byte power of 1n and everything else will
* have 0n. This indicates the supported miner contains all of the storage
* power for the entire network (which is true). Any number would do, so we'll
* stick with 1n.
*
* Quality adjusted power will be 0n always as relative
* power doesn't change:
* "The storage power a storage miner earns from a storage deal offered by a
* verified client will be augmented by a multiplier."
* https://docs.filecoin.io/reference/glossary/#quality-adjusted-storage-power
*
* @param minerAddress - The miner address to get miner power for.
* @returns The MinerPower object.
*/
async "Filecoin.StateMinerPower"(
minerAddress: string
): Promise<SerializedMinerPower> {
if (minerAddress === this.#blockchain.miner.value) {
const power = new MinerPower({
minerPower: new PowerClaim({
rawBytePower: 1n,
qualityAdjPower: 0n
}),
totalPower: new PowerClaim({
rawBytePower: 1n,
qualityAdjPower: 0n
}),
hasMinPower: false
});
return power.serialize();
} else {
const power = new MinerPower({
minerPower: new PowerClaim({
rawBytePower: 0n,
qualityAdjPower: 0n
}),
totalPower: new PowerClaim({
rawBytePower: 0n,
qualityAdjPower: 0n
}),
hasMinPower: false
});
return power.serialize();
}
}
/**
* Returns the miner info for the given miner address.
*
* @param minerAddress -
* @param tipsetKey - A normal Lotus node uses tipsetKey to get the
* miner info at that Tipset. However, the miner info in
* Filecoin-flavored Ganache will not change based on the tipset,
* so this parameter is ignored by Ganache.
* @returns The MinerInfo object.
*/
async "Filecoin.StateMinerInfo"(
minerAddress: string,
tipsetKey: Array<RootCID>
): Promise<SerializedMinerInfo> {
if (minerAddress === this.#blockchain.miner.value) {
// The defaults are set up to correspond to the current
// miner address t0100, which is not configurable currently
return new MinerInfo().serialize();
} else {
throw new Error("Failed to load miner actor: actor not found");
}
}
/**
* Returns the default address of the wallet; this is also the first address
* that is returned in `Filecoin.WalletList`.
*
* @returns A `string` of the public address.
*/
async "Filecoin.WalletDefaultAddress"(): Promise<SerializedAddress> {
await this.#blockchain.waitForReady();
const accounts = await this.#blockchain.accountManager!.getControllableAccounts();
return accounts[0].address.serialize();
}
/**
* Sets the default address to the provided address. This will move the
* address from its current position in the `Filecoin.WalletList` response
* to the front of the array. This change is persisted across Ganache sessions
* if you are using a persisted database with `database.db` or
* `database.dbPath` options.
*
* @param address - The public address to set as the default address. Must be an address
* that is in the wallet; see `Filecoin.WalletList` to get a list of addresses
* in the wallet.
*/
async "Filecoin.WalletSetDefault"(address: string): Promise<void> {
await this.#blockchain.waitForReady();
await this.#blockchain.privateKeyManager!.setDefault(address);
}
/**
* Returns the balance of any address.
*
* @param address - The public address to retrieve the balance for.
* @returns A `string` of the `attoFIL` balance of `address`,
* encoded in base-10 (aka decimal format).
*/
async "Filecoin.WalletBalance"(address: string): Promise<string> {
await this.#blockchain.waitForReady();
const account = await this.#blockchain.accountManager!.getAccount(address);
return account.balance.serialize();
}
/**
* Generate a new random address to add to the wallet. This new
* address is persisted across Ganache sessions if you are using
* a persisted database with `database.db` or `database.dbPath` options.
*
* @param keyType - The key type (`bls` or `secp256k1`) to use
* to generate the address. KeyType of `secp256k1-ledger` is
* not supported in Filecoin-flavored Ganache.
* @returns The public address as a `string`.
*/
async "Filecoin.WalletNew"(keyType: KeyType): Promise<SerializedAddress> {
let protocol: AddressProtocol;
switch (keyType) {
case KeyType.KeyTypeBLS: {
protocol = AddressProtocol.BLS;
break;
}
case KeyType.KeyTypeSecp256k1: {
protocol = AddressProtocol.SECP256K1;
break;
}
case KeyType.KeyTypeSecp256k1Ledger:
default: {
throw new Error(
`KeyType of ${keyType} is not supported. Please use "bls" or "secp256k1".`
);
}
}
const account = await this.#blockchain.createAccount(protocol);
return account.address.serialize();
}
/**
* Returns the list of addresses in the wallet. The wallet stores the private
* key of these addresses and therefore can sign messages and random bytes.
*
* @returns An array of `string`'s of each public address in the wallet.
*/
async "Filecoin.WalletList"(): Promise<Array<SerializedAddress>> {
await this.#blockchain.waitForReady();
const accounts = await this.#blockchain.accountManager!.getControllableAccounts();
return accounts.map(account => account.address.serialize());
}
/**
* Checks whether or not the wallet includes the provided address.
*
* @param address - The public address of type `string` to check.
* @returns `true` if the address is in the wallet, `false` otherwise.
*/
async "Filecoin.WalletHas"(address: string): Promise<boolean> {
await this.#blockchain.waitForReady();
return await this.#blockchain.privateKeyManager!.hasPrivateKey(address);
}
/**
* Removes the address from the wallet. This method is unrecoverable.
* If you want to recover the address removed from this method, you
* must use `Filecoin.WalletImport` with the correct private key.
* Removing addresses from the wallet will persist between Ganache
* sessions if you are using a persisted database with
* `database.db` or `database.dbPath` options.
*
* @param address - A `string` of the public address to remove.
*/
async "Filecoin.WalletDelete"(address: string): Promise<void> {
await this.#blockchain.waitForReady();
await this.#blockchain.privateKeyManager!.deletePrivateKey(address);
}
/**
* Exports the private key information from an address stored in the wallet.
*
* @param address - A `string` of the public address to export.
* @returns The KeyInfo object.
*/
async "Filecoin.WalletExport"(address: string): Promise<SerializedKeyInfo> {
await this.#blockchain.waitForReady();
const privateKey = await this.#blockchain.privateKeyManager!.getPrivateKey(
address
);
if (privateKey === null) {
throw new Error("key not found");
}
const protocol = Address.parseProtocol(address);
const keyInfo = new KeyInfo({
type:
protocol === AddressProtocol.BLS
? KeyType.KeyTypeBLS
: KeyType.KeyTypeSecp256k1,
privateKey: Buffer.from(privateKey, "hex")
});
return keyInfo.serialize();
}
/**
* Imports an address into the wallet with provided private key info.
* Use this method to add more addresses to the wallet. Adding addresses
* to the wallet will persist between Ganache sessions if you are using
* a persisted database with with `database.db` or `database.dbPath` options.
*
* @param serializedKeyInfo - The private key KeyInfo object for the address to import.
* @returns The corresponding public address of type `string`.
*/
async "Filecoin.WalletImport"(
serializedKeyInfo: SerializedKeyInfo
): Promise<SerializedAddress> {
await this.#blockchain.waitForReady();
const keyInfo = new KeyInfo(serializedKeyInfo);
if (keyInfo.type === KeyType.KeyTypeSecp256k1Ledger) {
throw new Error(
"Ganache doesn't support ledger accounts; please use 'bls' or 'secp256k1' key types."
);
}
const protocol =
keyInfo.type === KeyType.KeyTypeBLS
? AddressProtocol.BLS
: AddressProtocol.SECP256K1;
const address = Address.fromPrivateKey(
keyInfo.privateKey.toString("hex"),
protocol
);
await this.#blockchain.privateKeyManager!.putPrivateKey(
address.value,
address.privateKey!
);
return address.serialize();
}
/**
* Signs an arbitrary byte string using the private key info
* stored in the wallet.
*
* @param address - A `string` of the public address in the wallet to
* sign with.
* @param data - A `string` of a base-64 encoded byte array to sign.
* @returns A Signature object which contains the signature details.
*/
async "Filecoin.WalletSign"(
address: string,
data: string
): Promise<SerializedSignature> {
await this.#blockchain.waitForReady();
const account = await this.#blockchain.accountManager!.getAccount(address);
const signedData = await account.address.signBuffer(
Buffer.from(data, "base64")
);
const signature = new Signature({
type:
account.address.protocol === AddressProtocol.BLS
? SigType.SigTypeBLS
: SigType.SigTypeSecp256k1,
data: signedData
});
return signature.serialize();
}
/**
* Signs a Message using the private key info stored in the wallet.
*
* @param address - A `string` of the public address in the wallet to
* sign with.
* @param serializedMessage - A Message object that needs signing.
* @returns The corresponding SignedMessage object.
*/
async "Filecoin.WalletSignMessage"(
address: string,
serializedMessage: SerializedMessage
): Promise<SerializedSignedMessage> {
await this.#blockchain.waitForReady();
const account = await this.#blockchain.accountManager!.getAccount(address);
const message = new Message(serializedMessage);
const signedData = await account.address.signMessage(message);
const signedMessage = new SignedMessage({
message,
signature: new Signature({
type:
account.address.protocol === AddressProtocol.BLS
? SigType.SigTypeBLS
: SigType.SigTypeSecp256k1,
data: signedData
})
});
return signedMessage.serialize();
}
/**
* Verifies the validity of a signature for a given address
* and unsigned byte string.
*
* @param inputAddress - A `string` of the public address that
* supposedly signed `data` with `serializedSignature`
* @param data - A `string` of the data that was signed, encoded
* in base-64.
* @param serializedSignature - A Signature object of the signature
* you're trying to verify.
* @returns `true` if valid, `false` otherwise.
*/
async "Filecoin.WalletVerify"(
inputAddress: string,
data: string,
serializedSignature: SerializedSignature
): Promise<boolean> {
await this.#blockchain.waitForReady();
const signature = new Signature(serializedSignature);
const protocol = Address.parseProtocol(inputAddress);
const isBLS =
protocol === AddressProtocol.BLS && signature.type === SigType.SigTypeBLS;
const isSecp =
protocol === AddressProtocol.SECP256K1 &&
signature.type === SigType.SigTypeSecp256k1;
const isValid = isBLS || isSecp;
if (isValid) {
const address = new Address(inputAddress);
return await address.verifySignature(
Buffer.from(data, "base64"),
signature
);
} else {
throw new Error(
"Invalid address protocol with signature. Address protocol should match the corresponding signature Type. Only BLS or SECP256K1 are supported"
);
}
}
/**
* Checks the validity of a given public address.
*
* @param inputAddress - The `string` of the public address to check.
* @returns If successful, it returns the address back as a `string`.
* Otherwise returns an error.
*/
async "Filecoin.WalletValidateAddress"(
inputAddress: string
): Promise<SerializedAddress> {
await this.#blockchain.waitForReady();
const address = Address.validate(inputAddress);
return address.serialize();
}
/**
* Start a storage deal. The data must already be uploaded to
* the Ganache IPFS node. Deals are automatically accepted
* as long as the public address in `Wallet` is in Ganache's
* wallet (see `Filecoin.WalletList` or `Filecoin.WalletHas`
* to check). Storage deals in Ganache automatically progress
* each tipset from one state to the next towards the
* StorageDealStatusActive state.
*
* @param serializedProposal - A StartDealParams object of the deal details.
* @returns The RootCID of the new `DealInfo` =\> `DealInfo.ProposalCid`
*/
async "Filecoin.ClientStartDeal"(
serializedProposal: SerializedStartDealParams
): Promise<SerializedRootCID> {
const proposal = new StartDealParams(serializedProposal);
const proposalRootCid = await this.#blockchain.startDeal(proposal);
return proposalRootCid.serialize();
}
/**
* List all storage deals regardless of state, including expired deals.
*
* @returns An array of DealInfo objects.
*/
async "Filecoin.ClientListDeals"(): Promise<Array<SerializedDealInfo>> {
await this.#blockchain.waitForReady();
const deals = await this.#blockchain.dealInfoManager!.getDeals();
return deals.map(deal => deal.serialize());
}
/**
* Get the detailed info of a storage deal.
*
* Reference implementation: https://git.io/JthfU
*
* @param serializedCid - The `DealInfo.ProposalCid` RootCID for the
* deal you're searching for
* @returns A DealInfo object.
*/
async "Filecoin.ClientGetDealInfo"(
serializedCid: SerializedRootCID
): Promise<SerializedDealInfo> {
await this.#blockchain.waitForReady();
const dealInfo = await this.#blockchain.dealInfoManager!.get(
serializedCid["/"]
);
if (dealInfo) {
// Verified that this is the correct lookup since dealsByCid
// uses the ProposalCid (ref impl: https://git.io/Jthv7) and the
// reference implementation of the lookup follows suit: https://git.io/Jthvp
//
return dealInfo.serialize();
} else {
throw new Error("Could not find a deal for the provided CID");
}
}
/**
* Get the corresponding string that represents a StorageDealStatus
* code.
*
* Reference implementation: https://git.io/JqUXg
*
* @param statusCode - A `number` that's stored in `DealInfo.State`
* which represents the current state of a storage deal.
* @returns A `string` representation of the provided `statusCode`.
*/
async "Filecoin.ClientGetDealStatus"(statusCode: number): Promise<string> {
const status = StorageDealStatus[statusCode];
if (!status) {
throw new Error(`no such deal state ${statusCode}`);
}
return `StorageDeal${status}`;
}
/**
* Starts a subscription to receive updates when storage deals
* change state.
*
* @param rpcId - This parameter is not provided by the user, but
* injected by the internal system.
* @returns An object with the subscription ID and an unsubscribe
* function.
*/
"Filecoin.ClientGetDealUpdates"(rpcId?: string): PromiEvent<Subscription> {
const subscriptionId = this.#getId();
let promiEvent: PromiEvent<Subscription>;
const unsubscribeFromEmittery = this.#blockchain.on(
"dealUpdate",
(deal: DealInfo) => {
if (promiEvent) {
promiEvent.emit("message", {
type: SubscriptionMethod.ChannelUpdated,
data: [subscriptionId.toString(), deal.serialize()]
});
}
}
);
const unsubscribe = (): void => {
unsubscribeFromEmittery();
// Per https://git.io/JtOc1 and https://git.io/JtO3H
// implementations, we're should cancel the subscription
// since the protocol technically supports multiple channels
// per subscription, but implementation seems to show that there's
// only one channel per subscription
if (rpcId) {
promiEvent.emit("message", {
type: SubscriptionMethod.SubscriptionCanceled,
data: [rpcId]
});
}
};
promiEvent = PromiEvent.resolve({
unsubscribe,
id: subscriptionId
});
// There currently isn't an unsubscribe method,
// but it would go here
this.#subscriptions.set(subscriptionId.toString()!, unsubscribe);
return promiEvent;
}
/**
* Ask the node to search for data stored in the IPFS node.
*
* @param rootCid - The RootCID to search for.
* @returns A QueryOffer with details of the data for further
* retrieval.
*/
async "Filecoin.ClientFindData"(
rootCid: SerializedRootCID
): Promise<Array<SerializedQueryOffer>> {
const remoteOffer = await this.#blockchain.createQueryOffer(
new RootCID(rootCid)
);
return [remoteOffer.serialize()];
}
/**
* Returns whether or not the local IPFS node has the data
* requested. Since Filecoin-flavored Ganache doesn't connect
* to any external networks, all data on the IPFS node is local.
*
* @param rootCid - The RootCID to serach for.
* @returns `true` if the local IPFS node has the data,
* `false` otherwise.
*/
async "Filecoin.ClientHasLocal"(
rootCid: SerializedRootCID
): Promise<boolean> {
return await this.#blockchain.hasLocal(rootCid["/"]);
}
/**
* Download the contents of a storage deal to disk (local
* to Ganache).
*
* @param retrievalOrder - A RetrievalOrder object detailing
* the deal, retrieval price, etc.
* @param ref - A FileRef object specifying where the file
* should be saved to.
*/
async "Filecoin.ClientRetrieve"(
retrievalOrder: SerializedRetrievalOrder,
ref: SerializedFileRef
): Promise<void> {
await this.#blockchain.retrieve(
new RetrievalOrder(retrievalOrder),
new FileRef(ref)
);
}
/**
* Manually mine a tipset immediately. Mines even if the
* miner is disabled.
*
* @returns The Tipset object that was mined.
*/
async "Ganache.MineTipset"(): Promise<SerializedTipset> {
await this.#blockchain.mineTipset();
const tipset = this.#blockchain.latestTipset();
return tipset.serialize();
}
/**
* Enables the miner.
*/
async "Ganache.EnableMiner"(): Promise<void> {
await this.#blockchain.enableMiner();
}
/**
* Disables the miner.
*/
async "Ganache.DisableMiner"(): Promise<void> {
await this.#blockchain.disableMiner();
}
/**
* The current status on whether or not the miner
* is enabled. The initial value is determined by
* the option `miner.mine`. If `true`, then auto-mining
* (`miner.blockTime = 0`) and interval mining
* (`miner.blockTime > 0`) will be processed.
* If `false`, tipsets/blocks will only be mined with
* `Ganache.MineTipset`
*
* @returns A `boolean` on whether or not the miner is
* enabled.
*/
async "Ganache.MinerEnabled"(): Promise<boolean> {
return this.#blockchain.minerEnabled;
}
/**
* A subscription method that provides an update
* whenever the miner is enabled or disabled.
*
* @param rpcId - This parameter is not provided by the user, but
* injected by the internal system.
* @returns An object with the subscription ID and an unsubscribe
* function.
*/
"Ganache.MinerEnabledNotify"(rpcId?: string): PromiEvent<Subscription> {
const subscriptionId = this.#getId();
let promiEvent: PromiEvent<Subscription>;
const unsubscribeFromEmittery = this.#blockchain.on(
"minerEnabled",
(minerEnabled: boolean) => {
if (promiEvent) {
promiEvent.emit("message", {
type: SubscriptionMethod.ChannelUpdated,
data: [subscriptionId.toString(), minerEnabled]
});
}
}
);
const unsubscribe = (): void => {
unsubscribeFromEmittery();
// Per https://git.io/JtOc1 and https://git.io/JtO3H
// implementations, we're should cancel the subscription
// since the protocol technically supports multiple channels
// per subscription, but implementation seems to show that there's
// only one channel per subscription
if (rpcId) {
promiEvent.emit("message", {
type: SubscriptionMethod.SubscriptionCanceled,
data: [rpcId]
});
}
};
promiEvent = PromiEvent.resolve({
unsubscribe,
id: subscriptionId
});
// There currently isn't an unsubscribe method,
// but it would go here
this.#subscriptions.set(subscriptionId.toString()!, unsubscribe);
promiEvent.emit("message", {
type: SubscriptionMethod.ChannelUpdated,
data: [subscriptionId.toString(), this.#blockchain.minerEnabled]
});
return promiEvent;
}
/**
* Retrieves an internal `DealInfo` by its `DealID`.
*
* @param dealId - A `number` corresponding to the `DealInfo.DealID`
* for the deal to retrieve.
* @returns The matched DealInfo object.
*/
async "Ganache.GetDealById"(dealId: number): Promise<SerializedDealInfo> {
await this.#blockchain.waitForReady();
const deal = await this.#blockchain.dealInfoManager!.getDealById(dealId);
if (deal) {
return deal.serialize();
} else {
throw new Error("Could not find a deal for the provided ID");
}
}
} | the_stack |
import Long from "long";
import _m0 from "protobufjs/minimal";
import { Value } from "../../google/protobuf/struct";
export const protobufPackage = "grpc.gateway.protoc_gen_openapiv2.options";
/**
* Scheme describes the schemes supported by the OpenAPI Swagger
* and Operation objects.
*/
export enum Scheme {
UNKNOWN = 0,
HTTP = 1,
HTTPS = 2,
WS = 3,
WSS = 4,
UNRECOGNIZED = -1,
}
export function schemeFromJSON(object: any): Scheme {
switch (object) {
case 0:
case "UNKNOWN":
return Scheme.UNKNOWN;
case 1:
case "HTTP":
return Scheme.HTTP;
case 2:
case "HTTPS":
return Scheme.HTTPS;
case 3:
case "WS":
return Scheme.WS;
case 4:
case "WSS":
return Scheme.WSS;
case -1:
case "UNRECOGNIZED":
default:
return Scheme.UNRECOGNIZED;
}
}
export function schemeToJSON(object: Scheme): string {
switch (object) {
case Scheme.UNKNOWN:
return "UNKNOWN";
case Scheme.HTTP:
return "HTTP";
case Scheme.HTTPS:
return "HTTPS";
case Scheme.WS:
return "WS";
case Scheme.WSS:
return "WSS";
default:
return "UNKNOWN";
}
}
/**
* `Swagger` is a representation of OpenAPI v2 specification's Swagger object.
*
* See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#swaggerObject
*
* Example:
*
* option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_swagger) = {
* info: {
* title: "Echo API";
* version: "1.0";
* description: ";
* contact: {
* name: "gRPC-Gateway project";
* url: "https://github.com/grpc-ecosystem/grpc-gateway";
* email: "none@example.com";
* };
* license: {
* name: "BSD 3-Clause License";
* url: "https://github.com/grpc-ecosystem/grpc-gateway/blob/master/LICENSE.txt";
* };
* };
* schemes: HTTPS;
* consumes: "application/json";
* produces: "application/json";
* };
*/
export interface Swagger {
/**
* Specifies the OpenAPI Specification version being used. It can be
* used by the OpenAPI UI and other clients to interpret the API listing. The
* value MUST be "2.0".
*/
swagger: string;
/**
* Provides metadata about the API. The metadata can be used by the
* clients if needed.
*/
info?: Info;
/**
* The host (name or ip) serving the API. This MUST be the host only and does
* not include the scheme nor sub-paths. It MAY include a port. If the host is
* not included, the host serving the documentation is to be used (including
* the port). The host does not support path templating.
*/
host: string;
/**
* The base path on which the API is served, which is relative to the host. If
* it is not included, the API is served directly under the host. The value
* MUST start with a leading slash (/). The basePath does not support path
* templating.
* Note that using `base_path` does not change the endpoint paths that are
* generated in the resulting OpenAPI file. If you wish to use `base_path`
* with relatively generated OpenAPI paths, the `base_path` prefix must be
* manually removed from your `google.api.http` paths and your code changed to
* serve the API from the `base_path`.
*/
basePath: string;
/**
* The transfer protocol of the API. Values MUST be from the list: "http",
* "https", "ws", "wss". If the schemes is not included, the default scheme to
* be used is the one used to access the OpenAPI definition itself.
*/
schemes: Scheme[];
/**
* A list of MIME types the APIs can consume. This is global to all APIs but
* can be overridden on specific API calls. Value MUST be as described under
* Mime Types.
*/
consumes: string[];
/**
* A list of MIME types the APIs can produce. This is global to all APIs but
* can be overridden on specific API calls. Value MUST be as described under
* Mime Types.
*/
produces: string[];
/**
* An object to hold responses that can be used across operations. This
* property does not define global responses for all operations.
*/
responses: { [key: string]: Response };
/** Security scheme definitions that can be used across the specification. */
securityDefinitions?: SecurityDefinitions;
/**
* A declaration of which security schemes are applied for the API as a whole.
* The list of values describes alternative security schemes that can be used
* (that is, there is a logical OR between the security requirements).
* Individual operations can override this definition.
*/
security: SecurityRequirement[];
/** Additional external documentation. */
externalDocs?: ExternalDocumentation;
extensions: { [key: string]: Value };
}
export interface Swagger_ResponsesEntry {
key: string;
value?: Response;
}
export interface Swagger_ExtensionsEntry {
key: string;
value?: Value;
}
/**
* `Operation` is a representation of OpenAPI v2 specification's Operation object.
*
* See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#operationObject
*
* Example:
*
* service EchoService {
* rpc Echo(SimpleMessage) returns (SimpleMessage) {
* option (google.api.http) = {
* get: "/v1/example/echo/{id}"
* };
*
* option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_operation) = {
* summary: "Get a message.";
* operation_id: "getMessage";
* tags: "echo";
* responses: {
* key: "200"
* value: {
* description: "OK";
* }
* }
* };
* }
* }
*/
export interface Operation {
/**
* A list of tags for API documentation control. Tags can be used for logical
* grouping of operations by resources or any other qualifier.
*/
tags: string[];
/**
* A short summary of what the operation does. For maximum readability in the
* swagger-ui, this field SHOULD be less than 120 characters.
*/
summary: string;
/**
* A verbose explanation of the operation behavior. GFM syntax can be used for
* rich text representation.
*/
description: string;
/** Additional external documentation for this operation. */
externalDocs?: ExternalDocumentation;
/**
* Unique string used to identify the operation. The id MUST be unique among
* all operations described in the API. Tools and libraries MAY use the
* operationId to uniquely identify an operation, therefore, it is recommended
* to follow common programming naming conventions.
*/
operationId: string;
/**
* A list of MIME types the operation can consume. This overrides the consumes
* definition at the OpenAPI Object. An empty value MAY be used to clear the
* global definition. Value MUST be as described under Mime Types.
*/
consumes: string[];
/**
* A list of MIME types the operation can produce. This overrides the produces
* definition at the OpenAPI Object. An empty value MAY be used to clear the
* global definition. Value MUST be as described under Mime Types.
*/
produces: string[];
/**
* The list of possible responses as they are returned from executing this
* operation.
*/
responses: { [key: string]: Response };
/**
* The transfer protocol for the operation. Values MUST be from the list:
* "http", "https", "ws", "wss". The value overrides the OpenAPI Object
* schemes definition.
*/
schemes: Scheme[];
/**
* Declares this operation to be deprecated. Usage of the declared operation
* should be refrained. Default value is false.
*/
deprecated: boolean;
/**
* A declaration of which security schemes are applied for this operation. The
* list of values describes alternative security schemes that can be used
* (that is, there is a logical OR between the security requirements). This
* definition overrides any declared top-level security. To remove a top-level
* security declaration, an empty array can be used.
*/
security: SecurityRequirement[];
extensions: { [key: string]: Value };
}
export interface Operation_ResponsesEntry {
key: string;
value?: Response;
}
export interface Operation_ExtensionsEntry {
key: string;
value?: Value;
}
/**
* `Header` is a representation of OpenAPI v2 specification's Header object.
*
* See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#headerObject
*/
export interface Header {
/** `Description` is a short description of the header. */
description: string;
/** The type of the object. The value MUST be one of "string", "number", "integer", or "boolean". The "array" type is not supported. */
type: string;
/** `Format` The extending format for the previously mentioned type. */
format: string;
/**
* `Default` Declares the value of the header that the server will use if none is provided.
* See: https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-6.2.
* Unlike JSON Schema this value MUST conform to the defined type for the header.
*/
default: string;
/** 'Pattern' See https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.2.3. */
pattern: string;
}
/**
* `Response` is a representation of OpenAPI v2 specification's Response object.
*
* See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#responseObject
*/
export interface Response {
/**
* `Description` is a short description of the response.
* GFM syntax can be used for rich text representation.
*/
description: string;
/**
* `Schema` optionally defines the structure of the response.
* If `Schema` is not provided, it means there is no content to the response.
*/
schema?: Schema;
/**
* `Headers` A list of headers that are sent with the response.
* `Header` name is expected to be a string in the canonical format of the MIME header key
* See: https://golang.org/pkg/net/textproto/#CanonicalMIMEHeaderKey
*/
headers: { [key: string]: Header };
/**
* `Examples` gives per-mimetype response examples.
* See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#example-object
*/
examples: { [key: string]: string };
extensions: { [key: string]: Value };
}
export interface Response_HeadersEntry {
key: string;
value?: Header;
}
export interface Response_ExamplesEntry {
key: string;
value: string;
}
export interface Response_ExtensionsEntry {
key: string;
value?: Value;
}
/**
* `Info` is a representation of OpenAPI v2 specification's Info object.
*
* See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#infoObject
*
* Example:
*
* option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_swagger) = {
* info: {
* title: "Echo API";
* version: "1.0";
* description: ";
* contact: {
* name: "gRPC-Gateway project";
* url: "https://github.com/grpc-ecosystem/grpc-gateway";
* email: "none@example.com";
* };
* license: {
* name: "BSD 3-Clause License";
* url: "https://github.com/grpc-ecosystem/grpc-gateway/blob/master/LICENSE.txt";
* };
* };
* ...
* };
*/
export interface Info {
/** The title of the application. */
title: string;
/**
* A short description of the application. GFM syntax can be used for rich
* text representation.
*/
description: string;
/** The Terms of Service for the API. */
termsOfService: string;
/** The contact information for the exposed API. */
contact?: Contact;
/** The license information for the exposed API. */
license?: License;
/**
* Provides the version of the application API (not to be confused
* with the specification version).
*/
version: string;
extensions: { [key: string]: Value };
}
export interface Info_ExtensionsEntry {
key: string;
value?: Value;
}
/**
* `Contact` is a representation of OpenAPI v2 specification's Contact object.
*
* See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#contactObject
*
* Example:
*
* option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_swagger) = {
* info: {
* ...
* contact: {
* name: "gRPC-Gateway project";
* url: "https://github.com/grpc-ecosystem/grpc-gateway";
* email: "none@example.com";
* };
* ...
* };
* ...
* };
*/
export interface Contact {
/** The identifying name of the contact person/organization. */
name: string;
/**
* The URL pointing to the contact information. MUST be in the format of a
* URL.
*/
url: string;
/**
* The email address of the contact person/organization. MUST be in the format
* of an email address.
*/
email: string;
}
/**
* `License` is a representation of OpenAPI v2 specification's License object.
*
* See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#licenseObject
*
* Example:
*
* option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_swagger) = {
* info: {
* ...
* license: {
* name: "BSD 3-Clause License";
* url: "https://github.com/grpc-ecosystem/grpc-gateway/blob/master/LICENSE.txt";
* };
* ...
* };
* ...
* };
*/
export interface License {
/** The license name used for the API. */
name: string;
/** A URL to the license used for the API. MUST be in the format of a URL. */
url: string;
}
/**
* `ExternalDocumentation` is a representation of OpenAPI v2 specification's
* ExternalDocumentation object.
*
* See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#externalDocumentationObject
*
* Example:
*
* option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_swagger) = {
* ...
* external_docs: {
* description: "More about gRPC-Gateway";
* url: "https://github.com/grpc-ecosystem/grpc-gateway";
* }
* ...
* };
*/
export interface ExternalDocumentation {
/**
* A short description of the target documentation. GFM syntax can be used for
* rich text representation.
*/
description: string;
/**
* The URL for the target documentation. Value MUST be in the format
* of a URL.
*/
url: string;
}
/**
* `Schema` is a representation of OpenAPI v2 specification's Schema object.
*
* See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#schemaObject
*/
export interface Schema {
jsonSchema?: JSONSchema;
/**
* Adds support for polymorphism. The discriminator is the schema property
* name that is used to differentiate between other schema that inherit this
* schema. The property name used MUST be defined at this schema and it MUST
* be in the required property list. When used, the value MUST be the name of
* this schema or any schema that inherits it.
*/
discriminator: string;
/**
* Relevant only for Schema "properties" definitions. Declares the property as
* "read only". This means that it MAY be sent as part of a response but MUST
* NOT be sent as part of the request. Properties marked as readOnly being
* true SHOULD NOT be in the required list of the defined schema. Default
* value is false.
*/
readOnly: boolean;
/** Additional external documentation for this schema. */
externalDocs?: ExternalDocumentation;
/**
* A free-form property to include an example of an instance for this schema in JSON.
* This is copied verbatim to the output.
*/
example: string;
}
/**
* `JSONSchema` represents properties from JSON Schema taken, and as used, in
* the OpenAPI v2 spec.
*
* This includes changes made by OpenAPI v2.
*
* See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#schemaObject
*
* See also: https://cswr.github.io/JsonSchema/spec/basic_types/,
* https://github.com/json-schema-org/json-schema-spec/blob/master/schema.json
*
* Example:
*
* message SimpleMessage {
* option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_schema) = {
* json_schema: {
* title: "SimpleMessage"
* description: "A simple message."
* required: ["id"]
* }
* };
*
* // Id represents the message identifier.
* string id = 1; [
* (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_field) = {
* {description: "The unique identifier of the simple message."
* }];
* }
*/
export interface JSONSchema {
/**
* Ref is used to define an external reference to include in the message.
* This could be a fully qualified proto message reference, and that type must
* be imported into the protofile. If no message is identified, the Ref will
* be used verbatim in the output.
* For example:
* `ref: ".google.protobuf.Timestamp"`.
*/
ref: string;
/** The title of the schema. */
title: string;
/** A short description of the schema. */
description: string;
default: string;
readOnly: boolean;
/**
* A free-form property to include a JSON example of this field. This is copied
* verbatim to the output swagger.json. Quotes must be escaped.
* This property is the same for 2.0 and 3.0.0 https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/3.0.0.md#schemaObject https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#schemaObject
*/
example: string;
multipleOf: number;
/**
* Maximum represents an inclusive upper limit for a numeric instance. The
* value of MUST be a number,
*/
maximum: number;
exclusiveMaximum: boolean;
/**
* minimum represents an inclusive lower limit for a numeric instance. The
* value of MUST be a number,
*/
minimum: number;
exclusiveMinimum: boolean;
maxLength: number;
minLength: number;
pattern: string;
maxItems: number;
minItems: number;
uniqueItems: boolean;
maxProperties: number;
minProperties: number;
required: string[];
/** Items in 'array' must be unique. */
array: string[];
type: JSONSchema_JSONSchemaSimpleTypes[];
/** `Format` */
format: string;
/** Items in `enum` must be unique https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.1 */
enum: string[];
}
export enum JSONSchema_JSONSchemaSimpleTypes {
UNKNOWN = 0,
ARRAY = 1,
BOOLEAN = 2,
INTEGER = 3,
NULL = 4,
NUMBER = 5,
OBJECT = 6,
STRING = 7,
UNRECOGNIZED = -1,
}
export function jSONSchema_JSONSchemaSimpleTypesFromJSON(
object: any,
): JSONSchema_JSONSchemaSimpleTypes {
switch (object) {
case 0:
case "UNKNOWN":
return JSONSchema_JSONSchemaSimpleTypes.UNKNOWN;
case 1:
case "ARRAY":
return JSONSchema_JSONSchemaSimpleTypes.ARRAY;
case 2:
case "BOOLEAN":
return JSONSchema_JSONSchemaSimpleTypes.BOOLEAN;
case 3:
case "INTEGER":
return JSONSchema_JSONSchemaSimpleTypes.INTEGER;
case 4:
case "NULL":
return JSONSchema_JSONSchemaSimpleTypes.NULL;
case 5:
case "NUMBER":
return JSONSchema_JSONSchemaSimpleTypes.NUMBER;
case 6:
case "OBJECT":
return JSONSchema_JSONSchemaSimpleTypes.OBJECT;
case 7:
case "STRING":
return JSONSchema_JSONSchemaSimpleTypes.STRING;
case -1:
case "UNRECOGNIZED":
default:
return JSONSchema_JSONSchemaSimpleTypes.UNRECOGNIZED;
}
}
export function jSONSchema_JSONSchemaSimpleTypesToJSON(
object: JSONSchema_JSONSchemaSimpleTypes,
): string {
switch (object) {
case JSONSchema_JSONSchemaSimpleTypes.UNKNOWN:
return "UNKNOWN";
case JSONSchema_JSONSchemaSimpleTypes.ARRAY:
return "ARRAY";
case JSONSchema_JSONSchemaSimpleTypes.BOOLEAN:
return "BOOLEAN";
case JSONSchema_JSONSchemaSimpleTypes.INTEGER:
return "INTEGER";
case JSONSchema_JSONSchemaSimpleTypes.NULL:
return "NULL";
case JSONSchema_JSONSchemaSimpleTypes.NUMBER:
return "NUMBER";
case JSONSchema_JSONSchemaSimpleTypes.OBJECT:
return "OBJECT";
case JSONSchema_JSONSchemaSimpleTypes.STRING:
return "STRING";
default:
return "UNKNOWN";
}
}
/**
* `Tag` is a representation of OpenAPI v2 specification's Tag object.
*
* See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#tagObject
*/
export interface Tag {
/**
* A short description for the tag. GFM syntax can be used for rich text
* representation.
*/
description: string;
/** Additional external documentation for this tag. */
externalDocs?: ExternalDocumentation;
}
/**
* `SecurityDefinitions` is a representation of OpenAPI v2 specification's
* Security Definitions object.
*
* See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#securityDefinitionsObject
*
* A declaration of the security schemes available to be used in the
* specification. This does not enforce the security schemes on the operations
* and only serves to provide the relevant details for each scheme.
*/
export interface SecurityDefinitions {
/**
* A single security scheme definition, mapping a "name" to the scheme it
* defines.
*/
security: { [key: string]: SecurityScheme };
}
export interface SecurityDefinitions_SecurityEntry {
key: string;
value?: SecurityScheme;
}
/**
* `SecurityScheme` is a representation of OpenAPI v2 specification's
* Security Scheme object.
*
* See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#securitySchemeObject
*
* Allows the definition of a security scheme that can be used by the
* operations. Supported schemes are basic authentication, an API key (either as
* a header or as a query parameter) and OAuth2's common flows (implicit,
* password, application and access code).
*/
export interface SecurityScheme {
/**
* The type of the security scheme. Valid values are "basic",
* "apiKey" or "oauth2".
*/
type: SecurityScheme_Type;
/** A short description for security scheme. */
description: string;
/**
* The name of the header or query parameter to be used.
* Valid for apiKey.
*/
name: string;
/**
* The location of the API key. Valid values are "query" or
* "header".
* Valid for apiKey.
*/
in: SecurityScheme_In;
/**
* The flow used by the OAuth2 security scheme. Valid values are
* "implicit", "password", "application" or "accessCode".
* Valid for oauth2.
*/
flow: SecurityScheme_Flow;
/**
* The authorization URL to be used for this flow. This SHOULD be in
* the form of a URL.
* Valid for oauth2/implicit and oauth2/accessCode.
*/
authorizationUrl: string;
/**
* The token URL to be used for this flow. This SHOULD be in the
* form of a URL.
* Valid for oauth2/password, oauth2/application and oauth2/accessCode.
*/
tokenUrl: string;
/**
* The available scopes for the OAuth2 security scheme.
* Valid for oauth2.
*/
scopes?: Scopes;
extensions: { [key: string]: Value };
}
/**
* The type of the security scheme. Valid values are "basic",
* "apiKey" or "oauth2".
*/
export enum SecurityScheme_Type {
TYPE_INVALID = 0,
TYPE_BASIC = 1,
TYPE_API_KEY = 2,
TYPE_OAUTH2 = 3,
UNRECOGNIZED = -1,
}
export function securityScheme_TypeFromJSON(object: any): SecurityScheme_Type {
switch (object) {
case 0:
case "TYPE_INVALID":
return SecurityScheme_Type.TYPE_INVALID;
case 1:
case "TYPE_BASIC":
return SecurityScheme_Type.TYPE_BASIC;
case 2:
case "TYPE_API_KEY":
return SecurityScheme_Type.TYPE_API_KEY;
case 3:
case "TYPE_OAUTH2":
return SecurityScheme_Type.TYPE_OAUTH2;
case -1:
case "UNRECOGNIZED":
default:
return SecurityScheme_Type.UNRECOGNIZED;
}
}
export function securityScheme_TypeToJSON(object: SecurityScheme_Type): string {
switch (object) {
case SecurityScheme_Type.TYPE_INVALID:
return "TYPE_INVALID";
case SecurityScheme_Type.TYPE_BASIC:
return "TYPE_BASIC";
case SecurityScheme_Type.TYPE_API_KEY:
return "TYPE_API_KEY";
case SecurityScheme_Type.TYPE_OAUTH2:
return "TYPE_OAUTH2";
default:
return "UNKNOWN";
}
}
/** The location of the API key. Valid values are "query" or "header". */
export enum SecurityScheme_In {
IN_INVALID = 0,
IN_QUERY = 1,
IN_HEADER = 2,
UNRECOGNIZED = -1,
}
export function securityScheme_InFromJSON(object: any): SecurityScheme_In {
switch (object) {
case 0:
case "IN_INVALID":
return SecurityScheme_In.IN_INVALID;
case 1:
case "IN_QUERY":
return SecurityScheme_In.IN_QUERY;
case 2:
case "IN_HEADER":
return SecurityScheme_In.IN_HEADER;
case -1:
case "UNRECOGNIZED":
default:
return SecurityScheme_In.UNRECOGNIZED;
}
}
export function securityScheme_InToJSON(object: SecurityScheme_In): string {
switch (object) {
case SecurityScheme_In.IN_INVALID:
return "IN_INVALID";
case SecurityScheme_In.IN_QUERY:
return "IN_QUERY";
case SecurityScheme_In.IN_HEADER:
return "IN_HEADER";
default:
return "UNKNOWN";
}
}
/**
* The flow used by the OAuth2 security scheme. Valid values are
* "implicit", "password", "application" or "accessCode".
*/
export enum SecurityScheme_Flow {
FLOW_INVALID = 0,
FLOW_IMPLICIT = 1,
FLOW_PASSWORD = 2,
FLOW_APPLICATION = 3,
FLOW_ACCESS_CODE = 4,
UNRECOGNIZED = -1,
}
export function securityScheme_FlowFromJSON(object: any): SecurityScheme_Flow {
switch (object) {
case 0:
case "FLOW_INVALID":
return SecurityScheme_Flow.FLOW_INVALID;
case 1:
case "FLOW_IMPLICIT":
return SecurityScheme_Flow.FLOW_IMPLICIT;
case 2:
case "FLOW_PASSWORD":
return SecurityScheme_Flow.FLOW_PASSWORD;
case 3:
case "FLOW_APPLICATION":
return SecurityScheme_Flow.FLOW_APPLICATION;
case 4:
case "FLOW_ACCESS_CODE":
return SecurityScheme_Flow.FLOW_ACCESS_CODE;
case -1:
case "UNRECOGNIZED":
default:
return SecurityScheme_Flow.UNRECOGNIZED;
}
}
export function securityScheme_FlowToJSON(object: SecurityScheme_Flow): string {
switch (object) {
case SecurityScheme_Flow.FLOW_INVALID:
return "FLOW_INVALID";
case SecurityScheme_Flow.FLOW_IMPLICIT:
return "FLOW_IMPLICIT";
case SecurityScheme_Flow.FLOW_PASSWORD:
return "FLOW_PASSWORD";
case SecurityScheme_Flow.FLOW_APPLICATION:
return "FLOW_APPLICATION";
case SecurityScheme_Flow.FLOW_ACCESS_CODE:
return "FLOW_ACCESS_CODE";
default:
return "UNKNOWN";
}
}
export interface SecurityScheme_ExtensionsEntry {
key: string;
value?: Value;
}
/**
* `SecurityRequirement` is a representation of OpenAPI v2 specification's
* Security Requirement object.
*
* See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#securityRequirementObject
*
* Lists the required security schemes to execute this operation. The object can
* have multiple security schemes declared in it which are all required (that
* is, there is a logical AND between the schemes).
*
* The name used for each property MUST correspond to a security scheme
* declared in the Security Definitions.
*/
export interface SecurityRequirement {
/**
* Each name must correspond to a security scheme which is declared in
* the Security Definitions. If the security scheme is of type "oauth2",
* then the value is a list of scope names required for the execution.
* For other security scheme types, the array MUST be empty.
*/
securityRequirement: {
[key: string]: SecurityRequirement_SecurityRequirementValue;
};
}
/**
* If the security scheme is of type "oauth2", then the value is a list of
* scope names required for the execution. For other security scheme types,
* the array MUST be empty.
*/
export interface SecurityRequirement_SecurityRequirementValue {
scope: string[];
}
export interface SecurityRequirement_SecurityRequirementEntry {
key: string;
value?: SecurityRequirement_SecurityRequirementValue;
}
/**
* `Scopes` is a representation of OpenAPI v2 specification's Scopes object.
*
* See: https://github.com/OAI/OpenAPI-Specification/blob/3.0.0/versions/2.0.md#scopesObject
*
* Lists the available scopes for an OAuth2 security scheme.
*/
export interface Scopes {
/**
* Maps between a name of a scope to a short description of it (as the value
* of the property).
*/
scope: { [key: string]: string };
}
export interface Scopes_ScopeEntry {
key: string;
value: string;
}
const baseSwagger: object = {
swagger: "",
host: "",
basePath: "",
schemes: 0,
consumes: "",
produces: "",
};
export const Swagger = {
encode(message: Swagger, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.swagger !== "") {
writer.uint32(10).string(message.swagger);
}
if (message.info !== undefined) {
Info.encode(message.info, writer.uint32(18).fork()).ldelim();
}
if (message.host !== "") {
writer.uint32(26).string(message.host);
}
if (message.basePath !== "") {
writer.uint32(34).string(message.basePath);
}
writer.uint32(42).fork();
for (const v of message.schemes) {
writer.int32(v);
}
writer.ldelim();
for (const v of message.consumes) {
writer.uint32(50).string(v!);
}
for (const v of message.produces) {
writer.uint32(58).string(v!);
}
Object.entries(message.responses).forEach(([key, value]) => {
Swagger_ResponsesEntry.encode({ key: key as any, value }, writer.uint32(82).fork()).ldelim();
});
if (message.securityDefinitions !== undefined) {
SecurityDefinitions.encode(message.securityDefinitions, writer.uint32(90).fork()).ldelim();
}
for (const v of message.security) {
SecurityRequirement.encode(v!, writer.uint32(98).fork()).ldelim();
}
if (message.externalDocs !== undefined) {
ExternalDocumentation.encode(message.externalDocs, writer.uint32(114).fork()).ldelim();
}
Object.entries(message.extensions).forEach(([key, value]) => {
Swagger_ExtensionsEntry.encode(
{ key: key as any, value },
writer.uint32(122).fork(),
).ldelim();
});
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Swagger {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseSwagger } as Swagger;
message.schemes = [];
message.consumes = [];
message.produces = [];
message.responses = {};
message.security = [];
message.extensions = {};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.swagger = reader.string();
break;
case 2:
message.info = Info.decode(reader, reader.uint32());
break;
case 3:
message.host = reader.string();
break;
case 4:
message.basePath = reader.string();
break;
case 5:
if ((tag & 7) === 2) {
const end2 = reader.uint32() + reader.pos;
while (reader.pos < end2) {
message.schemes.push(reader.int32() as any);
}
} else {
message.schemes.push(reader.int32() as any);
}
break;
case 6:
message.consumes.push(reader.string());
break;
case 7:
message.produces.push(reader.string());
break;
case 10:
const entry10 = Swagger_ResponsesEntry.decode(reader, reader.uint32());
if (entry10.value !== undefined) {
message.responses[entry10.key] = entry10.value;
}
break;
case 11:
message.securityDefinitions = SecurityDefinitions.decode(reader, reader.uint32());
break;
case 12:
message.security.push(SecurityRequirement.decode(reader, reader.uint32()));
break;
case 14:
message.externalDocs = ExternalDocumentation.decode(reader, reader.uint32());
break;
case 15:
const entry15 = Swagger_ExtensionsEntry.decode(reader, reader.uint32());
if (entry15.value !== undefined) {
message.extensions[entry15.key] = entry15.value;
}
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Swagger {
const message = { ...baseSwagger } as Swagger;
message.schemes = [];
message.consumes = [];
message.produces = [];
message.responses = {};
message.security = [];
message.extensions = {};
if (object.swagger !== undefined && object.swagger !== null) {
message.swagger = String(object.swagger);
} else {
message.swagger = "";
}
if (object.info !== undefined && object.info !== null) {
message.info = Info.fromJSON(object.info);
} else {
message.info = undefined;
}
if (object.host !== undefined && object.host !== null) {
message.host = String(object.host);
} else {
message.host = "";
}
if (object.basePath !== undefined && object.basePath !== null) {
message.basePath = String(object.basePath);
} else {
message.basePath = "";
}
if (object.schemes !== undefined && object.schemes !== null) {
for (const e of object.schemes) {
message.schemes.push(schemeFromJSON(e));
}
}
if (object.consumes !== undefined && object.consumes !== null) {
for (const e of object.consumes) {
message.consumes.push(String(e));
}
}
if (object.produces !== undefined && object.produces !== null) {
for (const e of object.produces) {
message.produces.push(String(e));
}
}
if (object.responses !== undefined && object.responses !== null) {
Object.entries(object.responses).forEach(([key, value]) => {
message.responses[key] = Response.fromJSON(value);
});
}
if (object.securityDefinitions !== undefined && object.securityDefinitions !== null) {
message.securityDefinitions = SecurityDefinitions.fromJSON(object.securityDefinitions);
} else {
message.securityDefinitions = undefined;
}
if (object.security !== undefined && object.security !== null) {
for (const e of object.security) {
message.security.push(SecurityRequirement.fromJSON(e));
}
}
if (object.externalDocs !== undefined && object.externalDocs !== null) {
message.externalDocs = ExternalDocumentation.fromJSON(object.externalDocs);
} else {
message.externalDocs = undefined;
}
if (object.extensions !== undefined && object.extensions !== null) {
Object.entries(object.extensions).forEach(([key, value]) => {
message.extensions[key] = Value.fromJSON(value);
});
}
return message;
},
toJSON(message: Swagger): unknown {
const obj: any = {};
message.swagger !== undefined && (obj.swagger = message.swagger);
message.info !== undefined && (obj.info = message.info ? Info.toJSON(message.info) : undefined);
message.host !== undefined && (obj.host = message.host);
message.basePath !== undefined && (obj.basePath = message.basePath);
if (message.schemes) {
obj.schemes = message.schemes.map(e => schemeToJSON(e));
} else {
obj.schemes = [];
}
if (message.consumes) {
obj.consumes = message.consumes.map(e => e);
} else {
obj.consumes = [];
}
if (message.produces) {
obj.produces = message.produces.map(e => e);
} else {
obj.produces = [];
}
obj.responses = {};
if (message.responses) {
Object.entries(message.responses).forEach(([k, v]) => {
obj.responses[k] = Response.toJSON(v);
});
}
message.securityDefinitions !== undefined &&
(obj.securityDefinitions = message.securityDefinitions
? SecurityDefinitions.toJSON(message.securityDefinitions)
: undefined);
if (message.security) {
obj.security = message.security.map(e => (e ? SecurityRequirement.toJSON(e) : undefined));
} else {
obj.security = [];
}
message.externalDocs !== undefined &&
(obj.externalDocs = message.externalDocs
? ExternalDocumentation.toJSON(message.externalDocs)
: undefined);
obj.extensions = {};
if (message.extensions) {
Object.entries(message.extensions).forEach(([k, v]) => {
obj.extensions[k] = Value.toJSON(v);
});
}
return obj;
},
fromPartial(object: DeepPartial<Swagger>): Swagger {
const message = { ...baseSwagger } as Swagger;
message.schemes = [];
message.consumes = [];
message.produces = [];
message.responses = {};
message.security = [];
message.extensions = {};
if (object.swagger !== undefined && object.swagger !== null) {
message.swagger = object.swagger;
} else {
message.swagger = "";
}
if (object.info !== undefined && object.info !== null) {
message.info = Info.fromPartial(object.info);
} else {
message.info = undefined;
}
if (object.host !== undefined && object.host !== null) {
message.host = object.host;
} else {
message.host = "";
}
if (object.basePath !== undefined && object.basePath !== null) {
message.basePath = object.basePath;
} else {
message.basePath = "";
}
if (object.schemes !== undefined && object.schemes !== null) {
for (const e of object.schemes) {
message.schemes.push(e);
}
}
if (object.consumes !== undefined && object.consumes !== null) {
for (const e of object.consumes) {
message.consumes.push(e);
}
}
if (object.produces !== undefined && object.produces !== null) {
for (const e of object.produces) {
message.produces.push(e);
}
}
if (object.responses !== undefined && object.responses !== null) {
Object.entries(object.responses).forEach(([key, value]) => {
if (value !== undefined) {
message.responses[key] = Response.fromPartial(value);
}
});
}
if (object.securityDefinitions !== undefined && object.securityDefinitions !== null) {
message.securityDefinitions = SecurityDefinitions.fromPartial(object.securityDefinitions);
} else {
message.securityDefinitions = undefined;
}
if (object.security !== undefined && object.security !== null) {
for (const e of object.security) {
message.security.push(SecurityRequirement.fromPartial(e));
}
}
if (object.externalDocs !== undefined && object.externalDocs !== null) {
message.externalDocs = ExternalDocumentation.fromPartial(object.externalDocs);
} else {
message.externalDocs = undefined;
}
if (object.extensions !== undefined && object.extensions !== null) {
Object.entries(object.extensions).forEach(([key, value]) => {
if (value !== undefined) {
message.extensions[key] = Value.fromPartial(value);
}
});
}
return message;
},
};
const baseSwagger_ResponsesEntry: object = { key: "" };
export const Swagger_ResponsesEntry = {
encode(message: Swagger_ResponsesEntry, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.key !== "") {
writer.uint32(10).string(message.key);
}
if (message.value !== undefined) {
Response.encode(message.value, writer.uint32(18).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Swagger_ResponsesEntry {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseSwagger_ResponsesEntry } as Swagger_ResponsesEntry;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.string();
break;
case 2:
message.value = Response.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Swagger_ResponsesEntry {
const message = { ...baseSwagger_ResponsesEntry } as Swagger_ResponsesEntry;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = Response.fromJSON(object.value);
} else {
message.value = undefined;
}
return message;
},
toJSON(message: Swagger_ResponsesEntry): unknown {
const obj: any = {};
message.key !== undefined && (obj.key = message.key);
message.value !== undefined &&
(obj.value = message.value ? Response.toJSON(message.value) : undefined);
return obj;
},
fromPartial(object: DeepPartial<Swagger_ResponsesEntry>): Swagger_ResponsesEntry {
const message = { ...baseSwagger_ResponsesEntry } as Swagger_ResponsesEntry;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = Response.fromPartial(object.value);
} else {
message.value = undefined;
}
return message;
},
};
const baseSwagger_ExtensionsEntry: object = { key: "" };
export const Swagger_ExtensionsEntry = {
encode(message: Swagger_ExtensionsEntry, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.key !== "") {
writer.uint32(10).string(message.key);
}
if (message.value !== undefined) {
Value.encode(message.value, writer.uint32(18).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Swagger_ExtensionsEntry {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseSwagger_ExtensionsEntry,
} as Swagger_ExtensionsEntry;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.string();
break;
case 2:
message.value = Value.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Swagger_ExtensionsEntry {
const message = {
...baseSwagger_ExtensionsEntry,
} as Swagger_ExtensionsEntry;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = Value.fromJSON(object.value);
} else {
message.value = undefined;
}
return message;
},
toJSON(message: Swagger_ExtensionsEntry): unknown {
const obj: any = {};
message.key !== undefined && (obj.key = message.key);
message.value !== undefined &&
(obj.value = message.value ? Value.toJSON(message.value) : undefined);
return obj;
},
fromPartial(object: DeepPartial<Swagger_ExtensionsEntry>): Swagger_ExtensionsEntry {
const message = {
...baseSwagger_ExtensionsEntry,
} as Swagger_ExtensionsEntry;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = Value.fromPartial(object.value);
} else {
message.value = undefined;
}
return message;
},
};
const baseOperation: object = {
tags: "",
summary: "",
description: "",
operationId: "",
consumes: "",
produces: "",
schemes: 0,
deprecated: false,
};
export const Operation = {
encode(message: Operation, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
for (const v of message.tags) {
writer.uint32(10).string(v!);
}
if (message.summary !== "") {
writer.uint32(18).string(message.summary);
}
if (message.description !== "") {
writer.uint32(26).string(message.description);
}
if (message.externalDocs !== undefined) {
ExternalDocumentation.encode(message.externalDocs, writer.uint32(34).fork()).ldelim();
}
if (message.operationId !== "") {
writer.uint32(42).string(message.operationId);
}
for (const v of message.consumes) {
writer.uint32(50).string(v!);
}
for (const v of message.produces) {
writer.uint32(58).string(v!);
}
Object.entries(message.responses).forEach(([key, value]) => {
Operation_ResponsesEntry.encode(
{ key: key as any, value },
writer.uint32(74).fork(),
).ldelim();
});
writer.uint32(82).fork();
for (const v of message.schemes) {
writer.int32(v);
}
writer.ldelim();
if (message.deprecated === true) {
writer.uint32(88).bool(message.deprecated);
}
for (const v of message.security) {
SecurityRequirement.encode(v!, writer.uint32(98).fork()).ldelim();
}
Object.entries(message.extensions).forEach(([key, value]) => {
Operation_ExtensionsEntry.encode(
{ key: key as any, value },
writer.uint32(106).fork(),
).ldelim();
});
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Operation {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseOperation } as Operation;
message.tags = [];
message.consumes = [];
message.produces = [];
message.responses = {};
message.schemes = [];
message.security = [];
message.extensions = {};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.tags.push(reader.string());
break;
case 2:
message.summary = reader.string();
break;
case 3:
message.description = reader.string();
break;
case 4:
message.externalDocs = ExternalDocumentation.decode(reader, reader.uint32());
break;
case 5:
message.operationId = reader.string();
break;
case 6:
message.consumes.push(reader.string());
break;
case 7:
message.produces.push(reader.string());
break;
case 9:
const entry9 = Operation_ResponsesEntry.decode(reader, reader.uint32());
if (entry9.value !== undefined) {
message.responses[entry9.key] = entry9.value;
}
break;
case 10:
if ((tag & 7) === 2) {
const end2 = reader.uint32() + reader.pos;
while (reader.pos < end2) {
message.schemes.push(reader.int32() as any);
}
} else {
message.schemes.push(reader.int32() as any);
}
break;
case 11:
message.deprecated = reader.bool();
break;
case 12:
message.security.push(SecurityRequirement.decode(reader, reader.uint32()));
break;
case 13:
const entry13 = Operation_ExtensionsEntry.decode(reader, reader.uint32());
if (entry13.value !== undefined) {
message.extensions[entry13.key] = entry13.value;
}
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Operation {
const message = { ...baseOperation } as Operation;
message.tags = [];
message.consumes = [];
message.produces = [];
message.responses = {};
message.schemes = [];
message.security = [];
message.extensions = {};
if (object.tags !== undefined && object.tags !== null) {
for (const e of object.tags) {
message.tags.push(String(e));
}
}
if (object.summary !== undefined && object.summary !== null) {
message.summary = String(object.summary);
} else {
message.summary = "";
}
if (object.description !== undefined && object.description !== null) {
message.description = String(object.description);
} else {
message.description = "";
}
if (object.externalDocs !== undefined && object.externalDocs !== null) {
message.externalDocs = ExternalDocumentation.fromJSON(object.externalDocs);
} else {
message.externalDocs = undefined;
}
if (object.operationId !== undefined && object.operationId !== null) {
message.operationId = String(object.operationId);
} else {
message.operationId = "";
}
if (object.consumes !== undefined && object.consumes !== null) {
for (const e of object.consumes) {
message.consumes.push(String(e));
}
}
if (object.produces !== undefined && object.produces !== null) {
for (const e of object.produces) {
message.produces.push(String(e));
}
}
if (object.responses !== undefined && object.responses !== null) {
Object.entries(object.responses).forEach(([key, value]) => {
message.responses[key] = Response.fromJSON(value);
});
}
if (object.schemes !== undefined && object.schemes !== null) {
for (const e of object.schemes) {
message.schemes.push(schemeFromJSON(e));
}
}
if (object.deprecated !== undefined && object.deprecated !== null) {
message.deprecated = Boolean(object.deprecated);
} else {
message.deprecated = false;
}
if (object.security !== undefined && object.security !== null) {
for (const e of object.security) {
message.security.push(SecurityRequirement.fromJSON(e));
}
}
if (object.extensions !== undefined && object.extensions !== null) {
Object.entries(object.extensions).forEach(([key, value]) => {
message.extensions[key] = Value.fromJSON(value);
});
}
return message;
},
toJSON(message: Operation): unknown {
const obj: any = {};
if (message.tags) {
obj.tags = message.tags.map(e => e);
} else {
obj.tags = [];
}
message.summary !== undefined && (obj.summary = message.summary);
message.description !== undefined && (obj.description = message.description);
message.externalDocs !== undefined &&
(obj.externalDocs = message.externalDocs
? ExternalDocumentation.toJSON(message.externalDocs)
: undefined);
message.operationId !== undefined && (obj.operationId = message.operationId);
if (message.consumes) {
obj.consumes = message.consumes.map(e => e);
} else {
obj.consumes = [];
}
if (message.produces) {
obj.produces = message.produces.map(e => e);
} else {
obj.produces = [];
}
obj.responses = {};
if (message.responses) {
Object.entries(message.responses).forEach(([k, v]) => {
obj.responses[k] = Response.toJSON(v);
});
}
if (message.schemes) {
obj.schemes = message.schemes.map(e => schemeToJSON(e));
} else {
obj.schemes = [];
}
message.deprecated !== undefined && (obj.deprecated = message.deprecated);
if (message.security) {
obj.security = message.security.map(e => (e ? SecurityRequirement.toJSON(e) : undefined));
} else {
obj.security = [];
}
obj.extensions = {};
if (message.extensions) {
Object.entries(message.extensions).forEach(([k, v]) => {
obj.extensions[k] = Value.toJSON(v);
});
}
return obj;
},
fromPartial(object: DeepPartial<Operation>): Operation {
const message = { ...baseOperation } as Operation;
message.tags = [];
message.consumes = [];
message.produces = [];
message.responses = {};
message.schemes = [];
message.security = [];
message.extensions = {};
if (object.tags !== undefined && object.tags !== null) {
for (const e of object.tags) {
message.tags.push(e);
}
}
if (object.summary !== undefined && object.summary !== null) {
message.summary = object.summary;
} else {
message.summary = "";
}
if (object.description !== undefined && object.description !== null) {
message.description = object.description;
} else {
message.description = "";
}
if (object.externalDocs !== undefined && object.externalDocs !== null) {
message.externalDocs = ExternalDocumentation.fromPartial(object.externalDocs);
} else {
message.externalDocs = undefined;
}
if (object.operationId !== undefined && object.operationId !== null) {
message.operationId = object.operationId;
} else {
message.operationId = "";
}
if (object.consumes !== undefined && object.consumes !== null) {
for (const e of object.consumes) {
message.consumes.push(e);
}
}
if (object.produces !== undefined && object.produces !== null) {
for (const e of object.produces) {
message.produces.push(e);
}
}
if (object.responses !== undefined && object.responses !== null) {
Object.entries(object.responses).forEach(([key, value]) => {
if (value !== undefined) {
message.responses[key] = Response.fromPartial(value);
}
});
}
if (object.schemes !== undefined && object.schemes !== null) {
for (const e of object.schemes) {
message.schemes.push(e);
}
}
if (object.deprecated !== undefined && object.deprecated !== null) {
message.deprecated = object.deprecated;
} else {
message.deprecated = false;
}
if (object.security !== undefined && object.security !== null) {
for (const e of object.security) {
message.security.push(SecurityRequirement.fromPartial(e));
}
}
if (object.extensions !== undefined && object.extensions !== null) {
Object.entries(object.extensions).forEach(([key, value]) => {
if (value !== undefined) {
message.extensions[key] = Value.fromPartial(value);
}
});
}
return message;
},
};
const baseOperation_ResponsesEntry: object = { key: "" };
export const Operation_ResponsesEntry = {
encode(message: Operation_ResponsesEntry, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.key !== "") {
writer.uint32(10).string(message.key);
}
if (message.value !== undefined) {
Response.encode(message.value, writer.uint32(18).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Operation_ResponsesEntry {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseOperation_ResponsesEntry,
} as Operation_ResponsesEntry;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.string();
break;
case 2:
message.value = Response.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Operation_ResponsesEntry {
const message = {
...baseOperation_ResponsesEntry,
} as Operation_ResponsesEntry;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = Response.fromJSON(object.value);
} else {
message.value = undefined;
}
return message;
},
toJSON(message: Operation_ResponsesEntry): unknown {
const obj: any = {};
message.key !== undefined && (obj.key = message.key);
message.value !== undefined &&
(obj.value = message.value ? Response.toJSON(message.value) : undefined);
return obj;
},
fromPartial(object: DeepPartial<Operation_ResponsesEntry>): Operation_ResponsesEntry {
const message = {
...baseOperation_ResponsesEntry,
} as Operation_ResponsesEntry;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = Response.fromPartial(object.value);
} else {
message.value = undefined;
}
return message;
},
};
const baseOperation_ExtensionsEntry: object = { key: "" };
export const Operation_ExtensionsEntry = {
encode(message: Operation_ExtensionsEntry, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.key !== "") {
writer.uint32(10).string(message.key);
}
if (message.value !== undefined) {
Value.encode(message.value, writer.uint32(18).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Operation_ExtensionsEntry {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseOperation_ExtensionsEntry,
} as Operation_ExtensionsEntry;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.string();
break;
case 2:
message.value = Value.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Operation_ExtensionsEntry {
const message = {
...baseOperation_ExtensionsEntry,
} as Operation_ExtensionsEntry;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = Value.fromJSON(object.value);
} else {
message.value = undefined;
}
return message;
},
toJSON(message: Operation_ExtensionsEntry): unknown {
const obj: any = {};
message.key !== undefined && (obj.key = message.key);
message.value !== undefined &&
(obj.value = message.value ? Value.toJSON(message.value) : undefined);
return obj;
},
fromPartial(object: DeepPartial<Operation_ExtensionsEntry>): Operation_ExtensionsEntry {
const message = {
...baseOperation_ExtensionsEntry,
} as Operation_ExtensionsEntry;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = Value.fromPartial(object.value);
} else {
message.value = undefined;
}
return message;
},
};
const baseHeader: object = {
description: "",
type: "",
format: "",
default: "",
pattern: "",
};
export const Header = {
encode(message: Header, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.description !== "") {
writer.uint32(10).string(message.description);
}
if (message.type !== "") {
writer.uint32(18).string(message.type);
}
if (message.format !== "") {
writer.uint32(26).string(message.format);
}
if (message.default !== "") {
writer.uint32(50).string(message.default);
}
if (message.pattern !== "") {
writer.uint32(106).string(message.pattern);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Header {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseHeader } as Header;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.description = reader.string();
break;
case 2:
message.type = reader.string();
break;
case 3:
message.format = reader.string();
break;
case 6:
message.default = reader.string();
break;
case 13:
message.pattern = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Header {
const message = { ...baseHeader } as Header;
if (object.description !== undefined && object.description !== null) {
message.description = String(object.description);
} else {
message.description = "";
}
if (object.type !== undefined && object.type !== null) {
message.type = String(object.type);
} else {
message.type = "";
}
if (object.format !== undefined && object.format !== null) {
message.format = String(object.format);
} else {
message.format = "";
}
if (object.default !== undefined && object.default !== null) {
message.default = String(object.default);
} else {
message.default = "";
}
if (object.pattern !== undefined && object.pattern !== null) {
message.pattern = String(object.pattern);
} else {
message.pattern = "";
}
return message;
},
toJSON(message: Header): unknown {
const obj: any = {};
message.description !== undefined && (obj.description = message.description);
message.type !== undefined && (obj.type = message.type);
message.format !== undefined && (obj.format = message.format);
message.default !== undefined && (obj.default = message.default);
message.pattern !== undefined && (obj.pattern = message.pattern);
return obj;
},
fromPartial(object: DeepPartial<Header>): Header {
const message = { ...baseHeader } as Header;
if (object.description !== undefined && object.description !== null) {
message.description = object.description;
} else {
message.description = "";
}
if (object.type !== undefined && object.type !== null) {
message.type = object.type;
} else {
message.type = "";
}
if (object.format !== undefined && object.format !== null) {
message.format = object.format;
} else {
message.format = "";
}
if (object.default !== undefined && object.default !== null) {
message.default = object.default;
} else {
message.default = "";
}
if (object.pattern !== undefined && object.pattern !== null) {
message.pattern = object.pattern;
} else {
message.pattern = "";
}
return message;
},
};
const baseResponse: object = { description: "" };
export const Response = {
encode(message: Response, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.description !== "") {
writer.uint32(10).string(message.description);
}
if (message.schema !== undefined) {
Schema.encode(message.schema, writer.uint32(18).fork()).ldelim();
}
Object.entries(message.headers).forEach(([key, value]) => {
Response_HeadersEntry.encode({ key: key as any, value }, writer.uint32(26).fork()).ldelim();
});
Object.entries(message.examples).forEach(([key, value]) => {
Response_ExamplesEntry.encode({ key: key as any, value }, writer.uint32(34).fork()).ldelim();
});
Object.entries(message.extensions).forEach(([key, value]) => {
Response_ExtensionsEntry.encode(
{ key: key as any, value },
writer.uint32(42).fork(),
).ldelim();
});
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Response {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseResponse } as Response;
message.headers = {};
message.examples = {};
message.extensions = {};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.description = reader.string();
break;
case 2:
message.schema = Schema.decode(reader, reader.uint32());
break;
case 3:
const entry3 = Response_HeadersEntry.decode(reader, reader.uint32());
if (entry3.value !== undefined) {
message.headers[entry3.key] = entry3.value;
}
break;
case 4:
const entry4 = Response_ExamplesEntry.decode(reader, reader.uint32());
if (entry4.value !== undefined) {
message.examples[entry4.key] = entry4.value;
}
break;
case 5:
const entry5 = Response_ExtensionsEntry.decode(reader, reader.uint32());
if (entry5.value !== undefined) {
message.extensions[entry5.key] = entry5.value;
}
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Response {
const message = { ...baseResponse } as Response;
message.headers = {};
message.examples = {};
message.extensions = {};
if (object.description !== undefined && object.description !== null) {
message.description = String(object.description);
} else {
message.description = "";
}
if (object.schema !== undefined && object.schema !== null) {
message.schema = Schema.fromJSON(object.schema);
} else {
message.schema = undefined;
}
if (object.headers !== undefined && object.headers !== null) {
Object.entries(object.headers).forEach(([key, value]) => {
message.headers[key] = Header.fromJSON(value);
});
}
if (object.examples !== undefined && object.examples !== null) {
Object.entries(object.examples).forEach(([key, value]) => {
message.examples[key] = String(value);
});
}
if (object.extensions !== undefined && object.extensions !== null) {
Object.entries(object.extensions).forEach(([key, value]) => {
message.extensions[key] = Value.fromJSON(value);
});
}
return message;
},
toJSON(message: Response): unknown {
const obj: any = {};
message.description !== undefined && (obj.description = message.description);
message.schema !== undefined &&
(obj.schema = message.schema ? Schema.toJSON(message.schema) : undefined);
obj.headers = {};
if (message.headers) {
Object.entries(message.headers).forEach(([k, v]) => {
obj.headers[k] = Header.toJSON(v);
});
}
obj.examples = {};
if (message.examples) {
Object.entries(message.examples).forEach(([k, v]) => {
obj.examples[k] = v;
});
}
obj.extensions = {};
if (message.extensions) {
Object.entries(message.extensions).forEach(([k, v]) => {
obj.extensions[k] = Value.toJSON(v);
});
}
return obj;
},
fromPartial(object: DeepPartial<Response>): Response {
const message = { ...baseResponse } as Response;
message.headers = {};
message.examples = {};
message.extensions = {};
if (object.description !== undefined && object.description !== null) {
message.description = object.description;
} else {
message.description = "";
}
if (object.schema !== undefined && object.schema !== null) {
message.schema = Schema.fromPartial(object.schema);
} else {
message.schema = undefined;
}
if (object.headers !== undefined && object.headers !== null) {
Object.entries(object.headers).forEach(([key, value]) => {
if (value !== undefined) {
message.headers[key] = Header.fromPartial(value);
}
});
}
if (object.examples !== undefined && object.examples !== null) {
Object.entries(object.examples).forEach(([key, value]) => {
if (value !== undefined) {
message.examples[key] = String(value);
}
});
}
if (object.extensions !== undefined && object.extensions !== null) {
Object.entries(object.extensions).forEach(([key, value]) => {
if (value !== undefined) {
message.extensions[key] = Value.fromPartial(value);
}
});
}
return message;
},
};
const baseResponse_HeadersEntry: object = { key: "" };
export const Response_HeadersEntry = {
encode(message: Response_HeadersEntry, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.key !== "") {
writer.uint32(10).string(message.key);
}
if (message.value !== undefined) {
Header.encode(message.value, writer.uint32(18).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Response_HeadersEntry {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseResponse_HeadersEntry } as Response_HeadersEntry;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.string();
break;
case 2:
message.value = Header.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Response_HeadersEntry {
const message = { ...baseResponse_HeadersEntry } as Response_HeadersEntry;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = Header.fromJSON(object.value);
} else {
message.value = undefined;
}
return message;
},
toJSON(message: Response_HeadersEntry): unknown {
const obj: any = {};
message.key !== undefined && (obj.key = message.key);
message.value !== undefined &&
(obj.value = message.value ? Header.toJSON(message.value) : undefined);
return obj;
},
fromPartial(object: DeepPartial<Response_HeadersEntry>): Response_HeadersEntry {
const message = { ...baseResponse_HeadersEntry } as Response_HeadersEntry;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = Header.fromPartial(object.value);
} else {
message.value = undefined;
}
return message;
},
};
const baseResponse_ExamplesEntry: object = { key: "", value: "" };
export const Response_ExamplesEntry = {
encode(message: Response_ExamplesEntry, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.key !== "") {
writer.uint32(10).string(message.key);
}
if (message.value !== "") {
writer.uint32(18).string(message.value);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Response_ExamplesEntry {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseResponse_ExamplesEntry } as Response_ExamplesEntry;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.string();
break;
case 2:
message.value = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Response_ExamplesEntry {
const message = { ...baseResponse_ExamplesEntry } as Response_ExamplesEntry;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = String(object.value);
} else {
message.value = "";
}
return message;
},
toJSON(message: Response_ExamplesEntry): unknown {
const obj: any = {};
message.key !== undefined && (obj.key = message.key);
message.value !== undefined && (obj.value = message.value);
return obj;
},
fromPartial(object: DeepPartial<Response_ExamplesEntry>): Response_ExamplesEntry {
const message = { ...baseResponse_ExamplesEntry } as Response_ExamplesEntry;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = object.value;
} else {
message.value = "";
}
return message;
},
};
const baseResponse_ExtensionsEntry: object = { key: "" };
export const Response_ExtensionsEntry = {
encode(message: Response_ExtensionsEntry, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.key !== "") {
writer.uint32(10).string(message.key);
}
if (message.value !== undefined) {
Value.encode(message.value, writer.uint32(18).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Response_ExtensionsEntry {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseResponse_ExtensionsEntry,
} as Response_ExtensionsEntry;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.string();
break;
case 2:
message.value = Value.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Response_ExtensionsEntry {
const message = {
...baseResponse_ExtensionsEntry,
} as Response_ExtensionsEntry;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = Value.fromJSON(object.value);
} else {
message.value = undefined;
}
return message;
},
toJSON(message: Response_ExtensionsEntry): unknown {
const obj: any = {};
message.key !== undefined && (obj.key = message.key);
message.value !== undefined &&
(obj.value = message.value ? Value.toJSON(message.value) : undefined);
return obj;
},
fromPartial(object: DeepPartial<Response_ExtensionsEntry>): Response_ExtensionsEntry {
const message = {
...baseResponse_ExtensionsEntry,
} as Response_ExtensionsEntry;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = Value.fromPartial(object.value);
} else {
message.value = undefined;
}
return message;
},
};
const baseInfo: object = {
title: "",
description: "",
termsOfService: "",
version: "",
};
export const Info = {
encode(message: Info, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.title !== "") {
writer.uint32(10).string(message.title);
}
if (message.description !== "") {
writer.uint32(18).string(message.description);
}
if (message.termsOfService !== "") {
writer.uint32(26).string(message.termsOfService);
}
if (message.contact !== undefined) {
Contact.encode(message.contact, writer.uint32(34).fork()).ldelim();
}
if (message.license !== undefined) {
License.encode(message.license, writer.uint32(42).fork()).ldelim();
}
if (message.version !== "") {
writer.uint32(50).string(message.version);
}
Object.entries(message.extensions).forEach(([key, value]) => {
Info_ExtensionsEntry.encode({ key: key as any, value }, writer.uint32(58).fork()).ldelim();
});
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Info {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseInfo } as Info;
message.extensions = {};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.title = reader.string();
break;
case 2:
message.description = reader.string();
break;
case 3:
message.termsOfService = reader.string();
break;
case 4:
message.contact = Contact.decode(reader, reader.uint32());
break;
case 5:
message.license = License.decode(reader, reader.uint32());
break;
case 6:
message.version = reader.string();
break;
case 7:
const entry7 = Info_ExtensionsEntry.decode(reader, reader.uint32());
if (entry7.value !== undefined) {
message.extensions[entry7.key] = entry7.value;
}
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Info {
const message = { ...baseInfo } as Info;
message.extensions = {};
if (object.title !== undefined && object.title !== null) {
message.title = String(object.title);
} else {
message.title = "";
}
if (object.description !== undefined && object.description !== null) {
message.description = String(object.description);
} else {
message.description = "";
}
if (object.termsOfService !== undefined && object.termsOfService !== null) {
message.termsOfService = String(object.termsOfService);
} else {
message.termsOfService = "";
}
if (object.contact !== undefined && object.contact !== null) {
message.contact = Contact.fromJSON(object.contact);
} else {
message.contact = undefined;
}
if (object.license !== undefined && object.license !== null) {
message.license = License.fromJSON(object.license);
} else {
message.license = undefined;
}
if (object.version !== undefined && object.version !== null) {
message.version = String(object.version);
} else {
message.version = "";
}
if (object.extensions !== undefined && object.extensions !== null) {
Object.entries(object.extensions).forEach(([key, value]) => {
message.extensions[key] = Value.fromJSON(value);
});
}
return message;
},
toJSON(message: Info): unknown {
const obj: any = {};
message.title !== undefined && (obj.title = message.title);
message.description !== undefined && (obj.description = message.description);
message.termsOfService !== undefined && (obj.termsOfService = message.termsOfService);
message.contact !== undefined &&
(obj.contact = message.contact ? Contact.toJSON(message.contact) : undefined);
message.license !== undefined &&
(obj.license = message.license ? License.toJSON(message.license) : undefined);
message.version !== undefined && (obj.version = message.version);
obj.extensions = {};
if (message.extensions) {
Object.entries(message.extensions).forEach(([k, v]) => {
obj.extensions[k] = Value.toJSON(v);
});
}
return obj;
},
fromPartial(object: DeepPartial<Info>): Info {
const message = { ...baseInfo } as Info;
message.extensions = {};
if (object.title !== undefined && object.title !== null) {
message.title = object.title;
} else {
message.title = "";
}
if (object.description !== undefined && object.description !== null) {
message.description = object.description;
} else {
message.description = "";
}
if (object.termsOfService !== undefined && object.termsOfService !== null) {
message.termsOfService = object.termsOfService;
} else {
message.termsOfService = "";
}
if (object.contact !== undefined && object.contact !== null) {
message.contact = Contact.fromPartial(object.contact);
} else {
message.contact = undefined;
}
if (object.license !== undefined && object.license !== null) {
message.license = License.fromPartial(object.license);
} else {
message.license = undefined;
}
if (object.version !== undefined && object.version !== null) {
message.version = object.version;
} else {
message.version = "";
}
if (object.extensions !== undefined && object.extensions !== null) {
Object.entries(object.extensions).forEach(([key, value]) => {
if (value !== undefined) {
message.extensions[key] = Value.fromPartial(value);
}
});
}
return message;
},
};
const baseInfo_ExtensionsEntry: object = { key: "" };
export const Info_ExtensionsEntry = {
encode(message: Info_ExtensionsEntry, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.key !== "") {
writer.uint32(10).string(message.key);
}
if (message.value !== undefined) {
Value.encode(message.value, writer.uint32(18).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Info_ExtensionsEntry {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseInfo_ExtensionsEntry } as Info_ExtensionsEntry;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.string();
break;
case 2:
message.value = Value.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Info_ExtensionsEntry {
const message = { ...baseInfo_ExtensionsEntry } as Info_ExtensionsEntry;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = Value.fromJSON(object.value);
} else {
message.value = undefined;
}
return message;
},
toJSON(message: Info_ExtensionsEntry): unknown {
const obj: any = {};
message.key !== undefined && (obj.key = message.key);
message.value !== undefined &&
(obj.value = message.value ? Value.toJSON(message.value) : undefined);
return obj;
},
fromPartial(object: DeepPartial<Info_ExtensionsEntry>): Info_ExtensionsEntry {
const message = { ...baseInfo_ExtensionsEntry } as Info_ExtensionsEntry;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = Value.fromPartial(object.value);
} else {
message.value = undefined;
}
return message;
},
};
const baseContact: object = { name: "", url: "", email: "" };
export const Contact = {
encode(message: Contact, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.name !== "") {
writer.uint32(10).string(message.name);
}
if (message.url !== "") {
writer.uint32(18).string(message.url);
}
if (message.email !== "") {
writer.uint32(26).string(message.email);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Contact {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseContact } as Contact;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.name = reader.string();
break;
case 2:
message.url = reader.string();
break;
case 3:
message.email = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Contact {
const message = { ...baseContact } as Contact;
if (object.name !== undefined && object.name !== null) {
message.name = String(object.name);
} else {
message.name = "";
}
if (object.url !== undefined && object.url !== null) {
message.url = String(object.url);
} else {
message.url = "";
}
if (object.email !== undefined && object.email !== null) {
message.email = String(object.email);
} else {
message.email = "";
}
return message;
},
toJSON(message: Contact): unknown {
const obj: any = {};
message.name !== undefined && (obj.name = message.name);
message.url !== undefined && (obj.url = message.url);
message.email !== undefined && (obj.email = message.email);
return obj;
},
fromPartial(object: DeepPartial<Contact>): Contact {
const message = { ...baseContact } as Contact;
if (object.name !== undefined && object.name !== null) {
message.name = object.name;
} else {
message.name = "";
}
if (object.url !== undefined && object.url !== null) {
message.url = object.url;
} else {
message.url = "";
}
if (object.email !== undefined && object.email !== null) {
message.email = object.email;
} else {
message.email = "";
}
return message;
},
};
const baseLicense: object = { name: "", url: "" };
export const License = {
encode(message: License, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.name !== "") {
writer.uint32(10).string(message.name);
}
if (message.url !== "") {
writer.uint32(18).string(message.url);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): License {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseLicense } as License;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.name = reader.string();
break;
case 2:
message.url = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): License {
const message = { ...baseLicense } as License;
if (object.name !== undefined && object.name !== null) {
message.name = String(object.name);
} else {
message.name = "";
}
if (object.url !== undefined && object.url !== null) {
message.url = String(object.url);
} else {
message.url = "";
}
return message;
},
toJSON(message: License): unknown {
const obj: any = {};
message.name !== undefined && (obj.name = message.name);
message.url !== undefined && (obj.url = message.url);
return obj;
},
fromPartial(object: DeepPartial<License>): License {
const message = { ...baseLicense } as License;
if (object.name !== undefined && object.name !== null) {
message.name = object.name;
} else {
message.name = "";
}
if (object.url !== undefined && object.url !== null) {
message.url = object.url;
} else {
message.url = "";
}
return message;
},
};
const baseExternalDocumentation: object = { description: "", url: "" };
export const ExternalDocumentation = {
encode(message: ExternalDocumentation, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.description !== "") {
writer.uint32(10).string(message.description);
}
if (message.url !== "") {
writer.uint32(18).string(message.url);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): ExternalDocumentation {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseExternalDocumentation } as ExternalDocumentation;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.description = reader.string();
break;
case 2:
message.url = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): ExternalDocumentation {
const message = { ...baseExternalDocumentation } as ExternalDocumentation;
if (object.description !== undefined && object.description !== null) {
message.description = String(object.description);
} else {
message.description = "";
}
if (object.url !== undefined && object.url !== null) {
message.url = String(object.url);
} else {
message.url = "";
}
return message;
},
toJSON(message: ExternalDocumentation): unknown {
const obj: any = {};
message.description !== undefined && (obj.description = message.description);
message.url !== undefined && (obj.url = message.url);
return obj;
},
fromPartial(object: DeepPartial<ExternalDocumentation>): ExternalDocumentation {
const message = { ...baseExternalDocumentation } as ExternalDocumentation;
if (object.description !== undefined && object.description !== null) {
message.description = object.description;
} else {
message.description = "";
}
if (object.url !== undefined && object.url !== null) {
message.url = object.url;
} else {
message.url = "";
}
return message;
},
};
const baseSchema: object = { discriminator: "", readOnly: false, example: "" };
export const Schema = {
encode(message: Schema, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.jsonSchema !== undefined) {
JSONSchema.encode(message.jsonSchema, writer.uint32(10).fork()).ldelim();
}
if (message.discriminator !== "") {
writer.uint32(18).string(message.discriminator);
}
if (message.readOnly === true) {
writer.uint32(24).bool(message.readOnly);
}
if (message.externalDocs !== undefined) {
ExternalDocumentation.encode(message.externalDocs, writer.uint32(42).fork()).ldelim();
}
if (message.example !== "") {
writer.uint32(50).string(message.example);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Schema {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseSchema } as Schema;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.jsonSchema = JSONSchema.decode(reader, reader.uint32());
break;
case 2:
message.discriminator = reader.string();
break;
case 3:
message.readOnly = reader.bool();
break;
case 5:
message.externalDocs = ExternalDocumentation.decode(reader, reader.uint32());
break;
case 6:
message.example = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Schema {
const message = { ...baseSchema } as Schema;
if (object.jsonSchema !== undefined && object.jsonSchema !== null) {
message.jsonSchema = JSONSchema.fromJSON(object.jsonSchema);
} else {
message.jsonSchema = undefined;
}
if (object.discriminator !== undefined && object.discriminator !== null) {
message.discriminator = String(object.discriminator);
} else {
message.discriminator = "";
}
if (object.readOnly !== undefined && object.readOnly !== null) {
message.readOnly = Boolean(object.readOnly);
} else {
message.readOnly = false;
}
if (object.externalDocs !== undefined && object.externalDocs !== null) {
message.externalDocs = ExternalDocumentation.fromJSON(object.externalDocs);
} else {
message.externalDocs = undefined;
}
if (object.example !== undefined && object.example !== null) {
message.example = String(object.example);
} else {
message.example = "";
}
return message;
},
toJSON(message: Schema): unknown {
const obj: any = {};
message.jsonSchema !== undefined &&
(obj.jsonSchema = message.jsonSchema ? JSONSchema.toJSON(message.jsonSchema) : undefined);
message.discriminator !== undefined && (obj.discriminator = message.discriminator);
message.readOnly !== undefined && (obj.readOnly = message.readOnly);
message.externalDocs !== undefined &&
(obj.externalDocs = message.externalDocs
? ExternalDocumentation.toJSON(message.externalDocs)
: undefined);
message.example !== undefined && (obj.example = message.example);
return obj;
},
fromPartial(object: DeepPartial<Schema>): Schema {
const message = { ...baseSchema } as Schema;
if (object.jsonSchema !== undefined && object.jsonSchema !== null) {
message.jsonSchema = JSONSchema.fromPartial(object.jsonSchema);
} else {
message.jsonSchema = undefined;
}
if (object.discriminator !== undefined && object.discriminator !== null) {
message.discriminator = object.discriminator;
} else {
message.discriminator = "";
}
if (object.readOnly !== undefined && object.readOnly !== null) {
message.readOnly = object.readOnly;
} else {
message.readOnly = false;
}
if (object.externalDocs !== undefined && object.externalDocs !== null) {
message.externalDocs = ExternalDocumentation.fromPartial(object.externalDocs);
} else {
message.externalDocs = undefined;
}
if (object.example !== undefined && object.example !== null) {
message.example = object.example;
} else {
message.example = "";
}
return message;
},
};
const baseJSONSchema: object = {
ref: "",
title: "",
description: "",
default: "",
readOnly: false,
example: "",
multipleOf: 0,
maximum: 0,
exclusiveMaximum: false,
minimum: 0,
exclusiveMinimum: false,
maxLength: 0,
minLength: 0,
pattern: "",
maxItems: 0,
minItems: 0,
uniqueItems: false,
maxProperties: 0,
minProperties: 0,
required: "",
array: "",
type: 0,
format: "",
enum: "",
};
export const JSONSchema = {
encode(message: JSONSchema, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.ref !== "") {
writer.uint32(26).string(message.ref);
}
if (message.title !== "") {
writer.uint32(42).string(message.title);
}
if (message.description !== "") {
writer.uint32(50).string(message.description);
}
if (message.default !== "") {
writer.uint32(58).string(message.default);
}
if (message.readOnly === true) {
writer.uint32(64).bool(message.readOnly);
}
if (message.example !== "") {
writer.uint32(74).string(message.example);
}
if (message.multipleOf !== 0) {
writer.uint32(81).double(message.multipleOf);
}
if (message.maximum !== 0) {
writer.uint32(89).double(message.maximum);
}
if (message.exclusiveMaximum === true) {
writer.uint32(96).bool(message.exclusiveMaximum);
}
if (message.minimum !== 0) {
writer.uint32(105).double(message.minimum);
}
if (message.exclusiveMinimum === true) {
writer.uint32(112).bool(message.exclusiveMinimum);
}
if (message.maxLength !== 0) {
writer.uint32(120).uint64(message.maxLength);
}
if (message.minLength !== 0) {
writer.uint32(128).uint64(message.minLength);
}
if (message.pattern !== "") {
writer.uint32(138).string(message.pattern);
}
if (message.maxItems !== 0) {
writer.uint32(160).uint64(message.maxItems);
}
if (message.minItems !== 0) {
writer.uint32(168).uint64(message.minItems);
}
if (message.uniqueItems === true) {
writer.uint32(176).bool(message.uniqueItems);
}
if (message.maxProperties !== 0) {
writer.uint32(192).uint64(message.maxProperties);
}
if (message.minProperties !== 0) {
writer.uint32(200).uint64(message.minProperties);
}
for (const v of message.required) {
writer.uint32(210).string(v!);
}
for (const v of message.array) {
writer.uint32(274).string(v!);
}
writer.uint32(282).fork();
for (const v of message.type) {
writer.int32(v);
}
writer.ldelim();
if (message.format !== "") {
writer.uint32(290).string(message.format);
}
for (const v of message.enum) {
writer.uint32(370).string(v!);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): JSONSchema {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseJSONSchema } as JSONSchema;
message.required = [];
message.array = [];
message.type = [];
message.enum = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 3:
message.ref = reader.string();
break;
case 5:
message.title = reader.string();
break;
case 6:
message.description = reader.string();
break;
case 7:
message.default = reader.string();
break;
case 8:
message.readOnly = reader.bool();
break;
case 9:
message.example = reader.string();
break;
case 10:
message.multipleOf = reader.double();
break;
case 11:
message.maximum = reader.double();
break;
case 12:
message.exclusiveMaximum = reader.bool();
break;
case 13:
message.minimum = reader.double();
break;
case 14:
message.exclusiveMinimum = reader.bool();
break;
case 15:
message.maxLength = longToNumber(reader.uint64() as Long);
break;
case 16:
message.minLength = longToNumber(reader.uint64() as Long);
break;
case 17:
message.pattern = reader.string();
break;
case 20:
message.maxItems = longToNumber(reader.uint64() as Long);
break;
case 21:
message.minItems = longToNumber(reader.uint64() as Long);
break;
case 22:
message.uniqueItems = reader.bool();
break;
case 24:
message.maxProperties = longToNumber(reader.uint64() as Long);
break;
case 25:
message.minProperties = longToNumber(reader.uint64() as Long);
break;
case 26:
message.required.push(reader.string());
break;
case 34:
message.array.push(reader.string());
break;
case 35:
if ((tag & 7) === 2) {
const end2 = reader.uint32() + reader.pos;
while (reader.pos < end2) {
message.type.push(reader.int32() as any);
}
} else {
message.type.push(reader.int32() as any);
}
break;
case 36:
message.format = reader.string();
break;
case 46:
message.enum.push(reader.string());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): JSONSchema {
const message = { ...baseJSONSchema } as JSONSchema;
message.required = [];
message.array = [];
message.type = [];
message.enum = [];
if (object.ref !== undefined && object.ref !== null) {
message.ref = String(object.ref);
} else {
message.ref = "";
}
if (object.title !== undefined && object.title !== null) {
message.title = String(object.title);
} else {
message.title = "";
}
if (object.description !== undefined && object.description !== null) {
message.description = String(object.description);
} else {
message.description = "";
}
if (object.default !== undefined && object.default !== null) {
message.default = String(object.default);
} else {
message.default = "";
}
if (object.readOnly !== undefined && object.readOnly !== null) {
message.readOnly = Boolean(object.readOnly);
} else {
message.readOnly = false;
}
if (object.example !== undefined && object.example !== null) {
message.example = String(object.example);
} else {
message.example = "";
}
if (object.multipleOf !== undefined && object.multipleOf !== null) {
message.multipleOf = Number(object.multipleOf);
} else {
message.multipleOf = 0;
}
if (object.maximum !== undefined && object.maximum !== null) {
message.maximum = Number(object.maximum);
} else {
message.maximum = 0;
}
if (object.exclusiveMaximum !== undefined && object.exclusiveMaximum !== null) {
message.exclusiveMaximum = Boolean(object.exclusiveMaximum);
} else {
message.exclusiveMaximum = false;
}
if (object.minimum !== undefined && object.minimum !== null) {
message.minimum = Number(object.minimum);
} else {
message.minimum = 0;
}
if (object.exclusiveMinimum !== undefined && object.exclusiveMinimum !== null) {
message.exclusiveMinimum = Boolean(object.exclusiveMinimum);
} else {
message.exclusiveMinimum = false;
}
if (object.maxLength !== undefined && object.maxLength !== null) {
message.maxLength = Number(object.maxLength);
} else {
message.maxLength = 0;
}
if (object.minLength !== undefined && object.minLength !== null) {
message.minLength = Number(object.minLength);
} else {
message.minLength = 0;
}
if (object.pattern !== undefined && object.pattern !== null) {
message.pattern = String(object.pattern);
} else {
message.pattern = "";
}
if (object.maxItems !== undefined && object.maxItems !== null) {
message.maxItems = Number(object.maxItems);
} else {
message.maxItems = 0;
}
if (object.minItems !== undefined && object.minItems !== null) {
message.minItems = Number(object.minItems);
} else {
message.minItems = 0;
}
if (object.uniqueItems !== undefined && object.uniqueItems !== null) {
message.uniqueItems = Boolean(object.uniqueItems);
} else {
message.uniqueItems = false;
}
if (object.maxProperties !== undefined && object.maxProperties !== null) {
message.maxProperties = Number(object.maxProperties);
} else {
message.maxProperties = 0;
}
if (object.minProperties !== undefined && object.minProperties !== null) {
message.minProperties = Number(object.minProperties);
} else {
message.minProperties = 0;
}
if (object.required !== undefined && object.required !== null) {
for (const e of object.required) {
message.required.push(String(e));
}
}
if (object.array !== undefined && object.array !== null) {
for (const e of object.array) {
message.array.push(String(e));
}
}
if (object.type !== undefined && object.type !== null) {
for (const e of object.type) {
message.type.push(jSONSchema_JSONSchemaSimpleTypesFromJSON(e));
}
}
if (object.format !== undefined && object.format !== null) {
message.format = String(object.format);
} else {
message.format = "";
}
if (object.enum !== undefined && object.enum !== null) {
for (const e of object.enum) {
message.enum.push(String(e));
}
}
return message;
},
toJSON(message: JSONSchema): unknown {
const obj: any = {};
message.ref !== undefined && (obj.ref = message.ref);
message.title !== undefined && (obj.title = message.title);
message.description !== undefined && (obj.description = message.description);
message.default !== undefined && (obj.default = message.default);
message.readOnly !== undefined && (obj.readOnly = message.readOnly);
message.example !== undefined && (obj.example = message.example);
message.multipleOf !== undefined && (obj.multipleOf = message.multipleOf);
message.maximum !== undefined && (obj.maximum = message.maximum);
message.exclusiveMaximum !== undefined && (obj.exclusiveMaximum = message.exclusiveMaximum);
message.minimum !== undefined && (obj.minimum = message.minimum);
message.exclusiveMinimum !== undefined && (obj.exclusiveMinimum = message.exclusiveMinimum);
message.maxLength !== undefined && (obj.maxLength = message.maxLength);
message.minLength !== undefined && (obj.minLength = message.minLength);
message.pattern !== undefined && (obj.pattern = message.pattern);
message.maxItems !== undefined && (obj.maxItems = message.maxItems);
message.minItems !== undefined && (obj.minItems = message.minItems);
message.uniqueItems !== undefined && (obj.uniqueItems = message.uniqueItems);
message.maxProperties !== undefined && (obj.maxProperties = message.maxProperties);
message.minProperties !== undefined && (obj.minProperties = message.minProperties);
if (message.required) {
obj.required = message.required.map(e => e);
} else {
obj.required = [];
}
if (message.array) {
obj.array = message.array.map(e => e);
} else {
obj.array = [];
}
if (message.type) {
obj.type = message.type.map(e => jSONSchema_JSONSchemaSimpleTypesToJSON(e));
} else {
obj.type = [];
}
message.format !== undefined && (obj.format = message.format);
if (message.enum) {
obj.enum = message.enum.map(e => e);
} else {
obj.enum = [];
}
return obj;
},
fromPartial(object: DeepPartial<JSONSchema>): JSONSchema {
const message = { ...baseJSONSchema } as JSONSchema;
message.required = [];
message.array = [];
message.type = [];
message.enum = [];
if (object.ref !== undefined && object.ref !== null) {
message.ref = object.ref;
} else {
message.ref = "";
}
if (object.title !== undefined && object.title !== null) {
message.title = object.title;
} else {
message.title = "";
}
if (object.description !== undefined && object.description !== null) {
message.description = object.description;
} else {
message.description = "";
}
if (object.default !== undefined && object.default !== null) {
message.default = object.default;
} else {
message.default = "";
}
if (object.readOnly !== undefined && object.readOnly !== null) {
message.readOnly = object.readOnly;
} else {
message.readOnly = false;
}
if (object.example !== undefined && object.example !== null) {
message.example = object.example;
} else {
message.example = "";
}
if (object.multipleOf !== undefined && object.multipleOf !== null) {
message.multipleOf = object.multipleOf;
} else {
message.multipleOf = 0;
}
if (object.maximum !== undefined && object.maximum !== null) {
message.maximum = object.maximum;
} else {
message.maximum = 0;
}
if (object.exclusiveMaximum !== undefined && object.exclusiveMaximum !== null) {
message.exclusiveMaximum = object.exclusiveMaximum;
} else {
message.exclusiveMaximum = false;
}
if (object.minimum !== undefined && object.minimum !== null) {
message.minimum = object.minimum;
} else {
message.minimum = 0;
}
if (object.exclusiveMinimum !== undefined && object.exclusiveMinimum !== null) {
message.exclusiveMinimum = object.exclusiveMinimum;
} else {
message.exclusiveMinimum = false;
}
if (object.maxLength !== undefined && object.maxLength !== null) {
message.maxLength = object.maxLength;
} else {
message.maxLength = 0;
}
if (object.minLength !== undefined && object.minLength !== null) {
message.minLength = object.minLength;
} else {
message.minLength = 0;
}
if (object.pattern !== undefined && object.pattern !== null) {
message.pattern = object.pattern;
} else {
message.pattern = "";
}
if (object.maxItems !== undefined && object.maxItems !== null) {
message.maxItems = object.maxItems;
} else {
message.maxItems = 0;
}
if (object.minItems !== undefined && object.minItems !== null) {
message.minItems = object.minItems;
} else {
message.minItems = 0;
}
if (object.uniqueItems !== undefined && object.uniqueItems !== null) {
message.uniqueItems = object.uniqueItems;
} else {
message.uniqueItems = false;
}
if (object.maxProperties !== undefined && object.maxProperties !== null) {
message.maxProperties = object.maxProperties;
} else {
message.maxProperties = 0;
}
if (object.minProperties !== undefined && object.minProperties !== null) {
message.minProperties = object.minProperties;
} else {
message.minProperties = 0;
}
if (object.required !== undefined && object.required !== null) {
for (const e of object.required) {
message.required.push(e);
}
}
if (object.array !== undefined && object.array !== null) {
for (const e of object.array) {
message.array.push(e);
}
}
if (object.type !== undefined && object.type !== null) {
for (const e of object.type) {
message.type.push(e);
}
}
if (object.format !== undefined && object.format !== null) {
message.format = object.format;
} else {
message.format = "";
}
if (object.enum !== undefined && object.enum !== null) {
for (const e of object.enum) {
message.enum.push(e);
}
}
return message;
},
};
const baseTag: object = { description: "" };
export const Tag = {
encode(message: Tag, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.description !== "") {
writer.uint32(18).string(message.description);
}
if (message.externalDocs !== undefined) {
ExternalDocumentation.encode(message.externalDocs, writer.uint32(26).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Tag {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseTag } as Tag;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 2:
message.description = reader.string();
break;
case 3:
message.externalDocs = ExternalDocumentation.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Tag {
const message = { ...baseTag } as Tag;
if (object.description !== undefined && object.description !== null) {
message.description = String(object.description);
} else {
message.description = "";
}
if (object.externalDocs !== undefined && object.externalDocs !== null) {
message.externalDocs = ExternalDocumentation.fromJSON(object.externalDocs);
} else {
message.externalDocs = undefined;
}
return message;
},
toJSON(message: Tag): unknown {
const obj: any = {};
message.description !== undefined && (obj.description = message.description);
message.externalDocs !== undefined &&
(obj.externalDocs = message.externalDocs
? ExternalDocumentation.toJSON(message.externalDocs)
: undefined);
return obj;
},
fromPartial(object: DeepPartial<Tag>): Tag {
const message = { ...baseTag } as Tag;
if (object.description !== undefined && object.description !== null) {
message.description = object.description;
} else {
message.description = "";
}
if (object.externalDocs !== undefined && object.externalDocs !== null) {
message.externalDocs = ExternalDocumentation.fromPartial(object.externalDocs);
} else {
message.externalDocs = undefined;
}
return message;
},
};
const baseSecurityDefinitions: object = {};
export const SecurityDefinitions = {
encode(message: SecurityDefinitions, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
Object.entries(message.security).forEach(([key, value]) => {
SecurityDefinitions_SecurityEntry.encode(
{ key: key as any, value },
writer.uint32(10).fork(),
).ldelim();
});
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): SecurityDefinitions {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseSecurityDefinitions } as SecurityDefinitions;
message.security = {};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
const entry1 = SecurityDefinitions_SecurityEntry.decode(reader, reader.uint32());
if (entry1.value !== undefined) {
message.security[entry1.key] = entry1.value;
}
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): SecurityDefinitions {
const message = { ...baseSecurityDefinitions } as SecurityDefinitions;
message.security = {};
if (object.security !== undefined && object.security !== null) {
Object.entries(object.security).forEach(([key, value]) => {
message.security[key] = SecurityScheme.fromJSON(value);
});
}
return message;
},
toJSON(message: SecurityDefinitions): unknown {
const obj: any = {};
obj.security = {};
if (message.security) {
Object.entries(message.security).forEach(([k, v]) => {
obj.security[k] = SecurityScheme.toJSON(v);
});
}
return obj;
},
fromPartial(object: DeepPartial<SecurityDefinitions>): SecurityDefinitions {
const message = { ...baseSecurityDefinitions } as SecurityDefinitions;
message.security = {};
if (object.security !== undefined && object.security !== null) {
Object.entries(object.security).forEach(([key, value]) => {
if (value !== undefined) {
message.security[key] = SecurityScheme.fromPartial(value);
}
});
}
return message;
},
};
const baseSecurityDefinitions_SecurityEntry: object = { key: "" };
export const SecurityDefinitions_SecurityEntry = {
encode(
message: SecurityDefinitions_SecurityEntry,
writer: _m0.Writer = _m0.Writer.create(),
): _m0.Writer {
if (message.key !== "") {
writer.uint32(10).string(message.key);
}
if (message.value !== undefined) {
SecurityScheme.encode(message.value, writer.uint32(18).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): SecurityDefinitions_SecurityEntry {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseSecurityDefinitions_SecurityEntry,
} as SecurityDefinitions_SecurityEntry;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.string();
break;
case 2:
message.value = SecurityScheme.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): SecurityDefinitions_SecurityEntry {
const message = {
...baseSecurityDefinitions_SecurityEntry,
} as SecurityDefinitions_SecurityEntry;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = SecurityScheme.fromJSON(object.value);
} else {
message.value = undefined;
}
return message;
},
toJSON(message: SecurityDefinitions_SecurityEntry): unknown {
const obj: any = {};
message.key !== undefined && (obj.key = message.key);
message.value !== undefined &&
(obj.value = message.value ? SecurityScheme.toJSON(message.value) : undefined);
return obj;
},
fromPartial(
object: DeepPartial<SecurityDefinitions_SecurityEntry>,
): SecurityDefinitions_SecurityEntry {
const message = {
...baseSecurityDefinitions_SecurityEntry,
} as SecurityDefinitions_SecurityEntry;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = SecurityScheme.fromPartial(object.value);
} else {
message.value = undefined;
}
return message;
},
};
const baseSecurityScheme: object = {
type: 0,
description: "",
name: "",
in: 0,
flow: 0,
authorizationUrl: "",
tokenUrl: "",
};
export const SecurityScheme = {
encode(message: SecurityScheme, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.type !== 0) {
writer.uint32(8).int32(message.type);
}
if (message.description !== "") {
writer.uint32(18).string(message.description);
}
if (message.name !== "") {
writer.uint32(26).string(message.name);
}
if (message.in !== 0) {
writer.uint32(32).int32(message.in);
}
if (message.flow !== 0) {
writer.uint32(40).int32(message.flow);
}
if (message.authorizationUrl !== "") {
writer.uint32(50).string(message.authorizationUrl);
}
if (message.tokenUrl !== "") {
writer.uint32(58).string(message.tokenUrl);
}
if (message.scopes !== undefined) {
Scopes.encode(message.scopes, writer.uint32(66).fork()).ldelim();
}
Object.entries(message.extensions).forEach(([key, value]) => {
SecurityScheme_ExtensionsEntry.encode(
{ key: key as any, value },
writer.uint32(74).fork(),
).ldelim();
});
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): SecurityScheme {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseSecurityScheme } as SecurityScheme;
message.extensions = {};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.type = reader.int32() as any;
break;
case 2:
message.description = reader.string();
break;
case 3:
message.name = reader.string();
break;
case 4:
message.in = reader.int32() as any;
break;
case 5:
message.flow = reader.int32() as any;
break;
case 6:
message.authorizationUrl = reader.string();
break;
case 7:
message.tokenUrl = reader.string();
break;
case 8:
message.scopes = Scopes.decode(reader, reader.uint32());
break;
case 9:
const entry9 = SecurityScheme_ExtensionsEntry.decode(reader, reader.uint32());
if (entry9.value !== undefined) {
message.extensions[entry9.key] = entry9.value;
}
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): SecurityScheme {
const message = { ...baseSecurityScheme } as SecurityScheme;
message.extensions = {};
if (object.type !== undefined && object.type !== null) {
message.type = securityScheme_TypeFromJSON(object.type);
} else {
message.type = 0;
}
if (object.description !== undefined && object.description !== null) {
message.description = String(object.description);
} else {
message.description = "";
}
if (object.name !== undefined && object.name !== null) {
message.name = String(object.name);
} else {
message.name = "";
}
if (object.in !== undefined && object.in !== null) {
message.in = securityScheme_InFromJSON(object.in);
} else {
message.in = 0;
}
if (object.flow !== undefined && object.flow !== null) {
message.flow = securityScheme_FlowFromJSON(object.flow);
} else {
message.flow = 0;
}
if (object.authorizationUrl !== undefined && object.authorizationUrl !== null) {
message.authorizationUrl = String(object.authorizationUrl);
} else {
message.authorizationUrl = "";
}
if (object.tokenUrl !== undefined && object.tokenUrl !== null) {
message.tokenUrl = String(object.tokenUrl);
} else {
message.tokenUrl = "";
}
if (object.scopes !== undefined && object.scopes !== null) {
message.scopes = Scopes.fromJSON(object.scopes);
} else {
message.scopes = undefined;
}
if (object.extensions !== undefined && object.extensions !== null) {
Object.entries(object.extensions).forEach(([key, value]) => {
message.extensions[key] = Value.fromJSON(value);
});
}
return message;
},
toJSON(message: SecurityScheme): unknown {
const obj: any = {};
message.type !== undefined && (obj.type = securityScheme_TypeToJSON(message.type));
message.description !== undefined && (obj.description = message.description);
message.name !== undefined && (obj.name = message.name);
message.in !== undefined && (obj.in = securityScheme_InToJSON(message.in));
message.flow !== undefined && (obj.flow = securityScheme_FlowToJSON(message.flow));
message.authorizationUrl !== undefined && (obj.authorizationUrl = message.authorizationUrl);
message.tokenUrl !== undefined && (obj.tokenUrl = message.tokenUrl);
message.scopes !== undefined &&
(obj.scopes = message.scopes ? Scopes.toJSON(message.scopes) : undefined);
obj.extensions = {};
if (message.extensions) {
Object.entries(message.extensions).forEach(([k, v]) => {
obj.extensions[k] = Value.toJSON(v);
});
}
return obj;
},
fromPartial(object: DeepPartial<SecurityScheme>): SecurityScheme {
const message = { ...baseSecurityScheme } as SecurityScheme;
message.extensions = {};
if (object.type !== undefined && object.type !== null) {
message.type = object.type;
} else {
message.type = 0;
}
if (object.description !== undefined && object.description !== null) {
message.description = object.description;
} else {
message.description = "";
}
if (object.name !== undefined && object.name !== null) {
message.name = object.name;
} else {
message.name = "";
}
if (object.in !== undefined && object.in !== null) {
message.in = object.in;
} else {
message.in = 0;
}
if (object.flow !== undefined && object.flow !== null) {
message.flow = object.flow;
} else {
message.flow = 0;
}
if (object.authorizationUrl !== undefined && object.authorizationUrl !== null) {
message.authorizationUrl = object.authorizationUrl;
} else {
message.authorizationUrl = "";
}
if (object.tokenUrl !== undefined && object.tokenUrl !== null) {
message.tokenUrl = object.tokenUrl;
} else {
message.tokenUrl = "";
}
if (object.scopes !== undefined && object.scopes !== null) {
message.scopes = Scopes.fromPartial(object.scopes);
} else {
message.scopes = undefined;
}
if (object.extensions !== undefined && object.extensions !== null) {
Object.entries(object.extensions).forEach(([key, value]) => {
if (value !== undefined) {
message.extensions[key] = Value.fromPartial(value);
}
});
}
return message;
},
};
const baseSecurityScheme_ExtensionsEntry: object = { key: "" };
export const SecurityScheme_ExtensionsEntry = {
encode(
message: SecurityScheme_ExtensionsEntry,
writer: _m0.Writer = _m0.Writer.create(),
): _m0.Writer {
if (message.key !== "") {
writer.uint32(10).string(message.key);
}
if (message.value !== undefined) {
Value.encode(message.value, writer.uint32(18).fork()).ldelim();
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): SecurityScheme_ExtensionsEntry {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseSecurityScheme_ExtensionsEntry,
} as SecurityScheme_ExtensionsEntry;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.string();
break;
case 2:
message.value = Value.decode(reader, reader.uint32());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): SecurityScheme_ExtensionsEntry {
const message = {
...baseSecurityScheme_ExtensionsEntry,
} as SecurityScheme_ExtensionsEntry;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = Value.fromJSON(object.value);
} else {
message.value = undefined;
}
return message;
},
toJSON(message: SecurityScheme_ExtensionsEntry): unknown {
const obj: any = {};
message.key !== undefined && (obj.key = message.key);
message.value !== undefined &&
(obj.value = message.value ? Value.toJSON(message.value) : undefined);
return obj;
},
fromPartial(object: DeepPartial<SecurityScheme_ExtensionsEntry>): SecurityScheme_ExtensionsEntry {
const message = {
...baseSecurityScheme_ExtensionsEntry,
} as SecurityScheme_ExtensionsEntry;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = Value.fromPartial(object.value);
} else {
message.value = undefined;
}
return message;
},
};
const baseSecurityRequirement: object = {};
export const SecurityRequirement = {
encode(message: SecurityRequirement, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
Object.entries(message.securityRequirement).forEach(([key, value]) => {
SecurityRequirement_SecurityRequirementEntry.encode(
{ key: key as any, value },
writer.uint32(10).fork(),
).ldelim();
});
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): SecurityRequirement {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseSecurityRequirement } as SecurityRequirement;
message.securityRequirement = {};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
const entry1 = SecurityRequirement_SecurityRequirementEntry.decode(
reader,
reader.uint32(),
);
if (entry1.value !== undefined) {
message.securityRequirement[entry1.key] = entry1.value;
}
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): SecurityRequirement {
const message = { ...baseSecurityRequirement } as SecurityRequirement;
message.securityRequirement = {};
if (object.securityRequirement !== undefined && object.securityRequirement !== null) {
Object.entries(object.securityRequirement).forEach(([key, value]) => {
message.securityRequirement[key] =
SecurityRequirement_SecurityRequirementValue.fromJSON(value);
});
}
return message;
},
toJSON(message: SecurityRequirement): unknown {
const obj: any = {};
obj.securityRequirement = {};
if (message.securityRequirement) {
Object.entries(message.securityRequirement).forEach(([k, v]) => {
obj.securityRequirement[k] = SecurityRequirement_SecurityRequirementValue.toJSON(v);
});
}
return obj;
},
fromPartial(object: DeepPartial<SecurityRequirement>): SecurityRequirement {
const message = { ...baseSecurityRequirement } as SecurityRequirement;
message.securityRequirement = {};
if (object.securityRequirement !== undefined && object.securityRequirement !== null) {
Object.entries(object.securityRequirement).forEach(([key, value]) => {
if (value !== undefined) {
message.securityRequirement[key] =
SecurityRequirement_SecurityRequirementValue.fromPartial(value);
}
});
}
return message;
},
};
const baseSecurityRequirement_SecurityRequirementValue: object = { scope: "" };
export const SecurityRequirement_SecurityRequirementValue = {
encode(
message: SecurityRequirement_SecurityRequirementValue,
writer: _m0.Writer = _m0.Writer.create(),
): _m0.Writer {
for (const v of message.scope) {
writer.uint32(10).string(v!);
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number,
): SecurityRequirement_SecurityRequirementValue {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseSecurityRequirement_SecurityRequirementValue,
} as SecurityRequirement_SecurityRequirementValue;
message.scope = [];
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.scope.push(reader.string());
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): SecurityRequirement_SecurityRequirementValue {
const message = {
...baseSecurityRequirement_SecurityRequirementValue,
} as SecurityRequirement_SecurityRequirementValue;
message.scope = [];
if (object.scope !== undefined && object.scope !== null) {
for (const e of object.scope) {
message.scope.push(String(e));
}
}
return message;
},
toJSON(message: SecurityRequirement_SecurityRequirementValue): unknown {
const obj: any = {};
if (message.scope) {
obj.scope = message.scope.map(e => e);
} else {
obj.scope = [];
}
return obj;
},
fromPartial(
object: DeepPartial<SecurityRequirement_SecurityRequirementValue>,
): SecurityRequirement_SecurityRequirementValue {
const message = {
...baseSecurityRequirement_SecurityRequirementValue,
} as SecurityRequirement_SecurityRequirementValue;
message.scope = [];
if (object.scope !== undefined && object.scope !== null) {
for (const e of object.scope) {
message.scope.push(e);
}
}
return message;
},
};
const baseSecurityRequirement_SecurityRequirementEntry: object = { key: "" };
export const SecurityRequirement_SecurityRequirementEntry = {
encode(
message: SecurityRequirement_SecurityRequirementEntry,
writer: _m0.Writer = _m0.Writer.create(),
): _m0.Writer {
if (message.key !== "") {
writer.uint32(10).string(message.key);
}
if (message.value !== undefined) {
SecurityRequirement_SecurityRequirementValue.encode(
message.value,
writer.uint32(18).fork(),
).ldelim();
}
return writer;
},
decode(
input: _m0.Reader | Uint8Array,
length?: number,
): SecurityRequirement_SecurityRequirementEntry {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = {
...baseSecurityRequirement_SecurityRequirementEntry,
} as SecurityRequirement_SecurityRequirementEntry;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.string();
break;
case 2:
message.value = SecurityRequirement_SecurityRequirementValue.decode(
reader,
reader.uint32(),
);
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): SecurityRequirement_SecurityRequirementEntry {
const message = {
...baseSecurityRequirement_SecurityRequirementEntry,
} as SecurityRequirement_SecurityRequirementEntry;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = SecurityRequirement_SecurityRequirementValue.fromJSON(object.value);
} else {
message.value = undefined;
}
return message;
},
toJSON(message: SecurityRequirement_SecurityRequirementEntry): unknown {
const obj: any = {};
message.key !== undefined && (obj.key = message.key);
message.value !== undefined &&
(obj.value = message.value
? SecurityRequirement_SecurityRequirementValue.toJSON(message.value)
: undefined);
return obj;
},
fromPartial(
object: DeepPartial<SecurityRequirement_SecurityRequirementEntry>,
): SecurityRequirement_SecurityRequirementEntry {
const message = {
...baseSecurityRequirement_SecurityRequirementEntry,
} as SecurityRequirement_SecurityRequirementEntry;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = SecurityRequirement_SecurityRequirementValue.fromPartial(object.value);
} else {
message.value = undefined;
}
return message;
},
};
const baseScopes: object = {};
export const Scopes = {
encode(message: Scopes, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
Object.entries(message.scope).forEach(([key, value]) => {
Scopes_ScopeEntry.encode({ key: key as any, value }, writer.uint32(10).fork()).ldelim();
});
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Scopes {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseScopes } as Scopes;
message.scope = {};
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
const entry1 = Scopes_ScopeEntry.decode(reader, reader.uint32());
if (entry1.value !== undefined) {
message.scope[entry1.key] = entry1.value;
}
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Scopes {
const message = { ...baseScopes } as Scopes;
message.scope = {};
if (object.scope !== undefined && object.scope !== null) {
Object.entries(object.scope).forEach(([key, value]) => {
message.scope[key] = String(value);
});
}
return message;
},
toJSON(message: Scopes): unknown {
const obj: any = {};
obj.scope = {};
if (message.scope) {
Object.entries(message.scope).forEach(([k, v]) => {
obj.scope[k] = v;
});
}
return obj;
},
fromPartial(object: DeepPartial<Scopes>): Scopes {
const message = { ...baseScopes } as Scopes;
message.scope = {};
if (object.scope !== undefined && object.scope !== null) {
Object.entries(object.scope).forEach(([key, value]) => {
if (value !== undefined) {
message.scope[key] = String(value);
}
});
}
return message;
},
};
const baseScopes_ScopeEntry: object = { key: "", value: "" };
export const Scopes_ScopeEntry = {
encode(message: Scopes_ScopeEntry, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.key !== "") {
writer.uint32(10).string(message.key);
}
if (message.value !== "") {
writer.uint32(18).string(message.value);
}
return writer;
},
decode(input: _m0.Reader | Uint8Array, length?: number): Scopes_ScopeEntry {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = { ...baseScopes_ScopeEntry } as Scopes_ScopeEntry;
while (reader.pos < end) {
const tag = reader.uint32();
switch (tag >>> 3) {
case 1:
message.key = reader.string();
break;
case 2:
message.value = reader.string();
break;
default:
reader.skipType(tag & 7);
break;
}
}
return message;
},
fromJSON(object: any): Scopes_ScopeEntry {
const message = { ...baseScopes_ScopeEntry } as Scopes_ScopeEntry;
if (object.key !== undefined && object.key !== null) {
message.key = String(object.key);
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = String(object.value);
} else {
message.value = "";
}
return message;
},
toJSON(message: Scopes_ScopeEntry): unknown {
const obj: any = {};
message.key !== undefined && (obj.key = message.key);
message.value !== undefined && (obj.value = message.value);
return obj;
},
fromPartial(object: DeepPartial<Scopes_ScopeEntry>): Scopes_ScopeEntry {
const message = { ...baseScopes_ScopeEntry } as Scopes_ScopeEntry;
if (object.key !== undefined && object.key !== null) {
message.key = object.key;
} else {
message.key = "";
}
if (object.value !== undefined && object.value !== null) {
message.value = object.value;
} else {
message.value = "";
}
return message;
},
};
declare var self: any | undefined;
declare var window: any | undefined;
declare var global: any | undefined;
var globalThis: any = (() => {
if (typeof globalThis !== "undefined") return globalThis;
if (typeof self !== "undefined") return self;
if (typeof window !== "undefined") return window;
if (typeof global !== "undefined") return global;
throw "Unable to locate global object";
})();
type Builtin = Date | Function | Uint8Array | string | number | boolean | undefined;
export type DeepPartial<T> = T extends Builtin
? T
: T extends Array<infer U>
? Array<DeepPartial<U>>
: T extends ReadonlyArray<infer U>
? ReadonlyArray<DeepPartial<U>>
: T extends {}
? { [K in keyof T]?: DeepPartial<T[K]> }
: Partial<T>;
function longToNumber(long: Long): number {
if (long.gt(Number.MAX_SAFE_INTEGER)) {
throw new globalThis.Error("Value is larger than Number.MAX_SAFE_INTEGER");
}
return long.toNumber();
}
if (_m0.util.Long !== Long) {
_m0.util.Long = Long as any;
_m0.configure();
} | the_stack |
/// <reference types="amap-js-api" />
/// <reference types="amap-js-api-place-search" />
declare namespace AMap {
enum DrivingPolicy {
/**
* 最快捷模式
*/
LEAST_TIME = 0,
/**
* 最经济模式
*/
LEAST_FEE = 1,
/**
* 最短距离模式
*/
LEAST_DISTANCE = 2,
/**
* 考虑实时路况
*/
REAL_TRAFFIC = 4,
// form DragRoute
MULTI_POLICIES = 5,
HIGHWAY = 6,
FEE_HIGHWAY = 7,
FEE_TRAFFIC = 8,
TRAFFIC_HIGHWAY = 9
}
namespace Driving {
interface EventMap {
complete: Event<'complete', SearchResult | { info: string }>;
error: Event<'error', { info: string }>;
}
interface Options {
/**
* 驾车路线规划策略
*/
policy?: DrivingPolicy | undefined;
/**
* 返回信息种类
* 默认值:base,返回基本地址信息
* 当取值为:all,返回DriveStep基本信息+DriveStep详细信息
*/
extensions?: 'base' | 'all' | undefined;
/**
* 默认为0,表示可以使用轮渡,为1的时候表示不可以使用轮渡
*/
ferry?: boolean | undefined;
/**
* AMap.Map对象
* 展现结果的地图实例。当指定此参数后,搜索结果的标注、线路等均会自动添加到此地图上。
*/
map?: Map | undefined;
/**
* 结果列表的HTML容器id或容器元素,提供此参数后,结果列表将在此容器中进行展示。
*/
panel?: string | HTMLElement | undefined;
/**
* 设置隐藏路径规划的起始点图标
*/
hideMarkers?: boolean | undefined;
/**
* 设置是否显示实时路况信息,默认设置为true。
* 显示绿色代表畅通,黄色代表轻微拥堵,红色代表比较拥堵,灰色表示无路况信息。
*/
showTraffic?: boolean | undefined;
/**
* 车牌省份的汉字缩写,用于判断是否限行,与number属性组合使用。
*/
province?: string | undefined;
/**
* 除省份之外车牌的字母和数字,用于判断限行相关,与province属性组合使用。
*/
number?: string | undefined;
/**
* 使用map属性时,绘制的规划线路是否显示描边。缺省为true
*/
isOutline?: boolean | undefined;
/**
* 使用map属性时,绘制的规划线路的描边颜色。缺省为'white'
*/
outlineColor?: string | undefined;
/**
* 于控制在路径规划结束后,是否自动调整地图视野使绘制的路线处于视口的可见范围
*/
autoFitView?: boolean | undefined;
// internal
showDir?: boolean | undefined;
}
interface SearchOptions {
/**
* 途经点
*/
waypoints?: LocationValue[] | undefined;
}
interface SearchPoint {
/**
* 关键词
*/
keyword: string;
/**
* 城市
*/
city?: string | undefined;
}
interface TMCsPath {
path: LngLat[];
status: string;
}
interface DriveStep {
/**
* 此路段起点
*/
start_location: LngLat;
/**
* 此路段终点
*/
end_location: LngLat;
/**
* 此路段说明
*/
instruction: string;
/**
* 本驾车子路段完成后动作
*/
action: string;
/**
* 驾车子路段完成后辅助动作,一般为到达某个目的地时返回
*/
assistant_action: string;
/**
* 驾车方向
*/
orientation: string;
/**
* 道路
*/
road: string;
/**
* 此路段距离,单位:米
*/
distance: number;
/**
* 此段收费,单位:元
*/
tolls: number;
/**
* 收费路段长度,单位:米
*/
toll_distance: number;
/**
* 主要收费道路
*/
toll_road: string;
/**
* 此路段预计使用时间,单位:秒
*/
time: number;
/**
* 此路段坐标集合
*/
path: LngLat[];
/**
* 途径城市列表
*/
cities?: ViaCity[] | undefined;
/**
* 实时交通信息列表
*/
tmcs?: TMC[] | undefined;
tmcsPaths?: TMCsPath[] | undefined;
}
interface District {
/**
* 行政区名称
*/
name: string;
/**
* 行政区编号
*/
adcode: string;
}
interface ViaCity {
/**
* 途径名称
*/
name: string;
/**
* 城市编码
*/
citycode: string;
/**
* 区域编码
*/
adcode: string;
/**
* 途径行政区列表
*/
districts: District[];
}
interface TMC {
/**
* 路况信息对应的编码
* 如果direction是正向 lcode返回值大于0;否则lcode,返回值小于0;
* 如果返回0则说明此路段无lcode
*/
lcode: string | never[];
/**
* 此lcode对应的路段长度,单位: 米
*/
distance: number;
/**
* 路况状态,可能的值有:未知,畅通,缓行,拥堵
*/
status: string;
path: LngLat[];
polyline: string;
}
interface DriveRoute {
/**
* 起点到终点的驾车距离,单位:米
*/
distance: number;
/**
* 时间预计,单位:秒
*/
time: number;
/**
* 驾车规划策略
*/
policy: string;
/**
* 此驾车路线收费金额,单位:元
*/
tolls: number;
/**
* 收费路段长度,单位:米
*/
tolls_distance: number;
/**
* 子路段DriveStep集合
*/
steps: DriveStep[];
/**
* 限行结果
* 0 代表限行已规避或未限行,即该路线没有限行路段
* 1 代表限行无法规避,即该线路有限行路段
*/
restriction: 0 | 1;
}
interface Poi {
location: LngLat;
name: string;
type: 'start' | 'end' | 'waypoint';
}
interface SearchResultCommon {
/**
* 成功状态说明
*/
info: string;
/**
* 驾车规划起点坐标
*/
origin: LngLat;
/**
* 驾车规划终点坐标
*/
destination: LngLat;
/**
* 驾车规划路线列表
*/
routes: DriveRoute[];
/**
* 打车费用,仅extensions为“all”时返回
* 单位:元
*/
taxi_cost?: number | undefined;
}
interface SearchResultBase extends SearchResultCommon {
/**
* 驾车规划起点
*/
start: Poi;
/**
* 驾车规划终点
*/
end: Poi;
/**
* 驾车规划途经点
*/
waypoints: Array<Poi & { isWaypoint: boolean }>;
}
interface SearchResultExt extends SearchResultCommon {
/**
* 驾车规划起点
*/
start: PlaceSearch.PoiExt;
/**
* 驾车规划终点
*/
end: PlaceSearch.PoiExt;
/**
* 驾车规划起点名称
*/
originName: string;
/**
* 驾车规划终点名称
*/
destinationName: string;
/**
* 驾车规划途经点
*/
waypoints: Array<PlaceSearch.PoiExt & { isWaypoint: boolean }>;
}
type SearchResult = SearchResultBase | SearchResultExt;
type SearchStatus = 'error' | 'no_data' | 'complete';
}
class Driving extends EventEmitter {
/**
* 驾车路线规划服务
* @param options 自定义选项
*/
constructor(options?: Driving.Options);
/**
* 以名称关键字查询驾车路线规划
* @param points 途经点数组
* @param callback 查询回调
*/
search(
points: Driving.SearchPoint[],
callback?: (status: Driving.SearchStatus, result: string | Driving.SearchResultExt) => void
): void;
/**
* 根据起点、终点坐标查询驾车路线规划
* @param origin 起点坐标
* @param destination 终点坐标
* @param callback 查询回调
*/
search(
origin: LocationValue,
destination: LocationValue,
callback?: (status: Driving.SearchStatus, result: string | Driving.SearchResultBase) => void
): void;
/**
* 根据起点、终点坐标和途径点查询驾车路线规划
* @param origin 起点坐标
* @param destination 终点坐标
* @param opts 查询选项,用户设定途径点
* @param callback 查询回调
*/
search(
origin: LocationValue,
destination: LocationValue,
opts?: Driving.SearchOptions,
callback?: (status: Driving.SearchStatus, result: string | Driving.SearchResultBase) => void
): void;
/**
* 设置驾车路线规划策略
* @param policy 路线规划策略
*/
setPolicy(policy?: DrivingPolicy): void;
/**
* 设置避让区域,最大支持三个避让区域,避让道路和避让区域不能同时使用
* @param path 避让区域
*/
setAvoidPolygons(path: LocationValue[][]): void;
/**
* 设置避让道路名称,只支持一条避让道路,避让道路和避让区域不能同时使用
* @param road 道路名称
*/
setAvoidRoad(road: string): void;
/**
* 清除避让道路
*/
clearAvoidRoad(): void;
/**
* 清除避让区域
*/
clearAvoidPolygons(): void;
/**
* 获取避让区域
*/
getAvoidPolygons(): LngLat[];
/**
* 获取避让道路
*/
getAvoidRoad(): string | undefined;
/**
* 清除搜索结果
*/
clear(): void;
/**
* 唤起高德地图客户端驾车路径规划
* @param obj 唤起参数
*/
searchOnAMAP(obj: { origin: LocationValue, originName?: string | undefined, destination: LocationValue, destinationName?: string | undefined }): void;
/**
* 设置车牌的汉字首字符和首字后的号码,
* 设置后路线规划的结果将考虑该车牌在当前时间的限行路段
* @param province 省份缩写
* @param number 车牌号码
*/
setProvinceAndNumber(province: string, number: string): void;
// internal
open(): void;
close(): void;
}
} | the_stack |
'use strict';
import { Chart, registerAction } from '@antv/g2/esm';
import * as React from 'react';
import { BaseChartConfig, ChartData, Size, Language, Types } from "./types";
import { getParentSize, requestAnimationFrame, isEqualWith, merge } from './common';
import highchartsDataToG2Data from './dataAdapter';
import chartLog, { warn } from './log';
import eventBus from './eventBus';
import { FullCrossName } from '../constants';
import { ListChecked } from './interaction';
registerAction('list-checked', ListChecked);
// 图表唯一id
let uniqueId = 0;
function generateUniqueId(): string {
return `react-g2-${uniqueId++}`;
}
export const rootClassName = `${FullCrossName} `;
export const rootChildClassName = `${FullCrossName}-children`;
/** 修复旧版 padding 部分 auto 的设置导致图表白屏的问题 */
function fixPadding(padding: Types.ViewPadding | (number | string)[]) {
if (Array.isArray(padding)) {
for (let i = 0; i < padding.length; i++) {
if (padding[i] === 'auto') {
warn('config.padding', '不再支持 auto 和 数值 混用,请使用 config.padding = \'auto\'');
return 'auto';
}
}
}
return padding as Types.ViewPadding;
}
const needFixEventName = {
'plotenter': 'plot:enter',
'plotmove': 'plot:move',
'plotleave': 'plot:leave',
'plotclick': 'plot:click',
'plotdblclick': 'plot:dblclick',
}
/** 修复部分事件名称改变导致在新版不生效的问题 */
function fixEventName(eventName: string): string {
// @ts-ignore
if (needFixEventName[eventName]) {
// @ts-ignore
warn('event', `事件 ${eventName} 名称更改为:${needFixEventName[eventName]}`);
// @ts-ignore
return needFixEventName[eventName];
}
return eventName
}
export interface ChartProps<ChartConfig> {
className?: string;
style?: React.CSSProperties;
width?: Size;
height?: Size;
config?: ChartConfig;
data?: ChartData;
event?: {
[eventKey: string]: () => void;
};
interaction?: {
[actionName: string]: Types.LooseObject
};
language?: Language;
getChartInstance?: (chart: Chart) => void;
enableFunctionUpdate?: boolean;
// G2 顶层属性
padding?: Types.ViewPadding;
localRefresh?: boolean;
renderer?: 'canvas' | 'svg';
syncViewPadding?: boolean;
/** @deprecated 该属性移至 config.animate */
animate?: boolean;
/** @deprecated 自定义图表请使用类继承 */
customChart?: any;
}
/**
* React 图表基类
*
* @template ChartConfig 泛型 - 配置项
* @template Props 泛型 - Props参数
* */
class Base<ChartConfig extends BaseChartConfig, Props extends ChartProps<ChartConfig> = ChartProps<ChartConfig>> extends React.Component<Props> {
static defaultProps? = {};
static isG2Chart = true;
public chartName = 'Base';
public chart: Chart;
public chartDom: HTMLDivElement;
readonly chartId: string;
public defaultConfig: ChartConfig;
protected language: Language;
protected rawData: ChartData;
constructor(props: Props) {
super(props);
this.chart = null;
this.chartDom = null;
this.chartId = generateUniqueId();
this.defaultConfig = ({} as ChartConfig);
this.autoResize = this.autoResize.bind(this);
this.rerender = this.rerender.bind(this);
// 图表初始化时记录日志
chartLog(this.chartName, 'init');
}
// 图表生命周期
/** 是否自动转换数据格式 */
public convertData: boolean = true;
/** 获取图表默认配置项 */
public getDefaultConfig(): ChartConfig {
return ({} as ChartConfig);
}
/** 初始化前对props额外处理 */
public beforeInit?(props: Props): Props;
/** 初始化函数 */
public init(chart: Chart, config: ChartConfig, data: ChartData): void { };
/** 自定义判断配置项是否更改 */
public isChangeEqual?(objValue: any, othValue: any, key: number | string): undefined | boolean;
/** 更新数据 */
public changeData(chart: Chart, config: ChartConfig, data: ChartData): void {
chart && chart.changeData(data);
};
/** 更新尺寸 */
public changeSize(chart: Chart, config: ChartConfig, width: number, height: number): void {
chart && chart.changeSize(width, height);
};
/** @deprecated 图表渲染后回调 */
public afterRender?(config: ChartConfig): void;
/** 销毁图表 */
public destroy?(): void;
// 基类自己的生命周期
componentDidMount() {
this.language = this.props.language || 'zh-cn';
// 设置初始高宽
this.initSize();
this.initChart();
eventBus.on('setTheme', this.rerender);
}
protected isReRendering = false;
// private reRenderTimer: any = null;
rerender() {
// 修复 变化过快时 chart.destroy 方法无法清除dom,导致dom重复的问题。
if (this.isReRendering) {
// window.cancelAnimationFrame(this.reRenderTimer);
}
this.isReRendering = true;
this.handleDestroy();
// this.reRenderTimer = requestAnimationFrame(() => {
if (!this.chartDom) {
return;
}
this.initSize();
this.initChart();
this.isReRendering = false;
// });
}
isEqualCustomizer = (objValue: any, othValue: any, key: number | string): undefined | boolean => {
const res = this.isChangeEqual ? this.isChangeEqual(objValue, othValue, key) : undefined;
if (res !== undefined) {
return res;
}
const enableFunctionUpdate = this.props.enableFunctionUpdate;
// 默认忽略全部function,开启 enableFunctionUpdate 可以接受function更新
if (!enableFunctionUpdate && typeof objValue === 'function' && typeof othValue === 'function') {
return true;
}
// 其余情况使用lodash的默认判断
return undefined;
};
checkConfigChange(newConfig: ChartConfig, oldConfig: ChartConfig): boolean {
let hasConfigChange = false;
if (!isEqualWith(newConfig, oldConfig, this.isEqualCustomizer)) {
hasConfigChange = true;
}
return hasConfigChange;
}
componentDidUpdate(prevProps: Props) {
const {
data: newData,
width: newWidth,
height: newHeight,
config: newConfig,
event: newEvent,
interaction: newInteraction,
// changeConfig = true,
} = this.props;
const {
data: oldData,
width: oldWidth,
height: oldHeight,
config: oldConfig,
event: oldEvent,
interaction: oldInteraction,
} = prevProps;
this.language = this.props.language || 'zh-cn';
// 配置项有变化,重新生成图表
// if (changeConfig !== false) {
if (this.checkConfigChange(newConfig, oldConfig)) {
this.rerender();
return;
}
// }
// 更新事件
if (newEvent !== oldEvent) {
// 清除旧事件
Object.keys(oldEvent).forEach(eventKey => {
this.chart.off(fixEventName(eventKey), oldEvent[eventKey]);
});
// 绑定新事件
Object.keys(newEvent).forEach(eventKey => {
this.chart.on(fixEventName(eventKey), newEvent[eventKey]);
});
}
if (newInteraction !== oldInteraction) {
// 清除旧交互
Object.keys(oldInteraction).forEach(interactionName => {
this.chart.removeInteraction(interactionName);
});
// 绑定新交互
Object.keys(newInteraction).forEach(interactionName => {
this.chart.interaction(interactionName, newInteraction[interactionName]);
});
}
let needAfterRender = false;
// 数据有变化
if (
newData !== oldData ||
(Array.isArray(newData) &&
Array.isArray(oldData) &&
newData.length !== oldData.length)
) {
const mergeConfig = merge({}, this.defaultConfig, newConfig)
const data =
this.convertData &&
mergeConfig.dataType !== 'g2'
? highchartsDataToG2Data(newData, mergeConfig)
: newData;
this.rawData = newData;
this.changeData(
this.chart,
mergeConfig,
data
);
// if (this.chartProcess.changeData) {
// this.chart &&
// this.chartProcess.changeData.call(
// this,
// this.chart,
// newConfig,
// data
// );
// } else {
// this.chart && this.chart.changeData(data);
// }
needAfterRender = true;
}
// 传入的长宽有变化
if (newWidth !== oldWidth || newHeight !== oldHeight) {
this.handleChangeSize(newConfig, newWidth, newHeight);
needAfterRender = true;
}
if (needAfterRender) {
this.handleAfterRender(newConfig);
}
}
// 渲染控制,仅 class、style、children 变化会触发渲染
// shouldComponentUpdate(nextProps) {
// const { className: newClass, style: newStyle, children: newChild } = nextProps;
// const { className: oldClass, style: oldStyle, children: oldChild } = this.props;
// return newClass !== oldClass || newStyle !== oldStyle || newChild !== oldChild;
// }
// 准备销毁
unmountCallbacks: ((chart: Chart) => void)[] = [];
handleDestroy() {
// 清空缩放相关变量和事件
this.resizeRunning = false;
window.cancelAnimationFrame(this.resizeTimer);
window.removeEventListener('resize', this.autoResize);
// 清除配置变化重新生成图表的定时器
// window.cancelAnimationFrame(this.reRenderTimer);
// 清除afterRender的定时器
clearTimeout(this.afterRenderTimer);
if (this.destroy) {
this.chart && this.destroy();
}
if (this.unmountCallbacks.length > 0) {
this.unmountCallbacks.forEach(cb => {
cb && cb.call(this, this.chart);
});
}
this.chart && this.chart.destroy && this.chart.destroy();
this.chart = null;
// this.chartDom = null;
// this.chartId = null;
if (typeof this.props.getChartInstance === 'function') {
this.props.getChartInstance(null);
}
this.afterRenderCallbacks = [];
this.unmountCallbacks = [];
}
componentWillUnmount() {
this.handleDestroy();
eventBus.off('setTheme', this.rerender);
}
initChart() {
this.defaultConfig = this.getDefaultConfig();
// 合并默认配置项
let currentProps: Props = {
...this.props,
config: merge({}, this.defaultConfig, this.props.config),
};
// 开始初始化图表
if (this.beforeInit) {
currentProps = this.beforeInit(currentProps);
}
currentProps.config.padding = fixPadding(currentProps.padding || currentProps.config.padding);
const {
width,
height,
data: initData,
padding,
// forceFit,
config,
event,
interaction,
animate,
...otherProps
} = currentProps;
// 生成图表实例
const chart = new Chart({
container: this.chartDom,
width: this.size[0],
height: this.size[1] || 200,
padding: config.padding,
// forceFit: forceFit || false,
// auto-padding 时自带的内边距
// autoPaddingAppend: 3,
...otherProps,
});
// 预处理数据
const data =
this.convertData &&
config.dataType !== 'g2'
? highchartsDataToG2Data(initData, config)
: initData;
this.rawData = initData;
if (animate !== undefined) {
warn('animate', '请使用 config.animate 设置动画开关。');
// 将 props.animate 传入 config.animate
if (config.animate === undefined) {
config.animate = animate;
}
}
// 绘制逻辑
chart && this.init(chart, config, data);
// 全局动画设置
if (typeof config.animate === 'boolean') {
chart.animate(config.animate);
}
// 开始渲染
chart.render();
// 绑定事件,这里透传了G2的所有事件,暂时不做额外封装
if (chart && event) {
Object.keys(event).forEach(eventKey => {
chart.on(fixEventName(eventKey), event[eventKey]);
});
}
// 绑定交互
if (chart && interaction) {
Object.keys(interaction).forEach(interactionName => {
chart.interaction(interactionName, interaction[interactionName]);
});
}
this.chart = chart;
if (typeof currentProps.getChartInstance === 'function') {
currentProps.getChartInstance(chart);
}
this.handleAfterRender(config);
}
public size: number[] = [0, 0];
// 初始化时适配高宽
initSize() {
const { width, height } = this.props;
const parentSize = getParentSize(this.chartDom, width, height);
this.setSize(parentSize);
window.addEventListener('resize', this.autoResize);
}
handleChangeSize(config: ChartConfig, w: Size = this.size[0], h: Size = this.size[1]) {
this.setSize([w, h]);
// 强制转换为数字
this.changeSize(this.chart, config, Number(w), Number(h));
// if (this.chartProcess.changeSize) {
// this.chart &&
// this.chartProcess.changeSize.call(this, this.chart, config, w, h);
// } else {
// this.chart && this.chart.changeSize(w, h);
// }
}
// 动态适配高宽,利用 resizeRunning 做节流
private resizeRunning = false;
private resizeTimer: any = null;
autoResize() {
if (this.resizeRunning) {
// this.resizeRunning = false;
// window.cancelAnimationFrame(this.resizeTimer);
return;
}
const { chartDom: element, props, size } = this;
this.resizeRunning = true;
this.resizeTimer = requestAnimationFrame(() => {
this.resizeRunning = false;
const parentSize = getParentSize(element, props.width, props.height);
// 读取的高宽需要是有效值,0 也不可以
if (
!(parentSize[0] === size[0] && parentSize[1] === size[1]) &&
parentSize[0] &&
parentSize[1]
) {
this.handleChangeSize(props.config, parentSize[0], parentSize[1]);
this.handleAfterRender();
}
});
}
// 设置高宽
setSize([w, h]: Size[]) {
const element = this.chartDom;
this.size = [Number(w), Number(h)];
if (w) {
element.style.width = `${w}px`;
}
if (h) {
element.style.height = `${h}px`;
}
}
protected afterRenderCallbacks: ((chart: Chart, config: ChartConfig) => void)[] = [];
protected afterRenderTimer: any = null;
handleAfterRender(config?: ChartConfig) {
if (this.afterRender || this.afterRenderCallbacks.length > 0) {
this.afterRenderTimer = setTimeout(() => {
if (this.chart && this.afterRender) {
this.afterRender(config || this.props.config);
}
if (this.afterRenderCallbacks.length > 0) {
this.afterRenderCallbacks.forEach(cb => {
cb && cb.call(this, this.chart, config || this.props.config);
});
}
}, 50);
}
}
render() {
const {
className = '',
style,
children,
data,
width,
height,
padding,
config,
event,
interaction,
animate,
language,
localRefresh,
renderer,
syncViewPadding,
customChart,
getChartInstance,
enableFunctionUpdate,
...otherProps
} = this.props;
return (
<div
ref={dom => (this.chartDom = dom)}
id={this.chartId}
key={this.chartId}
className={`${rootClassName + this.chartName} ${className}`}
style={style}
{...otherProps}>
{children ? (
<div className={rootChildClassName}>{children}</div>
) : null}
</div>
);
}
}
// Base.baseClassName = rootClassName + name;
export default Base;
export interface BaseClass<ChartConfig, Props = {}> {
new (props: Props): Base<ChartConfig, Props>;
isG2Chart: boolean;
displayName?: string;
defaultProps?: Partial<Props>;
} | the_stack |
import React, { useState, useEffect, Fragment, useRef } from "react";
import EasybaseContext from "./EasybaseContext";
import deepEqual from "fast-deep-equal";
import {
EasybaseProviderProps,
ContextValue,
UseReturnValue,
POST_TYPES,
FrameConfiguration,
FileFromURI,
AddRecordOptions,
UpdateRecordAttachmentOptions,
StatusResponse,
ConfigureFrameOptions,
DeleteRecordOptions,
DB_STATUS,
EXECUTE_COUNT
} from "./types/types";
import imageExtensions from "./assets/image-extensions.json";
import videoExtensions from "./assets/video-extensions.json";
import utilsFactory from "../node_modules/easybasejs/src/EasybaseProvider/utils";
import tableFactory from "../node_modules/easybasejs/src/EasybaseProvider/table";
import authFactory from "../node_modules/easybasejs/src/EasybaseProvider/auth";
import dbFactory from "../node_modules/easybasejs/src/EasybaseProvider/db";
import { gFactory } from "../node_modules/easybasejs/src/EasybaseProvider/g";
import { Observable } from "object-observer";
import { SQW } from "easyqb/types/sq";
import fetch from 'cross-fetch';
const cache = require("./cache");
let _isFrameInitialized: boolean = true;
let _frameConfiguration: FrameConfiguration = {
offset: 0,
limit: 0
};
let _effect: React.EffectCallback = () => () => { };
let _signInCallback: () => void;
const _observedChangeStack: Record<string, any>[] = [];
let _recordIdMap: WeakMap<Record<string, any>, "string"> = new WeakMap();
let _proxyRecordMap: WeakMap<Record<string, any>, "string"> = new WeakMap();
const EasybaseProvider = ({ children, ebconfig, options }: EasybaseProviderProps) => {
if (typeof ebconfig !== 'object' || ebconfig === null || ebconfig === undefined) {
console.error("No ebconfig object passed. do `import ebconfig from \"./ebconfig.js\"` and pass it to the Easybase provider");
return (
<Fragment>
{children}
</Fragment>
);
} else if (!ebconfig.integration) {
console.error("Invalid ebconfig object passed. Download ebconfig.json from Easybase.io and try again.");
return (
<Fragment>
{children}
</Fragment>
);
}
const [mounted, setMounted] = useState<boolean>(false);
const [isSyncing, setIsSyncing] = useState<boolean>(false);
const [userSignedIn, setUserSignedIn] = useState<boolean>(false);
const [_frame, _setFrame] = useState<Record<string, any>[]>([]);
const [_observableFrame, _setObservableFrame] = useState<any>({
observe: () => { },
unobserve: () => { }
});
const _ranSignInCallback = useRef<boolean>(false);
// TODO: useRef vs useState({})
const g = useRef(gFactory({ ebconfig, options })).current;
const {
initAuth,
tokenPost,
tokenPostAttachment,
signUp,
setUserAttribute,
getUserAttributes,
resetUserPassword,
signIn,
signOut,
forgotPassword,
forgotPasswordConfirm,
userID
} = useRef(authFactory(g)).current;
const { log } = useRef(utilsFactory(g)).current;
const {
Query,
fullTableSize,
tableTypes
} = useRef(tableFactory(g)).current;
const {
db,
dbEventListener,
e,
setFile,
setImage,
setVideo
} = useRef(dbFactory(g)).current;
useEffect(() => {
const mount = async () => {
// eslint-disable-next-line dot-notation
const isIE = typeof document !== 'undefined' && !!document['documentMode'];
if (isIE) {
console.error("EASYBASE — easybase-react does not support Internet Explorer. Please use a different browser.");
}
g.instance = (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') ? "React Native" : "React";
if (options?.googleAnalyticsId) {
if (options.googleAnalyticsId.startsWith("G-")) {
if (g.instance === "React") {
const { GA4React } = await import('ga-4-react');
const ga4ReactLoader = new GA4React(options.googleAnalyticsId);
try {
const ga4React = await ga4ReactLoader.initialize();
g.analyticsEvent = (eventTitle: string, params?: Record<string, any>) => ga4React.gtag('event', eventTitle, params);
g.analyticsIdentify = (hashedUserId: string) => ga4React.gtag('config', options.googleAnalyticsId, { user_id: hashedUserId });
g.analyticsEnabled = true;
if (window.location.hash) {
// Using hash router - https://github.com/unrealmanu/ga-4-react/issues/15
window.onhashchange = () => {
ga4React.pageview(window.location.hash);
};
}
} catch (error) {
log("Analytics initialization error: ", error)
}
} else if (g.instance === "React Native") {
if (options.googleAnalyticsSecret) {
const genUUID = () => {
// https://www.w3resource.com/javascript-exercises/javascript-math-exercise-23.php
let dt = new Date().getTime();
const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = (dt + Math.random() * 16) % 16 | 0;
dt = Math.floor(dt / 16);
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
}
let _userIdHash: string;
const _mockDeviceId = genUUID();
// Mocking a 'pageview'
fetch(`https://www.google-analytics.com/mp/collect?measurement_id=${options.googleAnalyticsId}&api_secret=${options.googleAnalyticsSecret}`, {
method: "POST",
body: JSON.stringify({
client_id: _mockDeviceId,
events: [{ name: 'select_content' }]
})
});
g.analyticsEvent = (eventTitle: string, params?: Record<string, any>) => fetch(`https://www.google-analytics.com/mp/collect?measurement_id=${options.googleAnalyticsId}&api_secret=${options.googleAnalyticsSecret}`, {
method: "POST",
body: JSON.stringify({
client_id: _mockDeviceId,
user_id: _userIdHash,
events: [{
name: eventTitle,
params
}]
})
});
g.analyticsIdentify = (hashedUserId: string) => { _userIdHash = hashedUserId };
g.analyticsEnabled = true;
} else {
console.error("EASYBASE — React Native analytics requires the presence of 'googleAnalyticsSecret'. To create a new secret, navigate in the Google Analytics UI to: Admin > Data Streams > choose your stream > Measurement Protocol > Create");
}
}
} else if (options.googleAnalyticsId.startsWith("UA-")) {
console.error("EASYBASE — Detected Universal Analytics tag in googleAnalyticsId parameter. This version is not supported – please update to Google Analytics 4.\nhttps://support.google.com/analytics/answer/9744165?hl=en");
} else {
console.error("EASYBASE — Unknown googleAnalyticsId version parameter. Please use Google Analytics 4.\nhttps://support.google.com/analytics/answer/9744165?hl=en");
}
}
if (g.ebconfig.tt && g.ebconfig.integration.split("-")[0].toUpperCase() !== "PROJECT") {
const t1 = Date.now();
log("mounting...");
await initAuth();
const res = await tokenPost(POST_TYPES.VALID_TOKEN);
const elapsed = Date.now() - t1;
if (res.success) {
log("Valid auth initiation in " + elapsed + "ms");
setMounted(true);
}
} else {
g.mounted = true; // Bypass initAuth()
const cookieName = g.ebconfig.integration.slice(-10);
const {
cacheToken,
cacheRefreshToken,
cacheSession
} = await cache.getCacheTokens(cookieName);
if (cacheRefreshToken) {
g.token = cacheToken;
g.refreshToken = cacheRefreshToken;
g.session = +cacheSession;
const fallbackMount = setTimeout(() => { setMounted(true) }, 2500);
const [refreshTokenRes, { hash }, { fromUtf8 }] = await Promise.all([
tokenPost(POST_TYPES.REQUEST_TOKEN, {
refreshToken: g.refreshToken,
token: g.token,
getUserID: true
}),
import('fast-sha256'),
import('@aws-sdk/util-utf8-browser')
])
if (refreshTokenRes.success) {
clearTimeout(fallbackMount);
g.token = refreshTokenRes.data.token;
g.userID = refreshTokenRes.data.userID;
if (g.analyticsEnabled && g.analyticsEventsToTrack.login) {
const hashOut = hash(fromUtf8(g.GA_USER_ID_SALT + refreshTokenRes.data.userID));
const hexHash = Array.prototype.map.call(hashOut, x => ('00' + x.toString(16)).slice(-2)).join('');
g.analyticsIdentify(hexHash);
g.analyticsEvent('login', { method: "Easybase" });
}
await cache.setCacheTokens(g, cookieName);
setUserSignedIn(true);
} else {
cache.clearCacheTokens(cookieName);
}
}
setMounted(true);
}
}
mount();
}, []);
const useFrameEffect = (effect: React.EffectCallback) => {
_effect = effect;
};
useEffect(() => {
if (userSignedIn === true && _ranSignInCallback.current === false && _signInCallback !== undefined) {
_signInCallback();
_ranSignInCallback.current = true;
}
}, [userSignedIn])
const onSignIn = (callback: () => void) => {
_signInCallback = callback;
if (userSignedIn === true && _ranSignInCallback.current === false && _signInCallback !== undefined) {
_signInCallback();
_ranSignInCallback.current = true;
}
}
useEffect(() => {
_observableFrame.observe((allChanges: any[]) => {
allChanges.forEach((change: any) => {
_observedChangeStack.push({
type: change.type,
path: change.path,
value: change.value,
_id: _recordIdMap.get(_frame[Number(change.path[0])])
// Not bringing change.object or change.oldValue
});
log(JSON.stringify({
type: change.type,
path: change.path,
value: change.value,
_id: _recordIdMap.get(_frame[Number(change.path[0])])
// Not bringing change.object or change.oldValue
}))
});
});
_proxyRecordMap = new WeakMap();
_frame.forEach((_: any, i: number) => _proxyRecordMap.set(_observableFrame[i], "" + i as any))
_effect(); // call useFrameEffect
}, [_observableFrame]);
useEffect(() => {
_observableFrame.unobserve();
_setObservableFrame(Observable.from(_frame));
}, [_frame]);
function Frame(): Record<string, any>[];
function Frame(index: number): Record<string, any>;
function Frame(index?: number): Record<string, any>[] | Record<string, any> {
if (typeof index === "number") {
return _observableFrame[index];
} else {
return _observableFrame;
}
}
const _recordIDExists = (record: Record<string, any>): Boolean => !!_recordIdMap.get(record) || !!_recordIdMap.get(_getRawRecordFromProxy(record) || {});
const _getRawRecordFromProxy = (proxyRecord: Record<string, any>): Record<string, any> | undefined => _proxyRecordMap.get(proxyRecord) ? _frame[+_proxyRecordMap.get(proxyRecord)!] : undefined
const configureFrame = (options: ConfigureFrameOptions): StatusResponse => {
_frameConfiguration = { ..._frameConfiguration };
if (options.limit !== undefined) _frameConfiguration.limit = options.limit;
if (options.offset !== undefined && options.offset >= 0) _frameConfiguration.offset = options.offset;
if (options.tableName !== undefined) _frameConfiguration.tableName = options.tableName;
_isFrameInitialized = false;
return {
message: "Successfully configured frame. Run sync() for changes to be shown in frame",
success: true
}
}
const currentConfiguration = (): FrameConfiguration => ({ ..._frameConfiguration });
const addRecord = async (options: AddRecordOptions): Promise<StatusResponse> => {
const defaultValues: AddRecordOptions = {
insertAtEnd: false,
newRecord: {},
tableName: undefined
}
const fullOptions: AddRecordOptions = { ...defaultValues, ...options };
try {
const res = await tokenPost(POST_TYPES.SYNC_INSERT, fullOptions);
return {
message: res.data,
success: res.success
}
} catch (err: any) {
console.error("Easybase Error: addRecord failed ", err);
return {
message: "Easybase Error: addRecord failed " + err,
success: false,
errorCode: err
}
}
}
const deleteRecord = async (options: DeleteRecordOptions): Promise<StatusResponse> => {
const _frameRecord = _getRawRecordFromProxy(options.record) || _frame.find(ele => deepEqual(ele, options.record));
if (_frameRecord && _recordIdMap.get(_frameRecord)) {
const res = await tokenPost(POST_TYPES.SYNC_DELETE, {
_id: _recordIdMap.get(_frameRecord),
tableName: options.tableName
});
return {
success: res.success,
message: res.data
}
} else {
try {
const res = await tokenPost(POST_TYPES.SYNC_DELETE, {
record: options.record,
tableName: options.tableName
});
return {
success: res.success,
message: res.data
}
} catch (error: any) {
console.error("Easybase Error: deleteRecord failed ", error);
return {
success: false,
message: "Easybase Error: deleteRecord failed " + error,
errorCode: error.errorCode || undefined
}
}
}
}
// Only allow the deletion of one element at a time
// First handle shifting of the array size. Then iterate
const sync = async (): Promise<StatusResponse> => {
const _realignFrames = (newData: Record<string, any>[]) => {
let isNewDataTheSame = true;
if (newData.length !== _frame.length) {
isNewDataTheSame = false;
} else {
for (let i = 0; i < newData.length; i++) {
const newDataNoId = { ...newData[i] };
delete newDataNoId._id;
if (!deepEqual(newDataNoId, _frame[i])) {
isNewDataTheSame = false;
break;
}
}
}
if (!isNewDataTheSame) {
_recordIdMap = new WeakMap();
_frame.length = newData.length;
newData.forEach((currNewEle, i) => {
_frame[i] = currNewEle;
_recordIdMap.set(currNewEle, currNewEle._id);
delete currNewEle._id;
});
_setFrame([..._frame]);
}
}
if (isSyncing) {
return {
success: false,
message: "Easybase Error: the provider is currently syncing, use 'await sync()' before calling sync() again"
};
}
setIsSyncing(true);
if (_isFrameInitialized) {
if (_observedChangeStack.length > 0) {
log("Stack change: ", _observedChangeStack);
const res = await tokenPost(POST_TYPES.SYNC_STACK, {
stack: _observedChangeStack,
..._frameConfiguration
});
if (res.success) {
_observedChangeStack.length = 0;
}
}
}
try {
const res = await tokenPost(POST_TYPES.GET_FRAME, _frameConfiguration);
// Check if the array received from db is the same as frame
// If not, update it and send useFrameEffect
if (res.success === false) {
console.error(res.data);
setIsSyncing(false);
return {
success: false,
message: "" + res.data
}
} else {
_isFrameInitialized = true;
_realignFrames(res.data);
setIsSyncing(false);
return {
message: 'Success. Call frame for data',
success: true
}
}
} catch (error: any) {
console.error("Easybase Error: get failed ", error);
setIsSyncing(false);
return {
success: false,
message: "Easybase Error: get failed " + error,
errorCode: error.errorCode || undefined
}
}
}
const updateRecordImage = async (options: UpdateRecordAttachmentOptions): Promise<StatusResponse> => {
const res = await _updateRecordAttachment(options, "image");
return res;
}
const updateRecordVideo = async (options: UpdateRecordAttachmentOptions): Promise<StatusResponse> => {
const res = await _updateRecordAttachment(options, "video");
return res;
}
const updateRecordFile = async (options: UpdateRecordAttachmentOptions): Promise<StatusResponse> => {
const res = await _updateRecordAttachment(options, "file");
return res;
}
const _updateRecordAttachment = async (options: UpdateRecordAttachmentOptions, type: string): Promise<StatusResponse> => {
const _frameRecord: Record<string, any> | undefined = _getRawRecordFromProxy(options.record) || _frame.find(ele => deepEqual(ele, options.record));
if (_frameRecord === undefined || !_recordIDExists(_frameRecord)) {
log("Attempting to add attachment to a new record that has not been synced. Please sync() before trying to add attachment.");
return {
success: false,
message: "Attempting to add attachment to a new record that has not been synced. Please sync() before trying to add attachment."
}
}
const ext: string = options.attachment.name.split(".").pop()!.toLowerCase();
log(ext);
if (type === "image" && !imageExtensions.includes(ext)) {
return {
success: false,
message: "Image files must have a proper image extension in the file name"
};
}
if (type === "video" && !videoExtensions.includes(ext)) {
return {
success: false,
message: "Video files must have a proper video extension in the file name"
};
}
function isFileFromURI(f: File | FileFromURI): f is FileFromURI {
return (f as FileFromURI).uri !== undefined;
}
const formData = new FormData();
if (isFileFromURI(options.attachment)) {
formData.append("file", options.attachment as any);
formData.append("name", options.attachment.name);
} else {
formData.append("file", options.attachment);
formData.append("name", options.attachment.name);
}
const customHeaders = {
'Eb-upload-type': type,
'Eb-column-name': options.columnName,
'Eb-record-id': _recordIdMap.get(_frameRecord),
'Eb-table-name': options.tableName
}
const res = await tokenPostAttachment(formData, customHeaders);
await sync();
return {
message: res.data,
success: res.success
};
}
const isUserSignedIn = (): boolean => userSignedIn;
g.newTokenCallback = () => {
const cookieName = g.ebconfig.integration.slice(-10);
if (!g.token) {
// User signed out
cache.clearCacheTokens(cookieName).then((_: any) => {
setUserSignedIn(false);
_ranSignInCallback.current = false;
});
} else {
// User signed in or refreshed token
cache.setCacheTokens(g, cookieName).then((_: any) => {
setUserSignedIn(true);
});
}
}
const useReturn = <T, >(dbInstance: () => SQW, deps?: React.DependencyList): UseReturnValue<T> => {
// eslint-disable-next-line no-extra-parens
const [unsubscribe, setUnsubscribe] = useState<() => void>(() => () => { });
const [frame, setFrame] = useState<T[]>([]);
const [error, setError] = useState<any>(null);
const [loading, setLoading] = useState<boolean>(false);
const [dead, setDead] = useState<boolean>(false);
const doFetch = async (): Promise<void> => {
setLoading(true);
try {
const res = await dbInstance().all();
if (Array.isArray(res)) {
setFrame(res as T[]);
}
} catch (error) {
setError(error);
}
setLoading(false);
}
useEffect(() => {
let isAlive = true;
if (!dead) {
const _instanceTableName: string = (dbInstance() as any)._tableName;
(unsubscribe as any)("true");
const _listener = dbEventListener((status?: DB_STATUS, queryType?: string, executeCount?: EXECUTE_COUNT, tableName?: string | null, returned?: any) => {
if (!isAlive) {
return;
}
log(_instanceTableName, status, queryType, executeCount, tableName)
if ((tableName === null && _instanceTableName === "untable") || tableName === _instanceTableName) {
if (status === DB_STATUS.SUCCESS && queryType !== "select") {
if (typeof returned === "number" && returned > 0) {
doFetch();
} else if (Array.isArray(returned) && typeof returned[0] === "number" && returned[0] > 0) {
doFetch();
}
}
}
});
setUnsubscribe(() => (stayAlive?: string) => {
_listener();
stayAlive !== "true" && setDead(true);
});
doFetch();
}
return () => { isAlive = false; }
}, deps || []);
return {
frame,
unsubscribe,
error,
manualFetch: doFetch,
loading
};
};
const c: ContextValue = {
configureFrame,
addRecord,
deleteRecord,
sync,
updateRecordImage,
updateRecordVideo,
updateRecordFile,
Frame,
useFrameEffect,
fullTableSize,
tableTypes,
currentConfiguration,
Query,
signIn,
signOut,
isUserSignedIn,
signUp,
setUserAttribute,
getUserAttributes,
resetUserPassword,
onSignIn,
db,
dbEventListener,
e,
setFile,
setImage,
setVideo,
useReturn,
forgotPassword,
forgotPasswordConfirm,
userID
}
return (
<EasybaseContext.Provider value={c}>
{mounted && children}
</EasybaseContext.Provider>
)
}
export default EasybaseProvider; | the_stack |
import api from "@/api";
import stream from "@/api";
import { hiveWithAllTable } from "@/components/helpDoc/docs";
import { DATA_SOURCE_ENUM, DATA_SOURCE_TEXT, formItemLayout, PARTITION_TYPE, SYNC_TYPE, WRITE_TABLE_TYPE } from "@/constant";
import { getFlinkDisabledSource } from "@/utils/enums";
import { isKafka, isMysqlTypeSource, isHive } from '@/utils/is';
import molecule from "@dtinsight/molecule";
import { connect as moleculeConnect } from '@dtinsight/molecule/esm/react';
import { Button, Form, FormInstance, Radio, Select } from "antd";
import { ExclamationCircleOutlined } from '@ant-design/icons'
import React from "react";
import { streamTaskActions } from "../taskFunc";
import Kafka from "./component/kafka";
import Hdfs from "./component/hdfs";
import Hive from "./component/hive";
import Emq from "./component/emq";
import { targetDefaultValue } from "../helper";
import Adb from "./component/adb";
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
// eslint-disable-next-line
const prefixRule = '${schema}_${table}';
function getSourceInitialField(sourceType: any, data: any) {
const initialFields: any = { type: sourceType };
const { sourceMap = {} } = data;
const isMysqlSource = isMysqlTypeSource(sourceMap.type);
switch (sourceType) {
case DATA_SOURCE_ENUM.HDFS: {
initialFields.fileType = 'orc';
initialFields.fieldDelimiter = ',';
initialFields.encoding = 'utf-8';
initialFields.writeMode = 'APPEND';
return initialFields;
}
case DATA_SOURCE_ENUM.HIVE: {
// eslint-disable-next-line
initialFields.partitionType = PARTITION_TYPE.DAY;
initialFields.analyticalRules = isMysqlSource ? prefixRule : undefined;
initialFields.partition = isMysqlSource ? 'pt' : undefined; // 后端(nanqi)要求自动建表默认加一个partition = pt。
initialFields.writeTableType = isMysqlSource ? WRITE_TABLE_TYPE.AUTO : WRITE_TABLE_TYPE.HAND;
initialFields.maxFileSize = `${10 * 1024 * 1024}`;
initialFields.writeMode = 'insert';
return initialFields;
}
case DATA_SOURCE_ENUM.KAFKA:
case DATA_SOURCE_ENUM.KAFKA_2X:
case DATA_SOURCE_ENUM.TBDS_KAFKA:
case DATA_SOURCE_ENUM.KAFKA_HUAWEI: {
initialFields.dataSequence = false;
initialFields.partitionKey = undefined;
return initialFields;
}
case DATA_SOURCE_ENUM.ADB_FOR_PG: {
initialFields.writeMode = 'APPEND';
initialFields.mappingType = 1;
return initialFields;
}
}
return initialFields;
}
// 是否可以填选 partition key
function canPartitionKeyWrite(sourceMap: any) {
return [DATA_SOURCE_ENUM.MYSQL, DATA_SOURCE_ENUM.UPDRDB, DATA_SOURCE_ENUM.ORACLE].includes(sourceMap.type) && sourceMap.rdbmsDaType === SYNC_TYPE.INTERVAL;
}
class CollectionTarget extends React.Component<any, any> {
formRef = React.createRef<FormInstance>()
constructor(props: any) {
super(props);
this.state = {
tableList: [],
partitions: [],
loading: false,
sourceId: null,
schemaList: [],
adbTableList: []
}
}
componentDidMount() {
const { collectionData } = this.props;
const { targetMap = {}, sourceMap = {} } = collectionData;
const { sourceId, type, table } = targetMap;
const { type: dataSourceType, rdbmsDaType, transferType } = sourceMap;
console.log(sourceId)
if (sourceId) {
this.onSourceIdChange(type, sourceId, transferType);
if (isHive(type) && table) {
this.onHiveTableChange(sourceId, table);
}
}
if (!targetMap.tableMappingList && table?.length) {
const tableMappingList = table.map((item: string) => {
return {
source: item,
sink: null
}
})
const fields = {
...targetMap,
tableMappingList
}
streamTaskActions.updateTargetMap(fields, false, true);
}
}
getSchemaList = async (sourceId: any, schema?: string) => {
const res = await api.getAllSchemas({ sourceId, isSys: false, schema });
if (res?.code === 1) {
this.setState({
schemaList: res.data
})
}
}
getTableList = (sourceId: number, searchKey?: string) => {
api.getOfflineTableList({
sourceId,
isSys: false,
name: searchKey,
}).then((res: any) => {
if (res.code === 1) {
this.setState({
tableList: res.data || []
});
}
});
}
/**
* @param syncSchema - props 里的 schema 可能是老的,react 还没异步更新,用 syncSchema 传个最新的值
*/
getSchemaTableList = (searchKey?: string, syncSchema?: string) => {
const { collectionData } = this.props;
const { targetMap = {} } = collectionData;
const { sourceId, schema } = targetMap;
stream.listTablesBySchema({
sourceId,
searchKey,
schema: syncSchema || schema
}).then((res: any) => {
if (res.code === 1) {
this.setState({
adbTableList: res.data || []
});
}
});
}
/**
* 数据源改变
* @param type
* @param sourceId
* @param transferType
*/
onSourceIdChange(type: any, sourceId: any, transferType?: any) {
this.setState({
tableList: [],
partitions: [],
sourceId,
schemaList: [],
adbTableList: []
})
if (isHive(type)) {
this.getTableList(sourceId);
} else if (type === DATA_SOURCE_ENUM.ADB_FOR_PG) {
this.getSchemaList(sourceId);
transferType === 1 && this.getSchemaTableList()
}
}
/**
* hive表改变
* @param sourceId 数据源ID
* @param tableName 表名
* @returns
*/
async onHiveTableChange(sourceId: any, tableName: any) {
this.setState({
partition: [],
partitions: []
})
if (!sourceId || !tableName) {
return;
}
this.setState({
loading: true
})
let res = await api.getHivePartitions({
sourceId,
tableName
});
this.setState({
loading: false
})
if (res && res.code == 1) {
const partitions = res.data;
if (partitions && partitions.length) {
this.setState({
partitions: res.data
});
}
}
}
onSelectSource = (value: any, option: any) => {
if (!value) {
streamTaskActions.updateTargetMap({ type: undefined, sourceId: value }, true);
setTimeout(() => {
this.formRef.current?.setFieldsValue(this.props.collectionData?.targetMap)
});
return;
}
const sourceType = option.data.dataTypeCode;
const initialFields = getSourceInitialField(sourceType, this.props.collectionData);
/**
* sourceId 改变,则清空表
*/
streamTaskActions.updateTargetMap({ ...initialFields, sourceId: value }, true);
setTimeout(() => {
this.formRef.current?.setFieldsValue(initialFields)
}, 0);
}
prev() {
streamTaskActions.navtoStep(0)
}
next() {
this.formRef.current?.validateFields().then(values => {
streamTaskActions.navtoStep(2)
})
}
renderDynamic = (sourceId: any) => {
const { collectionData } = this.props;
const { targetMap = {} } = collectionData;
switch (targetMap.type) {
case DATA_SOURCE_ENUM.TBDS_KAFKA:
case DATA_SOURCE_ENUM.KAFKA:
case DATA_SOURCE_ENUM.KAFKA_2X:
case DATA_SOURCE_ENUM.KAFKA_09:
case DATA_SOURCE_ENUM.KAFKA_10:
case DATA_SOURCE_ENUM.KAFKA_11:
case DATA_SOURCE_ENUM.KAFKA_HUAWEI: {
return <Kafka collectionData={collectionData} />
}
case DATA_SOURCE_ENUM.HDFS: {
return <Hdfs collectionData={collectionData} />
}
case DATA_SOURCE_ENUM.HIVE: {
return <Hive collectionData={collectionData} />
}
case DATA_SOURCE_ENUM.EMQ: {
return <Emq collectionData={collectionData} />
}
case DATA_SOURCE_ENUM.ADB_FOR_PG: {
return <Adb collectionData={collectionData} />
}
default: {
return null;
}
}
}
/**
* 改变提交按钮状态
*/
onFormValuesChange = () => {
setTimeout(() => {
this.formRef.current?.validateFields().then(values => {
streamTaskActions.updateCurrentPage({
invalidSubmit: false
});
}).catch(err => {
streamTaskActions.updateCurrentPage({
invalidSubmit: true
});
})
}, 200)
}
/**
* 表单值改变监听
* @param fields
*/
handleValuesChange = (fields: any) => {
if (fields.hasOwnProperty('analyticalRules')) {
if (fields['analyticalRules']) {
if (fields['analyticalRules'][0] == '_') {
fields['analyticalRules'] = prefixRule + fields['analyticalRules'];
} else {
fields['analyticalRules'] = prefixRule + '_' + fields['analyticalRules'];
}
} else {
fields['analyticalRules'] = prefixRule
}
}
// 建表模式
if (fields.hasOwnProperty('writeTableType')) {
if (fields['writeTableType'] == WRITE_TABLE_TYPE.AUTO) {
fields['fileType'] = 'orc';
fields['analyticalRules'] = prefixRule;
} else {
fields['analyticalRules'] = undefined;
fields['fileType'] = undefined;
}
fields['table'] = undefined;
fields['partition'] = undefined;
}
// 写入表
if (fields.hasOwnProperty('table')) {
fields['partition'] = undefined;
}
if (fields['maxFileSize']) {
fields['maxFileSize'] = fields['maxFileSize'] * 1024 * 1024;
}
streamTaskActions.updateTargetMap(fields, false);
if (this.onFormValuesChange) {
this.onFormValuesChange();
}
}
mapPropsToFields() {
const { collectionData } = this.props;
const targetMap = collectionData.targetMap;
if (!targetMap) return {};
const initMaxFileSize = targetMap?.maxFileSize || targetMap.bufferSize;
let values = {};
Object.entries(targetMap).forEach(([key, value]) => {
if (targetDefaultValue(key)) {
values = Object.assign({}, values, {
[key]: value
});
}
})
return {
...values,
analyticalRules: targetMap.analyticalRules ? targetMap.analyticalRules.replace(prefixRule, '') : '',
fileType: targetMap.fileType || 'orc',
maxFileSize: Number.isNaN(parseInt(initMaxFileSize)) ? undefined : initMaxFileSize / (1024 * 1024)
}
}
render(): React.ReactNode {
const { readonly, collectionData, sourceList } = this.props;
const { isEdit, sourceMap = {}, targetMap = {}, componentVersion } = collectionData;
const { loading } = this.state;
return (<div>
<Form
ref={this.formRef}
{...formItemLayout}
onValuesChange={this.handleValuesChange}
initialValues={this.mapPropsToFields()}
>
<FormItem
name='sourceId'
rules={[{ required: true, message: '请选择数据源' }]}
label="数据源"
tooltip={targetMap?.type == DATA_SOURCE_ENUM.HIVE && sourceMap?.allTable ? { title: hiveWithAllTable, icon: <ExclamationCircleOutlined /> } : ''}
>
<Select
getPopupContainer={(triggerNode: any) => triggerNode}
disabled={isEdit}
placeholder="请选择数据源"
onChange={this.onSelectSource}
style={{ width: '100%' }}
allowClear
>
{sourceList.filter((d: any) => isKafka(d.dataTypeCode)).map((item: any) => {
const allow110List = [DATA_SOURCE_ENUM.TBDS_HBASE, DATA_SOURCE_ENUM.TBDS_KAFKA, DATA_SOURCE_ENUM.KAFKA_HUAWEI, DATA_SOURCE_ENUM.HBASE_HUAWEI];
const { ONLY_ALLOW_FLINK_1_10_DISABLED } = getFlinkDisabledSource({
version: componentVersion,
value: item.dataTypeCode,
allow110List
});
return <Option
{...{ data: item }}
key={item.dataInfoId}
value={item.dataInfoId}
disabled={ONLY_ALLOW_FLINK_1_10_DISABLED}
>
{item.dataName}({DATA_SOURCE_TEXT[item.dataTypeCode as DATA_SOURCE_ENUM]})
</Option>
}).filter(Boolean)}
</Select>
</FormItem>
<FormItem noStyle dependencies={['sourceId']}>
{(f) => this.renderDynamic(f.getFieldValue('sourceId'))}
</FormItem>
{/* { this.renderDynamic() } */}
</Form>
{!readonly && (
<div className="steps-action">
<Button style={{ marginRight: 8 }} onClick={() => this.prev()}>上一步</Button>
<Button loading={loading} type="primary" onClick={() => this.next()}>下一步</Button>
</div>
)}
</div>)
}
}
export default moleculeConnect(molecule.editor, CollectionTarget); | the_stack |
declare interface EDictionary {
/**
* Iterates through the EDictionary
* @param fn Provides (obj: any, i: number) to your function
*/
forEach(fn: (obj: any, i: number) => void): void
/**
* Adds an object to the EDictionary. The object *MUST* have a nid/id property as defined in the nengiConfig
* @param obj
*/
add(obj: any): void
/**
* Removes an object from the EDictionary by reference
* @param obj
*/
remove(obj: any): void
/**
* Removes an object from the EDictionary by type
* @param id
*/
removeById(id: number): void
/**
* Provides access to the underlying data as an array. There is no performance penalty as the underlying data *is* an array. Do not mutate it, use add and remove instead.
*/
toArray(): any[]
}
declare namespace nengi {
import EventEmitter from 'events'
type NameAndClassTuple = any
// why not? [string, new (...args: any[]) => Class] ; causes typescript errors
export interface Config {
[prop: string]: any // misc config variables
protocols: {
entities: NameAndClassTuple[],
localMessages: NameAndClassTuple[],
messages: NameAndClassTuple[],
commands: NameAndClassTuple[],
basics: NameAndClassTuple[],
}
}
export class Channel {
/**
* Not intended for direct use, instead use instance.createChannel()
* @param instance
* @param id
*/
constructor(instance: Instance, id: number)
/**
* Adds an entity to the channel. Will attach a nid/ntype to the entity.
* @param entity
*/
addEntity(entity: any)
/**
* Removes an entity from the channel
* @param entity
*/
removeEntity(entity: any)
/**
* Adds a message to the channel
* @param message
*/
addMessage(message: any)
/**
* Adds a client to the channel
* @param client
*/
subscribe(client: any)
/**
* Removes a client from the channel
* @param client
*/
unsubscribe(client: any)
/**
* Destroys a channel, important for memory clean up. Will automatically unsubscribe clients, and remove contained entities.
*/
destroy()
}
export interface View {
x: number
y: number
z?: number
halfWidth: number
halfHeight: number
halfDepth?: number
}
export interface CommandCollection {
tick: number
client: ConnectedClient
commands: any[]
}
export interface ConnectedClient {
// public
id: number
latency: number
view: View
connection: any
[prop: string]: any
// private ish
config: Config
accepted: boolean
lastReceivedDataTimestamp: Date
lastReceivedTick: number
lastProcessedClientTick: number
latencyRecord: any
entityIds: number[]
messageQueue: any[]
jsonQueue: any[]
entityCache: any
cache: any
cacheArr: any[]
channels: Channel[]
cr: any[]
de: any[]
addCreate(id: number)
addDelete(id: number)
subscribe(channel: Channel)
unsubcribe(channel: Channel)
queueMessage(message: any)
queueJSON(json: any)
createOrUpdate(id: number, tick: number, toCreate: number[], toUpdate: number[])
checkVisibility(spatialStructure: any, tick: number)
saveSnapshot(snapshot: any, protocols: any, tick: number)
}
export class Instance extends EventEmitter {
constructor(config: Config, webConfig: any)
clients: EDictionary
config: Config
//on(event: 'disconnect', callback: (client: any) => {}): void
//on(event: string, callback: (a: any, b: any, c: any) => {}): void
//on(event: string, callback: (a: any, b: any) => {}): void
//on(event: string, callback: (client: ConnectedClient) => void): void
// Warning: this function is only present if a nengi hooks mixin has been used.
emitCommands(): void
/**
* (NOT WORKING) Disables interpolation for an entity for one frame.
* @param nid
*/
noInterp(nid: number): void
/**
* Sleeps an entity, aka stops nengi from scanning the entity for changes each tick
* @param entity
*/
sleep(entity: any): void
/**
* Returns true if entity is awake
* @param entity
*/
isAwake(entity: any): boolean
/**
* Returns true if entity is asleep
* @param entity
*/
isAsleep(entity: any): boolean
/**
* Wakes an entity, aka enables nengi scanning the entity for changes each tick
* @param entity
*/
wake(entity: any): void
/**
* Wakes an entity for one server tick, so that changes to it will be networked. Entity will return to sleep the following tick.
* @param entity
*/
wakeOnce(entity: any): void
/**
* Sets the callback that will be invoked when a client connects.
* @param {} connectCallback
* Example of accepting everyone:
* ```js
* instance.onConnect(client, data, (acceptOrDenyCallback) => {
* acceptOrDenyCallback({ accepted: true, text: 'Welcome!'})
* })
* ```
* Advanced authentication example:
* ```js
* instance.onConnect(client, data, async (acceptOrDenyCallback) => {
* const user = await authService.verify(data.token) // hypothetical token passed
* if (user) {
* client.user = user // could contain data from a db
* acceptOrDenyCallback({ accepted: true, text: 'Welcome!'})
* } else {
* acceptOrDenyCallback({ accepted: false, text: 'Unauthenticated'})
* }
* })
* ```
*/
onConnect(connectCallback: (client: ConnectedClient, data: any, acceptOrDenyCallback: ({ accepted, text }: { accepted: boolean, text: string }) => void) => void): void
/**
* Sets the callback that will be invoked when a client disonnects.
* Example:
* ```js
* instance.onDisconnect((client) => {
* // clean up! (hypothetical)
* if (client.entity) {
* instance.removeEntity(client.entity)
* }
* })
* ```
* @param client
*/
onDisconnect(callback: (client: ConnectedClient) => void)
/**
* Returns the next incoming command from a queue and marks it as processed. Will return undefined if no more commands are queued.
*/
getNextCommand(): CommandCollection | undefined
// none of these are intended for public consumption
//onMessage(message: any, client: any): void
//acceptConnection(client: any, text: string): void
//denyConnection(client: any, text: string): void
//connect(connection: any)
/**
* Adds an entity to the game instance where it will be automatically synchronized to game clients. Assigns a nid and ntype to the entity.
* @param entity
*/
addEntity(entity: any): void
/**
* Removes an entity from the instance, causes it to disappear from all game clients. Changes entity nid to -1.
* @param entity
*/
removeEntity(entity: any): void
/**
* Gets an entity from the instance by nid. Will scan channels and all forms of visibility.
* @param id
*/
getEntity(id: number): any
/**
* Sends a message to one or more clients.
*
* @param message Message
* @param clientOrClients A client or an array of clients
*/
message(message: any, clientOrClients: ConnectedClient | ConnectedClient[]): any
/**
* Sends a message to all clients.
* @param message
*/
messageAll(message: any): void
/**
* Creates and returns a new Channel
*/
createChannel(): Channel
/**
* Sends network snapshots to all clients. To be invoked towards the end of a game tick in most cases.
*/
update(): void
}
/**
* A single prediction error, in the format { nid, prop, predictedValue, actualValue, deltaValue }
* Using clientsideEntity[prop] = actualValue will correct the clientside state
*/
export class PredictionErrorProperty {
nid: number
prop: string
predictedValue: any
actualValue: any
deltaValue: any
}
/**
* A specific entity and an array of its prediction errors
*/
export class PredictionErrorEntity {
errors: PredictionErrorProperty[]
}
/**
* Contains a Map collection of entities that experienced a prediciton error
*/
export class PredictionErrorFrame {
tick: number
entities: Map<number, PredictionErrorEntity>
}
export interface ClientInterpolatedViewStateSnapshot {
messages: any[]
localMessages: any[]
entities: EntityStateSnapshot[]
jsons: any[]
predictionErrors: any[]
}
export interface EntityUpdate {
[prop: string]: any // placeholder for configurable nid property
prop: string
value: any
path: string[]
}
export interface EntityStateSnapshot {
createEntities: any[]
updateEntities: EntityUpdate[]
deleteEntities: number[]
}
export class Client {
constructor(config: Config, interDelay: number)
// allow any prop to be attached to Client, aka normal JavaScript
[prop: string]: any
config: Config
tick: number
/**
* Connect to an instance
*
* @param address Address, e.g. ws://localhost:8001
* @param handshake (optional) Handshake object with any properties and values to pass to the server.
*/
connect(address: string, handshake?: any): void
/**
* Adds a command to the outbound queue
* @param command
*/
addCommand(command: any): void
/**
* Reads any queued data from the server, and returns them in snapshot format.
* @returns {ClientInterpolatedViewStateSnapshot}
*/
readNetwork(): ClientInterpolatedViewStateSnapshot
/**
* Flushes (sends) any outbound commands.
*/
update(): void
/**
* Reads any queued data from the server and emits it in the nengi hooks api format. Warning: this function is only present if a nengi hooks mixin has been used.
*/
readNetworkAndEmit(): any
/**
* Add a clientside prediction about an entity's state
* @param tick clientside tick number, usually `client.tick`
* @param entity the entity being predicted, or an object with the same nid and props, e.g. { nid, x, y }
* @param props list of predicted props as an array, e.g. ['x', 'y', 'rotation']
*/
addPrediction(tick: number, entity: any, props: string[])
/**
* Add a clientside prediction about an entity's state, optionally attaching more properties to it than those which are networked
* @param tick clientside tick number, usually `client.tick`
* @param entity the entity being predicted, or an object with the same nid and props, e.g. { nid, x, y }
* @param props list of predicted props as an array, e.g. ['x', 'y', 'rotation']
*/
addCustomPrediction(tick: number, entity: any, props: string[])
// TODO
on(event: string, callback: (message: any) => void): void
}
/**
* Holds a boolean value, serializes over the network to 1 bit
*/
export const Boolean: number
/**
* Holds any integer in the range 0 to3
*/
export const UInt2: number
/**
* Holds any integer in the range 0 to 7
*/
export const UInt3: number
/**
* Holds any integer in the range -8 to 7
*/
export const Int4: number
/**
* Holds any integer in the range 0 to 15
*/
export const UInt4: number
/**
* Holds any integer in the range -32 to 31
*/
export const Int6: number
/**
* Holds any integer in the range 0 to 61
*/
export const UInt6: number
/**
* Holds any integer in the range -128 to 127
*/
export const Int8: number
/**
* Holds any integer in the range 0 to 255
*/
export const UInt8: number
/**
* Holds any integer in the range -512 to 511
*/
export const Int10: number
/**
* Holds any integer in the range 0 to 1023
*/
export const UInt10: number
/**
* Holds any integer in the range 0 to 4095
*/
export const UInt12: number
/**
* Holds any integer in the range -32768 to 32767
*/
export const Int16: number
/**
* Holds any integer in the range 0 to 65535
*/
export const UInt16: number
/**
* Holds any integer in the range -2147483648 to 2147483647
*/
export const Int32: number
/**
* Holds any integer in the range 0 to 4294967295
*/
export const UInt32: number
/**
* Holds a JavaScript Number (64 bit), same as Float64
*/
export const Number: number
/**
* Holds a 32 bit floating point, half the resolution of Float64 aka Number
*/
export const Float32: number
/**
* Holds a 64 bit floating point, same as Number
*/
export const Float64: number
/**
* Holds a 32 bit floating point that will be interpolated around
*/
export const RotationFloat32: number
/**
* Holds a string with a max length of 255 where each character is networked as byte (not utf8 safe!).
*/
export const ASCIIString: number
/**
* Alias to UTF8String
*/
export const String: number
/**
* Holds a string of UTF8 characters, maximum 4294967295 bytes
*/
export const UTF8String: number
}
export = nengi | the_stack |
import { BrowserAdapter } from 'common/browser-adapters/browser-adapter';
import { BackchannelStoreRequestMessage } from 'common/types/backchannel-message-type';
import { BrowserBackchannelWindowMessagePoster } from 'injected/frameCommunicators/browser-backchannel-window-message-poster';
import { WindowMessage } from 'injected/frameCommunicators/window-message';
import {
createSimulatedWindowUtils,
SimulatedWindowUtils,
} from 'tests/unit/common/simulated-window';
import { IMock, It, Mock, Times } from 'typemoq';
import {
BackchannelMessagePair,
BackchannelWindowMessageTranslator,
MESSAGE_STABLE_SIGNATURE,
WindowMessageMetadata,
} from '../../../../../injected/frameCommunicators/backchannel-window-message-translator';
describe('BrowserBackchannelWindowMessagePoster', () => {
let testSubject: BrowserBackchannelWindowMessagePoster;
let mockBrowserAdapter: IMock<BrowserAdapter>;
let mockBackchannelWindowMessageTranslator: IMock<BackchannelWindowMessageTranslator>;
let mockWindowUtils: SimulatedWindowUtils;
const messageSourceId = 'app id';
const messageVersion = 'app version';
let manifest: chrome.runtime.Manifest;
function getSampleMessageWithResponseId(): WindowMessage {
return {
message: 'hello',
command: 'message',
messageId: 'id1',
error: {},
} as WindowMessage;
}
const sampleMessage = getSampleMessageWithResponseId();
const sampleBackchannelMessage = {
...sampleMessage,
messageSourceId: messageSourceId,
messageStableSignature: MESSAGE_STABLE_SIGNATURE,
messageVersion: messageVersion,
};
const backchannelResponseMessage = {
messageId: sampleMessage.messageId,
messageType: 'backchannel_window_message.retrieve_response',
stringifiedMessageData: sampleMessage.message,
messageSourceId: messageSourceId,
messageStableSignature: MESSAGE_STABLE_SIGNATURE,
messageVersion: messageVersion,
};
beforeEach(() => {
manifest = {
name: messageSourceId,
version: messageVersion,
} as chrome.runtime.Manifest;
mockBrowserAdapter = Mock.ofType<BrowserAdapter>();
mockBrowserAdapter.setup(b => b.getManifest()).returns(() => manifest);
mockWindowUtils = createSimulatedWindowUtils();
mockBackchannelWindowMessageTranslator = Mock.ofType<BackchannelWindowMessageTranslator>();
testSubject = new BrowserBackchannelWindowMessagePoster(
mockWindowUtils.object,
mockBrowserAdapter.object,
mockBackchannelWindowMessageTranslator.object,
);
});
test('adds event listener on initialize', () => {
mockWindowUtils
.setup(x => x.addEventListener(window, 'message', It.isAny(), false))
.verifiable(Times.once());
testSubject.initialize();
mockWindowUtils.verifyAll();
mockBrowserAdapter.verifyAll();
mockBackchannelWindowMessageTranslator.verifyAll();
});
test('postMessage successfully posts to both backchannel and to frame', async () => {
testSubject.initialize();
const targetWindow = {} as Window;
const sampleMessage = getSampleMessageWithResponseId();
mockBackchannelWindowMessageTranslator
.setup(x => x.splitWindowMessage(sampleMessage))
.returns(
() =>
({
backchannelMessage: {
messageType: 'backchannel_window_message.store_request',
stringifiedMessageData: sampleMessage.message,
...sampleMessage,
} as BackchannelStoreRequestMessage,
windowMessageMetadata: sampleMessage as WindowMessageMetadata,
} as BackchannelMessagePair),
)
.verifiable(Times.once());
mockBrowserAdapter
.setup(x =>
x.sendRuntimeMessage({
messageType: 'backchannel_window_message.store_request',
stringifiedMessageData: sampleMessage.message,
...sampleMessage,
}),
)
.verifiable(Times.once());
mockWindowUtils
.setup(x => x.postMessage(targetWindow, sampleMessage, '*'))
.verifiable(Times.once());
// sending message to iframe
testSubject.postMessage(targetWindow, sampleMessage);
mockWindowUtils.verifyAll();
mockBrowserAdapter.verifyAll();
mockBackchannelWindowMessageTranslator.verifyAll();
});
test('onWindowMessageEvent bails if we cannot parse receive message', () => {
testSubject.initialize();
const targetWindow = {} as Window;
const sampleMessageEvent: MessageEvent = {
source: targetWindow,
data: { ...sampleBackchannelMessage, messageType: 'random type' },
} as MessageEvent;
mockBackchannelWindowMessageTranslator
.setup(x =>
x.tryCreateBackchannelReceiveMessage({
...sampleBackchannelMessage,
messageType: 'random type',
}),
)
.returns(() => null)
.verifiable(Times.once());
mockBrowserAdapter
.setup(adapter => adapter.sendRuntimeMessage(It.isAny()))
.verifiable(Times.never());
mockBackchannelWindowMessageTranslator
.setup(translator => translator.tryParseBackchannelRetrieveResponseMessage(It.isAny()))
.verifiable(Times.never());
// trigger message
mockWindowUtils.notifyOnMessageEvent(sampleMessageEvent);
mockWindowUtils.verifyAll();
mockBrowserAdapter.verifyAll();
mockBackchannelWindowMessageTranslator.verifyAll();
});
test('onWindowMessageEvent parses messages from backchannel and sends response to registered listeners', async () => {
testSubject.initialize();
const targetWindow = {} as Window;
const sampleMessageEvent: MessageEvent = {
source: targetWindow,
data: sampleBackchannelMessage,
} as MessageEvent;
const listener1 = jest.fn((msg, win) => {
expect(msg).toBe(sampleMessage.message);
expect(win).toBe(targetWindow);
return msg;
});
const listener2 = jest.fn((msg, win) => {
expect(msg).toBe(sampleMessage.message);
expect(win).toBe(targetWindow);
return msg;
});
testSubject.addMessageListener(listener1);
testSubject.addMessageListener(listener2);
mockBackchannelWindowMessageTranslator
.setup(x => x.tryCreateBackchannelReceiveMessage(sampleBackchannelMessage))
.returns(() => {
return {
messageId: sampleBackchannelMessage.messageId,
messageType: 'backchannel_window_message.retrieve_request',
};
})
.verifiable(Times.once());
mockBrowserAdapter
.setup(adapter => adapter.sendRuntimeMessage(It.isAny()))
.returns(() => Promise.resolve(backchannelResponseMessage))
.verifiable(Times.once());
mockBackchannelWindowMessageTranslator
.setup(translator =>
translator.tryParseBackchannelRetrieveResponseMessage(backchannelResponseMessage),
)
.returns(() => ({
messageId: sampleMessage.messageId,
messageType: 'backchannel_window_message.retrieve_response',
stringifiedMessageData: JSON.stringify(sampleMessage.message),
}))
.verifiable(Times.once());
// trigger message
await mockWindowUtils.notifyOnMessageEvent(sampleMessageEvent);
expect(listener1).toHaveBeenCalledTimes(1);
expect(listener2).toHaveBeenCalledTimes(1);
mockWindowUtils.verifyAll();
mockBrowserAdapter.verifyAll();
mockBackchannelWindowMessageTranslator.verifyAll();
});
test('onWindowMessageEvent does not call listeners if no response from browser', async () => {
testSubject.initialize();
const targetWindow = {} as Window;
const sampleMessageEvent: MessageEvent = {
source: targetWindow,
data: sampleBackchannelMessage,
} as MessageEvent;
const listener1 = jest.fn((msg, win) => {
expect(msg).toBe(sampleMessage.message);
expect(win).toBe(targetWindow);
return msg;
});
const listener2 = jest.fn((msg, win) => {
expect(msg).toBe(sampleMessage.message);
expect(win).toBe(targetWindow);
return msg;
});
testSubject.addMessageListener(listener1);
testSubject.addMessageListener(listener2);
mockBackchannelWindowMessageTranslator
.setup(x => x.tryCreateBackchannelReceiveMessage(sampleBackchannelMessage))
.returns(() => {
return {
messageId: sampleBackchannelMessage.messageId,
messageType: 'backchannel_window_message.retrieve_request',
};
})
.verifiable(Times.once());
mockBrowserAdapter
.setup(adapter =>
adapter.sendRuntimeMessage({
messageId: sampleBackchannelMessage.messageId,
messageType: 'backchannel_window_message.retrieve_request',
}),
)
.returns(() => null)
.verifiable(Times.once());
mockBackchannelWindowMessageTranslator
.setup(translator => translator.tryParseBackchannelRetrieveResponseMessage(It.isAny()))
.returns(() => null)
.verifiable(Times.once());
// trigger message
await mockWindowUtils.notifyOnMessageEvent(sampleMessageEvent);
expect(listener1).not.toHaveBeenCalled();
expect(listener2).not.toHaveBeenCalled();
mockWindowUtils.verifyAll();
mockBrowserAdapter.verifyAll();
mockBackchannelWindowMessageTranslator.verifyAll();
});
test('onWindowMessageEvent bails silently if the browser indicates an invalid message token', async () => {
testSubject.initialize();
const targetWindow = {} as Window;
const sampleMessageEvent: MessageEvent = {
source: targetWindow,
data: sampleBackchannelMessage,
} as MessageEvent;
const listener1 = jest.fn((msg, win) => {
expect(msg).toBe(sampleMessage.message);
expect(win).toBe(targetWindow);
return msg;
});
const listener2 = jest.fn((msg, win) => {
expect(msg).toBe(sampleMessage.message);
expect(win).toBe(targetWindow);
return msg;
});
testSubject.addMessageListener(listener1);
testSubject.addMessageListener(listener2);
mockBackchannelWindowMessageTranslator
.setup(x => x.tryCreateBackchannelReceiveMessage(sampleBackchannelMessage))
.returns(() => {
return {
messageId: sampleBackchannelMessage.messageId,
messageType: 'backchannel_window_message.retrieve_request',
};
})
.verifiable(Times.once());
mockBrowserAdapter
.setup(adapter =>
adapter.sendRuntimeMessage({
messageId: sampleBackchannelMessage.messageId,
messageType: 'backchannel_window_message.retrieve_request',
}),
)
.returns(() => Promise.reject(new Error('Could not find content for specified token')))
.verifiable(Times.once());
// trigger message
await mockWindowUtils.notifyOnMessageEvent(sampleMessageEvent);
expect(listener1).not.toHaveBeenCalled();
expect(listener2).not.toHaveBeenCalled();
mockWindowUtils.verifyAll();
mockBrowserAdapter.verifyAll();
mockBackchannelWindowMessageTranslator.verifyAll();
});
}); | the_stack |
import {Buffer} from 'node:buffer';
import type {IncomingHttpHeaders} from 'node:http';
import test from 'ava';
import type {RequestHandler} from 'express';
import FormData from 'form-data';
import ky from '../source/index.js';
import {createHttpTestServer} from './helpers/create-http-test-server.js';
const echoHeaders: RequestHandler = (request, response) => {
request.resume();
response.end(JSON.stringify(request.headers));
};
test.serial('works with nullish headers even in old browsers', async t => {
t.plan(4);
const server = await createHttpTestServer();
server.get('/', echoHeaders);
const OriginalHeaders = Headers;
// Some old browsers throw for new Headers(undefined) or new Headers(null)
// so we check that Ky never does that and passes an empty object instead.
// See: https://github.com/sindresorhus/ky/issues/260
globalThis.Headers = class Headers extends OriginalHeaders {
constructor(headersInit?: HeadersInit | undefined) {
t.deepEqual(headersInit, {});
super(headersInit);
}
};
const response = await ky.get(server.url).json<IncomingHttpHeaders>();
t.is(typeof response, 'object');
t.truthy(response);
await server.close();
globalThis.Headers = OriginalHeaders;
});
test('`user-agent`', async t => {
const server = await createHttpTestServer();
server.get('/', echoHeaders);
const headers = await ky.get(server.url).json<IncomingHttpHeaders>();
t.is(headers['user-agent'], 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
});
test('`accept-encoding`', async t => {
const server = await createHttpTestServer();
server.get('/', echoHeaders);
const headers = await ky.get(server.url).json<IncomingHttpHeaders>();
t.is(headers['accept-encoding'], 'gzip,deflate');
});
test('does not override provided `accept-encoding`', async t => {
const server = await createHttpTestServer();
server.get('/', echoHeaders);
const headers = await ky
.get(server.url, {
headers: {
'accept-encoding': 'gzip',
},
})
.json<IncomingHttpHeaders>();
t.is(headers['accept-encoding'], 'gzip');
});
test('does not remove user headers from `url` object argument', async t => {
const server = await createHttpTestServer();
server.get('/', echoHeaders);
const headers = await ky
.get(server.url, {
headers: {
'X-Request-Id': 'value',
},
})
.json<IncomingHttpHeaders>();
t.is(headers.accept, 'application/json');
t.is(headers['user-agent'], 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
t.is(headers['accept-encoding'], 'gzip,deflate');
t.is(headers['x-request-id'], 'value');
});
test('`accept` header with `json` option', async t => {
const server = await createHttpTestServer();
server.get('/', echoHeaders);
let headers = await ky.get(server.url).json<IncomingHttpHeaders>();
t.is(headers.accept, 'application/json');
headers = await ky
.get(server.url, {
headers: {
accept: '',
},
})
.json<IncomingHttpHeaders>();
t.is(headers.accept, 'application/json');
});
test('`host` header', async t => {
const server = await createHttpTestServer();
server.get('/', echoHeaders);
const headers = await ky.get(server.url).json<IncomingHttpHeaders>();
t.is(headers.host, `localhost:${server.port}`);
});
test('transforms names to lowercase', async t => {
const server = await createHttpTestServer();
server.get('/', echoHeaders);
const headers = await ky(server.url, {
headers: {
'ACCEPT-ENCODING': 'identity',
},
}).json<IncomingHttpHeaders>();
t.is(headers['accept-encoding'], 'identity');
});
test('setting `content-length` to 0', async t => {
const server = await createHttpTestServer();
server.post('/', echoHeaders);
const headers = await ky
.post(server.url, {
headers: {
'content-length': '0',
},
body: 'sup',
})
.json<IncomingHttpHeaders>();
t.is(headers['content-length'], '3');
});
test('sets `content-length` to `0` when requesting PUT with empty body', async t => {
const server = await createHttpTestServer();
server.put('/', echoHeaders);
const headers = await ky.put(server.url).json<IncomingHttpHeaders>();
t.is(headers['content-length'], '0');
});
test('form-data manual `content-type` header', async t => {
const server = await createHttpTestServer();
server.post('/', echoHeaders);
const form = new FormData();
form.append('a', 'b');
const headers = await ky
.post(server.url, {
headers: {
'content-type': 'custom',
},
// @ts-expect-error FormData type mismatch
body: form,
})
.json<IncomingHttpHeaders>();
t.is(headers['content-type'], 'custom');
});
test('form-data automatic `content-type` header', async t => {
const server = await createHttpTestServer();
server.post('/', echoHeaders);
const form = new FormData();
form.append('a', 'b');
const headers = await ky
.post(server.url, {
// @ts-expect-error FormData type mismatch
body: form,
})
.json<IncomingHttpHeaders>();
t.is(headers['content-type'], `multipart/form-data;boundary=${form.getBoundary()}`);
});
test('form-data manual `content-type` header with search params', async t => {
const server = await createHttpTestServer();
server.post('/', echoHeaders);
const form = new FormData();
form.append('a', 'b');
const headers = await ky
.post(server.url, {
searchParams: 'foo=1',
headers: {
'content-type': 'custom',
},
// @ts-expect-error FormData type mismatch
body: form,
})
.json<IncomingHttpHeaders>();
t.is(headers['content-type'], 'custom');
});
test('form-data automatic `content-type` header with search params', async t => {
const server = await createHttpTestServer();
server.post('/', echoHeaders);
const form = new FormData();
form.append('a', 'b');
const headers = await ky
.post(server.url, {
searchParams: 'foo=1',
// @ts-expect-error FormData type mismatch
body: form,
})
.json<IncomingHttpHeaders>();
t.is(headers['content-type'], `multipart/form-data;boundary=${form.getBoundary()}`);
});
test('form-data sets `content-length` header', async t => {
const server = await createHttpTestServer();
server.post('/', echoHeaders);
const form = new FormData();
form.append('a', 'b');
// @ts-expect-error FormData type mismatch
const headers = await ky.post(server.url, {body: form}).json<IncomingHttpHeaders>();
t.is(headers['content-length'], '157');
});
test('buffer as `options.body` sets `content-length` header', async t => {
const server = await createHttpTestServer();
server.post('/', echoHeaders);
const buffer = Buffer.from('unicorn');
const headers = await ky
.post(server.url, {
body: buffer,
})
.json<IncomingHttpHeaders>();
t.is(Number(headers['content-length']), buffer.length);
});
// TODO: Enable this when node-fetch allows for removal of default headers. Context: https://github.com/node-fetch/node-fetch/issues/591
test.failing('removes undefined value headers', async t => {
const server = await createHttpTestServer();
server.get('/', echoHeaders);
const headers = await ky
.get(server.url, {
headers: {
'user-agent': undefined,
unicorn: 'unicorn',
},
})
.json<IncomingHttpHeaders>();
t.is(headers['user-agent'], 'undefined');
t.is(headers['unicorn'], 'unicorn');
});
test('non-existent headers set to undefined are omitted', async t => {
const server = await createHttpTestServer();
server.get('/', echoHeaders);
const headers = await ky
.get(server.url, {
headers: {
blah: undefined,
rainbow: 'unicorn',
},
})
.json<IncomingHttpHeaders>();
t.false('blah' in headers);
t.true('rainbow' in headers);
});
test('preserve port in host header if non-standard port', async t => {
const server = await createHttpTestServer();
server.get('/', echoHeaders);
const body = await ky.get(server.url).json<IncomingHttpHeaders>();
t.is(body.host, `localhost:${server.port}`);
});
test('strip port in host header if explicit standard port (:80) & protocol (HTTP)', async t => {
const body = await ky.get('http://httpbin.org:80/headers').json<{headers: IncomingHttpHeaders}>();
t.is(body.headers['Host'], 'httpbin.org');
});
test('strip port in host header if explicit standard port (:443) & protocol (HTTPS)', async t => {
const body = await ky.get('https://httpbin.org:443/headers').json<{headers: IncomingHttpHeaders}>();
t.is(body.headers['Host'], 'httpbin.org');
});
test('strip port in host header if implicit standard port & protocol (HTTP)', async t => {
const body = await ky.get('http://httpbin.org/headers').json<{headers: IncomingHttpHeaders}>();
t.is(body.headers['Host'], 'httpbin.org');
});
test('strip port in host header if implicit standard port & protocol (HTTPS)', async t => {
const body = await ky.get('https://httpbin.org/headers').json<{headers: IncomingHttpHeaders}>();
t.is(body.headers['Host'], 'httpbin.org');
});
test('remove custom header by extending instance (plain objects)', async t => {
const server = await createHttpTestServer();
server.get('/', echoHeaders);
const original = ky.create({
headers: {
rainbow: 'rainbow',
unicorn: 'unicorn',
},
});
const extended = original.extend({
headers: {
rainbow: undefined,
},
});
const response = await extended(server.url).json<IncomingHttpHeaders>();
t.true('unicorn' in response);
t.false('rainbow' in response);
await server.close();
});
test('remove header by extending instance (Headers instance)', async t => {
const server = await createHttpTestServer();
server.get('/', echoHeaders);
const original = ky.create({
headers: new Headers({
rainbow: 'rainbow',
unicorn: 'unicorn',
}),
});
const extended = original.extend({
// @ts-expect-error Headers does not support undefined values
headers: new Headers({
rainbow: undefined,
}),
});
const response = await extended(server.url).json<IncomingHttpHeaders>();
t.false('rainbow' in response);
t.true('unicorn' in response);
await server.close();
});
test('remove header by extending instance (Headers instance and plain object)', async t => {
const server = await createHttpTestServer();
server.get('/', echoHeaders);
const original = ky.create({
headers: new Headers({
rainbow: 'rainbow',
unicorn: 'unicorn',
}),
});
const extended = original.extend({
headers: {
rainbow: undefined,
},
});
const response = await extended(server.url).json<IncomingHttpHeaders>();
t.false('rainbow' in response);
t.true('unicorn' in response);
await server.close();
});
test('remove header by extending instance (plain object and Headers instance)', async t => {
const server = await createHttpTestServer();
server.get('/', echoHeaders);
const original = ky.create({
headers: {
rainbow: 'rainbow',
unicorn: 'unicorn',
},
});
const extended = original.extend({
// @ts-expect-error Headers does not support undefined values
headers: new Headers({
rainbow: undefined,
}),
});
const response = await extended(server.url).json<IncomingHttpHeaders>();
t.false('rainbow' in response);
t.true('unicorn' in response);
await server.close();
}); | the_stack |
import {
Directive,
Renderer2,
ElementRef,
OnInit,
Output,
Input,
EventEmitter,
OnDestroy,
NgZone,
Inject,
PLATFORM_ID,
} from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { Subject, Observable, Observer, merge } from 'rxjs';
import {
map,
mergeMap,
takeUntil,
filter,
pairwise,
take,
share,
tap,
} from 'rxjs/operators';
import { Edges } from './interfaces/edges.interface';
import { BoundingRectangle } from './interfaces/bounding-rectangle.interface';
import { ResizeEvent } from './interfaces/resize-event.interface';
import { IS_TOUCH_DEVICE } from './util/is-touch-device';
import { deepCloneNode } from './util/clone-node';
interface PointerEventCoordinate {
clientX: number;
clientY: number;
event: MouseEvent | TouchEvent;
}
interface Coordinate {
x: number;
y: number;
}
function getNewBoundingRectangle(
startingRect: BoundingRectangle,
edges: Edges,
clientX: number,
clientY: number
): BoundingRectangle {
const newBoundingRect: BoundingRectangle = {
top: startingRect.top,
bottom: startingRect.bottom,
left: startingRect.left,
right: startingRect.right,
};
if (edges.top) {
newBoundingRect.top += clientY;
}
if (edges.bottom) {
newBoundingRect.bottom += clientY;
}
if (edges.left) {
newBoundingRect.left += clientX;
}
if (edges.right) {
newBoundingRect.right += clientX;
}
newBoundingRect.height = newBoundingRect.bottom - newBoundingRect.top;
newBoundingRect.width = newBoundingRect.right - newBoundingRect.left;
return newBoundingRect;
}
function getElementRect(
element: ElementRef,
ghostElementPositioning: string
): BoundingRectangle {
let translateX = 0;
let translateY = 0;
const style = element.nativeElement.style;
const transformProperties = [
'transform',
'-ms-transform',
'-moz-transform',
'-o-transform',
];
const transform = transformProperties
.map((property) => style[property])
.find((value) => !!value);
if (transform && transform.includes('translate')) {
translateX = transform.replace(
/.*translate3?d?\((-?[0-9]*)px, (-?[0-9]*)px.*/,
'$1'
);
translateY = transform.replace(
/.*translate3?d?\((-?[0-9]*)px, (-?[0-9]*)px.*/,
'$2'
);
}
if (ghostElementPositioning === 'absolute') {
return {
height: element.nativeElement.offsetHeight,
width: element.nativeElement.offsetWidth,
top: element.nativeElement.offsetTop - translateY,
bottom:
element.nativeElement.offsetHeight +
element.nativeElement.offsetTop -
translateY,
left: element.nativeElement.offsetLeft - translateX,
right:
element.nativeElement.offsetWidth +
element.nativeElement.offsetLeft -
translateX,
};
} else {
const boundingRect: BoundingRectangle =
element.nativeElement.getBoundingClientRect();
return {
height: boundingRect.height,
width: boundingRect.width,
top: boundingRect.top - translateY,
bottom: boundingRect.bottom - translateY,
left: boundingRect.left - translateX,
right: boundingRect.right - translateX,
scrollTop: element.nativeElement.scrollTop,
scrollLeft: element.nativeElement.scrollLeft,
};
}
}
export interface ResizeCursors {
topLeft: string;
topRight: string;
bottomLeft: string;
bottomRight: string;
leftOrRight: string;
topOrBottom: string;
}
const DEFAULT_RESIZE_CURSORS: ResizeCursors = Object.freeze({
topLeft: 'nw-resize',
topRight: 'ne-resize',
bottomLeft: 'sw-resize',
bottomRight: 'se-resize',
leftOrRight: 'col-resize',
topOrBottom: 'row-resize',
});
function getResizeCursor(edges: Edges, cursors: ResizeCursors): string {
if (edges.left && edges.top) {
return cursors.topLeft;
} else if (edges.right && edges.top) {
return cursors.topRight;
} else if (edges.left && edges.bottom) {
return cursors.bottomLeft;
} else if (edges.right && edges.bottom) {
return cursors.bottomRight;
} else if (edges.left || edges.right) {
return cursors.leftOrRight;
} else if (edges.top || edges.bottom) {
return cursors.topOrBottom;
} else {
return '';
}
}
function getEdgesDiff({
edges,
initialRectangle,
newRectangle,
}: {
edges: Edges;
initialRectangle: BoundingRectangle;
newRectangle: BoundingRectangle;
}): Edges {
const edgesDiff: Edges = {};
Object.keys(edges).forEach((edge) => {
edgesDiff[edge] = (newRectangle[edge] || 0) - (initialRectangle[edge] || 0);
});
return edgesDiff;
}
const RESIZE_ACTIVE_CLASS: string = 'resize-active';
const RESIZE_GHOST_ELEMENT_CLASS: string = 'resize-ghost-element';
export const MOUSE_MOVE_THROTTLE_MS: number = 50;
/**
* Place this on an element to make it resizable. For example:
*
* ```html
* <div
* mwlResizable
* [resizeEdges]="{bottom: true, right: true, top: true, left: true}"
* [enableGhostResize]="true">
* </div>
* ```
* Or in case they are sibling elements:
* ```html
* <div mwlResizable #resizableElement="mwlResizable"></div>
* <div mwlResizeHandle [resizableContainer]="resizableElement" [resizeEdges]="{bottom: true, right: true}"></div>
* ```
*/
@Directive({
selector: '[mwlResizable]',
exportAs: 'mwlResizable',
})
export class ResizableDirective implements OnInit, OnDestroy {
/**
* A function that will be called before each resize event. Return `true` to allow the resize event to propagate or `false` to cancel it
*/
@Input() validateResize: (resizeEvent: ResizeEvent) => boolean;
/**
* Set to `true` to enable a temporary resizing effect of the element in between the `resizeStart` and `resizeEnd` events.
*/
@Input() enableGhostResize: boolean = false;
/**
* A snap grid that resize events will be locked to.
*
* e.g. to only allow the element to be resized every 10px set it to `{left: 10, right: 10}`
*/
@Input() resizeSnapGrid: Edges = {};
/**
* The mouse cursors that will be set on the resize edges
*/
@Input() resizeCursors: ResizeCursors = DEFAULT_RESIZE_CURSORS;
/**
* Define the positioning of the ghost element (can be fixed or absolute)
*/
@Input() ghostElementPositioning: 'fixed' | 'absolute' = 'fixed';
/**
* Allow elements to be resized to negative dimensions
*/
@Input() allowNegativeResizes: boolean = false;
/**
* The mouse move throttle in milliseconds, default: 50 ms
*/
@Input() mouseMoveThrottleMS: number = MOUSE_MOVE_THROTTLE_MS;
/**
* Called when the mouse is pressed and a resize event is about to begin. `$event` is a `ResizeEvent` object.
*/
@Output() resizeStart = new EventEmitter<ResizeEvent>();
/**
* Called as the mouse is dragged after a resize event has begun. `$event` is a `ResizeEvent` object.
*/
@Output() resizing = new EventEmitter<ResizeEvent>();
/**
* Called after the mouse is released after a resize event. `$event` is a `ResizeEvent` object.
*/
@Output() resizeEnd = new EventEmitter<ResizeEvent>();
/**
* @hidden
*/
public mouseup = new Subject<{
clientX: number;
clientY: number;
edges?: Edges;
}>();
/**
* @hidden
*/
public mousedown = new Subject<{
clientX: number;
clientY: number;
edges?: Edges;
}>();
/**
* @hidden
*/
public mousemove = new Subject<{
clientX: number;
clientY: number;
edges?: Edges;
event: MouseEvent | TouchEvent;
}>();
private pointerEventListeners: PointerEventListeners;
private destroy$ = new Subject<void>();
/**
* @hidden
*/
constructor(
@Inject(PLATFORM_ID) private platformId: any,
private renderer: Renderer2,
public elm: ElementRef,
private zone: NgZone
) {
this.pointerEventListeners = PointerEventListeners.getInstance(
renderer,
zone
);
}
/**
* @hidden
*/
ngOnInit(): void {
const mousedown$: Observable<{
clientX: number;
clientY: number;
edges?: Edges;
}> = merge(this.pointerEventListeners.pointerDown, this.mousedown);
const mousemove$ = merge(
this.pointerEventListeners.pointerMove,
this.mousemove
).pipe(
tap(({ event }) => {
if (currentResize) {
try {
event.preventDefault();
} catch (e) {
// just adding try-catch not to see errors in console if there is a passive listener for same event somewhere
// browser does nothing except of writing errors to console
}
}
}),
share()
);
const mouseup$ = merge(this.pointerEventListeners.pointerUp, this.mouseup);
let currentResize: {
edges: Edges;
startingRect: BoundingRectangle;
currentRect: BoundingRectangle;
clonedNode?: HTMLElement;
} | null;
const removeGhostElement = () => {
if (currentResize && currentResize.clonedNode) {
this.elm.nativeElement.parentElement.removeChild(
currentResize.clonedNode
);
this.renderer.setStyle(this.elm.nativeElement, 'visibility', 'inherit');
}
};
const getResizeCursors = (): ResizeCursors => {
return {
...DEFAULT_RESIZE_CURSORS,
...this.resizeCursors,
};
};
const mousedrag: Observable<any> = mousedown$
.pipe(
mergeMap((startCoords) => {
function getDiff(moveCoords: { clientX: number; clientY: number }) {
return {
clientX: moveCoords.clientX - startCoords.clientX,
clientY: moveCoords.clientY - startCoords.clientY,
};
}
const getSnapGrid = () => {
const snapGrid: Coordinate = { x: 1, y: 1 };
if (currentResize) {
if (this.resizeSnapGrid.left && currentResize.edges.left) {
snapGrid.x = +this.resizeSnapGrid.left;
} else if (
this.resizeSnapGrid.right &&
currentResize.edges.right
) {
snapGrid.x = +this.resizeSnapGrid.right;
}
if (this.resizeSnapGrid.top && currentResize.edges.top) {
snapGrid.y = +this.resizeSnapGrid.top;
} else if (
this.resizeSnapGrid.bottom &&
currentResize.edges.bottom
) {
snapGrid.y = +this.resizeSnapGrid.bottom;
}
}
return snapGrid;
};
function getGrid(
coords: { clientX: number; clientY: number },
snapGrid: Coordinate
) {
return {
x: Math.ceil(coords.clientX / snapGrid.x),
y: Math.ceil(coords.clientY / snapGrid.y),
};
}
return (
merge(
mousemove$.pipe(take(1)).pipe(map((coords) => [, coords])),
mousemove$.pipe(pairwise())
) as Observable<
[
{ clientX: number; clientY: number },
{ clientX: number; clientY: number }
]
>
)
.pipe(
map(([previousCoords, newCoords]) => {
return [
previousCoords ? getDiff(previousCoords) : previousCoords,
getDiff(newCoords),
];
})
)
.pipe(
filter(([previousCoords, newCoords]) => {
if (!previousCoords) {
return true;
}
const snapGrid: Coordinate = getSnapGrid();
const previousGrid: Coordinate = getGrid(
previousCoords,
snapGrid
);
const newGrid: Coordinate = getGrid(newCoords, snapGrid);
return (
previousGrid.x !== newGrid.x || previousGrid.y !== newGrid.y
);
})
)
.pipe(
map(([, newCoords]) => {
const snapGrid: Coordinate = getSnapGrid();
return {
clientX:
Math.round(newCoords.clientX / snapGrid.x) * snapGrid.x,
clientY:
Math.round(newCoords.clientY / snapGrid.y) * snapGrid.y,
};
})
)
.pipe(takeUntil(merge(mouseup$, mousedown$)));
})
)
.pipe(filter(() => !!currentResize));
mousedrag
.pipe(
map(({ clientX, clientY }) => {
return getNewBoundingRectangle(
currentResize!.startingRect,
currentResize!.edges,
clientX,
clientY
);
})
)
.pipe(
filter((newBoundingRect: BoundingRectangle) => {
return (
this.allowNegativeResizes ||
!!(
newBoundingRect.height &&
newBoundingRect.width &&
newBoundingRect.height > 0 &&
newBoundingRect.width > 0
)
);
})
)
.pipe(
filter((newBoundingRect: BoundingRectangle) => {
return this.validateResize
? this.validateResize({
rectangle: newBoundingRect,
edges: getEdgesDiff({
edges: currentResize!.edges,
initialRectangle: currentResize!.startingRect,
newRectangle: newBoundingRect,
}),
})
: true;
}),
takeUntil(this.destroy$)
)
.subscribe((newBoundingRect: BoundingRectangle) => {
if (currentResize && currentResize.clonedNode) {
this.renderer.setStyle(
currentResize.clonedNode,
'height',
`${newBoundingRect.height}px`
);
this.renderer.setStyle(
currentResize.clonedNode,
'width',
`${newBoundingRect.width}px`
);
this.renderer.setStyle(
currentResize.clonedNode,
'top',
`${newBoundingRect.top}px`
);
this.renderer.setStyle(
currentResize.clonedNode,
'left',
`${newBoundingRect.left}px`
);
}
if (this.resizing.observers.length > 0) {
this.zone.run(() => {
this.resizing.emit({
edges: getEdgesDiff({
edges: currentResize!.edges,
initialRectangle: currentResize!.startingRect,
newRectangle: newBoundingRect,
}),
rectangle: newBoundingRect,
});
});
}
currentResize!.currentRect = newBoundingRect;
});
mousedown$
.pipe(
map(({ edges }) => {
return edges || {};
}),
filter((edges: Edges) => {
return Object.keys(edges).length > 0;
}),
takeUntil(this.destroy$)
)
.subscribe((edges: Edges) => {
if (currentResize) {
removeGhostElement();
}
const startingRect: BoundingRectangle = getElementRect(
this.elm,
this.ghostElementPositioning
);
currentResize = {
edges,
startingRect,
currentRect: startingRect,
};
const resizeCursors = getResizeCursors();
const cursor = getResizeCursor(currentResize.edges, resizeCursors);
this.renderer.setStyle(document.body, 'cursor', cursor);
this.setElementClass(this.elm, RESIZE_ACTIVE_CLASS, true);
if (this.enableGhostResize) {
currentResize.clonedNode = deepCloneNode(this.elm.nativeElement);
this.elm.nativeElement.parentElement.appendChild(
currentResize.clonedNode
);
this.renderer.setStyle(
this.elm.nativeElement,
'visibility',
'hidden'
);
this.renderer.setStyle(
currentResize.clonedNode,
'position',
this.ghostElementPositioning
);
this.renderer.setStyle(
currentResize.clonedNode,
'left',
`${currentResize.startingRect.left}px`
);
this.renderer.setStyle(
currentResize.clonedNode,
'top',
`${currentResize.startingRect.top}px`
);
this.renderer.setStyle(
currentResize.clonedNode,
'height',
`${currentResize.startingRect.height}px`
);
this.renderer.setStyle(
currentResize.clonedNode,
'width',
`${currentResize.startingRect.width}px`
);
this.renderer.setStyle(
currentResize.clonedNode,
'cursor',
getResizeCursor(currentResize.edges, resizeCursors)
);
this.renderer.addClass(
currentResize.clonedNode,
RESIZE_GHOST_ELEMENT_CLASS
);
currentResize.clonedNode!.scrollTop = currentResize.startingRect
.scrollTop as number;
currentResize.clonedNode!.scrollLeft = currentResize.startingRect
.scrollLeft as number;
}
if (this.resizeStart.observers.length > 0) {
this.zone.run(() => {
this.resizeStart.emit({
edges: getEdgesDiff({
edges,
initialRectangle: startingRect,
newRectangle: startingRect,
}),
rectangle: getNewBoundingRectangle(startingRect, {}, 0, 0),
});
});
}
});
mouseup$.pipe(takeUntil(this.destroy$)).subscribe(() => {
if (currentResize) {
this.renderer.removeClass(this.elm.nativeElement, RESIZE_ACTIVE_CLASS);
this.renderer.setStyle(document.body, 'cursor', '');
this.renderer.setStyle(this.elm.nativeElement, 'cursor', '');
if (this.resizeEnd.observers.length > 0) {
this.zone.run(() => {
this.resizeEnd.emit({
edges: getEdgesDiff({
edges: currentResize!.edges,
initialRectangle: currentResize!.startingRect,
newRectangle: currentResize!.currentRect,
}),
rectangle: currentResize!.currentRect,
});
});
}
removeGhostElement();
currentResize = null;
}
});
}
/**
* @hidden
*/
ngOnDestroy(): void {
// browser check for angular universal, because it doesn't know what document is
if (isPlatformBrowser(this.platformId)) {
this.renderer.setStyle(document.body, 'cursor', '');
}
this.mousedown.complete();
this.mouseup.complete();
this.mousemove.complete();
this.destroy$.next();
}
private setElementClass(elm: ElementRef, name: string, add: boolean): void {
if (add) {
this.renderer.addClass(elm.nativeElement, name);
} else {
this.renderer.removeClass(elm.nativeElement, name);
}
}
}
class PointerEventListeners {
public pointerDown: Observable<PointerEventCoordinate>;
public pointerMove: Observable<PointerEventCoordinate>;
public pointerUp: Observable<PointerEventCoordinate>;
private static instance: PointerEventListeners;
public static getInstance(
renderer: Renderer2,
zone: NgZone
): PointerEventListeners {
if (!PointerEventListeners.instance) {
PointerEventListeners.instance = new PointerEventListeners(
renderer,
zone
);
}
return PointerEventListeners.instance;
}
constructor(renderer: Renderer2, zone: NgZone) {
this.pointerDown = new Observable(
(observer: Observer<PointerEventCoordinate>) => {
let unsubscribeMouseDown: () => void;
let unsubscribeTouchStart: (() => void) | undefined;
zone.runOutsideAngular(() => {
unsubscribeMouseDown = renderer.listen(
'document',
'mousedown',
(event: MouseEvent) => {
observer.next({
clientX: event.clientX,
clientY: event.clientY,
event,
});
}
);
if (IS_TOUCH_DEVICE) {
unsubscribeTouchStart = renderer.listen(
'document',
'touchstart',
(event: TouchEvent) => {
observer.next({
clientX: event.touches[0].clientX,
clientY: event.touches[0].clientY,
event,
});
}
);
}
});
return () => {
unsubscribeMouseDown();
if (IS_TOUCH_DEVICE) {
unsubscribeTouchStart!();
}
};
}
).pipe(share());
this.pointerMove = new Observable(
(observer: Observer<PointerEventCoordinate>) => {
let unsubscribeMouseMove: () => void;
let unsubscribeTouchMove: (() => void) | undefined;
zone.runOutsideAngular(() => {
unsubscribeMouseMove = renderer.listen(
'document',
'mousemove',
(event: MouseEvent) => {
observer.next({
clientX: event.clientX,
clientY: event.clientY,
event,
});
}
);
if (IS_TOUCH_DEVICE) {
unsubscribeTouchMove = renderer.listen(
'document',
'touchmove',
(event: TouchEvent) => {
observer.next({
clientX: event.targetTouches[0].clientX,
clientY: event.targetTouches[0].clientY,
event,
});
}
);
}
});
return () => {
unsubscribeMouseMove();
if (IS_TOUCH_DEVICE) {
unsubscribeTouchMove!();
}
};
}
).pipe(share());
this.pointerUp = new Observable(
(observer: Observer<PointerEventCoordinate>) => {
let unsubscribeMouseUp: () => void;
let unsubscribeTouchEnd: (() => void) | undefined;
let unsubscribeTouchCancel: (() => void) | undefined;
zone.runOutsideAngular(() => {
unsubscribeMouseUp = renderer.listen(
'document',
'mouseup',
(event: MouseEvent) => {
observer.next({
clientX: event.clientX,
clientY: event.clientY,
event,
});
}
);
if (IS_TOUCH_DEVICE) {
unsubscribeTouchEnd = renderer.listen(
'document',
'touchend',
(event: TouchEvent) => {
observer.next({
clientX: event.changedTouches[0].clientX,
clientY: event.changedTouches[0].clientY,
event,
});
}
);
unsubscribeTouchCancel = renderer.listen(
'document',
'touchcancel',
(event: TouchEvent) => {
observer.next({
clientX: event.changedTouches[0].clientX,
clientY: event.changedTouches[0].clientY,
event,
});
}
);
}
});
return () => {
unsubscribeMouseUp();
if (IS_TOUCH_DEVICE) {
unsubscribeTouchEnd!();
unsubscribeTouchCancel!();
}
};
}
).pipe(share());
}
} | the_stack |
import { JSDOM } from 'jsdom'
import { Analytics } from '../../analytics'
const sleep = (time: number): Promise<void> =>
new Promise((resolve) => {
setTimeout(resolve, time)
})
async function resolveWhen(
condition: () => boolean,
timeout?: number
): Promise<void> {
return new Promise((resolve, _reject) => {
if (condition()) {
resolve()
return
}
const check = () =>
setTimeout(() => {
if (condition()) {
resolve()
} else {
check()
}
}, timeout)
check()
})
}
describe('track helpers', () => {
describe('trackLink', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let link: any
let wrap: SVGSVGElement
let svg: SVGAElement
let analytics = new Analytics({ writeKey: 'foo' })
let mockTrack = jest.spyOn(analytics, 'track')
beforeEach(() => {
analytics = new Analytics({ writeKey: 'foo' })
// @ts-ignore
global.jQuery = require('jquery')
const jsd = new JSDOM('', {
runScripts: 'dangerously',
resources: 'usable',
})
document = jsd.window.document
jest.spyOn(console, 'error').mockImplementationOnce(() => {})
document.querySelector('html')!.innerHTML = `
<html>
<body>
<a href='foo.com' id='foo'></a>
<div id='bar'>
<div>
<a href='bar.com'></a>
</div>
</div>
</body>
</html>`
link = document.getElementById('foo')
wrap = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
svg = document.createElementNS('http://www.w3.org/2000/svg', 'a')
wrap.appendChild(svg)
document.body.appendChild(wrap)
jest.spyOn(window, 'location', 'get').mockReturnValue({
...window.location,
})
mockTrack = jest.spyOn(analytics, 'track')
// We need to mock the track function for the .catch() call not to break when testing
// eslint-disable-next-line @typescript-eslint/unbound-method
mockTrack.mockImplementation(Analytics.prototype.track)
})
it('should stay on same page with blank href', async () => {
link.href = ''
await analytics.trackLink(link!, 'foo')
link.click()
expect(mockTrack).toHaveBeenCalled()
expect(window.location.href).toBe('http://localhost/')
})
it('should work with nested link', async () => {
const nested = document.getElementById('bar')
await analytics.trackLink(nested, 'foo')
nested!.click()
expect(mockTrack).toHaveBeenCalled()
await resolveWhen(() => window.location.href === 'bar.com')
expect(window.location.href).toBe('bar.com')
})
it('should make a track call', async () => {
await analytics.trackLink(link!, 'foo')
link.click()
expect(mockTrack).toHaveBeenCalled()
})
it.only('should still navigate even if the track call fails', async () => {
mockTrack.mockClear()
let rejected = false
mockTrack.mockImplementationOnce(() => {
rejected = true
return Promise.reject(new Error('boo!'))
})
const nested = document.getElementById('bar')
await analytics.trackLink(nested, 'foo')
nested!.click()
await resolveWhen(() => rejected)
await resolveWhen(() => window.location.href === 'bar.com')
expect(window.location.href).toBe('bar.com')
})
it('should still navigate even if the track call times out', async () => {
mockTrack.mockClear()
let timedOut = false
mockTrack.mockImplementationOnce(async () => {
await sleep(600)
timedOut = true
return Promise.resolve() as any
})
const nested = document.getElementById('bar')
await analytics.trackLink(nested, 'foo')
nested!.click()
await resolveWhen(() => window.location.href === 'bar.com')
expect(window.location.href).toBe('bar.com')
expect(timedOut).toBe(false)
await resolveWhen(() => timedOut)
})
it('should accept a jquery object for an element', async () => {
const $link = jQuery(link)
await analytics.trackLink($link, 'foo')
link.click()
expect(mockTrack).toBeCalled()
})
it('accepts array of elements', async () => {
const links = [link, link]
await analytics.trackLink(links, 'foo')
link.click()
expect(mockTrack).toHaveBeenCalled()
})
it('should send an event and properties', async () => {
await analytics.trackLink(link, 'event', { property: true })
link.click()
expect(mockTrack).toBeCalledWith('event', { property: true })
})
it('should accept an event function', async () => {
function event(el: Element): string {
return el.nodeName
}
await analytics.trackLink(link, event, { foo: 'bar' })
link.click()
expect(mockTrack).toBeCalledWith('A', { foo: 'bar' })
})
it('should accept a properties function', async () => {
function properties(el: Record<string, string>): Record<string, string> {
return { type: el.nodeName }
}
await analytics.trackLink(link, 'event', properties)
link.click()
expect(mockTrack).toBeCalledWith('event', { type: 'A' })
})
it('should load an href on click', async () => {
link.href = '#test'
await analytics.trackLink(link, 'foo')
link.click()
await resolveWhen(() => window.location.href === '#test')
expect(global.window.location.href).toBe('#test')
})
it('should only navigate after the track call has been completed', async () => {
link.href = '#test'
await analytics.trackLink(link, 'foo')
link.click()
await resolveWhen(() => mockTrack.mock.calls.length === 1)
await resolveWhen(() => window.location.href === '#test')
expect(global.window.location.href).toBe('#test')
})
it('should support svg .href attribute', async () => {
svg.setAttribute('href', '#svg')
await analytics.trackLink(svg, 'foo')
const clickEvent = new Event('click')
svg.dispatchEvent(clickEvent)
await resolveWhen(() => window.location.href === '#svg')
expect(global.window.location.href).toBe('#svg')
})
it('should fallback to getAttributeNS', async () => {
svg.setAttributeNS('http://www.w3.org/1999/xlink', 'href', '#svg')
await analytics.trackLink(svg, 'foo')
const clickEvent = new Event('click')
svg.dispatchEvent(clickEvent)
await resolveWhen(() => window.location.href === '#svg')
expect(global.window.location.href).toBe('#svg')
})
it('should support xlink:href', async () => {
svg.setAttribute('xlink:href', '#svg')
await analytics.trackLink(svg, 'foo')
const clickEvent = new Event('click')
svg.dispatchEvent(clickEvent)
await resolveWhen(() => window.location.href === '#svg')
expect(global.window.location.href).toBe('#svg')
})
it('should not load an href for a link with a blank target', async () => {
link.href = '/base/test/support/mock.html'
link.target = '_blank'
await analytics.trackLink(link, 'foo')
link.click()
await sleep(300)
expect(global.window.location.href).not.toBe('#test')
})
})
describe('trackForm', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let form: any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let submit: any
const analytics = new Analytics({ writeKey: 'foo' })
let mockTrack = jest.spyOn(analytics, 'track')
beforeEach(() => {
document.querySelector('html')!.innerHTML = `
<html>
<body>
<form target='_blank' action='/base/test/support/mock.html' id='form'>
<input type='submit' id='submit'/>
</form>
</body>
</html>`
form = document.getElementById('form')
submit = document.getElementById('submit')
// @ts-ignore
global.jQuery = require('jquery')
mockTrack = jest.spyOn(analytics, 'track')
// eslint-disable-next-line @typescript-eslint/unbound-method
mockTrack.mockImplementation(Analytics.prototype.track)
})
afterEach(() => {
window.location.hash = ''
document.body.removeChild(form)
})
it('should not error or send track event on null form', async () => {
const form = document.getElementById('fake-form') as HTMLFormElement
await analytics.trackForm(form, 'Signed Up', {
plan: 'Premium',
revenue: 99.0,
})
submit.click()
expect(mockTrack).not.toBeCalled()
})
it('should trigger a track on a form submit', async () => {
await analytics.trackForm(form, 'foo')
submit.click()
expect(mockTrack).toBeCalled()
})
it('should accept a jquery object for an element', async () => {
await analytics.trackForm(form, 'foo')
submit.click()
expect(mockTrack).toBeCalled()
})
it('should not accept a string for an element', async () => {
try {
// @ts-expect-error
await analytics.trackForm('foo')
submit.click()
} catch (e) {
expect(e instanceof TypeError).toBe(true)
}
expect(mockTrack).not.toBeCalled()
})
it('should send an event and properties', async () => {
await analytics.trackForm(form, 'event', { property: true })
submit.click()
expect(mockTrack).toBeCalledWith('event', { property: true })
})
it('should accept an event function', async () => {
function event(): string {
return 'event'
}
await analytics.trackForm(form, event, { foo: 'bar' })
submit.click()
expect(mockTrack).toBeCalledWith('event', { foo: 'bar' })
})
it('should accept a properties function', async () => {
function properties(): Record<string, boolean> {
return { property: true }
}
await analytics.trackForm(form, 'event', properties)
submit.click()
expect(mockTrack).toBeCalledWith('event', { property: true })
})
it('should call submit after a timeout', async (done) => {
const submitSpy = jest.spyOn(form, 'submit')
const mockedTrack = jest.fn()
// eslint-disable-next-line @typescript-eslint/unbound-method
mockedTrack.mockImplementation(Analytics.prototype.track)
analytics.track = mockedTrack
await analytics.trackForm(form, 'foo')
submit.click()
setTimeout(function () {
expect(submitSpy).toHaveBeenCalled()
done()
}, 500)
})
it('should trigger an existing submit handler', async (done) => {
form.addEventListener('submit', () => {
done()
})
await analytics.trackForm(form, 'foo')
submit.click()
})
it('should trigger an existing jquery submit handler', async (done) => {
const $form = jQuery(form)
$form.submit(function () {
done()
})
await analytics.trackForm(form, 'foo')
submit.click()
})
it('should track on a form submitted via jquery', async () => {
const $form = jQuery(form)
await analytics.trackForm(form, 'foo')
$form.submit()
expect(mockTrack).toBeCalled()
})
it('should trigger an existing jquery submit handler on a form submitted via jquery', async (done) => {
const $form = jQuery(form)
$form.submit(function () {
done()
})
await analytics.trackForm(form, 'foo')
$form.submit()
})
})
}) | the_stack |
import { IPdfWriter } from './../../interfaces/i-pdf-writer';
import { PdfStream } from './../primitives/pdf-stream';
import { Operators } from './pdf-operators';
import { PdfNumber } from './../primitives/pdf-number';
import { PointF, RectangleF } from './../drawing/pdf-drawing';
import { TextRenderingMode, PdfLineCap, PdfLineJoin, PdfColorSpace } from './../graphics/enum';
import { PdfString } from './../primitives/pdf-string';
import { PdfName } from './../primitives/pdf-name';
import { PdfFont } from './../graphics/fonts/pdf-font';
import { PdfTransformationMatrix } from './../graphics/pdf-transformation-matrix';
import { PdfColor } from './../graphics/pdf-color';
import { PdfArray } from './../primitives/pdf-array';
import { PdfDocument } from './../document/pdf-document';
/**
* Helper class to `write PDF graphic streams` easily.
* @private
*/
export class PdfStreamWriter implements IPdfWriter {
//Fields
/**
* The PDF `stream` where the data should be write into.
* @private
*/
private stream : PdfStream;
/**
* Initialize an instance of `PdfStreamWriter` class.
* @private
*/
public constructor(stream : PdfStream) {
if (stream == null) {
throw new Error('ArgumentNullException:stream');
}
this.stream = stream;
}
//Implementation
/**
* `Clear` the stream.
* @public
*/
public clear() : void {
this.stream.clearStream();
}
/**
* Sets the `graphics state`.
* @private
*/
public setGraphicsState(dictionaryName : PdfName) : void
/**
* Sets the `graphics state`.
* @private
*/
public setGraphicsState(dictionaryName : string) : void
public setGraphicsState(dictionaryName : PdfName|string) : void {
if (dictionaryName instanceof PdfName) {
this.stream.write(dictionaryName.toString());
this.stream.write(Operators.whiteSpace);
this.writeOperator(Operators.setGraphicsState);
} else {
this.stream.write(Operators.slash);
this.stream.write(dictionaryName);
this.stream.write(Operators.whiteSpace);
this.writeOperator(Operators.setGraphicsState);
}
}
/**
* `Executes the XObject`.
* @private
*/
public executeObject(name : PdfName) : void {
this.stream.write(name.toString());
this.stream.write(Operators.whiteSpace);
this.writeOperator(Operators.paintXObject);
this.stream.write(Operators.newLine);
}
/**
* `Closes path object`.
* @private
*/
public closePath() : void {
this.writeOperator(Operators.closePath);
}
/**
* `Clips the path`.
* @private
*/
public clipPath(useEvenOddRule : boolean) : void {
this.stream.write(Operators.clipPath);
if (useEvenOddRule) {
this.stream.write(Operators.evenOdd);
}
this.stream.write(Operators.whiteSpace);
this.stream.write(Operators.endPath);
this.stream.write(Operators.newLine);
}
/**
* `Closes, then fills and strokes the path`.
* @private
*/
public closeFillStrokePath(useEvenOddRule : boolean) : void {
this.stream.write(Operators.closeFillStrokePath);
if (useEvenOddRule) {
this.stream.write(Operators.evenOdd);
this.stream.write(Operators.newLine);
} else {
this.stream.write(Operators.newLine);
}
}
/**
* `Fills and strokes path`.
* @private
*/
public fillStrokePath(useEvenOddRule : boolean) : void {
this.stream.write(Operators.fillStroke);
if (useEvenOddRule) {
this.stream.write(Operators.evenOdd);
this.stream.write(Operators.newLine);
} else {
this.stream.write(Operators.newLine);
}
}
/**
* `Fills path`.
* @private
*/
public fillPath(useEvenOddRule : boolean) : void {
this.stream.write(Operators.fill);
if (useEvenOddRule) {
this.stream.write(Operators.evenOdd);
this.stream.write(Operators.newLine);
} else {
this.stream.write(Operators.newLine);
}
}
/**
* `Ends the path`.
* @private
*/
public endPath() : void {
this.writeOperator(Operators.n);
}
/**
* `Closes and fills the path`.
* @private
*/
public closeFillPath(useEvenOddRule : boolean) : void {
this.writeOperator(Operators.closePath);
this.stream.write(Operators.fill);
if (useEvenOddRule) {
this.stream.write(Operators.evenOdd);
this.stream.write(Operators.newLine);
} else {
this.stream.write(Operators.newLine);
}
}
/**
* `Closes and strokes the path`.
* @private
*/
public closeStrokePath() : void {
this.writeOperator(Operators.closeStrokePath);
}
/**
* `Sets the text scaling`.
* @private
*/
public setTextScaling(textScaling : number) : void {
this.stream.write(PdfNumber.floatToString(textScaling));
this.stream.write(Operators.whiteSpace);
this.writeOperator(Operators.setTextScaling);
}
/**
* `Strokes path`.
* @private
*/
public strokePath() : void {
this.writeOperator(Operators.stroke);
}
/**
* `Restores` the graphics state.
* @private
*/
public restoreGraphicsState() : void {
this.writeOperator(Operators.restoreState);
}
/**
* `Saves` the graphics state.
* @private
*/
public saveGraphicsState() : void {
this.writeOperator(Operators.saveState);
}
/**
* `Shifts the text to the point`.
* @private
*/
public startNextLine() : void
/**
* `Shifts the text to the point`.
* @private
*/
public startNextLine(point : PointF) : void
/**
* `Shifts the text to the point`.
* @private
*/
public startNextLine(x : number, y : number) : void
public startNextLine(arg1 ?: PointF | number, arg2 ?: number) : void {
if (typeof arg1 === 'undefined') {
this.writeOperator(Operators.goToNextLine);
} else if (arg1 instanceof PointF) {
this.writePoint(arg1);
this.writeOperator(Operators.setCoords);
} else {
this.writePoint(arg1, arg2);
this.writeOperator(Operators.setCoords);
}
}
/**
* Shows the `text`.
* @private
*/
public showText(text : PdfString) : void {
this.checkTextParam(text);
this.writeText(text);
this.writeOperator(Operators.setText);
}
/**
* Sets `text leading`.
* @private
*/
public setLeading(leading : number) : void {
this.stream.write(PdfNumber.floatToString(leading));
this.stream.write(Operators.whiteSpace);
this.writeOperator(Operators.setTextLeading);
}
/**
* `Begins the path`.
* @private
*/
public beginPath(x : number, y : number) : void {
this.writePoint(x, y);
this.writeOperator(Operators.beginPath);
}
/**
* `Begins text`.
* @private
*/
public beginText() : void {
this.writeOperator(Operators.beginText);
}
/**
* `Ends text`.
* @private
*/
public endText() : void {
this.writeOperator(Operators.endText);
}
/**
* `Appends the rectangle`.
* @private
*/
public appendRectangle(rectangle : RectangleF) : void
/**
* `Appends the rectangle`.
* @private
*/
public appendRectangle(x : number, y : number, width : number, height : number) : void
public appendRectangle(arg1 : number|RectangleF, arg2 ?: number, arg3 ?: number, arg4 ?: number) : void {
if (arg1 instanceof RectangleF) {
this.appendRectangle(arg1.x, arg1.y, arg1.width, arg1.height);
} else {
this.writePoint(arg1 as number, arg2);
this.writePoint(arg3, arg4);
this.writeOperator(Operators.appendRectangle);
}
}
/**
* `Appends a line segment`.
* @private
*/
public appendLineSegment(point : PointF) : void
/**
* `Appends a line segment`.
* @private
*/
public appendLineSegment(x : number, y : number) : void
public appendLineSegment(arg1 : number | PointF, arg2 ?: number) : void {
if (arg1 instanceof PointF) {
this.appendLineSegment(arg1.x, arg1.y);
} else {
this.writePoint(arg1, arg2);
this.writeOperator(Operators.appendLineSegment);
}
}
/**
* Sets the `text rendering mode`.
* @private
*/
public setTextRenderingMode(renderingMode : TextRenderingMode) : void {
this.stream.write((<number>renderingMode).toString());
this.stream.write(Operators.whiteSpace);
this.writeOperator(Operators.setRenderingMode);
}
/**
* Sets the `character spacing`.
* @private
*/
public setCharacterSpacing(charSpacing : number) : void {
this.stream.write(PdfNumber.floatToString(charSpacing));
this.stream.write(Operators.whiteSpace);
this.stream.write(Operators.setCharacterSpace);
this.stream.write(Operators.newLine);
}
/**
* Sets the `word spacing`.
* @private
*/
public setWordSpacing(wordSpacing : number) : void {
this.stream.write(PdfNumber.floatToString(wordSpacing));
this.stream.write(Operators.whiteSpace);
this.writeOperator(Operators.setWordSpace);
}
// public showNextLineText(text : number[], hex : boolean) : void
/**
* Shows the `next line text`.
* @private
*/
public showNextLineText(text : string, hex : boolean) : void
/**
* Shows the `next line text`.
* @private
*/
public showNextLineText(text : PdfString) : void
public showNextLineText(arg1 ?: PdfString|string , arg2 ?: boolean) : void {
if (arg1 instanceof PdfString) {
this.checkTextParam(arg1);
this.writeText(arg1);
this.writeOperator(Operators.setTextOnNewLine);
} else {
this.checkTextParam(arg1);
this.writeText(arg1, arg2);
this.writeOperator(Operators.setTextOnNewLine);
}
}
/**
* Set the `color space`.
* @private
*/
public setColorSpace(name : string, forStroking : boolean) : void
/**
* Set the `color space`.
* @private
*/
public setColorSpace(name : PdfName, forStroking : boolean) : void
public setColorSpace(arg1 : PdfName|string, arg2 : boolean|PdfName) : void {
if (arg1 instanceof PdfName && typeof arg2 === 'boolean') {
let temparg1 : PdfName = arg1 as PdfName;
let temparg2 : boolean = arg2 as boolean;
// if (temparg1 == null) {
// throw new Error('ArgumentNullException:name');
// }
let op : string = (temparg2) ? Operators.selectcolorspaceforstroking : Operators.selectcolorspacefornonstroking;
this.stream.write(temparg1.toString());
this.stream.write(Operators.whiteSpace);
this.stream.write(op);
this.stream.write(Operators.newLine);
} else {
let temparg1 : string = arg1 as string;
let temparg2 : boolean = arg2 as boolean;
this.setColorSpace(new PdfName(temparg1), temparg2);
}
}
/**
* Modifies current `transformation matrix`.
* @private
*/
public modifyCtm(matrix : PdfTransformationMatrix) : void {
if (matrix == null) {
throw new Error('ArgumentNullException:matrix');
}
this.stream.write(matrix.toString());
this.stream.write(Operators.whiteSpace);
this.writeOperator(Operators.modifyCtm);
}
/**
* Sets `font`.
* @private
*/
public setFont(font : PdfFont, name : string, size : number) : void
/**
* Sets `font`.
* @private
*/
public setFont(font : PdfFont, name : PdfName, size : number) : void
public setFont(font : PdfFont, name : PdfName|string, size : number) : void {
if (typeof name === 'string') {
this.setFont(font, new PdfName(name), size);
} else {
if (font == null) {
throw new Error('ArgumentNullException:font');
}
this.stream.write(name.toString());
this.stream.write(Operators.whiteSpace);
this.stream.write(PdfNumber.floatToString(size));
this.stream.write(Operators.whiteSpace);
this.writeOperator(Operators.setFont);
}
}
/**
* `Writes the operator`.
* @private
*/
private writeOperator(opcode : string) : void {
this.stream.write(opcode);
this.stream.write(Operators.newLine);
}
/**
* Checks the `text param`.
* @private
*/
private checkTextParam(text : string) : void
/**
* Checks the `text param`.
* @private
*/
private checkTextParam(text : PdfString) : void
private checkTextParam(text : PdfString|string) : void {
if (text == null) {
throw new Error('ArgumentNullException:text');
}
if (typeof text === 'string' && text === '') {
throw new Error('ArgumentException:The text can not be an empty string, text');
}
}
/**
* `Writes the text`.
* @private
*/
private writeText(text : string, hex : boolean) : void
/**
* `Writes the text`.
* @private
*/
private writeText(text : PdfString) : void
private writeText(arg1 : PdfString|string, arg2 ?: boolean) : void {
if ((arg1 instanceof PdfString) && (typeof arg2 === 'undefined')) {
this.stream.write(arg1.pdfEncode());
} else {
let start : string;
let end : string;
if (arg2) {
start = PdfString.hexStringMark[0];
end = PdfString.hexStringMark[1];
} else {
start = PdfString.stringMark[0];
end = PdfString.stringMark[1];
}
this.stream.write(start);
this.stream.write(arg1 as string);
this.stream.write(end);
}
}
/**
* `Writes the point`.
* @private
*/
private writePoint(point : PointF) : void
/**
* `Writes the point`.
* @private
*/
private writePoint(x : number, y : number) : void
private writePoint(arg1 : number|PointF, arg2 ?: number) : void {
if ((arg1 instanceof PointF) && (typeof arg2 === 'undefined')) {
this.writePoint(arg1.x, arg1.y);
} else {
let temparg1 : number = arg1 as number;
this.stream.write(PdfNumber.floatToString(temparg1));
this.stream.write(Operators.whiteSpace);
// NOTE: Change Y co-ordinate because we shifted co-ordinate system only.
arg2 = this.updateY(arg2);
this.stream.write(PdfNumber.floatToString(arg2));
this.stream.write(Operators.whiteSpace);
}
}
/**
* `Updates y` co-ordinate.
* @private
*/
public updateY(arg : number) : number {
return -arg;
}
/**
* `Writes string` to the file.
* @private
*/
public write(string : string) : void {
let builder : string = '';
builder += string;
builder += Operators.newLine;
this.writeOperator(builder);
}
/**
* `Writes comment` to the file.
* @private
*/
public writeComment(comment : string) : void {
if (comment != null && comment.length > 0) {
let builder : string = '';
builder += Operators.comment;
builder += Operators.whiteSpace;
builder += comment;
//builder.Append( Operators.NewLine );
this.writeOperator(builder);
} else {
throw new Error('Invalid comment');
}
}
/**
* Sets the `color and space`.
* @private
*/
public setColorAndSpace(color : PdfColor, colorSpace : PdfColorSpace, forStroking : boolean) : void {
if (!color.isEmpty) {
// bool test = color is PdfExtendedColor;
this.stream.write(color.toString(colorSpace, forStroking));
this.stream.write(Operators.newLine);
}
}
// public setLineDashPattern(pattern : number[], patternOffset : number) : void
// {
// let pat : PdfArray = new PdfArray(pattern);
// let off : PdfNumber = new PdfNumber(patternOffset);
// this.setLineDashPatternHelper(pat, off);
// }
// private setLineDashPatternHelper(pattern : PdfArray, patternOffset : PdfNumber) : void
// {
// pattern.Save(this);
// this.m_stream.write(Operators.whiteSpace);
// patternOffset.Save(this);
// this.m_stream.write(Operators.whiteSpace);
// this.writeOperator(Operators.setDashPattern);
// }
/**
* Sets the `line dash pattern`.
* @private
*/
public setLineDashPattern(pattern : number[], patternOffset : number) : void {
// let pat : PdfArray = new PdfArray(pattern);
// let off : PdfNumber = new PdfNumber(patternOffset);
// this.setLineDashPatternHelper(pat, off);
this.setLineDashPatternHelper(pattern, patternOffset);
}
/**
* Sets the `line dash pattern`.
* @private
*/
private setLineDashPatternHelper(pattern : number[], patternOffset : number) : void {
let tempPattern : string = '[';
if (pattern.length > 1) {
for (let index : number = 0; index < pattern.length; index++) {
if (index === pattern.length - 1) {
tempPattern += pattern[index].toString();
} else {
tempPattern += pattern[index].toString() + ' ';
}
}
}
tempPattern += '] ';
tempPattern += patternOffset.toString();
tempPattern += ' ' + Operators.setDashPattern;
this.stream.write(tempPattern);
this.stream.write(Operators.newLine);
}
/**
* Sets the `miter limit`.
* @private
*/
public setMiterLimit(miterLimit : number) : void {
this.stream.write(PdfNumber.floatToString(miterLimit));
this.stream.write(Operators.whiteSpace);
this.writeOperator(Operators.setMiterLimit);
}
/**
* Sets the `width of the line`.
* @private
*/
public setLineWidth(width : number) : void {
this.stream.write(PdfNumber.floatToString(width));
this.stream.write(Operators.whiteSpace);
this.writeOperator(Operators.setLineWidth);
}
/**
* Sets the `line cap`.
* @private
*/
public setLineCap(lineCapStyle : PdfLineCap) : void {
this.stream.write((lineCapStyle).toString());
this.stream.write(Operators.whiteSpace);
this.writeOperator(Operators.setLineCapStyle);
}
/**
* Sets the `line join`.
* @private
*/
public setLineJoin(lineJoinStyle : PdfLineJoin) : void {
this.stream.write((lineJoinStyle).toString());
this.stream.write(Operators.whiteSpace);
this.writeOperator(Operators.setLineJoinStyle);
}
//IPdfWriter members
/**
* Gets or sets the current `position` within the stream.
* @private
*/
public get position() : number {
return this.stream.position;
}
/**
* Gets `stream length`.
* @private
*/
public get length() : number {
let returnValue : number = 0;
if (this.stream.data.length !== 0 && this.stream.data.length !== -1) {
for (let index : number = 0; index < this.stream.data.length; index++) {
returnValue += this.stream.data[index].length;
}
}
return returnValue;
}
/**
* Gets and Sets the `current document`.
* @private
*/
public get document() : PdfDocument {
return null;
}
/**
* `Appends a line segment`.
* @public
*/
public appendBezierSegment(arg1 : PointF, arg2 : PointF, arg3 : PointF) : void
public appendBezierSegment(x1 : number, y1 : number, x2 : number, y2 : number, x3 : number, y3 : number ) : void
/* tslint:disable-next-line:max-line-length */
public appendBezierSegment(arg1 : number|PointF, arg2 : number|PointF, arg3 : number|PointF, arg4 ?: number, arg5 ?: number, arg6 ?: number ) : void {
if (arg1 instanceof PointF && arg2 instanceof PointF && arg3 instanceof PointF) {
this.writePoint(arg1.x, arg1.y);
this.writePoint(arg2.x, arg2.y);
this.writePoint(arg3.x, arg3.y);
} else {
this.writePoint(arg1 as number, arg2 as number);
this.writePoint(arg3 as number, arg4 as number);
this.writePoint(arg5 as number, arg6 as number);
}
this.writeOperator(Operators.appendbeziercurve);
}
public setColourWithPattern(colours: number[], patternName: PdfName, forStroking: boolean) : void {
if ((colours != null)) {
let count: number = colours.length;
let i : number = 0;
for (i = 0; i < count; ++i) {
this.stream.write(colours[i].toString());
this.stream.write(Operators.whiteSpace);
}
}
if ((patternName != null)) {
this.stream.write(patternName.toString());
this.stream.write(Operators.whiteSpace);
}
if (forStroking) {
this.writeOperator(Operators.setColorAndPatternStroking);
} else {
this.writeOperator(Operators.setColorAndPattern);
}
}
} | the_stack |
import { createConnection, getConnection } from 'typeorm';
import { ReportAudit } from '../entity/ReportAudit';
import { User } from '../entity/User';
import { Assessment } from '../entity/Assessment';
import { Organization } from '../entity/Organization';
import { Vulnerability } from '../entity/Vulnerability';
import { Asset } from '../entity/Asset';
import { ProblemLocation } from '../entity/ProblemLocation';
import { Resource } from '../entity/Resource';
import { File } from '../entity/File';
import { Jira } from '../entity/Jira';
import { Team } from '../entity/Team';
import { v4 as uuidv4 } from 'uuid';
import { generateHash } from '../utilities/password.utility';
import MockExpressRequest = require('mock-express-request');
import MockExpressResponse = require('mock-express-response');
import { ROLE } from '../enums/roles-enum';
import { status } from '../enums/status-enum';
import { ApiKey } from '../entity/ApiKey';
import {
createTeam,
addTeamMember,
removeTeamMember,
deleteTeam,
updateTeamInfo,
getMyTeams,
addTeamAsset,
removeTeamAsset,
getAllTeams,
} from '../routes/team.controller';
describe('Team Controller', () => {
beforeEach(() => {
return createConnection({
type: 'sqlite',
database: ':memory:',
dropSchema: true,
entities: [
ReportAudit,
User,
File,
Assessment,
Asset,
Organization,
Jira,
Vulnerability,
ProblemLocation,
Resource,
Team,
ApiKey,
],
synchronize: true,
logging: false,
});
});
afterEach(() => {
const conn = getConnection();
return conn.close();
});
test('Create Team', async () => {
const existUser = new User();
existUser.firstName = 'master';
existUser.lastName = 'chief';
existUser.email = 'testing@jest.com';
existUser.active = true;
const uuid = uuidv4();
existUser.uuid = uuid;
existUser.password = await generateHash('TangoDown123!!!');
const savedUser = await getConnection().getRepository(User).save(existUser);
const newOrg: Organization = {
id: null,
name: 'Test Org',
status: status.active,
asset: null,
teams: null,
};
const savedOrg = await getConnection()
.getRepository(Organization)
.save(newOrg);
// create assets
const asset: Asset = {
organization: savedOrg,
name: 'Test Asset 1',
status: 'A',
id: null,
jira: null,
assessment: null,
teams: null,
};
const savedAsset = await getConnection().getRepository(Asset).save(asset);
const asset2: Asset = {
organization: savedOrg,
name: 'Test Asset 1',
status: 'A',
id: null,
jira: null,
assessment: null,
teams: null,
};
const savedAsset2 = await getConnection().getRepository(Asset).save(asset2);
const asset3: Asset = {
organization: savedOrg,
name: 'Test Asset 1',
status: 'A',
id: null,
jira: null,
assessment: null,
teams: null,
};
const savedAsset3 = await getConnection().getRepository(Asset).save(asset3);
const assetAry: Asset[] = [];
const request = new MockExpressRequest({
body: {
id: null,
name: 'Test Team',
organization: savedOrg.id,
asset: null,
role: ROLE.ADMIN,
assetIds: [savedAsset.id, savedAsset2.id],
users: [savedUser.id],
},
user: savedUser.id,
});
const response = new MockExpressResponse();
await createTeam(request, response);
expect(response.statusCode).toBe(200);
const teams = await getConnection()
.getRepository(Team)
.find({ relations: ['users', 'assets'] });
expect(teams.length).toBe(1);
expect(teams[0].users.length).toBe(1);
expect(teams[0].assets.length).toBe(2);
});
test('Create Team Failure', async () => {
const existUser = new User();
existUser.firstName = 'master';
existUser.lastName = 'chief';
existUser.email = 'testing@jest.com';
existUser.active = true;
const uuid = uuidv4();
existUser.uuid = uuid;
existUser.password = await generateHash('TangoDown123!!!');
const savedUser = await getConnection().getRepository(User).save(existUser);
const newOrg: Organization = {
id: null,
name: 'Test Org',
status: status.active,
asset: null,
teams: null,
};
const savedOrg = await getConnection()
.getRepository(Organization)
.save(newOrg);
const badRequest = new MockExpressRequest({
params: {
id: 1,
},
body: {
id: null,
name: 'test',
organization: savedOrg.id,
asset: null,
role: 'not a role',
users: [],
},
user: savedUser.id,
});
const badResponse = new MockExpressResponse();
await createTeam(badRequest, badResponse);
expect(badResponse.statusCode).toBe(400);
const teams = await getConnection().getRepository(Team).find({});
expect(teams.length).toBe(0);
const badRequest2 = new MockExpressRequest({
params: {
id: 1,
},
body: {
id: null,
name: 'test',
organization: 3,
asset: null,
role: 'not a role',
users: [],
},
user: savedUser.id,
});
const badResponse2 = new MockExpressResponse();
await createTeam(badRequest2, badResponse2);
expect(badResponse2.statusCode).toBe(404);
});
test('add team member', async () => {
// create org
const newOrg: Organization = {
id: null,
name: 'Test Org',
status: status.active,
asset: null,
teams: null,
};
const savedOrg = await getConnection()
.getRepository(Organization)
.save(newOrg);
// user 1
const teamMember1 = new User();
teamMember1.firstName = 'master';
teamMember1.lastName = 'chief';
teamMember1.email = 'testing1@jest.com';
teamMember1.active = true;
const uuid = uuidv4();
teamMember1.uuid = uuid;
teamMember1.password = await generateHash('TangoDown123!!!');
const addedUser1 = await getConnection()
.getRepository(User)
.save(teamMember1);
// user 2
const teamMember2 = new User();
teamMember2.firstName = 'master';
teamMember2.lastName = 'chief';
teamMember2.email = 'testing2@jest.com';
teamMember2.active = true;
const uuid2 = uuidv4();
teamMember2.uuid = uuid2;
teamMember2.password = await generateHash('TangoDown123!!!');
const addedUser2 = await getConnection()
.getRepository(User)
.save(teamMember2);
// user 3
const teamMember3 = new User();
teamMember3.firstName = 'master';
teamMember3.lastName = 'chief';
teamMember3.email = 'testing3@jest.com';
teamMember3.active = true;
const uuid3 = uuidv4();
teamMember3.uuid = uuid3;
teamMember3.password = await generateHash('TangoDown123!!!');
const addedUser3 = await getConnection()
.getRepository(User)
.save(teamMember3);
// create team
const bravoTeam = new Team();
bravoTeam.name = 'Bravo';
bravoTeam.organization = savedOrg;
bravoTeam.id = null;
bravoTeam.createdDate = new Date();
bravoTeam.lastUpdatedDate = new Date();
bravoTeam.createdBy = 0;
bravoTeam.lastUpdatedBy = 0;
bravoTeam.role = ROLE.READONLY;
const savedTeam = await getConnection().getRepository(Team).save(bravoTeam);
const request = new MockExpressRequest({
body: {
userIds: [1, 2, 3],
teamId: savedTeam.id,
},
});
const response = new MockExpressResponse();
await addTeamMember(request, response);
expect(response.statusCode).toBe(200);
const badRequest2 = new MockExpressRequest({
body: {
userIds: [1, 2, 3],
teamId: 'lol',
},
});
const badResponse2 = new MockExpressResponse();
await addTeamMember(badRequest2, badResponse2);
expect(badResponse2.statusCode).toBe(404);
const badRequest3 = new MockExpressRequest({
body: {
userIds: [1, 2, 3],
},
});
const badResponse3 = new MockExpressResponse();
await addTeamMember(badRequest3, badResponse3);
expect(badResponse3.statusCode).toBe(400);
const team = await getConnection()
.getRepository(Team)
.findOne(savedTeam.id, { relations: ['users'] });
expect(team.users.length).toBe(3);
});
test('remove team member', async () => {
// create org
const newOrg: Organization = {
id: null,
name: 'Test Org',
status: status.active,
asset: null,
teams: null,
};
const savedOrg = await getConnection()
.getRepository(Organization)
.save(newOrg);
// user 1
const teamMember1 = new User();
teamMember1.firstName = 'master';
teamMember1.lastName = 'chief';
teamMember1.email = 'testing1@jest.com';
teamMember1.active = true;
const uuid = uuidv4();
teamMember1.uuid = uuid;
teamMember1.password = await generateHash('TangoDown123!!!');
const addedUser1 = await getConnection()
.getRepository(User)
.save(teamMember1);
// user 2
const teamMember2 = new User();
teamMember2.firstName = 'master';
teamMember2.lastName = 'chief';
teamMember2.email = 'testing2@jest.com';
teamMember2.active = true;
const uuid2 = uuidv4();
teamMember2.uuid = uuid2;
teamMember2.password = await generateHash('TangoDown123!!!');
const addedUser2 = await getConnection()
.getRepository(User)
.save(teamMember2);
// user 3
const teamMember3 = new User();
teamMember3.firstName = 'master';
teamMember3.lastName = 'chief';
teamMember3.email = 'testing3@jest.com';
teamMember3.active = true;
const uuid3 = uuidv4();
teamMember3.uuid = uuid3;
teamMember3.password = await generateHash('TangoDown123!!!');
const addedUser3 = await getConnection()
.getRepository(User)
.save(teamMember3);
// create team
const bravoTeam = new Team();
bravoTeam.name = 'Bravo';
bravoTeam.organization = savedOrg;
bravoTeam.id = null;
bravoTeam.createdDate = new Date();
bravoTeam.lastUpdatedDate = new Date();
bravoTeam.createdBy = 0;
bravoTeam.lastUpdatedBy = 0;
bravoTeam.role = ROLE.READONLY;
const savedTeam = await getConnection().getRepository(Team).save(bravoTeam);
let fetchTeam = await getConnection()
.getRepository(Team)
.findOne(savedTeam.id, { relations: ['users'] });
expect(fetchTeam.users.length).toBe(0);
fetchTeam.users.push(addedUser1, addedUser2, addedUser3);
fetchTeam = await getConnection().getRepository(Team).save(fetchTeam);
fetchTeam = await getConnection()
.getRepository(Team)
.findOne(fetchTeam.id, { relations: ['users'] });
expect(fetchTeam.users.length).toBe(3);
const request = new MockExpressRequest({
body: {
userIds: [1],
teamId: savedTeam.id,
},
});
const response = new MockExpressResponse();
await removeTeamMember(request, response);
expect(response.statusCode).toBe(200);
fetchTeam = await getConnection()
.getRepository(Team)
.findOne(fetchTeam.id, { relations: ['users'] });
expect(fetchTeam.users.length).toBe(2);
const badRequest = new MockExpressRequest({
body: {
userIds: [1],
},
});
const badResponse = new MockExpressResponse();
await removeTeamMember(badRequest, badResponse);
expect(badResponse.statusCode).toBe(400);
const badRequest2 = new MockExpressRequest({
body: {
userIds: [1],
teamId: 6,
},
});
const badResponse2 = new MockExpressResponse();
await removeTeamMember(badRequest2, badResponse2);
expect(badResponse2.statusCode).toBe(404);
const badRequest3 = new MockExpressRequest({
body: {
userIds: [2, 6],
teamId: savedTeam.id,
},
});
const badResponse3 = new MockExpressResponse();
await removeTeamMember(badRequest3, badResponse3);
expect(badResponse3.statusCode).toBe(404);
});
test('update team info', async () => {
// create user
const existUser = new User();
existUser.firstName = 'master';
existUser.lastName = 'chief';
existUser.email = 'testing@jest.com';
existUser.active = true;
const uuid = uuidv4();
existUser.uuid = uuid;
existUser.password = await generateHash('TangoDown123!!!');
const savedUser = await getConnection().getRepository(User).save(existUser);
// create user
const existUser2 = new User();
existUser2.firstName = 'master';
existUser2.lastName = 'chief';
existUser2.email = 'testing2@jest.com';
existUser2.active = true;
const uuid2 = uuidv4();
existUser2.uuid = uuid2;
existUser2.password = await generateHash('TangoDown123!!!');
const savedUser2 = await getConnection()
.getRepository(User)
.save(existUser2);
// create org
const newOrg: Organization = {
id: null,
name: 'Test Org',
status: status.active,
asset: null,
teams: null,
};
const savedOrg = await getConnection()
.getRepository(Organization)
.save(newOrg);
// create assets
const asset: Asset = {
organization: savedOrg,
name: 'Test Asset 1',
status: 'A',
id: null,
jira: null,
assessment: null,
teams: null,
};
const savedAsset = await getConnection().getRepository(Asset).save(asset);
const asset2: Asset = {
organization: savedOrg,
name: 'Test Asset 1',
status: 'A',
id: null,
jira: null,
assessment: null,
teams: null,
};
const savedAsset2 = await getConnection().getRepository(Asset).save(asset2);
const asset3: Asset = {
organization: savedOrg,
name: 'Test Asset 1',
status: 'A',
id: null,
jira: null,
assessment: null,
teams: null,
};
const savedAsset3 = await getConnection().getRepository(Asset).save(asset3);
const assetAry: Asset[] = [];
assetAry.push(savedAsset, savedAsset2);
// create team
const bravoTeam = new Team();
bravoTeam.name = 'Bravo';
bravoTeam.organization = savedOrg;
bravoTeam.id = null;
bravoTeam.createdDate = new Date();
bravoTeam.lastUpdatedDate = new Date();
bravoTeam.createdBy = 0;
bravoTeam.lastUpdatedBy = 0;
bravoTeam.role = ROLE.READONLY;
bravoTeam.assets = assetAry;
bravoTeam.users = [savedUser];
const savedTeam = await getConnection().getRepository(Team).save(bravoTeam);
expect(savedTeam.assets.length).toBe(2);
expect(savedTeam.users.length).toBe(1);
const request = new MockExpressRequest({
body: {
name: 'Alpha',
organization: savedOrg.id,
asset: null,
role: ROLE.TESTER,
id: savedTeam.id,
users: [savedUser, savedUser2],
assetIds: [],
},
});
const response = new MockExpressResponse();
await updateTeamInfo(request, response);
expect(response.statusCode).toBe(200);
const updatedTeam = await getConnection()
.getRepository(Team)
.findOne(savedTeam.id, { relations: ['users', 'assets'] });
expect(updatedTeam.name).toBe('Alpha');
expect(updatedTeam.role).toBe(ROLE.TESTER);
expect(updatedTeam.users.length).toBe(2);
expect(updatedTeam.assets.length).toBe(0);
const badRequest = new MockExpressRequest({
body: {
id: savedTeam.id,
},
});
const badResponse = new MockExpressResponse();
await updateTeamInfo(badRequest, badResponse);
expect(badResponse.statusCode).toBe(400);
const badRequest2 = new MockExpressRequest({
body: {
name: 'Alpha',
organization: savedOrg.id,
assetIds: [],
role: ROLE.TESTER,
},
});
const badResponse2 = new MockExpressResponse();
await updateTeamInfo(badRequest2, badResponse2);
expect(badResponse2.statusCode).toBe(400);
const badRequest3 = new MockExpressRequest({
body: {
name: 'Alpha',
organization: savedOrg.id,
assetIds: [],
role: ROLE.TESTER,
id: 6,
},
});
const badResponse3 = new MockExpressResponse();
await updateTeamInfo(badRequest3, badResponse3);
expect(badResponse3.statusCode).toBe(404);
expect(badResponse2.statusCode).toBe(400);
const badRequest4 = new MockExpressRequest({
body: {
name: 'Alpha',
organization: savedOrg.id,
assetIds: [],
role: 'not a role',
id: savedTeam.id,
},
});
const badResponse4 = new MockExpressResponse();
await updateTeamInfo(badRequest4, badResponse4);
expect(badResponse4.statusCode).toBe(400);
});
test('delete team', async () => {
// create org
const newOrg: Organization = {
id: null,
name: 'Test Org',
status: status.active,
asset: null,
teams: null,
};
const savedOrg = await getConnection()
.getRepository(Organization)
.save(newOrg);
// user 1
const teamMember1 = new User();
teamMember1.firstName = 'master';
teamMember1.lastName = 'chief';
teamMember1.email = 'testing1@jest.com';
teamMember1.active = true;
const uuid = uuidv4();
teamMember1.uuid = uuid;
teamMember1.password = await generateHash('TangoDown123!!!');
const addedUser1 = await getConnection()
.getRepository(User)
.save(teamMember1);
// create team
const bravoTeam = new Team();
bravoTeam.name = 'Bravo';
bravoTeam.organization = savedOrg;
bravoTeam.id = null;
bravoTeam.createdDate = new Date();
bravoTeam.lastUpdatedDate = new Date();
bravoTeam.createdBy = 0;
bravoTeam.lastUpdatedBy = 0;
bravoTeam.role = ROLE.READONLY;
const savedTeam = await getConnection().getRepository(Team).save(bravoTeam);
const fetchTeam = await getConnection()
.getRepository(Team)
.findOne(savedTeam.id, { relations: ['users'] });
fetchTeam.users.push(addedUser1);
const savedTeamWithUser = await getConnection()
.getRepository(Team)
.save(fetchTeam);
const userWithTeam = await getConnection()
.getRepository(User)
.findOne(addedUser1.id, { relations: ['teams'] });
expect(userWithTeam.teams.length).toBe(1);
let teams = await getConnection().getRepository(Team).find({});
expect(teams.length).toBe(1);
const request = new MockExpressRequest({
params: {
teamId: savedTeamWithUser.id,
},
});
const response = new MockExpressResponse();
await deleteTeam(request, response);
expect(response.statusCode).toBe(200);
teams = await getConnection().getRepository(Team).find({});
expect(teams.length).toBe(0);
const userNoTeam = await getConnection()
.getRepository(User)
.findOne(addedUser1.id, { relations: ['teams'] });
expect(userNoTeam.teams.length).toBe(0);
const badRequest = new MockExpressRequest({
params: {},
});
const badResponse = new MockExpressResponse();
await deleteTeam(badRequest, badResponse);
expect(badResponse.statusCode).toBe(400);
const badRequest2 = new MockExpressRequest({
params: {
teamId: 34,
},
});
const badResponse2 = new MockExpressResponse();
await deleteTeam(badRequest2, badResponse2);
expect(badResponse2.statusCode).toBe(404);
});
test('get user teams', async () => {
// create org
const newOrg: Organization = {
id: null,
name: 'Test Org',
status: status.active,
asset: null,
teams: null,
};
const savedOrg = await getConnection()
.getRepository(Organization)
.save(newOrg);
const teamMember1 = new User();
teamMember1.firstName = 'master';
teamMember1.lastName = 'chief';
teamMember1.email = 'testing1@jest.com';
teamMember1.active = true;
const uuid = uuidv4();
teamMember1.uuid = uuid;
teamMember1.password = await generateHash('TangoDown123!!!');
const addedUser1 = await getConnection()
.getRepository(User)
.save(teamMember1);
// Team 1
const bravoTeam = new Team();
bravoTeam.name = 'Bravo';
bravoTeam.organization = savedOrg;
bravoTeam.id = null;
bravoTeam.createdDate = new Date();
bravoTeam.lastUpdatedDate = new Date();
bravoTeam.createdBy = 0;
bravoTeam.lastUpdatedBy = 0;
bravoTeam.role = ROLE.READONLY;
const savedTeam = await getConnection().getRepository(Team).save(bravoTeam);
const fetchTeam = await getConnection()
.getRepository(Team)
.findOne(savedTeam.id, { relations: ['users'] });
fetchTeam.users.push(addedUser1);
await getConnection().getRepository(Team).save(fetchTeam);
// Team 2
const alphaTeam = new Team();
alphaTeam.name = 'Alpha';
alphaTeam.organization = savedOrg;
alphaTeam.id = null;
alphaTeam.createdDate = new Date();
alphaTeam.lastUpdatedDate = new Date();
alphaTeam.createdBy = 0;
alphaTeam.lastUpdatedBy = 0;
alphaTeam.role = ROLE.TESTER;
const savedTeam2 = await getConnection()
.getRepository(Team)
.save(alphaTeam);
const fetchTeam2 = await getConnection()
.getRepository(Team)
.findOne(savedTeam2.id, { relations: ['users'] });
fetchTeam2.users.push(addedUser1);
await getConnection().getRepository(Team).save(fetchTeam2);
const request = new MockExpressRequest({
user: addedUser1.id,
});
const response = new MockExpressResponse();
await getMyTeams(request, response);
expect(response.statusCode).toBe(200);
const userTeams: Team[] = response._getJSON();
expect(userTeams[0].name).toBe(bravoTeam.name);
expect(userTeams[1].name).toBe(alphaTeam.name);
});
test('add asset to team', async () => {
// create org
const newOrg: Organization = {
id: null,
name: 'Test Org',
status: status.active,
asset: null,
teams: null,
};
const savedOrg = await getConnection()
.getRepository(Organization)
.save(newOrg);
const assessments: Assessment[] = [];
const asset1: Asset = {
id: null,
name: 'testAsset1',
status: status.active,
organization: savedOrg,
assessment: assessments,
jira: null,
teams: null,
};
const savedAsset1 = await getConnection().getRepository(Asset).save(asset1);
const asset2: Asset = {
id: null,
name: 'testAsset2',
status: status.active,
organization: savedOrg,
assessment: assessments,
jira: null,
teams: null,
};
const savedAsset2 = await getConnection().getRepository(Asset).save(asset2);
const asset3: Asset = {
id: null,
name: 'testAsset3',
status: status.active,
organization: savedOrg,
assessment: assessments,
jira: null,
teams: null,
};
const savedAsset3 = await getConnection().getRepository(Asset).save(asset3);
// Team 1
const team1 = new Team();
team1.name = 'Bravo';
team1.organization = savedOrg;
team1.id = null;
team1.createdDate = new Date();
team1.lastUpdatedDate = new Date();
team1.createdBy = 0;
team1.lastUpdatedBy = 0;
team1.role = ROLE.READONLY;
const savedTeam = await getConnection().getRepository(Team).save(team1);
const request = new MockExpressRequest({
body: {
assetIds: [savedAsset1.id, savedAsset2.id, savedAsset3.id],
teamId: savedTeam.id,
},
});
const response = new MockExpressResponse();
await addTeamAsset(request, response);
expect(response.statusCode).toBe(200);
const fetchTeam = await getConnection()
.getRepository(Team)
.findOne(savedTeam.id, { relations: ['assets'] });
expect(fetchTeam.assets.length).toBe(3);
const badRequest = new MockExpressRequest({
body: {
assetIds: [savedAsset1.id, savedAsset2.id, savedAsset3.id],
},
});
const badResponse = new MockExpressResponse();
await addTeamAsset(badRequest, badResponse);
expect(badResponse.statusCode).toBe(400);
const badRequest2 = new MockExpressRequest({
body: {
assetIds: [savedAsset1.id, savedAsset2.id, savedAsset3.id],
teamId: 5,
},
});
const badResponse2 = new MockExpressResponse();
await addTeamAsset(badRequest2, badResponse2);
expect(badResponse2.statusCode).toBe(404);
const badRequest3 = new MockExpressRequest({
body: {
assetIds: [savedAsset1.id, savedAsset2.id, 5],
teamId: savedTeam.id,
},
});
const badResponse3 = new MockExpressResponse();
await addTeamAsset(badRequest3, badResponse3);
expect(badResponse3.statusCode).toBe(401);
});
test('remove asset from team', async () => {
// create org
const newOrg: Organization = {
id: null,
name: 'Test Org',
status: status.active,
asset: null,
teams: null,
};
const savedOrg = await getConnection()
.getRepository(Organization)
.save(newOrg);
const assessments: Assessment[] = [];
const asset1: Asset = {
id: null,
name: 'testAsset1',
status: status.active,
organization: savedOrg,
assessment: assessments,
jira: null,
teams: null,
};
const savedAsset1 = await getConnection().getRepository(Asset).save(asset1);
const asset2: Asset = {
id: null,
name: 'testAsset2',
status: status.active,
organization: savedOrg,
assessment: assessments,
jira: null,
teams: null,
};
const savedAsset2 = await getConnection().getRepository(Asset).save(asset2);
const asset3: Asset = {
id: null,
name: 'testAsset3',
status: status.active,
organization: savedOrg,
assessment: assessments,
jira: null,
teams: null,
};
const savedAsset3 = await getConnection().getRepository(Asset).save(asset3);
// Team 1
const team1 = new Team();
team1.name = 'Bravo';
team1.organization = savedOrg;
team1.id = null;
team1.createdDate = new Date();
team1.lastUpdatedDate = new Date();
team1.createdBy = 0;
team1.lastUpdatedBy = 0;
team1.role = ROLE.READONLY;
const savedTeam = await getConnection().getRepository(Team).save(team1);
const fetchTeam = await getConnection()
.getRepository(Team)
.findOne(savedTeam.id, { relations: ['assets'] });
fetchTeam.assets.push(savedAsset1, savedAsset2, savedAsset3);
await getConnection().getRepository(Team).save(fetchTeam);
const fetchTeamWithAssets = await getConnection()
.getRepository(Team)
.findOne(savedTeam.id, { relations: ['assets'] });
expect(fetchTeamWithAssets.assets.length).toBe(3);
const request = new MockExpressRequest({
body: {
assetIds: [savedAsset1.id, savedAsset2.id],
teamId: savedTeam.id,
},
});
const response = new MockExpressResponse();
await removeTeamAsset(request, response);
const fetchTeamWithRemovedAsset = await getConnection()
.getRepository(Team)
.findOne(savedTeam.id, { relations: ['assets'] });
expect(fetchTeamWithRemovedAsset.assets.length).toBe(1);
const badRequest = new MockExpressRequest({
body: {
assetIds: [savedAsset1.id, savedAsset2.id, savedAsset3.id],
},
});
const badResponse = new MockExpressResponse();
await removeTeamAsset(badRequest, badResponse);
expect(badResponse.statusCode).toBe(400);
const badRequest2 = new MockExpressRequest({
body: {
assetIds: [savedAsset1.id, savedAsset2.id, savedAsset3.id],
teamId: 5,
},
});
const badResponse2 = new MockExpressResponse();
await removeTeamAsset(badRequest2, badResponse2);
expect(badResponse2.statusCode).toBe(404);
const badRequest3 = new MockExpressRequest({
body: {
assetIds: [savedAsset1.id, savedAsset2.id, 5],
teamId: savedTeam.id,
},
});
const badResponse3 = new MockExpressResponse();
await removeTeamAsset(badRequest3, badResponse3);
expect(badResponse3.statusCode).toBe(401);
});
test('get all teams', async () => {
const request = new MockExpressRequest({});
const response = new MockExpressResponse();
await getAllTeams(request, response);
const fetchedTeams: Team[] = response._getJSON();
expect(fetchedTeams.length).toBe(0);
});
}); | the_stack |
import http = require('http');
import url = require('url');
import http_client = require('../http_client');
import streamutil = require('../base/streamutil');
import stringutil = require('../base/stringutil');
import vfs = require('./vfs');
import vfs_util = require('./util');
import { defer } from '../base/promise_util';
export const ACCESS_TOKEN = 'dummytoken';
/** VFS which accesses a file system exposed over HTTP
* via a simple REST-like API. It implements a fake OAuth
* authorization endpoint for use in testing.
*
* GET /files/path - Read file
* GET /files/path/ - Read directory. Returns a list of vfs.FileInfo objects
* PUT /files/path - Write file
* PUT /files/path/ - Create directory
* DELETE /files/path - Delete file
*
* GET /auth/authorize - OAuth2 authorization endpoint.
*/
export class Client implements vfs.VFS {
private _credentials: vfs.Credentials;
constructor(public url: string) {}
authURL() {
return `${this.url}/auth/authorize`;
}
credentials(): vfs.Credentials {
return this._credentials;
}
setCredentials(credentials: vfs.Credentials): void {
this._credentials = credentials;
}
accountInfo() {
let account: vfs.AccountInfo = {
userId: '42',
name: 'John Doe',
email: 'john.doe@gmail.com',
};
return Promise.resolve(account);
}
stat(path: string): Promise<vfs.FileInfo> {
// stat() is implemented by listing the parent dir
// and returning the corresponding FileInfo object from
// that
while (stringutil.endsWith(path, '/')) {
path = path.slice(0, path.length - 1);
}
let fileNameSep = path.lastIndexOf('/');
let parentDir = path;
let name = path;
if (fileNameSep != -1) {
name = name.slice(fileNameSep + 1);
parentDir = path.slice(0, fileNameSep);
} else {
parentDir = '';
}
return this.list(parentDir).then(files => {
let matches = files.filter(file => file.name === name);
if (matches.length == 0) {
throw new vfs.VfsError(
vfs.ErrorType.FileNotFound,
`No file ${name} found in ${path}`
);
} else {
return Promise.resolve(matches[0]);
}
});
}
search(
namePattern: string,
cb: (error: Error, files: vfs.FileInfo[]) => any
): void {
vfs_util.searchIn(this, '', namePattern, cb);
}
read(path: string): Promise<string> {
if (stringutil.endsWith(path, '/')) {
return Promise.reject<string>(
new Error(`Cannot read file. ${path} is a directory`)
);
}
return this.request('GET', path).then(reply => {
if (reply.status !== 200) {
throw this.translateError(reply);
} else {
return reply.body;
}
});
}
write(path: string, content: string): Promise<vfs.FileInfo> {
if (stringutil.endsWith(path, '/')) {
return Promise.reject<vfs.FileInfo>(
new Error(`Cannot write file. ${path} is a directory`)
);
}
return this.request('PUT', path, content).then(reply => {
if (reply.status !== 200) {
throw this.translateError(reply);
} else {
return this.stat(path);
}
});
}
list(path: string): Promise<vfs.FileInfo[]> {
if (!stringutil.endsWith(path, '/')) {
path += '/';
}
return this.request('GET', path).then(reply => {
if (reply.status !== 200) {
throw this.translateError(reply);
} else {
return JSON.parse(reply.body);
}
});
}
rm(path: string): Promise<void> {
return this.request('DELETE', path).then(reply => {
if (reply.status !== 200) {
throw this.translateError(reply);
}
});
}
mkpath(path: string): Promise<void> {
if (!stringutil.endsWith(path, '/')) {
path += '/';
}
return this.request('PUT', path, null).then(reply => {
if (reply.status !== 200) {
throw this.translateError(reply);
}
});
}
private translateError(reply: http_client.Reply) {
let errorType = vfs.ErrorType.Other;
switch (reply.status) {
case 401:
// fallthrough
case 403:
errorType = vfs.ErrorType.AuthError;
break;
case 404:
errorType = vfs.ErrorType.FileNotFound;
break;
case 409:
errorType = vfs.ErrorType.Conflict;
break;
}
return new vfs.VfsError(errorType, reply.body);
}
private fileURL(path: string) {
if (!stringutil.startsWith(path, '/')) {
path = `/${path}`;
}
return `${this.url}/files/${path}`;
}
private request(
method: string,
path: string,
data?: any
): Promise<http_client.Reply> {
let requestOpts: http_client.RequestOpts = {
headers: {
['Authentication']: `Bearer ${this._credentials.accessToken}`,
},
};
return http_client.request(
method,
this.fileURL(path),
data,
requestOpts
);
}
}
export interface ServerOptions {
/** Specifies whether HTTP calls must be authenticated via
* an Authentication header.
*/
requireAuthentication?: boolean;
}
/** Exposes an existing file system (eg. a local file system)
* via a REST API for use with HttpVFS
*/
export class Server {
fs: vfs.VFS;
server: http.Server;
options: ServerOptions;
constructor(fs: vfs.VFS, options: ServerOptions = {}) {
this.fs = fs;
this.options = options;
this.server = http.createServer(this.handleRequest.bind(this));
}
listen(port: number): Promise<void> {
var ready = defer<void>();
this.server.listen(port, () => {
ready.resolve(null);
});
this.server.on('clientError', (ex: any) => {
console.log('server client connection err', ex);
});
return ready.promise;
}
close() {
this.server.close();
}
private handleRequest(req: http.ServerRequest, res: http.ServerResponse) {
let parsedURL = url.parse(req.url, true /* parse query string */);
if (parsedURL.pathname.match(/^\/files\//)) {
this.handleFileRequest(req, res);
} else if (parsedURL.pathname === '/auth/authorize') {
// mock OAuth endpoint
let accessToken = ACCESS_TOKEN;
let stateParam = '';
if (parsedURL.query.state) {
stateParam = `&state=${parsedURL.query.state}`;
}
let redirectURL = parsedURL.query.redirect_uri;
if (!redirectURL) {
res.statusCode = 400;
res.end('redirect_uri parameter not specified');
return;
}
res.statusCode = 200;
res.end(
`
<html>
<body>
Authorize app?
<button id="authButton">Authorize</button>
<script>
document.getElementById('authButton').addEventListener('click', function() {
document.location.href = '${redirectURL}#access_token=${accessToken}${
stateParam
}';
});
</script>
</form>
</body>
</html>
`
);
} else {
res.statusCode = 404;
res.end('Unknown route');
}
}
private handleFileRequest(
req: http.ServerRequest,
res: http.ServerResponse
) {
let fail = (err: any) => {
res.statusCode = 400;
res.end(JSON.stringify(err));
};
let done = (content?: any) => {
res.statusCode = 200;
res.end(content, 'binary');
};
res.setHeader('Access-Control-Allow-Origin', '*');
// check for Authentication header if OAuth is enabled
if (
this.options.requireAuthentication &&
req.method !== 'OPTIONS' &&
req.headers['authentication'] !== `Bearer ${ACCESS_TOKEN}`
) {
res.statusCode = 403;
res.end(
JSON.stringify({
error: 'Incorrect or missing access token',
})
);
return;
}
let path = url.parse(req.url).pathname.replace(/^\/files\//, '');
if (req.method == 'GET') {
this.fs
.stat(path)
.then(fileInfo => {
if (fileInfo.isDir) {
this.fs
.list(path)
.then(files => {
done(JSON.stringify(files));
})
.catch(err => {
fail(err);
});
} else {
this.fs
.read(path)
.then(content => {
done(content);
})
.catch(err => {
fail(err);
});
}
})
.catch(err => {
fail(err);
});
} else if (req.method == 'PUT') {
if (stringutil.endsWith(path, '/')) {
this.fs
.mkpath(path)
.then(() => {
done();
})
.catch(err => {
fail(err);
});
} else {
streamutil.readAll(req).then(content => {
this.fs
.write(path, content)
.then(() => {
done();
})
.catch(err => {
fail(err);
});
});
}
} else if (req.method == 'DELETE') {
this.fs
.rm(path)
.then(() => {
done();
})
.catch(err => {
fail(err);
});
} else if (req.method == 'OPTIONS') {
res.setHeader('Access-Control-Allow-Methods', 'GET, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Authentication');
done();
} else {
throw 'Unhandled method ' + req.method;
}
}
}
export const DEFAULT_PORT = 3030;
export const DEFAULT_URL = `http://localhost:${DEFAULT_PORT}`;
function main() {
var nodefs = require('./node');
var port = DEFAULT_PORT;
var dirPath = process.argv[2] || process.cwd();
var server = new Server(new nodefs.FileVFS(dirPath));
server.listen(port).then(() => {
console.log('Exposing %s via HTTP port %d', dirPath, port);
});
}
if (require.main == module) {
main();
} | the_stack |
import { FlagsConfig, SfdxCommand, flags } from '@salesforce/command';
import { Messages } from '@salesforce/core';
import { AnyJson } from '@salesforce/ts-types';
import {
Logger,
RESOURCES,
COMMAND_EXIT_STATUSES
} from "../../modules/components/common_components/logger";
import { RunCommand } from "../../modules/commands_processors/runCommand";
import { Common } from "../../modules/components/common_components/common";
import { CommandInitializationError, SuccessExit, OrgMetadataError, CommandExecutionError, UnresolvableWarning, CommandAbortedByUserError, CommandAbortedByAddOnError } from "../../modules/models/common_models/errors";
import { ADDON_EVENTS } from '../../modules/components/common_components/enumerations';
import { CONSTANTS } from '../../modules/components/common_components/statics';
Messages.importMessagesDirectory(__dirname);
const commandMessages = Messages.loadMessages('sfdmu', 'run');
const resources = Messages.loadMessages('sfdmu', 'resources');
export default class Run extends SfdxCommand {
command: RunCommand;
protected static supportsUsername = true;
protected static requiresUsername = false;
protected static varargs = false;
public static description = commandMessages.getMessage('commandDescription');
public static longDescription = commandMessages.getMessage('commandLongDescription');
// TODO: Add deprecation to the command if neededsfdx sfdmu:
// public static deprecated = {
// version: 47,
// to: 'force:package:create'
// };
protected static flagsConfig: FlagsConfig = {
sourceusername: flags.string({
char: "s",
description: commandMessages.getMessage('sourceusernameFlagDescription'),
longDescription: commandMessages.getMessage('sourceusernameFlagLongDescription'),
default: '',
// TODO: Add deprecation to the flag if needed
// deprecated: {
// version: 43,
// to: 'force:package:create'
// },
}),
path: flags.directory({
char: 'p',
description: commandMessages.getMessage('pathFlagDescription'),
longDescription: commandMessages.getMessage('pathFlagLongDescription'),
default: '',
// TODO: Add deprecation to the flag if needed
// deprecated: {
// version: 43,
// to: 'force:package:create'
// },
}),
verbose: flags.builtin({
description: commandMessages.getMessage('verboseFlagDescription'),
longDescription: commandMessages.getMessage('verboseFlagLongDescription')
}),
concise: flags.builtin({
description: commandMessages.getMessage('conciseFlagDescription'),
longDescription: commandMessages.getMessage('conciseFlagLongDescription'),
}),
quiet: flags.builtin({
description: commandMessages.getMessage('quietFlagDescription'),
longDescription: commandMessages.getMessage('quietFlagLongDescription'),
}),
silent: flags.boolean({
description: commandMessages.getMessage("silentFlagDescription"),
longDescription: commandMessages.getMessage("silentFlagLongDescription")
}),
version: flags.boolean({
description: commandMessages.getMessage("versionFlagDescription"),
longDescription: commandMessages.getMessage("versionFlagLongDescription"),
// TODO: Add deprecation to the flag if needed
// deprecated: {
// version: 43,
// to: 'force:package:create'
// },
}),
apiversion: flags.builtin({
description: commandMessages.getMessage("apiversionFlagDescription"),
longDescription: commandMessages.getMessage("apiversionFlagLongDescription")
}),
filelog: flags.boolean({
description: commandMessages.getMessage("filelogFlagDescription"),
longDescription: commandMessages.getMessage("filelogFlagLongDescription"),
// TODO: Add deprecation to the flag if needed
// deprecated: {
// version: 43,
// to: 'force:package:create'
// },
}),
noprompt: flags.boolean({
description: commandMessages.getMessage("nopromptFlagDescription"),
longDescription: commandMessages.getMessage("nopromptLongFlagDescription")
}),
json: flags.boolean({
description: commandMessages.getMessage("jsonFlagDescription"),
longDescription: commandMessages.getMessage("jsonLongFlagDescription"),
default: false
}),
nowarnings: flags.boolean({
description: commandMessages.getMessage("nowarningsFlagDescription"),
longDescription: commandMessages.getMessage("nowarningsLongFlagDescription")
}),
canmodify: flags.string({
char: "c",
description: commandMessages.getMessage('canModifyFlagDescription'),
longDescription: commandMessages.getMessage('canModifyFlagLongDescription'),
default: '',
// TODO: Add deprecation to the flag if needed
// deprecated: {
// version: 43,
// to: 'force:package:create'
// },
})
};
public async run(): Promise<AnyJson> {
this.ux["isOutputEnabled"] = true;
this.flags.verbose = this.flags.verbose && !this.flags.json;
this.flags.quiet = this.flags.quiet || this.flags.silent || this.flags.version;
this.flags.filelog = this.flags.filelog && !this.flags.version;
Common.logger = new Logger(
resources,
commandMessages,
this.ux,
this,
this.flags.loglevel,
this.flags.path,
this.flags.verbose,
this.flags.concise,
this.flags.quiet,
this.flags.json,
this.flags.noprompt,
this.flags.nowarnings,
this.flags.filelog);
try {
let pinfo = Common.getPluginInfo(this);
// Process --version flag
if (this.flags.version) {
// Exit - success
Common.logger.commandExitMessage(
RESOURCES.pluginVersion,
COMMAND_EXIT_STATUSES.SUCCESS,
undefined,
pinfo.pluginName, pinfo.version);
process.exit(COMMAND_EXIT_STATUSES.SUCCESS);
// --
}
// At least one of the flags is required.
// The second is always the default one.
if (!this.flags.sourceusername && !this.flags.targetusername) {
throw new CommandInitializationError(commandMessages.getMessage('errorMissingRequiredFlag', ['--targetusername']));
}
if (!this.flags.sourceusername) {
this.flags.sourceusername = CONSTANTS.DEFAULT_ORG_MEDIA_TYPE;
}
if (!this.flags.targetusername) {
this.flags.targetusername = CONSTANTS.DEFAULT_ORG_MEDIA_TYPE;
}
let commandResult: any;
this.command = new RunCommand(pinfo,
Common.logger,
this.flags.path,
this.flags.sourceusername,
this.flags.targetusername,
this.flags.apiversion,
this.flags.canmodify);
await this.command.setupAsync();
await this.command.createJobAsync();
await this.command.processCSVFilesAsync();
await this.command.prepareJobAsync();
await this.command.runAddonEvent(ADDON_EVENTS.onBefore);
await this.command.executeJobAsync();
await this.command.runAddonEvent(ADDON_EVENTS.onAfter);
// Exit - success
Common.logger.commandExitMessage(
commandResult || RESOURCES.successfullyCompletedResult,
COMMAND_EXIT_STATUSES.SUCCESS);
process.exit(COMMAND_EXIT_STATUSES.SUCCESS);
// --
} catch (e) {
// Exit - errors
switch (e.constructor) {
case SuccessExit:
Common.logger.commandExitMessage(
RESOURCES.successfullyCompletedResult,
COMMAND_EXIT_STATUSES.SUCCESS);
process.exit(COMMAND_EXIT_STATUSES.SUCCESS);
case CommandInitializationError:
Common.logger.commandExitMessage(
RESOURCES.commandInitializationErrorResult,
COMMAND_EXIT_STATUSES.COMMAND_INITIALIZATION_ERROR,
e.stack, e.message);
process.exit(COMMAND_EXIT_STATUSES.COMMAND_INITIALIZATION_ERROR);
case OrgMetadataError:
Common.logger.commandExitMessage(
RESOURCES.orgMetadataErrorResult,
COMMAND_EXIT_STATUSES.ORG_METADATA_ERROR,
e.stack, e.message);
process.exit(COMMAND_EXIT_STATUSES.ORG_METADATA_ERROR);
case CommandExecutionError:
Common.logger.commandExitMessage(
RESOURCES.commandExecutionErrorResult,
COMMAND_EXIT_STATUSES.COMMAND_EXECUTION_ERROR,
e.stack, e.message);
process.exit(COMMAND_EXIT_STATUSES.COMMAND_EXECUTION_ERROR);
case UnresolvableWarning:
Common.logger.commandExitMessage(
RESOURCES.commandUnresolvableWarningResult,
COMMAND_EXIT_STATUSES.UNRESOLWABLE_WARNING, e.message);
process.exit(COMMAND_EXIT_STATUSES.UNRESOLWABLE_WARNING);
case CommandAbortedByUserError:
Common.logger.commandExitMessage(
RESOURCES.commandAbortedByUserErrorResult,
COMMAND_EXIT_STATUSES.COMMAND_ABORTED_BY_USER,
e.stack, e.message);
process.exit(COMMAND_EXIT_STATUSES.COMMAND_ABORTED_BY_USER);
case CommandAbortedByAddOnError:
Common.logger.commandExitMessage(
RESOURCES.commandAbortedByAddOnErrorResult,
COMMAND_EXIT_STATUSES.COMMAND_ABORTED_BY_ADDON,
e.stack, e.message);
process.exit(COMMAND_EXIT_STATUSES.COMMAND_ABORTED_BY_ADDON);
default:
Common.logger.commandExitMessage(
RESOURCES.commandUnexpectedErrorResult,
COMMAND_EXIT_STATUSES.COMMAND_UNEXPECTED_ERROR,
e.stack, e.message);
process.exit(COMMAND_EXIT_STATUSES.COMMAND_UNEXPECTED_ERROR);
}
// --
}
return {};
}
} | the_stack |
import Resource, { DetailOpts } from './index'
import assert from 'assert'
import { AttributeError } from './exceptions'
import { getContentTypeWeak } from './util'
export type RelatedObjectValue = string | string[] | number | number[] | Record<string, any> | Record<string, any>[]
export type CollectionValue = Record<string, any>[]
export default class RelatedManager<T extends typeof Resource = typeof Resource> {
to: T
value: RelatedObjectValue
many: boolean = false
/**
* Is `true` when `resolve()` is called and first page of results loads up to `this.batchSize` objects
*/
resolved: boolean = false
/**
* Deferred promises when `this.resolve()` hits the max requests in `this.batchSize`
*/
deferred: (() => Promise<InstanceType<T>>)[] = []
/**
* List of stringified Primary Keys, even if `this.value` is a list of objects, or Resource instances
*/
primaryKeys: string[]
/**
* When sending `this.resolve()`, only send out the first `n` requests where `n` is `this.batchSize`. You
* can call `this.all()` to recursively get all objects
*/
batchSize: number = Infinity
_resources: Record<string, InstanceType<T>> = {}
constructor(to: T, value: RelatedObjectValue) {
assert(typeof to === 'function', `RelatedManager expected first parameter to be Resource class, received "${to}". Please double check related definitions on class.`)
this.to = to
this.value = value
this.many = Array.isArray(value)
this.primaryKeys = this.getPrimaryKeys()
if (!this.value || (this.many && !Object.keys(this.value).length)) {
this.resolved = true
}
}
/**
* Check if values exist on manager
*/
hasValues() {
if (this.many) {
return (this.value as any[]).length > 0
}
return Boolean(this.value)
}
canAutoResolve() {
let value = this.value as any
let isObject = Object === this.getValueContentType()
let hasIds = this.primaryKeys.length > 0
if (this.many) {
return isObject && hasIds && this.primaryKeys.length === value.length
}
return isObject && hasIds
}
/**
* Return a constructor so we can guess the content type. For example, if an object literal
* is passed, this function should return `Object`, and it's likely one single object literal representing attributes.
* If the constructor is an `Array`, then all we know is that there are many of these sub items (in which case, we're
* taking the first node of that array and using that node to guess). If it's a `Number`, then it's likely
* that it's just a primary key. If it's a `Resource` instance, it should return `Resource`. Etc.
* @returns Function
*/
getValueContentType() {
return getContentTypeWeak(this.value)
}
/**
* Get the current value and the content type and turn it into a list of primary keys
* @returns String
*/
getPrimaryKeys(): string[] {
if (!Boolean(this.value) || (Array.isArray(this.value) && !this.value.length)) {
return []
}
let contentType = this.getValueContentType()
let iterValue = this.value as any[]
if (this.many) {
if (contentType === Resource) {
return iterValue.map((resource: InstanceType<T>) => this.getIdFromResource(resource))
} else if (this.many && contentType === Object) {
return iterValue.map((record) => this.getIdFromObject(record))
} else {
return this.value as string[]
}
} else {
if (contentType === Resource) {
return [this.getIdFromResource(this.value as InstanceType<T>)]
} else if (contentType === Object) {
return [this.getIdFromObject(this.value)]
} else {
return [this.value as string]
}
}
}
/**
* Get unique key property from object literal and turn it into a string
* @param object Object
*/
getIdFromObject(object: any): string {
return String(object[this.to.uniqueKey])
}
/**
* Get unique key from resource instance
* @param resource Resource
*/
getIdFromResource(resource: InstanceType<T>) {
return resource.id
}
/**
* Get a single resource from the endpoint given an ID
* @param id String | Number
*/
getOne(id: string | number, options?: DetailOpts): Promise<InstanceType<T>> {
return this.to.detail<T>(id, options).then((resource: InstanceType<T>) => {
assert(resource.getConstructor().toResourceName() == this.to.toResourceName(), `Related class detail() returned invalid instance: ${resource.toResourceName()} (returned) !== ${this.to.toResourceName()} (expected)`)
this._resources[resource.id] = resource
return resource
})
}
/**
* Same as getOne but allow lookup by index
* @param index Number
*/
getOneAtIndex(index: number) {
return this.getOne(this.primaryKeys[index])
}
/**
* Get all loaded resources relevant to this relation
* Like manager.resources getter except it won't throw an AttributeError and will return with any loaded resources if its ID is listed in `this.primaryKeys`
*/
getAllLoaded(): InstanceType<T>[] {
try {
return this.resources
} catch (e) {
if (e.name === 'AttributeError') {
// Some resources aren't loaded -- just return any cached resources
let cachedObjects = []
for (let id of this.primaryKeys) {
// Check relation cache
let cached = this.to.getCached(id)
// If cache is good, add it to the list of objects to respond wtih
if (cached) {
cachedObjects.push(cached.resource as InstanceType<T>)
}
}
return cachedObjects
} else {
throw e
}
}
}
/**
* Primary function of the RelatedManager -- get some objects (`this.primaryKeys`) related to some
* other Resource (`this.to` instance). Load the first n objects (`this.batchSize`) and set `this.resolved = true`.
* Subsequent calls may be required to get all objects in `this.primaryKeys` because there is an inherent
* limit to how many requests that can be made at one time. If you want to remove this limit, set `this.batchSize` to `Infinity`
* @param options DetailOpts
*/
async resolve(options?: DetailOpts): Promise<InstanceType<T>[]> {
const promises: Promise<any>[] = []
this.deferred = []
for (let i in this.primaryKeys) {
let pk = this.primaryKeys[i]
if (Number(i) > this.batchSize) {
this.deferred.push(this.getOne.bind(this, pk, options))
} else {
promises.push(this.getOne(pk, options))
}
}
await Promise.all(promises)
this.resolved = true
return Object.values(this.resources)
}
async next(options?: DetailOpts): Promise<InstanceType<T>[]> {
const promises: Promise<InstanceType<T>>[] = []
if (!this.resolved) {
return await this.resolve(options)
}
// Take 0 to n items from this.deferred where n is this.batchSize
this.deferred.splice(0, this.batchSize).forEach((deferredFn) => {
promises.push(deferredFn())
})
return await Promise.all(promises)
}
/**
* Calls pending functions in `this.deferred` until it's empty. Runs `this.resolve()` first if it hasn't been ran yet
* @param options DetailOpts
*/
async all(options?: DetailOpts): Promise<InstanceType<T>[]> {
await this.next(options)
if (this.deferred.length) {
// Still have some left
return await this.all(options)
} else {
return Object.values(this.resources)
}
}
resolveFromObjectValue() {
let Ctor = this.to
let value = this.value as any
let contentType = this.getValueContentType()
let newResources: Record<string, InstanceType<T>> = {}
assert(Object === contentType, `Expected RelatedResource.value to be an Object. Received ${contentType}`)
try {
if (this.many) {
for (let i in value) {
let resource = new Ctor(value[i]) as InstanceType<T>
assert(!!resource.id, `RelatedResource.value[${i}] does not have an ID.`)
newResources[resource.id] = resource
}
} else {
let resource = new Ctor(value) as InstanceType<T>
assert(!!resource.id, `RelatedResource value does not have an ID.`)
newResources[this.getIdFromObject(value)] = new Ctor(value) as InstanceType<T>
}
this.resolved = true
Object.assign(this._resources, newResources)
return true
} catch (e) {
throw e
}
}
/**
* Add a resource to the manager
* @param resource Resource instance
*/
add(resource: InstanceType<T>) {
assert(this.many, `Related Manager "many" must be true to add()`)
assert(resource.id, `Resource must be saved before adding to Related Manager`)
assert(resource.getConstructor() === this.to, `Related Manager add() expected ${this.to.toResourceName()}, received ${resource.getConstructor().toResourceName()}`)
const ContentCtor = this.getValueContentType()
var value
if (ContentCtor === Object) {
value = resource.toJSON()
} else if (ContentCtor === Number || ContentCtor === String) {
value = resource.id
}
;(this.value as any[]).push(value)
this._resources[resource.id] = resource
}
/**
* Create a copy of `this` except with new value(s)
* @param value
*/
fromValue<T extends typeof RelatedManager>(this: InstanceType<T>, value: any): InstanceType<T> {
let Ctor = <T>this.constructor
return new Ctor(this.to, value) as InstanceType<T>
}
/**
* Getter -- get `this._resources` but make sure we've actually retrieved the objects first
* Throws AttributeError if `this.resolve()` hasn't finished
*/
get resources(): InstanceType<T>[] {
if (!this.resolved) {
throw new AttributeError(`Can't read results of ${this.constructor.name}[resources], ${this.to.toResourceName()} must resolve() first`)
}
const allObjects = Object.values(this._resources)
return allObjects
}
/**
* Getter -- Same as manager.resources except returns first node
*/
get resource(): InstanceType<T> {
return this.resources[0]
}
get length(): number {
return this.primaryKeys.length
}
toString() {
return this.primaryKeys.join(', ')
}
toJSON() {
return JSON.parse(JSON.stringify(this.value))
}
} | the_stack |
import {
AfterViewInit,
ChangeDetectorRef,
Component,
ComponentFactoryResolver,
ElementRef,
OnDestroy,
OnInit,
ViewChild
} from '@angular/core';
import {WidgetComponent} from '../../../shared/widget/widget.component';
import {DashboardService} from '../../../shared/dashboard.service';
import {OpensourceScanService} from '../opensource-scan.service';
import {catchError, distinctUntilChanged, startWith, switchMap} from 'rxjs/operators';
import {of, Subscription} from 'rxjs';
import {LayoutDirective} from '../../../shared/layouts/layout.directive';
import {OSS_CHARTS} from './oss-charts';
import {DashStatus} from '../../../shared/dash-status/DashStatus';
import {
IClickListData,
IClickListItemOSS
} from '../../../shared/charts/click-list/click-list-interfaces';
import {OSSDetailComponent} from '../oss-detail/oss-detail.component';
import {TwoByOneLayoutComponent} from '../../../shared/layouts/two-by-one-layout/two-by-one-layout.component';
import {IOpensourceScan, IThreat} from '../interfaces';
import {OSSDetailAllComponent} from '../oss-detail-all/oss-detail-all.component';
import {WidgetState} from '../../../shared/widget-header/widget-state';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ICollItem } from 'src/app/viewer_modules/collector-item/interfaces';
import { RefreshModalComponent } from '../../../shared/modals/refresh-modal/refresh-modal.component';
@Component({
selector: 'app-oss-widget',
templateUrl: './oss-widget.component.html',
styleUrls: ['./oss-widget.component.scss']
})
export class OSSWidgetComponent extends WidgetComponent implements OnInit, AfterViewInit, OnDestroy {
// private readonly OSS_MAX_CNT = 1;
// Reference to the subscription used to refresh the widget
private intervalRefreshSubscription: Subscription;
private params;
public allCollectorItems;
public loading: boolean;
private selectedIndex: number;
public hasRefreshLink: boolean;
@ViewChild('projectSelector', { static: true }) projectSelector: ElementRef;
@ViewChild(LayoutDirective, {static: false}) childLayoutTag: LayoutDirective;
constructor(componentFactoryResolver: ComponentFactoryResolver,
cdr: ChangeDetectorRef,
dashboardService: DashboardService,
private modalService: NgbModal,
private ossService: OpensourceScanService) {
super(componentFactoryResolver, cdr, dashboardService);
}
ngOnInit() {
this.widgetId = 'codeanalysis0';
this.layout = TwoByOneLayoutComponent;
this.charts = OSS_CHARTS;
this.auditType = 'LIBRARY_POLICY';
this.allCollectorItems = [];
this.init();
}
// After the view is ready start the refresh interval.
ngAfterViewInit() {
this.startRefreshInterval();
}
ngOnDestroy() {
this.stopRefreshInterval();
}
// Start a subscription to the widget configuration for this widget
// and refresh the charts
startRefreshInterval() {
this.intervalRefreshSubscription = this.dashboardService.dashboardRefresh$.pipe(
startWith(-1), // Refresh this widget seperate from dashboard (ex. config is updated)
distinctUntilChanged(), // If dashboard is loaded the first time, ignore widget double refresh
switchMap(_ => this.getCurrentWidgetConfig()),
switchMap(widgetConfig => {
if (!widgetConfig) {
this.widgetConfigExists = false;
return of([]);
}
this.widgetConfigExists = true;
// check if collector item type is tied to dashboard
// if true, set state to READY, otherwise keep at default CONFIGURE
if (this.dashboardService.checkCollectorItemTypeExist('LibraryPolicy')) {
this.state = WidgetState.READY;
}
this.params = {
componentId: widgetConfig.componentId,
max: 1
};
return this.ossService.getLibraryPolicyCollectorItems(widgetConfig.componentId).pipe(catchError(err => of(err)));
})).subscribe(result => {
this.hasData = result && result.length > 0;
if (this.hasData) {
this.loadCharts(result, 0);
} else {
this.setDefaultIfNoData();
}
});
// for quality widget, subscribe to updates from other quality components
this.dashboardService.dashboardQualityConfig$.subscribe(result => {
if (result) {
this.widgetConfigSubject.next(result);
} else {
this.widgetConfigSubject.next();
}
});
}
// Unsubscribe from the widget refresh observable, which stops widget updating.
stopRefreshInterval() {
if (this.intervalRefreshSubscription) {
this.intervalRefreshSubscription.unsubscribe();
}
}
loadCharts(result: ICollItem[], index) {
this.selectedIndex = index;
if ( result[this.selectedIndex].refreshLink ) {
this.hasRefreshLink = true;
} else {
this.hasRefreshLink = false;
}
this.populateDropdown(result);
const collectorItemId = result[index].id;
this.ossService.fetchDetails(this.params.componentId, collectorItemId).subscribe(libraryPolicy => {
if (libraryPolicy.length > 0) {
this.generateLicenseDetails(libraryPolicy[0]);
this.generateSecurityDetails(libraryPolicy[0]);
super.loadComponent(this.childLayoutTag);
} else {
this.setDefaultIfNoData();
}
});
}
populateDropdown(collectorItems) {
collectorItems.map(item => {
if (item.description) {
item.description = item.description.split(':')[0];
}
});
this.allCollectorItems = collectorItems;
}
generateLicenseDetails(result: IOpensourceScan) {
if (!result || !result.threats || !result.threats.License) {
this.charts[0].data = [];
return;
}
let count = 0;
let openCount = 0;
const sorted = result.threats.License.sort((a: IThreat, b: IThreat): number => {
return this.getDashStatus(a.level) - this.getDashStatus(b.level);
}).reverse();
const latestDetails = sorted.map(oss => {
const ossStatus = this.getDashStatus(oss.level);
const open = (oss.dispositionCounts.Open) ? oss.dispositionCounts.Open : 0;
const ossStatusTitle = oss.level + ' (' + open + '/' + oss.count + ')';
count += oss.count;
openCount += open;
return {
status: ossStatus,
statusText: oss.level,
title: ossStatusTitle,
subtitles: [],
url: result.reportUrl,
components: oss.components,
lastUpdated: result.timestamp
} as IClickListItemOSS;
}
);
this.charts[0].title = 'License (' + openCount + '/' + count + ')';
this.charts[0].data = {
items: latestDetails,
clickableContent: OSSDetailComponent,
clickableHeader: OSSDetailAllComponent
} as IClickListData;
}
generateSecurityDetails(result: IOpensourceScan) {
if (!result || !result.threats || !result.threats.Security) {
this.charts[1].data = [];
return;
}
let count = 0;
let openCount = 0;
const sorted = result.threats.Security.sort((a: IThreat, b: IThreat): number => {
return this.getDashStatus(a.level) - this.getDashStatus(b.level);
}).reverse();
const latestDetails = sorted.map(oss => {
const ossStatus = this.getDashStatus(oss.level);
const open = (oss.dispositionCounts.Open) ? oss.dispositionCounts.Open : 0;
const ossStatusTitle = oss.level + ' (' + open + '/' + oss.count + ')';
count += oss.count;
openCount += open;
return {
status: ossStatus,
statusText: oss.level,
title: ossStatusTitle,
subtitles: [],
url: result.reportUrl,
components: oss.components,
lastUpdated: result.timestamp
} as IClickListItemOSS;
}
);
this.charts[1].title = 'Security (' + openCount + '/' + count + ')';
this.charts[1].data = {
items: latestDetails,
clickableContent: OSSDetailComponent,
clickableHeader: OSSDetailAllComponent
} as IClickListData;
}
getDashStatus(level: string) {
switch (level.toLowerCase()) {
case 'critical':
return DashStatus.CRITICAL;
case 'high':
return DashStatus.UNAUTH;
case 'medium':
return DashStatus.WARN;
case 'low' :
return DashStatus.IN_PROGRESS;
default:
return DashStatus.PASS;
}
}
setDefaultIfNoData() {
if (!this.hasData) {
this.charts[0].data = { items: [{ title: 'No Data Found' }]};
this.charts[1].data = { items: [{ title: 'No Data Found' }]};
}
super.loadComponent(this.childLayoutTag);
}
refreshProject() {
const refreshLink = this.allCollectorItems[this.selectedIndex].refreshLink;
// Redundant check for refresh link, but just in case somebody attempts to call refreshProject() without hitting the button
if ( !this.hasData || !refreshLink ) {
return;
}
this.loading = true;
this.ossService.refreshProject(refreshLink).subscribe(refreshResult => {
this.loading = false;
const modalRef = this.modalService.open(RefreshModalComponent);
modalRef.componentInstance.message = refreshResult;
modalRef.componentInstance.title = this.projectSelector.nativeElement.value;
modalRef.result.then(modalResult => {
this.reloadAfterRefresh();
});
}, err => {
console.log(err);
this.loading = false;
const modalRef = this.modalService.open(RefreshModalComponent);
modalRef.componentInstance.message = 'Something went wrong while trying to refresh the data.';
modalRef.componentInstance.title = this.allCollectorItems[this.selectedIndex].description;
modalRef.result.then(modalResult => {
this.reloadAfterRefresh();
});
});
}
reloadAfterRefresh() {
this.ossService.getLibraryPolicyCollectorItems(this.params.componentId).subscribe(result => {
this.hasData = (result && result.length > 0);
if (this.hasData) {
this.loadCharts(result, this.selectedIndex);
} else {
// Select the first option in the dropdown since there will only be the default option.
this.selectedIndex = 0;
this.setDefaultIfNoData();
}
super.loadComponent(this.childLayoutTag);
this.hasRefreshLink = true;
this.projectSelector.nativeElement.selectedIndex = this.selectedIndex;
});
}
} | the_stack |
import {
FeatureCollection,
FlatTheme,
LineCaps,
SolidLineTechniqueParams,
Style
} from "@here/harp-datasource-protocol";
import { GeoPointLike } from "@here/harp-geoutils";
import { LookAtParams } from "@here/harp-mapview";
import * as turf from "@turf/turf";
import { assert } from "chai";
import * as THREE from "three";
import { GeoJsonStore } from "./utils/GeoJsonStore";
import { GeoJsonTest } from "./utils/GeoJsonTest";
import { ThemeBuilder } from "./utils/ThemeBuilder";
const strokePolygonLayer = (params: Partial<SolidLineTechniqueParams> = {}): Style => {
return {
id: "stroke-polygon",
styleSet: "geojson",
technique: "solid-line",
color: "orange",
lineWidth: ["world-ppi-scale", 20],
secondaryColor: "magenta",
secondaryWidth: ["world-ppi-scale", 35],
...(params as any)
};
};
describe("GeoJson features", function () {
const geoJsonTest = new GeoJsonTest();
const lights = ThemeBuilder.lights;
afterEach(() => geoJsonTest.dispose());
it("Stroke Circle", async function () {
const pos = [13.2, 53.2];
const circle = turf.circle(pos, 600, {
units: "meters"
});
const geoJson = turf.featureCollection([circle]);
await geoJsonTest.run({
testImageName: "geojson-stroke-circle",
mochaTest: this,
geoJson: geoJson as FeatureCollection,
lookAt: {
target: pos as GeoPointLike,
zoomLevel: 14
},
theme: {
lights,
styles: [
strokePolygonLayer({
lineWidth: ["world-ppi-scale", 50],
secondaryWidth: ["world-ppi-scale", 80]
})
]
}
});
});
it("Extrude Circle", async function () {
const pos = [13.2, 53.2];
const circle = turf.circle(pos, 600, {
units: "meters"
});
const geoJson = turf.featureCollection([circle]);
await geoJsonTest.run({
testImageName: "geojson-extruded-circle",
mochaTest: this,
geoJson: geoJson as FeatureCollection,
lookAt: {
target: pos as GeoPointLike,
zoomLevel: 14,
tilt: 60
},
theme: {
lights,
styles: [
{
styleSet: "geojson",
technique: "extruded-polygon",
color: "red",
constantHeight: true,
height: 700
}
]
}
});
});
describe("Stroke Arcs", async function () {
const lineCaps: LineCaps[] = ["None", "Round", "Square", "TriangleIn", "TriangleOut"];
lineCaps.forEach(caps => {
it(`Stroke Arc using from 0 to 300 using '${caps}' caps`, async function () {
const center = [13.2, 53.2];
const arc = turf.lineArc(center, 5, 0, 300);
const geoJson = turf.featureCollection([arc]);
await geoJsonTest.run({
mochaTest: this,
geoJson: geoJson as FeatureCollection,
testImageName: `stroke-arc-with-caps-${caps}`,
lookAt: {
target: center as GeoPointLike,
zoomLevel: 10
},
theme: {
lights,
styles: [strokePolygonLayer({ caps })]
}
});
});
});
});
describe("Stroke Circles created using lineArc", async function () {
const lineCaps: LineCaps[] = ["None", "Round", "Square", "TriangleIn", "TriangleOut"];
lineCaps.forEach(caps => {
it(`Stroke Arc from 0 to 360 using '${caps}' caps`, async function () {
const center = [13.2, 53.2];
const arc = turf.lineArc(center, 5, 0, 360);
const geoJson = turf.featureCollection([arc]);
await geoJsonTest.run({
mochaTest: this,
geoJson: geoJson as FeatureCollection,
testImageName: `stroke-circles-creates-from-arcs-${caps}`,
lookAt: {
target: center as GeoPointLike,
zoomLevel: 10
},
theme: {
lights,
styles: [strokePolygonLayer({ caps })]
}
});
});
});
});
describe("extruded-polygon technique", async function () {
// Helper function to test the winding of the rings.
const isClockWise = (ring: turf.Position[]) =>
THREE.ShapeUtils.isClockWise(ring.map(p => new THREE.Vector2().fromArray(p)));
// the theme used by this test suite.
const theme: FlatTheme = {
lights,
styles: [
{
styleSet: "geojson",
technique: "extruded-polygon",
color: "#0335a2",
lineWidth: 1,
lineColor: "red",
constantHeight: true,
height: 300
}
]
};
// the polygon feature
const polygon = turf.polygon([
[
[0.00671649362467299, 51.49353450058163, 0],
[0.006598810705050831, 51.48737650885326, 0],
[0.015169103358567556, 51.48731300784492, 0],
[0.015286786278189713, 51.49347100814989, 0],
[0.006716493624672999, 51.49353450058163, 0],
[0.00671649362467299, 51.49353450058163, 0]
]
]);
// the center geo location of the polygon
const [longitude, latitude] = turf.center(polygon).geometry!.coordinates;
// the default camera setup used by this test suite.
const lookAt: Partial<LookAtParams> = {
target: [longitude, latitude],
zoomLevel: 15,
tilt: 40,
heading: 45
};
it("Clockwise polygon touching tile border", async function () {
const dataProvider = new GeoJsonStore();
dataProvider.features.insert(polygon);
await geoJsonTest.run({
mochaTest: this,
dataProvider,
testImageName: `geojson-extruded-polygon-touching-tile-bounds`,
lookAt,
theme
});
});
it("Clockwise polygon with a hole", async function () {
const dataProvider = new GeoJsonStore();
const innerPolygon = turf.transformScale(polygon, 0.8, { origin: "center" });
const polygonWithHole = turf.difference(polygon, innerPolygon)!;
dataProvider.features.insert(polygonWithHole);
assert.strictEqual(polygonWithHole?.geometry?.coordinates.length, 2);
const outerRing = polygonWithHole.geometry!.coordinates[0] as turf.Position[];
const innerRing = polygonWithHole.geometry!.coordinates[1] as turf.Position[];
// test that the winding of the inner ring is opposite to the winding
// of the outer ring.
assert.notStrictEqual(isClockWise(outerRing), isClockWise(innerRing));
await geoJsonTest.run({
mochaTest: this,
dataProvider,
testImageName: `geojson-extruded-polygon-cw-with-hole`,
lookAt,
theme
});
});
it("Clockwise polygon with a hole wrong winding", async function () {
const dataProvider = new GeoJsonStore();
const innerPolygon = turf.transformScale(polygon, 0.8, { origin: "center" });
const polygonWithHole = turf.difference(polygon, innerPolygon)!;
dataProvider.features.insert(polygonWithHole);
assert.strictEqual(polygonWithHole?.geometry?.coordinates.length, 2);
const outerRing = polygonWithHole.geometry!.coordinates[0] as turf.Position[];
const innerRing = polygonWithHole.geometry!.coordinates[1] as turf.Position[];
// reverse the winding of the inner ring so to have the same winding
// of the outer ring
innerRing.reverse();
// verify that the winding of the rings is the same
assert.strictEqual(isClockWise(outerRing), isClockWise(innerRing));
await geoJsonTest.run({
mochaTest: this,
dataProvider,
testImageName: `geojson-extruded-polygon-cw-wrong-winding-of-inner-ring`,
lookAt,
theme
});
});
it("Clockwise multi-polygon with a hole wrong winding", async function () {
const dataProvider = new GeoJsonStore();
const scaledPolygon = turf.transformScale(polygon, 0.5, { origin: "center" });
const innerPolygon = turf.transformScale(scaledPolygon, 0.8, { origin: "center" });
const polygonWithHole = turf.difference(scaledPolygon, innerPolygon)!;
const otherPolygonWithHole = turf.clone(polygonWithHole)!;
turf.transformTranslate(polygonWithHole, 200, 90, { units: "meters", mutate: true });
turf.transformTranslate(otherPolygonWithHole, 200, -90, {
units: "meters",
mutate: true
});
const multi = turf.union(polygonWithHole as any, otherPolygonWithHole as any);
assert.strictEqual(multi.geometry?.type, "MultiPolygon");
dataProvider.features.insert(multi);
await geoJsonTest.run({
mochaTest: this,
dataProvider,
testImageName: `geojson-extruded-multi-polygon-cw-wrong-winding-of-inner-ring`,
lookAt,
theme
});
});
});
describe("fill technqiue", async function () {
it("Stroked enclosed polygons", async function () {
const box1 = turf.bboxPolygon([-0.1, -0.1, 0.1, 0.1]);
box1.properties = {
"fill-color": "rgba(0, 255, 0, 0.5)",
"render-order": 2,
"stroke-color": "rgba(0, 255, 255, 0.5)",
"stroke-size": 40,
"stroke-render-order": 2.5
};
const box2 = turf.bboxPolygon([-0.4, -0.4, 0.4, 0.4]);
box2.properties = {
"fill-color": "rgba(255, 0, 0, 0.5)",
"render-order": 1,
"stroke-color": "rgba(0, 0, 255, 0.5)",
"stroke-size": 40,
"stroke-render-order": 1.5
};
const dataProvider = new GeoJsonStore();
dataProvider.features.insert(box1);
dataProvider.features.insert(box2);
await geoJsonTest.run({
mochaTest: this,
dataProvider,
testImageName: `geojson-stroked-enclosed-polygons`,
lookAt: {
target: [0, 0],
zoomLevel: 8.8
},
theme: {
lights: ThemeBuilder.lights,
styles: [
{
styleSet: "geojson",
technique: "fill",
color: ["get", "fill-color"],
renderOrder: ["get", "render-order"]
},
{
styleSet: "geojson",
technique: "solid-line",
color: ["get", "stroke-color"],
lineWidth: ["world-ppi-scale", ["get", "stroke-size"]],
renderOrder: ["get", "stroke-render-order"],
clipping: true
}
]
}
});
});
});
}); | the_stack |
import React, { useContext, useEffect, useMemo, useState } from 'react';
import { connect } from 'react-redux';
import { RootState } from 'typesafe-actions';
import { REACT_COMPONENT_TYPE } from '@/constants/build';
import GlobalContext from '@/pages/GlobalContext';
import { ComponentStructure } from '@/types/builder';
import { newWrapperComponent } from '../../../services/builder';
import * as ACTIONS from '../../../store/actions/builder/template';
import { ROOT_CONTAINER, SYSTEM_PAGE } from '../constant';
import Tools from './tools/HoverBoundary';
import ToolBar from './tools/ToolBar';
import PlaceholderElem from './Placeholder';
import TreeMemo from './Tree';
import {
getAttrData,
getComponentNode,
getFirstChildNode,
getNodeData,
getParentId,
getRootLastNode,
newDnd,
newRect,
} from './utils';
const mapStateToProps = (store: RootState) => ({
applicationId: store.builder.page.applicationId,
version: store.builder.template.version,
// dragging: store.builder.template.dragging,
selectedComponentId: store.builder.template.selectedComponentId,
renderStructure: store.builder.template.renderStructure,
componentSourceMap: store.builder.template.componentSourceMap,
componentList: store.builder.template.componentList,
registeredComponent: store.builder.componentList.allComponent,
versionType: store.builder.template.versionType,
});
const mapDispatchToProps = {
updateDndInfo: ACTIONS.updateDndInfo,
setSelectedId: ACTIONS.setSelectedComponent,
saveComponent: ACTIONS.saveComponent,
pushComponentSource: ACTIONS.pushComponentSource,
appendComponent: ACTIONS.appendComponent,
};
type ContainerProps = ReturnType<typeof mapStateToProps> & typeof mapDispatchToProps;
const Container: React.FC<ContainerProps> = props => {
const {
applicationId,
// dragging,
version,
selectedComponentId,
renderStructure,
componentSourceMap,
versionType,
componentList,
registeredComponent,
updateDndInfo,
setSelectedId,
saveComponent,
pushComponentSource,
appendComponent,
} = props;
const [expendIds, setExpendIds] = useState<string[]>([]);
const [dragState, setDragState] = useState<{ id: string | undefined; status: boolean }>({
id: undefined,
status: false,
});
const { locale } = useContext(GlobalContext);
const { file } = locale.business;
const { id: dragedComponentId, status: dragStatus = false } = dragState;
const ROOT_TOP = 0; // todo
let dndInfo: any = {}; // dnd default info
let type = 'MOVE'; // move、insert、append
useEffect(() => {
handleDragEnd();
}, []);
const handleChange = (dragInfo: any = {}, desc: any = {}) => {
let position = dragInfo.pos === 'APPEND_BEFORE' ? dragInfo.destIndex - 1 : dragInfo.destIndex;
if (!version?.content?.schemas) {
appendComponent(applicationId, ROOT_CONTAINER, desc);
return;
}
const parentId =
dragInfo.parentId && SYSTEM_PAGE !== dragInfo.parentId
? dragInfo.parentId
: versionType === 'page'
? version.content.schemas[0]?.id
: undefined;
let finalParentId;
if (dragInfo.method === 'INSERT') {
finalParentId = parentId;
const parentComponent = componentList.find((item: ComponentStructure) => item.id === finalParentId);
position = parentComponent?.children?.length;
} else {
const targetComponent = componentList.find((item: ComponentStructure) => item.id === dragInfo.componentId);
if (targetComponent && targetComponent.wrapper) {
const container = componentList.find((item: ComponentStructure) => item.id === targetComponent.wrapper);
finalParentId = container?.parentId;
} else {
finalParentId = targetComponent?.parentId;
}
}
if (desc.type === 'add') {
const params = {
id: version.content.id,
parentId: finalParentId,
type: desc.type,
position,
content: newWrapperComponent(registeredComponent, desc.name, finalParentId),
requireLoad: true,
};
pushComponentSource([desc.name]);
saveComponent(applicationId, params, false);
} else {
const { wrapper } = desc;
const wrapperComponent = componentList.find((item: ComponentStructure) => item.id === wrapper);
const content = wrapperComponent
? {
id: wrapper,
label: wrapperComponent.label,
name: wrapperComponent.name,
props: wrapperComponent.props || {},
parentId: finalParentId,
children: wrapperComponent.children || [],
type: wrapperComponent.type || REACT_COMPONENT_TYPE,
directive: wrapperComponent.directive,
}
: {
id: desc.id,
label: desc.label,
name: desc.name,
props: desc.props || {},
parentId: finalParentId,
children: dragInfo.children || [],
type: REACT_COMPONENT_TYPE,
directive: desc.directive,
};
const params = {
id: version.content.id,
parentId: finalParentId,
type: desc.type,
position,
content: content,
requireLoad: false,
};
saveComponent(applicationId, params, false);
}
};
const handleDragStart = (ev: any, component: any, index: number) => {
if (!dragStatus) {
const dsl = {
id: component.id,
label: component.label,
name: component.name,
content: component.content,
props: component.props,
children: component.children,
wrapper: component.wrapper,
directive: component.directive,
type: 'move',
};
ev.dataTransfer.setData('data-dsl', JSON.stringify(Object.assign({}, dsl)));
setTimeout(() => {
setDragState({ status: true, id: component.id });
}, 100);
dndInfo = {
type: 'MOVE',
draggedId: component.id,
originIdx: index,
};
}
};
const handleDragOver = (e: any) => {
const { target, clientY } = e;
const nodeType = getAttrData(target, 'data-type');
const newDragInfo: any = {}; // init dragInfo
if (nodeType === 'root') {
// drag over root
const rooDom = window.document.getElementById('root');
const lastRootDom = getRootLastNode(rooDom);
if (lastRootDom) {
// exist component node
const { componentId, parentId, destIndex } = getNodeData(lastRootDom);
const rect = lastRootDom.parentNode.parentNode.getBoundingClientRect();
Object.assign(
newDragInfo,
newDnd(
'APPEND_AFTER',
'APPEND_AFTER',
componentId,
'',
parentId,
Number(destIndex),
newRect(rect.height, rect.width, rect.height, rect.bottom - ROOT_TOP),
),
);
} else if (rooDom) {
// no component, now add first component node
const rect = rooDom.getBoundingClientRect();
Object.assign(
newDragInfo,
newDnd(
'APPEND_BEFORE',
'APPEND_BEFORE',
'',
'',
'',
0,
newRect(0, rect.width - 20, rect.height, rect.bottom),
),
);
}
if (!dndInfo.type) {
// new append component
type = 'APPEND';
}
} else if (nodeType === 'mask') {
// over mask
const { top, width, height, bottom } = target.getBoundingClientRect();
const beforePos = clientY <= top + height / 2;
Object.assign(
newDragInfo,
newDnd(
beforePos ? 'APPEND_BEFORE' : 'APPEND_AFTER',
beforePos ? 'APPEND_BEFORE' : 'APPEND_AFTER',
null,
getParentId(target.parentNode.parentNode),
'',
0,
newRect(top - ROOT_TOP, width, height, bottom - ROOT_TOP),
),
);
} else {
// over general component
const overComponent = getComponentNode(target);
if (!dndInfo.type) {
// new insert component
type = 'INSERT';
}
if (overComponent) {
const { top, width, height, bottom } = overComponent.getBoundingClientRect();
const rectInfo = newRect(top - ROOT_TOP, width, height, bottom - ROOT_TOP);
// insert child
const couldInsert = getAttrData(overComponent, 'data-with-children');
// can not insert when component without children
if (couldInsert !== 'true') {
const { componentId, parentId, destIndex } = getNodeData(overComponent);
if (clientY <= top + height / 2) {
// before append
Object.assign(
newDragInfo,
newDnd('APPEND_BEFORE', 'APPEND_BEFORE', componentId, parentId, parentId, Number(destIndex), rectInfo),
);
} else {
// after append
Object.assign(
newDragInfo,
newDnd('APPEND_AFTER', 'APPEND_AFTER', componentId, parentId, parentId, Number(destIndex), rectInfo),
);
}
} else {
// cannot insert children
// eslint-disable-next-line no-lonely-if
if (clientY >= top + 10 && clientY <= bottom - 10) {
const { componentId, destIndex } = getNodeData(overComponent);
Object.assign(
newDragInfo,
newDnd('INSERT', 'INSERT', componentId, componentId, componentId, Number(destIndex), rectInfo),
);
if (!dndInfo.type) {
// new append component
type = 'APPEND';
}
} else if (clientY < top + 10) {
// before append
const { componentId, parentId, destIndex } = getNodeData(overComponent);
Object.assign(
newDragInfo,
newDnd('APPEND_BEFORE', 'APPEND_BEFORE', componentId, parentId, parentId, Number(destIndex), rectInfo),
);
} else if (clientY > bottom - 10) {
// after append
const close = getAttrData(overComponent, 'data-close');
// node close state (if expend fix insert child or brother problem)
if (close === 'false') {
const firstChildNode = getFirstChildNode(overComponent);
if (firstChildNode) {
const { componentId, parentId, destIndex } = getNodeData(firstChildNode);
const rect = firstChildNode.getBoundingClientRect();
const newRectInfo = newRect(rect.top - ROOT_TOP, rect.width, rect.height, rect.bottom - ROOT_TOP);
Object.assign(
newDragInfo,
newDnd(
'APPEND_BEFORE',
'APPEND_AFTER',
componentId,
parentId,
parentId,
Number(destIndex),
newRectInfo,
),
);
} else {
const { parentId, destIndex } = getNodeData(overComponent);
Object.assign(
newDragInfo,
newDnd('APPEND_AFTER', 'APPEND_AFTER', parentId, parentId, parentId, Number(destIndex), rectInfo),
);
}
} else {
// after append
const { parentId, destIndex } = getNodeData(overComponent);
Object.assign(
newDragInfo,
newDnd('APPEND_AFTER', 'APPEND_AFTER', parentId, parentId, parentId, Number(destIndex), rectInfo),
);
}
}
}
}
}
if (
dndInfo.hoverComponentId !== newDragInfo.hoverComponentId ||
dndInfo.method !== newDragInfo.method ||
dndInfo.parentId !== newDragInfo.parentId ||
dndInfo.componentId !== newDragInfo.componentId ||
dndInfo.destIndex !== newDragInfo.destIndex ||
dndInfo.pos !== newDragInfo.pos
) {
dndInfo = Object.assign({}, dndInfo, newDragInfo);
updateDndInfo(newDragInfo);
}
e.preventDefault();
};
const handleDragEnd = () => {
updateDndInfo();
dndInfo = {};
type = '';
setDragState({ status: false, id: undefined });
};
const handleOnDrop = (e: any) => {
e.preventDefault();
const desc = JSON.parse(e.dataTransfer.getData('data-dsl'));
if (dndInfo && (['INSERT', 'APPEND'].indexOf(dndInfo.type) > -1 || dndInfo.componentId !== null)) {
if (!dndInfo.type) {
Object.assign(dndInfo, { type });
}
handleChange(dndInfo, desc);
}
handleDragEnd();
};
const handleToggleExpend = (e: any, componentId: string) => {
const list: string[] = expendIds.slice();
const index = list.indexOf(componentId);
if (index > -1) {
list.splice(index, 1);
} else {
list.push(componentId);
}
setSelectedId(undefined);
setExpendIds(list);
e.stopPropagation();
};
const TreeView = useMemo(
() =>
TreeMemo({
renderStructure:
versionType === 'page'
? [{ id: SYSTEM_PAGE, name: SYSTEM_PAGE, label: file.page, children: renderStructure }]
: renderStructure,
dragedComponentId,
expendIds,
componentSourceMap,
selectedComponentId,
onDragStart: handleDragStart,
onDragOver: handleDragOver,
onDrop: handleOnDrop,
onDragEnd: handleDragEnd,
onToggleExpend: handleToggleExpend,
handleSelectComponent: (componentId: string) => {
setSelectedId(componentId);
},
}),
[renderStructure, dragedComponentId, expendIds, selectedComponentId],
);
return (
<div id="structure-container" style={{ position: 'relative', maxHeight: '50%', flex: 1, overflow: 'hidden' }}>
<React.Fragment>
{TreeView}
<PlaceholderElem />
<Tools />
<ToolBar />
</React.Fragment>
{/* {renderStructure ? (
<React.Fragment>
{TreeView}
<PlaceholderElem />
<Tools />
</React.Fragment>
) : (
<Spin />
)} */}
</div>
);
};
export default connect(mapStateToProps, mapDispatchToProps)(Container); | the_stack |
import * as path from "path";
import { CancellationToken, Hover, HoverProvider, MarkdownString, Position, Range, TextDocument, TextLine, Uri, workspace, WorkspaceConfiguration } from "vscode";
import { extensionContext, LANGUAGE_ID } from "../cfmlMain";
import { VALUE_PATTERN } from "../entities/attribute";
import { Component, COMPONENT_EXT, objectNewInstanceInitPrefix } from "../entities/component";
import { IPropertyData, IAtDirectiveData } from "../entities/css/cssLanguageTypes";
import { cssDataManager, getEntryDescription as getCSSEntryDescription, cssWordRegex } from "../entities/css/languageFacts";
import { cssPropertyPattern } from "../entities/css/property";
import { DataType } from "../entities/dataType";
import { constructSyntaxString, Function, getFunctionSuffixPattern } from "../entities/function";
import { GlobalFunction, GlobalTag, globalTagSyntaxToScript } from "../entities/globals";
import { ITagData as HTMLTagData } from "../entities/html/htmlLanguageTypes";
import { getTag as getHTMLTag, isKnownTag as isKnownHTMLTag } from "../entities/html/languageFacts";
import { constructParameterLabel, getParameterName, Parameter } from "../entities/parameter";
import { Signature } from "../entities/signature";
import { expressionCfmlTags, getCfScriptTagAttributePattern, getCfTagAttributePattern, getTagPrefixPattern } from "../entities/tag";
import { getFunctionFromPrefix, UserFunction } from "../entities/userFunction";
import { CFMLEngine, CFMLEngineName } from "../utils/cfdocs/cfmlEngine";
import { CFDocsDefinitionInfo, EngineCompatibilityDetail } from "../utils/cfdocs/definitionInfo";
import { MyMap, MySet } from "../utils/collections";
import { getCssRanges, isCfmFile } from "../utils/contextUtil";
import { DocumentPositionStateContext, getDocumentPositionStateContext } from "../utils/documentUtil";
import { equalsIgnoreCase, textToMarkdownCompatibleString, textToMarkdownString } from "../utils/textUtil";
import * as cachedEntity from "./cachedEntities";
import { getComponent } from "./cachedEntities";
const cfDocsLinkPrefix = "https://cfdocs.org/";
const mdnLinkPrefix = "https://developer.mozilla.org/docs/Web/";
interface HoverProviderItem {
name: string;
syntax: string;
symbolType: string;
description: string;
params?: Parameter[];
returnType?: string;
genericDocLink?: string;
engineLinks?: MyMap<CFMLEngineName, Uri>;
language?: string;
}
export default class CFMLHoverProvider implements HoverProvider {
/**
* Provides a hover for the given position and document
* @param document The document in which the hover was invoked.
* @param position The position at which the hover was invoked.
* @param _token A cancellation token.
*/
public async provideHover(document: TextDocument, position: Position, _token: CancellationToken): Promise<Hover | undefined> {
const cfmlHoverSettings: WorkspaceConfiguration = workspace.getConfiguration("cfml.hover", document.uri);
if (!cfmlHoverSettings.get<boolean>("enable", true)) {
return undefined;
}
const filePath: string = document.fileName;
if (!filePath) {
return undefined;
}
return this.getHover(document, position);
}
/**
* Generates hover
* @param document The document in which the hover was invoked.
* @param position The position at which the hover was invoked.
*/
public async getHover(document: TextDocument, position: Position): Promise<Hover | undefined> {
let definition: HoverProviderItem;
const documentPositionStateContext: DocumentPositionStateContext = getDocumentPositionStateContext(document, position);
const userEngine: CFMLEngine = documentPositionStateContext.userEngine;
const wordRange: Range = document.getWordRangeAtPosition(position);
if (wordRange) {
const textLine: TextLine = document.lineAt(position);
const lineText: string = documentPositionStateContext.sanitizedDocumentText.slice(document.offsetAt(textLine.range.start), document.offsetAt(textLine.range.end));
const currentWord: string = documentPositionStateContext.currentWord;
const lowerCurrentWord = currentWord.toLowerCase();
const lineSuffix: string = lineText.slice(wordRange.end.character, textLine.range.end.character);
const docPrefix: string = documentPositionStateContext.docPrefix;
const positionIsCfScript: boolean = documentPositionStateContext.positionIsScript;
let userFunc: UserFunction;
const tagPrefixPattern: RegExp = getTagPrefixPattern();
const functionSuffixPattern: RegExp = getFunctionSuffixPattern();
if (documentPositionStateContext.positionInComment) {
return undefined;
}
// Global tags
if (cachedEntity.isGlobalTag(currentWord)) {
if (tagPrefixPattern.test(docPrefix)) {
definition = this.globalTagToHoverProviderItem(cachedEntity.getGlobalTag(lowerCurrentWord));
return this.createHover(definition);
}
if (userEngine.supportsScriptTags() && functionSuffixPattern.test(lineSuffix)) {
definition = this.globalTagToHoverProviderItem(cachedEntity.getGlobalTag(lowerCurrentWord), true);
return this.createHover(definition);
}
}
// Check if instantiating via "new" operator
const componentPathWordRange: Range = document.getWordRangeAtPosition(position, /[$\w.]+/);
const componentPathWord: string = document.getText(componentPathWordRange);
const componentPathWordPrefix: string = documentPositionStateContext.sanitizedDocumentText.slice(0, document.offsetAt(componentPathWordRange.start));
const startSigPositionPrefix = `${componentPathWordPrefix}${componentPathWord}(`;
const objectNewInstanceInitPrefixMatch: RegExpExecArray = objectNewInstanceInitPrefix.exec(startSigPositionPrefix);
if (objectNewInstanceInitPrefixMatch && objectNewInstanceInitPrefixMatch[2] === componentPathWord) {
const componentUri: Uri = cachedEntity.componentPathToUri(componentPathWord, document.uri);
if (componentUri) {
const initComponent: Component = getComponent(componentUri);
if (initComponent) {
const initMethod = initComponent.initmethod ? initComponent.initmethod.toLowerCase() : "init";
if (initComponent.functions.has(initMethod)) {
userFunc = initComponent.functions.get(initMethod);
definition = this.functionToHoverProviderItem(userFunc);
return this.createHover(definition, componentPathWordRange);
}
}
}
}
// Functions
if (functionSuffixPattern.test(lineSuffix)) {
// Global function
if (!documentPositionStateContext.isContinuingExpression && cachedEntity.isGlobalFunction(currentWord)) {
definition = this.functionToHoverProviderItem(cachedEntity.getGlobalFunction(lowerCurrentWord));
return this.createHover(definition);
}
// User function
userFunc = await getFunctionFromPrefix(documentPositionStateContext, lowerCurrentWord);
if (userFunc) {
definition = this.functionToHoverProviderItem(userFunc);
return this.createHover(definition);
}
}
// Global tag attributes
if (!positionIsCfScript || userEngine.supportsScriptTags()) {
const cfTagAttributePattern: RegExp = positionIsCfScript ? getCfScriptTagAttributePattern() : getCfTagAttributePattern();
const cfTagAttributeMatch: RegExpExecArray = cfTagAttributePattern.exec(docPrefix);
if (cfTagAttributeMatch) {
const ignoredTags: string[] = expressionCfmlTags;
const tagName: string = cfTagAttributeMatch[2];
const globalTag: GlobalTag = cachedEntity.getGlobalTag(tagName);
const attributeValueMatch: RegExpExecArray = VALUE_PATTERN.exec(docPrefix);
if (globalTag && !ignoredTags.includes(globalTag.name) && !attributeValueMatch) {
// TODO: Check valid attribute before calling createHover
definition = this.attributeToHoverProviderItem(globalTag, currentWord);
return this.createHover(definition);
}
}
}
// TODO: Function arguments used within function body, or named argument invocation. Component properties.
// HTML tags
const htmlHoverSettings: WorkspaceConfiguration = workspace.getConfiguration("cfml.hover.html", document.uri);
if (isCfmFile(document) && htmlHoverSettings.get<boolean>("enable", true) && tagPrefixPattern.test(docPrefix) && isKnownHTMLTag(lowerCurrentWord)) {
definition = this.htmlTagToHoverProviderItem(getHTMLTag(lowerCurrentWord));
return this.createHover(definition);
}
}
// CSS
const cssHoverSettings: WorkspaceConfiguration = workspace.getConfiguration("cfml.hover.css", document.uri);
const cssRanges: Range[] = getCssRanges(documentPositionStateContext);
if (cssHoverSettings.get<boolean>("enable", true)) {
for (const cssRange of cssRanges) {
if (!cssRange.contains(position)) {
continue;
}
const rangeTextOffset: number = document.offsetAt(cssRange.start);
const rangeText: string = documentPositionStateContext.sanitizedDocumentText.slice(rangeTextOffset, document.offsetAt(cssRange.end));
let propertyMatch: RegExpExecArray;
while (propertyMatch = cssPropertyPattern.exec(rangeText)) {
const propertyName: string = propertyMatch[2];
const propertyRange: Range = new Range(
document.positionAt(rangeTextOffset + propertyMatch.index),
document.positionAt(rangeTextOffset + propertyMatch.index + propertyMatch[0].length)
);
if (propertyRange.contains(position) && cssDataManager.isKnownProperty(propertyName)) {
definition = this.cssPropertyToHoverProviderItem(cssDataManager.getProperty(propertyName));
return this.createHover(definition, propertyRange);
}
}
const cssWordRange: Range = document.getWordRangeAtPosition(position, cssWordRegex);
const currentCssWord: string = cssWordRange ? document.getText(cssWordRange) : "";
if (currentCssWord.startsWith("@")) {
const cssAtDir: IAtDirectiveData = cssDataManager.getAtDirective(currentCssWord);
if (cssAtDir) {
definition = this.cssAtDirectiveToHoverProviderItem(cssAtDir);
return this.createHover(definition, cssWordRange);
}
}
}
}
return undefined;
}
/**
* Creates HoverProviderItem from given global tag
* @param tag Global tag to convert
* @param isScript Whether this is a script tag
*/
public globalTagToHoverProviderItem(tag: GlobalTag, isScript: boolean = false): HoverProviderItem {
let paramArr: Parameter[] = [];
let paramNames = new MySet<string>();
tag.signatures.forEach((sig: Signature) => {
sig.parameters.forEach((param: Parameter) => {
const paramName = getParameterName(param);
if (!paramNames.has(paramName)) {
paramNames.add(paramName);
paramArr.push(param);
}
});
});
let hoverItem: HoverProviderItem = {
name: tag.name,
syntax: (isScript ? globalTagSyntaxToScript(tag) : tag.syntax),
symbolType: "tag",
description: tag.description,
params: paramArr,
returnType: undefined,
genericDocLink: cfDocsLinkPrefix + tag.name,
language: LANGUAGE_ID
};
let globalEntity: CFDocsDefinitionInfo = cachedEntity.getGlobalEntityDefinition(tag.name);
if (globalEntity && globalEntity.engines) {
hoverItem.engineLinks = new MyMap();
const cfmlEngineNames: CFMLEngineName[] = [
CFMLEngineName.ColdFusion,
CFMLEngineName.Lucee,
CFMLEngineName.OpenBD
];
for (const cfmlEngineName of cfmlEngineNames) {
if (globalEntity.engines.hasOwnProperty(cfmlEngineName)) {
const cfEngineInfo: EngineCompatibilityDetail = globalEntity.engines[cfmlEngineName];
if (cfEngineInfo.docs) {
try {
const engineDocUri: Uri = Uri.parse(cfEngineInfo.docs);
hoverItem.engineLinks.set(CFMLEngineName.valueOf(cfmlEngineName), engineDocUri);
} catch (ex) {
console.error(ex);
}
}
}
}
}
return hoverItem;
}
/**
* Creates HoverProviderItem from given function
* @param func Function to convert
*/
public functionToHoverProviderItem(func: Function): HoverProviderItem {
let paramArr: Parameter[] = [];
let paramNames = new MySet<string>();
func.signatures.forEach((sig: Signature) => {
sig.parameters.forEach((param: Parameter) => {
const paramName = getParameterName(param);
if (!paramNames.has(paramName)) {
paramNames.add(paramName);
paramArr.push(param);
}
});
});
let returnType: string;
if ("returnTypeUri" in func) {
const userFunction: UserFunction = func as UserFunction;
if (userFunction.returnTypeUri) {
returnType = path.basename(userFunction.returnTypeUri.fsPath, COMPONENT_EXT);
}
}
if (!returnType && func.returntype) {
returnType = func.returntype;
} else {
returnType = DataType.Any;
}
let hoverItem: HoverProviderItem = {
name: func.name,
syntax: constructSyntaxString(func),
symbolType: "function",
description: func.description,
params: paramArr,
returnType: returnType
};
if (cachedEntity.isGlobalFunction(func.name)) {
const globalFunc = func as GlobalFunction;
// TODO: Use constructed syntax string instead. Indicate overloads/multiple signatures
hoverItem.syntax = globalFunc.syntax + ": " + returnType;
hoverItem.genericDocLink = cfDocsLinkPrefix + globalFunc.name;
let globalEntity: CFDocsDefinitionInfo = cachedEntity.getGlobalEntityDefinition(globalFunc.name);
if (globalEntity && globalEntity.engines) {
hoverItem.engineLinks = new MyMap();
const cfmlEngineNames: CFMLEngineName[] = [
CFMLEngineName.ColdFusion,
CFMLEngineName.Lucee,
CFMLEngineName.OpenBD
];
for (const cfmlEngineName of cfmlEngineNames) {
if (globalEntity.engines.hasOwnProperty(cfmlEngineName)) {
const cfEngineInfo: EngineCompatibilityDetail = globalEntity.engines[cfmlEngineName];
if (cfEngineInfo.docs) {
try {
const engineDocUri: Uri = Uri.parse(cfEngineInfo.docs);
hoverItem.engineLinks.set(CFMLEngineName.valueOf(cfmlEngineName), engineDocUri);
} catch (ex) {
console.error(ex);
}
}
}
}
}
}
return hoverItem;
}
/**
* Creates HoverProviderItem from given global tag attribute
* @param tag Global tag to which the attribute belongs
* @param attributeName Global tag attribute name to convert
*/
public attributeToHoverProviderItem(tag: GlobalTag, attributeName: string): HoverProviderItem {
let attribute: Parameter;
tag.signatures.forEach((sig: Signature) => {
attribute = sig.parameters.find((param: Parameter) => {
const paramName = getParameterName(param);
return equalsIgnoreCase(paramName, attributeName);
});
});
if (!attribute) {
return undefined;
}
return {
name: attributeName,
syntax: `${attribute.required ? "(required) " : ""}${tag.name}[@${attributeName}]: ${attribute.dataType}`,
symbolType: "attribute",
description: attribute.description,
genericDocLink: `${cfDocsLinkPrefix}${tag.name}#p-${attribute.name}`
};
}
/**
* Creates HoverProviderItem from given HTML tag
* @param htmlTag HTML tag to convert
*/
public htmlTagToHoverProviderItem(htmlTag: HTMLTagData): HoverProviderItem {
let hoverItem: HoverProviderItem = {
name: htmlTag.name,
syntax: `<${htmlTag.name}>`,
symbolType: "tag",
description: htmlTag.description,
params: [],
returnType: undefined,
genericDocLink: `${mdnLinkPrefix}HTML/Element/${htmlTag.name}`,
language: "html"
};
return hoverItem;
}
/**
* Creates HoverProviderItem from given CSS property
* @param cssProperty CSS property to convert
*/
public cssPropertyToHoverProviderItem(cssProperty: IPropertyData): HoverProviderItem {
let hoverItem: HoverProviderItem = {
name: cssProperty.name,
syntax: `${cssProperty.name}: value`,
symbolType: "property",
description: getCSSEntryDescription(cssProperty),
params: [],
returnType: undefined,
genericDocLink: `${mdnLinkPrefix}CSS/${cssProperty.name}`
};
if (cssProperty.syntax) {
hoverItem.syntax = `${cssProperty.name}: ${cssProperty.syntax}`;
}
return hoverItem;
}
/**
* Creates HoverProviderItem from given CSS at directive
* @param cssAtDir CSS at directive to convert
*/
public cssAtDirectiveToHoverProviderItem(cssAtDir: IAtDirectiveData): HoverProviderItem {
let hoverItem: HoverProviderItem = {
name: cssAtDir.name,
syntax: cssAtDir.name,
symbolType: "property",
description: getCSSEntryDescription(cssAtDir),
params: [],
returnType: undefined,
genericDocLink: `${mdnLinkPrefix}CSS/${cssAtDir.name.replace(/-[a-z]+-/, "")}`,
language: "css"
};
return hoverItem;
}
/**
* Creates a list of MarkdownString that becomes the hover based on the symbol definition
* @param definition The symbol definition information
* @param range An optional range to which this hover applies
*/
public async createHover(definition: HoverProviderItem, range?: Range): Promise<Hover> {
if (!definition) {
return Promise.reject(new Error("Definition not found"));
}
if (!definition.name) {
return Promise.reject(new Error("Invalid definition format"));
}
return new Hover(this.createHoverText(definition), range);
}
/**
* Creates a list of MarkdownString that becomes the hover text based on the symbol definition
* @param definition The symbol definition information
*/
public createHoverText(definition: HoverProviderItem): MarkdownString[] {
const cfdocsIconUri: Uri = Uri.file(extensionContext.asAbsolutePath("images/cfdocs.png"));
const mdnIconUri: Uri = Uri.file(extensionContext.asAbsolutePath("images/mdn.png"));
let hoverTexts: MarkdownString[] = [];
let syntax: string = definition.syntax;
const symbolType: string = definition.symbolType;
let language: string = "plaintext";
// let paramKind = "";
if (symbolType === "function") {
if (!syntax.startsWith("function ")) {
syntax = "function " + syntax;
}
language = definition.language ? definition.language : "typescript"; // cfml not coloring properly
// paramKind = "Parameter";
} else if (symbolType === "tag") {
language = definition.language ? definition.language : LANGUAGE_ID;
// paramKind = "Attribute";
} else if (symbolType === "attribute") {
language = definition.language ? definition.language : "typescript";
} else if (symbolType === "property") {
if (definition.language) {
language = definition.language;
}
} else {
return undefined;
}
hoverTexts.push(new MarkdownString().appendCodeblock(syntax, language));
if (definition.description) {
hoverTexts.push(textToMarkdownString(definition.description));
} else {
hoverTexts.push(new MarkdownString("_No " + symbolType.toLowerCase() + " description_"));
}
if (definition.genericDocLink) {
let docLinks: string = "";
if (definition.genericDocLink.startsWith(cfDocsLinkPrefix)) {
docLinks = `[})](${definition.genericDocLink})`;
if (definition.engineLinks) {
definition.engineLinks.forEach((docUri: Uri, engineName: CFMLEngineName) => {
const engineIconUri = CFMLEngine.getIconUri(engineName);
if (engineIconUri) {
docLinks += ` [})](${docUri.toString()})`;
}
});
}
} else if (definition.genericDocLink.startsWith(mdnLinkPrefix)) {
docLinks = `[})](${definition.genericDocLink})`;
}
hoverTexts.push(new MarkdownString(docLinks));
}
const paramList: Parameter[] = definition.params;
if (paramList && paramList.length > 0) {
hoverTexts.push(this.paramsMarkdownPreview(paramList));
}
return hoverTexts;
}
public paramsMarkdownPreview(params: Parameter[], isVerbose: boolean = true): MarkdownString {
const paramDocFunction: (param: Parameter) => string = isVerbose ? this.getVerboseParamDocumentation : this.getParamDocumentation;
return new MarkdownString(params.map(paramDocFunction).join(" \n\n"));
}
public getParamDocumentation(param: Parameter): string {
const paramName = getParameterName(param);
const doc = param.description;
const label = `\`${paramName}\``;
if (!doc) {
return label;
}
return label + (/\n/.test(doc) ? " \n" + doc : ` — ${doc}`);
}
public getVerboseParamDocumentation(param: Parameter): string {
let paramString = constructParameterLabel(param);
if (!param.required && typeof param.default !== "undefined") {
let paramDefault = param.default;
// TODO: Improve check
if (typeof paramDefault === "string") {
if (param.dataType === DataType.String) {
if (!paramDefault.trim().startsWith("'") && !paramDefault.trim().startsWith('"')) {
paramDefault = `"${paramDefault.trim()}"`;
}
} else if (param.dataType === DataType.Numeric) {
paramDefault = paramDefault.replace(/['"]/, "").trim();
} else if (param.dataType === DataType.Boolean) {
paramDefault = DataType.isTruthy(paramDefault).toString();
}
}
if (paramDefault) {
paramString += " = " + paramDefault;
}
}
let hoverText = new MarkdownString(`\`${paramString}\``).appendMarkdown(" \n ");
if (param.description) {
hoverText.appendMarkdown(textToMarkdownCompatibleString(param.description));
} else {
hoverText.appendMarkdown("_No description_");
}
return hoverText.value;
}
} | the_stack |
module Kiwi.Animations {
/**
* Manages the tweening of properties/values on a single object. A Tween is the animation of a number between an initially value to and final value (that you specify).
* Note: When using a Tween you need to make sure that the Tween has been added to a TweenManager. You can either do this by creating the Tween via the Manager or alternatively using the 'add' method on the TweenManager. Otherwise the tween will not work.
*
* Based on tween.js by sole. Converted to TypeScript and integrated into Kiwi.
* https://github.com/sole/tween.js
*
* @class Tween
* @constructor
* @namespace Kiwi.Animations
* @param object {Any} The object that this tween is taking affect on.
* @param game {Kiwi.Game} The game that this tween is for.
* @return {Kiwi.Animations.Tween} This tween.
*
* @author sole / http://soledadpenades.com
* @author mrdoob / http://mrdoob.com
* @author Robert Eisele / http://www.xarg.org
* @author Philippe / http://philippe.elsass.me
* @author Robert Penner / http://www.robertpenner.com/easing_terms_of_use.html
* @author Paul Lewis / http://www.aerotwist.com/
* @author lechecacharro
* @author Josh Faul / http://jocafa.com/
* @author egraether / http://egraether.com/
*
*/
export class Tween {
constructor(object, game:Kiwi.Game = null) {
this._object = object;
if (game !== null)
{
this._game = game;
this._manager = this._game.tweens;
}
this.isRunning = false;
}
/**
* The type of object that this is.
* @method objType
* @return {String} "Tween"
* @public
*/
public objType() {
return "Tween";
}
/**
* The game that this tween belongs to.
* @property _game
* @type Kiwi.Game
* @private
*/
private _game: Kiwi.Game = null;
/**
* The manager that this tween belongs to.
* @property _manager
* @type Kiwi.Animations.Tweens.TweenManager
* @private
*/
private _manager: Kiwi.Animations.Tweens.TweenManager = null;
/**
* The manager that this tween belongs to.
* @property manager
* @type Kiwi.Animations.Tweens.TweenManager
* @private
* @since 1.2.0
*/
public get manager(): Kiwi.Animations.Tweens.TweenManager {
return this._manager;
}
public set manager( value: Kiwi.Animations.Tweens.TweenManager ) {
this._manager = value;
}
/**
* The object that this tween is affecting.
* @property _object
* @type Any
* @private
*/
private _object = null;
/**
* The object that this tween is affecting.
* If you change this, it will continue to tween,
* but any properties that are not on the new object
* will be discarded from the tween.
* @property object
* @type any
* @public
*/
public get object(): any {
return this._object;
}
public set object( value: any ) {
var i,
newValues = {};
this._object = value;
for ( i in this._valuesEnd ) {
if ( value[ i ] ) {
newValues[ i ] = this._valuesEnd[ i ];
}
}
this._valuesEnd = newValues;
}
/**
* The starting values of the properties that the tween is animating.
* @property _valuesStart
* @type Object
* @private
*/
private _valuesStart = {};
/**
* The end values of the properties that the tween is animating.
* @property _valuesEnd
* @type Object
* @private
*/
private _valuesEnd = {};
/**
* The duration of the tween, in milliseconds.
* @property _duration
* @type Number
* @private
*/
private _duration = 1000;
/**
* The amount of time to delay the tween by. In Milliseconds.
* @property _delayTime
* @type Number
* @private
*/
private _delayTime:number = 0;
/**
* The time at which the tween started.
* @property _startTime
* @type Number
* @private
*/
private _startTime:number = null;
/**
* The easing function that is to be used while tweening.
* @property _easingFunction
* @type Function
* @default Kiwi.Tweens.Easing.Linear.None
* @private
*/
private _easingFunction = Kiwi.Animations.Tweens.Easing.Linear.None;
/**
* [NEEDS DESCRIPTION]
* @property _interpolationFunction
* @type Function
* @default Kiwi.Utils.Interpolation.Linear
* @private
*/
private _interpolationFunction = Kiwi.Utils.GameMath.linearInterpolation;
/**
* An array containing all of the tweens that are to be played when this one finishes.
* @property _chainedTweens
* @type Tween[]
* @private
*/
private _chainedTweens = [];
/**
* The method that is to be called when the tween starts playing.
* @property _onStartCallback
* @type Function
* @default null
* @private
*/
private _onStartCallback = null;
/**
* The context that the _onStartCallback method is to be called in.
* @property _onStartContext
* @type Any
* @default null
* @private
*/
private _onStartContext:any = null;
/**
* A boolean indicating if the starting callback has been called or not.
* @property _onStartCallbackFired
* @type boolean
* @default false
* @private
*/
private _onStartCallbackFired:boolean = false;
/**
* A callback method that will be called each time the tween updates.
* @property _onUpdateCallback
* @type Function
* @default null
* @private
*/
private _onUpdateCallback = null;
/**
* The context that the update callback has when called.
* @property _onUpdateContext
* @type any
* @default null
* @private
*/
private _onUpdateContext:any = null;
/**
* A method to be called when the tween finish's tweening.
* @property _onCompleteCallback
* @type function
* @default null
* @private
*/
private _onCompleteCallback = null;
/*
* A boolean indicating whether or not the _onCompleteCallback has been called.
* Is reset each time you tell the tween to start.
* @property _onCompleteCalled
* @type boolean
* @default false
* @private
*/
private _onCompleteCalled: boolean = false;
/**
* The context that the onCompleteCallback should have when called.
* @property _onCompleteContext
* @type any
* @default null
* @private
*/
private _onCompleteContext: any = null;
/**
* An indication of whether or not this tween is currently running.
* @property isRunning.
* @type boolean
* @default false
* @public
*/
public isRunning: boolean = false;
/**
* Sets up the various properties that define this tween.
* The ending position/properties for this tween, how long the tween should go for, easing method to use and if should start right way.
*
* @method to
* @param properties {Object} The ending location of the properties that you want to tween.
* @param [duration=1000] {Number} The duration of the tween.
* @param [ease=null] {Any} The easing method to be used. If not specifed then this will default to LINEAR.
* @param [autoStart=false] {boolean} If the tween should start right away.
* @return {Kiwi.Animations.Tween}
* @public
*/
public to(properties, duration: number = 1000, ease: any = null, autoStart: boolean = false):Tween {
this._duration = duration;
// If properties isn't an object this will fail, sanity check it here somehow?
this._valuesEnd = properties;
if (ease !== null) {
this._easingFunction = ease;
}
if (autoStart === true) {
return this.start();
} else {
return this;
}
}
/**
* Gets the initial values for the properties that it is to animate and starts the tween process.
* @method start
* @public
*/
public start() {
var property;
if (this._game === null || this._object === null)
{
return;
}
this.isRunning = true;
this._manager.add(this);
this._onStartCallbackFired = false;
this._onCompleteCalled = false;
this._startTime = this._manager.clock.elapsed() * 1000 + this._delayTime;
for ( var property in this._valuesEnd ) {
// This prevents the interpolation of null values or of non-existing properties
if ( this._object[ property ] === null || !( property in this._object ) ) {
continue;
}
// check if an Array was provided as property value
if ( this._valuesEnd[ property ] instanceof Array ) {
if ( this._valuesEnd[ property ].length === 0 ) {
continue;
}
// create a local copy of the Array with the start value at the front
this._valuesEnd[ property ] = [ this._object[ property ] ].concat(this._valuesEnd[ property ]);
}
// Check if property is a function
if ( typeof this._object[ property ] === "function" ) {
this._valuesStart[ property ] = this._object[ property ]();
} else {
this._valuesStart[ property ] = this._object[ property ];
}
}
return this;
}
/**
* Stops the Tween from running and removes it from the manager.
* @method stop
* @public
*/
public stop() {
if (this._manager !== null)
{
this._manager.remove(this);
}
this.isRunning = false;
return this;
}
/**
* Sets the game and the manager of this tween.
* @method setParent
* @param {Kiwi.Game} value
* @public
*/
public setParent(value:Kiwi.Game) {
this._game = value;
this._manager = this._game.tweens;
}
/**
* Sets the amount of delay that the tween is to have before it starts playing.
* @method delay
* @param amount {Number} The amount of time to delay the tween by.
* @return {Kiwi.Animations.Tween}
* @public
*/
public delay(amount:number):Tween {
this._delayTime = amount;
return this;
}
/**
* Sets the easing method that is to be used when animating this tween.
* @method easing
* @param easing {Function} The easing function to use.
* @return {Kiwi.Animations.Tween}
* @public
*/
public easing(easing):Tween {
this._easingFunction = easing;
return this;
}
/**
* [REQUIRES DESCRIPTION]
* @method interpolation
* @param {Any} interpolation
* @return {Kiwi.Animations.Tween}
* @public
*/
public interpolation(interpolation):Tween {
this._interpolationFunction = interpolation;
return this;
}
/**
* Adds another tween that should start playing once tween has completed.
* @method chain
* @param tween {Kiwi.Animations.Tween}
* @return {Kiwi.Animations.Tween}
* @public
*/
public chain(tween:Kiwi.Animations.Tween):Tween {
this._chainedTweens.push(tween);
return this;
}
/**
* Adds a function that is to be executed when the tween start playing.
* @method onStart
* @param callback {Function} The function that is to be executed on tween start.
* @param context {any} The context that function is to have when called.
* @return {Kiwi.Animations.Tween}
* @public
*/
public onStart(callback, context):Tween {
this._onStartCallback = callback;
this._onStartContext = context;
return this;
}
/**
* Adds a function that is to be executed when this tween updates while it is playing.
* @method onUpdate
* @param callback {Function} The method that is to be executed.
* @param context {Any} The context the method is to have when called.
* @public
*/
public onUpdate(callback, context) {
this._onUpdateCallback = callback;
this._onUpdateContext = context;
return this;
}
/**
* Defines a method that is to be called when this tween is finished.
* @method onComplete
* @param callback {Function} The method that is to be executed.
* @param context {Any} The context the method is to have when called.
* @public
*/
public onComplete(callback, context) {
this._onCompleteCallback = callback;
this._onCompleteContext = context;
return this;
}
/**
* The update loop is executed every frame whilst the tween is running.
* @method update
* @param time {Number}
* @return {boolean} Whether the Tween is still running
* @public
*/
public update( time: number ) {
if ( time < this._startTime - this._delayTime ) {
return false;
}
if ( this._onStartCallbackFired === false ) {
if ( this._onStartCallback !== null ) {
this._onStartCallback.call( this._onStartContext,
this._object );
}
this._onStartCallbackFired = true;
}
var elapsed = ( time - this._startTime ) / this._duration;
elapsed = elapsed > 1 ? 1 :
elapsed < 0 ? 0 :
elapsed;
var value = this._easingFunction( elapsed );
for ( var property in this._valuesStart ) {
var start = this._valuesStart[ property ];
var end = this._valuesEnd[ property ];
// Add checks for object, array, numeric up front
if ( end instanceof Array ) {
this._object[ property ] =
this._interpolationFunction( end, value );
} else {
if ( typeof this._object[ property ] === "function" ) {
this._object[ property ]( start + ( end - start ) * value );
} else {
this._object[ property ] = start + ( end - start ) * value;
}
}
}
if ( this._onUpdateCallback !== null ) {
this._onUpdateCallback.call( this._onUpdateContext,
this._object, value );
}
if ( elapsed === 1 ) {
this.isRunning = false;
if ( this._onCompleteCallback !== null &&
this._onCompleteCalled === false ) {
this._onCompleteCalled = true;
this._onCompleteCallback.call(
this._onCompleteContext, this._object );
}
for ( var i = 0; i < this._chainedTweens.length; i++ ) {
this._chainedTweens[ i ].start();
}
return false;
}
return true;
}
}
} | the_stack |
import {RpcError} from "./rpc-error";
import type {RpcMetadata} from "./rpc-metadata";
import type {RpcStatus} from "./rpc-status";
import type {RpcTransport} from "./rpc-transport";
import type {MethodInfo} from "./reflection-info";
import {assert} from "@protobuf-ts/runtime";
import {RpcOutputStreamController} from "./rpc-output-stream";
import {mergeRpcOptions, RpcOptions} from "./rpc-options";
import {UnaryCall} from "./unary-call";
import {ServerStreamingCall} from "./server-streaming-call";
import {ClientStreamingCall} from "./client-streaming-call";
import {DuplexStreamingCall} from "./duplex-streaming-call";
import type {RpcInputStream} from "./rpc-input-stream";
/**
* Mock data for the TestTransport.
*/
interface TestTransportMockData {
/**
* Input stream behaviour for client streaming and bidi calls.
* If RpcError, sending a message rejects with this error.
* If number, sending message is delayed for N milliseconds.
* If omitted, sending a message is delayed for 10 milliseconds.
*/
inputMessage?: RpcError | number;
/**
* Input stream behaviour for client streaming and bidi calls.
* If RpcError, completing the stream rejects with this error.
* If number, completing the stream is delayed for N milliseconds.
* If omitted, completing the stream is delayed for 10 milliseconds.
*/
inputComplete?: RpcError | number;
/**
* If not provided, defaults to `{ responseHeader: "test" }`
* If RpcError, the "headers" promise is rejected with this error.
*/
headers?: RpcMetadata | RpcError;
/**
* If not provided, transport creates default output message using method info
* If RpcError, the "response" promise / stream is rejected with this error.
*/
response?: object | readonly object[] | RpcError;
/**
* If not provided, defaults to `{ code: "OK", detail: "all good" }`
* If RpcError, the "status" promise is rejected with this error.
*/
status?: RpcStatus | RpcError;
/**
* If not provided, defaults to `{ responseTrailer: "test" }`
* If RpcError, the "trailers" promise is rejected with this error.
*/
trailers?: RpcMetadata | RpcError;
}
/**
* Transport for testing.
*/
export class TestTransport implements RpcTransport {
static readonly defaultHeaders: Readonly<RpcMetadata> = {
responseHeader: "test"
};
static readonly defaultStatus: Readonly<RpcStatus> = {
code: "OK", detail: "all good"
};
static readonly defaultTrailers: Readonly<RpcMetadata> = {
responseTrailer: "test"
};
/**
* Sent message(s) during the last operation.
*/
public get sentMessages(): any[] {
if (this.lastInput instanceof TestInputStream) {
return this.lastInput.sent;
} else if (typeof this.lastInput == "object") {
return [this.lastInput.single];
}
return [];
}
/**
* Sending message(s) completed?
*/
public get sendComplete(): boolean {
if (this.lastInput instanceof TestInputStream) {
return this.lastInput.completed;
} else if (typeof this.lastInput == "object") {
return true;
}
return false;
}
/**
* Suppress warning / error about uncaught rejections of
* "status" and "trailers".
*/
public suppressUncaughtRejections = true;
private readonly data: TestTransportMockData;
private readonly headerDelay = 10;
private readonly responseDelay = 50;
private readonly betweenResponseDelay = 10;
private readonly afterResponseDelay = 10;
private lastInput: TestInputStream<any> | { single: any } | undefined
/**
* Initialize with mock data. Omitted fields have default value.
*/
constructor(data?: TestTransportMockData) {
this.data = data ?? {};
}
// Creates a promise for response headers from the mock data.
private promiseHeaders(): Promise<RpcMetadata> {
const headers = this.data.headers ?? TestTransport.defaultHeaders;
return headers instanceof RpcError
? Promise.reject(headers)
: Promise.resolve(headers);
}
// Creates a promise for a single, valid, message from the mock data.
private promiseSingleResponse(method: MethodInfo): Promise<any> {
if (this.data.response instanceof RpcError) {
return Promise.reject(this.data.response);
}
let r: object;
if (Array.isArray(this.data.response)) {
assert(this.data.response.length > 0);
r = this.data.response[0];
} else if (this.data.response !== undefined) {
r = this.data.response;
} else {
r = method.O.create();
}
assert(method.O.is(r));
return Promise.resolve(r);
}
/**
* Pushes response messages from the mock data to the output stream.
* If an error response, status or trailers are mocked, the stream is
* closed with the respective error.
* Otherwise, stream is completed successfully.
*
* The returned promise resolves when the stream is closed. It should
* not reject. If it does, code is broken.
*/
private async streamResponses<I extends object, O extends object>(method: MethodInfo<I, O>, stream: RpcOutputStreamController<O>, abort?: AbortSignal): Promise<void> {
// normalize "data.response" into an array of valid output messages
const messages: O[] = [];
if (this.data.response === undefined) {
messages.push(method.O.create());
} else if (Array.isArray(this.data.response)) {
for (let msg of this.data.response) {
assert(method.O.is(msg));
messages.push(msg);
}
} else if (!(this.data.response instanceof RpcError)) {
assert(method.O.is(this.data.response));
messages.push(this.data.response);
}
// start the stream with an initial delay.
// if the request is cancelled, notify() error and exit.
try {
await delay(this.responseDelay, abort)(undefined);
} catch (error) {
stream.notifyError(error);
return;
}
// if error response was mocked, notify() error (stream is now closed with error) and exit.
if (this.data.response instanceof RpcError) {
stream.notifyError(this.data.response);
return;
}
// regular response messages were mocked. notify() them.
for (let msg of messages) {
stream.notifyMessage(msg);
// add a short delay between responses
// if the request is cancelled, notify() error and exit.
try {
await delay(this.betweenResponseDelay, abort)(undefined);
} catch (error) {
stream.notifyError(error);
return;
}
}
// error status was mocked, notify() error (stream is now closed with error) and exit.
if (this.data.status instanceof RpcError) {
stream.notifyError(this.data.status);
return;
}
// error trailers were mocked, notify() error (stream is now closed with error) and exit.
if (this.data.trailers instanceof RpcError) {
stream.notifyError(this.data.trailers);
return;
}
// stream completed successfully
stream.notifyComplete();
}
// Creates a promise for response status from the mock data.
private promiseStatus(): Promise<RpcStatus> {
const status = this.data.status ?? TestTransport.defaultStatus;
return status instanceof RpcError
? Promise.reject(status)
: Promise.resolve(status);
}
// Creates a promise for response trailers from the mock data.
private promiseTrailers(): Promise<RpcMetadata> {
const trailers = this.data.trailers ?? TestTransport.defaultTrailers;
return trailers instanceof RpcError
? Promise.reject(trailers)
: Promise.resolve(trailers);
}
private maybeSuppressUncaught(...promise: Promise<any>[]): void {
if (this.suppressUncaughtRejections) {
for (let p of promise) {
p.catch(() => {
});
}
}
}
mergeOptions(options?: Partial<RpcOptions>): RpcOptions {
return mergeRpcOptions({}, options);
}
unary<I extends object, O extends object>(method: MethodInfo<I, O>, input: I, options: RpcOptions): UnaryCall<I, O> {
const
requestHeaders = options.meta ?? {},
headersPromise = this.promiseHeaders()
.then(delay(this.headerDelay, options.abort)),
responsePromise: Promise<O> = headersPromise
.catch(_ => {
})
.then(delay(this.responseDelay, options.abort))
.then(_ => this.promiseSingleResponse(method)),
statusPromise = responsePromise
.catch(_ => {
})
.then(delay(this.afterResponseDelay, options.abort))
.then(_ => this.promiseStatus()),
trailersPromise = responsePromise
.catch(_ => {
})
.then(delay(this.afterResponseDelay, options.abort))
.then(_ => this.promiseTrailers());
this.maybeSuppressUncaught(statusPromise, trailersPromise);
this.lastInput = {single: input};
return new UnaryCall(method, requestHeaders, input, headersPromise, responsePromise, statusPromise, trailersPromise);
}
serverStreaming<I extends object, O extends object>(method: MethodInfo<I, O>, input: I, options: RpcOptions): ServerStreamingCall<I, O> {
const
requestHeaders = options.meta ?? {},
headersPromise = this.promiseHeaders()
.then(delay(this.headerDelay, options.abort)),
outputStream = new RpcOutputStreamController<O>(),
responseStreamClosedPromise = headersPromise
.then(delay(this.responseDelay, options.abort))
.catch(() => {
})
.then(() => this.streamResponses(method, outputStream, options.abort))
.then(delay(this.afterResponseDelay, options.abort)),
statusPromise = responseStreamClosedPromise
.then(() => this.promiseStatus()),
trailersPromise = responseStreamClosedPromise
.then(() => this.promiseTrailers());
this.maybeSuppressUncaught(statusPromise, trailersPromise);
this.lastInput = {single: input};
return new ServerStreamingCall<I, O>(method, requestHeaders, input, headersPromise, outputStream, statusPromise, trailersPromise);
}
clientStreaming<I extends object, O extends object>(method: MethodInfo<I, O>, options: RpcOptions): ClientStreamingCall<I, O> {
const
requestHeaders = options.meta ?? {},
headersPromise = this.promiseHeaders()
.then(delay(this.headerDelay, options.abort)),
responsePromise: Promise<O> = headersPromise
.catch(_ => {
})
.then(delay(this.responseDelay, options.abort))
.then(_ => this.promiseSingleResponse(method)),
statusPromise = responsePromise
.catch(_ => {
})
.then(delay(this.afterResponseDelay, options.abort))
.then(_ => this.promiseStatus()),
trailersPromise = responsePromise
.catch(_ => {
})
.then(delay(this.afterResponseDelay, options.abort))
.then(_ => this.promiseTrailers());
this.maybeSuppressUncaught(statusPromise, trailersPromise);
this.lastInput = new TestInputStream(this.data, options.abort);
return new ClientStreamingCall<I, O>(method, requestHeaders, this.lastInput, headersPromise, responsePromise, statusPromise, trailersPromise);
}
duplex<I extends object, O extends object>(method: MethodInfo<I, O>, options: RpcOptions): DuplexStreamingCall<I, O> {
const
requestHeaders = options.meta ?? {},
headersPromise = this.promiseHeaders()
.then(delay(this.headerDelay, options.abort)),
outputStream = new RpcOutputStreamController<O>(),
responseStreamClosedPromise = headersPromise
.then(delay(this.responseDelay, options.abort))
.catch(() => {
})
.then(() => this.streamResponses(method, outputStream, options.abort))
.then(delay(this.afterResponseDelay, options.abort)),
statusPromise = responseStreamClosedPromise
.then(() => this.promiseStatus()),
trailersPromise = responseStreamClosedPromise
.then(() => this.promiseTrailers());
this.maybeSuppressUncaught(statusPromise, trailersPromise);
this.lastInput = new TestInputStream(this.data, options.abort);
return new DuplexStreamingCall<I, O>(method, requestHeaders, this.lastInput, headersPromise, outputStream, statusPromise, trailersPromise);
}
}
function delay<T>(ms: number, abort?: AbortSignal): (v: T) => Promise<T> {
return (v: T) => new Promise<T>((resolve, reject) => {
if (abort?.aborted) {
reject(new RpcError("user cancel", "CANCELLED"));
} else {
const id = setTimeout(() => resolve(v), ms);
if (abort) {
abort.addEventListener("abort", ev => {
clearTimeout(id);
reject(new RpcError("user cancel", "CANCELLED"));
});
}
}
});
}
class TestInputStream<T> implements RpcInputStream<T> {
public get sent(): T[] {
return this._sent;
}
public get completed(): boolean {
return this._completed;
}
private _completed = false;
private readonly _sent: T[] = [];
private readonly data: Pick<TestTransportMockData, "inputMessage" | "inputComplete">;
private readonly abort?: AbortSignal;
constructor(data: Pick<TestTransportMockData, "inputMessage" | "inputComplete">, abort?: AbortSignal) {
this.data = data;
this.abort = abort;
}
send(message: T): Promise<void> {
if (this.data.inputMessage instanceof RpcError) {
return Promise.reject(this.data.inputMessage);
}
const delayMs = this.data.inputMessage === undefined
? 10
: this.data.inputMessage;
return Promise.resolve(undefined)
.then(() => {
this._sent.push(message);
})
.then(delay(delayMs, this.abort));
}
complete(): Promise<void> {
if (this.data.inputComplete instanceof RpcError) {
return Promise.reject(this.data.inputComplete);
}
const delayMs = this.data.inputComplete === undefined
? 10
: this.data.inputComplete;
return Promise.resolve(undefined)
.then(() => {
this._completed = true;
})
.then(delay(delayMs, this.abort));
}
} | the_stack |
import * as sls from "../socketLib/socketLibServer";
import * as contract from "./socketContract";
import http = require("http");
import https = require("https");
import * as fsu from "../server/utils/fsu";
import * as flm from "../server/workers/fileListing/fileListingMaster";
import * as workingDir from "../server/disk/workingDir";
import { FileModel } from "../server/disk/fileModel";
import * as gitService from "../server/workers/external/gitService";
import * as npmService from "../server/workers/external/npmService";
import * as findAndReplaceMultiService from "../server/workers/external/findAndReplaceMultiService";
import * as configCreatorService from "../server/workers/external/configCreatorService";
import * as settings from "../server/disk/settings";
import * as serverDiskService from "../server/workers/external/serverDiskService";
import * as session from "../server/disk/session";
import * as utils from "../common/utils";
import { TypedEvent } from '../common/events';
import { onServerExit } from "./serverExit";
import * as bundlerMaster from '../server/workers/external/demoReact/bundler/bundlerMaster';
let resolve = sls.resolve;
import * as fmc from "../server/disk/fileModelCache";
import * as activeProjectConfig from "../server/disk/activeProjectConfig";
import { errorsCache } from "../server/globalErrorCacheServer";
import * as projectServiceMaster from "../server/workers/lang/projectServiceMaster";
import { testCache, working as testedWorking } from "../server/workers/tested/testedMaster";
import * as demoService from '../server/workers/external/demoService';
import * as demoReactService from '../server/workers/external/demoReact/bundler/bundlerMaster';
export const serverGotExplicitSaveCommand = new TypedEvent<{ filePath: string }>();
namespace Server {
export var echo: typeof contract.server.echo = (data, client) => {
console.log('Echo request received:', data);
return client.increment({ num: data.num }).then((res) => {
return {
text: data.text,
num: res.num
};
});
}
export var filePaths: typeof contract.server.filePaths = (data) => {
return flm.filePathsUpdated.current().then(res => ({ filePaths: res.filePaths, completed: res.completed, rootDir: res.rootDir }));
}
export var makeAbsolute: typeof contract.server.makeAbsolute = (data) => {
return Promise.resolve({ filePath: workingDir.makeAbsolute(data.relativeFilePath) });
}
/**
* File stuff
*/
export var openFile: typeof contract.server.openFile = (data) => {
let file = fmc.getOrCreateOpenFile(data.filePath, /*autoCreate*/ true);
return resolve({ contents: file.getContents(), saved: file.saved(), editorOptions: file.editorOptions });
}
export var closeFile: typeof contract.server.closeFile = (data) => {
fmc.closeOpenFile(data.filePath);
return resolve({});
}
export var editFile: typeof contract.server.editFile = (data) => {
let file = fmc.getOrCreateOpenFile(data.filePath);
let {saved} = file.edits(data.edits);
// console.log('-------------------------');
// console.log(file.getContents());
return resolve({ saved });
}
export var saveFile: typeof contract.server.saveFile = (data) => {
fmc.saveOpenFile(data.filePath);
serverGotExplicitSaveCommand.emit({ filePath: data.filePath });
return resolve({});
}
export var getFileStatus: typeof contract.server.getFileStatus = (data) => {
let file = fmc.getOrCreateOpenFile(data.filePath, /*autoCreate*/ true);
return resolve({ saved: file.saved() });
}
export var addFile: typeof contract.server.addFile = (data) => {
let file = fmc.getOrCreateOpenFile(data.filePath, /*autoCreate*/ true);
return resolve({ error: null });
}
export var addFolder: typeof contract.server.addFolder = (data) => {
let file = fmc.addFolder(data.filePath);
return resolve({ error: null });
}
export var deleteFromDisk: typeof contract.server.deleteFromDisk = (data) => {
let file = fmc.deleteFromDisk(data);
return resolve({ errors: [] });
}
export var duplicateFile: typeof contract.server.duplicateFile = (data) => {
let file = fmc.duplicateFile(data);
return resolve({ error: null });
}
export var duplicateDir: typeof contract.server.duplicateDir = (data) => {
return fmc.duplicateDir(data).then(error => {
return { error };
});
}
export var movePath: typeof contract.server.movePath = (data) => {
return fmc.movePath(data).then(error => {
return { error };
});
}
export var launchDirectory: typeof contract.server.launchDirectory = (data) => {
return fmc.launchDirectory(data);
}
export var launchTerminal: typeof contract.server.launchTerminal = (data) => {
return fmc.launchTerminal(data);
}
/**
* Config stuff
*/
export var availableProjects: typeof contract.server.availableProjects = (data) => {
return activeProjectConfig.availableProjects.current();
};
export var getActiveProjectConfigDetails: typeof contract.server.getActiveProjectConfigDetails = (data) => {
return activeProjectConfig.activeProjectConfigDetailsUpdated.current();
};
export var setActiveProjectConfigDetails: typeof contract.server.setActiveProjectConfigDetails = (data) => {
activeProjectConfig.syncCore(data);
return resolve({});
};
export var isFilePathInActiveProject: typeof contract.server.isFilePathInActiveProject = (data) => {
return activeProjectConfig.projectFilePathsUpdated.current().then(res => {
const inActiveProject = res.filePaths.some(fp => fp === data.filePath);
return { inActiveProject };
});
};
export var setOpenUITabs: typeof contract.server.setOpenUITabs = (data) => {
session.setOpenUITabs(data.sessionId, data.tabLayout, data.selectedTabId);
return resolve({});
};
export var getOpenUITabs: typeof contract.server.getOpenUITabs = (data) => {
const result = session.getOpenUITabs(data.sessionId);
return resolve(result);
};
export var activeProjectFilePaths: typeof contract.server.activeProjectFilePaths = (data) => {
return activeProjectConfig.projectFilePathsUpdated.current();
};
export var sync: typeof contract.server.sync = (data) => {
activeProjectConfig.sync();
return resolve({});
};
export var setSetting: typeof contract.server.setSetting = (data) => {
session.setSetting(data);
return resolve({});
};
export var getSetting: typeof contract.server.getSetting = (data) => {
return resolve(session.getSetting(data));
};
export var getValidSessionId: typeof contract.server.getValidSessionId = (data) => {
return resolve(session.getValidSessionId(data.sessionId));
};
/**
* Error handling
*/
export var getErrors: typeof contract.server.getErrors = (data) => {
return resolve(errorsCache.getErrors());
}
/**
* Tested
*/
export var getTestResults: typeof contract.server.getTestResults = (data) => {
return resolve(testCache.getResults());
}
/**
* Project service
*/
export var getCompletionsAtPosition: typeof contract.server.getCompletionsAtPosition = (query) => {
return projectServiceMaster.worker.getCompletionsAtPosition(query);
}
export var quickInfo: typeof contract.server.quickInfo = (query) => {
return projectServiceMaster.worker.quickInfo(query);
}
export var getCompletionEntryDetails: typeof contract.server.getCompletionEntryDetails = projectServiceMaster.worker.getCompletionEntryDetails;
export var getRenameInfo: typeof contract.server.getRenameInfo = projectServiceMaster.worker.getRenameInfo;
export var getDefinitionsAtPosition: typeof contract.server.getDefinitionsAtPosition = projectServiceMaster.worker.getDefinitionsAtPosition;
export var getDoctorInfo: typeof contract.server.getDoctorInfo = projectServiceMaster.worker.getDoctorInfo;
export var getReferences: typeof contract.server.getReferences = projectServiceMaster.worker.getReferences;
export var formatDocument: typeof contract.server.formatDocument = projectServiceMaster.worker.formatDocument;
export var formatDocumentRange: typeof contract.server.formatDocumentRange = projectServiceMaster.worker.formatDocumentRange;
export var getNavigateToItems: typeof contract.server.getNavigateToItems = projectServiceMaster.worker.getNavigateToItems;
export var getNavigateToItemsForFilePath: typeof contract.server.getNavigateToItemsForFilePath = projectServiceMaster.worker.getNavigateToItemsForFilePath;
export var getDependencies: typeof contract.server.getDependencies = projectServiceMaster.worker.getDependencies;
export var getAST: typeof contract.server.getAST = projectServiceMaster.worker.getAST;
export var getQuickFixes: typeof contract.server.getQuickFixes = projectServiceMaster.worker.getQuickFixes;
export var applyQuickFix: typeof contract.server.applyQuickFix = projectServiceMaster.worker.applyQuickFix;
export var build: typeof contract.server.build = projectServiceMaster.worker.build;
export var getSemanticTree: typeof contract.server.getSemanticTree = projectServiceMaster.worker.getSemanticTree;
export var getOccurrencesAtPosition: typeof contract.server.getOccurrencesAtPosition = projectServiceMaster.worker.getOccurrencesAtPosition;
export var getFormattingEditsAfterKeystroke: typeof contract.server.getFormattingEditsAfterKeystroke = projectServiceMaster.worker.getFormattingEditsAfterKeystroke;
export var removeUnusedImports: typeof contract.server.removeUnusedImports = projectServiceMaster.worker.removeUnusedImports;
/**
* Documentation browser
*/
export var getTopLevelModuleNames: typeof contract.server.getTopLevelModuleNames = projectServiceMaster.worker.getTopLevelModuleNames;
export var getUpdatedModuleInformation: typeof contract.server.getUpdatedModuleInformation = projectServiceMaster.worker.getUpdatedModuleInformation;
/** UML Diagram */
export var getUmlDiagramForFile: typeof contract.server.getUmlDiagramForFile = projectServiceMaster.worker.getUmlDiagramForFile;
/** tsFlow */
export var getFlowRoots: typeof contract.server.getFlowRoots = projectServiceMaster.worker.getFlowRoots;
/** live analysis */
export var getLiveAnalysis: typeof contract.server.getLiveAnalysis = projectServiceMaster.worker.getLiveAnalysis;
/**
* Output Status
*/
export const getCompleteOutputStatusCache: typeof contract.server.getCompleteOutputStatusCache =
(data) => {
return cast.completeOutputStatusCacheUpdated.current();
}
export const getLiveBuildResults: typeof contract.server.getLiveBuildResults =
(data) => {
return cast.liveBuildResults.current();
}
export const getJSOutputStatus: typeof contract.server.getJSOutputStatus = projectServiceMaster.worker.getJSOutputStatus;
/**
* Live demo
*/
export const enableLiveDemo = demoService.WorkerImplementation.enableLiveDemo;
export const disableLiveDemo = demoService.WorkerImplementation.disableLiveDemo;
export const enableLiveDemoReact = demoReactService.ExternalAPI.enableLiveDemo;
export const disableLiveDemoReact = demoReactService.ExternalAPI.disableLiveDemo;
/**
* Git service
*/
export var gitStatus: typeof contract.server.gitStatus = gitService.gitStatus;
export var gitReset: typeof contract.server.gitReset = gitService.gitReset;
export var gitDiff: typeof contract.server.gitDiff = gitService.gitDiff;
export var gitAddAllCommitAndPush: typeof contract.server.gitAddAllCommitAndPush = gitService.gitAddAllCommitAndPush;
export var gitFetchLatestAndRebase: typeof contract.server.gitFetchLatestAndRebase = gitService.gitFetchLatestAndRebase;
/**
* NPM service
*/
export var npmLatest: typeof contract.server.npmLatest = npmService.npmLatest;
/**
* FARM
*/
export var startFarming: typeof contract.server.startFarming = findAndReplaceMultiService.startFarming;
export var stopFarmingIfRunning: typeof contract.server.stopFarmingIfRunning = findAndReplaceMultiService.stopFarmingIfRunning;
export var farmResults: typeof contract.server.farmResults = (query: {}) => findAndReplaceMultiService.farmResultsUpdated.current();
/**
* Config creator
*/
export const createEditorconfig = configCreatorService.createEditorconfig;
/**
* Settings
*/
export const getSettingsFilePath: typeof contract.server.getSettingsFilePath = (query: {}) => Promise.resolve({ filePath: settings.getSettingsFilePath() });
/**
* Server Disk Service
*/
export const getDirItems: typeof contract.server.getDirItems = (query: { dirPath: string }) => Promise.resolve({ dirItems: serverDiskService.getDirItems(query.dirPath) });
}
// Ensure that the namespace follows the contract
var _checkTypes: typeof contract.server = Server;
/** Will be available after register is called */
export let cast = contract.cast;
/** launch server */
export function register(app: http.Server | https.Server) {
let runResult = sls.run({
app,
serverImplementation: Server,
clientContract: contract.client,
cast: contract.cast
});
cast = runResult.cast;
/** File model */
fmc.savedFileChangedOnDisk.pipe(cast.savedFileChangedOnDisk);
fmc.didEdits.pipe(cast.didEdits);
fmc.didStatusChange.pipe(cast.didStatusChange);
fmc.editorOptionsChanged.pipe(cast.editorOptionsChanged);
/** File listing updates */
flm.filePathsUpdated.pipe(cast.filePathsUpdated);
/** Active Project */
activeProjectConfig.availableProjects.pipe(cast.availableProjectsUpdated);
activeProjectConfig.activeProjectConfigDetailsUpdated.pipe(cast.activeProjectConfigDetailsUpdated);
activeProjectConfig.projectFilePathsUpdated.pipe(cast.activeProjectFilePathsUpdated);
activeProjectConfig.errorsInTsconfig.errorsDelta.on((delta) => errorsCache.applyDelta(delta));
/** Errors */
errorsCache.errorsDelta.pipe(cast.errorsDelta);
/** Tested */
testCache.testResultsDelta.pipe(cast.testResultsDelta);
testedWorking.pipe(cast.testedWorking);
/** FARM */
findAndReplaceMultiService.farmResultsUpdated.pipe(cast.farmResultsUpdated);
/** JS Output Status */
cast.liveBuildResults.emit({ builtCount: 0, totalCount: 0 }); // for initial joiners
cast.completeOutputStatusCacheUpdated.emit({}); // for initial joiners
projectServiceMaster.fileOutputStatusUpdated.pipe(cast.fileOutputStatusUpdated);
projectServiceMaster.completeOutputStatusCacheUpdated.pipe(cast.completeOutputStatusCacheUpdated);
projectServiceMaster.liveBuildResults.pipe(cast.liveBuildResults);
/** Live demo */
demoService.WorkerImplementation.liveDemoData.pipe(cast.liveDemoData);
bundlerMaster.liveDemoBuildComplete.pipe(cast.liveDemoBuildComplete);
serverGotExplicitSaveCommand.on(e => {
if (e.filePath === demoService.WorkerImplementation.currentFilePath) {
demoService.WorkerImplementation.enableLiveDemo({ filePath: e.filePath });
}
if (e.filePath === demoReactService.ExternalAPI.currentFilePath) {
demoReactService.ExternalAPI.enableLiveDemo({ filePath: e.filePath });
}
})
/** TS Working */
projectServiceMaster.working.pipe(cast.tsWorking);
/** If the server exits notify the clients */
onServerExit(() => cast.serverExiting.emit({}));
// For testing
// setInterval(() => cast.hello.emit({ text: 'nice' }), 1000);
} | the_stack |
import AnchoredData from './models/AnchoredData';
import AnchoredDataSerializer from './AnchoredDataSerializer';
import AnchoredOperationModel from '../../models/AnchoredOperationModel';
import ArrayMethods from './util/ArrayMethods';
import ChunkFile from './ChunkFile';
import ChunkFileModel from './models/ChunkFileModel';
import CoreIndexFile from './CoreIndexFile';
import CoreProofFile from './CoreProofFile';
import DownloadManager from '../../DownloadManager';
import ErrorCode from './ErrorCode';
import FeeManager from './FeeManager';
import FetchResultCode from '../../../common/enums/FetchResultCode';
import IBlockchain from '../../interfaces/IBlockchain';
import IOperationStore from '../../interfaces/IOperationStore';
import ITransactionProcessor from '../../interfaces/ITransactionProcessor';
import IVersionMetadataFetcher from '../../interfaces/IVersionMetadataFetcher';
import LogColor from '../../../common/LogColor';
import Logger from '../../../common/Logger';
import OperationType from '../../enums/OperationType';
import ProtocolParameters from './ProtocolParameters';
import ProvisionalIndexFile from './ProvisionalIndexFile';
import ProvisionalProofFile from './ProvisionalProofFile';
import SidetreeError from '../../../common/SidetreeError';
import TransactionModel from '../../../common/models/TransactionModel';
import ValueTimeLockVerifier from './ValueTimeLockVerifier';
/**
* Implementation of the `ITransactionProcessor`.
*/
export default class TransactionProcessor implements ITransactionProcessor {
public constructor (
private downloadManager: DownloadManager,
private operationStore: IOperationStore,
private blockchain: IBlockchain,
private versionMetadataFetcher: IVersionMetadataFetcher) {
}
public async processTransaction (transaction: TransactionModel): Promise<boolean> {
// Download the core (index and proof) files.
let anchoredData: AnchoredData;
let coreIndexFile: CoreIndexFile;
let coreProofFile: CoreProofFile | undefined;
try {
// Decode the anchor string.
anchoredData = AnchoredDataSerializer.deserialize(transaction.anchorString);
// Verify enough fee paid.
FeeManager.verifyTransactionFeeAndThrowOnError(transaction.transactionFeePaid, anchoredData.numberOfOperations, transaction.normalizedTransactionFee!);
// Download and verify core index file.
coreIndexFile = await this.downloadAndVerifyCoreIndexFile(transaction, anchoredData.coreIndexFileUri, anchoredData.numberOfOperations);
// Download and verify core proof file.
coreProofFile = await this.downloadAndVerifyCoreProofFile(coreIndexFile);
} catch (error) {
let retryNeeded = true;
if (error instanceof SidetreeError) {
// If error is related to CAS network connectivity issues, we need to retry later.
if (error.code === ErrorCode.CasNotReachable ||
error.code === ErrorCode.CasFileNotFound) {
retryNeeded = true;
} else {
// eslint-disable-next-line max-len
Logger.info(LogColor.lightBlue(`Invalid core file found for anchor string '${LogColor.green(transaction.anchorString)}', the entire batch is discarded. Error: ${LogColor.yellow(error.message)}`));
retryNeeded = false;
}
} else {
Logger.error(LogColor.red(`Unexpected error while fetching and downloading core files, MUST investigate and fix: ${error.message}`));
retryNeeded = true;
}
const transactionProcessedCompletely = !retryNeeded;
return transactionProcessedCompletely;
}
// Once code reaches here, it means core files are valid. In order to be compatible with the future data-pruning feature,
// the operations referenced in core index file must be retained regardless of the validity of provisional and chunk files.
// Download provisional and chunk files.
let retryNeeded: boolean;
let provisionalIndexFile: ProvisionalIndexFile | undefined;
let provisionalProofFile: ProvisionalProofFile | undefined;
let chunkFileModel: ChunkFileModel | undefined;
try {
// Download and verify provisional index file.
provisionalIndexFile = await this.downloadAndVerifyProvisionalIndexFile(coreIndexFile, anchoredData.numberOfOperations);
// Download and verify provisional proof file.
provisionalProofFile = await this.downloadAndVerifyProvisionalProofFile(provisionalIndexFile);
// Download and verify chunk file.
chunkFileModel = await this.downloadAndVerifyChunkFile(coreIndexFile, provisionalIndexFile);
retryNeeded = false;
} catch (error) {
// If we encounter any error, regardless of whether the transaction should be retried for processing,
// we set all the provisional/chunk files to be `undefined`,
// this is because chunk file would not be available/valid for its deltas to be used during resolutions,
// thus no need to store the operation references found in the provisional index file.
provisionalIndexFile = undefined;
provisionalProofFile = undefined;
chunkFileModel = undefined;
// Now we decide if we should try to process this transaction again in the future.
if (error instanceof SidetreeError) {
// If error is related to CAS network connectivity issues, we need to retry later.
if (error.code === ErrorCode.CasNotReachable ||
error.code === ErrorCode.CasFileNotFound) {
retryNeeded = true;
} else {
// eslint-disable-next-line max-len
Logger.info(LogColor.lightBlue(`Invalid provisional/chunk file found for anchor string '${LogColor.green(transaction.anchorString)}', the entire batch is discarded. Error: ${LogColor.yellow(error.message)}`));
retryNeeded = false;
}
} else {
Logger.error(LogColor.red(`Unexpected error while fetching and downloading provisional files, MUST investigate and fix: ${error.message}`));
retryNeeded = true;
}
}
// Once code reaches here, it means all the files that are not `undefined` (and their relationships) are validated,
// there is no need to perform any more validations at this point, we just need to compose the anchored operations and store them.
// Compose using files downloaded into anchored operations.
const operations = await this.composeAnchoredOperationModels(
transaction, coreIndexFile, provisionalIndexFile, coreProofFile, provisionalProofFile, chunkFileModel
);
await this.operationStore.insertOrReplace(operations);
Logger.info(LogColor.lightBlue(`Processed ${LogColor.green(operations.length)} operations. Retry needed: ${LogColor.green(retryNeeded)}`));
const transactionProcessedCompletely = !retryNeeded;
return transactionProcessedCompletely;
}
private async downloadAndVerifyCoreIndexFile (transaction: TransactionModel, coreIndexFileUri: string, paidOperationCount: number): Promise<CoreIndexFile> {
// Verify the number of paid operations does not exceed the maximum allowed limit.
if (paidOperationCount > ProtocolParameters.maxOperationsPerBatch) {
throw new SidetreeError(
ErrorCode.TransactionProcessorPaidOperationCountExceedsLimit,
`Paid batch size of ${paidOperationCount} operations exceeds the allowed limit of ${ProtocolParameters.maxOperationsPerBatch}.`
);
}
Logger.info(`Downloading core index file '${coreIndexFileUri}', max file size limit ${ProtocolParameters.maxCoreIndexFileSizeInBytes} bytes...`);
const fileBuffer = await this.downloadFileFromCas(coreIndexFileUri, ProtocolParameters.maxCoreIndexFileSizeInBytes);
const coreIndexFile = await CoreIndexFile.parse(fileBuffer);
const operationCountInCoreIndexFile = coreIndexFile.didUniqueSuffixes.length;
if (operationCountInCoreIndexFile > paidOperationCount) {
throw new SidetreeError(
ErrorCode.CoreIndexFileOperationCountExceededPaidLimit,
`Operation count ${operationCountInCoreIndexFile} in core index file exceeded limit of : ${paidOperationCount}`);
}
// Verify required lock if one was needed.
const valueTimeLock = coreIndexFile.model.writerLockId
? await this.blockchain.getValueTimeLock(coreIndexFile.model.writerLockId)
: undefined;
ValueTimeLockVerifier.verifyLockAmountAndThrowOnError(
valueTimeLock,
paidOperationCount,
transaction.transactionTime,
transaction.writer,
this.versionMetadataFetcher);
return coreIndexFile;
}
private async downloadAndVerifyCoreProofFile (coreIndexFile: CoreIndexFile): Promise<CoreProofFile | undefined> {
const coreProofFileUri = coreIndexFile.model.coreProofFileUri;
if (coreProofFileUri === undefined) {
return;
}
Logger.info(`Downloading core proof file '${coreProofFileUri}', max file size limit ${ProtocolParameters.maxProofFileSizeInBytes}...`);
const fileBuffer = await this.downloadFileFromCas(coreProofFileUri, ProtocolParameters.maxProofFileSizeInBytes);
const coreProofFile = await CoreProofFile.parse(fileBuffer, coreIndexFile.deactivateDidSuffixes);
const recoverAndDeactivateCount = coreIndexFile.deactivateDidSuffixes.length + coreIndexFile.recoverDidSuffixes.length;
const proofCountInCoreProofFile = coreProofFile.deactivateProofs.length + coreProofFile.recoverProofs.length;
if (recoverAndDeactivateCount !== proofCountInCoreProofFile) {
throw new SidetreeError(
ErrorCode.CoreProofFileProofCountNotTheSameAsOperationCountInCoreIndexFile,
`Proof count of ${proofCountInCoreProofFile} in core proof file different to ` +
`recover + deactivate count of ${recoverAndDeactivateCount} in core index file.`
);
}
return coreProofFile;
}
private async downloadAndVerifyProvisionalProofFile (provisionalIndexFile: ProvisionalIndexFile | undefined): Promise<ProvisionalProofFile | undefined> {
// If there is no provisional proof file to download, just return.
if (provisionalIndexFile === undefined || provisionalIndexFile.model.provisionalProofFileUri === undefined) {
return;
}
const provisionalProofFileUri = provisionalIndexFile.model.provisionalProofFileUri;
Logger.info(`Downloading provisional proof file '${provisionalProofFileUri}', max file size limit ${ProtocolParameters.maxProofFileSizeInBytes}...`);
const fileBuffer = await this.downloadFileFromCas(provisionalProofFileUri, ProtocolParameters.maxProofFileSizeInBytes);
const provisionalProofFile = await ProvisionalProofFile.parse(fileBuffer);
const operationCountInProvisionalIndexFile = provisionalIndexFile.didUniqueSuffixes.length;
const proofCountInProvisionalProofFile = provisionalProofFile.updateProofs.length;
if (operationCountInProvisionalIndexFile !== proofCountInProvisionalProofFile) {
throw new SidetreeError(
ErrorCode.ProvisionalProofFileProofCountNotTheSameAsOperationCountInProvisionalIndexFile,
`Proof count ${proofCountInProvisionalProofFile} in provisional proof file is different from ` +
`operation count ${operationCountInProvisionalIndexFile} in provisional index file.`
);
}
return provisionalProofFile;
}
private async downloadAndVerifyProvisionalIndexFile (coreIndexFile: CoreIndexFile, paidOperationCount: number): Promise<ProvisionalIndexFile | undefined> {
const coreIndexFileModel = coreIndexFile.model;
// If no provisional index file URI is defined (legitimate case when there is only deactivates in the operation batch),
// then no provisional index file to download.
const provisionalIndexFileUri = coreIndexFileModel.provisionalIndexFileUri;
if (provisionalIndexFileUri === undefined) {
return undefined;
}
Logger.info(
`Downloading provisional index file '${provisionalIndexFileUri}', max file size limit ${ProtocolParameters.maxProvisionalIndexFileSizeInBytes}...`
);
const fileBuffer = await this.downloadFileFromCas(provisionalIndexFileUri, ProtocolParameters.maxProvisionalIndexFileSizeInBytes);
const provisionalIndexFile = await ProvisionalIndexFile.parse(fileBuffer);
// Calculate the max paid update operation count.
const operationCountInCoreIndexFile = coreIndexFile.didUniqueSuffixes.length;
const maxPaidUpdateOperationCount = paidOperationCount - operationCountInCoreIndexFile;
const updateOperationCount = provisionalIndexFile.didUniqueSuffixes.length;
if (updateOperationCount > maxPaidUpdateOperationCount) {
throw new SidetreeError(
ErrorCode.ProvisionalIndexFileUpdateOperationCountGreaterThanMaxPaidCount,
`Update operation count of ${updateOperationCount} in provisional index file is greater than max paid count of ${maxPaidUpdateOperationCount}.`
);
}
// If we find operations for the same DID between anchor and provisional index files,
// we will penalize the writer by not accepting any updates.
if (!ArrayMethods.areMutuallyExclusive(coreIndexFile.didUniqueSuffixes, provisionalIndexFile.didUniqueSuffixes)) {
throw new SidetreeError(
ErrorCode.ProvisionalIndexFileDidReferenceDuplicatedWithCoreIndexFile,
`Provisional index file has at least one DID reference duplicated with core index file.`
);
}
return provisionalIndexFile;
}
private async downloadAndVerifyChunkFile (
coreIndexFile: CoreIndexFile,
provisionalIndexFile: ProvisionalIndexFile | undefined
): Promise<ChunkFileModel | undefined> {
// Can't download chunk file if provisional index file is not given.
if (provisionalIndexFile === undefined) {
return undefined;
}
const chunkFileUri = provisionalIndexFile.model.chunks[0].chunkFileUri;
Logger.info(`Downloading chunk file '${chunkFileUri}', max size limit ${ProtocolParameters.maxChunkFileSizeInBytes}...`);
const fileBuffer = await this.downloadFileFromCas(chunkFileUri, ProtocolParameters.maxChunkFileSizeInBytes);
const chunkFileModel = await ChunkFile.parse(fileBuffer);
const totalCountOfOperationsWithDelta =
coreIndexFile.createDidSuffixes.length + coreIndexFile.recoverDidSuffixes.length + provisionalIndexFile.didUniqueSuffixes.length;
if (chunkFileModel.deltas.length !== totalCountOfOperationsWithDelta) {
throw new SidetreeError(
ErrorCode.ChunkFileDeltaCountIncorrect,
`Delta array length ${chunkFileModel.deltas.length} is not the same as the count of ${totalCountOfOperationsWithDelta} operations with delta.`
);
}
return chunkFileModel;
}
private async composeAnchoredOperationModels (
transaction: TransactionModel,
coreIndexFile: CoreIndexFile,
provisionalIndexFile: ProvisionalIndexFile | undefined,
coreProofFile: CoreProofFile | undefined,
provisionalProofFile: ProvisionalProofFile | undefined,
chunkFile: ChunkFileModel | undefined
): Promise<AnchoredOperationModel[]> {
const anchoredCreateOperationModels = TransactionProcessor.composeAnchoredCreateOperationModels(
transaction, coreIndexFile, chunkFile
);
const anchoredRecoverOperationModels = TransactionProcessor.composeAnchoredRecoverOperationModels(
transaction, coreIndexFile, coreProofFile!, chunkFile
);
const anchoredDeactivateOperationModels = TransactionProcessor.composeAnchoredDeactivateOperationModels(
transaction, coreIndexFile, coreProofFile!
);
const anchoredUpdateOperationModels = TransactionProcessor.composeAnchoredUpdateOperationModels(
transaction, coreIndexFile, provisionalIndexFile, provisionalProofFile, chunkFile
);
const anchoredOperationModels = [];
anchoredOperationModels.push(...anchoredCreateOperationModels);
anchoredOperationModels.push(...anchoredRecoverOperationModels);
anchoredOperationModels.push(...anchoredDeactivateOperationModels);
anchoredOperationModels.push(...anchoredUpdateOperationModels);
return anchoredOperationModels;
}
private static composeAnchoredCreateOperationModels (
transaction: TransactionModel,
coreIndexFile: CoreIndexFile,
chunkFile: ChunkFileModel | undefined
): AnchoredOperationModel[] {
if (coreIndexFile.createDidSuffixes.length === 0) {
return [];
}
let createDeltas;
if (chunkFile !== undefined) {
createDeltas = chunkFile.deltas.slice(0, coreIndexFile.createDidSuffixes.length);
}
const createDidSuffixes = coreIndexFile.createDidSuffixes;
const anchoredOperationModels = [];
for (let i = 0; i < createDidSuffixes.length; i++) {
const suffixData = coreIndexFile.model.operations!.create![i].suffixData;
// Compose the original operation request from the files.
const composedRequest = {
type: OperationType.Create,
suffixData: suffixData,
delta: createDeltas?.[i] // Add `delta` property if chunk file found.
};
// TODO: Issue 442 - https://github.com/decentralized-identity/sidetree/issues/442
// Use actual operation request object instead of buffer.
const operationBuffer = Buffer.from(JSON.stringify(composedRequest));
const anchoredOperationModel: AnchoredOperationModel = {
didUniqueSuffix: createDidSuffixes[i],
type: OperationType.Create,
operationBuffer,
operationIndex: i,
transactionNumber: transaction.transactionNumber,
transactionTime: transaction.transactionTime
};
anchoredOperationModels.push(anchoredOperationModel);
}
return anchoredOperationModels;
}
private static composeAnchoredRecoverOperationModels (
transaction: TransactionModel,
coreIndexFile: CoreIndexFile,
coreProofFile: CoreProofFile,
chunkFile: ChunkFileModel | undefined
): AnchoredOperationModel[] {
if (coreIndexFile.recoverDidSuffixes.length === 0) {
return [];
}
let recoverDeltas;
if (chunkFile !== undefined) {
const recoverDeltaStartIndex = coreIndexFile.createDidSuffixes.length;
const recoverDeltaEndIndexExclusive = recoverDeltaStartIndex + coreIndexFile.recoverDidSuffixes.length;
recoverDeltas = chunkFile.deltas.slice(recoverDeltaStartIndex, recoverDeltaEndIndexExclusive);
}
const recoverDidSuffixes = coreIndexFile.recoverDidSuffixes;
const recoverProofs = coreProofFile.recoverProofs.map((proof) => proof.signedDataJws.toCompactJws());
const anchoredOperationModels = [];
for (let i = 0; i < recoverDidSuffixes.length; i++) {
// Compose the original operation request from the files.
const composedRequest = {
type: OperationType.Recover,
didSuffix: recoverDidSuffixes[i],
revealValue: coreIndexFile.model!.operations!.recover![i].revealValue,
signedData: recoverProofs[i],
delta: recoverDeltas?.[i] // Add `delta` property if chunk file found.
};
// TODO: Issue 442 - https://github.com/decentralized-identity/sidetree/issues/442
// Use actual operation request object instead of buffer.
const operationBuffer = Buffer.from(JSON.stringify(composedRequest));
const anchoredOperationModel: AnchoredOperationModel = {
didUniqueSuffix: recoverDidSuffixes[i],
type: OperationType.Recover,
operationBuffer,
operationIndex: coreIndexFile.createDidSuffixes.length + i,
transactionNumber: transaction.transactionNumber,
transactionTime: transaction.transactionTime
};
anchoredOperationModels.push(anchoredOperationModel);
}
return anchoredOperationModels;
}
private static composeAnchoredDeactivateOperationModels (
transaction: TransactionModel,
coreIndexFile: CoreIndexFile,
coreProofFile: CoreProofFile
): AnchoredOperationModel[] {
if (coreIndexFile.deactivateDidSuffixes.length === 0) {
return [];
}
const deactivateDidSuffixes = coreIndexFile.deactivateDidSuffixes;
const deactivateProofs = coreProofFile.deactivateProofs.map((proof) => proof.signedDataJws.toCompactJws());
const anchoredOperationModels = [];
for (let i = 0; i < deactivateDidSuffixes.length; i++) {
// Compose the original operation request from the files.
const composedRequest = {
type: OperationType.Deactivate,
didSuffix: deactivateDidSuffixes[i],
revealValue: coreIndexFile.model!.operations!.deactivate![i].revealValue,
signedData: deactivateProofs[i]
};
// TODO: Issue 442 - https://github.com/decentralized-identity/sidetree/issues/442
// Use actual operation request object instead of buffer.
const operationBuffer = Buffer.from(JSON.stringify(composedRequest));
const anchoredOperationModel: AnchoredOperationModel = {
didUniqueSuffix: deactivateDidSuffixes[i],
type: OperationType.Deactivate,
operationBuffer,
operationIndex: coreIndexFile.createDidSuffixes.length + coreIndexFile.recoverDidSuffixes.length + i,
transactionNumber: transaction.transactionNumber,
transactionTime: transaction.transactionTime
};
anchoredOperationModels.push(anchoredOperationModel);
}
return anchoredOperationModels;
}
private static composeAnchoredUpdateOperationModels (
transaction: TransactionModel,
coreIndexFile: CoreIndexFile,
provisionalIndexFile: ProvisionalIndexFile | undefined,
provisionalProofFile: ProvisionalProofFile | undefined,
chunkFile: ChunkFileModel | undefined
): AnchoredOperationModel[] {
// If provisional index file is undefined (in the case of batch containing only deactivates) or
// if provisional index file's update operation reference count is zero (in the case of batch containing creates and/or recovers).
if (provisionalIndexFile === undefined ||
provisionalIndexFile.didUniqueSuffixes.length === 0) {
return [];
}
let updateDeltas;
if (chunkFile !== undefined) {
const updateDeltaStartIndex = coreIndexFile.createDidSuffixes.length + coreIndexFile.recoverDidSuffixes.length;
updateDeltas = chunkFile!.deltas.slice(updateDeltaStartIndex);
}
const updateDidSuffixes = provisionalIndexFile.didUniqueSuffixes;
const updateProofs = provisionalProofFile!.updateProofs.map((proof) => proof.signedDataJws.toCompactJws());
const anchoredOperationModels = [];
for (let i = 0; i < updateDidSuffixes.length; i++) {
// Compose the original operation request from the files.
const composedRequest = {
type: OperationType.Update,
didSuffix: updateDidSuffixes[i],
revealValue: provisionalIndexFile.model!.operations!.update[i].revealValue,
signedData: updateProofs[i],
delta: updateDeltas?.[i] // Add `delta` property if chunk file found.
};
// TODO: Issue 442 - https://github.com/decentralized-identity/sidetree/issues/442
// Use actual operation request object instead of buffer.
const operationBuffer = Buffer.from(JSON.stringify(composedRequest));
const anchoredOperationModel: AnchoredOperationModel = {
didUniqueSuffix: updateDidSuffixes[i],
type: OperationType.Update,
operationBuffer,
operationIndex: coreIndexFile.didUniqueSuffixes.length + i,
transactionNumber: transaction.transactionNumber,
transactionTime: transaction.transactionTime
};
anchoredOperationModels.push(anchoredOperationModel);
}
return anchoredOperationModels;
}
private async downloadFileFromCas (fileUri: string, maxFileSizeInBytes: number): Promise<Buffer> {
Logger.info(`Downloading file '${fileUri}', max size limit ${maxFileSizeInBytes}...`);
const fileFetchResult = await this.downloadManager.download(fileUri, maxFileSizeInBytes);
if (fileFetchResult.code === FetchResultCode.InvalidHash) {
throw new SidetreeError(ErrorCode.CasFileUriNotValid, `File hash '${fileUri}' is not a valid hash.`);
}
if (fileFetchResult.code === FetchResultCode.MaxSizeExceeded) {
throw new SidetreeError(ErrorCode.CasFileTooLarge, `File '${fileUri}' exceeded max size limit of ${maxFileSizeInBytes} bytes.`);
}
if (fileFetchResult.code === FetchResultCode.NotAFile) {
throw new SidetreeError(ErrorCode.CasFileNotAFile, `File hash '${fileUri}' points to a content that is not a file.`);
}
if (fileFetchResult.code === FetchResultCode.CasNotReachable) {
throw new SidetreeError(ErrorCode.CasNotReachable, `CAS not reachable for file '${fileUri}'.`);
}
if (fileFetchResult.code === FetchResultCode.NotFound) {
throw new SidetreeError(ErrorCode.CasFileNotFound, `File '${fileUri}' not found.`);
}
Logger.info(`File '${fileUri}' of size ${fileFetchResult.content!.length} downloaded.`);
return fileFetchResult.content!;
}
} | the_stack |
import { Component, ViewChild } from '@angular/core';
import {IonContent} from '@ionic/angular';
import {
InterstitialAdEvents,
BannerAdSize,
BannerAdEvents,
RewardAdEvents,
SplashAdEvents,
Gender, Anchor,
ChildProtection,
UnderAgeOfPromise,
HMSScreenOrientation,
AdContentClassification,
NonPersonalizedAd,
RollAdEvents,
NativeAdEvents,
NativeAdTemplate,
Color,
HMSAds
} from '@hmscore/ionic-native-hms-ads/ngx';
import { from } from 'rxjs';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
@ViewChild(IonContent, { static: false }) content: IonContent;
bannerAdSize: BannerAdSize;
bannerAdColor: Color;
nativeAdSize: NativeAdTemplate;
bannerAd;
rollAdInstance;
nativeAdInstance;
constructor(private hmsAds: HMSAds) {
this.bannerAdSize = BannerAdSize.BANNER_SIZE_360_144;
this.bannerAdColor = Color.TRANSPARENT;
this.nativeAdSize = NativeAdTemplate.NATIVE_AD_SMALL_TEMPLATE;
this.hmsAds.init();
}
getSDKVersion() {
this.hmsAds.getSDKVersion().then(result => alert(JSON.stringify(result)));
}
getAdvertisingIdInfo() {
this.hmsAds.getAdvertisingIdInfo().then(result => alert(JSON.stringify(result)));
}
setRequestOptions() {
const reqOpt = {
adContentClassification: AdContentClassification.AD_CONTENT_CLASSIFICATION_W,
appLang: 'En',
appCountry: 'TR',
tagForChildProtection: ChildProtection.TAG_FOR_CHILD_PROTECTION_FALSE,
tagForUnderAgeOfPromise: UnderAgeOfPromise.PROMISE_TRUE,
nonPersonalizedAd: NonPersonalizedAd.ALLOW_ALL,
};
this.hmsAds.setRequestOptions(reqOpt)
.then((result) => alert('setRequestOptions :: ' + JSON.stringify(result)))
.catch((error) => console.log('setRequestOptions :: Error!', error));
}
getRequestOptions() {
this.hmsAds.getRequestOptions()
.then((result) => alert('getRequestOptions :: ' + JSON.stringify(result)))
.catch((error) => console.log('getRequestOptions :: Error!', error));
}
startClient() {
this.hmsAds.referrerClientStartConnection(true)
.then((result) => alert('referrerClientStartConnection :: ' + JSON.stringify(result)))
.catch((error) => alert('referrerClientStartConnection :: Error!' + error));
}
getReferrerDetails() {
this.hmsAds.getInstallReferrer()
.then((result) => alert('getInstallReferrer :: ' + JSON.stringify(result)))
.catch((error) => alert('getInstallReferrer :: Error!' + error));
this.hmsAds.referrerClientEndConnection()
.then((result) => console.log('referrerClientEndConnection :: ', JSON.stringify(result)))
.catch((error) => console.log('referrerClientEndConnection :: Error!', error));
}
async interstitialAd() {
const interstitialAd = new this.hmsAds.HMSInterstitialAd();
await interstitialAd.create(true);
await interstitialAd.setAdId('testb4znbuh3n2');
await interstitialAd.setAdListener();
interstitialAd.on(
InterstitialAdEvents.INTERSTITIAL_AD_LOADED,
async () => {
await interstitialAd
.isLoaded()
.then((result) => alert('isLoaded -> ' + result))
.catch((error) => console.log('isLoaded => Error!', error));
await interstitialAd.show();
}
);
await interstitialAd.loadAd();
}
async createBannerAd() {
if (this.bannerAd) {
await this.bannerAd.destroy();
}
this.bannerAd = new this.hmsAds.HMSBannerAd();
const banner = document.getElementById('bannerAdElement');
if (this.bannerAdSize === BannerAdSize.BANNER_SIZE_320_50) {
banner.style.height = '50px';
} else if (this.bannerAdSize === BannerAdSize.BANNER_SIZE_300_250) {
banner.style.height = '250px';
} else if (this.bannerAdSize === BannerAdSize.BANNER_SIZE_320_100) {
banner.style.height = '100px';
} else if (this.bannerAdSize === BannerAdSize.BANNER_SIZE_360_144) {
banner.style.height = '144px';
} else if (this.bannerAdSize === BannerAdSize.BANNER_SIZE_360_57) {
banner.style.height = '57px';
} else if (this.bannerAdSize === BannerAdSize.BANNER_SIZE_468_60) {
banner.style.height = '60px';
} else if (this.bannerAdSize === BannerAdSize.BANNER_SIZE_160_600) {
banner.style.height = '600px';
} else if (this.bannerAdSize === BannerAdSize.BANNER_SIZE_728_90) {
banner.style.height = '90px';
} else {
banner.style.height = '200px';
}
await this.bannerAd.create('bannerAdElement');
await this.bannerAd.setAdId('testw6vs28auh3');
await this.bannerAd.setBannerAdSize(this.bannerAdSize);
await this.bannerAd.setBackgroundColor(this.bannerAdColor);
await this.bannerAd.setBannerRefresh(50);
await this.bannerAd.setAdListener();
this.bannerAd.on(BannerAdEvents.BANNER_AD_FAILED, async (result) => {
alert('BANNER_AD_FAILED :: ' + result.message);
});
this.bannerAd.on(BannerAdEvents.BANNER_AD_LOADED, async () => {
console.log('bannerAd Loaded');
});
this.bannerAd.loadAd();
}
async rewardAd() {
const rewardAd = new this.hmsAds.HMSRewardAd();
await rewardAd.create('testx9dtjwj8hp');
rewardAd.on(RewardAdEvents.REWARDED_LOADED, async () => {
await rewardAd.show(true); // if you use loadAdWithAdId() function ,call setRewardAdListener(), listen HMSConstants.RewardAdEvents.REWARD_AD_LOADED and HMSConstants.RewardAdEvents.REWARDED
});
rewardAd.on(RewardAdEvents.REWARDED_STATUS, (reward) => {
console.log('Reward => ', JSON.stringify(reward));
});
await rewardAd.loadAd();
}
async splashAd() {
const splashAd = new this.hmsAds.HMSSplashAd();
await splashAd.create();
await splashAd.setLogo('public/assets/logo.html');
await splashAd.setSloganResId('default_slogan');
splashAd.setAdDisplayListener();
splashAd.on(SplashAdEvents.SPLASH_AD_LOADED, async () => {
console.log('splash loaded');
});
splashAd.on(SplashAdEvents.SPLASH_AD_DISMISSED, async () => {
await splashAd.destroyView();
});
const adParams = {
gender: Gender.FEMALE,
adContentClassification:
AdContentClassification.AD_CONTENT_CLASSIFICATION_W,
tagForUnderAgeOfPromise: UnderAgeOfPromise.PROMISE_FALSE,
tagForChildProtection:
ChildProtection.TAG_FOR_CHILD_PROTECTION_FALSE,
nonPersonalizedAd: NonPersonalizedAd.ALLOW_ALL,
appCountry: 'TR',
appLang: 'En',
countryCode: 'TR',
};
await splashAd.load({
adId: 'testd7c5cewoj6',
orientation: HMSScreenOrientation.SCREEN_ORIENTATION_PORTRAIT,
adParam: adParams,
logoAnchor: Anchor.TOP,
});
}
async rollAd() {
if (this.rollAdInstance) { await this.rollAdInstance.destroy(); }
this.rollAdInstance = new this.hmsAds.HMSRollAd();
await this.rollAdInstance.create(
{ adId: 'testy3cglm3pj0', totalDuration: 60, maxCount: 4 },
'rollAdArea'
);
await this.rollAdInstance.setInstreamMediaChangeListener();
await this.rollAdInstance.setOnInstreamAdClickListener();
await this.rollAdInstance.setMediaMuteListener();
this.rollAdInstance.on(RollAdEvents.ROLL_AD_LOADED, async () => {
console.log('ROLL_AD_LOADED');
this.rollAdInstance.setInstreamAds();
});
this.rollAdInstance.on(RollAdEvents.ROLL_AD_WHY_THIS_AD, async (result) => {
console.log('Why this ad clicked');
window.location.href = result;
});
this.rollAdInstance.on(
RollAdEvents.ROLL_AD_MEDIA_COMPLETION,
async (result) => {
console.log('ROLL_AD_MEDIA_COMPLETION');
this.rollAdInstance.destroy();
}
);
await this.rollAdInstance.loadAd({ file: 'public/assets/roll.html' });
await this.rollAdInstance.setInstreamMediaStateListener();
}
async nativeAd() {
if (this.nativeAdInstance) { await this.nativeAdInstance.destroy(); }
const nativeElem = document.getElementById('native-ad-element');
// Pick a better size for given template
let adId = 'testu7m3hc4gvm';
if (this.nativeAdSize === NativeAdTemplate.NATIVE_AD_SMALL_TEMPLATE) {
nativeElem.style.height = '100px';
} else if (this.nativeAdSize === NativeAdTemplate.NATIVE_AD_FULL_TEMPLATE) {
nativeElem.style.height = '350px';
} else if (this.nativeAdSize === NativeAdTemplate.NATIVE_AD_BANNER_TEMPLATE) {
nativeElem.style.height = '200px';
} else if (this.nativeAdSize === NativeAdTemplate.NATIVE_AD_VIDEO_TEMPLATE) {
adId = 'testy63txaom86';
nativeElem.style.height = '300px';
}
const template = this.nativeAdSize as NativeAdTemplate;
this.nativeAdInstance = new this.hmsAds.HMSNativeAd();
await this.nativeAdInstance.create({
div: 'native-ad-element',
template,
bg: '#E4E4E4',
});
const nativeAdOptions = { requestCustomDislikeThisAd: true };
this.nativeAdInstance.on(NativeAdEvents.NATIVE_AD_LOADED, async () => {
console.log('Native Ad Loaded');
this.nativeAdInstance.show();
});
await this.nativeAdInstance.loadAd({ adId, nativeAdOptions });
}
async why() {
await this.nativeAdInstance.gotoWhyThisAdPage(false);
}
async dislike() {
await this.nativeAdInstance.setDislikeAdListener();
this.nativeAdInstance.on(NativeAdEvents.NATIVE_AD_DISLIKED, async () => {
console.log('nativeAd :: disliked');
await this.nativeAdInstance.destroy();
this.nativeAdInstance = undefined;
});
const res = await this.nativeAdInstance.dislikeAd('Do not like this ad!');
alert('dislikeAd -> success! ' + JSON.stringify(res));
}
onBannerAdSizeChange(bannerAdSize) {
this.bannerAdSize = bannerAdSize;
console.log(this.bannerAdSize);
}
onBannerAdColorChange(bannerAdColor) {
this.bannerAdColor = bannerAdColor;
console.log(this.bannerAdColor);
}
onNativeAdSizeChange(nativeAdSize) {
this.nativeAdSize = nativeAdSize;
console.log(this.nativeAdSize);
}
logScrollStart(event) {
console.log('logScrollStart : When Scroll Starts', event);
}
logScrolling(event) {
console.log('logScrolling : When Scrolling', event);
if (this.bannerAd){
this.bannerAd.scroll();
}
if (this.rollAdInstance){
this.rollAdInstance.scroll();
}
if (this.nativeAdInstance){
this.nativeAdInstance.scroll();
}
}
logScrollEnd(event) {
console.log('logScrollEnd : When Scroll Ends', event);
}
} | the_stack |
'use strict'
import { identity, isUndefined, uniqBy } from 'lodash'
/**
* The input of a {@link PipelineStage}, either another {@link PipelineStage}, an array, an iterable or a promise.
*/
export type PipelineInput<T> = PipelineStage<T> | StreamPipelineInput<T> | Iterable<T> | PromiseLike<T> | ArrayLike<T>
interface SubGroup<K, R> {
key: K,
value: R
}
/**
* An input of a {@link PipelineStage} which produces items in stream/async way.
* Usefull for connecting a Node.JS stream into a pipeline of iterators.
* @author Thomas Minier
*/
export interface StreamPipelineInput<T> {
/**
* Produces a new value and inject it into the pipeline
* @param value - New value produced
*/
next (value: T): void
/**
* Close the pipeline input
*/
complete (): void
/**
* Report an error that occurs during execution
* @param err - The error to report
*/
error (err: any): void
}
/**
* A step in a pipeline. Data can be consumed in a pull-based or push-bashed fashion.
* @author Thomas Minier
*/
export interface PipelineStage<T> {
/**
* Subscribes to the items emitted by the stage, in a push-based fashion
* @param onData - Function invoked on each item produced by the stage
* @param onError - Function invoked in cas of an error
* @param onEnd - Function invoked when the stage ends
*/
subscribe (onData: (value: T) => void, onError: (err: any) => void, onEnd: () => void): void
/**
* Invoke a callback on each item produced by the stage
* @param cb - Function invoked on each item produced by the stage
*/
forEach (cb: (value: T) => void): void
}
/**
* Abstract representation used to apply transformations on a pipeline of iterators.
* Concrete subclasses are used by the framework to build the query execution pipeline.
* @abstract
* @author Thomas Minier
*/
export abstract class PipelineEngine {
/**
* Creates a PipelineStage that emits no items
* @return A PipelineStage that emits no items
*/
abstract empty<T> (): PipelineStage<T>
/**
* Converts the arguments to a PipelineStage
* @param values - Values to convert
* @return A PipelineStage that emits the values
*/
abstract of<T> (...values: T[]): PipelineStage<T>
/**
* Creates a PipelineStage from an Array, an array-like object, a Promise, an iterable object, or an Observable-like object.
* @param value - Source object
* @return A PipelineStage that emits the values contains in the object
*/
abstract from<T> (value: PipelineInput<T>): PipelineStage<T>
/**
* Creates a PipelineStage from a something that emits values asynchronously, using a {@link StreamPipelineInput} to feed values/errors into the pipeline.
* @param cb - Callback invoked with a {@link StreamPipelineInput} used to feed values inot the pipeline.
* @return A PipelineStage that emits the values produces asynchronously
*/
abstract fromAsync<T> (cb: (input: StreamPipelineInput<T>) => void): PipelineStage<T>
/**
* Clone a PipelineStage
* @param stage - PipelineStage to clone
* @return Cloned PipelineStage
*/
abstract clone<T> (stage: PipelineStage<T>): PipelineStage<T>
/**
* Handle errors raised in the pipeline as follows:
* 1) Default: raise the error
* 2) Use a handler function to returns a new PipelineStage in case of error
* @param input - Source PipelineStage
* @param handler - Function called in case of error to generate a new PipelineStage
* @return Output PipelineStage
*/
abstract catch<T, O> (input: PipelineStage<T>, handler?: (err: Error) => PipelineStage<O>): PipelineStage<T | O>
/**
* Creates an output PipelineStage which concurrently emits all values from every given input PipelineStage.
* @param inputs - Inputs PipelineStage
* @return Output PipelineStage
*/
abstract merge<T> (...inputs: Array<PipelineStage<T> | PipelineInput<T>>): PipelineStage<T>
/**
* Applies a given `mapper` function to each value emitted by the source PipelineStage, and emits the resulting values as a PipelineStage.
* @param input - Source PipelineStage
* @param mapper - The function to apply to each value emitted by the source PipelineStage
* @return A PipelineStage that emits the values from the source PipelineStage transformed by the given `mapper` function.
*/
abstract map<F, T> (input: PipelineStage<F>, mapper: (value: F) => T): PipelineStage<T>
/**
* Projects each source value to a PipelineStage which is merged in the output PipelineStage.
* @param input - Input PipelineStage
* @param mapper - Transformation function
* @return Output PipelineStage
*/
abstract mergeMap<F, T> (input: PipelineStage<F>, mapper: (value: F) => PipelineStage<T>): PipelineStage<T>
/**
* Do something after the PipelineStage has produced all its results
* @param input - Input PipelineStage
* @param callback - Function invoked after the PipelineStage has produced all its results
* @return Output PipelineStage
*/
abstract finalize<T> (input: PipelineStage<T>, callback: () => void): PipelineStage<T>
/**
* Maps each source value to an array of values which is merged in the output PipelineStage.
* @param input - Input PipelineStage
* @param mapper - Transformation function
* @return Output PipelineStage
*/
flatMap<F, T> (input: PipelineStage<F>, mapper: (value: F) => T[]): PipelineStage<T> {
return this.mergeMap(input, (value: F) => this.of(...mapper(value)))
}
/**
* Flatten the output of a pipeline stage that emits array of values into single values.
* @param input - Input PipelineStage
* @return Output PipelineStage
*/
flatten<T> (input: PipelineStage<T[]>): PipelineStage<T> {
return this.flatMap(input, v => v)
}
/**
* Filter items emitted by the source PipelineStage by only emitting those that satisfy a specified predicate.
* @param input - Input PipelineStage
* @param predicate - Predicate function
* @return Output PipelineStage
*/
abstract filter<T> (input: PipelineStage<T>, predicate: (value: T) => boolean): PipelineStage<T>
/**
* Applies an accumulator function over the source PipelineStage, and returns the accumulated result when the source completes, given an optional initial value.
* @param input - Input PipelineStage
* @param reducer - Accumulator function
* @return A PipelineStage that emits a single value that is the result of accumulating the values emitted by the source PipelineStage.
*/
abstract reduce<F, T> (input: PipelineStage<F>, reducer: (acc: T, value: F) => T, initial: T): PipelineStage<T>
/**
* Emits only the first `count` values emitted by the source PipelineStage.
* @param input - Input PipelineStage
* @param count - How many items to take
* @return A PipelineStage that emits only the first count values emitted by the source PipelineStage, or all of the values from the source if the source emits fewer than count values.
*/
abstract limit<T> (input: PipelineStage<T>, count: number): PipelineStage<T>
/**
* Returns a PipelineStage that skips the first count items emitted by the source PipelineStage.
* @param input - Input PipelineStage
* @param count - How many items to skip
* @return A PipelineStage that skips values emitted by the source PipelineStage.
*/
abstract skip<T> (input: PipelineStage<T>, count: number): PipelineStage<T>
/**
* Apply a callback on every item emitted by the source PipelineStage
* @param input - Input PipelineStage
* @param cb - Callback
*/
abstract forEach<T> (input: PipelineStage<T>, cb: (value: T) => void): void
/**
* Emits given values if the source PipelineStage completes without emitting any next value, otherwise mirrors the source PipelineStage.
* @param input - Input PipelineStage
* @param defaultValue - The default values used if the source Observable is empty.
* @return A PipelineStage that emits either the specified default values if the source PipelineStage emits no items, or the values emitted by the source PipelineStage.
*/
abstract defaultValues<T> (input: PipelineStage<T>, ...values: T[]): PipelineStage<T>
/**
* Buffers the source PipelineStage values until the size hits the maximum bufferSize given.
* @param input - Input PipelineStage
* @param count - The maximum size of the buffer emitted.
* @return A PipelineStage of arrays of buffered values.
*/
abstract bufferCount<T> (input: PipelineStage<T>, count: number): PipelineStage<T[]>
/**
* Creates a PipelineStage which collect all items from the source PipelineStage into an array, and then emits this array.
* @param input - Input PipelineStage
* @return A PipelineStage which emits all values emitted by the source PipelineStage as an array
*/
abstract collect<T> (input: PipelineStage<T>): PipelineStage<T[]>
/**
* Returns a PipelineStage that emits all items emitted by the source PipelineStage that are distinct by comparison from previous items.
* @param input - Input PipelineStage
* @param selector - Optional function to select which value you want to check as distinct.
* @return A PipelineStage that emits items from the source PipelineStage with distinct values.
*/
distinct<T, K> (input: PipelineStage<T>, selector?: (value: T) => T | K): PipelineStage<T> {
if (isUndefined(selector)) {
selector = identity
}
return this.flatMap(this.collect(input), (values: T[]) => uniqBy(values, selector!))
}
/**
* Emits only the first value (or the first value that meets some condition) emitted by the source PipelineStage.
* @param input - Input PipelineStage
* @return A PipelineStage of the first item that matches the condition.
*/
first<T> (input: PipelineStage<T>): PipelineStage<T> {
return this.limit(input, 1)
}
/**
* Returns a PipelineStage that emits the items you specify as arguments after it finishes emitting items emitted by the source PipelineStage.
* @param input - Input PipelineStage
* @param values - Values to append
* @return A PipelineStage that emits the items emitted by the source PipelineStage and then emits the additional values.
*/
endWith<T> (input: PipelineStage<T>, values: T[]): PipelineStage<T> {
return this.merge(input, this.from(values))
}
/**
* Perform a side effect for every emission on the source PipelineStage, but return a PipelineStage that is identical to the source.
* @param input - Input PipelineStage
* @param cb - Callback invoked on each item
* @return A PipelineStage identical to the source, but runs the specified PipelineStage or callback(s) for each item.
*/
tap<T> (input: PipelineStage<T>, cb: (value: T) => void): PipelineStage<T> {
return this.map(input, (value: T) => {
cb(value)
return value
})
}
/**
* Find the smallest value produced by a pipeline of iterators.
* It takes a ranking function as input, which is invoked with (x, y)
* and must returns True if x < y and False otherwise.
* Warning: this function needs to materialize all values of the pipeline.
* @param input - Input PipelineStage
* @param comparator - (optional) Ranking function
* @return A pipeline stage that emits the lowest value found
*/
min<T> (input: PipelineStage<T>, ranking?: (x: T, y: T) => boolean): PipelineStage<T> {
if (isUndefined(ranking)) {
ranking = (x: T, y: T) => x < y
}
return this.map(this.collect(input), (values: T[]) => {
let minValue = values[0]
for (let i = 1; i < values.length - 1; i++) {
if (ranking!(values[i], minValue)) {
minValue = values[i]
}
}
return minValue
})
}
/**
* Find the smallest value produced by a pipeline of iterators.
* It takes a ranking function as input, which is invoked with (x, y)
* and must returns True if x > y and False otherwise.
* Warning: this function needs to materialize all values of the pipeline.
* @param input - Input PipelineStage
* @param comparator - (optional) Ranking function
* @return A pipeline stage that emits the highest value found
*/
max<T> (input: PipelineStage<T>, ranking?: (x: T, y: T) => boolean): PipelineStage<T> {
if (isUndefined(ranking)) {
ranking = (x: T, y: T) => x > y
}
return this.map(this.collect(input), (values: T[]) => {
let maxValue = values[0]
for (let i = 1; i < values.length - 1; i++) {
if (ranking!(values[i], maxValue)) {
maxValue = values[i]
}
}
return maxValue
})
}
/**
* Groups the items produced by a pipeline according to a specified criterion,
* and emits the resulting groups
* @param input - Input PipelineStage
* @param keySelector - A function that extracts the grouping key for each item
* @param elementSelector - (optional) A function that transforms items before inserting them in a group
*/
groupBy<T, K, R> (input: PipelineStage<T>, keySelector: (value: T) => K, elementSelector?: (value: T) => R): PipelineStage<[K, R[]]> {
if (isUndefined(elementSelector)) {
elementSelector = identity
}
const groups: Map<K, R[]> = new Map()
let stage: PipelineStage<SubGroup<K, R>> = this.map(input, value => {
return {
key: keySelector(value),
value: elementSelector!(value)
}
})
return this.mergeMap(this.collect(stage), (subgroups: SubGroup<K, R>[]) => {
// build groups
subgroups.forEach(g => {
if (!groups.has(g.key)) {
groups.set(g.key, [ g.value ])
} else {
groups.set(g.key, groups.get(g.key)!.concat([g.value]))
}
})
// inject groups into the pipeline
return this.fromAsync(input => {
groups.forEach((value, key) => input.next([key, value]))
})
})
}
/**
* Peek values from the input pipeline stage, and use them to decide
* between two candidate pipeline stages to continue the pipeline.
* @param input - Input pipeline stage
* @param count - How many items to peek from the input?
* @param predicate - Predicate function invoked with the values
* @param ifCase - Callback invoked if the predicate function evaluates to True
* @param elseCase - Callback invoked if the predicate function evaluates to False
* @return A pipeline stage
*/
peekIf<T, O> (input: PipelineStage<T>, count: number, predicate: (values: T[]) => boolean, ifCase: (values: T[]) => PipelineStage<O>, elseCase: (values: T[]) => PipelineStage<O>): PipelineStage<O> {
const peekable = this.limit(this.clone(input), count)
return this.mergeMap(this.collect(peekable), values => {
if (predicate(values)) {
return ifCase(values)
}
return elseCase(values)
})
}
} | the_stack |
"use strict";
// uuid: a54e855a-464d-4624-a7ce-fc39cb72a0f3
// ------------------------------------------------------------------------
// Copyright (c) 2018 Alexandre Bento Freire. All rights reserved.
// Licensed under the MIT License+uuid License. See License.txt for details
// ------------------------------------------------------------------------
// Implementation of Tasks
/** @module end-user | The lines bellow convey information for the end-user */
/**
* ## Description
*
* A **task** is a function executed at the beginning of `addAnimations`,
* before selector and properties information is processed,
* and has the following goals:
*
* - *Setup*: A setup allows to prepare elements for further processing.
* An example is text splitting. text splitting prepares DOM for individual
* character manipulation.
* Setup tasks can stop the processing of a `addAnimations`, and might not
* require a selector..
*
* - *Wrapping*: Only `addAnimations` can be stored in a JSON file or sent
* for remote rendering. In this case, methods such as `addStills` and scene transitions
* need to be wrapped in a task.
* Wrapping tasks can stop the processing of a `addAnimations`, and might not
* require a selector.
*
* - *Asset creation*: A task can create an asset avoiding the need of loading external
* assets such as svg shape files.
*
* - *Complex animations*: A task can simplify the creation of a complex animation.
*
* ## F/X
*
* If you just want to do a single-shot animation, use `scene.addAnimations`,
* but if you want to reuse the animation or want to break down the complexity
* into multiple parts, the best is to create a task.
*
* A task implementation is a function with the following syntax:
* ```typescript
* function myTaskFunc(anime: Animation, wkTask: WorkTask,
* params: FactoryTaskParams, stage?: uint, args?: ABeamerArgs): TaskResult;
* ```
* And add this task to ABeamer using `ABeamer.pluginManager.addTasks([['my-task', myTaskFunc]]);`.
*
* If the task just uses plain DOM, the simplest is to:
* - inject DOM by using the animation `selector`, and then
* ```typescript
* switch (stage) {
* case TS_INIT:
* const adapters = args.scene.getElementAdapters(anime.selector);
* elAdapters.forEach((elAdapter, elIndex) => {
* const html = elAdapter.getProp('html', args);
* const myPiece = '<div>Hello</div>';
* elAdapter.setProp('html', html + myPiece, args);
* });
* }
* ```
*
* - inject animation properties into the pipeline by:
* ```typescript
* switch (stage) {
* case TS_INIT:
* anime.props.push({ prop: 'text', value: ['hello'] });
* }
* ```
*/
namespace ABeamer {
// #generate-group-section
// ------------------------------------------------------------------------
// Tasks
// ------------------------------------------------------------------------
// The following section contains data for the end-user
// generated by `gulp build-definition-files`
// -------------------------------
// #export-section-start: release
// ------------------------------------------------------------------------
// Task Results
// ------------------------------------------------------------------------
export const TR_EXIT = 0;
export const TR_DONE = 1;
export const TR_INTERACTIVE = 2;
export type TaskResult = 0 | 1 | 2;
// ------------------------------------------------------------------------
// Task Stage
// ------------------------------------------------------------------------
export const TS_INIT = 0;
export const TS_ANIME_LOOP = 1;
export const TS_TELEPORT = 2;
// ------------------------------------------------------------------------
// Task Interface
// ------------------------------------------------------------------------
export type TaskFunc = (anime: Animation, wkTask: WorkTask,
params?: AnyParams, stage?: uint, args?: ABeamerArgs) => TaskResult;
export type TaskHandler = TaskName | TaskFunc;
export type TaskName = string
| GeneralTaskName
| TextTaskName
| ShapeTaskName
| AttackTaskName
;
export type TaskParams = AnyParams
| GeneralTaskParams
| TextTaskParams
| ShapeTaskParams
| AttackTaskParams
;
/**
* Parameters provided by the user during an `addAnimation`.
*/
export interface Task {
/** Task Name, Expression or Input Function defined by the user. */
handler: TaskHandler;
/** Parameters passed to the task function */
params?: TaskParams;
}
/**
* Parameters passed to a task during the execution.
*/
export interface WorkTask {
name: string;
params: TaskParams;
animeIndex: uint;
}
export type GeneralTaskName =
/** @see TaskFactoryParams */
| 'factory'
;
export type GeneralTaskParams =
| FactoryTaskParams
;
export type FactoryTaskAttr = string | ExprString | number | string[] | number[];
export interface FactoryTaskParams extends AnyParams {
count: uint | ExprString;
tag?: string;
content?: FactoryTaskAttr;
isContentFormatted?: boolean;
attrs?: {
name: string;
value: FactoryTaskAttr;
isFormatted?: boolean;
}[];
}
// #export-section-end: release
// -------------------------------
// ------------------------------------------------------------------------
// Implementation
// ------------------------------------------------------------------------
/** Map of the built-in path tasks, plus the ones added via plugins. */
export const _taskFunctions: { [name: string]: TaskFunc } = {};
export interface _WorkTask extends WorkTask {
func: TaskFunc;
}
function _buildWorkTask(task: Task, anime: Animation,
toTeleport: boolean, args: ABeamerArgs): _WorkTask {
const handler = task.handler;
let taskFunc: TaskFunc;
args.user = task.params;
switch (typeof handler) {
case 'string':
taskFunc = _taskFunctions[handler as string];
break;
case 'function':
taskFunc = handler as TaskFunc;
throwIfI8n(toTeleport, Msgs.NoCode);
break;
}
if (!taskFunc) {
throwI8n(Msgs.UnknownOf, { type: Msgs.task, p: handler as string });
}
const wkTask: _WorkTask = {
func: taskFunc,
name: handler as string,
params: task.params || {},
animeIndex: -1,
};
if (toTeleport) {
task.handler = handler as string;
taskFunc(anime, wkTask, wkTask.params, TS_TELEPORT, args);
}
return wkTask;
}
/**
* Converts the Handlers into strings, and calls tasks on TELEPORT stage.
*/
export function _prepareTasksForTeleporting(anime: Animation,
tasks: Task[], args: ABeamerArgs): void {
tasks.forEach(task => { _buildWorkTask(task, anime, true, args); });
}
/**
* If it returns true, this Animation is full processed
* and the animation should be bypassed.
*/
export function _processTasks(tasks: Task[], wkTasks: _WorkTask[],
anime: Animation, args: ABeamerArgs): boolean {
let toExit = true;
tasks.forEach(task => {
const wkTask = _buildWorkTask(task, anime, false, args);
const taskResult = wkTask.func(anime, wkTask, wkTask.params, TS_INIT, args);
switch (taskResult) {
case TR_EXIT: return;
case TR_DONE: toExit = false; break;
case TR_INTERACTIVE:
toExit = false;
wkTasks.push(wkTask);
break;
}
});
return toExit;
}
export function _runTasks(wkTasks: _WorkTask[], anime: Animation,
animeIndex: uint, args: ABeamerArgs): void {
wkTasks.forEach(wkTask => {
wkTask.animeIndex = animeIndex;
wkTask.func(anime, wkTask, wkTask.params, TS_ANIME_LOOP, args);
});
}
// ------------------------------------------------------------------------
// factory Task
// ------------------------------------------------------------------------
function _formatValue(value: FactoryTaskAttr, isFormatted: boolean | undefined,
index: uint, args: ABeamerArgs): string {
if (typeof value === 'object') {
value = value[index % value.length];
}
if (isFormatted === false) {
return value as string;
}
args.vars.i = index;
const exprValue = ifExprCalc(value as string, args);
return exprValue !== undefined ? exprValue.toString() :
sprintf(value as string, index);
}
_taskFunctions['factory'] = _factory;
/** Implements the Factory Task */
function _factory(anime: Animation, _wkTask: WorkTask,
params: FactoryTaskParams, stage: uint, args: ABeamerArgs): TaskResult {
switch (stage) {
case TS_INIT:
const tag = params.tag || 'div';
const count = ifExprCalcNum(params.count as string,
params.count as number, args);
const needsClosing = ['img'].indexOf(tag) === -1;
const elAdapters = args.scene.getElementAdapters(anime.selector);
args.vars.elCount = elAdapters.length;
elAdapters.forEach((elAdapter, elIndex) => {
args.vars.elIndex = elIndex;
const inTextHtml: string[] = [];
for (let i = 0; i < count; i++) {
const parts = ['<' + tag];
(params.attrs || []).forEach(param => {
const value = _formatValue(param.value, param.isFormatted, i, args);
parts.push(` ${param.name}="${value}"`);
});
parts.push('>');
parts.push(_formatValue(params.content || '',
params.isContentFormatted, i, args));
if (needsClosing) { parts.push(`</${tag}>`); }
inTextHtml.push(parts.join(''));
}
elAdapter.setProp('html', inTextHtml.join('\n'), args);
});
return TR_EXIT;
}
}
} | the_stack |
import {Injectable} from "@angular/core";
import * as angular from "angular";
import "fattable";
import {DomainType} from "../../../services/DomainTypesService";
import {DataCategory} from "../../wrangler/column-delegate";
// import './cell-menu.template.scss';
/**
* Default font.
*/
const DEFAULT_FONT = "10px ''SourceSansPro'";
/**
* HTML template for header cells.
*/
const HEADER_TEMPLATE = "js/feed-mgr/visual-query/transform-data/visual-query-table/visual-query-table-header.html";
/**
* Pixel unit.
*/
const PIXELS = "px";
@Injectable()
export class VisualQueryPainterService extends fattable.Painter {
/**
* Maximum display length for column context functions before they are ellipses (asthetics)
*/
static readonly MAX_DISPLAY_LENGTH = 25;
/**
* Left and right padding for normal columns.
*/
static readonly COLUMN_PADDING = 5;
/**
* Left padding for the first column.
*/
static readonly COLUMN_PADDING_FIRST = 24;
/**
* Height of header row.
*/
static readonly HEADER_HEIGHT = 56;
/**
* Height of data rows.
*/
static readonly ROW_HEIGHT = 27;
/**
* Class for selected cells.
*/
static readonly SELECTED_CLASS = "selected";
/**
* Visual Query Component instance.
*/
private _delegate: any;
/**
* List of available domain types.
*/
private _domainTypes: DomainType[];
/**
* Font for the header row
*/
private _headerFont: string;
/**
* Font for the data rows
*/
private _rowFont: string;
/**
* Panel containing the cell menu.
*/
private menuPanel: angular.material.IPanelRef;
/**
* Indicates that the menu should be visible.
*/
private menuVisible: boolean = false;
/**
* Cell that was last clicked.
*/
private selectedCell: HTMLElement;
/**
* Panel containing the tooltip.
*/
private tooltipPanel: angular.material.IPanelRef;
/**
* Indicates that the tooltip should be visible.
*/
private tooltipVisible: boolean = false;
/**
* Indicate thate the header template has been loaded into the $templateCache
* @type {boolean}
*/
private headerTemplateLoaded : boolean = false;
/**
* Array of header div HTMLElements that are waiting for the HEADER_TEMPLATE to get loaded.
* Once the template is loaded these elements will get filled
* @type {any[]}
*/
private waitingHeaderDivs : HTMLElement[] = [];
private $compile: angular.ICompileService;
private $mdPanel: angular.material.IPanelService;
private $scope: angular.IRootScopeService;
private $templateCache: angular.ITemplateCacheService;
private $templateRequest: angular.ITemplateRequestService;
private $timeout: angular.ITimeoutService;
private $window: angular.IWindowService;
/**
* Constructs a {@code VisualQueryPainterService}.
*/
constructor() {
super();
// Load AngularJS services
const injector = angular.element(document.body).injector();
this.$compile = injector.get("$compile");
this.$mdPanel = injector.get("$mdPanel");
this.$scope = injector.get("$rootScope");
this.$templateCache = injector.get("$templateCache");
this.$templateRequest = injector.get("$templateRequest");
this.$timeout = injector.get("$timeout");
this.$window = injector.get("$window");
//Request the Header template and fill in the contents of any header divs waiting on the template.
this.$templateRequest(HEADER_TEMPLATE).then((response) => {
this.headerTemplateLoaded = true;
angular.forEach(this.waitingHeaderDivs,(headerDiv : HTMLElement) => {
this.compileHeader(headerDiv);
});
this.waitingHeaderDivs = [];
});
// Hide tooltip on scroll. Skip Angular change detection.
/*
window.addEventListener("scroll", () => {
if (this.tooltipVisible) {
this.hideTooltip();
}
}, {passive:true, capture:true});
*/
// Create menu
this.menuPanel = this.$mdPanel.create({
animation: this.$mdPanel.newPanelAnimation().withAnimation({open: 'md-active md-clickable', close: 'md-leave'}),
attachTo: angular.element(document.body),
clickOutsideToClose: true,
escapeToClose: true,
focusOnOpen: true,
panelClass: "_md md-open-menu-container md-whiteframe-z2 visual-query-menu",
template: require("./cell-menu.template.html")
});
this.menuPanel.attach();
// Create tooltip
this.tooltipPanel = this.$mdPanel.create({
animation: this.$mdPanel.newPanelAnimation().withAnimation({open: "md-show", close: "md-hide"}),
attachTo: angular.element(document.body),
template: `{{value}}<ul><li ng-repeat="item in validation">{{item.rule}}: {{item.reason}}</li></ul>`,
focusOnOpen: false,
panelClass: "md-tooltip md-origin-bottom visual-query-tooltip",
propagateContainerEvents: true,
zIndex: 100
});
this.tooltipPanel.attach();
}
/**
* Gets the Visual Query Component for this painter.
*/
get delegate(): any {
return this._delegate;
}
set delegate(value: any) {
this._delegate = value;
}
/**
* Gets the list of available domain types.
*/
get domainTypes(): DomainType[] {
return this._domainTypes;
}
set domainTypes(value: DomainType[]) {
this._domainTypes = value;
}
/**
* Gets the font for the header row.
*/
get headerFont() {
return (this._headerFont != null) ? this._headerFont : DEFAULT_FONT;
}
set headerFont(value: string) {
this._headerFont = value;
}
/**
* Gets the font for the data rows.
*/
get rowFont() {
return (this._rowFont != null) ? this._rowFont : DEFAULT_FONT;
}
set rowFont(value: string) {
this._rowFont = value;
}
fillCellPending(cellDiv: HTMLElement) {
cellDiv.textContent = "Loading...";
cellDiv.className = "pending";
}
fillHeaderPending(cellDiv: HTMLElement) {
// Override so it doesn't replace our angular template for column cell
}
/**
* Fills and style a cell div.
*
* @param {HTMLElement} cellDiv the cell <div> element
* @param {VisualQueryTableCell|null} cell the cell object
*/
fillCell(cellDiv: HTMLElement, cell: any) {
// Set style
if (cell === null) {
cellDiv.className = "";
} else if (cell.validation) {
$(cellDiv).addClass("invalid");
} else if (cell.value === null) {
cellDiv.className = "null";
} else {
cellDiv.className = "";
}
// Adjust padding based on column number
if (cell !== null && cell.column === 0) {
cellDiv.className += " first-column ";
}
// Set contents
if (cell === null) {
cellDiv.textContent = "";
} else if (cell.value !== null && cell.value.sqltypeName && cell.value.sqltypeName.startsWith("PERIOD")) {
cellDiv.textContent = "(" + cell.value.attributes.join(", ") + ")";
} else {
cellDiv.textContent = cell.value
}
if (cell !== null) {
cellDiv.className += cellDiv.className + " " + (cell.row % 2 == 0 ? "even" : "odd");
angular.element(cellDiv)
.data("column", cell.column)
.data("validation", cell.validation)
.data("realValue", cell.value);
}
cellDiv.innerHTML = cellDiv.innerHTML.replace(/\s/g,"<span class='ws-text'>·</span>");
}
/**
* Fills and style a column div.
*
* @param {HTMLElement} headerDiv the header <div> element
* @param {VisualQueryTableHeader|null} header the column header
*/
fillHeader(headerDiv: HTMLElement, header: any) {
// Update scope in a separate thread
const $scope: any = angular.element(headerDiv).scope();
if (header != null && $scope.header !== header && header.delegate != undefined) {
$scope.header = header;
$scope.table = this.delegate;
$scope.availableCasts = header.delegate.getAvailableCasts();
$scope.availableDomainTypes = this.domainTypes;
$scope.domainType = header.domainTypeId ? this.domainTypes.find((domainType: DomainType) => domainType.id === header.domainTypeId) : null;
$scope.header.unsort = this.unsort.bind(this);
}
}
/**
* Hides the tooltip.
*/
hideTooltip() {
this.tooltipVisible = false;
this.$timeout(() => {
if (this.tooltipVisible === false) {
this.tooltipPanel.hide();
}
}, 75);
}
/**
* Setup method are called at the creation of the cells. That is during initialization and for all window resize event.
*
* Cells are recycled.
*
* @param {HTMLElement} cellDiv the cell <div> element
*/
setupCell(cellDiv: HTMLElement) {
angular.element(cellDiv)
.on("contextmenu", () => false)
.on("mousedown", () => this.setSelected(cellDiv))
.on("mouseenter", () => this.showTooltip(cellDiv))
.on("mouseleave", () => this.hideTooltip())
.on("mouseup", event => this.showMenu(cellDiv, event));
cellDiv.style.font = this.rowFont;
cellDiv.style.lineHeight = VisualQueryPainterService.ROW_HEIGHT + PIXELS;
}
/**
* Setup method are called at the creation of the column header. That is during initialization and for all window resize event.
*
* Columns are recycled.
*
* @param {HTMLElement} headerDiv the header <div> element
*/
setupHeader(headerDiv: HTMLElement) {
// Set style attributes
headerDiv.style.font = this.headerFont;
headerDiv.style.lineHeight = VisualQueryPainterService.HEADER_HEIGHT + PIXELS;
//if the header template is not loaded yet then fill it with Loading text.
// the callback on the templateRequest will compile those headers waiting
if(!this.headerTemplateLoaded) {
headerDiv.textContent = "Loading...";
headerDiv.className = "pending";
this.waitingHeaderDivs.push(headerDiv)
}
else {
this.compileHeader(headerDiv);
}
}
/**
* Cleanup any events attached to the header
* @param headerDiv
*/
cleanUpHeader(headerDiv: HTMLElement){
//destroy the old scope if it exists
let oldScope = angular.element(headerDiv).isolateScope();
if(angular.isDefined(oldScope)){
oldScope.$destroy();
}
}
/**
* Cleanup any events attached to the cell
* @param cellDiv
*/
cleanUpCell(cellDiv: HTMLElement) {
angular.element(cellDiv).unbind();
}
/**
* Called when the table is refreshed
* This should cleanup any events/bindings/scopes created by the prior render of the table
* @param table
*/
cleanUp(table:HTMLElement){
//remove all header scopes
this.headerScopes.forEach((headerScope: IScope) => {
headerScope.$destroy();
});
this.headerScopes = [];
super.cleanUp(table);
angular.element(table).unbind();
}
private headerScopes : IScope[] = []
private compileHeader(headerDiv: HTMLElement) {
// Load template
headerDiv.innerHTML = this.$templateCache.get(HEADER_TEMPLATE) as string;
let newScope = this.$scope.$new(true)
this.headerScopes.push(newScope);
this.$compile(headerDiv)(newScope);
}
/**
* Hides the cell menu.
*/
private hideMenu() {
this.menuVisible = false;
this.$timeout(() => {
if (this.menuVisible === false) {
this.menuPanel.close();
}
}, 75);
}
/**
* Sets the currently selected cell.
*/
private setSelected(cellDiv: HTMLElement) {
// Remove previous selection
if (this.selectedCell) {
angular.element(this.selectedCell).removeClass(VisualQueryPainterService.SELECTED_CLASS);
}
// Set new selection
this.selectedCell = cellDiv;
angular.element(this.selectedCell).addClass(VisualQueryPainterService.SELECTED_CLASS);
}
/**
* Create the display string for a selection
*/
private niceSelection(selection:string) : string {
switch (selection) {
case ' ':
return '(space)';
case '':
return '(empty)';
case null:
return '(empty)';
default:
return selection;
}
}
// Replace dots in the
private cleanDots(value: string) : string {
return value.replace(/·/g, " ");
}
/**
* Shows the cell menu on the specified cell.
*/
private showMenu(cellDiv: HTMLElement, event: JQueryEventObject) {
// Get column info
const cell = angular.element(cellDiv);
const column = cell.data("column");
const header = this.delegate.columns[column];
const isNull = cell.hasClass("null");
const selection = this.$window.getSelection();
if (event.button != 0 || !(selection.focusNode.nodeType == 3 || selection.toString() == "") || !(this.selectedCell == event.target || $.contains(this.selectedCell, event.target))) {
return;
}
//if (this.selectedCell !== event.target || (selection.anchorNode !== null && selection.anchorNode !== selection.focusNode)) {
// return; // ignore dragging between elements
// }
if (angular.element(document.body).children(".CodeMirror-hints").length > 0) {
return; // ignore clicks when CodeMirror function list is active
} else if (header.delegate.dataCategory === DataCategory.DATETIME || header.delegate.dataCategory === DataCategory.NUMERIC || header.delegate.dataCategory === DataCategory.STRING) {
this.menuVisible = true;
} else {
return; // ignore clicks on columns with unsupported data types
}
// Update content
// Calculate the actual offset considering the inner spans
let trueOffset = function(selection:any) {
let offset = selection.anchorOffset;
let node = ( selection.anchorNode.parentNode.className === 'ws-text' ? selection.anchorNode.parentElement : selection.anchorNode);
while (node.previousSibling) {
node = node.previousSibling;
offset += node.textContent.length;
}
return offset;
}
const $scope: IScope = (this.menuPanel.config as any).scope;
$scope.DataCategory = DataCategory;
$scope.header = header;
$scope.selection = this.cleanDots(selection.toString()); //(header.delegate.dataCategory === DataCategory.STRING) ? cleanDots(selection.toString()) : null;
let startOffset = trueOffset(selection);
$scope.range = (selection != null ? { startOffset: startOffset, endOffset: startOffset+$scope.selection.length } : null);
$scope.selectionDisplay = this.niceSelection($scope.selection)
$scope.table = this.delegate;
$scope.value = isNull ? null : $(cellDiv).data('realValue');
$scope.displayValue = (isNull || $scope.value == null ? "(empty)" : ($scope.value.length > VisualQueryPainterService.MAX_DISPLAY_LENGTH ? $scope.value.substring(0, VisualQueryPainterService.MAX_DISPLAY_LENGTH) + "...": $scope.value));
// Update position
this.menuPanel.updatePosition(
this.$mdPanel.newPanelPosition()
.left(event.clientX + PIXELS)
.top(event.clientY + PIXELS)
);
// Show menu
this.menuPanel.open()
.then(() => {
// Add click listener
this.menuPanel.panelEl.on("click", "button", () => this.hideMenu());
// Calculate position
const element = angular.element(this.menuPanel.panelEl);
const height = element.height();
const offset = element.offset();
const width = element.width();
// Fix position if off screen
const left = (offset.left + width > this.$window.innerWidth) ? this.$window.innerWidth - width - 8 : event.clientX;
const top = (offset.top + height > this.$window.innerHeight) ? this.$window.innerHeight - height - 8 : event.clientY;
if (left !== event.clientX || top !== event.clientY) {
this.menuPanel.updatePosition(
this.$mdPanel.newPanelPosition()
.left(left + PIXELS)
.top(top + PIXELS)
);
}
});
}
/**
* Shows the tooltip on the specified cell.
*/
private showTooltip(cellDiv: HTMLElement) {
this.tooltipVisible = true;
// Update content
const $scope = this.tooltipPanel.panelEl.scope() as any;
$scope.validation = angular.element(cellDiv).data("validation");
$scope.value = cellDiv.innerText;
if ($scope.value && $scope.value.length > 22) {
// Update position
const cellOffset = angular.element(cellDiv).offset();
let offsetY;
let yPosition;
if (cellOffset.top + VisualQueryPainterService.ROW_HEIGHT * 3 > this.$window.innerHeight) {
offsetY = "-27" + PIXELS;
yPosition = this.$mdPanel.yPosition.ABOVE;
} else {
offsetY = "0";
yPosition = this.$mdPanel.yPosition.BELOW;
}
this.tooltipPanel.updatePosition(
this.$mdPanel.newPanelPosition()
.relativeTo(cellDiv)
.addPanelPosition(this.$mdPanel.xPosition.ALIGN_START, yPosition)
.withOffsetX("28px")
.withOffsetY(offsetY)
);
// Show tooltip
this.tooltipPanel.open();
} else {
this.hideTooltip();
}
}
/**
* Turns off sorting.
*/
private unsort() {
if (this.delegate) {
this.delegate.unsort();
}
}
} | the_stack |
import { buildFormValidationResult } from './form-validation-summary-builder';
import { InternalValidationResult } from './model';
describe('form-validation-summary-build specs', () => {
describe(`buildFormValidationResult`, () => {
it(`Spec #1 => should returns new FormValidationResult equals { succeeded: true }
when passing fieldValidationResults and recordValidationResults equals undefined`, () => {
// Arrange
const fieldValidationResults: InternalValidationResult[] = void 0;
const recordValidationResults: InternalValidationResult[] = void 0;
// Act
const formValidationSummary = buildFormValidationResult(
fieldValidationResults,
recordValidationResults
);
// Assert
expect(formValidationSummary.succeeded).toBeTruthy();
expect(formValidationSummary.fieldErrors).toEqual({});
expect(formValidationSummary.recordErrors).toEqual({});
});
it(`Spec #2 => should returns new FormValidationResult equals { succeeded: true }
when passing fieldValidationResults and recordValidationResults equals null`, () => {
// Arrange
const fieldValidationResults: InternalValidationResult[] = null;
const recordValidationResults: InternalValidationResult[] = null;
// Act
const formValidationSummary = buildFormValidationResult(
fieldValidationResults,
recordValidationResults
);
// Assert
expect(formValidationSummary.succeeded).toBeTruthy();
expect(formValidationSummary.fieldErrors).toEqual({});
expect(formValidationSummary.recordErrors).toEqual({});
});
it(`Spec #3 => should returns new FormValidationResult equals { succeeded: true }
when passing fieldValidationResults and recordValidationResults equals []`, () => {
// Arrange
const fieldValidationResults: InternalValidationResult[] = [];
const recordValidationResults: InternalValidationResult[] = [];
// Act
const formValidationSummary = buildFormValidationResult(
fieldValidationResults,
recordValidationResults
);
// Assert
expect(formValidationSummary.succeeded).toBeTruthy();
expect(formValidationSummary.fieldErrors).toEqual({});
expect(formValidationSummary.recordErrors).toEqual({});
});
it(`Spec #4 => should returns new FormValidationResult equals { succeeded: true }
when passing fieldValidationResults and recordValidationResults contains one element and succeeded`, () => {
// Arrange
const fieldValidationResults: InternalValidationResult[] = [
{
succeeded: true,
type: 'MY_VALIDATION_1',
message: 'My Error Message 1',
key: 'myfield',
},
];
const recordValidationResults: InternalValidationResult[] = [
{
succeeded: true,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
key: 'myrecord',
},
];
// Act
const formValidationSummary = buildFormValidationResult(
fieldValidationResults,
recordValidationResults
);
// Assert
expect(formValidationSummary.succeeded).toBeTruthy();
expect(formValidationSummary.fieldErrors).toEqual({
myfield: {
succeeded: true,
type: 'MY_VALIDATION_1',
message: 'My Error Message 1',
},
});
expect(formValidationSummary.recordErrors).toEqual({
myrecord: {
succeeded: true,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
},
});
});
it(`Spec #5 => should returns new FormValidationResult equals { succeeded: false }
when passing fieldValidationResults and recordValidationResults contains one element and failed`, () => {
// Arrange
const fieldValidationResults: InternalValidationResult[] = [
{
succeeded: false,
type: 'MY_VALIDATION_1',
message: 'My Error Message 1',
key: 'myfield',
},
];
const recordValidationResults: InternalValidationResult[] = [
{
succeeded: false,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
key: 'myrecord',
},
];
// Act
const formValidationSummary = buildFormValidationResult(
fieldValidationResults,
recordValidationResults
);
// Assert
expect(formValidationSummary.succeeded).toBeFalsy();
expect(formValidationSummary.fieldErrors).toEqual({
myfield: {
succeeded: false,
type: 'MY_VALIDATION_1',
message: 'My Error Message 1',
},
});
expect(formValidationSummary.recordErrors).toEqual({
myrecord: {
succeeded: false,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
},
});
});
it(`Spec #6 => should returns new FormValidationResult equals { succeeded: false }
when passing fieldValidationResults contains one element and failed and recordValidationResults contains one element and succeeded`, () => {
// Arrange
const fieldValidationResults: InternalValidationResult[] = [
{
succeeded: false,
type: 'MY_VALIDATION_1',
message: 'My Error Message 1',
key: 'myfield',
},
];
const recordValidationResults: InternalValidationResult[] = [
{
succeeded: true,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
key: 'myrecord',
},
];
// Act
const formValidationSummary = buildFormValidationResult(
fieldValidationResults,
recordValidationResults
);
// Assert
expect(formValidationSummary.succeeded).toBeFalsy();
expect(formValidationSummary.fieldErrors).toEqual({
myfield: {
succeeded: false,
type: 'MY_VALIDATION_1',
message: 'My Error Message 1',
},
});
expect(formValidationSummary.recordErrors).toEqual({
myrecord: {
succeeded: true,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
},
});
});
it(`Spec #7 => should returns new FormValidationResult equals { succeeded: false }
when passing fieldValidationResults contains one element and succeeded and recordValidationResults contains one element and failed`, () => {
// Arrange
const fieldValidationResults: InternalValidationResult[] = [
{
succeeded: true,
type: 'MY_VALIDATION_1',
message: 'My Error Message 1',
key: 'myfield',
},
];
const recordValidationResults: InternalValidationResult[] = [
{
succeeded: false,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
key: 'myrecord',
},
];
// Act
const formValidationSummary = buildFormValidationResult(
fieldValidationResults,
recordValidationResults
);
// Assert
expect(formValidationSummary.succeeded).toBeFalsy();
expect(formValidationSummary.fieldErrors).toEqual({
myfield: {
succeeded: true,
type: 'MY_VALIDATION_1',
message: 'My Error Message 1',
},
});
expect(formValidationSummary.recordErrors).toEqual({
myrecord: {
succeeded: false,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
},
});
});
it(`Spec #8 => should returns new FormValidationResult equals { succeeded: false }
when passing fieldValidationResults and recordValidationResults with two items first equals { succeeded: true }
and second equals { succeeded: false }
`, () => {
// Arrange
const fieldValidationResults: InternalValidationResult[] = [
{
succeeded: true,
type: 'MY_VALIDATION_1',
message: 'My Error Message 1',
key: 'myfield',
},
{
succeeded: false,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
key: 'myotherfield',
},
];
const recordValidationResults: InternalValidationResult[] = [
{
succeeded: true,
type: 'MY_VALIDATION_3',
message: 'My Error Message 3',
key: 'myrecord',
},
{
succeeded: false,
type: 'MY_VALIDATION_4',
message: 'My Error Message 4',
key: 'myotherrecord',
},
];
// Act
const formValidationSummary = buildFormValidationResult(
fieldValidationResults,
recordValidationResults
);
// Assert
expect(formValidationSummary.succeeded).toBeFalsy();
expect(formValidationSummary.fieldErrors).toEqual({
myfield: {
succeeded: true,
type: 'MY_VALIDATION_1',
message: 'My Error Message 1',
},
myotherfield: {
succeeded: false,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
},
});
expect(formValidationSummary.recordErrors).toEqual({
myrecord: {
succeeded: true,
type: 'MY_VALIDATION_3',
message: 'My Error Message 3',
},
myotherrecord: {
succeeded: false,
type: 'MY_VALIDATION_4',
message: 'My Error Message 4',
},
});
});
it(`Spec #9 => should returns new FormValidationResult equals { succeeded: true }
when passing fieldValidationResults and recordValidationResults with two items first equals { succeeded: true }
and second equals { succeeded: true }
`, () => {
// Arrange
const fieldValidationResults: InternalValidationResult[] = [
{
succeeded: true,
type: 'MY_VALIDATION_1',
message: 'My Error Message 1',
key: 'myfield',
},
{
succeeded: true,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
key: 'myotherfield',
},
];
const recordValidationResults: InternalValidationResult[] = [
{
succeeded: true,
type: 'MY_VALIDATION_3',
message: 'My Error Message 3',
key: 'myrecord',
},
{
succeeded: true,
type: 'MY_VALIDATION_4',
message: 'My Error Message 4',
key: 'myotherrecord',
},
];
// Act
const formValidationSummary = buildFormValidationResult(
fieldValidationResults,
recordValidationResults
);
// Assert
expect(formValidationSummary.succeeded).toBeTruthy();
expect(formValidationSummary.fieldErrors).toEqual({
myfield: {
succeeded: true,
type: 'MY_VALIDATION_1',
message: 'My Error Message 1',
},
myotherfield: {
succeeded: true,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
},
});
expect(formValidationSummary.recordErrors).toEqual({
myrecord: {
succeeded: true,
type: 'MY_VALIDATION_3',
message: 'My Error Message 3',
},
myotherrecord: {
succeeded: true,
type: 'MY_VALIDATION_4',
message: 'My Error Message 4',
},
});
});
it(`Spec #10 => should returns new FormValidationResult equals { succeeded: true } with one field object and one record object
when passing fieldValidationResults and recordValidationResults with two items with same key and succeeded true
`, () => {
// Arrange
const fieldValidationResults: InternalValidationResult[] = [
{
succeeded: true,
type: 'MY_VALIDATION_1',
message: 'My Error Message 1',
key: 'myfield',
},
{
succeeded: true,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
key: 'myfield',
},
];
const recordValidationResults: InternalValidationResult[] = [
{
succeeded: true,
type: 'MY_VALIDATION_3',
message: 'My Error Message 3',
key: 'myrecord',
},
{
succeeded: true,
type: 'MY_VALIDATION_4',
message: 'My Error Message 4',
key: 'myrecord',
},
];
// Act
const formValidationSummary = buildFormValidationResult(
fieldValidationResults,
recordValidationResults
);
// Assert
expect(formValidationSummary.succeeded).toBeTruthy();
expect(formValidationSummary.fieldErrors).toEqual({
myfield: {
succeeded: true,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
},
});
expect(formValidationSummary.recordErrors).toEqual({
myrecord: {
succeeded: true,
type: 'MY_VALIDATION_4',
message: 'My Error Message 4',
},
});
});
it(`Spec #11 => should returns new FormValidationResult equals { succeeded: false } with one field object and one record object
when passing fieldValidationResults and recordValidationResults with two items with same key and succeeded false
`, () => {
// Arrange
const fieldValidationResults: InternalValidationResult[] = [
{
succeeded: false,
type: 'MY_VALIDATION_1',
message: 'My Error Message 1',
key: 'myfield',
},
{
succeeded: false,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
key: 'myfield',
},
];
const recordValidationResults: InternalValidationResult[] = [
{
succeeded: false,
type: 'MY_VALIDATION_3',
message: 'My Error Message 3',
key: 'myrecord',
},
{
succeeded: false,
type: 'MY_VALIDATION_4',
message: 'My Error Message 4',
key: 'myrecord',
},
];
// Act
const formValidationSummary = buildFormValidationResult(
fieldValidationResults,
recordValidationResults
);
// Assert
expect(formValidationSummary.succeeded).toBeFalsy();
expect(formValidationSummary.fieldErrors).toEqual({
myfield: {
succeeded: false,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
},
});
expect(formValidationSummary.recordErrors).toEqual({
myrecord: {
succeeded: false,
type: 'MY_VALIDATION_4',
message: 'My Error Message 4',
},
});
});
it(`Spec #12 => should returns new FormValidationResult equals { succeeded: false } with one field object and one record object
when passing fieldValidationResults and recordValidationResults with two items with same key and first succeeded true and second succeeded false
`, () => {
// Arrange
const fieldValidationResults: InternalValidationResult[] = [
{
succeeded: true,
type: 'MY_VALIDATION_1',
message: 'My Error Message 1',
key: 'myfield',
},
{
succeeded: false,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
key: 'myfield',
},
];
const recordValidationResults: InternalValidationResult[] = [
{
succeeded: true,
type: 'MY_VALIDATION_3',
message: 'My Error Message 3',
key: 'myrecord',
},
{
succeeded: false,
type: 'MY_VALIDATION_4',
message: 'My Error Message 4',
key: 'myrecord',
},
];
// Act
const formValidationSummary = buildFormValidationResult(
fieldValidationResults,
recordValidationResults
);
// Assert
expect(formValidationSummary.succeeded).toBeFalsy();
expect(formValidationSummary.fieldErrors).toEqual({
myfield: {
succeeded: false,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
},
});
expect(formValidationSummary.recordErrors).toEqual({
myrecord: {
succeeded: false,
type: 'MY_VALIDATION_4',
message: 'My Error Message 4',
},
});
});
it(`Spec #13 => should returns new FormValidationResult equals { succeeded: false } with one field object and one record object
when passing fieldValidationResults and recordValidationResults with two items with same key and first succeeded false and second succeeded true
`, () => {
// Arrange
const fieldValidationResults: InternalValidationResult[] = [
{
succeeded: false,
type: 'MY_VALIDATION_1',
message: 'My Error Message 1',
key: 'myfield',
},
{
succeeded: true,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
key: 'myfield',
},
];
const recordValidationResults: InternalValidationResult[] = [
{
succeeded: false,
type: 'MY_VALIDATION_3',
message: 'My Error Message 3',
key: 'myrecord',
},
{
succeeded: true,
type: 'MY_VALIDATION_4',
message: 'My Error Message 4',
key: 'myrecord',
},
];
// Act
const formValidationSummary = buildFormValidationResult(
fieldValidationResults,
recordValidationResults
);
// Assert
expect(formValidationSummary.succeeded).toBeFalsy();
expect(formValidationSummary.fieldErrors).toEqual({
myfield: {
succeeded: true,
type: 'MY_VALIDATION_2',
message: 'My Error Message 2',
},
});
expect(formValidationSummary.recordErrors).toEqual({
myrecord: {
succeeded: true,
type: 'MY_VALIDATION_4',
message: 'My Error Message 4',
},
});
});
});
}); | the_stack |
import { StandardArticle } from "@artsy/reaction/dist/Components/Publishing/Fixtures/Articles"
import {
applySelectionToEditorState,
htmlWithDisallowedStyles,
htmlWithRichBlocks,
} from "client/components/draft/shared/test_helpers"
import { convertFromHTML } from "draft-convert"
import Draft, { EditorState } from "draft-js"
import { mount } from "enzyme"
import React from "react"
import { RichText } from "../rich_text"
jest.mock("lodash/debounce", () => jest.fn(e => e))
Draft.getVisibleSelectionRect = jest.fn().mockReturnValue({
bottom: 170,
height: 25,
left: 425,
right: 525,
top: 145,
width: 95,
})
const Selection = require("../../shared/selection")
jest.mock("../../shared/selection", () => ({
getSelectionDetails: jest.fn().mockReturnValue({
anchorOffset: 0,
isFirstBlock: true,
}),
}))
window.scrollTo = jest.fn()
describe("RichText", () => {
let props
const html = StandardArticle.sections && StandardArticle.sections[0].body
const getWrapper = (passedProps = props) => {
return mount(<RichText {...passedProps} />)
}
beforeEach(() => {
props = {
allowedBlocks: ["h1", "h2", "h3", "ul", "ol", "blockquote", "p"],
html,
hasLinks: true,
onChange: jest.fn(),
onHandleBackspace: jest.fn(),
onHandleBlockQuote: jest.fn(),
onHandleReturn: jest.fn(),
onHandleTab: jest.fn(),
placeholder: "Start typing...",
}
delete props.allowedStyles
})
const getClientRects = jest.fn().mockReturnValue([
{
bottom: 170,
height: 25,
left: 425,
right: 525,
top: 145,
width: 95,
},
])
const getRangeAt = jest.fn().mockReturnValue({ getClientRects })
describe("#setEditorState", () => {
describe("Create from empty", () => {
it("Can initialize an empty state", () => {
props.html = null
const component = getWrapper()
expect(component.text()).toBe("Start typing...")
})
})
describe("Create with content", () => {
it("Can initialize with existing content", () => {
const component = getWrapper()
expect(component.text()).toMatch(
"What would Antoine Court’s de Gébelin think of the Happy Squirrel?"
)
})
it("Can initialize existing content with decorators", () => {
const component = getWrapper()
expect(component.html()).toMatch("<a href=")
})
})
})
describe("#editorStateToHtml", () => {
it("Removes disallowed blocks from existing content", () => {
const disallowedBlocks = convertFromHTML({})(htmlWithRichBlocks)
const editorState = EditorState.createWithContent(disallowedBlocks)
const component = getWrapper().instance() as RichText
const stateAsHtml = component.editorStateToHTML(editorState)
expect(stateAsHtml).toBe(
"<p>a link</p><p></p><h1>an h1</h1><h2>an h2</h2><h3>an h3</h3><p>an h4</p><p>an h5</p><p>an h6</p><ul><li>unordered list</li><li>second list item</li></ul><ol><li>ordered list</li></ol><blockquote>a blockquote</blockquote>"
)
})
it("Removes disallowed styles from existing content", () => {
const disallowedStyles = convertFromHTML({})(htmlWithDisallowedStyles)
const editorState = EditorState.createWithContent(disallowedStyles)
const component = getWrapper().instance() as RichText
const stateAsHtml = component.editorStateToHTML(editorState)
expect(stateAsHtml).toBe(
"<p><s>Strikethrough text</s> Code text Underline text <i>Italic text</i> <i>Italic text</i> <b>Bold text</b> <b>Bold text</b></p>"
)
})
})
describe("#editorStateFromHTML", () => {
it("Removes disallowed blocks", () => {
props.html = htmlWithRichBlocks
props.hasLinks = true
const component = getWrapper()
const instance = component.instance() as RichText
const editorState = instance.editorStateFromHTML(component.props().html)
instance.onChange(editorState)
expect(instance.state.html).toBe(
'<p><a href="https://artsy.net/">a link</a></p><h1>an h1</h1><h2>an h2</h2><h3>an h3</h3><p>an h4</p><p>an h5</p><p>an h6</p><ul><li>unordered list</li><li>second list item</li></ul><ol><li>ordered list</li></ol><blockquote>a blockquote</blockquote>'
)
})
it("Removes links if props.hasLinks is false", () => {
props.html = htmlWithRichBlocks
props.hasLinks = false
const component = getWrapper()
const instance = component.instance() as RichText
const editorState = instance.editorStateFromHTML(component.props().html)
instance.onChange(editorState)
expect(instance.state.html).toBe(
"<p>a link</p><h1>an h1</h1><h2>an h2</h2><h3>an h3</h3><p>an h4</p><p>an h5</p><p>an h6</p><ul><li>unordered list</li><li>second list item</li></ul><ol><li>ordered list</li></ol><blockquote>a blockquote</blockquote>"
)
})
it("Removes empty blocks unless h1", () => {
props.html = "<p>A paragraph</p><p></p><h1></h1><h2></h2>"
const component = getWrapper()
const instance = component.instance() as RichText
const editorState = instance.editorStateFromHTML(component.props().html)
instance.onChange(editorState)
expect(instance.state.html).toBe("<p>A paragraph</p><h1></h1>")
})
it("Removes disallowed styles", () => {
props.html = htmlWithDisallowedStyles
const component = getWrapper()
const instance = component.instance() as RichText
const editorState = instance.editorStateFromHTML(component.props().html)
instance.onChange(editorState)
expect(instance.state.html).toBe(
"<p><s>Strikethrough text</s> Code text Underline text <i>Italic text</i> <i>Italic text</i> <b>Bold text</b> <b>Bold text</b></p>"
)
})
it("Calls #stripGoogleStyles", () => {
props.html =
'<b style="font-weight:normal;" id="docs-internal-guid-ce2bb19a-cddb-9e53-cb18-18e71847df4e"><p><span style="font-size:11pt;color:#000000;background-color:transparent;font-weight:400;font-style:normal;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre-wrap;">Available at: <em>Espacio Valverde</em> • Galleries Sector, Booth 9F01</span></p>'
const component = getWrapper(props)
const instance = component.instance() as RichText
const editorState = instance.editorStateFromHTML(component.props().html)
instance.onChange(editorState)
expect(instance.state.html).toBe(
"<p>Available at: <i>Espacio Valverde</i> • Galleries Sector, Booth 9F01</p>"
)
})
})
describe("#onChange", () => {
it("Sets state with new editorState and html", () => {
const editorContent = convertFromHTML({})("<p>A new piece of text.</p>")
const editorState = EditorState.createWithContent(editorContent)
const component = getWrapper(props)
const instance = component.instance() as RichText
const originalState = instance.state.editorState
instance.onChange(editorState)
expect(instance.state.html).toBe("<p>A new piece of text.</p>")
expect(instance.state.editorState).not.toBe(originalState)
})
it("Calls props.onChange if html is changed", () => {
const editorContent = convertFromHTML({})("<p>A new piece of text.</p>")
const editorState = EditorState.createWithContent(editorContent)
const component = getWrapper()
const instance = component.instance() as RichText
instance.onChange(editorState)
expect(instance.state.html).toBe("<p>A new piece of text.</p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
it("Does not call props.onChange if html is unchanged", () => {
props.html = "<p>A new piece of text.</p>"
const editorContent = convertFromHTML({})(props.html)
const editorState = EditorState.createWithContent(editorContent)
const component = getWrapper()
const instance = component.instance() as RichText
instance.setState = jest.fn()
component.update()
instance.onChange(editorState)
expect(instance.setState).toBeCalled()
expect(instance.props.onChange).not.toHaveBeenCalled()
})
})
describe("#focus", () => {
beforeEach(() => {
window.getSelection = jest.fn().mockReturnValue({
isCollapsed: false,
getRangeAt,
})
})
it("Calls focus on the editor", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.focus()
// TODO: update to work with new enzyme types
// @ts-ignore
const { hasFocus } = instance.state.editorState.getSelection()
expect(hasFocus).toBeTruthy()
})
it("Calls #checkSelection", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.checkSelection = jest.fn()
component.update()
instance.focus()
expect(instance.checkSelection).toBeCalled()
})
})
it("#blur removes focus from the editor", () => {
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.blur()
// TODO: update to work with new enzyme types
// @ts-ignore
const { hasFocus } = instance.state.editorState.getSelection()
expect(hasFocus).toBeFalsy()
})
describe("#resetEditorState", () => {
it("Resets the editorState with current props.html", done => {
const component = getWrapper()
const instance = component.instance() as RichText
props.html = "<p>A piece of text</p>"
component.setProps(props)
instance.resetEditorState()
setTimeout(() => {
expect(instance.state.html).toBe("<p>A piece of text</p>")
done()
}, 10)
})
})
xdescribe("#componentWillReceiveProps", () => {
xit("does a thing", () => {
expect(true).toBeTruthy()
})
})
describe("#handleBackspace", () => {
it("Returns not handled if cursor is inside block", () => {
window.getSelection = jest.fn().mockReturnValue({
isCollapsed: false,
getRangeAt,
})
const component = getWrapper()
const instance = component.instance() as RichText
instance.blur = jest.fn()
component.update()
const selectedState = applySelectionToEditorState(
instance.state.editorState,
20
)
instance.onChange(selectedState)
const handler = instance.handleBackspace()
expect(handler).toBe("not-handled")
expect(props.onHandleBackspace).not.toBeCalled()
expect(instance.blur).not.toBeCalled()
})
it("Returns not handled if text is selected", () => {
window.getSelection = jest.fn().mockReturnValue({
isCollapsed: true,
getRangeAt,
})
const component = getWrapper()
const instance = component.instance() as RichText
instance.blur = jest.fn()
component.update()
const selectedState = applySelectionToEditorState(
instance.state.editorState,
20
)
instance.onChange(selectedState)
const handler = instance.handleBackspace()
expect(handler).toBe("not-handled")
expect(props.onHandleBackspace).not.toBeCalled()
expect(instance.blur).not.toBeCalled()
})
it("Returns not handled if props.onHandleBackspace is not provided", () => {
delete props.onHandleBackspace
window.getSelection = jest.fn().mockReturnValue({
isCollapsed: false,
getRangeAt,
})
const component = getWrapper()
const instance = component.instance() as RichText
instance.blur = jest.fn()
component.update()
instance.focus()
const handler = instance.handleBackspace()
expect(handler).toBe("not-handled")
expect(instance.blur).not.toBeCalled()
})
it("If blocks should merge, returns handled", () => {
window.getSelection = jest.fn().mockReturnValue({
isCollapsed: false,
getRangeAt,
})
const component = getWrapper()
const instance = component.instance() as RichText
instance.blur = jest.fn()
component.update()
instance.focus()
const handler = instance.handleBackspace()
expect(handler).toBe("handled")
expect(props.onHandleBackspace).toBeCalled()
expect(instance.blur).toBeCalled()
})
})
describe("#handleReturn", () => {
it("Calls props.onHandleReturn provided and result is handled", () => {
Selection.getSelectionDetails.mockReturnValueOnce({
isFirstBlock: false,
})
const preventDefault = jest.fn()
const component = getWrapper(props).instance() as RichText
component.focus()
const handleReturn = component.handleReturn({ preventDefault })
expect(preventDefault).toBeCalled()
expect(props.onHandleReturn).toBeCalled()
expect(handleReturn).toBe("handled")
})
it("Does not call props.onHandleReturn provided and result is not-handled", () => {
const component = getWrapper(props).instance() as RichText
const handleReturn = component.handleReturn({})
expect(handleReturn).toBe("not-handled")
expect(props.onHandleReturn).not.toBeCalled()
})
it("Returns not-handled by default", () => {
const component = getWrapper(props).instance() as RichText
const handleReturn = component.handleReturn({})
expect(handleReturn).toBe("not-handled")
expect(props.onHandleReturn).not.toBeCalled()
})
})
describe("#handleKeyCommand", () => {
it("Calls #handleBackspace if backspace", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.handleBackspace = jest.fn()
component.update()
instance.handleKeyCommand("backspace")
expect(instance.handleBackspace).toBeCalled()
})
it("Calls #makePlainText if plain-text", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.makePlainText = jest.fn()
component.update()
instance.handleKeyCommand("plain-text")
expect(instance.makePlainText).toBeCalled()
})
describe("links", () => {
it("Calls #promptForLink if link-prompt and props.hasLinks", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.promptForLink = jest.fn()
component.update()
instance.handleKeyCommand("link-prompt")
expect(instance.promptForLink).toBeCalled()
})
it("Returns not-handled if link-prompt and props.hasLinks is false", () => {
props.hasLinks = false
const component = getWrapper()
const instance = component.instance() as RichText
instance.promptForLink = jest.fn()
component.update()
const handleKeyCommand = instance.handleKeyCommand("link-prompt")
expect(instance.promptForLink).not.toBeCalled()
expect(handleKeyCommand).toBe("not-handled")
})
})
describe("blocks", () => {
it("Calls #keyCommandBlockType if blockquote", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.keyCommandBlockType = jest.fn()
component.update()
instance.handleKeyCommand("blockquote")
expect(instance.keyCommandBlockType).toBeCalledWith("blockquote")
})
it("Calls #keyCommandBlockType if header-one", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.keyCommandBlockType = jest.fn()
component.update()
instance.handleKeyCommand("header-one")
expect(instance.keyCommandBlockType).toBeCalledWith("header-one")
})
it("Calls #keyCommandBlockType if header-two", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.keyCommandBlockType = jest.fn()
component.update()
instance.handleKeyCommand("header-two")
expect(instance.keyCommandBlockType).toBeCalledWith("header-two")
})
it("Calls #keyCommandBlockType if header-three", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.keyCommandBlockType = jest.fn()
component.update()
instance.handleKeyCommand("header-three")
expect(instance.keyCommandBlockType).toBeCalledWith("header-three")
})
it("Returns not-handled for disallowed blocks", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.keyCommandBlockType = jest.fn()
component.update()
instance.handleKeyCommand("header-four")
expect(instance.keyCommandBlockType).not.toBeCalled()
})
})
describe("styles", () => {
it("Calls #keyCommandInlineStyle if bold", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.keyCommandInlineStyle = jest.fn()
component.update()
instance.handleKeyCommand("bold")
expect(instance.keyCommandInlineStyle).toBeCalledWith("bold")
})
it("Calls #keyCommandInlineStyle if italic", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.keyCommandInlineStyle = jest.fn()
component.update()
instance.handleKeyCommand("italic")
expect(instance.keyCommandInlineStyle).toBeCalledWith("italic")
})
it("Calls #keyCommandInlineStyle if underline", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.keyCommandInlineStyle = jest.fn()
component.update()
instance.handleKeyCommand("underline")
expect(instance.keyCommandInlineStyle).toBeCalledWith("underline")
})
it("Calls #toggleInlineStyle if strikethrough", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.toggleInlineStyle = jest.fn()
component.update()
instance.handleKeyCommand("strikethrough")
expect(instance.toggleInlineStyle).toBeCalledWith("strikethrough")
})
it("Returns not-handled for disallowed styles", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.keyCommandInlineStyle = jest.fn()
instance.toggleInlineStyle = jest.fn()
component.update()
instance.handleKeyCommand("code")
expect(instance.keyCommandInlineStyle).not.toBeCalled()
expect(instance.toggleInlineStyle).not.toBeCalled()
})
})
})
describe("#keyCommandBlockType", () => {
beforeEach(() => {
props.html = "<p>A piece of text</p>"
})
it("Returns not-handled for disallowed blocks", () => {
props.allowedBlocks = ["p"]
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandBlockType("header-one")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).not.toHaveBeenCalled()
})
describe("H1", () => {
it("Can create h1 blocks", () => {
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandBlockType("header-one")
expect(instance.state.html).toBe("<h1>A piece of text</h1>")
expect(instance.props.onChange).toHaveBeenCalled()
})
it("Can remove existing h1 blocks", () => {
props.html = "<h1>A piece of text</h1>"
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandBlockType("header-one")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
})
describe("H2", () => {
it("Can create h2 blocks", () => {
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandBlockType("header-two")
expect(instance.state.html).toBe("<h2>A piece of text</h2>")
expect(instance.props.onChange).toHaveBeenCalled()
})
it("Can remove existing h2 blocks", () => {
props.html = "<h2>A piece of text</h2>"
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandBlockType("header-two")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
})
describe("H3", () => {
it("Can create h3 blocks", () => {
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandBlockType("header-three")
expect(instance.state.html).toBe("<h3>A piece of text</h3>")
expect(instance.props.onChange).toHaveBeenCalled()
})
it("Can remove existing h3 blocks", () => {
props.html = "<h3>A piece of text</h3>"
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandBlockType("header-three")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
})
describe("OL", () => {
it("Can create OL blocks", () => {
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandBlockType("ordered-list-item")
expect(instance.state.html).toBe("<ol><li>A piece of text</li></ol>")
expect(instance.props.onChange).toHaveBeenCalled()
})
it("Can remove existing OL blocks", () => {
props.html = "<ol><li>A piece of text</li></ol>"
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandBlockType("ordered-list-item")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
})
describe("UL", () => {
it("Can create UL blocks", () => {
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandBlockType("unordered-list-item")
expect(instance.state.html).toBe("<ul><li>A piece of text</li></ul>")
expect(instance.props.onChange).toHaveBeenCalled()
})
it("Can remove existing UL blocks", () => {
props.html = "<ul><li>A piece of text</li></ul>"
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandBlockType("unordered-list-item")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
})
describe("Blockquote", () => {
it("Can create blockquote blocks", () => {
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandBlockType("blockquote")
expect(instance.state.html).toBe(
"<blockquote>A piece of text</blockquote>"
)
expect(instance.props.onChange).toHaveBeenCalled()
expect(props.onHandleBlockQuote).toHaveBeenCalled()
})
it("Can remove existing blockquote blocks", () => {
props.html = "<blockquote>A piece of text</blockquote>"
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandBlockType("blockquote")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).toHaveBeenCalled()
expect(props.onHandleBlockQuote).not.toHaveBeenCalled()
})
})
})
describe("#toggleBlockType", () => {
beforeEach(() => {
props.html = "<p>A piece of text</p>"
})
it("Does nothing for disallowed blocks", () => {
props.allowedBlocks = ["p"]
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleBlockType("header-one")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).not.toHaveBeenCalled()
})
describe("H1", () => {
it("Can create h1 blocks", () => {
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleBlockType("header-one")
expect(instance.state.html).toBe("<h1>A piece of text</h1>")
expect(instance.props.onChange).toHaveBeenCalled()
})
it("Can remove existing h1 blocks", () => {
props.html = "<h1>A piece of text</h1>"
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleBlockType("header-one")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
})
describe("H2", () => {
it("Can create h2 blocks", () => {
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleBlockType("header-two")
expect(instance.state.html).toBe("<h2>A piece of text</h2>")
expect(instance.props.onChange).toHaveBeenCalled()
})
it("Can remove existing h2 blocks", () => {
props.html = "<h2>A piece of text</h2>"
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleBlockType("header-two")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
})
describe("H3", () => {
it("Can create h3 blocks", () => {
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleBlockType("header-three")
expect(instance.state.html).toBe("<h3>A piece of text</h3>")
expect(instance.props.onChange).toHaveBeenCalled()
})
it("Can remove existing h2 blocks", () => {
props.html = "<h3>A piece of text</h3>"
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleBlockType("header-three")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
})
describe("OL", () => {
it("Can create ol blocks", () => {
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleBlockType("ordered-list-item")
expect(instance.state.html).toBe("<ol><li>A piece of text</li></ol>")
expect(instance.props.onChange).toHaveBeenCalled()
})
it("Can remove existing ol blocks", () => {
props.html = "<ol><li>A piece of text</li></ol>"
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleBlockType("ordered-list-item")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
})
describe("UL", () => {
it("Can create ul blocks", () => {
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleBlockType("unordered-list-item")
expect(instance.state.html).toBe("<ul><li>A piece of text</li></ul>")
expect(instance.props.onChange).toHaveBeenCalled()
})
it("Can remove existing ul blocks", () => {
props.html = "<ul><li>A piece of text</li></ul>"
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleBlockType("unordered-list-item")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
})
describe("Blockquote", () => {
it("Can create blockquote blocks", () => {
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleBlockType("blockquote")
expect(instance.state.html).toBe(
"<blockquote>A piece of text</blockquote>"
)
expect(instance.props.onChange).toHaveBeenCalled()
expect(props.onHandleBlockQuote).toHaveBeenCalled()
})
it("Can remove existing blockquote blocks", () => {
props.html = "<blockquote>A piece of text</blockquote>"
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleBlockType("blockquote")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).toHaveBeenCalled()
expect(props.onHandleBlockQuote).not.toHaveBeenCalled()
})
})
})
describe("#keyCommandInlineStyle", () => {
beforeEach(() => {
props.html = "<p>A piece of text</p>"
})
describe("Bold", () => {
it("Applies bold styles if allowed", () => {
const component = getWrapper()
const instance = component.instance() as RichText
// Set text selection
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandInlineStyle("bold")
expect(instance.state.html).toBe("<p><b>A piece of text</b></p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
it("Does not apply bold styles if not allowed", () => {
props.allowedStyles = ["I"]
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandInlineStyle("bold")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).not.toHaveBeenCalled()
})
it("Can remove existing bold styles", () => {
props.html = "<p><b>A piece of text</b></p>"
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandInlineStyle("bold")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
})
describe("Italic", () => {
it("Applies italic styles if allowed", () => {
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandInlineStyle("italic")
expect(instance.state.html).toBe("<p><i>A piece of text</i></p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
it("Does not apply italic styles if not allowed", () => {
props.allowedStyles = ["B"]
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandInlineStyle("italic")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).not.toHaveBeenCalled()
})
it("Can remove existing italic styles", () => {
props.html = "<p><i>A piece of text</i></p>"
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandInlineStyle("italic")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
})
describe("Underline", () => {
it("Applies underline styles if allowed", () => {
props.allowedStyles = ["U"]
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandInlineStyle("underline")
expect(instance.state.html).toBe("<p><u>A piece of text</u></p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
it("Does not apply underline styles if not allowed", () => {
props.allowedStyles = ["B"]
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandInlineStyle("underline")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).not.toHaveBeenCalled()
})
it("Can remove existing underline styles", () => {
props.allowedStyles = ["U"]
props.html = "<p><u>A piece of text</u></p>"
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.keyCommandInlineStyle("underline")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
})
})
describe("#toggleInlineStyle", () => {
beforeEach(() => {
props.html = "<p>A piece of text</p>"
})
describe("Bold", () => {
it("Applies bold styles if allowed", () => {
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleInlineStyle("BOLD")
expect(instance.state.html).toBe("<p><b>A piece of text</b></p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
it("Does not apply bold styles if not allowed", () => {
props.allowedStyles = ["I"]
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleInlineStyle("BOLD")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).not.toHaveBeenCalled()
})
it("Can remove existing bold styles", () => {
props.html = "<p><b>A piece of text</b></p>"
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleInlineStyle("BOLD")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
})
describe("Italic", () => {
it("Applies italic styles if allowed", () => {
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleInlineStyle("ITALIC")
expect(instance.state.html).toBe("<p><i>A piece of text</i></p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
it("Does not apply italic styles if not allowed", () => {
props.allowedStyles = ["B"]
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleInlineStyle("ITALIC")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).not.toHaveBeenCalled()
})
it("Can remove existing italic styles", () => {
props.html = "<p><i>A piece of text</i></p>"
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleInlineStyle("ITALIC")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
})
describe("Underline", () => {
beforeEach(() => {
props.allowedStyles = ["U"]
})
it("Applies underline styles if allowed", () => {
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleInlineStyle("UNDERLINE")
expect(instance.state.html).toBe("<p><u>A piece of text</u></p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
it("Does not apply underline styles if not allowed", () => {
props.allowedStyles = ["B"]
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleInlineStyle("UNDERLINE")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).not.toHaveBeenCalled()
})
it("Can remove existing underline styles", () => {
props.html = "<p><u>A piece of text</u></p>"
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleInlineStyle("UNDERLINE")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
})
describe("Strikethrough", () => {
beforeEach(() => {
props.allowedStyles = ["S"]
})
it("Applies strikethrough styles if allowed", () => {
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleInlineStyle("STRIKETHROUGH")
expect(instance.state.html).toBe("<p><s>A piece of text</s></p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
it("Does not apply strikethrough styles if not allowed", () => {
props.allowedStyles = ["B"]
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleInlineStyle("STRIKETHROUGH")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).not.toHaveBeenCalled()
})
it("Can remove existing strikethrough styles", () => {
props.html = "<p><s>A piece of text</s></p>"
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.toggleInlineStyle("STRIKETHROUGH")
expect(instance.state.html).toBe("<p>A piece of text</p>")
expect(instance.props.onChange).toHaveBeenCalled()
})
})
})
describe("#makePlainText", () => {
it("strips links from text", () => {
props.html = "<p><a href='artsy.net'>A link</a></p>"
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.makePlainText()
expect(instance.state.html).toBe("<p>A link</p>")
})
it("strips blocks from text", () => {
props.html = "<h1><a href='artsy.net'>A linked h1</a></h1>"
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.makePlainText()
expect(instance.state.html).toBe("<p>A linked h1</p>")
})
it("strips styles from text", () => {
props.html =
"<h1><a href='artsy.net'><b>A strong <em>italic linked h1</em></b></a></h1>"
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.makePlainText()
expect(instance.state.html).toBe("<p>A strong italic linked h1</p>")
})
})
describe("#handlePastedText", () => {
beforeEach(() => {
props.html = "<p>A piece of text</p>"
})
it("Can paste plain text", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.handlePastedText("Some pasted text...")
expect(instance.state.html).toBe(
"<p>Some pasted text...A piece of text</p>"
)
})
it("Can paste html", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.handlePastedText("", "<p>Some pasted text...</p>")
expect(instance.state.html).toBe(
"<p>Some pasted text...A piece of text</p>"
)
})
it("Removes disallowed blocks from pasted content", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.handlePastedText("", htmlWithRichBlocks)
expect(instance.state.html).toBe(
'<p><a href="https://artsy.net/">a link</a></p><h1>an h1</h1><h2>an h2</h2><h3>an h3</h3><p>an h4</p><p>an h5</p><p>an h6</p><ul><li>unordered list</li><li>second list item</li></ul><ol><li>ordered list</li></ol><blockquote>a blockquoteA piece of text</blockquote>'
)
})
it("Removes disallowed styles from pasted content", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.handlePastedText("", htmlWithDisallowedStyles)
expect(instance.state.html).toBe(
"<p><s>Strikethrough text</s> Code text Underline text <i>Italic text</i> <i>Italic text</i> <b>Bold text</b> <b>Bold text</b>A piece of text</p>"
)
})
it("Strips linebreaks from pasted content", () => {
props.stripLinebreaks = true
const component = getWrapper()
const instance = component.instance() as RichText
instance.handlePastedText("", htmlWithRichBlocks)
expect(instance.state.html).toBe(
'<p><a href="https://artsy.net/">a link</a></p><h1>an h1</h1><h2>an h2</h2><h3>an h3</h3><p>an h4</p><p>an h5</p><p>an h6</p><ul><li>unordered list</li><li>second list item</li></ul><ol><li>ordered list</li></ol><blockquote>a blockquoteA piece of text</blockquote>'
)
})
})
describe("Links", () => {
beforeEach(() => {
props.hasLinks = true
window.getSelection = jest.fn().mockReturnValue({
isCollapsed: false,
getRangeAt,
})
})
describe("#promptForLink", () => {
it("Sets editorPosition", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.promptForLink()
expect(instance.state.editorPosition).toEqual({
bottom: 0,
height: 0,
left: 0,
right: 0,
top: 0,
width: 0,
})
})
it("Sets urlValue with data", () => {
props.html = '<p><a href="https://artsy.net">A link</a></p>'
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.promptForLink()
expect(instance.state.urlValue).toBe("https://artsy.net/")
})
it("Sets urlValue without data", () => {
props.html = "<p>A piece of text</p>"
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.promptForLink()
expect(instance.state.urlValue).toBe("")
})
it("Hides nav", () => {
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.checkSelection()
expect(instance.state.showNav).toBe(true)
instance.promptForLink()
expect(instance.state.showNav).toBe(false)
})
it("Shows url input", () => {
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.promptForLink()
expect(instance.state.showUrlInput).toBe(true)
})
})
describe("#confirmLink", () => {
it("Sets editorPosition to null", () => {
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.confirmLink("https://artsy.net/articles")
expect(instance.state.editorPosition).toBe(null)
})
it("Sets urlValue to empty string", () => {
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.confirmLink("https://artsy.net/articles")
expect(instance.state.urlValue).toBe("")
})
it("Hides nav and url input", () => {
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.confirmLink("https://artsy.net/articles")
expect(instance.state.showNav).toBe(false)
expect(instance.state.showUrlInput).toBe(false)
})
it("Adds a link to selected text", () => {
props.html = "<p>A piece of text</p>"
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.confirmLink("https://artsy.net/articles")
expect(instance.state.html).toBe(
'<p><a href="https://artsy.net/articles">A piece of text</a></p>'
)
})
})
describe("#removeLink", () => {
beforeEach(() => {
props.html = '<p><a href="https://artsy.net">A link</a></p>'
})
it("Removes a link from selected entity", () => {
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.removeLink()
expect(instance.state.html).toBe("<p>A link</p>")
})
it("Hides url input", () => {
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.removeLink()
expect(instance.state.showUrlInput).toBe(false)
})
it("Sets urlValue to empty string", () => {
const component = getWrapper()
const instance = component.instance() as RichText
const selectedState = applySelectionToEditorState(
instance.state.editorState
)
instance.onChange(selectedState)
instance.removeLink()
expect(instance.state.urlValue).toBe("")
})
})
})
describe("#checkSelection", () => {
describe("Has selection", () => {
beforeEach(() => {
window.getSelection = jest.fn().mockReturnValue({
isCollapsed: false,
getRangeAt,
})
})
it("Sets editorPosition if has selection", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.checkSelection()
expect(instance.state.editorPosition).toEqual({
bottom: 0,
height: 0,
left: 0,
right: 0,
top: 0,
width: 0,
})
})
it("Shows nav if has selection", () => {
const component = getWrapper()
const instance = component.instance() as RichText
instance.checkSelection()
expect(instance.state.showNav).toBe(true)
})
})
describe("No selection", () => {
beforeEach(() => {
window.getSelection = jest.fn().mockReturnValue({
isCollapsed: true,
})
})
it("Resets editorPosition to null if no selection", () => {
const component = getWrapper()
const instance = component.instance() as RichText
component.setState({ editorPosition: { top: 50, left: 100 } })
instance.checkSelection()
expect(instance.state.editorPosition).toBe(null)
})
it("Hides nav if no selection", () => {
const component = getWrapper()
const instance = component.instance() as RichText
component.setState({
showNav: true,
editorPosition: { top: 50, left: 100 },
})
instance.checkSelection()
expect(instance.state.showNav).toBe(false)
})
})
})
}) | the_stack |
import React, { useState, useEffect } from "react";
import {
View,
Text,
StyleSheet,
TextInput,
Pressable,
KeyboardAvoidingView,
Platform,
Image,
Alert,
} from "react-native";
import {
SimpleLineIcons,
Feather,
MaterialCommunityIcons,
AntDesign,
Ionicons,
} from "@expo/vector-icons";
import { DataStore } from "@aws-amplify/datastore";
import { ChatRoom, Message } from "../../src/models";
import { Auth, Storage } from "aws-amplify";
import EmojiSelector from "react-native-emoji-selector";
import * as ImagePicker from "expo-image-picker";
import { v4 as uuidv4 } from "uuid";
import { Audio, AVPlaybackStatus } from "expo-av";
import AudioPlayer from "../AudioPlayer";
import MessageComponent from "../Message";
import { ChatRoomUser } from "../../src/models";
import { useNavigation } from "@react-navigation/core";
import { box } from "tweetnacl";
import {
encrypt,
getMySecretKey,
stringToUint8Array,
} from "../../utils/crypto";
const MessageInput = ({ chatRoom, messageReplyTo, removeMessageReplyTo }) => {
const [message, setMessage] = useState("");
const [isEmojiPickerOpen, setIsEmojiPickerOpen] = useState(false);
const [image, setImage] = useState<string | null>(null);
const [progress, setProgress] = useState(0);
const [recording, setRecording] = useState<Audio.Recording | null>(null);
const [soundURI, setSoundURI] = useState<string | null>(null);
const navigation = useNavigation();
useEffect(() => {
(async () => {
if (Platform.OS !== "web") {
const libraryResponse =
await ImagePicker.requestMediaLibraryPermissionsAsync();
const photoResponse = await ImagePicker.requestCameraPermissionsAsync();
await Audio.requestPermissionsAsync();
if (
libraryResponse.status !== "granted" ||
photoResponse.status !== "granted"
) {
alert("Sorry, we need camera roll permissions to make this work!");
}
}
})();
}, []);
const sendMessageToUser = async (user, fromUserId) => {
// send message
const ourSecretKey = await getMySecretKey();
if (!ourSecretKey) {
return;
}
if (!user.publicKey) {
Alert.alert(
"The user haven't set his keypair yet",
"Until the user generates the keypair, you cannot securely send him messages"
);
return;
}
console.log("private key", ourSecretKey);
const sharedKey = box.before(
stringToUint8Array(user.publicKey),
ourSecretKey
);
console.log("shared key", sharedKey);
const encryptedMessage = encrypt(sharedKey, { message });
console.log("encrypted message", encryptedMessage);
const newMessage = await DataStore.save(
new Message({
content: encryptedMessage, // <- this messages should be encrypted
userID: fromUserId,
forUserId: user.id,
chatroomID: chatRoom.id,
replyToMessageID: messageReplyTo?.id,
})
);
// updateLastMessage(newMessage);
};
const sendMessage = async () => {
// get all the users of this chatroom
const authUser = await Auth.currentAuthenticatedUser();
const users = (await DataStore.query(ChatRoomUser))
.filter((cru) => cru.chatroom.id === chatRoom.id)
.map((cru) => cru.user);
console.log("users", users);
// for each user, encrypt the `content` with his public key, and save it as a new message
await Promise.all(
users.map((user) => sendMessageToUser(user, authUser.attributes.sub))
);
resetFields();
};
const updateLastMessage = async (newMessage) => {
DataStore.save(
ChatRoom.copyOf(chatRoom, (updatedChatRoom) => {
updatedChatRoom.LastMessage = newMessage;
})
);
};
const onPlusClicked = () => {
console.warn("On plus clicked");
};
const onPress = () => {
if (image) {
sendImage();
} else if (soundURI) {
sendAudio();
} else if (message) {
sendMessage();
} else {
onPlusClicked();
}
};
const resetFields = () => {
setMessage("");
setIsEmojiPickerOpen(false);
setImage(null);
setProgress(0);
setSoundURI(null);
removeMessageReplyTo();
};
// Image picker
const pickImage = async () => {
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [4, 3],
quality: 0.5,
});
if (!result.cancelled) {
setImage(result.uri);
}
};
const takePhoto = async () => {
const result = await ImagePicker.launchCameraAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
aspect: [4, 3],
});
if (!result.cancelled) {
setImage(result.uri);
}
};
const progressCallback = (progress) => {
setProgress(progress.loaded / progress.total);
};
const sendImage = async () => {
if (!image) {
return;
}
const blob = await getBlob(image);
const { key } = await Storage.put(`${uuidv4()}.png`, blob, {
progressCallback,
});
// send message
const user = await Auth.currentAuthenticatedUser();
const newMessage = await DataStore.save(
new Message({
content: message,
image: key,
userID: user.attributes.sub,
chatroomID: chatRoom.id,
replyToMessageID: messageReplyTo?.id,
})
);
updateLastMessage(newMessage);
resetFields();
};
const getBlob = async (uri: string) => {
const respone = await fetch(uri);
const blob = await respone.blob();
return blob;
};
async function startRecording() {
try {
await Audio.setAudioModeAsync({
allowsRecordingIOS: true,
playsInSilentModeIOS: true,
});
console.log("Starting recording..");
const { recording } = await Audio.Recording.createAsync(
Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY
);
setRecording(recording);
console.log("Recording started");
} catch (err) {
console.error("Failed to start recording", err);
}
}
async function stopRecording() {
console.log("Stopping recording..");
if (!recording) {
return;
}
setRecording(null);
await recording.stopAndUnloadAsync();
await Audio.setAudioModeAsync({
allowsRecordingIOS: false,
});
const uri = recording.getURI();
console.log("Recording stopped and stored at", uri);
if (!uri) {
return;
}
setSoundURI(uri);
}
const sendAudio = async () => {
if (!soundURI) {
return;
}
const uriParts = soundURI.split(".");
const extenstion = uriParts[uriParts.length - 1];
const blob = await getBlob(soundURI);
const { key } = await Storage.put(`${uuidv4()}.${extenstion}`, blob, {
progressCallback,
});
// send message
const user = await Auth.currentAuthenticatedUser();
const newMessage = await DataStore.save(
new Message({
content: message,
audio: key,
userID: user.attributes.sub,
chatroomID: chatRoom.id,
status: "SENT",
replyToMessageID: messageReplyTo?.id,
})
);
updateLastMessage(newMessage);
resetFields();
};
return (
<KeyboardAvoidingView
style={[styles.root, { height: isEmojiPickerOpen ? "50%" : "auto" }]}
behavior={Platform.OS === "ios" ? "padding" : "height"}
keyboardVerticalOffset={100}
>
{messageReplyTo && (
<View
style={{
backgroundColor: "#f2f2f2",
padding: 5,
flexDirection: "row",
alignSelf: "stretch",
justifyContent: "space-between",
}}
>
<View style={{ flex: 1 }}>
<Text>Reply to:</Text>
<MessageComponent message={messageReplyTo} />
</View>
<Pressable onPress={() => removeMessageReplyTo()}>
<AntDesign
name="close"
size={24}
color="black"
style={{ margin: 5 }}
/>
</Pressable>
</View>
)}
{image && (
<View style={styles.sendImageContainer}>
<Image
source={{ uri: image }}
style={{ width: 100, height: 100, borderRadius: 10 }}
/>
<View
style={{
flex: 1,
justifyContent: "flex-start",
alignSelf: "flex-end",
}}
>
<View
style={{
height: 5,
borderRadius: 5,
backgroundColor: "#3777f0",
width: `${progress * 100}%`,
}}
/>
</View>
<Pressable onPress={() => setImage(null)}>
<AntDesign
name="close"
size={24}
color="black"
style={{ margin: 5 }}
/>
</Pressable>
</View>
)}
{soundURI && <AudioPlayer soundURI={soundURI} />}
<View style={styles.row}>
<View style={styles.inputContainer}>
<Pressable
onPress={() =>
setIsEmojiPickerOpen((currentValue) => !currentValue)
}
>
<SimpleLineIcons
name="emotsmile"
size={24}
color="#595959"
style={styles.icon}
/>
</Pressable>
<TextInput
style={styles.input}
value={message}
onChangeText={setMessage}
placeholder="Signal message..."
/>
<Pressable onPress={pickImage}>
<Feather
name="image"
size={24}
color="#595959"
style={styles.icon}
/>
</Pressable>
<Pressable onPress={takePhoto}>
<Feather
name="camera"
size={24}
color="#595959"
style={styles.icon}
/>
</Pressable>
<Pressable onPressIn={startRecording} onPressOut={stopRecording}>
<MaterialCommunityIcons
name={recording ? "microphone" : "microphone-outline"}
size={24}
color={recording ? "red" : "#595959"}
style={styles.icon}
/>
</Pressable>
</View>
<Pressable onPress={onPress} style={styles.buttonContainer}>
{message || image || soundURI ? (
<Ionicons name="send" size={18} color="white" />
) : (
<AntDesign name="plus" size={24} color="white" />
)}
</Pressable>
</View>
{isEmojiPickerOpen && (
<EmojiSelector
onEmojiSelected={(emoji) =>
setMessage((currentMessage) => currentMessage + emoji)
}
columns={8}
/>
)}
</KeyboardAvoidingView>
);
};
const styles = StyleSheet.create({
root: {
padding: 10,
},
row: {
flexDirection: "row",
},
inputContainer: {
backgroundColor: "#f2f2f2",
flex: 1,
marginRight: 10,
borderRadius: 25,
borderWidth: 1,
borderColor: "#dedede",
alignItems: "center",
flexDirection: "row",
padding: 5,
},
input: {
flex: 1,
marginHorizontal: 5,
},
icon: {
marginHorizontal: 5,
},
buttonContainer: {
width: 40,
height: 40,
backgroundColor: "#3777f0",
borderRadius: 25,
justifyContent: "center",
alignItems: "center",
},
buttonText: {
color: "white",
fontSize: 35,
},
sendImageContainer: {
flexDirection: "row",
marginVertical: 10,
alignSelf: "stretch",
justifyContent: "space-between",
borderWidth: 1,
borderColor: "lightgray",
borderRadius: 10,
},
});
export default MessageInput; | the_stack |
import assert from 'assert';
import {
getDottedName,
getDottedNameWithGivenNodeAsLastName,
getFirstAncestorOrSelfOfKind,
getFirstNameOfDottedName,
getFullStatementRange,
getStringNodeValueRange,
isFirstNameOfDottedName,
isFromImportAlias,
isFromImportModuleName,
isFromImportName,
isImportAlias,
isImportModuleName,
isLastNameOfDottedName,
} from '../analyzer/parseTreeUtils';
import { rangesAreEqual, TextRange } from '../common/textRange';
import { MemberAccessNode, NameNode, ParseNodeType, StringNode } from '../parser/parseNodes';
import { getNodeAtMarker, getNodeForRange, parseAndGetTestState, TestState } from './harness/fourslash/testState';
test('isImportModuleName', () => {
const code = `
//// import [|/*marker*/os|]
`;
assert(isImportModuleName(getNodeAtMarker(code)));
});
test('isImportAlias', () => {
const code = `
//// import os as [|/*marker*/os|]
`;
assert(isImportAlias(getNodeAtMarker(code)));
});
test('isFromImportModuleName', () => {
const code = `
//// from [|/*marker*/os|] import path
`;
assert(isFromImportModuleName(getNodeAtMarker(code)));
});
test('isFromImportName', () => {
const code = `
//// from . import [|/*marker*/os|]
`;
assert(isFromImportName(getNodeAtMarker(code)));
});
test('isFromImportAlias', () => {
const code = `
//// from . import os as [|/*marker*/os|]
`;
assert(isFromImportAlias(getNodeAtMarker(code)));
});
test('getFirstAncestorOrSelfOfKind', () => {
const code = `
//// import a.b.c
//// a.b.c.function(
//// 1 + 2 + 3,
//// [|/*result*/a.b.c.function2(
//// [|/*marker*/"name"|]
//// )|]
//// )
`;
const state = parseAndGetTestState(code).state;
const node = getFirstAncestorOrSelfOfKind(getNodeAtMarker(state), ParseNodeType.Call);
assert(node);
const result = state.getRangeByMarkerName('result')!;
assert(node.nodeType === ParseNodeType.Call);
assert(node.start === result.pos);
assert(TextRange.getEnd(node) === result.end);
});
test('getDottedNameWithGivenNodeAsLastName', () => {
const code = `
//// [|/*result1*/[|/*marker1*/a|]|]
//// [|/*result2*/a.[|/*marker2*/b|]|]
//// [|/*result3*/a.b.[|/*marker3*/c|]|]
//// [|/*result4*/a.[|/*marker4*/b|]|].c
//// [|/*result5*/[|/*marker5*/a|]|].b.c
`;
const state = parseAndGetTestState(code).state;
for (let i = 1; i <= 5; i++) {
const markerName = 'marker' + i;
const resultName = 'result' + i;
const node = getDottedNameWithGivenNodeAsLastName(getNodeAtMarker(state, markerName) as NameNode);
const result = state.getRangeByMarkerName(resultName)!;
assert(node.nodeType === ParseNodeType.Name || node.nodeType === ParseNodeType.MemberAccess);
assert(node.start === result.pos);
assert(TextRange.getEnd(node) === result.end);
}
});
test('getDottedName', () => {
const code = `
//// [|/*marker1*/a|]
//// [|/*marker2*/a.b|]
//// [|/*marker3*/a.b.c|]
//// [|/*marker4*/a.b|].c
//// [|/*marker5*/a|].b.c
`;
const state = parseAndGetTestState(code).state;
assert.strictEqual(getDottedNameString('marker1'), 'a');
assert.strictEqual(getDottedNameString('marker2'), 'a.b');
assert.strictEqual(getDottedNameString('marker3'), 'a.b.c');
assert.strictEqual(getDottedNameString('marker4'), 'a.b');
assert.strictEqual(getDottedNameString('marker5'), 'a');
function getDottedNameString(marker: string) {
const node = getNodeForRange(state, marker);
return getDottedName(node as NameNode | MemberAccessNode)
?.map((n) => n.value)
.join('.');
}
});
test('getFirstNameOfDottedName', () => {
const code = `
//// [|/*marker1*/a|]
//// [|/*marker2*/a.b|]
//// [|/*marker3*/a.b.c|]
//// [|/*marker4*/a.b|].c
//// [|/*marker5*/a|].b.c
`;
const state = parseAndGetTestState(code).state;
assert.strictEqual(getDottedNameString('marker1'), 'a');
assert.strictEqual(getDottedNameString('marker2'), 'a');
assert.strictEqual(getDottedNameString('marker3'), 'a');
assert.strictEqual(getDottedNameString('marker4'), 'a');
assert.strictEqual(getDottedNameString('marker5'), 'a');
function getDottedNameString(marker: string) {
const node = getNodeForRange(state, marker);
return getFirstNameOfDottedName(node as NameNode | MemberAccessNode)?.value ?? '';
}
});
test('isLastNameOfDottedName', () => {
const code = `
//// [|/*marker1*/a|]
//// a.[|/*marker2*/b|]
//// a.b.[|/*marker3*/c|]
//// a.[|/*marker4*/b|].c
//// [|/*marker5*/a|].b.c
//// (a).[|/*marker6*/b|]
//// (a.b).[|/*marker7*/c|]
//// a().[|/*marker8*/b|]
//// a[0].[|/*marker9*/b|]
//// a.b([|/*marker10*/c|]).d
//// a.b.([|/*marker11*/c|])
//// a.[|/*marker12*/b|].c()
//// a.[|/*marker13*/b|]()
//// a.[|/*marker14*/b|][]
`;
const state = parseAndGetTestState(code).state;
assert.strictEqual(isLastNameOfDottedName(getNodeAtMarker(state, 'marker1') as NameNode), true);
assert.strictEqual(isLastNameOfDottedName(getNodeAtMarker(state, 'marker2') as NameNode), true);
assert.strictEqual(isLastNameOfDottedName(getNodeAtMarker(state, 'marker3') as NameNode), true);
assert.strictEqual(isLastNameOfDottedName(getNodeAtMarker(state, 'marker4') as NameNode), false);
assert.strictEqual(isLastNameOfDottedName(getNodeAtMarker(state, 'marker5') as NameNode), false);
assert.strictEqual(isLastNameOfDottedName(getNodeAtMarker(state, 'marker6') as NameNode), true);
assert.strictEqual(isLastNameOfDottedName(getNodeAtMarker(state, 'marker7') as NameNode), true);
assert.strictEqual(isLastNameOfDottedName(getNodeAtMarker(state, 'marker8') as NameNode), false);
assert.strictEqual(isLastNameOfDottedName(getNodeAtMarker(state, 'marker9') as NameNode), false);
assert.strictEqual(isLastNameOfDottedName(getNodeAtMarker(state, 'marker10') as NameNode), true);
assert.strictEqual(isLastNameOfDottedName(getNodeAtMarker(state, 'marker11') as NameNode), true);
assert.strictEqual(isLastNameOfDottedName(getNodeAtMarker(state, 'marker12') as NameNode), false);
assert.strictEqual(isLastNameOfDottedName(getNodeAtMarker(state, 'marker13') as NameNode), true);
assert.strictEqual(isLastNameOfDottedName(getNodeAtMarker(state, 'marker14') as NameNode), true);
});
test('isFirstNameOfDottedName', () => {
const code = `
//// [|/*marker1*/a|]
//// a.[|/*marker2*/b|]
//// a.b.[|/*marker3*/c|]
//// a.[|/*marker4*/b|].c
//// [|/*marker5*/a|].b.c
//// ([|/*marker6*/a|]).b
//// (a.b).[|/*marker7*/c|]
//// [|/*marker8*/a|]().b
//// a[0].[|/*marker9*/b|]
//// a.b([|/*marker10*/c|]).d
//// a.b.([|/*marker11*/c|])
//// a.[|/*marker12*/b|].c()
//// [|/*marker13*/a|].b()
//// a.[|/*marker14*/b|][]
//// [|/*marker15*/a|][]
`;
const state = parseAndGetTestState(code).state;
assert.strictEqual(isFirstNameOfDottedName(getNodeAtMarker(state, 'marker1') as NameNode), true);
assert.strictEqual(isFirstNameOfDottedName(getNodeAtMarker(state, 'marker2') as NameNode), false);
assert.strictEqual(isFirstNameOfDottedName(getNodeAtMarker(state, 'marker3') as NameNode), false);
assert.strictEqual(isFirstNameOfDottedName(getNodeAtMarker(state, 'marker4') as NameNode), false);
assert.strictEqual(isFirstNameOfDottedName(getNodeAtMarker(state, 'marker5') as NameNode), true);
assert.strictEqual(isFirstNameOfDottedName(getNodeAtMarker(state, 'marker6') as NameNode), true);
assert.strictEqual(isFirstNameOfDottedName(getNodeAtMarker(state, 'marker7') as NameNode), false);
assert.strictEqual(isFirstNameOfDottedName(getNodeAtMarker(state, 'marker8') as NameNode), true);
assert.strictEqual(isFirstNameOfDottedName(getNodeAtMarker(state, 'marker9') as NameNode), false);
assert.strictEqual(isFirstNameOfDottedName(getNodeAtMarker(state, 'marker10') as NameNode), true);
assert.strictEqual(isFirstNameOfDottedName(getNodeAtMarker(state, 'marker11') as NameNode), true);
assert.strictEqual(isFirstNameOfDottedName(getNodeAtMarker(state, 'marker12') as NameNode), false);
assert.strictEqual(isFirstNameOfDottedName(getNodeAtMarker(state, 'marker13') as NameNode), true);
assert.strictEqual(isFirstNameOfDottedName(getNodeAtMarker(state, 'marker14') as NameNode), false);
assert.strictEqual(isFirstNameOfDottedName(getNodeAtMarker(state, 'marker15') as NameNode), true);
});
test('getStringNodeValueRange', () => {
const code = `
//// a = "[|/*marker1*/test|]"
//// b = '[|/*marker2*/test2|]'
//// c = '''[|/*marker3*/test3|]'''
`;
const state = parseAndGetTestState(code).state;
for (let i = 1; i <= 3; i++) {
const markerName = 'marker' + i;
const range = getStringNodeValueRange(getNodeAtMarker(state, markerName) as StringNode);
const result = state.getRangeByMarkerName(markerName)!;
assert(range.start === result.pos);
assert(TextRange.getEnd(range) === result.end);
}
});
test('getFullStatementRange', () => {
const code = `
//// [|/*marker1*/import a
//// |][|/*marker2*/a = 1; |][|/*marker3*/b = 2
//// |][|/*marker4*/if True:
//// pass|]
`;
const state = parseAndGetTestState(code).state;
testRange(state, 'marker1', ParseNodeType.Import);
testRange(state, 'marker2', ParseNodeType.Assignment);
testRange(state, 'marker3', ParseNodeType.Assignment);
testRange(state, 'marker4', ParseNodeType.If);
function testRange(state: TestState, markerName: string, type: ParseNodeType) {
const range = state.getRangeByMarkerName(markerName)!;
const sourceFile = state.program.getBoundSourceFile(range.marker!.fileName)!;
const statementNode = getFirstAncestorOrSelfOfKind(getNodeAtMarker(state, markerName), type)!;
const statementRange = getFullStatementRange(statementNode, sourceFile.getParseResults()!.tokenizerOutput);
const expectedRange = state.convertPositionRange(range);
assert(rangesAreEqual(expectedRange, statementRange));
}
}); | the_stack |
import assert from 'assert';
import Node, { SourceRange } from './base';
import NodeVisitor from './visitor';
import { FunctionDef } from './function_def';
import { Value } from './values';
import { Expression, FilterExpression, InvocationExpression, ProjectionExpression } from './expression';
import Type from '../type';
import * as Optimizer from '../optimize';
import {
iterateSlots2InputParams,
recursiveYieldArraySlots,
makeScope,
FilterSlot,
FieldSlot,
AbstractSlot,
OldSlot,
ScopeMap,
InvocationLike
} from './slots';
import {
DeviceSelector,
Invocation,
InputParam
} from './invocation';
import { TokenStream } from '../new-syntax/tokenstream';
import List from '../utils/list';
import { UnserializableError } from "../utils/errors";
import {
SyntaxPriority,
addParenthesis
} from './syntax_priority';
import arrayEquals from './array_equals';
/**
* An expression that computes a boolean predicate.
* This AST node is used in filter expressions.
*/
export abstract class BooleanExpression extends Node {
static And : any;
isAnd ! : boolean;
static Or : any;
isOr ! : boolean;
static Atom : any;
isAtom ! : boolean;
static Not : any;
isNot ! : boolean;
static External : any;
isExternal ! : boolean;
static ExistentialSubquery : any;
isExistentialSubquery ! : boolean;
static ComparisonSubquery : any;
isComparisonSubquery ! : boolean;
/**
* The constant `true` boolean expression.
*
* This is a singleton, not a class.
*/
static True : BooleanExpression;
isTrue ! : boolean;
/**
* The constant `false` boolean expression.
*
* This is a singleton, not a class.
*/
static False : BooleanExpression;
isFalse ! : boolean;
static Compute : any;
isCompute ! : boolean;
static DontCare : any;
isDontCare ! : boolean;
optimize() : BooleanExpression {
return Optimizer.optimizeFilter(this);
}
abstract get priority() : SyntaxPriority;
abstract clone() : BooleanExpression;
abstract equals(other : BooleanExpression) : boolean;
abstract toLegacy() : BooleanExpression;
/**
* Iterate all slots (scalar value nodes) in this boolean expression.
*
* @deprecated Use {@link Ast.BooleanExpression.iterateSlots2} instead.
*/
abstract iterateSlots(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<OldSlot, void>;
/**
* Iterate all slots (scalar value nodes) in this boolean expression.
*/
abstract iterateSlots2(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, void>;
}
BooleanExpression.prototype.isAnd = false;
BooleanExpression.prototype.isOr = false;
BooleanExpression.prototype.isAtom = false;
BooleanExpression.prototype.isNot = false;
BooleanExpression.prototype.isExternal = false;
BooleanExpression.prototype.isExistentialSubquery = false;
BooleanExpression.prototype.isComparisonSubquery = false;
BooleanExpression.prototype.isTrue = false;
BooleanExpression.prototype.isFalse = false;
BooleanExpression.prototype.isCompute = false;
BooleanExpression.prototype.isDontCare = false;
/**
* A conjunction boolean expression (ThingTalk operator `&&`)
*/
export class AndBooleanExpression extends BooleanExpression {
/**
* The expression operands.
*/
operands : BooleanExpression[];
/**
* Construct a new And expression.
*
* @param location - the position of this node in the source code
* @param operands - the expression operands
*/
constructor(location : SourceRange|null, operands : BooleanExpression[]) {
super(location);
assert(Array.isArray(operands));
this.operands = operands;
}
get priority() : SyntaxPriority {
return SyntaxPriority.And;
}
toSource() : TokenStream {
return List.join(this.operands.map((op) => addParenthesis(this.priority, op.priority, op.toSource())), '&&');
}
toLegacy() : AndBooleanExpression {
return new AndBooleanExpression(null, this.operands.map((op) => op.toLegacy()));
}
equals(other : BooleanExpression) : boolean {
return other instanceof AndBooleanExpression &&
arrayEquals(this.operands, other.operands);
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitAndBooleanExpression(this)) {
for (const operand of this.operands)
operand.visit(visitor);
}
visitor.exit(this);
}
clone() : AndBooleanExpression {
return new AndBooleanExpression(
this.location,
this.operands.map((operand) => operand.clone())
);
}
*iterateSlots(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<OldSlot, void> {
for (const op of this.operands)
yield* op.iterateSlots(schema, prim, scope);
}
*iterateSlots2(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, void> {
for (const op of this.operands)
yield* op.iterateSlots2(schema, prim, scope);
}
}
BooleanExpression.And = AndBooleanExpression;
BooleanExpression.And.prototype.isAnd = true;
/**
* A disjunction boolean expression (ThingTalk operator `||`)
*/
export class OrBooleanExpression extends BooleanExpression {
/**
* The expression operands.
*/
operands : BooleanExpression[];
/**
* Construct a new Or expression.
*
* @param {Ast~SourceRange|null} location - the position of this node
* in the source code
* @param {Ast.BooleanExpression[]} operands - the expression operands
*/
constructor(location : SourceRange|null, operands : BooleanExpression[]) {
super(location);
assert(Array.isArray(operands));
this.operands = operands;
}
get priority() : SyntaxPriority {
return SyntaxPriority.Or;
}
toSource() : TokenStream {
return List.join(this.operands.map((op) => addParenthesis(this.priority, op.priority, op.toSource())), '||');
}
toLegacy() : OrBooleanExpression {
return new OrBooleanExpression(null, this.operands.map((op) => op.toLegacy()));
}
equals(other : BooleanExpression) : boolean {
return other instanceof OrBooleanExpression &&
arrayEquals(this.operands, other.operands);
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitOrBooleanExpression(this)) {
for (const operand of this.operands)
operand.visit(visitor);
}
visitor.exit(this);
}
clone() : OrBooleanExpression {
return new OrBooleanExpression(
this.location,
this.operands.map((operand) => operand.clone())
);
}
*iterateSlots(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<OldSlot, void> {
for (const op of this.operands)
yield* op.iterateSlots(schema, prim, scope);
}
*iterateSlots2(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, void> {
for (const op of this.operands)
yield* op.iterateSlots2(schema, prim, scope);
}
}
BooleanExpression.Or = OrBooleanExpression;
BooleanExpression.Or.prototype.isOr = true;
const INFIX_COMPARISON_OPERATORS = new Set(['==', '>=', '<=', '>', '<', '=~', '~=']);
/**
* A comparison expression (predicate atom)
*/
export class AtomBooleanExpression extends BooleanExpression {
/**
* The parameter name to compare.
*/
name : string;
/**
* The comparison operator.
*/
operator : string;
/**
* The value being compared against.
*/
value : Value;
overload : Type[]|null;
/**
* Construct a new atom boolean expression.
*
* @param location - the position of this node in the source code
* @param name - the parameter name to compare
* @param operator - the comparison operator
* @param value - the value being compared against
*/
constructor(location : SourceRange|null,
name : string,
operator : string,
value : Value,
overload : Type[]|null) {
super(location);
assert(typeof name === 'string');
this.name = name;
assert(typeof operator === 'string');
this.operator = operator;
assert(value instanceof Value);
this.value = value;
this.overload = overload;
}
get priority() : SyntaxPriority {
return INFIX_COMPARISON_OPERATORS.has(this.operator) ? SyntaxPriority.Comp : SyntaxPriority.Primary;
}
toSource() : TokenStream {
const name = List.join(this.name.split('.').map((n) => List.singleton(n)), '.');
if (INFIX_COMPARISON_OPERATORS.has(this.operator)) {
return List.concat(name, this.operator,
addParenthesis(SyntaxPriority.Add, this.value.priority, this.value.toSource()));
} else {
return List.concat(this.operator, '(', name, ',', this.value.toSource(), ')');
}
}
toLegacy() : AtomBooleanExpression {
return this;
}
equals(other : BooleanExpression) : boolean {
return other instanceof AtomBooleanExpression &&
this.name === other.name &&
this.operator === other.operator &&
this.value.equals(other.value);
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitAtomBooleanExpression(this))
this.value.visit(visitor);
visitor.exit(this);
}
clone() : AtomBooleanExpression {
return new AtomBooleanExpression(
this.location,
this.name,
this.operator,
this.value.clone(),
this.overload
);
}
toString() : string {
return `Atom(${this.name}, ${this.operator}, ${this.value})`;
}
*iterateSlots(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<OldSlot, void> {
yield [schema, this, prim, scope];
}
*iterateSlots2(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, void> {
const arg = (schema ? schema.getArgument(this.name) : null) || null;
yield* recursiveYieldArraySlots(new FilterSlot(prim, scope, arg, this));
}
}
BooleanExpression.Atom = AtomBooleanExpression;
BooleanExpression.Atom.prototype.isAtom = true;
/**
* A negation boolean expression (ThingTalk operator `!`)
*/
export class NotBooleanExpression extends BooleanExpression {
/**
* The expression being negated.
*/
expr : BooleanExpression;
/**
* Construct a new Not expression.
*
* @param location - the position of this node in the source code
* @param expr - the expression being negated
*/
constructor(location : SourceRange|null, expr : BooleanExpression) {
super(location);
assert(expr instanceof BooleanExpression);
this.expr = expr;
}
get priority() : SyntaxPriority {
return SyntaxPriority.Not;
}
toSource() : TokenStream {
return List.concat('!', addParenthesis(this.priority, this.expr.priority, this.expr.toSource()));
}
toLegacy() : NotBooleanExpression {
return new NotBooleanExpression(null, this.expr.toLegacy());
}
equals(other : BooleanExpression) : boolean {
return other instanceof NotBooleanExpression &&
this.expr.equals(other.expr);
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitNotBooleanExpression(this))
this.expr.visit(visitor);
visitor.exit(this);
}
clone() : NotBooleanExpression {
return new NotBooleanExpression(this.location, this.expr.clone());
}
*iterateSlots(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<OldSlot, void> {
yield* this.expr.iterateSlots(schema, prim, scope);
}
*iterateSlots2(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, void> {
yield* this.expr.iterateSlots2(schema, prim, scope);
}
}
BooleanExpression.Not = NotBooleanExpression;
BooleanExpression.Not.prototype.isNot = true;
/**
* A boolean expression that calls a Thingpedia query function
* and filters the result.
*
* The boolean expression is true if at least one result from the function
* call satisfies the filter.
*
* @deprecated Use {@link ComparisonSubqueryBooleanExpression} or {@link ExistentialSubqueryBooleanExpression} instead.
*/
export class ExternalBooleanExpression extends BooleanExpression {
/**
* The selector choosing where the function is invoked.
*/
selector : DeviceSelector;
/**
* The function name being invoked.
*/
channel : string;
/**
* The input parameters passed to the function.
*/
in_params : InputParam[];
/**
* The predicate to apply on the invocation's results.
*/
filter : BooleanExpression;
/**
* Type signature of the invoked function.
* This property is guaranteed not `null` after type-checking.
*/
schema : FunctionDef|null;
__effectiveSelector : DeviceSelector|null = null;
/**
* Construct a new external boolean expression.
*
* @param {Ast.Selector.Device} selector - the selector choosing where the function is invoked
* @param {string} channel - the function name
* @param {Ast.InputParam[]} in_params - input parameters passed to the function
* @param {Ast.BooleanExpression} filter - the filter to apply on the invocation's results
* @param {Ast.FunctionDef|null} schema - type signature of the invoked function
*/
constructor(location : SourceRange|null,
selector : DeviceSelector,
channel : string,
in_params : InputParam[],
filter : BooleanExpression,
schema : FunctionDef|null) {
super(location);
assert(selector instanceof DeviceSelector);
this.selector = selector;
assert(typeof channel === 'string');
this.channel = channel;
assert(Array.isArray(in_params));
this.in_params = in_params;
assert(filter instanceof BooleanExpression);
this.filter = filter;
assert(schema === null || schema instanceof FunctionDef);
this.schema = schema;
}
get priority() : SyntaxPriority {
return SyntaxPriority.Primary;
}
toSource() : TokenStream {
const inv = new Invocation(null, this.selector, this.channel, this.in_params, this.schema);
return List.concat('any', '(', inv.toSource(), 'filter', this.filter.toSource(), ')');
}
toString() : string {
return `External(${this.selector}, ${this.channel}, ${this.in_params}, ${this.filter})`;
}
toLegacy() : ExternalBooleanExpression {
return this;
}
equals(other : BooleanExpression) : boolean {
return other instanceof ExternalBooleanExpression &&
this.selector.equals(other.selector) &&
this.channel === other.channel &&
arrayEquals(this.in_params, other.in_params) &&
this.filter.equals(other.filter);
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitExternalBooleanExpression(this)) {
this.selector.visit(visitor);
for (const in_param of this.in_params)
in_param.visit(visitor);
this.filter.visit(visitor);
}
visitor.exit(this);
}
clone() : ExternalBooleanExpression {
return new ExternalBooleanExpression(
this.location,
this.selector.clone(),
this.channel,
this.in_params.map((p) => p.clone()),
this.filter.clone(),
this.schema ? this.schema.clone(): null
);
}
*iterateSlots(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<OldSlot, void> {
yield* Invocation.prototype.iterateSlots.call(this, scope);
yield* this.filter.iterateSlots(this.schema, prim, makeScope(this));
}
*iterateSlots2(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, void> {
yield this.selector;
yield* iterateSlots2InputParams(this, scope);
yield* this.filter.iterateSlots2(this.schema, this, makeScope(this));
}
}
BooleanExpression.External = ExternalBooleanExpression;
BooleanExpression.External.prototype.isExternal = true;
/**
* A boolean expression that calls a Thingpedia query function
* and filters the result.
*
* The boolean expression is true if at least one result from the function
* call satisfies the filter.
*
*/
export class ExistentialSubqueryBooleanExpression extends BooleanExpression {
subquery : Expression;
/**
* Construct a new existential subquery boolean expression.
*
* @param location
* @param subquery: the query used for check existence of result
*/
constructor(location : SourceRange|null,
subquery : Expression) {
super(location);
this.subquery = subquery;
}
get priority() : SyntaxPriority {
return SyntaxPriority.Primary;
}
toSource() : TokenStream {
return List.concat('any', '(', this.subquery.toSource(), ')');
}
toString() : string {
return `ExistentialSubquery(${this.subquery})`;
}
toLegacy() : ExternalBooleanExpression {
if (this.subquery instanceof FilterExpression && this.subquery.expression instanceof InvocationExpression) {
const invocation = this.subquery.expression.invocation;
return new ExternalBooleanExpression(
null,
invocation.selector,
invocation.channel,
invocation.in_params,
this.subquery.filter.toLegacy(),
this.subquery.schema
);
}
throw new UnserializableError('Existential Subquery');
}
equals(other : BooleanExpression) : boolean {
return other instanceof ExistentialSubqueryBooleanExpression &&
this.subquery.equals(other.subquery);
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitExistentialSubqueryBooleanExpression(this))
this.subquery.visit(visitor);
visitor.exit(this);
}
clone() : ExistentialSubqueryBooleanExpression {
return new ExistentialSubqueryBooleanExpression(
this.location,
this.subquery.clone()
);
}
*iterateSlots(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<OldSlot, void> {
yield* this.subquery.iterateSlots(scope);
}
*iterateSlots2(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, void> {
yield* this.subquery.iterateSlots2(scope);
}
}
BooleanExpression.ExistentialSubquery = ExistentialSubqueryBooleanExpression;
BooleanExpression.ExistentialSubquery.prototype.isExistentialSubquery = true;
/**
* A boolean expression that calls a Thingpedia query function
* and compares the result with another value.
*
*/
export class ComparisonSubqueryBooleanExpression extends BooleanExpression {
lhs : Value;
rhs : Expression;
operator : string;
overload : Type[]|null;
/**
* Construct a new comparison subquery boolean expression.
*
* @param location
* @param lhs - the parameter name to compare
* @param operator - the comparison operator
* @param rhs - a projection subquery which returns one field
* @param overload - type overload
*/
constructor(location : SourceRange|null,
lhs : Value,
operator : string,
rhs : Expression,
overload : Type[]|null) {
super(location);
this.lhs =lhs;
this.rhs = rhs;
this.operator = operator;
this.overload = overload;
}
get priority() : SyntaxPriority {
return INFIX_COMPARISON_OPERATORS.has(this.operator) ? SyntaxPriority.Comp : SyntaxPriority.Primary;
}
toSource() : TokenStream {
if (INFIX_COMPARISON_OPERATORS.has(this.operator))
return List.concat(addParenthesis(SyntaxPriority.Add, this.lhs.priority, this.lhs.toSource()), this.operator, 'any', '(', this.rhs.toSource(), ')');
else
return List.concat(this.operator, '(', this.lhs.toSource(), ',', 'any', '(', this.rhs.toSource(), ')', ')');
}
toString() : string {
return `ComparisonSubquery(${this.lhs}, ${this.operator}, ${this.rhs})`;
}
toLegacy() : ExternalBooleanExpression {
if (this.rhs instanceof ProjectionExpression && this.rhs.args.length + this.rhs.computations.length === 1) {
const expr = this.rhs.expression;
if (expr instanceof FilterExpression && expr.expression instanceof InvocationExpression) {
const invocation = expr.expression.invocation;
const extraFilter = new ComputeBooleanExpression(
null,
this.lhs,
this.operator,
this.rhs.args.length ? new Value.VarRef(this.rhs.args[0]) : this.rhs.computations[0]
);
const filter = new AndBooleanExpression(null, [expr.filter.toLegacy(), extraFilter]);
return new ExternalBooleanExpression(
null,
invocation.selector,
invocation.channel,
invocation.in_params,
filter,
invocation.schema
);
}
}
throw new UnserializableError('Comparison Subquery');
}
equals(other : BooleanExpression) : boolean {
return other instanceof ComparisonSubqueryBooleanExpression &&
this.lhs.equals(other.lhs) &&
this.operator === other.operator &&
this.rhs.equals(other.rhs);
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitComparisonSubqueryBooleanExpression(this)) {
this.lhs.visit(visitor);
this.rhs.visit(visitor);
}
visitor.exit(this);
}
clone() : ComparisonSubqueryBooleanExpression {
return new ComparisonSubqueryBooleanExpression(
this.location,
this.lhs.clone(),
this.operator,
this.rhs.clone(),
this.overload
);
}
*iterateSlots(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<OldSlot, void> {
// XXX this API cannot support comparison subquery expressions
}
*iterateSlots2(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, void> {
const [resolvedLhs, ] = this.overload || [null, null];
yield* recursiveYieldArraySlots(new FieldSlot(prim, scope, resolvedLhs || this.lhs.getType(), this, 'comparison_subquery_filter', 'lhs'));
yield* this.rhs.iterateSlots2(scope);
}
}
BooleanExpression.ComparisonSubquery = ComparisonSubqueryBooleanExpression;
BooleanExpression.ComparisonSubquery.prototype.isComparisonSubquery = true;
/**
* A boolean expression that expresses that the user does not care about a specific parameter.
*
* It is essentially the same as "true", but it has a parameter attached to it.
*/
export class DontCareBooleanExpression extends BooleanExpression {
name : string;
constructor(location : SourceRange|null, name : string) {
super(location);
assert(typeof name === 'string');
this.name = name;
}
get priority() : SyntaxPriority {
return SyntaxPriority.Primary;
}
toSource() : TokenStream {
return List.concat('true', '(', this.name, ')');
}
toLegacy() : DontCareBooleanExpression {
return this;
}
equals(other : BooleanExpression) : boolean {
return other instanceof DontCareBooleanExpression && this.name === other.name;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
visitor.visitDontCareBooleanExpression(this);
visitor.exit(this);
}
clone() : DontCareBooleanExpression {
return new DontCareBooleanExpression(this.location, this.name);
}
*iterateSlots(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<OldSlot, void> {
}
*iterateSlots2(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, void> {
}
}
BooleanExpression.DontCare = DontCareBooleanExpression;
DontCareBooleanExpression.prototype.isDontCare = true;
export class TrueBooleanExpression extends BooleanExpression {
constructor() {
super(null);
}
get priority() : SyntaxPriority {
return SyntaxPriority.Primary;
}
toSource() : TokenStream {
return List.singleton('true');
}
toLegacy() : TrueBooleanExpression {
return this;
}
equals(other : BooleanExpression) : boolean {
return this === other;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
visitor.visitTrueBooleanExpression(this);
visitor.exit(this);
}
clone() : TrueBooleanExpression {
return this;
}
*iterateSlots(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<OldSlot, void> {
}
*iterateSlots2(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, void> {
}
}
TrueBooleanExpression.prototype.isTrue = true;
BooleanExpression.True = new TrueBooleanExpression();
export class FalseBooleanExpression extends BooleanExpression {
constructor() {
super(null);
}
get priority() : SyntaxPriority {
return SyntaxPriority.Primary;
}
toSource() : TokenStream {
return List.singleton('false');
}
toLegacy() : FalseBooleanExpression {
return this;
}
equals(other : BooleanExpression) : boolean {
return this === other;
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
visitor.visitFalseBooleanExpression(this);
visitor.exit(this);
}
clone() : FalseBooleanExpression {
return this;
}
*iterateSlots(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<OldSlot, void> {
}
*iterateSlots2(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, void> {
}
}
FalseBooleanExpression.prototype.isFalse = true;
BooleanExpression.False = new FalseBooleanExpression();
/**
* A boolean expression that computes a scalar expression and then does a comparison
*
*/
export class ComputeBooleanExpression extends BooleanExpression {
/**
* The scalar expression being compared.
*/
lhs : Value;
/**
* The comparison operator.
*/
operator : string;
/**
* The value being compared against.
*/
rhs : Value;
overload : Type[]|null;
/**
* Construct a new compute boolean expression.
*
* @param {Ast~SourceRange|null} location - the position of this node
* in the source code
* @param {Ast.ScalarExpression} lhs - the scalar expression to compute
* @param {string} operator - the comparison operator
* @param {Ast.Value} value - the value being compared against
*/
constructor(location : SourceRange|null,
lhs : Value,
operator : string,
rhs : Value,
overload : Type[]|null = null) {
super(location);
assert(lhs instanceof Value);
this.lhs = lhs;
assert(typeof operator === 'string');
this.operator = operator;
assert(rhs instanceof Value);
this.rhs = rhs;
this.overload = overload;
}
get priority() : SyntaxPriority {
return INFIX_COMPARISON_OPERATORS.has(this.operator) ? SyntaxPriority.Comp : SyntaxPriority.Primary;
}
toSource() : TokenStream {
if (INFIX_COMPARISON_OPERATORS.has(this.operator)) {
return List.concat(
// force parenthesis around constants on the LHS of the filter, because it will be ambiguous otherwise
this.lhs.isConstant() ?
List.concat('(', this.lhs.toSource(), ')') :
addParenthesis(SyntaxPriority.Add, this.lhs.priority, this.lhs.toSource()),
this.operator,
addParenthesis(SyntaxPriority.Add, this.rhs.priority, this.rhs.toSource()));
} else {
return List.concat(this.operator, '(', this.lhs.toSource(), ',', this.rhs.toSource(), ')');
}
}
toLegacy() : ComputeBooleanExpression {
return this;
}
equals(other : BooleanExpression) : boolean {
return other instanceof ComputeBooleanExpression &&
this.lhs.equals(other.lhs) &&
this.operator === other.operator &&
this.rhs.equals(other.rhs);
}
visit(visitor : NodeVisitor) : void {
visitor.enter(this);
if (visitor.visitComputeBooleanExpression(this)) {
this.lhs.visit(visitor);
this.rhs.visit(visitor);
}
visitor.exit(this);
}
clone() : ComputeBooleanExpression {
return new ComputeBooleanExpression(
this.location,
this.lhs.clone(),
this.operator,
this.rhs.clone(),
this.overload
);
}
*iterateSlots(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<OldSlot, void> {
// XXX this API cannot support Compute expressions
}
*iterateSlots2(schema : FunctionDef|null,
prim : InvocationLike|null,
scope : ScopeMap) : Generator<DeviceSelector|AbstractSlot, void> {
const [resolvedLhs, resolvedRhs] = this.overload || [null, null];
yield* recursiveYieldArraySlots(new FieldSlot(prim, scope, resolvedLhs || this.lhs.getType(), this, 'compute_filter', 'lhs'));
yield* recursiveYieldArraySlots(new FieldSlot(prim, scope, resolvedRhs || this.rhs.getType(), this, 'compute_filter', 'rhs'));
}
toString() : string {
return `Compute(${this.lhs}, ${this.operator}, ${this.rhs})`;
}
}
BooleanExpression.Compute = ComputeBooleanExpression;
BooleanExpression.Compute.prototype.isCompute = true; | the_stack |
import React from 'react';
import cx from 'classnames';
import { IconButton } from '../Buttons';
import { Input } from '../Input';
import { ColorValue, CommonProps, InputContainer, useTheme } from '../utils';
import { useColorPickerContext } from './ColorPickerContext';
import SvgSwap from '@itwin/itwinui-icons-react/cjs/icons/Swap';
import '@itwin/itwinui-css/css/color-picker.css';
export type ColorInputPanelProps = {
/**
* The default color format to be inputted in the panel.
*/
defaultColorFormat: 'hsl' | 'rgb' | 'hex';
/**
* Color formats to switch between. The swap button will cycle between these formats.
*
* If array only has one option, then swap button will not be shown.
*
* @default ['hsl', 'rgb', 'hex']
*/
allowedColorFormats?: ('hsl' | 'rgb' | 'hex')[];
} & Omit<CommonProps, 'title'>;
/**
* `ColorInputPanel` shows input fields to enter precise color values in the specified format.
* It also allows switching between the specified formats using a swap button.
* @example
* <ColorPicker>
* // ...
* <ColorInputPanel defaultColorFormat='hsl' />
* </ColorPicker>
*/
export const ColorInputPanel = React.forwardRef(
(props: ColorInputPanelProps, ref: React.Ref<HTMLDivElement>) => {
const {
defaultColorFormat,
allowedColorFormats = ['hsl', 'rgb', 'hex'],
className,
...rest
} = props;
useTheme();
const inputsContainerRef = React.useRef<HTMLDivElement>(null);
const {
activeColor,
applyHsvColorChange,
hsvColor,
showAlpha,
} = useColorPickerContext();
const [currentFormat, setCurrentFormat] = React.useState(
defaultColorFormat,
);
React.useEffect(() => {
setCurrentFormat(defaultColorFormat);
}, [defaultColorFormat]);
// need to use state since input may have parsing error
const [input, setInput] = React.useState<Array<string>>(['', '', '', '']);
React.useEffect(() => {
if (currentFormat === 'hsl') {
const hsl = activeColor.toHslColor();
setInput([
ColorValue.getFormattedColorNumber(hsvColor.h), // use hsvColor to preserve hue for 0,0,0 edge case
ColorValue.getFormattedColorNumber(hsl.s),
ColorValue.getFormattedColorNumber(hsl.l),
ColorValue.getFormattedColorNumber(
hsl.a ?? activeColor.getAlpha() / 255,
2,
),
]);
} else if (currentFormat === 'rgb') {
const rgb = activeColor.toRgbColor();
setInput([
rgb.r.toString(),
rgb.g.toString(),
rgb.b.toString(),
ColorValue.getFormattedColorNumber(
rgb.a ?? activeColor.getAlpha() / 255,
2,
),
]);
} else {
setInput([activeColor.toHexString(showAlpha)]);
setValidHexInput(true);
}
}, [activeColor, hsvColor.h, currentFormat, showAlpha]);
const [validHexInput, setValidHexInput] = React.useState(true);
const swapColorFormat = React.useCallback(() => {
const newFormat =
allowedColorFormats[
(allowedColorFormats.indexOf(currentFormat) + 1) %
allowedColorFormats.length
] ?? allowedColorFormats[0];
setCurrentFormat(newFormat);
}, [currentFormat, allowedColorFormats]);
const isFocusInside = (focused?: EventTarget | null) =>
!!(
focused &&
inputsContainerRef.current &&
inputsContainerRef.current.contains(focused as HTMLElement)
);
const handleColorInputChange = () => {
let color;
if (currentFormat === 'hex') {
try {
const value = input[0].replace(/ /g, '').toLowerCase(); // remove white space from input
color = ColorValue.create(value);
setValidHexInput(true);
if (activeColor.toHexString(showAlpha).toLowerCase() === value) {
return;
}
} catch (_e) {
setValidHexInput(false);
return;
}
}
if (currentFormat === 'hsl') {
const [h, s, l, a] = input.map(Number);
if (
h < 0 ||
h > 360 ||
s < 0 ||
s > 100 ||
l < 0 ||
l > 100 ||
a < 0 ||
a > 1
) {
return;
}
const hsl = activeColor.toHslColor();
if (hsl.h === h && hsl.s === s && hsl.l === l && hsl.a === a) {
return;
}
color = ColorValue.create({ h, s, l, a });
}
if (currentFormat === 'rgb') {
const [r, g, b, a] = input.map(Number);
if (
r < 0 ||
r > 255 ||
g < 0 ||
g > 255 ||
b < 0 ||
b > 255 ||
a < 0 ||
a > 1
) {
return;
}
const rgb = activeColor.toRgbColor();
if (rgb.r === r && rgb.g === g && rgb.b === b && rgb.a === a) {
return;
}
color = ColorValue.create({ r, g, b, a });
}
if (color) {
applyHsvColorChange(color.toHsvColor(), true, color);
}
};
const hexInputField = (
<InputContainer status={validHexInput ? undefined : 'negative'}>
<Input
size='small'
maxLength={showAlpha ? 9 : 7}
minLength={1}
placeholder='HEX'
value={input[0]}
onChange={(event) => {
const value = event.target.value.startsWith('#')
? event.target.value
: `#${event.target.value}`;
setInput([value]);
}}
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
handleColorInputChange();
}
}}
onBlur={(event) => {
event.preventDefault();
handleColorInputChange();
}}
/>
</InputContainer>
);
const hslInputs = (
<>
<InputContainer
status={
Number(input[0]) < 0 || Number(input[0]) > 360
? 'negative'
: undefined
}
>
<Input
size='small'
type='number'
min='0'
max='359'
step='.1'
placeholder='H'
value={input[0] ?? ''}
onChange={(event) => {
setInput([event.target.value, input[1], input[2], input[3]]);
}}
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
handleColorInputChange();
}
}}
onBlur={(event) => {
event.preventDefault();
if (!isFocusInside(event.relatedTarget)) {
handleColorInputChange();
}
}}
/>
</InputContainer>
<InputContainer
status={
Number(input[1]) < 0 || Number(input[1]) > 100
? 'negative'
: undefined
}
>
<Input
size='small'
type='number'
min='0'
max='100'
step='.1'
placeholder='S'
value={input[1] ?? ''}
onChange={(event) => {
setInput([input[0], event.target.value, input[2], input[3]]);
}}
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
handleColorInputChange();
}
}}
onBlur={(event) => {
event.preventDefault();
if (!isFocusInside(event.relatedTarget)) {
handleColorInputChange();
}
}}
/>
</InputContainer>
<InputContainer
status={
Number(input[2]) < 0 || Number(input[2]) > 100
? 'negative'
: undefined
}
>
<Input
size='small'
type='number'
min='0'
max='100'
step='.1'
placeholder='L'
value={input[2] ?? ''}
onChange={(event) => {
setInput([input[0], input[1], event.target.value, input[3]]);
}}
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
handleColorInputChange();
}
}}
onBlur={(event) => {
event.preventDefault();
if (!isFocusInside(event.relatedTarget)) {
handleColorInputChange();
}
}}
/>
</InputContainer>
{showAlpha && (
<InputContainer
status={
Number(input[3]) < 0 || Number(input[3]) > 1
? 'negative'
: undefined
}
>
<Input
size='small'
type='number'
min='0'
max='1'
step='.01'
placeholder='A'
value={input[3] ?? ''}
onChange={(event) => {
setInput([input[0], input[1], input[2], event.target.value]);
}}
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
handleColorInputChange();
}
}}
onBlur={(event) => {
event.preventDefault();
if (!isFocusInside(event.relatedTarget)) {
handleColorInputChange();
}
}}
/>
</InputContainer>
)}
</>
);
const rgbInputs = (
<>
<InputContainer
status={
Number(input[0]) < 0 || Number(input[0]) > 255
? 'negative'
: undefined
}
>
<Input
size='small'
type='number'
min='0'
max='255'
placeholder='R'
value={input[0] ?? ''}
onChange={(event) => {
setInput([event.target.value, input[1], input[2], input[3]]);
}}
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
handleColorInputChange();
}
}}
onBlur={(event) => {
event.preventDefault();
if (!isFocusInside(event.relatedTarget)) {
handleColorInputChange();
}
}}
/>
</InputContainer>
<InputContainer
status={
Number(input[1]) < 0 || Number(input[1]) > 255
? 'negative'
: undefined
}
>
<Input
size='small'
type='number'
min='0'
max='255'
placeholder='G'
value={input[1] ?? ''}
onChange={(event) => {
setInput([input[0], event.target.value, input[2], input[3]]);
}}
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
handleColorInputChange();
}
}}
onBlur={(event) => {
event.preventDefault();
if (!isFocusInside(event.relatedTarget)) {
handleColorInputChange();
}
}}
/>
</InputContainer>
<InputContainer
status={
Number(input[2]) < 0 || Number(input[2]) > 255
? 'negative'
: undefined
}
>
<Input
size='small'
type='number'
min='0'
max='255'
placeholder={'B'}
value={input[2] ?? ''}
onChange={(event) => {
setInput([input[0], input[1], event.target.value, input[3]]);
}}
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
handleColorInputChange();
}
}}
onBlur={(event) => {
event.preventDefault();
if (!isFocusInside(event.relatedTarget)) {
handleColorInputChange();
}
}}
/>
</InputContainer>
{showAlpha && (
<InputContainer
status={
Number(input[3]) < 0 || Number(input[3]) > 1
? 'negative'
: undefined
}
>
<Input
size='small'
type='number'
min='0'
max='1'
step='.01'
placeholder='A'
value={input[3] ?? ''}
onChange={(event) => {
setInput([input[0], input[1], input[2], event.target.value]);
}}
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
handleColorInputChange();
}
}}
onBlur={(event) => {
event.preventDefault();
if (!isFocusInside(event.relatedTarget)) {
handleColorInputChange();
}
}}
/>
</InputContainer>
)}
</>
);
return (
<div
className={cx('iui-color-input-wrapper', className)}
ref={ref}
{...rest}
>
<div className='iui-color-picker-section-label'>
{showAlpha && currentFormat != 'hex'
? currentFormat.toUpperCase() + 'A'
: currentFormat.toUpperCase()}
</div>
<div className='iui-color-input'>
{allowedColorFormats.length > 1 && (
<IconButton
styleType='borderless'
onClick={swapColorFormat}
size='small'
>
<SvgSwap />
</IconButton>
)}
<div ref={inputsContainerRef} className='iui-color-input-fields'>
{currentFormat === 'hex' && hexInputField}
{currentFormat === 'rgb' && rgbInputs}
{currentFormat === 'hsl' && hslInputs}
</div>
</div>
</div>
);
},
);
export default ColorInputPanel; | the_stack |
import {IPwmService} from './pwm.service';
import {ILogService, IPromise, IQService, IWindowService} from 'angular';
import LocalStorageService from './local-storage.service';
import ObjectService from './object.service';
import SearchResult from '../models/search-result.model';
import {IQuery} from './people.service';
const VERIFICATION_PROCESS_ACTIONS = {
ATTRIBUTES: 'validateAttributes',
TOKEN: 'verifyVerificationToken',
OTP: 'validateOtpCode'
};
const DEFAULT_SHOW_STRENGTH_METER = false;
export interface IHelpDeskService {
checkVerification(userKey: string): IPromise<IVerificationStatus>;
clearOtpSecret(userKey: string): IPromise<ISuccessResponse>;
clearResponses(userKey: string): IPromise<ISuccessResponse>;
customAction(actionName: string, userKey: string): IPromise<ISuccessResponse>;
deleteUser(userKey: string): IPromise<ISuccessResponse>;
getPerson(userKey: string): IPromise<any>;
getPersonCard(userKey: string): IPromise<any>;
getRandomPassword(userKey: string): IPromise<IRandomPasswordResponse>;
getRecentVerifications(): IPromise<IRecentVerifications>;
search(query: string): IPromise<SearchResult>;
advancedSearch(queries: IQuery[]): IPromise<SearchResult>;
sendVerificationToken(userKey: string, choice: string): IPromise<IVerificationTokenResponse>;
setPassword(userKey: string, random: boolean, password?: string): IPromise<ISuccessResponse>;
unlockIntruder(userKey: string): IPromise<ISuccessResponse>;
validateVerificationData(userKey: string, formData: any, method: any): IPromise<IVerificationStatus>;
showStrengthMeter: boolean;
}
export type IRecentVerifications = IRecentVerification[];
type IRecentVerification = {
profile: string,
username: string,
timestamp: string,
method: string
};
export interface IRandomPasswordResponse {
password: string;
}
export interface ISuccessResponse {
successMessage: string;
}
interface IValidationStatus extends IVerificationStatus {
verificationState: string;
}
export interface IVerificationOptions {
verificationMethods: {
optional: string[];
required: string[];
},
verificationForm: [{
name: string;
label: string;
}],
tokenDestinations: [{
id: string;
display: string;
type: string;
}]
}
export interface IVerificationStatus {
passed: boolean;
verificationOptions: IVerificationOptions;
}
export interface IVerificationTokenResponse {
destination: string;
}
export default class HelpDeskService implements IHelpDeskService {
PWM_GLOBAL: any;
static $inject = [ '$log', '$q', 'LocalStorageService', 'ObjectService', 'PwmService', '$window' ];
constructor(private $log: ILogService,
private $q: IQService,
private localStorageService: LocalStorageService,
private objectService: ObjectService,
private pwmService: IPwmService,
$window: IWindowService) {
if ($window['PWM_GLOBAL']) {
this.PWM_GLOBAL = $window['PWM_GLOBAL'];
}
else {
this.$log.warn('PWM_GLOBAL is not defined on window');
}
}
checkVerification(userKey: string): IPromise<IVerificationStatus> {
let url: string = this.pwmService.getServerUrl('checkVerification');
let data = {
userKey: userKey,
verificationState: undefined
};
const verificationState = this.localStorageService.getItem(this.localStorageService.keys.VERIFICATION_STATE);
if (verificationState != null) {
data.verificationState = verificationState;
}
return this.pwmService
.httpRequest(url, { data: data })
.then((result: any) => {
return result.data;
});
}
clearOtpSecret(userKey: string): IPromise<ISuccessResponse> {
let url: string = this.pwmService.getServerUrl('clearOtpSecret');
let data: any = { userKey: userKey };
return this.pwmService
.httpRequest(url, { data: data })
.then((result: ISuccessResponse) => {
return result;
});
}
clearResponses(userKey: string): IPromise<ISuccessResponse> {
let url: string = this.pwmService.getServerUrl('clearResponses');
url += `&userKey=${userKey}`;
return this.pwmService
.httpRequest(url, {})
.then((result: ISuccessResponse) => {
return result;
});
}
customAction(actionName: string, userKey: string): IPromise<ISuccessResponse> {
let url: string = this.pwmService.getServerUrl('executeAction');
url += `&name=${actionName}`;
let data: any = { userKey: userKey };
return this.pwmService
.httpRequest(url, { data: data })
.then((result: ISuccessResponse) => {
return result;
});
}
deleteUser(userKey: string): IPromise<ISuccessResponse> {
let url: string = this.pwmService.getServerUrl('deleteUser');
url += `&userKey=${userKey}`;
return this.pwmService
.httpRequest(url, {})
.then((result: ISuccessResponse) => {
return result;
});
}
getPerson(userKey: string): IPromise<any> {
let url: string = this.pwmService.getServerUrl('detail');
url += `&userKey=${userKey}`;
const verificationState = this.localStorageService.getItem(this.localStorageService.keys.VERIFICATION_STATE);
if (verificationState != null) {
url += `&verificationState=${verificationState}`;
}
return this.pwmService
.httpRequest(url, {})
.then((result: any) => {
return result.data;
});
}
getPersonCard(userKey: string): IPromise<any> {
let url = this.pwmService.getServerUrl('card');
url += `&userKey=${userKey}`;
return this.pwmService
.httpRequest(url, {})
.then((result: any) => {
return result.data;
});
}
getRandomPassword(userKey: string): IPromise<IRandomPasswordResponse> {
let url: string = this.pwmService.getServerUrl('randomPassword');
let data = {
username: userKey,
strength: 0
};
return this.pwmService
.httpRequest(url, { data: data })
.then((result: { data: IRandomPasswordResponse }) => {
return result.data;
});
}
getRecentVerifications(): IPromise<IRecentVerifications> {
let url: string = this.pwmService.getServerUrl('showVerifications');
const data = {
verificationState: undefined
};
const verificationState = this.localStorageService.getItem(this.localStorageService.keys.VERIFICATION_STATE);
if (verificationState != null) {
data.verificationState = verificationState;
}
return this.pwmService
.httpRequest(url, { data: data })
.then((result: any) => {
return result.data.records;
});
}
search(query: string): IPromise<SearchResult> {
let formID: string = encodeURIComponent('&pwmFormID=' + this.PWM_GLOBAL['pwmFormID']);
let url: string = this.pwmService.getServerUrl('search')
+ '&pwmFormID=' + this.PWM_GLOBAL['pwmFormID'];
let data = {
mode: 'simple',
username: query,
pwmFormID: formID
};
return this.pwmService
.httpRequest(url, {
data: data,
preventCache: true
})
.then((result: any) => {
let receivedData: any = result.data;
let searchResult: SearchResult = new SearchResult(receivedData);
return searchResult;
});
}
advancedSearch(queries: IQuery[]): IPromise<SearchResult> {
let formID: string = encodeURIComponent('&pwmFormID=' + this.PWM_GLOBAL['pwmFormID']);
let url: string = this.pwmService.getServerUrl('search')
+ '&pwmFormID=' + this.PWM_GLOBAL['pwmFormID'];
let data = {
mode: 'advanced',
pwmFormID: formID,
searchValues: queries
};
return this.pwmService
.httpRequest(url, {
data: data,
preventCache: true
})
.then((result: any) => {
let receivedData: any = result.data;
let searchResult: SearchResult = new SearchResult(receivedData);
return searchResult;
});
}
sendVerificationToken(userKey: string, destinationID: string): IPromise<IVerificationTokenResponse> {
let url: string = this.pwmService.getServerUrl('sendVerificationToken');
let data: any = {
userKey: userKey,
id: destinationID
};
return this.pwmService
.httpRequest(url, { data: data })
.then((result: IVerificationTokenResponse) => {
return result;
});
}
setPassword(userKey: string, random: boolean, password?: string): IPromise<ISuccessResponse> {
let url: string = this.pwmService.getServerUrl('setPassword');
let data: any = { username: userKey };
if (random) {
data.random = true;
}
else {
data.password = password;
}
return this.pwmService
.httpRequest(url, { data: data })
.then((result: ISuccessResponse) => {
return result;
});
}
unlockIntruder(userKey: string): IPromise<ISuccessResponse> {
let url: string = this.pwmService.getServerUrl('unlockIntruder');
url += `&userKey=${userKey}`;
return this.pwmService
.httpRequest(url, {})
.then((result: ISuccessResponse) => {
return result;
});
}
validateVerificationData(userKey: string, data: any, method: string): IPromise<IVerificationStatus> {
let processAction = VERIFICATION_PROCESS_ACTIONS[method];
let url: string = this.pwmService.getServerUrl(processAction);
let content = {
userKey: userKey,
verificationState: undefined
};
const verificationState = this.localStorageService.getItem(this.localStorageService.keys.VERIFICATION_STATE);
if (verificationState != null) {
content.verificationState = verificationState;
}
this.objectService.assign(data, content);
return this.pwmService
.httpRequest(url, { data: data })
.then((result: any) => {
const validationStatus: IValidationStatus = result.data;
this.localStorageService.setItem(
this.localStorageService.keys.VERIFICATION_STATE,
validationStatus.verificationState
);
return validationStatus;
});
}
get showStrengthMeter(): boolean {
if (this.PWM_GLOBAL) {
return this.PWM_GLOBAL['setting-showStrengthMeter'] || DEFAULT_SHOW_STRENGTH_METER;
}
return DEFAULT_SHOW_STRENGTH_METER;
}
} | the_stack |
import { createSetupForContentReview } from "../utils/helpers";
import { useContentGqlHandler } from "../utils/useContentGqlHandler";
describe("Page publishing workflow", () => {
const options = {
path: "manage/en-US"
};
const gqlHandler = useContentGqlHandler({
...options
});
const {
createContentReviewMutation,
getContentReviewQuery,
updatePage,
createPage,
getPageQuery,
provideSignOffMutation,
retractSignOffMutation,
publishContentMutation,
unpublishContentMutation
} = gqlHandler;
/**
* Let's do the setup.
*/
const setup = async () => createSetupForContentReview(gqlHandler);
test(`Should able to "publish" page for content review process`, async () => {
const { page, workflow } = await setup();
/**
* Initial a review.
*/
const [createContentReviewResponse] = await createContentReviewMutation({
data: {
content: {
id: page.id,
type: "page"
}
}
});
const createdContentReview = createContentReviewResponse.data.apw.createContentReview.data;
/*
* Check content status, it should be "under review".
*/
expect(createdContentReview.status).toEqual("underReview");
expect(createdContentReview.title).toEqual(page.title);
/*
* We should be able to make updates to the page.
*/
const [updatePageResponse] = await updatePage({
id: page.id,
data: {
title: "About us"
}
});
const updatedPage = updatePageResponse.data.pageBuilder.updatePage.data;
/**
* Page should have "apw" properties after update.
*/
expect(updatedPage.settings.apw).toEqual({
workflowId: workflow.id,
contentReviewId: createdContentReview.id
});
/**
* Fetch the content review and check if the updates were successful.
*/
let [getContentReviewResponse] = await getContentReviewQuery({
id: createdContentReview.id
});
const contentReview = getContentReviewResponse.data.apw.getContentReview.data;
expect(contentReview.status).toEqual("underReview");
expect(contentReview.title).toEqual(updatedPage.title);
/**
* Should not let us publish a page.
*/
let [publishContentResponse] = await publishContentMutation({ id: contentReview.id });
expect(publishContentResponse).toEqual({
data: {
apw: {
publishContent: {
data: null,
error: {
code: "NOT_READY_TO_BE_PUBLISHED",
message: expect.any(String),
data: expect.any(Object)
}
}
}
}
});
/**
* Should be able to create a new revision, even though the content is "underReview".
*/
const [createPageFromResponse] = await createPage({
from: page.id,
category: page.category.slug
});
expect(createPageFromResponse).toEqual({
data: {
pageBuilder: {
createPage: {
data: expect.any(Object),
error: null
}
}
}
});
const pageRevision2 = createPageFromResponse.data.pageBuilder.createPage.data;
/**
* Should still have the workflow assigned.
* But, should not have "contentReviewId".
*/
expect(pageRevision2.settings.apw).toEqual({
workflowId: page.settings.apw.workflowId,
contentReviewId: null
});
/**
* Let's provide sign-off to every step of the publishing workflow.
*/
const [step1, step2, step3] = contentReview.steps;
let [provideSignOffResponse] = await provideSignOffMutation({
id: contentReview.id,
step: step1.id
});
expect(provideSignOffResponse).toEqual({
data: {
apw: {
provideSignOff: {
data: true,
error: null
}
}
}
});
[provideSignOffResponse] = await provideSignOffMutation({
id: contentReview.id,
step: step2.id
});
expect(provideSignOffResponse).toEqual({
data: {
apw: {
provideSignOff: {
data: true,
error: null
}
}
}
});
[provideSignOffResponse] = await provideSignOffMutation({
id: contentReview.id,
step: step3.id
});
expect(provideSignOffResponse).toEqual({
data: {
apw: {
provideSignOff: {
data: true,
error: null
}
}
}
});
/**
* After providing sign-off to every step of the workflow,
* Now the content should be in "readyToBePublished" stage.
*/
[getContentReviewResponse] = await getContentReviewQuery({
id: createdContentReview.id
});
const updatedContentReview = getContentReviewResponse.data.apw.getContentReview.data;
expect(updatedContentReview.status).toEqual("readyToBePublished");
expect(updatedContentReview.title).toEqual(updatedPage.title);
/**
* Let's retract the provided sign-off for a "required step" of the publishing workflow.
*/
const [retractSignOffResponse] = await retractSignOffMutation({
id: contentReview.id,
step: step2.id
});
expect(retractSignOffResponse).toEqual({
data: {
apw: {
retractSignOff: {
data: true,
error: null
}
}
}
});
/**
* After retracting sign-off to a step of the workflow,
* Now the content should be back in "underReview" stage.
*/
[getContentReviewResponse] = await getContentReviewQuery({
id: createdContentReview.id
});
expect(getContentReviewResponse.data.apw.getContentReview.data.status).toEqual(
"underReview"
);
/**
* Let's again provide the sign-off for step 2.
*/
[provideSignOffResponse] = await provideSignOffMutation({
id: contentReview.id,
step: step2.id
});
expect(provideSignOffResponse).toEqual({
data: {
apw: {
provideSignOff: {
data: true,
error: null
}
}
}
});
/**
* After providing sign-off to every step of the workflow,
* Should be able to publish the page.
*/
[publishContentResponse] = await publishContentMutation({ id: contentReview.id });
expect(publishContentResponse).toEqual({
data: {
apw: {
publishContent: {
data: true,
error: null
}
}
}
});
/**
* Let's confirm that the content is "published".
*/
const [getPageResponse] = await getPageQuery({ id: page.id });
expect(getPageResponse).toEqual({
data: {
pageBuilder: {
getPage: {
data: expect.any(Object),
error: null
}
}
}
});
expect(getPageResponse.data.pageBuilder.getPage.data.status).toEqual("published");
expect(getPageResponse.data.pageBuilder.getPage.data.version).toEqual(1);
/**
* Fetch the content review and check if the status has been updated successful.
*/
[getContentReviewResponse] = await getContentReviewQuery({
id: createdContentReview.id
});
expect(getContentReviewResponse.data.apw.getContentReview.data.status).toEqual("published");
});
test(`Should able to "unpublish" page for content review process`, async () => {
const { page } = await setup();
/**
* Initial a review.
*/
const [createContentReviewResponse] = await createContentReviewMutation({
data: {
content: {
id: page.id,
type: "page"
}
}
});
const createdContentReview = createContentReviewResponse.data.apw.createContentReview.data;
/*
* Check content status, it should be "under review".
*/
expect(createdContentReview.status).toEqual("underReview");
expect(createdContentReview.title).toEqual(page.title);
/*
* We should be able to make updates to the page.
*/
const [updatePageResponse] = await updatePage({
id: page.id,
data: {
title: "About us"
}
});
const updatedPage = updatePageResponse.data.pageBuilder.updatePage.data;
/**
* Fetch the content review and check if the updates were successful.
*/
let [getContentReviewResponse] = await getContentReviewQuery({
id: createdContentReview.id
});
const contentReview = getContentReviewResponse.data.apw.getContentReview.data;
expect(contentReview.status).toEqual("underReview");
expect(contentReview.title).toEqual(updatedPage.title);
/**
* Should not let us publish a page.
*/
let [publishContentResponse] = await publishContentMutation({ id: contentReview.id });
expect(publishContentResponse).toEqual({
data: {
apw: {
publishContent: {
data: null,
error: {
code: "NOT_READY_TO_BE_PUBLISHED",
message: expect.any(String),
data: expect.any(Object)
}
}
}
}
});
/**
* Should be able to create a new revision, even though the content is "underReview".
*/
const [createPageFromResponse] = await createPage({
from: page.id,
category: page.category.slug
});
expect(createPageFromResponse).toEqual({
data: {
pageBuilder: {
createPage: {
data: expect.any(Object),
error: null
}
}
}
});
const pageRevision2 = createPageFromResponse.data.pageBuilder.createPage.data;
/**
* Should still have the workflow assigned.
* But, should not have "contentReviewId".
*/
expect(pageRevision2.settings.apw).toEqual({
workflowId: page.settings.apw.workflowId,
contentReviewId: null
});
/**
* Let's provide sign-off to every step of the publishing workflow.
*/
const [step1, step2, step3] = contentReview.steps;
let [provideSignOffResponse] = await provideSignOffMutation({
id: contentReview.id,
step: step1.id
});
expect(provideSignOffResponse).toEqual({
data: {
apw: {
provideSignOff: {
data: true,
error: null
}
}
}
});
[provideSignOffResponse] = await provideSignOffMutation({
id: contentReview.id,
step: step2.id
});
expect(provideSignOffResponse).toEqual({
data: {
apw: {
provideSignOff: {
data: true,
error: null
}
}
}
});
[provideSignOffResponse] = await provideSignOffMutation({
id: contentReview.id,
step: step3.id
});
expect(provideSignOffResponse).toEqual({
data: {
apw: {
provideSignOff: {
data: true,
error: null
}
}
}
});
/**
* After providing sign-off to every step of the workflow,
* Now the content should be in "readyToBePublished" stage.
*/
[getContentReviewResponse] = await getContentReviewQuery({
id: createdContentReview.id
});
const updatedContentReview = getContentReviewResponse.data.apw.getContentReview.data;
expect(updatedContentReview.status).toEqual("readyToBePublished");
expect(updatedContentReview.title).toEqual(updatedPage.title);
/**
* Let's retract the provided sign-off for a "required step" of the publishing workflow.
*/
const [retractSignOffResponse] = await retractSignOffMutation({
id: contentReview.id,
step: step2.id
});
expect(retractSignOffResponse).toEqual({
data: {
apw: {
retractSignOff: {
data: true,
error: null
}
}
}
});
/**
* After retracting sign-off to a step of the workflow,
* Now the content should be back in "underReview" stage.
*/
[getContentReviewResponse] = await getContentReviewQuery({
id: createdContentReview.id
});
expect(getContentReviewResponse.data.apw.getContentReview.data.status).toEqual(
"underReview"
);
/**
* Let's again provide the sign-off for step 2.
*/
[provideSignOffResponse] = await provideSignOffMutation({
id: contentReview.id,
step: step2.id
});
expect(provideSignOffResponse).toEqual({
data: {
apw: {
provideSignOff: {
data: true,
error: null
}
}
}
});
/**
* After providing sign-off to every step of the workflow,
* Should be able to publish the page.
*/
[publishContentResponse] = await publishContentMutation({ id: contentReview.id });
expect(publishContentResponse).toEqual({
data: {
apw: {
publishContent: {
data: true,
error: null
}
}
}
});
/**
* Let's confirm that the content is "published".
*/
let [getPageResponse] = await getPageQuery({ id: page.id });
expect(getPageResponse).toEqual({
data: {
pageBuilder: {
getPage: {
data: expect.any(Object),
error: null
}
}
}
});
expect(getPageResponse.data.pageBuilder.getPage.data.status).toEqual("published");
expect(getPageResponse.data.pageBuilder.getPage.data.version).toEqual(1);
/**
* Fetch the content review and check if the status has been updated successful.
*/
[getContentReviewResponse] = await getContentReviewQuery({
id: createdContentReview.id
});
expect(getContentReviewResponse.data.apw.getContentReview.data.status).toEqual("published");
/**
* Let's "unpublish" the content.
*/
const [unPublishContentResponse] = await unpublishContentMutation({ id: contentReview.id });
expect(unPublishContentResponse).toEqual({
data: {
apw: {
unpublishContent: {
data: true,
error: null
}
}
}
});
/**
* Let's confirm that the content is "unpublished".
*/
[getPageResponse] = await getPageQuery({ id: page.id });
expect(getPageResponse).toEqual({
data: {
pageBuilder: {
getPage: {
data: expect.any(Object),
error: null
}
}
}
});
expect(getPageResponse.data.pageBuilder.getPage.data.status).toEqual("unpublished");
expect(getPageResponse.data.pageBuilder.getPage.data.version).toEqual(1);
/**
* Fetch the content review and check if the status has been updated successful.
*/
[getContentReviewResponse] = await getContentReviewQuery({
id: createdContentReview.id
});
expect(getContentReviewResponse.data.apw.getContentReview.data.status).toEqual(
"readyToBePublished"
);
});
}); | the_stack |
import { GlobalProps } from 'ojs/ojvcomponent';
import { ComponentChildren } from 'preact';
import { DataProvider } from '../ojdataprovider';
import { dvtBaseComponent, dvtBaseComponentEventMap, dvtBaseComponentSettableProperties } from '../ojdvt-base';
import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojPictoChart<K, D extends ojPictoChart.Item<K> | any> extends dvtBaseComponent<ojPictoChartSettableProperties<K, D>> {
animationDuration?: number;
animationOnDataChange?: 'auto' | 'none';
animationOnDisplay?: 'auto' | 'popIn' | 'alphaFade' | 'zoom' | 'none';
as?: string;
columnCount?: number | null;
columnWidth?: number | null;
data: DataProvider<K, D> | null;
drilling?: 'on' | 'off';
hiddenCategories?: string[];
highlightMatch?: 'any' | 'all';
highlightedCategories?: string[];
hoverBehavior?: 'dim' | 'none';
hoverBehaviorDelay?: number;
layout?: 'vertical' | 'horizontal';
layoutOrigin?: 'topEnd' | 'bottomStart' | 'bottomEnd' | 'topStart';
rowCount?: number | null;
rowHeight?: number | null;
selection?: K[];
selectionMode?: 'none' | 'single' | 'multiple';
tooltip?: {
renderer: ((context: ojPictoChart.TooltipContext<K>) => ({
insert: Element | string;
} | {
preventDefault: boolean;
})) | null;
};
translations: {
componentName?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelInvalidData?: string;
labelNoData?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
};
addEventListener<T extends keyof ojPictoChartEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojPictoChartEventMap<K, D>[T]) => any, options?: (boolean | AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojPictoChartSettableProperties<K, D>>(property: T): ojPictoChart<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojPictoChartSettableProperties<K, D>>(property: T, value: ojPictoChartSettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojPictoChartSettableProperties<K, D>>): void;
setProperties(properties: ojPictoChartSettablePropertiesLenient<K, D>): void;
getContextByNode(node: Element): ojPictoChart.NodeContext | null;
}
export namespace ojPictoChart {
interface ojDrill extends CustomEvent<{
id: any;
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type animationDurationChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["animationDuration"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDataChangeChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["animationOnDataChange"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDisplayChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["animationOnDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type asChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["as"]>;
// tslint:disable-next-line interface-over-type-literal
type columnCountChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["columnCount"]>;
// tslint:disable-next-line interface-over-type-literal
type columnWidthChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["columnWidth"]>;
// tslint:disable-next-line interface-over-type-literal
type dataChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["data"]>;
// tslint:disable-next-line interface-over-type-literal
type drillingChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type hiddenCategoriesChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["hiddenCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightMatchChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["highlightMatch"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightedCategoriesChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["highlightedCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type hoverBehaviorChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["hoverBehavior"]>;
// tslint:disable-next-line interface-over-type-literal
type hoverBehaviorDelayChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["hoverBehaviorDelay"]>;
// tslint:disable-next-line interface-over-type-literal
type layoutChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["layout"]>;
// tslint:disable-next-line interface-over-type-literal
type layoutOriginChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["layoutOrigin"]>;
// tslint:disable-next-line interface-over-type-literal
type rowCountChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["rowCount"]>;
// tslint:disable-next-line interface-over-type-literal
type rowHeightChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["rowHeight"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["selection"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionModeChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["selectionMode"]>;
// tslint:disable-next-line interface-over-type-literal
type tooltipChanged<K, D extends Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["tooltip"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type trackResizeChanged<K, D extends Item<K> | any> = dvtBaseComponent.trackResizeChanged<ojPictoChartSettableProperties<K, D>>;
// tslint:disable-next-line interface-over-type-literal
type Item<K> = {
borderColor?: string;
borderWidth?: number;
categories?: string[];
color?: string;
columnSpan?: number;
count?: number;
drilling?: 'inherit' | 'off' | 'on';
id?: K;
name?: string;
rowSpan?: number;
shape?: 'ellipse' | 'square' | 'circle' | 'diamond' | 'triangleUp' | 'triangleDown' | 'star' | 'plus' | 'human' | 'none' | 'rectangle' | string;
shortDesc?: (string | ((context: ItemShortDescContext<K>) => string));
source?: string;
sourceHover?: string;
sourceHoverSelected?: string;
sourceSelected?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type ItemContext<K> = {
color: string;
count: number;
id: K;
name: string;
selected: boolean;
tooltip: string;
};
// tslint:disable-next-line interface-over-type-literal
type ItemShortDescContext<K> = {
count: number;
id: K;
name: string;
};
// tslint:disable-next-line interface-over-type-literal
type ItemTemplateContext = {
componentElement: Element;
data: object;
index: number;
key: any;
};
// tslint:disable-next-line interface-over-type-literal
type NodeContext = {
index: number;
subId: string;
};
// tslint:disable-next-line interface-over-type-literal
type TooltipContext<K> = {
color: string;
componentElement: Element;
count: number;
id: K;
name: string;
parentElement: Element;
};
}
export interface ojPictoChartEventMap<K, D extends ojPictoChart.Item<K> | any> extends dvtBaseComponentEventMap<ojPictoChartSettableProperties<K, D>> {
'ojDrill': ojPictoChart.ojDrill;
'animationDurationChanged': JetElementCustomEvent<ojPictoChart<K, D>["animationDuration"]>;
'animationOnDataChangeChanged': JetElementCustomEvent<ojPictoChart<K, D>["animationOnDataChange"]>;
'animationOnDisplayChanged': JetElementCustomEvent<ojPictoChart<K, D>["animationOnDisplay"]>;
'asChanged': JetElementCustomEvent<ojPictoChart<K, D>["as"]>;
'columnCountChanged': JetElementCustomEvent<ojPictoChart<K, D>["columnCount"]>;
'columnWidthChanged': JetElementCustomEvent<ojPictoChart<K, D>["columnWidth"]>;
'dataChanged': JetElementCustomEvent<ojPictoChart<K, D>["data"]>;
'drillingChanged': JetElementCustomEvent<ojPictoChart<K, D>["drilling"]>;
'hiddenCategoriesChanged': JetElementCustomEvent<ojPictoChart<K, D>["hiddenCategories"]>;
'highlightMatchChanged': JetElementCustomEvent<ojPictoChart<K, D>["highlightMatch"]>;
'highlightedCategoriesChanged': JetElementCustomEvent<ojPictoChart<K, D>["highlightedCategories"]>;
'hoverBehaviorChanged': JetElementCustomEvent<ojPictoChart<K, D>["hoverBehavior"]>;
'hoverBehaviorDelayChanged': JetElementCustomEvent<ojPictoChart<K, D>["hoverBehaviorDelay"]>;
'layoutChanged': JetElementCustomEvent<ojPictoChart<K, D>["layout"]>;
'layoutOriginChanged': JetElementCustomEvent<ojPictoChart<K, D>["layoutOrigin"]>;
'rowCountChanged': JetElementCustomEvent<ojPictoChart<K, D>["rowCount"]>;
'rowHeightChanged': JetElementCustomEvent<ojPictoChart<K, D>["rowHeight"]>;
'selectionChanged': JetElementCustomEvent<ojPictoChart<K, D>["selection"]>;
'selectionModeChanged': JetElementCustomEvent<ojPictoChart<K, D>["selectionMode"]>;
'tooltipChanged': JetElementCustomEvent<ojPictoChart<K, D>["tooltip"]>;
'trackResizeChanged': JetElementCustomEvent<ojPictoChart<K, D>["trackResize"]>;
}
export interface ojPictoChartSettableProperties<K, D extends ojPictoChart.Item<K> | any> extends dvtBaseComponentSettableProperties {
animationDuration?: number;
animationOnDataChange?: 'auto' | 'none';
animationOnDisplay?: 'auto' | 'popIn' | 'alphaFade' | 'zoom' | 'none';
as?: string;
columnCount?: number | null;
columnWidth?: number | null;
data: DataProvider<K, D> | null;
drilling?: 'on' | 'off';
hiddenCategories?: string[];
highlightMatch?: 'any' | 'all';
highlightedCategories?: string[];
hoverBehavior?: 'dim' | 'none';
hoverBehaviorDelay?: number;
layout?: 'vertical' | 'horizontal';
layoutOrigin?: 'topEnd' | 'bottomStart' | 'bottomEnd' | 'topStart';
rowCount?: number | null;
rowHeight?: number | null;
selection?: K[];
selectionMode?: 'none' | 'single' | 'multiple';
tooltip?: {
renderer: ((context: ojPictoChart.TooltipContext<K>) => ({
insert: Element | string;
} | {
preventDefault: boolean;
})) | null;
};
translations: {
componentName?: string;
labelAndValue?: string;
labelClearSelection?: string;
labelCountWithTotal?: string;
labelDataVisualization?: string;
labelInvalidData?: string;
labelNoData?: string;
stateCollapsed?: string;
stateDrillable?: string;
stateExpanded?: string;
stateHidden?: string;
stateIsolated?: string;
stateMaximized?: string;
stateMinimized?: string;
stateSelected?: string;
stateUnselected?: string;
stateVisible?: string;
};
}
export interface ojPictoChartSettablePropertiesLenient<K, D extends ojPictoChart.Item<K> | any> extends Partial<ojPictoChartSettableProperties<K, D>> {
[key: string]: any;
}
export interface ojPictoChartItem<K = any> extends dvtBaseComponent<ojPictoChartItemSettableProperties<K>> {
borderColor?: string;
borderWidth?: number;
categories?: string[];
color?: string;
columnSpan?: number;
count?: number;
drilling?: 'inherit' | 'off' | 'on';
name?: string;
rowSpan?: number;
shape?: 'circle' | 'diamond' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | 'none' | string;
shortDesc?: (string | ((context: ojPictoChart.ItemShortDescContext<K>) => string));
source?: string;
sourceHover?: string;
sourceHoverSelected?: string;
sourceSelected?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
addEventListener<T extends keyof ojPictoChartItemEventMap<K>>(type: T, listener: (this: HTMLElement, ev: ojPictoChartItemEventMap<K>[T]) => any, options?: (boolean |
AddEventListenerOptions)): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void;
getProperty<T extends keyof ojPictoChartItemSettableProperties<K>>(property: T): ojPictoChartItem<K>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojPictoChartItemSettableProperties<K>>(property: T, value: ojPictoChartItemSettableProperties<K>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojPictoChartItemSettableProperties<K>>): void;
setProperties(properties: ojPictoChartItemSettablePropertiesLenient<K>): void;
}
export namespace ojPictoChartItem {
// tslint:disable-next-line interface-over-type-literal
type borderColorChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["borderColor"]>;
// tslint:disable-next-line interface-over-type-literal
type borderWidthChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["borderWidth"]>;
// tslint:disable-next-line interface-over-type-literal
type categoriesChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["categories"]>;
// tslint:disable-next-line interface-over-type-literal
type colorChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["color"]>;
// tslint:disable-next-line interface-over-type-literal
type columnSpanChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["columnSpan"]>;
// tslint:disable-next-line interface-over-type-literal
type countChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["count"]>;
// tslint:disable-next-line interface-over-type-literal
type drillingChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type nameChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["name"]>;
// tslint:disable-next-line interface-over-type-literal
type rowSpanChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["rowSpan"]>;
// tslint:disable-next-line interface-over-type-literal
type shapeChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["shape"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["source"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceHoverChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["sourceHover"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceHoverSelectedChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["sourceHoverSelected"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceSelectedChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["sourceSelected"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["svgStyle"]>;
}
export interface ojPictoChartItemEventMap<K = any> extends dvtBaseComponentEventMap<ojPictoChartItemSettableProperties<K>> {
'borderColorChanged': JetElementCustomEvent<ojPictoChartItem<K>["borderColor"]>;
'borderWidthChanged': JetElementCustomEvent<ojPictoChartItem<K>["borderWidth"]>;
'categoriesChanged': JetElementCustomEvent<ojPictoChartItem<K>["categories"]>;
'colorChanged': JetElementCustomEvent<ojPictoChartItem<K>["color"]>;
'columnSpanChanged': JetElementCustomEvent<ojPictoChartItem<K>["columnSpan"]>;
'countChanged': JetElementCustomEvent<ojPictoChartItem<K>["count"]>;
'drillingChanged': JetElementCustomEvent<ojPictoChartItem<K>["drilling"]>;
'nameChanged': JetElementCustomEvent<ojPictoChartItem<K>["name"]>;
'rowSpanChanged': JetElementCustomEvent<ojPictoChartItem<K>["rowSpan"]>;
'shapeChanged': JetElementCustomEvent<ojPictoChartItem<K>["shape"]>;
'shortDescChanged': JetElementCustomEvent<ojPictoChartItem<K>["shortDesc"]>;
'sourceChanged': JetElementCustomEvent<ojPictoChartItem<K>["source"]>;
'sourceHoverChanged': JetElementCustomEvent<ojPictoChartItem<K>["sourceHover"]>;
'sourceHoverSelectedChanged': JetElementCustomEvent<ojPictoChartItem<K>["sourceHoverSelected"]>;
'sourceSelectedChanged': JetElementCustomEvent<ojPictoChartItem<K>["sourceSelected"]>;
'svgClassNameChanged': JetElementCustomEvent<ojPictoChartItem<K>["svgClassName"]>;
'svgStyleChanged': JetElementCustomEvent<ojPictoChartItem<K>["svgStyle"]>;
}
export interface ojPictoChartItemSettableProperties<K = any> extends dvtBaseComponentSettableProperties {
borderColor?: string;
borderWidth?: number;
categories?: string[];
color?: string;
columnSpan?: number;
count?: number;
drilling?: 'inherit' | 'off' | 'on';
name?: string;
rowSpan?: number;
shape?: 'circle' | 'diamond' | 'human' | 'plus' | 'rectangle' | 'square' | 'star' | 'triangleDown' | 'triangleUp' | 'none' | string;
shortDesc?: (string | ((context: ojPictoChart.ItemShortDescContext<K>) => string));
source?: string;
sourceHover?: string;
sourceHoverSelected?: string;
sourceSelected?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
}
export interface ojPictoChartItemSettablePropertiesLenient<K = any> extends Partial<ojPictoChartItemSettableProperties<K>> {
[key: string]: any;
}
export type PictoChartElement<K, D extends ojPictoChart.Item<K> | any> = ojPictoChart<K, D>;
export type PictoChartItemElement<K = any> = ojPictoChartItem<K>;
export namespace PictoChartElement {
interface ojDrill extends CustomEvent<{
id: any;
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type animationDurationChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["animationDuration"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDataChangeChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["animationOnDataChange"]>;
// tslint:disable-next-line interface-over-type-literal
type animationOnDisplayChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["animationOnDisplay"]>;
// tslint:disable-next-line interface-over-type-literal
type asChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["as"]>;
// tslint:disable-next-line interface-over-type-literal
type columnCountChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["columnCount"]>;
// tslint:disable-next-line interface-over-type-literal
type columnWidthChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["columnWidth"]>;
// tslint:disable-next-line interface-over-type-literal
type dataChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["data"]>;
// tslint:disable-next-line interface-over-type-literal
type drillingChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type hiddenCategoriesChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["hiddenCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightMatchChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["highlightMatch"]>;
// tslint:disable-next-line interface-over-type-literal
type highlightedCategoriesChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["highlightedCategories"]>;
// tslint:disable-next-line interface-over-type-literal
type hoverBehaviorChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["hoverBehavior"]>;
// tslint:disable-next-line interface-over-type-literal
type hoverBehaviorDelayChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["hoverBehaviorDelay"]>;
// tslint:disable-next-line interface-over-type-literal
type layoutChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["layout"]>;
// tslint:disable-next-line interface-over-type-literal
type layoutOriginChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["layoutOrigin"]>;
// tslint:disable-next-line interface-over-type-literal
type rowCountChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["rowCount"]>;
// tslint:disable-next-line interface-over-type-literal
type rowHeightChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["rowHeight"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["selection"]>;
// tslint:disable-next-line interface-over-type-literal
type selectionModeChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["selectionMode"]>;
// tslint:disable-next-line interface-over-type-literal
type tooltipChanged<K, D extends ojPictoChart.Item<K> | any> = JetElementCustomEvent<ojPictoChart<K, D>["tooltip"]>;
//------------------------------------------------------------
// Start: generated events for inherited properties
//------------------------------------------------------------
// tslint:disable-next-line interface-over-type-literal
type trackResizeChanged<K, D extends ojPictoChart.Item<K> | any> = dvtBaseComponent.trackResizeChanged<ojPictoChartSettableProperties<K, D>>;
// tslint:disable-next-line interface-over-type-literal
type Item<K> = {
borderColor?: string;
borderWidth?: number;
categories?: string[];
color?: string;
columnSpan?: number;
count?: number;
drilling?: 'inherit' | 'off' | 'on';
id?: K;
name?: string;
rowSpan?: number;
shape?: 'ellipse' | 'square' | 'circle' | 'diamond' | 'triangleUp' | 'triangleDown' | 'star' | 'plus' | 'human' | 'none' | 'rectangle' | string;
shortDesc?: (string | ((context: ojPictoChart.ItemShortDescContext<K>) => string));
source?: string;
sourceHover?: string;
sourceHoverSelected?: string;
sourceSelected?: string;
svgClassName?: string;
svgStyle?: Partial<CSSStyleDeclaration>;
};
// tslint:disable-next-line interface-over-type-literal
type ItemShortDescContext<K> = {
count: number;
id: K;
name: string;
};
// tslint:disable-next-line interface-over-type-literal
type NodeContext = {
index: number;
subId: string;
};
}
export namespace PictoChartItemElement {
// tslint:disable-next-line interface-over-type-literal
type borderColorChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["borderColor"]>;
// tslint:disable-next-line interface-over-type-literal
type borderWidthChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["borderWidth"]>;
// tslint:disable-next-line interface-over-type-literal
type categoriesChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["categories"]>;
// tslint:disable-next-line interface-over-type-literal
type colorChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["color"]>;
// tslint:disable-next-line interface-over-type-literal
type columnSpanChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["columnSpan"]>;
// tslint:disable-next-line interface-over-type-literal
type countChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["count"]>;
// tslint:disable-next-line interface-over-type-literal
type drillingChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["drilling"]>;
// tslint:disable-next-line interface-over-type-literal
type nameChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["name"]>;
// tslint:disable-next-line interface-over-type-literal
type rowSpanChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["rowSpan"]>;
// tslint:disable-next-line interface-over-type-literal
type shapeChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["shape"]>;
// tslint:disable-next-line interface-over-type-literal
type shortDescChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["shortDesc"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["source"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceHoverChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["sourceHover"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceHoverSelectedChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["sourceHoverSelected"]>;
// tslint:disable-next-line interface-over-type-literal
type sourceSelectedChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["sourceSelected"]>;
// tslint:disable-next-line interface-over-type-literal
type svgClassNameChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["svgClassName"]>;
// tslint:disable-next-line interface-over-type-literal
type svgStyleChanged<K = any> = JetElementCustomEvent<ojPictoChartItem<K>["svgStyle"]>;
}
export interface PictoChartIntrinsicProps extends Partial<Readonly<ojPictoChartSettableProperties<any, any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onojDrill?: (value: ojPictoChartEventMap<any, any>['ojDrill']) => void;
onanimationDurationChanged?: (value: ojPictoChartEventMap<any, any>['animationDurationChanged']) => void;
onanimationOnDataChangeChanged?: (value: ojPictoChartEventMap<any, any>['animationOnDataChangeChanged']) => void;
onanimationOnDisplayChanged?: (value: ojPictoChartEventMap<any, any>['animationOnDisplayChanged']) => void;
onasChanged?: (value: ojPictoChartEventMap<any, any>['asChanged']) => void;
oncolumnCountChanged?: (value: ojPictoChartEventMap<any, any>['columnCountChanged']) => void;
oncolumnWidthChanged?: (value: ojPictoChartEventMap<any, any>['columnWidthChanged']) => void;
ondataChanged?: (value: ojPictoChartEventMap<any, any>['dataChanged']) => void;
ondrillingChanged?: (value: ojPictoChartEventMap<any, any>['drillingChanged']) => void;
onhiddenCategoriesChanged?: (value: ojPictoChartEventMap<any, any>['hiddenCategoriesChanged']) => void;
onhighlightMatchChanged?: (value: ojPictoChartEventMap<any, any>['highlightMatchChanged']) => void;
onhighlightedCategoriesChanged?: (value: ojPictoChartEventMap<any, any>['highlightedCategoriesChanged']) => void;
onhoverBehaviorChanged?: (value: ojPictoChartEventMap<any, any>['hoverBehaviorChanged']) => void;
onhoverBehaviorDelayChanged?: (value: ojPictoChartEventMap<any, any>['hoverBehaviorDelayChanged']) => void;
onlayoutChanged?: (value: ojPictoChartEventMap<any, any>['layoutChanged']) => void;
onlayoutOriginChanged?: (value: ojPictoChartEventMap<any, any>['layoutOriginChanged']) => void;
onrowCountChanged?: (value: ojPictoChartEventMap<any, any>['rowCountChanged']) => void;
onrowHeightChanged?: (value: ojPictoChartEventMap<any, any>['rowHeightChanged']) => void;
onselectionChanged?: (value: ojPictoChartEventMap<any, any>['selectionChanged']) => void;
onselectionModeChanged?: (value: ojPictoChartEventMap<any, any>['selectionModeChanged']) => void;
ontooltipChanged?: (value: ojPictoChartEventMap<any, any>['tooltipChanged']) => void;
ontrackResizeChanged?: (value: ojPictoChartEventMap<any, any>['trackResizeChanged']) => void;
children?: ComponentChildren;
}
export interface PictoChartItemIntrinsicProps extends Partial<Readonly<ojPictoChartItemSettableProperties<any>>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> {
onborderColorChanged?: (value: ojPictoChartItemEventMap<any>['borderColorChanged']) => void;
onborderWidthChanged?: (value: ojPictoChartItemEventMap<any>['borderWidthChanged']) => void;
oncategoriesChanged?: (value: ojPictoChartItemEventMap<any>['categoriesChanged']) => void;
oncolorChanged?: (value: ojPictoChartItemEventMap<any>['colorChanged']) => void;
oncolumnSpanChanged?: (value: ojPictoChartItemEventMap<any>['columnSpanChanged']) => void;
oncountChanged?: (value: ojPictoChartItemEventMap<any>['countChanged']) => void;
ondrillingChanged?: (value: ojPictoChartItemEventMap<any>['drillingChanged']) => void;
onnameChanged?: (value: ojPictoChartItemEventMap<any>['nameChanged']) => void;
onrowSpanChanged?: (value: ojPictoChartItemEventMap<any>['rowSpanChanged']) => void;
onshapeChanged?: (value: ojPictoChartItemEventMap<any>['shapeChanged']) => void;
onshortDescChanged?: (value: ojPictoChartItemEventMap<any>['shortDescChanged']) => void;
onsourceChanged?: (value: ojPictoChartItemEventMap<any>['sourceChanged']) => void;
onsourceHoverChanged?: (value: ojPictoChartItemEventMap<any>['sourceHoverChanged']) => void;
onsourceHoverSelectedChanged?: (value: ojPictoChartItemEventMap<any>['sourceHoverSelectedChanged']) => void;
onsourceSelectedChanged?: (value: ojPictoChartItemEventMap<any>['sourceSelectedChanged']) => void;
onsvgClassNameChanged?: (value: ojPictoChartItemEventMap<any>['svgClassNameChanged']) => void;
onsvgStyleChanged?: (value: ojPictoChartItemEventMap<any>['svgStyleChanged']) => void;
children?: ComponentChildren;
}
declare global {
namespace preact.JSX {
interface IntrinsicElements {
"oj-picto-chart": PictoChartIntrinsicProps;
"oj-picto-chart-item": PictoChartItemIntrinsicProps;
}
}
} | the_stack |
import * as React from 'react';
import { reaction, IReactionDisposer } from 'mobx';
import { inject, observer } from 'mobx-react';
import {
InputGroup,
ControlGroup,
Button,
ButtonGroup,
Popover,
Intent,
Alert,
HotkeysTarget,
Hotkeys,
Hotkey,
Tooltip,
Position,
IHotkeysProps,
} from '@blueprintjs/core';
import { AppState } from '../state/appState';
import { FileMenu } from './FileMenu';
import { MakedirDialog } from './dialogs/MakedirDialog';
import { AppAlert } from './AppAlert';
import { Logger } from './Log';
import { AppToaster } from './AppToaster';
import { withNamespaces, WithNamespaces, Trans } from 'react-i18next';
import { WithMenuAccelerators, Accelerators, Accelerator } from './WithMenuAccelerators';
import { throttle } from '../utils/throttle';
import { isWin, isMac } from '../utils/platform';
import { ViewState } from '../state/viewState';
import { FileState } from '../state/fileState';
import { LocalizedError } from '../locale/error';
const TOOLTIP_DELAY = 1200;
const MOVE_EVENT_THROTTLE = 300;
const ERROR_MESSAGE_TIMEOUT = 3500;
interface Props extends WithNamespaces {
onPaste: () => void;
active: boolean;
}
interface InjectedProps extends Props {
appState: AppState;
viewState: ViewState;
}
interface PathInputState {
status: -1 | 0 | 1;
path: string;
isOpen: boolean;
isDeleteOpen: boolean;
isTooltipOpen: boolean;
}
enum KEYS {
Escape = 27,
Enter = 13,
}
@inject('appState', 'viewState')
@observer
@HotkeysTarget
@WithMenuAccelerators
export class ToolbarClass extends React.Component<Props, PathInputState> {
private input: HTMLInputElement | null = null;
private disposer: IReactionDisposer;
private tooltipReady = false;
private tooltipTimeout = 0;
private canShowTooltip = false;
constructor(props: Props) {
super(props);
const { viewState } = this.injected;
const fileCache = viewState.getVisibleCache();
this.state = {
status: 0,
path: fileCache.path,
isOpen: false,
isDeleteOpen: false,
isTooltipOpen: false,
};
this.installReactions();
}
private get injected(): InjectedProps {
return this.props as InjectedProps;
}
private get cache(): FileState {
const { viewState } = this.injected;
return viewState.getVisibleCache();
}
// reset status once path has been modified from outside this component
private installReactions(): void {
this.disposer = reaction(
(): string => {
return this.cache.path;
},
(path): void => {
this.setState({ path, status: 0 });
},
);
}
private onBackward = (): void => {
this.cache.navHistory(-1);
};
private onForward = (): void => {
this.cache.navHistory(1);
};
private onPathChange = (event: React.FormEvent<HTMLElement>): void => {
const path = (event.target as HTMLInputElement).value;
this.setState({ path });
// this.checkPath(event);
};
private onSubmit = (): void => {
if (this.cache.path !== this.state.path) {
this.input.blur();
const path = this.state.path;
this.cache.cd(this.state.path).catch((err: LocalizedError) => {
AppAlert.show(`${err.message} (${err.code})`, {
intent: 'danger',
}).then((): void => {
// we restore the wrong path entered and focus the input:
// in case the user made a simple typo he doesn't want
// to type it again
this.setState({ path });
this.input.focus();
});
});
}
};
private onKeyUp = (event: React.KeyboardEvent<HTMLElement>): void => {
this.hideTooltip();
if (event.keyCode === KEYS.Escape) {
// since React events are attached to the root document
// event already has bubbled up so we must stop
// its immediate propagation
event.nativeEvent.stopImmediatePropagation();
// lose focus
this.input.blur();
// workaround for Cypress bug https://github.com/cypress-io/cypress/issues/1176
// this.onBlur();
} else if (event.keyCode === KEYS.Enter) {
this.onSubmit();
}
};
private onBlur = (): void => {
this.setState({ path: this.cache.path, status: 0, isTooltipOpen: false });
};
private onReload = (): void => {
this.cache.reload();
};
private refHandler = (input: HTMLInputElement): void => {
this.input = input;
};
private makedir = async (dirName: string, navigate: boolean): Promise<void> => {
this.setState({ isOpen: false });
if (!dirName.length) {
return;
}
try {
Logger.log("Let's create a directory :)", dirName, navigate);
const dir = await this.cache.makedir(this.state.path, dirName);
if (!navigate) {
this.cache.reload();
} else {
this.cache.cd(dir as string);
}
} catch (err) {
const { t } = this.props;
AppToaster.show({
message: t('ERRORS.CREATE_FOLDER', { message: err.message }),
icon: 'error',
intent: Intent.DANGER,
timeout: ERROR_MESSAGE_TIMEOUT,
});
}
};
private deleteCancel = (): void => {
this.setState({ isDeleteOpen: false });
};
private onDeleteError = (err?: LocalizedError) => {
const { t } = this.props;
if (err) {
AppToaster.show({
message: t('ERRORS.DELETE', { message: err.message }),
icon: 'error',
intent: Intent.DANGER,
timeout: ERROR_MESSAGE_TIMEOUT,
});
} else {
AppToaster.show({
message: t('ERRORS.DELETE_WARN'),
icon: 'warning-sign',
intent: Intent.WARNING,
timeout: ERROR_MESSAGE_TIMEOUT,
});
}
};
private delete = async (): Promise<void> => {
Logger.log('delete selected files');
try {
const { viewState } = this.injected;
const fileCache = viewState.getVisibleCache();
const cache = this.cache;
const deleted = await cache.delete(this.state.path, fileCache.selected);
// TODO: reset selection ?
if (!deleted) {
this.onDeleteError();
} else {
if (deleted !== fileCache.selected.length) {
// show warning
this.onDeleteError();
}
if (cache.getFS().options.needsRefresh) {
cache.reload();
}
}
} catch (err: LocalizedError) {
this.onDeleteError(err);
}
this.setState({ isDeleteOpen: false });
};
private onMakedir = (): void => {
const { appState, viewState } = this.injected;
if (appState.getActiveCache() === viewState.getVisibleCache()) {
this.setState({ isOpen: true });
}
};
private onDelete = (): void => {
const { appState, viewState } = this.injected;
const fileCache = viewState.getVisibleCache();
if (appState.getActiveCache() === fileCache && fileCache.selected.length) {
this.setState({ isDeleteOpen: true });
}
};
private onFileAction = (action: string): void => {
switch (action) {
case 'makedir':
Logger.log('Opening new folder dialog');
this.onMakedir();
break;
case 'delete':
this.onDelete();
break;
case 'paste':
this.props.onPaste();
break;
default:
Logger.warn('action unknown', action);
}
};
public onActivatePath = (): void => {
if (this.props.active) {
this.input.focus();
}
};
public hideTooltip(): void {
this.canShowTooltip = false;
this.setState({ isTooltipOpen: false });
}
public onFocus = (): void => {
if (this.state.isTooltipOpen) {
this.hideTooltip();
} else {
this.canShowTooltip = false;
}
this.input.select();
};
public componentWillUnmount(): void {
this.disposer();
}
// shouldComponentUpdate() {
// console.time('Toolbar Render');
// return true;
// }
// componentDidUpdate() {
// console.timeEnd('Toolbar Render');
// }
renderMenuAccelerators(): React.ReactElement {
return (
<Accelerators>
<Accelerator combo="CmdOrCtrl+N" onClick={this.onMakedir}></Accelerator>
<Accelerator combo="CmdOrCtrl+D" onClick={this.onDelete}></Accelerator>
</Accelerators>
);
}
public renderHotkeys(): React.ReactElement<IHotkeysProps> {
const { t } = this.props;
return (
<Hotkeys>
<Hotkey
global={true}
combo="mod+l"
label={t('SHORTCUT.ACTIVE_VIEW.FOCUS_PATH')}
onKeyDown={this.onActivatePath}
group={t('SHORTCUT.GROUP.ACTIVE_VIEW')}
/>
{/* <Hotkey
global={true}
combo="mod+n"
label={t('COMMON.MAKEDIR')}
onKeyDown={this.onMakedir}
group={t('SHORTCUT.GROUP.ACTIVE_VIEW')}
/> */}
{/* <Hotkey
global={true}
combo="mod+d"
label={t('SHORTCUT.ACTIVE_VIEW.DELETE')}
onKeyDown={this.onDelete}
group={t('SHORTCUT.GROUP.ACTIVE_VIEW')}
/> */}
</Hotkeys>
) as React.ReactElement<IHotkeysProps>;
}
onPathEnter = (): void => {
this.tooltipReady = true;
this.canShowTooltip = true;
this.setTooltipTimeout();
};
onPathLeave = (): void => {
this.tooltipReady = false;
};
onPathMouseMove = throttle((): void => {
if (this.state.isTooltipOpen) {
// if tooltip was visible and mouse moves
// then it cannot be opened again unless the
// user leaves the text input
this.canShowTooltip = false;
this.setState({ isTooltipOpen: false });
} else if (this.canShowTooltip && this.tooltipReady) {
clearTimeout(this.tooltipTimeout);
this.setTooltipTimeout();
}
}, MOVE_EVENT_THROTTLE);
setTooltipTimeout(): void {
this.tooltipTimeout = window.setTimeout(() => {
if (this.tooltipReady && this.canShowTooltip) {
this.setState({ isTooltipOpen: true });
}
}, TOOLTIP_DELAY);
}
onParent = (): void => {
const { viewState } = this.injected;
const fileCache = viewState.getVisibleCache();
fileCache.openParentDirectory();
};
private renderTooltip(): JSX.Element {
const { t } = this.props;
const localExample = isWin
? t('TOOLTIP.PATH.EXAMPLE_WIN')
: (isMac && t('TOOLTIP.PATH.EXAMPLE_MAC')) || t('TOOLTIP.PATH.EXAMPLE_LINUX');
return (
<div>
<p>{t('TOOLTIP.PATH.TITLE1')}</p>
<p>{t('TOOLTIP.PATH.TITLE2')}</p>
<ul>
<li>{localExample}</li>
{/* <li>{t('TOOLTIP.PATH.FTP1')}</li>
<li>{t('TOOLTIP.PATH.FTP2')}</li> */}
</ul>
</div>
);
}
public render(): JSX.Element {
const { status, path, isOpen, isDeleteOpen, isTooltipOpen } = this.state;
const { viewState } = this.injected;
const fileCache = viewState.getVisibleCache();
const { selected, history, current } = fileCache;
const { t } = this.props;
if (!fileCache) {
console.log('oops', fileCache);
debugger;
}
const canGoBackward = current > 0;
const canGoForward = history.length > 1 && current < history.length - 1;
// const loadingSpinner = false ? <Spinner size={Icon.SIZE_STANDARD} /> : undefined;
const reloadButton = (
<Button className="small data-cy-reload" onClick={this.onReload} minimal rightIcon="repeat"></Button>
);
const intent = status === -1 ? 'danger' : 'none';
const count = selected.length;
const isRoot = fileCache.isRoot();
return (
<ControlGroup className="toolbar">
<ButtonGroup style={{ minWidth: 120, overflow: 'hidden' }}>
<Button
title={t('TOOLBAR.BACK')}
data-cy-backward
disabled={!canGoBackward}
onClick={this.onBackward}
rightIcon="chevron-left"
></Button>
<Button
title={t('TOOLBAR.FORWARD')}
data-cy-forward
disabled={!canGoForward}
onClick={this.onForward}
rightIcon="chevron-right"
></Button>
<Button
title={t('TOOLBAR.PARENT')}
disabled={isRoot}
onClick={this.onParent}
rightIcon="arrow-up"
></Button>
<Popover content={<FileMenu selectedItems={selected} onFileAction={this.onFileAction} />}>
<Button rightIcon="caret-down" icon="cog" text="" />
</Popover>
</ButtonGroup>
<Tooltip
content={this.renderTooltip()}
position={Position.BOTTOM}
hoverOpenDelay={1500}
openOnTargetFocus={false}
isOpen={isTooltipOpen}
>
<InputGroup
data-cy-path
onChange={this.onPathChange}
onKeyUp={this.onKeyUp}
placeholder={t('COMMON.PATH_PLACEHOLDER')}
rightElement={reloadButton}
value={path}
intent={intent}
inputRef={this.refHandler}
onBlur={this.onBlur}
onFocus={this.onFocus}
onMouseEnter={this.onPathEnter}
onMouseLeave={this.onPathLeave}
onMouseMove={this.onPathMouseMove}
/>
</Tooltip>
{isOpen && (
<MakedirDialog
isOpen={isOpen}
onClose={this.makedir}
onValidation={fileCache.isDirectoryNameValid}
parentPath={path}
></MakedirDialog>
)}
<Alert
cancelButtonText={t('COMMON.CANCEL')}
confirmButtonText={t('APP_MENUS.DELETE')}
icon="trash"
intent={Intent.DANGER}
isOpen={isDeleteOpen}
onConfirm={this.delete}
onCancel={this.deleteCancel}
>
<p>
<Trans i18nKey="DIALOG.DELETE.CONFIRM" count={count}>
Are you sure you want to delete <b>{{ count }}</b> file(s)/folder(s)?
<br />
<br />
This action will <b>permanentaly</b> delete the selected elements.
</Trans>
</p>
</Alert>
<Button
rightIcon="arrow-right"
className="data-cy-submit-path"
disabled={status === -1}
onClick={this.onSubmit}
/>
</ControlGroup>
);
}
}
const Toolbar = withNamespaces()(ToolbarClass);
export { Toolbar }; | the_stack |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="pt">
<context>
<name>MainUI</name>
<message>
<location filename="../mainUI.ui" line="14"/>
<location filename="../mainUI.cpp" line="286"/>
<source>Media Player</source>
<translation>Reprodutor multimédia</translation>
</message>
<message>
<location filename="../mainUI.ui" line="50"/>
<location filename="../mainUI.ui" line="261"/>
<location filename="../mainUI.cpp" line="632"/>
<source>Now Playing</source>
<translation>Em reprodução</translation>
</message>
<message>
<location filename="../mainUI.ui" line="74"/>
<source>(No Running Video)</source>
<translation>(Nenhum vídeo em reprodução)</translation>
</message>
<message>
<location filename="../mainUI.ui" line="105"/>
<source>Playlist</source>
<translation>Lista de reprodução</translation>
</message>
<message>
<location filename="../mainUI.ui" line="167"/>
<source>up</source>
<translation>Subir</translation>
</message>
<message>
<location filename="../mainUI.ui" line="183"/>
<source>down</source>
<translation>Descer</translation>
</message>
<message>
<location filename="../mainUI.ui" line="267"/>
<source>Current Song</source>
<translation>Faixa atual</translation>
</message>
<message>
<location filename="../mainUI.ui" line="303"/>
<source>TITLE</source>
<translation>Título</translation>
</message>
<message>
<location filename="../mainUI.ui" line="327"/>
<source>ARTIST</source>
<translation>Artista</translation>
</message>
<message>
<location filename="../mainUI.ui" line="337"/>
<source>ALBUM</source>
<translation>Álbum</translation>
</message>
<message>
<location filename="../mainUI.ui" line="368"/>
<source>Love this song</source>
<translation>Gosto desta faixa</translation>
</message>
<message>
<location filename="../mainUI.ui" line="384"/>
<source>Tired of this song (will not play for a month)</source>
<translation>Estou farto desta faixa (não reproduzir durante 1 mês)</translation>
</message>
<message>
<location filename="../mainUI.ui" line="397"/>
<source>Ban this song (will never play again)</source>
<translation>Banir faixa (não voltar a reproduzir)</translation>
</message>
<message>
<location filename="../mainUI.ui" line="417"/>
<source>View details about song (launches web browser)</source>
<translation>Ver detalhes sobre a faixa (abre o navegador web)</translation>
</message>
<message>
<location filename="../mainUI.ui" line="448"/>
<source>Current Station</source>
<translation>Estação atual</translation>
</message>
<message>
<location filename="../mainUI.ui" line="479"/>
<source>Delete current station</source>
<translation>Apagar estação atual</translation>
</message>
<message>
<location filename="../mainUI.ui" line="482"/>
<source>rm</source>
<translation>remover</translation>
</message>
<message>
<location filename="../mainUI.ui" line="492"/>
<source>Create new station</source>
<translation>Criar nova estação</translation>
</message>
<message>
<location filename="../mainUI.ui" line="495"/>
<source>add</source>
<translation>adicionar</translation>
</message>
<message>
<location filename="../mainUI.ui" line="512"/>
<source>Settings</source>
<translation>Definições</translation>
</message>
<message>
<location filename="../mainUI.ui" line="521"/>
<source>Pandora Account Login</source>
<translation>Credenciais Pandora</translation>
</message>
<message>
<location filename="../mainUI.ui" line="527"/>
<source>Email</source>
<translation>E-mail</translation>
</message>
<message>
<location filename="../mainUI.ui" line="537"/>
<source>Password</source>
<translation>Palavra-passe</translation>
</message>
<message>
<location filename="../mainUI.ui" line="557"/>
<source><a href=https://www.pandora.com/account/register>Need an account?</a></source>
<translation><a href=https://www.pandora.com/account/register>Necessita de uma conta?</a></translation>
</message>
<message>
<location filename="../mainUI.ui" line="573"/>
<source>Audio Quality</source>
<translation>Qualidade de áudio</translation>
</message>
<message>
<location filename="../mainUI.ui" line="583"/>
<source>Proxy URL</source>
<translation>URL do proxy</translation>
</message>
<message>
<location filename="../mainUI.ui" line="593"/>
<source>Control Proxy URL</source>
<translation>Controlar URL do proxy</translation>
</message>
<message>
<location filename="../mainUI.ui" line="618"/>
<source>Apply Settings</source>
<translation>Aplicar definições</translation>
</message>
<message>
<location filename="../mainUI.ui" line="656"/>
<source>Audio Driver</source>
<translation>Controlador áudio</translation>
</message>
<message>
<location filename="../mainUI.ui" line="681"/>
<source>&File</source>
<translation>&Ficheiro</translation>
</message>
<message>
<location filename="../mainUI.ui" line="688"/>
<source>&View</source>
<translation>&Ver</translation>
</message>
<message>
<location filename="../mainUI.ui" line="723"/>
<source>Play</source>
<translation>Reproduzir</translation>
</message>
<message>
<location filename="../mainUI.ui" line="728"/>
<source>Pause</source>
<translation>Pausa</translation>
</message>
<message>
<location filename="../mainUI.ui" line="733"/>
<source>Stop</source>
<translation>Parar</translation>
</message>
<message>
<location filename="../mainUI.ui" line="738"/>
<source>Next</source>
<translation>Seguinte</translation>
</message>
<message>
<location filename="../mainUI.ui" line="743"/>
<source>Back</source>
<translation>Anterior</translation>
</message>
<message>
<location filename="../mainUI.ui" line="748"/>
<source>VolUp</source>
<translation>Aumentar</translation>
</message>
<message>
<location filename="../mainUI.ui" line="751"/>
<source>Raise audio volume</source>
<translation>Aumenta o volume áudio</translation>
</message>
<message>
<location filename="../mainUI.ui" line="756"/>
<source>VolDown</source>
<translation>Diminuir</translation>
</message>
<message>
<location filename="../mainUI.ui" line="759"/>
<source>Lower audio volume</source>
<translation>Diminui o volume áudio</translation>
</message>
<message>
<location filename="../mainUI.ui" line="764"/>
<source>Close Application</source>
<translation>Fechar aplicação</translation>
</message>
<message>
<location filename="../mainUI.ui" line="767"/>
<source>Ctrl+Q</source>
<translation>Ctrl+Q</translation>
</message>
<message>
<location filename="../mainUI.ui" line="781"/>
<source>Close to tray when active</source>
<translation>Fechar para a bandeja se ativa</translation>
</message>
<message>
<location filename="../mainUI.ui" line="786"/>
<source>From current artist</source>
<translation>Do artista atual</translation>
</message>
<message>
<location filename="../mainUI.ui" line="789"/>
<source>Create station from current artist</source>
<translation>Criar estação do artista atual</translation>
</message>
<message>
<location filename="../mainUI.ui" line="794"/>
<source>From current song</source>
<translation>Da faixa atual</translation>
</message>
<message>
<location filename="../mainUI.ui" line="797"/>
<source>Create station from current song</source>
<translation>Criara estação da faixa atual</translation>
</message>
<message>
<location filename="../mainUI.ui" line="808"/>
<source>Show song notifications</source>
<translation>Mostrar notificações</translation>
</message>
<message>
<location filename="../mainUI.ui" line="813"/>
<source>Search...</source>
<translation>Pesquisar...</translation>
</message>
<message>
<location filename="../mainUI.ui" line="816"/>
<source>Search for a new station</source>
<translation>Pesquisar por uma estação</translation>
</message>
<message>
<location filename="../mainUI.ui" line="828"/>
<location filename="../mainUI.cpp" line="277"/>
<source>Pandora Radio</source>
<translation>Pandora Radio</translation>
</message>
<message>
<location filename="../mainUI.ui" line="831"/>
<source>Stream from Pandora Radio</source>
<translation>Reproduzir de Pandora Radio</translation>
</message>
<message>
<location filename="../mainUI.ui" line="839"/>
<source>Local Files</source>
<translation>Ficheiros locais</translation>
</message>
<message>
<location filename="../mainUI.ui" line="842"/>
<source>Play Local Files</source>
<translation>Reproduzir ficheiros locais</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="105"/>
<source>Please install the `pianobar` utility to enable this functionality</source>
<translation>Tem que instalar 'pianobar' para ativar esta funcionalidade</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="109"/>
<source>Stream music from the Pandora online radio service</source>
<translation>Reproduzir músicas do serviço web Pandora</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="122"/>
<source>Low</source>
<translation>Baixa</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="123"/>
<source>Medium</source>
<translation>Média</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="124"/>
<source>High</source>
<translation>Alta</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="359"/>
<source>Open Multimedia Files</source>
<translation>Abrir ficheiros multimédia</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="407"/>
<source>Now Playing:</source>
<translation>Em reprodução:</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="472"/>
<source>[PLAYBACK ERROR]
%1</source>
<translation>[Erro de reprodução]
%1</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="489"/>
<source>Media Loading...</source>
<translation>A carregar...</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="491"/>
<source>Media Stalled...</source>
<translation>Bloqueada...</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="493"/>
<source>Media Buffering...</source>
<translation>A processar...</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="577"/>
<source>Pandora: Create Station</source>
<translation>Pandora: Criar estação</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="577"/>
<source>Search Term</source>
<translation>Termo de pesquisa</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="655"/>
<source>Pandora Question</source>
<translation>Pergunta Pandora</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="660"/>
<source>Pandora Error</source>
<translation>Erro Pandora</translation>
</message>
</context>
<context>
<name>PianoBarProcess</name>
<message>
<location filename="../PianoBarProcess.cpp" line="360"/>
<source>Could not find any matches. Please try a different search term</source>
<translation>Não foi encontrada qualquer ocorrência. Tente um termo de pesquisa diferente.</translation>
</message>
</context>
<context>
<name>XDGDesktopList</name>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="618"/>
<source>Multimedia</source>
<translation>Multimédia</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="619"/>
<source>Development</source>
<translation>Desenvolvimento</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="620"/>
<source>Education</source>
<translation>Educação</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="621"/>
<source>Games</source>
<translation>Jogos</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="622"/>
<source>Graphics</source>
<translation>Gráficos</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="623"/>
<source>Network</source>
<translation>Rede</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="624"/>
<source>Office</source>
<translation>Escritório</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="625"/>
<source>Science</source>
<translation>Ciência</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="626"/>
<source>Settings</source>
<translation>Definições</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="627"/>
<source>System</source>
<translation>Sistema</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="628"/>
<source>Utility</source>
<translation>Utilitários</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="629"/>
<source>Wine</source>
<translation>Wine</translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="630"/>
<source>Unsorted</source>
<translation>Sem grupo</translation>
</message>
</context>
</TS> | the_stack |
import log from "../../../../../log";
import { base64ToBytes } from "../../../../../utils/base64";
import isNonEmptyString from "../../../../../utils/is_non_empty_string";
import { IScheme } from "../../node_parser_types";
const iso8601Duration =
/^P(([\d.]*)Y)?(([\d.]*)M)?(([\d.]*)D)?T?(([\d.]*)H)?(([\d.]*)M)?(([\d.]*)S)?/;
const rangeRe = /([0-9]+)-([0-9]+)/;
/**
* Parse MPD boolean attributes.
*
* The returned value is a tuple of two elements where:
* 1. the first value is the parsed boolean - or `null` if we could not parse
* it
* 2. the second value is a possible error encountered while parsing this
* value - set to `null` if no error was encountered.
* @param {string} val - The value to parse
* @param {string} displayName - The name of the property. Used for error
* formatting.
* @returns {Array.<Boolean | Error | null>}
*/
function parseBoolean(
val : string,
displayName : string
) : [boolean,
MPDError | null]
{
if (val === "true") {
return [true, null];
}
if (val === "false") {
return [false, null];
}
const error = new MPDError(
`\`${displayName}\` property is not a boolean value but "${val}"`);
return [false, error];
}
/**
* Parse MPD integer attributes.
*
* The returned value is a tuple of two elements where:
* 1. the first value is the parsed boolean - or `null` if we could not parse
* it
* 2. the second value is a possible error encountered while parsing this
* value - set to `null` if no error was encountered.
* @param {string} val - The value to parse
* @param {string} displayName - The name of the property. Used for error
* formatting.
* @returns {Array.<number | Error | null>}
*/
function parseMPDInteger(
val : string,
displayName : string
) : [number | null,
MPDError | null]
{
const toInt = parseInt(val, 10);
if (isNaN(toInt)) {
const error = new MPDError(
`\`${displayName}\` property is not an integer value but "${val}"`);
return [null, error];
}
return [toInt, null];
}
/**
* Parse MPD float attributes.
*
* The returned value is a tuple of two elements where:
* 1. the first value is the parsed boolean - or `null` if we could not parse
* it
* 2. the second value is a possible error encountered while parsing this
* value - set to `null` if no error was encountered.
* @param {string} val - The value to parse
* @param {string} displayName - The name of the property. Used for error
* formatting.
* @returns {Array.<number | Error | null>}
*/
function parseMPDFloat(
val : string,
displayName : string
) : [number | null,
MPDError | null]
{
const toInt = parseFloat(val);
if (isNaN(toInt)) {
const error = new MPDError(
`\`${displayName}\` property is not an integer value but "${val}"`);
return [null, error];
}
return [toInt, null];
}
/**
* Parse MPD attributes which are either integer or boolean values.
*
* The returned value is a tuple of two elements where:
* 1. the first value is the parsed value - or `null` if we could not parse
* it
* 2. the second value is a possible error encountered while parsing this
* value - set to `null` if no error was encountered.
* @param {string} val - The value to parse
* @param {string} displayName - The name of the property. Used for error
* formatting.
* @returns {Array.<Boolean | number | Error | null>}
*/
function parseIntOrBoolean(
val : string,
displayName : string
) : [ boolean | number | null,
MPDError | null ] {
if (val === "true") {
return [true, null];
}
if (val === "false") {
return [false, null];
}
const toInt = parseInt(val, 10);
if (isNaN(toInt)) {
const error = new MPDError(
`\`${displayName}\` property is not a boolean nor an integer but "${val}"`);
return [null, error];
}
return [toInt, null];
}
/**
* Parse MPD date attributes.
*
* The returned value is a tuple of two elements where:
* 1. the first value is the parsed value - or `null` if we could not parse
* it
* 2. the second value is a possible error encountered while parsing this
* value - set to `null` if no error was encountered.
* @param {string} val - The value to parse
* @param {string} displayName - The name of the property. Used for error
* formatting.
* @returns {Array.<Date | null | Error>}
*/
function parseDateTime(
val : string,
displayName : string
) : [number | null,
MPDError | null ] {
const parsed = Date.parse(val);
if (isNaN(parsed)) {
const error = new MPDError(
`\`${displayName}\` is in an invalid date format: "${val}"`);
return [null, error];
}
return [new Date(Date.parse(val)).getTime() / 1000, null];
}
/**
* Parse MPD ISO8601 duration attributes into seconds.
*
* The returned value is a tuple of two elements where:
* 1. the first value is the parsed value - or `null` if we could not parse
* it
* 2. the second value is a possible error encountered while parsing this
* value - set to `null` if no error was encountered.
* @param {string} val - The value to parse
* @param {string} displayName - The name of the property. Used for error
* formatting.
* @returns {Array.<number | Error | null>}
*/
function parseDuration(
val : string,
displayName : string
) : [number | null,
MPDError | null] {
if (!isNonEmptyString(val)) {
const error = new MPDError(`\`${displayName}\` property is empty`);
return [0, error];
}
const match = iso8601Duration.exec(val) as RegExpExecArray;
if (match === null) {
const error = new MPDError(
`\`${displayName}\` property has an unrecognized format "${val}"`);
return [null, error];
}
const duration =
(parseFloat(isNonEmptyString(match[2]) ? match[2] :
"0") * 365 * 24 * 60 * 60 +
parseFloat(isNonEmptyString(match[4]) ? match[4] :
"0") * 30 * 24 * 60 * 60 +
parseFloat(isNonEmptyString(match[6]) ? match[6] :
"0") * 24 * 60 * 60 +
parseFloat(isNonEmptyString(match[8]) ? match[8] :
"0") * 60 * 60 +
parseFloat(isNonEmptyString(match[10]) ? match[10] :
"0") * 60 +
parseFloat(isNonEmptyString(match[12]) ? match[12] :
"0"));
return [duration, null];
}
/**
* Parse MPD byterange attributes into arrays of two elements: the start and
* the end.
*
* The returned value is a tuple of two elements where:
* 1. the first value is the parsed value - or `null` if we could not parse
* it
* 2. the second value is a possible error encountered while parsing this
* value - set to `null` if no error was encountered.
* @param {string} val
* @param {string} displayName
* @returns {Array.<Array.<number> | Error | null>}
*/
function parseByteRange(
val : string,
displayName : string
) : [ [number, number] | null, MPDError | null ] {
const match = rangeRe.exec(val);
if (match === null) {
const error = new MPDError(
`\`${displayName}\` property has an unrecognized format "${val}"`);
return [null, error];
} else {
return [[+match[1], +match[2]], null];
}
}
/**
* Parse MPD base64 attribute into an Uint8Array.
* the end.
*
* The returned value is a tuple of two elements where:
* 1. the first value is the parsed value - or `null` if we could not parse
* it
* 2. the second value is a possible error encountered while parsing this
* value - set to `null` if no error was encountered.
* @param {string} val
* @param {string} displayName
* @returns {Uint8Array | Error | null>}
*/
function parseBase64(
val : string,
displayName : string
) : [ Uint8Array | null, MPDError | null ] {
try {
return [base64ToBytes(val), null];
} catch (_) {
const error = new MPDError(
`\`${displayName}\` is not a valid base64 string: "${val}"`);
return [null, error];
}
}
/**
* @param {Element} root
* @returns {Object}
*/
function parseScheme(root: Element) : IScheme {
let schemeIdUri : string|undefined;
let value : string|undefined;
for (let i = 0; i < root.attributes.length; i++) {
const attribute = root.attributes[i];
switch (attribute.name) {
case "schemeIdUri":
schemeIdUri = attribute.value;
break;
case "value":
value = attribute.value;
break;
}
}
return { schemeIdUri,
value };
}
/**
* Create a function to factorize the MPD parsing logic.
* @param {Object} dest - The destination object which will contain the parsed
* values.
* @param {Array.<Error>} warnings - An array which will contain every parsing
* error encountered.
* @return {Function}
*/
function ValueParser<T>(
dest : T,
warnings : Error[]
) {
/**
* Parse a single value and add it to the `dest` objects.
* If an error arised while parsing, add it at the end of the `warnings` array.
* @param {string} objKey - The key which will be added to the `dest` object.
* @param {string} val - The value found in the MPD which we should parse.
* @param {Function} parsingFn - The parsing function adapted for this value.
* @param {string} displayName - The name of the key as it appears in the MPD.
* This is used only in error formatting,
*/
return function(
val : string,
{ asKey, parser, dashName } : {
asKey : keyof T;
parser : (
value : string,
displayName : string
) => [T[keyof T] | null, MPDError | null];
dashName : string;
}
) : void {
const [parsingResult, parsingError] = parser(val, dashName);
if (parsingError !== null) {
log.warn(parsingError.message);
warnings.push(parsingError);
}
if (parsingResult !== null) {
dest[asKey] = parsingResult;
}
};
}
/**
* Error arising when parsing the MPD.
* @class MPDError
* @extends Error
*/
class MPDError extends Error {
public readonly name : "MPDError";
public readonly message : string;
/**
* @param {string} message
*/
constructor(message : string) {
super();
// @see https://stackoverflow.com/questions/41102060/typescript-extending-error-class
Object.setPrototypeOf(this, MPDError.prototype);
this.name = "MPDError";
this.message = message;
}
}
export {
MPDError,
ValueParser,
parseBase64,
parseBoolean,
parseByteRange,
parseDateTime,
parseDuration,
parseIntOrBoolean,
parseMPDFloat,
parseMPDInteger,
parseScheme,
}; | the_stack |
import { Group, Path, Point, PointText, Raster, Size, view } from 'paper';
import i18next from 'i18next';
import PerspT from 'perspective-transform';
import { renderModal } from './modal';
import { createButton } from './createButton';
import { colors } from '../colors';
import { emitter } from '../emitter';
import { layers } from '../layers';
import { updateMapOverlay } from './screenshotOverlay';
import { loadImage } from '../load';
let switchMenu: paper.Group;
export function showSwitchModal(isShown) {
if (switchMenu == null) {
if (!isShown) return;
renderScreenshotModal();
}
switchMenu.data.show(isShown);
}
class ZoomCanvas {
private canvas: HTMLCanvasElement;
constructor(event: paper.MouseEvent, zoomLevel: number) {
const zoom = document.createElement("canvas");
zoom.height = 200;
zoom.width = 200;
zoom.style.position = 'absolute';
zoom.style.display = "block";
document.body.appendChild(zoom);
this.canvas = zoom;
this.update(event, zoomLevel, event.point);
}
public update(event, zoomLevel: number, pointGlobalPosition: paper.Point) {
const zoomSize = 100;
const zoom = this.canvas;
const pointCanvasPosition = layers.fixedLayer.globalToLocal(pointGlobalPosition);
zoom.getContext("2d")?.drawImage(view.element,
pointCanvasPosition.x * view.pixelRatio - zoomLevel * zoomSize * 0.5,
pointCanvasPosition.y * view.pixelRatio - zoomLevel * zoomSize * 0.5,
zoomLevel * zoomSize, zoomLevel * zoomSize,
0, 0, zoomSize * 2, zoomSize * 2);
if (event.event.touches) {
if (event.event.touches.length > 0) {
zoom.style.top = event.event.touches[0].pageY - 30 - zoomSize * 2 + "px";
zoom.style.left = event.event.touches[0].pageX - zoomSize + "px";
}
} else {
zoom.style.top = pointCanvasPosition.y - 10 - zoomSize * 2 + "px";
zoom.style.left = pointCanvasPosition.x - 10 - zoomSize * 2 + "px";
}
}
public remove() {
this.canvas.remove();
}
}
function renderScreenshotModal() {
const isMobile = Math.min(view.bounds.width * view.scaling.x, view.bounds.height * view.scaling.y) < 400;
const margin = isMobile ? 5 : 20;
switchMenu = renderModal(i18next.t('load_game_map'), margin, margin, function() {showSwitchModal(false)}, {fullscreen: true});
const uploadGroup = new Group();
uploadGroup.applyMatrix = false;
switchMenu.data.contents.addChild(uploadGroup);
{
var instructionImage = new Raster(
isMobile ? 'static/img/screenshot-instructions-mobile.png': 'static/img/screenshot-instructions.png');
instructionImage.scale(0.5);
instructionImage.onLoad = function() {
if (instructionImage.bounds.width > switchMenu.data.width) {
instructionImage.scale(switchMenu.data.width / instructionImage.width);
instructionImage.bounds.topCenter = new Point(0, 0);
}
if (instructionImage.bounds.height > switchMenu.data.height * 0.5) {
instructionImage.scale((switchMenu.data.height * 0.5) / instructionImage.height);
instructionImage.bounds.topCenter = new Point(0, 0);
}
const instructions = new PointText(instructionImage.bounds.bottomCenter.add(new Point(0, 60)));
instructions.justification = 'center';
instructions.fontFamily = 'TTNorms, sans-serif';
instructions.fontSize = isMobile ? 14 : 18;
instructions.fillColor = colors.text.color;
instructions.content = i18next.t('load_game_map_instructions');
const uploadIcon = new Raster('static/img/ui-upload-white.png');
uploadIcon.scale(0.4);
var uploadButton = createButton(uploadIcon, 30, function() {
loadImage(loadMapImage);
}, {
alpha: .9,
highlightedColor: colors.jaybird.color,
selectedColor: colors.blue.color,
disabledColor: colors.text.color,
});
uploadButton.position = instructions.position.add(new Point(0, 100));
uploadGroup.addChildren([instructionImage, instructions, uploadButton]);
uploadGroup.position = new Point(switchMenu.data.width / 2, switchMenu.data.height / 2);
};
}
const mapImageGroup = new Group();
mapImageGroup.applyMatrix = false;
switchMenu.data.contents.addChildren([mapImageGroup]);
let mapImage;
function loadMapImage(image) {
if (mapImage) mapImage.remove();
mapImage = new Raster(image);
mapImage.onLoad = function() {
uploadGroup.visible = false;
//var maxImageWidth = 700;
//var maxImageHeight = 700;
//var originalSize = new Size(mapImage.size);
//var scale = Math.min(maxImageWidth / mapImage.width, maxImageHeight / mapImage.height);
//console.log(maxImageWidth / mapImage.width, maxImageHeight / mapImage.height);
//var newSize = originalSize * scale;
//console.log(originalSize, scale, newSize)
//mapImage.scale(scale);
//var resampled = mapImage.rasterize(view.resolution / view.pixelRatio);
//resampled.smoothing=false;
//mapImage.remove();
//mapImage = resampled;
const newSize = mapImage.size;
const margin = isMobile ? -34 : 0;
mapImage.bounds.topLeft = new Point(0, 0);
const maxImageWidth = switchMenu.data.width - margin * 2;
const maxImageHeight = switchMenu.data.height - 100 - margin * 2; // need 100px for the button
mapImageGroup.scaling = new Point(1, 1);
mapImageGroup.scale(Math.min(maxImageWidth / newSize.width, maxImageHeight / newSize.height));
mapImageGroup.position = new Point(margin, 0);
const inverseScale = 1 / mapImageGroup.scaling.x;
const closeIcon = new Raster('static/img/ui-x.png');
closeIcon.scale(.5);
const closeButton = createButton(closeIcon, 24, function(){mapImage.data.remove()}, {
alpha: 0.9,
highlightedColor: colors.paperOverlay.color,
selectedColor: colors.paperOverlay2.color,
});
closeButton.scale(inverseScale);
closeButton.position = mapImage.bounds.topRight;
const confirmIcon = new Raster('static/img/ui-check-white.png');
confirmIcon.scale(0.5);
const confirmButton = createButton(confirmIcon, 30, function() {
mapImage.data.perspectiveWarp();
updateMapOverlay(mapImage.data.perspectiveWarpImage);
switchMenu.data.show(false);
}, {
alpha: .9,
highlightedColor: colors.jaybird.color,
selectedColor: colors.blue.color,
disabledColor: colors.text.color,
});
confirmButton.data.disable(true);
confirmButton.bounds.topCenter = mapImage.bounds.bottomCenter.add(new Point(0, 58 * inverseScale));
confirmButton.scale(inverseScale);
emitter.on('screenshot_update_point', function(pointCount) {
if (pointCount == 4) {
confirmButton.data.disable(false);
} else {
confirmButton.data.disable(true);
}
});
const mapImagePoints = new Group();
mapImageGroup.addChildren([mapImage, mapImagePoints, confirmButton]);
mapImageGroup.position = new Point(switchMenu.data.width / 2, switchMenu.data.height / 2);
mapImageGroup.addChild(closeButton);
mapImage.data.hoveredPoint = null;
mapImage.data.grabbedPoint = null;
mapImage.data.updateHoveredPoint = function(position) {
const point = this.points.find(function(point) {
return point.position.getDistance(position) < 80;
});
if (point != this.hoveredPoint) {
const oldPoint = this.hoveredPoint;
if (oldPoint) {
oldPoint.data.hover(false);
}
}
this.hoveredPoint = point;
if (point) {
point.data.hover(true);
}
return point;
}
mapImage.data.pointIndex = 0;
mapImage.data.points = [];
mapImage.onMouseMove = function(event) {
// retain the same point after grab has begun
if (this.data.grabbedPoint) return;
const rawCoordinate = mapImageGroup.globalToLocal(event.point);
this.data.updateHoveredPoint(rawCoordinate);
}
mapImage.onMouseDown = function(event) {
const rawCoordinate = mapImageGroup.globalToLocal(event.point);
this.data.updateHoveredPoint(rawCoordinate);
if (this.data.hoveredPoint) {
this.data.grabbedPoint = this.data.hoveredPoint;
this.data.grabbedPoint.data.select(true);
this.data.grabbedPoint.data.startPoint = rawCoordinate;
this.data.grabbedPoint.data.grabPivot = rawCoordinate.subtract(this.data.grabbedPoint.position);
}
if (mapImage.data.points.length < 4 && !this.data.grabbedPoint) {
const point = new Group();
point.pivot = new Point(0, 0);
point.applyMatrix = false;
point.addChildren([
new Path.Circle({
center: [0, 0],
radius: 1,
fillColor: colors.yellow.color,
}),
new Path({
segments: [[0, 3], [0, 8]],
strokeWidth: 1,
strokeColor: colors.yellow.color,
strokeCap: 'round',
}),
new Path({
segments: [[3, 0], [8, 0]],
strokeWidth: 1,
strokeColor: colors.yellow.color,
strokeCap: 'round',
}),
new Path({
segments: [[0, -3], [0, -8]],
strokeWidth: 1,
strokeColor: colors.yellow.color,
strokeCap: 'round',
}),
new Path({
segments: [[-3, 0], [-8, 0]],
strokeWidth: 1,
strokeColor: colors.yellow.color,
strokeCap: 'round',
}),
new Path.Circle({
center: [0, 0],
radius: 15,
fillColor: colors.invisible.color,
strokeColor: colors.yellow.color,
strokeWidth: 2,
}),
]);
point.scale(1 / mapImageGroup.scaling.x);
point.position = rawCoordinate;
point.data.startPoint = rawCoordinate;
point.data.grabPivot = new Point(0, 0);
point.locked = true;
point.data.updateColor = function() {
point.children.forEach(function(path) {
path.strokeColor =
point.data.selected ? colors.yellow.color
: point.data.hovered ? colors.lightYellow.color : colors.yellow.color;
})
}
point.data.hover = function(isHovered) {
point.data.hovered = isHovered;
point.data.updateColor();
}
point.data.select = function(isSelected) {
point.data.selected = isSelected;
point.data.updateColor();
if (isMobile) point.scale(isSelected ? 0.4 / mapImageGroup.scaling.x : 1 / mapImageGroup.scaling.x);
}
mapImagePoints.addChild(point);
mapImage.data.hoveredPoint = point;
mapImage.data.grabbedPoint = point;
point.data.hover(true);
point.data.select(true);
mapImage.data.pointIndex = mapImage.data.points.length;
mapImage.data.points[mapImage.data.pointIndex] = point;
emitter.emit('screenshot_update_point', mapImage.data.points.length);
}
if (this.data.grabbedPoint) {
var zoomLevel = Math.min(0.8, 4 * mapImageGroup.scaling.x) * view.pixelRatio;
mapImage.data.zoom = new ZoomCanvas(event, zoomLevel);
// wait for the point to appear before grabbing canvas
setTimeout(() => mapImage.data.zoom.update(event, zoomLevel, event.point), 100);
}
}
mapImage.onMouseDrag = function(event) {
const rawCoordinate = mapImageGroup.globalToLocal(event.point);
const point = mapImage.data.grabbedPoint;
if (point) {
const delta = rawCoordinate.subtract(point.data.startPoint);
point.position = point.data.startPoint.subtract(point.data.grabPivot).add(delta.multiply(isMobile ? 0.08 : 0.2));
var zoomLevel = Math.min(0.8, 4 * mapImageGroup.scaling.x) * view.pixelRatio;
mapImage.data.zoom.update(event, zoomLevel, mapImageGroup.localToGlobal(point.position));
if (this.data.outline) {
this.data.updateOutline();
}
}
}
mapImage.onMouseUp = function(event) {
if (mapImage.data.zoom) {
mapImage.data.zoom.remove();
mapImage.data.zoom = null;
}
if (this.data.grabbedPoint) {
this.data.grabbedPoint.data.select(false);
this.data.grabbedPoint = null;
}
if (event.event.touches && this.data.hoveredPoint) {
this.data.hoveredPoint.data.hover(false);
this.data.hoveredPoint = null;
}
if (mapImage.data.points.length == 4) {
this.data.updateOutline();
//this.data.perspectiveWarp();
}
}
mapImage.data.sortPoints = function() {
// reorder the points to clockwise starting from top left
{
var points = mapImage.data.points;
points.sort(function (a, b) {return a.position.y - b.position.y})
function slope(a, b) {
return (a.y - b.y) / (a.x - b.x);
}
// the top/bottom edge must contain the top point and has slope closest to zero
function getHorizontalEdge(point, otherPoints) {
otherPoints.sort(function(a, b) {return Math.abs(slope(a.position, point.position)) - Math.abs(slope(b.position, point.position))});
const edgePoint = otherPoints[0];
const edge = [edgePoint, point];
edge.sort(function(a, b){return a.position.x - b.position.x});
return edge;
}
const topEdge = getHorizontalEdge(points[0], points.slice(1, -1));
const bottomEdge = getHorizontalEdge(points[3], points.slice(1, -1));
mapImage.data.points = [
topEdge[0], topEdge[1], bottomEdge[1], bottomEdge[0]
];
}
}
mapImage.data.updateOutline = function() {
if (this.outline) {
this.outline.data.update();
return;
}
const outline = new Group();
outline.locked = true;
const rect = new Path();
rect.fillColor = colors.yellow.color;
rect.opacity = 0.3;
outline.data.rect = rect;
outline.addChild(rect);
const lines = new Group();
outline.data.lines = lines;
outline.addChild(lines);
outline.data.update = function() {
mapImage.data.sortPoints();
outline.data.rect.segments = mapImage.data.points.map(function(p) { return p.position});
if (!mapImage.data.flashingInterval) {
mapImage.data.flashingInterval = setInterval(function() {
if (uploadGroup.visible || !switchMenu.data.isShown()) {
clearInterval(mapImage.data.flashingInterval);
mapImage.data.flashingInterval = null;
return;
}
lines.opacity = lines.opacity == 0 ? 1 : 0;
}, 500);
}
const perspectiveTransformMatrix = PerspT(
[0, 0,
5, 0,
5, 4,
0, 4],
mapImage.data.points.reduce(function(acc, point) {
acc.push(point.position.x, point.position.y); return acc;
}, []));
function calculateLines(p0: paper.Point, p1: paper.Point, axis: paper.Point, numLines: number) {
var lines: Array<[number, number]> = [];
for (let i = 0; i < numLines; i++) {
const offset = new Point(axis.y, axis.x).multiply(1.1);
const pp0 = p0.add(axis.multiply(i)).subtract(offset);
const pp1 = p1.add(axis.multiply(i)).add(offset);
lines.push([
perspectiveTransformMatrix.transform(pp0.x, pp0.y),
perspectiveTransformMatrix.transform(pp1.x, pp1.y)]);
}
return lines;
}
function drawLinePath(points: [number, number], index: number) {
if (!outline.data.lines.children[index]) {
const line = new Path.Line(points);
line.strokeWidth = 1.5 / mapImageGroup.scaling.x;
line.strokeColor = colors.white.color.clone();
line.strokeColor.alpha = 0.3;
outline.data.lines.addChild(line);
}
outline.data.lines.children[index].segments = points;
}
let index = 0;
calculateLines(new Point(0, 0), new Point(0, 4),
new Point(1, 0), 6)
.forEach(function(line) {drawLinePath(line, index); index++})
calculateLines(new Point(0, 0), new Point(5, 0),
new Point(0, 1), 5)
.forEach(function(line) {drawLinePath(line, index); index++})
}.bind(this);
outline.data.update();
mapImageGroup.addChild(outline);
this.outline = outline;
}
mapImage.data.perspectiveWarp = function() {
return new Promise(function(onComplete) {
const resultSize = new Size(700, 600);
mapImage.data.sortPoints();
const perspectiveTransformMatrix = PerspT(
mapImage.data.points.reduce(function(acc, point) {
acc.push(point.position.x, point.position.y); return acc;
}, []),
[0, 0,
resultSize.width, 0,
resultSize.width, resultSize.height,
0, resultSize.height]);
const mapImageData = mapImage.getImageData(0, 0, mapImage.width, mapImage.height);
if (!mapImage.data.perspectiveWarpImage) {
mapImage.data.perspectiveWarpImage = new Raster(resultSize);
mapImageGroup.addChild(mapImage.data.perspectiveWarpImage);
mapImage.data.perspectiveWarpImage.position = mapImage.position;
//this.perspectiveWarpImage.scaling = 1 / mapImageGroup.scaling.x;
mapImage.data.perspectiveWarpImage.scaling = 16 * 7 / resultSize.width;
mapImage.data.perspectiveWarpImage.bounds.topCenter = mapImage.bounds.bottomCenter;
}
const context = mapImage.data.perspectiveWarpImage.context;
const xScale = 7 / 5;
const yScale = 6 / 4;
const imageData = context.createImageData(resultSize.width, resultSize.height)
for (let y = 0; y < resultSize.height; y++) {
const rowIndex = y * resultSize.width;
for (let x = 0; x < resultSize.width; x++) {
const index = (rowIndex + x) * 4;
// the points we want is actually an acre outside the bounds
const mapPosX = x * xScale - resultSize.width / 5;
const mapPosY = y * yScale - resultSize.height / 4;
const srcPt = perspectiveTransformMatrix.transformInverse(mapPosX, mapPosY);
const srcIndex = (Math.round(srcPt[0]) + Math.round(srcPt[1]) * mapImage.width) * 4;
//console.log(x, y, '->', Math.round(srcPt[0]), Math.round(srcPt[1]), srcIndex);
//var srcIndex = ((x) + (y + 10) * mapImage.width) * 4;
imageData.data[index] = mapImageData.data[srcIndex];
imageData.data[index+1] = mapImageData.data[srcIndex+1];
imageData.data[index+2] = mapImageData.data[srcIndex+2];
imageData.data[index+3] = mapImageData.data[srcIndex+3];
}
}
context.putImageData(imageData, 0, 0);
onComplete();
});
};
mapImage.data.remove = function() {
emitter.emit('screenshot_update_point', 0);
mapImageGroup.removeChildren();
uploadGroup.visible = true;
}
};
}
switchMenu.data.contents.addChildren([mapImageGroup]);
switchMenu.opacity = 0;
} | the_stack |
import { FloatArray, Nullable } from './types'
import { Vector3 } from './Vector3'
import { Quaternion } from './Quaternion'
import { MathTmp } from './preallocatedVariables'
import { Plane } from './Plane'
import { Vector4 } from './Vector4'
/**
* Class used to store matrix data (4x4)
* @public
*/
export class Matrix {
/**
* Gets the internal data of the matrix
*/
public get m(): Readonly<FloatArray> {
return this._m
}
/**
* Gets an identity matrix that must not be updated
*/
public static get IdentityReadOnly(): Readonly<Matrix> {
return Matrix._identityReadOnly
}
private static _updateFlagSeed = 0
private static _identityReadOnly = Matrix.Identity()
/**
* Gets the update flag of the matrix which is an unique number for the matrix.
* It will be incremented every time the matrix data change.
* You can use it to speed the comparison between two versions of the same matrix.
*/
public updateFlag!: number
private _isIdentity = false
private _isIdentityDirty = true
private _isIdentity3x2 = true
private _isIdentity3x2Dirty = true
private readonly _m: FloatArray = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
/**
* Creates an empty matrix (filled with zeros)
*/
public constructor() {
this._updateIdentityStatus(false)
}
// Statics
/**
* Creates a matrix from an array
* @param array - defines the source array
* @param offset - defines an offset in the source array
* @returns a new Matrix set from the starting index of the given array
*/
public static FromArray(array: ArrayLike<number>, offset: number = 0): Matrix {
let result = new Matrix()
Matrix.FromArrayToRef(array, offset, result)
return result
}
/**
* Copy the content of an array into a given matrix
* @param array - defines the source array
* @param offset - defines an offset in the source array
* @param result - defines the target matrix
*/
public static FromArrayToRef(array: ArrayLike<number>, offset: number, result: Matrix) {
for (let index = 0; index < 16; index++) {
result._m[index] = array[index + offset]
}
result._markAsUpdated()
}
/**
* Stores an array into a matrix after having multiplied each component by a given factor
* @param array - defines the source array
* @param offset - defines the offset in the source array
* @param scale - defines the scaling factor
* @param result - defines the target matrix
*/
public static FromFloatArrayToRefScaled(array: FloatArray, offset: number, scale: number, result: Matrix) {
for (let index = 0; index < 16; index++) {
result._m[index] = array[index + offset] * scale
}
result._markAsUpdated()
}
/**
* Stores a list of values (16) inside a given matrix
* @param initialM11 - defines 1st value of 1st row
* @param initialM12 - defines 2nd value of 1st row
* @param initialM13 - defines 3rd value of 1st row
* @param initialM14 - defines 4th value of 1st row
* @param initialM21 - defines 1st value of 2nd row
* @param initialM22 - defines 2nd value of 2nd row
* @param initialM23 - defines 3rd value of 2nd row
* @param initialM24 - defines 4th value of 2nd row
* @param initialM31 - defines 1st value of 3rd row
* @param initialM32 - defines 2nd value of 3rd row
* @param initialM33 - defines 3rd value of 3rd row
* @param initialM34 - defines 4th value of 3rd row
* @param initialM41 - defines 1st value of 4th row
* @param initialM42 - defines 2nd value of 4th row
* @param initialM43 - defines 3rd value of 4th row
* @param initialM44 - defines 4th value of 4th row
* @param result - defines the target matrix
*/
public static FromValuesToRef(
initialM11: number,
initialM12: number,
initialM13: number,
initialM14: number,
initialM21: number,
initialM22: number,
initialM23: number,
initialM24: number,
initialM31: number,
initialM32: number,
initialM33: number,
initialM34: number,
initialM41: number,
initialM42: number,
initialM43: number,
initialM44: number,
result: Matrix
): void {
const m = result._m
m[0] = initialM11
m[1] = initialM12
m[2] = initialM13
m[3] = initialM14
m[4] = initialM21
m[5] = initialM22
m[6] = initialM23
m[7] = initialM24
m[8] = initialM31
m[9] = initialM32
m[10] = initialM33
m[11] = initialM34
m[12] = initialM41
m[13] = initialM42
m[14] = initialM43
m[15] = initialM44
result._markAsUpdated()
}
/**
* Creates new matrix from a list of values (16)
* @param initialM11 - defines 1st value of 1st row
* @param initialM12 - defines 2nd value of 1st row
* @param initialM13 - defines 3rd value of 1st row
* @param initialM14 - defines 4th value of 1st row
* @param initialM21 - defines 1st value of 2nd row
* @param initialM22 - defines 2nd value of 2nd row
* @param initialM23 - defines 3rd value of 2nd row
* @param initialM24 - defines 4th value of 2nd row
* @param initialM31 - defines 1st value of 3rd row
* @param initialM32 - defines 2nd value of 3rd row
* @param initialM33 - defines 3rd value of 3rd row
* @param initialM34 - defines 4th value of 3rd row
* @param initialM41 - defines 1st value of 4th row
* @param initialM42 - defines 2nd value of 4th row
* @param initialM43 - defines 3rd value of 4th row
* @param initialM44 - defines 4th value of 4th row
* @returns the new matrix
*/
public static FromValues(
initialM11: number,
initialM12: number,
initialM13: number,
initialM14: number,
initialM21: number,
initialM22: number,
initialM23: number,
initialM24: number,
initialM31: number,
initialM32: number,
initialM33: number,
initialM34: number,
initialM41: number,
initialM42: number,
initialM43: number,
initialM44: number
): Matrix {
let result = new Matrix()
const m = result._m
m[0] = initialM11
m[1] = initialM12
m[2] = initialM13
m[3] = initialM14
m[4] = initialM21
m[5] = initialM22
m[6] = initialM23
m[7] = initialM24
m[8] = initialM31
m[9] = initialM32
m[10] = initialM33
m[11] = initialM34
m[12] = initialM41
m[13] = initialM42
m[14] = initialM43
m[15] = initialM44
result._markAsUpdated()
return result
}
/**
* Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
* @param scale - defines the scale vector3
* @param rotation - defines the rotation quaternion
* @param translation - defines the translation vector3
* @returns a new matrix
*/
public static Compose(scale: Vector3, rotation: Quaternion, translation: Vector3): Matrix {
let result = new Matrix()
Matrix.ComposeToRef(scale, rotation, translation, result)
return result
}
/**
* Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
* @param scale - defines the scale vector3
* @param rotation - defines the rotation quaternion
* @param translation - defines the translation vector3
* @param result - defines the target matrix
*/
public static ComposeToRef(scale: Vector3, rotation: Quaternion, translation: Vector3, result: Matrix): void {
Matrix.ScalingToRef(scale.x, scale.y, scale.z, MathTmp.Matrix[1])
rotation.toRotationMatrix(MathTmp.Matrix[0])
MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result)
result.setTranslation(translation)
}
/**
* Creates a new identity matrix
* @returns a new identity matrix
*/
public static Identity(): Matrix {
const identity = Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0)
identity._updateIdentityStatus(true)
return identity
}
/**
* Creates a new identity matrix and stores the result in a given matrix
* @param result - defines the target matrix
*/
public static IdentityToRef(result: Matrix): void {
Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result)
result._updateIdentityStatus(true)
}
/**
* Creates a new zero matrix
* @returns a new zero matrix
*/
public static Zero(): Matrix {
const zero = Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
zero._updateIdentityStatus(false)
return zero
}
/**
* Creates a new rotation matrix for "angle" radians around the X axis
* @param angle - defines the angle (in radians) to use
* @returns the new matrix
*/
public static RotationX(angle: number): Matrix {
let result = new Matrix()
Matrix.RotationXToRef(angle, result)
return result
}
/**
* Creates a new matrix as the invert of a given matrix
* @param source - defines the source matrix
* @returns the new matrix
*/
public static Invert(source: Matrix): Matrix {
let result = new Matrix()
source.invertToRef(result)
return result
}
/**
* Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
* @param angle - defines the angle (in radians) to use
* @param result - defines the target matrix
*/
public static RotationXToRef(angle: number, result: Matrix): void {
let s = Math.sin(angle)
let c = Math.cos(angle)
Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, result)
result._updateIdentityStatus(c === 1 && s === 0)
}
/**
* Creates a new rotation matrix for "angle" radians around the Y axis
* @param angle - defines the angle (in radians) to use
* @returns the new matrix
*/
public static RotationY(angle: number): Matrix {
let result = new Matrix()
Matrix.RotationYToRef(angle, result)
return result
}
/**
* Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
* @param angle - defines the angle (in radians) to use
* @param result - defines the target matrix
*/
public static RotationYToRef(angle: number, result: Matrix): void {
let s = Math.sin(angle)
let c = Math.cos(angle)
Matrix.FromValuesToRef(c, 0.0, -s, 0.0, 0.0, 1.0, 0.0, 0.0, s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0, result)
result._updateIdentityStatus(c === 1 && s === 0)
}
/**
* Creates a new rotation matrix for "angle" radians around the Z axis
* @param angle - defines the angle (in radians) to use
* @returns the new matrix
*/
public static RotationZ(angle: number): Matrix {
let result = new Matrix()
Matrix.RotationZToRef(angle, result)
return result
}
/**
* Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
* @param angle - defines the angle (in radians) to use
* @param result - defines the target matrix
*/
public static RotationZToRef(angle: number, result: Matrix): void {
let s = Math.sin(angle)
let c = Math.cos(angle)
Matrix.FromValuesToRef(c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result)
result._updateIdentityStatus(c === 1 && s === 0)
}
/**
* Creates a new rotation matrix for "angle" radians around the given axis
* @param axis - defines the axis to use
* @param angle - defines the angle (in radians) to use
* @returns the new matrix
*/
public static RotationAxis(axis: Vector3, angle: number): Matrix {
let result = new Matrix()
Matrix.RotationAxisToRef(axis, angle, result)
return result
}
/**
* Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
* @param axis - defines the axis to use
* @param angle - defines the angle (in radians) to use
* @param result - defines the target matrix
*/
public static RotationAxisToRef(axis: Vector3, angle: number, result: Matrix): void {
let s = Math.sin(-angle)
let c = Math.cos(-angle)
let c1 = 1 - c
axis.normalize()
const m = result._m
m[0] = axis.x * axis.x * c1 + c
m[1] = axis.x * axis.y * c1 - axis.z * s
m[2] = axis.x * axis.z * c1 + axis.y * s
m[3] = 0.0
m[4] = axis.y * axis.x * c1 + axis.z * s
m[5] = axis.y * axis.y * c1 + c
m[6] = axis.y * axis.z * c1 - axis.x * s
m[7] = 0.0
m[8] = axis.z * axis.x * c1 - axis.y * s
m[9] = axis.z * axis.y * c1 + axis.x * s
m[10] = axis.z * axis.z * c1 + c
m[11] = 0.0
m[12] = 0.0
m[13] = 0.0
m[14] = 0.0
m[15] = 1.0
result._markAsUpdated()
}
/**
* Creates a rotation matrix
* @param yaw - defines the yaw angle in radians (Y axis)
* @param pitch - defines the pitch angle in radians (X axis)
* @param roll - defines the roll angle in radians (X axis)
* @returns the new rotation matrix
*/
public static RotationYawPitchRoll(yaw: number, pitch: number, roll: number): Matrix {
let result = new Matrix()
Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result)
return result
}
/**
* Creates a rotation matrix and stores it in a given matrix
* @param yaw - defines the yaw angle in radians (Y axis)
* @param pitch - defines the pitch angle in radians (X axis)
* @param roll - defines the roll angle in radians (X axis)
* @param result - defines the target matrix
*/
public static RotationYawPitchRollToRef(yaw: number, pitch: number, roll: number, result: Matrix): void {
Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, MathTmp.Quaternion[0])
MathTmp.Quaternion[0].toRotationMatrix(result)
}
/**
* Creates a scaling matrix
* @param x - defines the scale factor on X axis
* @param y - defines the scale factor on Y axis
* @param z - defines the scale factor on Z axis
* @returns the new matrix
*/
public static Scaling(x: number, y: number, z: number): Matrix {
let result = new Matrix()
Matrix.ScalingToRef(x, y, z, result)
return result
}
/**
* Creates a scaling matrix and stores it in a given matrix
* @param x - defines the scale factor on X axis
* @param y - defines the scale factor on Y axis
* @param z - defines the scale factor on Z axis
* @param result - defines the target matrix
*/
public static ScalingToRef(x: number, y: number, z: number, result: Matrix): void {
Matrix.FromValuesToRef(x, 0.0, 0.0, 0.0, 0.0, y, 0.0, 0.0, 0.0, 0.0, z, 0.0, 0.0, 0.0, 0.0, 1.0, result)
result._updateIdentityStatus(x === 1 && y === 1 && z === 1)
}
/**
* Creates a translation matrix
* @param x - defines the translation on X axis
* @param y - defines the translation on Y axis
* @param z - defines the translationon Z axis
* @returns the new matrix
*/
public static Translation(x: number, y: number, z: number): Matrix {
let result = new Matrix()
Matrix.TranslationToRef(x, y, z, result)
return result
}
/**
* Creates a translation matrix and stores it in a given matrix
* @param x - defines the translation on X axis
* @param y - defines the translation on Y axis
* @param z - defines the translationon Z axis
* @param result - defines the target matrix
*/
public static TranslationToRef(x: number, y: number, z: number, result: Matrix): void {
Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result)
result._updateIdentityStatus(x === 0 && y === 0 && z === 0)
}
/**
* Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
* @param startValue - defines the start value
* @param endValue - defines the end value
* @param gradient - defines the gradient factor
* @returns the new matrix
*/
public static Lerp(startValue: Matrix, endValue: Matrix, gradient: number): Matrix {
let result = new Matrix()
Matrix.LerpToRef(startValue, endValue, gradient, result)
return result
}
/**
* Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
* @param startValue - defines the start value
* @param endValue - defines the end value
* @param gradient - defines the gradient factor
* @param result - defines the Matrix object where to store data
*/
public static LerpToRef(startValue: Matrix, endValue: Matrix, gradient: number, result: Matrix): void {
for (let index = 0; index < 16; index++) {
result._m[index] = startValue._m[index] * (1.0 - gradient) + endValue._m[index] * gradient
}
result._markAsUpdated()
}
/**
* Builds a new matrix whose values are computed by:
* * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
* * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
* * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
* @param startValue - defines the first matrix
* @param endValue - defines the second matrix
* @param gradient - defines the gradient between the two matrices
* @returns the new matrix
*/
public static DecomposeLerp(startValue: Matrix, endValue: Matrix, gradient: number): Matrix {
let result = new Matrix()
Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result)
return result
}
/**
* Update a matrix to values which are computed by:
* * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
* * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
* * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
* @param startValue - defines the first matrix
* @param endValue - defines the second matrix
* @param gradient - defines the gradient between the two matrices
* @param result - defines the target matrix
*/
public static DecomposeLerpToRef(startValue: Matrix, endValue: Matrix, gradient: number, result: Matrix) {
let startScale = MathTmp.Vector3[0]
let startRotation = MathTmp.Quaternion[0]
let startTranslation = MathTmp.Vector3[1]
startValue.decompose(startScale, startRotation, startTranslation)
let endScale = MathTmp.Vector3[2]
let endRotation = MathTmp.Quaternion[1]
let endTranslation = MathTmp.Vector3[3]
endValue.decompose(endScale, endRotation, endTranslation)
let resultScale = MathTmp.Vector3[4]
Vector3.LerpToRef(startScale, endScale, gradient, resultScale)
let resultRotation = MathTmp.Quaternion[2]
Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation)
let resultTranslation = MathTmp.Vector3[5]
Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation)
Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result)
}
/**
* Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
* This function works in left handed mode
* @param eye - defines the final position of the entity
* @param target - defines where the entity should look at
* @param up - defines the up vector for the entity
* @returns the new matrix
*/
public static LookAtLH(eye: Vector3, target: Vector3, up: Vector3): Matrix {
let result = new Matrix()
Matrix.LookAtLHToRef(eye, target, up, result)
return result
}
/**
* Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
* This function works in left handed mode
* @param eye - defines the final position of the entity
* @param target - defines where the entity should look at
* @param up - defines the up vector for the entity
* @param result - defines the target matrix
*/
public static LookAtLHToRef(eye: Vector3, target: Vector3, up: Vector3, result: Matrix): void {
const xAxis = MathTmp.Vector3[0]
const yAxis = MathTmp.Vector3[1]
const zAxis = MathTmp.Vector3[2]
// Z axis
target.subtractToRef(eye, zAxis)
zAxis.normalize()
// X axis
Vector3.CrossToRef(up, zAxis, xAxis)
const xSquareLength = xAxis.lengthSquared()
if (xSquareLength === 0) {
xAxis.x = 1.0
} else {
xAxis.normalizeFromLength(Math.sqrt(xSquareLength))
}
// Y axis
Vector3.CrossToRef(zAxis, xAxis, yAxis)
yAxis.normalize()
// Eye angles
let ex = -Vector3.Dot(xAxis, eye)
let ey = -Vector3.Dot(yAxis, eye)
let ez = -Vector3.Dot(zAxis, eye)
Matrix.FromValuesToRef(
xAxis.x,
yAxis.x,
zAxis.x,
0.0,
xAxis.y,
yAxis.y,
zAxis.y,
0.0,
xAxis.z,
yAxis.z,
zAxis.z,
0.0,
ex,
ey,
ez,
1.0,
result
)
}
/**
* Gets a new rotation matrix used to rotate an entity so as it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up"
* This function works in right handed mode
* @param eye - defines the final position of the entity
* @param target - defines where the entity should look at
* @param up - defines the up vector for the entity
* @returns the new matrix
*/
public static LookAtRH(eye: Vector3, target: Vector3, up: Vector3): Matrix {
let result = new Matrix()
Matrix.LookAtRHToRef(eye, target, up, result)
return result
}
/**
* Sets the given "result" Matrix to a rotation matrix used to rotate an entity so that it looks at the target vector3, from the eye vector3 position, the up vector3 being oriented like "up".
* This function works in right handed mode
* @param eye - defines the final position of the entity
* @param target - defines where the entity should look at
* @param up - defines the up vector for the entity
* @param result - defines the target matrix
*/
public static LookAtRHToRef(eye: Vector3, target: Vector3, up: Vector3, result: Matrix): void {
const xAxis = MathTmp.Vector3[0]
const yAxis = MathTmp.Vector3[1]
const zAxis = MathTmp.Vector3[2]
// Z axis
eye.subtractToRef(target, zAxis)
zAxis.normalize()
// X axis
Vector3.CrossToRef(up, zAxis, xAxis)
const xSquareLength = xAxis.lengthSquared()
if (xSquareLength === 0) {
xAxis.x = 1.0
} else {
xAxis.normalizeFromLength(Math.sqrt(xSquareLength))
}
// Y axis
Vector3.CrossToRef(zAxis, xAxis, yAxis)
yAxis.normalize()
// Eye angles
let ex = -Vector3.Dot(xAxis, eye)
let ey = -Vector3.Dot(yAxis, eye)
let ez = -Vector3.Dot(zAxis, eye)
Matrix.FromValuesToRef(
xAxis.x,
yAxis.x,
zAxis.x,
0.0,
xAxis.y,
yAxis.y,
zAxis.y,
0.0,
xAxis.z,
yAxis.z,
zAxis.z,
0.0,
ex,
ey,
ez,
1.0,
result
)
}
/**
* Create a left-handed orthographic projection matrix
* @param width - defines the viewport width
* @param height - defines the viewport height
* @param znear - defines the near clip plane
* @param zfar - defines the far clip plane
* @returns a new matrix as a left-handed orthographic projection matrix
*/
public static OrthoLH(width: number, height: number, znear: number, zfar: number): Matrix {
let matrix = new Matrix()
Matrix.OrthoLHToRef(width, height, znear, zfar, matrix)
return matrix
}
/**
* Store a left-handed orthographic projection to a given matrix
* @param width - defines the viewport width
* @param height - defines the viewport height
* @param znear - defines the near clip plane
* @param zfar - defines the far clip plane
* @param result - defines the target matrix
*/
public static OrthoLHToRef(width: number, height: number, znear: number, zfar: number, result: Matrix): void {
let n = znear
let f = zfar
let a = 2.0 / width
let b = 2.0 / height
let c = 2.0 / (f - n)
let d = -(f + n) / (f - n)
Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result)
result._updateIdentityStatus(a === 1 && b === 1 && c === 1 && d === 0)
}
/**
* Create a left-handed orthographic projection matrix
* @param left - defines the viewport left coordinate
* @param right - defines the viewport right coordinate
* @param bottom - defines the viewport bottom coordinate
* @param top - defines the viewport top coordinate
* @param znear - defines the near clip plane
* @param zfar - defines the far clip plane
* @returns a new matrix as a left-handed orthographic projection matrix
*/
public static OrthoOffCenterLH(
left: number,
right: number,
bottom: number,
top: number,
znear: number,
zfar: number
): Matrix {
let matrix = new Matrix()
Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix)
return matrix
}
/**
* Stores a left-handed orthographic projection into a given matrix
* @param left - defines the viewport left coordinate
* @param right - defines the viewport right coordinate
* @param bottom - defines the viewport bottom coordinate
* @param top - defines the viewport top coordinate
* @param znear - defines the near clip plane
* @param zfar - defines the far clip plane
* @param result - defines the target matrix
*/
public static OrthoOffCenterLHToRef(
left: number,
right: number,
bottom: number,
top: number,
znear: number,
zfar: number,
result: Matrix
): void {
let n = znear
let f = zfar
let a = 2.0 / (right - left)
let b = 2.0 / (top - bottom)
let c = 2.0 / (f - n)
let d = -(f + n) / (f - n)
let i0 = (left + right) / (left - right)
let i1 = (top + bottom) / (bottom - top)
Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result)
result._markAsUpdated()
}
/**
* Creates a right-handed orthographic projection matrix
* @param left - defines the viewport left coordinate
* @param right - defines the viewport right coordinate
* @param bottom - defines the viewport bottom coordinate
* @param top - defines the viewport top coordinate
* @param znear - defines the near clip plane
* @param zfar - defines the far clip plane
* @returns a new matrix as a right-handed orthographic projection matrix
*/
public static OrthoOffCenterRH(
left: number,
right: number,
bottom: number,
top: number,
znear: number,
zfar: number
): Matrix {
let matrix = new Matrix()
Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix)
return matrix
}
/**
* Stores a right-handed orthographic projection into a given matrix
* @param left - defines the viewport left coordinate
* @param right - defines the viewport right coordinate
* @param bottom - defines the viewport bottom coordinate
* @param top - defines the viewport top coordinate
* @param znear - defines the near clip plane
* @param zfar - defines the far clip plane
* @param result - defines the target matrix
*/
public static OrthoOffCenterRHToRef(
left: number,
right: number,
bottom: number,
top: number,
znear: number,
zfar: number,
result: Matrix
): void {
Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result)
result._m[10] *= -1 // No need to call _markAsUpdated as previous function already called it and let _isIdentityDirty to true
}
/**
* Creates a left-handed perspective projection matrix
* @param width - defines the viewport width
* @param height - defines the viewport height
* @param znear - defines the near clip plane
* @param zfar - defines the far clip plane
* @returns a new matrix as a left-handed perspective projection matrix
*/
public static PerspectiveLH(width: number, height: number, znear: number, zfar: number): Matrix {
let matrix = new Matrix()
let n = znear
let f = zfar
let a = (2.0 * n) / width
let b = (2.0 * n) / height
let c = (f + n) / (f - n)
let d = (-2.0 * f * n) / (f - n)
Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix)
matrix._updateIdentityStatus(false)
return matrix
}
/**
* Creates a left-handed perspective projection matrix
* @param fov - defines the horizontal field of view
* @param aspect - defines the aspect ratio
* @param znear - defines the near clip plane
* @param zfar - defines the far clip plane
* @returns a new matrix as a left-handed perspective projection matrix
*/
public static PerspectiveFovLH(fov: number, aspect: number, znear: number, zfar: number): Matrix {
let matrix = new Matrix()
Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix)
return matrix
}
/**
* Stores a left-handed perspective projection into a given matrix
* @param fov - defines the horizontal field of view
* @param aspect - defines the aspect ratio
* @param znear - defines the near clip plane
* @param zfar - defines the far clip plane
* @param result - defines the target matrix
* @param isVerticalFovFixed - defines it the fov is vertically fixed (default) or horizontally
*/
public static PerspectiveFovLHToRef(
fov: number,
aspect: number,
znear: number,
zfar: number,
result: Matrix,
isVerticalFovFixed = true
): void {
let n = znear
let f = zfar
let t = 1.0 / Math.tan(fov * 0.5)
let a = isVerticalFovFixed ? t / aspect : t
let b = isVerticalFovFixed ? t : t * aspect
let c = (f + n) / (f - n)
let d = (-2.0 * f * n) / (f - n)
Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result)
result._updateIdentityStatus(false)
}
/**
* Creates a right-handed perspective projection matrix
* @param fov - defines the horizontal field of view
* @param aspect - defines the aspect ratio
* @param znear - defines the near clip plane
* @param zfar - defines the far clip plane
* @returns a new matrix as a right-handed perspective projection matrix
*/
public static PerspectiveFovRH(fov: number, aspect: number, znear: number, zfar: number): Matrix {
let matrix = new Matrix()
Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix)
return matrix
}
/**
* Stores a right-handed perspective projection into a given matrix
* @param fov - defines the horizontal field of view
* @param aspect - defines the aspect ratio
* @param znear - defines the near clip plane
* @param zfar - defines the far clip plane
* @param result - defines the target matrix
* @param isVerticalFovFixed - defines it the fov is vertically fixed (default) or horizontally
*/
public static PerspectiveFovRHToRef(
fov: number,
aspect: number,
znear: number,
zfar: number,
result: Matrix,
isVerticalFovFixed = true
): void {
/* alternatively this could be expressed as:
// m = PerspectiveFovLHToRef
// m[10] *= -1.0;
// m[11] *= -1.0;
*/
let n = znear
let f = zfar
let t = 1.0 / Math.tan(fov * 0.5)
let a = isVerticalFovFixed ? t / aspect : t
let b = isVerticalFovFixed ? t : t * aspect
let c = -(f + n) / (f - n)
let d = (-2 * f * n) / (f - n)
Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result)
result._updateIdentityStatus(false)
}
/**
* Stores a perspective projection for WebVR info a given matrix
* @param fov - defines the field of view
* @param znear - defines the near clip plane
* @param zfar - defines the far clip plane
* @param result - defines the target matrix
* @param rightHanded - defines if the matrix must be in right-handed mode (false by default)
*/
public static PerspectiveFovWebVRToRef(
fov: { upDegrees: number; downDegrees: number; leftDegrees: number; rightDegrees: number },
znear: number,
zfar: number,
result: Matrix,
rightHanded = false
): void {
let rightHandedFactor = rightHanded ? -1 : 1
let upTan = Math.tan((fov.upDegrees * Math.PI) / 180.0)
let downTan = Math.tan((fov.downDegrees * Math.PI) / 180.0)
let leftTan = Math.tan((fov.leftDegrees * Math.PI) / 180.0)
let rightTan = Math.tan((fov.rightDegrees * Math.PI) / 180.0)
let xScale = 2.0 / (leftTan + rightTan)
let yScale = 2.0 / (upTan + downTan)
const m = result._m
m[0] = xScale
m[1] = m[2] = m[3] = m[4] = 0.0
m[5] = yScale
m[6] = m[7] = 0.0
m[8] = (leftTan - rightTan) * xScale * 0.5
m[9] = -((upTan - downTan) * yScale * 0.5)
m[10] = -zfar / (znear - zfar)
m[11] = 1.0 * rightHandedFactor
m[12] = m[13] = m[15] = 0.0
m[14] = -(2.0 * zfar * znear) / (zfar - znear)
result._markAsUpdated()
}
/**
* Extracts a 2x2 matrix from a given matrix and store the result in a FloatArray
* @param matrix - defines the matrix to use
* @returns a new FloatArray array with 4 elements : the 2x2 matrix extracted from the given matrix
*/
public static GetAsMatrix2x2(matrix: Matrix): FloatArray {
return [matrix._m[0], matrix._m[1], matrix._m[4], matrix._m[5]]
}
/**
* Extracts a 3x3 matrix from a given matrix and store the result in a FloatArray
* @param matrix - defines the matrix to use
* @returns a new FloatArray array with 9 elements : the 3x3 matrix extracted from the given matrix
*/
public static GetAsMatrix3x3(matrix: Matrix): FloatArray {
return [
matrix._m[0],
matrix._m[1],
matrix._m[2],
matrix._m[4],
matrix._m[5],
matrix._m[6],
matrix._m[8],
matrix._m[9],
matrix._m[10]
]
}
/**
* Compute the transpose of a given matrix
* @param matrix - defines the matrix to transpose
* @returns the new matrix
*/
public static Transpose(matrix: Matrix): Matrix {
let result = new Matrix()
Matrix.TransposeToRef(matrix, result)
return result
}
/**
* Compute the transpose of a matrix and store it in a target matrix
* @param matrix - defines the matrix to transpose
* @param result - defines the target matrix
*/
public static TransposeToRef(matrix: Matrix, result: Matrix): void {
const rm = result._m
const mm = matrix._m
rm[0] = mm[0]
rm[1] = mm[4]
rm[2] = mm[8]
rm[3] = mm[12]
rm[4] = mm[1]
rm[5] = mm[5]
rm[6] = mm[9]
rm[7] = mm[13]
rm[8] = mm[2]
rm[9] = mm[6]
rm[10] = mm[10]
rm[11] = mm[14]
rm[12] = mm[3]
rm[13] = mm[7]
rm[14] = mm[11]
rm[15] = mm[15]
// identity-ness does not change when transposing
result._updateIdentityStatus(matrix._isIdentity, matrix._isIdentityDirty)
}
/**
* Computes a reflection matrix from a plane
* @param plane - defines the reflection plane
* @returns a new matrix
*/
public static Reflection(plane: Plane): Matrix {
let matrix = new Matrix()
Matrix.ReflectionToRef(plane, matrix)
return matrix
}
/**
* Computes a reflection matrix from a plane
* @param plane - defines the reflection plane
* @param result - defines the target matrix
*/
public static ReflectionToRef(plane: Plane, result: Matrix): void {
plane.normalize()
let x = plane.normal.x
let y = plane.normal.y
let z = plane.normal.z
let temp = -2 * x
let temp2 = -2 * y
let temp3 = -2 * z
Matrix.FromValuesToRef(
temp * x + 1,
temp2 * x,
temp3 * x,
0.0,
temp * y,
temp2 * y + 1,
temp3 * y,
0.0,
temp * z,
temp2 * z,
temp3 * z + 1,
0.0,
temp * plane.d,
temp2 * plane.d,
temp3 * plane.d,
1.0,
result
)
}
/**
* Sets the given matrix as a rotation matrix composed from the 3 left handed axes
* @param xaxis - defines the value of the 1st axis
* @param yaxis - defines the value of the 2nd axis
* @param zaxis - defines the value of the 3rd axis
* @param result - defines the target matrix
*/
public static FromXYZAxesToRef(xaxis: Vector3, yaxis: Vector3, zaxis: Vector3, result: Matrix) {
Matrix.FromValuesToRef(
xaxis.x,
xaxis.y,
xaxis.z,
0.0,
yaxis.x,
yaxis.y,
yaxis.z,
0.0,
zaxis.x,
zaxis.y,
zaxis.z,
0.0,
0.0,
0.0,
0.0,
1.0,
result
)
}
/**
* Creates a rotation matrix from a quaternion and stores it in a target matrix
* @param quat - defines the quaternion to use
* @param result - defines the target matrix
*/
public static FromQuaternionToRef(quat: Quaternion, result: Matrix) {
let xx = quat.x * quat.x
let yy = quat.y * quat.y
let zz = quat.z * quat.z
let xy = quat.x * quat.y
let zw = quat.z * quat.w
let zx = quat.z * quat.x
let yw = quat.y * quat.w
let yz = quat.y * quat.z
let xw = quat.x * quat.w
result._m[0] = 1.0 - 2.0 * (yy + zz)
result._m[1] = 2.0 * (xy + zw)
result._m[2] = 2.0 * (zx - yw)
result._m[3] = 0.0
result._m[4] = 2.0 * (xy - zw)
result._m[5] = 1.0 - 2.0 * (zz + xx)
result._m[6] = 2.0 * (yz + xw)
result._m[7] = 0.0
result._m[8] = 2.0 * (zx + yw)
result._m[9] = 2.0 * (yz - xw)
result._m[10] = 1.0 - 2.0 * (yy + xx)
result._m[11] = 0.0
result._m[12] = 0.0
result._m[13] = 0.0
result._m[14] = 0.0
result._m[15] = 1.0
result._markAsUpdated()
}
/** @internal */
public _markAsUpdated() {
this.updateFlag = Matrix._updateFlagSeed++
this._isIdentity = false
this._isIdentity3x2 = false
this._isIdentityDirty = true
this._isIdentity3x2Dirty = true
}
// Properties
/**
* Check if the current matrix is identity
* @returns true is the matrix is the identity matrix
*/
public isIdentity(): boolean {
if (this._isIdentityDirty) {
this._isIdentityDirty = false
const m = this._m
this._isIdentity =
m[0] === 1.0 &&
m[1] === 0.0 &&
m[2] === 0.0 &&
m[3] === 0.0 &&
m[4] === 0.0 &&
m[5] === 1.0 &&
m[6] === 0.0 &&
m[7] === 0.0 &&
m[8] === 0.0 &&
m[9] === 0.0 &&
m[10] === 1.0 &&
m[11] === 0.0 &&
m[12] === 0.0 &&
m[13] === 0.0 &&
m[14] === 0.0 &&
m[15] === 1.0
}
return this._isIdentity
}
/**
* Check if the current matrix is identity as a texture matrix (3x2 store in 4x4)
* @returns true is the matrix is the identity matrix
*/
public isIdentityAs3x2(): boolean {
if (this._isIdentity3x2Dirty) {
this._isIdentity3x2Dirty = false
if (this._m[0] !== 1.0 || this._m[5] !== 1.0 || this._m[15] !== 1.0) {
this._isIdentity3x2 = false
} else if (
this._m[1] !== 0.0 ||
this._m[2] !== 0.0 ||
this._m[3] !== 0.0 ||
this._m[4] !== 0.0 ||
this._m[6] !== 0.0 ||
this._m[7] !== 0.0 ||
this._m[8] !== 0.0 ||
this._m[9] !== 0.0 ||
this._m[10] !== 0.0 ||
this._m[11] !== 0.0 ||
this._m[12] !== 0.0 ||
this._m[13] !== 0.0 ||
this._m[14] !== 0.0
) {
this._isIdentity3x2 = false
} else {
this._isIdentity3x2 = true
}
}
return this._isIdentity3x2
}
/**
* Gets the determinant of the matrix
* @returns the matrix determinant
*/
public determinant(): number {
if (this._isIdentity === true) {
return 1
}
const m = this._m
// tslint:disable-next-line:one-variable-per-declaration
const m00 = m[0],
m01 = m[1],
m02 = m[2],
m03 = m[3]
// tslint:disable-next-line:one-variable-per-declaration
const m10 = m[4],
m11 = m[5],
m12 = m[6],
m13 = m[7]
// tslint:disable-next-line:one-variable-per-declaration
const m20 = m[8],
m21 = m[9],
m22 = m[10],
m23 = m[11]
// tslint:disable-next-line:one-variable-per-declaration
const m30 = m[12],
m31 = m[13],
m32 = m[14],
m33 = m[15]
/*
// https://en.wikipedia.org/wiki/Laplace_expansion
// to compute the deterrminant of a 4x4 Matrix we compute the cofactors of any row or column,
// then we multiply each Cofactor by its corresponding matrix value and sum them all to get the determinant
// Cofactor(i, j) = sign(i,j) * det(Minor(i, j))
// where
// - sign(i,j) = (i+j) % 2 === 0 ? 1 : -1
// - Minor(i, j) is the 3x3 matrix we get by removing row i and column j from current Matrix
//
// Here we do that for the 1st row.
*/
// tslint:disable:variable-name
const det_22_33 = m22 * m33 - m32 * m23
const det_21_33 = m21 * m33 - m31 * m23
const det_21_32 = m21 * m32 - m31 * m22
const det_20_33 = m20 * m33 - m30 * m23
const det_20_32 = m20 * m32 - m22 * m30
const det_20_31 = m20 * m31 - m30 * m21
const cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32)
const cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32)
const cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31)
const cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31)
// tslint:enable:variable-name
return m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03
}
// Methods
/**
* Returns the matrix as a FloatArray
* @returns the matrix underlying array
*/
public toArray(): Readonly<FloatArray> {
return this._m
}
/**
* Returns the matrix as a FloatArray
* @returns the matrix underlying array.
*/
public asArray(): Readonly<FloatArray> {
return this._m
}
/**
* Inverts the current matrix in place
* @returns the current inverted matrix
*/
public invert(): Matrix {
this.invertToRef(this)
return this
}
/**
* Sets all the matrix elements to zero
* @returns the current matrix
*/
public reset(): Matrix {
Matrix.FromValuesToRef(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, this)
this._updateIdentityStatus(false)
return this
}
/**
* Adds the current matrix with a second one
* @param other - defines the matrix to add
* @returns a new matrix as the addition of the current matrix and the given one
*/
public add(other: Matrix): Matrix {
let result = new Matrix()
this.addToRef(other, result)
return result
}
/**
* Sets the given matrix "result" to the addition of the current matrix and the given one
* @param other - defines the matrix to add
* @param result - defines the target matrix
* @returns the current matrix
*/
public addToRef(other: Matrix, result: Matrix): Matrix {
for (let index = 0; index < 16; index++) {
result._m[index] = this._m[index] + other._m[index]
}
result._markAsUpdated()
return this
}
/**
* Adds in place the given matrix to the current matrix
* @param other - defines the second operand
* @returns the current updated matrix
*/
public addToSelf(other: Matrix): Matrix {
for (let index = 0; index < 16; index++) {
this._m[index] += other._m[index]
}
this._markAsUpdated()
return this
}
/**
* Sets the given matrix to the current inverted Matrix
* @param other - defines the target matrix
* @returns the unmodified current matrix
*/
public invertToRef(other: Matrix): Matrix {
if (this._isIdentity === true) {
Matrix.IdentityToRef(other)
return this
}
// the inverse of a Matrix is the transpose of cofactor matrix divided by the determinant
const m = this._m
// tslint:disable:one-variable-per-declaration
const m00 = m[0],
m01 = m[1],
m02 = m[2],
m03 = m[3]
const m10 = m[4],
m11 = m[5],
m12 = m[6],
m13 = m[7]
const m20 = m[8],
m21 = m[9],
m22 = m[10],
m23 = m[11]
const m30 = m[12],
m31 = m[13],
m32 = m[14],
m33 = m[15]
// tslint:enable:one-variable-per-declaration
// tslint:disable:variable-name
const det_22_33 = m22 * m33 - m32 * m23
const det_21_33 = m21 * m33 - m31 * m23
const det_21_32 = m21 * m32 - m31 * m22
const det_20_33 = m20 * m33 - m30 * m23
const det_20_32 = m20 * m32 - m22 * m30
const det_20_31 = m20 * m31 - m30 * m21
const cofact_00 = +(m11 * det_22_33 - m12 * det_21_33 + m13 * det_21_32)
const cofact_01 = -(m10 * det_22_33 - m12 * det_20_33 + m13 * det_20_32)
const cofact_02 = +(m10 * det_21_33 - m11 * det_20_33 + m13 * det_20_31)
const cofact_03 = -(m10 * det_21_32 - m11 * det_20_32 + m12 * det_20_31)
const det = m00 * cofact_00 + m01 * cofact_01 + m02 * cofact_02 + m03 * cofact_03
if (det === 0) {
// not invertible
other.copyFrom(this)
return this
}
const detInv = 1 / det
const det_12_33 = m12 * m33 - m32 * m13
const det_11_33 = m11 * m33 - m31 * m13
const det_11_32 = m11 * m32 - m31 * m12
const det_10_33 = m10 * m33 - m30 * m13
const det_10_32 = m10 * m32 - m30 * m12
const det_10_31 = m10 * m31 - m30 * m11
const det_12_23 = m12 * m23 - m22 * m13
const det_11_23 = m11 * m23 - m21 * m13
const det_11_22 = m11 * m22 - m21 * m12
const det_10_23 = m10 * m23 - m20 * m13
const det_10_22 = m10 * m22 - m20 * m12
const det_10_21 = m10 * m21 - m20 * m11
const cofact_10 = -(m01 * det_22_33 - m02 * det_21_33 + m03 * det_21_32)
const cofact_11 = +(m00 * det_22_33 - m02 * det_20_33 + m03 * det_20_32)
const cofact_12 = -(m00 * det_21_33 - m01 * det_20_33 + m03 * det_20_31)
const cofact_13 = +(m00 * det_21_32 - m01 * det_20_32 + m02 * det_20_31)
const cofact_20 = +(m01 * det_12_33 - m02 * det_11_33 + m03 * det_11_32)
const cofact_21 = -(m00 * det_12_33 - m02 * det_10_33 + m03 * det_10_32)
const cofact_22 = +(m00 * det_11_33 - m01 * det_10_33 + m03 * det_10_31)
const cofact_23 = -(m00 * det_11_32 - m01 * det_10_32 + m02 * det_10_31)
const cofact_30 = -(m01 * det_12_23 - m02 * det_11_23 + m03 * det_11_22)
const cofact_31 = +(m00 * det_12_23 - m02 * det_10_23 + m03 * det_10_22)
const cofact_32 = -(m00 * det_11_23 - m01 * det_10_23 + m03 * det_10_21)
const cofact_33 = +(m00 * det_11_22 - m01 * det_10_22 + m02 * det_10_21)
Matrix.FromValuesToRef(
cofact_00 * detInv,
cofact_10 * detInv,
cofact_20 * detInv,
cofact_30 * detInv,
cofact_01 * detInv,
cofact_11 * detInv,
cofact_21 * detInv,
cofact_31 * detInv,
cofact_02 * detInv,
cofact_12 * detInv,
cofact_22 * detInv,
cofact_32 * detInv,
cofact_03 * detInv,
cofact_13 * detInv,
cofact_23 * detInv,
cofact_33 * detInv,
other
)
// tslint:enable:variable-name
return this
}
/**
* add a value at the specified position in the current Matrix
* @param index - the index of the value within the matrix. between 0 and 15.
* @param value - the value to be added
* @returns the current updated matrix
*/
public addAtIndex(index: number, value: number): Matrix {
this._m[index] += value
this._markAsUpdated()
return this
}
/**
* mutiply the specified position in the current Matrix by a value
* @param index - the index of the value within the matrix. between 0 and 15.
* @param value - the value to be added
* @returns the current updated matrix
*/
public multiplyAtIndex(index: number, value: number): Matrix {
this._m[index] *= value
this._markAsUpdated()
return this
}
/**
* Inserts the translation vector (using 3 floats) in the current matrix
* @param x - defines the 1st component of the translation
* @param y - defines the 2nd component of the translation
* @param z - defines the 3rd component of the translation
* @returns the current updated matrix
*/
public setTranslationFromFloats(x: number, y: number, z: number): Matrix {
this._m[12] = x
this._m[13] = y
this._m[14] = z
this._markAsUpdated()
return this
}
/**
* Inserts the translation vector in the current matrix
* @param vector3 - defines the translation to insert
* @returns the current updated matrix
*/
public setTranslation(vector3: Vector3): Matrix {
return this.setTranslationFromFloats(vector3.x, vector3.y, vector3.z)
}
/**
* Gets the translation value of the current matrix
* @returns a new Vector3 as the extracted translation from the matrix
*/
public getTranslation(): Vector3 {
return new Vector3(this._m[12], this._m[13], this._m[14])
}
/**
* Fill a Vector3 with the extracted translation from the matrix
* @param result - defines the Vector3 where to store the translation
* @returns the current matrix
*/
public getTranslationToRef(result: Vector3): Matrix {
result.x = this._m[12]
result.y = this._m[13]
result.z = this._m[14]
return this
}
/**
* Remove rotation and scaling part from the matrix
* @returns the updated matrix
*/
public removeRotationAndScaling(): Matrix {
const m = this.m
Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, m[12], m[13], m[14], m[15], this)
this._updateIdentityStatus(m[12] === 0 && m[13] === 0 && m[14] === 0 && m[15] === 1)
return this
}
/**
* Multiply two matrices
* @param other - defines the second operand
* @returns a new matrix set with the multiplication result of the current Matrix and the given one
*/
public multiply(other: Readonly<Matrix>): Matrix {
let result = new Matrix()
this.multiplyToRef(other, result)
return result
}
/**
* Copy the current matrix from the given one
* @param other - defines the source matrix
* @returns the current updated matrix
*/
public copyFrom(other: Readonly<Matrix>): Matrix {
other.copyToArray(this._m)
const o = other as Matrix
this._updateIdentityStatus(o._isIdentity, o._isIdentityDirty, o._isIdentity3x2, o._isIdentity3x2Dirty)
return this
}
/**
* Populates the given array from the starting index with the current matrix values
* @param array - defines the target array
* @param offset - defines the offset in the target array where to start storing values
* @returns the current matrix
*/
public copyToArray(array: FloatArray, offset: number = 0): Matrix {
for (let index = 0; index < 16; index++) {
array[offset + index] = this._m[index]
}
return this
}
/**
* Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
* @param other - defines the second operand
* @param result - defines the matrix where to store the multiplication
* @returns the current matrix
*/
public multiplyToRef(other: Readonly<Matrix>, result: Matrix): Matrix {
if (this._isIdentity) {
result.copyFrom(other)
return this
}
if ((other as Matrix)._isIdentity) {
result.copyFrom(this)
return this
}
this.multiplyToArray(other, result._m, 0)
result._markAsUpdated()
return this
}
/**
* Sets the FloatArray "result" from the given index "offset" with the multiplication of the current matrix and the given one
* @param other - defines the second operand
* @param result - defines the array where to store the multiplication
* @param offset - defines the offset in the target array where to start storing values
* @returns the current matrix
*/
public multiplyToArray(other: Readonly<Matrix>, result: FloatArray, offset: number): Matrix {
const m = this._m
const otherM = other.m
// tslint:disable:one-variable-per-declaration
let tm0 = m[0],
tm1 = m[1],
tm2 = m[2],
tm3 = m[3]
let tm4 = m[4],
tm5 = m[5],
tm6 = m[6],
tm7 = m[7]
let tm8 = m[8],
tm9 = m[9],
tm10 = m[10],
tm11 = m[11]
let tm12 = m[12],
tm13 = m[13],
tm14 = m[14],
tm15 = m[15]
let om0 = otherM[0],
om1 = otherM[1],
om2 = otherM[2],
om3 = otherM[3]
let om4 = otherM[4],
om5 = otherM[5],
om6 = otherM[6],
om7 = otherM[7]
let om8 = otherM[8],
om9 = otherM[9],
om10 = otherM[10],
om11 = otherM[11]
let om12 = otherM[12],
om13 = otherM[13],
om14 = otherM[14],
om15 = otherM[15]
// tslint:enable:one-variable-per-declaration
result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12
result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13
result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14
result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15
result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12
result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13
result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14
result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15
result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12
result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13
result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14
result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15
result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12
result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13
result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14
result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15
return this
}
/**
* Check equality between this matrix and a second one
* @param value - defines the second matrix to compare
* @returns true is the current matrix and the given one values are strictly equal
*/
public equals(value: Matrix): boolean {
const other = value
if (!other) {
return false
}
if (this._isIdentity || other._isIdentity) {
if (!this._isIdentityDirty && !other._isIdentityDirty) {
return this._isIdentity && other._isIdentity
}
}
const m = this.m
const om = other.m
return (
m[0] === om[0] &&
m[1] === om[1] &&
m[2] === om[2] &&
m[3] === om[3] &&
m[4] === om[4] &&
m[5] === om[5] &&
m[6] === om[6] &&
m[7] === om[7] &&
m[8] === om[8] &&
m[9] === om[9] &&
m[10] === om[10] &&
m[11] === om[11] &&
m[12] === om[12] &&
m[13] === om[13] &&
m[14] === om[14] &&
m[15] === om[15]
)
}
/**
* Clone the current matrix
* @returns a new matrix from the current matrix
*/
public clone(): Matrix {
const matrix = new Matrix()
matrix.copyFrom(this)
return matrix
}
/**
* Returns the name of the current matrix class
* @returns the string "Matrix"
*/
public getClassName(): string {
return 'Matrix'
}
/**
* Gets the hash code of the current matrix
* @returns the hash code
*/
public getHashCode(): number {
let hash = this._m[0] || 0
for (let i = 1; i < 16; i++) {
hash = (hash * 397) ^ (this._m[i] || 0)
}
return hash
}
/**
* Decomposes the current Matrix into a translation, rotation and scaling components
* @param scale - defines the scale vector3 given as a reference to update
* @param rotation - defines the rotation quaternion given as a reference to update
* @param translation - defines the translation vector3 given as a reference to update
* @returns true if operation was successful
*/
public decompose(scale?: Vector3, rotation?: Quaternion, translation?: Vector3): boolean {
if (this._isIdentity) {
if (translation) {
translation.setAll(0)
}
if (scale) {
scale.setAll(1)
}
if (rotation) {
rotation.copyFromFloats(0, 0, 0, 1)
}
return true
}
const m = this._m
if (translation) {
translation.copyFromFloats(m[12], m[13], m[14])
}
const usedScale = scale || MathTmp.Vector3[0]
usedScale.x = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2])
usedScale.y = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6])
usedScale.z = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10])
if (this.determinant() <= 0) {
usedScale.y *= -1
}
if (usedScale.x === 0 || usedScale.y === 0 || usedScale.z === 0) {
if (rotation) {
rotation.copyFromFloats(0.0, 0.0, 0.0, 1.0)
}
return false
}
if (rotation) {
// tslint:disable-next-line:one-variable-per-declaration
const sx = 1 / usedScale.x,
sy = 1 / usedScale.y,
sz = 1 / usedScale.z
Matrix.FromValuesToRef(
m[0] * sx,
m[1] * sx,
m[2] * sx,
0.0,
m[4] * sy,
m[5] * sy,
m[6] * sy,
0.0,
m[8] * sz,
m[9] * sz,
m[10] * sz,
0.0,
0.0,
0.0,
0.0,
1.0,
MathTmp.Matrix[0]
)
Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation)
}
return true
}
/**
* Gets specific row of the matrix
* @param index - defines the number of the row to get
* @returns the index-th row of the current matrix as a new Vector4
*/
public getRow(index: number): Nullable<Vector4> {
if (index < 0 || index > 3) {
return null
}
let i = index * 4
return new Vector4(this._m[i + 0], this._m[i + 1], this._m[i + 2], this._m[i + 3])
}
/**
* Sets the index-th row of the current matrix to the vector4 values
* @param index - defines the number of the row to set
* @param row - defines the target vector4
* @returns the updated current matrix
*/
public setRow(index: number, row: Vector4): Matrix {
return this.setRowFromFloats(index, row.x, row.y, row.z, row.w)
}
/**
* Compute the transpose of the matrix
* @returns the new transposed matrix
*/
public transpose(): Matrix {
return Matrix.Transpose(this)
}
/**
* Compute the transpose of the matrix and store it in a given matrix
* @param result - defines the target matrix
* @returns the current matrix
*/
public transposeToRef(result: Matrix): Matrix {
Matrix.TransposeToRef(this, result)
return this
}
/**
* Sets the index-th row of the current matrix with the given 4 x float values
* @param index - defines the row index
* @param x - defines the x component to set
* @param y - defines the y component to set
* @param z - defines the z component to set
* @param w - defines the w component to set
* @returns the updated current matrix
*/
public setRowFromFloats(index: number, x: number, y: number, z: number, w: number): Matrix {
if (index < 0 || index > 3) {
return this
}
let i = index * 4
this._m[i + 0] = x
this._m[i + 1] = y
this._m[i + 2] = z
this._m[i + 3] = w
this._markAsUpdated()
return this
}
/**
* Compute a new matrix set with the current matrix values multiplied by scale (float)
* @param scale - defines the scale factor
* @returns a new matrix
*/
public scale(scale: number): Matrix {
let result = new Matrix()
this.scaleToRef(scale, result)
return result
}
/**
* Scale the current matrix values by a factor to a given result matrix
* @param scale - defines the scale factor
* @param result - defines the matrix to store the result
* @returns the current matrix
*/
public scaleToRef(scale: number, result: Matrix): Matrix {
for (let index = 0; index < 16; index++) {
result._m[index] = this._m[index] * scale
}
result._markAsUpdated()
return this
}
/**
* Scale the current matrix values by a factor and add the result to a given matrix
* @param scale - defines the scale factor
* @param result - defines the Matrix to store the result
* @returns the current matrix
*/
public scaleAndAddToRef(scale: number, result: Matrix): Matrix {
for (let index = 0; index < 16; index++) {
result._m[index] += this._m[index] * scale
}
result._markAsUpdated()
return this
}
/**
* Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
* @param ref - matrix to store the result
*/
public toNormalMatrix(ref: Matrix): void {
const tmp = MathTmp.Matrix[0]
this.invertToRef(tmp)
tmp.transposeToRef(ref)
let m = ref._m
Matrix.FromValuesToRef(
m[0],
m[1],
m[2],
0.0,
m[4],
m[5],
m[6],
0.0,
m[8],
m[9],
m[10],
0.0,
0.0,
0.0,
0.0,
1.0,
ref
)
}
/**
* Gets only rotation part of the current matrix
* @returns a new matrix sets to the extracted rotation matrix from the current one
*/
public getRotationMatrix(): Matrix {
let result = new Matrix()
this.getRotationMatrixToRef(result)
return result
}
/**
* Extracts the rotation matrix from the current one and sets it as the given "result"
* @param result - defines the target matrix to store data to
* @returns the current matrix
*/
public getRotationMatrixToRef(result: Matrix): Matrix {
const scale = MathTmp.Vector3[0]
if (!this.decompose(scale)) {
Matrix.IdentityToRef(result)
return this
}
const m = this._m
// tslint:disable-next-line:one-variable-per-declaration
const sx = 1 / scale.x,
sy = 1 / scale.y,
sz = 1 / scale.z
Matrix.FromValuesToRef(
m[0] * sx,
m[1] * sx,
m[2] * sx,
0.0,
m[4] * sy,
m[5] * sy,
m[6] * sy,
0.0,
m[8] * sz,
m[9] * sz,
m[10] * sz,
0.0,
0.0,
0.0,
0.0,
1.0,
result
)
return this
}
/**
* Toggles model matrix from being right handed to left handed in place and vice versa
*/
public toggleModelMatrixHandInPlace() {
const m = this._m
m[2] *= -1
m[6] *= -1
m[8] *= -1
m[9] *= -1
m[14] *= -1
this._markAsUpdated()
}
/**
* Toggles projection matrix from being right handed to left handed in place and vice versa
*/
public toggleProjectionMatrixHandInPlace() {
let m = this._m
m[8] *= -1
m[9] *= -1
m[10] *= -1
m[11] *= -1
this._markAsUpdated()
}
/** @internal */
private _updateIdentityStatus(
isIdentity: boolean,
isIdentityDirty: boolean = false,
isIdentity3x2: boolean = false,
isIdentity3x2Dirty: boolean = true
) {
this.updateFlag = Matrix._updateFlagSeed++
this._isIdentity = isIdentity
this._isIdentity3x2 = isIdentity || isIdentity3x2
this._isIdentityDirty = this._isIdentity ? false : isIdentityDirty
this._isIdentity3x2Dirty = this._isIdentity3x2 ? false : isIdentity3x2Dirty
}
} | the_stack |
import * as React from "react"
import { Formik, Form, FastField, Field } from "formik"
import * as Yup from "yup"
import { RouteComponentProps } from "react-router-dom"
import {
FormGroup,
Button,
Intent,
Spinner,
Classes,
RadioGroup,
Radio,
Collapse,
} from "@blueprintjs/core"
import api from "../api"
import {
TemplateExecutionRequest,
Run,
ExecutionEngine,
Template,
} from "../types"
import Request, {
ChildProps as RequestChildProps,
RequestStatus,
} from "./Request"
import EnvFieldArray from "./EnvFieldArray"
import ClusterSelect from "./ClusterSelect"
import { TemplateContext, TemplateCtx } from "./Template"
import Toaster from "./Toaster"
import ErrorCallout from "./ErrorCallout"
import FieldError from "./FieldError"
import NodeLifecycleSelect from "./NodeLifecycleSelect"
import * as helpers from "../helpers/runFormHelpers"
import { useSelector } from "react-redux"
import { RootState } from "../state/store"
import JSONSchemaForm, {
FieldTemplateProps,
UiSchema,
ArrayFieldTemplateProps,
} from "react-jsonschema-form"
const getInitialValuesForTemplateRun = (): TemplateExecutionRequest => {
return {
template_payload: {},
cluster: "",
env: [],
owner_id: "",
memory: 512,
cpu: 512,
engine: ExecutionEngine.EKS,
}
}
const validationSchema = Yup.object().shape({
owner_id: Yup.string(),
cluster: Yup.string().required("Required"),
memory: Yup.number()
.required("Required")
.min(0),
cpu: Yup.number()
.required("Required")
.min(512),
env: Yup.array().of(
Yup.object().shape({
name: Yup.string().required(),
value: Yup.string().required(),
})
),
engine: Yup.string()
.matches(/(eks|ecs)/)
.required("A valid engine type of ecs or eks must be set."),
node_lifecycle: Yup.string().matches(/(spot|ondemand)/),
template_payload: Yup.object().required("template_payload is required"),
})
type Props = RequestChildProps<
Run,
{ templateID: string; data: TemplateExecutionRequest }
> & {
templateID: string
initialValues: TemplateExecutionRequest
template: Template
}
const FieldTemplate: React.FC<FieldTemplateProps> = props => {
return (
<FormGroup
label={props.label}
helperText={props.description}
labelInfo={props.required ? "(Required)" : ""}
>
{props.children}
</FormGroup>
)
}
const ArrayFieldTemplate: React.FC<ArrayFieldTemplateProps> = props => {
return (
<div>
{props.items.map((element, i) =>
React.cloneElement(element.children, { key: i })
)}
{props.canAdd && (
<Button type="button" onClick={props.onAddClick} icon="plus" fill>
Add {props.title}
</Button>
)}
</div>
)
}
class RunForm extends React.Component<Props> {
private FORMIK_REF = React.createRef<Formik<TemplateExecutionRequest>>()
// Note: this method is a bit hacky as we have two form elements - Formik (F)
// and JSONSchemaForm (J). F does not have a submit button, J does. When J's
// submit button is clicked, this method is called. We get the values of the
// F form via the `FORMIK_REF` ref binding. Then we take the J form's values
// and shove them into F form's `template_payload` field. This request is
// then sent to the server.
onSubmit(jsonschemaForm: any) {
if (this.FORMIK_REF.current) {
const formikValues = this.FORMIK_REF.current.state.values
formikValues["template_payload"] = jsonschemaForm
this.props.request({
templateID: this.props.templateID,
data: formikValues,
})
}
}
render() {
const {
initialValues,
request,
requestStatus,
isLoading,
error,
templateID,
template,
} = this.props
return (
<div className="flotilla-form-container">
<Formik<TemplateExecutionRequest>
ref={this.FORMIK_REF}
isInitialValid={(values: any) =>
validationSchema.isValidSync(values.initialValues)
}
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={data => {}}
>
{({ errors, values, setFieldValue, isValid, ...rest }) => {
const getEngine = (): ExecutionEngine => values.engine
return (
<Form>
{requestStatus === RequestStatus.ERROR && error && (
<ErrorCallout error={error} />
)}
{/* Owner ID Field */}
<FormGroup
label={helpers.ownerIdFieldSpec.label}
helperText={helpers.ownerIdFieldSpec.description}
>
<FastField
name={helpers.ownerIdFieldSpec.name}
value={values.owner_id}
className={Classes.INPUT}
/>
{errors.owner_id && (
<FieldError>{errors.owner_id}</FieldError>
)}
</FormGroup>
<div className="flotilla-form-section-divider" />
{/* Engine Type Field */}
<RadioGroup
inline
label="Engine Type"
onChange={(evt: React.FormEvent<HTMLInputElement>) => {
setFieldValue("engine", evt.currentTarget.value)
if (evt.currentTarget.value === ExecutionEngine.EKS) {
setFieldValue(
"cluster",
process.env.REACT_APP_EKS_CLUSTER_NAME || ""
)
} else if (getEngine() === ExecutionEngine.EKS) {
setFieldValue("cluster", "")
}
}}
selectedValue={values.engine}
>
<Radio label="EKS" value={ExecutionEngine.EKS} />
<Radio label="ECS" value={ExecutionEngine.ECS} />
</RadioGroup>
<div className="flotilla-form-section-divider" />
{/*
Cluster Field. Note: this is a "Field" rather than a
"FastField" as it needs to re-render when value.engine is
updated.
*/}
{getEngine() !== ExecutionEngine.EKS && (
<FormGroup
label="Cluster"
helperText="Select a cluster for this task to execute on."
>
<Field
name="cluster"
component={ClusterSelect}
value={values.cluster}
onChange={(value: string) => {
setFieldValue("cluster", value)
}}
/>
{errors.cluster && (
<FieldError>{errors.cluster}</FieldError>
)}
</FormGroup>
)}
{/* CPU Field */}
<FormGroup
label={helpers.cpuFieldSpec.label}
helperText={helpers.cpuFieldSpec.description}
>
<FastField
type="number"
name={helpers.cpuFieldSpec.name}
className={Classes.INPUT}
min="512"
/>
{errors.cpu && <FieldError>{errors.cpu}</FieldError>}
</FormGroup>
{/* Memory Field */}
<FormGroup
label={helpers.memoryFieldSpec.label}
helperText={helpers.memoryFieldSpec.description}
>
<FastField
type="number"
name={helpers.memoryFieldSpec.name}
className={Classes.INPUT}
/>
{errors.memory && <FieldError>{errors.memory}</FieldError>}
</FormGroup>
<div className="flotilla-form-section-divider" />
{/* Node Lifecycle Field */}
<FormGroup
label="Node Lifecycle"
helperText="This field is only applicable to tasks running on EKS. For more information, please view this document: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances.html"
>
<Field
name="node_lifecycle"
component={NodeLifecycleSelect}
value={values.node_lifecycle}
onChange={(value: string) => {
setFieldValue("node_lifecycle", value)
}}
isDisabled={getEngine() !== ExecutionEngine.EKS}
/>
{errors.node_lifecycle && (
<FieldError>{errors.node_lifecycle}</FieldError>
)}
</FormGroup>
<div className="flotilla-form-section-divider" />
<EnvFieldArray />
</Form>
)
}}
</Formik>
<div className="flotilla-form-section-divider" />
<JSONSchemaForm
schema={template.schema}
onSubmit={({ formData }) => {
this.onSubmit(formData)
}}
onError={() => console.log("errors")}
FieldTemplate={FieldTemplate}
ArrayFieldTemplate={ArrayFieldTemplate}
widgets={{
BaseInput: props => {
return (
<input
className="bp3-input"
value={props.value}
required={props.required}
onChange={evt => {
props.onChange(evt.target.value)
}}
/>
)
},
}}
>
<Button
intent={Intent.PRIMARY}
type="submit"
disabled={isLoading}
style={{ marginTop: 24 }}
large
fill
>
Submit
</Button>
</JSONSchemaForm>
</div>
)
}
}
const Connected: React.FunctionComponent<RouteComponentProps> = ({
history,
}) => {
return (
<Request<Run, { templateID: string; data: TemplateExecutionRequest }>
requestFn={api.runTemplate}
shouldRequestOnMount={false}
onSuccess={(data: Run) => {
Toaster.show({
message: `Run ${data.run_id} submitted successfully!`,
intent: Intent.SUCCESS,
})
history.push(`/runs/${data.run_id}`)
}}
onFailure={() => {
Toaster.show({
message: "An error occurred.",
intent: Intent.DANGER,
})
}}
>
{requestProps => (
<TemplateContext.Consumer>
{(ctx: TemplateCtx) => {
switch (ctx.requestStatus) {
case RequestStatus.ERROR:
return <ErrorCallout error={ctx.error} />
case RequestStatus.READY:
if (ctx.data) {
const initialValues: TemplateExecutionRequest = getInitialValuesForTemplateRun()
return (
<RunForm
templateID={ctx.templateID}
initialValues={initialValues}
template={ctx.data}
{...requestProps}
/>
)
}
break
case RequestStatus.NOT_READY:
default:
return <Spinner />
}
}}
</TemplateContext.Consumer>
)}
</Request>
)
}
export default Connected | the_stack |
import { IEquals, IllegalArgumentError } from "funfix-core"
/**
* A `TimeUnit` represents time durations at a given unit of
* granularity and provides utility methods to convert across units,
* and to perform timing and delay operations in these units.
*
* A `TimeUnit` does not maintain time information, but only helps
* organize and use time representations that may be maintained
* separately across various contexts. A nanosecond is defined as one
* thousandth of a microsecond, a microsecond as one thousandth of a
* millisecond, a millisecond as one thousandth of a second, a minute
* as sixty seconds, an hour as sixty minutes, and a day as twenty
* four hours.
*
* `TimeUnit` is an enumeration and in usage the already defined
* constants should be used:
*
* - [[NANOSECONDS]]
* - [[MICROSECONDS]]
* - [[MILLISECONDS]]
* - [[SECONDS]]
* - [[MINUTES]]
* - [[HOURS]]
* - [[DAYS]]
*
* Example:
*
* ```typescript
* // Converting 10 minutes to nanoseconds
* MINUTES.toNanos(10)
* // Equivalent with the above:
* NANOSECONDS.convert(10, MINUTES)
* ```
*/
export abstract class TimeUnit {
/**
* Converts the given time duration in the given unit to this unit.
* Conversions from finer to coarser granularities truncate, so lose
* precision. For example, converting `999` milliseconds to seconds
* results in `0`. Conversions from coarser to finer granularities
* with arguments that would numerically overflow saturate to
* `Number.MAX_VALUE` if negative or `MAX_VALUE` if positive.
*
* For example, to convert 10 minutes to milliseconds, use:
*
* ```typescript
* MILLISECONDS.convert(10, MINUTES)
* // ... or ...
* MINUTES.toMillis(10)
* ```
*
* @param duration the time duration in the given `unit`
* @param unit the unit of the `duration` argument
*
* @return the converted duration in this unit, or `Number.MIN_VALUE`
* if conversion would negatively overflow, or `Number.MAX_VALUE`
* if it would positively overflow
*/
abstract convert(duration: number, unit: TimeUnit): number
/**
* Converts the given `d` value to nanoseconds.
*
* Equivalent with `NANOSECONDS.convert(duration, this)`.
*
* @param d is the converted duration
* @return the converted duration, or `Number.MAX_SAFE_INTEGER + 1`
* (or `2^53`) if it overflows, or `Number.MIN_SAFE_INTEGER - 1` if it
* underflows (or `-2^53`).
*/
abstract toNanos(d: number): number
/**
* Converts the given `d` value to microseconds.
*
* Equivalent with `MICROSECONDS.convert(duration, this)`.
*
* @param d is the converted duration
* @return the converted duration, or `Number.MAX_SAFE_INTEGER + 1`
* (or `2^53`) if it overflows, or `Number.MIN_SAFE_INTEGER - 1` if it
* underflows (or `-2^53`).
*/
abstract toMicros(d: number): number
/**
* Converts the given `d` value to milliseconds.
*
* Equivalent with `MILLISECONDS.convert(duration, this)`.
*
* @param d is the converted duration
* @return the converted duration, or `Number.MAX_SAFE_INTEGER + 1`
* (or `2^53`) if it overflows, or `Number.MIN_SAFE_INTEGER - 1` if it
* underflows (or `-2^53`).
*/
abstract toMillis(d: number): number
/**
* Converts the given `d` value to seconds.
*
* Equivalent with `SECONDS.convert(duration, this)`.
*
* @param d is the converted duration
* @return the converted duration, or `Number.MAX_SAFE_INTEGER + 1`
* (or `2^53`) if it overflows, or `Number.MIN_SAFE_INTEGER - 1` if it
* underflows (or `-2^53`).
*/
abstract toSeconds(d: number): number
/**
* Converts the given `d` value to minutes.
*
* Equivalent with `MINUTES.convert(duration, this)`.
*
* @param d is the converted duration
* @return the converted duration, or `Number.MAX_SAFE_INTEGER + 1`
* (or `2^53`) if it overflows, or `Number.MIN_SAFE_INTEGER - 1` if it
* underflows (or `-2^53`).
*/
abstract toMinutes(d: number): number
/**
* Converts the given `d` value to hours.
*
* Equivalent with `HOURS.convert(duration, this)`.
*
* @param d is the converted duration
* @return the converted duration, or `Number.MAX_SAFE_INTEGER + 1`
* (or `2^53`) if it overflows, or `Number.MIN_SAFE_INTEGER - 1` if it
* underflows (or `-2^53`).
*/
abstract toHours(d: number): number
/**
* Converts the given `d` value to days.
*
* Equivalent with `DAYS.convert(duration, this)`.
*
* @param d is the converted duration
* @return the converted duration, or `Number.MAX_SAFE_INTEGER + 1`
* (or `2^53`) if it overflows, or `Number.MIN_SAFE_INTEGER - 1` if it
* underflows (or `-2^53`).
*/
abstract toDays(d: number): number
/**
* A number representing the unit's ordering in the `TimeUnit`
* enumeration, useful for doing comparisons to find out which unit
* is more coarse grained.
*
* ```typescript
* MINUTES.ord < DAYS.ord // true
* SECONDS.ord > MICROSECONDS.org // true
* ```
*/
abstract ord: number
/**
* A human readable label for this unit.
*/
abstract label: string
/** Override for `Object.toString`. */
toString(): string {
return this.label.toUpperCase()
}
}
/** @hidden */ const C0 = 1
/** @hidden */ const C1 = C0 * 1000
/** @hidden */ const C2 = C1 * 1000
/** @hidden */ const C3 = C2 * 1000
/** @hidden */ const C4 = C3 * 60
/** @hidden */ const C5 = C4 * 60
/** @hidden */ const C6 = C5 * 24
/** @hidden */ const MIN = -9007199254740992
/** @hidden */ const MAX = 9007199254740992
/** @hidden */
const trunc: (x: number) => number = Math.trunc ||
/* istanbul ignore next */
function (x) {
if (isNaN(x)) return NaN
if (x > 0) return Math.floor(x)
return Math.ceil(x)
}
/** @hidden */
function x(d: number, m: number, over: number): number {
if (d > over) return MAX
if (d < -over) return MIN
return d * m
}
/** @hidden */
class Nanoseconds extends TimeUnit {
ord: number = 0
label = "nanoseconds"
convert(duration: number, unit: TimeUnit): number { return unit.toNanos(duration) }
toNanos(d: number): number { return d }
toMicros(d: number): number { return trunc(d / (C1 / C0)) }
toMillis(d: number): number { return trunc(d / (C2 / C0)) }
toSeconds(d: number): number { return trunc(d / (C3 / C0)) }
toMinutes(d: number): number { return trunc(d / (C4 / C0)) }
toHours(d: number): number { return trunc(d / (C5 / C0)) }
toDays(d: number): number { return trunc(d / (C6 / C0)) }
}
/**
* Time unit for representing nanoseconds, where 1 nanosecond is
* one thousandth of a microsecond.
*/
export const NANOSECONDS: TimeUnit =
new Nanoseconds()
/** @hidden */
class Microseconds extends TimeUnit {
ord: number = 1
label = "microseconds"
convert(duration: number, unit: TimeUnit): number { return unit.toMicros(duration) }
toNanos(d: number): number { return x(d, C1 / C0, trunc(MAX / (C1 / C0))) }
toMicros(d: number): number { return d }
toMillis(d: number): number { return trunc(d / (C2 / C1)) }
toSeconds(d: number): number { return trunc(d / (C3 / C1)) }
toMinutes(d: number): number { return trunc(d / (C4 / C1)) }
toHours(d: number): number { return trunc(d / (C5 / C1)) }
toDays(d: number): number { return trunc(d / (C6 / C1)) }
}
/**
* Time unit for representing microseconds, where 1 microsecond is
* one thousandth of a millisecond.
*/
export const MICROSECONDS: TimeUnit =
new Microseconds()
/** @hidden */
class Milliseconds extends TimeUnit {
ord: number = 2
label = "milliseconds"
convert(duration: number, unit: TimeUnit): number { return unit.toMillis(duration) }
toNanos(d: number): number { return x(d, C2 / C0, trunc(MAX / (C2 / C0))) }
toMicros(d: number): number { return x(d, C2 / C1, trunc(MAX / (C2 / C1))) }
toMillis(d: number): number { return d }
toSeconds(d: number): number { return trunc(d / (C3 / C2)) }
toMinutes(d: number): number { return trunc(d / (C4 / C2)) }
toHours(d: number): number { return trunc(d / (C5 / C2)) }
toDays(d: number): number { return trunc(d / (C6 / C2)) }
}
/**
* Time unit for representing milliseconds, where 1 millisecond is
* one thousandth of a second.
*/
export const MILLISECONDS: TimeUnit =
new Milliseconds()
/** @hidden */
class Seconds extends TimeUnit {
ord: number = 3
label = "seconds"
convert(duration: number, unit: TimeUnit): number { return unit.toSeconds(duration) }
toNanos(d: number): number { return x(d, C3 / C0, trunc(MAX / (C3 / C0))) }
toMicros(d: number): number { return x(d, C3 / C1, trunc(MAX / (C3 / C1))) }
toMillis(d: number): number { return x(d, C3 / C2, trunc(MAX / (C3 / C2))) }
toSeconds(d: number): number { return d }
toMinutes(d: number): number { return trunc(d / (C4 / C3)) }
toHours(d: number): number { return trunc(d / (C5 / C3)) }
toDays(d: number): number { return trunc(d / (C6 / C3)) }
}
/**
* Time unit for representing seconds.
*/
export const SECONDS: TimeUnit =
new Seconds()
/** @hidden */
class Minutes extends TimeUnit {
ord: number = 4
label = "minutes"
convert(duration: number, unit: TimeUnit): number { return unit.toMinutes(duration) }
toNanos(d: number): number { return x(d, C4 / C0, trunc(MAX / (C4 / C0))) }
toMicros(d: number): number { return x(d, C4 / C1, trunc(MAX / (C4 / C1))) }
toMillis(d: number): number { return x(d, C4 / C2, trunc(MAX / (C4 / C2))) }
toSeconds(d: number): number { return x(d, C4 / C3, trunc(MAX / (C4 / C3))) }
toMinutes(d: number): number { return d }
toHours(d: number): number { return trunc(d / (C5 / C4)) }
toDays(d: number): number { return trunc(d / (C6 / C4)) }
}
/**
* Time unit for representing minutes.
*/
export const MINUTES: TimeUnit =
new Minutes()
/** @hidden */
class Hours extends TimeUnit {
ord: number = 5
label = "hours"
convert(duration: number, unit: TimeUnit): number { return unit.toHours(duration) }
toNanos(d: number): number { return x(d, C5 / C0, trunc(MAX / (C5 / C0))) }
toMicros(d: number): number { return x(d, C5 / C1, trunc(MAX / (C5 / C1))) }
toMillis(d: number): number { return x(d, C5 / C2, trunc(MAX / (C5 / C2))) }
toSeconds(d: number): number { return x(d, C5 / C3, trunc(MAX / (C5 / C3))) }
toMinutes(d: number): number { return x(d, C5 / C4, trunc(MAX / (C5 / C4))) }
toHours(d: number): number { return d }
toDays(d: number): number { return trunc(d / (C6 / C5)) }
}
/**
* Time unit for representing hours.
*/
export const HOURS: TimeUnit =
new Hours()
/** @hidden */
class Days extends TimeUnit {
ord: number = 6
label = "days"
convert(duration: number, unit: TimeUnit): number { return unit.toDays(duration) }
toNanos(d: number): number { return x(d, C6 / C0, trunc(MAX / (C6 / C0))) }
toMicros(d: number): number { return x(d, C6 / C1, trunc(MAX / (C6 / C1))) }
toMillis(d: number): number { return x(d, C6 / C2, trunc(MAX / (C6 / C2))) }
toSeconds(d: number): number { return x(d, C6 / C3, trunc(MAX / (C6 / C3))) }
toMinutes(d: number): number { return x(d, C6 / C4, trunc(MAX / (C6 / C4))) }
toHours(d: number): number { return x(d, C6 / C5, trunc(MAX / (C6 / C5))) }
toDays(d: number): number { return d }
}
/**
* Time unit for representing days.
*/
export const DAYS: TimeUnit =
new Days()
/**
* A simple representation for time durations, based on [[TimeUnit]].
*/
export class Duration implements IEquals<Duration> {
public duration: number
public unit: TimeUnit
constructor(duration: number, unit: TimeUnit) {
if (isNaN(duration)) {
throw new IllegalArgumentError("NaN is not supported for a Duration")
}
// Only integers allowed
this.duration = trunc(duration)
this.unit = unit
}
/**
* This method returns `true` if this duration is finite,
* or `false otherwise.
*/
isFinite(): boolean { return isFinite(this.duration) }
/**
* Calculates the nanoseconds described by the source [[Duration]].
*/
toNanos(): number {
return NANOSECONDS.convert(this.duration, this.unit)
}
/**
* Calculates the microseconds described by the source [[Duration]].
*/
toMicros(): number {
return MICROSECONDS.convert(this.duration, this.unit)
}
/**
* Calculates the milliseconds described by the source [[Duration]].
*/
toMillis(): number {
return MILLISECONDS.convert(this.duration, this.unit)
}
/**
* Calculates the seconds described by the source [[Duration]].
*/
toSeconds(): number {
return SECONDS.convert(this.duration, this.unit)
}
/**
* Calculates the minutes described by the source [[Duration]].
*/
toMinutes(): number {
return MINUTES.convert(this.duration, this.unit)
}
/**
* Calculates the hours described by the source [[Duration]].
*/
toHours(): number {
return HOURS.convert(this.duration, this.unit)
}
/**
* Calculates the days described by the source [[Duration]].
*/
toDays(): number {
return DAYS.convert(this.duration, this.unit)
}
/**
* Returns a new `Duration` value that represents `this` converted
* to use the given `unit`.
*
* Note that this may be a lossy conversion, e.g. when converting
* 27 hours to 1 day, there's a loss of fidelity.
*/
convertTo(unit: TimeUnit): Duration {
return new Duration(unit.convert(this.duration, this.unit), unit)
}
/**
* Negates `this` duration, by changing the sign.
*/
negate(): Duration {
switch (this.duration) {
case Infinity: return Duration.negInf()
case -Infinity: return Duration.inf()
default:
return new Duration(-this.duration, this.unit)
}
}
/**
* Return the sum of `this` duration and `other`.
*
* Note that the `unit` used for the result will be the
* more finer grained one out of the two.
*
* ```typescript
* // Result will be 27 hours
* Duration.days(1).plus(Duration.hours(3))
* ```
*/
plus(other: Duration): Duration {
if (!isFinite(this.duration)) {
if (!isFinite(other.duration) && this.duration !== other.duration) {
throw new IllegalArgumentError(
"cannot deal with two infinities with different signs, " +
"as that would be a NaN")
}
return this
} else if (other.duration === 0) {
return this
} else if (this.duration === 0) {
return other
}
if (!isFinite(other.duration)) return other
let d1: Duration = this
let d2: Duration = other
if (d2.unit.ord < d1.unit.ord) { d1 = other; d2 = this }
d2 = d2.convertTo(d1.unit)
return new Duration(d1.duration + d2.duration, d1.unit)
}
/**
* Subtracts the `other` duration from `this`.
*
* Note that the `unit` used for the result will be the
* more finer grained one out of the two:
*
* ```typescript
* // Result will be 21 hours
* Duration.days(1).minus(Duration.hours(3))
* ```
*/
minus(other: Duration): Duration {
return this.plus(other.negate())
}
/** @inheritdoc */
equals(other: Duration): boolean {
function cmp(s: Duration, o: Duration) {
const n = s.unit.convert(o.duration, o.unit)
return n === s.duration
}
if (!isFinite(this.duration)) {
return !isFinite(other.duration) &&
this.duration === other.duration
}
return this.unit.ord <= other.unit.ord
? cmp(this, other) : cmp(other, this)
}
/** @inheritdoc */
hashCode(): number {
if (this.isFinite()) {
return this.toNanos()
} else if (this.duration === Infinity) {
return 7540833725118015
} else {
return 422082410550358
}
}
toString(): string {
if (this.isFinite())
return `${this.duration} ${this.unit.label}`
else if (this.duration >= 0)
return "[end of time]"
else
return "[beginning of time]"
}
/**
* Wraps the argument in a `Duration.millis` reference, in case it's
* a number, otherwise returns the argument as is.
*
* In Javascript code it is customary to express durations with
* numbers representing milliseconds and in functions it's good
* to still allow developers to do that because it's the standard
* convention.
*
* Thus one can work with a union type like `number | Duration`.
* And in case a `number` is given, then it is interpreted as
* milliseconds.
*
* Usage:
*
* ```typescript
* function delay(d: number | Duration, r: () => {}) {
* const millis = Duration.of(d).toMillis()
* return setTimeout(r, millis)
* }
* ```
*/
static of(value: number | Duration): Duration {
return typeof value === "number"
? Duration.millis(value)
: value
}
/** Returns a zero length duration. */
static zero(): Duration {
return new Duration(0, DAYS)
}
/** Returns a [[Duration]] representing positive infinite. */
static inf(): Duration {
return new Duration(Infinity, DAYS)
}
/** Returns a [[Duration]] representing negative infinite. */
static negInf(): Duration {
return new Duration(-Infinity, DAYS)
}
/**
* Constructs a `Duration` instance out of a value representing
* nanoseconds.
*/
static nanos(d: number): Duration {
return new Duration(d, NANOSECONDS)
}
/**
* Constructs a `Duration` instance out of a value representing
* microseconds.
*/
static micros(d: number): Duration {
return new Duration(d, MICROSECONDS)
}
/**
* Constructs a `Duration` instance out of a value representing
* milliseconds.
*/
static millis(d: number): Duration {
return new Duration(d, MILLISECONDS)
}
/**
* Constructs a `Duration` instance out of a value representing
* seconds.
*/
static seconds(d: number): Duration {
return new Duration(d, SECONDS)
}
/**
* Constructs a `Duration` instance out of a value representing
* minutes.
*/
static minutes(d: number): Duration {
return new Duration(d, MINUTES)
}
/**
* Constructs a `Duration` instance out of a value representing
* hours.
*/
static hours(d: number): Duration {
return new Duration(d, HOURS)
}
/**
* Constructs a `Duration` instance out of a value representing
* days.
*/
static days(d: number): Duration {
return new Duration(d, DAYS)
}
} | the_stack |
import type {
ConcatOptions,
ConcatSource,
FFmpegCommand,
FFmpegInput,
FFmpegOptions,
FFmpegOutput,
FFmpegProcess,
InputSource,
OutputDestination,
ProbeOptions,
ProbeResult,
SpawnOptions,
} from './types';
import { pipeline } from 'stream';
import {
DEV_NULL,
flatMap,
isInputSource,
isNullish,
isWritableStream,
read,
toReadableStream,
} from './utils';
import {
escapeConcatFile,
escapeTeeComponent,
stringifyFilterDescription,
stringifyValue,
} from './string';
import { startSocketServer, getSocketPath, getSocketURL } from './sock';
import { spawn } from './process';
import { probe } from './probe';
/**
* Create a new FFmpegCommand.
* @param options -
* @public
*/
export function ffmpeg(options: FFmpegOptions = {}): FFmpegCommand {
return new Command(options);
}
class Command implements FFmpegCommand {
constructor(options: FFmpegOptions) {
const { level, progress = true, overwrite = true } = options;
this.args(overwrite ? '-y' : '-n');
if (progress)
this.args('-progress', 'pipe:1');
this.args('-loglevel', `+repeat+level${level ? `+${level}` : ''}`);
}
readonly #args: string[] = [];
readonly #inputs: Input[] = [];
readonly #outputs: Output[] = [];
readonly #inputStreams: (readonly [string, NodeJS.ReadableStream])[] = [];
readonly #outputStreams: (readonly [string, readonly NodeJS.WritableStream[]])[] = [];
input(source: InputSource): FFmpegInput {
const [url, isStream, stream] = handleInputSource(source, this.#inputStreams);
const input = new Input(url, isStream, stream);
this.#inputs.push(input);
return input;
}
concat(sources: ConcatSource[], options: ConcatOptions = {}): FFmpegInput {
const { safe = false, protocols, useDataURI = false } = options;
const inputStreams = this.#inputStreams;
// Dynamically create an ffconcat file with the given directives.
// https://ffmpeg.org/ffmpeg-all.html#concat-1
const directives = ['ffconcat version 1.0'];
const addFile = (source: InputSource) => {
const [url] = handleInputSource(source, inputStreams);
directives.push(`file ${escapeConcatFile(url)}`);
};
for (const source of sources) {
if (isInputSource(source)) {
addFile(source);
} else {
const { file, duration, inpoint, outpoint } = source;
addFile(file);
if (duration !== void 0)
directives.push(`duration ${duration}ms`);
if (inpoint !== void 0)
directives.push(`inpoint ${inpoint}ms`);
if (outpoint !== void 0)
directives.push(`outpoint ${outpoint}ms`);
// TODO: add support for the directives file_packet_metadata, stream and exact_stream_id
}
}
// Create the ffconcat script as a buffer.
const ffconcat = Buffer.from(directives.join('\n'), 'utf8');
const source = useDataURI
// FFmpeg only supports base64-encoded data urls.
? `data:text/plain;base64,${ffconcat.toString('base64')}`
: ffconcat;
const input = this.input(source);
// Add extra arguments to the input based on the given options
// the option safe is NOT enabled by default because it doesn't
// allow streams or protocols other than the currently used one,
// which, depending on the platform, may be `file` (on Windows)
// or `unix` (on every other platform).
input.args('-safe', safe ? '1' : '0');
// Protocol whitelist enables certain protocols in the ffconcat
// file dynamically created by this method.
if (protocols && protocols.length > 0)
input.args('-protocol_whitelist', protocols.join(','));
return input;
}
output(...destinations: OutputDestination[]): FFmpegOutput {
const urls: string[] = [];
let isStream = false;
let streams: NodeJS.WritableStream[];
for (const dest of destinations) {
if (typeof dest === 'string') {
urls.push(dest);
} else {
if (!isWritableStream(dest))
throw new TypeError(`${dest} is not a writable stream`);
if (isStream) {
streams!.push(dest);
} else {
// When the output has to be written to multiple streams, we
// we only use one unix socket / windows pipe by writing the
// same output to multiple streams internally.
isStream = true;
streams = [dest];
const path = getSocketPath();
urls.push(getSocketURL(path));
this.#outputStreams.push([path, streams]);
}
}
}
// - If there are no urls the output will be discarded by
// using `/dev/null` or `NUL` as the destination.
// - If there is only one url it will be given directly
// as the output url to ffmpeg.
// - If there is more than one url, the `tee` protocol
// will be used.
const url = urls.length === 0 ? DEV_NULL
: urls.length === 1 ? urls[0]
: `tee:${urls.map(escapeTeeComponent).join('|')}`;
const output = new Output(url, isStream);
this.#outputs.push(output);
return output;
}
async spawn(options: SpawnOptions = {}): Promise<FFmpegProcess> {
const args = this.getArgs();
const inputStreams = this.#inputStreams;
const outputStreams = this.#outputStreams;
// Start all socket servers needed to handle the streams, skipped if there are no streams.
const ioSocketServers = (inputStreams.length > 0 || outputStreams.length > 0) && await Promise.all([
...inputStreams.map(async ([path, stream]) => {
const server = await startSocketServer(path);
server.once('connection', (socket) => {
pipeline(stream, socket, () => {
// Close the socket connection if still writable, this reduces the risk
// of ffmpeg waiting for further chunks that will never be emitted by
// an errored stream.
if (socket.writable) socket.end();
});
// Do NOT accept further connections, close() will close the server after
// all existing connections are ended.
server.close();
});
return server;
}),
...outputStreams.map(async ([path, streams]) => {
const server = await startSocketServer(path);
server.once('connection', (socket) => {
socket.on('error', () => {
// TODO: improve error handling
if (socket.writable) socket.end();
});
socket.on('data', (data) => {
// TODO: errors in output streams will fall through, so we just rely
// on the user to add an error listener to their output streams.
// Could this be different from the behavior one might expect?
for (const stream of streams) if (stream.writable) stream.write(data);
});
socket.on('end', () => {
for (const stream of streams) if (stream.writable) stream.end();
});
// Do NOT accept further connections, close() will close the server after
// all existing connections are ended.
server.close();
});
return server;
}),
]);
const p = spawn(args, options);
if (ioSocketServers) {
const cp = p.unwrap();
const onExit = () => {
cp.off('exit', onExit);
cp.off('error', onExit);
// Close all socket servers, this is necessary for proper cleanup after
// failed conversions, or otherwise errored ffmpeg processes.
for (const server of ioSocketServers) {
if (server.listening) server.close();
}
};
cp.on('exit', onExit);
cp.on('error', onExit);
}
return p;
}
args(...args: string[]): this {
this.#args.push(...args);
return this;
}
getArgs(): string[] {
return [
...this.#args,
...flatMap(this.#inputs, (input) => input.getArgs()),
...flatMap(this.#outputs, (output) => output.getArgs()),
];
}
}
class Input implements FFmpegInput {
constructor(url: string, public readonly isStream: boolean, stream?: NodeJS.ReadableStream) {
this.#url = url;
this.#stream = stream;
}
readonly #url: string;
readonly #args: string[] = [];
readonly #stream?: NodeJS.ReadableStream;
offset(offset: number): this {
return this.args('-itsoffset', `${offset}ms`);
}
duration(duration: number): this {
return this.args('-t', `${duration}ms`);
}
start(start: number): this {
return this.args('-ss', `${start}ms`);
}
format(format: string): this {
return this.args('-f', format);
}
codec(codec: string): this {
return this.args('-c', codec);
}
videoCodec(codec: string): this {
return this.args('-c:V', codec);
}
audioCodec(codec: string): this {
return this.args('-c:a', codec);
}
subtitleCodec(codec: string): this {
return this.args('-c:s', codec);
}
async probe(options: ProbeOptions = {}): Promise<ProbeResult> {
const { probeSize } = options;
if (probeSize !== void 0 && (!Number.isInteger(probeSize) || probeSize < 32))
throw new TypeError(`Cannot probe ${probeSize} bytes, probeSize must be an integer >= 32`);
let source: Uint8Array | string;
if (this.isStream) {
// TODO: pipe the stream to ffprobe
const stream = this.#stream!;
source = await read(stream, probeSize ?? 5000000);
stream.unshift(source);
} else {
source = this.#url;
}
return await probe(source, options);
}
getArgs(): string[] {
return [
...this.#args,
'-i',
this.#url,
];
}
args(...args: string[]): this {
this.#args.push(...args);
return this;
}
}
class Output implements FFmpegOutput {
constructor(url: string, public readonly isStream: boolean) {
this.#url = url;
}
readonly #url: string;
readonly #args: string[] = [];
readonly #videoFilters: string[] = [];
readonly #audioFilters: string[] = [];
videoFilter(filter: string, options: Record<string, unknown> | unknown[] | undefined = void 0) {
this.#videoFilters.push(stringifyFilterDescription(filter, options));
return this;
}
audioFilter(filter: string, options: Record<string, unknown> | unknown[] | undefined = void 0) {
this.#audioFilters.push(stringifyFilterDescription(filter, options));
return this;
}
metadata(metadata: Record<string, unknown>, stream: string | undefined = void 0): this {
return this.args(...flatMap(Object.entries(metadata), ([key, value]) => [
`-metadata${stream ? `:${stream}` : ''}`,
`${key}=${value === '' || isNullish(value) ? '' : stringifyValue(value)}`,
]));
}
map(...streams: string[]): this {
return this.args(...flatMap(streams, (stream) => ['-map', stream]));
}
format(format: string): this {
return this.args('-f', format);
}
codec(codec: string): this {
return this.args('-c', codec);
}
videoCodec(codec: string): this {
return this.args('-c:V', codec);
}
audioCodec(codec: string): this {
return this.args('-c:a', codec);
}
subtitleCodec(codec: string): this {
return this.args('-c:s', codec);
}
duration(duration: number): this {
return this.args('-t', `${duration}ms`);
}
start(start: number): this {
return this.args('-ss', `${start}ms`);
}
args(...args: string[]): this {
this.#args.push(...args);
return this;
}
getArgs(): string[] {
const videoFilters = this.#videoFilters;
const audioFilters = this.#audioFilters;
return [
...this.#args,
...(videoFilters.length > 0 ? ['-filter:V', videoFilters.join(',')] : []),
...(audioFilters.length > 0 ? ['-filter:a', audioFilters.join(',')] : []),
this.#url,
];
}
}
function handleInputSource(source: InputSource, streams: (readonly [string, NodeJS.ReadableStream])[]): [string, boolean, NodeJS.ReadableStream?] {
if (!isInputSource(source))
throw new TypeError(`${source} is not a valid input source`);
if (typeof source === 'string') {
return [source, false];
} else {
const path = getSocketPath();
const stream = toReadableStream(source);
streams.push([path, stream]);
return [getSocketURL(path), true, stream];
}
} | the_stack |
import { expect } from "chai";
import { IModelConnection, SnapshotConnection } from "@itwin/core-frontend";
import {
ChildNodeSpecificationTypes, InstanceLabelOverrideValueSpecificationType, RelationshipDirection, Ruleset, RuleTypes,
} from "@itwin/presentation-common";
import { Presentation } from "@itwin/presentation-frontend";
import { initialize, terminate } from "../../IntegrationTests";
import { printRuleset } from "../Utils";
describe("Learning Snippets", () => {
let imodel: IModelConnection;
beforeEach(async () => {
await initialize();
imodel = await SnapshotConnection.openFile("assets/datasets/Properties_60InstancesWithUrl2.ibim");
});
afterEach(async () => {
await imodel.close();
await terminate();
});
describe("Customization Rules", () => {
describe("InstanceLabelOverride", () => {
it("uses `requiredSchemas` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.InstanceLabelOverride.RequiredSchemas.Ruleset
// The ruleset has root node rule that returns `Generic.PhysicalObject` instances and
// customization rule to override label using related `bis.ExternalSourceAspect` property.
// `bis.ExternalSourceAspect` ECClass was introduced in BisCore version 1.0.2, so the rule needs
// a `requiredSchemas` attribute to only use the rule if the version meets the requirement.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.RootNodes,
specifications: [{
specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses,
classes: { schemaName: "Generic", classNames: ["PhysicalObject"], arePolymorphic: true },
groupByClass: false,
groupByLabel: false,
}],
}, {
ruleType: RuleTypes.InstanceLabelOverride,
requiredSchemas: [{ name: "BisCore", minVersion: "1.0.2" }],
class: { schemaName: "Generic", className: "PhysicalObject" },
values: [{
specType: InstanceLabelOverrideValueSpecificationType.Property,
propertySource: {
relationship: { schemaName: "BisCore", className: "ElementOwnsMultiAspects" },
direction: RelationshipDirection.Forward,
targetClass: { schemaName: "BisCore", className: "ExternalSourceAspect" },
},
propertyName: "Identifier",
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// verify that label was not overriden because imodel has older BisCore schema than required by label override
const nodes = await Presentation.presentation.getNodes({
imodel,
rulesetOrId: ruleset,
});
expect(nodes).to.be.lengthOf(2).and.to.containSubset([
{ label: { displayValue: "Physical Object [0-38]" } },
{ label: { displayValue: "Physical Object [0-39]" } },
]);
});
it("uses `priority` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.InstanceLabelOverride.Priority.Ruleset
// The ruleset has root node rule that returns `bis.GeometricModel3d` instances and two
// customization rules to override labels. The rules have different priorities and
// higher priority rule is handled first.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.RootNodes,
specifications: [{
specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses,
classes: { schemaName: "BisCore", classNames: ["GeometricModel3d"], arePolymorphic: true },
groupByClass: false,
groupByLabel: false,
}],
}, {
ruleType: RuleTypes.InstanceLabelOverride,
priority: 1,
class: { schemaName: "BisCore", className: "GeometricModel3d" },
values: [{
specType: InstanceLabelOverrideValueSpecificationType.String,
value: "Model A",
}],
}, {
ruleType: RuleTypes.InstanceLabelOverride,
priority: 2,
class: { schemaName: "BisCore", className: "GeometricModel3d" },
values: [{
specType: InstanceLabelOverrideValueSpecificationType.String,
value: "Model B",
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// verify that label override with higher priority was applied
const nodes = await Presentation.presentation.getNodes({
imodel,
rulesetOrId: ruleset,
});
expect(nodes).to.be.lengthOf(1).and.to.containSubset([
{ label: { displayValue: "Model B" } },
]);
});
it("uses `onlyIfNotHandled` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.InstanceLabelOverride.OnlyIfNotHandled.Ruleset
// The ruleset has root node rule that returns `bis.GeometricModel3d` instances and two
// customization rules to override label. The first label override rule has lower priority and
// `onlyIfNodeHandled` attribute, which allows it to be overriden by higher priority rules. Even
// if rule with higher priority does not provide value for label rule with lower priority is not used.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.RootNodes,
specifications: [{
specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses,
classes: { schemaName: "BisCore", classNames: ["GeometricModel3d"], arePolymorphic: true },
groupByClass: false,
groupByLabel: false,
}],
}, {
ruleType: RuleTypes.InstanceLabelOverride,
priority: 1,
onlyIfNotHandled: true,
class: { schemaName: "BisCore", className: "GeometricModel3d" },
values: [{
specType: InstanceLabelOverrideValueSpecificationType.String,
value: "Model A",
}],
}, {
ruleType: RuleTypes.InstanceLabelOverride,
priority: 2,
class: { schemaName: "BisCore", className: "GeometricModel3d" },
values: [{
specType: InstanceLabelOverrideValueSpecificationType.String,
value: "",
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// verify that only label override with higher priority was applied
const nodes = await Presentation.presentation.getNodes({
imodel,
rulesetOrId: ruleset,
});
expect(nodes).to.be.lengthOf(1).and.to.containSubset([
{ label: { displayValue: "Ñót spêçìfíêd" } },
]);
});
it("uses `class` attribute", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.InstanceLabelOverride.Class.Ruleset
// The ruleset has root node rule that returns `bis.Model` instances.
// Also there is customization rule to override label only for `bis.GeometricModel3d` instances.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.RootNodes,
specifications: [{
specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses,
classes: { schemaName: "BisCore", classNames: ["Model"], arePolymorphic: true },
groupByClass: false,
groupByLabel: false,
}],
}, {
ruleType: RuleTypes.InstanceLabelOverride,
class: { schemaName: "BisCore", className: "GeometricModel3d" },
values: [{
specType: InstanceLabelOverrideValueSpecificationType.String,
value: "Geometric Model Node",
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// verify that only `bis.GeometricModel3d` instances label was overriden
const nodes = await Presentation.presentation.getNodes({
imodel,
rulesetOrId: ruleset,
});
expect(nodes).to.be.lengthOf(8).and.to.containSubset([
{ label: { displayValue: "BisCore.DictionaryModel" } },
{ label: { displayValue: "BisCore.RealityDataSources" } },
{ label: { displayValue: "Converted Drawings" } },
{ label: { displayValue: "Converted Groups" } },
{ label: { displayValue: "Converted Sheets" } },
{ label: { displayValue: "Definition Model For DgnV8Bridge:D:\\Temp\\Properties_60InstancesWithUrl2.dgn, Default" } },
{ label: { displayValue: "DgnV8Bridge" } },
{ label: { displayValue: "Geometric Model Node" } },
]);
});
it("uses composite value specification", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.InstanceLabelOverride.CompositeValueSpecification.Ruleset
// The ruleset has root node rule that returns `bis.GeometricElement3d` instances and
// customization rule to override instance label composed of string "ECClass" and instance ECClass name.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.RootNodes,
specifications: [{
specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses,
classes: { schemaName: "BisCore", classNames: ["GeometricModel3d"], arePolymorphic: true },
groupByClass: false,
groupByLabel: false,
}],
}, {
ruleType: RuleTypes.InstanceLabelOverride,
class: { schemaName: "BisCore", className: "GeometricModel3d" },
values: [{
specType: InstanceLabelOverrideValueSpecificationType.Composite,
separator: "-",
parts: [
{ spec: { specType: InstanceLabelOverrideValueSpecificationType.String, value: "ECClass" } },
{ spec: { specType: InstanceLabelOverrideValueSpecificationType.ClassName } },
],
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// verify that label was set to composed value
const nodes = await Presentation.presentation.getNodes({
imodel,
rulesetOrId: ruleset,
});
expect(nodes).to.be.lengthOf(1).and.to.containSubset([
{ label: { displayValue: "ECClass-PhysicalModel" } },
]);
});
it("uses property value specification", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.InstanceLabelOverride.PropertyValueSpecification.Ruleset
// The ruleset has root node rule that returns `bis.SpatialViewDefinition` instances and
// customization rule to override instance label using `Pitch` property value.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.RootNodes,
specifications: [{
specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses,
classes: { schemaName: "BisCore", classNames: ["SpatialViewDefinition"], arePolymorphic: true },
groupByClass: false,
groupByLabel: false,
}],
}, {
ruleType: RuleTypes.InstanceLabelOverride,
class: { schemaName: "BisCore", className: "SpatialViewDefinition" },
values: [{
specType: InstanceLabelOverrideValueSpecificationType.Property,
propertyName: "Pitch",
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// verify that labels was set to `Pitch` property value
const nodes = await Presentation.presentation.getNodes({
imodel,
rulesetOrId: ruleset,
});
expect(nodes).to.be.lengthOf(4).and.to.containSubset([
{ label: { displayValue: "-35.26" } },
{ label: { displayValue: "-160.99" } },
{ label: { displayValue: "0.00" } },
{ label: { displayValue: "90.00" } },
]);
});
it("uses related property value specification", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.InstanceLabelOverride.RelatedPropertyValueSpecification.Ruleset
// The ruleset has root node rule that returns `meta.ECEnumerationDef` instances and
// customization rule to override instance label using `Alias` property value of
// `meta.ECSchemaDef` instance that is containing `meta.ECEnumerationDef` instance.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.RootNodes,
specifications: [{
specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses,
classes: { schemaName: "ECDbMeta", classNames: ["ECEnumerationDef"] },
groupByClass: false,
groupByLabel: false,
}],
}, {
ruleType: RuleTypes.InstanceLabelOverride,
class: { schemaName: "ECDbMeta", className: "ECEnumerationDef" },
values: [{
specType: InstanceLabelOverrideValueSpecificationType.Property,
propertySource: {
relationship: { schemaName: "ECDbMeta", className: "SchemaOwnsEnumerations" },
direction: RelationshipDirection.Backward,
},
propertyName: "Alias",
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// verify that labels were set to related `meta.ECSchemaDef` instance `Alias` property value
const nodes = await Presentation.presentation.getNodes({
imodel,
rulesetOrId: ruleset,
});
expect(nodes).to.be.lengthOf(18).and.to.containSubset([
{ label: { displayValue: "bis" } },
{ label: { displayValue: "bis" } },
{ label: { displayValue: "bsca" } },
{ label: { displayValue: "bsca" } },
{ label: { displayValue: "bsca" } },
{ label: { displayValue: "CoreCA" } },
{ label: { displayValue: "CoreCA" } },
{ label: { displayValue: "dgnca" } },
{ label: { displayValue: "ecdbf" } },
{ label: { displayValue: "meta" } },
{ label: { displayValue: "meta" } },
{ label: { displayValue: "meta" } },
{ label: { displayValue: "meta" } },
{ label: { displayValue: "meta" } },
{ label: { displayValue: "meta" } },
{ label: { displayValue: "meta" } },
{ label: { displayValue: "meta" } },
{ label: { displayValue: "PCJTest" } },
]);
});
it("uses string value specification", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.InstanceLabelOverride.StringValueSpecification.Ruleset
// The ruleset has root node rule that returns `bis.GeometricModel3d` instances and
// customization rule to override label using string "Model Node".
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.RootNodes,
specifications: [{
specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses,
classes: { schemaName: "BisCore", classNames: ["GeometricModel3d"], arePolymorphic: true },
groupByClass: false,
groupByLabel: false,
}],
}, {
ruleType: RuleTypes.InstanceLabelOverride,
class: { schemaName: "BisCore", className: "GeometricModel3d" },
values: [{
specType: InstanceLabelOverrideValueSpecificationType.String,
value: "Model Node",
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// verify that label was set to "Model Node"
const nodes = await Presentation.presentation.getNodes({
imodel,
rulesetOrId: ruleset,
});
expect(nodes).to.be.lengthOf(1).and.to.containSubset([
{ label: { displayValue: "Model Node" } },
]);
});
it("uses class name value specification", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.InstanceLabelOverride.ClassNameValueSpecification.Ruleset
// The ruleset has root node rule that returns `bis.GeometricModel3d` instances and
// customization rule to override instance label using full name of instance ECClass.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.RootNodes,
specifications: [{
specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses,
classes: { schemaName: "BisCore", classNames: ["GeometricModel3d"], arePolymorphic: true },
groupByClass: false,
groupByLabel: true,
}],
}, {
ruleType: RuleTypes.InstanceLabelOverride,
class: { schemaName: "BisCore", className: "GeometricModel3d" },
values: [{
specType: InstanceLabelOverrideValueSpecificationType.ClassName,
full: true,
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// verify that label was set to full class name
const nodes = await Presentation.presentation.getNodes({
imodel,
rulesetOrId: ruleset,
});
expect(nodes).to.be.lengthOf(1).and.to.containSubset([
{ label: { displayValue: "BisCore:PhysicalModel" } },
]);
});
it("uses class label value specification", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.InstanceLabelOverride.ClassLabelValueSpecification.Ruleset
// The ruleset has root node rule that returns 'bis.GeometricModel3d' instances and
// customization rule to override instance label with instance class label.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.RootNodes,
specifications: [{
specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses,
classes: { schemaName: "BisCore", classNames: ["GeometricModel3d"], arePolymorphic: true },
groupByClass: false,
groupByLabel: false,
}],
}, {
ruleType: RuleTypes.InstanceLabelOverride,
class: { schemaName: "BisCore", className: "GeometricModel3d" },
values: [{
specType: InstanceLabelOverrideValueSpecificationType.ClassLabel,
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// verify that label value was set to instance ECClass label
const nodes = await Presentation.presentation.getNodes({
imodel,
rulesetOrId: ruleset,
});
expect(nodes).to.be.lengthOf(1).and.to.containSubset([
{ label: { displayValue: "Physical Model" } },
]);
});
it("uses briefcaseId value specification", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.InstanceLabelOverride.BriefcaseIdValueSpecification.Ruleset
// The ruleset has root node rule that returns `bis.GeometricModel3d` instances and
// customization rule to override instance label with BriefcaseId value.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.RootNodes,
specifications: [{
specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses,
classes: { schemaName: "BisCore", classNames: ["GeometricModel3d"], arePolymorphic: true },
groupByClass: false,
groupByLabel: false,
}],
}, {
ruleType: RuleTypes.InstanceLabelOverride,
class: { schemaName: "BisCore", className: "GeometricModel3d" },
values: [{
specType: InstanceLabelOverrideValueSpecificationType.BriefcaseId,
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// verify that only label override with higher priority was applied
const nodes = await Presentation.presentation.getNodes({
imodel,
rulesetOrId: ruleset,
});
expect(nodes).to.be.lengthOf(1).and.to.containSubset([
{ label: { displayValue: "0" } },
]);
});
it("uses localId value specification", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.InstanceLabelOverride.LocalIdValueSpecification.Ruleset
// The ruleset has root node rule that returns `bis.GeometricModel3d` instances and
// customization rule to override instance label with LocalId value.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.RootNodes,
specifications: [{
specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses,
classes: { schemaName: "BisCore", classNames: ["GeometricModel3d"], arePolymorphic: true },
groupByClass: false,
groupByLabel: false,
}],
}, {
ruleType: RuleTypes.InstanceLabelOverride,
class: { schemaName: "BisCore", className: "GeometricModel3d" },
values: [{
specType: InstanceLabelOverrideValueSpecificationType.LocalId,
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// verify that only label override with higher priority was applied
const nodes = await Presentation.presentation.getNodes({
imodel,
rulesetOrId: ruleset,
});
expect(nodes).to.be.lengthOf(1).and.to.containSubset([
{ label: { displayValue: "S" } },
]);
});
it("uses related instance label value specification", async () => {
// __PUBLISH_EXTRACT_START__ Presentation.InstanceLabelOverride.RelatedInstanceLabelValueSpecification.Ruleset
// The ruleset has root node rule that returns `Generic.PhysicalObject` instances and
// customization rule to override instance label with label of `bis.Model` instance
// containing `Generic.PhysicalObject` instance.
const ruleset: Ruleset = {
id: "example",
rules: [{
ruleType: RuleTypes.RootNodes,
specifications: [{
specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses,
classes: { schemaName: "Generic", classNames: ["PhysicalObject"], arePolymorphic: true },
groupByClass: false,
groupByLabel: false,
}],
}, {
ruleType: RuleTypes.InstanceLabelOverride,
class: { schemaName: "Generic", className: "PhysicalObject" },
values: [{
specType: InstanceLabelOverrideValueSpecificationType.RelatedInstanceLabel,
pathToRelatedInstance: {
relationship: { schemaName: "BisCore", className: "ModelContainsElements" },
direction: RelationshipDirection.Backward,
},
}],
}],
};
// __PUBLISH_EXTRACT_END__
printRuleset(ruleset);
// verify that only label override with higher priority was applied
const nodes = await Presentation.presentation.getNodes({
imodel,
rulesetOrId: ruleset,
});
expect(nodes).to.be.lengthOf(2).and.to.containSubset([
{ label: { displayValue: "Properties_60InstancesWithUrl2" } },
{ label: { displayValue: "Properties_60InstancesWithUrl2" } },
]);
});
});
});
}); | the_stack |
import { Component } from 'vue-property-decorator';
import { select, Selection } from 'd3-selection';
import { axisLeft } from 'd3-axis';
import { scaleLinear } from 'd3-scale';
import { line } from 'd3-shape';
import _ from 'lodash';
import $ from 'jquery';
import ColumnList from '@/components/column-list/column-list';
import template from './parallel-coordinates.html';
import {
DEFAULT_PLOT_MARGINS,
drawBrushLasso,
getScale,
injectVisualizationTemplate,
LABEL_OFFSET_PX,
multiplyVisuals,
PlotMargins,
Scale,
Visualization,
AnyScale,
} from '@/components/visualization';
import { fadeOut, getTransform, areSegmentsIntersected } from '@/common/util';
import { SELECTED_COLOR } from '@/common/constants';
import { VisualProperties } from '@/data/visuals';
import { isContinuousDomain } from '@/data/util';
import * as history from './history';
const DEFAULT_NUM_COLUMNS = 6;
const ORDINAL_DOMAIN_LENGTH_THRESHOLD = 10;
interface ParallelCoordinatesSave {
columns: number[];
areTicksVisible: boolean;
areAxesLabelsVisible: boolean;
axisMargin: boolean;
useDatasetRange: boolean;
}
interface ParallelCoordinatesItemProps {
index: number;
values: Array<number | string>;
hasVisuals: boolean;
selected: boolean;
visuals: VisualProperties;
}
const DEFAULT_ITEM_VISUALS: VisualProperties = {
color: 'black',
width: 1.5,
border: 'none',
opacity: .15,
};
const SELECTED_ITEM_VISUALS: VisualProperties = {
color: SELECTED_COLOR,
opacity: .75,
};
@Component({
template: injectVisualizationTemplate(template),
components: {
ColumnList,
},
})
export default class ParallelCoordinates extends Visualization {
protected NODE_TYPE = 'parallel-coordinates';
protected DEFAULT_WIDTH = 450;
protected DEFAULT_HEIGHT = 250;
private columns: number[] = [];
private xScale!: Scale;
private yScales!: Scale[];
private margins: PlotMargins = { ...DEFAULT_PLOT_MARGINS, left: 30, bottom: 20 };
private areTicksVisible = true;
private areAxesLabelsVisible = true;
private axisMargin = true;
private useDatasetRange = false;
public setColumns(columns: number[]) {
this.columns = columns;
this.draw();
}
public setUseDatasetRange(value: boolean) {
this.useDatasetRange = value;
this.draw();
}
public setAxisMargin(value: boolean) {
this.axisMargin = value;
this.draw();
}
public applyColumns(columns: number[]) {
if (!columns.length) {
this.findDefaultColumns();
} else {
this.columns = columns;
}
if (this.hasDataset()) {
this.draw();
}
}
protected created() {
this.serializationChain.push((): ParallelCoordinatesSave => ({
columns: this.columns,
areTicksVisible: this.areTicksVisible,
areAxesLabelsVisible: this.areAxesLabelsVisible,
axisMargin: this.axisMargin,
useDatasetRange: this.useDatasetRange,
}));
}
protected draw() {
if (!this.columns.length) {
this.coverText = 'Please choose columns';
return;
}
this.coverText = '';
this.computeScales();
this.updateLeftMargin();
const itemProps = this.getItemProps();
this.drawLines(itemProps);
this.drawAxes();
}
protected findDefaultColumns() {
if (!this.hasDataset()) {
return;
}
const dataset = this.getDataset();
this.columns = dataset.getColumns()
.filter(column => {
return isContinuousDomain(column.type) ||
dataset.getDomain(column.index).length <= ORDINAL_DOMAIN_LENGTH_THRESHOLD;
})
.slice(0, DEFAULT_NUM_COLUMNS)
.map(column => column.index);
}
protected brushed(brushPoints: Point[], isBrushStop?: boolean) {
if (isBrushStop) {
this.computeBrushedItems(brushPoints);
this.computeSelection();
this.drawLines(this.getItemProps());
this.propagateSelection();
}
drawBrushLasso(this.$refs.brush as SVGElement, !isBrushStop ? brushPoints : []);
}
private computeBrushedItems(brushPoints: Point[]) {
if (!brushPoints.length) {
return;
}
const [start, end] = [_.first(brushPoints), _.last(brushPoints)] as [Point, Point];
if (start.x === end.x && start.y === end.y) {
return;
}
if (!this.isShiftPressed) {
this.selection.clear();
}
const dataset = this.getDataset();
const items = this.inputPortMap.in.getSubsetPackage().getItemIndices();
for (const itemIndex of items) {
if (this.selection.hasItem(itemIndex)) {
continue;
}
const points: Point[] = dataset.rowOnSubColumns(itemIndex, this.columns, { forScale: true })
.map((value, axisIndex) => ({ x: this.xScale(axisIndex), y: this.yScales[axisIndex](value) }));
let hit = false;
for (let axisIndex = 0; axisIndex < this.columns.length - 1 && !hit; axisIndex++) {
for (let i = 0; i < brushPoints.length - 1 && !hit; i++) {
if (areSegmentsIntersected(points[axisIndex], points[axisIndex + 1], brushPoints[i], brushPoints[i + 1])) {
hit = true;
this.selection.addItem(itemIndex);
}
}
}
}
}
private computeScales() {
const pkg = this.inputPortMap.in.getSubsetPackage();
const yRange = [this.svgHeight - this.margins.bottom, this.margins.top];
const dataset = this.getDataset();
this.yScales = this.columns.map(columnIndex => {
return getScale(
dataset.getColumnType(columnIndex),
dataset.getDomain(columnIndex, this.useDatasetRange ? undefined : pkg.getItemIndices()),
yRange,
{ domainMargin: this.axisMargin ? undefined : 0 },
);
});
this.xScale = scaleLinear()
.domain([0, this.columns.length - 1])
.range([this.margins.left, this.svgWidth - this.margins.right]) as Scale;
this.updateLeftMargin();
}
private updateLeftMargin() {
if (!this.columns.length) {
this.margins.left = DEFAULT_PLOT_MARGINS.left;
(this.xScale as AnyScale).range([this.margins.left, this.svgWidth - this.margins.right]);
return;
}
// Axes are drawn with transition, which would affect the width computation.
this.isTransitionDisabled = true;
this.drawAxis(0, this.columns[0]);
this.updateMargins(() => {
const maxTickWidth = _.max($(this.$refs.axes as SVGGElement)
.find(`#axis-${this.columns[0]} > .tick > text, #axis-${this.columns[0]} > .label`)
.map((index: number, element: SVGGraphicsElement) => element.getBBox().width)) || 0;
this.margins.left = DEFAULT_PLOT_MARGINS.left + maxTickWidth;
(this.xScale as AnyScale).range([this.margins.left, this.svgWidth - this.margins.right]);
this.isTransitionDisabled = false;
});
}
private getItemProps(): ParallelCoordinatesItemProps[] {
const pkg = this.inputPortMap.in.getSubsetPackage();
const items = pkg.getItems();
const itemProps: ParallelCoordinatesItemProps[] = items.map(item => {
const props: ParallelCoordinatesItemProps = {
index: item.index,
values: this.getDataset().rowOnSubColumns(item.index, this.columns, { forScale: true }),
visuals: _.extend({}, DEFAULT_ITEM_VISUALS, item.visuals),
hasVisuals: !_.isEmpty(item.visuals),
selected: this.selection.hasItem(item.index),
};
if (this.selection.hasItem(item.index)) {
_.extend(props.visuals, SELECTED_ITEM_VISUALS);
multiplyVisuals(props.visuals);
}
return props;
});
return itemProps;
}
private drawLines(itemProps: ParallelCoordinatesItemProps[]) {
const l = line<number | string>()
.x((p, axisIndex) => this.xScale(axisIndex))
.y((p, axisIndex) => this.yScales[axisIndex](p));
let lines = select(this.$refs.lines as SVGGElement).selectAll<SVGPathElement, ParallelCoordinatesItemProps>('path')
.data(itemProps, d => d.index.toString());
fadeOut(lines.exit());
lines = lines.enter().append<SVGPathElement>('path')
.attr('id', d => d.index.toString())
.merge(lines)
.attr('has-visuals', d => d.hasVisuals)
.attr('is-selected', d => d.selected);
const updatedLines = this.isTransitionFeasible(itemProps.length) ? lines.transition() : lines;
updatedLines
.attr('d', d => l(d.values))
.style('stroke', d => d.visuals.color as string)
.style('stroke-width', d => d.visuals.width + 'px')
.style('opacity', d => d.visuals.opacity as number);
this.moveSelectedLinesToFront();
}
private moveSelectedLinesToFront() {
const gLines = this.$refs.lines as SVGGElement;
const $lines = $(gLines);
$lines.children('path[has-visuals=true]').appendTo(gLines);
$lines.children('path[is-selected=true]').appendTo(gLines);
}
private drawAxes() {
const exitAxes = select(this.$refs.axes as SVGGElement).selectAll<SVGGElement, number>('g.axis')
.data(this.columns, columnIndex => columnIndex.toString())
.exit();
fadeOut(exitAxes);
this.columns.forEach((columnIndex, axisIndex) => {
this.drawAxis(axisIndex, columnIndex);
});
}
private drawAxis(axisIndex: number, columnIndex: number) {
const pkg = this.inputPortMap.in.getSubsetPackage();
const yScale = this.yScales[axisIndex];
const id = 'axis-' + columnIndex.toString();
const axis = axisLeft(yScale)
.tickValues(this.areTicksVisible && pkg.numItems() ? yScale.domain() : []);
const svgAxes: Selection<SVGGElement, string, null, undefined> = select(this.$refs.axes as SVGGElement);
let g = svgAxes.select<SVGGElement>('#' + id);
const gTransform = getTransform([this.xScale(axisIndex), 0]);
if (g.empty()) {
g = svgAxes.append<SVGGElement>('g').datum(columnIndex.toString())
.attr('id', id)
.classed('axis', true)
.attr('transform', gTransform);
}
g.call(axis);
// Axes transition does not depend on the number of data items.
const updatedG = this.isTransitionFeasible(0) ? g.transition() : g;
updatedG
.style('opacity', 1)
.attr('transform', gTransform);
if (this.areAxesLabelsVisible) {
let label = g.select<SVGTextElement>('.label');
const labelTransform = getTransform([0, this.svgHeight - LABEL_OFFSET_PX]);
if (label.empty()) {
label = g.append('text')
.classed('label', true)
.attr('transform', labelTransform);
}
const updatedLabel = this.isTransitionFeasible(0) ? label.transition() : label;
updatedLabel
.style('opacity', 1)
.attr('transform', labelTransform)
.text(this.getDataset().getColumnName(columnIndex));
} else {
fadeOut(g.select('.label'));
}
}
private onSelectColumns(columns: number[], prevColumns: number[]) {
this.commitHistory(history.selectColumnsEvent(this, columns, prevColumns));
this.setColumns(columns);
}
private onToggleAxisMargin(value: boolean) {
this.commitHistory(history.toggleAxisMarginEvent(this, value));
this.setAxisMargin(value);
}
private onToggleUseDatasetRange(value: boolean) {
this.commitHistory(history.toggleUseDatasetRangeEvent(this, value));
this.setUseDatasetRange(value);
}
} | the_stack |
import { Configuration } from "../configuration/Configuration.js";
import { ILog } from "../logging/ILog.js";
import { Event } from "../models/Event.js";
import { IEventQueue } from "../queue/IEventQueue.js";
import { Response } from "../submission/Response.js";
interface EventQueueItem {
file: string,
event: Event
}
export class DefaultEventQueue implements IEventQueue {
/**
* A list of handlers that will be fired when events are submitted.
* @type {Array}
* @private
*/
private _handlers: Array<(events: Event[], response: Response) => Promise<void>> = [];
/**
* Suspends processing until the specified time.
* @type {Date}
* @private
*/
private _suspendProcessingUntil?: Date;
/**
* Discards queued items until the specified time.
* @type {Date}
* @private
*/
private _discardQueuedItemsUntil?: Date;
/**
* Returns true if the queue is processing.
* @type {boolean}
* @private
*/
private _processingQueue = false;
/**
* Processes the queue every xx seconds.
* @type {Timer}
* @private
*/
private _queueTimerId = 0;
private readonly QUEUE_PREFIX: string = "q:";
private _lastFileTimestamp = 0;
private _queue: EventQueueItem[] = [];
private _loadPersistedEvents = true;
constructor(
private config: Configuration,
private maxItems: number = 250
) { }
public async enqueue(event: Event): Promise<void> {
const eventWillNotBeQueued = "The event will not be queued.";
const config: Configuration = this.config;
const log: ILog = config.services.log;
if (!config.enabled) {
log.info(`Configuration is disabled. ${eventWillNotBeQueued}`);
return;
}
if (!config.isValid) {
log.info(`Invalid Api Key. ${eventWillNotBeQueued}`);
return;
}
if (this.areQueuedItemsDiscarded()) {
log.info(`Queue items are currently being discarded. ${eventWillNotBeQueued}`);
return;
}
const file = await this.enqueueEvent(event);
const logText = `type=${<string>event.type} reference_id=${<string>event.reference_id} source=${<string>event.source} message=${<string>event.message}`;
log.info(`Enqueued event: ${file} (${logText})`);
}
public async process(): Promise<void> {
const queueNotProcessed = "The queue will not be processed";
const { log } = this.config.services;
if (this._processingQueue) {
return;
}
log.trace("Processing queue...");
if (!this.config.enabled) {
log.info(`Configuration is disabled: ${queueNotProcessed}`);
return;
}
if (!this.config.isValid) {
log.info(`Invalid Api Key: ${queueNotProcessed}`);
return;
}
this._processingQueue = true;
try {
if (this._loadPersistedEvents) {
if (this.config.usePersistedQueueStorage) {
await this.loadEvents();
}
this._loadPersistedEvents = false;
}
const items = this._queue.slice(0, this.config.submissionBatchSize);
if (!items || items.length === 0) {
this._processingQueue = false;
return;
}
log.info(`Sending ${items.length} events to ${this.config.serverUrl}`);
const events = items.map(i => i.event);
const response = await this.config.services.submissionClient.submitEvents(events);
await this.processSubmissionResponse(response, items);
await this.eventsPosted(events, response);
log.trace("Finished processing queue");
this._processingQueue = false;
} catch (ex) {
log.error(`Error processing queue: ${ex instanceof Error ? ex.message : ex + ''}`);
await this.suspendProcessing();
this._processingQueue = false;
}
}
public startup(): Promise<void> {
if (this._queueTimerId === 0) {
// TODO: Fix awaiting promise.
this._queueTimerId = setInterval(() => void this.onProcessQueue(), 10000);
}
return Promise.resolve();
}
public suspend(): Promise<void> {
clearInterval(this._queueTimerId);
this._queueTimerId = 0;
return Promise.resolve();
}
public async suspendProcessing(durationInMinutes?: number, discardFutureQueuedItems?: boolean, clearQueue?: boolean): Promise<void> {
const config: Configuration = this.config; // Optimization for minifier.
const currentDate = new Date();
if (!durationInMinutes || durationInMinutes <= 0) {
durationInMinutes = Math.ceil(currentDate.getMinutes() / 15) * 15 - currentDate.getMinutes();
}
config.services.log.info(`Suspending processing for ${durationInMinutes} minutes.`);
this._suspendProcessingUntil = new Date(currentDate.getTime() + (durationInMinutes * 60000));
if (discardFutureQueuedItems) {
this._discardQueuedItemsUntil = this._suspendProcessingUntil;
}
if (clearQueue) {
// Account is over the limit and we want to ensure that the sample size being sent in will contain newer errors.
await this.removeEvents(this._queue);
}
}
// TODO: See if this makes sense.
public onEventsPosted(handler: (events: Event[], response: Response) => Promise<void>): void {
handler && this._handlers.push(handler);
}
private async eventsPosted(events: Event[], response: Response): Promise<void> {
const handlers = this._handlers;
for (const handler of handlers) {
try {
await handler(events, response);
} catch (ex) {
this.config.services.log.error(`Error calling onEventsPosted handler: ${ex instanceof Error ? ex.message : ex + ''}`);
}
}
}
private areQueuedItemsDiscarded(): boolean {
return this._discardQueuedItemsUntil &&
this._discardQueuedItemsUntil > new Date() || false;
}
private isQueueProcessingSuspended(): boolean {
return this._suspendProcessingUntil &&
this._suspendProcessingUntil > new Date() || false;
}
private async onProcessQueue(): Promise<void> {
if (!this.isQueueProcessingSuspended() && !this._processingQueue) {
await this.process();
}
}
private async processSubmissionResponse(response: Response, items: EventQueueItem[]): Promise<void> {
const noSubmission = "The event will not be submitted";
const config: Configuration = this.config;
const log: ILog = config.services.log;
if (response.status === 202) {
log.info(`Sent ${items.length} events`);
await this.removeEvents(items);
return;
}
if (response.status === 429 || response.rateLimitRemaining === 0 || response.status === 503) {
// You are currently over your rate limit or the servers are under stress.
log.error("Server returned service unavailable");
await this.suspendProcessing();
return;
}
if (response.status === 402) {
// If the organization over the rate limit then discard the event.
log.info("Too many events have been submitted, please upgrade your plan");
await this.suspendProcessing(0, true, true);
return;
}
if (response.status === 401 || response.status === 403) {
// The api key was suspended or could not be authorized.
log.info(`Unable to authenticate, please check your configuration. ${noSubmission}`);
await this.suspendProcessing(15);
await this.removeEvents(items);
return;
}
if (response.status === 400 || response.status === 404) {
// The service end point could not be found.
log.error(`Error while trying to submit data: ${response.message}`);
await this.suspendProcessing(60 * 4);
await this.removeEvents(items);
return;
}
if (response.status === 413) {
const message = "Event submission discarded for being too large.";
if (config.submissionBatchSize > 1) {
log.error(`${message} Retrying with smaller batch size.`);
config.submissionBatchSize = Math.max(1, Math.round(config.submissionBatchSize / 1.5));
} else {
log.error(`${message} ${noSubmission}`);
await this.removeEvents(items);
}
return;
}
log.error(`Error submitting events: ${response.message || "Please check the network tab for more info."}`);
await this.suspendProcessing();
}
private async loadEvents(): Promise<void> {
if (this.config.usePersistedQueueStorage) {
try {
const storage = this.config.services.storage;
const files: string[] = await storage.keys();
for (const file of files) {
if (file?.startsWith(this.QUEUE_PREFIX)) {
const json = await storage.getItem(file);
if (json)
this._queue.push({ file, event: JSON.parse(json) as Event });
}
}
} catch (ex) {
this.config.services.log.error(`Error loading queue items from storage: ${ex instanceof Error ? ex.message : ex + ''}`)
}
}
}
private async enqueueEvent(event: Event): Promise<string> {
this._lastFileTimestamp = Math.max(Date.now(), this._lastFileTimestamp + 1);
const file = `${this.QUEUE_PREFIX}${this._lastFileTimestamp}.json`;
const { storage, log } = this.config.services;
const useStorage: boolean = this.config.usePersistedQueueStorage;
if (this._queue.push({ file, event }) > this.maxItems) {
log.trace("Removing oldest queue entry: maxItems exceeded");
const item = this._queue.shift();
if (useStorage && item) {
await storage.removeItem(item.file);
}
}
if (useStorage) {
try {
await storage.setItem(file, JSON.stringify(event));
} catch (ex) {
log.error(`Error saving queue item to storage: ${ex instanceof Error ? ex.message : ex + ''}`)
}
}
return file;
}
private async removeEvents(items: EventQueueItem[]): Promise<void> {
const files = items.map(i => i.file);
if (this.config.usePersistedQueueStorage) {
for (const file of files) {
try {
await this.config.services.storage.removeItem(file);
} catch (ex) {
this.config.services.log.error(`Error removing queue item from storage: ${ex instanceof Error ? ex.message : ex + ''}`)
}
}
}
this._queue = this._queue.filter(i => !files.includes(i.file));
}
} | the_stack |
import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { trigger, transition, style, animate, state, keyframes } from '@angular/animations';
import { Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { identity } from 'lodash/fp';
import { filter, pluck, takeUntil, distinctUntilChanged, map } from 'rxjs/operators';
import { combineLatest, Subject, Observable } from 'rxjs';
import { ChefSorters } from 'app/helpers/auth/sorter';
import { Regex } from 'app/helpers/auth/regex';
import { NgrxStateAtom } from 'app/ngrx.reducers';
import { routeParams } from 'app/route.selectors';
import { EntityStatus, allLoadedSuccessfully, pending } from 'app/entities/entities';
import {
GetPolicy, AddPolicyMembers, PolicyMembersMgmtPayload
} from 'app/entities/policies/policy.actions';
import {
policyFromRoute,
getStatus as getPolicyStatus,
addPolicyMembersStatus
} from 'app/entities/policies/policy.selectors';
import { Policy, Member, Type, stringToMember } from 'app/entities/policies/policy.model';
import { allTeams, getAllStatus as getAllTeamsStatus } from 'app/entities/teams/team.selectors';
import { Team } from 'app/entities/teams/team.model';
import { GetTeams } from 'app/entities/teams/team.actions';
import { allUsers, getStatus as getAllUsersStatus } from 'app/entities/users/user.selectors';
import {
GetUsers
} from 'app/entities/users/user.actions';
import { User } from 'app/entities/users/user.model';
export type FieldName = 'type' | 'identityProvider' | 'name';
@Component({
selector: 'app-policy-add-members',
templateUrl: './policy-add-members.component.html',
styleUrls: ['./policy-add-members.component.scss'],
animations: [
trigger('dropInAnimation', [
state('void', style({ 'opacity': '0', 'height' : '0' })),
transition('void => *', animate(400, keyframes([
style({opacity: 0, offset: 0}),
style({opacity: 0, height: '{{height}}px', offset: 0.3}),
style({opacity: 1, height: '{{height}}px', offset: 1})
]))),
transition('* => void', animate(150, keyframes([
style({ opacity: 1, height: '{{height}}px', offset: 0 }),
style({ opacity: 0, height: '{{height}}px', offset: 0.1 }),
style({ opacity: 0, height: '0px', offset: 1 })
])))
])
]
})
export class PolicyAddMembersComponent implements OnInit, OnDestroy {
// Data structures and state
public policy: Policy;
// Members that are in the list of possible members to add.
private membersAvailableMap: { [id: string]: Member } = {};
// Sorted version of the above in array form for chef-table.
// Use addAvailableMember and removeAvailableMember to keep in sync.
public sortedMembersAvailable: Member[];
// Members that user has selected to add on page submit.
private membersToAdd: { [id: string]: Member } = {};
// Map of local user and team member IDs to URLs.
// Will not contain LDAP and SAML stuff.
private memberURLs: { [id: string]: string[] } = {};
// If all required data has loaded or not.
public loading$: Observable<boolean>;
// If the request to add members is in progress.
public addingMembers = false;
private isDestroyed: Subject<boolean> = new Subject<boolean>();
public addMembersFailed = '';
// Add expression modal and modal error cases
public modalVisible = false;
public unparsableMember = false;
public duplicateMember = false;
public alreadyPolicyMember = false;
// Form info
public expressionForm: FormGroup;
public expressionOutput: string;
public allIdentity: string;
public nameOrId: string;
public ldapOrSaml = false;
// Animation
public triggerValue: 'void' | '*';
constructor(
private store: Store<NgrxStateAtom>,
private router: Router,
fb: FormBuilder) {
this.expressionForm = fb.group({
// Must stay in sync with error checks in policy-add-members.component.html
type: ['', Validators.required]
});
}
ngOnInit(): void {
this.store.select(routeParams).pipe(
takeUntil(this.isDestroyed),
pluck('id'),
filter(identity),
distinctUntilChanged()
).subscribe((id: string) => this.store.dispatch(new GetPolicy({ id })));
this.store.dispatch(new GetTeams());
this.store.dispatch(new GetUsers());
this.loading$ = combineLatest([
this.store.select(getAllTeamsStatus),
this.store.select(getAllUsersStatus),
this.store.select(getPolicyStatus)
]).pipe(
map((statuses: EntityStatus[]) => !allLoadedSuccessfully(statuses)));
combineLatest([
this.store.select(allTeams),
this.store.select(allUsers),
this.store.select(policyFromRoute),
this.loading$
]).pipe(
takeUntil(this.isDestroyed),
filter(([_teams, _users, _policy, loading]) => !loading)
).subscribe(([teams, users, policy, _loading]) => {
this.policy = <Policy>Object.assign({}, policy);
teams.forEach((team: Team) => {
const member = stringToMember(`team:local:${team.id}`);
this.memberURLs[member.name] = ['/settings', 'teams', team.id];
// We'll refresh the sorted map for the chef-table below.
this.addAvailableMember(member, false);
});
users.forEach((user: User) => {
const member = stringToMember(`user:local:${user.id}`);
this.memberURLs[member.name] = ['/settings', 'users', user.id];
// We'll refresh the sorted map for the chef-table below.
this.addAvailableMember(member, false);
});
this.policy.members.forEach((memberName: string) => {
if (memberName in this.membersAvailableMap) {
this.removeAvailableMember(memberName, false);
}
});
// Now that the membersAvailableMap is correct, refresh.
this.refreshSortedMembersAvailable();
});
this.store.select(addPolicyMembersStatus).pipe(
takeUntil(this.isDestroyed),
filter(addState => this.addingMembers && !pending(addState)))
.subscribe(() => {
this.addingMembers = false;
this.closePage();
});
}
addAvailableMember(member: Member, refresh: boolean): void {
this.membersAvailableMap[member.name] = member;
if (refresh) {
this.refreshSortedMembersAvailable();
}
}
removeAvailableMember(memberName: string, refresh: boolean): void {
delete this.membersAvailableMap[memberName];
if (refresh) {
this.refreshSortedMembersAvailable();
}
}
refreshSortedMembersAvailable(): void {
this.sortedMembersAvailable = this.membersMapAvailableToSortedToArray();
}
addMembers(): void {
this.addingMembers = true;
this.addMembersFailed = '';
this.store.dispatch(new AddPolicyMembers(<PolicyMembersMgmtPayload>{
id: this.policy.id,
members: this.membersToAddValues()
}));
}
ngOnDestroy() {
this.isDestroyed.next(true);
this.isDestroyed.complete();
}
closePage() {
this.router.navigate(this.backRoute(), { fragment: 'members' });
}
getHeading() {
return this.policy
? `Add Members to ${this.policy.name}`
: '';
}
getMemberConfirmBtnText() {
if (this.addingMembers) {
return (this.membersToAddValues().length < 2)
? 'Adding Member...'
: `Adding ${this.membersToAddValues().length} Members...`;
} else {
return (this.membersToAddValues().length < 2)
? 'Add Member'
: `Add ${this.membersToAddValues().length} Members`;
}
}
getErrorMessage() {
return this.addMembersFailed.length > 0 ? this.addMembersFailed : undefined;
}
backRoute(): string[] {
return ['/settings', 'policies', this.policy.id];
}
public closeModal(): void {
this.resetModal();
this.modalVisible = false;
}
public openModal(): void {
this.resetModal();
this.modalVisible = true;
}
resetModal(): void {
this.resetForm();
this.resetErrors();
}
memberHasURL(member: Member): boolean {
return member.name in this.memberURLs;
}
memberURL(member: Member): string[] {
return this.memberURLs[member.name];
}
membersMapAvailableToSortedToArray(): Member[] {
const membersAvailable = Object.values(this.membersAvailableMap);
// sort by displayName then by name
return ChefSorters.naturalSort(membersAvailable, ['displayName', 'name']);
}
membersToAddValues(): Member[] {
return Object.values(this.membersToAdd);
}
addOrRemoveQueuedMember(checked: boolean, member: Member): void {
if (checked) {
this.membersToAdd[member.name] = member;
} else {
delete this.membersToAdd[member.name];
}
}
isMemberChecked(member: Member): boolean {
return member.name in this.membersToAdd;
}
private resetErrors(): void {
this.unparsableMember = false;
this.duplicateMember = false;
this.alreadyPolicyMember = false;
}
public validateAndAddExpression(): void {
this.resetErrors();
const member = stringToMember(this.expressionOutput.trim());
if (member.type === Type.Unknown) {
this.unparsableMember = true;
return;
}
if (member.name in this.membersAvailableMap) {
this.duplicateMember = true;
return;
}
this.policy.members.forEach((policyMember: string) => {
if (policyMember === member.name) {
this.alreadyPolicyMember = true;
return;
}
});
this.addAvailableMember(member, true);
this.addOrRemoveQueuedMember(true, member);
this.closeModal();
}
private showInputs(fieldName: FieldName): void {
const formValues = this.expressionForm.value;
const matchAllWildCard = '*';
this.setFormLabels(formValues.type);
switch (fieldName) {
case 'type':
this.resetFormControls();
this.resetErrors();
if (formValues.type === 'user' || formValues.type === 'team') {
this.addIdentityControl();
} else if (formValues.type === 'token') {
this.addNameControl(null);
}
break;
case 'identityProvider':
this.resetErrors();
this.expressionForm.removeControl('name');
if (formValues.identityProvider !== matchAllWildCard) {
this.addNameControl(formValues.identityProvider);
}
break;
case 'name': // fallthrough
default:
break;
}
}
private setFormLabels(typeValue): void {
if (typeValue === 'token') {
this.nameOrId = 'ID';
} else {
this.allIdentity = typeValue;
this.nameOrId = 'Name';
}
}
private resetFormControls(): void {
this.expressionForm.removeControl('identityProvider');
this.expressionForm.removeControl('name');
}
private resetForm(): void {
this.resetFormControls();
this.expressionForm.reset();
this.expressionOutput = '';
}
private addIdentityControl(): void {
this.expressionForm.addControl('identityProvider', new FormControl('', Validators.required));
}
private addNameControl(identityProvider): void {
if (identityProvider === 'ldap' || identityProvider === 'saml' ) {
this.ldapOrSaml = true;
this.expressionForm.addControl('name', new FormControl('',
[
Validators.required,
Validators.pattern(Regex.patterns.NO_MIXED_WILDCARD_ALLOW_SPECIAL)
]
)
);
} else {
this.ldapOrSaml = false;
this.expressionForm.addControl('name', new FormControl('',
[
Validators.required,
Validators.pattern(Regex.patterns.NO_MIXED_WILDCARD_ALLOW_HYPHEN)
]
)
);
}
}
private setExpressionOutput(): void {
this.expressionOutput =
(Object.values(this.expressionForm.value) as string[])
.filter(value => value != null && value.length > 0)
.join(':');
}
public updateFormDisplay(fieldName: FieldName): void {
this.showInputs(fieldName);
this.setExpressionOutput();
}
} | the_stack |
import { PdfStringFormat, PdfDocument, PdfPage, PdfGraphics, RectangleF } from "../../../../../src/index";
import { PdfGrid } from "../../../../../src/index";
import { PdfGridCell, PdfGridCellCollection } from "../../../../../src/index";
import { PdfGridRow } from "../../../../../src/index";
import { PdfGridCellStyle } from "../../../../../src/index";
import { PdfStandardFont, PdfFontFamily, PdfBorders, PdfSolidBrush, PointF } from "../../../../../src/index";
import { PdfPaddings, PdfPen, PdfColor, PdfDashStyle, PdfFont, SizeF, PdfTextAlignment } from "../../../../../src/index";
describe('PdfGridCell.ts', () => {
describe('Constructor initializing',()=> {
let grid : PdfGrid = new PdfGrid();
let gridRow : PdfGridRow = new PdfGridRow(grid);
let t1 : PdfGridCell = new PdfGridCell();
let t2 : PdfGridCell = new PdfGridCell(gridRow);
let t3 : PdfGridCell = new PdfGridCell(gridRow);
it('-RemainingString == undefined', () => {
expect(t1.remainingString).toBeUndefined();
})
it('-Set RemainingString', () => {
t1.remainingString = 'grid';
expect(t1.remainingString).toEqual('grid');
})
it('-stringFormat != undefined', () => {
expect(t1.stringFormat).not.toBeUndefined();
})
it('-Set stringFormat', () => {
let value : PdfStringFormat = new PdfStringFormat();
t1.stringFormat = value;
expect(t1.stringFormat).not.toBeUndefined();
})
it('-row == undefined', () => {
expect(t1.row).toBeUndefined();
})
it('-Set row', () => {
t1.row = gridRow;
expect(t1.row).not.toBeUndefined();
})
it('-value == undefined', () => {
expect(t1.value).toBeUndefined();
})
it('-Set value', () => {
t1.value = 1;
expect(t1.value).toEqual(1);
})
it('-rowSpan == 1', () => {
expect(t1.rowSpan).toEqual(1);
})
it('-Set rowSpan == 3', () => {
t1.rowSpan = 3;
expect(t1.rowSpan).toEqual(3);
})
it('-Set rowSpan == -1', () => {
expect(function (): void {t1.rowSpan = -1; }).toThrowError();
})
it('-style != undefined', () => {
expect(t1.style).not.toBeUndefined();
})
it('-Set style', () => {
let value : PdfGridCellStyle = new PdfGridCellStyle();
t1.style = value;
expect(t1.style).not.toBeUndefined();
})
// it('-height == undefined', () => {
// expect(t1.height).toBeUndefined();
// })
it('-Set height', () => {
t1.height = 50;
expect(t1.height).toEqual(50);
})
it('-columnSpan == 1', () => {
expect(t1.columnSpan).toEqual(1);
})
it('-Set columnSpan == 3', () => {
t1.columnSpan = 3;
expect(t1.columnSpan).toEqual(3);
})
it('-Set columnSpan == -1', () => {
expect(function (): void {t1.columnSpan = -1;}).toThrowError();
})
it('-width == 5.52', () => {
expect(t1.width).not.toBeNull();
})
it('-Set width', () => {
t1.width = 1;
expect(t1.width).toEqual(1);
})
it('-isRowMergeStart == true', () => {
t1.isRowMergeStart = true;
expect(t1.isRowMergeStart).not.toBeNull();
})
it('-isCellMergeStart == true', () => {
t1.isCellMergeStart = true;
expect(t1.isCellMergeStart).not.toBeNull();
})
it('-isRowMergeContinue == true', () => {
t1.isRowMergeContinue = true;
expect(t1.isRowMergeContinue).not.toBeNull();
})
it('-isCellMergeContinue == true', () => {
t1.isCellMergeContinue = true;
expect(t1.isCellMergeContinue).not.toBeNull();
})
let document : PdfDocument = new PdfDocument()
let page : PdfPage = document.pages.add();
let graphics : PdfGraphics = page.graphics;
let rect : RectangleF = new RectangleF(new PointF(10, 10), new SizeF(50, 50));
t2.drawCellBackground(graphics, rect);
t2.drawCellBorders(graphics, rect);
t2.style.cellPadding = new PdfPaddings(2, 3, 4, 5);
t2.draw(page.graphics, new RectangleF(new PointF(10, 10), new SizeF(50, 50)), true);
// t2.rowSpan = 2;
t2.draw(page.graphics, new RectangleF(new PointF(10, 10), new SizeF(50, 50)), true);
t2.draw(page.graphics, new RectangleF(new PointF(10, 10), new SizeF(50, 50)), true);
let border : PdfBorders = new PdfBorders();
let pen : PdfPen = new PdfPen(new PdfColor(0, 0, 255), 10);
pen.dashStyle = PdfDashStyle.Dot;
border.all = pen;
t2.style.borders = border;
t2.drawCellBorders(page.graphics, new RectangleF(new PointF(10, 10), new SizeF(50, 50)));
t2.drawCellBorders(page.graphics, new RectangleF(new PointF(10, 500), new SizeF(50, 600)));
it('Grid.style.font != null && GetTextFont() calling', () => {
let document : PdfDocument = new PdfDocument();
let font : PdfFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 10);
let page : PdfPage = document.pages.add();
let grid : PdfGrid = new PdfGrid();
grid.columns.add(3);
//Add header.
grid.headers.add(1);
let pdfGridHeader3 : PdfGridRow = grid.headers.getHeader(0);
pdfGridHeader3.cells.getCell(0).value = 'ID';
pdfGridHeader3.cells.getCell(0).style.font = font;
pdfGridHeader3.cells.getCell(0).style.textBrush = new PdfSolidBrush(new PdfColor(127, 255, 212));
pdfGridHeader3.cells.getCell(0).style.textPen = new PdfPen(new PdfColor(127, 255, 212));
pdfGridHeader3.cells.getCell(0).style.backgroundBrush = new PdfSolidBrush(new PdfColor(127, 255, 212));
pdfGridHeader3.cells.getCell(0).style.stringFormat = new PdfStringFormat(PdfTextAlignment.Center);
pdfGridHeader3.cells.getCell(1).value = 'Company name';
pdfGridHeader3.cells.getCell(2).value = 'Salary';
for (let i : number = 0; i < 50; i++) {
let pdfGridRow1 : PdfGridRow = grid.rows.addRow();
pdfGridRow1.cells.getCell(0).value = 'E-1';
pdfGridRow1.cells.getCell(0).style.font = font;
pdfGridRow1.cells.getCell(0).style.cellPadding = new PdfPaddings(3, 4, 5, 6);
pdfGridRow1.cells.getCell(0).style.textBrush = new PdfSolidBrush(new PdfColor(127, 255, 212));
pdfGridRow1.cells.getCell(0).style.textPen = new PdfPen(new PdfColor(127, 255, 212));
pdfGridRow1.cells.getCell(0).style.backgroundBrush = new PdfSolidBrush(new PdfColor(127, 255, 212));
pdfGridRow1.cells.getCell(0).style.stringFormat = new PdfStringFormat(PdfTextAlignment.Center);
pdfGridRow1.cells.getCell(1).value = 'Syncfusion Software Private Limited';
pdfGridRow1.cells.getCell(2).value = '$15,000';
}
let bounds : RectangleF = new RectangleF(10, 10, 100, 200);
grid.rows.getRow(0).cells.getCell(0).draw(page.graphics, bounds, true);
// it('MeasureHeight() with Padding', () => {
expect(function (): void {grid.rows.getRow(0).cells.getCell(0).measureHeight();}).not.toThrowError();
// })
// it('t3.style.borders = null - testing', () => {
// t3.style.borders = null;
expect(function (): void {t2.drawCellBorders(page.graphics, new RectangleF(new PointF(10, 500), new SizeF(50, 600)));}).not.toThrowError();
// })
})
});
});
// let t3 : PdfGridCell = new PdfGridCell(gridRow);
// it('-RemainingString == undefined', () => {
// expect(t1.remainingString).toBeUndefined();
// })
// it('-Set RemainingString', () => {
// t1.remainingString = 'grid';
// expect(t1.remainingString).toEqual('grid');
// })
// it('-stringFormat != undefined', () => {
// expect(t1.stringFormat).not.toBeUndefined();
// })
// it('-Set stringFormat', () => {
// let value : PdfStringFormat = new PdfStringFormat();
// t1.stringFormat = value;
// expect(t1.stringFormat).not.toBeUndefined();
// })
// it('-row == undefined', () => {
// expect(t1.row).toBeUndefined();
// })
// it('-Set row', () => {
// t1.row = gridRow;
// expect(t1.row).not.toBeUndefined();
// })
// it('-value == undefined', () => {
// expect(t1.value).toBeUndefined();
// })
// it('-Set value', () => {
// t1.value = 1;
// expect(t1.value).toEqual(1);
// })
// it('-rowSpan == 1', () => {
// expect(t1.rowSpan).toEqual(1);
// })
// it('-Set rowSpan == 3', () => {
// t1.rowSpan = 3;
// expect(t1.rowSpan).toEqual(3);
// })
// it('-Set rowSpan == -1', () => {
// expect(function (): void {t1.rowSpan = -1; }).toThrowError();
// })
// it('-style != undefined', () => {
// expect(t1.style).not.toBeUndefined();
// })
// it('-Set style', () => {
// let value : PdfGridCellStyle = new PdfGridCellStyle();
// t1.style = value;
// expect(t1.style).not.toBeUndefined();
// })
// // it('-height == undefined', () => {
// // expect(t1.height).toBeUndefined();
// // })
// it('-Set height', () => {
// t1.height = 50;
// expect(t1.height).toEqual(50);
// })
// it('-columnSpan == 1', () => {
// expect(t1.columnSpan).toEqual(1);
// })
// it('-Set columnSpan == 3', () => {
// t1.columnSpan = 3;
// expect(t1.columnSpan).toEqual(3);
// })
// it('-Set columnSpan == -1', () => {
// expect(function (): void {t1.columnSpan = -1;}).toThrowError();
// })
// it('-width == 5.52', () => {
// expect(t1.width).not.toBeNull();
// })
// it('-Set width', () => {
// t1.width = 1;
// expect(t1.width).toEqual(1);
// })
// it('-isRowMergeContinue == true', () => {
// t1.isRowMergeContinue = true;
// expect(t1.isRowMergeContinue).not.toBeNull();
// })
// it('-isCellMergeContinue == true', () => {
// t1.isCellMergeContinue = true;
// expect(t1.isCellMergeContinue).not.toBeNull();
// })
// let document : PdfDocument = new PdfDocument()
// let page : PdfPage = document.pages.add();
// let graphics : PdfGraphics = page.graphics;
// let rect : RectangleF = new RectangleF(new PointF(10, 10), new SizeF(50, 50));
// t2.drawCellBackground(graphics, rect);
// t2.drawCellBorders(graphics, rect);
// t2.style.cellPadding = new PdfPaddings(2, 3, 4, 5);
// t2.draw(page.graphics, new RectangleF(new PointF(10, 10), new SizeF(50, 50)), true);
// t2.rowSpan = 2;
// t2.draw(page.graphics, new RectangleF(new PointF(10, 10), new SizeF(50, 50)), true);
// t2.draw(page.graphics, new RectangleF(new PointF(10, 10), new SizeF(50, 50)), true);
// let border : PdfBorders = new PdfBorders();
// let pen : PdfPen = new PdfPen(new PdfColor(0, 0, 255), 10);
// pen.dashStyle = PdfDashStyle.Dot;
// border.all = pen;
// t2.style.borders = border;
// t2.drawCellBorders(page.graphics, new RectangleF(new PointF(10, 10), new SizeF(50, 50)));
// t2.drawCellBorders(page.graphics, new RectangleF(new PointF(10, 500), new SizeF(50, 600)));
// it('Grid.style.font != null && GetTextFont() calling', () => {
// let document : PdfDocument = new PdfDocument();
// let font : PdfFont = new PdfStandardFont(PdfFontFamily.TimesRoman, 10);
// let page : PdfPage = document.pages.add();
// let grid : PdfGrid = new PdfGrid();
// grid.columns.add(3);
// //Add header.
// grid.headers.add(1);
// let pdfGridHeader3 : PdfGridRow = grid.headers.getHeader(0);
// pdfGridHeader3.cells.getCell(0).value = 'ID';
// pdfGridHeader3.cells.getCell(0).style.font = font;
// pdfGridHeader3.cells.getCell(0).style.textBrush = new PdfSolidBrush(new PdfColor(127, 255, 212));
// pdfGridHeader3.cells.getCell(0).style.textPen = new PdfPen(new PdfColor(127, 255, 212));
// pdfGridHeader3.cells.getCell(0).style.backgroundBrush = new PdfSolidBrush(new PdfColor(127, 255, 212));
// pdfGridHeader3.cells.getCell(0).style.stringFormat = new PdfStringFormat(PdfTextAlignment.Center);
// pdfGridHeader3.cells.getCell(1).value = 'Company name';
// pdfGridHeader3.cells.getCell(2).value = 'Salary';
// for (let i : number = 0; i < 50; i++) {
// let pdfGridRow1 : PdfGridRow = grid.rows.addRow();
// pdfGridRow1.cells.getCell(0).value = 'E-1';
// pdfGridRow1.cells.getCell(0).style.font = font;
// pdfGridRow1.cells.getCell(0).style.cellPadding = new PdfPaddings(3, 4, 5, 6);
// pdfGridRow1.cells.getCell(0).style.textBrush = new PdfSolidBrush(new PdfColor(127, 255, 212));
// pdfGridRow1.cells.getCell(0).style.textPen = new PdfPen(new PdfColor(127, 255, 212));
// pdfGridRow1.cells.getCell(0).style.backgroundBrush = new PdfSolidBrush(new PdfColor(127, 255, 212));
// pdfGridRow1.cells.getCell(0).style.stringFormat = new PdfStringFormat(PdfTextAlignment.Center);
// pdfGridRow1.cells.getCell(1).value = 'Syncfusion Software Private Limited';
// pdfGridRow1.cells.getCell(2).value = '$15,000';
// }
// let bounds : RectangleF = new RectangleF(10, 10, 100, 200);
// grid.rows.getRow(0).cells.getCell(0).draw(page.graphics, bounds, true);
// it('MeasureHeight() with Padding', () => {
// expect(function (): void {grid.rows.getRow(0).cells.getCell(0).measureHeight();}).not.toThrowError();
// })
// it('t3.style.borders = null - testing', () => {
// t3.style.borders = null;
// expect(function (): void {t2.drawCellBorders(page.graphics, new RectangleF(new PointF(10, 500), new SizeF(50, 600)));}).toThrowError();
// })
// })
// })
// })
describe('PdfGridCellCollection.ts', () => {
describe('Constructor initializing',()=> {
let grid : PdfGrid = new PdfGrid();
let gridRow : PdfGridRow = new PdfGridRow(grid);
let t1 : PdfGridCellCollection = new PdfGridCellCollection(gridRow);
it('-count == 2', () => {
expect(t1.count).toEqual(2);
})
let gridCell : PdfGridCell = new PdfGridCell();
t1.add();
it('-this.Add() method calling', () => {
expect(t1.add()).toBeUndefined();
})
t1.add(gridCell);
it('-this.Add(PdfGridCell) method calling', () => {
expect(t1.add(gridCell)).toBeUndefined();
})
t1.indexOf(gridCell);
it('-this.IndexOf(PdfGridCell) method calling', () => {
expect(t1.indexOf(gridCell)).not.toBeUndefined();
});
it('-this.getCell(number) method calling', () => {
expect(function (): void {t1.getCell(-1); }).toThrowError();
})
})
}) | the_stack |
import * as vscode from 'vscode';
import { promises as fs, PathLike } from 'fs';
import path from 'path';
import AppMapAgent, { StatusResponse } from './agent/appMapAgent';
import LanguageResolver from './languageResolver';
import { createMilestones, MilestoneMap, MilestoneType } from './milestones';
import {
Telemetry,
DEBUG_EXCEPTION,
PROJECT_CLIENT_AGENT_REMOVE,
PROJECT_CONFIG_WRITE,
PROJECT_OPEN,
} from './telemetry';
import { unreachable } from './util';
import AppMapProperties from './appmapProperties';
import { ErrorUnsupportedLanguage } from './agent/AppMapAgentDummy';
function resolveFullyQualifiedKey(key: string, obj: Record<string, unknown>): unknown {
const tokens = key.split(/\./);
let iterObj = obj;
for (;;) {
if (!iterObj) {
return undefined;
}
const token = tokens.shift();
if (!token) {
return iterObj;
}
iterObj = iterObj[token] as Record<string, unknown>;
}
}
/**
* A utility class that provides simplified object property comparisons.
*/
class ObjectKeyDiff {
private readonly last: Record<string, unknown> | undefined;
private readonly current: Record<string, unknown>;
constructor(last: Record<string, unknown> | undefined, current: Record<string, unknown>) {
this.last = last;
this.current = current;
}
getValues(key: string): [unknown, unknown] | undefined {
if (!this.last) {
return undefined;
}
return [resolveFullyQualifiedKey(key, this.last), resolveFullyQualifiedKey(key, this.current)];
}
changed(key: string): boolean {
return (
this.last !== undefined &&
resolveFullyQualifiedKey(key, this.last) !== resolveFullyQualifiedKey(key, this.current)
);
}
valueChangedTo(key: string, value: unknown): boolean {
return this.changed(key) && this.current[key] === value;
}
/**
* Receive a callback if the value of `key` differs.
* @param key The key to be compared in both objects
* @param callback If the values differ, a callback to receive both values
*/
on(key, callback: (newVal: unknown, oldVal: unknown) => void): ObjectKeyDiff {
const values = this.getValues(key);
if (values) {
if (values[0] !== values[1]) {
callback(values[1], values[0]);
}
}
return this;
}
}
interface ProjectWatcherState {
onEnter?(project: ProjectWatcher): void;
onExit?(project: ProjectWatcher): void;
tick(
project: ProjectWatcher,
agent: AppMapAgent,
lastStatus?: StatusResponse
): Promise<StatusResponse | undefined>;
}
/**
* ProjectWatcher state definitions.
* - `onEnter`: Called when this state becomes the current state.
* - `onExit`: Called just before changing to another state.
* - `tick`: Called every time the ProjectWatcher is ticked.
*/
const STATE = {
WAIT_FOR_AGENT_INSTALL: new (class implements ProjectWatcherState {
onEnter(project: ProjectWatcher) {
project.milestones.INSTALL_AGENT.setState('incomplete');
}
onExit(project: ProjectWatcher) {
project.milestones.INSTALL_AGENT.setState('complete');
project.milestones.RECORD_APPMAP.setState('incomplete');
project.milestones.VIEW_APPMAP.setState('incomplete');
}
async tick(project: ProjectWatcher, agent: AppMapAgent): Promise<StatusResponse | undefined> {
const isInstalled = await agent.isInstalled(project.rootDirectory);
if (!isInstalled) {
return undefined;
}
let initialStatus: StatusResponse | undefined;
try {
initialStatus = await agent.status(project.rootDirectory);
const { config } = initialStatus.properties;
if (config.present) {
project.milestones.CREATE_CONFIGURATION.setState(config.valid ? 'complete' : 'error');
}
} catch (e) {
// It's likely the user has an incompatible version of the agent. An upgrade will need to be performed.
project.milestones.INSTALL_AGENT.setState('error');
return undefined;
}
project.setState(STATE.WATCH_PROJECT_STATUS);
return initialStatus;
}
})(),
WATCH_PROJECT_STATUS: new (class implements ProjectWatcherState {
private appmapCreatedListener?: vscode.Disposable;
cleanupListener() {
this.appmapCreatedListener?.dispose();
this.appmapCreatedListener = undefined;
}
onEnter(project: ProjectWatcher) {
if (project.appmapExists()) {
return;
}
this.appmapCreatedListener = project.onAppMapCreated(() => {
project.milestones.RECORD_APPMAP.setState('complete');
project.forceNextTick();
this.cleanupListener();
});
}
onExit(project: ProjectWatcher) {
Telemetry.sendEvent(PROJECT_CLIENT_AGENT_REMOVE, {
rootDirectory: project.rootDirectory,
});
this.cleanupListener();
}
async tick(
project: ProjectWatcher,
agent: AppMapAgent,
lastStatus?: StatusResponse
): Promise<StatusResponse | undefined> {
const isInstalled = await agent.isInstalled(project.rootDirectory);
if (!isInstalled) {
project.setState(STATE.WAIT_FOR_AGENT_INSTALL);
return;
}
const status = await agent.status(project.rootDirectory);
if (!status) {
project.setState(STATE.WAIT_FOR_AGENT_INSTALL);
return;
}
// Begin comparing the results of this status report to the last good status report. We want to react to properties
// which have changed between the two.
const diff = new ObjectKeyDiff(
lastStatus as Record<string, unknown> | undefined,
(status as unknown) as Record<string, unknown>
);
diff
.on('properties.config.present', (isPresent) => {
// Send a telemetry event.
Telemetry.sendEvent(PROJECT_CONFIG_WRITE, {
rootDirectory: project.rootDirectory,
});
if (!isPresent) {
project.milestones.CREATE_CONFIGURATION.setState('incomplete');
}
})
.on('properties.config.valid', (isValid) => {
if (isValid) {
project.milestones.CREATE_CONFIGURATION.setState('complete');
project.milestones.RECORD_APPMAP.setState('incomplete');
project.milestones.VIEW_APPMAP.setState('incomplete');
} else if (status.properties.config.present) {
project.milestones.CREATE_CONFIGURATION.setState('error');
}
});
if (await project.appmapExists()) {
project.milestones.RECORD_APPMAP.setState('complete');
}
if (project.appmapOpened()) {
project.milestones.VIEW_APPMAP.setState('complete');
}
return status;
}
})(),
};
/**
* Maintains milestones and project state.
*/
export default class ProjectWatcher {
// onAppMapCreated is emitted when a new AppMap is created within the project directory.
private readonly onAppMapCreatedEmitter = new vscode.EventEmitter<vscode.Uri>();
public readonly onAppMapCreated = this.onAppMapCreatedEmitter.event;
public readonly workspaceFolder: vscode.WorkspaceFolder;
public readonly milestones: MilestoneMap;
public readonly context: vscode.ExtensionContext;
private readonly frequencyMs: number;
private readonly properties: AppMapProperties;
private _language?: string;
private agent?: AppMapAgent;
private nextStatusTimer?: NodeJS.Timeout;
private lastStatus?: StatusResponse;
private currentState: ProjectWatcherState;
constructor(
context: vscode.ExtensionContext,
workspaceFolder: vscode.WorkspaceFolder,
appmapWatcher: vscode.FileSystemWatcher,
properties: AppMapProperties,
frequencyMs = 6000
) {
this.context = context;
this.workspaceFolder = workspaceFolder;
this.frequencyMs = frequencyMs;
this.milestones = createMilestones(this);
this.currentState = STATE.WAIT_FOR_AGENT_INSTALL;
this.properties = properties;
appmapWatcher.onDidCreate((uri) => {
if (uri.fsPath.startsWith(this.rootDirectory as string)) {
this.onAppMapCreatedEmitter.fire(uri);
}
});
}
get rootDirectory(): PathLike {
return this.workspaceFolder.uri.fsPath;
}
/**
* Basic state machine implementation. This method changes the current state, first exiting the current state then
* entering the new state.
*/
setState(state: ProjectWatcherState): void {
if (this.currentState.onExit) {
this.currentState.onExit(this);
}
this.currentState = state;
if (this.currentState.onEnter) {
this.currentState.onEnter(this);
}
}
async performMilestoneAction(id: MilestoneType, data?: Record<string, unknown>): Promise<void> {
if (!this.language || !this.agent) {
throw new Error(`unsupported project type ${this.language ? `(${this.language})` : ''}`);
}
switch (id) {
case 'INSTALL_AGENT':
await this.agent.install(this.rootDirectory);
this.forceNextTick();
break;
case 'CREATE_CONFIGURATION':
{
const response = await this.agent.init(this.rootDirectory);
const { filename, contents } = response.configuration;
await fs.writeFile(path.join(this.rootDirectory as string, filename), contents);
this.forceNextTick();
}
break;
case 'RECORD_APPMAP':
await this.agent.test(this.rootDirectory, data?.command as Array<string>);
break;
default:
// Do nothing
}
}
/**
* Utility getter. Returns true if the user has previously recorded an AppMap in this project directory.
*/
appmapExists(): boolean {
return this.properties.getWorkspaceRecordedAppMap(this.workspaceFolder);
}
/**
* Utility getter. Returns true if the user has previously opened an AppMap from within this project directory.
*/
appmapOpened(): boolean {
return this.properties.getWorkspaceOpenedAppMap(this.workspaceFolder);
}
/**
* Begins the main status polling loop. If appropriate, this method will update or install the agent CLI and run the
* project initialization command prior to the first tick.
*/
async initialize(): Promise<void> {
if (this.nextStatusTimer) {
throw new Error('initialization has already occurred');
}
Telemetry.sendEvent(PROJECT_OPEN, { rootDirectory: this.rootDirectory, agent: this.agent });
this.language = await LanguageResolver.getLanguage(this.rootDirectory);
if (!this.agent) {
const languageDistribution = await LanguageResolver.getLanguageDistribution(
this.rootDirectory
);
throw new Error(
`no agent was found for this project type (${this.language}):\n${JSON.stringify(
languageDistribution,
null,
2
)}`
);
}
// Begin the main loop
this.tick();
}
/**
* Logic for the main status polling loop. This method is called continuously at a frequency set by `frequencyMs`.
*/
private async tick(): Promise<void> {
let status: StatusResponse | undefined;
try {
if (!this.agent) {
unreachable('attempted to tick with no available agent');
}
if (this.nextStatusTimer) {
unreachable('tick was called outside of the main tick loop');
}
status = await this.currentState.tick(this, this.agent, this.lastStatus);
} catch (exception) {
if (exception instanceof ErrorUnsupportedLanguage) {
// give up on this project
return;
}
Telemetry.sendEvent(DEBUG_EXCEPTION, { exception });
// For now, assume that the error is unrecoverable and stop polling.
return;
}
this.queueNextTick(status);
}
/**
* Begin a timer to execute `tick`, the status polling logic.
* @param currentStatus The current status held by the caller, to be used in the next tick as the previous status.
*/
private queueNextTick(currentStatus?: StatusResponse): void {
if (currentStatus) {
this.lastStatus = currentStatus;
}
this.nextStatusTimer = setTimeout(() => {
this.nextStatusTimer = undefined;
this.tick();
}, this.frequencyMs);
}
public forceNextTick(): void {
if (this.nextStatusTimer) {
clearTimeout(this.nextStatusTimer);
this.nextStatusTimer = undefined;
}
this.tick();
}
/**
* @returns An array of test framework identifiers (e.g. `rspec`, `mocha`, etc.) that are used by the project.
*/
get testFrameworks(): Record<string, string> {
return (
this.lastStatus?.test_commands?.reduce((obj, test) => {
const tokens: string[] = [];
if (test.command.environment) {
Object.entries(test.command.environment).forEach(([key, value]) => {
if (value !== undefined) {
tokens.push(`${key}=${value}`);
}
});
}
tokens.push(test.command.program);
if (test.command.args) {
tokens.push(...test.command.args);
}
obj[test.framework] = tokens.join(' ');
return obj;
}, {}) || {}
);
}
async appmapYml(): Promise<string | undefined> {
if (await this.agent?.isInstalled(this.rootDirectory)) {
try {
const response = await this.agent?.init(this.rootDirectory);
return response?.configuration.contents;
} catch {
this.milestones.INSTALL_AGENT.setState('error');
}
}
return undefined;
}
/**
* Changes the language, and thus the agent, used by the project. This is an action permitted by the frontend UI.
*/
set language(language: string | undefined) {
this._language = language;
this.agent = language ? LanguageResolver.getAgentForLanguage(language) : undefined;
}
get language(): string | undefined {
return this._language;
}
} | the_stack |
import { Vector3, Matrix4 } from 'three'
import { Debug, Log, ParserRegistry } from '../globals'
import StructureParser from './structure-parser'
import { HelixTypes } from './pdb-parser'
import Entity from '../structure/entity'
import Unitcell, { UnitcellParams } from '../symmetry/unitcell'
import Assembly from '../symmetry/assembly'
import Selection from '../selection/selection'
import {
assignResidueTypeBonds, assignSecondaryStructure, buildUnitcellAssembly,
calculateBonds, calculateSecondaryStructure
} from '../structure/structure-utils'
import { Structure } from '../ngl';
import StructureBuilder from '../structure/structure-builder';
import { NumberArray } from '../types';
const reWhitespace = /\s+/
const reQuotedWhitespace = /'((?:(?!'\s).)*)'|"((?:(?!"\s).)*)"|(\S+)/g
const reDoubleQuote = /"/g
const reTrimQuotes = /^['"]+|['"]+$/g
interface Cif {[k: string]: any}
function trimQuotes (str: string) {
if (str && str[0] === str[ str.length - 1 ] && (str[0] === "'" || str[0] === '"')) {
return str.substring(1, str.length - 1)
} else {
return str
}
}
function ensureArray (dict: {[k: string]: any[]}, field: string) {
if (!Array.isArray(dict[ field ])) {
Object.keys(dict).forEach(function (key) {
dict[ key ] = [ dict[ key ] ]
})
}
}
function hasValue (d: string) {
return d !== '?'
}
function cifDefaults (value: string, defaultValue: string) {
return hasValue(value) ? value : defaultValue
}
function getBondOrder (valueOrder: string) {
switch (valueOrder.toLowerCase()) {
case '?': // assume single bond
case 'sing':
return 1
case 'doub':
return 2
case 'trip':
return 3
case 'quad':
return 4
}
return 0
}
function parseChemComp (cif: Cif, structure: Structure, structureBuilder: StructureBuilder) {
const atomStore = structure.atomStore
const atomMap = structure.atomMap
let i, n
const cc = cif.chem_comp
const cca = cif.chem_comp_atom
const ccb = cif.chem_comp_bond
if (cc) {
if (cc.name) {
structure.title = cc.name.trim().replace(reTrimQuotes, '')
}
if (cc.id) {
structure.id = cc.id.trim().replace(reTrimQuotes, '')
}
}
var atomnameDict: {[k: string]: number} = {}
if (cca) {
ensureArray(cca, 'comp_id')
var atomname, element, resname, resno
n = cca.comp_id.length
for (i = 0; i < n; ++i) {
atomStore.growIfFull()
atomname = cca.atom_id[ i ].replace(reDoubleQuote, '')
element = cca.type_symbol[ i ]
atomnameDict[ atomname ] = i
atomStore.atomTypeId[ i ] = atomMap.add(atomname, element)
atomStore.x[ i ] = cca.model_Cartn_x[ i ]
atomStore.y[ i ] = cca.model_Cartn_y[ i ]
atomStore.z[ i ] = cca.model_Cartn_z[ i ]
atomStore.serial[ i ] = i
resname = cca.pdbx_component_comp_id[ i ]
resno = cca.pdbx_residue_numbering ? cca.pdbx_residue_numbering[ i ] : 1
structureBuilder.addAtom(0, '', '', resname, resno, true)
}
for (i = 0; i < n; ++i) {
var j = i + n
atomStore.growIfFull()
atomname = cca.atom_id[ i ].replace(reDoubleQuote, '')
element = cca.type_symbol[ i ]
atomStore.atomTypeId[ j ] = atomMap.add(atomname, element)
atomStore.x[ j ] = cca.pdbx_model_Cartn_x_ideal[ i ]
atomStore.y[ j ] = cca.pdbx_model_Cartn_y_ideal[ i ]
atomStore.z[ j ] = cca.pdbx_model_Cartn_z_ideal[ i ]
atomStore.serial[ j ] = j
resname = cca.pdbx_component_comp_id[ i ]
resno = cca.pdbx_residue_numbering ? cca.pdbx_residue_numbering[ i ] : 1
structureBuilder.addAtom(1, '', '', resname, resno, true)
}
}
if (cca && ccb) {
ensureArray(ccb, 'comp_id')
var atomname1, atomname2, bondOrder
n = ccb.comp_id.length
var na = cca.comp_id.length
var ap1 = structure.getAtomProxy()
var ap2 = structure.getAtomProxy()
for (i = 0; i < n; ++i) {
atomname1 = ccb.atom_id_1[ i ].replace(reDoubleQuote, '')
atomname2 = ccb.atom_id_2[ i ].replace(reDoubleQuote, '')
bondOrder = getBondOrder(ccb.value_order[ i ])
ap1.index = atomnameDict[ atomname1 ]
ap2.index = atomnameDict[ atomname2 ]
structure.bondStore.growIfFull()
structure.bondStore.addBond(ap1, ap2, bondOrder)
ap1.index += na
ap2.index += na
structure.bondStore.growIfFull()
structure.bondStore.addBond(ap1, ap2, bondOrder)
}
}
}
function parseCore (cif: Cif, structure: Structure, structureBuilder: StructureBuilder) {
var atomStore = structure.atomStore
var atomMap = structure.atomMap
if (cif.data) {
structure.id = cif.data
structure.name = cif.data
}
structure.unitcell = new Unitcell({
a: parseFloat(cif.cell_length_a),
b: parseFloat(cif.cell_length_b),
c: parseFloat(cif.cell_length_c),
alpha: parseFloat(cif.cell_angle_alpha),
beta: parseFloat(cif.cell_angle_beta),
gamma: parseFloat(cif.cell_angle_gamma),
spacegroup: trimQuotes(cif['symmetry_space_group_name_H-M'])
})
const v = new Vector3()
const c = new Vector3()
const n = cif.atom_site_type_symbol.length
for (let i = 0; i < n; ++i) {
atomStore.growIfFull()
const atomname = cif.atom_site_label[ i ]
const element = cif.atom_site_type_symbol[ i ]
atomStore.atomTypeId[ i ] = atomMap.add(atomname, element)
v.set(
cif.atom_site_fract_x[ i ],
cif.atom_site_fract_y[ i ],
cif.atom_site_fract_z[ i ]
)
v.applyMatrix4(structure.unitcell.fracToCart)
c.add(v)
atomStore.x[ i ] = v.x
atomStore.y[ i ] = v.y
atomStore.z[ i ] = v.z
if (cif.atom_site_occupancy) {
atomStore.occupancy[ i ] = parseFloat(cif.atom_site_occupancy[ i ])
}
atomStore.serial[ i ] = i
structureBuilder.addAtom(0, '', '', 'HET', 1, true)
}
c.divideScalar(n)
structure.center = c
buildUnitcellAssembly(structure)
const v2 = new Vector3()
const v3 = new Vector3()
const ml = structure.biomolDict.SUPERCELL.partList[ 0 ].matrixList
let k = n
function covalent (idx: number) {
return atomMap.get(atomStore.atomTypeId[ idx ]).covalent
}
const identityMatrix = new Matrix4()
for (let i = 0; i < n; ++i) {
const covalentI = covalent(i)
v.set(
atomStore.x[ i ],
atomStore.y[ i ],
atomStore.z[ i ]
)
ml.forEach(function (m) {
if (identityMatrix.equals(m)) return
v2.copy(v)
v2.applyMatrix4(m)
for (let j = 0; j < n; ++j) {
v3.set(
atomStore.x[ j ],
atomStore.y[ j ],
atomStore.z[ j ]
)
const distSquared = v2.distanceToSquared(v3)
const d = covalent(j) + covalentI
const d1 = d + 0.3
const d2 = d - 0.5
if (distSquared < (d1 * d1) && distSquared > (d2 * d2)) {
atomStore.growIfFull()
atomStore.atomTypeId[ k ] = atomStore.atomTypeId[ i ]
atomStore.x[ k ] = v2.x
atomStore.y[ k ] = v2.y
atomStore.z[ k ] = v2.z
atomStore.occupancy[ k ] = atomStore.occupancy[ i ]
atomStore.serial[ k ] = k
atomStore.altloc[ k ] = 'A'.charCodeAt(0)
structureBuilder.addAtom(0, '', '', 'HET', 1, true)
k += 1
return
}
}
})
}
}
function processSecondaryStructure (cif: Cif, structure: Structure, asymIdDict: {[k: string]: string}) {
var helices: [string, number, string, string, number, string, number][] = []
var sheets: [string, number, string, string, number, string][] = []
var i, il, begIcode, endIcode
// get helices
var sc = cif.struct_conf
if (sc) {
ensureArray(sc, 'id')
for (i = 0, il = sc.beg_auth_seq_id.length; i < il; ++i) {
var helixType = parseInt(sc.pdbx_PDB_helix_class[ i ])
if (!Number.isNaN(helixType)) {
begIcode = sc.pdbx_beg_PDB_ins_code[ i ]
endIcode = sc.pdbx_end_PDB_ins_code[ i ]
helices.push([
asymIdDict[ sc.beg_label_asym_id[ i ] ],
parseInt(sc.beg_auth_seq_id[ i ]),
cifDefaults(begIcode, ''),
asymIdDict[ sc.end_label_asym_id[ i ] ],
parseInt(sc.end_auth_seq_id[ i ]),
cifDefaults(endIcode, ''),
(HelixTypes[ helixType ] || HelixTypes[0]).charCodeAt(0)
])
}
}
}
// get sheets
var ssr = cif.struct_sheet_range
if (ssr) {
ensureArray(ssr, 'id')
for (i = 0, il = ssr.beg_auth_seq_id.length; i < il; ++i) {
begIcode = ssr.pdbx_beg_PDB_ins_code[ i ]
endIcode = ssr.pdbx_end_PDB_ins_code[ i ]
sheets.push([
asymIdDict[ ssr.beg_label_asym_id[ i ] ],
parseInt(ssr.beg_auth_seq_id[ i ]),
cifDefaults(begIcode, ''),
asymIdDict[ ssr.end_label_asym_id[ i ] ],
parseInt(ssr.end_auth_seq_id[ i ]),
cifDefaults(endIcode, '')
])
}
}
if (sc || ssr) {
return {
helices: helices,
sheets: sheets
}
} else {
return false
}
}
function processSymmetry (cif: Cif, structure: Structure, asymIdDict: {[k: string]: string}) {
// biomol & ncs processing
var operDict: {[k: string]: Matrix4} = {}
var biomolDict = structure.biomolDict
if (cif.pdbx_struct_oper_list) {
var biomolOp = cif.pdbx_struct_oper_list
ensureArray(biomolOp, 'id')
biomolOp.id.forEach(function (id: number, i: number) {
var m = new Matrix4()
var elms = m.elements
elms[ 0 ] = parseFloat(biomolOp[ 'matrix[1][1]' ][ i ])
elms[ 1 ] = parseFloat(biomolOp[ 'matrix[1][2]' ][ i ])
elms[ 2 ] = parseFloat(biomolOp[ 'matrix[1][3]' ][ i ])
elms[ 4 ] = parseFloat(biomolOp[ 'matrix[2][1]' ][ i ])
elms[ 5 ] = parseFloat(biomolOp[ 'matrix[2][2]' ][ i ])
elms[ 6 ] = parseFloat(biomolOp[ 'matrix[2][3]' ][ i ])
elms[ 8 ] = parseFloat(biomolOp[ 'matrix[3][1]' ][ i ])
elms[ 9 ] = parseFloat(biomolOp[ 'matrix[3][2]' ][ i ])
elms[ 10 ] = parseFloat(biomolOp[ 'matrix[3][3]' ][ i ])
elms[ 3 ] = parseFloat(biomolOp[ 'vector[1]' ][ i ])
elms[ 7 ] = parseFloat(biomolOp[ 'vector[2]' ][ i ])
elms[ 11 ] = parseFloat(biomolOp[ 'vector[3]' ][ i ])
m.transpose()
operDict[ id ] = m
})
}
if (cif.pdbx_struct_assembly_gen) {
var gen = cif.pdbx_struct_assembly_gen
ensureArray(gen, 'assembly_id')
var getMatrixDict = function (expr: string) {
var matDict: {[k: string]: Matrix4} = {}
var l = expr.replace(/[()']/g, '').split(',')
l.forEach(function (e) {
if (e.includes('-')) {
var es = e.split('-')
var j = parseInt(es[ 0 ])
var m = parseInt(es[ 1 ])
for (; j <= m; ++j) {
matDict[ j ] = operDict[ j ]
}
} else {
matDict[ e ] = operDict[ e ]
}
})
return matDict
}
gen.assembly_id.forEach(function (id: string, i: number) {
var md:{[k: string]: Matrix4} = {}
var oe = gen.oper_expression[ i ].replace(/['"]\(|['"]/g, '')
if (oe.includes(')(') || oe.indexOf('(') > 0) {
oe = oe.split('(')
var md1 = getMatrixDict(oe[ 0 ])
var md2 = getMatrixDict(oe[ 1 ])
Object.keys(md1).forEach(function (k1) {
Object.keys(md2).forEach(function (k2) {
var mat = new Matrix4()
mat.multiplyMatrices(md1[ k1 ], md2[ k2 ])
md[ k1 + 'x' + k2 ] = mat
})
})
} else {
md = getMatrixDict(oe)
}
var matrixList = []
for (var k in md) {
matrixList.push(md[ k ])
}
var name = id
if (/^(0|[1-9][0-9]*)$/.test(name)) name = 'BU' + name
var chainList = gen.asym_id_list[ i ].split(',')
for (var j = 0, jl = chainList.length; j < jl; ++j) {
chainList[ j ] = asymIdDict[ chainList[ j ] ]
}
if (biomolDict[ name ] === undefined) {
biomolDict[ name ] = new Assembly(name)
}
biomolDict[ name ].addPart(matrixList, chainList)
})
}
// non-crystallographic symmetry operations
if (cif.struct_ncs_oper) {
var ncsOp = cif.struct_ncs_oper
ensureArray(ncsOp, 'id')
var ncsName = 'NCS'
biomolDict[ ncsName ] = new Assembly(ncsName)
var ncsPart = biomolDict[ ncsName ].addPart()
ncsOp.id.forEach(function (id: string, i: number) {
// ignore 'given' operators
if (ncsOp.code[ i ] === 'given') return
var m = new Matrix4()
var elms = m.elements
elms[ 0 ] = parseFloat(ncsOp[ 'matrix[1][1]' ][ i ])
elms[ 1 ] = parseFloat(ncsOp[ 'matrix[1][2]' ][ i ])
elms[ 2 ] = parseFloat(ncsOp[ 'matrix[1][3]' ][ i ])
elms[ 4 ] = parseFloat(ncsOp[ 'matrix[2][1]' ][ i ])
elms[ 5 ] = parseFloat(ncsOp[ 'matrix[2][2]' ][ i ])
elms[ 6 ] = parseFloat(ncsOp[ 'matrix[2][3]' ][ i ])
elms[ 8 ] = parseFloat(ncsOp[ 'matrix[3][1]' ][ i ])
elms[ 9 ] = parseFloat(ncsOp[ 'matrix[3][2]' ][ i ])
elms[ 10 ] = parseFloat(ncsOp[ 'matrix[3][3]' ][ i ])
elms[ 3 ] = parseFloat(ncsOp[ 'vector[1]' ][ i ])
elms[ 7 ] = parseFloat(ncsOp[ 'vector[2]' ][ i ])
elms[ 11 ] = parseFloat(ncsOp[ 'vector[3]' ][ i ])
m.transpose()
ncsPart.matrixList.push(m)
})
if (ncsPart.matrixList.length === 0) {
delete biomolDict[ ncsName ]
}
}
// cell & symmetry
const unitcellDict: {
a?: number
b?: number
c?: number
alpha?: number
beta?: number
gamma?: number
spacegroup?: string
origx?: Matrix4
scale?: Matrix4
} = {}
if (cif.cell) {
const cell = cif.cell
const a = parseFloat(cell.length_a)
const b = parseFloat(cell.length_b)
const c = parseFloat(cell.length_c)
const box = new Float32Array(9)
box[ 0 ] = a
box[ 4 ] = b
box[ 8 ] = c
structure.boxes.push(box)
unitcellDict.a = a
unitcellDict.b = b
unitcellDict.c = c
unitcellDict.alpha = parseFloat(cell.angle_alpha)
unitcellDict.beta = parseFloat(cell.angle_beta)
unitcellDict.gamma = parseFloat(cell.angle_gamma)
}
if (cif.symmetry) {
unitcellDict.spacegroup = trimQuotes(
cif.symmetry[ 'space_group_name_H-M' ]
)
}
// origx
var origx = new Matrix4()
if (cif.database_PDB_matrix) {
var origxMat = cif.database_PDB_matrix
var origxElms = origx.elements
origxElms[ 0 ] = parseFloat(origxMat[ 'origx[1][1]' ])
origxElms[ 1 ] = parseFloat(origxMat[ 'origx[1][2]' ])
origxElms[ 2 ] = parseFloat(origxMat[ 'origx[1][3]' ])
origxElms[ 4 ] = parseFloat(origxMat[ 'origx[2][1]' ])
origxElms[ 5 ] = parseFloat(origxMat[ 'origx[2][2]' ])
origxElms[ 6 ] = parseFloat(origxMat[ 'origx[2][3]' ])
origxElms[ 8 ] = parseFloat(origxMat[ 'origx[3][1]' ])
origxElms[ 9 ] = parseFloat(origxMat[ 'origx[3][2]' ])
origxElms[ 10 ] = parseFloat(origxMat[ 'origx[3][3]' ])
origxElms[ 3 ] = parseFloat(origxMat[ 'origx_vector[1]' ])
origxElms[ 7 ] = parseFloat(origxMat[ 'origx_vector[2]' ])
origxElms[ 11 ] = parseFloat(origxMat[ 'origx_vector[3]' ])
origx.transpose()
unitcellDict.origx = origx
}
// scale
var scale = new Matrix4()
if (cif.atom_sites) {
var scaleMat = cif.atom_sites
var scaleElms = scale.elements
scaleElms[ 0 ] = parseFloat(scaleMat[ 'fract_transf_matrix[1][1]' ])
scaleElms[ 1 ] = parseFloat(scaleMat[ 'fract_transf_matrix[1][2]' ])
scaleElms[ 2 ] = parseFloat(scaleMat[ 'fract_transf_matrix[1][3]' ])
scaleElms[ 4 ] = parseFloat(scaleMat[ 'fract_transf_matrix[2][1]' ])
scaleElms[ 5 ] = parseFloat(scaleMat[ 'fract_transf_matrix[2][2]' ])
scaleElms[ 6 ] = parseFloat(scaleMat[ 'fract_transf_matrix[2][3]' ])
scaleElms[ 8 ] = parseFloat(scaleMat[ 'fract_transf_matrix[3][1]' ])
scaleElms[ 9 ] = parseFloat(scaleMat[ 'fract_transf_matrix[3][2]' ])
scaleElms[ 10 ] = parseFloat(scaleMat[ 'fract_transf_matrix[3][3]' ])
scaleElms[ 3 ] = parseFloat(scaleMat[ 'fract_transf_vector[1]' ])
scaleElms[ 7 ] = parseFloat(scaleMat[ 'fract_transf_vector[2]' ])
scaleElms[ 11 ] = parseFloat(scaleMat[ 'fract_transf_vector[3]' ])
scale.transpose()
unitcellDict.scale = scale
}
if (unitcellDict.a !== undefined) {
structure.unitcell = new Unitcell(unitcellDict as UnitcellParams)
} else {
structure.unitcell = undefined
}
}
function processConnections (cif: Cif, structure: Structure, asymIdDict: {[k: string]: string}) {
// add connections
var sc = cif.struct_conn
if (sc) {
ensureArray(sc, 'id')
var reDoubleQuote = /"/g
var ap1 = structure.getAtomProxy()
var ap2 = structure.getAtomProxy()
var atomIndicesCache: {[k: string]: Uint32Array|undefined} = {}
for (var i = 0, il = sc.id.length; i < il; ++i) {
// ignore:
// hydrog - hydrogen bond
// mismat - mismatched base pairs
// saltbr - ionic interaction
var connTypeId = sc.conn_type_id[ i ]
if (connTypeId === 'hydrog' ||
connTypeId === 'mismat' ||
connTypeId === 'saltbr') continue
// ignore bonds between symmetry mates
if (sc.ptnr1_symmetry[ i ] !== '1_555' ||
sc.ptnr2_symmetry[ i ] !== '1_555') continue
// process:
// covale - covalent bond
// covale_base -
// covalent modification of a nucleotide base
// covale_phosphate -
// covalent modification of a nucleotide phosphate
// covale_sugar -
// covalent modification of a nucleotide sugar
// disulf - disulfide bridge
// metalc - metal coordination
// modres - covalent residue modification
var inscode1 = sc.pdbx_ptnr1_PDB_ins_code[ i ]
var altloc1 = sc.pdbx_ptnr1_label_alt_id[ i ]
var sele1 = (
sc.ptnr1_auth_seq_id[ i ] +
(hasValue(inscode1) ? ('^' + inscode1) : '') +
':' + asymIdDict[ sc.ptnr1_label_asym_id[ i ] ] +
'.' + sc.ptnr1_label_atom_id[ i ].replace(reDoubleQuote, '') +
(hasValue(altloc1) ? ('%' + altloc1) : '')
)
var atomIndices1 = atomIndicesCache[ sele1 ]
if (!atomIndices1) {
var selection1 = new Selection(sele1)
if (selection1.selection.error) {
if (Debug) Log.warn('invalid selection for connection', sele1)
continue
}
atomIndices1 = structure.getAtomIndices(selection1)
atomIndicesCache[ sele1 ] = atomIndices1
}
var inscode2 = sc.pdbx_ptnr2_PDB_ins_code[ i ]
var altloc2 = sc.pdbx_ptnr2_label_alt_id[ i ]
var sele2 = (
sc.ptnr2_auth_seq_id[ i ] +
(hasValue(inscode2) ? ('^' + inscode2) : '') +
':' + asymIdDict[ sc.ptnr2_label_asym_id[ i ] ] +
'.' + sc.ptnr2_label_atom_id[ i ].replace(reDoubleQuote, '') +
(hasValue(altloc2) ? ('%' + altloc2) : '')
)
var atomIndices2 = atomIndicesCache[ sele2 ]
if (!atomIndices2) {
var selection2 = new Selection(sele2)
if (selection2.selection.error) {
if (Debug) Log.warn('invalid selection for connection', sele2)
continue
}
atomIndices2 = structure.getAtomIndices(selection2)
atomIndicesCache[ sele2 ] = atomIndices2
}
// cases with more than one atom per selection
// - #altloc1 to #altloc2
// - #model to #model
// - #altloc1 * #model to #altloc2 * #model
var k = atomIndices1!.length
var l = atomIndices2!.length
if (k > l) {
var tmpA = k
k = l
l = tmpA
var tmpB = atomIndices1
atomIndices1 = atomIndices2
atomIndices2 = tmpB
}
// console.log( k, l );
if (k === 0 || l === 0) {
if (Debug) Log.warn('no atoms found for', sele1, sele2)
continue
}
for (var j = 0; j < l; ++j) {
ap1.index = atomIndices1![ j % k ]
ap2.index = atomIndices2![ j ]
if (ap1 && ap2) {
structure.bondStore.addBond(
ap1, ap2, getBondOrder(sc.pdbx_value_order[ i ])
)
} else {
Log.log('atoms for connection not found')
}
}
}
}
}
function processEntities (cif: Cif, structure: Structure, chainIndexDict: {[k: string]: Set<number>}) {
if (cif.entity) {
ensureArray(cif.entity, 'id')
var e = cif.entity
var n = e.id.length
for (var i = 0; i < n; ++i) {
var description = e.pdbx_description[ i ]
var type = e.type[ i ]
var chainIndexList: number[] = Array.from(chainIndexDict[ e.id[ i ] ])
structure.entityList[ i ] = new Entity(
structure, i, description, type, chainIndexList
)
}
}
}
//
class CifParser extends StructureParser {
get type () { return 'cif' }
_parse () {
// http://mmcif.wwpdb.org/
Log.time('CifParser._parse ' + this.name)
var s = this.structure
var sb = this.structureBuilder
var firstModelOnly = this.firstModelOnly
var asTrajectory = this.asTrajectory
var cAlphaOnly = this.cAlphaOnly
var frames = s.frames
var currentFrame: NumberArray, currentCoord: number
var rawline, line
//
var cif: Cif = {}
var asymIdDict: {[k: string]: string} = {}
var chainIndexDict:{[k: string]: Set<number>} = {}
var pendingString = false
var currentString: string|null = null
var pendingValue = false
var pendingLoop = false
var pendingName = false
var loopPointers: string[][] = []
var currentLoopIndex: number|null = null
var currentCategory: string|null = null
var currentName: string|boolean|null = null
var first: boolean|null = null
var pointerNames: string[] = []
var authAsymId: number, authSeqId: number,
labelAtomId: number, labelCompId: number, labelAsymId: number, labelEntityId: number, labelAltId: number,
groupPDB: number, id: number, typeSymbol: number, pdbxPDBmodelNum: number, pdbxPDBinsCode: number,
CartnX: number, CartnY: number, CartnZ: number, bIsoOrEquiv: number, occupancy: number
//
var atomMap = s.atomMap
var atomStore = s.atomStore
atomStore.resize(this.streamer.data.length / 100)
var idx = 0
var modelIdx = 0
var modelNum: number
function _parseChunkOfLines (_i: number, _n: number, lines: string[]) {
for (var i = _i; i < _n; ++i) {
rawline = lines[i]
line = rawline.trim()
if ((!line && !pendingString && !pendingLoop) || line[0] === '#') {
// Log.log( "NEW BLOCK" );
pendingString = false
pendingLoop = false
pendingValue = false
loopPointers.length = 0
currentLoopIndex = null
currentCategory = null
currentName = null
first = null
pointerNames.length = 0
} else if (line.substring(0, 5) === 'data_') {
cif.data = line.substring(5).trim()
// Log.log( "DATA", data );
} else if (line[0] === ';') {
if (pendingString) {
// Log.log( "STRING END", currentString );
if (pendingLoop) {
if (currentLoopIndex === loopPointers.length) {
currentLoopIndex = 0
}
loopPointers[ currentLoopIndex as number ].push(currentString as string);
(currentLoopIndex as number) += 1
} else {
if (currentName === false) {
cif[ currentCategory as string ] = currentString
} else {
cif[ currentCategory as string ][ currentName as string ] = currentString //TODO currentname can equals null
}
}
pendingString = false
currentString = null
} else {
// Log.log( "STRING START" );
pendingString = true
currentString = line.substring(1)
}
} else if (line === 'loop_') {
// Log.log( "LOOP START" );
pendingLoop = true
pendingName = true
loopPointers.length = 0
pointerNames.length = 0
currentLoopIndex = 0
} else if (line[0] === '_') {
var keyParts, category, name
if (pendingLoop && !pendingName) {
pendingLoop = false
}
if (pendingLoop) {
// Log.log( "LOOP KEY", line );
keyParts = line.split('.')
category = keyParts[ 0 ].substring(1)
name = keyParts[ 1 ]
if (keyParts.length === 1) {
name = false
if (!cif[ category ]) cif[ category ] = []
loopPointers.push(cif[ category ])
} else {
if (!cif[ category ]) cif[ category ] = {}
if (cif[ category ][ name ]) {
if (Debug) Log.warn(category, name, 'already exists')
} else {
cif[ category ][ name ] = []
loopPointers.push(cif[ category ][ name ])
pointerNames.push(name)
}
}
currentCategory = category
currentName = name
first = true
} else {
var keyValuePair = line.match(reQuotedWhitespace)
var key = keyValuePair![ 0 ]
var value = keyValuePair![ 1 ]
keyParts = key.split('.')
category = keyParts[ 0 ].substring(1)
name = keyParts[ 1 ]
if (keyParts.length === 1) {
name = false
cif[ category ] = value
} else {
if (!cif[ category ]) cif[ category ] = {}
if (cif[ category ][ name ]) {
if (Debug) Log.warn(category, name, 'already exists')
} else {
cif[ category ][ name ] = value
}
}
if (!value) pendingValue = true
currentCategory = category
currentName = name
}
} else {
if (pendingString) {
// Log.log( "STRING VALUE", line );
currentString += rawline
} else if (pendingLoop) {
// Log.log( "LOOP VALUE", line );
if (!line) {
continue
} else if (currentCategory === 'atom_site') {
const ls = line.split(reWhitespace)
if (first) {
authAsymId = pointerNames.indexOf('auth_asym_id')
authSeqId = pointerNames.indexOf('auth_seq_id')
labelAtomId = pointerNames.indexOf('label_atom_id')
labelCompId = pointerNames.indexOf('label_comp_id')
labelAsymId = pointerNames.indexOf('label_asym_id')
labelEntityId = pointerNames.indexOf('label_entity_id')
labelAltId = pointerNames.indexOf('label_alt_id')
CartnX = pointerNames.indexOf('Cartn_x')
CartnY = pointerNames.indexOf('Cartn_y')
CartnZ = pointerNames.indexOf('Cartn_z')
id = pointerNames.indexOf('id')
typeSymbol = pointerNames.indexOf('type_symbol')
groupPDB = pointerNames.indexOf('group_PDB')
bIsoOrEquiv = pointerNames.indexOf('B_iso_or_equiv')
pdbxPDBmodelNum = pointerNames.indexOf('pdbx_PDB_model_num')
pdbxPDBinsCode = pointerNames.indexOf('pdbx_PDB_ins_code')
occupancy = pointerNames.indexOf('occupancy')
first = false
modelNum = parseInt(ls[ pdbxPDBmodelNum ])
if (asTrajectory) {
currentFrame = []
currentCoord = 0
}
}
//
const _modelNum = parseInt(ls[ pdbxPDBmodelNum ])
if (modelNum !== _modelNum) {
if (asTrajectory) {
if (modelIdx === 0) {
frames.push(new Float32Array(currentFrame))
}
currentFrame = new Float32Array(atomStore.count * 3)
frames.push(currentFrame)
currentCoord = 0
}
modelIdx += 1
}
modelNum = _modelNum
if (firstModelOnly && modelIdx > 0) continue
//
const atomname = ls[ labelAtomId ].replace(reDoubleQuote, '')
if (cAlphaOnly && atomname !== 'CA') continue
const x = parseFloat(ls[ CartnX ])
const y = parseFloat(ls[ CartnY ])
const z = parseFloat(ls[ CartnZ ])
if (asTrajectory) {
const frameOffset = currentCoord * 3
currentFrame[ frameOffset + 0 ] = x
currentFrame[ frameOffset + 1 ] = y
currentFrame[ frameOffset + 2 ] = z
currentCoord += 1
if (modelIdx > 0) continue
}
//
const resname = ls[ labelCompId ]
const resno = parseInt(ls[ authSeqId ])
let inscode = ls[ pdbxPDBinsCode ]
inscode = (inscode === '?') ? '' : inscode
const chainname = ls[ authAsymId ]
const chainid = ls[ labelAsymId ]
const hetero = (ls[ groupPDB ][ 0 ] === 'H') ? 1 : 0
//
const element = ls[ typeSymbol ]
const bfactor = parseFloat(ls[ bIsoOrEquiv ])
const occ = parseFloat(ls[ occupancy ])
let altloc = ls[ labelAltId ]
altloc = (altloc === '.') ? '' : altloc
atomStore.growIfFull()
atomStore.atomTypeId[ idx ] = atomMap.add(atomname, element)
atomStore.x[ idx ] = x
atomStore.y[ idx ] = y
atomStore.z[ idx ] = z
atomStore.serial[ idx ] = parseInt(ls[ id ])
atomStore.bfactor[ idx ] = isNaN(bfactor) ? 0 : bfactor
atomStore.occupancy[ idx ] = isNaN(occ) ? 0 : occ
atomStore.altloc[ idx ] = altloc.charCodeAt(0)
sb.addAtom(modelIdx, chainname, chainid, resname, resno, hetero, undefined, inscode)
if (Debug) {
// check if one-to-many (chainname-asymId) relationship is
// actually a many-to-many mapping
const assignedChainname = asymIdDict[ chainid ]
if (assignedChainname !== undefined && assignedChainname !== chainname) {
if (Debug) Log.warn(assignedChainname, chainname)
}
}
// chainname mapping: label_asym_id -> auth_asym_id
asymIdDict[ chainid ] = chainname
// entity mapping: chainIndex -> label_entity_id
const entityId = ls[ labelEntityId ]
if (!chainIndexDict[ entityId ]) {
chainIndexDict[ entityId ] = new Set()
}
chainIndexDict[ entityId ].add(s.chainStore.count - 1)
idx += 1
} else {
const ls = line.match(reQuotedWhitespace)
const nn = ls!.length
if (currentLoopIndex === loopPointers.length) {
currentLoopIndex = 0
}/* else if( currentLoopIndex + nn > loopPointers.length ){
Log.warn( "cif parsing error, wrong number of loop data entries", nn, loopPointers.length );
} */
for (let j = 0; j < nn; ++j) {
loopPointers[ <number>currentLoopIndex + j ].push(ls![ j ])
}
(<number>currentLoopIndex) += nn
}
pendingName = false
} else if (line[0] === "'" && line[line.length - 1] === "'") {
// Log.log( "NEWLINE STRING", line );
const str = line.substring(1, line.length - 1)
if (currentName === false) {
cif[ currentCategory as string ] = str
} else {
cif[ currentCategory as string ][ currentName as string ] = str
}
} else if (pendingValue) {
// Log.log( "NEWLINE VALUE", line );
if (currentName === false) {
cif[ currentCategory as string ] = line
} else {
cif[ currentCategory as string ][ currentName as string ] = line
}
} else {
if (Debug) Log.log('CifParser._parse: unknown state', line)
}
}
}
}
this.streamer.eachChunkOfLines(function (lines/*, chunkNo, chunkCount */) {
_parseChunkOfLines(0, lines.length, lines)
})
if (cif.chem_comp && cif.chem_comp_atom) {
parseChemComp(cif, s, sb)
sb.finalize()
s.finalizeAtoms()
s.finalizeBonds()
assignResidueTypeBonds(s)
} else if (cif.atom_site_type_symbol && cif.atom_site_label && cif.atom_site_fract_x) {
parseCore(cif, s, sb)
sb.finalize()
s.finalizeAtoms()
calculateBonds(s)
s.finalizeBonds()
// assignResidueTypeBonds( s );
} else {
var secStruct = processSecondaryStructure(cif, s, asymIdDict)
processSymmetry(cif, s, asymIdDict)
processConnections(cif, s, asymIdDict)
processEntities(cif, s, chainIndexDict)
if (cif.struct && cif.struct.title) {
s.title = cif.struct.title.trim().replace(reTrimQuotes, '')
}
if (cif.entry && cif.entry.id) {
s.id = cif.entry.id.trim().replace(reTrimQuotes, '')
}
// structure header (mimicking biojava)
if (cif.pdbx_audit_revision_history) {
if (cif.pdbx_audit_revision_history.revision_date) {
ensureArray(cif.pdbx_audit_revision_history, 'revision_date')
const dates = cif.pdbx_audit_revision_history.revision_date.filter(hasValue)
if (dates.length) {
s.header.releaseDate = dates[ 0 ]
}
}
if (cif.pdbx_database_status.recvd_initial_deposition_date) {
ensureArray(cif.pdbx_database_status, 'recvd_initial_deposition_date')
const depDates = cif.pdbx_database_status.recvd_initial_deposition_date.filter(hasValue)
if (depDates.length) {
s.header.depositionDate = depDates[ 0 ]
}
}
} else if (cif.database_PDB_rev) {
if (cif.database_PDB_rev.date) {
ensureArray(cif.database_PDB_rev, 'date')
const dates = cif.database_PDB_rev.date.filter(hasValue)
if (dates.length) {
s.header.releaseDate = dates[ 0 ]
}
}
if (cif.database_PDB_rev.date_original) {
ensureArray(cif.database_PDB_rev, 'date_original')
const depDates = cif.database_PDB_rev.date_original.filter(hasValue)
if (depDates.length) {
s.header.depositionDate = depDates[ 0 ]
}
}
}
if (cif.reflns && cif.reflns.d_resolution_high) {
if (hasValue(cif.reflns.d_resolution_high)) {
s.header.resolution = parseFloat(cif.reflns.d_resolution_high)
}
} else if (cif.refine && cif.refine.ls_d_res_high) {
if (hasValue(cif.refine.ls_d_res_high)) {
s.header.resolution = parseFloat(cif.refine.ls_d_res_high)
}
}
if (cif.refine && cif.refine.ls_R_factor_R_free) {
if (hasValue(cif.refine.ls_R_factor_R_free)) {
s.header.rFree = parseFloat(cif.refine.ls_R_factor_R_free)
}
}
if (cif.refine && cif.refine.ls_R_factor_R_work) {
if (hasValue(cif.refine.ls_R_factor_R_work)) {
s.header.rWork = parseFloat(cif.refine.ls_R_factor_R_work)
}
}
if (cif.exptl && cif.exptl.method) {
ensureArray(cif.exptl, 'method')
s.header.experimentalMethods = cif.exptl.method.map(function (m: string) {
return m.replace(reTrimQuotes, '')
})
}
sb.finalize()
s.finalizeAtoms()
calculateBonds(s)
s.finalizeBonds()
if (!secStruct) {
calculateSecondaryStructure(s)
} else {
assignSecondaryStructure(s, secStruct)
}
buildUnitcellAssembly(s)
s.extraData.cif = cif
}
if (Debug) Log.timeEnd('CifParser._parse ' + this.name)
}
}
ParserRegistry.add('cif', CifParser)
ParserRegistry.add('mcif', CifParser)
ParserRegistry.add('mmcif', CifParser)
export default CifParser | the_stack |
import { mat4 } from 'gl-matrix';
import { vtkObject } from "../../../interfaces" ;
import { Bounds, Vector3, Range } from '../../../types';
/**
*
*/
export interface ICameraInitialValues {
position?: number[];
focalPoint?: number[];
viewUp?: number[];
directionOfProjection?: number[];
parallelProjection?: boolean;
useHorizontalViewAngle?: boolean;
viewAngle?: number;
parallelScale?: number;
clippingRange?: number[];
windowCenter?: number[];
viewPlaneNormal?: number[];
useOffAxisProjection?: boolean;
screenBottomLeft?: number[];
screenBottomRight?: number[];
screenTopRight?: number[];
freezeFocalPoint?: boolean;
physicalTranslation?: number[];
physicalScale?: number;
physicalViewUp?: number[];
physicalViewNorth?: number[];
}
export interface vtkCamera extends vtkObject {
/**
* Apply a transform to the camera.
* The camera position, focal-point, and view-up are re-calculated
* using the transform's matrix to multiply the old points by the new transform.
* @param {mat4} transformMat4 Transform matrix.
*/
applyTransform(transformMat4: mat4): void;
/**
* Rotate the camera about the view up vector centered at the focal point.
* @param {Number} angle The angle value.
*/
azimuth(angle: number): void;
/**
*
* @param {Bounds} bounds The bounds value.
*/
computeClippingRange(bounds: Bounds): Range;
/**
* This method must be called when the focal point or camera position changes
*/
computeDistance(): void;
/**
* the provided matrix should include translation and orientation only mat
* is physical to view
* @param {mat4} mat The physical matrix.
*/
computeViewParametersFromPhysicalMatrix(mat: mat4): void;
/**
*
* @param {mat4} vmat The view matrix.
*/
computeViewParametersFromViewMatrix(vmat: mat4): void;
/**
* Not implemented yet
* @param {vtkCamera} sourceCamera The camera source.
*/
deepCopy(sourceCamera: vtkCamera): void;
/**
* Move the position of the camera along the view plane normal. Moving
* towards the focal point (e.g., > 1) is a dolly-in, moving away
* from the focal point (e.g., < 1) is a dolly-out.
* @param {Number} amount The amount value.
*/
dolly(amount: number): void;
/**
* Rotate the camera about the cross product of the negative of the
* direction of projection and the view up vector, using the focal point as
* the center of rotation.
* @param {Number} angle The angle value.
*/
elevation(angle: number): void;
/**
* Not implemented yet
*/
getCameraLightTransformMatrix(): void;
/**
* Get the location of the near and far clipping planes along the direction
* of projection.
*/
getClippingRange(): Range;
/**
* Get the location of the near and far clipping planes along the direction
* of projection.
*/
getClippingRangeByReference(): Range;
/**
*
* @param {Number} aspect Camera frustum aspect ratio.
* @param {Number} nearz Camera frustum near plane.
* @param {Number} farz Camera frustum far plane.
*/
getCompositeProjectionMatrix(aspect: number, nearz: number, farz: number): mat4;
/**
* Get the vector in the direction from the camera position to the focal
* point.
*/
getDirectionOfProjection(): Vector3;
/**
* Get the vector in the direction from the camera position to the focal
* point.
*/
getDirectionOfProjectionByReference(): Vector3;
/**
* Get the distance from the camera position to the focal point.
*/
getDistance(): number;
/**
* Get the focal of the camera in world coordinates.
*/
getFocalPoint(): Vector3;
/**
* Get the focal of the camera in world coordinates.
*/
getFocalPointByReference(): Vector3;
/**
* Get the value of the FreezeDolly instance variable.
*/
getFreezeFocalPoint(): boolean;
/**
* Not implemented yet
* Get the plane equations that bound the view frustum.
* @param {Number} aspect Camera frustum aspect ratio.
*/
getFrustumPlanes(aspect: number): void;
/**
* Not implemented yet
* Get the orientation of the camera.
*/
getOrientation(): void;
/**
* Not implemented yet
* Get the orientation of the camera.
*/
getOrientationWXYZ(): void;
/**
* Get the value of the ParallelProjection instance variable.
* This determines if the camera should do a perspective or parallel projection.
*/
getParallelProjection(): boolean;
/**
* Get the scaling used for a parallel projection.
*/
getParallelScale(): number;
/**
*
*/
getPhysicalScale(): number;
/**
*
* @param {mat4} result The world matrix.
*/
getPhysicalToWorldMatrix(result: mat4): void;
/**
*
*/
getPhysicalTranslation(): number[];
/**
*
*/
getPhysicalTranslationByReference(): number[];
/**
*
*/
getPhysicalViewNorth(): number[];
/**
*
*/
getPhysicalViewNorthByReference(): number[];
/**
*
*/
getPhysicalViewUp(): number[];
/**
*
*/
getPhysicalViewUpByReference(): number[];
/**
* Get the position of the camera in world coordinates.
*/
getPosition(): Vector3;
/**
* Get the position of the camera in world coordinates.
*/
getPositionByReference(): Vector3;
/**
* Get the projection matrix.
* @param {Number} aspect Camera frustum aspect ratio.
* @param {Number} nearz Camera frustum near plane.
* @param {Number} farz Camera frustum far plane.
*/
getProjectionMatrix(aspect: number, nearz: number, farz: number): mat4;
/**
* Not implemented yet
* Get the roll angle of the camera about the direction of projection.
*/
getRoll(): void;
/**
* Get top left corner point of the screen.
*/
getScreenBottomLeft(): Vector3;
/**
*
*/
getScreenBottomLeftByReference(): Vector3;
/**
* Get bottom left corner point of the screen
*/
getScreenBottomRight(): Vector3;
/**
*
*/
getScreenBottomRightByReference(): Vector3;
/**
*
*/
getScreenTopRight(): Vector3;
/**
*
*/
getScreenTopRightByReference(): Vector3;
/**
* Get the center of the window in viewport coordinates.
*/
getThickness(): number;
/**
* Get the value of the UseHorizontalViewAngle.
*/
getUseHorizontalViewAngle(): boolean;
/**
* Get use offaxis frustum.
*/
getUseOffAxisProjection(): boolean;
/**
* Get the camera view angle.
*/
getViewAngle(): number;
/**
*
*/
getViewMatrix(): mat4;
/**
* Get the ViewPlaneNormal.
* This vector will point opposite to the direction of projection,
* unless you have created a sheared output view using SetViewShear/SetObliqueAngles.
*/
getViewPlaneNormal(): Vector3;
/**
* Get the ViewPlaneNormal by reference.
*/
getViewPlaneNormalByReference(): Vector3;
/**
* Get ViewUp vector.
*/
getViewUp(): Vector3;
/**
* Get ViewUp vector by reference.
*/
getViewUpByReference(): Vector3;
/**
* Get the center of the window in viewport coordinates.
* The viewport coordinate range is ([-1,+1],[-1,+1]).
*/
getWindowCenter(): Range;
/**
*
*/
getWindowCenterByReference(): Range;
/**
*
* @param {mat4} result
*/
getWorldToPhysicalMatrix(result: mat4): void;
/**
* Recompute the ViewUp vector to force it to be perpendicular to
* camera.focalpoint vector.
*/
orthogonalizeViewUp(): void;
/**
*
* @param {Number[]} ori
*/
physicalOrientationToWorldDirection(ori: number[]): any;
/**
* Rotate the focal point about the cross product of the view up vector and
* the direction of projection, using the camera's position as the center of
* rotation.
* @param {Number} angle The value of the angle.
*/
pitch(angle: number): void;
/**
* Rotate the camera about the direction of projection.
* @param {Number} angle The value of the angle.
*/
roll(angle: number): void;
/**
* Set the location of the near and far clipping planes along the direction
* of projection.
* @param {Number} near The near clipping planes.
* @param {Number} far The far clipping planes.
*/
setClippingRange(near: number, far: number): boolean;
/**
* Set the location of the near and far clipping planes along the direction
* of projection.
* @param {Range} clippingRange
*/
setClippingRange(clippingRange: Range): boolean;
/**
* Set the location of the near and far clipping planes along the direction
* of projection.
* @param {Range} clippingRange
*/
setClippingRangeFrom(clippingRange: Range): boolean;
/**
* Used to handle convert js device orientation angles
* when you use this method the camera will adjust to the
* device orientation such that the physicalViewUp you set
* in world coordinates looks up, and the physicalViewNorth
* you set in world coorindates will (maybe) point north
*
* NOTE WARNING - much of the documentation out there on how
* orientation works is seriously wrong. Even worse the Chrome
* device orientation simulator is completely wrong and should
* never be used. OMG it is so messed up.
*
* how it seems to work on iOS is that the device orientation
* is specified in extrinsic angles with a alpha, beta, gamma
* convention with axes of Z, X, Y (the code below substitutes
* the physical coordinate system for these axes to get the right
* modified coordinate system.
* @param {Number} alpha The value of the alpha.
* @param {Number} beta The value of the beta.
* @param {Number} gamma The value of the gamma.
* @param {Number} screen The value of the screen.
*/
setDeviceAngles(alpha: number, beta: number, gamma: number, screen: number): boolean;
/**
* Set the direction of projection.
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Number} z The z coordinate.
*/
setDirectionOfProjection(x: number, y: number, z: number): boolean;
/**
* Move the focal point so that it is the specified distance from the camera
* position.
*
* This distance must be positive.
* @param {Number} distance The value of the distance.
*/
setDistance(distance: number): boolean;
/**
* Set the focal of the camera in world coordinates.
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Number} z The z coordinate.
*/
setFocalPoint(x: number, y: number, z: number): boolean;
/**
* Set the focal of the camera in world coordinates.
* @param {Vector3} focalPoint
*/
setFocalPointFrom(focalPoint: Vector3): boolean;
/**
* Not implement yet
* Set the oblique viewing angles.
* The first angle, alpha, is the angle (measured from the horizontal) that
* rays along the direction of projection will follow once projected onto
* the 2D screen. The second angle, beta, is the angle between the view
* plane and the direction of projection. This creates a shear transform x'
* = x + dz*cos(alpha)/tan(beta), y' = dz*sin(alpha)/tan(beta) where dz is
* the distance of the point from the focal plane. The angles are (45,90) by
* default. Oblique projections commonly use (30,63.435).
*
* @param {Number} alpha The aplha angle value.
* @param {Number} beta The beta angle value.
*/
setObliqueAngles(alpha: number, beta: number): boolean;
/**
* Set the value of the OrientationWXYZ.
* @param {Number} degrees
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Number} z The z coordinate.
*/
setOrientationWXYZ(degrees: number, x: number, y: number, z: number): boolean;
/**
* Set the value of the ParallelProjection.
* @param {Boolean} parallelProjection The value of the parallelProjection.
*/
setParallelProjection(parallelProjection: boolean): boolean;
/**
* Set the value of the parallelScale.
* @param {Number} parallelScale The value of the parallelScale.
*/
setParallelScale(parallelScale: number): boolean;
/**
* Set the value of the physicalScale.
* @param {Number} physicalScale The value of the the physicalScale.
*/
setPhysicalScale(physicalScale: number): boolean;
/**
* Set the value of the physicalTranslation.
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Number} z The z coordinate.
*/
setPhysicalTranslation(x: number, y: number, z: number): boolean;
/**
* Set the value of the physicalTranslation.
* @param {Number[]} physicalTranslation The value of the physicalTranslation.
*/
setPhysicalTranslationFrom(physicalTranslation: number[]): boolean;
/**
*
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Number} z The z coordinate.
*/
setPhysicalViewNorth(x: number, y: number, z: number): boolean;
/**
*
* @param {Number[]} physicalViewNorth
*/
setPhysicalViewNorthFrom(physicalViewNorth: number[]): boolean;
/**
*
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Number} z The z coordinate.
*/
setPhysicalViewUp(x: number, y: number, z: number): boolean;
/**
*
* @param {Number[]} physicalViewUp
*/
setPhysicalViewUpFrom(physicalViewUp: number[]): boolean;
/**
* Set the position of the camera in world coordinates.
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Number} z The z coordinate.
*/
setPosition(x: number, y: number, z: number): boolean;
/**
*
* @param {mat4} mat
*/
setProjectionMatrix(mat: mat4): boolean;
/**
* Set the roll angle of the camera about the direction of projection.
* @todo Not implemented yet
* @param {Number} angle The value of the roll angle.
*/
setRoll(angle: number): boolean;
/**
* Set top left corner point of the screen.
*
* This will be used only for offaxis frustum calculation.
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Number} z The z coordinate.
*/
setScreenBottomLeft(x: number, y: number, z: number): boolean;
/**
* Set top left corner point of the screen.
*
* This will be used only for offaxis frustum calculation.
* @param {Vector3} screenBottomLeft The screenBottomLeft coordiante.
*/
setScreenBottomLeft(screenBottomLeft: Vector3): boolean;
/**
* Set top left corner point of the screen.
* @param {Vector3} screenBottomLeft The screenBottomLeft coordiante.
*/
setScreenBottomLeftFrom(screenBottomLeft: Vector3): boolean;
/**
*
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Number} z The z coordinate.
*/
setScreenBottomRight(x: number, y: number, z: number): boolean;
/**
* Set bottom right corner point of the screen.
* @param {Vector3} screenBottomRight The screenBottomRight coordiante.
*/
setScreenBottomRight(screenBottomRight: Vector3): boolean;
/**
* Set bottom right corner point of the screen.
* @param {Vector3} screenBottomRight The screenBottomRight coordiante.
*/
setScreenBottomRightFrom(screenBottomRight: Vector3): boolean;
/**
* Set top right corner point of the screen.
*
* This will be used only for offaxis frustum calculation.
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Number} z The z coordinate.
*/
setScreenTopRight(x: number, y: number, z: number): boolean;
/**
* Set top right corner point of the screen.
*
* This will be used only for offaxis frustum calculation.
* @param {Vector3} screenTopRight The screenTopRight coordiante.
*/
setScreenTopRight(screenTopRight: Vector3): boolean;
/**
* Set top right corner point of the screen.
* @param {Vector3} screenTopRight The screenTopRight coordiante.
*/
setScreenTopRightFrom(screenTopRight: Vector3): boolean;
/**
* Set the distance between clipping planes.
*
* This method adjusts the far clipping plane to be set a distance
* 'thickness' beyond the near clipping plane.
* @param {Number} thickness
*/
setThickness(thickness: number): boolean;
/**
*
* @param {Number} thickness The value of the thickness.
*/
setThicknessFromFocalPoint(thickness: number): boolean;
/**
* Set the value of the useHorizontalViewAngle.
* @param {Boolean} useHorizontalViewAngle The value of the useHorizontalViewAngle.
*/
setUseHorizontalViewAngle(useHorizontalViewAngle: boolean): boolean;
/**
* Set use offaxis frustum.
*
* OffAxis frustum is used for off-axis frustum calculations specifically for
* stereo rendering. For reference see "High Resolution Virtual Reality", in
* Proc. SIGGRAPH '92, Computer Graphics, pages 195-202, 1992.
* @param {Boolean} useOffAxisProjection The value of the useOffAxisProjection.
*/
setUseOffAxisProjection(useOffAxisProjection: boolean): boolean;
/**
* Set the camera view angle, which is the angular height of the camera view
* measured in degrees.
* @param {Number} viewAngle The value of the viewAngle.
*/
setViewAngle(viewAngle: number): boolean;
/**
* Set the view matrix for the camera.
* @param {mat4} mat The value of the view matrix.
*/
setViewMatrix(mat: mat4): boolean;
/**
* Set the view up direction for the camera.
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Number} z The z coordinate.
*/
setViewUp(x: number, y: number, z: number): boolean;
/**
* Set the view up direction for the camera.
* @param {Vector3} viewUp The viewUp coordinate.
*/
setViewUp(viewUp: Vector3): boolean;
/**
* Set the view up direction for the camera.
* @param {Vector3} viewUp The viewUp coordinate.
*/
setViewUpFrom(viewUp: Vector3): boolean;
/**
* Set the center of the window in viewport coordinates.
*
* The viewport coordinate range is ([-1,+1],[-1,+1]).
*
* This method is for if you have one window which consists of several
* viewports, or if you have several screens which you want to act together
* as one large screen.
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
*/
setWindowCenter(x: number, y: number): boolean;
/**
* Set the center of the window in viewport coordinates from an array.
* @param {Range} windowCenter
*/
setWindowCenterFrom(windowCenter: Range): boolean;
/**
*
* @param {Number} x The x coordinate.
* @param {Number} y The y coordinate.
* @param {Number} z The z coordinate.
*/
translate(x: number, y: number, z: number): void;
/**
* Rotate the focal point about the view up vector, using the camera's
* position as the center of rotation.
* @param {Number} angle The value of the angle.
*/
yaw(angle: number): void;
/**
* In perspective mode, decrease the view angle by the specified factor.
* @param {Number} factor The value of the zoom factor.
*/
zoom(factor: number): void;
}
/**
* Method use to decorate a given object (publicAPI+model) with vtkRenderer characteristics.
*
* @param publicAPI object on which methods will be bounds (public)
* @param model object on which data structure will be bounds (protected)
* @param {ICameraInitialValues} [initialValues] (default: {})
*/
export function extend(publicAPI: object, model: object, initialValues?: ICameraInitialValues): void;
/**
* Method use to create a new instance of vtkCamera with its focal point at the origin,
* and position=(0,0,1). The view up is along the y-axis, view angle is 30 degrees,
* and the clipping range is (.1,1000).
* @param {ICameraInitialValues} [initialValues] for pre-setting some of its content
*/
export function newInstance(initialValues?: ICameraInitialValues): vtkCamera;
/**
* vtkCamera is a virtual camera for 3D rendering. It provides methods
* to position and orient the view point and focal point. Convenience
* methods for moving about the focal point also are provided. More
* complex methods allow the manipulation of the computer graphics model
* including view up vector, clipping planes, and camera perspective.
*/
export declare const vtkCamera: {
newInstance: typeof newInstance,
extend: typeof extend,
};
export default vtkCamera; | the_stack |
import $ from "jquery";
import { dom, status } from "./helper";
export default class Save {
default_filename: any;
savedata: any;
constructor(public window: number, public config, public eventhandler) {
this.config = config;
this.window = window;
this.default_filename = "mysprites";
this.eventhandler = eventhandler;
const template = `
<div id="window-save">
<div class="center">
Filename: <input autofocus type="text" id="filename" name="filename" value="${this.default_filename}">
<p>The file will be saved to your browser's default download location.</p>
</div>
<br/>
<fieldset>
<legend>Spritemate // *.spm</legend>
<button id="button-save-spm">Save as Spritemate</button>
<p>JSON file format for spritemate. Recommended as long as you are not done working on the sprites.</p>
</fieldset>
<fieldset>
<legend>Spritepad // *.spd</legend>
<div class="fieldset right">
<button id="button-save-spd">Save as 2.0</button>
<button id="button-save-spd-old">Save as 1.8.1</button>
</div>
<p>Choose between the 2.0 beta or the older 1.8.1 file format, which is recommended if you want to import the data in your C64 project.</p>
</fieldset>
<fieldset>
<legend>Assembly code // *.txt</legend>
<div class="fieldset right">
<button id="button-save-source-kick">KICK ASS (hex)</button>
<button id="button-save-source-kick-binary">KICK ASS (binary)</button>
<button id="button-save-source-acme">ACME (hex)</button>
<button id="button-save-source-acme-binary">ACME (binary)</button>
</div>
<p>A text file containing the sprite data in assembly language. KICK ASS and ACME are compilers with slightly different syntax. Choose "hex" to save a byte like $01 or "binary" for %00000001.</p>
</fieldset>
<fieldset>
<legend>BASIC // *.bas</legend>
<button id="button-save-basic">Save as BASIC 2.0</button>
<p>A BASIC 2.0 text file that you can copy & paste into VICE.</p>
</fieldset>
<fieldset>
<legend>PNG image</legend>
<p>To save a sprite as a PNG image, "right click" on the sprite in the PREVIEW window. Your browser will display a "save image as..." option in the context menu. The size of the PNG can be set with the zoom levels of the PREVIEW window.</p>
</fieldset>
<div id="button-row">
<button id="button-save-cancel" class="button-cancel">Cancel</button>
</div>
</div>
`;
dom.append("#window-" + this.window, template);
$("#window-" + this.window).dialog({ show: "fade", hide: "fade" });
dom.sel("#button-save-cancel").onclick = () => this.close_window();
dom.sel("#button-save-spm").onclick = () => this.save_spm();
dom.sel("#button-save-spd").onclick = () => this.save_spd("new");
dom.sel("#button-save-spd-old").onclick = () => this.save_spd("old");
dom.sel("#button-save-source-kick").onclick = () =>
this.save_assembly("kick", false);
dom.sel("#button-save-source-kick-binary").onclick = () =>
this.save_assembly("kick", true);
dom.sel("#button-save-source-acme").onclick = () =>
this.save_assembly("acme", false);
dom.sel("#button-save-source-acme-binary").onclick = () =>
this.save_assembly("acme", true);
dom.sel("#button-save-basic").onclick = () => this.save_basic();
dom.sel("#filename").onkeyup = () => {
this.default_filename = dom.val("#filename");
if (this.default_filename.length < 1) {
dom.add_class("#filename", "error");
dom.disabled("#button-save-spm", true);
dom.add_class("#button-save-spm", "error");
dom.disabled("#button-save-spd", true);
dom.add_class("#button-save-spd", "error");
dom.disabled("#button-save-spd-old", true);
dom.add_class("#button-save-spd-old", "error");
dom.disabled("#button-save-source-kick", true);
dom.add_class("#button-save-source-kick", "error");
dom.disabled("#button-save-source-kick-binary", true);
dom.add_class("#button-save-source-kick-binary", "error");
dom.disabled("#button-save-source-acme", true);
dom.add_class("#button-save-source-acme", "error");
dom.disabled("#button-save-source-acme-binary", true);
dom.add_class("#button-save-source-acme-binary", "error");
dom.disabled("#button-save-basic", true);
dom.add_class("#button-save-basic", "error");
} else {
dom.remove_class("#filename", "error");
dom.disabled("#button-save-spm", false);
dom.remove_class("#button-save-spm", "error");
dom.disabled("#button-save-spd", false);
dom.remove_class("#button-save-spd", "error");
dom.disabled("#button-save-spd-old", false);
dom.remove_class("#button-save-spd-old", "error");
dom.disabled("#button-save-source-kick", false);
dom.remove_class("#button-save-source-kick", "error");
dom.disabled("#button-save-source-kick-binary", false);
dom.remove_class("#button-save-source-kick-binary", "error");
dom.disabled("#button-save-source-acme", false);
dom.remove_class("#button-save-source-acme", "error");
dom.disabled("#button-save-source-acme-binary", false);
dom.remove_class("#button-save-source-acme-binary", "error");
dom.disabled("#button-save-basic", false);
dom.remove_class("#button-save-basic", "error");
}
};
}
// https://stackoverflow.com/questions/13405129/javascript-create-and-save-file
save_file_to_disk(file, filename): void {
if (window.navigator.msSaveOrOpenBlob)
// IE10+
window.navigator.msSaveOrOpenBlob(file, filename);
else {
// Others
const a = document.createElement("a"),
url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function () {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
status("File has been saved.");
dom.html("#menubar-filename-name", filename);
}
save_spm(): void {
const filename = this.default_filename + ".spm";
let data = JSON.stringify(this.savedata);
// these regular expressions are used to make the outpult file
// easier to read with line breaks
data = data
.replace(/],/g, "],\n")
.replace(/\[\[/g, "[\n[")
.replace(/]]/g, "]\n]");
const file = new Blob([data], { type: "text/plain" });
this.save_file_to_disk(file, filename);
this.close_window();
}
save_assembly(format, encode_as_binary): void {
const filename = this.default_filename + ".txt";
const data = this.create_assembly(format, encode_as_binary);
const file = new Blob([data], { type: "text/plain" });
this.save_file_to_disk(file, filename);
this.close_window();
}
save_spd(format): void {
const filename = this.default_filename + ".spd";
const hexdata = this.create_spd_array(format);
const bytes = new Uint8Array(hexdata);
const file = new Blob([bytes], { type: "application/octet-stream" });
this.save_file_to_disk(file, filename);
this.close_window();
}
save_basic(): void {
const filename = this.default_filename + ".bas";
const data = this.create_basic();
const file = new Blob([data], { type: "text/plain" });
this.save_file_to_disk(file, filename);
this.close_window();
}
/*
SSSSSSSSSSSSSSS PPPPPPPPPPPPPPPPP DDDDDDDDDDDDD
SS:::::::::::::::SP::::::::::::::::P D::::::::::::DDD
S:::::SSSSSS::::::SP::::::PPPPPP:::::P D:::::::::::::::DD
S:::::S SSSSSSSPP:::::P P:::::PDDD:::::DDDDD:::::D
S:::::S P::::P P:::::P D:::::D D:::::D
S:::::S P::::P P:::::P D:::::D D:::::D
S::::SSSS P::::PPPPPP:::::P D:::::D D:::::D
SS::::::SSSSS P:::::::::::::PP D:::::D D:::::D
SSS::::::::SS P::::PPPPPPPPP D:::::D D:::::D
SSSSSS::::S P::::P D:::::D D:::::D
S:::::S P::::P D:::::D D:::::D
S:::::S P::::P D:::::D D:::::D
SSSSSSS S:::::SPP::::::PP DDD:::::DDDDD:::::D
S::::::SSSSSS:::::SP::::::::P D:::::::::::::::DD
S:::::::::::::::SS P::::::::P D::::::::::::DDD
SSSSSSSSSSSSSSS PPPPPPPPPP DDDDDDDDDDDDD
*/
create_spd_array(format) {
// SPD file format information
// bytes 00,01,02 = "SPD"
// byte 03 = version number of spritepad
// byte 04 = number of sprites
// byte 05 = number of animations
// byte 06 = color transparent
// byte 07 = color multicolor 1
// byte 08 = color multicolor 2
// byte 09 = start of sprite data
// byte 73 = 0-3 color, 4 overlay, 7 multicolor/singlecolor
// bytes xx = "00", "00", "01", "00" added at the end of file (SpritePad animation info)
const data = [] as any;
if (format == "new") {
data.push(83, 80, 68); // the "SPD" header that identifies SPD files apparently
data.push(1, this.savedata.sprites.length - 1, 0); // number of sprites
}
data.push(
this.savedata.colors[0],
this.savedata.colors[2],
this.savedata.colors[3]
); // colors
let byte = "";
let bit = "";
for (
let j = 0;
j < this.savedata.sprites.length;
j++ // iterate through all sprites
) {
const spritedata = [].concat.apply([], this.savedata.sprites[j].pixels); // flatten 2d array
const is_multicolor = this.savedata.sprites[j].multicolor;
const is_overlay = this.savedata.sprites[j].overlay;
let stepping = 1;
if (is_multicolor) stepping = 2; // for multicolor, half of the array data can be ignored
// iterate through the pixel data array
// and create a hex values based on multicolor or singlecolor
for (let i = 0; i < spritedata.length; i = i + 8) {
for (let k = 0; k < 8; k = k + stepping) {
const pen = spritedata[i + k];
if (is_multicolor) {
if (pen == 0) bit = "00";
if (pen == 1) bit = "10";
if (pen == 2) bit = "01";
if (pen == 3) bit = "11";
}
if (!is_multicolor) {
bit = "1";
if (pen == 0) bit = "0";
}
byte = byte + bit;
}
const hex = parseInt(byte, 2);
data.push(hex);
byte = "";
}
// finally, we add multicolor, overlay and color info for byte 64
// bit 7 of the high nibble stands for multicolor
let multicolor = "00";
if (is_multicolor) multicolor = "10";
// bit 4 of the high nibble stands for overlay
let overlay = "00";
if (is_overlay) overlay = "01";
const high_nibble = multicolor + overlay;
const low_nibble = (
"000" + (this.savedata.sprites[j].color >>> 0).toString(2)
).slice(-4);
const color_byte = parseInt(high_nibble + low_nibble, 2);
data.push(color_byte); // should be the individual color
}
if (format == "new") {
// almost done, just add some animation data crap at the end
data.push(0, 0, 1, 0); // SpritePad animation info (currently unused)
}
return data;
}
/*
AAA SSSSSSSSSSSSSSS MMMMMMMM MMMMMMMM
A:::A SS:::::::::::::::SM:::::::M M:::::::M
A:::::A S:::::SSSSSS::::::SM::::::::M M::::::::M
A:::::::A S:::::S SSSSSSSM:::::::::M M:::::::::M
A:::::::::A S:::::S M::::::::::M M::::::::::M
A:::::A:::::A S:::::S M:::::::::::M M:::::::::::M
A:::::A A:::::A S::::SSSS M:::::::M::::M M::::M:::::::M
A:::::A A:::::A SS::::::SSSSS M::::::M M::::M M::::M M::::::M
A:::::A A:::::A SSS::::::::SS M::::::M M::::M::::M M::::::M
A:::::AAAAAAAAA:::::A SSSSSS::::S M::::::M M:::::::M M::::::M
A:::::::::::::::::::::A S:::::SM::::::M M:::::M M::::::M
A:::::AAAAAAAAAAAAA:::::A S:::::SM::::::M MMMMM M::::::M
A:::::A A:::::A SSSSSSS S:::::SM::::::M M::::::M
A:::::A A:::::A S::::::SSSSSS:::::SM::::::M M::::::M
A:::::A A:::::AS:::::::::::::::SS M::::::M M::::::M
AAAAAAA AAAAAAASSSSSSSSSSSSSSS MMMMMMMM MMMMMMMM
*/
create_assembly(format, encode_as_binary) {
let comment = "; ";
let prefix = "!";
let label_suffix = "";
if (format == "kick") {
comment = "// ";
prefix = ".";
label_suffix = ":";
}
let data = "";
data +=
"\n" +
comment +
this.savedata.sprites.length +
" sprites generated with spritemate on " +
new Date().toLocaleString();
if (!encode_as_binary)
data +=
"\n" +
comment +
"Byte 64 of each sprite contains multicolor (high nibble) & color (low nibble) information";
data +=
"\n\nLDA #$" +
("0" + this.savedata.colors[2].toString(16)).slice(-2) +
" " +
comment +
"sprite multicolor 1";
data += "\nSTA $D025";
data +=
"\nLDA #$" +
("0" + this.savedata.colors[3].toString(16)).slice(-2) +
" " +
comment +
"sprite multicolor 2";
data += "\nSTA $D026";
data += "\n";
let byte = "";
let bit = "";
for (
let j = 0;
j < this.savedata.sprites.length;
j++ // iterate through all sprites
) {
const spritedata = [].concat.apply([], this.savedata.sprites[j].pixels); // flatten 2d array
const is_multicolor = this.savedata.sprites[j].multicolor;
let stepping = 1;
if (is_multicolor) stepping = 2; // for multicolor, half of the array data can be ignored
const line_breaks_after = encode_as_binary ? 24 : 64;
data += "\n\n" + comment + "sprite " + j;
if (is_multicolor) {
data += " / " + "multicolor";
} else {
data += " / " + "singlecolor";
}
data +=
" / color: " +
"$" +
("0" + this.savedata.sprites[j].color.toString(16)).slice(-2);
data += "\n" + this.savedata.sprites[j].name + label_suffix + "\n";
// iterate through the pixel data array
// and create a hex or binary values based on multicolor or singlecolor
for (let i = 0; i < spritedata.length; i = i + 8) {
if (i % line_breaks_after == 0) {
data = data.substring(0, data.length - 1);
data += "\n" + prefix + "byte ";
}
for (let k = 0; k < 8; k = k + stepping) {
const pen = spritedata[i + k];
if (is_multicolor) {
if (pen == 0) bit = "00";
if (pen == 1) bit = "10";
if (pen == 2) bit = "01";
if (pen == 3) bit = "11";
}
if (!is_multicolor) {
bit = "1";
if (pen == 0) bit = "0";
}
byte = byte + bit;
}
if (encode_as_binary) {
data += "%" + byte + ",";
} else {
const hex = parseInt(byte, 2).toString(16);
data += "$" + ("0" + hex).slice(-2) + ",";
}
byte = "";
}
if (encode_as_binary) {
data = data.substring(0, data.length - 1);
} else {
// finally, we add multicolor and color info for byte 64
let high_nibble = "0000";
if (is_multicolor) high_nibble = "1000";
const low_nibble = (
"000" + (this.savedata.sprites[j].color >>> 0).toString(2)
).slice(-4);
const color_byte =
"$" +
("0" + parseInt(high_nibble + low_nibble, 2).toString(16)).slice(-2);
data += color_byte; // should be the individual color
}
}
return data;
}
/*
BBBBBBBBBBBBBBBBB AAA SSSSSSSSSSSSSSS IIIIIIIIII CCCCCCCCCCCCC
B::::::::::::::::B A:::A SS:::::::::::::::SI::::::::I CCC::::::::::::C
B::::::BBBBBB:::::B A:::::A S:::::SSSSSS::::::SI::::::::I CC:::::::::::::::C
BB:::::B B:::::B A:::::::A S:::::S SSSSSSSII::::::IIC:::::CCCCCCCC::::C
B::::B B:::::B A:::::::::A S:::::S I::::I C:::::C CCCCCC
B::::B B:::::B A:::::A:::::A S:::::S I::::IC:::::C
B::::BBBBBB:::::B A:::::A A:::::A S::::SSSS I::::IC:::::C
B:::::::::::::BB A:::::A A:::::A SS::::::SSSSS I::::IC:::::C
B::::BBBBBB:::::B A:::::A A:::::A SSS::::::::SS I::::IC:::::C
B::::B B:::::B A:::::AAAAAAAAA:::::A SSSSSS::::S I::::IC:::::C
B::::B B:::::B A:::::::::::::::::::::A S:::::S I::::IC:::::C
B::::B B:::::B A:::::AAAAAAAAAAAAA:::::A S:::::S I::::I C:::::C CCCCCC
BB:::::BBBBBB::::::BA:::::A A:::::A SSSSSSS S:::::SII::::::IIC:::::CCCCCCCC::::C
B:::::::::::::::::BA:::::A A:::::A S::::::SSSSSS:::::SI::::::::I CC:::::::::::::::C
B::::::::::::::::BA:::::A A:::::AS:::::::::::::::SS I::::::::I CCC::::::::::::C
BBBBBBBBBBBBBBBBBAAAAAAA AAAAAAASSSSSSSSSSSSSSS IIIIIIIIII CCCCCCCCCCCCC
*/
create_basic() {
let line_number = 10;
const line_inc = 10;
let data = "";
const max_sprites = Math.min(8, this.savedata.sprites.length); // display up to 8 sprites
data += line_number + " print chr$(147)";
line_number += line_inc;
data += "\n" + line_number + ' print "generated with spritemate"';
line_number += line_inc;
data +=
"\n" +
line_number +
' print "' +
max_sprites +
" of " +
this.savedata.sprites.length +
' sprites displayed."';
line_number += line_inc;
data +=
"\n" +
line_number +
" poke 53285," +
this.savedata.colors[2] +
": rem multicolor 1";
line_number += line_inc;
data +=
"\n" +
line_number +
" poke 53286," +
this.savedata.colors[3] +
": rem multicolor 2";
line_number += line_inc;
data +=
"\n" + line_number + " poke 53269,255 : rem set all 8 sprites visible";
line_number += line_inc;
data +=
"\n" +
line_number +
" for x=12800 to 12800+" +
(this.savedata.sprites.length * 64 - 1) +
": read y: poke x,y: next x: rem sprite generation";
line_number += line_inc;
let multicolor_byte = 0;
let double_x_byte = 0;
let double_y_byte = 0;
for (
let j = 0;
j < max_sprites;
j++ // iterate through all sprites
) {
data += "\n" + line_number + " :: rem " + this.savedata.sprites[j].name;
line_number += line_inc;
data +=
"\n" +
line_number +
" poke " +
(53287 + j) +
"," +
this.savedata.sprites[j].color +
": rem color = " +
this.savedata.sprites[j].color;
line_number += line_inc;
data +=
"\n" +
line_number +
" poke " +
(2040 + j) +
"," +
(200 + j) +
": rem pointer";
line_number += line_inc;
let xpos = j * 48 + 24 + 20;
let ypos = 120;
if (j >= 4) {
xpos -= 4 * 48;
ypos += 52;
}
data +=
"\n" +
line_number +
" poke " +
(53248 + j * 2) +
", " +
xpos +
": rem x pos";
line_number += line_inc;
data +=
"\n" +
line_number +
" poke " +
(53249 + j * 2) +
", " +
ypos +
": rem y pos";
line_number += line_inc;
// this bit manipulation is brilliant Ingo
if (this.savedata.sprites[j].multicolor)
multicolor_byte = multicolor_byte | (1 << j);
if (this.savedata.sprites[j].double_x)
double_x_byte = double_x_byte | (1 << j);
if (this.savedata.sprites[j].double_y)
double_y_byte = double_y_byte | (1 << j);
}
data +=
"\n" +
line_number +
" poke 53276, " +
multicolor_byte +
": rem multicolor";
line_number += line_inc;
data +=
"\n" + line_number + " poke 53277, " + double_x_byte + ": rem width";
line_number += line_inc;
data +=
"\n" + line_number + " poke 53271, " + double_y_byte + ": rem height";
line_number += line_inc;
let byte = "";
let bit = "";
line_number = 1000;
for (
let j = 0;
j < this.savedata.sprites.length;
j++ // iterate through all sprites
) {
const spritedata = [].concat.apply([], this.savedata.sprites[j].pixels); // flatten 2d array
const is_multicolor = this.savedata.sprites[j].multicolor;
let stepping = 1;
if (is_multicolor) stepping = 2; // for multicolor, half of the array data can be ignored
data += "\n" + line_number + " :: rem " + this.savedata.sprites[j].name;
line_number += line_inc;
if (is_multicolor) {
data += " / " + "multicolor";
} else {
data += " / " + "singlecolor";
}
data += " / color: " + this.savedata.sprites[j].color;
// iterate through the pixel data array
// and create a hex values based on multicolor or singlecolor
for (let i = 0; i < spritedata.length; i = i + 8) {
if (i % 128 == 0) {
data += "\n" + line_number + " data ";
line_number += line_inc;
}
for (let k = 0; k < 8; k = k + stepping) {
const pen = spritedata[i + k];
if (is_multicolor) {
if (pen == 0) bit = "00";
if (pen == 1) bit = "10";
if (pen == 2) bit = "01";
if (pen == 3) bit = "11";
}
if (!is_multicolor) {
bit = "1";
if (pen == 0) bit = "0";
}
byte = byte + bit;
}
const hex = parseInt(byte, 2).toString(10);
data += hex + ",";
byte = "";
}
// finally, we add multicolor and color info for byte 64
let high_nibble = "0000";
if (is_multicolor) high_nibble = "1000";
const low_nibble = (
"000" + (this.savedata.sprites[j].color >>> 0).toString(2)
).slice(-4);
const color_byte = parseInt(high_nibble + low_nibble, 2).toString(10);
data += color_byte; // should be the individual color
}
data += "\n";
data = data.replace(/,\n/g, "\n"); // removes all commas at the end of a DATA line
return data;
}
set_save_data(savedata): void {
this.savedata = savedata;
}
close_window(): void {
$("#window-" + this.window).dialog("close");
this.eventhandler.onLoad(); // calls "regain_keyboard_controls" method in app.js
}
} | the_stack |
* {{cookiecutter.project_name}}
* {{cookiecutter.project_name}} API
*
* The version of the OpenAPI document: 0.1.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import globalAxios, { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios';
import { Configuration } from '../configuration';
// Some imports not used depending on template conditions
// @ts-ignore
import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from '../common';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from '../base';
// @ts-ignore
import { BearerResponse } from '../models';
// @ts-ignore
import { ErrorModel } from '../models';
// @ts-ignore
import { HTTPValidationError } from '../models';
// @ts-ignore
import { User } from '../models';
// @ts-ignore
import { UserCreate } from '../models';
/**
* AuthApi - axios parameter creator
* @export
*/
export const AuthApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @summary Auth:Jwt.Login
* @param {string} username
* @param {string} password
* @param {string} [grantType]
* @param {string} [scope]
* @param {string} [clientId]
* @param {string} [clientSecret]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
authJwtLogin: async (username: string, password: string, grantType?: string, scope?: string, clientId?: string, clientSecret?: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'username' is not null or undefined
assertParamExists('authJwtLogin', 'username', username)
// verify required parameter 'password' is not null or undefined
assertParamExists('authJwtLogin', 'password', password)
const localVarPath = `/api/v1/auth/jwt/login`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
const localVarFormParams = new URLSearchParams();
if (grantType !== undefined) {
localVarFormParams.set('grant_type', grantType as any);
}
if (username !== undefined) {
localVarFormParams.set('username', username as any);
}
if (password !== undefined) {
localVarFormParams.set('password', password as any);
}
if (scope !== undefined) {
localVarFormParams.set('scope', scope as any);
}
if (clientId !== undefined) {
localVarFormParams.set('client_id', clientId as any);
}
if (clientSecret !== undefined) {
localVarFormParams.set('client_secret', clientSecret as any);
}
localVarHeaderParameter['Content-Type'] = 'application/x-www-form-urlencoded';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = localVarFormParams.toString();
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Auth:Jwt.Logout
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
authJwtLogout: async (options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/api/v1/auth/jwt/logout`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication OAuth2PasswordBearer required
// oauth required
await setOAuthToObject(localVarHeaderParameter, "OAuth2PasswordBearer", [], configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Register:Register
* @param {UserCreate} userCreate
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
registerRegister: async (userCreate: UserCreate, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'userCreate' is not null or undefined
assertParamExists('registerRegister', 'userCreate', userCreate)
const localVarPath = `/api/v1/auth/register`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(userCreate, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* AuthApi - functional programming interface
* @export
*/
export const AuthApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = AuthApiAxiosParamCreator(configuration)
return {
/**
*
* @summary Auth:Jwt.Login
* @param {string} username
* @param {string} password
* @param {string} [grantType]
* @param {string} [scope]
* @param {string} [clientId]
* @param {string} [clientSecret]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async authJwtLogin(username: string, password: string, grantType?: string, scope?: string, clientId?: string, clientSecret?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<BearerResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.authJwtLogin(username, password, grantType, scope, clientId, clientSecret, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Auth:Jwt.Logout
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async authJwtLogout(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<any>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.authJwtLogout(options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Register:Register
* @param {UserCreate} userCreate
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async registerRegister(userCreate: UserCreate, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<User>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.registerRegister(userCreate, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* AuthApi - factory interface
* @export
*/
export const AuthApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = AuthApiFp(configuration)
return {
/**
*
* @summary Auth:Jwt.Login
* @param {string} username
* @param {string} password
* @param {string} [grantType]
* @param {string} [scope]
* @param {string} [clientId]
* @param {string} [clientSecret]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
authJwtLogin(username: string, password: string, grantType?: string, scope?: string, clientId?: string, clientSecret?: string, options?: any): AxiosPromise<BearerResponse> {
return localVarFp.authJwtLogin(username, password, grantType, scope, clientId, clientSecret, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Auth:Jwt.Logout
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
authJwtLogout(options?: any): AxiosPromise<any> {
return localVarFp.authJwtLogout(options).then((request) => request(axios, basePath));
},
/**
*
* @summary Register:Register
* @param {UserCreate} userCreate
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
registerRegister(userCreate: UserCreate, options?: any): AxiosPromise<User> {
return localVarFp.registerRegister(userCreate, options).then((request) => request(axios, basePath));
},
};
};
/**
* Request parameters for authJwtLogin operation in AuthApi.
* @export
* @interface AuthApiAuthJwtLoginRequest
*/
export interface AuthApiAuthJwtLoginRequest {
/**
*
* @type {string}
* @memberof AuthApiAuthJwtLogin
*/
readonly username: string
/**
*
* @type {string}
* @memberof AuthApiAuthJwtLogin
*/
readonly password: string
/**
*
* @type {string}
* @memberof AuthApiAuthJwtLogin
*/
readonly grantType?: string
/**
*
* @type {string}
* @memberof AuthApiAuthJwtLogin
*/
readonly scope?: string
/**
*
* @type {string}
* @memberof AuthApiAuthJwtLogin
*/
readonly clientId?: string
/**
*
* @type {string}
* @memberof AuthApiAuthJwtLogin
*/
readonly clientSecret?: string
}
/**
* Request parameters for registerRegister operation in AuthApi.
* @export
* @interface AuthApiRegisterRegisterRequest
*/
export interface AuthApiRegisterRegisterRequest {
/**
*
* @type {UserCreate}
* @memberof AuthApiRegisterRegister
*/
readonly userCreate: UserCreate
}
/**
* AuthApi - object-oriented interface
* @export
* @class AuthApi
* @extends {BaseAPI}
*/
export class AuthApi extends BaseAPI {
/**
*
* @summary Auth:Jwt.Login
* @param {AuthApiAuthJwtLoginRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof AuthApi
*/
public authJwtLogin(requestParameters: AuthApiAuthJwtLoginRequest, options?: AxiosRequestConfig) {
return AuthApiFp(this.configuration).authJwtLogin(requestParameters.username, requestParameters.password, requestParameters.grantType, requestParameters.scope, requestParameters.clientId, requestParameters.clientSecret, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Auth:Jwt.Logout
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof AuthApi
*/
public authJwtLogout(options?: AxiosRequestConfig) {
return AuthApiFp(this.configuration).authJwtLogout(options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Register:Register
* @param {AuthApiRegisterRegisterRequest} requestParameters Request parameters.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof AuthApi
*/
public registerRegister(requestParameters: AuthApiRegisterRegisterRequest, options?: AxiosRequestConfig) {
return AuthApiFp(this.configuration).registerRegister(requestParameters.userCreate, options).then((request) => request(this.axios, this.basePath));
}
} | the_stack |
import 'chrome://resources/cr_components/managed_dialog/managed_dialog.js';
import 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js';
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import 'chrome://resources/cr_elements/cr_checkbox/cr_checkbox.m.js';
import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js';
import 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.m.js';
import 'chrome://resources/cr_elements/icons.m.js';
import 'chrome://resources/cr_elements/policy/cr_policy_pref_indicator.m.js';
import 'chrome://resources/cr_elements/shared_style_css.m.js';
import 'chrome://resources/cr_elements/shared_vars_css.m.js';
import 'chrome://resources/js/action_link.js';
import 'chrome://resources/cr_elements/action_link_css.m.js';
import 'chrome://resources/polymer/v3_0/iron-flex-layout/iron-flex-layout-classes.js';
import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js';
import './add_languages_dialog.js';
import './languages.js';
import '../controls/settings_toggle_button.js';
import '../icons.js';
import '../settings_shared_css.js';
import '../settings_vars_css.js';
import {CrActionMenuElement} from '//resources/cr_elements/cr_action_menu/cr_action_menu.js';
import {CrCheckboxElement} from 'chrome://resources/cr_elements/cr_checkbox/cr_checkbox.m.js';
import {CrLazyRenderElement} from 'chrome://resources/cr_elements/cr_lazy_render/cr_lazy_render.m.js';
import {assert} from 'chrome://resources/js/assert.m.js';
import {isWindows} from 'chrome://resources/js/cr.m.js';
import {focusWithoutInk} from 'chrome://resources/js/cr/ui/focus_without_ink.m.js';
import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js';
import {flush, html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {SettingsToggleButtonElement} from '../controls/settings_toggle_button.js';
import {loadTimeData} from '../i18n_setup.js';
import {LifetimeBrowserProxyImpl} from '../lifetime_browser_proxy.js';
import {PrefsMixin} from '../prefs/prefs_mixin.js';
import {LanguageSettingsActionType, LanguageSettingsMetricsProxy, LanguageSettingsMetricsProxyImpl, LanguageSettingsPageImpressionType} from './languages_settings_metrics_proxy.js';
import {LanguageHelper, LanguagesModel, LanguageState} from './languages_types.js';
/**
* Millisecond delay that can be used when closing an action menu to keep it
* briefly on-screen.
*/
export const kMenuCloseDelay: number = 100;
interface RepeaterEvent<T> extends Event {
model: {
item: T,
};
}
type FocusConfig = Map<string, (string|(() => void))>;
export interface SettingsLanguagesSubpageElement {
$: {
menu: CrLazyRenderElement<CrActionMenuElement>,
}
}
const SettingsLanguagesSubpageElementBase =
I18nMixin(PrefsMixin(PolymerElement));
export class SettingsLanguagesSubpageElement extends
SettingsLanguagesSubpageElementBase {
static get is() {
return 'settings-languages-subpage';
}
static get properties() {
return {
/**
* Preferences state.
*/
prefs: {
type: Object,
notify: true,
},
/**
* Read-only reference to the languages model provided by the
* 'settings-languages' instance.
*/
languages: {
type: Object,
notify: true,
},
languageHelper: Object,
/**
* The language to display the details for.
*/
detailLanguage_: Object,
showAddLanguagesDialog_: Boolean,
showAddAlwaysTranslateDialog_: Boolean,
showAddNeverTranslateDialog_: Boolean,
addLanguagesDialogLanguages_: Array,
focusConfig_: {
type: Object,
value: function() {
return new Map();
},
},
showManagedLanguageDialog_: {
type: Boolean,
value: false,
},
enableDesktopDetailedLanguageSettings_: {
type: Boolean,
value: function() {
let enabled = false;
// <if expr="not lacros">
enabled =
loadTimeData.getBoolean('enableDesktopDetailedLanguageSettings');
// </if>
return enabled;
},
},
};
}
languages?: LanguagesModel;
languageHelper: LanguageHelper;
private detailLanguage_?: LanguageState;
private showAddLanguagesDialog_: boolean;
private showAddAlwaysTranslateDialog_: boolean;
private showAddNeverTranslateDialog_: boolean;
private addLanguagesDialogLanguages_:
Array<chrome.languageSettingsPrivate.Language>|null;
private focusConfig_: FocusConfig;
private showManagedLanguageDialog_: boolean;
private enableDesktopDetailedLanguageSettings_: boolean;
private languageSettingsMetricsProxy_: LanguageSettingsMetricsProxy =
LanguageSettingsMetricsProxyImpl.getInstance();
// <if expr="is_win">
private isChangeInProgress_: boolean = false;
// </if>
/**
* Stamps and opens the Add Languages dialog, registering a listener to
* disable the dialog's dom-if again on close.
*/
private onAddLanguagesTap_(e: Event) {
e.preventDefault();
this.languageSettingsMetricsProxy_.recordPageImpressionMetric(
LanguageSettingsPageImpressionType.ADD_LANGUAGE);
this.addLanguagesDialogLanguages_ = this.languages!.supported.filter(
language => this.languageHelper.canEnableLanguage(language));
this.showAddLanguagesDialog_ = true;
}
private onAddLanguagesDialogClose_() {
this.showAddLanguagesDialog_ = false;
this.addLanguagesDialogLanguages_ = null;
focusWithoutInk(assert(this.shadowRoot!.querySelector('#addLanguages')!));
}
private onLanguagesAdded_(e: CustomEvent<Array<string>>) {
const languagesToAdd = e.detail;
languagesToAdd.forEach(languageCode => {
this.languageHelper.enableLanguage(languageCode);
LanguageSettingsMetricsProxyImpl.getInstance().recordSettingsMetric(
LanguageSettingsActionType.LANGUAGE_ADDED);
});
}
/**
* Stamps and opens the Add Languages dialog, registering a listener to
* disable the dialog's dom-if again on close.
*/
private onAddAlwaysTranslateLanguagesClick_(e: Event) {
e.preventDefault();
const translatableLanguages = this.getTranslatableLanguages_();
this.addLanguagesDialogLanguages_ = translatableLanguages.filter(
language => !this.languages!.alwaysTranslate.includes(language));
this.showAddAlwaysTranslateDialog_ = true;
}
private onAlwaysTranslateDialogClose_() {
this.showAddAlwaysTranslateDialog_ = false;
this.addLanguagesDialogLanguages_ = null;
focusWithoutInk(
assert(this.shadowRoot!.querySelector('#addAlwaysTranslate')!));
}
/**
* Helper function fired by the add dialog's on-languages-added event. Adds
* selected languages to the always-translate languages list.
*/
private onAlwaysTranslateLanguagesAdded_(e: CustomEvent<Array<string>>) {
const languagesToAdd = e.detail;
languagesToAdd.forEach(languageCode => {
this.languageHelper.setLanguageAlwaysTranslateState(languageCode, true);
});
}
/**
* Removes a language from the always translate languages list.
*/
private onRemoveAlwaysTranslateLanguageClick_(
e: RepeaterEvent<chrome.languageSettingsPrivate.Language>) {
const languageCode = e.model.item.code;
this.languageHelper.setLanguageAlwaysTranslateState(languageCode, false);
}
/**
* Checks if there are supported languages that are not enabled but can be
* enabled.
* @return True if there is at least one available language.
*/
private canEnableSomeSupportedLanguage_(languages?: LanguagesModel): boolean {
return languages === undefined || languages.supported.some(language => {
return this.languageHelper.canEnableLanguage(language);
});
}
/**
* Stamps and opens the Add Languages dialog, registering a listener to
* disable the dialog's dom-if again on close.
*/
private onAddNeverTranslateLanguagesClick_(e: Event) {
e.preventDefault();
this.addLanguagesDialogLanguages_ = this.languages!.supported.filter(
language => !this.languages!.neverTranslate.includes(language));
this.showAddNeverTranslateDialog_ = true;
}
private onNeverTranslateDialogClose_() {
this.showAddNeverTranslateDialog_ = false;
this.addLanguagesDialogLanguages_ = null;
focusWithoutInk(
assert(this.shadowRoot!.querySelector('#addNeverTranslate')!));
}
private onNeverTranslateLanguagesAdded_(e: CustomEvent<Array<string>>) {
const languagesToAdd = e.detail;
languagesToAdd.forEach(languageCode => {
this.languageHelper.disableTranslateLanguage(languageCode);
});
}
/**
* Removes a language from the never translate languages list.
*/
private onRemoveNeverTranslateLanguageClick_(
e: RepeaterEvent<chrome.languageSettingsPrivate.Language>) {
const languageCode = e.model.item.code;
this.languageHelper.enableTranslateLanguage(languageCode);
}
/**
* Used to determine whether to show the separator between checkbox settings
* and move buttons in the dialog menu.
* @return True if there is currently more than one selected language.
*/
private shouldShowDialogSeparator_(): boolean {
return this.languages !== undefined && this.languages.enabled.length > 1;
}
/**
* Used to determine which "Move" buttons to show for ordering enabled
* languages.
* @return True if |language| is at the |n|th index in the list of enabled
* languages.
*/
private isNthLanguage_(n: number): boolean {
if (this.languages === undefined || this.detailLanguage_ === undefined) {
return false;
}
if (n >= this.languages.enabled.length) {
return false;
}
const compareLanguage = assert(this.languages.enabled[n]);
return this.detailLanguage_.language === compareLanguage.language;
}
/**
* @return True if the "Move to top" option for |language| should be visible.
*/
private showMoveUp_(): boolean {
// "Move up" is a no-op for the top language, and redundant with
// "Move to top" for the 2nd language.
return !this.isNthLanguage_(0) && !this.isNthLanguage_(1);
}
/**
* @return True if the "Move down" option for |language| should be visible.
*/
private showMoveDown_(): boolean {
return this.languages !== undefined &&
!this.isNthLanguage_(this.languages.enabled.length - 1);
}
/**
* @return True if there are less than 2 languages.
*/
private isHelpTextHidden_(): boolean {
return this.languages !== undefined && this.languages.enabled.length <= 1;
}
/**
* @param languageCode The language code identifying a language.
* @param translateTarget The target language.
* @return 'target' if |languageCode| matches the target language,
* 'non-target' otherwise.
*/
isTranslationTarget_(languageCode: string, translateTarget: string): string {
if (this.languageHelper.convertLanguageCodeForTranslate(languageCode) ===
translateTarget) {
return 'target';
} else {
return 'non-target';
}
}
private onTranslateToggleChange_(e: Event) {
this.languageSettingsMetricsProxy_.recordSettingsMetric(
(e.target as SettingsToggleButtonElement).checked ?
LanguageSettingsActionType.ENABLE_TRANSLATE_GLOBALLY :
LanguageSettingsActionType.DISABLE_TRANSLATE_GLOBALLY);
}
// <if expr="is_win">
/**
* @param languageCode The language code identifying a language.
* @param prospectiveUILanguage The prospective UI language.
* @return True if the prospective UI language is set to
* |languageCode| but requires a restart to take effect.
*/
private isRestartRequired_(
languageCode: string, prospectiveUILanguage: string): boolean {
return prospectiveUILanguage === languageCode &&
this.languageHelper.requiresRestart();
}
private onCloseMenu_() {
if (!this.isChangeInProgress_) {
return;
}
flush();
this.isChangeInProgress_ = false;
const restartButton = this.shadowRoot!.querySelector('#restartButton');
if (!restartButton) {
return;
}
focusWithoutInk(restartButton);
}
/**
* @param prospectiveUILanguage The chosen UI language.
* @return True if the given language cannot be set as the
* prospective UI language by the user.
*/
private disableUILanguageCheckbox_(
languageState: LanguageState, prospectiveUILanguage: string): boolean {
if (this.detailLanguage_ === undefined) {
return true;
}
// If the language cannot be a UI language, we can't set it as the
// prospective UI language.
if (!languageState.language.supportsUI) {
return true;
}
// Unchecking the currently chosen language doesn't make much sense.
if (languageState.language.code === prospectiveUILanguage) {
return true;
}
// Check if the language is prohibited by the current "AllowedLanguages"
// policy.
if (languageState.language.isProhibitedLanguage) {
return true;
}
// Otherwise, the prospective language can be changed to this language.
return false;
}
/**
* Handler for changes to the UI language checkbox.
*/
private onUILanguageChange_(e: Event) {
// We don't support unchecking this checkbox. TODO(michaelpg): Ask for a
// simpler widget.
assert((e.target as CrCheckboxElement).checked);
this.isChangeInProgress_ = true;
this.languageHelper.setProspectiveUILanguage(
this.detailLanguage_!.language.code);
this.languageHelper.moveLanguageToFront(
this.detailLanguage_!.language.code);
this.closeMenuSoon_();
}
/**
* Checks whether the prospective UI language (the pref that indicates what
* language to use in Chrome) matches the current language. This pref is
* used only on Chrome OS and Windows; we don't control the UI language
* elsewhere.
* @param languageCode The language code identifying a language.
* @param prospectiveUILanguage The prospective UI language.
* @return True if the given language matches the prospective UI pref (which
* may be different from the actual UI language).
*/
private isProspectiveUILanguage_(
languageCode: string, prospectiveUILanguage: string): boolean {
return languageCode === prospectiveUILanguage;
}
/**
* Handler for the restart button.
*/
private onRestartTap_() {
// <if expr="is_win">
LifetimeBrowserProxyImpl.getInstance().restart();
// </if>
}
// </if>
/**
* @param targetLanguageCode The default translate target language.
* @return True if the translate checkbox should be disabled.
*/
private disableTranslateCheckbox_(
languageState: LanguageState|undefined,
targetLanguageCode: string): boolean {
if (languageState === undefined || languageState.language === undefined ||
!languageState.language.supportsTranslate) {
return true;
}
if (this.languageHelper.isOnlyTranslateBlockedLanguage(languageState)) {
return true;
}
return this.languageHelper.convertLanguageCodeForTranslate(
languageState.language.code) === targetLanguageCode;
}
/**
* Handler for changes to the translate checkbox.
*/
private onTranslateCheckboxChange_(e: Event) {
if ((e.target as CrCheckboxElement).checked) {
this.languageHelper.enableTranslateLanguage(
this.detailLanguage_!.language.code);
this.languageSettingsMetricsProxy_.recordSettingsMetric(
LanguageSettingsActionType.ENABLE_TRANSLATE_FOR_SINGLE_LANGUAGE);
} else {
this.languageHelper.disableTranslateLanguage(
this.detailLanguage_!.language.code);
this.languageSettingsMetricsProxy_.recordSettingsMetric(
LanguageSettingsActionType.DISABLE_TRANSLATE_FOR_SINGLE_LANGUAGE);
}
this.closeMenuSoon_();
}
/**
* Returns "complex" if the menu includes checkboxes, which should change
* the spacing of items and show a separator in the menu.
*/
getMenuClass_(translateEnabled: boolean): string {
if (translateEnabled || isWindows) {
return 'complex';
}
return '';
}
/**
* Moves the language to the top of the list.
*/
private onMoveToTopTap_() {
this.$.menu.get().close();
if (this.detailLanguage_!.isForced) {
// If language is managed, show dialog to inform user it can't be modified
this.showManagedLanguageDialog_ = true;
return;
}
this.languageHelper.moveLanguageToFront(
this.detailLanguage_!.language.code);
this.languageSettingsMetricsProxy_.recordSettingsMetric(
LanguageSettingsActionType.LANGUAGE_LIST_REORDERED);
}
/**
* Moves the language up in the list.
*/
private onMoveUpTap_() {
this.$.menu.get().close();
if (this.detailLanguage_!.isForced) {
// If language is managed, show dialog to inform user it can't be modified
this.showManagedLanguageDialog_ = true;
return;
}
this.languageHelper.moveLanguage(
this.detailLanguage_!.language.code, true /* upDirection */);
this.languageSettingsMetricsProxy_.recordSettingsMetric(
LanguageSettingsActionType.LANGUAGE_LIST_REORDERED);
}
/**
* Moves the language down in the list.
*/
private onMoveDownTap_() {
this.$.menu.get().close();
if (this.detailLanguage_!.isForced) {
// If language is managed, show dialog to inform user it can't be modified
this.showManagedLanguageDialog_ = true;
return;
}
this.languageHelper.moveLanguage(
this.detailLanguage_!.language.code, false /* upDirection */);
this.languageSettingsMetricsProxy_.recordSettingsMetric(
LanguageSettingsActionType.LANGUAGE_LIST_REORDERED);
}
/**
* Disables the language.
*/
private onRemoveLanguageTap_() {
this.$.menu.get().close();
if (this.detailLanguage_!.isForced) {
// If language is managed, show dialog to inform user it can't be modified
this.showManagedLanguageDialog_ = true;
return;
}
this.languageHelper.disableLanguage(this.detailLanguage_!.language.code);
this.languageSettingsMetricsProxy_.recordSettingsMetric(
LanguageSettingsActionType.LANGUAGE_REMOVED);
}
/**
* Returns either the "selected" class, if the language matches the
* prospective UI language, or an empty string. Languages can only be
* selected on Chrome OS and Windows.
* @param languageCode The language code identifying a language.
* @param prospectiveUILanguage The prospective UI language.
* @return The class name for the language item.
*/
private getLanguageItemClass_(
languageCode: string, prospectiveUILanguage: string): string {
if (isWindows && languageCode === prospectiveUILanguage) {
return 'selected';
}
return '';
}
private onDotsTap_(e: RepeaterEvent<LanguageState>) {
// Set a copy of the LanguageState object since it is not data-bound to
// the languages model directly.
this.detailLanguage_ = Object.assign({}, e.model.item);
this.$.menu.get().showAt(e.target as HTMLElement);
this.languageSettingsMetricsProxy_.recordPageImpressionMetric(
LanguageSettingsPageImpressionType.LANGUAGE_OVERFLOW_MENU_OPENED);
}
/**
* Closes the shared action menu after a short delay, so when a checkbox is
* clicked it can be seen to change state before disappearing.
*/
private closeMenuSoon_() {
const menu = this.$.menu.get();
setTimeout(function() {
if (menu.open) {
menu.close();
}
}, kMenuCloseDelay);
}
/**
* Triggered when the managed language dialog is dismissed.
*/
private onManagedLanguageDialogClosed_() {
this.showManagedLanguageDialog_ = false;
}
/**
* @return Whether the list is non-null and has items.
*/
private hasSome_(list: Array<any>): boolean {
return !!(list && list.length);
}
/**
* Gets the list of languages that chrome can translate
*/
private getTranslatableLanguages_():
Array<chrome.languageSettingsPrivate.Language> {
return this.languages!.supported.filter(language => {
return this.languageHelper.isLanguageTranslatable(language);
});
}
static get template() {
return html`{__html_template__}`;
}
}
customElements.define(
SettingsLanguagesSubpageElement.is, SettingsLanguagesSubpageElement); | the_stack |
import camelCase from '../../x/camelCase.ts';
import { normalize } from './normalize.ts';
import { IFlagArgument, IFlagOptions, IFlags, IFlagsResult, IFlagValue, IFlagValueType, IParseOptions, IType, OptionType } from './types.ts';
import { boolean } from './types/boolean.ts';
import { number } from './types/number.ts';
import { string } from './types/string.ts';
import { validateFlags } from './validate-flags.ts';
const Types: Record<string, IType<any>> = {
[ OptionType.STRING ]: string,
[ OptionType.NUMBER ]: number,
[ OptionType.BOOLEAN ]: boolean
};
/**
* Parse command line arguments.
*
* @param args Command line arguments e.g: `Deno.args`
* @param opts Parse options.
*/
export function parseFlags<O = any>( args: string[], opts: IParseOptions = {} ): IFlagsResult<O> {
!opts.flags && ( opts.flags = [] );
const normalized = normalize( args );
let inLiteral = false;
let negate = false;
const flags: IFlags = {};
const literal: string[] = [];
const unknown: string[] = [];
let stopEarly: boolean = false;
opts.flags.forEach( opt => {
opt.depends?.forEach( flag => {
if ( !opts.flags || !getOption( opts.flags, flag ) ) {
throw new Error( `Unknown required option: ${ flag }` );
}
} );
opt.conflicts?.forEach( flag => {
if ( !opts.flags || !getOption( opts.flags, flag ) ) {
throw new Error( `Unknown conflicting option: ${ flag }` );
}
} );
} );
for ( let i = 0; i < normalized.length; i++ ) {
let option: IFlagOptions | undefined;
let args: IFlagArgument[] | undefined;
const current = normalized[ i ];
// literal args after --
if ( inLiteral ) {
literal.push( current );
continue;
}
if ( current === '--' ) {
inLiteral = true;
continue;
}
const isFlag = current.length > 1 && current[ 0 ] === '-';
const next = () => normalized[ i + 1 ];
if ( isFlag && !stopEarly ) {
if ( current[ 2 ] === '-' || ( current[ 1 ] === '-' && current.length === 3 ) ) {
throw new Error( `Invalid flag name: ${ current }` );
}
negate = current.indexOf( '--no-' ) === 0;
const name = current.replace( /^-+(no-)?/, '' );
option = getOption( opts.flags, name );
if ( !option ) {
if ( opts.flags.length ) {
throw new Error( `Unknown option: ${ current }` );
}
option = {
name,
optionalValue: true,
type: OptionType.STRING
};
}
if ( !option.name ) {
throw new Error( `Missing name for option: ${ current }` );
}
const friendlyName: string = camelCase( option.name );
if ( typeof flags[ friendlyName ] !== 'undefined' && !option.collect ) {
throw new Error( `Duplicate option: ${ current }` );
}
args = option.args?.length ? option.args : [ {
type: option.type,
requiredValue: option.requiredValue,
optionalValue: option.optionalValue,
variadic: option.variadic,
list: option.list,
separator: option.separator
} ];
let argIndex = 0;
let inOptionalArg = false;
const previous = flags[ friendlyName ];
parseNext( option, args );
if ( typeof flags[ friendlyName ] === 'undefined' ) {
if ( typeof option.default !== 'undefined' ) {
flags[ friendlyName ] = typeof option.default === 'function' ? option.default() : option.default;
} else if ( args[ argIndex ].requiredValue ) {
throw new Error( `Missing value for option: --${ option.name }` );
} else {
flags[ friendlyName ] = true;
}
}
if ( typeof option.value !== 'undefined' ) {
flags[ friendlyName ] = option.value( flags[ friendlyName ], previous );
} else if ( option.collect ) {
const value = ( previous || [] ) as IFlagValue[];
value.push( flags[ friendlyName ] as IFlagValue );
flags[ friendlyName ] = value;
}
/** Parse next argument for current option. */
function parseNext( option: IFlagOptions, args: IFlagArgument[] ): void {
const arg: IFlagArgument = args[ argIndex ];
if ( !arg ) {
throw new Error( 'Unknown option: ' + next() );
}
if ( !arg.type ) {
arg.type = OptionType.BOOLEAN;
}
if ( option.args?.length ) {
// make all value's required per default
if ( ( typeof arg.optionalValue === 'undefined' || arg.optionalValue === false ) &&
typeof arg.requiredValue === 'undefined'
) {
arg.requiredValue = true;
}
} else {
// make non boolean value required per default
if ( arg.type !== OptionType.BOOLEAN &&
( typeof arg.optionalValue === 'undefined' || arg.optionalValue === false ) &&
typeof arg.requiredValue === 'undefined'
) {
arg.requiredValue = true;
}
}
if ( arg.requiredValue ) {
if ( inOptionalArg ) {
throw new Error( `An required argument can not follow an optional argument but found in: ${ option.name }` );
}
} else {
inOptionalArg = true;
}
if ( negate ) {
if ( arg.type !== OptionType.BOOLEAN && !arg.optionalValue ) {
throw new Error( `Negate not supported by --${ option.name }. Only optional option or options of type boolean can be negated.` );
}
flags[ friendlyName ] = false;
return;
}
let result: IFlagValue | undefined;
let increase = false;
if ( arg.list && hasNext( arg ) ) {
const parsed: IFlagValueType[] = next()
.split( arg.separator || ',' )
.map( ( nextValue: string ) => {
const value = parseValue( option, arg, nextValue );
if ( typeof value === 'undefined' ) {
throw new Error( `List item of option --${ option?.name } must be of type ${ arg.type } but got: ${ nextValue }` );
}
return value;
} );
if ( parsed?.length ) {
result = parsed;
}
} else {
if ( hasNext( arg ) ) {
result = parseValue( option, arg, next() );
} else if ( arg.optionalValue && arg.type === OptionType.BOOLEAN ) {
result = true;
}
}
if ( increase ) {
i++;
if ( !arg.variadic ) {
argIndex++;
} else if ( args[ argIndex + 1 ] ) {
throw new Error( 'An argument cannot follow an variadic argument: ' + next() );
}
}
if ( typeof result !== 'undefined' && ( ( args.length > 1 ) || arg.variadic ) ) {
if ( !flags[ friendlyName ] ) {
flags[ friendlyName ] = [];
}
( flags[ friendlyName ] as IFlagValue[] ).push( result );
if ( hasNext( arg ) ) {
parseNext( option, args );
}
} else {
flags[ friendlyName ] = result;
}
/** Check if current option should have an argument. */
function hasNext( arg: IFlagArgument ): boolean {
return !!(
normalized[ i + 1 ] &&
( arg.optionalValue || arg.requiredValue || arg.variadic ) &&
( normalized[ i + 1 ][ 0 ] !== '-' ||
( arg.type === OptionType.NUMBER && !isNaN( normalized[ i + 1 ] as any ) )
) &&
arg );
}
/** Parse argument value. */
function parseValue( option: IFlagOptions, arg: IFlagArgument, nextValue: string ): IFlagValueType {
let result: IFlagValueType = opts.parse ?
opts.parse( arg.type || OptionType.STRING, option, arg, nextValue ) :
parseFlagValue( option, arg, nextValue );
if ( typeof result !== 'undefined' ) {
increase = true;
}
return result;
}
}
} else {
if ( opts.stopEarly ) {
stopEarly = true;
}
unknown.push( current );
}
}
if ( opts.flags && opts.flags.length ) {
validateFlags( opts.flags, flags, opts.knownFlaks, opts.allowEmpty );
}
return { flags: flags as any as O, unknown, literal };
}
export function parseFlagValue( option: IFlagOptions, arg: IFlagArgument, nextValue: string ): any {
const type = Types[ arg.type || OptionType.STRING ];
if ( !type ) {
throw new Error( `Unknown type ${ arg.type }` );
}
return type( option, arg, nextValue );
}
/**
* Find option by name.
*
* @param flags Source option's array.
* @param name Name of the option.
*/
export function getOption( flags: IFlagOptions[], name: string ): IFlagOptions | undefined {
while ( name[ 0 ] === '-' ) {
name = name.slice( 1 );
}
for ( const flag of flags ) {
if ( isOption( flag, name ) ) {
return flag;
}
}
return;
}
/**
* Check if option has name or alias.
*
* @param option The option to check.
* @param name The option name or alias.
*/
export function isOption( option: IFlagOptions, name: string ) {
return option.name === name ||
( option.aliases && option.aliases.indexOf( name ) !== -1 );
} | the_stack |
import React, { FC, useEffect, useRef, useCallback, useState, HTMLProps } from 'react';
import throttle from 'lodash.throttle'
import { Universe, UniverseState, CanvasRenderer, Simulator, ParticleForce, Vector, forces, PixelManager, Array2D, timing } from '../universe'
import { getMousePosition, getTouchPosition, RGBA } from '../utils'
import createImageUniverse, { ImageUniverseSetupResult } from './createImageUniverse'
import useTransientParticleForce from './useTransientParticleForce';
import { Dimensions, ImageState } from '../types'
export type PixelOptions = {
x: number;
y: number;
image: Array2D<RGBA>
}
/**
* Options to be applied to particles during their creation.
*/
export interface ParticleOptions {
/**
* Given a pixel in the img, the filter determines whether or not a particle should be created for this pixel.
* This is run for all pixels in the image in random order until maxParticles limit is reached. If the filter
* returns true, a particle will be created for this pixel.
*/
filter?: (options: PixelOptions) => boolean;
/**
* Given a pixel in the img, calculates the radius of the corresponding particle.
* This function is only executed on pixels whose filters return true.
*/
radius?: (options: PixelOptions) => number;
/**
* Given a pixel in the img, calculates the mass of the corresponding particle.
* This function is only executed on pixels whose filters return true.
*/
mass?: (options: PixelOptions) => number;
/**
* Given a pixel in the img, calculates the color of the corresponding particle.
* Fewer colors will result in better performance (higher framerates).
* This function is only executed on pixels whose filters return true.
*/
color?: (options: PixelOptions) => string;
/**
* Given a pixel in the img, calculates the coefficient of kinetic friction of the corresponding particle.
* This should have a value between 0 and 1.
* This function is only executed on pixels whose filters return true.
*/
friction?: (options: PixelOptions) => number;
/**
* Given a pixel in the img, calculates the initial position vector of the corresponding particle.
* This function is only executed on pixels whose filters return true.
*/
initialPosition?: (options: PixelOptions & {finalPosition: Vector, canvasDimensions: Dimensions}) => Vector;
/**
* Given a pixel in the img, calculates the initial velocity vector of the corresponding particle.
* This function is only executed on pixels whose filters return true.
*/
initialVelocity?: (options: PixelOptions) => Vector;
}
/**
* Available props for ParticleImage.
* @noInheritDoc
*/
export interface ParticleImageProps extends HTMLProps<HTMLCanvasElement> {
/**
* Img src url to load image
*/
src: string
/**
* Height of the canvas.
*/
height?: number;
/**
* Width of the canvas.
*/
width?: number;
/**
* Scales the image provided via src.
*/
scale?: number;
/**
* The maximum number of particles that will be created in the canvas.
*/
maxParticles?: number;
/**
* The amount of entropy to act on the particles.
*/
entropy?: number;
/**
* The background color of the canvas.
*/
backgroundColor?: string;
/**
* Options to be applied to particles during their creation.
*/
particleOptions?: ParticleOptions;
/**
* An interactive force to be applied to the particles during mousemove events.
*/
mouseMoveForce?: (x: number, y: number) => ParticleForce;
/**
* Time in milliseconds that force resulting from mousemove event should last in universe.
*/
mouseMoveForceDuration?: number;
/**
* An interactive force to be applied to the particles during touchmove events.
*/
touchMoveForce?: (x: number, y: number) => ParticleForce;
/**
* Time in milliseconds that force resulting from mousemove event should last in universe.
*/
touchMoveForceDuration?: number;
/**
* An interactive force to be applied to the particles during mousedown events.
*/
mouseDownForce?: (x: number, y: number) => ParticleForce;
/**
* Time in milliseconds that force resulting from mousemove event should last in universe.
*/
mouseDownForceDuration?: number;
/**
* The duration in milliseconds that it should take for the universe to reach full health.
*/
creationDuration?: number;
/**
* The duration in milliseconds that it should take for the universe to die.
*/
deathDuration?: number;
/**
* A timing function to dictate how the particles in the universe grow from radius zero to their full radius.
* This function receives a progress argument between 0 and 1 and should return a number between 0 and 1.
*/
creationTimingFn?: timing.TimingFunction;
/**
* A timing function to dictate how the particles in the universe shrink from their full radius to radius zero.
* This function receives a progress argument between 0 and 1 and should return a number between 0 and 1.
*/
deathTimingFn?: timing.TimingFunction;
/**
* Callback invoked on universe state changes.
*/
onUniverseStateChange?: (state: UniverseState, universe: Universe) => void;
/**
* Callback invoked on image loading state changes.
*/
onImageStateChange?: (state: ImageState) => void;
}
/**
* Default particle options
* @internal
*/
const defaultParticleOptions: Required<ParticleOptions> = {
filter: () => true,
radius: () => 1,
mass: () => 50,
color: () => 'white',
friction: () => .15,
initialPosition: ({finalPosition}) => finalPosition,
initialVelocity: () => new Vector(0, 0)
}
const ParticleImage: FC<ParticleImageProps> = ({
src,
height = 400,
width = 400,
scale = 1,
maxParticles = 5000,
entropy = 20,
backgroundColor = '#222',
particleOptions = {},
mouseMoveForce,
touchMoveForce,
mouseDownForce,
mouseMoveForceDuration = 100,
touchMoveForceDuration = 100,
mouseDownForceDuration = 100,
creationTimingFn,
creationDuration,
deathTimingFn,
deathDuration,
onUniverseStateChange,
onImageStateChange,
style={},
...otherProps
}) => {
const [canvas, setCanvas] = useState<HTMLCanvasElement>()
const [universe, setUniverse] = useState<Universe>()
const simulatorRef = useRef<Simulator>()
const entropyForceRef = useRef<ParticleForce>()
const [pixelManagers, setPixelManagers] = useState<PixelManager[]>([])
const mergedParticleOptions: Required<ParticleOptions> = {
...defaultParticleOptions,
...particleOptions
}
useEffect(() => {
if (canvas) {
const renderer = new CanvasRenderer(canvas)
const simulator = new Simulator(renderer)
simulatorRef.current = simulator
simulator.start()
return () => simulator.stop()
}
}, [canvas])
useEffect(() => {
if (canvas) {
const canvasDimensions = {
width: canvas.width,
height: canvas.height
}
const death = universe?.die()
const setUp = createImageUniverse({
url: src,
maxParticles,
particleOptions: mergedParticleOptions,
scale,
canvasDimensions,
creationTimingFn,
creationDuration,
deathTimingFn,
deathDuration,
onUniverseStateChange
})
onImageStateChange?.(ImageState.Loading)
setUp
.then(() => {
onImageStateChange?.(ImageState.Loaded)
})
.catch(() => {
onImageStateChange?.(ImageState.Error)
})
Promise.all<ImageUniverseSetupResult, void>([setUp, death])
.then(([{universe, pixelManagers}]) => {
setPixelManagers(pixelManagers)
universe.addParticleForce(forces.friction)
simulatorRef.current?.setUniverse(universe)
setUniverse(universe)
})
.catch(() => {
// Eat it here, let the consumer handle it via onImageStateChange
})
}
}, [canvas, src])
useEffect(() => {
universe?.setOnStateChange(onUniverseStateChange)
}, [universe, onUniverseStateChange])
const updateScale = useCallback(throttle((scale: number) => {
pixelManagers.forEach((pixelManager) => {
pixelManager.setScale(scale)
})
}, 50), [pixelManagers])
const updateWidth = useCallback(throttle((width: number) => {
pixelManagers.forEach((pixelManager) => {
pixelManager.setCanvasWidth(width)
})
}, 50), [pixelManagers])
const updateHeight = useCallback(throttle((height: number) => {
pixelManagers.forEach((pixelManager) => {
pixelManager.setCanvasHeight(height)
})
}, 50), [pixelManagers])
useEffect(() => {
updateScale(scale)
}, [scale, updateScale])
useEffect(() => {
updateWidth(width)
}, [width, updateWidth])
useEffect(() => {
updateHeight(height)
}, [height, updateHeight])
useEffect(() => {
const entropyForce = forces.entropy(entropy)
universe?.addParticleForce(entropyForce)
entropyForceRef.current = entropyForce
return () => {
universe?.removeParticleForce(entropyForce)
}
}, [entropy, canvas, universe])
const [mouseMoveParticleForce, setMouseMoveParticleForce] = useTransientParticleForce({universe, duration: mouseMoveForceDuration})
const [touchMoveParticleForce, setTouchMoveParticleForce] = useTransientParticleForce({universe, duration: touchMoveForceDuration})
const [mouseDownParticleForce, setMouseDownParticleForce] = useTransientParticleForce({universe, duration: mouseDownForceDuration})
const handleMouseMove = (e) => {
if (mouseMoveForce) {
const position = getMousePosition(e)
setMouseMoveParticleForce(() => mouseMoveForce(position.x, position.y))
}
otherProps.onMouseMove?.(e)
}
const handleTouchMove = (e) => {
if (touchMoveForce) {
const position = getTouchPosition(e)
setTouchMoveParticleForce(() => touchMoveForce(position.x, position.y))
}
otherProps.onTouchMove?.(e)
}
const handleMouseDown = (e) => {
if (mouseDownForce) {
const position = getMousePosition(e)
setMouseDownParticleForce(() => mouseDownForce(position.x, position.y))
}
otherProps.onMouseDown?.(e)
}
return (
<canvas
{...otherProps}
onMouseMove={handleMouseMove}
onTouchMove={handleTouchMove}
onMouseDown={handleMouseDown}
height={height}
width={width}
style={{backgroundColor, touchAction: 'none', ...style}}
ref={(c) => {
if (c?.getContext('2d')) {
setCanvas(c)
}
}}
/>
)
}
export default ParticleImage | the_stack |
import test = require('tape-promise/tape')
import { sandbox, FetchMockSandbox } from 'fetch-mock'
import NodeFetch from 'node-fetch'
import { Readable, PassThrough, ReadableOptions } from 'stream'
import { DriverModel, DriverModelTestMethods } from '../../src/server/driverModel'
import * as utils from '../../src/server/utils'
import * as mockTestDrivers from './testDrivers/mockTestDrivers'
import * as integrationTestDrivers from './testDrivers/integrationTestDrivers'
import { BadPathError, DoesNotExist, ConflictError } from '../../src/server/errors'
import { tryFor } from '../../src/server/utils'
export function addMockFetches(fetchLib: FetchMockSandbox, prefix: any, dataMap: {key: string, data: string}[]) {
dataMap.forEach(item => {
fetchLib.get(`${prefix}${item.key}`, item.data, { overwriteRoutes: true })
})
}
function testDriver(testName: string, mockTest: boolean, dataMap: {key: string, data: string}[], createDriver: (config?: any) => DriverModel) {
test(testName, async (t) => {
const topLevelStorage = `${Date.now()}r${Math.random()*1e6|0}`
const cacheControlOpt = 'no-cache, no-store, must-revalidate'
const driver = createDriver({
pageSize: 3,
cacheControl: cacheControlOpt
})
try {
await driver.ensureInitialized()
const prefix = driver.getReadURLPrefix()
const sampleDataString = 'hello world'
const getSampleData = () => {
const contentBuff = Buffer.from(sampleDataString)
const s = new Readable()
s.push(contentBuff)
s.push(null)
return { stream: s, contentLength: contentBuff.length }
}
const fetch = (mockTest ? sandbox() : NodeFetch) as FetchMockSandbox
try {
const writeArgs : any = { path: '../foo.js'}
await driver.performWrite(writeArgs)
t.fail('Should have thrown')
}
catch (err) {
t.equal(err.message, 'Invalid Path', 'Should throw bad path')
}
const fileSubDir = 'somedir'
// Test binary data content-type
const binFileName = `${fileSubDir}/foo.bin`;
let sampleData = getSampleData();
let writeResponse = await driver.performWrite({
path: binFileName,
storageTopLevel: topLevelStorage,
stream: sampleData.stream,
contentType: 'application/octet-stream',
contentLength: sampleData.contentLength
});
let readUrl = writeResponse.publicURL;
t.ok(readUrl.startsWith(`${prefix}${topLevelStorage}`), `${readUrl} must start with readUrlPrefix ${prefix}${topLevelStorage}`)
if (mockTest) {
addMockFetches(fetch, prefix, dataMap)
}
let resp = await fetch(readUrl)
t.ok(resp.ok, 'fetch should return 2xx OK status code')
let resptxt = await resp.text()
t.equal(resptxt, sampleDataString, `Must get back ${sampleDataString}: got back: ${resptxt}`)
if (!mockTest) {
t.equal(resp.headers.get('content-type'), 'application/octet-stream', 'Read endpoint response should contain correct content-type')
t.equal(resp.headers.get('etag'), writeResponse.etag,
'Read endpoint should contain correct etag')
t.equal(resp.headers.get('cache-control'), cacheControlOpt, 'cacheControl not respected in response headers')
}
let files = await driver.listFiles({pathPrefix: topLevelStorage})
t.equal(files.entries.length, 1, 'Should return one file')
t.equal(files.entries[0], binFileName, `Should be ${binFileName}!`)
t.ok(!files.page, 'list files for 1 result should not have returned a page')
// Test a text content-type that has implicit charset set
const txtFileName = `${fileSubDir}/foo_text.txt`;
sampleData = getSampleData();
writeResponse = await driver.performWrite(
{ path: txtFileName,
storageTopLevel: topLevelStorage,
stream: sampleData.stream,
contentType: 'text/plain; charset=utf-8',
contentLength: sampleData.contentLength,
ifNoneMatch: '*' })
readUrl = writeResponse.publicURL;
t.ok(readUrl.startsWith(`${prefix}${topLevelStorage}`), `${readUrl} must start with readUrlPrefix ${prefix}${topLevelStorage}`)
if (mockTest) {
addMockFetches(fetch, prefix, dataMap)
}
// if-match & if-none-match tests
if (!mockTest && driver.supportsETagMatching) {
try {
sampleData = getSampleData();
await driver.performWrite({
path: txtFileName,
storageTopLevel: topLevelStorage,
stream: sampleData.stream,
contentType: 'text/plain; charset=utf-8',
contentLength: sampleData.contentLength,
ifNoneMatch: '*'
})
} catch(err) {
if (err.name === 'PreconditionFailedError') {
t.ok(err, 'Should fail to write new file if file already exists')
} else {
t.error('Should throw PreconditionFailedError');
}
}
try {
sampleData = getSampleData();
await driver.performWrite({
path: txtFileName,
storageTopLevel: topLevelStorage,
stream: sampleData.stream,
contentType: 'text/plain; charset=utf-8',
contentLength: sampleData.contentLength,
ifMatch: writeResponse.etag
})
} catch(err) {
t.error(err, 'Should perform write with correct etag')
}
try {
sampleData = getSampleData();
await driver.performWrite({
path: txtFileName,
storageTopLevel: topLevelStorage,
stream: sampleData.stream,
contentType: 'text/plain; charset=utf-8',
contentLength: sampleData.contentLength,
ifMatch: 'bad-etag'
})
} catch(err) {
t.ok(err, 'Should fail to write with bad etag')
}
}
resp = await fetch(readUrl)
t.ok(resp.ok, 'fetch should return 2xx OK status code')
resptxt = await resp.text()
t.equal(resptxt, sampleDataString, `Must get back ${sampleDataString}: got back: ${resptxt}`)
if (!mockTest) {
t.equal(resp.headers.get('content-type'), 'text/plain; charset=utf-8', 'Read-end point response should contain correct content-type')
}
files = await driver.listFiles({pathPrefix: topLevelStorage})
t.equal(files.entries.length, 2, 'Should return two files')
t.ok(files.entries.includes(txtFileName), `Should include ${txtFileName}`)
files = await driver.listFiles({pathPrefix: `${Date.now()}r${Math.random()*1e6|0}`})
t.equal(files.entries.length, 0, 'List files for empty directory should return zero entries')
files = await driver.listFiles({pathPrefix: `${topLevelStorage}/${txtFileName}`})
t.equal(files.entries.length, 1, 'List files on a file rather than directory should return a single entry')
t.equal(files.entries[0], '', 'List files on a file rather than directory should return a single empty entry')
t.strictEqual(files.page, null, 'List files page result should be null')
try {
await driver.performDelete({path: txtFileName, storageTopLevel: topLevelStorage})
t.pass('Should performDelete on an existing file')
files = await driver.listFiles({pathPrefix: topLevelStorage})
t.equal(files.entries.length, 1, 'Should return single file after one was deleted')
t.ok(!files.entries.includes(txtFileName), `Should not have listed deleted file ${txtFileName}`)
} catch (error) {
t.error(error, 'Should performDelete on an existing file')
}
try {
await driver.performDelete({path: txtFileName, storageTopLevel: topLevelStorage})
t.fail('Should fail to performDelete on non-existent file')
} catch (error) {
t.pass('Should fail to performDelete on non-existent file')
if (!(error instanceof DoesNotExist)) {
t.equal(error.constructor.name, 'DoesNotExist', 'Should throw DoesNotExist trying to performDelete on non-existent file')
}
}
try {
await driver.performDelete({path: fileSubDir, storageTopLevel: topLevelStorage})
t.fail('Should fail to performDelete on a directory')
} catch (error) {
t.pass('Should fail to performDelete on a directory')
if (!(error instanceof DoesNotExist)) {
t.equal(error.constructor.name, 'DoesNotExist', 'Should throw DoesNotExist trying to performDelete on directory')
}
}
try {
await driver.performDelete({path: '../foo.js', storageTopLevel: topLevelStorage})
t.fail('Should have thrown deleting file with invalid path')
}
catch (error) {
t.pass('Should fail to performDelete on invalid path')
if (!(error instanceof BadPathError)) {
t.equal(error.constructor.name, 'BadPathError', 'Should throw BadPathError trying to performDelete on directory')
}
}
if (!mockTest) {
// test file read
try {
const readTestFile = 'read_test_file.txt'
const stream = new PassThrough()
stream.end('Hello read test!')
const dateNow1 = Math.round(Date.now() / 1000)
const writeResult = await driver.performWrite({
path: readTestFile,
storageTopLevel: topLevelStorage,
stream: stream,
contentType: 'text/plain; charset=utf-8',
contentLength: 100
})
const readResult = await driver.performRead({
path: readTestFile,
storageTopLevel: topLevelStorage
})
const dataBuffer = await utils.readStream(readResult.data)
const dataStr = dataBuffer.toString('utf8')
t.equal(dataStr, 'Hello read test!', 'File read should return data matching the write')
t.equal(readResult.exists, true, 'File stat should return exists after write')
t.equal(readResult.contentLength, 16, 'File stat should have correct content length')
t.equal(readResult.contentType, "text/plain; charset=utf-8", 'File stat should have correct content type')
t.equal(readResult.etag, writeResult.etag, 'File read should return same etag as write result')
const dateDiff = Math.abs(readResult.lastModifiedDate - dateNow1)
t.equal(dateDiff < 10, true, `File stat last modified date is not within range, diff: ${dateDiff} -- ${readResult.lastModifiedDate} vs ${dateNow1}`)
const fetchResult = await fetch(writeResult.publicURL)
t.equal(fetchResult.status, 200, 'Read endpoint HEAD fetch should return 200 OK status code')
const fetchStr = await fetchResult.text()
t.equal(fetchStr, 'Hello read test!', 'Read endpoint GET should return data matching the write')
t.equal(fetchResult.headers.get('content-length'), '16', 'Read endpoint GET should have correct content length header')
t.equal(fetchResult.headers.get('content-type'), 'text/plain; charset=utf-8', 'Read endpoint GET should have correct content type header')
t.equal(fetchResult.headers.get('etag'), readResult.etag, 'Read endpoint GET should return same etag as read result')
const lastModifiedHeader = new Date(fetchResult.headers.get('last-modified')).getTime()
const fetchDateDiff = Math.abs(lastModifiedHeader - dateNow1)
t.equal(dateDiff < 10, true, `Read endpoint HEAD last-modified header is not within range, diff: ${fetchDateDiff} -- ${lastModifiedHeader} vs ${dateNow1}`)
} catch (error) {
t.error(error, 'Error performing file read test')
}
// test file read on non-existent file
try {
const nonExistentFile = 'read_none.txt'
const statResult = await driver.performRead({
path: nonExistentFile,
storageTopLevel: topLevelStorage
})
t.equal(statResult.exists, false, 'File read should throw not exist')
} catch (error) {
t.pass('Should fail to performRead on non-existent file')
if (!(error instanceof DoesNotExist)) {
t.equal(error.constructor.name, 'DoesNotExist', 'Should throw DoesNotExist trying to performRead on non-existent file')
}
}
// test file read on invalid path
try {
await driver.performRead({path: '../foo.js', storageTopLevel: topLevelStorage})
t.fail('Should have thrown performing file read with invalid path')
}
catch (error) {
t.pass('Should fail to performStat on invalid path')
if (!(error instanceof BadPathError)) {
t.equal(error.constructor.name, 'BadPathError', 'Should throw BadPathError trying to performRead on directory')
}
}
// test file read on subdirectory
try {
const result = await driver.performRead({path: fileSubDir, storageTopLevel: topLevelStorage})
t.equal(result.exists, false, 'performRead on a directory should return not exists')
} catch (error) {
t.pass('Should fail to performRead on directory')
if (!(error instanceof DoesNotExist)) {
t.equal(error.constructor.name, 'DoesNotExist', 'Should throw DoesNotExist trying to performRead on directory')
}
}
// test file stat on listFiles
try {
const statTestFile = 'list_stat_test.txt'
const stream1 = new PassThrough()
stream1.end('abc sample content 1', 'utf8')
const dateNow1 = Math.round(Date.now() / 1000)
const writeResult = await driver.performWrite({
path: statTestFile,
storageTopLevel: topLevelStorage,
stream: stream1,
contentType: 'text/plain; charset=utf-8',
contentLength: 100
})
const listStatResult = await driver.listFilesStat({
pathPrefix: topLevelStorage
})
const statResult = listStatResult.entries.find(e => e.name.includes(statTestFile))
t.equal(statResult.exists, true, 'File stat should return exists after write')
t.equal(statResult.contentLength, 20, 'File stat should have correct content length')
t.equal(statResult.etag, writeResult.etag, 'File read should return same etag as write file result')
const dateDiff = Math.abs(statResult.lastModifiedDate - dateNow1)
t.equal(dateDiff < 10, true, `File stat last modified date is not within range, diff: ${dateDiff} -- ${statResult.lastModifiedDate} vs ${dateNow1}`)
const fetchResult = await fetch(writeResult.publicURL, { method: 'HEAD' })
t.equal(fetchResult.status, 200, 'Read endpoint HEAD fetch should return 200 OK status code')
t.equal(fetchResult.headers.get('content-length'), '20', 'Read endpoint HEAD should have correct content length')
t.equal(fetchResult.headers.get('etag'), statResult.etag, 'Read endpoint HEAD should return same etag as list files stat result')
const lastModifiedHeader = new Date(fetchResult.headers.get('last-modified')).getTime()
const fetchDateDiff = Math.abs(statResult.lastModifiedDate - dateNow1)
t.equal(dateDiff < 10, true, `Read endpoint HEAD last-modified header is not within range, diff: ${fetchDateDiff} -- ${lastModifiedHeader} vs ${dateNow1}`)
} catch (error) {
t.error(error, 'File stat on list files error')
}
// test file stat
try {
const statTestFile = 'stat_test.txt'
const stream1 = new PassThrough()
stream1.end('abc sample content 1', 'utf8')
const dateNow1 = Math.round(Date.now() / 1000)
const writeResult = await driver.performWrite({
path: statTestFile,
storageTopLevel: topLevelStorage,
stream: stream1,
contentType: 'text/plain; charset=utf-8',
contentLength: 100
})
const statResult = await driver.performStat({
path: statTestFile,
storageTopLevel: topLevelStorage
})
t.equal(statResult.exists, true, 'File stat should return exists after write')
t.equal(statResult.contentLength, 20, 'File stat should have correct content length')
t.equal(statResult.contentType, "text/plain; charset=utf-8", 'File stat should have correct content type')
t.equal(statResult.etag, writeResult.etag, 'File stat should return same etag as write file result')
const dateDiff = Math.abs(statResult.lastModifiedDate - dateNow1)
t.equal(dateDiff < 10, true, `File stat last modified date is not within range, diff: ${dateDiff} -- ${statResult.lastModifiedDate} vs ${dateNow1}`)
const fetchResult = await fetch(writeResult.publicURL, { method: 'HEAD' })
t.equal(fetchResult.status, 200, 'Read endpoint HEAD fetch should return 200 OK status code')
t.equal(fetchResult.headers.get('content-length'), '20', 'Read endpoint HEAD should have correct content length')
t.equal(fetchResult.headers.get('etag'), statResult.etag, 'Read endpoint HEAD should return same etag as stat file result')
const lastModifiedHeader = new Date(fetchResult.headers.get('last-modified')).getTime()
const fetchDateDiff = Math.abs(statResult.lastModifiedDate - dateNow1)
t.equal(dateDiff < 10, true, `Read endpoint HEAD last-modified header is not within range, diff: ${fetchDateDiff} -- ${lastModifiedHeader} vs ${dateNow1}`)
} catch (error) {
t.error(error, 'File stat error')
}
// test file stat on non-existent file
try {
const nonExistentFile = 'stat_none.txt'
const statResult = await driver.performStat({
path: nonExistentFile,
storageTopLevel: topLevelStorage
})
t.equal(statResult.exists, false, 'File stat should return not exist')
} catch (error) {
t.error(error, 'File stat non-exists error')
}
// test file stat on invalid path
try {
await driver.performStat({path: '../foo.js', storageTopLevel: topLevelStorage})
t.fail('Should have thrown performing file stat with invalid path')
}
catch (error) {
t.pass('Should fail to performStat on invalid path')
if (!(error instanceof BadPathError)) {
t.equal(error.constructor.name, 'BadPathError', 'Should throw BadPathError trying to performStat on directory')
}
}
// test file stat on subdirectory
try {
const result = await driver.performStat({path: fileSubDir, storageTopLevel: topLevelStorage})
t.equal(result.exists, false, 'performStat on a directory should return not exists')
} catch (error) {
t.error(error, 'File stat directory error')
}
sampleData = getSampleData();
const bogusContentType = 'x'.repeat(3000)
try {
await driver.performWrite(
{ path: 'bogusContentTypeFile',
storageTopLevel: topLevelStorage,
stream: sampleData.stream,
contentType: bogusContentType,
contentLength: sampleData.contentLength })
t.fail('Extremely large content-type headers should fail to write')
} catch (error) {
t.pass('Extremely large content-type headers should fail to write')
}
// test file write without content-length
const zeroByteTestFile = 'zero_bytes.txt'
const stream = new PassThrough()
stream.end(Buffer.alloc(0));
await driver.performWrite({
path: zeroByteTestFile,
storageTopLevel: topLevelStorage,
stream: stream,
contentType: 'text/plain; charset=utf-8',
contentLength: undefined
})
// test zero-byte file read result
const readResult = await driver.performRead({
path: zeroByteTestFile,
storageTopLevel: topLevelStorage
})
t.equal(readResult.contentLength, 0, 'Zero bytes file write should result in read content-length of 0');
const dataBuffer = await utils.readStream(readResult.data)
t.equal(dataBuffer.length, 0, 'Zero bytes file write should result in read of zero bytes');
// test zero-byte file stat result
const statResult = await driver.performStat({
path: zeroByteTestFile,
storageTopLevel: topLevelStorage
})
t.equal(statResult.contentLength, 0, 'Zero bytes file write should result in stat result content-length of 0');
// test zero-byte file list stat result
const statFilesResult = await driver.listFilesStat({
pathPrefix: topLevelStorage,
pageSize: 1000
})
const statFile = statFilesResult.entries.find(f => f.name.includes(zeroByteTestFile))
t.equal(statFile.contentLength, 0, 'Zero bytes file write should result in list file stat content-length 0');
}
try {
const invalidFileName = `../../your_password`;
let sampleData = getSampleData();
await driver.performWrite({
path: invalidFileName,
storageTopLevel: topLevelStorage,
stream: sampleData.stream,
contentType: 'application/octet-stream',
contentLength: sampleData.contentLength
});
t.fail('File write with a filename containing path traversal should have been rejected')
} catch (error) {
t.pass('File write with a filename containing path traversal should have been rejected')
}
if (!mockTest) {
const pageTestDir = 'page_test_dir'
for (var i = 0; i < 5; i++) {
const binFileName = `${pageTestDir}/foo_${i}.bin`;
let sampleData = getSampleData();
await driver.performWrite({
path: binFileName,
storageTopLevel: topLevelStorage,
stream: sampleData.stream,
contentType: 'application/octet-stream',
contentLength: sampleData.contentLength
});
}
const pagedFiles = await driver.listFiles({pathPrefix: `${topLevelStorage}/${pageTestDir}`})
t.equal(pagedFiles.entries.length, 3, 'List files with no pagination and maxPage size specified should have returned 3 entries')
const remainingFiles = await driver.listFiles({pathPrefix: `${topLevelStorage}/${pageTestDir}`, page: pagedFiles.page})
t.equal(remainingFiles.entries.length, 2, 'List files with pagination should have returned 2 remaining entries')
try {
const bogusPageResult = await driver.listFiles({pathPrefix: `${topLevelStorage}/${pageTestDir}`, page: "bogus page data"})
if (bogusPageResult.entries.length > 0) {
t.fail('List files with invalid page data should fail or return no results')
}
t.pass('List files with invalid page data should fail or return no results')
} catch (error) {
t.pass('List files with invalid page data should have failed')
}
// test file renames
try {
const renameTestFile1a = 'renamable1a.txt'
const stream1 = new PassThrough()
stream1.end('abc sample content 1', 'utf8')
await driver.performWrite({
path: renameTestFile1a,
storageTopLevel: topLevelStorage,
stream: stream1,
contentType: 'text/plain; charset=utf-8',
contentLength: 100
});
const dateNow1 = Math.round(Date.now() / 1000)
const renameTestFile2b = 'renamable2b.txt'
await driver.performRename({
path: renameTestFile1a,
storageTopLevel: topLevelStorage,
newPath: renameTestFile2b
})
// test that the renamed file has the properties of the original file
const renamedFileRead = await driver.performRead({
path: renameTestFile2b,
storageTopLevel: topLevelStorage
})
const renamedFileContent = (await utils.readStream(renamedFileRead.data)).toString('utf8')
t.equal(renamedFileContent, 'abc sample content 1')
t.equal(renamedFileRead.exists, true, 'File stat should return exists after write')
t.equal(renamedFileRead.contentLength, 20, 'File stat should have correct content length')
t.equal(renamedFileRead.contentType, "text/plain; charset=utf-8", 'File stat should have correct content type')
const dateDiff = Math.abs(renamedFileRead.lastModifiedDate - dateNow1)
t.equal(dateDiff < 10, true, `File stat last modified date is not within range, diff: ${dateDiff} -- ${renamedFileRead.lastModifiedDate} vs ${dateNow1}`)
// test that the original file is reported as deleted
const movedFileStat = await driver.performStat({path: renameTestFile1a, storageTopLevel: topLevelStorage})
t.equal(movedFileStat.exists, false, 'Renamed file original path should report as non-existent')
} catch (error) {
t.error(error, `File rename error`)
}
// test invalid file rename
try {
await driver.performRename({
path: 'does-not-exist-rename.txt',
storageTopLevel: topLevelStorage,
newPath: 'new-location.txt'
})
t.fail('File rename for non-existent file should have thrown')
} catch(error) {
if (error instanceof DoesNotExist) {
t.pass('Rename of non-existent file resulted in DoesNotExist')
} else {
t.error(error, 'Unexpected error during rename of non-existent file')
}
}
// test file renames with invalid original path
try {
await driver.performRename({
path: '../foo.js',
storageTopLevel: topLevelStorage,
newPath: 'new-location.txt'
})
t.fail('Should have thrown performing file rename with invalid original path')
}
catch (error) {
t.pass('Should fail to performRename on invalid original path')
if (!(error instanceof BadPathError)) {
t.equal(error.constructor.name, 'BadPathError', 'Should throw BadPathError trying to performRename on invalid original path')
}
}
// test file renames with invalid target path
try {
await driver.performRename({
path: 'some-file.txt',
storageTopLevel: topLevelStorage,
newPath: '../foo.js'
})
t.fail('Should have thrown performing file rename with invalid new path')
}
catch (error) {
t.pass('Should fail to performRename on invalid new path')
if (!(error instanceof BadPathError)) {
t.equal(error.constructor.name, 'BadPathError', 'Should throw BadPathError trying to performRename on invalid new path')
}
}
// test file renames with subdirectories
try {
await driver.performRename({
path: fileSubDir,
storageTopLevel: topLevelStorage,
newPath: 'some-file-from-dir.txt'
})
t.fail('Should have thrown performing file rename with sub-directory as original path')
}
catch (error) {
t.pass('Should fail to performRename on sub-directory as original path')
if (!(error instanceof DoesNotExist)) {
t.equal(error.constructor.name, 'DoesNotExist', 'Should throw DoesNotExist trying to performRename on sub-directory as new path')
}
}
// test concurrent writes to same file
try {
const concurrentTestFile = 'concurrent_file_test'
const stream1 = new PassThrough()
stream1.write('abc sample content 1', 'utf8')
const writeRequest1 = driver.performWrite({
path: concurrentTestFile,
storageTopLevel: topLevelStorage,
stream: stream1,
contentType: 'text/plain; charset=utf-8',
contentLength: stream1.readableLength
})
const stream2 = new PassThrough()
stream2.write('xyz sample content 2', 'utf8')
await utils.timeout(100)
const writeRequest2 = driver.performWrite({
path: concurrentTestFile,
storageTopLevel: topLevelStorage,
stream: stream2,
contentType: 'text/plain; charset=utf-8',
contentLength: stream1.readableLength
})
const writePromises = Promise.all([
writeRequest1.catch(() => {
// ignore
}),
writeRequest2.catch(() => {
// ignore
})
])
await utils.timeout(100)
stream1.end()
await utils.timeout(100)
stream2.end()
await writePromises
const [ writeResponse ] = await Promise.all([writeRequest1, writeRequest2])
const readEndpoint = writeResponse.publicURL
resp = await fetch(readEndpoint)
resptxt = await resp.text()
if (resptxt === 'xyz sample content 2' || resptxt === 'abc sample content 1') {
t.ok(resptxt, 'Concurrent writes resulted in conflict resolution at the storage provider')
} else {
t.fail(`Concurrent writes resulted in mangled data: ${resptxt}`)
}
} catch (error) {
if (error instanceof ConflictError) {
t.pass('Concurrent writes resulted in ConflictError')
} else {
t.error(error, 'Unexpected error during concurrent writes')
}
}
try {
const brokenUploadStream = new BrokenReadableStream({autoDestroy: true})
await driver.performWrite({
path: 'broken_upload_stream_test',
storageTopLevel: topLevelStorage,
stream: brokenUploadStream,
contentType: 'application/octet-stream',
contentLength: 100
});
t.fail('Perform write with broken upload stream should have failed')
} catch (error) {
t.pass('Perform write with broken upload stream should have failed')
}
}
if (mockTest) {
fetch.restore()
}
}
finally {
await driver.dispose();
}
});
}
function testDriverBucketCreation(driverName: string, createDriver: (config?: Object) => DriverModelTestMethods) {
test(`bucket creation for driver: ${driverName}`, async (t) => {
const topLevelStorage = `test-buckets-creation${Date.now()}r${Math.random()*1e6|0}`
const driver = createDriver({ bucket: topLevelStorage })
try {
await driver.ensureInitialized()
t.pass('Successfully initialized driver with creation of a new bucket')
} catch (error) {
t.fail(`Could not initialize driver with creation of a new bucket: ${error}`)
} finally {
try {
await tryFor(() => driver.deleteEmptyBucket(), 100, 1500)
} catch (error) {
t.fail(`Error trying to cleanup bucket: ${error}`)
}
await driver.dispose()
}
})
}
/**
* Readable stream that simulates an interrupted http upload/POST request.
* Outputs some data then errors unexpectedly .
*/
class BrokenReadableStream extends Readable {
readCount: number
sampleData: Buffer
constructor(options?: ReadableOptions) {
super(options)
this.readCount = 0
this.sampleData = Buffer.from('hello world sample data')
}
_read(size: number): void {
if (this.readCount === 0) {
super.push(this.sampleData)
} else if (this.readCount === 1) {
super.emit('error', new Error('example stream read failure'))
super.emit('close')
}
this.readCount++
}
}
function performDriverMockTests() {
for (const name in mockTestDrivers.availableMockedDrivers) {
const testName = `mock test for driver: ${name}`
const mockTest = true
const { driverClass, dataMap, config } = mockTestDrivers.availableMockedDrivers[name]();
testDriver(testName, mockTest, dataMap, testConfig => new driverClass({...config, ...testConfig}))
}
}
function performDriverIntegrationTests() {
for (const name in integrationTestDrivers.availableDrivers) {
const driverInfo = integrationTestDrivers.availableDrivers[name];
const testName = `integration test for driver: ${name}`
const mockTest = false
testDriver(testName, mockTest, [], testConfig => driverInfo.create(testConfig))
}
}
function performDriverBucketCreationTests() {
// Test driver initialization that require the creation of a new bucket,
// only on configured driver that implement the `deleteEmptyBucket` method
// so as not to exceed cloud provider max bucket/container limits.
for (const name in integrationTestDrivers.availableDrivers) {
const driverInfo = integrationTestDrivers.availableDrivers[name];
const classPrototype: any = driverInfo.class.prototype
if (classPrototype.deleteEmptyBucket) {
testDriverBucketCreation(name, testConfig => <any>driverInfo.create(testConfig))
}
}
}
export function testDrivers() {
performDriverMockTests()
performDriverIntegrationTests()
performDriverBucketCreationTests()
} | the_stack |
if (!SVGPathElement.prototype.getPathData || !SVGPathElement.prototype.setPathData) {
(function () {
var commandsMap = {
"Z": "Z", "M": "M", "L": "L", "C": "C", "Q": "Q", "A": "A", "H": "H", "V": "V", "S": "S", "T": "T",
"z": "Z", "m": "m", "l": "l", "c": "c", "q": "q", "a": "a", "h": "h", "v": "v", "s": "s", "t": "t"
};
var Source = function (string) {
//@ts-ignore
this._string = string;
//@ts-ignore
this._currentIndex = 0;
//@ts-ignore
this._endIndex = this._string.length;
//@ts-ignore
this._prevCommand = null;
//@ts-ignore
this._skipOptionalSpaces();
};
Source.prototype = {
parseSegment: function () {
var char = this._string[this._currentIndex];
var command = commandsMap[char] ? commandsMap[char] : null;
if (command === null) {
// Possibly an implicit command. Not allowed if this is the first command.
if (this._prevCommand === null) {
return null;
}
// Check for remaining coordinates in the current command.
if (
(char === "+" || char === "-" || char === "." || (char >= "0" && char <= "9")) && this._prevCommand !== "Z"
) {
if (this._prevCommand === "M") {
command = "L";
}
else if (this._prevCommand === "m") {
command = "l";
}
else {
command = this._prevCommand;
}
}
else {
command = null;
}
if (command === null) {
return null;
}
}
else {
this._currentIndex += 1;
}
this._prevCommand = command;
var values = null;
var cmd = command.toUpperCase();
if (cmd === "H" || cmd === "V") {
values = [this._parseNumber()];
}
else if (cmd === "M" || cmd === "L" || cmd === "T") {
values = [this._parseNumber(), this._parseNumber()];
}
else if (cmd === "S" || cmd === "Q") {
values = [this._parseNumber(), this._parseNumber(), this._parseNumber(), this._parseNumber()];
}
else if (cmd === "C") {
values = [
this._parseNumber(),
this._parseNumber(),
this._parseNumber(),
this._parseNumber(),
this._parseNumber(),
this._parseNumber()
];
}
else if (cmd === "A") {
values = [
this._parseNumber(),
this._parseNumber(),
this._parseNumber(),
this._parseArcFlag(),
this._parseArcFlag(),
this._parseNumber(),
this._parseNumber()
];
}
else if (cmd === "Z") {
this._skipOptionalSpaces();
values = [];
}
if (values === null || values.indexOf(null) >= 0) {
// Unknown command or known command with invalid values
return null;
}
else {
return { type: command, values: values };
}
},
hasMoreData: function () {
return this._currentIndex < this._endIndex;
},
peekSegmentType: function () {
var char = this._string[this._currentIndex];
return commandsMap[char] ? commandsMap[char] : null;
},
initialCommandIsMoveTo: function () {
// If the path is empty it is still valid, so return true.
if (!this.hasMoreData()) {
return true;
}
var command = this.peekSegmentType();
// Path must start with moveTo.
return command === "M" || command === "m";
},
_isCurrentSpace: function () {
var char = this._string[this._currentIndex];
return char <= " " && (char === " " || char === "\n" || char === "\t" || char === "\r" || char === "\f");
},
_skipOptionalSpaces: function () {
while (this._currentIndex < this._endIndex && this._isCurrentSpace()) {
this._currentIndex += 1;
}
return this._currentIndex < this._endIndex;
},
_skipOptionalSpacesOrDelimiter: function () {
if (
this._currentIndex < this._endIndex &&
!this._isCurrentSpace() &&
this._string[this._currentIndex] !== ","
) {
return false;
}
if (this._skipOptionalSpaces()) {
if (this._currentIndex < this._endIndex && this._string[this._currentIndex] === ",") {
this._currentIndex += 1;
this._skipOptionalSpaces();
}
}
return this._currentIndex < this._endIndex;
},
// Parse a number from an SVG path. This very closely follows genericParseNumber(...) from
// Source/core/svg/SVGParserUtilities.cpp.
// Spec: http://www.w3.org/TR/SVG11/single-page.html#paths-PathDataBNF
_parseNumber: function () {
var exponent = 0;
var integer = 0;
var frac = 1;
var decimal = 0;
var sign = 1;
var expsign = 1;
var startIndex = this._currentIndex;
this._skipOptionalSpaces();
// Read the sign.
if (this._currentIndex < this._endIndex && this._string[this._currentIndex] === "+") {
this._currentIndex += 1;
}
else if (this._currentIndex < this._endIndex && this._string[this._currentIndex] === "-") {
this._currentIndex += 1;
sign = -1;
}
if (
this._currentIndex === this._endIndex ||
(
(this._string[this._currentIndex] < "0" || this._string[this._currentIndex] > "9") &&
this._string[this._currentIndex] !== "."
)
) {
// The first character of a number must be one of [0-9+-.].
return null;
}
// Read the integer part, build right-to-left.
var startIntPartIndex = this._currentIndex;
while (
this._currentIndex < this._endIndex &&
this._string[this._currentIndex] >= "0" &&
this._string[this._currentIndex] <= "9"
) {
this._currentIndex += 1; // Advance to first non-digit.
}
if (this._currentIndex !== startIntPartIndex) {
var scanIntPartIndex = this._currentIndex - 1;
var multiplier = 1;
while (scanIntPartIndex >= startIntPartIndex) {
integer += multiplier * (this._string[scanIntPartIndex] - <any>"0");
scanIntPartIndex -= 1;
multiplier *= 10;
}
}
// Read the decimals.
if (this._currentIndex < this._endIndex && this._string[this._currentIndex] === ".") {
this._currentIndex += 1;
// There must be a least one digit following the .
if (
this._currentIndex >= this._endIndex ||
this._string[this._currentIndex] < "0" ||
this._string[this._currentIndex] > "9"
) {
return null;
}
while (
this._currentIndex < this._endIndex &&
this._string[this._currentIndex] >= "0" &&
this._string[this._currentIndex] <= "9"
) {
frac *= 10;
decimal += (this._string.charAt(this._currentIndex) - <any>"0") / frac;
this._currentIndex += 1;
}
}
// Read the exponent part.
if (
this._currentIndex !== startIndex &&
this._currentIndex + 1 < this._endIndex &&
(this._string[this._currentIndex] === "e" || this._string[this._currentIndex] === "E") &&
(this._string[this._currentIndex + 1] !== "x" && this._string[this._currentIndex + 1] !== "m")
) {
this._currentIndex += 1;
// Read the sign of the exponent.
if (this._string[this._currentIndex] === "+") {
this._currentIndex += 1;
}
else if (this._string[this._currentIndex] === "-") {
this._currentIndex += 1;
expsign = -1;
}
// There must be an exponent.
if (
this._currentIndex >= this._endIndex ||
this._string[this._currentIndex] < "0" ||
this._string[this._currentIndex] > "9"
) {
return null;
}
while (
this._currentIndex < this._endIndex &&
this._string[this._currentIndex] >= "0" &&
this._string[this._currentIndex] <= "9"
) {
exponent *= 10;
exponent += (this._string[this._currentIndex] - <any>"0");
this._currentIndex += 1;
}
}
var number = integer + decimal;
number *= sign;
if (exponent) {
number *= Math.pow(10, expsign * exponent);
}
if (startIndex === this._currentIndex) {
return null;
}
this._skipOptionalSpacesOrDelimiter();
return number;
},
_parseArcFlag: function () {
if (this._currentIndex >= this._endIndex) {
return null;
}
var flag = null;
var flagChar = this._string[this._currentIndex];
this._currentIndex += 1;
if (flagChar === "0") {
flag = 0;
}
else if (flagChar === "1") {
flag = 1;
}
else {
return null;
}
this._skipOptionalSpacesOrDelimiter();
return flag;
}
};
var parsePathDataString = function (string): PathData[] {
if (!string || string.length === 0) return [];
var source = new Source(string);
var pathData = [];
if (source.initialCommandIsMoveTo()) {
while (source.hasMoreData()) {
var pathSeg = source.parseSegment();
if (pathSeg === null) {
break;
}
else {
pathData.push(pathSeg);
}
}
}
return pathData;
}
// @info
// Get an array of corresponding cubic bezier curve parameters for given arc curve paramters.
var arcToCubicCurves = function (x1, y1, x2, y2, r1, r2, angle, largeArcFlag, sweepFlag, _recursive?) {
var degToRad = function (degrees) {
return (Math.PI * degrees) / 180;
};
var rotate = function (x, y, angleRad) {
var X = x * Math.cos(angleRad) - y * Math.sin(angleRad);
var Y = x * Math.sin(angleRad) + y * Math.cos(angleRad);
return { x: X, y: Y };
};
var angleRad = degToRad(angle);
var params = [];
var f1, f2, cx, cy;
if (_recursive) {
f1 = _recursive[0];
f2 = _recursive[1];
cx = _recursive[2];
cy = _recursive[3];
}
else {
var p1 = rotate(x1, y1, -angleRad);
x1 = p1.x;
y1 = p1.y;
var p2 = rotate(x2, y2, -angleRad);
x2 = p2.x;
y2 = p2.y;
var x = (x1 - x2) / 2;
var y = (y1 - y2) / 2;
var h = (x * x) / (r1 * r1) + (y * y) / (r2 * r2);
if (h > 1) {
h = Math.sqrt(h);
r1 = h * r1;
r2 = h * r2;
}
var sign;
if (largeArcFlag === sweepFlag) {
sign = -1;
}
else {
sign = 1;
}
var r1Pow = r1 * r1;
var r2Pow = r2 * r2;
var left = r1Pow * r2Pow - r1Pow * y * y - r2Pow * x * x;
var right = r1Pow * y * y + r2Pow * x * x;
var k = sign * Math.sqrt(Math.abs(left / right));
cx = k * r1 * y / r2 + (x1 + x2) / 2;
cy = k * -r2 * x / r1 + (y1 + y2) / 2;
f1 = Math.asin(parseFloat(((y1 - cy) / r2).toFixed(9)));
f2 = Math.asin(parseFloat(((y2 - cy) / r2).toFixed(9)));
if (x1 < cx) {
f1 = Math.PI - f1;
}
if (x2 < cx) {
f2 = Math.PI - f2;
}
if (f1 < 0) {
f1 = Math.PI * 2 + f1;
}
if (f2 < 0) {
f2 = Math.PI * 2 + f2;
}
if (sweepFlag && f1 > f2) {
f1 = f1 - Math.PI * 2;
}
if (!sweepFlag && f2 > f1) {
f2 = f2 - Math.PI * 2;
}
}
var df = f2 - f1;
if (Math.abs(df) > (Math.PI * 120 / 180)) {
var f2old = f2;
var x2old = x2;
var y2old = y2;
if (sweepFlag && f2 > f1) {
f2 = f1 + (Math.PI * 120 / 180) * (1);
}
else {
f2 = f1 + (Math.PI * 120 / 180) * (-1);
}
x2 = cx + r1 * Math.cos(f2);
y2 = cy + r2 * Math.sin(f2);
params = arcToCubicCurves(x2, y2, x2old, y2old, r1, r2, angle, 0, sweepFlag, [f2, f2old, cx, cy]);
}
df = f2 - f1;
var c1 = Math.cos(f1);
var s1 = Math.sin(f1);
var c2 = Math.cos(f2);
var s2 = Math.sin(f2);
var t = Math.tan(df / 4);
var hx = 4 / 3 * r1 * t;
var hy = 4 / 3 * r2 * t;
var m1 = [x1, y1];
var m2 = [x1 + hx * s1, y1 - hy * c1];
var m3 = [x2 + hx * s2, y2 - hy * c2];
var m4 = [x2, y2];
m2[0] = 2 * m1[0] - m2[0];
m2[1] = 2 * m1[1] - m2[1];
if (_recursive) {
return [m2, m3, m4].concat(params);
}
else {
params = [m2, m3, m4].concat(params);
var curves = [];
for (var i = 0; i < params.length; i += 3) {
let r1 = rotate(params[i][0], params[i][1], angleRad);
let r2 = rotate(params[i + 1][0], params[i + 1][1], angleRad);
let r3 = rotate(params[i + 2][0], params[i + 2][1], angleRad);
curves.push([r1.x, r1.y, r2.x, r2.y, r3.x, r3.y]);
}
return curves;
}
};
/*var clonePathData = function (pathData) {
return pathData.map(function (seg) {
return { type: seg.type, values: Array.prototype.slice.call(seg.values) }
});
};*/
// @info
// Takes any path data, returns path data that consists only from absolute commands.
var absolutizePathData = function (pathData) {
var absolutizedPathData = [];
var currentX = null;
var currentY = null;
var subpathX = null;
var subpathY = null;
pathData.forEach(function (seg) {
var type = seg.type;
if (type === "M") {
var x = seg.values[0];
var y = seg.values[1];
absolutizedPathData.push({ type: "M", values: [x, y] });
subpathX = x;
subpathY = y;
currentX = x;
currentY = y;
}
else if (type === "m") {
var x = currentX + seg.values[0];
var y = currentY + seg.values[1];
absolutizedPathData.push({ type: "M", values: [x, y] });
subpathX = x;
subpathY = y;
currentX = x;
currentY = y;
}
else if (type === "L") {
var x = seg.values[0];
var y = seg.values[1];
absolutizedPathData.push({ type: "L", values: [x, y] });
currentX = x;
currentY = y;
}
else if (type === "l") {
var x = currentX + seg.values[0];
var y = currentY + seg.values[1];
absolutizedPathData.push({ type: "L", values: [x, y] });
currentX = x;
currentY = y;
}
else if (type === "C") {
var x1 = seg.values[0];
var y1 = seg.values[1];
var x2 = seg.values[2];
var y2 = seg.values[3];
var x = seg.values[4];
var y = seg.values[5];
absolutizedPathData.push({ type: "C", values: [x1, y1, x2, y2, x, y] });
currentX = x;
currentY = y;
}
else if (type === "c") {
var x1 = currentX + seg.values[0];
var y1 = currentY + seg.values[1];
var x2 = currentX + seg.values[2];
var y2 = currentY + seg.values[3];
var x = currentX + seg.values[4];
var y = currentY + seg.values[5];
absolutizedPathData.push({ type: "C", values: [x1, y1, x2, y2, x, y] });
currentX = x;
currentY = y;
}
else if (type === "Q") {
var x1 = seg.values[0];
var y1 = seg.values[1];
var x = seg.values[2];
var y = seg.values[3];
absolutizedPathData.push({ type: "Q", values: [x1, y1, x, y] });
currentX = x;
currentY = y;
}
else if (type === "q") {
var x1 = currentX + seg.values[0];
var y1 = currentY + seg.values[1];
var x = currentX + seg.values[2];
var y = currentY + seg.values[3];
absolutizedPathData.push({ type: "Q", values: [x1, y1, x, y] });
currentX = x;
currentY = y;
}
else if (type === "A") {
var x = seg.values[5];
var y = seg.values[6];
absolutizedPathData.push({
type: "A",
values: [seg.values[0], seg.values[1], seg.values[2], seg.values[3], seg.values[4], x, y]
});
currentX = x;
currentY = y;
}
else if (type === "a") {
var x = currentX + seg.values[5];
var y = currentY + seg.values[6];
absolutizedPathData.push({
type: "A",
values: [seg.values[0], seg.values[1], seg.values[2], seg.values[3], seg.values[4], x, y]
});
currentX = x;
currentY = y;
}
else if (type === "H") {
var x = seg.values[0];
absolutizedPathData.push({ type: "H", values: [x] });
currentX = x;
}
else if (type === "h") {
var x = currentX + seg.values[0];
absolutizedPathData.push({ type: "H", values: [x] });
currentX = x;
}
else if (type === "V") {
var y = seg.values[0];
absolutizedPathData.push({ type: "V", values: [y] });
currentY = y;
}
else if (type === "v") {
var y = currentY + seg.values[0];
absolutizedPathData.push({ type: "V", values: [y] });
currentY = y;
}
else if (type === "S") {
var x2 = seg.values[0];
var y2 = seg.values[1];
var x = seg.values[2];
var y = seg.values[3];
absolutizedPathData.push({ type: "S", values: [x2, y2, x, y] });
currentX = x;
currentY = y;
}
else if (type === "s") {
var x2 = currentX + seg.values[0];
var y2 = currentY + seg.values[1];
var x = currentX + seg.values[2];
var y = currentY + seg.values[3];
absolutizedPathData.push({ type: "S", values: [x2, y2, x, y] });
currentX = x;
currentY = y;
}
else if (type === "T") {
var x = seg.values[0];
var y = seg.values[1]
absolutizedPathData.push({ type: "T", values: [x, y] });
currentX = x;
currentY = y;
}
else if (type === "t") {
var x = currentX + seg.values[0];
var y = currentY + seg.values[1]
absolutizedPathData.push({ type: "T", values: [x, y] });
currentX = x;
currentY = y;
}
else if (type === "Z" || type === "z") {
absolutizedPathData.push({ type: "Z", values: [] });
currentX = subpathX;
currentY = subpathY;
}
});
return absolutizedPathData;
};
// @info
// Takes path data that consists only from absolute commands, returns path data that consists only from
// "M", "L", "C" and "Z" commands.
var reducePathData = function (pathData) {
var reducedPathData = [];
var lastType = null;
var lastControlX = null;
var lastControlY = null;
var currentX = null;
var currentY = null;
var subpathX = null;
var subpathY = null;
pathData.forEach(function (seg) {
if (seg.type === "M") {
var x = seg.values[0];
var y = seg.values[1];
reducedPathData.push({ type: "M", values: [x, y] });
subpathX = x;
subpathY = y;
currentX = x;
currentY = y;
}
else if (seg.type === "C") {
var x1 = seg.values[0];
var y1 = seg.values[1];
var x2 = seg.values[2];
var y2 = seg.values[3];
var x = seg.values[4];
var y = seg.values[5];
reducedPathData.push({ type: "C", values: [x1, y1, x2, y2, x, y] });
lastControlX = x2;
lastControlY = y2;
currentX = x;
currentY = y;
}
else if (seg.type === "L") {
var x = seg.values[0];
var y = seg.values[1];
reducedPathData.push({ type: "L", values: [x, y] });
currentX = x;
currentY = y;
}
else if (seg.type === "H") {
var x = seg.values[0];
reducedPathData.push({ type: "L", values: [x, currentY] });
currentX = x;
}
else if (seg.type === "V") {
var y = seg.values[0];
reducedPathData.push({ type: "L", values: [currentX, y] });
currentY = y;
}
else if (seg.type === "S") {
var x2 = seg.values[0];
var y2 = seg.values[1];
var x = seg.values[2];
var y = seg.values[3];
var cx1, cy1;
if (lastType === "C" || lastType === "S") {
cx1 = currentX + (currentX - lastControlX);
cy1 = currentY + (currentY - lastControlY);
}
else {
cx1 = currentX;
cy1 = currentY;
}
reducedPathData.push({ type: "C", values: [cx1, cy1, x2, y2, x, y] });
lastControlX = x2;
lastControlY = y2;
currentX = x;
currentY = y;
}
else if (seg.type === "T") {
var x = seg.values[0];
var y = seg.values[1];
var x1, y1;
if (lastType === "Q" || lastType === "T") {
x1 = currentX + (currentX - lastControlX);
y1 = currentY + (currentY - lastControlY);
}
else {
x1 = currentX;
y1 = currentY;
}
var cx1 = currentX + 2 * (x1 - currentX) / 3;
var cy1 = currentY + 2 * (y1 - currentY) / 3;
var cx2 = x + 2 * (x1 - x) / 3;
var cy2 = y + 2 * (y1 - y) / 3;
reducedPathData.push({ type: "C", values: [cx1, cy1, cx2, cy2, x, y] });
lastControlX = x1;
lastControlY = y1;
currentX = x;
currentY = y;
}
else if (seg.type === "Q") {
var x1 = seg.values[0];
var y1 = seg.values[1];
var x = seg.values[2];
var y = seg.values[3];
var cx1 = currentX + 2 * (x1 - currentX) / 3;
var cy1 = currentY + 2 * (y1 - currentY) / 3;
var cx2 = x + 2 * (x1 - x) / 3;
var cy2 = y + 2 * (y1 - y) / 3;
reducedPathData.push({ type: "C", values: [cx1, cy1, cx2, cy2, x, y] });
lastControlX = x1;
lastControlY = y1;
currentX = x;
currentY = y;
}
else if (seg.type === "A") {
let r1 = Math.abs(seg.values[0]);
let r2 = Math.abs(seg.values[1]);
var angle = seg.values[2];
var largeArcFlag = seg.values[3];
var sweepFlag = seg.values[4];
var x = seg.values[5];
var y = seg.values[6];
if (r1 === 0 || r2 === 0) {
reducedPathData.push({ type: "C", values: [currentX, currentY, x, y, x, y] });
currentX = x;
currentY = y;
}
else {
if (currentX !== x || currentY !== y) {
var curves = arcToCubicCurves(currentX, currentY, x, y, r1, r2, angle, largeArcFlag, sweepFlag);
curves.forEach(function (curve) {
reducedPathData.push({ type: "C", values: curve });
});
currentX = x;
currentY = y;
}
}
}
else if (seg.type === "Z") {
reducedPathData.push(seg);
currentX = subpathX;
currentY = subpathY;
}
lastType = seg.type;
});
return reducedPathData;
};
SVGPathElement.prototype.getPathData = function (options) {
if (options && options.normalize) {
/*if (this[$cachedNormalizedPathData]) {
return clonePathData(this[$cachedNormalizedPathData]);
}
else */ {
let pathData;
/*if (this[$cachedPathData]) {
pathData = clonePathData(this[$cachedPathData]);
}
else */{
pathData = parsePathDataString(this.getAttribute("d") || "");
//this[$cachedPathData] = clonePathData(pathData);
}
let normalizedPathData = reducePathData(absolutizePathData(pathData));
//this[$cachedNormalizedPathData] = clonePathData(normalizedPathData);
return normalizedPathData;
}
}
else {
/*if (this[$cachedPathData]) {
return clonePathData(this[$cachedPathData]);
}
else*/ {
let pathData = parsePathDataString(this.getAttribute("d") || "");
//this[$cachedPathData] = clonePathData(pathData);
return pathData;
}
}
};
SVGPathElement.prototype.setPathData = function (pathData) {
if (pathData.length === 0) {
this.removeAttribute("d");
}
else {
let d = "";
for (let i = 0, l = pathData.length; i < l; i += 1) {
let seg: any = pathData[i];
if (i > 0) {
d += " ";
}
d += seg.type;
if (seg.values && seg.values.length > 0) {
d += " " + seg.values.join(" ");
}
}
this.setAttribute("d", d);
}
};
SVGRectElement.prototype.getPathData = function (options) {
var x = this.x.baseVal.value;
var y = this.y.baseVal.value;
var width = this.width.baseVal.value;
var height = this.height.baseVal.value;
var rx = this.hasAttribute("rx") ? this.rx.baseVal.value : this.ry.baseVal.value;
var ry = this.hasAttribute("ry") ? this.ry.baseVal.value : this.rx.baseVal.value;
if (rx > width / 2) {
rx = width / 2;
}
if (ry > height / 2) {
ry = height / 2;
}
var pathData: any = [
{ type: "M", values: [x + rx, y] },
{ type: "H", values: [x + width - rx] },
{ type: "A", values: [rx, ry, 0, 0, 1, x + width, y + ry] },
{ type: "V", values: [y + height - ry] },
{ type: "A", values: [rx, ry, 0, 0, 1, x + width - rx, y + height] },
{ type: "H", values: [x + rx] },
{ type: "A", values: [rx, ry, 0, 0, 1, x, y + height - ry] },
{ type: "V", values: [y + ry] },
{ type: "A", values: [rx, ry, 0, 0, 1, x + rx, y] },
{ type: "Z", values: [] }
];
// Get rid of redundant "A" segs when either rx or ry is 0
pathData = pathData.filter(function (s) {
return s.type === "A" && (s.values[0] === 0 || s.values[1] === 0) ? false : true;
});
if (options && options.normalize === true) {
pathData = reducePathData(pathData);
}
return pathData;
};
SVGCircleElement.prototype.getPathData = function (options) {
var cx = this.cx.baseVal.value;
var cy = this.cy.baseVal.value;
var r = this.r.baseVal.value;
var pathData: any = [
{ type: "M", values: [cx + r, cy] },
{ type: "A", values: [r, r, 0, 0, 1, cx, cy + r] },
{ type: "A", values: [r, r, 0, 0, 1, cx - r, cy] },
{ type: "A", values: [r, r, 0, 0, 1, cx, cy - r] },
{ type: "A", values: [r, r, 0, 0, 1, cx + r, cy] },
{ type: "Z", values: [] }
];
if (options && options.normalize === true) {
pathData = reducePathData(pathData);
}
return pathData;
};
SVGEllipseElement.prototype.getPathData = function (options) {
var cx = this.cx.baseVal.value;
var cy = this.cy.baseVal.value;
var rx = this.rx.baseVal.value;
var ry = this.ry.baseVal.value;
var pathData: any = [
{ type: "M", values: [cx + rx, cy] },
{ type: "A", values: [rx, ry, 0, 0, 1, cx, cy + ry] },
{ type: "A", values: [rx, ry, 0, 0, 1, cx - rx, cy] },
{ type: "A", values: [rx, ry, 0, 0, 1, cx, cy - ry] },
{ type: "A", values: [rx, ry, 0, 0, 1, cx + rx, cy] },
{ type: "Z", values: [] }
];
if (options && options.normalize === true) {
pathData = reducePathData(pathData);
}
return pathData;
};
SVGLineElement.prototype.getPathData = function () {
return <any>[
{ type: "M", values: [this.x1.baseVal.value, this.y1.baseVal.value] },
{ type: "L", values: [this.x2.baseVal.value, this.y2.baseVal.value] }
];
};
SVGPolylineElement.prototype.getPathData = function () {
var pathData = [];
for (var i = 0; i < this.points.numberOfItems; i += 1) {
var point = this.points.getItem(i);
pathData.push({
type: (i === 0 ? "M" : "L"),
values: [point.x, point.y]
});
}
return pathData;
};
SVGPolygonElement.prototype.getPathData = function () {
var pathData = [];
for (var i = 0; i < this.points.numberOfItems; i += 1) {
var point = this.points.getItem(i);
pathData.push({
type: (i === 0 ? "M" : "L"),
values: [point.x, point.y]
});
}
pathData.push({
type: "Z",
values: []
});
return pathData;
};
})();
}
export { }
declare type PathDataM = { type: 'M' | 'm', values: [x: number, y: number] }
declare type PathDataL = { type: 'L' | 'l', values: [x: number, y: number] }
declare type PathDataT = { type: 'T' | 't', values: [x: number, y: number] }
declare type PathDataH = { type: 'H' | 'h', values: [x: number] }
declare type PathDataV = { type: 'V' | 'v', values: [y: number] }
declare type PathDataZ = { type: 'Z' | 'z', values?: [] }
declare type PathDataC = { type: 'C' | 'c', values: [x1: number, y1: number, x2: number, y2: number, x: number, y: number] }
declare type PathDataS = { type: 'S' | 's', values: [x2: number, y2: number, x: number, y: number] }
declare type PathDataQ = { type: 'Q' | 'q', values: [x1: number, y1: number, x: number, y: number] }
declare type PathDataA = { type: 'A' | 'a', values: [rx: number, ry: number, ang: number, flag1: 0 | 1, flag2: 0 | 1, x: number, y: number] }
declare type PathData = { type: string } & (PathDataM | PathDataL | PathDataH | PathDataV | PathDataZ | PathDataC | PathDataS | PathDataQ | PathDataT | PathDataA)[];
export function movePathData(path: SVGPathElement, xFactor: number, yFactor: number): string {
let newPathData = "";
let pd = path.getPathData({ normalize: true });
{
for (let p of pd) {
switch (p.type) {
case ('M'):
case ('m'):
case ('L'):
case ('l'):
case ('T'):
case ('t'):
newPathData += p.type + (p.values[0] - xFactor) + " " + (p.values[1] - yFactor);
break;
case ('Z'):
case ('z'):
newPathData += p.type;
break;
case ('C'):
case ('c'):
newPathData += p.type + (p.values[0] - xFactor) + " " + (p.values[1] - yFactor) + " " + (p.values[2] - xFactor) + " " + (p.values[3] - yFactor) + " " + (p.values[4] - xFactor) + " " + (p.values[5] - yFactor);
break;
case ('S'):
case ('s'):
case ('Q'):
case ('q'):
newPathData += p.type + (p.values[0] - xFactor) + " " + (p.values[1] - yFactor) + " " + (p.values[2] - xFactor) + " " + (p.values[3] - yFactor);
break;
case ('A'):
case ('a'):
newPathData += p.type + (p.values[0] - xFactor) + " " + (p.values[1] - yFactor) + " " + p.values[2] + " " + p.values[3] + " " + p.values[4] + " " + (p.values[5] - xFactor) + " " + (p.values[6] - yFactor);
break;
}
}
}
return newPathData;
}
declare global {
interface SVGGraphicsElement {
getPathData(options?: { normalize?: boolean }): PathData[]
isPointInStroke(point: { x: number, y: number })
isPointInFill(point: { x: number, y: number })
}
interface SVGPathElement {
getPathData(options?: { normalize?: boolean }): PathData[]
setPathData(pathData: PathData[])
}
interface SVGRectElement {
getPathData(options?: { normalize?: boolean }): PathData[]
}
interface SVGCircleElement {
getPathData(options?: { normalize?: boolean }): PathData[]
}
interface SVGEllipseElement {
getPathData(options?: { normalize?: boolean }): PathData[]
}
interface SVGLineElement {
getPathData(options?: { normalize?: boolean }): PathData[]
}interface SVGPolylineElement {
getPathData(options?: { normalize?: boolean }): PathData[]
}
interface SVGPolygonElement {
getPathData(options?: { normalize?: boolean }): PathData[]
}
} | the_stack |
import FDBError from './error'
import {
Watch,
NativeTransaction,
Callback,
NativeValue,
Version,
} from './native'
import {
strInc,
strNext,
asBuf
} from './util'
import keySelector, {KeySelector} from './keySelector'
import {eachOption} from './opts'
import {
TransactionOptions,
TransactionOptionCode,
transactionOptionData,
StreamingMode,
MutationType
} from './opts.g'
import Database from './database'
import {
Transformer,
} from './transformer'
import {
UnboundStamp,
packVersionstamp,
packVersionstampPrefixSuffix
} from './versionstamp'
import Subspace, { GetSubspace } from './subspace'
const byteZero = Buffer.alloc(1)
byteZero.writeUInt8(0, 0)
export interface RangeOptionsBatch {
// defaults to Iterator for batch mode, WantAll for getRangeAll.
streamingMode?: StreamingMode,
limit?: number,
reverse?: boolean,
}
export interface RangeOptions extends RangeOptionsBatch {
targetBytes?: number,
}
export type KVList<Key, Value> = {
results: [Key, Value][], // [key, value] pair.
more: boolean,
}
export {Watch}
export type WatchOptions = {
throwAllErrors?: boolean
}
// Polyfill for node < 10.0 to make asyncIterators work (getRange / getRangeBatch).
if ((<any>Symbol).asyncIterator == null) (<any>Symbol).asyncIterator = Symbol.for("Symbol.asyncIterator")
const doNothing = () => {}
type BakeItem<T> = {item: T, transformer: Transformer<T, any>, code: Buffer | null}
// This scope object is shared by the family of transaction objects made with .scope().
interface TxnCtx {
nextCode: number
// If you call setVersionstampedKey / setVersionstampedValue, we pull out
// the versionstamp from the txn and bake it back into the tuple (or
// whatever) after the transaction commits.
toBake: null | BakeItem<any>[]
}
/**
* This class wraps a foundationdb transaction object. All interaction with the
* data in a foundationdb database happens through a transaction. For more
* detail about how to model your queries, see the [transaction chapter of the
* FDB developer
* guide](https://apple.github.io/foundationdb/developer-guide.html?#transaction-basics).
*
* You should never create transactions directly. Instead, open a database and
* call `await db.doTn(async tn => {...})`.
*
* ```javascript
* const db = fdb.open()
* const val = await db.doTn(async tn => {
* // Use the transaction in this block. The transaction will be automatically
* // committed (and potentially retried) after this block returns.
* tn.set('favorite color', 'hotpink')
* return await tn.get('another key')
* })
* ```
*
* ---
*
* This class has 4 template parameters - which is kind of messy. They're used
* to make the class typesafe in the face of key and value transformers. These
* parameters should be automatically inferred, but sometimes you will need to
* specify them explicitly. They are:
*
* @param KeyIn The type for keys passed by the user into functions (eg `get(k:
* KeyIn)`). Defaults to string | Buffer. Change this by scoping the transaction
* with a subspace with a key transformer. Eg
* `txn.at(fdb.root.withKeyEncoding(fdb.tuple)).get([1, 2, 3])`.
* @param KeyOut The type of keys returned by methods which return keys - like
* `getKey(..) => Promise<KeyOut?>`. Unless you have a KV transformer, this will
* be Buffer.
* @param ValIn The type of values passed into transaction functions, like
* `txn.set(key, val: ValIn)`. By default this is string | Buffer. Override this
* by applying a value transformer to your subspace.
* @param ValOut The type of database values returned by functions. Eg,
* `txn.get(...) => Promise<ValOut | undefined>`. Defaults to Buffer, but if you
* apply a value transformer this will change.
*/
export default class Transaction<KeyIn = NativeValue, KeyOut = Buffer, ValIn = NativeValue, ValOut = Buffer> {
/** @internal */ _tn: NativeTransaction
isSnapshot: boolean
subspace: Subspace<KeyIn, KeyOut, ValIn, ValOut>
// Copied out from scope for convenience, since these are so heavily used. Not
// sure if this is a good idea.
private _keyEncoding: Transformer<KeyIn, KeyOut>
private _valueEncoding: Transformer<ValIn, ValOut>
private _ctx: TxnCtx
/**
* NOTE: Do not call this directly. Instead transactions should be created
* via db.doTn(...)
*
* @internal
*/
constructor(tn: NativeTransaction, snapshot: boolean,
subspace: Subspace<KeyIn, KeyOut, ValIn, ValOut>,
// keyEncoding: Transformer<KeyIn, KeyOut>, valueEncoding: Transformer<ValIn, ValOut>,
opts?: TransactionOptions, ctx?: TxnCtx) {
this._tn = tn
this.isSnapshot = snapshot
this.subspace = subspace
this._keyEncoding = subspace._bakedKeyXf
this._valueEncoding = subspace.valueXf
// this._root = root || this
if (opts) eachOption(transactionOptionData, opts, (code, val) => tn.setOption(code, val))
this._ctx = ctx ? ctx : {
nextCode: 0,
toBake: null
}
}
// Internal method to actually run a transaction retry loop. Do not call
// this directly - instead use Database.doTn().
/** @internal */
async _exec<T>(body: (tn: Transaction<KeyIn, KeyOut, ValIn, ValOut>) => Promise<T>, opts?: TransactionOptions): Promise<T> {
// Logic described here:
// https://apple.github.io/foundationdb/api-c.html#c.fdb_transaction_on_error
do {
try {
const result = await body(this)
const stampPromise = (this._ctx.toBake && this._ctx.toBake.length)
? this.getVersionstamp() : null
await this.rawCommit()
if (stampPromise) {
const stamp = await stampPromise.promise
this._ctx.toBake!.forEach(({item, transformer, code}) => (
transformer.bakeVersionstamp!(item, stamp, code))
)
}
return result // Ok, success.
} catch (err) {
// See if we can retry the transaction
if (err instanceof FDBError) {
await this.rawOnError(err.code) // If this throws, punt error to caller.
// If that passed, loop.
} else throw err
}
// Reset our local state that will have been filled in by calling the body.
this._ctx.nextCode = 0
if (this._ctx.toBake) this._ctx.toBake.length = 0
} while (true)
}
/**
* Set options on the transaction object. These options can have a variety of
* effects - see TransactionOptionCode for details. For options which are
* persistent on the transaction, its recommended to set the option when the
* transaction is constructed.
*
* Note that options are shared between a transaction object and any aliases
* of the transaction object (eg in other scopes or from `txn.snapshot()`).
*/
setOption(opt: TransactionOptionCode, value?: number | string | Buffer) {
// TODO: Check type of passed option is valid.
this._tn.setOption(opt, (value == null) ? null : value)
}
/**
* Returns a shallow copy of the transaction object which does snapshot reads.
*/
snapshot(): Transaction<KeyIn, KeyOut, ValIn, ValOut> {
return new Transaction(this._tn, true, this.subspace, undefined, this._ctx)
}
/**
* Create a shallow copy of the transaction in the specified subspace (or database, transaction, or directory).
*/
at<CKI, CKO, CVI, CVO>(hasSubspace: GetSubspace<CKI, CKO, CVI, CVO>): Transaction<CKI, CKO, CVI, CVO> {
return new Transaction(this._tn, this.isSnapshot, hasSubspace.getSubspace(), undefined, this._ctx)
}
/** @deprecated - use transaction.at(db) instead. */
scopedTo<CKI, CKO, CVI, CVO>(db: Database<CKI, CKO, CVI, CVO>): Transaction<CKI, CKO, CVI, CVO> {
return this.at(db)
}
/** Get the current subspace */
getSubspace() { return this.subspace }
// You probably don't want to call any of these functions directly. Instead call db.transact(async tn => {...}).
/**
* This uses the raw API to commit a transaction. 99% of users shouldn't touch this, and should instead use `db.doTn(async tn => {...})`, which will automatically commit the transaction and retry if necessary.
*/
rawCommit(): Promise<void>
/** @deprecated - Use promises API instead. */
rawCommit(cb: Callback<void>): void
rawCommit(cb?: Callback<void>) {
return cb
? this._tn.commit(cb)
: this._tn.commit()
}
rawReset() { this._tn.reset() }
rawCancel() { this._tn.cancel() }
rawOnError(code: number): Promise<void>
/** @deprecated - Use promises API instead. */
rawOnError(code: number, cb: Callback<void>): void
rawOnError(code: number, cb?: Callback<void>) {
return cb
? this._tn.onError(code, cb)
: this._tn.onError(code)
}
/**
* Get the value for the specified key in the database.
*
* @returns the value for the specified key, or `undefined` if the key does
* not exist in the database.
*/
get(key: KeyIn): Promise<ValOut | undefined>
/** @deprecated - Use promises API instead. */
get(key: KeyIn, cb: Callback<ValOut | undefined>): void
get(key: KeyIn, cb?: Callback<ValOut | undefined>) {
const keyBuf = this._keyEncoding.pack(key)
return cb
? this._tn.get(keyBuf, this.isSnapshot, (err, val) => {
cb(err, val == null ? undefined : this._valueEncoding.unpack(val))
})
: this._tn.get(keyBuf, this.isSnapshot)
.then(val => val == null ? undefined : this._valueEncoding.unpack(val))
}
/** Checks if the key exists in the database. This is just a shorthand for
* tn.get() !== undefined.
*/
exists(key: KeyIn): Promise<boolean> {
const keyBuf = this._keyEncoding.pack(key)
return this._tn.get(keyBuf, this.isSnapshot).then(val => val != undefined)
}
/**
* Find and return the first key which matches the specified key selector
* inside the given subspace. Returns undefined if no key matching the
* selector falls inside the current subspace.
*
* If you pass a key instead of a selector, this method will find the first
* key >= the specified key. Aka `getKey(someKey)` is the equivalent of
* `getKey(keySelector.firstGreaterOrEqual(somekey))`.
*
* Note that this method is a little funky in the root subspace:
*
* - We cannot differentiate between "no smaller key found" and "found the
* empty key ('')". To make the API more consistent, we assume you aren't
* using the empty key in your dataset.
* - If your key selector looks forward in the dataset, this method may find
* and return keys in the system portion (starting with '\xff').
*/
getKey(_sel: KeySelector<KeyIn> | KeyIn): Promise<KeyOut | undefined> {
const sel = keySelector.from(_sel)
return this._tn.getKey(this._keyEncoding.pack(sel.key), sel.orEqual, sel.offset, this.isSnapshot)
.then(key => (
(key.length === 0 || !this.subspace.contains(key))
? undefined
: this._keyEncoding.unpack(key)
))
}
/** Set the specified key/value pair in the database */
set(key: KeyIn, val: ValIn) {
this._tn.set(this._keyEncoding.pack(key), this._valueEncoding.pack(val))
}
/** Remove the value for the specified key */
clear(key: KeyIn) {
const pack = this._keyEncoding.pack(key)
this._tn.clear(pack)
}
/** Alias for `tn.clear()` to match semantics of javascripts Map/Set/etc classes */
delete(key: KeyIn) {
return this.clear(key)
}
// This just destructively edits the result in-place.
private _encodeRangeResult(r: [Buffer, Buffer][]): [KeyOut, ValOut][] {
// This is slightly faster but I have to throw away the TS checks in the process. :/
for (let i = 0; i < r.length; i++) {
;(r as any)[i][0] = this._keyEncoding.unpack(r[i][0])
;(r as any)[i][1] = this._valueEncoding.unpack(r[i][1])
}
return r as any as [KeyOut, ValOut][]
}
getRangeNative(start: KeySelector<NativeValue>,
end: KeySelector<NativeValue> | null, // If not specified, start is used as a prefix.
limit: number, targetBytes: number, streamingMode: StreamingMode,
iter: number, reverse: boolean): Promise<KVList<Buffer, Buffer>> {
const _end = end != null ? end : keySelector.firstGreaterOrEqual(strInc(start.key))
return this._tn.getRange(
start.key, start.orEqual, start.offset,
_end.key, _end.orEqual, _end.offset,
limit, targetBytes, streamingMode,
iter, this.isSnapshot, reverse)
}
getRangeRaw(start: KeySelector<KeyIn>, end: KeySelector<KeyIn> | null,
limit: number, targetBytes: number, streamingMode: StreamingMode,
iter: number, reverse: boolean): Promise<KVList<KeyOut, ValOut>> {
return this.getRangeNative(
keySelector.toNative(start, this._keyEncoding),
end != null ? keySelector.toNative(end, this._keyEncoding) : null,
limit, targetBytes, streamingMode, iter, reverse)
.then(r => ({more: r.more, results: this._encodeRangeResult(r.results)}))
}
/**
* This method is functionally the same as *getRange*, but values are returned
* in the batches they're delivered in from the database. This method is
* present because it may be marginally faster than `getRange`.
*
* Example:
*
* ```
* for await (const batch of tn.getRangeBatch(0, 1000)) {
* for (let k = 0; k < batch.length; k++) {
* const [key, val] = batch[k]
* // ...
* }
* }
* ```
*
* @see Transaction.getRange
*/
async *getRangeBatch(
_start: KeyIn | KeySelector<KeyIn>, // Consider also supporting string / buffers for these.
_end?: KeyIn | KeySelector<KeyIn>, // If not specified, start is used as a prefix.
opts: RangeOptions = {}) {
// This is a bit of a dog's breakfast. We're trying to handle a lot of different cases here:
// - The start and end parameters can be specified as keys or as selectors
// - The end parameter can be missing / null, and if it is we want to "do the right thing" here
// - Which normally means searching between [start, strInc(start)]
// - But with tuple encoding this means between [start + '\x00', start + '\xff']
let start: KeySelector<string | Buffer>, end: KeySelector<string | Buffer>
const startSelEnc = keySelector.from(_start)
if (_end == null) {
const range = this.subspace.packRange(startSelEnc.key)
start = keySelector(range.begin, startSelEnc.orEqual, startSelEnc.offset)
end = keySelector.firstGreaterOrEqual(range.end)
} else {
start = keySelector.toNative(startSelEnc, this._keyEncoding)
end = keySelector.toNative(keySelector.from(_end), this._keyEncoding)
}
let limit = opts.limit || 0
const streamingMode = opts.streamingMode == null ? StreamingMode.Iterator : opts.streamingMode
let iter = 0
while (1) {
const {results, more} = await this.getRangeNative(start, end,
limit, 0, streamingMode, ++iter, opts.reverse || false)
if (results.length) {
if (!opts.reverse) start = keySelector.firstGreaterThan(results[results.length-1][0])
else end = keySelector.firstGreaterOrEqual(results[results.length-1][0])
}
// This destructively consumes results.
yield this._encodeRangeResult(results)
if (!more) break
if (limit) {
limit -= results.length
if (limit <= 0) break
}
}
}
// TODO: getRangeBatchStartsWith
/**
* Get all key value pairs within the specified range. This method returns an
* async generator, which can be iterated over in a `for await(...)` loop like
* this:
*
* ```
* for await (const [key, value] of tn.getRange('a', 'z')) {
* // ...
* }
* ```
*
* The values will be streamed from the database as they are read.
*
* Key value pairs will be yielded in the order they are present in the
* database - from lowest to highest key. (Or the reverse order if
* `reverse:true` is set in options).
*
* Note that transactions are [designed to be short
* lived](https://apple.github.io/foundationdb/developer-guide.html?#long-running-transactions),
* and will error if the read operation takes more than 5 seconds.
*
* The end of the range is optional. If missing, this method will use the
* first parameter as a prefix and fetch all key value pairs starting with
* that key.
*
* The start or the end can be specified using KeySelectors instead of raw
* keys in order to specify offsets and such.
*
* getRange also takes an optional extra options object parameter. Valid
* options are:
*
* - **limit:** (number) Maximum number of items returned by the call to
* getRange
* - **reverse:** (boolean) Flag to reverse the iteration, and instead search
* from `end` to `start`. Key value pairs will be returned from highest key
* to lowest key.
* - **streamingMode:** (enum StreamingMode) *(rarely used)* The policy for
* how eager FDB should be about prefetching data. See enum StreamingMode in
* opts.
*/
async *getRange(
start: KeyIn | KeySelector<KeyIn>, // Consider also supporting string / buffers for these.
end?: KeyIn | KeySelector<KeyIn>,
opts?: RangeOptions) {
for await (const batch of this.getRangeBatch(start, end, opts)) {
for (const pair of batch) yield pair
}
}
// TODO: getRangeStartsWtih
/**
* Same as getRange, but prefetches and returns all values in an array rather
* than streaming the values over the wire. This is often more convenient, and
* makes sense when dealing with a small range.
*
* @see Transaction.getRange
*
* @returns array of [key, value] pairs
*/
async getRangeAll(
start: KeyIn | KeySelector<KeyIn>,
end?: KeyIn | KeySelector<KeyIn>, // if undefined, start is used as a prefix.
opts: RangeOptions = {}) {
const childOpts: RangeOptions = {...opts}
if (childOpts.streamingMode == null) childOpts.streamingMode = StreamingMode.WantAll
const result: [KeyOut, ValOut][] = []
for await (const batch of this.getRangeBatch(start, end, childOpts)) {
result.push.apply(result, batch)
}
return result
}
getRangeAllStartsWith(prefix: KeyIn | KeySelector<KeyIn>, opts?: RangeOptions) {
return this.getRangeAll(prefix, undefined, opts)
}
/**
* Removes all key value pairs from the database in between start and end.
*
* End parameter is optional. If not specified, this removes all keys with
* *start* as a prefix.
*/
clearRange(_start: KeyIn, _end?: KeyIn) {
let start: NativeValue, end: NativeValue
// const _start = this._keyEncoding.pack(start)
if (_end == null) {
const range = this.subspace.packRange(_start)
start = range.begin
end = range.end
} else {
start = this._keyEncoding.pack(_start)
end = this._keyEncoding.pack(_end)
}
// const _end = end == null ? strInc(_start) : this._keyEncoding.pack(end)
this._tn.clearRange(start, end)
}
/** An alias for unary clearRange */
clearRangeStartsWith(prefix: KeyIn) {
this.clearRange(prefix)
}
watch(key: KeyIn, opts?: WatchOptions): Watch {
const throwAll = opts && opts.throwAllErrors
const watch = this._tn.watch(this._keyEncoding.pack(key), !throwAll)
// Suppress the global unhandledRejection handler when a watch errors
watch.promise.catch(doNothing)
return watch
}
addReadConflictRange(start: KeyIn, end: KeyIn) {
this._tn.addReadConflictRange(this._keyEncoding.pack(start), this._keyEncoding.pack(end))
}
addReadConflictKey(key: KeyIn) {
const keyBuf = this._keyEncoding.pack(key)
this._tn.addReadConflictRange(keyBuf, strNext(keyBuf))
}
addWriteConflictRange(start: KeyIn, end: KeyIn) {
this._tn.addWriteConflictRange(this._keyEncoding.pack(start), this._keyEncoding.pack(end))
}
addWriteConflictKey(key: KeyIn) {
const keyBuf = this._keyEncoding.pack(key)
this._tn.addWriteConflictRange(keyBuf, strNext(keyBuf))
}
// version must be 8 bytes
setReadVersion(v: Version) { this._tn.setReadVersion(v) }
/** Get the database version used to perform reads in this transaction. */
getReadVersion(): Promise<Version>
/** @deprecated - Use promises API instead. */
getReadVersion(cb: Callback<Version>): void
getReadVersion(cb?: Callback<Version>) {
return cb ? this._tn.getReadVersion(cb) : this._tn.getReadVersion()
}
getCommittedVersion() { return this._tn.getCommittedVersion() }
// Note: This promise can't be directly returned via the return value of a
// transaction.
getVersionstamp(): {promise: Promise<Buffer>}
/** @deprecated - Use promises API instead. */
getVersionstamp(cb: Callback<Buffer>): void
getVersionstamp(cb?: Callback<Buffer>) {
if (cb) return this._tn.getVersionstamp(cb)
else {
// This one is surprisingly tricky:
//
// - If we return the promise as normal, you'll deadlock if you try to
// return it via your async tn function (since JS automatically
// flatmaps promises)
// - Also if the tn conflicts, this promise will also generate an error.
// By default node will crash your program when it sees this error.
// We'll allow the error naturally, but suppress node's default
// response by adding an empty catch function
const promise = this._tn.getVersionstamp()
promise.catch(doNothing)
return {promise}
}
}
getAddressesForKey(key: KeyIn): string[] {
return this._tn.getAddressesForKey(this._keyEncoding.pack(key))
}
// **** Atomic operations
atomicOpNative(opType: MutationType, key: NativeValue, oper: NativeValue) {
this._tn.atomicOp(opType, key, oper)
}
atomicOpKB(opType: MutationType, key: KeyIn, oper: Buffer) {
this._tn.atomicOp(opType, this._keyEncoding.pack(key), oper)
}
atomicOp(opType: MutationType, key: KeyIn, oper: ValIn) {
this._tn.atomicOp(opType, this._keyEncoding.pack(key), this._valueEncoding.pack(oper))
}
/**
* Does little-endian addition on encoded values. Value transformer should encode to some
* little endian type.
*/
add(key: KeyIn, oper: ValIn) { this.atomicOp(MutationType.Add, key, oper) }
max(key: KeyIn, oper: ValIn) { this.atomicOp(MutationType.Max, key, oper) }
min(key: KeyIn, oper: ValIn) { this.atomicOp(MutationType.Min, key, oper) }
// Raw buffer variants are provided here to support fancy bit packing semantics.
bitAnd(key: KeyIn, oper: ValIn) { this.atomicOp(MutationType.BitAnd, key, oper) }
bitOr(key: KeyIn, oper: ValIn) { this.atomicOp(MutationType.BitOr, key, oper) }
bitXor(key: KeyIn, oper: ValIn) { this.atomicOp(MutationType.BitXor, key, oper) }
bitAndBuf(key: KeyIn, oper: Buffer) { this.atomicOpKB(MutationType.BitAnd, key, oper) }
bitOrBuf(key: KeyIn, oper: Buffer) { this.atomicOpKB(MutationType.BitOr, key, oper) }
bitXorBuf(key: KeyIn, oper: Buffer) { this.atomicOpKB(MutationType.BitXor, key, oper) }
/*
* Performs lexicographic comparison of byte strings. Sets the value in the
* database to the lexographical min of its current value and the value
* supplied as a parameter. If the key does not exist in the database this is
* the same as set().
*/
byteMin(key: KeyIn, val: ValIn) { this.atomicOp(MutationType.ByteMin, key, val) }
/*
* Performs lexicographic comparison of byte strings. Sets the value in the
* database to the lexographical max of its current value and the value
* supplied as a parameter. If the key does not exist in the database this is
* the same as set().
*/
byteMax(key: KeyIn, val: ValIn) { this.atomicOp(MutationType.ByteMax, key, val) }
// **** Version stamp stuff
getNextTransactionID() { return this._ctx.nextCode++ }
private _bakeCode(into: UnboundStamp) {
if (this.isSnapshot) throw new Error('Cannot use this method in a snapshot transaction')
if (into.codePos != null) {
// We edit the buffer in-place but leave the codepos as is so if the txn
// retries it'll overwrite the code.
const id = this.getNextTransactionID()
if (id > 0xffff) throw new Error('Cannot use more than 65536 unique versionstamps in a single transaction. Either split your writes into multiple transactions or add explicit codes to your unbound versionstamps')
into.data.writeInt16BE(id, into.codePos)
return into.data.slice(into.codePos, into.codePos+2)
}
return null
}
setVersionstampedKeyRaw(keyBytes: Buffer, value: ValIn) {
this.atomicOpNative(MutationType.SetVersionstampedKey, keyBytes, this._valueEncoding.pack(value))
}
// This sets the key [prefix, 10 bytes versionstamp, suffix] to value.
setVersionstampedKeyBuf(prefix: Buffer | undefined, suffix: Buffer | undefined, value: ValIn) {
const key = packVersionstampPrefixSuffix(prefix, suffix, true)
// console.log('key', key)
this.atomicOpNative(MutationType.SetVersionstampedKey, key, this._valueEncoding.pack(value))
}
private _addBakeItem<T>(item: T, transformer: Transformer<T, any>, code: Buffer | null) {
if (transformer.bakeVersionstamp) {
const scope = this._ctx
if (scope.toBake == null) scope.toBake = []
scope.toBake.push({item, transformer, code})
}
}
// TODO: These method names are a bit confusing.
//
// The short version is, if you're using the tuple type with an unbound
// versionstamp, use setVersionstampedKey. Otherwise if you just want your
// key to be baked out with a versionstamp after it, use
// setVersionstampSuffixedKey.
setVersionstampedKey(key: KeyIn, value: ValIn, bakeAfterCommit: boolean = true) {
if (!this._keyEncoding.packUnboundVersionstamp) {
throw TypeError('Key encoding does not support unbound versionstamps. Use setVersionstampPrefixedValue instead')
}
const pack = this._keyEncoding.packUnboundVersionstamp(key)
const code = this._bakeCode(pack)
this.setVersionstampedKeyRaw(packVersionstamp(pack, true), value)
if (bakeAfterCommit) this._addBakeItem(key, this._keyEncoding, code)
}
setVersionstampSuffixedKey(key: KeyIn, value: ValIn, suffix?: Buffer) {
const prefix = asBuf(this._keyEncoding.pack(key))
this.setVersionstampedKeyBuf(prefix, suffix, value)
}
// Ok now versionstamped values
setVersionstampedValueRaw(key: KeyIn, value: Buffer) {
this.atomicOpKB(MutationType.SetVersionstampedValue, key, value)
}
setVersionstampedValue(key: KeyIn, value: ValIn, bakeAfterCommit: boolean = true) {
// This is super similar to setVersionstampedKey. I wish I could reuse the code.
if (!this._valueEncoding.packUnboundVersionstamp) {
throw TypeError('Value encoding does not support unbound versionstamps. Use setVersionstampPrefixedValue instead')
}
const pack = this._valueEncoding.packUnboundVersionstamp(value)
const code = this._bakeCode(pack)
this.setVersionstampedValueRaw(key, packVersionstamp(pack, false))
if (bakeAfterCommit) this._addBakeItem(value, this._valueEncoding, code)
}
/**
* Set key = [10 byte versionstamp, value in bytes]. This function leans on
* the value transformer to pack & unpack versionstamps. An extra value
* prefix is only supported on API version 520+.
*/
setVersionstampPrefixedValue(key: KeyIn, value?: ValIn, prefix?: Buffer) {
const valBuf = value !== undefined ? asBuf(this._valueEncoding.pack(value)) : undefined
const val = packVersionstampPrefixSuffix(prefix, valBuf, false)
this.atomicOpKB(MutationType.SetVersionstampedValue, key, val)
}
/**
* Helper to get the specified key and split out the stamp and value pair.
* This requires that the stamp is at offset 0 (the start) of the value.
* This is designed to work with setVersionstampPrefixedValue. If you're
* using setVersionstampedValue with tuples, just call get().
*/
async getVersionstampPrefixedValue(key: KeyIn): Promise<{stamp: Buffer, value?: ValOut} | null> {
const val = await this._tn.get(this._keyEncoding.pack(key), this.isSnapshot)
return val == null ? null
: {
stamp: val.slice(0, 10),
// So this is a bit opinionated - if you call
// setVersionstampPrefixedValue with no value, the db will just have
// the 10 byte versionstamp. So when you get here, we have no bytes
// for the decoder and that can cause issues. We'll just return null
// in that case - but, yeah, controversial. You might want some other
// encoding or something. File an issue if this causes you grief.
value: val.length > 10 ? this._valueEncoding.unpack(val.slice(10)) : undefined
}
}
getApproximateSize() {
return this._tn.getApproximateSize()
}
// This packs the value by prefixing the version stamp to the
// valueEncoding's packed version of the value.
// This is intended for use with getPackedVersionstampedValue.
//
// If your key transformer sometimes returns an unbound value for this key
// (eg using tuples), just call set(key, value).
// setVersionstampedValueBuf(key: KeyIn, value: Buffer, pos: number = 0) {
// // const valPack = packVersionstampedValue(asBuf(this._valueEncoding.pack(value)), pos)
// const valPack = packVersionstampRaw(value, pos, true)
// this.atomicOpKB(MutationType.SetVersionstampedValue, key, valPack)
// }
} | the_stack |
import { CheckBoxFlag, DropDownFlag, InputFlag } from './flag';
export class NewWorkflowFlags {
flags= {};
constructor(workflows) {
// General flags.
this.flags['skip_start'] = new SkipStartFlag(0, 'skip_start');
this.flags['skip_start'].positional = true;
this.flags['skip_start'].namedPositional = 'skip_start';
this.flags['factory_name'] = new FactoryNameFlag(1, 'factory_name', workflows);
this.flags['factory_name'].positional = true;
// Flags for the Sleep workflow.
this.flags['sleep_duration'] = new SleepDurationFlag(2, 'sleep_duration');
this.flags['sleep_duration'].positional = true;
this.flags['sleep_duration'].namedPositional = 'duration';
// Flags for the Schema Swap workflow.
this.flags['schema_swap_keyspace'] = new SchemaSwapKeyspaceFlag(3, 'schema_swap_keyspace');
this.flags['schema_swap_keyspace'].positional = true;
this.flags['schema_swap_keyspace'].namedPositional = 'keyspace';
this.flags['schema_swap_sql'] = new SchemaSwapSQLFlag(4, 'schema_swap_sql');
this.flags['schema_swap_sql'].positional = true;
this.flags['schema_swap_sql'].namedPositional = 'sql';
// Flags for Horizontal Resharding workflow.
this.flags['horizontal_resharding_keyspace'] = new HorizontalReshardingKeyspaceFlag(5, 'horizontal_resharding_keyspace', 'horizontal_resharding');
this.flags['horizontal_resharding_keyspace'].positional = true;
this.flags['horizontal_resharding_keyspace'].namedPositional = 'keyspace';
this.flags['horizontal_resharding_source_shards'] = new HorizontalReshardingSourceShardsFlag(6, 'horizontal_resharding_source_shards', 'horizontal_resharding');
this.flags['horizontal_resharding_source_shards'].positional = true;
this.flags['horizontal_resharding_source_shards'].namedPositional = 'source_shards';
this.flags['horizontal_resharding_destination_shards'] = new HorizontalReshardingDestinationShardsFlag(7, 'horizontal_resharding_destination_shards', 'horizontal_resharding');
this.flags['horizontal_resharding_destination_shards'].positional = true;
this.flags['horizontal_resharding_destination_shards'].namedPositional = 'destination_shards';
this.flags['horizontal_resharding_vtworkers'] = new HorizontalReshardingVtworkerFlag(8, 'horizontal_resharding_vtworkers', 'horizontal_resharding');
this.flags['horizontal_resharding_vtworkers'].positional = true;
this.flags['horizontal_resharding_vtworkers'].namedPositional = 'vtworkers';
this.flags['horizontal_resharding_exclude_tables'] = new HorizontalReshardingExcludeTablesFlag(9, 'horizontal_resharding_exclude_tables', 'horizontal_resharding');
this.flags['horizontal_resharding_exclude_tables'].positional = true;
this.flags['horizontal_resharding_exclude_tables'].namedPositional = 'exclude_tables';
this.flags['horizontal_resharding_split_cmd'] = new SplitCloneCommand(10, 'horizontal_resharding_split_cmd', 'horizontal_resharding');
this.flags['horizontal_resharding_split_cmd'].positional = true;
this.flags['horizontal_resharding_split_cmd'].namedPositional = 'split_cmd';
this.flags['horizontal_resharding_split_diff_cmd'] = new SplitDiffCommand(11, 'horizontal_resharding_split_diff_cmd', 'horizontal_resharding');
this.flags['horizontal_resharding_split_diff_cmd'].positional = true;
this.flags['horizontal_resharding_split_diff_cmd'].namedPositional = 'split_diff_cmd';
this.flags['horizontal_resharding_split_diff_dest_tablet_type'] = new SplitDiffTabletType(12, 'horizontal_resharding_split_diff_dest_tablet_type', 'horizontal_resharding');
this.flags['horizontal_resharding_split_diff_dest_tablet_type'].positional = true;
this.flags['horizontal_resharding_split_diff_dest_tablet_type'].namedPositional = 'split_diff_dest_tablet_type';
this.flags['horizontal_resharding_min_healthy_rdonly_tablets'] = new HorizontalReshardingMinHealthyRdonlyTablets(13, 'horizontal_resharding_min_healthy_rdonly_tablets', 'horizontal_resharding');
this.flags['horizontal_resharding_min_healthy_rdonly_tablets'].positional = true;
this.flags['horizontal_resharding_min_healthy_rdonly_tablets'].namedPositional = 'min_healthy_rdonly_tablets';
this.flags['horizontal_resharding_skip_split_ratio_check'] = new HorizontalReshardingSkipSplitRatioCheckFlag(14, 'horizontal_resharding_skip_split_ratio_check', 'Skip Split Ratio Check', 'horizontal_resharding');
this.flags['horizontal_resharding_skip_split_ratio_check'].positional = true;
this.flags['horizontal_resharding_skip_split_ratio_check'].namedPositional = 'skip_split_ratio_check';
this.flags['horizontal_resharding_use_consistent_snapshot'] = new HorizontalReshardingConsistentSnapshotFlag(15, 'horizontal_resharding_use_consistent_snapshot', 'Use Consistent Snapshot', 'horizontal_resharding');
this.flags['horizontal_resharding_use_consistent_snapshot'].positional = true;
this.flags['horizontal_resharding_use_consistent_snapshot'].namedPositional = 'use_consistent_snapshot';
this.flags['horizontal_resharding_enable_approvals_copy_schema'] = new HorizontalReshardingEnableApprovalsFlag(16, 'horizontal_resharding_enable_approvals_copy_schema', 'Copy Schema enable approvals', 'horizontal_resharding');
this.flags['horizontal_resharding_enable_approvals_copy_schema'].positional = true;
this.flags['horizontal_resharding_enable_approvals_copy_schema'].namedPositional = 'copy_schema';
this.flags['horizontal_resharding_enable_approvals_clone'] = new HorizontalReshardingEnableApprovalsFlag(17, 'horizontal_resharding_enable_approvals_clone', 'Clone enable approvals', 'horizontal_resharding');
this.flags['horizontal_resharding_enable_approvals_clone'].positional = true;
this.flags['horizontal_resharding_enable_approvals_clone'].namedPositional = 'clone';
this.flags['horizontal_resharding_enable_approvals_wait_filtered_replication'] = new HorizontalReshardingEnableApprovalsFlag(18, 'horizontal_resharding_enable_approvals_wait_filtered_replication', 'Wait filtered replication enable approvals', 'horizontal_resharding');
this.flags['horizontal_resharding_enable_approvals_wait_filtered_replication'].positional = true;
this.flags['horizontal_resharding_enable_approvals_wait_filtered_replication'].namedPositional = 'wait_for_filtered_replication';
this.flags['horizontal_resharding_enable_approvals_diff'] = new HorizontalReshardingEnableApprovalsFlag(19, 'horizontal_resharding_enable_approvals_diff', 'Diff enable approvals', 'horizontal_resharding');
this.flags['horizontal_resharding_enable_approvals_diff'].positional = true;
this.flags['horizontal_resharding_enable_approvals_diff'].namedPositional = 'diff';
this.flags['horizontal_resharding_enable_approvals_migrate_serving_types'] = new HorizontalReshardingEnableApprovalsFlag(20, 'horizontal_resharding_enable_approvals_migrate_serving_types', 'Migrate serving types enable approvals', 'horizontal_resharding');
this.flags['horizontal_resharding_enable_approvals_migrate_serving_types'].positional = true;
this.flags['horizontal_resharding_enable_approvals_migrate_serving_types'].namedPositional = 'migrate_rdonly,migrate_replica,migrate_master';
this.flags['horizontal_resharding_phase_enable_approvals'] = new HorizontalReshardingPhaseEnableApprovalFlag(21, 'horizontal_resharding_phase_enable_approvals');
this.flags['horizontal_resharding_phase_enable_approvals'].positional = true;
this.flags['horizontal_resharding_phase_enable_approvals'].namedPositional = 'phase_enable_approvals';
// // Flags for keyspace resharding workflow.
this.flags['hr_workflow_gen_keyspace'] = new HorizontalReshardingKeyspaceFlag(22, 'hr_workflow_gen_keyspace', 'hr_workflow_gen');
this.flags['hr_workflow_gen_keyspace'].positional = true;
this.flags['hr_workflow_gen_keyspace'].namedPositional = 'keyspace';
this.flags['hr_workflow_gen_vtworkers'] = new HorizontalReshardingVtworkerFlag(23, 'hr_workflow_gen_vtworkers', 'hr_workflow_gen');
this.flags['hr_workflow_gen_vtworkers'].positional = true;
this.flags['hr_workflow_gen_vtworkers'].namedPositional = 'vtworkers';
this.flags['hr_workflow_gen_exclude_tables'] = new HorizontalReshardingExcludeTablesFlag(24, 'hr_workflow_gen_exclude_tables', 'hr_workflow_gen');
this.flags['hr_workflow_gen_exclude_tables'].positional = true;
this.flags['hr_workflow_gen_exclude_tables'].namedPositional = 'exclude_tables';
this.flags['hr_workflow_gen_split_cmd'] = new SplitCloneCommand(25, 'hr_workflow_gen_split_cmd', 'hr_workflow_gen');
this.flags['hr_workflow_gen_split_cmd'].positional = true;
this.flags['hr_workflow_gen_split_cmd'].namedPositional = 'split_cmd';
this.flags['hr_workflow_gen_split_diff_cmd'] = new SplitDiffCommand(26, 'hr_workflow_gen_split_diff_cmd', 'hr_workflow_gen');
this.flags['hr_workflow_gen_split_diff_cmd'].positional = true;
this.flags['hr_workflow_gen_split_diff_cmd'].namedPositional = 'split_diff_cmd';
this.flags['hr_workflow_gen_split_diff_dest_tablet_type'] = new SplitDiffTabletType(27, 'hr_workflow_gen_split_diff_dest_tablet_type', 'hr_workflow_gen');
this.flags['hr_workflow_gen_split_diff_dest_tablet_type'].positional = true;
this.flags['hr_workflow_gen_split_diff_dest_tablet_type'].namedPositional = 'split_diff_dest_tablet_type';
this.flags['hr_workflow_gen_min_healthy_rdonly_tablets'] = new HorizontalReshardingMinHealthyRdonlyTablets(28, 'hr_workflow_gen_min_healthy_rdonly_tablets', 'hr_workflow_gen');
this.flags['hr_workflow_gen_min_healthy_rdonly_tablets'].positional = true;
this.flags['hr_workflow_gen_min_healthy_rdonly_tablets'].namedPositional = 'min_healthy_rdonly_tablets';
this.flags['hr_workflow_gen_skip_split_ratio_check'] = new HorizontalReshardingSkipSplitRatioCheckFlag(29, 'hr_workflow_gen_skip_split_ratio_check', 'Skip Split Ratio Check', 'hr_workflow_gen');
this.flags['hr_workflow_gen_skip_split_ratio_check'].positional = true;
this.flags['hr_workflow_gen_skip_split_ratio_check'].namedPositional = 'skip_split_ratio_check';
this.flags['hr_workflow_gen_use_consistent_snapshot'] = new HorizontalReshardingConsistentSnapshotFlag(30, 'hr_workflow_gen_use_consistent_snapshot', 'Use Consistent Snapshot', 'hr_workflow_gen');
this.flags['hr_workflow_gen_use_consistent_snapshot'].positional = true;
this.flags['hr_workflow_gen_use_consistent_snapshot'].namedPositional = 'use_consistent_snapshot';
this.flags['hr_workflow_gen_enable_approvals_copy_schema'] = new HorizontalReshardingEnableApprovalsFlag(31, 'hr_workflow_gen_enable_approvals_copy_schema', 'Copy Schema enable approvals', 'hr_workflow_gen');
this.flags['hr_workflow_gen_enable_approvals_copy_schema'].positional = true;
this.flags['hr_workflow_gen_enable_approvals_copy_schema'].namedPositional = 'copy_schema';
this.flags['hr_workflow_gen_enable_approvals_clone'] = new HorizontalReshardingEnableApprovalsFlag(32, 'hr_workflow_gen_enable_approvals_clone', 'Clone enable approvals', 'hr_workflow_gen');
this.flags['hr_workflow_gen_enable_approvals_clone'].positional = true;
this.flags['hr_workflow_gen_enable_approvals_clone'].namedPositional = 'clone';
this.flags['hr_workflow_gen_enable_approvals_wait_filtered_replication'] = new HorizontalReshardingEnableApprovalsFlag(33, 'hr_workflow_gen_enable_approvals_wait_filtered_replication', 'Wait filtered replication enable approvals', 'hr_workflow_gen');
this.flags['hr_workflow_gen_enable_approvals_wait_filtered_replication'].positional = true;
this.flags['hr_workflow_gen_enable_approvals_wait_filtered_replication'].namedPositional = 'wait_for_filtered_replication';
this.flags['hr_workflow_gen_enable_approvals_diff'] = new HorizontalReshardingEnableApprovalsFlag(34, 'hr_workflow_gen_enable_approvals_diff', 'Diff enable approvals', 'hr_workflow_gen');
this.flags['hr_workflow_gen_enable_approvals_diff'].positional = true;
this.flags['hr_workflow_gen_enable_approvals_diff'].namedPositional = 'diff';
this.flags['hr_workflow_gen_enable_approvals_migrate_serving_types'] = new HorizontalReshardingEnableApprovalsFlag(35, 'hr_workflow_gen_enable_approvals_migrate_serving_types', 'Migrate serving types enable approvals', 'hr_workflow_gen');
this.flags['hr_workflow_gen_enable_approvals_migrate_serving_types'].positional = true;
this.flags['hr_workflow_gen_enable_approvals_migrate_serving_types'].namedPositional = 'migrate_rdonly,migrate_replica,migrate_master';
this.flags['hr_workflow_gen_phase_enable_approvals'] = new HorizontalReshardingPhaseEnableApprovalFlag(36, 'hr_workflow_gen_phase_enable_approvals');
this.flags['hr_workflow_gen_phase_enable_approvals'].positional = true;
this.flags['hr_workflow_gen_phase_enable_approvals'].namedPositional = 'phase_enable_approvals';
this.flags['hr_workflow_gen_skip_start_workflows'] = new ReshardingWorkflowGenSkipStartFlag(37, 'hr_workflow_gen_skip_start_workflows');
this.flags['hr_workflow_gen_skip_start_workflows'].positional = true;
this.flags['hr_workflow_gen_skip_start_workflows'].namedPositional = 'skip_start_workflows';
}
}
export class SplitCloneCommand extends DropDownFlag {
constructor(position: number, id: string, setDisplayOn: string) {
super(position, id, 'Split Clone Command', 'Specifies the split command to use.', '');
let options = [];
options.push({
label: 'SplitClone',
value: 'SplitClone'
});
this.setOptions(options);
this.value = options[0].value;
this.setDisplayOn('factory_name', setDisplayOn);
}
}
export class SplitDiffCommand extends DropDownFlag {
constructor(position: number, id: string, setDisplayOn: string) {
super(position, id, 'Split Diff Command', 'Specifies the split diff command to use.', '');
let options = [];
options.push({
label: 'SplitDiff',
value: 'SplitDiff'
});
options.push({
label: 'MultiSplitDiff',
value: 'MultiSplitDiff'
});
this.setOptions(options);
this.value = options[0].value;
this.setDisplayOn('factory_name', setDisplayOn);
}
}
export class SplitDiffTabletType extends DropDownFlag {
constructor(position: number, id: string, setDisplayOn: string) {
super(position, id, 'SplitDiff destination tablet type', 'Specifies tablet type to use in destination shards while performing SplitDiff operation', '');
let options = [];
options.push({
label: 'RDONLY',
value: 'RDONLY'
});
options.push({
label: 'REPLICA',
value: 'REPLICA'
});
this.setOptions(options);
this.value = options[0].value;
this.setDisplayOn('factory_name', setDisplayOn);
}
}
export class FactoryNameFlag extends DropDownFlag {
constructor(position: number, id: string, workflows) {
super(position, id, 'Factory Name', 'Specifies the type of workflow to create.', '');
let options = [];
if (workflows.hr_workflow_gen) {
options.push({
label: 'Horizontal Resharding Workflow Generator',
value: 'hr_workflow_gen'
});
}
if (workflows.horizontal_resharding) {
options.push({
label: 'Horizontal Resharding',
value: 'horizontal_resharding'
});
}
if (workflows.schema_swap) {
options.push({
label: 'Schema Swap',
value: 'schema_swap'
});
}
if (workflows.sleep) {
options.push({
label: 'Sleep',
value: 'sleep'
});
}
if (workflows.topo_validator) {
options.push({
label: 'Topology Validator',
value: 'topo_validator',
});
}
this.setOptions(options);
this.value = options[0].value;
}
}
export class SkipStartFlag extends CheckBoxFlag {
constructor(position: number, id: string, value= true) {
super(position, id, 'Skip Start', 'Create the workflow, but don\'t start it.', value);
}
}
export class ReshardingWorkflowGenSkipStartFlag extends CheckBoxFlag {
constructor(position: number, id: string, value= true) {
super(position, id, 'Skip Start Workflows', 'Skip start in all horizontal resharding workflows to be created.', value);
}
}
export class SleepDurationFlag extends InputFlag {
constructor(position: number, id: string, value= '') {
super(position, id, 'Sleep Duration', 'Time to sleep for, in seconds.', value);
this.setDisplayOn('factory_name', 'sleep');
}
}
export class SchemaSwapKeyspaceFlag extends InputFlag {
constructor(position: number, id: string, value= '') {
super(position, id, 'Keyspace', 'Name of a keyspace.', value);
this.setDisplayOn('factory_name', 'schema_swap');
}
}
export class SchemaSwapSQLFlag extends InputFlag {
constructor(position: number, id: string, value= '') {
super(position, id, 'SQL', 'SQL representing the schema change.', value);
this.setDisplayOn('factory_name', 'schema_swap');
}
}
export class HorizontalReshardingKeyspaceFlag extends InputFlag {
constructor(position: number, id: string, setDisplayOn: string, value= '') {
super(position, id, 'Keyspace', 'Name of a keyspace.', value);
this.setDisplayOn('factory_name', setDisplayOn);
}
}
export class HorizontalReshardingSourceShardsFlag extends InputFlag {
constructor(position: number, id: string, setDisplayOn: string, value= '') {
super(position, id, 'Source Shards', 'A comma-separated list of source shards.', value);
this.setDisplayOn('factory_name', setDisplayOn);
}
}
export class HorizontalReshardingDestinationShardsFlag extends InputFlag {
constructor(position: number, id: string, setDisplayOn: string, value= '') {
super(position, id, 'Destination Shards', 'A comma-separated list of destination shards.', value);
this.setDisplayOn('factory_name', setDisplayOn);
}
}
export class HorizontalReshardingVtworkerFlag extends InputFlag {
constructor(position: number, id: string, setDisplayOn: string, value= '') {
super(position, id, 'vtworker Addresses', 'Comma-separated list of vtworker addresses.', value);
this.setDisplayOn('factory_name', setDisplayOn);
}
}
export class HorizontalReshardingExcludeTablesFlag extends InputFlag {
constructor(position: number, id: string, setDisplayOn: string, value= '') {
super(position, id, 'exclude tables', 'Comma-separated list of tables to exclude', value);
this.setDisplayOn('factory_name', setDisplayOn);
}
}
export class HorizontalReshardingPhaseEnableApprovalFlag extends InputFlag {
// This is a hidden flag
constructor(position: number, id: string, value= '') {
super(position, id, 'phase enable approval', '', value);
this.setDisplayOn('factory_name', '__hidden__');
}
}
export class HorizontalReshardingMinHealthyRdonlyTablets extends InputFlag {
constructor(position: number, id: string, setDisplayOn: string, value= '') {
super(position, id, 'min healthy rdonly tablets', 'Minimum number of healthy RDONLY tablets required in source shards', value);
this.setDisplayOn('factory_name', setDisplayOn);
}
}
export class HorizontalReshardingEnableApprovalsFlag extends CheckBoxFlag {
constructor(position: number, id: string, name: string, setDisplayOn: string, value=true) {
super(position, id, name, 'Set true if use user approvals of task execution.', value);
this.setDisplayOn('factory_name', setDisplayOn);
}
}
export class HorizontalReshardingConsistentSnapshotFlag extends CheckBoxFlag {
constructor(position: number, id: string, name: string, setDisplayOn: string, value = false) {
super(position, id, name, 'Use consistent snapshot to have a stable view of the data.', value);
this.setDisplayOn('factory_name', setDisplayOn);
}
}
export class HorizontalReshardingSkipSplitRatioCheckFlag extends CheckBoxFlag {
constructor(position: number, id: string, name: string, setDisplayOn: string, value = false) {
super(position, id, name, 'Skip the validation on minimum healthy rdonly tablets', value);
this.setDisplayOn('factory_name', setDisplayOn);
}
}
// WorkflowFlags is used by the Start / Stop / Delete dialogs.
export class WorkflowFlags {
flags= {};
constructor(path) {
this.flags['workflow_uuid'] = new WorkflowUuidFlag(0, 'workflow_uuid', path);
this.flags['workflow_uuid']['positional'] = true;
}
}
export class WorkflowUuidFlag extends InputFlag {
constructor(position: number, id: string, value= '') {
super(position, id, '', '', value, false);
}
} | the_stack |
import {
IAsyncEnumerable,
IAsyncEqualityComparer,
IAsyncParallel,
IComparer,
IEqualityComparer,
IGrouping,
InferType,
IOrderedParallelEnumerable,
OfType,
SelectorKeyType,
TypedData,
} from "./"
/**
* Parallel Async Iterable type with methods from LINQ.
*/
export interface IParallelEnumerable<TSource> extends IAsyncParallel<TSource> {
/**
* Used for processing.
*/
readonly dataFunc: TypedData<TSource>
/**
* Converts the parallel iterable to an @see {IAsyncEnumerable}
* @returns An IAsyncEnumerable<T>
*/
asAsync(): IAsyncEnumerable<TSource>
/**
* Concatenates two async sequences.
* @param second The async sequence to concatenate to the first sequence.
* @returns An IParallelEnumerable<T> that contains the concatenated elements of the two sequences.
*/
concatenate(second: IAsyncParallel<TSource>): IParallelEnumerable<TSource>
/**
* Returns distinct elements from a sequence by using the default or specified equality comparer to compare values.
* @param comparer An IEqualityComparer<T> to compare values. Optional. Defaults to Strict Equality Comparison.
* @returns An IParallelEnumerable<T> that contains distinct elements from the source sequence.
*/
distinct(comparer?: IEqualityComparer<TSource>): IParallelEnumerable<TSource>
/**
* Returns distinct elements from a sequence by using the specified equality comparer to compare values.
* @param comparer An IAsyncEqualityComparer<T> to compare values.
* @returns An IParallelEnumerable<T> that contains distinct elements from the source sequence.
*/
distinctAsync(comparer: IAsyncEqualityComparer<TSource>): IParallelEnumerable<TSource>
/**
* Performs a specified action on each element of the IParallelEnumerable<TSource>.
* The order of execution is not guaranteed.
* @param action The action to take an each element
* @returns A new IParallelEnumerable<T> that executes the action provided.
*/
each(action: (x: TSource) => void): IParallelEnumerable<TSource>
/**
* Performs a specified action on each element of the IParallelEnumerable<TSource>.
* The order of execution is not guaranteed.
* @param action The async action to take an each element
* @returns A new IParallelEnumerable<T> that executes the action provided.
*/
eachAsync(action: (x: TSource) => Promise<void>): IParallelEnumerable<TSource>
/**
* Produces the set difference of two sequences by using the comparer provided
* or EqualityComparer to compare values.
* @param second An IAsyncParallel<T> whose elements that also occur in the first sequence
* will cause those elements to be removed from the returned sequence.
* @param comparer An IEqualityComparer<T> to compare values. Optional.
* @returns A sequence that contains the set difference of the elements of two sequences.
*/
except(second: IAsyncParallel<TSource>,
comparer?: IEqualityComparer<TSource>): IParallelEnumerable<TSource>
/**
* Produces the set difference of two sequences by using the comparer provided to compare values.
* @param second An IAsyncParallel<T> whose elements that also occur in the first sequence
* will cause those elements to be removed from the returned sequence.
* @param comparer An IAsyncEqualityComparer<T> to compare values.
* @returns A sequence that contains the set difference of the elements of two sequences.
*/
exceptAsync(second: IAsyncParallel<TSource>,
comparer: IAsyncEqualityComparer<TSource>): IParallelEnumerable<TSource>
/**
* Groups the elements of a sequence according to a specified key selector function.
* @param keySelector A function to extract the key for each element.
* @returns An IParallelEnumerable<IGrouping<TKey, TSource>>
* where each IGrouping<TKey,TElement> object contains a sequence of objects and a key.
*/
groupBy<TKey extends SelectorKeyType>(
keySelector: (x: TSource) => TKey): IParallelEnumerable<IGrouping<TKey, TSource>>
/**
* Groups the elements of a sequence according to a key selector function.
* The keys are compared by using a comparer and each group's elements are projected by using a specified function.
* @param keySelector A function to extract the key for each element.
* @param comparer An IEqualityComparer<T> to compare keys.
* @returns An IParallelEnumerable<IGrouping<TKey, TSource>>
* where each IGrouping<TKey,TElement> object contains a sequence of objects and a key.
*/
groupBy<TKey>(
keySelector: (x: TSource) => TKey,
comparer: IEqualityComparer<TKey>): IParallelEnumerable<IGrouping<TKey, TSource>>
/**
* Groups the elements of a sequence according to a specified key selector function.
* @param keySelector An async function to extract the key for each element.
* @returns An IParallelEnumerable<IGrouping<TKey, TSource>>
* where each IGrouping<TKey,TElement> object contains a sequence of objects and a key.
*/
groupByAsync<TKey extends SelectorKeyType>(
keySelector: (x: TSource) => Promise<TKey>): IParallelEnumerable<IGrouping<TKey, TSource>>
/**
* Groups the elements of a sequence according to a specified key selector function.
* @param keySelector An async function to extract the key for each element.
* @param comparer An IEqualityComparer<T> or IAsyncEqualityComparer<T> to compare keys.
* @returns An IParallelEnumerable<IGrouping<TKey, TSource>>
* where each IGrouping<TKey,TElement> object contains a sequence of objects and a key.
*/
groupByAsync<TKey>(
keySelector: (x: TSource) => Promise<TKey> | TKey,
comparer: IEqualityComparer<TKey> | IAsyncEqualityComparer<TKey>)
: IParallelEnumerable<IGrouping<TKey, TSource>>
groupByWithSel<TElement, TKey extends SelectorKeyType>(
keySelector: ((x: TSource) => TKey),
elementSelector: (x: TSource) => TElement): IParallelEnumerable<IGrouping<TKey, TElement>>
groupByWithSel<TKey, TElement>(
keySelector: ((x: TSource) => TKey),
elementSelector: (x: TSource) => TElement,
comparer: IEqualityComparer<TKey>): IParallelEnumerable<IGrouping<TKey, TElement>>
intersect(second: IAsyncParallel<TSource>,
comparer?: IEqualityComparer<TSource>): IParallelEnumerable<TSource>
intersectAsync(second: IAsyncParallel<TSource>,
comparer: IAsyncEqualityComparer<TSource>): IParallelEnumerable<TSource>
// join in LINQ - but renamed to avoid clash with Array.prototype.join
joinByKey<TInner, TKey, TResult>(
inner: IAsyncParallel<TInner>,
outerKeySelector: (x: TSource) => TKey,
innerKeySelector: (x: TInner) => TKey,
resultSelector: (x: TSource, y: TInner) => TResult,
comparer?: IEqualityComparer<TKey>): IParallelEnumerable<TResult>
ofType<TType extends OfType>(type: TType): IParallelEnumerable<InferType<TType>>
orderBy<TKey>(
predicate: (x: TSource) => TKey,
comparer?: IComparer<TKey>): IOrderedParallelEnumerable<TSource>
orderByAsync<TKey>(
predicate: (x: TSource) => Promise<TKey>,
comparer?: IComparer<TKey>): IOrderedParallelEnumerable<TSource>
orderByDescending<TKey>(
predicate: (x: TSource) => TKey,
comparer?: IComparer<TKey>): IParallelEnumerable<TSource>
orderByDescendingAsync<TKey>(
predicate: (x: TSource) => Promise<TKey>,
comparer?: IComparer<TKey>): IParallelEnumerable<TSource>
/**
* Inverts the order of the elements in a sequence.
* @returns A sequence whose elements correspond to those of the input sequence in reverse order.
*/
reverse(): IParallelEnumerable<TSource>
select<TResult>(selector: (x: TSource, index: number) => TResult): IParallelEnumerable<TResult>
select<TKey extends keyof TSource>(key: TKey): IParallelEnumerable<TSource[TKey]>
selectAsync<TResult>(
selector: (x: TSource, index: number) => Promise<TResult>): IParallelEnumerable<TResult>
selectAsync<TKey extends keyof TSource, TResult>(
this: IParallelEnumerable<{ [key: string]: Promise<TResult> }>,
selector: TKey): IParallelEnumerable<TResult>
selectMany<TResult>(selector: (x: TSource, index: number) => Iterable<TResult>): IParallelEnumerable<TResult>
selectMany<TBindedSource extends { [key: string]: Iterable<TOut>}, TOut>(
this: IParallelEnumerable<TBindedSource>,
selector: keyof TBindedSource): IParallelEnumerable<TOut>
selectManyAsync<TResult>(
selector: (x: TSource, index: number) => Promise<Iterable<TResult>>): IParallelEnumerable<TResult>
sequenceEquals(second: IAsyncParallel<TSource>,
comparer?: IEqualityComparer<TSource>): Promise<boolean>
sequenceEqualsAsync(second: IAsyncParallel<TSource>,
comparer?: IAsyncEqualityComparer<TSource>): Promise<boolean>
skip(count: number): IParallelEnumerable<TSource>
skipWhile(predicate: (x: TSource, index: number) => boolean): IParallelEnumerable<TSource>
skipWhileAsync(predicate: (x: TSource, index: number) => Promise<boolean>): IParallelEnumerable<TSource>
take(amount: number): IParallelEnumerable<TSource>
takeWhile(predicate: (x: TSource, index: number) => boolean): IParallelEnumerable<TSource>
takeWhileAsync(predicate: (x: TSource, index: number) => Promise<boolean>): IParallelEnumerable<TSource>
union(second: IAsyncParallel<TSource>,
comparer?: IEqualityComparer<TSource>): IParallelEnumerable<TSource>
unionAsync(second: IAsyncParallel<TSource>,
comparer?: IAsyncEqualityComparer<TSource>): IParallelEnumerable<TSource>
/**
* Filters a sequence of values based on a predicate.
* Each element's index is used in the logic of the predicate function.
* @param predicate A function to test each source element for a condition;
* the second parameter of the function represents the index of the source element.
* @returns An IParallelEnumerable<T> that contains elements from the input sequence that satisfy the condition.
*/
where(predicate: (x: TSource, index: number) => boolean): IParallelEnumerable<TSource>
/**
* Filters a sequence of values based on a predicate.
* Each element's index is used in the logic of the predicate function.
* @param predicate A async function to test each source element for a condition;
* the second parameter of the function represents the index of the source element.
* @returns An IParallelEnumerable<T> that contains elements from the input sequence that satisfy the condition.
*/
whereAsync(predicate: (x: TSource, index: number) => Promise<boolean>): IParallelEnumerable<TSource>
zip<TSecond, TResult>(
second: IAsyncParallel<TSecond>,
resultSelector: (x: TSource, y: TSecond) => TResult): IParallelEnumerable<TResult>
zip<TSecond>(second: IAsyncParallel<TSecond>):
IParallelEnumerable<[TSource, TSecond]>
zipAsync<TSecond, TResult>(
second: IAsyncParallel<TSecond>,
resultSelector: (x: TSource, y: TSecond) => Promise<TResult>): IParallelEnumerable<TResult>
} | the_stack |
module TypeScript {
export interface ISyntaxToken extends ISyntaxNodeOrToken, INameSyntax, IPrimaryExpressionSyntax, IPropertyAssignmentSyntax, IPropertyNameSyntax {
// Adjusts the full start of this token. Should only be called by the parser.
setFullStart(fullStart: number): void;
// The absolute start of this element, including the leading trivia.
fullStart(): number;
// With of this element, including leading and trailing trivia.
fullWidth(): number;
// Text for this token, not including leading or trailing trivia.
text(): string;
fullText(text?: ISimpleText): string;
hasLeadingTrivia(): boolean;
hasLeadingNewLine(): boolean;
hasLeadingComment(): boolean;
hasLeadingSkippedToken(): boolean;
leadingTrivia(text?: ISimpleText): ISyntaxTriviaList;
leadingTriviaWidth(text?: ISimpleText): number;
// True if this was a keyword that the parser converted to an identifier. i.e. if you have
// x.public
//
// then 'public' will be converted to an identifier. These tokens should are parser
// generated and, as such, should not be returned when the incremental parser source
// hands out tokens. Note: If it is included in a node then *that* node may still
// be reusuable. i.e. if i have: private Foo() { x.public = 1; }
//
// Then that entire method node is reusable even if the 'public' identifier is not.
isKeywordConvertedToIdentifier(): boolean;
// True if this element cannot be reused in incremental parsing. There are several situations
// in which an element can not be reused. They are:
//
// 1) The element contained skipped text.
// 2) The element contained zero width tokens.
// 3) The element contains tokens generated by the parser (like >> or a keyword -> identifier
// conversion).
// 4) The element contains a regex token somewhere under it. A regex token is either a
// regex itself (i.e. /foo/), or is a token which could start a regex (i.e. "/" or "/="). This
// data is used by the incremental parser to decide if a node can be reused. Due to the
// lookahead nature of regex tokens, a node containing a regex token cannot be reused. Normally,
// changes to text only affect the tokens directly intersected. However, because regex tokens
// have such unbounded lookahead (technically bounded at the end of a line, but htat's minor),
// we need to recheck them to see if they've changed due to the edit. For example, if you had:
//
// while (true) /3; return;
//
// And you changed it to:
//
// while (true) /3; return/;
//
// Then even though only the 'return' and ';' colons were touched, we'd want to rescan the '/'
// token which we would then realize was a regex.
isIncrementallyUnusable(): boolean;
clone(): ISyntaxToken;
}
}
module TypeScript {
export function tokenValue(token: ISyntaxToken): any {
if (token.fullWidth() === 0) {
return undefined;
}
var kind = token.kind;
var text = token.text();
if (kind === SyntaxKind.IdentifierName) {
return massageEscapes(text);
}
switch (kind) {
case SyntaxKind.TrueKeyword:
return true;
case SyntaxKind.FalseKeyword:
return false;
case SyntaxKind.NullKeyword:
return undefined;
}
if (SyntaxFacts.isAnyKeyword(kind) || SyntaxFacts.isAnyPunctuation(kind)) {
return SyntaxFacts.getText(kind);
}
if (kind === SyntaxKind.NumericLiteral) {
return IntegerUtilities.isHexInteger(text) ? parseInt(text, /*radix:*/ 16) : parseFloat(text);
}
else if (kind === SyntaxKind.StringLiteral) {
return (text.length > 1 && text.charCodeAt(text.length - 1) === text.charCodeAt(0))
? massageEscapes(text.substr(1, text.length - "''".length))
: massageEscapes(text.substr(1));
}
else if (kind === SyntaxKind.NoSubstitutionTemplateToken || kind === SyntaxKind.TemplateEndToken) {
// Both of these template types may be missing their closing backtick (if they were at
// the end of the file). Check to make sure it is there before grabbing the portion
// we're examining.
return (text.length > 1 && text.charCodeAt(text.length - 1) === CharacterCodes.backtick)
? massageTemplate(text.substr(1, text.length - "``".length))
: massageTemplate(text.substr(1));
}
else if (kind === SyntaxKind.TemplateStartToken || kind === SyntaxKind.TemplateMiddleToken) {
// Both these tokens must have been properly ended. i.e. if it didn't end with a ${
// then we would not have parsed a start or middle token out at all. So we don't
// need to check for an incomplete token.
return massageTemplate(text.substr(1, text.length - "`${".length));
}
else if (kind === SyntaxKind.RegularExpressionLiteral) {
return regularExpressionValue(text);
}
else if (kind === SyntaxKind.EndOfFileToken || kind === SyntaxKind.ErrorToken) {
return undefined;
}
else {
throw Errors.invalidOperation();
}
}
export function tokenValueText(token: ISyntaxToken): string {
var value = tokenValue(token);
return value === undefined ? "" : massageDisallowedIdentifiers(value.toString());
}
function massageTemplate(text: string): string {
// First, convert all carriage-return newlines into line-feed newlines. This is due to:
//
// The TRV of LineTerminatorSequence :: <CR> is the code unit value 0x000A.
// ...
// The TRV of LineTerminatorSequence :: <CR><LF> is the sequence consisting of the code unit value 0x000A.
text = text.replace("\r\n", "\n").replace("\r", "\n");
// Now remove any escape characters that may be in the string.
return massageEscapes(text);
}
export function massageEscapes(text: string): string {
return text.indexOf("\\") >= 0 ? convertEscapes(text) : text;
}
function regularExpressionValue(text: string): RegExp {
try {
var lastSlash = text.lastIndexOf("/");
var body = text.substring(1, lastSlash);
var flags = text.substring(lastSlash + 1);
return new RegExp(body, flags);
}
catch (e) {
return undefined;
}
}
function massageDisallowedIdentifiers(text: string): string {
// We routinely store the 'valueText' for a token as keys in dictionaries. However, as those
// dictionaries are usually just a javascript object, we run into issues when teh keys collide
// with certain predefined keys they depend on (like __proto__). To workaround this
// we ensure that the valueText of any token is not __proto__ but is instead ___proto__.
//
// We also prepend a _ to any identifier starting with two __ . That allows us to carve
// out the entire namespace of identifiers starting with __ for ourselves.
if (text.charCodeAt(0) === CharacterCodes._ && text.charCodeAt(1) === CharacterCodes._) {
return "_" + text;
}
return text;
}
var characterArray: number[] = [];
function convertEscapes(text: string): string {
characterArray.length = 0;
var result = "";
for (var i = 0, n = text.length; i < n; i++) {
var ch = text.charCodeAt(i);
if (ch === CharacterCodes.backslash) {
i++;
if (i < n) {
ch = text.charCodeAt(i);
switch (ch) {
case CharacterCodes._0:
characterArray.push(CharacterCodes.nullCharacter);
continue;
case CharacterCodes.b:
characterArray.push(CharacterCodes.backspace);
continue;
case CharacterCodes.f:
characterArray.push(CharacterCodes.formFeed);
continue;
case CharacterCodes.n:
characterArray.push(CharacterCodes.lineFeed);
continue;
case CharacterCodes.r:
characterArray.push(CharacterCodes.carriageReturn);
continue;
case CharacterCodes.t:
characterArray.push(CharacterCodes.tab);
continue;
case CharacterCodes.v:
characterArray.push(CharacterCodes.verticalTab);
continue;
case CharacterCodes.x:
characterArray.push(hexValue(text, /*start:*/ i + 1, /*length:*/ 2));
i += 2;
continue;
case CharacterCodes.u:
characterArray.push(hexValue(text, /*start:*/ i + 1, /*length:*/ 4));
i += 4;
continue;
case CharacterCodes.carriageReturn:
var nextIndex = i + 1;
if (nextIndex < text.length && text.charCodeAt(nextIndex) === CharacterCodes.lineFeed) {
// Skip the entire \r\n sequence.
i++;
}
continue;
case CharacterCodes.lineFeed:
case CharacterCodes.paragraphSeparator:
case CharacterCodes.lineSeparator:
// From ES5: LineContinuation is the empty character sequence.
continue;
default:
// Any other character is ok as well. As per rule:
// EscapeSequence :: CharacterEscapeSequence
// CharacterEscapeSequence :: NonEscapeCharacter
// NonEscapeCharacter :: SourceCharacter but notEscapeCharacter or LineTerminator
//
// Intentional fall through
}
}
}
characterArray.push(ch);
if (i && !(i % 1024)) {
result = result.concat(String.fromCharCode.apply(undefined, characterArray));
characterArray.length = 0;
}
}
if (characterArray.length) {
result = result.concat(String.fromCharCode.apply(undefined, characterArray));
}
return result;
}
function hexValue(text: string, start: number, length: number): number {
var intChar = 0;
for (var i = 0; i < length; i++) {
var ch2 = text.charCodeAt(start + i);
if (!CharacterInfo.isHexDigit(ch2)) {
break;
}
intChar = (intChar << 4) + CharacterInfo.hexValue(ch2);
}
return intChar;
}
}
module TypeScript.Syntax {
export function realizeToken(token: ISyntaxToken, text: ISimpleText): ISyntaxToken {
return new RealizedToken(token.fullStart(), token.kind, token.isKeywordConvertedToIdentifier(), token.leadingTrivia(text), token.text());
}
export function convertKeywordToIdentifier(token: ISyntaxToken): ISyntaxToken {
return new ConvertedKeywordToken(token);
}
export function withLeadingTrivia(token: ISyntaxToken, leadingTrivia: ISyntaxTriviaList, text: ISimpleText): ISyntaxToken {
return new RealizedToken(token.fullStart(), token.kind, token.isKeywordConvertedToIdentifier(), leadingTrivia, token.text());
}
export function emptyToken(kind: SyntaxKind, fullStart: number): ISyntaxToken {
return new EmptyToken(kind, fullStart);
}
class EmptyToken implements ISyntaxToken {
public _primaryExpressionBrand: any; public _memberExpressionBrand: any; public _leftHandSideExpressionBrand: any; public _postfixExpressionBrand: any; public _unaryExpressionBrand: any; public _expressionBrand: any; public _typeBrand: any; public _nameBrand: any; public _propertyAssignmentBrand: any; public _propertyNameBrand: any;
public parent: ISyntaxElement;
public childCount: number;
constructor(public kind: SyntaxKind, private _fullStart: number) {
Debug.assert(!isNaN(_fullStart));
}
public setFullStart(fullStart: number): void {
this._fullStart = fullStart;
}
public childAt(index: number): ISyntaxElement { throw Errors.invalidOperation() }
public clone(): ISyntaxToken {
return new EmptyToken(this.kind, this._fullStart);
}
// Empty tokens are never incrementally reusable.
public isIncrementallyUnusable() { return true; }
public isKeywordConvertedToIdentifier() {
return false;
}
public fullWidth() { return 0; }
public fullStart(): number { return this._fullStart; }
public text() { return ""; }
public fullText(): string { return ""; }
public hasLeadingTrivia() { return false; }
public hasLeadingNewLine() { return false; }
public hasLeadingComment() { return false; }
public hasLeadingSkippedToken() { return false; }
public leadingTriviaWidth() { return 0; }
public leadingTrivia(): ISyntaxTriviaList { return Syntax.emptyTriviaList; }
}
EmptyToken.prototype.childCount = 0;
class RealizedToken implements ISyntaxToken {
public _primaryExpressionBrand: any; public _memberExpressionBrand: any; public _leftHandSideExpressionBrand: any; public _postfixExpressionBrand: any; public _unaryExpressionBrand: any; public _expressionBrand: any; public _typeBrand: any; public _nameBrand: any; public _propertyAssignmentBrand: any; public _propertyNameBrand: any;
private _isKeywordConvertedToIdentifier: boolean;
private _leadingTrivia: ISyntaxTriviaList;
private _text: string;
public parent: ISyntaxElement;
public childCount: number;
constructor(private _fullStart: number,
public kind: SyntaxKind,
isKeywordConvertedToIdentifier: boolean,
leadingTrivia: ISyntaxTriviaList,
text: string) {
Debug.assert(!isNaN(_fullStart));
this._isKeywordConvertedToIdentifier = isKeywordConvertedToIdentifier;
this._text = text;
this._leadingTrivia = leadingTrivia.clone();
if (!this._leadingTrivia.isShared()) {
this._leadingTrivia.parent = this;
}
}
public setFullStart(fullStart: number): void {
this._fullStart = fullStart;
}
public childAt(index: number): ISyntaxElement { throw Errors.invalidOperation() }
public clone(): ISyntaxToken {
return new RealizedToken(this._fullStart, this.kind, this._isKeywordConvertedToIdentifier, this._leadingTrivia, this._text);
}
// Realized tokens are created from the parser. They are *never* incrementally reusable.
public isIncrementallyUnusable() { return true; }
public isKeywordConvertedToIdentifier() {
return this._isKeywordConvertedToIdentifier;
}
public fullStart(): number { return this._fullStart; }
public fullWidth(): number { return this._leadingTrivia.fullWidth() + this._text.length; }
public text(): string { return this._text; }
public fullText(): string { return this._leadingTrivia.fullText() + this.text(); }
public hasLeadingTrivia(): boolean { return this._leadingTrivia.count() > 0; }
public hasLeadingNewLine(): boolean { return this._leadingTrivia.hasNewLine(); }
public hasLeadingComment(): boolean { return this._leadingTrivia.hasComment(); }
public hasLeadingSkippedToken(): boolean { return this._leadingTrivia.hasSkippedToken(); }
public leadingTrivia(): ISyntaxTriviaList { return this._leadingTrivia; }
public leadingTriviaWidth(): number { return this._leadingTrivia.fullWidth(); }
}
RealizedToken.prototype.childCount = 0;
class ConvertedKeywordToken implements ISyntaxToken {
public _primaryExpressionBrand: any; public _memberExpressionBrand: any; public _leftHandSideExpressionBrand: any; public _postfixExpressionBrand: any; public _unaryExpressionBrand: any; public _expressionBrand: any; public _typeBrand: any; public _nameBrand: any; public _propertyAssignmentBrand: any; public _propertyNameBrand: any;
public parent: ISyntaxElement;
public kind: SyntaxKind;
public childCount: number;
constructor(private underlyingToken: ISyntaxToken) {
}
public setFullStart(fullStart: number): void {
this.underlyingToken.setFullStart(fullStart);
}
public childAt(index: number): ISyntaxElement { throw Errors.invalidOperation() }
public fullStart(): number {
return this.underlyingToken.fullStart();
}
public fullWidth(): number {
return this.underlyingToken.fullWidth();
}
public text(): string {
return this.underlyingToken.text();
}
private syntaxTreeText(text: ISimpleText) {
var result = text || syntaxTree(this).text;
Debug.assert(result);
return result;
}
public fullText(text?: ISimpleText): string {
return this.underlyingToken.fullText(this.syntaxTreeText(text));
}
public hasLeadingTrivia(): boolean { return this.underlyingToken.hasLeadingTrivia(); }
public hasLeadingNewLine(): boolean { return this.underlyingToken.hasLeadingNewLine(); }
public hasLeadingComment(): boolean { return this.underlyingToken.hasLeadingComment(); }
public hasLeadingSkippedToken(): boolean { return this.underlyingToken.hasLeadingSkippedToken(); }
public leadingTrivia(text?: ISimpleText): ISyntaxTriviaList {
var result = this.underlyingToken.leadingTrivia(this.syntaxTreeText(text));
result.parent = this;
return result;
}
public leadingTriviaWidth(text?: ISimpleText): number {
return this.underlyingToken.leadingTriviaWidth(this.syntaxTreeText(text));
}
public isKeywordConvertedToIdentifier(): boolean {
return true;
}
public isIncrementallyUnusable(): boolean {
// We're incrementally unusable if our underlying token is unusable.
// For example, we may have: this.public \
// In this case we will keyword converted to an identifier that is still unusable because
// it has a trailing skipped token.
return this.underlyingToken.isIncrementallyUnusable();
}
public clone(): ISyntaxToken {
return new ConvertedKeywordToken(this.underlyingToken);
}
}
ConvertedKeywordToken.prototype.kind = SyntaxKind.IdentifierName;
ConvertedKeywordToken.prototype.childCount = 0;
} | the_stack |
import OperationLog, { getOperationIndex } from "./OperationLog";
import getElementOperationLogMapping from "./getHtmlNodeOperationLogMapping";
import getHtmlNodeOperationLogMapping from "./getHtmlNodeOperationLogMapping";
import initDomInspectionUI from "./initDomInspectionUI";
import KnownValues from "./KnownValues";
import { ExecContext } from "./ExecContext";
import operations from "../operations";
import { SKIP_TRACKING, VERIFY, KEEP_LOGS_IN_MEMORY } from "../config";
import * as FunctionNames from "../FunctionNames";
import { initLogging, consoleCount, consoleLog, consoleError } from "./logging";
import { getStoreLogsWorker } from "./storeLogsWorker";
import * as OperationTypes from "../OperationTypes";
import { mapPageHtml } from "../mapPageHtml";
import mapInnerHTMLAssignment from "../operations/domHelpers/mapInnerHTMLAssignment";
import { CreateOperationLogArgs, ValueTrackingValuePair } from "../types";
import { traverseObject } from "../traverseObject";
import * as objectPath from "object-path";
import { getShortOperationName } from "../names";
const accessToken = "ACCESS_TOKEN_PLACEHOLDER";
var global = Function("return this")();
global.__didInitializeDataFlowTracking = true;
global.getElementOperationLogMapping = getElementOperationLogMapping;
let knownValues = new KnownValues();
// Make sure to use native methods in case browser methods get
// overwritten (e.g. NewRelic instrumentation does it)
// (only matters if we're not in the web worker)
let fetch = knownValues.getValue("fetch");
initLogging(knownValues);
const startTime = new Date();
setTimeout(checkDone, 20);
function checkDone() {
if (typeof document === "undefined") {
return;
}
const done =
document.querySelector(".todo-list li") ||
document.querySelector(".list-card-title");
if (done) {
const doneTime = new Date();
consoleLog("#####################################");
consoleLog("#####################################");
consoleLog("#####################################");
consoleLog("#####################################");
consoleLog("#####################################");
consoleLog("#####################################");
consoleLog(
"DONE",
"timeTaken: " + (doneTime.valueOf() - startTime.valueOf()) / 1000 + "s"
);
worker.postMessage({ showDoneMessage: true });
} else {
setTimeout(checkDone, 20);
}
}
function nodeHttpReq({ port, path, headers, bodyString, method }) {
return new Promise(resolve => {
/* eval, otherwise webpack will replace it*/
const https = eval(`require("http")`);
const options = {
hostname: "localhost",
port: port,
path: path,
method,
headers: {
...headers,
"Content-Type": "application/json"
}
};
const req = https.request(options, res => {
console.log(`statusCode: ${res.statusCode}`);
let resStr = "";
res.on("data", d => {
console.log(d.toString());
resStr += d.toString();
});
res.on("end", d => {
console.log("req end");
resolve(resStr);
});
});
req.on("error", error => {
console.error(error);
});
if (bodyString) {
req.write(bodyString);
}
req.end();
});
}
let backendPort = "BACKEND_PORT_PLACEHOLDER";
let backendOriginWithoutPort = "BACKEND_ORIGIN_WITHOUT_PORT_PLACEHOLDER";
let requestQueueDirectory;
if (global.fromJSIsNode) {
const cmd = `node -e "eval(decodeURIComponent(\\"${encodeURIComponent(
nodeHttpReq.toString() +
`;nodeHttpReq({port: ${backendPort}, path: '/sessionInfo', headers: {}, method: 'GET'}).then(r => console.log('RES_'+r+'_RES'));`
)}\\"))"`;
const r = eval("require('child_process')").execSync(cmd);
const sessionInfo = JSON.parse(r.toString().match(/RES_(.*)_RES/)[1]);
console.log({ sessionInfo });
requestQueueDirectory = sessionInfo.requestQueueDirectory;
}
let fs;
let fsProperties;
if (global.fromJSIsNode) {
fs = eval("require('fs')");
fsProperties = { ...fs };
}
function setFsProperties(fsProperties) {
Object.keys(fsProperties).forEach(propertyName => {
let value = fsProperties[propertyName];
if (typeof value === "function") {
fs[propertyName] = fsProperties[propertyName];
}
});
}
function nodePost({ port, path, headers, bodyString }) {
if (requestQueueDirectory) {
// graceful-fs patches some methods and adding tracking data
// as part of saving stuff breaks the normal flow...
// (e.g. because lastmemberexpressionobject is not right any more)
let fsPropertiesBefore = { ...fs };
setFsProperties(fsProperties);
let opCount = ctx.countOperations(() => {
fs.writeFileSync(
requestQueueDirectory +
"/" +
new Date().valueOf() +
"_" +
Math.round(Math.random() * 1000) +
".json",
path + "\n" + bodyString
);
});
if (opCount > 0) {
console.log(
`Did ${opCount} operations during writeFileSync, maybe something is patched?`
);
}
setFsProperties(fsPropertiesBefore);
return Promise.resolve({});
}
return nodeHttpReq({ port, path, headers, bodyString, method: "POST" });
}
function makePostToBE({ accessToken, fetch }) {
return function postToBE(endpoint, data, statsCallback = function(stats) {}) {
const stringifyStart = new Date();
let body = data;
let bodyIsString = typeof body === "string";
if (!bodyIsString) {
console.time("stringify");
data.pageSessionId = global["fromJSPageSessionId"];
body = JSON.stringify(data);
console.timeEnd("stringify");
}
console.log("body len in mb", body.length / 1024 / 1024);
const stringifyEnd = new Date();
if (endpoint === "/storeLogs") {
statsCallback({
bodyLength: body.length,
stringifyTime: stringifyEnd.valueOf() - stringifyStart.valueOf()
});
}
const headers = {
Accept: "application/json",
Authorization: accessToken
};
if (!bodyIsString) {
headers["Content-Type"] = "application/json";
}
let p;
if (global.fromJSIsNode) {
p = nodePost({
port: backendPort,
path: endpoint,
bodyString: body,
headers
});
} else {
const url = backendOriginWithoutPort + ":" + backendPort + endpoint;
p = fetch(url, {
method: "POST",
headers: global.fromJSIsNode ? headers : new Headers(headers),
body: body
});
}
return p;
};
}
const postToBE = makePostToBE({ accessToken, fetch });
let logQueue = [];
global["__debugFromJSLogQueue"] = () => logQueue;
let evalScriptQueue = [];
let eventQueue = [];
let luckyMatchQueue = [];
let worker: Worker | null = null;
// temporarily disable worker because i think lighthouse runs stuff in isolated envs
// and it means hundreds of workers get created rather than always using same one?
// try {
// getStoreLogsWorker({
// makePostToBE,
// accessToken
// });
// }catch(err){
// console.log("Create worker error, should be ok though", err.message)
// }
let inProgressSendLogsRequests = 0;
async function sendLogsToServer() {
if (logQueue.length === 0 && evalScriptQueue.length == 0) {
return;
}
// const data = {
// logs: logQueue,
// evalScripts: evalScriptQueue,
// events: eventQueue
// };
let data = "";
data += JSON.stringify(evalScriptQueue);
data += "\n";
data += JSON.stringify(eventQueue);
data += "\n";
data += JSON.stringify(luckyMatchQueue);
data += "\n";
for (const item of logQueue) {
data += item[0] + "\n" + item[1] + "\n";
}
logQueue = [];
evalScriptQueue = [];
eventQueue = [];
luckyMatchQueue = [];
if (worker) {
// Doing this means the data will be cloned, but it seems to be
// reasonably fast anyway
// Creating the json and making the request in the main thread is super slow!
console.time("postMessage");
worker.postMessage(data);
console.timeEnd("postMessage");
} else {
// consoleLog(
// "Can't create worker (maybe already inside a web worker?), will send request in normal thread"
// );
inProgressSendLogsRequests++;
if (inProgressSendLogsRequests > 2) {
console.log({ inProgressSendLogsRequests });
}
await postToBE("/storeLogs", data);
inProgressSendLogsRequests--;
}
}
// If page laods quickly try to send data to BE soon, later on wait
// 1s between requests
setTimeout(sendLogsToServer, 200);
setTimeout(sendLogsToServer, 400);
setInterval(sendLogsToServer, 1000);
function remotelyStoreLog(logIndex, logString) {
logQueue.push([logIndex, logString]);
}
global["__fromJSWaitForSendLogsAndExitNodeProcess"] = async function() {
console.log("__fromJSWaitForSendLogsAndExitNodeProcess");
sendLogsToServer();
while (inProgressSendLogsRequests > 0) {
console.log({ inProgressSendLogsRequests });
await new Promise(resolve => setTimeout(resolve, 100));
}
eval("process.exit()");
};
declare var __storeLog;
const storeLog =
typeof __storeLog !== "undefined" ? __storeLog : remotelyStoreLog;
let skipTracking = SKIP_TRACKING;
let lastOperationType = null;
function createOperationLog(args: CreateOperationLogArgs, op, index) {
if (skipTracking) {
return null;
}
var log = OperationLog.createAtRuntime(args, knownValues, op);
storeLog(index, JSON.stringify(log));
if (KEEP_LOGS_IN_MEMORY) {
// Normally we just store the numbers, but it's useful for
// debugging to be able to view the log object
global["__debugAllLogs"] = global["__debugAllLogs"] || {};
global["__debugAllLogs"][log.index] = log;
}
}
// Used to speed up slow parts of a program, e.g. for the Lighthouse
// JSON parser or other buffer processing logic
// ----
// Counter used to handle nested function calls that disable at start and end
let skipTrackingCounter = 0;
global["__FromJSDisableCollectTrackingData"] = function(label) {
skipTrackingCounter++;
console.log("Disable FromJS tracking", { skipTrackingCounter, label });
skipTracking = true;
};
global["__FromJSEnableCollectTrackingData"] = function(label) {
skipTrackingCounter--;
console.log("Enable FromJS tracking", { skipTrackingCounter, label });
if (skipTrackingCounter === 0) {
skipTracking = SKIP_TRACKING;
}
};
if (KEEP_LOGS_IN_MEMORY) {
global["__debugLookupLog"] = function(logId, currentDepth = 0) {
try {
var log = JSON.parse(JSON.stringify(global["__debugAllLogs"][logId]));
if (currentDepth < 12) {
const newArgs = {};
Object.keys(log.args).forEach(key => {
newArgs[key] = global["__debugLookupLog"](
log.args[key],
currentDepth + 1
);
});
log.args = newArgs;
}
if (currentDepth < 12 && log.extraArgs) {
const newExtraArgs = {};
Object.keys(log.extraArgs).forEach(key => {
newExtraArgs[key] = global["__debugLookupLog"](
log.extraArgs[key],
currentDepth + 1
);
});
log.extraArgs = newExtraArgs;
}
return log;
} catch (err) {
return logId;
}
};
}
global[FunctionNames.getGlobal] = function() {
return global;
};
var argTrackingInfo = null;
var functionContextTrackingValue = null;
global["__fromJSGetTrackingIndex"] = function(value) {
return global[FunctionNames.getFunctionArgTrackingInfo](0);
};
global[FunctionNames.getFunctionArgTrackingInfo] = function getArgTrackingInfo(
index
) {
if (!argTrackingInfo) {
// this can happen when function is invoked without callexpression op,
// e.g. when it's a callback argument to a native api call
// TODO: return some kind of tracking value here ("untracked argument")
// ideally also include a loc
if (VERIFY) {
consoleLog("no arg tracking info...");
}
return undefined;
}
if (index === undefined) {
return argTrackingInfo;
}
return argTrackingInfo[index];
};
global[FunctionNames.getFunctionContextTrackingValue] = function() {
return functionContextTrackingValue;
};
global.getTrackingAndNormalValue = function(value) {
return {
normal: value,
tracking: argTrackingInfo[0]
};
};
// don't think this is needed, only used in demo with live code ediotr i think
global.inspect = function(value) {
global.inspectedValue = {
normal: value,
tracking: argTrackingInfo[0]
};
};
initDomInspectionUI(backendPort, backendOriginWithoutPort);
global["__getHtmlNodeOperationLogMapping"] = getHtmlNodeOperationLogMapping;
global["fromJSPageSessionId"] = (
Math.random().toString() +
"_" +
Math.random().toString()
).replace(/\./g, "");
global.fromJSInspect = function(value: any, charIndex: number) {
let logId;
if (!argTrackingInfo && typeof value === "number") {
if (charIndex) {
throw Error("Not supported yet");
}
logId = value;
} else if (value instanceof Node) {
const mapping = getHtmlNodeOperationLogMapping(value);
consoleLog({ mapping });
postToBE("/inspectDOM", { ...mapping, charIndex });
} else {
if (charIndex) {
throw Error("Not supported yet");
}
logId = argTrackingInfo[0];
}
if (window["onFromJSInspect"]) {
window["onFromJSInspect"]();
}
return postToBE("/inspect", {
logId
});
};
function getTrackingPropName(propName) {
if (VERIFY) {
try {
if (parseFloat(propName) > 200) {
consoleLog(
"tracking array index greater than 200...1) perf issue, 2) possibly some kind of infinite loop"
);
}
} catch (err) {}
}
// note: might be worth using Map instead and seeing how perf is affected
if (typeof propName === "symbol") {
return propName;
} else {
// "_" prefix because to avoid conflict with normal object methods,
// e.g. there used to be problems when getting tracking value for "constructor" prop
return "_" + propName;
}
}
function trackPromiseResolutionValue(promise, trackingValue) {
// todo: map<promise, trackingvalue> might be better
// if the program for some reason inspects the promise properties?
if (!promise) {
console.log("No promise passed into trackPromiseResolutionValue!");
return;
}
promise["_resTrackingValue"] = trackingValue;
}
function getPromiseResolutionTrackingValue(promise) {
if (!promise) {
console.log("No promise passed into getPromiseResolutionTrackingValue!");
return;
}
return promise["_resTrackingValue"];
}
const objTrackingMap = new WeakMap();
global["__debugObjTrackingMap"] = objTrackingMap;
function trackObjectPropertyAssignment(
obj,
propName,
propertyValueTrackingValue,
propertyNameTrackingValue = null
) {
if (!propertyNameTrackingValue && VERIFY) {
consoleCount("no propertyNameTrackingValue");
}
var objectPropertyTrackingInfo = objTrackingMap.get(obj);
if (!objectPropertyTrackingInfo) {
objectPropertyTrackingInfo = {};
objTrackingMap.set(obj, objectPropertyTrackingInfo);
}
if (
typeof propertyValueTrackingValue !== "number" &&
!!propertyValueTrackingValue
) {
console.log("Tracking value is not a number:", propertyValueTrackingValue);
debugger;
}
objectPropertyTrackingInfo[getTrackingPropName(propName)] = {
value: propertyValueTrackingValue,
name: propertyNameTrackingValue
};
}
function getObjectPropertyTrackingValues(obj, propName) {
var objectPropertyTrackingInfo = objTrackingMap.get(obj);
if (!objectPropertyTrackingInfo) {
return undefined;
}
const trackingValues =
objectPropertyTrackingInfo[getTrackingPropName(propName)];
if (!trackingValues) {
return undefined;
}
return trackingValues;
}
function getObjectPropertyValueTrackingValue(obj, propName) {
const trackingValues = getObjectPropertyTrackingValues(obj, propName);
if (trackingValues === undefined) {
return undefined;
}
return trackingValues.value;
}
global["getObjectPropertyTrackingValue"] = getObjectPropertyValueTrackingValue;
function getObjectPropertyNameTrackingValue(obj, propName) {
const trackingValues = getObjectPropertyTrackingValues(obj, propName);
if (trackingValues === undefined) {
return undefined;
}
return trackingValues.name;
}
global[
FunctionNames.getObjectPropertyNameTrackingValue
] = getObjectPropertyNameTrackingValue;
var lastMemberExpressionObjectValue = null;
var lastMemberExpressionObjectTrackingValue = null;
global[FunctionNames.getLastMemberExpressionObject] = function() {
return [
lastMemberExpressionObjectValue,
lastMemberExpressionObjectTrackingValue
];
};
global[FunctionNames.getEmptyTrackingInfo] = function(
type,
loc,
result = undefined
) {
let index = getOperationIndex();
let logData: any = {
operation: "emptyTrackingInfo",
result,
args: {},
runtimeArgs: { type },
astArgs: {},
loc
};
createOperationLog(logData, operations["emptyTrackingInfo"], index);
return index;
};
global[FunctionNames.expandArrayForArrayPattern] = function(
arr,
loc,
type,
namedParamCount
) {
if (!Array.isArray(arr)) {
// e.g. Maps or arguments objects
arr = Array.from(arr);
}
if (type === "forOf") {
return arr.map(val => {
return global[FunctionNames.expandArrayForArrayPattern](
val,
loc,
"forOf_element",
namedParamCount
);
});
}
const resultArr = [];
const restResult = [];
arr.forEach((value, i) => {
const trackingValue = ctx.getObjectPropertyTrackingValue(arr, i);
const newTrackingValue = ctx.createOperationLog({
operation: ctx.operationTypes.arrayPattern,
args: {
value: [value, trackingValue]
},
astArgs: {},
result: value,
loc: loc
});
if (i < namedParamCount) {
resultArr.push(value);
resultArr.push(newTrackingValue);
} else {
restResult.push(value);
ctx.trackObjectPropertyAssignment(
restResult,
i - namedParamCount,
newTrackingValue
);
}
});
while (namedParamCount > resultArr.length / 2) {
resultArr.push(undefined);
}
resultArr.push(
global[FunctionNames.getEmptyTrackingInfo](
"arrayPatternExpansion_rest",
loc
)
);
resultArr.push(restResult);
return resultArr;
};
global[FunctionNames.expandArrayForSpreadElement] = function(arr) {
if (!Array.isArray(arr)) {
// Map or arguments object
arr = Array.from(arr);
}
return arr.map((elem, i) => {
return [elem, ctx.getObjectPropertyTrackingValue(arr, i)];
});
};
const MAX_TRACKED_ARRAY_INDEX = 10;
var lastReturnStatementResult = null;
const memoValues = {};
global[FunctionNames.setMemoValue] = function(key, value, trackingValue) {
memoValues[key] = { value, trackingValue };
setLastOpTrackingResult(trackingValue);
if (VERIFY) {
validateTrackingValue(trackingValue);
}
return value;
};
global[FunctionNames.getMemoArray] = function(key) {
const memo = memoValues[key];
return [memo.value, memo.trackingValue];
};
global[FunctionNames.getMemoValue] = function(key) {
return memoValues[key].value;
};
global[FunctionNames.getMemoTrackingValue] = function(key) {
return memoValues[key].trackingValue;
};
function validateTrackingValue(trackingValue) {
if (!!trackingValue && typeof trackingValue !== "number") {
debugger;
throw Error("eee");
}
}
function setLastOpTrackingResult(trackingValue) {
if (VERIFY) {
validateTrackingValue(trackingValue);
}
lastOpTrackingResult = trackingValue;
}
const ctx: ExecContext = {
operationTypes: OperationTypes,
getObjectPropertyTrackingValue: getObjectPropertyValueTrackingValue,
getObjectPropertyNameTrackingValue,
trackObjectPropertyAssignment,
trackPromiseResolutionValue,
getPromiseResolutionTrackingValue,
hasInstrumentationFunction: typeof global["__fromJSEval"] === "function",
createOperationLog: function(args) {
let index = getOperationIndex();
const op = operations[args.operation];
args.operation = getShortOperationName(args.operation);
createOperationLog(args, op, index);
return index;
},
createArrayIndexOperationLog(index, loc) {
if (index > MAX_TRACKED_ARRAY_INDEX) {
// Just too much cost tracking this, and not much value
return null;
}
return ctx.createOperationLog({
operation: ctx.operationTypes.arrayIndex,
result: index,
loc: loc
});
},
knownValues,
global,
registerEvalScript(evalScript) {
// store code etc for eval'd code
evalScriptQueue.push(evalScript);
},
registerEvent(event) {
// events like file writes
eventQueue.push(event);
},
objectHasPropertyTrackingData(obj) {
return !!objTrackingMap.get(obj);
},
getEmptyTrackingInfo(type, loc, result = undefined) {
return global[FunctionNames.getEmptyTrackingInfo](type, loc, result);
},
getCurrentTemplateLiteralTrackingValues() {
return getCurrentTemplateLiteralTrackingValues();
},
get lastOpTrackingResult() {
return lastOpTrackingResult;
},
get lastOpTrackingResultWithoutResetting() {
return lastOpTrackingResultWithoutResetting;
},
get lastReturnStatementResult() {
return lastReturnStatementResult;
},
set lastReturnStatementResult(val) {
lastReturnStatementResult = val;
},
set lastMemberExpressionResult([normal, tracking]) {
lastMemberExpressionObjectValue = normal;
lastMemberExpressionObjectTrackingValue = tracking;
},
set argTrackingInfo(info) {
if (VERIFY && info) {
info.forEach(trackingValue => validateTrackingValue(trackingValue));
}
argTrackingInfo = info;
},
set functionContextTrackingValue(tv: number) {
functionContextTrackingValue = tv;
},
get lastOperationType() {
return lastOperationType;
},
countOperations(fn) {
let before = opExecCount;
fn();
return opExecCount - before;
}
};
var lastOpValueResult = null;
var lastOpTrackingResult = null;
let lastOpTrackingResultWithoutResetting = null;
let opExecCount = 0;
function makeDoOperation(opName: string, op) {
const opExec = op.exec;
const shortName = getShortOperationName(opName);
return function ___op(objArgs, astArgs, loc) {
let index = getOperationIndex();
let logData: any = {
operation: shortName,
args: objArgs,
astArgs: astArgs,
loc,
index
};
var ret = opExec(objArgs, astArgs, ctx, logData);
opExecCount++;
logData.result = ret;
createOperationLog(logData, op, index);
lastOpValueResult = ret;
lastOpTrackingResultWithoutResetting = index;
setLastOpTrackingResult(index);
lastOperationType = opName;
if (logQueue.length > 200000) {
// avoid running out of memory
sendLogsToServer();
}
return ret;
};
}
global[FunctionNames.doOperation] = function ___op(
opName: string,
objArgs,
astArgs,
loc
) {
return global["__" + opName](objArgs, astArgs, loc);
};
Object.keys(operations).forEach(opName => {
const op = operations[opName];
const doOpFunction = makeDoOperation(opName, op);
// The object creation in so many places is expensive
// so some simple ops have a shorthand function that
// is called instead of __op and calls through to __op
if (op.shorthand) {
global[op.shorthand.fnName] = op.shorthand.getExec(doOpFunction);
}
global["__" + opName] = doOpFunction;
});
global[FunctionNames.getLastOperationValueResult] = function getLastOp() {
var ret = lastOpValueResult;
lastOpValueResult = null;
return ret;
};
global[FunctionNames.getLastOperationTrackingResult] = function getLastOp() {
if (VERIFY) {
validateTrackingValue(lastOpTrackingResult);
}
var ret = lastOpTrackingResult;
lastOpTrackingResult = null;
return ret;
};
global[
FunctionNames.getLastOperationTrackingResultWithoutResetting
] = function getLastOp() {
if (VERIFY) {
validateTrackingValue(lastOpTrackingResult);
}
return lastOpTrackingResult;
};
let currentTemplateLiteralIndex = 1;
let allTemplateLiteralTrackingValues = {};
function getCurrentTemplateLiteralTrackingValues() {
if (!allTemplateLiteralTrackingValues[currentTemplateLiteralIndex]) {
allTemplateLiteralTrackingValues[currentTemplateLiteralIndex] = [];
}
return allTemplateLiteralTrackingValues[currentTemplateLiteralIndex];
}
function resetCurrentTemplateLiteralTrackingValues() {
allTemplateLiteralTrackingValues[currentTemplateLiteralIndex] = [];
}
global[FunctionNames.saveTemplateLiteralExpressionTrackingValue] = function(
expressionValue
) {
getCurrentTemplateLiteralTrackingValues().push({
trackingValue: lastOpTrackingResultWithoutResetting,
valueLength: (expressionValue + "").length
});
return expressionValue;
};
global[FunctionNames.exitTemplateLiteralAndGetTrackingValues] = function() {
const ret = getCurrentTemplateLiteralTrackingValues();
resetCurrentTemplateLiteralTrackingValues();
currentTemplateLiteralIndex--;
return ret;
};
global[FunctionNames.enterTemplateLiteral] = function() {
currentTemplateLiteralIndex++;
};
// note: would be good to make this spec complient, e.g. see how babel does it
// e.g. handle non own properties better
global[FunctionNames.provideObjectPatternTrackingValues] = function(
obj,
properties
) {
properties = properties.map(arr => {
let pathParts = arr[1].split(".");
return {
name: arr[0],
nameInPath: pathParts[pathParts.length - 1],
path: arr[1],
isRest: !!arr[2],
parentPath: pathParts.slice(0, -1).join(".")
};
});
let propertiesByParentPath = {};
properties.forEach(p => {
propertiesByParentPath[p.parentPath] =
propertiesByParentPath[p.parentPath] || [];
propertiesByParentPath[p.parentPath].push(p);
});
const res = {};
Object.keys(propertiesByParentPath).forEach(parentPath => {
let props = propertiesByParentPath[parentPath];
const subObj = objectPath.withInheritedProps.get(obj, parentPath);
let rest = { ...subObj };
let subRes = parentPath ? {} : res;
props.forEach(prop => {
if (prop.isRest) {
} else {
objectPath.set(
subRes,
prop.nameInPath,
objectPath.withInheritedProps.get(obj, prop.path)
);
let trackingValue = ctx.getObjectPropertyTrackingValue(
subObj,
prop.nameInPath
);
// The tracking values are set directly on res
objectPath.set(res, prop.name + "___tv", trackingValue);
delete rest[prop.nameInPath];
}
});
props.forEach(prop => {
if (prop.isRest) {
// !!!!! I THINK OBJECT.KEYS HERE MEAN WE MISS SOME NON OWN PROPERTIES !!!!
Object.keys(rest).forEach(key => {
objectPath.set(
subRes,
key,
objectPath.withInheritedProps.get(
obj,
(parentPath ? parentPath + "." : "") + key
)
);
});
}
});
if (parentPath) {
objectPath.set(res, parentPath, subRes);
}
});
return res;
};
global["__fromJSMaybeMapInitialPageHTML"] = function() {
if (!global["__fromJSInitialPageHtml"]) {
return;
}
if (global["__fromJSDidMapInitialPageHTML"]) {
return;
}
const initialPageHtml = global["__fromJSInitialPageHtml"];
if (document.body) {
// If there's not head tag these items are put in the body and would
// otherwise affect mapping, so remove them before we do the mapping
document
.querySelectorAll("[data-fromjs-remove-before-initial-html-mapping]")
.forEach(el => el.remove());
const tvIndex = window["__fromJSInitialPageHtmlLogIndex"];
createOperationLog(
{
operation: OperationTypes.initialPageHtml,
args: {},
runtimeArgs: {
url: location.href
},
result: initialPageHtml
},
operations[OperationTypes.initialPageHtml],
tvIndex
);
mapPageHtml(document, initialPageHtml, tvIndex, "initial page html");
global["__fromJSDidMapInitialPageHTML"] = true;
}
};
global["__fromJSMaybeMapInitialPageHTML"]();
global["__fromJSCallFunctionWithTrackingChainInterruption"] = function(fn) {
const ret = global[FunctionNames.doOperation](
"callExpression",
[[fn, null], [this, null], []],
{}
);
return ret;
};
global["__fromJSRegisterLuckyMatch"] = function(value) {
let valueTv = global[FunctionNames.getFunctionArgTrackingInfo](0);
luckyMatchQueue.push({
value,
trackingValue: valueTv
});
}; | the_stack |
import * as React from "react";
import * as ReactDOM from "react-dom";
import { IInspectorOptions } from "babylonjs/Debug/debugLayer";
import { Nullable } from "babylonjs/types";
import { Observable, Observer } from "babylonjs/Misc/observable";
import { EngineStore } from "babylonjs/Engines/engineStore";
import { Scene } from "babylonjs/scene";
import { SceneLoader } from "babylonjs/Loading/sceneLoader";
import { ActionTabsComponent } from "./components/actionTabs/actionTabsComponent";
import { SceneExplorerComponent } from "./components/sceneExplorer/sceneExplorerComponent";
import { EmbedHostComponent } from "./components/embedHost/embedHostComponent";
import { PropertyChangedEvent } from "./components/propertyChangedEvent";
import { GlobalState } from "./components/globalState";
interface IInternalInspectorOptions extends IInspectorOptions {
popup: boolean;
original: boolean;
explorerWidth?: string;
inspectorWidth?: string;
embedHostWidth?: string;
}
export class Inspector {
private static _SceneExplorerHost: Nullable<HTMLElement>;
private static _ActionTabsHost: Nullable<HTMLElement>;
private static _EmbedHost: Nullable<HTMLElement>;
private static _NewCanvasContainer: Nullable<HTMLElement>;
private static _SceneExplorerWindow: Window;
private static _ActionTabsWindow: Window;
private static _EmbedHostWindow: Window;
private static _Scene: Scene;
private static _OpenedPane = 0;
private static _OnBeforeRenderObserver: Nullable<Observer<Scene>>;
public static OnSelectionChangeObservable = new Observable<any>();
public static OnPropertyChangedObservable = new Observable<PropertyChangedEvent>();
private static _GlobalState = new GlobalState();
public static MarkLineContainerTitleForHighlighting(title: string) {
this._GlobalState.selectedLineContainerTitles = [];
this._GlobalState.selectedLineContainerTitles.push(title);
}
public static MarkMultipleLineContainerTitlesForHighlighting(titles: string[]) {
this._GlobalState.selectedLineContainerTitles = [];
this._GlobalState.selectedLineContainerTitles.push(...titles);
}
private static _CopyStyles(sourceDoc: HTMLDocument, targetDoc: HTMLDocument) {
for (var index = 0; index < sourceDoc.styleSheets.length; index++) {
var styleSheet: any = sourceDoc.styleSheets[index];
try {
if (styleSheet.cssRules) {
// for <style> elements
const newStyleEl = sourceDoc.createElement("style");
for (var cssRule of styleSheet.cssRules) {
// write the text of each rule into the body of the style element
newStyleEl.appendChild(sourceDoc.createTextNode(cssRule.cssText));
}
targetDoc.head!.appendChild(newStyleEl);
} else if (styleSheet.href) {
// for <link> elements loading CSS from a URL
const newLinkEl = sourceDoc.createElement("link");
newLinkEl.rel = "stylesheet";
newLinkEl.href = styleSheet.href;
targetDoc.head!.appendChild(newLinkEl);
}
} catch (e) {
}
}
}
private static _CreateSceneExplorer(scene: Scene, options: IInternalInspectorOptions, parentControlExplorer: Nullable<HTMLElement>) {
// Duplicating the options as they can be different for each pane
if (options.original) {
options = {
original: false,
popup: options.popup,
overlay: options.overlay,
showExplorer: options.showExplorer,
showInspector: options.showInspector,
embedMode: options.embedMode,
handleResize: options.handleResize,
enablePopup: options.enablePopup,
enableClose: options.enableClose,
explorerExtensibility: options.explorerExtensibility,
};
}
// Prepare the scene explorer host
if (parentControlExplorer) {
this._SceneExplorerHost = parentControlExplorer.ownerDocument!.createElement("div");
this._SceneExplorerHost.id = "scene-explorer-host";
this._SceneExplorerHost.style.width = options.explorerWidth || "auto";
if (!options.popup) {
parentControlExplorer.insertBefore(this._SceneExplorerHost, this._NewCanvasContainer);
} else {
parentControlExplorer.appendChild(this._SceneExplorerHost);
}
if (!options.overlay) {
this._SceneExplorerHost.style.position = "relative";
}
}
// Scene
if (this._SceneExplorerHost) {
this._OpenedPane++;
const sceneExplorerElement = React.createElement(SceneExplorerComponent, {
scene,
globalState: this._GlobalState,
extensibilityGroups: options.explorerExtensibility,
noClose: !options.enableClose,
noExpand: !options.enablePopup,
popupMode: options.popup,
onPopup: () => {
ReactDOM.unmountComponentAtNode(this._SceneExplorerHost!);
this._RemoveElementFromDOM(this._SceneExplorerHost);
if (options.popup) {
this._SceneExplorerWindow.close();
}
options.popup = !options.popup;
options.showExplorer = true;
options.showInspector = false;
options.explorerWidth = options.popup ? "100%" : "300px";
Inspector.Show(scene, options);
},
onClose: () => {
ReactDOM.unmountComponentAtNode(this._SceneExplorerHost!);
Inspector._OpenedPane--;
this._RemoveElementFromDOM(this._SceneExplorerHost);
this._Cleanup();
if (options.popup) {
this._SceneExplorerWindow.close();
}
},
});
ReactDOM.render(sceneExplorerElement, this._SceneExplorerHost);
}
}
private static _CreateActionTabs(scene: Scene, options: IInternalInspectorOptions, parentControlActions: Nullable<HTMLElement>) {
options.original = false;
// Prepare the inspector host
if (parentControlActions) {
const host = parentControlActions.ownerDocument!.createElement("div");
host.id = "inspector-host";
host.style.width = options.inspectorWidth || "auto";
parentControlActions.appendChild(host);
this._ActionTabsHost = host;
if (!options.overlay) {
this._ActionTabsHost.style.position = "relative";
}
}
if (this._ActionTabsHost) {
this._OpenedPane++;
const actionTabsElement = React.createElement(ActionTabsComponent, {
globalState: this._GlobalState,
scene: scene,
noClose: !options.enableClose,
noExpand: !options.enablePopup,
popupMode: options.popup,
onPopup: () => {
ReactDOM.unmountComponentAtNode(this._ActionTabsHost!);
this._RemoveElementFromDOM(this._ActionTabsHost);
if (options.popup) {
this._ActionTabsWindow.close();
}
options.popup = !options.popup;
options.showExplorer = false;
options.showInspector = true;
options.inspectorWidth = options.popup ? "100%" : "300px";
Inspector.Show(scene, options);
},
onClose: () => {
ReactDOM.unmountComponentAtNode(this._ActionTabsHost!);
Inspector._OpenedPane--;
this._Cleanup();
this._RemoveElementFromDOM(this._ActionTabsHost);
if (options.popup) {
this._ActionTabsWindow.close();
}
},
initialTab: options.initialTab,
});
ReactDOM.render(actionTabsElement, this._ActionTabsHost);
}
}
private static _CreateEmbedHost(scene: Scene, options: IInternalInspectorOptions, parentControl: Nullable<HTMLElement>, onSelectionChangedObservable: Observable<string>) {
// Prepare the inspector host
if (parentControl) {
const host = parentControl.ownerDocument!.createElement("div");
host.id = "embed-host";
host.style.width = options.embedHostWidth || "auto";
parentControl.appendChild(host);
this._EmbedHost = host;
if (!options.overlay) {
this._EmbedHost.style.position = "relative";
}
}
if (this._EmbedHost) {
this._OpenedPane++;
const embedHostElement = React.createElement(EmbedHostComponent, {
globalState: this._GlobalState,
scene: scene,
extensibilityGroups: options.explorerExtensibility,
noExpand: !options.enablePopup,
noClose: !options.enableClose,
popupMode: options.popup,
onPopup: () => {
ReactDOM.unmountComponentAtNode(this._EmbedHost!);
if (options.popup) {
this._EmbedHostWindow.close();
}
this._RemoveElementFromDOM(this._EmbedHost);
options.popup = !options.popup;
options.embedMode = true;
options.showExplorer = true;
options.showInspector = true;
options.embedHostWidth = options.popup ? "100%" : "auto";
Inspector.Show(scene, options);
},
onClose: () => {
ReactDOM.unmountComponentAtNode(this._EmbedHost!);
this._OpenedPane = 0;
this._Cleanup();
this._RemoveElementFromDOM(this._EmbedHost);
if (options.popup) {
this._EmbedHostWindow.close();
}
},
initialTab: options.initialTab,
});
ReactDOM.render(embedHostElement, this._EmbedHost);
}
}
public static _CreatePopup(title: string, windowVariableName: string, width = 300, height = 800, lateBinding?: boolean) {
const windowCreationOptionsList = {
width: width,
height: height,
top: (window.innerHeight - width) / 2 + window.screenY,
left: (window.innerWidth - height) / 2 + window.screenX,
};
var windowCreationOptions = Object.keys(windowCreationOptionsList)
.map((key) => key + "=" + (windowCreationOptionsList as any)[key])
.join(",");
const popupWindow = window.open("", title, windowCreationOptions);
if (!popupWindow) {
return null;
}
const parentDocument = popupWindow.document;
// Font
const newLinkEl = parentDocument.createElement("link");
newLinkEl.rel = "stylesheet";
newLinkEl.href = "https://use.typekit.net/cta4xsb.css";
parentDocument.head!.appendChild(newLinkEl);
parentDocument.title = title;
parentDocument.body.style.width = "100%";
parentDocument.body.style.height = "100%";
parentDocument.body.style.margin = "0";
parentDocument.body.style.padding = "0";
let parentControl = parentDocument.createElement("div");
parentControl.style.width = "100%";
parentControl.style.height = "100%";
parentControl.style.margin = "0";
parentControl.style.padding = "0";
popupWindow.document.body.appendChild(parentControl);
this._CopyStyles(window.document, parentDocument);
if (lateBinding) {
setTimeout(() => {
// need this for late bindings
this._CopyStyles(window.document, parentDocument);
}, 0);
}
(this as any)[windowVariableName] = popupWindow;
return parentControl;
}
public static get IsVisible(): boolean {
return this._OpenedPane > 0;
}
public static EarlyAttachToLoader() {
if (!this._GlobalState.onPluginActivatedObserver) {
this._GlobalState.onPluginActivatedObserver = SceneLoader.OnPluginActivatedObservable.add((rawLoader) => {
this._GlobalState.resetGLTFValidationResults();
const loader = rawLoader as import("babylonjs-loaders/glTF/index").GLTFFileLoader;
if (loader.name === "gltf") {
this._GlobalState.prepareGLTFPlugin(loader);
}
});
}
}
public static Show(scene: Scene, userOptions: Partial<IInspectorOptions>) {
const options: IInternalInspectorOptions = {
original: true,
popup: false,
overlay: false,
showExplorer: true,
showInspector: true,
embedMode: false,
enableClose: true,
handleResize: true,
enablePopup: true,
...userOptions,
};
// Prepare state
if (!this._GlobalState.onPropertyChangedObservable) {
this._GlobalState.init(this.OnPropertyChangedObservable);
}
if (!this._GlobalState.onSelectionChangedObservable) {
this._GlobalState.onSelectionChangedObservable = this.OnSelectionChangeObservable;
}
// Make sure it is not already opened
if (this.IsVisible && options.original) {
this.Hide();
}
if (!scene) {
scene = EngineStore.LastCreatedScene!;
}
this._Scene = scene;
var rootElement = scene ? scene.getEngine().getInputElement() : EngineStore.LastCreatedEngine!.getInputElement();
if (options.embedMode && options.showExplorer && options.showInspector) {
if (options.popup) {
this._CreateEmbedHost(scene, options, this._CreatePopup("INSPECTOR", "_EmbedHostWindow"), Inspector.OnSelectionChangeObservable);
} else {
if (!rootElement) {
return;
}
let parentControl = (options.globalRoot ? options.globalRoot : rootElement.parentElement) as HTMLElement;
if (!options.overlay && !this._NewCanvasContainer) {
this._CreateCanvasContainer(parentControl);
} else if (!options.overlay && this._NewCanvasContainer && this._NewCanvasContainer.parentElement) {
// the root is now the parent of the canvas container
parentControl = this._NewCanvasContainer.parentElement;
}
if (this._NewCanvasContainer) {
// If we move things around, let's control the resize
if (options.handleResize && scene) {
this._OnBeforeRenderObserver = scene.onBeforeRenderObservable.add(() => {
scene.getEngine().resize();
});
}
}
this._CreateEmbedHost(scene, options, parentControl, Inspector.OnSelectionChangeObservable);
}
} else if (options.popup) {
if (options.showExplorer) {
if (this._SceneExplorerHost) {
this._SceneExplorerHost.style.width = "0";
}
this._CreateSceneExplorer(scene, options, this._CreatePopup("SCENE EXPLORER", "_SceneExplorerWindow"));
}
if (options.showInspector) {
if (this._ActionTabsHost) {
this._ActionTabsHost.style.width = "0";
}
this._CreateActionTabs(scene, options, this._CreatePopup("INSPECTOR", "_ActionTabsWindow"));
}
} else {
let parentControl = (options.globalRoot ? options.globalRoot : rootElement!.parentElement) as HTMLElement;
if (!options.overlay && !this._NewCanvasContainer) {
this._CreateCanvasContainer(parentControl);
} else if (!options.overlay && this._NewCanvasContainer && this._NewCanvasContainer.parentElement) {
// the root is now the parent of the canvas container
parentControl = this._NewCanvasContainer.parentElement;
}
if (this._NewCanvasContainer) {
// If we move things around, let's control the resize
if (options.handleResize && scene) {
this._OnBeforeRenderObserver = scene.onBeforeRenderObservable.add(() => {
scene.getEngine().resize();
});
}
}
if (options.showExplorer) {
this._CreateSceneExplorer(scene, options, parentControl);
}
if (options.showInspector) {
this._CreateActionTabs(scene, options, parentControl);
}
}
}
public static _SetNewScene(scene: Scene) {
this._Scene = scene;
this._GlobalState.onNewSceneObservable.notifyObservers(scene);
}
public static _CreateCanvasContainer(parentControl: HTMLElement) {
// Create a container for previous elements
this._NewCanvasContainer = parentControl.ownerDocument!.createElement("div");
this._NewCanvasContainer.style.display = parentControl.style.display;
parentControl.style.display = "flex";
while (parentControl.childElementCount > 0) {
var child = parentControl.childNodes[0];
parentControl.removeChild(child);
this._NewCanvasContainer.appendChild(child);
}
parentControl.appendChild(this._NewCanvasContainer);
this._NewCanvasContainer.style.width = "100%";
this._NewCanvasContainer.style.height = "100%";
}
private static _DestroyCanvasContainer() {
if (!this._NewCanvasContainer) {
return;
}
const parentControl = this._NewCanvasContainer.parentElement!;
while (this._NewCanvasContainer.childElementCount > 0) {
const child = this._NewCanvasContainer.childNodes[0];
this._NewCanvasContainer.removeChild(child);
parentControl.appendChild(child);
}
parentControl.removeChild(this._NewCanvasContainer);
parentControl.style.display = this._NewCanvasContainer.style.display;
this._NewCanvasContainer = null;
}
private static _Cleanup() {
if (Inspector._OpenedPane !== 0) {
return;
}
// Gizmo disposal
this._GlobalState.lightGizmos.forEach((g) => {
if (g.light) {
this._GlobalState.enableLightGizmo(g.light, false);
}
});
this._GlobalState.cameraGizmos.forEach((g) => {
if (g.camera) {
this._GlobalState.enableCameraGizmo(g.camera, false);
}
});
if (this._Scene && this._Scene.reservedDataStore && this._Scene.reservedDataStore.gizmoManager) {
this._Scene.reservedDataStore.gizmoManager.dispose();
this._Scene.reservedDataStore.gizmoManager = null;
}
if (this._NewCanvasContainer) {
this._DestroyCanvasContainer();
}
if (this._OnBeforeRenderObserver && this._Scene) {
this._Scene.onBeforeRenderObservable.remove(this._OnBeforeRenderObserver);
this._OnBeforeRenderObserver = null;
this._Scene.getEngine().resize();
}
this._GlobalState.onInspectorClosedObservable.notifyObservers(this._Scene);
}
private static _RemoveElementFromDOM(element: Nullable<HTMLElement>) {
if (element && element.parentElement) {
element.parentElement.removeChild(element);
}
}
public static Hide() {
if (this._ActionTabsHost) {
ReactDOM.unmountComponentAtNode(this._ActionTabsHost);
this._RemoveElementFromDOM(this._ActionTabsHost);
this._ActionTabsHost = null;
}
if (this._SceneExplorerHost) {
ReactDOM.unmountComponentAtNode(this._SceneExplorerHost);
if (this._SceneExplorerHost.parentElement) {
this._SceneExplorerHost.parentElement.removeChild(this._SceneExplorerHost);
}
this._SceneExplorerHost = null;
}
if (this._EmbedHost) {
ReactDOM.unmountComponentAtNode(this._EmbedHost);
if (this._EmbedHost.parentElement) {
this._EmbedHost.parentElement.removeChild(this._EmbedHost);
}
this._EmbedHost = null;
}
Inspector._OpenedPane = 0;
this._Cleanup();
if (!this._GlobalState.onPluginActivatedObserver) {
SceneLoader.OnPluginActivatedObservable.remove(this._GlobalState.onPluginActivatedObserver);
this._GlobalState.onPluginActivatedObserver = null;
}
}
}
Inspector.EarlyAttachToLoader(); | the_stack |
import {DirectiveFn} from '../lib/directive.js';
import {createMarker, directive, NodePart, Part, removeNodes, reparentNodes} from '../lit-html.js';
export type KeyFn<T> = (item: T, index: number) => unknown;
export type ItemTemplate<T> = (item: T, index: number) => unknown;
// Helper functions for manipulating parts
// TODO(kschaaf): Refactor into Part API?
const createAndInsertPart =
(containerPart: NodePart, beforePart?: NodePart): NodePart => {
const container = containerPart.startNode.parentNode as Node;
const beforeNode = beforePart === undefined ? containerPart.endNode :
beforePart.startNode;
const startNode = container.insertBefore(createMarker(), beforeNode);
container.insertBefore(createMarker(), beforeNode);
const newPart = new NodePart(containerPart.options);
newPart.insertAfterNode(startNode);
return newPart;
};
const updatePart = (part: NodePart, value: unknown) => {
part.setValue(value);
part.commit();
return part;
};
const insertPartBefore =
(containerPart: NodePart, part: NodePart, ref?: NodePart) => {
const container = containerPart.startNode.parentNode as Node;
const beforeNode = ref ? ref.startNode : containerPart.endNode;
const endNode = part.endNode.nextSibling;
if (endNode !== beforeNode) {
reparentNodes(container, part.startNode, endNode, beforeNode);
}
};
const removePart = (part: NodePart) => {
removeNodes(
part.startNode.parentNode!, part.startNode, part.endNode.nextSibling);
};
// Helper for generating a map of array item to its index over a subset
// of an array (used to lazily generate `newKeyToIndexMap` and
// `oldKeyToIndexMap`)
const generateMap = (list: unknown[], start: number, end: number) => {
const map = new Map();
for (let i = start; i <= end; i++) {
map.set(list[i], i);
}
return map;
};
// Stores previous ordered list of parts and map of key to index
const partListCache = new WeakMap<NodePart, (NodePart | null)[]>();
const keyListCache = new WeakMap<NodePart, unknown[]>();
/**
* A directive that repeats a series of values (usually `TemplateResults`)
* generated from an iterable, and updates those items efficiently when the
* iterable changes based on user-provided `keys` associated with each item.
*
* Note that if a `keyFn` is provided, strict key-to-DOM mapping is maintained,
* meaning previous DOM for a given key is moved into the new position if
* needed, and DOM will never be reused with values for different keys (new DOM
* will always be created for new keys). This is generally the most efficient
* way to use `repeat` since it performs minimum unnecessary work for insertions
* and removals.
*
* IMPORTANT: If providing a `keyFn`, keys *must* be unique for all items in a
* given call to `repeat`. The behavior when two or more items have the same key
* is undefined.
*
* If no `keyFn` is provided, this directive will perform similar to mapping
* items to values, and DOM will be reused against potentially different items.
*/
export const repeat =
directive(
<T>(items: Iterable<T>,
keyFnOrTemplate: KeyFn<T>|ItemTemplate<T>,
template?: ItemTemplate<T>):
DirectiveFn => {
let keyFn: KeyFn<T>;
if (template === undefined) {
template = keyFnOrTemplate;
} else if (keyFnOrTemplate !== undefined) {
keyFn = keyFnOrTemplate as KeyFn<T>;
}
return (containerPart: Part): void => {
if (!(containerPart instanceof NodePart)) {
throw new Error('repeat can only be used in text bindings');
}
// Old part & key lists are retrieved from the last update
// (associated with the part for this instance of the directive)
const oldParts = partListCache.get(containerPart) || [];
const oldKeys = keyListCache.get(containerPart) || [];
// New part list will be built up as we go (either reused from
// old parts or created for new keys in this update). This is
// saved in the above cache at the end of the update.
const newParts: NodePart[] = [];
// New value list is eagerly generated from items along with a
// parallel array indicating its key.
const newValues: unknown[] = [];
const newKeys: unknown[] = [];
let index = 0;
for (const item of items) {
newKeys[index] = keyFn ? keyFn(item, index) : index;
newValues[index] = template !(item, index);
index++;
}
// Maps from key to index for current and previous update; these
// are generated lazily only when needed as a performance
// optimization, since they are only required for multiple
// non-contiguous changes in the list, which are less common.
let newKeyToIndexMap!: Map<unknown, number>;
let oldKeyToIndexMap!: Map<unknown, number>;
// Head and tail pointers to old parts and new values
let oldHead = 0;
let oldTail = oldParts.length - 1;
let newHead = 0;
let newTail = newValues.length - 1;
// Overview of O(n) reconciliation algorithm (general approach
// based on ideas found in ivi, vue, snabbdom, etc.):
//
// * We start with the list of old parts and new values (and
// arrays of their respective keys), head/tail pointers into
// each, and we build up the new list of parts by updating
// (and when needed, moving) old parts or creating new ones.
// The initial scenario might look like this (for brevity of
// the diagrams, the numbers in the array reflect keys
// associated with the old parts or new values, although keys
// and parts/values are actually stored in parallel arrays
// indexed using the same head/tail pointers):
//
// oldHead v v oldTail
// oldKeys: [0, 1, 2, 3, 4, 5, 6]
// newParts: [ , , , , , , ]
// newKeys: [0, 2, 1, 4, 3, 7, 6] <- reflects the user's new
// item order
// newHead ^ ^ newTail
//
// * Iterate old & new lists from both sides, updating,
// swapping, or removing parts at the head/tail locations
// until neither head nor tail can move.
//
// * Example below: keys at head pointers match, so update old
// part 0 in-place (no need to move it) and record part 0 in
// the `newParts` list. The last thing we do is advance the
// `oldHead` and `newHead` pointers (will be reflected in the
// next diagram).
//
// oldHead v v oldTail
// oldKeys: [0, 1, 2, 3, 4, 5, 6]
// newParts: [0, , , , , , ] <- heads matched: update 0
// newKeys: [0, 2, 1, 4, 3, 7, 6] and advance both oldHead
// & newHead
// newHead ^ ^ newTail
//
// * Example below: head pointers don't match, but tail
// pointers do, so update part 6 in place (no need to move
// it), and record part 6 in the `newParts` list. Last,
// advance the `oldTail` and `oldHead` pointers.
//
// oldHead v v oldTail
// oldKeys: [0, 1, 2, 3, 4, 5, 6]
// newParts: [0, , , , , , 6] <- tails matched: update 6
// newKeys: [0, 2, 1, 4, 3, 7, 6] and advance both oldTail
// & newTail
// newHead ^ ^ newTail
//
// * If neither head nor tail match; next check if one of the
// old head/tail items was removed. We first need to generate
// the reverse map of new keys to index (`newKeyToIndexMap`),
// which is done once lazily as a performance optimization,
// since we only hit this case if multiple non-contiguous
// changes were made. Note that for contiguous removal
// anywhere in the list, the head and tails would advance
// from either end and pass each other before we get to this
// case and removals would be handled in the final while loop
// without needing to generate the map.
//
// * Example below: The key at `oldTail` was removed (no longer
// in the `newKeyToIndexMap`), so remove that part from the
// DOM and advance just the `oldTail` pointer.
//
// oldHead v v oldTail
// oldKeys: [0, 1, 2, 3, 4, 5, 6]
// newParts: [0, , , , , , 6] <- 5 not in new map: remove
// newKeys: [0, 2, 1, 4, 3, 7, 6] 5 and advance oldTail
// newHead ^ ^ newTail
//
// * Once head and tail cannot move, any mismatches are due to
// either new or moved items; if a new key is in the previous
// "old key to old index" map, move the old part to the new
// location, otherwise create and insert a new part. Note
// that when moving an old part we null its position in the
// oldParts array if it lies between the head and tail so we
// know to skip it when the pointers get there.
//
// * Example below: neither head nor tail match, and neither
// were removed; so find the `newHead` key in the
// `oldKeyToIndexMap`, and move that old part's DOM into the
// next head position (before `oldParts[oldHead]`). Last,
// null the part in the `oldPart` array since it was
// somewhere in the remaining oldParts still to be scanned
// (between the head and tail pointers) so that we know to
// skip that old part on future iterations.
//
// oldHead v v oldTail
// oldKeys: [0, 1, -, 3, 4, 5, 6]
// newParts: [0, 2, , , , , 6] <- stuck: update & move 2
// newKeys: [0, 2, 1, 4, 3, 7, 6] into place and advance
// newHead
// newHead ^ ^ newTail
//
// * Note that for moves/insertions like the one above, a part
// inserted at the head pointer is inserted before the
// current `oldParts[oldHead]`, and a part inserted at the
// tail pointer is inserted before `newParts[newTail+1]`. The
// seeming asymmetry lies in the fact that new parts are
// moved into place outside in, so to the right of the head
// pointer are old parts, and to the right of the tail
// pointer are new parts.
//
// * We always restart back from the top of the algorithm,
// allowing matching and simple updates in place to
// continue...
//
// * Example below: the head pointers once again match, so
// simply update part 1 and record it in the `newParts`
// array. Last, advance both head pointers.
//
// oldHead v v oldTail
// oldKeys: [0, 1, -, 3, 4, 5, 6]
// newParts: [0, 2, 1, , , , 6] <- heads matched: update 1
// newKeys: [0, 2, 1, 4, 3, 7, 6] and advance both oldHead
// & newHead
// newHead ^ ^ newTail
//
// * As mentioned above, items that were moved as a result of
// being stuck (the final else clause in the code below) are
// marked with null, so we always advance old pointers over
// these so we're comparing the next actual old value on
// either end.
//
// * Example below: `oldHead` is null (already placed in
// newParts), so advance `oldHead`.
//
// oldHead v v oldTail
// oldKeys: [0, 1, -, 3, 4, 5, 6] <- old head already used:
// newParts: [0, 2, 1, , , , 6] advance oldHead
// newKeys: [0, 2, 1, 4, 3, 7, 6]
// newHead ^ ^ newTail
//
// * Note it's not critical to mark old parts as null when they
// are moved from head to tail or tail to head, since they
// will be outside the pointer range and never visited again.
//
// * Example below: Here the old tail key matches the new head
// key, so the part at the `oldTail` position and move its
// DOM to the new head position (before `oldParts[oldHead]`).
// Last, advance `oldTail` and `newHead` pointers.
//
// oldHead v v oldTail
// oldKeys: [0, 1, -, 3, 4, 5, 6]
// newParts: [0, 2, 1, 4, , , 6] <- old tail matches new
// newKeys: [0, 2, 1, 4, 3, 7, 6] head: update & move 4,
// advance oldTail & newHead
// newHead ^ ^ newTail
//
// * Example below: Old and new head keys match, so update the
// old head part in place, and advance the `oldHead` and
// `newHead` pointers.
//
// oldHead v oldTail
// oldKeys: [0, 1, -, 3, 4, 5, 6]
// newParts: [0, 2, 1, 4, 3, ,6] <- heads match: update 3
// newKeys: [0, 2, 1, 4, 3, 7, 6] and advance oldHead &
// newHead
// newHead ^ ^ newTail
//
// * Once the new or old pointers move past each other then all
// we have left is additions (if old list exhausted) or
// removals (if new list exhausted). Those are handled in the
// final while loops at the end.
//
// * Example below: `oldHead` exceeded `oldTail`, so we're done
// with the main loop. Create the remaining part and insert
// it at the new head position, and the update is complete.
//
// (oldHead > oldTail)
// oldKeys: [0, 1, -, 3, 4, 5, 6]
// newParts: [0, 2, 1, 4, 3, 7 ,6] <- create and insert 7
// newKeys: [0, 2, 1, 4, 3, 7, 6]
// newHead ^ newTail
//
// * Note that the order of the if/else clauses is not
// important to the algorithm, as long as the null checks
// come first (to ensure we're always working on valid old
// parts) and that the final else clause comes last (since
// that's where the expensive moves occur). The order of
// remaining clauses is is just a simple guess at which cases
// will be most common.
//
// * TODO(kschaaf) Note, we could calculate the longest
// increasing subsequence (LIS) of old items in new position,
// and only move those not in the LIS set. However that costs
// O(nlogn) time and adds a bit more code, and only helps
// make rare types of mutations require fewer moves. The
// above handles removes, adds, reversal, swaps, and single
// moves of contiguous items in linear time, in the minimum
// number of moves. As the number of multiple moves where LIS
// might help approaches a random shuffle, the LIS
// optimization becomes less helpful, so it seems not worth
// the code at this point. Could reconsider if a compelling
// case arises.
while (oldHead <= oldTail && newHead <= newTail) {
if (oldParts[oldHead] === null) {
// `null` means old part at head has already been used
// below; skip
oldHead++;
} else if (oldParts[oldTail] === null) {
// `null` means old part at tail has already been used
// below; skip
oldTail--;
} else if (oldKeys[oldHead] === newKeys[newHead]) {
// Old head matches new head; update in place
newParts[newHead] =
updatePart(oldParts[oldHead]!, newValues[newHead]);
oldHead++;
newHead++;
} else if (oldKeys[oldTail] === newKeys[newTail]) {
// Old tail matches new tail; update in place
newParts[newTail] =
updatePart(oldParts[oldTail]!, newValues[newTail]);
oldTail--;
newTail--;
} else if (oldKeys[oldHead] === newKeys[newTail]) {
// Old head matches new tail; update and move to new tail
newParts[newTail] =
updatePart(oldParts[oldHead]!, newValues[newTail]);
insertPartBefore(
containerPart,
oldParts[oldHead]!,
newParts[newTail + 1]);
oldHead++;
newTail--;
} else if (oldKeys[oldTail] === newKeys[newHead]) {
// Old tail matches new head; update and move to new head
newParts[newHead] =
updatePart(oldParts[oldTail]!, newValues[newHead]);
insertPartBefore(
containerPart, oldParts[oldTail]!, oldParts[oldHead]!);
oldTail--;
newHead++;
} else {
if (newKeyToIndexMap === undefined) {
// Lazily generate key-to-index maps, used for removals &
// moves below
newKeyToIndexMap = generateMap(newKeys, newHead, newTail);
oldKeyToIndexMap = generateMap(oldKeys, oldHead, oldTail);
}
if (!newKeyToIndexMap.has(oldKeys[oldHead])) {
// Old head is no longer in new list; remove
removePart(oldParts[oldHead]!);
oldHead++;
} else if (!newKeyToIndexMap.has(oldKeys[oldTail])) {
// Old tail is no longer in new list; remove
removePart(oldParts[oldTail]!);
oldTail--;
} else {
// Any mismatches at this point are due to additions or
// moves; see if we have an old part we can reuse and move
// into place
const oldIndex = oldKeyToIndexMap.get(newKeys[newHead]);
const oldPart =
oldIndex !== undefined ? oldParts[oldIndex] : null;
if (oldPart === null) {
// No old part for this value; create a new one and
// insert it
const newPart = createAndInsertPart(
containerPart, oldParts[oldHead]!);
updatePart(newPart, newValues[newHead]);
newParts[newHead] = newPart;
} else {
// Reuse old part
newParts[newHead] =
updatePart(oldPart, newValues[newHead]);
insertPartBefore(
containerPart, oldPart, oldParts[oldHead]!);
// This marks the old part as having been used, so that
// it will be skipped in the first two checks above
oldParts[oldIndex as number] = null;
}
newHead++;
}
}
}
// Add parts for any remaining new values
while (newHead <= newTail) {
// For all remaining additions, we insert before last new
// tail, since old pointers are no longer valid
const newPart =
createAndInsertPart(containerPart, newParts[newTail + 1]);
updatePart(newPart, newValues[newHead]);
newParts[newHead++] = newPart;
}
// Remove any remaining unused old parts
while (oldHead <= oldTail) {
const oldPart = oldParts[oldHead++];
if (oldPart !== null) {
removePart(oldPart);
}
}
// Save order of new parts for next round
partListCache.set(containerPart, newParts);
keyListCache.set(containerPart, newKeys);
};
}) as
<T>(items: Iterable<T>,
keyFnOrTemplate: KeyFn<T>|ItemTemplate<T>,
template?: ItemTemplate<T>) => DirectiveFn; | the_stack |
import { InboundFilters } from '../../../src/integrations/inboundfilters';
let inboundFilters: any;
describe('InboundFilters', () => {
beforeEach(() => {
inboundFilters = new InboundFilters();
});
describe('shouldDropEvent', () => {
it('should drop when error is internal one', () => {
inboundFilters._isSentryError = () => true;
expect(inboundFilters._shouldDropEvent({}, inboundFilters._mergeOptions())).toBe(true);
});
it('should drop when error is ignored', () => {
inboundFilters._isIgnoredError = () => true;
expect(inboundFilters._shouldDropEvent({}, inboundFilters._mergeOptions())).toBe(true);
});
it('should drop when url is denied', () => {
inboundFilters._isDeniedUrl = () => true;
expect(inboundFilters._shouldDropEvent({}, inboundFilters._mergeOptions())).toBe(true);
});
it('should drop when url is not allowed', () => {
inboundFilters._isAllowedUrl = () => false;
expect(inboundFilters._shouldDropEvent({}, inboundFilters._mergeOptions())).toBe(true);
});
it('should drop when url is not denied, but also not allowed', () => {
inboundFilters._isDeniedUrl = () => false;
inboundFilters._isAllowedUrl = () => false;
expect(inboundFilters._shouldDropEvent({}, inboundFilters._mergeOptions())).toBe(true);
});
it('should drop when url is denied and allowed at the same time', () => {
inboundFilters._isDeniedUrl = () => true;
inboundFilters._isAllowedUrl = () => true;
expect(inboundFilters._shouldDropEvent({}, inboundFilters._mergeOptions())).toBe(true);
});
it('should not drop when url is not denied, but allowed', () => {
inboundFilters._isDeniedUrl = () => false;
inboundFilters._isAllowedUrl = () => true;
expect(inboundFilters._shouldDropEvent({}, inboundFilters._mergeOptions())).toBe(false);
});
it('should not drop when any of checks dont match', () => {
inboundFilters._isIgnoredError = () => false;
inboundFilters._isDeniedUrl = () => false;
inboundFilters._isAllowedUrl = () => true;
expect(inboundFilters._shouldDropEvent({}, inboundFilters._mergeOptions())).toBe(false);
});
});
describe('isSentryError', () => {
const messageEvent = {
message: 'captureMessage',
};
const exceptionEvent = {
exception: {
values: [
{
type: 'SyntaxError',
value: 'unidentified ? at line 1337',
},
],
},
};
const sentryEvent = {
exception: {
values: [
{
type: 'SentryError',
value: 'something something server connection',
},
],
},
};
it('should work as expected', () => {
expect(inboundFilters._isSentryError(messageEvent, inboundFilters._mergeOptions())).toBe(false);
expect(inboundFilters._isSentryError(exceptionEvent, inboundFilters._mergeOptions())).toBe(false);
expect(inboundFilters._isSentryError(sentryEvent, inboundFilters._mergeOptions())).toBe(true);
});
it('should be configurable', () => {
inboundFilters = new InboundFilters({
ignoreInternal: false,
});
expect(inboundFilters._isSentryError(messageEvent, inboundFilters._mergeOptions())).toBe(false);
expect(inboundFilters._isSentryError(exceptionEvent, inboundFilters._mergeOptions())).toBe(false);
expect(inboundFilters._isSentryError(sentryEvent, inboundFilters._mergeOptions())).toBe(false);
});
});
describe('ignoreErrors', () => {
const messageEvent = {
message: 'captureMessage',
};
const exceptionEvent = {
exception: {
values: [
{
type: 'SyntaxError',
value: 'unidentified ? at line 1337',
},
],
},
};
it('string filter with partial match', () => {
expect(
inboundFilters._isIgnoredError(
messageEvent,
inboundFilters._mergeOptions({
ignoreErrors: ['capture'],
}),
),
).toBe(true);
});
it('string filter with exact match', () => {
expect(
inboundFilters._isIgnoredError(
messageEvent,
inboundFilters._mergeOptions({
ignoreErrors: ['captureMessage'],
}),
),
).toBe(true);
});
it('regexp filter with partial match', () => {
expect(
inboundFilters._isIgnoredError(
messageEvent,
inboundFilters._mergeOptions({
ignoreErrors: [/capture/],
}),
),
).toBe(true);
});
it('regexp filter with exact match', () => {
expect(
inboundFilters._isIgnoredError(
messageEvent,
inboundFilters._mergeOptions({
ignoreErrors: [/^captureMessage$/],
}),
),
).toBe(true);
expect(
inboundFilters._isIgnoredError(
{
message: 'captureMessageSomething',
},
inboundFilters._mergeOptions({
ignoreErrors: [/^captureMessage$/],
}),
),
).toBe(false);
});
it('uses message when both, message and exception are available', () => {
expect(
inboundFilters._isIgnoredError(
{
...exceptionEvent,
...messageEvent,
},
inboundFilters._mergeOptions({
ignoreErrors: [/captureMessage/],
}),
),
).toBe(true);
});
it('can use multiple filters', () => {
expect(
inboundFilters._isIgnoredError(
messageEvent,
inboundFilters._mergeOptions({
ignoreErrors: ['captureMessage', /SyntaxError/],
}),
),
).toBe(true);
expect(
inboundFilters._isIgnoredError(
exceptionEvent,
inboundFilters._mergeOptions({
ignoreErrors: ['captureMessage', /SyntaxError/],
}),
),
).toBe(true);
});
it('uses default filters', () => {
expect(
inboundFilters._isIgnoredError(
{
exception: {
values: [
{
type: '[undefined]',
value: 'Script error.',
},
],
},
},
inboundFilters._mergeOptions(),
),
).toBe(true);
});
describe('on exception', () => {
it('uses exceptions data when message is unavailable', () => {
expect(
inboundFilters._isIgnoredError(
exceptionEvent,
inboundFilters._mergeOptions({
ignoreErrors: ['SyntaxError: unidentified ? at line 1337'],
}),
),
).toBe(true);
});
it('can match on exception value', () => {
expect(
inboundFilters._isIgnoredError(
exceptionEvent,
inboundFilters._mergeOptions({
ignoreErrors: [/unidentified \?/],
}),
),
).toBe(true);
});
it('can match on exception type', () => {
expect(
inboundFilters._isIgnoredError(
exceptionEvent,
inboundFilters._mergeOptions({
ignoreErrors: [/^SyntaxError/],
}),
),
).toBe(true);
});
});
});
describe('denyUrls/allowUrls', () => {
const messageEvent = {
message: 'wat',
stacktrace: {
// Frames are always in the reverse order, as this is how Sentry expect them to come.
// Frame that crashed is the last one, the one from awesome-analytics
frames: [
{ filename: 'https://our-side.com/js/bundle.js' },
{ filename: 'https://our-side.com/js/bundle.js' },
{ filename: 'https://awesome-analytics.io/some/file.js' },
],
},
};
const exceptionEvent = {
exception: {
values: [
{
stacktrace: {
// Frames are always in the reverse order, as this is how Sentry expect them to come.
// Frame that crashed is the last one, the one from awesome-analytics
frames: [
{ filename: 'https://our-side.com/js/bundle.js' },
{ filename: 'https://our-side.com/js/bundle.js' },
{ filename: 'https://awesome-analytics.io/some/file.js' },
],
},
},
],
},
};
it('should filter captured message based on its stack trace using string filter', () => {
expect(
inboundFilters._isDeniedUrl(
messageEvent,
inboundFilters._mergeOptions({
allowUrls: ['https://awesome-analytics.io'],
denyUrls: ['https://awesome-analytics.io'],
}),
),
).toBe(true);
expect(
inboundFilters._isAllowedUrl(
messageEvent,
inboundFilters._mergeOptions({
allowUrls: ['https://awesome-analytics.io'],
denyUrls: ['https://awesome-analytics.io'],
}),
),
).toBe(true);
});
it('should filter captured message based on its stack trace using regexp filter', () => {
expect(
inboundFilters._isDeniedUrl(
messageEvent,
inboundFilters._mergeOptions({
denyUrls: [/awesome-analytics\.io/],
}),
),
).toBe(true);
expect(
inboundFilters._isAllowedUrl(
messageEvent,
inboundFilters._mergeOptions({
denyUrls: [/awesome-analytics\.io/],
}),
),
).toBe(true);
});
it('should not filter captured messages with no stacktraces', () => {
expect(
inboundFilters._isDeniedUrl(
{
message: 'any',
},
inboundFilters._mergeOptions({
allowUrls: ['https://awesome-analytics.io'],
denyUrls: ['https://awesome-analytics.io'],
}),
),
).toBe(false);
expect(
inboundFilters._isAllowedUrl(
{
message: 'any',
},
inboundFilters._mergeOptions({
allowUrls: ['https://awesome-analytics.io'],
denyUrls: ['https://awesome-analytics.io'],
}),
),
).toBe(true);
});
it('should filter captured exception based on its stack trace using string filter', () => {
expect(
inboundFilters._isDeniedUrl(
exceptionEvent,
inboundFilters._mergeOptions({
allowUrls: ['https://awesome-analytics.io'],
denyUrls: ['https://awesome-analytics.io'],
}),
),
).toBe(true);
expect(
inboundFilters._isAllowedUrl(
exceptionEvent,
inboundFilters._mergeOptions({
allowUrls: ['https://awesome-analytics.io'],
denyUrls: ['https://awesome-analytics.io'],
}),
),
).toBe(true);
});
it('should filter captured exceptions based on its stack trace using regexp filter', () => {
expect(
inboundFilters._isDeniedUrl(
exceptionEvent,
inboundFilters._mergeOptions({
allowUrls: [/awesome-analytics\.io/],
denyUrls: [/awesome-analytics\.io/],
}),
),
).toBe(true);
expect(
inboundFilters._isAllowedUrl(
exceptionEvent,
inboundFilters._mergeOptions({
allowUrls: [/awesome-analytics\.io/],
denyUrls: [/awesome-analytics\.io/],
}),
),
).toBe(true);
});
it('should not filter events that doesnt pass the test', () => {
expect(
inboundFilters._isDeniedUrl(
exceptionEvent,
inboundFilters._mergeOptions({
allowUrls: ['some-other-domain.com'],
denyUrls: ['some-other-domain.com'],
}),
),
).toBe(false);
expect(
inboundFilters._isAllowedUrl(
exceptionEvent,
inboundFilters._mergeOptions({
allowUrls: ['some-other-domain.com'],
denyUrls: ['some-other-domain.com'],
}),
),
).toBe(false);
});
it('should be able to use multiple filters', () => {
expect(
inboundFilters._isDeniedUrl(
exceptionEvent,
inboundFilters._mergeOptions({
allowUrls: ['some-other-domain.com', /awesome-analytics\.io/],
denyUrls: ['some-other-domain.com', /awesome-analytics\.io/],
}),
),
).toBe(true);
expect(
inboundFilters._isAllowedUrl(
exceptionEvent,
inboundFilters._mergeOptions({
allowUrls: ['some-other-domain.com', /awesome-analytics\.io/],
denyUrls: ['some-other-domain.com', /awesome-analytics\.io/],
}),
),
).toBe(true);
});
it('should not fail with malformed event event and default to false for isdeniedUrl and true for isallowedUrl', () => {
const malformedEvent = {
stacktrace: {
frames: undefined,
},
};
expect(
inboundFilters._isDeniedUrl(
malformedEvent,
inboundFilters._mergeOptions({
allowUrls: ['https://awesome-analytics.io'],
denyUrls: ['https://awesome-analytics.io'],
}),
),
).toBe(false);
expect(
inboundFilters._isAllowedUrl(
malformedEvent,
inboundFilters._mergeOptions({
allowUrls: ['https://awesome-analytics.io'],
denyUrls: ['https://awesome-analytics.io'],
}),
),
).toBe(true);
});
it('should search for script names when there is an anonymous callback at the last frame', () => {
const messageEvent = {
message: 'any',
stacktrace: {
frames: [
{ filename: 'https://our-side.com/js/bundle.js' },
{ filename: 'https://awesome-analytics.io/some/file.js' },
{ filename: '<anonymous>' },
],
},
};
expect(
inboundFilters._isAllowedUrl(
messageEvent,
inboundFilters._mergeOptions({
allowUrls: ['https://awesome-analytics.io/some/file.js'],
}),
),
).toBe(true);
expect(
inboundFilters._isDeniedUrl(
messageEvent,
inboundFilters._mergeOptions({
denyUrls: ['https://awesome-analytics.io/some/file.js'],
}),
),
).toBe(true);
});
it('should search for script names when the last frame is from native code', () => {
const messageEvent = {
message: 'any',
stacktrace: {
frames: [
{ filename: 'https://our-side.com/js/bundle.js' },
{ filename: 'https://awesome-analytics.io/some/file.js' },
{ filename: '[native code]' },
],
},
};
expect(
inboundFilters._isAllowedUrl(
messageEvent,
inboundFilters._mergeOptions({
allowUrls: ['https://awesome-analytics.io/some/file.js'],
}),
),
).toBe(true);
expect(
inboundFilters._isDeniedUrl(
messageEvent,
inboundFilters._mergeOptions({
denyUrls: ['https://awesome-analytics.io/some/file.js'],
}),
),
).toBe(true);
});
});
}); | the_stack |
import { Component, Type, ViewChild, ChangeDetectionStrategy, Injectable, Directive } from '@angular/core';
import { ComponentFixture, fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule, FormGroup, FormControl, Validators } from '@angular/forms';
import { NxCodeInputComponent } from './code-input.component';
import { NxCodeInputModule } from './code-input.module';
import { UP_ARROW, DOWN_ARROW, RIGHT_ARROW } from '@angular/cdk/keycodes';
import { dispatchKeyboardEvent, createKeyboardEvent } from '../cdk-test-utils';
import { NxCodeInputIntl } from './code-input-intl';
@Injectable()
class MyIntl extends NxCodeInputIntl {
inputFieldAriaLabel = 'Test';
ofLabel = 'testOf';
}
// For better readablity here, We can safely ignore some conventions in our specs
// tslint:disable:component-class-suffix
@Directive()
abstract class CodeInputTest {
@ViewChild(NxCodeInputComponent) codeInputInstance!: NxCodeInputComponent;
negative: boolean = false;
disabled: boolean = false;
onSubmit() { }
}
describe('NxCodeInputComponent', () => {
let fixture: ComponentFixture<CodeInputTest>;
let testInstance: CodeInputTest;
let codeInputElement: HTMLElement;
let inputElement: HTMLInputElement;
function createTestComponent(component: Type<CodeInputTest>) {
fixture = TestBed.createComponent(component);
fixture.detectChanges();
testInstance = fixture.componentInstance;
codeInputElement = fixture.nativeElement.querySelector('nx-code-input');
inputElement = (fixture.nativeElement.querySelector('.nx-code-input__field') as HTMLInputElement);
}
beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
NxCodeInputModule,
FormsModule,
ReactiveFormsModule
],
declarations: [
CodeInputTest1,
CodeInputTest2,
CodeInputTest3,
NumberCodeInput,
ConfigurableCodeInput,
OnPushCodeInput,
OverrideDefaultLabelsCodeInput
],
providers: [NxCodeInputIntl]
}).compileComponents();
})
);
it('creates a 4 character input form', () => {
createTestComponent(CodeInputTest1);
expect(testInstance).toBeTruthy();
});
it('should have a codeLength of 4', () => {
createTestComponent(CodeInputTest1);
expect(testInstance.codeInputInstance.codeLength).toBe(4);
});
it('should be a 6 input form per default', () => {
createTestComponent(CodeInputTest2);
expect(testInstance.codeInputInstance.codeLength).toBe(6);
});
it('should have a class nx-code-input', () => {
createTestComponent(CodeInputTest1);
expect(codeInputElement.classList.contains('nx-code-input')).toBe(true);
});
it('should auto capitalize input', fakeAsync(() => {
createTestComponent(CodeInputTest1);
inputElement.value = 'a';
inputElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
tick();
expect(inputElement.value).toBe('A');
}));
it('should be rendered invalid', () => {
createTestComponent(CodeInputTest1);
expect(codeInputElement.classList.contains('ng-invalid')).toBe(true);
});
it('should select second input on right arrow', fakeAsync(() => {
createTestComponent(CodeInputTest1);
inputElement.focus();
tick();
fixture.detectChanges();
// in order to trigger the right arrow event on an input we need an event of type input.
inputElement.value = '5';
dispatchKeyboardEvent(inputElement, 'keydown', RIGHT_ARROW);
inputElement.dispatchEvent(new Event('input'));
tick();
fixture.detectChanges();
expect(document.activeElement).toEqual(codeInputElement.querySelector('input:nth-child(2)'));
}));
it('should give code-input element has-error class on blur (with onPush)', fakeAsync(() => {
createTestComponent(CodeInputTest3);
const lastInput = fixture.nativeElement.querySelector('input:last-child');
lastInput.focus();
lastInput.blur();
tick();
fixture.detectChanges();
expect(codeInputElement.classList.contains('has-error')).toBe(true);
}));
it('should give code-input element has-error class on submit', fakeAsync(() => {
createTestComponent(CodeInputTest3);
expect(codeInputElement.classList).not.toContain('has-error');
const submitButton = fixture.nativeElement.querySelector('#submit-button') as HTMLButtonElement;
submitButton.click();
tick();
fixture.detectChanges();
expect(codeInputElement.classList).toContain('has-error');
}));
it('should paste', fakeAsync(() => {
createTestComponent(CodeInputTest1);
const data = new DataTransfer();
data.items.add('abcd', 'text/plain');
const clipboard = new ClipboardEvent('paste', {
clipboardData: data
} as ClipboardEventInit);
inputElement.focus();
inputElement.dispatchEvent(clipboard);
fixture.detectChanges();
tick(1);
['A', 'B', 'C', 'D'].forEach((char, i) => {
const input = codeInputElement.querySelector(`input:nth-child(${i + 1})`) as HTMLInputElement;
expect(input.value).toBe(char);
});
}));
it('should ignore non-number characters on paste on number input', fakeAsync(() => {
createTestComponent(NumberCodeInput);
const data = new DataTransfer();
data.items.add('1a23', 'text/plain');
const clipboard = new ClipboardEvent('paste', {
clipboardData: data
} as ClipboardEventInit);
inputElement.focus();
inputElement.dispatchEvent(clipboard);
fixture.detectChanges();
tick(1);
['1', '2', '3', ''].forEach((char, i) => {
const input = codeInputElement.querySelector(`input:nth-child(${i + 1})`) as HTMLInputElement;
expect(input.value).toBe(char);
});
// @ts-ignore
expect(testInstance.codeInputInstance._keyCode).toEqual(['1', '2', '3', undefined]);
}));
it('should prevent default on down arrow press in an empty input', fakeAsync(() => {
createTestComponent(NumberCodeInput);
inputElement.focus();
fixture.detectChanges();
tick();
const keydownEvent = createKeyboardEvent('keydown', DOWN_ARROW);
const spy = spyOn(keydownEvent, 'preventDefault');
inputElement.dispatchEvent(keydownEvent);
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(1);
}));
it('should not prevent default on up arrow press in an empty input', fakeAsync(() => {
createTestComponent(NumberCodeInput);
inputElement.focus();
fixture.detectChanges();
tick();
const keydownEvent = createKeyboardEvent('keydown', UP_ARROW);
const spy = spyOn(keydownEvent, 'preventDefault');
inputElement.dispatchEvent(keydownEvent);
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(0);
}));
it('should prevent default on up arrow press if value is 9', fakeAsync(() => {
createTestComponent(NumberCodeInput);
inputElement.focus();
fixture.detectChanges();
tick();
inputElement.value = '9';
inputElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
tick();
const keydownEvent = createKeyboardEvent('keydown', UP_ARROW);
const spy = spyOn(keydownEvent, 'preventDefault');
inputElement.dispatchEvent(keydownEvent);
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(1);
}));
it('should not prevent default on up arrow press if value is 5', fakeAsync(() => {
createTestComponent(NumberCodeInput);
inputElement.value = '5';
inputElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
tick();
inputElement.focus();
fixture.detectChanges();
tick();
const keydownEvent = createKeyboardEvent('keydown', UP_ARROW);
const spy = spyOn(keydownEvent, 'preventDefault');
inputElement.dispatchEvent(keydownEvent);
fixture.detectChanges();
const keyupEvent = createKeyboardEvent('keydown', DOWN_ARROW);
inputElement.dispatchEvent(keyupEvent);
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(0);
}));
it('should set tabindex on default', () => {
createTestComponent(CodeInputTest1);
expect(testInstance.codeInputInstance.tabindex).toBe(0);
});
it('should set the passed tabindex', () => {
createTestComponent(CodeInputTest1);
testInstance.codeInputInstance.tabindex = 1;
fixture.detectChanges();
expect(codeInputElement.getAttribute('tabindex')).toBe('-1');
const inputElements = codeInputElement.querySelectorAll('.nx-code-input__field');
Array.from(inputElements).forEach((inputEl) => {
expect((inputEl as HTMLElement).getAttribute('tabindex')).toBe(`1`);
});
});
it('should change the input type', fakeAsync(() => {
createTestComponent(CodeInputTest3);
fixture.componentInstance.codeInputInstance.type = 'number';
fixture.detectChanges();
const inputEl = fixture.nativeElement.querySelector('.nx-code-input__field') as HTMLInputElement;
expect(inputEl.getAttribute('type')).toBe('number');
}));
describe('negative', () => {
it('should create a basic code input with negative set to false', () => {
createTestComponent(CodeInputTest1);
expect(testInstance.codeInputInstance.negative).toBe(false);
});
it('should update on negative change', () => {
createTestComponent(ConfigurableCodeInput);
expect(testInstance.codeInputInstance.negative).toBe(false);
expect(codeInputElement.classList).not.toContain('is-negative');
testInstance.negative = true;
fixture.detectChanges();
expect(testInstance.codeInputInstance.negative).toBe(true);
expect(codeInputElement.classList).toContain('is-negative');
testInstance.negative = false;
fixture.detectChanges();
expect(testInstance.codeInputInstance.negative).toBe(false);
expect(codeInputElement.classList).not.toContain('is-negative');
});
it('should update on negative change (programmatic change)', () => {
createTestComponent(OnPushCodeInput);
testInstance.codeInputInstance.negative = true;
fixture.detectChanges();
expect(codeInputElement.classList).toContain('is-negative');
testInstance.codeInputInstance.negative = false;
fixture.detectChanges();
expect(codeInputElement.classList).not.toContain('is-negative');
});
});
describe('disabled', () => {
it('should create a basic code input with disabled set to false', () => {
createTestComponent(CodeInputTest1);
expect(testInstance.codeInputInstance.disabled).toBe(false);
});
it('should update on disabled change', () => {
createTestComponent(ConfigurableCodeInput);
const inputElements = codeInputElement.querySelectorAll('.nx-code-input__field');
expect(testInstance.codeInputInstance.disabled).toBe(false);
expect(codeInputElement.classList).not.toContain('is-disabled');
testInstance.disabled = true;
fixture.detectChanges();
expect(testInstance.codeInputInstance.disabled).toBe(true);
expect(codeInputElement.classList).toContain('is-disabled');
Array.from(inputElements).forEach((inputEl) => {
expect((inputEl as HTMLElement).getAttribute('disabled')).toBe('');
});
testInstance.disabled = false;
fixture.detectChanges();
expect(testInstance.codeInputInstance.disabled).toBe(false);
expect(codeInputElement.classList).not.toContain('is-disabled');
Array.from(inputElements).forEach((inputEl) => {
expect((inputEl as HTMLElement).getAttribute('disabled')).toBe(null);
});
});
it('should update on disabled change (programmatic change)', () => {
createTestComponent(OnPushCodeInput);
testInstance.codeInputInstance.disabled = true;
fixture.detectChanges();
expect(codeInputElement.classList).toContain('is-disabled');
testInstance.codeInputInstance.disabled = false;
fixture.detectChanges();
expect(codeInputElement.classList).not.toContain('is-disabled');
});
it('should update disabled on formGroup update', () => {
createTestComponent(CodeInputTest1);
expect(testInstance.codeInputInstance.disabled).toBe(false);
const form = (testInstance as CodeInputTest1).codeForm;
form.get('keyCode')!.disable();
expect(testInstance.codeInputInstance.disabled).toBe(true);
form.get('keyCode')!.enable();
expect(testInstance.codeInputInstance.disabled).toBe(false);
});
});
it('should overwrite the default aria labels', () => {
createTestComponent(OverrideDefaultLabelsCodeInput);
const inputElements = codeInputElement.querySelectorAll('.nx-code-input__field');
Array.from(inputElements).forEach((inputEl, index) => {
expect((inputEl as HTMLElement).getAttribute('aria-label')).toBe(`Test ${index + 1} testOf ${inputElements.length}`);
});
});
describe('a11y', () => {
it('has no accessibility violations', async () => {
createTestComponent(CodeInputTest1);
await expectAsync(fixture.nativeElement).toBeAccessible();
});
});
});
@Component({
template: `
<form class="nx-code-input-demo-form" [formGroup]="codeForm" (ngSubmit)="onSubmit()">
<nx-code-input
[length]="4"
nxConvertTo="upper"
formControlName="keyCode"
></nx-code-input>
</form>
`
})
class CodeInputTest1 extends CodeInputTest {
inputValue: string = '';
codeForm: FormGroup = new FormGroup({
keyCode: new FormControl(this.inputValue, {
validators: [
Validators.required,
Validators.pattern('[A-Z]+'),
Validators.minLength(4)
],
updateOn: 'submit'
})
});
}
@Component({
template: `
<form class="nx-code-input-demo-form" #form2="ngForm" [formGroup]="codeForm2" (ngSubmit)="onSubmit()">
<nx-code-input
formControlName="keyCode2"
></nx-code-input>
</form>
`
})
class CodeInputTest2 extends CodeInputTest {
inputValue2: string = '';
codeForm2: FormGroup = new FormGroup({
keyCode2: new FormControl(this.inputValue2, {
validators: [
Validators.required,
Validators.minLength(6)
],
updateOn: 'blur'
})
});
}
@Component({
template: `
<form class="nx-code-input-demo-form" #form3="ngForm" [formGroup]="codeForm3" (ngSubmit)="onSubmit()">
<nx-code-input formControlName="keyCode3"></nx-code-input>
<button nxButton='primary small' id="submit-button">Submit</button>
<button nxButton="secondary small" (click)="form.resetForm()">Clear</button>
</form>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
class CodeInputTest3 extends CodeInputTest {
inputValue3: string = '';
codeForm3: FormGroup = new FormGroup({
keyCode3: new FormControl(this.inputValue3, {
validators: [
Validators.required,
Validators.minLength(6)
],
updateOn: 'blur'
})
});
}
@Component({
template: `
<nx-code-input [length]="4" type="number"></nx-code-input>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
class NumberCodeInput extends CodeInputTest { }
@Component({
template: `
<nx-code-input
[negative]="negative"
[disabled]="disabled"
[length]="4">
</nx-code-input>
`
})
class ConfigurableCodeInput extends CodeInputTest {}
@Component({
template: `
<nx-code-input
[negative]="negative"
[length]="4">
</nx-code-input>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
class OnPushCodeInput extends CodeInputTest {}
@Component({
template: `
<nx-code-input [length]="4"></nx-code-input>
`,
providers: [
{ provide: NxCodeInputIntl, useClass: MyIntl }
]
})
class OverrideDefaultLabelsCodeInput extends CodeInputTest { } | the_stack |
import type * as kafkaTypes from "node-rdkafka";
import { Deferred } from "@fluidframework/common-utils";
import { IConsumer, IPartition, IPartitionWithEpoch, IQueuedMessage } from "@fluidframework/server-services-core";
import { ZookeeperClient } from "@fluidframework/server-services-ordering-zookeeper";
import { IKafkaBaseOptions, IKafkaEndpoints, RdkafkaBase } from "./rdkafkaBase";
export interface IKafkaConsumerOptions extends Partial<IKafkaBaseOptions> {
consumeTimeout: number;
consumeLoopTimeoutDelay: number;
optimizedRebalance: boolean;
commitRetryDelay: number;
automaticConsume: boolean;
maxConsumerCommitRetries: number;
additionalOptions?: kafkaTypes.ConsumerGlobalConfig;
}
/**
* Kafka consumer using the node-rdkafka library
*/
export class RdkafkaConsumer extends RdkafkaBase implements IConsumer {
private readonly consumerOptions: IKafkaConsumerOptions;
private consumer?: kafkaTypes.KafkaConsumer;
private zooKeeperClient?: ZookeeperClient;
private closed = false;
private isRebalancing = true;
private assignedPartitions: Set<number> = new Set();
private readonly pendingCommits: Map<number, Deferred<void>> = new Map();
private readonly pendingMessages: Map<number, kafkaTypes.Message[]> = new Map();
private readonly latestOffsets: Map<number, number> = new Map();
constructor(
endpoints: IKafkaEndpoints,
clientId: string,
topic: string,
public readonly groupId: string,
options?: Partial<IKafkaConsumerOptions>) {
super(endpoints, clientId, topic, options);
this.consumerOptions = {
...options,
consumeTimeout: options?.consumeTimeout ?? 1000,
consumeLoopTimeoutDelay: options?.consumeLoopTimeoutDelay ?? 100,
optimizedRebalance: options?.optimizedRebalance ?? false,
commitRetryDelay: options?.commitRetryDelay ?? 1000,
automaticConsume: options?.automaticConsume ?? true,
maxConsumerCommitRetries: options?.maxConsumerCommitRetries ?? 10,
};
}
/**
* Returns true if the consumer is connected
*/
public isConnected() {
return this.consumer?.isConnected() ? true : false;
}
/**
* Returns the offset of the latest consumsed message
*/
public getLatestMessageOffset(partitionId: number): number | undefined {
return this.latestOffsets.get(partitionId);
}
protected connect() {
if (this.closed) {
return;
}
const zookeeperEndpoints = this.endpoints.zooKeeper;
if (zookeeperEndpoints && zookeeperEndpoints.length > 0) {
const zooKeeperEndpoint = zookeeperEndpoints[Math.floor(Math.random() % zookeeperEndpoints.length)];
this.zooKeeperClient = new ZookeeperClient(zooKeeperEndpoint);
}
const options: kafkaTypes.ConsumerGlobalConfig = {
"metadata.broker.list": this.endpoints.kafka.join(","),
"socket.keepalive.enable": true,
"socket.nagle.disable": true,
"client.id": this.clientId,
"group.id": this.groupId,
"enable.auto.commit": false,
"fetch.min.bytes": 1,
"fetch.max.bytes": 1024 * 1024,
"offset_commit_cb": true,
"rebalance_cb": this.consumerOptions.optimizedRebalance ? this.rebalance.bind(this) : true,
...this.consumerOptions.additionalOptions,
...this.sslOptions,
};
const consumer: kafkaTypes.KafkaConsumer = this.consumer =
new this.kafka.KafkaConsumer(options, { "auto.offset.reset": "latest" });
consumer.setDefaultConsumeTimeout(this.consumerOptions.consumeTimeout);
consumer.setDefaultConsumeLoopTimeoutDelay(this.consumerOptions.consumeLoopTimeoutDelay);
consumer.on("ready", () => {
consumer.subscribe([this.topic]);
if (this.consumerOptions.automaticConsume) {
// start the consume loop
consumer.consume();
}
this.emit("connected", consumer);
});
consumer.on("disconnected", () => {
this.emit("disconnected");
});
// eslint-disable-next-line @typescript-eslint/no-misused-promises
consumer.on("connection.failure", async (error) => {
await this.close(true);
this.error(error);
this.connect();
});
consumer.on("data", this.processMessage.bind(this));
consumer.on("offset.commit", (err, offsets) => {
let shouldRetryCommit = false;
if (err) {
// a rebalance occurred while we were committing
// we can resubmit the commit if we still own the partition
shouldRetryCommit =
this.consumerOptions.optimizedRebalance &&
(err.code === this.kafka.CODES.ERRORS.ERR_REBALANCE_IN_PROGRESS ||
err.code === this.kafka.CODES.ERRORS.ERR_ILLEGAL_GENERATION);
if (!shouldRetryCommit) {
this.error(err);
}
}
for (const offset of offsets) {
const deferredCommit = this.pendingCommits.get(offset.partition);
if (deferredCommit) {
if (shouldRetryCommit) {
setTimeout(() => {
if (this.assignedPartitions.has(offset.partition)) {
// we still own this partition. checkpoint again
this.consumer?.commit(offset);
}
}, this.consumerOptions.commitRetryDelay);
continue;
}
this.pendingCommits.delete(offset.partition);
if (err) {
deferredCommit.reject(err);
} else {
deferredCommit.resolve();
this.emit("checkpoint", offset.partition, offset.offset);
}
} else {
this.error(new Error(`Unknown commit for partition ${offset.partition}`));
}
}
});
// eslint-disable-next-line @typescript-eslint/no-misused-promises
consumer.on("rebalance", async (err, topicPartitions) => {
if (err.code === this.kafka.CODES.ERRORS.ERR__ASSIGN_PARTITIONS ||
err.code === this.kafka.CODES.ERRORS.ERR__REVOKE_PARTITIONS) {
const newAssignedPartitions = new Set<number>(topicPartitions.map((tp) => tp.partition));
if (newAssignedPartitions.size === this.assignedPartitions.size &&
Array.from(this.assignedPartitions).every((ap) => newAssignedPartitions.has(ap))) {
// the consumer is already up to date
return;
}
// clear pending messages
this.pendingMessages.clear();
if (!this.consumerOptions.optimizedRebalance) {
if (this.isRebalancing) {
this.isRebalancing = false;
} else {
this.emit("rebalancing", this.getPartitions(this.assignedPartitions), err.code);
}
}
const originalAssignedPartitions = this.assignedPartitions;
this.assignedPartitions = newAssignedPartitions;
try {
this.isRebalancing = true;
const partitions = this.getPartitions(this.assignedPartitions);
const partitionsWithEpoch = await this.fetchPartitionEpochs(partitions);
this.emit("rebalanced", partitionsWithEpoch, err.code);
// cleanup things left over from the lost partitions
for (const partition of originalAssignedPartitions) {
if (!newAssignedPartitions.has(partition)) {
// clear latest offset
this.latestOffsets.delete(partition);
// reject pending commit
const deferredCommit = this.pendingCommits.get(partition);
if (deferredCommit) {
this.pendingCommits.delete(partition);
deferredCommit.reject(new Error(`Partition for commit was unassigned. ${partition}`));
}
}
}
this.isRebalancing = false;
for (const pendingMessages of this.pendingMessages.values()) {
// process messages sent while we were rebalancing for each partition in order
for (const pendingMessage of pendingMessages) {
this.processMessage(pendingMessage);
}
}
} catch (ex) {
this.isRebalancing = false;
this.error(ex);
} finally {
this.pendingMessages.clear();
}
} else {
this.error(err);
}
});
consumer.on("rebalance.error", (error) => {
this.error(error);
});
consumer.on("event.error", (error) => {
this.error(error);
});
consumer.on("event.throttle", (event) => {
this.emit("throttled", event);
});
consumer.connect();
}
public async close(reconnecting: boolean = false): Promise<void> {
if (this.closed) {
return;
}
if (!reconnecting) {
// when closed outside of this class, disable reconnecting
this.closed = true;
}
await new Promise<void>((resolve) => {
if (this.consumer && this.consumer.isConnected()) {
this.consumer.disconnect(resolve);
} else {
resolve();
}
});
this.consumer = undefined;
if (this.zooKeeperClient) {
this.zooKeeperClient.close();
this.zooKeeperClient = undefined;
}
this.assignedPartitions.clear();
this.pendingCommits.clear();
this.latestOffsets.clear();
if (this.closed) {
this.emit("closed");
this.removeAllListeners();
}
}
public async commitCheckpoint(
partitionId: number,
queuedMessage: IQueuedMessage,
retries: number = 0): Promise<void> {
const startTime = Date.now();
try {
if (!this.consumer) {
throw new Error("Invalid consumer");
}
if (this.pendingCommits.has(partitionId)) {
throw new Error(`There is already a pending commit for partition ${partitionId}`);
}
// this will be resolved in the "offset.commit" event
const deferredCommit = new Deferred<void>();
this.pendingCommits.set(partitionId, deferredCommit);
// logs are replayed from the last checkpointed offset.
// to avoid reprocessing the last message twice, we checkpoint at offset + 1
this.consumer.commit({
topic: this.topic,
partition: partitionId,
offset: queuedMessage.offset + 1,
});
const result = await deferredCommit.promise;
const latency = Date.now() - startTime;
this.emit("checkpoint_success", partitionId, queuedMessage, retries, latency);
return result;
} catch (ex) {
const hasPartition = this.assignedPartitions.has(partitionId);
const willRetry = this.consumer?.isConnected()
&& retries < this.consumerOptions.maxConsumerCommitRetries
&& hasPartition;
const latency = Date.now() - startTime;
this.emit("checkpoint_error", partitionId, queuedMessage, retries, latency, willRetry, ex);
if (willRetry) {
return this.commitCheckpoint(partitionId, queuedMessage, retries + 1);
}
throw ex;
}
}
public async pause() {
this.consumer?.unsubscribe();
this.emit("paused");
return Promise.resolve();
}
public async resume() {
this.consumer?.subscribe([this.topic]);
this.emit("resumed");
return Promise.resolve();
}
/**
* Saves the latest offset for the partition and emits the data event with the message.
* If we are in the middle of rebalancing and the message was sent for a partition we will own,
* the message will be saved and processed after rebalancing is completed.
* @param message The message
*/
private processMessage(message: kafkaTypes.Message) {
const partition = message.partition;
if (this.isRebalancing && this.assignedPartitions.has(partition)) {
/*
It is possible to receive messages while we have not yet finished rebalancing
due to how we wait for the fetchPartitionEpochs call to finish before emitting the rebalanced event.
This means that the PartitionManager has not yet created the partition,
so messages will be lost since they were sent to an "untracked partition".
To fix this, we should temporarily store the messages and emit them once we finish rebalancing.
*/
let pendingMessages = this.pendingMessages.get(partition);
if (!pendingMessages) {
pendingMessages = [];
this.pendingMessages.set(partition, pendingMessages);
}
pendingMessages.push(message);
return;
}
this.latestOffsets.set(partition, message.offset);
this.emit("data", message as IQueuedMessage);
}
private getPartitions(partitions: Set<number>): IPartition[] {
return Array.from(partitions).map((partition) => ({
topic: this.topic,
partition,
offset: -1, // n/a
}));
}
/**
* The default node-rdkafka consumer rebalance callback with the addition
* of continuing from the last seen offset for assignments that have not changed
*/
private rebalance(err: kafkaTypes.LibrdKafkaError, assignments: kafkaTypes.Assignment[]) {
if (!this.consumer) {
return;
}
try {
if (err.code === this.kafka.CODES.ERRORS.ERR__ASSIGN_PARTITIONS) {
for (const assignment of assignments) {
const offset = this.latestOffsets.get(assignment.partition);
if (offset !== undefined) {
// this consumer is already assigned this partition
// ensure we continue reading from our current offset
// + 1 so we do not read the latest message again
(assignment as kafkaTypes.TopicPartitionOffset).offset = offset + 1;
}
}
this.consumer.assign(assignments);
} else if (err.code === this.kafka.CODES.ERRORS.ERR__REVOKE_PARTITIONS) {
this.consumer.unassign();
}
} catch (ex) {
if (this.consumer.isConnected()) {
this.consumer.emit("rebalance.error", ex);
}
}
}
private async fetchPartitionEpochs(partitions: IPartition[]): Promise<IPartitionWithEpoch[]> {
let epochs: number[];
if (this.zooKeeperClient) {
const epochsP = new Array<Promise<number>>();
for (const partition of partitions) {
epochsP.push(this.zooKeeperClient.getPartitionLeaderEpoch(this.topic, partition.partition));
}
epochs = await Promise.all(epochsP);
} else {
epochs = new Array(partitions.length).fill(0);
}
const partitionsWithEpoch: IPartitionWithEpoch[] = [];
for (let i = 0; i < partitions.length; ++i) {
const partitionWithEpoch = partitions[i] as IPartitionWithEpoch;
partitionWithEpoch.leaderEpoch = epochs[i];
partitionsWithEpoch.push(partitionWithEpoch);
}
return partitionsWithEpoch;
}
} | the_stack |
import { Promise as bPromise } from 'bluebird'
import { Signer, ethers, Contract, providers } from 'ethers'
import { TransactionReceipt } from '@ethersproject/abstract-provider'
import { getContractInterface, getContractFactory } from 'old-contracts'
import { getContractInterface as getNewContractInterface } from '@eth-optimism/contracts'
import {
L2Block,
RollupInfo,
BatchElement,
Batch,
QueueOrigin,
} from '@eth-optimism/core-utils'
import { Logger, Metrics } from '@eth-optimism/common-ts'
/* Internal Imports */
import {
CanonicalTransactionChainContract,
encodeAppendSequencerBatch,
BatchContext,
AppendSequencerBatchParams,
} from '../transaction-chain-contract'
import { BlockRange, BatchSubmitter } from '.'
import { TransactionSubmitter } from '../utils'
export interface AutoFixBatchOptions {
fixDoublePlayedDeposits: boolean
fixMonotonicity: boolean
fixSkippedDeposits: boolean
}
export class TransactionBatchSubmitter extends BatchSubmitter {
protected chainContract: CanonicalTransactionChainContract
protected l2ChainId: number
protected syncing: boolean
private autoFixBatchOptions: AutoFixBatchOptions
private transactionSubmitter: TransactionSubmitter
private gasThresholdInGwei: number
constructor(
signer: Signer,
l2Provider: providers.StaticJsonRpcProvider,
minTxSize: number,
maxTxSize: number,
maxBatchSize: number,
maxBatchSubmissionTime: number,
numConfirmations: number,
resubmissionTimeout: number,
addressManagerAddress: string,
minBalanceEther: number,
gasThresholdInGwei: number,
transactionSubmitter: TransactionSubmitter,
blockOffset: number,
logger: Logger,
metrics: Metrics,
autoFixBatchOptions: AutoFixBatchOptions = {
fixDoublePlayedDeposits: false,
fixMonotonicity: false,
fixSkippedDeposits: false,
} // TODO: Remove this
) {
super(
signer,
l2Provider,
minTxSize,
maxTxSize,
maxBatchSize,
maxBatchSubmissionTime,
numConfirmations,
resubmissionTimeout,
0, // Supply dummy value because it is not used.
addressManagerAddress,
minBalanceEther,
blockOffset,
logger,
metrics
)
this.autoFixBatchOptions = autoFixBatchOptions
this.gasThresholdInGwei = gasThresholdInGwei
this.transactionSubmitter = transactionSubmitter
}
/*****************************
* Batch Submitter Overrides *
****************************/
public async _updateChainInfo(): Promise<void> {
const info: RollupInfo = await this._getRollupInfo()
if (info.mode === 'verifier') {
this.logger.error(
'Verifier mode enabled! Batch submitter only compatible with sequencer mode'
)
process.exit(1)
}
this.syncing = info.syncing
const addrs = await this._getChainAddresses()
const ctcAddress = addrs.ctcAddress
if (
typeof this.chainContract !== 'undefined' &&
ctcAddress === this.chainContract.address
) {
this.logger.debug('Chain contract already initialized', {
ctcAddress,
})
return
}
const unwrapped_OVM_CanonicalTransactionChain = (
await getContractFactory('OVM_CanonicalTransactionChain', this.signer)
).attach(ctcAddress)
this.chainContract = new CanonicalTransactionChainContract(
unwrapped_OVM_CanonicalTransactionChain.address,
getContractInterface('OVM_CanonicalTransactionChain'),
this.signer
)
this.logger.info('Initialized new CTC', {
address: this.chainContract.address,
})
return
}
public async _onSync(): Promise<TransactionReceipt> {
const pendingQueueElements =
await this.chainContract.getNumPendingQueueElements()
this.logger.debug('Got number of pending queue elements', {
pendingQueueElements,
})
if (pendingQueueElements !== 0) {
this.logger.info(
'Syncing mode enabled! Skipping batch submission and clearing queue elements',
{ pendingQueueElements }
)
}
this.logger.info('Syncing mode enabled but queue is empty. Skipping...')
return
}
public async _getBatchStartAndEnd(): Promise<BlockRange> {
this.logger.info(
'Getting batch start and end for transaction batch submitter...'
)
const startBlock =
(await this.chainContract.getTotalElements()).toNumber() +
this.blockOffset
this.logger.info('Retrieved start block number from CTC', {
startBlock,
})
const endBlock =
Math.min(
startBlock + this.maxBatchSize,
await this.l2Provider.getBlockNumber()
) + 1 // +1 because the `endBlock` is *exclusive*
this.logger.info('Retrieved end block number from L2 sequencer', {
endBlock,
})
if (startBlock >= endBlock) {
if (startBlock > endBlock) {
this.logger
.error(`More chain elements in L1 (${startBlock}) than in the L2 node (${endBlock}).
This shouldn't happen because we don't submit batches if the sequencer is syncing.`)
}
this.logger.info('No txs to submit. Skipping batch submission...')
return
}
return {
start: startBlock,
end: endBlock,
}
}
public async _submitBatch(
startBlock: number,
endBlock: number
): Promise<TransactionReceipt> {
// Do not submit batch if gas price above threshold
const gasPriceInGwei = parseInt(
ethers.utils.formatUnits(await this.signer.getGasPrice(), 'gwei'),
10
)
if (gasPriceInGwei > this.gasThresholdInGwei) {
this.logger.warn(
'Gas price is higher than gas price threshold; aborting batch submission',
{
gasPriceInGwei,
gasThresholdInGwei: this.gasThresholdInGwei,
}
)
return
}
const [batchParams, wasBatchTruncated] =
await this._generateSequencerBatchParams(startBlock, endBlock)
const batchSizeInBytes = encodeAppendSequencerBatch(batchParams).length / 2
this.logger.debug('Sequencer batch generated', {
batchSizeInBytes,
})
// Only submit batch if one of the following is true:
// 1. it was truncated
// 2. it is large enough
// 3. enough time has passed since last submission
if (!wasBatchTruncated && !this._shouldSubmitBatch(batchSizeInBytes)) {
return
}
this.metrics.numTxPerBatch.observe(endBlock - startBlock)
const l1tipHeight = await this.signer.provider.getBlockNumber()
this.logger.debug('Submitting batch.', {
calldata: batchParams,
l1tipHeight,
})
return this.submitAppendSequencerBatch(batchParams)
}
/*********************
* Private Functions *
********************/
private async submitAppendSequencerBatch(
batchParams: AppendSequencerBatchParams
): Promise<TransactionReceipt> {
const tx =
await this.chainContract.customPopulateTransaction.appendSequencerBatch(
batchParams
)
const submitTransaction = (): Promise<TransactionReceipt> => {
return this.transactionSubmitter.submitTransaction(
tx,
this._makeHooks('appendSequencerBatch')
)
}
return this._submitAndLogTx(submitTransaction, 'Submitted batch!')
}
private async _generateSequencerBatchParams(
startBlock: number,
endBlock: number
): Promise<[AppendSequencerBatchParams, boolean]> {
// Get all L2 BatchElements for the given range
const blockRange = endBlock - startBlock
let batch: Batch = await bPromise.map(
[...Array(blockRange).keys()],
(i) => {
this.logger.debug('Fetching L2BatchElement', {
blockNo: startBlock + i,
})
return this._getL2BatchElement(startBlock + i)
},
{ concurrency: 100 }
)
// Fix our batches if we are configured to. TODO: Remove this.
batch = await this._fixBatch(batch)
if (!(await this._validateBatch(batch))) {
this.metrics.malformedBatches.inc()
return
}
let sequencerBatchParams = await this._getSequencerBatchParams(
startBlock,
batch
)
let wasBatchTruncated = false
let encoded = encodeAppendSequencerBatch(sequencerBatchParams)
while (encoded.length / 2 > this.maxTxSize) {
this.logger.debug('Splicing batch...', {
batchSizeInBytes: encoded.length / 2,
})
batch.splice(Math.ceil((batch.length * 2) / 3)) // Delete 1/3rd of all of the batch elements
sequencerBatchParams = await this._getSequencerBatchParams(
startBlock,
batch
)
encoded = encodeAppendSequencerBatch(sequencerBatchParams)
// This is to prevent against the case where a batch is oversized,
// but then gets truncated to the point where it is under the minimum size.
// In this case, we want to submit regardless of the batch's size.
wasBatchTruncated = true
}
this.logger.info('Generated sequencer batch params', {
contexts: sequencerBatchParams.contexts,
transactions: sequencerBatchParams.transactions,
wasBatchTruncated,
})
return [sequencerBatchParams, wasBatchTruncated]
}
/**
* Returns true if the batch is valid.
*/
protected async _validateBatch(batch: Batch): Promise<boolean> {
// Verify all of the queue elements are what we expect
let nextQueueIndex = await this.chainContract.getNextQueueIndex()
for (const ele of batch) {
this.logger.debug('Verifying batch element', { ele })
if (!ele.isSequencerTx) {
this.logger.debug('Checking queue equality against L1 queue index', {
nextQueueIndex,
})
if (!(await this._doesQueueElementMatchL1(nextQueueIndex, ele))) {
return false
}
nextQueueIndex++
}
}
// Verify all of the batch elements are monotonic
let lastTimestamp: number
let lastBlockNumber: number
for (const [idx, ele] of batch.entries()) {
if (ele.timestamp < lastTimestamp) {
this.logger.error('Timestamp monotonicity violated! Element', {
idx,
ele,
})
return false
}
if (ele.blockNumber < lastBlockNumber) {
this.logger.error('Block Number monotonicity violated! Element', {
idx,
ele,
})
return false
}
lastTimestamp = ele.timestamp
lastBlockNumber = ele.blockNumber
}
return true
}
private async _doesQueueElementMatchL1(
queueIndex: number,
queueElement: BatchElement
): Promise<boolean> {
const logEqualityError = (name, index, expected, got) => {
this.logger.error('Observed mismatched values', {
index,
expected,
got,
})
}
let isEqual = true
const [queueEleHash, timestamp, blockNumber] =
await this.chainContract.getQueueElement(queueIndex)
// TODO: Verify queue element hash equality. The queue element hash can be computed with:
// keccak256( abi.encode( msg.sender, _target, _gasLimit, _data))
// Check timestamp & blockNumber equality
if (timestamp !== queueElement.timestamp) {
isEqual = false
logEqualityError(
'Timestamp',
queueIndex,
timestamp,
queueElement.timestamp
)
}
if (blockNumber !== queueElement.blockNumber) {
isEqual = false
logEqualityError(
'Block Number',
queueIndex,
blockNumber,
queueElement.blockNumber
)
}
return isEqual
}
/**
* Takes in a batch which is potentially malformed & returns corrected version.
* Current fixes that are supported:
* - Double played deposits.
*/
private async _fixBatch(batch: Batch): Promise<Batch> {
const fixDoublePlayedDeposits = async (b: Batch): Promise<Batch> => {
let nextQueueIndex = await this.chainContract.getNextQueueIndex()
const fixedBatch: Batch = []
for (const ele of b) {
if (!ele.isSequencerTx) {
if (!(await this._doesQueueElementMatchL1(nextQueueIndex, ele))) {
this.logger.warn('Fixing double played queue element.', {
nextQueueIndex,
})
fixedBatch.push(
await this._fixDoublePlayedDepositQueueElement(
nextQueueIndex,
ele
)
)
continue
}
nextQueueIndex++
}
fixedBatch.push(ele)
}
return fixedBatch
}
const fixSkippedDeposits = async (b: Batch): Promise<Batch> => {
this.logger.debug('Fixing skipped deposits...')
let nextQueueIndex = await this.chainContract.getNextQueueIndex()
const fixedBatch: Batch = []
for (const ele of b) {
// Look for skipped deposits
while (true) {
const pendingQueueElements =
await this.chainContract.getNumPendingQueueElements()
const nextRemoteQueueElements =
await this.chainContract.getNextQueueIndex()
const totalQueueElements =
pendingQueueElements + nextRemoteQueueElements
// No more queue elements so we clearly haven't skipped anything
if (nextQueueIndex >= totalQueueElements) {
break
}
const [queueEleHash, timestamp, blockNumber] =
await this.chainContract.getQueueElement(nextQueueIndex)
if (timestamp < ele.timestamp || blockNumber < ele.blockNumber) {
this.logger.warn('Fixing skipped deposit', {
badTimestamp: ele.timestamp,
skippedQueueTimestamp: timestamp,
badBlockNumber: ele.blockNumber,
skippedQueueBlockNumber: blockNumber,
})
// Push a dummy queue element
fixedBatch.push({
stateRoot: ele.stateRoot,
isSequencerTx: false,
rawTransaction: undefined,
timestamp,
blockNumber,
})
nextQueueIndex++
} else {
// The next queue element's timestamp is after this batch element so
// we must not have skipped anything.
break
}
}
fixedBatch.push(ele)
if (!ele.isSequencerTx) {
nextQueueIndex++
}
}
return fixedBatch
}
// TODO: Remove this super complex logic and rely on Geth to actually supply correct block data.
const fixMonotonicity = async (b: Batch): Promise<Batch> => {
this.logger.debug('Fixing monotonicity...')
// The earliest allowed timestamp/blockNumber is the last timestamp submitted on chain.
const { lastTimestamp, lastBlockNumber } =
await this._getLastTimestampAndBlockNumber()
let earliestTimestamp = lastTimestamp
let earliestBlockNumber = lastBlockNumber
this.logger.debug('Determined earliest timestamp and blockNumber', {
earliestTimestamp,
earliestBlockNumber,
})
// The latest allowed timestamp/blockNumber is the next queue element!
let nextQueueIndex = await this.chainContract.getNextQueueIndex()
let latestTimestamp: number
let latestBlockNumber: number
// updateLatestTimestampAndBlockNumber is a helper which updates
// the latest timestamp and block number based on the pending queue elements.
const updateLatestTimestampAndBlockNumber = async () => {
const pendingQueueElements =
await this.chainContract.getNumPendingQueueElements()
const nextRemoteQueueElements =
await this.chainContract.getNextQueueIndex()
const totalQueueElements =
pendingQueueElements + nextRemoteQueueElements
if (nextQueueIndex < totalQueueElements) {
const [queueEleHash, queueTimestamp, queueBlockNumber] =
await this.chainContract.getQueueElement(nextQueueIndex)
latestTimestamp = queueTimestamp
latestBlockNumber = queueBlockNumber
} else {
// If there are no queue elements left then just allow any timestamp/blocknumber
latestTimestamp = Number.MAX_SAFE_INTEGER
latestBlockNumber = Number.MAX_SAFE_INTEGER
}
}
// Actually update the latest timestamp and block number
await updateLatestTimestampAndBlockNumber()
this.logger.debug('Determined latest timestamp and blockNumber', {
latestTimestamp,
latestBlockNumber,
})
// Now go through our batch and fix the timestamps and block numbers
// to automatically enforce monotonicity.
const fixedBatch: Batch = []
for (const ele of b) {
if (!ele.isSequencerTx) {
// Set the earliest allowed timestamp to the old latest and set the new latest
// to the next queue element's timestamp / blockNumber
earliestTimestamp = latestTimestamp
earliestBlockNumber = latestBlockNumber
nextQueueIndex++
await updateLatestTimestampAndBlockNumber()
}
// Fix the element if its timestammp/blockNumber is too small
if (
ele.timestamp < earliestTimestamp ||
ele.blockNumber < earliestBlockNumber
) {
this.logger.warn('Fixing timestamp/blockNumber too small', {
oldTimestamp: ele.timestamp,
newTimestamp: earliestTimestamp,
oldBlockNumber: ele.blockNumber,
newBlockNumber: earliestBlockNumber,
})
ele.timestamp = earliestTimestamp
ele.blockNumber = earliestBlockNumber
}
// Fix the element if its timestammp/blockNumber is too large
if (
ele.timestamp > latestTimestamp ||
ele.blockNumber > latestBlockNumber
) {
this.logger.warn('Fixing timestamp/blockNumber too large.', {
oldTimestamp: ele.timestamp,
newTimestamp: latestTimestamp,
oldBlockNumber: ele.blockNumber,
newBlockNumber: latestBlockNumber,
})
ele.timestamp = latestTimestamp
ele.blockNumber = latestBlockNumber
}
earliestTimestamp = ele.timestamp
earliestBlockNumber = ele.blockNumber
fixedBatch.push(ele)
}
return fixedBatch
}
// NOTE: It is unsafe to combine multiple autoFix options.
// If you must combine them, manually verify the output before proceeding.
if (this.autoFixBatchOptions.fixDoublePlayedDeposits) {
batch = await fixDoublePlayedDeposits(batch)
}
if (this.autoFixBatchOptions.fixMonotonicity) {
batch = await fixMonotonicity(batch)
}
if (this.autoFixBatchOptions.fixSkippedDeposits) {
batch = await fixSkippedDeposits(batch)
}
return batch
}
private async _getLastTimestampAndBlockNumber(): Promise<{
lastTimestamp: number
lastBlockNumber: number
}> {
const manager = new Contract(
this.addressManagerAddress,
getNewContractInterface('Lib_AddressManager'),
this.signer.provider
)
const addr = await manager.getAddress(
'OVM_ChainStorageContainer-CTC-batches'
)
const container = new Contract(
addr,
getNewContractInterface('iOVM_ChainStorageContainer'),
this.signer.provider
)
let meta = await container.getGlobalMetadata()
// remove 0x
meta = meta.slice(2)
// convert to bytes27
meta = meta.slice(10)
const totalElements = meta.slice(-10)
const nextQueueIndex = meta.slice(-20, -10)
const lastTimestamp = parseInt(meta.slice(-30, -20), 16)
const lastBlockNumber = parseInt(meta.slice(-40, -30), 16)
this.logger.debug('Retrieved timestamp and block number from CTC', {
lastTimestamp,
lastBlockNumber,
})
return { lastTimestamp, lastBlockNumber }
}
private async _fixDoublePlayedDepositQueueElement(
queueIndex: number,
queueElement: BatchElement
): Promise<BatchElement> {
const [queueEleHash, timestamp, blockNumber] =
await this.chainContract.getQueueElement(queueIndex)
if (
timestamp > queueElement.timestamp &&
blockNumber > queueElement.blockNumber
) {
this.logger.warn(
'Double deposit detected. Fixing by skipping the deposit & replacing with a dummy tx.',
{
timestamp,
blockNumber,
queueElementTimestamp: queueElement.timestamp,
queueElementBlockNumber: queueElement.blockNumber,
}
)
const dummyTx: string = '0x1234'
return {
stateRoot: queueElement.stateRoot,
isSequencerTx: true,
rawTransaction: dummyTx,
timestamp: queueElement.timestamp,
blockNumber: queueElement.blockNumber,
}
}
if (
timestamp < queueElement.timestamp &&
blockNumber < queueElement.blockNumber
) {
this.logger.error('A deposit seems to have been skipped!')
throw new Error('Skipped deposit?!')
}
throw new Error('Unable to fix queue element!')
}
private async _getSequencerBatchParams(
shouldStartAtIndex: number,
blocks: Batch
): Promise<AppendSequencerBatchParams> {
const totalElementsToAppend = blocks.length
// Generate contexts
const contexts: BatchContext[] = []
let lastBlockIsSequencerTx = false
let lastTimestamp = 0
let lastBlockNumber = 0
const groupedBlocks: Array<{
sequenced: BatchElement[]
queued: BatchElement[]
}> = []
for (const block of blocks) {
if (
(lastBlockIsSequencerTx === false && block.isSequencerTx === true) ||
groupedBlocks.length === 0 ||
(block.timestamp !== lastTimestamp && block.isSequencerTx === true) ||
(block.blockNumber !== lastBlockNumber && block.isSequencerTx === true)
) {
groupedBlocks.push({
sequenced: [],
queued: [],
})
}
const cur = groupedBlocks.length - 1
block.isSequencerTx
? groupedBlocks[cur].sequenced.push(block)
: groupedBlocks[cur].queued.push(block)
lastBlockIsSequencerTx = block.isSequencerTx
lastTimestamp = block.timestamp
lastBlockNumber = block.blockNumber
}
for (const groupedBlock of groupedBlocks) {
if (
groupedBlock.sequenced.length === 0 &&
groupedBlock.queued.length === 0
) {
throw new Error(
'Attempted to generate batch context with 0 queued and 0 sequenced txs!'
)
}
contexts.push({
numSequencedTransactions: groupedBlock.sequenced.length,
numSubsequentQueueTransactions: groupedBlock.queued.length,
timestamp:
groupedBlock.sequenced.length > 0
? groupedBlock.sequenced[0].timestamp
: groupedBlock.queued[0].timestamp,
blockNumber:
groupedBlock.sequenced.length > 0
? groupedBlock.sequenced[0].blockNumber
: groupedBlock.queued[0].blockNumber,
})
}
// Generate sequencer transactions
const transactions: string[] = []
for (const block of blocks) {
if (!block.isSequencerTx) {
continue
}
transactions.push(block.rawTransaction)
}
return {
shouldStartAtElement: shouldStartAtIndex - this.blockOffset,
totalElementsToAppend,
contexts,
transactions,
}
}
private async _getL2BatchElement(blockNumber: number): Promise<BatchElement> {
const block = await this._getBlock(blockNumber)
this.logger.debug('Fetched L2 block', {
block,
})
const batchElement = {
stateRoot: block.stateRoot,
timestamp: block.timestamp,
blockNumber: block.transactions[0].l1BlockNumber,
isSequencerTx: false,
rawTransaction: undefined,
}
if (this._isSequencerTx(block)) {
batchElement.isSequencerTx = true
batchElement.rawTransaction = block.transactions[0].rawTransaction
}
return batchElement
}
private async _getBlock(blockNumber: number): Promise<L2Block> {
const p = this.l2Provider.getBlockWithTransactions(blockNumber)
return p as Promise<L2Block>
}
private _isSequencerTx(block: L2Block): boolean {
return block.transactions[0].queueOrigin === QueueOrigin.Sequencer
}
} | the_stack |
jest.unmock('../../src/test-provider/test-provider');
jest.unmock('../../src/test-provider/test-provider-context');
jest.unmock('./test-helper');
jest.unmock('../../src/appGlobals');
import * as vscode from 'vscode';
import { JestTestProvider } from '../../src/test-provider/test-provider';
import { WorkspaceRoot } from '../../src/test-provider/test-item-data';
import { JestTestProviderContext } from '../../src/test-provider/test-provider-context';
import { extensionId } from '../../src/appGlobals';
import { mockController, mockExtExplorerContext } from './test-helper';
const throwError = () => {
throw new Error('debug error');
};
describe('JestTestProvider', () => {
const makeItemData = (debuggable = true) => {
const data: any = {
discoverTest: jest.fn(),
scheduleTest: jest.fn(),
dispose: jest.fn(),
};
if (debuggable) {
data.getDebugInfo = jest.fn();
}
return data;
};
const setupTestItemData = (
id: string,
debuggable = true,
context?: JestTestProviderContext
): any => {
const data = makeItemData(debuggable);
data.item = context?.createTestItem(id, id, {} as any, data) ?? { id };
return data;
};
let controllerMock;
let extExplorerContextMock;
let workspaceRootMock;
let mockTestTag;
beforeEach(() => {
jest.resetAllMocks();
extExplorerContextMock = mockExtExplorerContext();
controllerMock = mockController();
(vscode.tests.createTestController as jest.Mocked<any>).mockImplementation((id, label) => {
controllerMock.id = id;
controllerMock.label = label;
return controllerMock;
});
mockTestTag = jest.fn((id) => ({ id }));
(vscode.TestTag as jest.Mocked<any>) = mockTestTag;
(vscode.workspace.getWorkspaceFolder as jest.Mocked<any>).mockImplementation((uri) => ({
name: uri,
}));
(WorkspaceRoot as jest.Mocked<any>).mockImplementation((context) => {
workspaceRootMock = setupTestItemData('workspace-root', false, context);
workspaceRootMock.context = context;
return workspaceRootMock;
});
});
describe('upon creation', () => {
it('will setup controller and WorkspaceRoot', () => {
new JestTestProvider(extExplorerContextMock);
expect(controllerMock.resolveHandler).not.toBeUndefined();
expect(vscode.tests.createTestController).toHaveBeenCalledWith(
`${extensionId}:TestProvider:ws-1`,
expect.stringContaining('ws-1')
);
expect(controllerMock.createRunProfile).toHaveBeenCalledTimes(2);
[
[vscode.TestRunProfileKind.Run, 'run'],
[vscode.TestRunProfileKind.Debug, 'debug'],
].forEach(([kind, id]) => {
expect(controllerMock.createRunProfile).toHaveBeenCalledWith(
expect.anything(),
kind,
expect.anything(),
true,
expect.objectContaining({ id })
);
});
expect(WorkspaceRoot).toBeCalled();
});
it.each`
isWatchMode
${true}
${false}
`('will create Profiles regardless isWatchMode=$isWatchMode', ({ isWatchMode }) => {
extExplorerContextMock.autoRun.isWatch = isWatchMode;
new JestTestProvider(extExplorerContextMock);
const kinds = [vscode.TestRunProfileKind.Debug, vscode.TestRunProfileKind.Run];
expect(controllerMock.createRunProfile).toHaveBeenCalledTimes(kinds.length);
kinds.forEach((kind) => {
expect(controllerMock.createRunProfile).toHaveBeenCalledWith(
expect.anything(),
kind,
expect.anything(),
true,
expect.anything()
);
});
});
});
describe('can discover tests', () => {
it('should only discover items with canResolveChildren = true', () => {
new JestTestProvider(extExplorerContextMock);
const data = setupTestItemData('whatever', true, workspaceRootMock.context);
data.item.canResolveChildren = true;
controllerMock.resolveHandler(data.item);
expect(controllerMock.createTestRun).toBeCalled();
controllerMock.createTestRun.mockClear();
data.item.canResolveChildren = false;
controllerMock.resolveHandler(data.item);
expect(controllerMock.createTestRun).not.toBeCalled();
});
describe('when no test item is requested', () => {
it('will resolve the whole workspace via workspaceRoot', () => {
new JestTestProvider(extExplorerContextMock);
workspaceRootMock.item.canResolveChildren = true;
controllerMock.resolveHandler();
expect(controllerMock.createTestRun).toBeCalled();
expect(workspaceRootMock.discoverTest).toBeCalledTimes(1);
expect(workspaceRootMock.discoverTest).toBeCalledWith(controllerMock.lastRunMock());
// run will be created with the controller's id
expect(controllerMock.lastRunMock().name).toEqual(
expect.stringContaining(controllerMock.id)
);
// run will be closed
expect(controllerMock.lastRunMock().end).toBeCalled();
});
});
describe('when specific item is requested', () => {
it('will forward the request to the item', () => {
new JestTestProvider(extExplorerContextMock);
const data = setupTestItemData('whatever', true, workspaceRootMock.context);
data.item.canResolveChildren = true;
controllerMock.resolveHandler(data.item);
expect(controllerMock.createTestRun).toBeCalled();
expect(data.discoverTest).toBeCalledWith(controllerMock.lastRunMock());
// run will be created with the controller's id
expect(controllerMock.lastRunMock().name).toEqual(
expect.stringContaining(controllerMock.id)
);
// run will be closed
expect(controllerMock.lastRunMock().end).toBeCalled();
});
it('should not crash if item not found in the item-data map', () => {
new JestTestProvider(extExplorerContextMock);
const data = makeItemData(true);
controllerMock.resolveHandler({ canResolveChildren: true });
expect(controllerMock.createTestRun).toBeCalled();
expect(data.discoverTest).not.toBeCalled();
expect(workspaceRootMock.discoverTest).not.toBeCalled();
// run will be created with the controller's id
expect(controllerMock.lastRunMock().name).toEqual(
expect.stringContaining(controllerMock.id)
);
// run will be closed
expect(controllerMock.lastRunMock().end).toBeCalled();
});
});
describe('if discover failed', () => {
it('error will be reported', () => {
new JestTestProvider(extExplorerContextMock);
workspaceRootMock.discoverTest.mockImplementation(() => {
throw new Error('forced crash');
});
workspaceRootMock.item.canResolveChildren = true;
controllerMock.resolveHandler();
expect(workspaceRootMock.item.error).toEqual(expect.stringContaining('discoverTest error'));
// run will be created with the controller's id
expect(controllerMock.lastRunMock().name).toEqual(
expect.stringContaining(controllerMock.id)
);
// run will be closed
expect(controllerMock.lastRunMock().end).toBeCalled();
});
});
});
describe('upon dispose', () => {
it('vscode.TestController will be disposed', () => {
const testProvider = new JestTestProvider(extExplorerContextMock);
testProvider.dispose();
expect(controllerMock.dispose).toBeCalled();
expect(workspaceRootMock.dispose).toBeCalled();
});
});
describe('supports explorer UI run and debug request', () => {
let cancelToken;
const setupItemData = (context, items = [1, 2, 3]) => {
const itemDataList = items.map((n) => setupTestItemData(`item-${n}`, true, context));
itemDataList.forEach((d) => {
d.context = { workspace: { name: 'whatever' } };
d.getDebugInfo = jest.fn().mockReturnValueOnce({});
});
return itemDataList;
};
beforeEach(() => {
cancelToken = { onCancellationRequested: jest.fn() };
});
describe('debug tests', () => {
let debugDone;
const finishDebug = async () => {
debugDone();
// flush system promise job queue
await Promise.resolve();
};
const controlled = () =>
new Promise<void>((resolve) => {
debugDone = () => resolve();
});
it.each`
debugInfo | testNamePattern | debugTests | hasError
${undefined} | ${undefined} | ${() => Promise.resolve()} | ${true}
${{ fileName: 'file' }} | ${'a test'} | ${() => Promise.resolve()} | ${false}
${{ fileName: 'file' }} | ${'a test'} | ${() => Promise.reject('error')} | ${true}
${{ fileName: 'file' }} | ${'a test'} | ${throwError} | ${true}
${{ fileName: 'file' }} | ${undefined} | ${() => Promise.resolve()} | ${false}
`(
"invoke debug test async: debugInfo = '$debugInfo', testNamePattern='$testNamePattern' when resultContextMock.debugTests = $resultContextMock.debugTests => error? $hasError",
async ({ debugInfo, testNamePattern, debugTests, hasError }) => {
expect.hasAssertions();
extExplorerContextMock.debugTests = jest.fn().mockImplementation(() => {
if (debugTests) {
return debugTests();
}
});
const testProvider = new JestTestProvider(extExplorerContextMock);
const itemDataList = setupItemData(workspaceRootMock.context, [1]);
itemDataList.forEach((d) => {
if (debugInfo) {
d.getDebugInfo = jest
.fn()
.mockImplementation(() =>
testNamePattern ? { ...debugInfo, testNamePattern } : debugInfo
);
} else {
d.getDebugInfo = undefined;
}
});
const request: any = {
include: itemDataList.map((d) => d.item),
profile: { kind: vscode.TestRunProfileKind.Debug },
};
await expect(testProvider.runTests(request, cancelToken)).resolves.toBe(undefined);
if (hasError) {
expect(controllerMock.lastRunMock().errored).toBeCalledWith(
itemDataList[0].item,
expect.anything()
);
expect(vscode.TestMessage).toBeCalledTimes(1);
} else {
if (testNamePattern) {
expect(extExplorerContextMock.debugTests).toBeCalledWith('file', testNamePattern);
} else {
expect(extExplorerContextMock.debugTests).toBeCalledWith('file');
}
}
}
);
it('debug tests are done in serial', async () => {
expect.hasAssertions();
extExplorerContextMock.debugTests.mockImplementation(controlled);
const testProvider = new JestTestProvider(extExplorerContextMock);
const itemDataList = setupItemData(workspaceRootMock.context);
const request: any = {
include: itemDataList.map((d) => d.item),
profile: { kind: vscode.TestRunProfileKind.Debug },
};
const p = testProvider.runTests(request, cancelToken);
// a run is created
expect(controllerMock.createTestRun).toBeCalled();
// verify seerial execution
expect(extExplorerContextMock.debugTests).toBeCalledTimes(1);
await finishDebug();
expect(extExplorerContextMock.debugTests).toBeCalledTimes(2);
await finishDebug();
expect(extExplorerContextMock.debugTests).toBeCalledTimes(3);
await finishDebug();
await p;
expect(extExplorerContextMock.debugTests).toBeCalledTimes(3);
// the run will be closed
expect(controllerMock.lastRunMock().end).toBeCalled();
});
it('cancellation means skip the rest of tests', async () => {
expect.hasAssertions();
extExplorerContextMock.debugTests.mockImplementation(controlled);
const testProvider = new JestTestProvider(extExplorerContextMock);
const itemDataList = setupItemData(workspaceRootMock.context);
const request: any = {
include: itemDataList.map((d) => d.item),
profile: { kind: vscode.TestRunProfileKind.Debug },
};
const p = testProvider.runTests(request, cancelToken);
// a run is created
expect(controllerMock.createTestRun).toBeCalled();
expect(extExplorerContextMock.debugTests).toBeCalledTimes(1);
const runMock = controllerMock.lastRunMock();
await finishDebug();
expect(extExplorerContextMock.debugTests).toBeCalledTimes(2);
// cancel the run during 2nd debug, the 3rd one should be skipped
cancelToken.isCancellationRequested = true;
await finishDebug();
expect(extExplorerContextMock.debugTests).toBeCalledTimes(2);
await p;
expect(extExplorerContextMock.debugTests).toBeCalledTimes(2);
expect(runMock.skipped).toBeCalledWith(request.include[2]);
// the run will be closed
expect(runMock.end).toBeCalledTimes(1);
});
it('can handle exception', async () => {
expect.hasAssertions();
extExplorerContextMock.debugTests
.mockImplementationOnce(() => Promise.resolve())
.mockImplementationOnce(() => Promise.reject())
.mockImplementationOnce(throwError);
const testProvider = new JestTestProvider(extExplorerContextMock);
const itemDataList = setupItemData(workspaceRootMock.context);
const request: any = {
include: itemDataList.map((d) => d.item),
profile: { kind: vscode.TestRunProfileKind.Debug },
};
await testProvider.runTests(request, cancelToken);
const runMock = controllerMock.lastRunMock();
expect(extExplorerContextMock.debugTests).toBeCalledTimes(3);
expect(runMock.errored).toBeCalledTimes(2);
expect(runMock.errored).toBeCalledWith(request.include[1], expect.anything());
expect(runMock.errored).toBeCalledWith(request.include[2], expect.anything());
expect(runMock.end).toBeCalled();
});
});
describe('run tests', () => {
const resolveSchedule = (_r, resolve) => {
resolve();
};
it.each`
scheduleTest | isCancelled | state
${resolveSchedule} | ${false} | ${undefined}
${resolveSchedule} | ${true} | ${'skipped'}
${throwError} | ${false} | ${'errored'}
`(
'run test should always resolve: schedule test pid = $pid, isCancelled=$isCancelled => state? $state',
async ({ scheduleTest, isCancelled, state }) => {
expect.hasAssertions();
const testProvider = new JestTestProvider(extExplorerContextMock);
const itemDataList = setupItemData(workspaceRootMock.context, [1]);
itemDataList.forEach((d) => d.scheduleTest.mockImplementation(scheduleTest));
const tData = itemDataList[0];
const request: any = {
include: itemDataList.map((d) => d.item),
profile: { kind: vscode.TestRunProfileKind.Run },
};
cancelToken.isCancellationRequested = isCancelled;
const p = testProvider.runTests(request, cancelToken);
const runMock = controllerMock.lastRunMock();
if (isCancelled) {
expect(tData.scheduleTest).not.toBeCalled();
} else {
expect(tData.scheduleTest).toBeCalled();
}
await expect(p).resolves.toBe(undefined);
expect(runMock.end).toBeCalled();
switch (state) {
case 'errored':
expect(runMock.errored).toBeCalledWith(tData.item, expect.anything());
expect(vscode.TestMessage).toBeCalledTimes(1);
break;
case 'skipped':
expect(runMock.skipped).toBeCalledWith(tData.item);
expect(vscode.TestMessage).not.toBeCalled();
break;
case undefined:
break;
default:
expect('unhandled state type').toBeUndefined();
break;
}
}
);
it('running tests in parallel', async () => {
expect.hasAssertions();
const testProvider = new JestTestProvider(extExplorerContextMock);
const itemDataList = setupItemData(workspaceRootMock.context);
// itemDataList.forEach((d, idx) => d.scheduleTest.mockReturnValueOnce(`pid-${idx}`));
const request: any = {
include: itemDataList.map((d) => d.item),
profile: { kind: vscode.TestRunProfileKind.Run },
};
const p = testProvider.runTests(request, cancelToken);
// a run is created
expect(controllerMock.createTestRun).toBeCalled();
const runMock = controllerMock.lastRunMock();
itemDataList.forEach((d) => {
expect(d.scheduleTest).toBeCalled();
const [run, resolve] = d.scheduleTest.mock.calls[0];
expect(run).toBe(runMock);
// close the schedule
resolve();
});
await p;
expect(runMock.end).toBeCalled();
});
it('cancellation is passed to the itemData to handle', async () => {
expect.hasAssertions();
const testProvider = new JestTestProvider(extExplorerContextMock);
const itemDataList = setupItemData(workspaceRootMock.context);
itemDataList.forEach((d, idx) => d.scheduleTest.mockReturnValueOnce(`pid-${idx}`));
const request: any = {
include: itemDataList.map((d) => d.item),
profile: { kind: vscode.TestRunProfileKind.Run },
};
const p = testProvider.runTests(request, cancelToken);
const runMock = controllerMock.lastRunMock();
// cacnel after run
cancelToken.isCancellationRequested = true;
// a run is already created
expect(controllerMock.createTestRun).toBeCalled();
itemDataList.forEach((d) => {
expect(d.scheduleTest).toBeCalled();
const [run, resolve] = d.scheduleTest.mock.calls[0];
expect(run).toBe(runMock);
// close the schedule
resolve();
});
await p;
expect(runMock.end).toBeCalledTimes(1);
});
it('can handle exception', async () => {
expect.hasAssertions();
const testProvider = new JestTestProvider(extExplorerContextMock);
const itemDataList = setupItemData(workspaceRootMock.context);
itemDataList.forEach((d, idx) => {
if (idx === 1) {
d.scheduleTest.mockImplementation(() => {
throw new Error('error scheduling test');
});
} else {
d.scheduleTest.mockReturnValueOnce(`pid-${idx}`);
}
});
const request: any = {
include: itemDataList.map((d) => d.item),
profile: { kind: vscode.TestRunProfileKind.Run },
};
const p = testProvider.runTests(request, cancelToken);
// cacnel after run
cancelToken.isCancellationRequested = true;
// a run is already created
expect(controllerMock.createTestRun).toBeCalled();
const runMock = controllerMock.lastRunMock();
itemDataList.forEach((d, idx) => {
expect(d.scheduleTest).toBeCalled();
const [run, resolve] = d.scheduleTest.mock.calls[0];
expect(run).toBe(runMock);
/* eslint-disable jest/no-conditional-expect */
if (idx === 1) {
expect(run.errored).toBeCalledWith(d.item, expect.anything());
} else {
expect(run.errored).not.toBeCalledWith(d.item, expect.anything());
// close the schedule
resolve();
}
});
await p;
expect(runMock.end).toBeCalled();
});
it('if no item in request, will run test for the whole workplace', async () => {
expect.hasAssertions();
const testProvider = new JestTestProvider(extExplorerContextMock);
const request: any = {
profile: { kind: vscode.TestRunProfileKind.Run },
};
const p = testProvider.runTests(request, cancelToken);
const runMock = controllerMock.lastRunMock();
expect(workspaceRootMock.scheduleTest).toBeCalledTimes(1);
const [run, resolve] = workspaceRootMock.scheduleTest.mock.calls[0];
expect(run).toBe(runMock);
resolve();
await p;
expect(runMock.end).toBeCalled();
});
it('will reject run request without profile', async () => {
expect.hasAssertions();
const testProvider = new JestTestProvider(extExplorerContextMock);
const request: any = {};
await expect(testProvider.runTests(request, cancelToken)).rejects.not.toThrow();
expect(workspaceRootMock.scheduleTest).toBeCalledTimes(0);
expect(controllerMock.createTestRun).not.toBeCalled();
});
});
});
}); | the_stack |
import { Position, CompletionList, CompletionItemKind, Range, TextEdit, InsertTextFormat, CompletionItem, MarkupKind } from 'vscode-languageserver-types';
import { TextDocument } from 'vscode-languageserver-textdocument';
import { HTMLDocument, Node } from '../parser/htmlParser';
import { createScanner } from '../parser/htmlScanner';
import { CompletionConfiguration, ICompletionParticipant, ScannerState, TokenType, ClientCapabilities } from '../htmlLanguageTypes';
import { entities } from '../parser/htmlEntities';
import { isLetterOrDigit, endsWith, startsWith } from '../utils/strings';
import { getAllDataProviders } from '../languageFacts/builtinDataProviders';
import { isVoidElement } from '../languageFacts/fact';
import { isDefined } from '../utils/object';
import { generateDocumentation } from '../languageFacts/dataProvider';
const localize = (a: string, b: string) => b;
export class HTMLCompletion {
completionParticipants: ICompletionParticipant[];
private supportsMarkdown: boolean | undefined;
constructor(private clientCapabilities: ClientCapabilities | undefined) {
this.completionParticipants = [];
}
setCompletionParticipants(registeredCompletionParticipants: ICompletionParticipant[]) {
this.completionParticipants = registeredCompletionParticipants || [];
}
doComplete(document: TextDocument, position: Position, htmlDocument: HTMLDocument, settings?: CompletionConfiguration): CompletionList {
const result = this._doComplete(document, position, htmlDocument, settings);
return this.convertCompletionList(result);
}
private _doComplete(document: TextDocument, position: Position, htmlDocument: HTMLDocument, settings?: CompletionConfiguration): CompletionList {
const result: CompletionList = {
isIncomplete: false,
items: []
};
const completionParticipants = this.completionParticipants;
const dataProviders = getAllDataProviders().filter(p => p.isApplicable(document.languageId) && (!settings || settings[p.getId()] !== false));
const doesSupportMarkdown = this.doesSupportMarkdown();
const text = document.getText();
const offset = document.offsetAt(position);
const node = htmlDocument.findNodeBefore(offset);
if (!node) {
return result;
}
const scanner = createScanner(text, node.start);
let currentTag: string = '';
let currentAttributeName: string;
function getReplaceRange(replaceStart: number, replaceEnd: number = offset): Range {
if (replaceStart > offset) {
replaceStart = offset;
}
return { start: document.positionAt(replaceStart), end: document.positionAt(replaceEnd) };
}
function collectOpenTagSuggestions(afterOpenBracket: number, tagNameEnd?: number): CompletionList {
const range = getReplaceRange(afterOpenBracket, tagNameEnd);
dataProviders.forEach((provider) => {
provider.provideTags().forEach(tag => {
result.items.push({
label: tag.name,
kind: CompletionItemKind.Property,
documentation: generateDocumentation(tag, doesSupportMarkdown),
textEdit: TextEdit.replace(range, tag.name),
insertTextFormat: InsertTextFormat.PlainText
});
});
});
return result;
}
function getLineIndent(offset: number) {
let start = offset;
while (start > 0) {
const ch = text.charAt(start - 1);
if ("\n\r".indexOf(ch) >= 0) {
return text.substring(start, offset);
}
if (!isWhiteSpace(ch)) {
return null;
}
start--;
}
return text.substring(0, offset);
}
function collectCloseTagSuggestions(afterOpenBracket: number, inOpenTag: boolean, tagNameEnd: number = offset): CompletionList {
const range = getReplaceRange(afterOpenBracket, tagNameEnd);
const closeTag = isFollowedBy(text, tagNameEnd, ScannerState.WithinEndTag, TokenType.EndTagClose) ? '' : '>';
let curr: Node | undefined = node;
if (inOpenTag) {
curr = curr.parent; // don't suggest the own tag, it's not yet open
}
while (curr) {
const tag = curr.tag;
if (tag && (!curr.closed || curr.endTagStart && (curr.endTagStart > offset))) {
const item: CompletionItem = {
label: '/' + tag,
kind: CompletionItemKind.Property,
filterText: '/' + tag,
textEdit: TextEdit.replace(range, '/' + tag + closeTag),
insertTextFormat: InsertTextFormat.PlainText
};
const startIndent = getLineIndent(curr.start);
const endIndent = getLineIndent(afterOpenBracket - 1);
if (startIndent !== null && endIndent !== null && startIndent !== endIndent) {
const insertText = startIndent + '</' + tag + closeTag;
item.textEdit = TextEdit.replace(getReplaceRange(afterOpenBracket - 1 - endIndent.length), insertText);
item.filterText = endIndent + '</' + tag;
}
result.items.push(item);
return result;
}
curr = curr.parent;
}
if (inOpenTag) {
return result;
}
dataProviders.forEach(provider => {
provider.provideTags().forEach(tag => {
result.items.push({
label: '/' + tag.name,
kind: CompletionItemKind.Property,
documentation: generateDocumentation(tag, doesSupportMarkdown),
filterText: '/' + tag + closeTag,
textEdit: TextEdit.replace(range, '/' + tag + closeTag),
insertTextFormat: InsertTextFormat.PlainText
});
});
});
return result;
}
function collectAutoCloseTagSuggestion(tagCloseEnd: number, tag: string): CompletionList {
if (settings && settings.hideAutoCompleteProposals) {
return result;
}
if (!isVoidElement(tag)) {
const pos = document.positionAt(tagCloseEnd);
result.items.push({
label: '</' + tag + '>',
kind: CompletionItemKind.Property,
filterText: '</' + tag + '>',
textEdit: TextEdit.insert(pos, '$0</' + tag + '>'),
insertTextFormat: InsertTextFormat.Snippet
});
}
return result;
}
function collectTagSuggestions(tagStart: number, tagEnd: number): CompletionList {
collectOpenTagSuggestions(tagStart, tagEnd);
collectCloseTagSuggestions(tagStart, true, tagEnd);
return result;
}
function collectAttributeNameSuggestions(nameStart: number, nameEnd: number = offset): CompletionList {
let replaceEnd = offset;
while (replaceEnd < nameEnd && text[replaceEnd] !== '<') { // < is a valid attribute name character, but we rather assume the attribute name ends. See #23236.
replaceEnd++;
}
const range = getReplaceRange(nameStart, replaceEnd);
const value = isFollowedBy(text, nameEnd, ScannerState.AfterAttributeName, TokenType.DelimiterAssign) ? '' : '="$1"';
const tag = currentTag.toLowerCase();
const seenAttributes = Object.create(null);
dataProviders.forEach(provider => {
provider.provideAttributes(tag).forEach(attr => {
if (seenAttributes[attr.name]) {
return;
}
seenAttributes[attr.name] = true;
let codeSnippet = attr.name;
let command;
if (attr.valueSet !== 'v' && value.length) {
codeSnippet = codeSnippet + value;
if (attr.valueSet || attr.name === 'style') {
command = {
title: 'Suggest',
command: 'editor.action.triggerSuggest'
};
}
}
result.items.push({
label: attr.name,
kind: attr.valueSet === 'handler' ? CompletionItemKind.Function : CompletionItemKind.Value,
documentation: generateDocumentation(attr, doesSupportMarkdown),
textEdit: TextEdit.replace(range, codeSnippet),
insertTextFormat: InsertTextFormat.Snippet,
command
});
});
});
collectDataAttributesSuggestions(range, seenAttributes);
return result;
}
function collectDataAttributesSuggestions(range: Range, seenAttributes: { [attribute: string]: boolean }) {
const dataAttr = 'data-';
const dataAttributes: { [name: string]: string } = {};
dataAttributes[dataAttr] = `${dataAttr}$1="$2"`;
function addNodeDataAttributes(node: Node) {
node.attributeNames.forEach(attr => {
if (startsWith(attr, dataAttr) && !dataAttributes[attr] && !seenAttributes[attr]) {
dataAttributes[attr] = attr + '="$1"';
}
});
node.children.forEach(child => addNodeDataAttributes(child));
}
if (htmlDocument) {
htmlDocument.roots.forEach(root => addNodeDataAttributes(root));
}
Object.keys(dataAttributes).forEach(attr => result.items.push({
label: attr,
kind: CompletionItemKind.Value,
textEdit: TextEdit.replace(range, dataAttributes[attr]),
insertTextFormat: InsertTextFormat.Snippet
}));
}
function collectAttributeValueSuggestions(valueStart: number, valueEnd: number = offset): CompletionList {
let range: Range;
let addQuotes: boolean;
let valuePrefix: string;
if (offset > valueStart && offset <= valueEnd && isQuote(text[valueStart])) {
// inside quoted attribute
const valueContentStart = valueStart + 1;
let valueContentEnd = valueEnd;
// valueEnd points to the char after quote, which encloses the replace range
if (valueEnd > valueStart && text[valueEnd - 1] === text[valueStart]) {
valueContentEnd--;
}
const wsBefore = getWordStart(text, offset, valueContentStart);
const wsAfter = getWordEnd(text, offset, valueContentEnd);
range = getReplaceRange(wsBefore, wsAfter);
valuePrefix = offset >= valueContentStart && offset <= valueContentEnd ? text.substring(valueContentStart, offset) : '';
addQuotes = false;
} else {
range = getReplaceRange(valueStart, valueEnd);
valuePrefix = text.substring(valueStart, offset);
addQuotes = true;
}
const tag = currentTag.toLowerCase();
const attribute = currentAttributeName.toLowerCase();
if (completionParticipants.length > 0) {
const fullRange = getReplaceRange(valueStart, valueEnd);
for (const participant of completionParticipants) {
if (participant.onHtmlAttributeValue) {
participant.onHtmlAttributeValue({ document, position, tag, attribute, value: valuePrefix, range: fullRange });
}
}
}
dataProviders.forEach(provider => {
provider.provideValues(tag, attribute).forEach(value => {
const insertText = addQuotes ? '"' + value.name + '"' : value.name;
result.items.push({
label: value.name,
filterText: insertText,
kind: CompletionItemKind.Unit,
documentation: generateDocumentation(value, doesSupportMarkdown),
textEdit: TextEdit.replace(range, insertText),
insertTextFormat: InsertTextFormat.PlainText
});
});
});
collectCharacterEntityProposals();
return result;
}
function scanNextForEndPos(nextToken: TokenType): number {
if (offset === scanner.getTokenEnd()) {
token = scanner.scan();
if (token === nextToken && scanner.getTokenOffset() === offset) {
return scanner.getTokenEnd();
}
}
return offset;
}
function collectInsideContent(): CompletionList {
for (const participant of completionParticipants) {
if (participant.onHtmlContent) {
participant.onHtmlContent({ document, position });
}
}
return collectCharacterEntityProposals();
}
function collectCharacterEntityProposals() {
// character entities
let k = offset - 1;
let characterStart = position.character;
while (k >= 0 && isLetterOrDigit(text, k)) {
k--;
characterStart--;
}
if (k >= 0 && text[k] === '&') {
const range = Range.create(Position.create(position.line, characterStart - 1), position);
for (const entity in entities) {
if (endsWith(entity, ';')) {
const label = '&' + entity;
result.items.push({
label,
kind: CompletionItemKind.Keyword,
documentation: localize('entity.propose', `Character entity representing '${entities[entity]}'`),
textEdit: TextEdit.replace(range, label),
insertTextFormat: InsertTextFormat.PlainText
});
}
}
}
return result;
}
function suggestDoctype(replaceStart: number, replaceEnd: number) {
const range = getReplaceRange(replaceStart, replaceEnd);
result.items.push({
label: '!DOCTYPE',
kind: CompletionItemKind.Property,
documentation: 'A preamble for an HTML document.',
textEdit: TextEdit.replace(range, '!DOCTYPE html>'),
insertTextFormat: InsertTextFormat.PlainText
});
}
let token = scanner.scan();
while (token !== TokenType.EOS && scanner.getTokenOffset() <= offset) {
switch (token) {
case TokenType.StartTagOpen:
if (scanner.getTokenEnd() === offset) {
const endPos = scanNextForEndPos(TokenType.StartTag);
if (position.line === 0) {
suggestDoctype(offset, endPos);
}
return collectTagSuggestions(offset, endPos);
}
break;
case TokenType.StartTag:
if (scanner.getTokenOffset() <= offset && offset <= scanner.getTokenEnd()) {
return collectOpenTagSuggestions(scanner.getTokenOffset(), scanner.getTokenEnd());
}
currentTag = scanner.getTokenText();
break;
case TokenType.AttributeName:
if (scanner.getTokenOffset() <= offset && offset <= scanner.getTokenEnd()) {
return collectAttributeNameSuggestions(scanner.getTokenOffset(), scanner.getTokenEnd());
}
currentAttributeName = scanner.getTokenText();
break;
case TokenType.DelimiterAssign:
if (scanner.getTokenEnd() === offset) {
const endPos = scanNextForEndPos(TokenType.AttributeValue);
return collectAttributeValueSuggestions(offset, endPos);
}
break;
case TokenType.AttributeValue:
if (scanner.getTokenOffset() <= offset && offset <= scanner.getTokenEnd()) {
return collectAttributeValueSuggestions(scanner.getTokenOffset(), scanner.getTokenEnd());
}
break;
case TokenType.Whitespace:
if (offset <= scanner.getTokenEnd()) {
switch (scanner.getScannerState()) {
case ScannerState.AfterOpeningStartTag:
const startPos = scanner.getTokenOffset();
const endTagPos = scanNextForEndPos(TokenType.StartTag);
return collectTagSuggestions(startPos, endTagPos);
case ScannerState.WithinTag:
case ScannerState.AfterAttributeName:
return collectAttributeNameSuggestions(scanner.getTokenEnd());
case ScannerState.BeforeAttributeValue:
return collectAttributeValueSuggestions(scanner.getTokenEnd());
case ScannerState.AfterOpeningEndTag:
return collectCloseTagSuggestions(scanner.getTokenOffset() - 1, false);
case ScannerState.WithinContent:
return collectInsideContent();
}
}
break;
case TokenType.EndTagOpen:
if (offset <= scanner.getTokenEnd()) {
const afterOpenBracket = scanner.getTokenOffset() + 1;
const endOffset = scanNextForEndPos(TokenType.EndTag);
return collectCloseTagSuggestions(afterOpenBracket, false, endOffset);
}
break;
case TokenType.EndTag:
if (offset <= scanner.getTokenEnd()) {
let start = scanner.getTokenOffset() - 1;
while (start >= 0) {
const ch = text.charAt(start);
if (ch === '/') {
return collectCloseTagSuggestions(start, false, scanner.getTokenEnd());
} else if (!isWhiteSpace(ch)) {
break;
}
start--;
}
}
break;
case TokenType.StartTagClose:
if (offset <= scanner.getTokenEnd()) {
if (currentTag) {
return collectAutoCloseTagSuggestion(scanner.getTokenEnd(), currentTag);
}
}
break;
case TokenType.Content:
if (offset <= scanner.getTokenEnd()) {
return collectInsideContent();
}
break;
default:
if (offset <= scanner.getTokenEnd()) {
return result;
}
break;
}
token = scanner.scan();
}
return result;
}
doTagComplete(document: TextDocument, position: Position, htmlDocument: HTMLDocument): string | null {
const offset = document.offsetAt(position);
if (offset <= 0) {
return null;
}
const char = document.getText().charAt(offset - 1);
if (char === '>') {
const node = htmlDocument.findNodeBefore(offset);
if (node && node.tag && !isVoidElement(node.tag) && node.start < offset && (!node.endTagStart || node.endTagStart > offset)) {
const scanner = createScanner(document.getText(), node.start);
let token = scanner.scan();
while (token !== TokenType.EOS && scanner.getTokenEnd() <= offset) {
if (token === TokenType.StartTagClose && scanner.getTokenEnd() === offset) {
return `$0</${node.tag}>`;
}
token = scanner.scan();
}
}
} else if (char === '/') {
let node: Node | undefined = htmlDocument.findNodeBefore(offset);
while (node && node.closed) {
node = node.parent;
}
if (node && node.tag) {
const scanner = createScanner(document.getText(), node.start);
let token = scanner.scan();
while (token !== TokenType.EOS && scanner.getTokenEnd() <= offset) {
if (token === TokenType.EndTagOpen && scanner.getTokenEnd() === offset) {
return `${node.tag}>`;
}
token = scanner.scan();
}
}
}
return null;
}
private convertCompletionList(list: CompletionList) {
if (!this.doesSupportMarkdown()) {
list.items.forEach(item => {
if (item.documentation && typeof item.documentation !== 'string') {
item.documentation = {
kind: 'plaintext',
value: item.documentation.value
};
}
});
}
return list;
}
private doesSupportMarkdown(): boolean {
if (!isDefined(this.supportsMarkdown)) {
if (!isDefined(this.clientCapabilities)) {
this.supportsMarkdown = true;
return this.supportsMarkdown;
}
const hover = this.clientCapabilities && this.clientCapabilities.textDocument && this.clientCapabilities.textDocument.hover;
this.supportsMarkdown = hover && hover.contentFormat && Array.isArray(hover.contentFormat) && hover.contentFormat.indexOf(MarkupKind.Markdown) !== -1;
}
return <boolean>this.supportsMarkdown;
}
}
function isQuote(s: string): boolean {
return /^["']*$/.test(s);
}
function isWhiteSpace(s: string): boolean {
return /^\s*$/.test(s);
}
function isFollowedBy(s: string, offset: number, intialState: ScannerState, expectedToken: TokenType) {
const scanner = createScanner(s, offset, intialState);
let token = scanner.scan();
while (token === TokenType.Whitespace) {
token = scanner.scan();
}
return token === expectedToken;
}
function getWordStart(s: string, offset: number, limit: number): number {
while (offset > limit && !isWhiteSpace(s[offset - 1])) {
offset--;
}
return offset;
}
function getWordEnd(s: string, offset: number, limit: number): number {
while (offset < limit && !isWhiteSpace(s[offset])) {
offset++;
}
return offset;
} | the_stack |
import {
getPrintedUiJsCode,
makeTestProjectCodeWithSnippet,
renderTestEditorWithCode,
TestScenePath,
} from './ui-jsx.test-utils' // IMPORTANT - THIS IMPORT MUST ALWAYS COME FIRST
import { canvasRectangle, CanvasVector } from '../../core/shared/math-utils'
import { setCanvasFrames } from '../editor/actions/action-creators'
import * as EP from '../../core/shared/element-path'
import {
pinFrameChange,
pinMoveChange,
pinSizeChange,
singleResizeChange,
EdgePosition,
} from './canvas-types'
describe('updateFramesOfScenesAndComponents - pinFrameChange -', () => {
it('a simple TLWH pin change works', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(`
<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 52, top: 61, width: 256, height: 202 }}
data-uid='bbb'
/>
</View>
`),
'await-first-dom-report',
)
const pinChange = pinFrameChange(
EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']),
canvasRectangle({ x: 20, y: 20, width: 100, height: 100 }),
)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 20, top: 20, width: 100, height: 100 }}
data-uid='bbb'
/>
</View>`,
),
)
})
it('a simple TLWH pin change works with old CanvasMetadata format as well', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(`
<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 52, top: 61, width: 256, height: 202 }}
data-uid='bbb'
/>
</View>
`),
'await-first-dom-report',
)
const pinChange = pinFrameChange(
EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']),
canvasRectangle({ x: 20, y: 20, width: 100, height: 100 }),
)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 20, top: 20, width: 100, height: 100 }}
data-uid='bbb'
/>
</View>`,
),
)
})
it('TLWH, but W and H are percentage works', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(`
<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 52, top: 61, width: '50%', height: '20%' }}
data-uid='bbb'
/>
</View>
`),
'await-first-dom-report',
)
const pinChange = pinFrameChange(
EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']),
canvasRectangle({ x: 20, y: 20, width: 100, height: 100 }),
)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 20, top: 20, width: '25%', height: '25%' }}
data-uid='bbb'
/>
</View>`,
),
)
})
it('TLW, missing H pin change works', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(`
<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 52, top: 61, width: 256 }}
data-uid='bbb'
/>
</View>
`),
'await-first-dom-report',
)
const pinChange = pinFrameChange(
EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']),
canvasRectangle({ x: 20, y: 20, width: 100, height: 100 }),
)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 20, top: 20, width: 100, height: 100 }}
data-uid='bbb'
/>
</View>`,
),
)
})
it('TLWHBR, too many frame points work', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(`
<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 52, top: 61, width: 256, height: 202, bottom: 137, right: 93 }}
data-uid='bbb'
/>
</View>
`),
'await-first-dom-report',
)
const pinChange = pinFrameChange(
EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']),
canvasRectangle({ x: 20, y: 20, width: 100, height: 100 }),
)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 20, top: 20, width: 100, height: 100 }}
${/** notice how the extraneous pins were removed automatically */ ''}
data-uid='bbb'
/>
</View>`,
),
)
})
it('TLRB pin change works', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 52, top: 61, right: 50, bottom: 20 }}
data-uid='bbb'
/>
</View>`,
),
'await-first-dom-report',
)
const pinChange = pinFrameChange(
EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']),
canvasRectangle({ x: 20, y: 20, width: 100, height: 100 }),
)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 20, top: 20, right: 280, bottom: 280 }}
data-uid='bbb'
/>
</View>`,
),
)
})
it('no layout prop on child', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(`
<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA' }}
data-uid='bbb'
/>
</View>
`),
'await-first-dom-report',
)
const pinChange = pinFrameChange(
EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']),
canvasRectangle({ x: 20, y: 20, width: 100, height: 100 }),
)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
${/** pins are magically created */ ''}
style={{ backgroundColor: '#0091FFAA', left: 20, top: 20, width: 100, height: 100 }}
data-uid='bbb'
/>
</View>`,
),
)
})
})
describe('updateFramesOfScenesAndComponents - pinMoveChange -', () => {
it('only TL pins work', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 52, top: 61 }}
data-uid='bbb'
/>
</View>`,
),
'await-first-dom-report',
)
const pinChange = pinMoveChange(EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']), {
x: -32,
y: -41,
} as CanvasVector)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 20, top: 20 }}
data-uid='bbb'
/>
</View>`,
),
)
})
it('only TL pins work with old CanvasMetadata as well', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 52, top: 61 }}
data-uid='bbb'
/>
</View>`,
),
'await-first-dom-report',
)
const pinChange = pinMoveChange(EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']), {
x: -32,
y: -41,
} as CanvasVector)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 20, top: 20 }}
data-uid='bbb'
/>
</View>`,
),
)
})
it('only RB pins work', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', right: 50, bottom: 50 }}
data-uid='bbb'
/>
</View>`,
),
'await-first-dom-report',
)
const pinChange = pinMoveChange(EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']), {
x: 20,
y: 20,
} as CanvasVector)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', right: 30, bottom: 30 }}
data-uid='bbb'
/>
</View>`,
),
)
})
it('just R pin gets turned into T,R', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', right: 50 }}
data-uid='bbb'
/>
</View>`,
),
'await-first-dom-report',
)
const pinChange = pinMoveChange(EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']), {
x: 20,
y: 20,
} as CanvasVector)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', right: 30, top: 20 }}
data-uid='bbb'
/>
</View>`,
),
)
})
it('just B pin gets turned into L,B', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', bottom: 50 }}
data-uid='bbb'
/>
</View>`,
),
'await-first-dom-report',
)
const pinChange = pinMoveChange(EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']), {
x: 20,
y: 20,
} as CanvasVector)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', bottom: 30, left: 20 }}
data-uid='bbb'
/>
</View>`,
),
)
})
it('just B pin doesn`t turn into L,B with deltaX=0', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', bottom: 50 }}
data-uid='bbb'
/>
</View>`,
),
'await-first-dom-report',
)
const pinChange = pinMoveChange(EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']), {
x: 0,
y: 20,
} as CanvasVector)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', bottom: 30 }}
data-uid='bbb'
/>
</View>`,
),
)
})
it('TLWH, but W and H are left alone', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(`
<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', width: '50%', height: 25, left: 52, top: 61 }}
data-uid='bbb'
/>
</View>
`),
'await-first-dom-report',
)
const pinChange = pinMoveChange(EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']), {
x: -32,
y: -41,
} as CanvasVector)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', width: '50%', height: 25, left: 20, top: 20 }}
data-uid='bbb'
/>
</View>`,
),
)
})
it('TLWH, but W and H are left alone, T, L are % values', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(`
<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', width: '50%', height: 25, left: '10%', top: '5%' }}
data-uid='bbb'
/>
</View>
`),
'await-first-dom-report',
)
const pinChange = pinMoveChange(EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']), {
x: -32,
y: 45,
} as CanvasVector)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', width: '50%', height: 25, left: '2%', top: '16.3%' }}
data-uid='bbb'
/>
</View>`,
),
)
})
it('TLRB pin change works', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 52, top: 61, right: 50, bottom: 20 }}
data-uid='bbb'
/>
</View>`,
),
'await-first-dom-report',
)
const pinChange = pinMoveChange(EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']), {
x: -32,
y: -41,
} as CanvasVector)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 20, top: 20, right: 82, bottom: 61 }}
data-uid='bbb'
/>
</View>`,
),
)
})
it('TLRB pin change works, with % values', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: '10%', top: '15%', right: '10%', bottom: '25%' }}
data-uid='bbb'
/>
</View>`,
),
'await-first-dom-report',
)
const pinChange = pinMoveChange(EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']), {
x: 20,
y: 65,
} as CanvasVector)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{
backgroundColor: '#0091FFAA',
position: 'absolute',
left: '15%',
top: '31.3%',
right: '5%',
bottom: '8.8%',
}}
data-uid='bbb'
/>
</View>`,
),
)
})
it('TLWHBR, too many frame points work', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(`
<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 52, top: 61, width: 256, height: 202, bottom: 137, right: 93 }}
data-uid='bbb'
/>
</View>
`),
'await-first-dom-report',
)
const pinChange = pinMoveChange(EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']), {
x: -32,
y: -41,
} as CanvasVector)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
${
/**
* we correctly update left, top, bottom, and right, but we do nothing to fix the fact that there are 6 pins competing for priorities here
* if we later revise the behavior and change how PIN_MOVE works when there is too many pins, don't be surprised if this test here breaks
* */ ''
}
style={{
backgroundColor: '#0091FFAA',
position: 'absolute',
left: 20,
top: 20,
width: 256,
height: 202,
bottom: 178,
right: 125,
}}
data-uid='bbb'
/>
</View>`,
),
)
})
it('TLR, no B pin change?', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 52, top: 61, right: 50 }}
data-uid='bbb'
/>
</View>`,
),
'await-first-dom-report',
)
const pinChange = pinMoveChange(EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']), {
x: -32,
y: -41,
} as CanvasVector)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 20, top: 20, right: 82 }}
data-uid='bbb'
/>
</View>`,
),
)
})
})
describe('updateFramesOfScenesAndComponents - pinSizeChange -', () => {
it('only TL pins work', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 52, top: 61 }}
data-uid='bbb'
/>
</View>`,
),
'await-first-dom-report',
)
const pinChange = pinSizeChange(
EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']),
canvasRectangle({ x: 20, y: 20, width: 100, height: 100 }),
null,
)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 20, top: 20, width: 100, height: 100 }}
data-uid='bbb'
/>
</View>`,
),
)
})
it('only TW pins work', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 52, width: 100 }}
data-uid='bbb'
/>
</View>`,
),
'await-first-dom-report',
)
const pinChange = pinSizeChange(
EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']),
canvasRectangle({ x: 20, y: 20, width: 100, height: 100 }),
null,
)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
// THIS IS THE IMPORTANT TEST, IT POINTS OUT THAT WE DO NOT ADD AN UNNECESSARY TOP PROPERTY, ONLY HEIGHT
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 20, width: 100, height: 100 }}
data-uid='bbb'
/>
</View>`,
),
)
})
it('TLRB pins work', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 52, top: 61, right: 150, bottom: 150 }}
data-uid='bbb'
/>
</View>`,
),
'await-first-dom-report',
)
const pinChange = pinSizeChange(
EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']),
canvasRectangle({ x: 20, y: 20, width: 100, height: 100 }),
null,
)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...props.style }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 20, top: 20, right: 280, bottom: 280 }}
data-uid='bbb'
/>
</View>`,
),
)
})
})
describe('updateFramesOfScenesAndComponents - singleResizeChange -', () => {
it('TLWH, but W and H are percentage works', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(`
<View style={{ ...(props.style || {}) }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 40, top: 40, width: '50%', height: '20%' }}
data-uid='bbb'
/>
</View>
`),
'await-first-dom-report',
)
const pinChange = singleResizeChange(
EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']),
{ x: 1, y: 1 } as EdgePosition,
{ x: -20, y: -10 } as CanvasVector,
)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...(props.style || {}) }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA', position: 'absolute', left: 40, top: 40, width: '45%', height: '17.5%' }}
data-uid='bbb'
/>
</View>`,
),
)
})
it('no layout prop on child', async () => {
const renderResult = await renderTestEditorWithCode(
makeTestProjectCodeWithSnippet(`
<View style={{ ...(props.style || {}) }} data-uid='aaa'>
<View
style={{ backgroundColor: '#0091FFAA' }}
data-uid='bbb'
/>
</View>
`),
'await-first-dom-report',
)
const pinChange = singleResizeChange(
EP.appendNewElementPath(TestScenePath, ['aaa', 'bbb']),
{ x: 0, y: 0 } as EdgePosition,
{ x: 50, y: 60 } as CanvasVector,
)
await renderResult.dispatch([setCanvasFrames([pinChange], false)], true)
expect(getPrintedUiJsCode(renderResult.getEditorState())).toEqual(
makeTestProjectCodeWithSnippet(
`<View style={{ ...(props.style || {}) }} data-uid='aaa'>
<View
${/** pins are magically created */ ''}
style={{ backgroundColor: '#0091FFAA', top: -60, height: 60, left: -50, width: 50 }}
data-uid='bbb'
/>
</View>`,
),
)
})
}) | the_stack |
import assert from 'assert';
import * as Tp from 'thingpedia';
import * as ThingTalk from 'thingtalk';
import { stringEscape } from './escaping';
import { splitParams } from './tokenize';
import * as db from './db';
import * as exampleModel from '../model/example';
import * as deviceModel from '../model/device';
import { InternalError } from './errors';
import { uniform } from './random';
export function exampleToCode(example : ThingTalk.Ast.Example) {
const clone = example.clone();
clone.id = -1;
clone.utterances = [];
clone.preprocessed = [];
clone.annotations = {};
let code = clone.prettyprint();
// porkaround a bug in ThingTalk
code = code.replace(/[ \r\n\t\v]*#_\[utterances=\[\]\][ \r\n\t\v]*/g, '').trim();
return code;
}
const platformDevices : Record<string, string> = {
'org.thingpedia.builtin.thingengine.gnome': 'gnome',
'org.thingpedia.builtin.thingengine.phone': 'android',
};
interface LoadThingpediaOptions {
forPlatform ?: string;
thingpedia ?: string;
dataset ?: string;
rng ?: () => number;
}
interface BasicDevice {
primary_kind : string;
name : string;
examples ?: SortedExampleRow[];
}
interface BasicExample {
kind : string;
utterance : string;
target_code : string;
}
export function getCheatsheet(language : string, options : LoadThingpediaOptions) {
return loadThingpedia(language, options).then(([devices, examples]) => {
const deviceMap = new Map<string, number>();
devices.forEach((d, i) => {
d.examples = [];
if (options.forPlatform && platformDevices[d.primary_kind]
&& options.forPlatform !== platformDevices[d.primary_kind])
return;
deviceMap.set(d.primary_kind, i);
});
const dupes = new Set<string>();
examples.forEach((ex) => {
if (dupes.has(ex.target_code) || !ex.target_code)
return;
dupes.add(ex.target_code);
const kind = ex.kind;
if (!deviceMap.has(kind)) {
// ignore what we don't recognize
console.log('Unrecognized kind ' + kind);
} else {
devices[deviceMap.get(kind)!].examples!.push(ex);
}
});
for (const device of devices)
device.examples = sortAndChunkExamples(device.examples!);
return devices;
});
}
async function loadCheatsheetFromFile(language : string,
thingpedia : string,
dataset : string,
random = true,
options : LoadThingpediaOptions = {})
: Promise<[BasicDevice[], BasicExample[]]> {
const tpClient = new Tp.FileClient({
locale: language,
thingpedia, dataset
});
const deviceNames = await tpClient.getAllDeviceNames();
const devices : BasicDevice[] = [];
const devices_rev : Record<string, boolean> = {};
for (const dev of deviceNames) {
devices.push({
primary_kind: dev.kind,
name: dev.kind_canonical
});
devices_rev[dev.kind] = true;
}
const parsed = ThingTalk.Syntax.parse(await tpClient.getAllExamples(), ThingTalk.Syntax.SyntaxType.Normal, {
locale: language,
timezone: 'UTC'
});
assert(parsed instanceof ThingTalk.Ast.Library);
const parsedExamples = parsed.datasets[0].examples;
const examples = parsedExamples.map((e) : BasicExample|null => {
let kind;
for (const [, invocation] of e.iteratePrimitives(false))
kind = invocation.selector.kind;
if (kind !== undefined && kind in devices_rev) {
const utterance = random ? uniform(e.utterances, options.rng) : e.utterances[0];
return {
kind: kind,
utterance: utterance,
target_code: exampleToCode(e)
};
} else {
return null;
}
}).filter((e) : e is BasicExample => !!e);
return [devices, examples];
}
function loadThingpedia(language : string, { forPlatform, thingpedia, dataset, rng = Math.random } : LoadThingpediaOptions) {
if (thingpedia && dataset) {
return loadCheatsheetFromFile(language, thingpedia, dataset, true, { rng });
} else {
return db.withClient((dbClient) : Promise<[BasicDevice[], BasicExample[]]> => {
const devices : Promise<BasicDevice[]> = forPlatform !== undefined ? deviceModel.getAllApprovedWithCode(dbClient, null) : deviceModel.getAllApproved(dbClient, null);
const examples : Promise<BasicExample[]> = exampleModel.getCheatsheet(dbClient, language);
return Promise.all([devices, examples]);
});
}
}
interface CoalescedExample {
id : number;
utterances : string[];
preprocessed : string[];
click_count : number;
like_count : number;
name : string|null;
//kind : string|null;
}
interface ExampleToDatasetOptions {
needs_compatibility ?: boolean;
thingtalk_version ?: string;
dbClient ?: db.Client;
editMode ?: boolean;
skipId ?: boolean;
}
function rowsToExamples(rows : Array<Omit<exampleModel.PrimitiveTemplateRow, "language"|"type">>, { editMode = false, skipId = false }) {
// coalesce by target code
// note: this code is designed to be fast, and avoid parsing the examples in the common
// case of up-to-date thingpedia
const uniqueCode = new Map<string, CoalescedExample>();
for (const row of rows) {
let targetCode = row.target_code;
if (!targetCode)
throw new InternalError('E_DATASET_CORRUPT', `Invalid example ${row.id}, missing program`);
// convert each example from ThingTalk 1 to ThingTalk 2 if necessary
// quick and dirty check to identify the syntax version
if (targetCode.indexOf(':=') >= 0) {
const parsed = ThingTalk.Syntax.parse(`dataset @foo { ${targetCode} }`, ThingTalk.Syntax.SyntaxType.Legacy, {
locale: 'en-US',
timezone: 'UTC'
});
assert(parsed instanceof ThingTalk.Ast.Library);
targetCode = parsed.datasets[0].examples[0].prettyprint();
// porkaround a bug in ThingTalk
targetCode = targetCode.replace(/#_\[utterances=\[\]\]/g, '').trim();
}
// remove trailing semicolon
targetCode = targetCode.replace(/[ \r\n\t\v]*;[ \r\n\t\v]*$/, '');
if (uniqueCode.has(targetCode)) {
const ex = uniqueCode.get(targetCode)!;
ex.utterances.push(row.utterance);
ex.preprocessed.push(row.preprocessed);
if (row.name && !ex.name)
ex.name = row.name;
} else {
uniqueCode.set(targetCode, {
id: row.id,
utterances: [row.utterance],
preprocessed: [row.preprocessed],
click_count: row.click_count,
like_count: row.like_count,
name: row.name,
});
}
}
const buffer = [];
for (const [targetCode, ex] of uniqueCode.entries()) {
if (editMode) {
if (!skipId && ex.id !== undefined) {
buffer.push(` ${targetCode}
#_[utterances=[${ex.utterances.map(stringEscape).join(',\n' + ' '.repeat(19))}]]
#[id=${ex.id}]
#[name=${stringEscape(ex.name || '')}];
`);
} else {
buffer.push(` ${targetCode}
#_[utterances=[${ex.utterances.map(stringEscape).join(',\n' + ' '.repeat(19))}]]
#[name=${stringEscape(ex.name || '')}];
`);
}
} else {
buffer.push(` ${targetCode}
#_[utterances=[${ex.utterances.map(stringEscape)}]]
#_[preprocessed=[${ex.preprocessed.map(stringEscape)}]]
#[id=${ex.id}] #[click_count=${ex.click_count}] #[like_count=${ex.like_count}]
#[name=${stringEscape((ex.name || ''))}];
`);
}
}
return buffer.join('');
}
export async function examplesToDataset(name : string, language : string, rows : Array<Omit<exampleModel.PrimitiveTemplateRow, "language"|"type">>, options : ExampleToDatasetOptions = {}) {
const code = `dataset @${name}
#[language="${language}"] {
${rowsToExamples(rows, options)}}`;
// convert code to thingtalk 1 if necessary
if (options.needs_compatibility) {
const AdminThingpediaClient = (await import('./admin-thingpedia-client')).default;
const tpClient = new AdminThingpediaClient(language, options.dbClient || null);
const schemas = new ThingTalk.SchemaRetriever(tpClient, null, true);
const parsed = ThingTalk.Syntax.parse(code, ThingTalk.Syntax.SyntaxType.Normal, {
locale: language,
timezone: 'UTC'
});
await parsed.typecheck(schemas, false);
return ThingTalk.Syntax.serialize(parsed, ThingTalk.Syntax.SyntaxType.Normal, undefined, {
compatibility: options.thingtalk_version
});
} else {
return code;
}
}
interface SortedExampleRow {
utterance : string;
target_code : string;
type ?: string;
utterance_chunks ?: Array<string|string[]>;
}
export function sortAndChunkExamples(rows : SortedExampleRow[]) {
const functionTypes = new Map<string, 'query'|'action'>();
const trigger_ex : SortedExampleRow[] = [], query_ex : SortedExampleRow[] = [], action_ex : SortedExampleRow[] = [], other_ex : SortedExampleRow[] = [];
for (const ex of rows) {
ex.target_code = ex.target_code.replace(/^\s*let\s+table/, 'query')
.replace(/^\s*let\s+(stream|query|action)/, '$1');
const match = /^\s*(stream|query|action|program)/.exec(ex.target_code);
if (match === null)
ex.type = 'program';
else
ex.type = match[1] as 'stream'|'query'|'action';
if (ex.utterance.startsWith(','))
ex.utterance = ex.utterance.substring(1);
ex.utterance_chunks = splitParams(ex.utterance.trim());
const functions = [];
for (const [fn,] of ex.target_code.matchAll(/@\s*[a-z0-9_-]+(?:\.[a-z0-9_-]+)*/g))
functions.push(fn.substring(1));
if (ex.type === 'action') {
// all queries except the last one
for (let i = 0; i < functions.length-1; i++)
functionTypes.set(functions[i], 'query');
functionTypes.set(functions[functions.length-1], 'action');
} else if (ex.type !== 'program') {
// all queries
for (let i = 0; i < functions.length; i++)
functionTypes.set(functions[i], 'query');
}
switch (ex.type) {
case 'stream':
trigger_ex.push(ex);
break;
case 'query':
query_ex.push(ex);
break;
case 'action':
action_ex.push(ex);
break;
default:
other_ex.push(ex);
break;
}
}
for (const ex of other_ex) {
// let's find what function this one is...
const functions = [];
for (const [fn,] of ex.target_code.matchAll(/@\s*[a-z0-9_-]+(?:\.[a-z0-9_-]+)*/g))
functions.push(fn.substring(1));
if (functions.length === 1 && functions[0] === 'org.thingpedia.builtin.thingengine.builtin.faq_reply')
ex.type = ex.utterance.endsWith('?') ? 'query' : 'action';
else if (functions.every((f) => functionTypes.get(f) === 'query'))
ex.type = 'query';
else
ex.type = 'action';
if (ex.type === 'action')
action_ex.push(ex);
else
query_ex.push(ex);
continue;
}
return ([] as SortedExampleRow[]).concat(trigger_ex, query_ex, action_ex);
} | the_stack |
import { autoBindMethodsForReact } from 'class-autobind-decorator';
import classnames from 'classnames';
import React, { Fragment, PureComponent } from 'react';
import { arrayMove, SortableContainer, SortableElement, SortEndHandler } from 'react-sortable-hoc';
import { AUTOBIND_CFG, DEBOUNCE_MILLIS } from '../../../common/constants';
import { database as db } from '../../../common/database';
import { docsTemplateTags } from '../../../common/documentation';
import * as models from '../../../models';
import type { Environment } from '../../../models/environment';
import type { Workspace } from '../../../models/workspace';
import { Button, ButtonProps } from '../base/button';
import { Dropdown } from '../base/dropdown/dropdown';
import { DropdownButton } from '../base/dropdown/dropdown-button';
import { DropdownItem } from '../base/dropdown/dropdown-item';
import { Editable } from '../base/editable';
import { Link } from '../base/link';
import { Modal, ModalProps } from '../base/modal';
import { ModalBody } from '../base/modal-body';
import { ModalFooter } from '../base/modal-footer';
import { ModalHeader } from '../base/modal-header';
import { PromptButton } from '../base/prompt-button';
import { EnvironmentEditor } from '../editors/environment-editor';
import { HelpTooltip } from '../help-tooltip';
import { Tooltip } from '../tooltip';
const ROOT_ENVIRONMENT_NAME = 'Base Environment';
interface Props extends ModalProps {
handleChangeEnvironment: (id: string | null) => void;
activeEnvironmentId: string | null;
}
interface State {
workspace: Workspace | null;
isValid: boolean;
subEnvironments: Environment[];
rootEnvironment: Environment | null;
selectedEnvironmentId: string | null;
}
interface SidebarListItemProps extends Pick<Props, 'activeEnvironmentId'> {
changeEnvironmentName: (environment: Environment, name?: string) => void;
environment: Environment;
handleActivateEnvironment: ButtonProps<Environment>['onClick'];
selectedEnvironment: Environment | null;
showEnvironment: ButtonProps<Environment>['onClick'];
}
const SidebarListItem = SortableElement<SidebarListItemProps>(({
activeEnvironmentId,
changeEnvironmentName,
environment,
handleActivateEnvironment,
selectedEnvironment,
showEnvironment,
}) => {
const classes = classnames({
'env-modal__sidebar-item': true,
'env-modal__sidebar-item--active': selectedEnvironment === environment,
// Specify theme because dragging will pull it out to <body>
'theme--dialog': true,
});
return (
<li key={environment._id} className={classes}>
<Button onClick={showEnvironment} value={environment}>
<i className="fa fa-drag-handle drag-handle" />
{environment.color ? (
<i
className="space-right fa fa-circle"
style={{
color: environment.color,
}}
/>
) : (
<i className="space-right fa fa-empty" />
)}
{environment.isPrivate && (
<Tooltip position="top" message="Environment will not be exported or synced">
<i className="fa fa-eye-slash faint space-right" />
</Tooltip>
)}
<Editable
className="inline-block"
onSubmit={name => changeEnvironmentName(environment, name)}
value={environment.name}
/>
</Button>
<div className="env-status">
{environment._id === activeEnvironmentId ? (
<i className="fa fa-square active" title="Active Environment" />
) : (
<Button onClick={handleActivateEnvironment} value={environment}>
<i className="fa fa-square-o inactive" title="Click to activate Environment" />
</Button>
)}
</div>
</li>
);
},
);
interface SidebarListProps extends Omit<SidebarListItemProps, 'environment'> {
environments: Environment[];
}
const SidebarList = SortableContainer<SidebarListProps>(
({
activeEnvironmentId,
changeEnvironmentName,
environments,
handleActivateEnvironment,
selectedEnvironment,
showEnvironment,
}) => (
<ul>
{environments.map((environment, index) => (
<SidebarListItem
activeEnvironmentId={activeEnvironmentId}
changeEnvironmentName={changeEnvironmentName}
environment={environment}
handleActivateEnvironment={handleActivateEnvironment}
index={index}
key={environment._id}
selectedEnvironment={selectedEnvironment}
showEnvironment={showEnvironment}
/>
))}
</ul>
),
);
@autoBindMethodsForReact(AUTOBIND_CFG)
export class WorkspaceEnvironmentsEditModal extends PureComponent<Props, State> {
environmentEditorRef: EnvironmentEditor | null = null;
environmentColorInputRef: HTMLInputElement | null = null;
saveTimeout: NodeJS.Timeout | null = null;
modal: Modal | null = null;
editorKey = 0;
state: State = {
workspace: null,
isValid: true,
subEnvironments: [],
rootEnvironment: null,
selectedEnvironmentId: null,
};
colorChangeTimeout: NodeJS.Timeout | null = null;
hide() {
this.modal?.hide();
}
_setEditorRef(environmentEditor: EnvironmentEditor) {
this.environmentEditorRef = environmentEditor;
}
_setModalRef(modal: Modal) {
this.modal = modal;
}
async show(workspace: Workspace) {
const { activeEnvironmentId } = this.props;
// Default to showing the currently active environment
if (activeEnvironmentId) {
this.setState({
selectedEnvironmentId: activeEnvironmentId,
});
}
await this._load(workspace);
this.modal?.show();
}
async _load(workspace: Workspace | null, environmentToSelect: Environment | null = null) {
if (!workspace) {
console.warn('Failed to reload environment editor without Workspace');
return;
}
const rootEnvironment = await models.environment.getOrCreateForParentId(workspace._id);
const subEnvironments = await models.environment.findByParentId(rootEnvironment._id);
let selectedEnvironmentId;
if (environmentToSelect) {
selectedEnvironmentId = environmentToSelect._id;
} else if (this.state.workspace && workspace._id !== this.state.workspace._id) {
// We've changed workspaces, so load the root one
selectedEnvironmentId = rootEnvironment._id;
} else {
// We haven't changed workspaces, so try loading the last environment, and fall back
// to the root one
selectedEnvironmentId = this.state.selectedEnvironmentId || rootEnvironment._id;
}
this.setState({
workspace,
rootEnvironment,
subEnvironments,
selectedEnvironmentId,
});
}
async _handleAddEnvironment(isPrivate = false) {
const { rootEnvironment, workspace } = this.state;
if (!rootEnvironment) {
console.warn('Failed to add environment. Unknown root environment');
return;
}
const parentId = rootEnvironment._id;
const environment = await models.environment.create({
parentId,
isPrivate,
});
await this._load(workspace, environment);
}
_handleShowEnvironment(environment: Environment) {
// Don't allow switching if the current one has errors
if (this.environmentEditorRef && !this.environmentEditorRef.isValid()) {
return;
}
if (environment === this._getSelectedEnvironment()) {
return;
}
const { workspace } = this.state;
this._load(workspace, environment);
}
async _handleDuplicateEnvironment(environment: Environment) {
const { workspace } = this.state;
const newEnvironment = await models.environment.duplicate(environment);
await this._load(workspace, newEnvironment);
}
async _handleDeleteEnvironment(environment: Environment) {
const { handleChangeEnvironment, activeEnvironmentId } = this.props;
const { rootEnvironment, workspace } = this.state;
// Don't delete the root environment
if (environment === rootEnvironment) {
return;
}
// Unset active environment if it's being deleted
if (activeEnvironmentId === environment._id) {
handleChangeEnvironment(null);
}
// Delete the current one
await models.environment.remove(environment);
await this._load(workspace, rootEnvironment);
}
async _updateEnvironment(
environment: Environment | null,
patch: Partial<Environment>,
refresh = true,
) {
if (environment === null) {
return;
}
const { workspace } = this.state;
// NOTE: Fetch the environment first because it might not be up to date.
// For example, editing the body updates silently.
const realEnvironment = await models.environment.getById(environment._id);
if (!realEnvironment) {
return;
}
await models.environment.update(realEnvironment, patch);
if (refresh) {
await this._load(workspace);
}
}
async _handleChangeEnvironmentName(environment: Environment, name: string) {
await this._updateEnvironment(environment, {
name,
});
}
_handleChangeEnvironmentColor(environment: Environment | null, color: string | null) {
if (this.colorChangeTimeout !== null) {
clearTimeout(this.colorChangeTimeout);
}
this.colorChangeTimeout = setTimeout(async () => {
await this._updateEnvironment(environment, { color });
}, DEBOUNCE_MILLIS);
}
_didChange() {
this._saveChanges();
// Call this last in case component unmounted
const isValid = this.environmentEditorRef ? this.environmentEditorRef.isValid() : false;
if (this.state.isValid !== isValid) {
this.setState({
isValid,
});
}
}
_getSelectedEnvironment(): Environment | null {
const { selectedEnvironmentId, subEnvironments, rootEnvironment } = this.state;
if (rootEnvironment && rootEnvironment._id === selectedEnvironmentId) {
return rootEnvironment;
} else {
return subEnvironments.find(subEnvironment => subEnvironment._id === selectedEnvironmentId) || null;
}
}
componentDidMount() {
db.onChange(async changes => {
const { selectedEnvironmentId } = this.state;
for (const change of changes) {
const [, doc, fromSync] = change;
// Force an editor refresh if any changes from sync come in
if (doc._id === selectedEnvironmentId && fromSync) {
this.editorKey = doc.modified;
await this._load(this.state.workspace);
}
}
});
}
_handleSortEnd: SortEndHandler = results => {
const { oldIndex, newIndex } = results;
if (newIndex === oldIndex) {
return;
}
const { subEnvironments } = this.state;
const newSubEnvironments = arrayMove(subEnvironments, oldIndex, newIndex);
this.setState({
subEnvironments: newSubEnvironments,
});
// Do this last so we don't block the sorting
db.bufferChanges();
Promise.all(newSubEnvironments.map((environment, index) => this._updateEnvironment(
environment,
{ metaSortKey: index },
false,
))).then(() => {
db.flushChanges();
});
};
_handleClickColorChange(environment: Environment) {
if (!environment.color) {
// TODO: fix magic-number. Currently this is the `surprise` background color for the default theme, but we should be grabbing the actual value from the user's actual theme instead.
this._handleChangeEnvironmentColor(environment, '#7d69cb');
}
this.environmentColorInputRef?.click();
}
_saveChanges() {
// Only save if it's valid
if (!this.environmentEditorRef || !this.environmentEditorRef.isValid()) {
return;
}
let patch;
try {
const data = this.environmentEditorRef.getValue();
patch = {
data: data && data.object,
dataPropertyOrder: data && data.propertyOrder,
};
} catch (err) {
// Invalid JSON probably
return;
}
const selectedEnvironment = this._getSelectedEnvironment();
if (selectedEnvironment) {
if (this.saveTimeout !== null) {
clearTimeout(this.saveTimeout);
}
this.saveTimeout = setTimeout(async () => {
await this._updateEnvironment(selectedEnvironment, patch);
}, DEBOUNCE_MILLIS * 4);
}
}
handleInputColorChage(event: React.ChangeEvent<HTMLInputElement>) {
this._handleChangeEnvironmentColor(this._getSelectedEnvironment(), event.target.value);
}
unsetColor(environment: Environment) {
this._handleChangeEnvironmentColor(environment, null);
}
_handleActivateEnvironment: ButtonProps<Environment>['onClick'] = (environment: Environment) => {
const { handleChangeEnvironment, activeEnvironmentId } = this.props;
if (environment._id === activeEnvironmentId) {
return;
}
handleChangeEnvironment(environment._id);
this._handleShowEnvironment(environment);
};
render() {
const {
activeEnvironmentId,
} = this.props;
const { subEnvironments, rootEnvironment, isValid } = this.state;
const selectedEnvironment = this._getSelectedEnvironment();
if (this.environmentColorInputRef !== null) {
this.environmentColorInputRef.value = selectedEnvironment?.color || '';
}
const environmentInfo = {
object: selectedEnvironment ? selectedEnvironment.data : {},
propertyOrder: selectedEnvironment && selectedEnvironment.dataPropertyOrder,
};
return (
<Modal ref={this._setModalRef} wide tall {...this.props}>
<ModalHeader>Manage Environments</ModalHeader>
<ModalBody noScroll className="env-modal">
<div className="env-modal__sidebar">
<li
className={classnames('env-modal__sidebar-root-item', {
'env-modal__sidebar-item--active': selectedEnvironment === rootEnvironment,
})}
>
<Button onClick={this._handleShowEnvironment} value={rootEnvironment}>
{ROOT_ENVIRONMENT_NAME}
<HelpTooltip className="space-left">
The variables in this environment are always available, regardless of which
sub-environment is active. Useful for storing default or fallback values.
</HelpTooltip>
</Button>
</li>
<div className="pad env-modal__sidebar-heading">
<h3 className="no-margin">Sub Environments</h3>
<Dropdown right>
<DropdownButton>
<i className="fa fa-plus-circle" />
<i className="fa fa-caret-down" />
</DropdownButton>
<DropdownItem onClick={this._handleAddEnvironment} value={false}>
<i className="fa fa-eye" /> Environment
</DropdownItem>
<DropdownItem
onClick={this._handleAddEnvironment}
value={true}
title="Environment will not be exported or synced"
>
<i className="fa fa-eye-slash" /> Private Environment
</DropdownItem>
</Dropdown>
</div>
<SidebarList
activeEnvironmentId={activeEnvironmentId}
handleActivateEnvironment={this._handleActivateEnvironment}
environments={subEnvironments}
selectedEnvironment={selectedEnvironment}
showEnvironment={this._handleShowEnvironment}
changeEnvironmentName={this._handleChangeEnvironmentName}
onSortEnd={this._handleSortEnd}
helperClass="env-modal__sidebar-item--dragging"
transitionDuration={0}
useWindowAsScrollContainer={false}
/>
</div>
<div className="env-modal__main">
<div className="env-modal__main__header">
<h1>
{rootEnvironment === selectedEnvironment ? (
ROOT_ENVIRONMENT_NAME
) : (
<Editable
singleClick
className="wide"
onSubmit={name => {
if (!selectedEnvironment || !name) {
return;
}
this._handleChangeEnvironmentName(selectedEnvironment, name);
}}
value={selectedEnvironment ? selectedEnvironment.name : ''}
/>
)}
</h1>
{selectedEnvironment && rootEnvironment !== selectedEnvironment ? (
<Fragment>
<input
className="hidden"
type="color"
ref={ref => {
this.environmentColorInputRef = ref;
}}
onChange={this.handleInputColorChage}
/>
<Dropdown className="space-right" right>
<DropdownButton className="btn btn--clicky">
{selectedEnvironment.color && (
<i
className="fa fa-circle space-right"
style={{
color: selectedEnvironment.color,
}}
/>
)}
Color <i className="fa fa-caret-down" />
</DropdownButton>
<DropdownItem value={selectedEnvironment} onClick={this._handleClickColorChange}>
<i
className="fa fa-circle"
style={{
...(selectedEnvironment.color ? { color: selectedEnvironment.color } : {}),
}}
/>
{selectedEnvironment.color ? 'Change Color' : 'Assign Color'}
</DropdownItem>
<DropdownItem
value={selectedEnvironment}
onClick={this.unsetColor}
disabled={!selectedEnvironment.color}
>
<i className="fa fa-minus-circle" />
Unset Color
</DropdownItem>
</Dropdown>
<Button
value={selectedEnvironment}
onClick={this._handleDuplicateEnvironment}
className="btn btn--clicky space-right"
>
<i className="fa fa-copy" /> Duplicate
</Button>
<PromptButton
value={selectedEnvironment}
onClick={this._handleDeleteEnvironment}
className="btn btn--clicky"
>
<i className="fa fa-trash-o" />
</PromptButton>
</Fragment>
) : null}
</div>
<div className="env-modal__editor">
<EnvironmentEditor
ref={this._setEditorRef}
key={`${this.editorKey}::${selectedEnvironment ? selectedEnvironment._id : 'n/a'}`}
environmentInfo={environmentInfo}
didChange={this._didChange}
/>
</div>
</div>
</ModalBody>
<ModalFooter>
<div className="margin-left italic txt-sm">
* Environment data can be used for
<Link href={docsTemplateTags}>Nunjucks Templating</Link> in your requests
</div>
<button className="btn" disabled={!isValid} onClick={this.hide}>
Done
</button>
</ModalFooter>
</Modal>
);
}
} | the_stack |
import { localize } from 'vs/nls';
import { IDialogService } from 'vs/platform/dialogs/common/dialogs';
import { VSBuffer } from 'vs/base/common/buffer';
import Severity from 'vs/base/common/severity';
import { IWorkspaceFolderCreationData, IWorkspacesService } from 'vs/platform/workspaces/common/workspaces';
import { basename, isEqual } from 'vs/base/common/resources';
import { ByteSize, IFileService } from 'vs/platform/files/common/files';
import { IWindowOpenable } from 'vs/platform/window/common/window';
import { URI } from 'vs/base/common/uri';
import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles';
import { FileAccess, Schemas } from 'vs/base/common/network';
import { IBaseTextResourceEditorInput } from 'vs/platform/editor/common/editor';
import { DataTransfers, IDragAndDropData } from 'vs/base/browser/dnd';
import { DragMouseEvent } from 'vs/base/browser/mouseEvent';
import { Mimes } from 'vs/base/common/mime';
import { isWeb, isWindows } from 'vs/base/common/platform';
import { IInstantiationService, ServicesAccessor } from 'vs/platform/instantiation/common/instantiation';
import { IEditorIdentifier, GroupIdentifier, isEditorIdentifier, EditorResourceAccessor } from 'vs/workbench/common/editor';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { Disposable, IDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { addDisposableListener, DragAndDropObserver, EventType } from 'vs/base/browser/dom';
import { IEditorGroup } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IWorkspaceEditingService } from 'vs/workbench/services/workspaces/common/workspaceEditing';
import { IHostService } from 'vs/workbench/services/host/browser/host';
import { Emitter } from 'vs/base/common/event';
import { coalesce } from 'vs/base/common/arrays';
import { parse, stringify } from 'vs/base/common/marshalling';
import { ILabelService } from 'vs/platform/label/common/label';
import { hasWorkspaceFileExtension, isTemporaryWorkspace, IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { withNullAsUndefined } from 'vs/base/common/types';
import { IDataTransfer } from 'vs/workbench/common/dnd';
import { extractSelection } from 'vs/platform/opener/common/opener';
import { IListDragAndDrop } from 'vs/base/browser/ui/list/list';
import { ElementsDragAndDropData } from 'vs/base/browser/ui/list/listView';
import { ITreeDragOverReaction } from 'vs/base/browser/ui/tree/tree';
import { WebFileSystemAccess } from 'vs/platform/files/browser/webFileSystemAccess';
import { HTMLFileSystemProvider } from 'vs/platform/files/browser/htmlFileSystemProvider';
import { DeferredPromise } from 'vs/base/common/async';
import { Registry } from 'vs/platform/registry/common/platform';
//#region Editor / Resources DND
export class DraggedEditorIdentifier {
constructor(readonly identifier: IEditorIdentifier) { }
}
export class DraggedEditorGroupIdentifier {
constructor(readonly identifier: GroupIdentifier) { }
}
export class DraggedTreeItemsIdentifier {
constructor(readonly identifier: string) { }
}
export const CodeDataTransfers = {
EDITORS: 'CodeEditors',
FILES: 'CodeFiles'
};
export interface IDraggedResourceEditorInput extends IBaseTextResourceEditorInput {
resource: URI | undefined;
/**
* A hint that the source of the dragged editor input
* might not be the application but some external tool.
*/
isExternal?: boolean;
/**
* Whether we probe for the dropped editor to be a workspace
* (i.e. code-workspace file or even a folder), allowing to
* open it as workspace instead of opening as editor.
*/
allowWorkspaceOpen?: boolean;
}
export async function extractEditorsDropData(accessor: ServicesAccessor, e: DragEvent): Promise<Array<IDraggedResourceEditorInput>> {
const editors: IDraggedResourceEditorInput[] = [];
if (e.dataTransfer && e.dataTransfer.types.length > 0) {
// Data Transfer: Code Editors
const rawEditorsData = e.dataTransfer.getData(CodeDataTransfers.EDITORS);
if (rawEditorsData) {
try {
editors.push(...parse(rawEditorsData));
} catch (error) {
// Invalid transfer
}
}
// Data Transfer: Resources
else {
try {
const rawResourcesData = e.dataTransfer.getData(DataTransfers.RESOURCES);
editors.push(...createDraggedEditorInputFromRawResourcesData(rawResourcesData));
} catch (error) {
// Invalid transfer
}
}
// Check for native file transfer
if (e.dataTransfer?.files) {
for (let i = 0; i < e.dataTransfer.files.length; i++) {
const file = e.dataTransfer.files[i];
if (file?.path /* Electron only */) {
try {
editors.push({ resource: URI.file(file.path), isExternal: true, allowWorkspaceOpen: true });
} catch (error) {
// Invalid URI
}
}
}
}
// Check for CodeFiles transfer
const rawCodeFiles = e.dataTransfer.getData(CodeDataTransfers.FILES);
if (rawCodeFiles) {
try {
const codeFiles: string[] = JSON.parse(rawCodeFiles);
for (const codeFile of codeFiles) {
editors.push({ resource: URI.file(codeFile), isExternal: true, allowWorkspaceOpen: true });
}
} catch (error) {
// Invalid transfer
}
}
// Web: Check for file transfer
if (isWeb && containsDragType(e, DataTransfers.FILES)) {
const files = e.dataTransfer.items;
if (files) {
const instantiationService = accessor.get(IInstantiationService);
const filesData = await instantiationService.invokeFunction(accessor => extractFilesDropData(accessor, e));
for (const fileData of filesData) {
editors.push({ resource: fileData.resource, contents: fileData.contents?.toString(), isExternal: true, allowWorkspaceOpen: fileData.isDirectory });
}
}
}
// Workbench contributions
const contributions = Registry.as<IDragAndDropContributionRegistry>(Extensions.DragAndDropContribution).getAll();
for (const contribution of contributions) {
const data = e.dataTransfer.getData(contribution.dataFormatKey);
if (data) {
try {
editors.push(...contribution.getEditorInputs(data));
} catch (error) {
// Invalid transfer
}
}
}
}
return editors;
}
function createDraggedEditorInputFromRawResourcesData(rawResourcesData: string | undefined): IDraggedResourceEditorInput[] {
const editors: IDraggedResourceEditorInput[] = [];
if (rawResourcesData) {
const resourcesRaw: string[] = JSON.parse(rawResourcesData);
for (const resourceRaw of resourcesRaw) {
if (resourceRaw.indexOf(':') > 0) { // mitigate https://github.com/microsoft/vscode/issues/124946
const { selection, uri } = extractSelection(URI.parse(resourceRaw));
editors.push({ resource: uri, options: { selection } });
}
}
}
return editors;
}
export async function extractTreeDropData(dataTransfer: IDataTransfer): Promise<Array<IDraggedResourceEditorInput>> {
const editors: IDraggedResourceEditorInput[] = [];
const resourcesKey = Mimes.uriList.toLowerCase();
// Data Transfer: Resources
if (dataTransfer.has(resourcesKey)) {
try {
const asString = await dataTransfer.get(resourcesKey)?.asString();
const rawResourcesData = JSON.stringify(asString?.split('\\n').filter(value => !value.startsWith('#')));
editors.push(...createDraggedEditorInputFromRawResourcesData(rawResourcesData));
} catch (error) {
// Invalid transfer
}
}
return editors;
}
export function convertResourceUrlsToUriList(resourceUrls: string): string {
const asJson: URI[] = JSON.parse(resourceUrls);
return asJson.map(uri => uri.toString()).join('\n');
}
interface IFileTransferData {
resource: URI;
isDirectory?: boolean;
contents?: VSBuffer;
}
async function extractFilesDropData(accessor: ServicesAccessor, event: DragEvent): Promise<IFileTransferData[]> {
// Try to extract via `FileSystemHandle`
if (WebFileSystemAccess.supported(window)) {
const items = event.dataTransfer?.items;
if (items) {
return extractFileTransferData(accessor, items);
}
}
// Try to extract via `FileList`
const files = event.dataTransfer?.files;
if (!files) {
return [];
}
return extractFileListData(accessor, files);
}
async function extractFileTransferData(accessor: ServicesAccessor, items: DataTransferItemList): Promise<IFileTransferData[]> {
const fileSystemProvider = accessor.get(IFileService).getProvider(Schemas.file);
if (!(fileSystemProvider instanceof HTMLFileSystemProvider)) {
return []; // only supported when running in web
}
const results: DeferredPromise<IFileTransferData | undefined>[] = [];
for (let i = 0; i < items.length; i++) {
const file = items[i];
if (file) {
const result = new DeferredPromise<IFileTransferData | undefined>();
results.push(result);
(async () => {
try {
const handle = await file.getAsFileSystemHandle();
if (!handle) {
result.complete(undefined);
return;
}
if (WebFileSystemAccess.isFileSystemFileHandle(handle)) {
result.complete({
resource: await fileSystemProvider.registerFileHandle(handle),
isDirectory: false
});
} else if (WebFileSystemAccess.isFileSystemDirectoryHandle(handle)) {
result.complete({
resource: await fileSystemProvider.registerDirectoryHandle(handle),
isDirectory: true
});
} else {
result.complete(undefined);
}
} catch (error) {
result.complete(undefined);
}
})();
}
}
return coalesce(await Promise.all(results.map(result => result.p)));
}
export async function extractFileListData(accessor: ServicesAccessor, files: FileList): Promise<IFileTransferData[]> {
const dialogService = accessor.get(IDialogService);
const results: DeferredPromise<IFileTransferData | undefined>[] = [];
for (let i = 0; i < files.length; i++) {
const file = files.item(i);
if (file) {
// Skip for very large files because this operation is unbuffered
if (file.size > 100 * ByteSize.MB) {
dialogService.show(Severity.Warning, localize('fileTooLarge', "File is too large to open as untitled editor. Please upload it first into the file explorer and then try again."));
continue;
}
const result = new DeferredPromise<IFileTransferData | undefined>();
results.push(result);
const reader = new FileReader();
reader.onerror = () => result.complete(undefined);
reader.onabort = () => result.complete(undefined);
reader.onload = async event => {
const name = file.name;
const loadResult = withNullAsUndefined(event.target?.result);
if (typeof name !== 'string' || typeof loadResult === 'undefined') {
result.complete(undefined);
return;
}
result.complete({
resource: URI.from({ scheme: Schemas.untitled, path: name }),
contents: typeof loadResult === 'string' ? VSBuffer.fromString(loadResult) : VSBuffer.wrap(new Uint8Array(loadResult))
});
};
// Start reading
reader.readAsArrayBuffer(file);
}
}
return coalesce(await Promise.all(results.map(result => result.p)));
}
export interface IResourcesDropHandlerOptions {
/**
* Whether we probe for the dropped resource to be a workspace
* (i.e. code-workspace file or even a folder), allowing to
* open it as workspace instead of opening as editor.
*/
readonly allowWorkspaceOpen: boolean;
}
/**
* Shared function across some components to handle drag & drop of resources.
* E.g. of folders and workspace files to open them in the window instead of
* the editor or to handle dirty editors being dropped between instances of Code.
*/
export class ResourcesDropHandler {
constructor(
private readonly options: IResourcesDropHandlerOptions,
@IFileService private readonly fileService: IFileService,
@IWorkspacesService private readonly workspacesService: IWorkspacesService,
@IEditorService private readonly editorService: IEditorService,
@IWorkspaceEditingService private readonly workspaceEditingService: IWorkspaceEditingService,
@IHostService private readonly hostService: IHostService,
@IWorkspaceContextService private readonly contextService: IWorkspaceContextService,
@IInstantiationService private readonly instantiationService: IInstantiationService
) {
}
async handleDrop(event: DragEvent, resolveTargetGroup: () => IEditorGroup | undefined, afterDrop: (targetGroup: IEditorGroup | undefined) => void, targetIndex?: number): Promise<void> {
const editors = await this.instantiationService.invokeFunction(accessor => extractEditorsDropData(accessor, event));
if (!editors.length) {
return;
}
// Make the window active to handle the drop properly within
await this.hostService.focus();
// Check for workspace file / folder being dropped if we are allowed to do so
if (this.options.allowWorkspaceOpen) {
const localFilesAllowedToOpenAsWorkspace = coalesce(editors.filter(editor => editor.allowWorkspaceOpen && editor.resource?.scheme === Schemas.file).map(editor => editor.resource));
if (localFilesAllowedToOpenAsWorkspace.length > 0) {
const isWorkspaceOpening = await this.handleWorkspaceDrop(localFilesAllowedToOpenAsWorkspace);
if (isWorkspaceOpening) {
return; // return early if the drop operation resulted in this window changing to a workspace
}
}
}
// Add external ones to recently open list unless dropped resource is a workspace
// and only for resources that are outside of the currently opened workspace
const externalLocalFiles = coalesce(editors.filter(editor => editor.isExternal && editor.resource?.scheme === Schemas.file).map(editor => editor.resource));
if (externalLocalFiles.length) {
this.workspacesService.addRecentlyOpened(externalLocalFiles
.filter(resource => !this.contextService.isInsideWorkspace(resource))
.map(resource => ({ fileUri: resource }))
);
}
// Open in Editor
const targetGroup = resolveTargetGroup();
await this.editorService.openEditors(editors.map(editor => ({
...editor,
resource: editor.resource,
options: {
...editor.options,
pinned: true,
index: targetIndex
}
})), targetGroup, { validateTrust: true });
// Finish with provided function
afterDrop(targetGroup);
}
private async handleWorkspaceDrop(resources: URI[]): Promise<boolean> {
const toOpen: IWindowOpenable[] = [];
const folderURIs: IWorkspaceFolderCreationData[] = [];
await Promise.all(resources.map(async resource => {
// Check for Workspace
if (hasWorkspaceFileExtension(resource)) {
toOpen.push({ workspaceUri: resource });
return;
}
// Check for Folder
try {
const stat = await this.fileService.stat(resource);
if (stat.isDirectory) {
toOpen.push({ folderUri: stat.resource });
folderURIs.push({ uri: stat.resource });
}
} catch (error) {
// Ignore error
}
}));
// Return early if no external resource is a folder or workspace
if (toOpen.length === 0) {
return false;
}
// Pass focus to window
this.hostService.focus();
// Open in separate windows if we drop workspaces or just one folder
if (toOpen.length > folderURIs.length || folderURIs.length === 1) {
await this.hostService.openWindow(toOpen);
}
// Add to workspace if we are in a temporary workspace
else if (isTemporaryWorkspace(this.contextService.getWorkspace())) {
await this.workspaceEditingService.addFolders(folderURIs);
}
// Finaly, enter untitled workspace when dropping >1 folders
else {
await this.workspaceEditingService.createAndEnterWorkspace(folderURIs);
}
return true;
}
}
interface IResourceStat {
resource: URI;
isDirectory?: boolean;
}
export function fillEditorsDragData(accessor: ServicesAccessor, resources: URI[], event: DragMouseEvent | DragEvent): void;
export function fillEditorsDragData(accessor: ServicesAccessor, resources: IResourceStat[], event: DragMouseEvent | DragEvent): void;
export function fillEditorsDragData(accessor: ServicesAccessor, editors: IEditorIdentifier[], event: DragMouseEvent | DragEvent): void;
export function fillEditorsDragData(accessor: ServicesAccessor, resourcesOrEditors: Array<URI | IResourceStat | IEditorIdentifier>, event: DragMouseEvent | DragEvent): void {
if (resourcesOrEditors.length === 0 || !event.dataTransfer) {
return;
}
const textFileService = accessor.get(ITextFileService);
const editorService = accessor.get(IEditorService);
const fileService = accessor.get(IFileService);
const labelService = accessor.get(ILabelService);
// Extract resources from URIs or Editors that
// can be handled by the file service
const resources = coalesce(resourcesOrEditors.map(resourceOrEditor => {
if (URI.isUri(resourceOrEditor)) {
return { resource: resourceOrEditor };
}
if (isEditorIdentifier(resourceOrEditor)) {
if (URI.isUri(resourceOrEditor.editor.resource)) {
return { resource: resourceOrEditor.editor.resource };
}
return undefined; // editor without resource
}
return resourceOrEditor;
}));
const fileSystemResources = resources.filter(({ resource }) => fileService.hasProvider(resource));
// Text: allows to paste into text-capable areas
const lineDelimiter = isWindows ? '\r\n' : '\n';
event.dataTransfer.setData(DataTransfers.TEXT, fileSystemResources.map(({ resource }) => labelService.getUriLabel(resource, { noPrefix: true })).join(lineDelimiter));
// Download URL: enables support to drag a tab as file to desktop
// Requirements:
// - Chrome/Edge only
// - only a single file is supported
// - only file:/ resources are supported
const firstFile = fileSystemResources.find(({ isDirectory }) => !isDirectory);
if (firstFile) {
const firstFileUri = FileAccess.asFileUri(firstFile.resource); // enforce `file:` URIs
if (firstFileUri.scheme === Schemas.file) {
event.dataTransfer.setData(DataTransfers.DOWNLOAD_URL, [Mimes.binary, basename(firstFile.resource), firstFileUri.toString()].join(':'));
}
}
// Resource URLs: allows to drop multiple file resources to a target in VS Code
const files = fileSystemResources.filter(({ isDirectory }) => !isDirectory);
if (files.length) {
event.dataTransfer.setData(DataTransfers.RESOURCES, JSON.stringify(files.map(({ resource }) => resource.toString())));
}
// Contributions
const contributions = Registry.as<IDragAndDropContributionRegistry>(Extensions.DragAndDropContribution).getAll();
for (const contribution of contributions) {
contribution.setData(resources, event);
}
// Editors: enables cross window DND of editors
// into the editor area while presering UI state
const draggedEditors: IDraggedResourceEditorInput[] = [];
for (const resourceOrEditor of resourcesOrEditors) {
// Extract resource editor from provided object or URI
let editor: IDraggedResourceEditorInput | undefined = undefined;
if (isEditorIdentifier(resourceOrEditor)) {
const untypedEditor = resourceOrEditor.editor.toUntyped({ preserveViewState: resourceOrEditor.groupId });
if (untypedEditor) {
editor = { ...untypedEditor, resource: EditorResourceAccessor.getCanonicalUri(untypedEditor) };
}
} else if (URI.isUri(resourceOrEditor)) {
const { selection, uri } = extractSelection(resourceOrEditor);
editor = { resource: uri, options: selection ? { selection } : undefined };
} else if (!resourceOrEditor.isDirectory) {
editor = { resource: resourceOrEditor.resource };
}
if (!editor) {
continue; // skip over editors that cannot be transferred via dnd
}
// Fill in some properties if they are not there already by accessing
// some well known things from the text file universe.
// This is not ideal for custom editors, but those have a chance to
// provide everything from the `toUntyped` method.
{
const resource = editor.resource;
if (resource) {
const textFileModel = textFileService.files.get(resource);
if (textFileModel) {
// language
if (typeof editor.languageId !== 'string') {
editor.languageId = textFileModel.getLanguageId();
}
// encoding
if (typeof editor.encoding !== 'string') {
editor.encoding = textFileModel.getEncoding();
}
// contents (only if dirty)
if (typeof editor.contents !== 'string' && textFileModel.isDirty()) {
editor.contents = textFileModel.textEditorModel.getValue();
}
}
// viewState
if (!editor.options?.viewState) {
editor.options = {
...editor.options,
viewState: (() => {
for (const visibleEditorPane of editorService.visibleEditorPanes) {
if (isEqual(visibleEditorPane.input.resource, resource)) {
const viewState = visibleEditorPane.getViewState();
if (viewState) {
return viewState;
}
}
}
return undefined;
})()
};
}
}
}
// Add as dragged editor
draggedEditors.push(editor);
}
if (draggedEditors.length) {
event.dataTransfer.setData(CodeDataTransfers.EDITORS, stringify(draggedEditors));
}
}
//#endregion
//#region DND contributions
export interface IDragAndDropContributionRegistry {
/**
* Registers a drag and drop contribution.
*/
register(contribution: IDragAndDropContribution): void;
/**
* Returns all registered drag and drop contributions.
*/
getAll(): IterableIterator<IDragAndDropContribution>;
}
export interface IDragAndDropContribution {
readonly dataFormatKey: string;
getEditorInputs(data: string): IDraggedResourceEditorInput[];
setData(resources: IResourceStat[], event: DragMouseEvent | DragEvent): void;
}
class DragAndDropContributionRegistry implements IDragAndDropContributionRegistry {
private readonly _contributions = new Map<string, IDragAndDropContribution>();
register(contribution: IDragAndDropContribution): void {
if (this._contributions.has(contribution.dataFormatKey)) {
throw new Error(`A drag and drop contributiont with key '${contribution.dataFormatKey}' was already registered.`);
}
this._contributions.set(contribution.dataFormatKey, contribution);
}
getAll(): IterableIterator<IDragAndDropContribution> {
return this._contributions.values();
}
}
export const Extensions = {
DragAndDropContribution: 'workbench.contributions.dragAndDrop'
};
Registry.add(Extensions.DragAndDropContribution, new DragAndDropContributionRegistry());
//#endregion
//#region DND Utilities
/**
* A singleton to store transfer data during drag & drop operations that are only valid within the application.
*/
export class LocalSelectionTransfer<T> {
private static readonly INSTANCE = new LocalSelectionTransfer();
private data?: T[];
private proto?: T;
private constructor() {
// protect against external instantiation
}
static getInstance<T>(): LocalSelectionTransfer<T> {
return LocalSelectionTransfer.INSTANCE as LocalSelectionTransfer<T>;
}
hasData(proto: T): boolean {
return proto && proto === this.proto;
}
clearData(proto: T): void {
if (this.hasData(proto)) {
this.proto = undefined;
this.data = undefined;
}
}
getData(proto: T): T[] | undefined {
if (this.hasData(proto)) {
return this.data;
}
return undefined;
}
setData(data: T[], proto: T): void {
if (proto) {
this.data = data;
this.proto = proto;
}
}
}
export function containsDragType(event: DragEvent, ...dragTypesToFind: string[]): boolean {
if (!event.dataTransfer) {
return false;
}
const dragTypes = event.dataTransfer.types;
const lowercaseDragTypes: string[] = [];
for (let i = 0; i < dragTypes.length; i++) {
lowercaseDragTypes.push(dragTypes[i].toLowerCase()); // somehow the types are lowercase
}
for (const dragType of dragTypesToFind) {
if (lowercaseDragTypes.indexOf(dragType.toLowerCase()) >= 0) {
return true;
}
}
return false;
}
//#endregion
//#region Composites DND
export type Before2D = {
readonly verticallyBefore: boolean;
readonly horizontallyBefore: boolean;
};
export interface ICompositeDragAndDrop {
drop(data: IDragAndDropData, target: string | undefined, originalEvent: DragEvent, before?: Before2D): void;
onDragOver(data: IDragAndDropData, target: string | undefined, originalEvent: DragEvent): boolean;
onDragEnter(data: IDragAndDropData, target: string | undefined, originalEvent: DragEvent): boolean;
}
export interface ICompositeDragAndDropObserverCallbacks {
onDragEnter?: (e: IDraggedCompositeData) => void;
onDragLeave?: (e: IDraggedCompositeData) => void;
onDrop?: (e: IDraggedCompositeData) => void;
onDragOver?: (e: IDraggedCompositeData) => void;
onDragStart?: (e: IDraggedCompositeData) => void;
onDragEnd?: (e: IDraggedCompositeData) => void;
}
export class CompositeDragAndDropData implements IDragAndDropData {
constructor(private type: 'view' | 'composite', private id: string) { }
update(dataTransfer: DataTransfer): void {
// no-op
}
getData(): {
type: 'view' | 'composite';
id: string;
} {
return { type: this.type, id: this.id };
}
}
export interface IDraggedCompositeData {
readonly eventData: DragEvent;
readonly dragAndDropData: CompositeDragAndDropData;
}
export class DraggedCompositeIdentifier {
constructor(private compositeId: string) { }
get id(): string {
return this.compositeId;
}
}
export class DraggedViewIdentifier {
constructor(private viewId: string) { }
get id(): string {
return this.viewId;
}
}
export type ViewType = 'composite' | 'view';
export class CompositeDragAndDropObserver extends Disposable {
private static instance: CompositeDragAndDropObserver | undefined;
static get INSTANCE(): CompositeDragAndDropObserver {
if (!CompositeDragAndDropObserver.instance) {
CompositeDragAndDropObserver.instance = new CompositeDragAndDropObserver();
}
return CompositeDragAndDropObserver.instance;
}
private readonly transferData = LocalSelectionTransfer.getInstance<DraggedCompositeIdentifier | DraggedViewIdentifier>();
private readonly onDragStart = this._register(new Emitter<IDraggedCompositeData>());
private readonly onDragEnd = this._register(new Emitter<IDraggedCompositeData>());
private constructor() {
super();
this._register(this.onDragEnd.event(e => {
const id = e.dragAndDropData.getData().id;
const type = e.dragAndDropData.getData().type;
const data = this.readDragData(type);
if (data?.getData().id === id) {
this.transferData.clearData(type === 'view' ? DraggedViewIdentifier.prototype : DraggedCompositeIdentifier.prototype);
}
}));
}
private readDragData(type: ViewType): CompositeDragAndDropData | undefined {
if (this.transferData.hasData(type === 'view' ? DraggedViewIdentifier.prototype : DraggedCompositeIdentifier.prototype)) {
const data = this.transferData.getData(type === 'view' ? DraggedViewIdentifier.prototype : DraggedCompositeIdentifier.prototype);
if (data && data[0]) {
return new CompositeDragAndDropData(type, data[0].id);
}
}
return undefined;
}
private writeDragData(id: string, type: ViewType): void {
this.transferData.setData([type === 'view' ? new DraggedViewIdentifier(id) : new DraggedCompositeIdentifier(id)], type === 'view' ? DraggedViewIdentifier.prototype : DraggedCompositeIdentifier.prototype);
}
registerTarget(element: HTMLElement, callbacks: ICompositeDragAndDropObserverCallbacks): IDisposable {
const disposableStore = new DisposableStore();
disposableStore.add(new DragAndDropObserver(element, {
onDragEnd: e => {
// no-op
},
onDragEnter: e => {
e.preventDefault();
if (callbacks.onDragEnter) {
const data = this.readDragData('composite') || this.readDragData('view');
if (data) {
callbacks.onDragEnter({ eventData: e, dragAndDropData: data! });
}
}
},
onDragLeave: e => {
const data = this.readDragData('composite') || this.readDragData('view');
if (callbacks.onDragLeave && data) {
callbacks.onDragLeave({ eventData: e, dragAndDropData: data! });
}
},
onDrop: e => {
if (callbacks.onDrop) {
const data = this.readDragData('composite') || this.readDragData('view');
if (!data) {
return;
}
callbacks.onDrop({ eventData: e, dragAndDropData: data! });
// Fire drag event in case drop handler destroys the dragged element
this.onDragEnd.fire({ eventData: e, dragAndDropData: data! });
}
},
onDragOver: e => {
e.preventDefault();
if (callbacks.onDragOver) {
const data = this.readDragData('composite') || this.readDragData('view');
if (!data) {
return;
}
callbacks.onDragOver({ eventData: e, dragAndDropData: data! });
}
}
}));
if (callbacks.onDragStart) {
this.onDragStart.event(e => {
callbacks.onDragStart!(e);
}, this, disposableStore);
}
if (callbacks.onDragEnd) {
this.onDragEnd.event(e => {
callbacks.onDragEnd!(e);
});
}
return this._register(disposableStore);
}
registerDraggable(element: HTMLElement, draggedItemProvider: () => { type: ViewType; id: string }, callbacks: ICompositeDragAndDropObserverCallbacks): IDisposable {
element.draggable = true;
const disposableStore = new DisposableStore();
disposableStore.add(addDisposableListener(element, EventType.DRAG_START, e => {
const { id, type } = draggedItemProvider();
this.writeDragData(id, type);
e.dataTransfer?.setDragImage(element, 0, 0);
this.onDragStart.fire({ eventData: e, dragAndDropData: this.readDragData(type)! });
}));
disposableStore.add(new DragAndDropObserver(element, {
onDragEnd: e => {
const { type } = draggedItemProvider();
const data = this.readDragData(type);
if (!data) {
return;
}
this.onDragEnd.fire({ eventData: e, dragAndDropData: data! });
},
onDragEnter: e => {
if (callbacks.onDragEnter) {
const data = this.readDragData('composite') || this.readDragData('view');
if (!data) {
return;
}
if (data) {
callbacks.onDragEnter({ eventData: e, dragAndDropData: data! });
}
}
},
onDragLeave: e => {
const data = this.readDragData('composite') || this.readDragData('view');
if (!data) {
return;
}
if (callbacks.onDragLeave) {
callbacks.onDragLeave({ eventData: e, dragAndDropData: data! });
}
},
onDrop: e => {
if (callbacks.onDrop) {
const data = this.readDragData('composite') || this.readDragData('view');
if (!data) {
return;
}
callbacks.onDrop({ eventData: e, dragAndDropData: data! });
// Fire drag event in case drop handler destroys the dragged element
this.onDragEnd.fire({ eventData: e, dragAndDropData: data! });
}
},
onDragOver: e => {
if (callbacks.onDragOver) {
const data = this.readDragData('composite') || this.readDragData('view');
if (!data) {
return;
}
callbacks.onDragOver({ eventData: e, dragAndDropData: data! });
}
}
}));
if (callbacks.onDragStart) {
this.onDragStart.event(e => {
callbacks.onDragStart!(e);
}, this, disposableStore);
}
if (callbacks.onDragEnd) {
this.onDragEnd.event(e => {
callbacks.onDragEnd!(e);
}, this, disposableStore);
}
return this._register(disposableStore);
}
}
export function toggleDropEffect(dataTransfer: DataTransfer | null, dropEffect: 'none' | 'copy' | 'link' | 'move', shouldHaveIt: boolean) {
if (!dataTransfer) {
return;
}
dataTransfer.dropEffect = shouldHaveIt ? dropEffect : 'none';
}
export class ResourceListDnDHandler<T> implements IListDragAndDrop<T> {
constructor(
private readonly toResource: (e: T) => URI | null,
@IInstantiationService private readonly instantiationService: IInstantiationService
) { }
getDragURI(element: T): string | null {
const resource = this.toResource(element);
return resource ? resource.toString() : null;
}
getDragLabel(elements: T[]): string | undefined {
const resources = coalesce(elements.map(this.toResource));
return resources.length === 1 ? basename(resources[0]) : resources.length > 1 ? String(resources.length) : undefined;
}
onDragStart(data: IDragAndDropData, originalEvent: DragEvent): void {
const resources: URI[] = [];
for (const element of (data as ElementsDragAndDropData<T>).elements) {
const resource = this.toResource(element);
if (resource) {
resources.push(resource);
}
}
if (resources.length) {
// Apply some datatransfer types to allow for dragging the element outside of the application
this.instantiationService.invokeFunction(accessor => fillEditorsDragData(accessor, resources, originalEvent));
}
}
onDragOver(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): boolean | ITreeDragOverReaction {
return false;
}
drop(data: IDragAndDropData, targetElement: T, targetIndex: number, originalEvent: DragEvent): void { }
}
//#endregion | the_stack |
import * as nunjucks from 'nunjucks'
import * as prettier from 'prettier'
import { plural } from 'pluralize'
import { DMMF } from '@prisma/generator-helper'
import { load as loadYaml } from 'js-yaml'
import {
DMMFPAS,
DMMFPAS_Field,
DMMFPAS_Directives,
CompilerOptions,
CompilerOptionsPrivate,
DMMFPAS_DirectiveAliases,
DMMFPAS_CustomResolver
} from './types'
import { parseAnnotations } from 'graphql-annotations'
import { join, extname, basename, dirname } from 'path'
import { readFile, outputFile, writeFile, readFileSync, copy, openSync, writeSync, close } from 'fs-extra'
import { flow, camelCase, upperFirst, merge } from 'lodash-es'
// AppSync schema helper
const { convertSchemas } = require('appsync-schema-converter')
// Custom lodash function
const pascalCase = flow(camelCase, upperFirst)
export class PrismaAppSyncCompiler {
private dmmf:DMMF.Document
private data:DMMFPAS
private options:CompilerOptionsPrivate
// Class constructor (entry point)
constructor(dmmf:DMMF.Document, options:CompilerOptions) {
this.options = {
directiveAliases: options.directiveAliases || {},
schemaPath: options.schemaPath || process.cwd(),
outputDir: options.outputDir || join(process.cwd(), 'generated/prisma-appsync'),
directivesPriorityScheme: {
model: {
type: ['type', 'default'],
query: ['query', 'type', 'default'],
mutation: ['mutation', 'type', 'default'],
batch: ['batch', 'mutation', 'type', 'default'],
subscription: ['subscription', 'type', 'default'],
get: ['get', 'query', 'type', 'default'],
list: ['list', 'query', 'type', 'default'],
count: ['count', 'query', 'type', 'default'],
create: ['create', 'mutation', 'type', 'default'],
update: ['update', 'mutation', 'type', 'default'],
upsert: ['upsert', 'mutation', 'type', 'default'],
delete: ['delete', 'mutation', 'type', 'default'],
createMany: ['createMany', 'batch', 'mutation', 'type', 'default'],
updateMany: ['updateMany', 'batch', 'mutation', 'type', 'default'],
deleteMany: ['deleteMany', 'batch', 'mutation', 'type', 'default'],
},
field: {
field: ['field'],
}
},
aliasPrefix: 'directiveAlias_',
debug: typeof options.debug !== 'undefined' ? options.debug : false
}
this.dmmf = dmmf
this.data = {
models: [],
enums: [],
directiveAliases: merge({ default: String() }, this.options.directiveAliases),
customResolvers: []
}
this.parseDMMF()
return this
}
// Generate and output AppSync schema
public async makeSchema(customSchemaPath?:string):Promise<this> {
// generate schema
const generatorSchemaPath = await this.makeFile(
join(__dirname, './templates/schema.gql.njk')
)
let userSchema = null
if (customSchemaPath) {
if (this.options.debug) {
console.log(`[Prisma-AppSync] Adding custom schema: `, join(dirname(this.options.schemaPath), customSchemaPath))
}
// read custom user schema
userSchema = await readFile(join(
dirname(this.options.schemaPath), customSchemaPath
), { encoding: 'utf-8' })
}
// read generated schema
const generatedSchema = await readFile(
generatorSchemaPath, { encoding: 'utf-8' }
)
// list of schemas to merge
const schemasList = [generatedSchema]
if (userSchema !== null) schemasList.push(userSchema)
// Merge both schema into one
const mergedSchema = await convertSchemas(schemasList, {
commentDescriptions: true,
includeDirectives: true,
})
// Prettify schema output
const prettySchema = prettier.format(mergedSchema, {
semi: false,
parser: 'graphql',
tabWidth: 4,
trailingComma: 'none',
singleQuote: true,
printWidth: 60
})
// Overrite generator schema with the new one
await writeFile(generatorSchemaPath, prettySchema)
return this
}
// Return the AppSync client config
public getClientConfig():string {
const config = {
prismaClientModels: {}
}
for (let i = 0; i < this.data.models.length; i++) {
const model = this.data.models[i]
if (model.name !== model.pluralizedName) {
config['prismaClientModels'][model.pluralizedName] = model.prismaRef
}
config['prismaClientModels'][model.name] = model.prismaRef
}
return JSON.stringify(config)
}
// Generate and output AppSync resolvers
public async makeResolvers(customResolversPath?:string):Promise<this> {
if (customResolversPath) {
if (this.options.debug) {
console.log(`[Prisma-AppSync] Adding custom resolver: `, join(dirname(this.options.schemaPath), customResolversPath))
}
// Read user-defined custom resolvers
this.data.customResolvers = (loadYaml(
readFileSync(
join(dirname(this.options.schemaPath), customResolversPath),
{ encoding: 'utf8' }
)
) as DMMFPAS_CustomResolver[])
}
// generate resolvers
await this.makeFile(
join(__dirname, './templates/resolvers.yaml.njk')
)
return this
}
// Generate client code for the Lambda resolver
public async makeClient():Promise<this> {
await copy(
join(__dirname, './prisma-appsync'),
join(this.options.outputDir, 'client')
)
// edit output to inject env var at beginning
const clientPath = join(this.options.outputDir, 'client', 'index.js')
const clientContent = readFileSync(clientPath)
const clientDescriptor = openSync(clientPath, 'w+')
const clientConfig = Buffer.from(
`process.env.PRISMA_APPSYNC_GENERATED_CONFIG=${JSON.stringify(this.getClientConfig())};`
)
writeSync(clientDescriptor, clientConfig, 0, clientConfig.length, 0)
writeSync(clientDescriptor, clientContent, 0, clientContent.length, clientConfig.length)
close(clientDescriptor)
return this
}
// Generate and output API documentation
public async makeDocs():Promise<this> {
// generate main readme file
await this.makeFile(
join(__dirname, './templates/docs/README.md.njk'),
{ outputDir: 'docs' }
)
// generate doc for each model
for (let i = 0; i < this.data.models.length; i++) {
const model = this.data.models[i]
await this.makeFile(
join(__dirname, './templates/docs/model.md.njk'),
{ data: { model }, outputFilename: `${model.name}.md`, outputDir: 'docs' }
)
}
return this
}
// Parse data from Prisma DMMF
private parseDMMF():this {
// models
this.dmmf.datamodel.models.forEach((model:DMMF.Model) => {
const modelDirectives:DMMFPAS_Directives = this.getModelDirectives(model)
const fields:DMMFPAS_Field[] = []
if (!this.isIgnored(model)) {
model.fields.forEach((field:DMMF.Field) => {
const fieldDirectives:DMMFPAS_Directives = this.getFieldDirectives(field, model)
if (!field.isGenerated && !this.isIgnored(field)) {
fields.push({
name: field.name,
scalar: this.getFieldScalar(field),
isRequired: this.isFieldRequired(field),
isEnum: this.isFieldEnum(field),
isEditable: !this.isFieldImmutableDate(field),
isUnique: this.isFieldUnique(field, model),
...(field.relationName && {
relation: {
name: this.getFieldRelationName(field, model),
kind: this.getFieldRelationKind(field),
type: this.getFieldType(field),
}
}),
...(Object.keys(fieldDirectives).length > 0 && {
directives: fieldDirectives
}),
sample: this.getFieldSample(field)
})
}
})
this.data.models.push({
name: pascalCase(model.name),
pluralizedName: pascalCase(plural(model.name)),
prismaRef: model.name.charAt(0).toLowerCase() + model.name.slice(1),
...(Object.keys(modelDirectives).length > 0 && {
directives: modelDirectives
}),
idFields: model.idFields,
fields: fields,
subscriptionFields: this.filterSubscriptionFields(fields, model.idFields)
})
}
})
// enums
this.dmmf.datamodel.enums.forEach((enumerated:DMMF.DatamodelEnum) => {
const enumValues:string[] = enumerated.values.map(v => v.name)
this.data.enums.push({
name: enumerated.name,
values: enumValues,
})
})
// console.log( inspect(this.data, false, null, true) )
return this
}
// Return fields for subscription
private filterSubscriptionFields(fields:DMMFPAS_Field[], idFields?:string[]):DMMFPAS_Field[] {
const subFields:DMMFPAS_Field[] = []
const maxFields:number = 5
let shouldContinue:boolean = true
let currentIndex:number = 0
while(shouldContinue) {
shouldContinue = false
const field:DMMFPAS_Field = fields[currentIndex]
if (typeof field !== 'undefined' && !field.relation && field.isUnique) {
subFields.push(field)
} currentIndex++
const hasRemainingFields:boolean = currentIndex < fields.length
const isBelowMaxFieldsLimit:boolean = subFields.length < maxFields
const hasMultipleIds:boolean =
subFields.findIndex(s => s.name === 'uuid') > -1
&& subFields.findIndex(s => s.name === 'id') > -1
if (
hasRemainingFields
&& isBelowMaxFieldsLimit
) {
shouldContinue = true
} else if (
hasRemainingFields
&& !isBelowMaxFieldsLimit
&& hasMultipleIds
) {
const destroyIndex = subFields.findIndex(s => s.name === 'uuid')
if (destroyIndex > -1) subFields.splice(destroyIndex, 1)
shouldContinue = true
} else if (
hasRemainingFields
&& !isBelowMaxFieldsLimit
&& idFields && idFields.length > 0
) {
subFields.push({
name: idFields.join('_'),
scalar: `${idFields.join('_')}FieldsInput!`,
isEnum: false,
isRequired: true,
isEditable: false,
isUnique: true,
sample: `2`
})
}
}
return subFields
}
// Return true if field is unique (meaning it can be used for WhereUniqueInputs)
private isFieldUnique(searchField:DMMF.Field, model:DMMF.Model):boolean {
return searchField.isId
|| searchField.isUnique
|| this.isFieldGeneratedRelation(searchField, model)
}
// Return true if field is required
private isFieldRequired(searchField:DMMF.Field):boolean {
return searchField.isRequired
&& !(searchField.relationName && searchField.isList)
}
// Return true if field is an enum type
private isFieldEnum(searchField:DMMF.Field):boolean {
return searchField.kind === 'enum'
}
// Return true if field shouldn't be mutated manually (e.g. `updatedAt`)
private isFieldImmutableDate(searchField:DMMF.Field):boolean {
return searchField.isId
|| searchField.isUpdatedAt
|| ['updatedAt', 'createdAt'].includes(searchField.name)
}
// Return true if field is generated by Prisma (e.g. `authorId` relationship)
private isFieldGeneratedRelation(searchField:DMMF.Field, model:DMMF.Model):boolean {
return model.fields.findIndex((field:DMMF.Field) => {
return field.relationFromFields
&& field.relationFromFields.includes(searchField.name)
}) > -1
}
// Compile and output file
private async makeFile(
inputFile:string,
outputFileOptions?:{ data?:any, outputFilename?:string, outputDir?:string }
):Promise<string> {
const inputContent:string = await readFile(inputFile, { encoding: 'utf8' })
const env = nunjucks.configure({ autoescape: true })
env.addFilter('pascalCase', (str:string) => pascalCase(str))
let outputContent:string = nunjucks.renderString(
inputContent.trim(),
outputFileOptions && outputFileOptions.data
? outputFileOptions.data
: this.data
)
const outputFilename:string = outputFileOptions && outputFileOptions.outputFilename
? outputFileOptions.outputFilename
: basename(inputFile.replace('.njk', ''))
let parserOpt:prettier.RequiredOptions['parser']|boolean
switch (extname(outputFilename)) {
case '.ts': parserOpt = 'typescript'; break
case '.json': parserOpt = 'json'; break
case '.gql': parserOpt = 'graphql'; break
case '.md': parserOpt = 'markdown'; break
case '.yaml': parserOpt = 'yaml'; break
case '.js': parserOpt = 'babel'; break
default: parserOpt = false; break
}
// pretiffy output
outputContent = parserOpt ? prettier.format(outputContent, {
semi: false,
parser: parserOpt,
tabWidth: 4,
trailingComma: 'none',
singleQuote: true,
printWidth: 60
}) : outputContent
const outputFilePath = join(
this.options.outputDir,
outputFileOptions && outputFileOptions.outputDir ? outputFileOptions.outputDir : ``,
outputFilename
)
await outputFile(
outputFilePath,
outputContent
)
return outputFilePath
}
// Return field sample for demo/docs
private getFieldSample(field:DMMF.Field):any {
switch (field.type) {
case 'Int':
return `2`
case 'String':
return `"Foo"`
case 'Json':
return { foo: "bar" }
case 'Float':
return `2.5`
case 'Boolean':
return `false`
case 'DateTime':
return `"dd/mm/YYYY"`
default:
return field.type
}
}
// Return relation name from Prisma type
private getFieldRelationName(field:DMMF.Field, model:DMMF.Model):string {
return pascalCase(`${model.name} ${field.name}`)
}
// Return relation kind (`one` or `many`) from Prisma type
private getFieldRelationKind(field:DMMF.Field):'one'|'many' {
return field.relationFromFields
&& field.relationFromFields.length === 1
? 'one' : 'many'
}
// Get AppSync scalar from Prisma type
private getFieldScalar(field:DMMF.Field):string {
let scalar:string = this.getFieldType(field)
if (field.isList) {
if (field.isRequired) scalar = `${scalar}!`
scalar = `[${scalar}]`
}
return scalar
}
// Get AppSync type from Prisma type
private getFieldType(field:DMMF.Field):string {
let type:string = 'String'
if (field.kind === 'scalar') {
switch(field.type.toLocaleLowerCase()) {
case 'int': type = 'Int'; break
case 'datetime': type = 'AWSDateTime'; break
case 'json': type = 'AWSJSON'; break
case 'float': type = 'Float'; break
case 'boolean': type = 'Boolean'; break
case 'string': type = 'String'; break
}
if (type === 'String') {
switch(field.name.toLocaleLowerCase()) {
case 'email': type = 'AWSEmail'; break
case 'url': type = 'AWSURL'; break
}
}
} else {
type = field.type
}
return type
}
// Read AppSync model directives from AST comments
private getModelDirectives(model:DMMF.Model):DMMFPAS_Directives {
return this.getDirectives(model, this.options.directivesPriorityScheme['model'])
}
// Return true if field or model is ignored /// @PrismaAppSync.ignore
private isIgnored(node:DMMF.Field|DMMF.Model):boolean {
let isIgnored = false
// search .ignore annotations in Prisma doc node (AST)
if (typeof node['documentation'] !== 'undefined'
&& node['documentation'].includes('@PrismaAppSync.ignore')) {
isIgnored = true
}
return isIgnored
}
// Read AppSync field directives from AST comments
private getFieldDirectives(field:DMMF.Field, model:DMMF.Model):DMMFPAS_Directives {
if (field.relationName) {
const relationModel:DMMF.Model|false = this.getModelIfExists(field.type)
if (relationModel) {
const modelDirectives = this.getModelDirectives(model)
const relationModelDirectives = this.getModelDirectives(relationModel)
const fieldDirectives:DMMFPAS_Directives = {
...(modelDirectives['type'] !== relationModelDirectives['type'] && {
'field': relationModelDirectives['type']
}),
...(modelDirectives['mutation'] !== relationModelDirectives['mutation'] && {
'mutation': relationModelDirectives['mutation']
}),
...(modelDirectives['create'] !== relationModelDirectives['create'] && {
'create': relationModelDirectives['create']
}),
...(modelDirectives['update'] !== relationModelDirectives['update'] && {
'update': relationModelDirectives['update']
}),
}
return fieldDirectives
}
}
return this.getDirectives(field, this.options.directivesPriorityScheme['field'])
}
// Return DMMF model from model name
private getModelIfExists(name:string):DMMF.Model|false {
const modelIndex = this.dmmf.datamodel.models.findIndex((model:DMMF.Model) => {
return model.name === name
})
return modelIndex > -1 ? this.dmmf.datamodel.models[modelIndex] : false
}
// Return directives strings
private getDirectives(
node:DMMF.Field|DMMF.Model, priorityScheme?:any
):DMMFPAS_Directives {
let directives:DMMFPAS_Directives = {}
let annotations:any
// search annotations in Prisma documentation node (AST)
if (typeof node['documentation'] !== 'undefined') {
annotations = parseAnnotations('PrismaAppSync', node['documentation'])
}
// format all directive aliases to with @@ prefix (except for default)
const directiveAliases:DMMFPAS_DirectiveAliases = {}
Object.keys(this.data.directiveAliases)
.forEach(alias => {
if (alias === 'default')
directiveAliases[alias] = this.data.directiveAliases[alias]
else
directiveAliases[`@@${alias}`] = this.data.directiveAliases[alias]
})
// merge directive alias with annotations
annotations = merge(annotations, directiveAliases)
// generate directives list based on priorityScheme
for (const schemaScope in priorityScheme) {
if (Object.prototype.hasOwnProperty.call(priorityScheme, schemaScope)) {
const priorityList:string[] = priorityScheme[schemaScope]
// If we find a matching scope rule, then apply AND stop
for (let i = 0; i < priorityList.length; i++) {
const scope:string = priorityList[i]
if (typeof annotations[scope] !== 'undefined') {
directives[schemaScope] = annotations[scope]
break
}
}
}
}
// replace all user aliases with matching directives
Object.keys(directives)
.forEach(scope => {
const directive = directives[scope]
const directiveKey = directive.replace('@@', '')
if (/\@\@\w+/.test(directive)
&& typeof this.data.directiveAliases[directiveKey] !== 'undefined'
) {
directives[scope] = this.data.directiveAliases[directiveKey]
}
})
return directives
}
} | the_stack |
import { ChangeDetectorRef, Component, DebugElement, ElementRef, OnInit, ViewChild } from '@angular/core';
import { ComponentFixture, fakeAsync, flush, TestBed, tick } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { AvatarModule } from 'ng-devui/avatar';
import { CheckBoxModule } from 'ng-devui/checkbox';
import { DataTableComponent, DataTableHeadComponent, DataTableRowComponent, TableCheckOptions } from 'ng-devui/data-table';
import { DatepickerComponent, DatepickerModule } from 'ng-devui/datepicker';
import { DropDownMenuDirective, DropDownToggleDirective } from 'ng-devui/dropdown';
import { InputNumberComponent, InputNumberModule } from 'ng-devui/input-number';
import { SelectModule } from 'ng-devui/select';
import { TooltipModule } from 'ng-devui/tooltip';
import { LoadingType } from '..';
import { I18nModule } from '../i18n';
import { createMouseEvent } from '../utils/testing/event-helper';
import { DataTableModule } from './data-table.module';
import { editableOriginSource, genderSource, originSource, SourceType, treeDataSource } from './demo/mock-data';
const dataTableOptions = {
columns: [
{
field: 'firstName',
header: 'First Name',
fieldType: 'text',
sortable: true,
order: 1
},
{
field: 'lastName',
header: 'Last Name',
fieldType: 'text',
sortable: true,
order: 2
},
{
field: 'gender',
header: 'gender',
fieldType: 'text',
sortable: true,
order: 3
},
{
field: 'dob',
header: 'Date of birth',
fieldType: 'date',
sortable: true,
order: 4
},
],
};
// column: basic & checkable
@Component({
template: `
<d-data-table #datatable [checkable]="checkable" [dataSource]="basicDataSource" [type]="'striped'"
[checkOptions]="checkOptions" [generalRowHoveredData]="true">
<d-column field="$index" header="#" [width]="'50px'"></d-column>
<d-column
*ngFor="let colOption of dataTableOptions.columns"
[field]="colOption.field"
[header]="colOption.header"
[fieldType]="colOption.fieldType"
[order]="colOption.order"
[width]="'150px'"
>
</d-column>
</d-data-table>
`,
})
class TestDataTableColumnBasicComponent {
@ViewChild('datatable') datatable;
basicDataSource: Array<SourceType> = JSON.parse(JSON.stringify(originSource.slice(0, 6)));
dataTableOptions = dataTableOptions;
checkable = false;
checkTotalData = jasmine.createSpy('call totalData function');
checkOptions: TableCheckOptions[] = [
{
label: '全选所有数据',
onChecked: this.checkTotalData.bind(this)
},
{
label: '全选当前页数据',
onChecked: undefined
}
];
}
// column: checkable, sortable, filterable
@Component({
template: `
<d-data-table
[dataSource]="sortableDataSource"
[onlyOneColumnSort]="onlyOneColumnSort"
[(multiSort)]="sortedColumn"
(multiSortChange)="multiSortChange($event)"
[scrollable]="true"
[resizeable]="true"
[showSortIcon]="true"
[checkable]="true"
[hideColumn]="hideColumn"
(pageIndexChange)="changePageContent($event)"
(resize)="onResize($event)"
(cellClick)="cellClick($event)"
(cellDBClick)="cellDBClick($event)"
(rowDBClick)="rowDBClick($event)"
(rowClick)="rowClick($event)"
>
<d-column field="$index" header="#" [width]="'50px'"></d-column>
<d-column
field="firstName"
header="First Name"
[sortable]="true"
[width]="'150px'"
[filterable]="true"
[filterList]="filterList"
[beforeFilter]="beforeFilter"
(filterChange)="filterChangeMultiple($event)"
></d-column>
<d-column
field="lastName"
header="Last Name"
[sortable]="true"
[width]="'150px'"
[minWidth]="'100px'"
[maxWidth]="'200px'"
[filterable]="true"
[filterList]="filterList2"
[filterIconActive]="filterIconActive"
[customFilterTemplate]="customFilterTemplate"
></d-column>
<d-column field="gender" header="Gender" [sortable]="true" [width]="'100px'"></d-column>
<d-column
field="dob"
header="Date of birth"
[fieldType]="'date'"
[extraOptions]="{ dateFormat: 'MM/dd/yyyy' }"
[width]="'2000px'"
></d-column>
<d-column field="hidden" header="hidden" [width]="'100px'">hidden</d-column>
</d-data-table>
<ng-template #customFilterTemplate let-filterList="filterListDisplay" let-dropdown="dropdown" let-column="column">
<div class="custom-filter-content">
<div class="filter-options">
<div *ngFor="let item of checkboxList" class="checkbox-group">
<d-checkbox
[label]="item.lastName"
[(ngModel)]="item.chosen"
[labelTemplate]="myCheckbox"
(change)="onCheckboxChange($event, item.lastName)"
>
<ng-template #myCheckbox let-label="label">
<d-avatar [name]="label" [width]="16" [height]="16"></d-avatar>
<span class="label-style">{{ label }}</span>
</ng-template>
</d-checkbox>
</div>
</div>
<div class="line"></div>
<div>
<span class="button-style" style="border-right: 1px solid #e8f0fd; margin-left: 10px;" (click)="filterSource(dropdown)"
>CONFIRM</span
>
<span class="button-style" (click)="cancelFilter(dropdown)">CANCEL</span>
</div>
</div>
</ng-template>
`,
})
class TestDataTableAdvancedColumnComponent implements OnInit {
constructor(private ref: ChangeDetectorRef) {}
@ViewChild(DataTableComponent) datatable: DataTableComponent;
pagerSource = JSON.parse(JSON.stringify(originSource));
sortableDataSource: Array<SourceType> = JSON.parse(JSON.stringify(originSource.slice(0, 6)));
onlyOneColumnSort = true;
sortedColumn = [
{
field: 'lastName',
direction: 'ASC',
},
];
filterList = [
{
name: 'Mark',
value: 'Mark',
},
{
name: 'Jacob',
value: 'Jacob',
},
{
name: 'Danni',
value: 'Danni',
},
{
name: 'green',
value: 'green',
},
{
name: 'po',
value: 'po',
},
{
name: 'john',
value: 'john',
},
];
filterList2 = [
{
name: 'Clear',
value: 'Clear',
},
{
name: 'Male',
value: 'Male',
},
{
name: 'Female',
value: 'Female',
},
];
filterListMulti = JSON.parse(JSON.stringify(originSource.slice(0, 6)));
hideColumn = ['hidden'];
total = 20;
next = 1;
complete = false;
lazyDataSource = [];
loading: LoadingType;
checkboxList = [];
allChecked = false;
halfChecked = false;
// record values to be test
testCellClickEvent = null;
testCellDbClickEvent = null;
testRowClickEvent = null;
testRowDblClickEvent = null;
resizeEvent = null;
multiSortChange = jasmine.createSpy('multi sort change');
cellClick(e) {
this.testCellClickEvent = e;
}
cellDBClick(e) {
this.testCellDbClickEvent = e;
}
rowClick(e) {
this.testRowClickEvent = e;
}
rowDBClick(e) {
this.testRowDblClickEvent = e;
}
ngOnInit() {
this.checkboxList = JSON.parse(JSON.stringify(originSource.slice(0, 6)));
}
changePageContent($event) {
this.sortableDataSource = this.pagerSource.slice(($event.pageIndex - 1) * $event.pageSize, $event.pageIndex * $event.pageSize - 1);
}
onResize(event) {
this.resizeEvent = event;
}
filterChangeMultiple($event) {
const filterList = $event.map(item => item.name);
const dataDisplay = [];
JSON.parse(JSON.stringify(originSource.slice(0, 6))).map(item => {
if (filterList.includes(item.firstName)) {
dataDisplay.push(item);
}
});
this.sortableDataSource = dataDisplay;
}
beforeFilter = currentValue => {
this.filterListMulti = this.filterList;
this.ref.detectChanges();
return true;
};
getCheckedRows() {
return this.datatable.getCheckedRows();
}
onCheckboxChange($event, name) {
this.setHalfChecked();
}
setHalfChecked() {
this.halfChecked = false;
const chosen = this.checkboxList.filter(item => item.chosen);
if (chosen.length === this.checkboxList.length) {
this.allChecked = true;
} else if (chosen.length > 0) {
this.halfChecked = true;
} else {
this.allChecked = false;
this.halfChecked = false;
}
}
}
// column: edit
@Component({
template: `
<d-data-table
#dataTable
[dataSource]="basicDataSource"
fixHeader="true"
maxHeight="150px"
(cellEditEnd)="thisCellEditEnd($event)"
[scrollable]="true"
>
<d-column field="lastName" header="Last Name" [width]="'100px'" [editable]="true">
<d-cell-edit>
<ng-template let-rowItem="rowItem" let-column="column">
<div class="customized-editor edit-padding-fix">
<input class="devui-form-control" [(ngModel)]="rowItem[column.field]" maxlength="5" />
</div>
</ng-template>
</d-cell-edit>
</d-column>
<d-column field="dob" header="Date of birth" [editable]="true" [width]="'150px'">
<d-cell>
<ng-template let-cellItem="cellItem">
{{ cellItem | i18nDate: 'full':false }}
</ng-template>
</d-cell>
<d-cell-edit>
<ng-template let-rowItem="rowItem" let-column="column">
<form class="form-inline edit-padding-fix">
<div class="devui-form-group">
<div class="devui-input-group">
<input
class="devui-form-control search"
[name]="column.field"
[(ngModel)]="rowItem[column.field]"
dDatepicker
appendToBody
[dateFormat]="yyyy / MM / DD"
#datePicker="datepicker"
[showTime]="true"
[autoOpen]="true"
/>
<div class="devui-input-group-addon" (click)="datePicker.toggle($event, true)">
<i class="icon icon-calendar"></i>
</div>
</div>
</div>
</form>
</ng-template>
</d-cell-edit>
</d-column>
<d-column field="age" fieldType="number" header="Age" [width]="'100px'" [editable]="true">
<d-cell-edit>
<ng-template let-rowItem="rowItem" let-column="column">
<div class="customized-editor edit-padding-fix">
<d-input-number [(ngModel)]="rowItem[column.field]" class="input-number"></d-input-number>
</div>
</ng-template>
</d-cell-edit>
</d-column>
<d-column field="gender" header="Gender" [width]="'100px'" [editable]="true">
<d-cell>
<ng-template let-cellItem="cellItem">
{{ cellItem.label }}
</ng-template>
</d-cell>
<d-cell-edit>
<ng-template let-rowItem="rowItem" let-column="column">
<div class="customized-editor edit-padding-fix">
<d-select
[options]="genderSource"
isSearch="true"
[filterKey]="'label'"
autoFocus="true"
toggleOnFocus="true"
[(ngModel)]="rowItem[column.field]"
(ngModelChange)="finishEdit()"
>
<ng-template let-option="option" let-filterKey="filterKey"> gender:{{ option[filterKey] }} </ng-template>
</d-select>
</div>
</ng-template>
</d-cell-edit>
</d-column>
</d-data-table>
`,
})
class TestDataTableColumnEditComponent {
@ViewChild(DataTableComponent) dataTable: DataTableComponent;
genderSource = genderSource;
basicDataSource: Array<SourceType> = JSON.parse(JSON.stringify(editableOriginSource.slice(0, 6)));
thisCellEditEnd = jasmine.createSpy('cell edit end');
finishEdit() {
this.dataTable.cancelEditingStatus();
}
}
// column: datatable with tree structure
@Component({
template: `
<d-data-table
#dataTable
[dataSource]="basicDataSource"
[checkable]="true"
[checkableRelation]="checkableRelation"
[scrollable]="true"
[loadChildrenTable]="loadChildrenTable"
[loadAllChildrenTable]="loadAllChildrenTable"
>
<d-column [order]="1" field="title" header="title" [width]="'40%'" [nestedColumn]="true" [extraOptions]="extraOptions"></d-column>
<d-column [order]="2" field="lastName" header="name" [width]="'20%'"></d-column>
<d-column [order]="3" field="status" header="status" [width]="'20%'"></d-column>
<d-column
[order]="4"
field="dob"
header="date"
[fieldType]="'date'"
[extraOptions]="{ dateFormat: 'MM/dd/yyyy' }"
[width]="'20%'"
></d-column>
</d-data-table>
`,
})
class TestDataTableColumnWithChildrenComponent {
basicDataSource: Array<SourceType> = JSON.parse(JSON.stringify(treeDataSource.slice(0, 6)));
}
// column: datatable multi header
@Component({
template: `
<d-data-table
[type]="'striped'"
[dataSource]="basicDataSource"
[scrollable]="true"
[resizeable]="resizable"
[colDraggable]="colDraggable"
>
<d-column [order]="1" field="$index" header="#" [width]="'50px'"></d-column>
<d-column
[order]="3"
field="firstName"
header="First Name"
[sortable]="true"
[width]="'150px'"
[advancedHeader]="[
{ header: 'Name', rowspan: 1, colspan: 2, $width: '300px' },
{ header: 'First Name', rowspan: 1, colspan: 1 }
]"
>
</d-column>
<d-column
[order]="5"
field="lastName"
header="Last Name"
[sortable]="true"
[width]="'150px'"
[advancedHeader]="[
{ header: 'Name', rowspan: 1, colspan: 0 },
{ header: 'Last Name', rowspan: 1, colspan: 1 }
]"
></d-column>
<d-column [order]="7" field="gender" header="Gender" [sortable]="true" [width]="'150px'"></d-column>
<d-column
[order]="2"
field="dob"
header="Date of birth"
[fieldType]="'date'"
[extraOptions]="{ dateFormat: 'MM/dd/yyyy' }"
[width]="'200px'"
></d-column>
</d-data-table>
`,
})
class TestDataTableColumnMultiHeaderComponent {
basicDataSource: Array<SourceType> = JSON.parse(JSON.stringify(originSource.slice(0, 6)));
resizable = false;
colDraggable = false;
}
// column: fix header
@Component({
template: `
<d-data-table
#datatable1
[dataSource]="maxHeightDataSource"
fixHeader="true"
maxHeight="400px"
[scrollable]="true"
[resizeable]="resizable"
>
<d-column field="$index" header="#" [width]="'100px'"></d-column>
<d-column
*ngFor="let colOption of dataTableOptions.columns"
[field]="colOption.field"
[header]="colOption.header"
[sortable]="colOption.sortable"
[fieldType]="colOption.fieldType"
[width]="'150px'"
>
</d-column>
</d-data-table>
`,
})
class TestDataTableColumnFixHeaderComponent {
resizable = false;
dataTableOptions = dataTableOptions;
maxHeightDataSource: Array<SourceType> = JSON.parse(JSON.stringify(originSource.slice()));
}
// column: column drag
@Component({
template: `
<d-data-table
#datatable
[dataSource]="basicDataSource"
[fixHeader]="isHeaderFixed"
colDraggable="true"
maxHeight="400px"
[scrollable]="true"
>
<d-column field="$index" header="#" [width]="'50px'"></d-column>
<d-column
*ngFor="let colOption of dataTableOptions.columns"
[field]="colOption.field"
[header]="colOption.header"
[fieldType]="colOption.fieldType"
[width]="'150px'"
>
</d-column>
</d-data-table>
`,
})
class TestDataTableColumnDragComponent {
isHeaderFixed = false;
dataTableOptions = dataTableOptions;
basicDataSource: Array<SourceType> = JSON.parse(JSON.stringify(originSource.slice()));
}
// expand row
@Component({
template: `
<d-data-table
#dataTable
[dataSource]="basicDataSource"
[checkable]="true"
[showExpandToggle]="true"
[scrollable]="true"
(detialToggle)="toggleChange($event)"
>
<d-column field="$index" header="#" [width]="'50px'"></d-column>
<d-column field="firstName" header="First Name" [width]="'150px'"></d-column>
<d-column field="lastName" header="Last Name" [width]="'150px'"></d-column>
<d-column field="gender" header="Gender" [width]="'100px'"></d-column>
</d-data-table>
<ng-template #addSubRowContent let-rowIndex="rowIndex" let-rowItem="rowItem">
<div class="edit-padding-fix">
<div class="input-block">
<input class="devui-form-control" [(ngModel)]="defaultRowData.firstName" placeholder="firstName" type="text" />
</div>
<div class="input-block">
<input class="devui-form-control" [(ngModel)]="defaultRowData.lastName" placeholder="lastName" type="text" />
</div>
</div>
</ng-template>
`,
})
class TestDataTableExpandComponent implements OnInit {
@ViewChild('addSubRowContent', { static: true }) addSubRowContent: ElementRef;
basicDataSource: Array<SourceType> = JSON.parse(JSON.stringify(originSource.slice(0, 6)));
defaultRowData = {
firstName: '',
lastName: '',
gender: 'Female',
dob: new Date(1991, 3, 1),
};
toggleChange = jasmine.createSpy('detail content toggle change');
ngOnInit() {
this.basicDataSource[0].$expandConfig = { expand: false, expandTemplateRef: this.addSubRowContent };
this.basicDataSource[1]['$isDetailOpen'] = true;
this.basicDataSource[1].detail = 'show detail';
}
}
describe('data-table column', () => {
describe('basic & checkable', () => {
let fixture: ComponentFixture<TestDataTableColumnBasicComponent>;
let debugEl: DebugElement;
let component: TestDataTableColumnBasicComponent;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [DataTableModule, I18nModule, NoopAnimationsModule],
declarations: [TestDataTableColumnBasicComponent],
});
});
beforeEach(() => {
fixture = TestBed.createComponent(TestDataTableColumnBasicComponent);
debugEl = fixture.debugElement;
component = fixture.componentInstance;
});
it('should create correctly', () => {
fixture.detectChanges();
expect(component).toBeTruthy();
});
it('should mouse enter/leave change row hovered to be true/false', () => {
fixture.detectChanges();
const tbodyRows = debugEl.queryAll(By.directive(DataTableRowComponent));
let item = tbodyRows[0].componentInstance;
expect(item.rowItem.$hovered).toBeFalsy();
expect(tbodyRows.length).toBe(component.basicDataSource.length);
tbodyRows[0].nativeElement.dispatchEvent(new Event('mouseenter'));
item = tbodyRows[0].componentInstance;
expect(item.rowItem.$hovered).toBeTruthy();
tbodyRows[0].nativeElement.dispatchEvent(new Event('mouseleave'));
item = tbodyRows[0].componentInstance;
expect(item.rowItem.$hovered).toBeFalsy();
});
it('should checkable bind function onRowCheckChange work', fakeAsync(() => {
component.checkable = true;
fixture.detectChanges();
const tbodyRows = debugEl.queryAll(By.directive(DataTableRowComponent));
let item = tbodyRows[0].componentInstance;
expect(item.rowItem.$checked).toBeFalsy();
const checkBoxElRow1 = tbodyRows[0].query(By.css('.devui-checkable-cell label'));
checkBoxElRow1.nativeElement.dispatchEvent(new Event('click'));
fixture.detectChanges();
tick();
fixture.detectChanges();
item = tbodyRows[0].componentInstance;
expect(item.rowItem.$checked).toBeTruthy();
checkBoxElRow1.nativeElement.dispatchEvent(new Event('click'));
fixture.detectChanges();
tick();
fixture.detectChanges();
item = tbodyRows[0].componentInstance;
expect(item.rowItem.$checked).toBeFalsy();
}));
it('should check all change header checkbox status to checked', fakeAsync(() => {
component.checkable = true;
fixture.detectChanges();
const tbodyRows = debugEl.queryAll(By.directive(DataTableRowComponent));
let checkBoxEl;
for (let i = 0; i < tbodyRows.length; i++) {
checkBoxEl = tbodyRows[i].query(By.css('.devui-checkable-cell label'));
checkBoxEl.nativeElement.dispatchEvent(new Event('click'));
fixture.detectChanges();
tick();
fixture.detectChanges();
}
tick(); // wait for head change
fixture.detectChanges();
const headerRowDebugEl = debugEl.query(By.directive(DataTableHeadComponent));
const headerCheckBox = headerRowDebugEl.query(By.css('.devui-checkable-cell label input'));
expect(headerCheckBox.properties.checked).toBeTruthy();
}));
it('should header checked will check all body checkbox', fakeAsync(() => {
component.checkable = true;
fixture.detectChanges();
const headerRowDebugEl = debugEl.query(By.directive(DataTableHeadComponent));
const headerCheckBoxLabel = headerRowDebugEl.query(By.css('.devui-checkable-cell label'));
headerCheckBoxLabel.nativeElement.dispatchEvent(new Event('click'));
tick();
fixture.detectChanges();
tick();
fixture.detectChanges();
const tbodyRows = debugEl.queryAll(By.directive(DataTableRowComponent));
for (let i = 0; i < tbodyRows.length; i++) {
expect(tbodyRows[i].componentInstance.rowItem.$checked).toBeTruthy();
}
}));
it('should change column order', fakeAsync(() => {
fixture.detectChanges();
component.dataTableOptions.columns[0].order = 5;
fixture.detectChanges();
flush();
const thTitle = debugEl.query(By.css('table th:nth-child(5) span.title span'));
expect(thTitle.nativeElement.textContent).toEqual('#');
}));
it('should set header checkOptions work', fakeAsync(() => {
component.checkable = true;
fixture.detectChanges();
const dropdownElement = debugEl.query(By.css('table .devui-checkable-cell .select-options'));
dropdownElement.nativeElement.dispatchEvent(new MouseEvent('mouseenter', {'bubbles': false, 'cancelable': false}));
fixture.detectChanges();
tick(50); // debounce time
fixture.detectChanges();
tick(); // animation time
fixture.detectChanges();
const dropdownMenuElement = debugEl.query(By.directive(DropDownMenuDirective));
expect(dropdownMenuElement).toBeTruthy();
const items = dropdownMenuElement.nativeElement.querySelectorAll('ul.devui-dropdown-menu li');
items[0].dispatchEvent(new Event('click'));
tick();
fixture.detectChanges();
expect(component.checkTotalData).toHaveBeenCalled();
}));
});
describe('advanced', () => {
let fixture: ComponentFixture<TestDataTableAdvancedColumnComponent>;
let debugEl: DebugElement;
let component: TestDataTableAdvancedColumnComponent;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [DataTableModule, FormsModule, CheckBoxModule, TooltipModule, AvatarModule, NoopAnimationsModule],
declarations: [TestDataTableAdvancedColumnComponent]
});
});
beforeEach(() => {
fixture = TestBed.createComponent(TestDataTableAdvancedColumnComponent);
debugEl = fixture.debugElement;
component = fixture.componentInstance;
});
describe('hideColumn', () => {
it('should data-table hide columns work', () => {
component.hideColumn = [];
fixture.detectChanges();
let thList = debugEl.queryAll(By.css('table th'));
expect(thList.length).toEqual(7);
component.hideColumn = ['hidden', 'gender'];
fixture.detectChanges();
thList = debugEl.queryAll(By.css('table th'));
expect(thList.length).toEqual(5);
});
});
describe('sortable', () => {
it('should sortable data-table created correctly', () => {
fixture.detectChanges();
expect(component).toBeTruthy();
});
it('should sortable can be click', () => {
fixture.detectChanges();
const sortClickEl = debugEl.query(By.css('.devui-table thead tr th:nth-child(4) .sort-clickable'));
let sortIcon = sortClickEl.query(By.css('.datatable-svg.sort-icon-asc'));
expect(sortIcon).toBeTruthy();
sortClickEl.nativeElement.dispatchEvent(new Event('click'));
fixture.detectChanges();
sortIcon = sortClickEl.query(By.css('.datatable-svg.sort-icon-desc'));
expect(sortIcon).toBeTruthy();
sortClickEl.nativeElement.dispatchEvent(new Event('click'));
fixture.detectChanges();
sortIcon = sortClickEl.query(By.css('.datatable-svg.sort-icon-asc'));
expect(sortIcon).toBeNull();
sortIcon = sortClickEl.query(By.css('.datatable-svg.sort-icon-desc'));
expect(sortIcon).toBeNull();
expect(component.multiSortChange).toHaveBeenCalledTimes(2);
sortClickEl.nativeElement.dispatchEvent(new Event('click'));
fixture.detectChanges();
sortIcon = sortClickEl.query(By.css('.datatable-svg.sort-icon-asc'));
expect(sortIcon).toBeTruthy();
});
it('should sortable can be change type', () => {
// multi sort
component.onlyOneColumnSort = false;
fixture.detectChanges();
const sortClickEl = debugEl.query(By.css('.devui-table thead tr th:nth-child(3) .sort-clickable'));
sortClickEl.nativeElement.dispatchEvent(new Event('click'));
fixture.detectChanges();
const sortIcon = debugEl.query(By.css('.devui-table thead tr th:nth-child(4) .sort-clickable .datatable-svg.sort-icon-asc'));
expect(sortIcon).toBeTruthy();
});
});
describe('filterable', () => {
it('should filterable click can work', fakeAsync(() => {
fixture.detectChanges();
let trs = debugEl.queryAll(By.css('table.devui-table tbody tr'));
expect(trs.length).toBe(6);
const filter = debugEl.query(By.css('table.devui-table thead th:nth-child(3) d-table-filter'));
const dropDownDebugEl = filter.query(By.directive(DropDownToggleDirective));
dropDownDebugEl.nativeElement.dispatchEvent(new Event('click'));
tick();
fixture.detectChanges();
const filterDropDownMenu = debugEl.query(By.directive(DropDownMenuDirective));
let filterContent = filterDropDownMenu.query(By.css('.data-table-column-filter-content.filter-bg'));
expect(filterContent).toBeTruthy();
flush();
// select first three should work
let checkBoxes = filterContent.queryAll(By.css('d-checkbox .devui-checkbox.unchecked label'));
for (let i = 1; i < 4; i++) {
checkBoxes[i].nativeElement.dispatchEvent(new Event('click'));
tick();
fixture.detectChanges();
}
let btnOK = filterContent.query(By.css('span.button-style'));
btnOK.nativeElement.dispatchEvent(new Event('click'));
tick();
fixture.detectChanges();
trs = debugEl.queryAll(By.css('table.devui-table tbody tr'));
expect(trs.length).toBe(3);
// select all should work
dropDownDebugEl.nativeElement.dispatchEvent(new Event('click'));
tick();
fixture.detectChanges();
filterContent = filterDropDownMenu.query(By.css('.data-table-column-filter-content.filter-bg'));
expect(filterContent).toBeTruthy();
flush();
checkBoxes = filterContent.queryAll(By.css('d-checkbox .devui-checkbox label'));
checkBoxes[0].nativeElement.dispatchEvent(new Event('click'));
tick();
fixture.detectChanges();
tick();
fixture.detectChanges();
btnOK = filterContent.query(By.css('span.button-style'));
btnOK.nativeElement.dispatchEvent(new Event('click'));
tick();
fixture.detectChanges();
trs = debugEl.queryAll(By.css('table.devui-table tbody tr'));
expect(trs.length).toBe(6);
}));
});
describe('resizable', () => {
beforeEach(() => {
fixture.detectChanges();
});
it('should resize bar appear', () => {
expect(debugEl.query(By.css('.resize-bar'))).toBeFalsy();
const resizeHandleEl = debugEl.query(By.css('table.devui-table thead .resize-handle'));
resizeHandleEl.nativeElement.dispatchEvent(
new MouseEvent('mousedown', {
bubbles: true,
})
);
fixture.detectChanges();
expect(debugEl.query(By.css('.resize-bar'))).toBeTruthy();
});
it('should mouse move can resize the column width', fakeAsync(() => {
let resizeHandleEl = debugEl.query(By.css('table.devui-table thead .resize-handle'));
let idxHeaderCell = debugEl.query(By.css('table.devui-table thead th:nth-child(2)'));
expect(idxHeaderCell.nativeElement.getBoundingClientRect().width).toEqual(50);
const { x, y } = resizeHandleEl.nativeElement.getBoundingClientRect();
resizeHandleEl.nativeElement.dispatchEvent(
new MouseEvent('mousedown', {
bubbles: true,
})
);
fixture.detectChanges();
document.dispatchEvent(createMouseEvent('mousemove', x, y));
document.dispatchEvent(createMouseEvent('mouseup'));
fixture.detectChanges();
tick();
fixture.detectChanges();
// column expand
resizeHandleEl = debugEl.query(By.css('table.devui-table thead .resize-handle'));
let xHandled = resizeHandleEl.nativeElement.getBoundingClientRect().x;
expect(xHandled).toBeCloseTo(2 * x, 0);
idxHeaderCell = debugEl.query(By.css('table.devui-table thead th:nth-child(2)'));
expect(idxHeaderCell.nativeElement.getBoundingClientRect().width).toBeCloseTo(50 + x, 0);
expect(component.resizeEvent).not.toBeNull();
component.resizeEvent = null; // re-initialize
resizeHandleEl.nativeElement.dispatchEvent(
new MouseEvent('mousedown', {
bubbles: true,
})
);
fixture.detectChanges();
document.dispatchEvent(createMouseEvent('mousemove', -x, y));
document.dispatchEvent(createMouseEvent('mouseup'));
fixture.detectChanges();
tick();
fixture.detectChanges();
resizeHandleEl = debugEl.query(By.css('table.devui-table thead .resize-handle'));
xHandled = resizeHandleEl.nativeElement.getBoundingClientRect().x;
expect(xHandled).toEqual(x);
idxHeaderCell = debugEl.query(By.css('table.devui-table thead th:nth-child(2)'));
expect(idxHeaderCell.nativeElement.getBoundingClientRect().width).toEqual(50);
expect(component.resizeEvent).not.toBeNull();
}));
it('should last name can not exceed max width or less than min width', fakeAsync(() => {
let lastNameColumn = debugEl.query(By.css('table.devui-table thead th:nth-child(4)'));
expect(lastNameColumn.nativeElement.getBoundingClientRect().width).toEqual(150);
let resizeElNearByLastNameCol = debugEl.query(By.css('table.devui-table thead th:nth-child(4) .resize-handle'));
const y = resizeElNearByLastNameCol.nativeElement.getBoundingClientRect().y;
resizeElNearByLastNameCol.nativeElement.dispatchEvent(
new MouseEvent('mousedown', {
bubbles: true,
})
);
fixture.detectChanges();
document.dispatchEvent(createMouseEvent('mousemove', 2000, y));
document.dispatchEvent(createMouseEvent('mouseup'));
fixture.detectChanges();
tick();
fixture.detectChanges();
lastNameColumn = debugEl.query(By.css('table.devui-table thead th:nth-child(4)'));
expect(lastNameColumn.nativeElement.getBoundingClientRect().width).toEqual(200);
resizeElNearByLastNameCol = debugEl.query(By.css('table.devui-table thead th:nth-child(4) .resize-handle'));
resizeElNearByLastNameCol.nativeElement.dispatchEvent(
new MouseEvent('mousedown', {
bubbles: true,
})
);
fixture.detectChanges();
document.dispatchEvent(createMouseEvent('mousemove', -2000, y));
document.dispatchEvent(createMouseEvent('mouseup'));
fixture.detectChanges();
tick();
fixture.detectChanges();
lastNameColumn = debugEl.query(By.css('table.devui-table thead th:nth-child(4)'));
expect(lastNameColumn.nativeElement.getBoundingClientRect().width).toEqual(100);
}));
});
describe('click related', () => {
beforeEach(() => {
fixture.detectChanges();
});
it('should cell click work', fakeAsync(() => {
const cellEl = debugEl.query(By.css('.devui-data-table .devui-table tbody tr td:nth-child(2)'));
cellEl.nativeElement.dispatchEvent(new Event('click'));
flush();
expect(component.testCellClickEvent).not.toBeNull();
}));
it('should cell double click work', fakeAsync(() => {
const cellEl = debugEl.query(By.css('.devui-data-table .devui-table tbody tr td:nth-child(2)'));
cellEl.nativeElement.dispatchEvent(new Event('dblclick'));
flush();
expect(component.testCellDbClickEvent).not.toBeNull();
}));
it('should row click work', fakeAsync(() => {
const rowEl = debugEl.query(By.css('.devui-data-table .devui-table tbody tr'));
rowEl.nativeElement.dispatchEvent(new Event('click'));
flush();
expect(component.testRowClickEvent).not.toBeNull();
fixture.detectChanges();
component.testRowClickEvent = null;
// click twice
rowEl.nativeElement.dispatchEvent(new Event('click'));
rowEl.nativeElement.dispatchEvent(new Event('click'));
expect(component.testRowClickEvent).toBeNull();
flush();
}));
it('should row dblclick work', fakeAsync(() => {
const rowEl = debugEl.query(By.css('.devui-data-table .devui-table tbody tr'));
rowEl.nativeElement.dispatchEvent(new Event('dblclick'));
flush();
expect(component.testRowDblClickEvent).not.toBeNull();
}));
});
});
describe('edit', () => {
let fixture: ComponentFixture<TestDataTableColumnEditComponent>;
let debugEl: DebugElement;
let component: TestDataTableColumnEditComponent;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule, DataTableModule, I18nModule, DatepickerModule, InputNumberModule, SelectModule, NoopAnimationsModule],
declarations: [TestDataTableColumnEditComponent]
});
});
beforeEach(() => {
fixture = TestBed.createComponent(TestDataTableColumnEditComponent);
debugEl = fixture.debugElement;
component = fixture.componentInstance;
});
it('should edit input display', fakeAsync(() => {
fixture.detectChanges();
const lastNameEditDebugEl = debugEl.query(By.css('.devui-table tbody tr .cell-editable'));
lastNameEditDebugEl.nativeElement.dispatchEvent(new Event('click'));
fixture.detectChanges();
tick();
fixture.detectChanges();
tick();
fixture.detectChanges();
const inputDebugEl = debugEl.query(By.css('.customized-editor.edit-padding-fix > input'));
expect(inputDebugEl).toBeTruthy();
expect(inputDebugEl.nativeElement.value).toEqual(component.basicDataSource[0]['lastName']);
inputDebugEl.nativeElement.value = 'testLastName';
inputDebugEl.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
// emit global click, finish edit
document.dispatchEvent(new Event('click'));
fixture.detectChanges();
flush();
fixture.detectChanges();
const firstLastNameDebugEl = debugEl.query(By.css('.devui-table tbody tr td'));
expect(firstLastNameDebugEl.nativeElement.textContent).toEqual('testLastName');
}));
it('should edit date work', fakeAsync(() => {
fixture.detectChanges();
let dateColumnDebugEl = debugEl.query(By.css('.devui-table tbody tr td:nth-child(2) .cell-editable'));
let dateText = dateColumnDebugEl.nativeElement.textContent.trim();
expect(dateText.substr(0, 10)).toBe('1991/01/01');
dateColumnDebugEl.nativeElement.dispatchEvent(new Event('click'));
tick();
fixture.detectChanges();
tick();
fixture.detectChanges();
const datePicker = debugEl.query(By.directive(DatepickerComponent));
expect(datePicker).toBeTruthy(); // date picker pop out
const date = datePicker.query(By.css('table.devui-table tbody tr:nth-child(2) td'));
date.nativeElement.dispatchEvent(new Event('click'));
tick();
fixture.detectChanges();
const dateConfirmBtn = datePicker.query(By.css('table.devui-table tfoot button.devui-btn'));
dateConfirmBtn.nativeElement.dispatchEvent(new Event('click'));
tick(); // wait for click event
fixture.detectChanges();
tick(); // wait for date confirm
fixture.detectChanges();
document.dispatchEvent(new Event('click'));
fixture.detectChanges();
flush();
fixture.detectChanges();
dateColumnDebugEl = debugEl.query(By.css('.devui-table tbody tr td:nth-child(2) .cell-editable'));
dateText = dateColumnDebugEl.nativeElement.textContent.trim();
expect(dateText.substr(8, 2)).toBe(date.nativeElement.textContent);
}));
it('should edit input-number work', fakeAsync(() => {
fixture.detectChanges();
tick();
fixture.detectChanges();
let ageColumnDebugEl = debugEl.query(By.css('.devui-table tbody tr td:nth-child(3) .cell-editable'));
let ageText = ageColumnDebugEl.nativeElement.textContent.trim();
expect(ageText).toBe('24');
ageColumnDebugEl.nativeElement.dispatchEvent(new Event('click'));
tick();
fixture.detectChanges();
tick(); // wait for number display
fixture.detectChanges();
const inputNumberDebugEl = debugEl.query(By.directive(InputNumberComponent));
const increaseBtn = inputNumberDebugEl.query(By.css('.input-control-inc'));
increaseBtn.nativeElement.dispatchEvent(new Event('click'));
tick();
fixture.detectChanges();
tick(); // wait for number change
fixture.detectChanges();
document.dispatchEvent(new Event('click'));
flush();
fixture.detectChanges();
ageColumnDebugEl = debugEl.query(By.css('.devui-table tbody tr td:nth-child(3) .cell-editable'));
ageText = ageColumnDebugEl.nativeElement.textContent.trim();
expect(ageText).toBe('25');
}));
it('should scroll cancel edit status', fakeAsync(() => {
fixture.detectChanges();
const lastNameEditDebugEl = debugEl.query(By.css('.devui-table tbody tr .cell-editable'));
lastNameEditDebugEl.nativeElement.dispatchEvent(new Event('click'));
tick();
fixture.detectChanges();
tick();
fixture.detectChanges();
let inputDebugEl = debugEl.query(By.css('.customized-editor.edit-padding-fix > input'));
expect(inputDebugEl).toBeTruthy();
const scrollViewEl = debugEl.query(By.css('.devui-scrollbar.scroll-view'));
scrollViewEl.nativeElement.scrollTop = 2;
scrollViewEl.nativeElement.dispatchEvent(new Event('scroll'));
tick();
fixture.detectChanges();
scrollViewEl.nativeElement.scrollTop = 45;
scrollViewEl.nativeElement.dispatchEvent(new Event('scroll'));
tick();
fixture.detectChanges();
inputDebugEl = debugEl.query(By.css('.customized-editor.edit-padding-fix > input'));
expect(inputDebugEl).toBeFalsy();
}));
});
describe('with children', () => {
let fixture: ComponentFixture<TestDataTableColumnWithChildrenComponent>;
let debugEl: DebugElement;
let component: TestDataTableColumnWithChildrenComponent;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [DataTableModule],
declarations: [TestDataTableColumnWithChildrenComponent]
});
});
beforeEach(() => {
fixture = TestBed.createComponent(TestDataTableColumnWithChildrenComponent);
debugEl = fixture.debugElement;
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create correctly', () => {
expect(component).toBeTruthy();
});
it('should set row child toggle status function work', fakeAsync(() => {
let checkBoxes = debugEl.queryAll(By.css('tbody .devui-checkbox.unchecked'));
let togglers = debugEl.queryAll(By.css('.childtable-toggler'));
let togglersShow = togglers.filter(item => item.nativeElement.style.visibility === 'visible');
expect(checkBoxes.length).toBe(component.basicDataSource.length);
expect(togglersShow.length).toBe(2);
const childTableToggler = debugEl.query(By.css('.devui-data-table table.devui-table tbody tr td .childtable-toggler'));
childTableToggler.nativeElement.dispatchEvent(new Event('click'));
fixture.detectChanges();
tick();
fixture.detectChanges();
checkBoxes = debugEl.queryAll(By.css('tbody .devui-checkbox.unchecked'));
togglers = debugEl.queryAll(By.css('.childtable-toggler'));
togglersShow = togglers.filter(item => item.nativeElement.style.visibility === 'visible');
expect(checkBoxes.length).toBe(component.basicDataSource.length + 2); // 展开的子元素2个
expect(togglersShow.length).toBe(3);
}));
});
describe('fix header', () => {
let fixture: ComponentFixture<TestDataTableColumnFixHeaderComponent>;
let debugEl: DebugElement;
let component: TestDataTableColumnFixHeaderComponent;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [DataTableModule, I18nModule, NoopAnimationsModule],
declarations: [TestDataTableColumnFixHeaderComponent]
});
});
beforeEach(() => {
fixture = TestBed.createComponent(TestDataTableColumnFixHeaderComponent);
debugEl = fixture.debugElement;
component = fixture.componentInstance;
});
it('should create correctly', () => {
fixture.detectChanges();
expect(component).toBeTruthy();
});
it('should scroll work', fakeAsync(() => {
fixture.detectChanges();
tick();
fixture.detectChanges();
const scrollViewEl = debugEl.query(By.css('.devui-scrollbar.scroll-view'));
expect(scrollViewEl).toBeTruthy();
const { top: scrollViewTop } = scrollViewEl.nativeElement.getBoundingClientRect();
let tbodyTrs = debugEl.queryAll(
By.css('.devui-data-table .devui-table-view .devui-scrollbar.scroll-view table.devui-table tbody tr')
);
let { top: tr1Top, height: trHeight } = tbodyTrs[0].nativeElement.getBoundingClientRect();
expect(scrollViewTop).toBe(tr1Top);
// scroll one tr height
scrollViewEl.nativeElement.scrollTop = trHeight;
scrollViewEl.nativeElement.dispatchEvent(new Event('scroll'));
tick();
fixture.detectChanges();
tbodyTrs = debugEl.queryAll(By.css('.devui-data-table .devui-table-view .devui-scrollbar.scroll-view table.devui-table tbody tr'));
({ top: tr1Top, height: trHeight } = tbodyTrs[0].nativeElement.getBoundingClientRect());
expect(Math.round(scrollViewTop - trHeight)).toBe(Math.round(tr1Top));
// scroll two tr height
scrollViewEl.nativeElement.scrollTop = 2 * trHeight;
scrollViewEl.nativeElement.dispatchEvent(new Event('scroll'));
tick();
fixture.detectChanges();
tbodyTrs = debugEl.queryAll(By.css('.devui-data-table .devui-table-view .devui-scrollbar.scroll-view table.devui-table tbody tr'));
({ top: tr1Top } = tbodyTrs[0].nativeElement.getBoundingClientRect());
expect(scrollViewTop - 2 * trHeight).toBeLessThanOrEqual(Math.round(tr1Top)); // touch bottom, maybe tr2 part visible
expect(Math.round(tr1Top)).toBeLessThan(Math.round(scrollViewTop));
}));
it('should resize work', fakeAsync(() => {
component.resizable = true;
fixture.detectChanges();
tick();
fixture.detectChanges();
const thsOfRow1 = debugEl.queryAll(By.css('table.devui-table thead tr:first-child th'));
const resizeBarOfIdx = thsOfRow1[0].query(By.css('.resize-handle'));
const { x: resizeBarX, y: resizeBarY } = resizeBarOfIdx.nativeElement.getBoundingClientRect();
const idxWidth = thsOfRow1[0].nativeElement.getBoundingClientRect().width;
const mouseDownEvt = createMouseEvent('mousedown', resizeBarX, resizeBarY);
resizeBarOfIdx.nativeElement.dispatchEvent(mouseDownEvt);
fixture.detectChanges();
const mouseMoveEvt = createMouseEvent('mousemove', resizeBarX + 10, resizeBarY);
document.dispatchEvent(mouseMoveEvt);
flush();
fixture.detectChanges();
document.dispatchEvent(createMouseEvent('mouseup', resizeBarX + 10, resizeBarY));
flush();
fixture.detectChanges();
const idxEl = debugEl.queryAll(By.css('table.devui-table thead tr:first-child th'))[0];
const idxElWidth = idxEl.nativeElement.getBoundingClientRect().width;
expect(idxWidth).toBeLessThan(idxElWidth);
}));
});
describe('multi header', () => {
let fixture: ComponentFixture<TestDataTableColumnMultiHeaderComponent>;
let debugEl: DebugElement;
let component: TestDataTableColumnMultiHeaderComponent;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [DataTableModule, I18nModule, NoopAnimationsModule],
declarations: [TestDataTableColumnMultiHeaderComponent]
});
});
beforeEach(() => {
fixture = TestBed.createComponent(TestDataTableColumnMultiHeaderComponent);
debugEl = fixture.debugElement;
component = fixture.componentInstance;
});
it('should create correctly', () => {
fixture.detectChanges();
expect(component).toBeTruthy();
});
it('should have multi header', () => {
fixture.detectChanges();
const thsOfRow1 = debugEl.queryAll(By.css('table.devui-table thead tr:first-child th'));
expect(thsOfRow1[0].nativeElement.getBoundingClientRect().height).toBe(thsOfRow1[1].nativeElement.getBoundingClientRect().height);
expect(thsOfRow1[1].nativeElement.getBoundingClientRect().height).toBe(thsOfRow1[3].nativeElement.getBoundingClientRect().height);
expect(Math.round(thsOfRow1[0].nativeElement.getBoundingClientRect().height)).toBe(
Math.round(thsOfRow1[2].nativeElement.getBoundingClientRect().height * 2)
);
const thsOfRow2 = debugEl.queryAll(By.css('table.devui-table thead tr:last-child th'));
const firstNameWidth = thsOfRow2[0].nativeElement.getBoundingClientRect().width;
const lastNameWidth = thsOfRow2[1].nativeElement.getBoundingClientRect().width;
const nameWidth = thsOfRow1[2].nativeElement.getBoundingClientRect().width;
expect(Math.round(firstNameWidth + lastNameWidth)).toBe(Math.round(nameWidth));
});
it('should multi header normal header can be resize', fakeAsync(() => {
component.resizable = true;
fixture.detectChanges();
tick();
fixture.detectChanges();
const thsOfRow1 = debugEl.queryAll(By.css('table.devui-table thead tr:first-child th'));
const resizeBarOfIdx = thsOfRow1[0].query(By.css('.resize-handle'));
const { x: resizeBarX, y: resizeBarY } = resizeBarOfIdx.nativeElement.getBoundingClientRect();
const idxWidth = thsOfRow1[0].nativeElement.getBoundingClientRect().width;
const mouseDownEvt = createMouseEvent('mousedown', resizeBarX, resizeBarY);
resizeBarOfIdx.nativeElement.dispatchEvent(mouseDownEvt);
fixture.detectChanges();
const mouseMoveEvt = createMouseEvent('mousemove', resizeBarX + 10, resizeBarY);
document.dispatchEvent(mouseMoveEvt);
flush();
fixture.detectChanges();
document.dispatchEvent(createMouseEvent('mouseup', resizeBarX + 10, resizeBarY));
flush();
fixture.detectChanges();
const idxEl = debugEl.queryAll(By.css('table.devui-table thead tr:first-child th'))[0];
const idxElWidth = idxEl.nativeElement.getBoundingClientRect().width;
expect(idxWidth).toBeLessThan(idxElWidth);
}));
it('should advanced headers parent is resizable', fakeAsync(() => {
component.resizable = true;
fixture.detectChanges();
tick();
fixture.detectChanges();
let nameEl = debugEl.queryAll(By.css('table.devui-table thead tr:first-child th'))[2].nativeElement;
const nameElWidth = nameEl.getBoundingClientRect().width;
const lastNameColumnDebugEl = debugEl.queryAll(By.css('table.devui-table thead tr:last-child th'))[1];
const lastNameResizeBar = lastNameColumnDebugEl.query(By.css('.resize-handle'));
const { x: resizeBarX, y: resizeBarY } = lastNameResizeBar.nativeElement.getBoundingClientRect();
const mouseDownEvt = createMouseEvent('mousedown', resizeBarX, resizeBarY);
lastNameResizeBar.nativeElement.dispatchEvent(mouseDownEvt);
fixture.detectChanges();
const mouseMoveEvt = createMouseEvent('mousemove', resizeBarX + 40, resizeBarY);
document.dispatchEvent(mouseMoveEvt);
flush();
fixture.detectChanges();
document.dispatchEvent(createMouseEvent('mouseup', resizeBarX + 40, resizeBarY));
flush();
fixture.detectChanges();
nameEl = debugEl.queryAll(By.css('table.devui-table thead tr:first-child th'))[2].nativeElement;
const nameElResizeWidth = nameEl.getBoundingClientRect().width;
expect(nameElWidth).toBeLessThan(nameElResizeWidth);
}));
it('should drag column work', fakeAsync(() => {
component.colDraggable = true;
fixture.detectChanges();
tick();
fixture.detectChanges();
const headerDebugEl = debugEl.query(By.directive(DataTableHeadComponent));
const dragIcon = headerDebugEl.query(By.css('th.sindu_handle.operable .header-container .drag-icon'));
expect(dragIcon).toBeTruthy();
}));
});
describe('drag header', () => {
let fixture: ComponentFixture<TestDataTableColumnDragComponent>;
let debugEl: DebugElement;
let component: TestDataTableColumnDragComponent;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [DataTableModule, NoopAnimationsModule],
declarations: [TestDataTableColumnDragComponent]
});
});
beforeEach(() => {
fixture = TestBed.createComponent(TestDataTableColumnDragComponent);
debugEl = fixture.debugElement;
component = fixture.componentInstance;
});
it('should create correctly', () => {
fixture.detectChanges();
expect(component).toBeTruthy();
});
it('should header can be drag', fakeAsync(() => {
fixture.detectChanges();
headerDrag(fixture);
}));
it('should fixed header can be drag', fakeAsync(() => {
component.isHeaderFixed = true;
fixture.detectChanges();
tick();
fixture.detectChanges();
headerDrag(fixture);
}));
});
describe('expand detail', () => {
let fixture: ComponentFixture<TestDataTableExpandComponent>;
let debugEl: DebugElement;
let component: TestDataTableExpandComponent;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [DataTableModule, NoopAnimationsModule, FormsModule],
declarations: [TestDataTableExpandComponent],
});
});
beforeEach(() => {
fixture = TestBed.createComponent(TestDataTableExpandComponent);
debugEl = fixture.debugElement;
component = fixture.componentInstance;
});
it('should create correctly', () => {
fixture.detectChanges();
const detailCell = debugEl.query(By.css('table.devui-table tbody tr td.devui-detail-cell'));
expect(detailCell).toBeTruthy();
});
it('should show detail when click icon', fakeAsync(() => {
fixture.detectChanges();
const detailCell = debugEl.query(By.css('table.devui-table tbody tr td.devui-detail-cell div'));
detailCell.nativeElement.dispatchEvent(new Event('click'));
tick();
fixture.detectChanges();
expect(component.toggleChange).toHaveBeenCalled();
const svgIcon = detailCell.nativeElement.querySelector('svg');
expect(svgIcon).toBeTruthy();
// test other detail row
fixture.detectChanges();
const detailCell2 = debugEl.query(By.css('table.devui-table tbody tr:nth-child(3) td.devui-detail-cell div'));
detailCell2.nativeElement.dispatchEvent(new Event('click'));
tick();
fixture.detectChanges();
expect(component.toggleChange).toHaveBeenCalled();
}));
});
});
function headerDrag(fixture: ComponentFixture<TestDataTableColumnDragComponent>) {
const debugEl = fixture.debugElement;
let dHeaderCells = debugEl.queryAll(By.css('.devui-data-table table.devui-table thead tr th'));
expect(dHeaderCells[1].nativeElement.textContent).toContain('First Name');
expect(dHeaderCells[2].nativeElement.textContent).toContain('Last Name');
const columnFirstNameDragIcon = dHeaderCells[1].query(By.css('.drag-icon'));
columnFirstNameDragIcon.nativeElement.style.visibility = 'visible';
const { x: fromX, y: fromY } = columnFirstNameDragIcon.nativeElement.getBoundingClientRect();
const { x: moveToX, y: moveToY, width, height } = dHeaderCells[2].nativeElement.getBoundingClientRect();
const mouseDownEvt = createMouseEvent('mousedown', fromX, fromY);
const mouseMoveEvt = createMouseEvent('mousemove', moveToX + width, moveToY + height / 2);
const mouseUpEvt = createMouseEvent('mouseup');
columnFirstNameDragIcon.nativeElement.dispatchEvent(mouseDownEvt);
tick(); // emit onTap, setTimeout: wait for mousemove & mouseup addEventListener
document.documentElement.dispatchEvent(mouseMoveEvt); // emit handleMouseMove, add event listener to grab
tick();
document.documentElement.dispatchEvent(mouseDownEvt); // emit grab
tick(); // add event listener mouse move
document.documentElement.dispatchEvent(mouseMoveEvt); // emit startBecauseMouseMoved
tick();
document.documentElement.dispatchEvent(mouseMoveEvt); // emit drag
tick();
document.documentElement.dispatchEvent(mouseUpEvt); // emit release
flush();
fixture.detectChanges();
dHeaderCells = debugEl.queryAll(By.css('.devui-data-table table.devui-table thead tr th'));
expect(dHeaderCells[1].nativeElement.textContent).toContain('Last Name');
expect(dHeaderCells[2].nativeElement.textContent).toContain('First Name');
} | the_stack |
// ***********************************************************
// This file is generated by the Angular build process.
// Please do not create manual edits or send pull requests
// modifying this file.
// ***********************************************************
// Angular depends transitively on these libraries.
// If you don't have them installed you can run
// $ tsd query es6-promise rx rx-lite --action install --save
///<reference path="../es6-promise/es6-promise.d.ts"/>
///<reference path="../rx/rx.d.ts"/>
interface List<T> extends Array<T> {}
interface Map<K,V> {}
interface StringMap<K,V> extends Map<K,V> {}
declare module ng {
// See https://github.com/Microsoft/TypeScript/issues/1168
class BaseException /* extends Error */ {
message: string;
stack: string;
toString(): string;
}
interface InjectableReference {}
}
/**
* The `angular2` is the single place to import all of the individual types.
*/
declare module ng {
/**
* Bootstrapping for Angular applications.
*
* You instantiate an Angular application by explicitly specifying a component to use as the root
* component for your
* application via the `bootstrap()` method.
*
* ## Simple Example
*
* Assuming this `index.html`:
*
* ```html
* <html>
* <!-- load Angular script tags here. -->
* <body>
* <my-app>loading...</my-app>
* </body>
* </html>
* ```
*
* An application is bootstrapped inside an existing browser DOM, typically `index.html`. Unlike
* Angular 1, Angular 2
* does not compile/process bindings in `index.html`. This is mainly for security reasons, as well
* as architectural
* changes in Angular 2. This means that `index.html` can safely be processed using server-side
* technologies such as
* bindings. Bindings can thus use double-curly `{{ syntax }}` without collision from Angular 2
* component double-curly
* `{{ syntax }}`.
*
* We can use this script code:
*
* ```
* @Component({
* selector: 'my-app'
* })
* @View({
* template: 'Hello {{ name }}!'
* })
* class MyApp {
* name:string;
*
* constructor() {
* this.name = 'World';
* }
* }
*
* main() {
* return bootstrap(MyApp);
* }
* ```
*
* When the app developer invokes `bootstrap()` with the root component `MyApp` as its argument,
* Angular performs the
* following tasks:
*
* 1. It uses the component's `selector` property to locate the DOM element which needs to be
* upgraded into
* the angular component.
* 2. It creates a new child injector (from the platform injector). Optionally, you can also
* override the injector configuration for an app by
* invoking `bootstrap` with the `componentInjectableBindings` argument.
* 3. It creates a new `Zone` and connects it to the angular application's change detection domain
* instance.
* 4. It creates a shadow DOM on the selected component's host element and loads the template into
* it.
* 5. It instantiates the specified component.
* 6. Finally, Angular performs change detection to apply the initial data bindings for the
* application.
*
*
* ## Instantiating Multiple Applications on a Single Page
*
* There are two ways to do this.
*
*
* ### Isolated Applications
*
* Angular creates a new application each time that the `bootstrap()` method is invoked. When
* multiple applications
* are created for a page, Angular treats each application as independent within an isolated change
* detection and
* `Zone` domain. If you need to share data between applications, use the strategy described in the
* next
* section, "Applications That Share Change Detection."
*
*
* ### Applications That Share Change Detection
*
* If you need to bootstrap multiple applications that share common data, the applications must
* share a common
* change detection and zone. To do that, create a meta-component that lists the application
* components in its template.
* By only invoking the `bootstrap()` method once, with the meta-component as its argument, you
* ensure that only a
* single change detection zone is created and therefore data can be shared across the applications.
*
*
* ## Platform Injector
*
* When working within a browser window, there are many singleton resources: cookies, title,
* location, and others.
* Angular services that represent these resources must likewise be shared across all Angular
* applications that
* occupy the same browser window. For this reason, Angular creates exactly one global platform
* injector which stores
* all shared services, and each angular application injector has the platform injector as its
* parent.
*
* Each application has its own private injector as well. When there are multiple applications on a
* page, Angular treats
* each application injector's services as private to that application.
*
*
* # API
* - `appComponentType`: The root component which should act as the application. This is a reference
* to a `Type`
* which is annotated with `@Component(...)`.
* - `componentInjectableBindings`: An additional set of bindings that can be added to the app
* injector
* to override default injection behavior.
* - `errorReporter`: `function(exception:any, stackTrace:string)` a default error reporter for
* unhandled exceptions.
*
* Returns a `Promise` of {@link ApplicationRef}.
*/
function bootstrap(appComponentType: /*Type*/ any, componentInjectableBindings?: List<Type | Binding | List<any>>) : Promise<ApplicationRef> ;
/**
* Declare reusable UI building blocks for an application.
*
* Each Angular component requires a single `@Component` and at least one `@View` annotation. The
* `@Component`
* annotation specifies when a component is instantiated, and which properties and hostListeners it
* binds to.
*
* When a component is instantiated, Angular
* - creates a shadow DOM for the component.
* - loads the selected template into the shadow DOM.
* - creates all the injectable objects configured with `bindings` and `viewBindings`.
*
* All template expressions and statements are then evaluated against the component instance.
*
* For details on the `@View` annotation, see {@link View}.
*
* ## Example
*
* ```
* @Component({
* selector: 'greet'
* })
* @View({
* template: 'Hello {{name}}!'
* })
* class Greet {
* name: string;
*
* constructor() {
* this.name = 'World';
* }
* }
* ```
*/
class ComponentAnnotation extends DirectiveAnnotation {
/**
* Defines the used change detection strategy.
*
* When a component is instantiated, Angular creates a change detector, which is responsible for
* propagating
* the component's bindings.
*
* The `changeDetection` property defines, whether the change detection will be checked every time
* or only when the component
* tells it to do so.
*/
changeDetection: string;
/**
* Defines the set of injectable objects that are visible to its view dom children.
*
* ## Simple Example
*
* Here is an example of a class that can be injected:
*
* ```
* class Greeter {
* greet(name:string) {
* return 'Hello ' + name + '!';
* }
* }
*
* @Directive({
* selector: 'needs-greeter'
* })
* class NeedsGreeter {
* greeter:Greeter;
*
* constructor(greeter:Greeter) {
* this.greeter = greeter;
* }
* }
*
* @Component({
* selector: 'greet',
* viewBindings: [
* Greeter
* ]
* })
* @View({
* template: `<needs-greeter></needs-greeter>`,
* directives: [NeedsGreeter]
* })
* class HelloWorld {
* }
*
* ```
*/
viewBindings: List<any>;
}
/**
* Directives allow you to attach behavior to elements in the DOM.
*
* {@link Directive}s with an embedded view are called {@link Component}s.
*
* A directive consists of a single directive annotation and a controller class. When the
* directive's `selector` matches
* elements in the DOM, the following steps occur:
*
* 1. For each directive, the `ElementInjector` attempts to resolve the directive's constructor
* arguments.
* 2. Angular instantiates directives for each matched element using `ElementInjector` in a
* depth-first order,
* as declared in the HTML.
*
* ## Understanding How Injection Works
*
* There are three stages of injection resolution.
* - *Pre-existing Injectors*:
* - The terminal {@link Injector} cannot resolve dependencies. It either throws an error or, if
* the dependency was
* specified as `@Optional`, returns `null`.
* - The platform injector resolves browser singleton resources, such as: cookies, title,
* location, and others.
* - *Component Injectors*: Each component instance has its own {@link Injector}, and they follow
* the same parent-child hierarchy
* as the component instances in the DOM.
* - *Element Injectors*: Each component instance has a Shadow DOM. Within the Shadow DOM each
* element has an `ElementInjector`
* which follow the same parent-child hierarchy as the DOM elements themselves.
*
* When a template is instantiated, it also must instantiate the corresponding directives in a
* depth-first order. The
* current `ElementInjector` resolves the constructor dependencies for each directive.
*
* Angular then resolves dependencies as follows, according to the order in which they appear in the
* {@link View}:
*
* 1. Dependencies on the current element
* 2. Dependencies on element injectors and their parents until it encounters a Shadow DOM boundary
* 3. Dependencies on component injectors and their parents until it encounters the root component
* 4. Dependencies on pre-existing injectors
*
*
* The `ElementInjector` can inject other directives, element-specific special objects, or it can
* delegate to the parent
* injector.
*
* To inject other directives, declare the constructor parameter as:
* - `directive:DirectiveType`: a directive on the current element only
* - `@Host() directive:DirectiveType`: any directive that matches the type between the current
* element and the
* Shadow DOM root.
* - `@Query(DirectiveType) query:QueryList<DirectiveType>`: A live collection of direct child
* directives.
* - `@QueryDescendants(DirectiveType) query:QueryList<DirectiveType>`: A live collection of any
* child directives.
*
* To inject element-specific special objects, declare the constructor parameter as:
* - `element: ElementRef` to obtain a reference to logical element in the view.
* - `viewContainer: ViewContainerRef` to control child template instantiation, for
* {@link Directive} directives only
* - `bindingPropagation: BindingPropagation` to control change detection in a more granular way.
*
* ## Example
*
* The following example demonstrates how dependency injection resolves constructor arguments in
* practice.
*
*
* Assume this HTML template:
*
* ```
* <div dependency="1">
* <div dependency="2">
* <div dependency="3" my-directive>
* <div dependency="4">
* <div dependency="5"></div>
* </div>
* <div dependency="6"></div>
* </div>
* </div>
* </div>
* ```
*
* With the following `dependency` decorator and `SomeService` injectable class.
*
* ```
* @Injectable()
* class SomeService {
* }
*
* @Directive({
* selector: '[dependency]',
* properties: [
* 'id: dependency'
* ]
* })
* class Dependency {
* id:string;
* }
* ```
*
* Let's step through the different ways in which `MyDirective` could be declared...
*
*
* ### No injection
*
* Here the constructor is declared with no arguments, therefore nothing is injected into
* `MyDirective`.
*
* ```
* @Directive({ selector: '[my-directive]' })
* class MyDirective {
* constructor() {
* }
* }
* ```
*
* This directive would be instantiated with no dependencies.
*
*
* ### Component-level injection
*
* Directives can inject any injectable instance from the closest component injector or any of its
* parents.
*
* Here, the constructor declares a parameter, `someService`, and injects the `SomeService` type
* from the parent
* component's injector.
* ```
* @Directive({ selector: '[my-directive]' })
* class MyDirective {
* constructor(someService: SomeService) {
* }
* }
* ```
*
* This directive would be instantiated with a dependency on `SomeService`.
*
*
* ### Injecting a directive from the current element
*
* Directives can inject other directives declared on the current element.
*
* ```
* @Directive({ selector: '[my-directive]' })
* class MyDirective {
* constructor(dependency: Dependency) {
* expect(dependency.id).toEqual(3);
* }
* }
* ```
* This directive would be instantiated with `Dependency` declared at the same element, in this case
* `dependency="3"`.
*
* ### Injecting a directive from any ancestor elements
*
* Directives can inject other directives declared on any ancestor element (in the current Shadow
* DOM), i.e. on the current element, the
* parent element, or its parents.
* ```
* @Directive({ selector: '[my-directive]' })
* class MyDirective {
* constructor(@Host() dependency: Dependency) {
* expect(dependency.id).toEqual(2);
* }
* }
* ```
*
* `@Host` checks the current element, the parent, as well as its parents recursively. If
* `dependency="2"` didn't
* exist on the direct parent, this injection would
* have returned
* `dependency="1"`.
*
*
* ### Injecting a live collection of direct child directives
*
*
* A directive can also query for other child directives. Since parent directives are instantiated
* before child directives, a directive can't simply inject the list of child directives. Instead,
* the directive injects a {@link QueryList}, which updates its contents as children are added,
* removed, or moved by a directive that uses a {@link ViewContainerRef} such as a `ng-for`, an
* `ng-if`, or an `ng-switch`.
*
* ```
* @Directive({ selector: '[my-directive]' })
* class MyDirective {
* constructor(@Query(Dependency) dependencies:QueryList<Dependency>) {
* }
* }
* ```
*
* This directive would be instantiated with a {@link QueryList} which contains `Dependency` 4 and
* 6. Here, `Dependency` 5 would not be included, because it is not a direct child.
*
* ### Injecting a live collection of descendant directives
*
* By passing the descendant flag to `@Query` above, we can include the children of the child
* elements.
*
* ```
* @Directive({ selector: '[my-directive]' })
* class MyDirective {
* constructor(@Query(Dependency, {descendants: true}) dependencies:QueryList<Dependency>) {
* }
* }
* ```
*
* This directive would be instantiated with a Query which would contain `Dependency` 4, 5 and 6.
*
* ### Optional injection
*
* The normal behavior of directives is to return an error when a specified dependency cannot be
* resolved. If you
* would like to inject `null` on unresolved dependency instead, you can annotate that dependency
* with `@Optional()`.
* This explicitly permits the author of a template to treat some of the surrounding directives as
* optional.
*
* ```
* @Directive({ selector: '[my-directive]' })
* class MyDirective {
* constructor(@Optional() dependency:Dependency) {
* }
* }
* ```
*
* This directive would be instantiated with a `Dependency` directive found on the current element.
* If none can be
* found, the injector supplies `null` instead of throwing an error.
*
* ## Example
*
* Here we use a decorator directive to simply define basic tool-tip behavior.
*
* ```
* @Directive({
* selector: '[tooltip]',
* properties: [
* 'text: tooltip'
* ],
* hostListeners: {
* 'onmouseenter': 'onMouseEnter()',
* 'onmouseleave': 'onMouseLeave()'
* }
* })
* class Tooltip{
* text:string;
* overlay:Overlay; // NOT YET IMPLEMENTED
* overlayManager:OverlayManager; // NOT YET IMPLEMENTED
*
* constructor(overlayManager:OverlayManager) {
* this.overlay = overlay;
* }
*
* onMouseEnter() {
* // exact signature to be determined
* this.overlay = this.overlayManager.open(text, ...);
* }
*
* onMouseLeave() {
* this.overlay.close();
* this.overlay = null;
* }
* }
* ```
* In our HTML template, we can then add this behavior to a `<div>` or any other element with the
* `tooltip` selector,
* like so:
*
* ```
* <div tooltip="some text here"></div>
* ```
*
* Directives can also control the instantiation, destruction, and positioning of inline template
* elements:
*
* A directive uses a {@link ViewContainerRef} to instantiate, insert, move, and destroy views at
* runtime.
* The {@link ViewContainerRef} is created as a result of `<template>` element, and represents a
* location in the current view
* where these actions are performed.
*
* Views are always created as children of the current {@link View}, and as siblings of the
* `<template>` element. Thus a
* directive in a child view cannot inject the directive that created it.
*
* Since directives that create views via ViewContainers are common in Angular, and using the full
* `<template>` element syntax is wordy, Angular
* also supports a shorthand notation: `<li *foo="bar">` and `<li template="foo: bar">` are
* equivalent.
*
* Thus,
*
* ```
* <ul>
* <li *foo="bar" title="text"></li>
* </ul>
* ```
*
* Expands in use to:
*
* ```
* <ul>
* <template [foo]="bar">
* <li title="text"></li>
* </template>
* </ul>
* ```
*
* Notice that although the shorthand places `*foo="bar"` within the `<li>` element, the binding for
* the directive
* controller is correctly instantiated on the `<template>` element rather than the `<li>` element.
*
*
* ## Example
*
* Let's suppose we want to implement the `unless` behavior, to conditionally include a template.
*
* Here is a simple directive that triggers on an `unless` selector:
*
* ```
* @Directive({
* selector: '[unless]',
* properties: ['unless']
* })
* export class Unless {
* viewContainer: ViewContainerRef;
* templateRef: TemplateRef;
* prevCondition: boolean;
*
* constructor(viewContainer: ViewContainerRef, templateRef: TemplateRef) {
* this.viewContainer = viewContainer;
* this.templateRef = templateRef;
* this.prevCondition = null;
* }
*
* set unless(newCondition) {
* if (newCondition && (isBlank(this.prevCondition) || !this.prevCondition)) {
* this.prevCondition = true;
* this.viewContainer.clear();
* } else if (!newCondition && (isBlank(this.prevCondition) || this.prevCondition)) {
* this.prevCondition = false;
* this.viewContainer.create(this.templateRef);
* }
* }
* }
* ```
*
* We can then use this `unless` selector in a template:
* ```
* <ul>
* <li *unless="expr"></li>
* </ul>
* ```
*
* Once the directive instantiates the child view, the shorthand notation for the template expands
* and the result is:
*
* ```
* <ul>
* <template [unless]="exp">
* <li></li>
* </template>
* <li></li>
* </ul>
* ```
*
* Note also that although the `<li></li>` template still exists inside the `<template></template>`,
* the instantiated
* view occurs on the second `<li></li>` which is a sibling to the `<template>` element.
*/
class DirectiveAnnotation extends InjectableMetadata {
/**
* The CSS selector that triggers the instantiation of a directive.
*
* Angular only allows directives to trigger on CSS selectors that do not cross element
* boundaries.
*
* `selector` may be declared as one of the following:
*
* - `element-name`: select by element name.
* - `.class`: select by class name.
* - `[attribute]`: select by attribute name.
* - `[attribute=value]`: select by attribute name and value.
* - `:not(sub_selector)`: select only if the element does not match the `sub_selector`.
* - `selector1, selector2`: select if either `selector1` or `selector2` matches.
*
*
* ## Example
*
* Suppose we have a directive with an `input[type=text]` selector.
*
* And the following HTML:
*
* ```html
* <form>
* <input type="text">
* <input type="radio">
* <form>
* ```
*
* The directive would only be instantiated on the `<input type="text">` element.
*/
selector: string;
/**
* Enumerates the set of properties that accept data binding for a directive.
*
* The `properties` property defines a set of `directiveProperty` to `bindingProperty`
* configuration:
*
* - `directiveProperty` specifies the component property where the value is written.
* - `bindingProperty` specifies the DOM property where the value is read from.
*
* You can include a {@link Pipe} when specifying a `bindingProperty` to allow for data
* transformation and structural change detection of the value. These pipes will be evaluated in
* the context of this component.
*
* ## Syntax
*
* There is no need to specify both `directiveProperty` and `bindingProperty` when they both have
* the same value.
*
* ```
* @Directive({
* properties: [
* 'propertyName', // shorthand notation for 'propertyName: propertyName'
* 'directiveProperty1: bindingProperty1',
* 'directiveProperty2: bindingProperty2 | pipe1 | ...',
* ...
* ]
* }
* ```
*
*
* ## Basic Property Binding
*
* We can easily build a simple `Tooltip` directive that exposes a `tooltip` property, which can
* be used in templates with standard Angular syntax. For example:
*
* ```
* @Directive({
* selector: '[tooltip]',
* properties: [
* 'text: tooltip'
* ]
* })
* class Tooltip {
* set text(value: string) {
* // This will get called every time with the new value when the 'tooltip' property changes
* }
* }
* ```
*
* We can then bind to the `tooltip' property as either an expression (`someExpression`) or as a
* string literal, as shown in the HTML template below:
*
* ```html
* <div [tooltip]="someExpression">...</div>
* <div tooltip="Some Text">...</div>
* ```
*
* Whenever the `someExpression` expression changes, the `properties` declaration instructs
* Angular to update the `Tooltip`'s `text` property.
*
* ## Bindings With Pipes
*
* You can also use pipes when writing binding definitions for a directive.
*
* For example, we could write a binding that updates the directive on structural changes, rather
* than on reference changes, as normally occurs in change detection.
*
* See {@link Pipe} and {@link KeyValueChanges} documentation for more details.
*
* ```
* @Directive({
* selector: '[class-set]',
* properties: [
* 'classChanges: classSet | keyValDiff'
* ]
* })
* class ClassSet {
* set classChanges(changes: KeyValueChanges) {
* // This will get called every time the `class-set` expressions changes its structure.
* }
* }
* ```
*
* The template that this directive is used in may also contain its own pipes. For example:
*
* ```html
* <div [class-set]="someExpression | somePipe">
* ```
*
* In this case, the two pipes compose as if they were inlined: `someExpression | somePipe |
* keyValDiff`.
*/
properties: List<string>;
/**
* Enumerates the set of emitted events.
*
* ## Syntax
*
* ```
* @Component({
* events: ['statusChange']
* })
* class TaskComponent {
* statusChange: EventEmitter;
*
* constructor() {
* this.statusChange = new EventEmitter();
* }
*
* onComplete() {
* this.statusChange.next('completed');
* }
* }
* ```
*
* Use `propertyName: eventName` when the event emitter property name is different from the name
* of the emitted event:
*
* ```
* @Component({
* events: ['status: statusChange']
* })
* class TaskComponent {
* status: EventEmitter;
*
* constructor() {
* this.status = new EventEmitter();
* }
*
* onComplete() {
* this.status.next('completed');
* }
* }
* ```
*/
events: List<string>;
/**
* Specifiy the events, actions, properties and attributes related to the host element.
*
* ## Events
*
* Specifies which DOM hostListeners a directive listens to via a set of `(event)` to `method`
* key-value pairs:
*
* - `event1`: the DOM event that the directive listens to.
* - `statement`: the statement to execute when the event occurs.
* If the evalutation of the statement returns `false`, then `preventDefault`is applied on the DOM
* event.
*
* To listen to global events, a target must be added to the event name.
* The target can be `window`, `document` or `body`.
*
* When writing a directive event binding, you can also refer to the following local variables:
* - `$event`: Current event object which triggered the event.
* - `$target`: The source of the event. This will be either a DOM element or an Angular
* directive. (will be implemented in later release)
*
* ## Syntax
*
* ```
* @Directive({
* host: {
* '(event1)': 'onMethod1(arguments)',
* '(target:event2)': 'onMethod2(arguments)',
* ...
* }
* }
* ```
*
* ## Basic Event Binding:
*
* Suppose you want to write a directive that reacts to `change` events in the DOM and on
* `resize` events in window.
* You would define the event binding as follows:
*
* ```
* @Directive({
* selector: 'input',
* host: {
* '(change)': 'onChange($event)',
* '(window:resize)': 'onResize($event)'
* }
* })
* class InputDirective {
* onChange(event:Event) {
* // invoked when the input element fires the 'change' event
* }
* onResize(event:Event) {
* // invoked when the window fires the 'resize' event
* }
* }
* ```
*
* ## Properties
*
* Specifies which DOM properties a directives updates.
*
* ## Syntax
*
* ```
* @Directive({
* selector: 'input',
* host: {
* '[prop]': 'expression'
* }
* })
* class InputDirective {
* value:string;
* }
* ```
*
* In this example the prop property of the host element is updated with the expression value
* every time it changes.
*
* ## Attributes
*
* Specifies static attributes that should be propagated to a host element. Attributes specified
* in `hostAttributes` are propagated only if a given attribute is not present on a host element.
*
* ## Syntax
*
* ```
* @Directive({
* selector: '[my-button]',
* host: {
* 'role': 'button'
* }
* })
* class MyButton {
* }
* ```
*
* In this example using `my-button` directive (ex.: `<div my-button></div>`) on a host element
* (here: `<div>` ) will ensure that this element will get the "button" role.
*
* ## Actions
*
* Specifies which DOM methods a directive can invoke.
*
* ## Syntax
*
* ```
* @Directive({
* selector: 'input',
* host: {
* '@emitFocus': 'focus()'
* }
* })
* class InputDirective {
* constructor() {
* this.emitFocus = new EventEmitter();
* }
*
* focus() {
* this.emitFocus.next();
* }
* }
* ```
*
* In this example calling focus on InputDirective will result in calling focus on the input.
*/
host: StringMap<string, string>;
/**
* Specifies which lifecycle should be notified to the directive.
*
* See {@link LifecycleEvent} for details.
*/
lifecycle: List<LifecycleEvent>;
/**
* If set to false the compiler does not compile the children of this directive.
*/
compileChildren: boolean;
/**
* Defines the set of injectable objects that are visible to a Directive and its light dom
* children.
*
* ## Simple Example
*
* Here is an example of a class that can be injected:
*
* ```
* class Greeter {
* greet(name:string) {
* return 'Hello ' + name + '!';
* }
* }
*
* @Directive({
* selector: 'greet',
* bindings: [
* Greeter
* ]
* })
* class HelloWorld {
* greeter:Greeter;
*
* constructor(greeter:Greeter) {
* this.greeter = greeter;
* }
* }
* ```
*/
bindings: List<any>;
/**
* Defines the name that can be used in the template to assign this directive to a variable.
*
* ## Simple Example
*
* ```
* @Directive({
* selector: 'child-dir',
* exportAs: 'child'
* })
* class ChildDir {
* }
*
* @Component({
* selector: 'main',
* })
* @View({
* template: `<child-dir #c="child"></child-dir>`,
* directives: [ChildDir]
* })
* class MainComponent {
* }
*
* ```
*/
exportAs: string;
}
/**
* Lifecycle events are guaranteed to be called in the following order:
* - `onChange` (optional if any bindings have changed),
* - `onInit` (optional after the first check only),
* - `onCheck`,
* - `onAllChangesDone`
*/
enum LifecycleEvent {
onDestroy,
onChange,
onCheck,
onInit,
onAllChangesDone
}
/**
* Declares the available HTML templates for an application.
*
* Each angular component requires a single `@Component` and at least one `@View` annotation. The
* `@View` annotation specifies the HTML template to use, and lists the directives that are active
* within the template.
*
* When a component is instantiated, the template is loaded into the component's shadow root, and
* the expressions and statements in the template are evaluated against the component.
*
* For details on the `@Component` annotation, see {@link Component}.
*
* ## Example
*
* ```
* @Component({
* selector: 'greet'
* })
* @View({
* template: 'Hello {{name}}!',
* directives: [GreetUser, Bold]
* })
* class Greet {
* name: string;
*
* constructor() {
* this.name = 'World';
* }
* }
* ```
*/
class ViewAnnotation {
/**
* Specifies a template URL for an angular component.
*
* NOTE: either `templateUrl` or `template` should be used, but not both.
*/
templateUrl: string;
/**
* Specifies an inline template for an angular component.
*
* NOTE: either `templateUrl` or `template` should be used, but not both.
*/
template: string;
/**
* Specifies stylesheet URLs for an angular component.
*/
styleUrls: List<string>;
/**
* Specifies an inline stylesheet for an angular component.
*/
styles: List<string>;
/**
* Specifies a list of directives that can be used within a template.
*
* Directives must be listed explicitly to provide proper component encapsulation.
*
* ## Example
*
* ```javascript
* @Component({
* selector: 'my-component'
* })
* @View({
* directives: [For]
* template: '
* <ul>
* <li *ng-for="#item of items">{{item}}</li>
* </ul>'
* })
* class MyComponent {
* }
* ```
*/
directives: List<Type | any | List<any>>;
/**
* Specify how the template and the styles should be encapsulated.
* The default is {@link ViewEncapsulation#EMULATED `ViewEncapsulation.EMULATED`} if the view
* has styles,
* otherwise {@link ViewEncapsulation#NONE `ViewEncapsulation.NONE`}.
*/
encapsulation: ViewEncapsulation;
}
/**
* How the template and styles of a view should be encapsulated.
*/
enum ViewEncapsulation {
EMULATED,
NATIVE,
NONE
}
/**
* Specifies that a {@link QueryList} should be injected.
*
* See {@link QueryList} for usage and example.
*/
class QueryAnnotation extends DependencyMetadata {
descendants: boolean;
isViewQuery: void;
selector: void;
isVarBindingQuery: boolean;
varBindings: List<string>;
toString(): string;
}
/**
* Specifies that a constant attribute value should be injected.
*
* The directive can inject constant string literals of host element attributes.
*
* ## Example
*
* Suppose we have an `<input>` element and want to know its `type`.
*
* ```html
* <input type="text">
* ```
*
* A decorator can inject string literal `text` like so:
*
* ```javascript
* @Directive({
* selector: `input'
* })
* class InputDirective {
* constructor(@Attribute('type') type) {
* // type would be `text` in this example
* }
* }
* ```
*/
class AttributeAnnotation extends DependencyMetadata {
attributeName: string;
token: void;
toString(): string;
}
/**
* Defines lifecycle method
* {@link annotations/LifeCycleEvent#onAllChangesDone `LifeCycleEvent.onAllChangesDone`}
* called when the bindings of all its children have been changed.
*/
interface OnAllChangesDone {
onAllChangesDone(): void;
}
/**
* Defines lifecycle method {@link annotations/LifeCycleEvent#onChange `LifeCycleEvent.onChange`}
* called after all of component's bound properties are updated.
*/
interface OnChange {
onChange(changes: StringMap<string, any>): void;
}
/**
* Defines lifecycle method {@link annotations/LifeCycleEvent#onDestroy `LifeCycleEvent.onDestroy`}
* called when a directive is being destroyed.
*/
interface OnDestroy {
onDestroy(): void;
}
/**
* Defines lifecycle method {@link annotations/LifeCycleEvent#onInit `LifeCycleEvent.onInit`}
* called when a directive is being checked the first time.
*/
interface OnInit {
onInit(): void;
}
/**
* Defines lifecycle method {@link annotations/LifeCycleEvent#onCheck `LifeCycleEvent.onCheck`}
* called when a directive is being checked.
*/
interface OnCheck {
onCheck(): void;
}
/**
* Provides a way for expressing ES6 classes with parameter annotations in ES5.
*
* ## Basic Example
*
* ```
* var Greeter = ng.Class({
* constructor: function(name) {
* this.name = name;
* },
*
* greet: function() {
* alert('Hello ' + this.name + '!');
* }
* });
* ```
*
* is equivalent to ES6:
*
* ```
* class Greeter {
* constructor(name) {
* this.name = name;
* }
*
* greet() {
* alert('Hello ' + this.name + '!');
* }
* }
* ```
*
* or equivalent to ES5:
*
* ```
* var Greeter = function (name) {
* this.name = name;
* }
*
* Greeter.prototype.greet = function () {
* alert('Hello ' + this.name + '!');
* }
* ```
*
* ## Example with parameter annotations
*
* ```
* var MyService = neg.Class({
* constructor: [String, [new Query(), QueryList], function(name, queryList) {
* ...
* }];
* });
* ```
*
* is equivalent to ES6:
*
* ```
* class MyService {
* constructor(name: string, @Query() queryList: QueryList) {
* ...
* }
* }
* ```
*
* ## Example with inheritance
*
* ```
* var Shape = ng.Class({
* constructor: (color) {
* this.color = color;
* }
* });
*
* var Square = ng.Class({
* extends: Shape,
* constructor: function(color, size) {
* Shape.call(this, color);
* this.size = size;
* }
* });
* ```
*/
function Class(clsDef: ClassDefinition) : Type ;
/**
* Declares the interface to be used with {@link Class}.
*/
interface ClassDefinition {
/**
* Optional argument for specifying the superclass.
*/
extends?: Type;
/**
* Required constructor function for a class.
*
* The function may be optionally wrapped in an `Array`, in which case additional parameter
* annotations may be specified.
* The number of arguments and the number of parameter annotations must match.
*
* See {@link Class} for example of usage.
*/
constructor: (Function | Array<any>);
}
/**
* An interface implemented by all Angular type decorators, which allows them to be used as ES7
* decorators as well as
* Angular DSL syntax.
*
* DSL syntax:
*
* ```
* var MyClass = ng
* .Component({...})
* .View({...})
* .Class({...});
* ```
*
* ES7 syntax:
*
* ```
* @ng.Component({...})
* @ng.View({...})
* class MyClass {...}
* ```
*/
interface TypeDecorator {
/**
* Invoke as ES7 decorator.
*/
<T extends Type>(type: T): T;
/**
* Storage for the accumulated annotations so far used by the DSL syntax.
*
* Used by {@link Class} to annotate the generated class.
*/
annotations: Array<any>;
/**
* Generate a class from the definition and annotate it with {@link TypeDecorator#annotations}.
*/
Class(obj: ClassDefinition): Type;
}
/**
* {@link Attribute} factory function.
*/
var Attribute : AttributeFactory ;
/**
* {@link Attribute} factory for creating annotations, decorators or DSL.
*
* ## Example as TypeScript Decorator
*
* ```
* import {Attribute, Component, View} from "angular2/angular2";
*
* @Component({...})
* @View({...})
* class MyComponent {
* constructor(@Attribute('title') title: string) {
* ...
* }
* }
* ```
*
* ## Example as ES5 DSL
*
* ```
* var MyComponent = ng
* .Component({...})
* .View({...})
* .Class({
* constructor: [new ng.Attribute('title'), function(title) {
* ...
* }]
* })
* ```
*
* ## Example as ES5 annotation
*
* ```
* var MyComponent = function(title) {
* ...
* };
*
* MyComponent.annotations = [
* new ng.Component({...})
* new ng.View({...})
* ]
* MyComponent.parameters = [
* [new ng.Attribute('title')]
* ]
* ```
*/
interface AttributeFactory {
new(name: string): AttributeAnnotation;
(name: string): TypeDecorator;
}
/**
* {@link Component} factory function.
*/
var Component : ComponentFactory ;
/**
* Interface for the {@link Component} decorator function.
*
* See {@link ComponentFactory}.
*/
interface ComponentDecorator extends TypeDecorator {
/**
* Chain {@link View} annotation.
*/
View(obj: {
templateUrl?: string,
template?: string,
directives?: List<Type | any | List<any>>,
renderer?: string,
styles?: List<string>,
styleUrls?: List<string>,
}): ViewDecorator;
}
/**
* {@link ComponentAnnotation} factory for creating annotations, decorators or DSL.
*
* ## Example as TypeScript Decorator
*
* ```
* import {Component, View} from "angular2/angular2";
*
* @Component({...})
* @View({...})
* class MyComponent {
* constructor() {
* ...
* }
* }
* ```
*
* ## Example as ES5 DSL
*
* ```
* var MyComponent = ng
* .Component({...})
* .View({...})
* .Class({
* constructor: function() {
* ...
* }
* })
* ```
*
* ## Example as ES5 annotation
*
* ```
* var MyComponent = function() {
* ...
* };
*
* MyComponent.annotations = [
* new ng.Component({...})
* new ng.View({...})
* ]
* ```
*/
interface ComponentFactory {
new(obj: {
selector?: string,
properties?: List<string>,
events?: List<string>,
host?: StringMap<string, string>,
lifecycle?: List<LifecycleEvent>,
bindings?: List<any>,
exportAs?: string,
compileChildren?: boolean,
viewBindings?: List<any>,
changeDetection?: string,
}): ComponentAnnotation;
(obj: {
selector?: string,
properties?: List<string>,
events?: List<string>,
host?: StringMap<string, string>,
lifecycle?: List<LifecycleEvent>,
bindings?: List<any>,
exportAs?: string,
compileChildren?: boolean,
viewBindings?: List<any>,
changeDetection?: string,
}): ComponentDecorator;
}
/**
* {@link Directive} factory function.
*/
var Directive : DirectiveFactory ;
/**
* Interface for the {@link Directive} decorator function.
*
* See {@link DirectiveFactory}.
*/
interface DirectiveDecorator extends TypeDecorator {
}
/**
* {@link Directive} factory for creating annotations, decorators or DSL.
*
* ## Example as TypeScript Decorator
*
* ```
* import {Directive} from "angular2/angular2";
*
* @Directive({...})
* class MyDirective {
* constructor() {
* ...
* }
* }
* ```
*
* ## Example as ES5 DSL
*
* ```
* var MyDirective = ng
* .Directive({...})
* .Class({
* constructor: function() {
* ...
* }
* })
* ```
*
* ## Example as ES5 annotation
*
* ```
* var MyDirective = function() {
* ...
* };
*
* MyDirective.annotations = [
* new ng.Directive({...})
* ]
* ```
*/
interface DirectiveFactory {
new(obj: {
selector?: string, properties?: List<string>, events?: List<string>,
host?: StringMap<string, string>, lifecycle?: List<LifecycleEvent>, bindings?: List<any>,
exportAs?: string, compileChildren?: boolean;
}): DirectiveAnnotation;
(obj: {
selector?: string, properties?: List<string>, events?: List<string>,
host?: StringMap<string, string>, lifecycle?: List<LifecycleEvent>, bindings?: List<any>,
exportAs?: string, compileChildren?: boolean;
}): DirectiveDecorator;
}
/**
* {@link View} factory function.
*/
var View : ViewFactory ;
/**
* Interface for the {@link View} decorator function.
*
* See {@link ViewFactory}.
*/
interface ViewDecorator extends TypeDecorator {
/**
* Chain {@link View} annotation.
*/
View(obj: {
templateUrl?: string,
template?: string,
directives?: List<Type | any | List<any>>,
renderer?: string,
styles?: List<string>,
styleUrls?: List<string>,
}): ViewDecorator;
}
/**
* {@link ViewAnnotation} factory for creating annotations, decorators or DSL.
*
* ## Example as TypeScript Decorator
*
* ```
* import {Component, View} from "angular2/angular2";
*
* @Component({...})
* @View({...})
* class MyComponent {
* constructor() {
* ...
* }
* }
* ```
*
* ## Example as ES5 DSL
*
* ```
* var MyComponent = ng
* .Component({...})
* .View({...})
* .Class({
* constructor: function() {
* ...
* }
* })
* ```
*
* ## Example as ES5 annotation
*
* ```
* var MyComponent = function() {
* ...
* };
*
* MyComponent.annotations = [
* new ng.Component({...})
* new ng.View({...})
* ]
* ```
*/
interface ViewFactory {
new(obj: {
templateUrl?: string,
template?: string,
directives?: List<Type | any | List<any>>,
encapsulation?: ViewEncapsulation,
styles?: List<string>,
styleUrls?: List<string>,
}): ViewAnnotation;
(obj: {
templateUrl?: string,
template?: string,
directives?: List<Type | any | List<any>>,
encapsulation?: ViewEncapsulation,
styles?: List<string>,
styleUrls?: List<string>,
}): ViewDecorator;
}
/**
* {@link Query} factory function.
*/
var Query : QueryFactory ;
/**
* {@link Query} factory for creating annotations, decorators or DSL.
*
* ## Example as TypeScript Decorator
*
* ```
* import {Query, QueryList, Component, View} from "angular2/angular2";
*
* @Component({...})
* @View({...})
* class MyComponent {
* constructor(@Query(SomeType) queryList: QueryList) {
* ...
* }
* }
* ```
*
* ## Example as ES5 DSL
*
* ```
* var MyComponent = ng
* .Component({...})
* .View({...})
* .Class({
* constructor: [new ng.Query(SomeType), function(queryList) {
* ...
* }]
* })
* ```
*
* ## Example as ES5 annotation
*
* ```
* var MyComponent = function(queryList) {
* ...
* };
*
* MyComponent.annotations = [
* new ng.Component({...})
* new ng.View({...})
* ]
* MyComponent.parameters = [
* [new ng.Query(SomeType)]
* ]
* ```
*/
interface QueryFactory {
new(selector: Type | string, {descendants}?: {descendants?: boolean}): QueryAnnotation;
(selector: Type | string, {descendants}?: {descendants?: boolean}): ParameterDecorator;
}
/**
* {@link ViewQuery} factory function.
*/
var ViewQuery : QueryFactory ;
/**
* CHECK_ONCE means that after calling detectChanges the mode of the change detector
* will become CHECKED.
*/
const CHECK_ONCE : string ;
/**
* CHECK_ALWAYS means that after calling detectChanges the mode of the change detector
* will remain CHECK_ALWAYS.
*/
const CHECK_ALWAYS : string ;
/**
* DETACHED means that the change detector sub tree is not a part of the main tree and
* should be skipped.
*/
const DETACHED : string ;
/**
* CHECKED means that the change detector should be skipped until its mode changes to
* CHECK_ONCE or CHECK_ALWAYS.
*/
const CHECKED : string ;
/**
* ON_PUSH means that the change detector's mode will be set to CHECK_ONCE during hydration.
*/
const ON_PUSH : string ;
/**
* DEFAULT means that the change detector's mode will be set to CHECK_ALWAYS during hydration.
*/
const DEFAULT : string ;
/**
* An error thrown if application changes model breaking the top-down data flow.
*
* Angular expects that the data flows from top (root) component to child (leaf) components.
* This is known as directed acyclic graph. This allows Angular to only execute change detection
* once and prevents loops in change detection data flow.
*
* This exception is only thrown in dev mode.
*/
class ExpressionChangedAfterItHasBeenCheckedException extends BaseException {
}
/**
* Thrown when an expression evaluation raises an exception.
*
* This error wraps the original exception, this is done to attach expression location information.
*/
class ChangeDetectionError extends BaseException {
/**
* Location of the expression.
*/
location: string;
}
interface ChangeDetector {
parent: ChangeDetector;
mode: string;
addChild(cd: ChangeDetector): void;
addShadowDomChild(cd: ChangeDetector): void;
removeChild(cd: ChangeDetector): void;
removeShadowDomChild(cd: ChangeDetector): void;
remove(): void;
hydrate(context: any, locals: Locals, directives: any, pipes: any): void;
dehydrate(): void;
markPathToRootAsCheckOnce(): void;
detectChanges(): void;
checkNoChanges(): void;
}
class Locals {
parent: Locals;
current: Map<any, any>;
contains(name: string): boolean;
get(name: string): any;
set(name: string, value: any): void;
clearValues(): void;
}
/**
* Controls change detection.
*
* {@link ChangeDetectorRef} allows requesting checks for detectors that rely on observables. It
* also allows detaching and attaching change detector subtrees.
*/
interface ChangeDetectorRef {
/**
* Request to check all ON_PUSH ancestors.
*/
requestCheck(): void;
/**
* Detaches the change detector from the change detector tree.
*
* The detached change detector will not be checked until it is reattached.
*/
detach(): void;
/**
* Reattach the change detector to the change detector tree.
*
* This also requests a check of this change detector. This reattached change detector will be
* checked during the
* next change detection run.
*/
reattach(): void;
}
/**
* Indicates that the result of a {@link Pipe} transformation has changed even though the reference
* has not changed.
*
* The wrapped value will be unwrapped by change detection, and the unwrapped value will be stored.
*/
class WrappedValue {
wrapped: any;
}
const defaultPipes : Pipes ;
/**
* An interface which all pipes must implement.
*
* #Example
*
* ```
* class DoublePipe implements Pipe {
* supports(obj) {
* return true;
* }
*
* onDestroy() {}
*
* transform(value, args = []) {
* return `${value}${value}`;
* }
* }
* ```
*/
interface Pipe {
/**
* Query if a pipe supports a particular object instance.
*/
supports(obj: any): boolean;
onDestroy(): void;
transform(value: any, args: List<any>): any;
}
class Pipes {
/**
* Map of {@link Pipe} names to {@link PipeFactory} lists used to configure the
* {@link Pipes} registry.
*
* #Example
*
* ```
* var pipesConfig = {
* 'json': [jsonPipeFactory]
* }
* @Component({
* viewBindings: [
* bind(Pipes).toValue(new Pipes(pipesConfig))
* ]
* })
* ```
*/
config: StringMap<string, PipeFactory[]>;
get(type: string, obj: any, cdRef?: ChangeDetectorRef, existingPipe?: Pipe): Pipe;
}
/**
* A repository of different iterable diffing strategies used by NgFor, NgClass, and others.
*/
class IterableDiffers {
factories: IterableDifferFactory[];
find(iterable: Object): IterableDifferFactory;
}
interface IterableDiffer {
diff(object: Object): any;
onDestroy(): void;
}
/**
* Provides a factory for {@link IterableDiffer}.
*/
interface IterableDifferFactory {
supports(objects: Object): boolean;
create(cdRef: ChangeDetectorRef): IterableDiffer;
}
/**
* A repository of different Map diffing strategies used by NgClass, NgStyle, and others.
*/
class KeyValueDiffers {
factories: KeyValueDifferFactory[];
find(kv: Object): KeyValueDifferFactory;
}
interface KeyValueDiffer {
diff(object: Object): void;
onDestroy(): void;
}
/**
* Provides a factory for {@link KeyValueDiffer}.
*/
interface KeyValueDifferFactory {
supports(objects: Object): boolean;
create(cdRef: ChangeDetectorRef): KeyValueDiffer;
}
interface PipeFactory {
supports(obs: any): boolean;
create(cdRef: ChangeDetectorRef): Pipe;
}
/**
* Provides default implementation of `supports` and `onDestroy` method.
*
* #Example
*
* ```
* class DoublePipe extends BasePipe {
* transform(value) {
* return `${value}${value}`;
* }
* }
* ```
*/
class BasePipe implements Pipe {
supports(obj: any): boolean;
onDestroy(): void;
transform(value: any, args: List<any>): any;
}
class NullPipe extends BasePipe {
called: boolean;
supports(obj: any): boolean;
transform(value: any, args?: List<any>): WrappedValue;
}
class NullPipeFactory implements PipeFactory {
supports(obj: any): boolean;
create(cdRef: ChangeDetectorRef): Pipe;
}
/**
* An opaque token representing the application root type in the {@link Injector}.
*
* ```
* @Component(...)
* @View(...)
* class MyApp {
* ...
* }
*
* bootstrap(MyApp).then((appRef:ApplicationRef) {
* expect(appRef.injector.get(appComponentTypeToken)).toEqual(MyApp);
* });
*
* ```
*/
const appComponentTypeToken : OpaqueToken ;
/**
* Represents a Angular's representation of an Application.
*
* `ApplicationRef` represents a running application instance. Use it to retrieve the host
* component, injector,
* or dispose of an application.
*/
interface ApplicationRef {
/**
* Returns the current {@link Component} type.
*/
hostComponentType: Type;
/**
* Returns the current {@link Component} instance.
*/
hostComponent: any;
/**
* Dispose (un-load) the application.
*/
dispose(): void;
/**
* Returns the root application {@link Injector}.
*/
injector: Injector;
}
/**
* Runtime representation of a type.
*
* In JavaScript a Type is a constructor function.
*/
interface Type extends Function {
new(args: any): any;
}
/**
* Specifies app root url for the application.
*
* Used by the {@link Compiler} when resolving HTML and CSS template URLs.
*
* This interface can be overridden by the application developer to create custom behavior.
*
* See {@link Compiler}
*/
class AppRootUrl {
/**
* Returns the base URL of the currently running application.
*/
value: void;
}
/**
* Used by the {@link Compiler} when resolving HTML and CSS template URLs.
*
* This interface can be overridden by the application developer to create custom behavior.
*
* See {@link Compiler}
*/
class UrlResolver {
/**
* Resolves the `url` given the `baseUrl`:
* - when the `url` is null, the `baseUrl` is returned,
* - if `url` is relative ('path/to/here', './path/to/here'), the resolved url is a combination of
* `baseUrl` and `url`,
* - if `url` is absolute (it has a scheme: 'http://', 'https://' or start with '/'), the `url` is
* returned as is (ignoring the `baseUrl`)
*
* @param {string} baseUrl
* @param {string} url
* @returns {string} the resolved URL
*/
resolve(baseUrl: string, url: string): string;
}
/**
* Resolve a `Type` from a {@link Component} into a URL.
*
* This interface can be overridden by the application developer to create custom behavior.
*
* See {@link Compiler}
*/
class ComponentUrlMapper {
/**
* Returns the base URL to the component source file.
* The returned URL could be:
* - an absolute URL,
* - a path relative to the application
*/
getUrl(component: Type): string;
}
/**
* Resolve a `Type` for {@link Directive}.
*
* This interface can be overridden by the application developer to create custom behavior.
*
* See {@link Compiler}
*/
class DirectiveResolver {
/**
* Return {@link Directive} for a given `Type`.
*/
resolve(type: Type): DirectiveAnnotation;
}
/**
* ## URL Resolution
*
* ```
* var appRootUrl: AppRootUrl = ...;
* var componentUrlMapper: ComponentUrlMapper = ...;
* var urlResolver: UrlResolver = ...;
*
* var componentType: Type = ...;
* var componentAnnotation: ComponentAnnotation = ...;
* var viewAnnotation: ViewAnnotation = ...;
*
* // Resolving a URL
*
* var url = viewAnnotation.templateUrl;
* var componentUrl = componentUrlMapper.getUrl(componentType);
* var componentResolvedUrl = urlResolver.resolve(appRootUrl.value, componentUrl);
* var templateResolvedUrl = urlResolver.resolve(componetResolvedUrl, url);
* ```
*/
interface Compiler {
compileInHost(componentTypeOrBinding: Type | Binding): Promise<ProtoViewRef>;
}
/**
* Entry point for creating, moving views in the view hierarchy and destroying views.
* This manager contains all recursion and delegates to helper methods
* in AppViewManagerUtils and the Renderer, so unit tests get simpler.
*/
interface AppViewManager {
/**
* Returns a {@link ViewContainerRef} at the {@link ElementRef} location.
*/
getViewContainer(location: ElementRef): ViewContainerRef;
/**
* Return the first child element of the host element view.
*/
getHostElement(hostViewRef: HostViewRef): ElementRef;
/**
* Returns an ElementRef for the element with the given variable name
* in the current view.
*
* - `hostLocation`: {@link ElementRef} of any element in the View which defines the scope of
* search.
* - `variableName`: Name of the variable to locate.
* - Returns {@link ElementRef} of the found element or null. (Throws if not found.)
*/
getNamedElementInComponentView(hostLocation: ElementRef, variableName: string): ElementRef;
/**
* Returns the component instance for a given element.
*
* The component is the execution context as seen by an expression at that {@link ElementRef}
* location.
*/
getComponent(hostLocation: ElementRef): any;
/**
* Load component view into existing element.
*
* Use this if a host element is already in the DOM and it is necessary to upgrade
* the element into Angular component by attaching a view but reusing the existing element.
*
* - `hostProtoViewRef`: {@link ProtoViewRef} Proto view to use in creating a view for this
* component.
* - `overrideSelector`: (optional) selector to use in locating the existing element to load
* the view into. If not specified use the selector in the component definition of the
* `hostProtoView`.
* - injector: {@link Injector} to use as parent injector for the view.
*
* See {@link AppViewManager#destroyRootHostView}.
*
* ## Example
*
* ```
* @ng.Component({
* selector: 'child-component'
* })
* @ng.View({
* template: 'Child'
* })
* class ChildComponent {
*
* }
*
* @ng.Component({
* selector: 'my-app'
* })
* @ng.View({
* template: `
* Parent (<some-component></some-component>)
* `
* })
* class MyApp {
* viewRef: ng.ViewRef;
*
* constructor(public appViewManager: ng.AppViewManager, compiler: ng.Compiler) {
* compiler.compileInHost(ChildComponent).then((protoView: ng.ProtoViewRef) => {
* this.viewRef = appViewManager.createRootHostView(protoView, 'some-component', null);
* })
* }
*
* onDestroy() {
* this.appViewManager.destroyRootHostView(this.viewRef);
* this.viewRef = null;
* }
* }
*
* ng.bootstrap(MyApp);
* ```
*/
createRootHostView(hostProtoViewRef: ProtoViewRef, overrideSelector: string, injector: Injector): HostViewRef;
/**
* Remove the View created with {@link AppViewManager#createRootHostView}.
*/
destroyRootHostView(hostViewRef: HostViewRef): void;
/**
* See {@link AppViewManager#destroyViewInContainer}.
*/
createEmbeddedViewInContainer(viewContainerLocation: ElementRef, atIndex: number, templateRef: TemplateRef): ViewRef;
/**
* See {@link AppViewManager#destroyViewInContainer}.
*/
createHostViewInContainer(viewContainerLocation: ElementRef, atIndex: number, protoViewRef: ProtoViewRef, imperativelyCreatedInjector: ResolvedBinding[]): HostViewRef;
/**
* See {@link AppViewManager#createViewInContainer}.
*/
destroyViewInContainer(viewContainerLocation: ElementRef, atIndex: number): void;
/**
* See {@link AppViewManager#detachViewInContainer}.
*/
attachViewInContainer(viewContainerLocation: ElementRef, atIndex: number, viewRef: ViewRef): ViewRef;
/**
* See {@link AppViewManager#attachViewInContainer}.
*/
detachViewInContainer(viewContainerLocation: ElementRef, atIndex: number): ViewRef;
}
/**
* An iterable live list of components in the Light DOM.
*
* Injectable Objects that contains a live list of child directives in the light DOM of a directive.
* The directives are kept in depth-first pre-order traversal of the DOM.
*
* The `QueryList` is iterable, therefore it can be used in both javascript code with `for..of` loop
* as well as in
* template with `*ng-for="of"` directive.
*
* NOTE: In the future this class will implement an `Observable` interface. For now it uses a plain
* list of observable
* callbacks.
*
* # Example:
*
* Assume that `<tabs>` component would like to get a list its children which are `<pane>`
* components as shown in this
* example:
*
* ```html
* <tabs>
* <pane title="Overview">...</pane>
* <pane *ng-for="#o of objects" [title]="o.title">{{o.text}}</pane>
* </tabs>
* ```
*
* In the above example the list of `<tabs>` elements needs to get a list of `<pane>` elements so
* that it could render
* tabs with the correct titles and in the correct order.
*
* A possible solution would be for a `<pane>` to inject `<tabs>` component and then register itself
* with `<tabs>`
* component's on `hydrate` and deregister on `dehydrate` event. While a reasonable approach, this
* would only work
* partialy since `*ng-for` could rearrange the list of `<pane>` components which would not be
* reported to `<tabs>`
* component and thus the list of `<pane>` components would be out of sync with respect to the list
* of `<pane>` elements.
*
* A preferred solution is to inject a `QueryList` which is a live list of directives in the
* component`s light DOM.
*
* ```javascript
* @Component({
* selector: 'tabs'
* })
* @View({
* template: `
* <ul>
* <li *ng-for="#pane of panes">{{pane.title}}</li>
* </ul>
* <content></content>
* `
* })
* class Tabs {
* panes: QueryList<Pane>
*
* constructor(@Query(Pane) panes:QueryList<Pane>) {
* this.panes = panes;
* }
* }
*
* @Component({
* selector: 'pane',
* properties: ['title']
* })
* @View(...)
* class Pane {
* title:string;
* }
* ```
*/
interface IQueryList<T> {
}
/**
* Injectable Objects that contains a live list of child directives in the light Dom of a directive.
* The directives are kept in depth-first pre-order traversal of the DOM.
*
* In the future this class will implement an Observable interface.
* For now it uses a plain list of observable callbacks.
*/
class QueryList<T> implements IQueryList<T> {
reset(newList: List<T>): void;
add(obj: T): void;
fireCallbacks(): void;
onChange(callback: () => void): void;
removeCallback(callback: () => void): void;
length: number;
first: T;
last: T;
map<U>(fn: (item: T) => U): U[];
}
/**
* Service for dynamically loading a Component into an arbitrary position in the internal Angular
* application tree.
*/
class DynamicComponentLoader {
/**
* Loads a root component that is placed at the first element that matches the component's
* selector.
*
* - `typeOrBinding` `Type` \ {@link Binding} - representing the component to load.
* - `overrideSelector` (optional) selector to load the component at (or use
* `@Component.selector`) The selector can be anywhere (i.e. outside the current component.)
* - `injector` {@link Injector} - optional injector to use for the component.
*
* The loaded component receives injection normally as a hosted view.
*
*
* ## Example
*
* ```
* @ng.Component({
* selector: 'child-component'
* })
* @ng.View({
* template: 'Child'
* })
* class ChildComponent {
* }
*
*
*
* @ng.Component({
* selector: 'my-app'
* })
* @ng.View({
* template: `
* Parent (<child id="child"></child>)
* `
* })
* class MyApp {
* constructor(dynamicComponentLoader: ng.DynamicComponentLoader, injector: ng.Injector) {
* dynamicComponentLoader.loadAsRoot(ChildComponent, '#child', injector);
* }
* }
*
* ng.bootstrap(MyApp);
* ```
*
* Resulting DOM:
*
* ```
* <my-app>
* Parent (
* <child id="child">
* Child
* </child>
* )
* </my-app>
* ```
*/
loadAsRoot(typeOrBinding: Type | Binding, overrideSelector: string, injector: Injector): Promise<ComponentRef>;
/**
* Loads a component into the component view of the provided ElementRef next to the element
* with the given name.
*
* The loaded component receives injection normally as a hosted view.
*
* ## Example
*
* ```
* @ng.Component({
* selector: 'child-component'
* })
* @ng.View({
* template: 'Child'
* })
* class ChildComponent {
* }
*
*
* @ng.Component({
* selector: 'my-app'
* })
* @ng.View({
* template: `
* Parent (<div #child></div>)
* `
* })
* class MyApp {
* constructor(dynamicComponentLoader: ng.DynamicComponentLoader, elementRef: ng.ElementRef) {
* dynamicComponentLoader.loadIntoLocation(ChildComponent, elementRef, 'child');
* }
* }
*
* ng.bootstrap(MyApp);
* ```
*
* Resulting DOM:
*
* ```
* <my-app>
* Parent (
* <div #child="" class="ng-binding"></div>
* <child-component class="ng-binding">Child</child-component>
* )
* </my-app>
* ```
*/
loadIntoLocation(typeOrBinding: Type | Binding, hostLocation: ElementRef, anchorName: string, bindings?: ResolvedBinding[]): Promise<ComponentRef>;
/**
* Loads a component next to the provided ElementRef.
*
* The loaded component receives injection normally as a hosted view.
*
*
* ## Example
*
* ```
* @ng.Component({
* selector: 'child-component'
* })
* @ng.View({
* template: 'Child'
* })
* class ChildComponent {
* }
*
*
* @ng.Component({
* selector: 'my-app'
* })
* @ng.View({
* template: `Parent`
* })
* class MyApp {
* constructor(dynamicComponentLoader: ng.DynamicComponentLoader, elementRef: ng.ElementRef) {
* dynamicComponentLoader.loadIntoLocation(ChildComponent, elementRef, 'child');
* }
* }
*
* ng.bootstrap(MyApp);
* ```
*
* Resulting DOM:
*
* ```
* <my-app>Parent</my-app>
* <child-component>Child</child-component>
* ```
*/
loadNextToLocation(typeOrBinding: Type | Binding, location: ElementRef, bindings?: ResolvedBinding[]): Promise<ComponentRef>;
}
/**
* Provides access to explicitly trigger change detection in an application.
*
* By default, `Zone` triggers change detection in Angular on each virtual machine (VM) turn. When
* testing, or in some
* limited application use cases, a developer can also trigger change detection with the
* `lifecycle.tick()` method.
*
* Each Angular application has a single `LifeCycle` instance.
*
* # Example
*
* This is a contrived example, since the bootstrap automatically runs inside of the `Zone`, which
* invokes
* `lifecycle.tick()` on your behalf.
*
* ```javascript
* bootstrap(MyApp).then((ref:ComponentRef) => {
* var lifeCycle = ref.injector.get(LifeCycle);
* var myApp = ref.instance;
*
* ref.doSomething();
* lifecycle.tick();
* });
* ```
*/
class LifeCycle {
/**
* @private
*/
registerWith(zone: NgZone, changeDetector?: ChangeDetector): void;
/**
* Invoke this method to explicitly process change detection and its side-effects.
*
* In development mode, `tick()` also performs a second change detection cycle to ensure that no
* further
* changes are detected. If additional changes are picked up during this second cycle, bindings
* in
* the app have
* side-effects that cannot be resolved in a single change detection pass. In this case, Angular
* throws an error,
* since an Angular application can only have one change detection pass during which all change
* detection must
* complete.
*/
tick(): void;
}
/**
* Reference to the element.
*
* Represents an opaque reference to the underlying element. The element is a DOM ELement in
* a Browser, but may represent other types on other rendering platforms. In the browser the
* `ElementRef` can be sent to the web-worker. Web Workers can not have references to the
* DOM Elements.
*/
class ElementRef implements RenderElementRef {
/**
* Reference to the {@link ViewRef} where the `ElementRef` is inside of.
*/
parentView: ViewRef;
/**
* Index of the element inside the {@link ViewRef}.
*
* This is used internally by the Angular framework to locate elements.
*/
boundElementIndex: number;
/**
* Index of the element inside the `RenderViewRef`.
*
* This is used internally by the Angular framework to locate elements.
*/
renderBoundElementIndex: number;
renderView: RenderViewRef;
/**
* Returns the native Element implementation.
*
* In the browser this represents the DOM Element.
*
* The `nativeElement` can be used as an escape hatch when direct DOM manipulation is needed. Use
* this with caution, as it creates tight coupling between your application and the Browser, which
* will not work in WebWorkers.
*
* NOTE: This method will return null in the webworker scenario!
*/
nativeElement: any;
}
/**
* Reference to a template within a component.
*
* Represents an opaque reference to the underlying template that can
* be instantiated using the {@link ViewContainerRef}.
*/
class TemplateRef {
/**
* The location of the template
*/
elementRef: ElementRef;
protoViewRef: ProtoViewRef;
/**
* Whether this template has a local variable with the given name
*/
hasLocal(name: string): boolean;
}
/**
* Abstract reference to the element which can be marshaled across web-worker boundary.
*
* This interface is used by the Renderer API.
*/
interface RenderElementRef {
/**
* Reference to the `RenderViewRef` where the `RenderElementRef` is inside of.
*/
renderView: RenderViewRef;
/**
* Index of the element inside the `RenderViewRef`.
*
* This is used internally by the Angular framework to locate elements.
*/
renderBoundElementIndex: number;
}
/**
* A reference to an Angular View.
*
* A View is a fundamental building block of Application UI. A View is the smallest set of
* elements which are created and destroyed together. A View can change properties on the elements
* within the view, but it can not change the structure of those elements.
*
* To change structure of the elements, the Views can contain zero or more {@link ViewContainerRef}s
* which allow the views to be nested.
*
* ## Example
*
* Given this template
*
* ```
* Count: {{items.length}}
* <ul>
* <li *ng-for="var item of items">{{item}}</li>
* </ul>
* ```
*
* The above example we have two {@link ProtoViewRef}s:
*
* Outter {@link ProtoViewRef}:
* ```
* Count: {{items.length}}
* <ul>
* <template ng-for var-item [ng-for-of]="items"></template>
* </ul>
* ```
*
* Inner {@link ProtoViewRef}:
* ```
* <li>{{item}}</li>
* ```
*
* Notice that the original template is broken down into two separate {@link ProtoViewRef}s.
*
* The outter/inner {@link ProtoViewRef}s are then assembled into views like so:
*
* ```
* <!-- ViewRef: outer-0 -->
* Count: 2
* <ul>
* <template view-container-ref></template>
* <!-- ViewRef: inner-1 --><li>first</li><!-- /ViewRef: inner-1 -->
* <!-- ViewRef: inner-2 --><li>second</li><!-- /ViewRef: inner-2 -->
* </ul>
* <!-- /ViewRef: outer-0 -->
* ```
*/
interface ViewRef extends HostViewRef {
/**
* Return `RenderViewRef`
*/
render: RenderViewRef;
/**
* Return `RenderFragmentRef`
*/
renderFragment: RenderFragmentRef;
/**
* Set local variable in a view.
*
* - `contextName` - Name of the local variable in a view.
* - `value` - Value for the local variable in a view.
*/
setLocal(contextName: string, value: any): void;
}
interface HostViewRef {
}
/**
* A reference to an Angular ProtoView.
*
* A ProtoView is a reference to a template for easy creation of views.
* (See {@link AppViewManager#createViewInContainer} and {@link AppViewManager#createRootHostView}).
*
* A `ProtoView` is a foctary for creating `View`s.
*
* ## Example
*
* Given this template
*
* ```
* Count: {{items.length}}
* <ul>
* <li *ng-for="var item of items">{{item}}</li>
* </ul>
* ```
*
* The above example we have two {@link ProtoViewRef}s:
*
* Outter {@link ProtoViewRef}:
* ```
* Count: {{items.length}}
* <ul>
* <template ng-for var-item [ng-for-of]="items"></template>
* </ul>
* ```
*
* Inner {@link ProtoViewRef}:
* ```
* <li>{{item}}</li>
* ```
*
* Notice that the original template is broken down into two separate {@link ProtoViewRef}s.
*/
interface ProtoViewRef {
}
/**
* A location where {@link ViewRef}s can be attached.
*
* A `ViewContainerRef` represents a location in a {@link ViewRef} where other child
* {@link ViewRef}s can be inserted. Adding and removing views is the only way of structurally
* changing the rendered DOM of the application.
*/
interface ViewContainerRef {
viewManager: AppViewManager;
element: ElementRef;
/**
* Remove all {@link ViewRef}s at current location.
*/
clear(): void;
/**
* Return a {@link ViewRef} at specific index.
*/
get(index: number): ViewRef;
/**
* Returns number of {@link ViewRef}s currently attached at this location.
*/
length: number;
/**
* Create and insert a {@link ViewRef} into the view-container.
*
* - `protoViewRef` (optional) {@link ProtoViewRef} - The `ProtoView` to use for creating
* `View` to be inserted at this location. If `ViewContainer` is created at a location
* of inline template, then `protoViewRef` is the `ProtoView` of the template.
* - `atIndex` (optional) `number` - location of insertion point. (Or at the end if unspecified.)
* - `context` (optional) {@link ElementRef} - Context (for expression evaluation) from the
* {@link ElementRef} location. (Or current context if unspecified.)
* - `bindings` (optional) Array of {@link ResolvedBinding} - Used for configuring
* `ElementInjector`.
*
* Returns newly created {@link ViewRef}.
*/
createEmbeddedView(templateRef: TemplateRef, atIndex?: number): ViewRef;
createHostView(protoViewRef?: ProtoViewRef, atIndex?: number, dynamicallyCreatedBindings?: ResolvedBinding[]): HostViewRef;
/**
* Insert a {@link ViewRef} at specefic index.
*
* The index is location at which the {@link ViewRef} should be attached. If omitted it is
* inserted at the end.
*
* Returns the inserted {@link ViewRef}.
*/
insert(viewRef: ViewRef, atIndex?: number): ViewRef;
/**
* Return the index of already inserted {@link ViewRef}.
*/
indexOf(viewRef: ViewRef): number;
/**
* Remove a {@link ViewRef} at specific index.
*
* If the index is omitted last {@link ViewRef} is removed.
*/
remove(atIndex?: number): void;
/**
* The method can be used together with insert to implement a view move, i.e.
* moving the dom nodes while the directives in the view stay intact.
*/
detach(atIndex?: number): ViewRef;
}
/**
* Angular's reference to a component instance.
*
* `ComponentRef` represents a component instance lifecycle and meta information.
*/
interface ComponentRef {
/**
* Location of the component host element.
*/
location: ElementRef;
/**
* Instance of component.
*/
instance: any;
/**
* Returns the host {@link ViewRef}.
*/
hostView: HostViewRef;
/**
* Dispose of the component instance.
*/
dispose(): void;
}
/**
* A wrapper around zones that lets you schedule tasks after it has executed a task.
*
* The wrapper maintains an "inner" and an "mount" `Zone`. The application code will executes
* in the "inner" zone unless `runOutsideAngular` is explicitely called.
*
* A typical application will create a singleton `NgZone`. The outer `Zone` is a fork of the root
* `Zone`. The default `onTurnDone` runs the Angular change detection.
*/
class NgZone {
/**
* Sets the zone hook that is called just before Angular event turn starts.
* It is called once per browser event.
*/
overrideOnTurnStart(onTurnStartFn: Function): void;
/**
* Sets the zone hook that is called immediately after Angular processes
* all pending microtasks.
*/
overrideOnTurnDone(onTurnDoneFn: Function): void;
/**
* Sets the zone hook that is called immediately after the last turn in
* an event completes. At this point Angular will no longer attempt to
* sync the UI. Any changes to the data model will not be reflected in the
* DOM. `onEventDoneFn` is executed outside Angular zone.
*
* This hook is useful for validating application state (e.g. in a test).
*/
overrideOnEventDone(onEventDoneFn: Function, opt_waitForAsync: boolean): void;
/**
* Sets the zone hook that is called when an error is uncaught in the
* Angular zone. The first argument is the error. The second argument is
* the stack trace.
*/
overrideOnErrorHandler(errorHandlingFn: Function): void;
/**
* Runs `fn` in the inner zone and returns whatever it returns.
*
* In a typical app where the inner zone is the Angular zone, this allows one to make use of the
* Angular's auto digest mechanism.
*
* ```
* var zone: NgZone = [ref to the application zone];
*
* zone.run(() => {
* // the change detection will run after this function and the microtasks it enqueues have
* executed.
* });
* ```
*/
run(fn: () => any): any;
/**
* Runs `fn` in the outer zone and returns whatever it returns.
*
* In a typical app where the inner zone is the Angular zone, this allows one to escape Angular's
* auto-digest mechanism.
*
* ```
* var zone: NgZone = [ref to the application zone];
*
* zone.runOutsideAngular(() => {
* element.onClick(() => {
* // Clicking on the element would not trigger the change detection
* });
* });
* ```
*/
runOutsideAngular(fn: () => any): any;
}
class Observable {
observer(generator: any): Object;
}
/**
* Use Rx.Observable but provides an adapter to make it work as specified here:
* https://github.com/jhusain/observable-spec
*
* Once a reference implementation of the spec is available, switch to it.
*/
class EventEmitter extends Observable {
observer(generator: any): Rx.IDisposable;
toRx(): Rx.Observable<any>;
next(value: any): void;
throw(error: any): void;
return(value?: any): void;
}
/**
* A parameter metadata that specifies a dependency.
*
* ```
* class AComponent {
* constructor(@Inject(MyService) aService:MyService) {}
* }
* ```
*/
class InjectMetadata {
token: void;
toString(): string;
}
/**
* A parameter metadata that marks a dependency as optional. {@link Injector} provides `null` if
* the dependency is not found.
*
* ```
* class AComponent {
* constructor(@Optional() aService:MyService) {
* this.aService = aService;
* }
* }
* ```
*/
class OptionalMetadata {
toString(): string;
}
/**
* A marker metadata that marks a class as available to `Injector` for creation. Used by tooling
* for generating constructor stubs.
*
* ```
* class NeedsService {
* constructor(svc:UsefulService) {}
* }
*
* @Injectable
* class UsefulService {}
* ```
*/
class InjectableMetadata {
}
/**
* Specifies that an injector should retrieve a dependency from itself.
*
* ## Example
*
* ```
* class Dependency {
* }
*
* class NeedsDependency {
* constructor(public @Self() dependency:Dependency) {}
* }
*
* var inj = Injector.resolveAndCreate([Dependency, NeedsDependency]);
* var nd = inj.get(NeedsDependency);
* expect(nd.dependency).toBeAnInstanceOf(Dependency);
* ```
*/
class SelfMetadata {
toString(): string;
}
/**
* Specifies that an injector should retrieve a dependency from any injector until reaching the
* closest host.
*
* ## Example
*
* ```
* class Dependency {
* }
*
* class NeedsDependency {
* constructor(public @Host() dependency:Dependency) {}
* }
*
* var parent = Injector.resolveAndCreate([
* bind(Dependency).toClass(HostDependency)
* ]);
* var child = parent.resolveAndCreateChild([]);
* var grandChild = child.resolveAndCreateChild([NeedsDependency, Depedency]);
* var nd = grandChild.get(NeedsDependency);
* expect(nd.dependency).toBeAnInstanceOf(HostDependency);
* ```
*/
class HostMetadata {
toString(): string;
}
/**
* Specifies that the dependency resolution should start from the parent injector.
*
* ## Example
*
*
* ```
* class Service {}
*
* class ParentService implements Service {
* }
*
* class ChildService implements Service {
* constructor(public @SkipSelf() parentService:Service) {}
* }
*
* var parent = Injector.resolveAndCreate([
* bind(Service).toClass(ParentService)
* ]);
* var child = parent.resolveAndCreateChild([
* bind(Service).toClass(ChildSerice)
* ]);
* var s = child.get(Service);
* expect(s).toBeAnInstanceOf(ChildService);
* expect(s.parentService).toBeAnInstanceOf(ParentService);
* ```
*/
class SkipSelfMetadata {
toString(): string;
}
/**
* `DependencyMetadata is used by the framework to extend DI.
*
* Only metadata implementing `DependencyMetadata` are added to the list of dependency
* properties.
*
* For example:
*
* ```
* class Exclude extends DependencyMetadata {}
* class NotDependencyProperty {}
*
* class AComponent {
* constructor(@Exclude @NotDependencyProperty aService:AService) {}
* }
* ```
*
* will create the following dependency:
*
* ```
* new Dependency(Key.get(AService), [new Exclude()])
* ```
*
* The framework can use `new Exclude()` to handle the `aService` dependency
* in a specific way.
*/
class DependencyMetadata {
token: void;
}
/**
* Allows to refer to references which are not yet defined.
*
* This situation arises when the key which we need te refer to for the purposes of DI is declared,
* but not yet defined.
*
* ## Example:
*
* ```
* class Door {
* // Incorrect way to refer to a reference which is defined later.
* // This fails because `Lock` is undefined at this point.
* constructor(lock:Lock) { }
*
* // Correct way to refer to a reference which is defined later.
* // The reference needs to be captured in a closure.
* constructor(@Inject(forwardRef(() => Lock)) lock:Lock) { }
* }
*
* // Only at this point the lock is defined.
* class Lock {
* }
* ```
*/
function forwardRef(forwardRefFn: ForwardRefFn) : Type ;
/**
* Lazily retrieve the reference value.
*
* See: {@link forwardRef}
*/
function resolveForwardRef(type: any) : any ;
interface ForwardRefFn {
(): any;
}
/**
* A dependency injection container used for resolving dependencies.
*
* An `Injector` is a replacement for a `new` operator, which can automatically resolve the
* constructor dependencies.
* In typical use, application code asks for the dependencies in the constructor and they are
* resolved by the `Injector`.
*
* ## Example:
*
* Suppose that we want to inject an `Engine` into class `Car`, we would define it like this:
*
* ```javascript
* class Engine {
* }
*
* class Car {
* constructor(@Inject(Engine) engine) {
* }
* }
*
* ```
*
* Next we need to write the code that creates and instantiates the `Injector`. We then ask for the
* `root` object, `Car`, so that the `Injector` can recursively build all of that object's
* dependencies.
*
* ```javascript
* main() {
* var injector = Injector.resolveAndCreate([Car, Engine]);
*
* // Get a reference to the `root` object, which will recursively instantiate the tree.
* var car = injector.get(Car);
* }
* ```
* Notice that we don't use the `new` operator because we explicitly want to have the `Injector`
* resolve all of the object's dependencies automatically.
*/
class Injector {
/**
* Returns debug information about the injector.
*
* This information is included into exceptions thrown by the injector.
*/
debugContext(): any;
/**
* Retrieves an instance from the injector.
*
* @param `token`: usually the `Type` of an object. (Same as the token used while setting up a
* binding).
* @returns an instance represented by the token. Throws if not found.
*/
get(token: any): any;
/**
* Retrieves an instance from the injector.
*
* @param `token`: usually a `Type`. (Same as the token used while setting up a binding).
* @returns an instance represented by the token. Returns `null` if not found.
*/
getOptional(token: any): any;
/**
* Retrieves an instance from the injector.
*
* @param `index`: index of an instance.
* @returns an instance represented by the index. Throws if not found.
*/
getAt(index: number): any;
/**
* Direct parent of this injector.
*/
parent: Injector;
/**
* Internal. Do not use.
*
* We return `any` not to export the InjectorStrategy type.
*/
internalStrategy: any;
/**
* Creates a child injector and loads a new set of bindings into it.
*
* A resolution is a process of flattening multiple nested lists and converting individual
* bindings into a list of {@link ResolvedBinding}s. The resolution can be cached by `resolve`
* for the {@link Injector} for performance-sensitive code.
*
* @param `bindings` can be a list of `Type`, {@link Binding}, {@link ResolvedBinding}, or a
* recursive list of more bindings.
* @param `depProvider`
*/
resolveAndCreateChild(bindings: List<Type | Binding | List<any>>, depProvider?: DependencyProvider): Injector;
/**
* Creates a child injector and loads a new set of {@link ResolvedBinding}s into it.
*
* @param `bindings`: A sparse list of {@link ResolvedBinding}s.
* See `resolve` for the {@link Injector}.
* @param `depProvider`
* @returns a new child {@link Injector}.
*/
createChildFromResolved(bindings: List<ResolvedBinding>, depProvider?: DependencyProvider): Injector;
displayName: string;
toString(): string;
}
class ProtoInjector {
numberOfBindings: number;
getBindingAtIndex(index: number): any;
}
class BindingWithVisibility {
binding: ResolvedBinding;
visibility: number;
getKeyId(): number;
}
/**
* Used to provide dependencies that cannot be easily expressed as bindings.
*/
interface DependencyProvider {
getDependency(injector: Injector, binding: ResolvedBinding, dependency: Dependency): any;
}
const PUBLIC_AND_PRIVATE : number ;
const PUBLIC : number ;
const PRIVATE : number ;
const undefinedValue : Object ;
/**
* Describes how the {@link Injector} should instantiate a given token.
*
* See {@link bind}.
*
* ## Example
*
* ```javascript
* var injector = Injector.resolveAndCreate([
* new Binding(String, { toValue: 'Hello' })
* ]);
*
* expect(injector.get(String)).toEqual('Hello');
* ```
*/
class Binding {
/**
* Token used when retrieving this binding. Usually the `Type`.
*/
token: void;
/**
* Binds an interface to an implementation / subclass.
*
* ## Example
*
* Becuse `toAlias` and `toClass` are often confused, the example contains both use cases for easy
* comparison.
*
* ```javascript
*
* class Vehicle {}
*
* class Car extends Vehicle {}
*
* var injectorClass = Injector.resolveAndCreate([
* Car,
* new Binding(Vehicle, { toClass: Car })
* ]);
* var injectorAlias = Injector.resolveAndCreate([
* Car,
* new Binding(Vehicle, { toAlias: Car })
* ]);
*
* expect(injectorClass.get(Vehicle)).not.toBe(injectorClass.get(Car));
* expect(injectorClass.get(Vehicle) instanceof Car).toBe(true);
*
* expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car));
* expect(injectorAlias.get(Vehicle) instanceof Car).toBe(true);
* ```
*/
toClass: Type;
/**
* Binds a key to a value.
*
* ## Example
*
* ```javascript
* var injector = Injector.resolveAndCreate([
* new Binding(String, { toValue: 'Hello' })
* ]);
*
* expect(injector.get(String)).toEqual('Hello');
* ```
*/
toValue: void;
/**
* Binds a key to the alias for an existing key.
*
* An alias means that {@link Injector} returns the same instance as if the alias token was used.
* This is in contrast to `toClass` where a separate instance of `toClass` is returned.
*
* ## Example
*
* Becuse `toAlias` and `toClass` are often confused the example contains both use cases for easy
* comparison.
*
* ```javascript
*
* class Vehicle {}
*
* class Car extends Vehicle {}
*
* var injectorAlias = Injector.resolveAndCreate([
* Car,
* new Binding(Vehicle, { toAlias: Car })
* ]);
* var injectorClass = Injector.resolveAndCreate([
* Car,
* new Binding(Vehicle, { toClass: Car })
* ]);
*
* expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car));
* expect(injectorAlias.get(Vehicle) instanceof Car).toBe(true);
*
* expect(injectorClass.get(Vehicle)).not.toBe(injectorClass.get(Car));
* expect(injectorClass.get(Vehicle) instanceof Car).toBe(true);
* ```
*/
toAlias: void;
/**
* Binds a key to a function which computes the value.
*
* ## Example
*
* ```javascript
* var injector = Injector.resolveAndCreate([
* new Binding(Number, { toFactory: () => { return 1+2; }}),
* new Binding(String, { toFactory: (value) => { return "Value: " + value; },
* dependencies: [Number] })
* ]);
*
* expect(injector.get(Number)).toEqual(3);
* expect(injector.get(String)).toEqual('Value: 3');
* ```
*/
toFactory: Function;
/**
* Used in conjunction with `toFactory` and specifies a set of dependencies
* (as `token`s) which should be injected into the factory function.
*
* ## Example
*
* ```javascript
* var injector = Injector.resolveAndCreate([
* new Binding(Number, { toFactory: () => { return 1+2; }}),
* new Binding(String, { toFactory: (value) => { return "Value: " + value; },
* dependencies: [Number] })
* ]);
*
* expect(injector.get(Number)).toEqual(3);
* expect(injector.get(String)).toEqual('Value: 3');
* ```
*/
dependencies: List<any>;
/**
* Converts the {@link Binding} into {@link ResolvedBinding}.
*
* {@link Injector} internally only uses {@link ResolvedBinding}, {@link Binding} contains
* convenience binding syntax.
*/
resolve(): ResolvedBinding;
}
/**
* Helper class for the {@link bind} function.
*/
class BindingBuilder {
token: void;
/**
* Binds an interface to an implementation / subclass.
*
* ## Example
*
* Because `toAlias` and `toClass` are often confused, the example contains both use cases for
* easy comparison.
*
* ```javascript
*
* class Vehicle {}
*
* class Car extends Vehicle {}
*
* var injectorClass = Injector.resolveAndCreate([
* Car,
* bind(Vehicle).toClass(Car)
* ]);
* var injectorAlias = Injector.resolveAndCreate([
* Car,
* bind(Vehicle).toAlias(Car)
* ]);
*
* expect(injectorClass.get(Vehicle)).not.toBe(injectorClass.get(Car));
* expect(injectorClass.get(Vehicle) instanceof Car).toBe(true);
*
* expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car));
* expect(injectorAlias.get(Vehicle) instanceof Car).toBe(true);
* ```
*/
toClass(type: Type): Binding;
/**
* Binds a key to a value.
*
* ## Example
*
* ```javascript
* var injector = Injector.resolveAndCreate([
* bind(String).toValue('Hello')
* ]);
*
* expect(injector.get(String)).toEqual('Hello');
* ```
*/
toValue(value: any): Binding;
/**
* Binds a key to the alias for an existing key.
*
* An alias means that we will return the same instance as if the alias token was used. (This is
* in contrast to `toClass` where a separate instance of `toClass` will be returned.)
*
* ## Example
*
* Becuse `toAlias` and `toClass` are often confused, the example contains both use cases for easy
* comparison.
*
* ```javascript
*
* class Vehicle {}
*
* class Car extends Vehicle {}
*
* var injectorAlias = Injector.resolveAndCreate([
* Car,
* bind(Vehicle).toAlias(Car)
* ]);
* var injectorClass = Injector.resolveAndCreate([
* Car,
* bind(Vehicle).toClass(Car)
* ]);
*
* expect(injectorAlias.get(Vehicle)).toBe(injectorAlias.get(Car));
* expect(injectorAlias.get(Vehicle) instanceof Car).toBe(true);
*
* expect(injectorClass.get(Vehicle)).not.toBe(injectorClass.get(Car));
* expect(injectorClass.get(Vehicle) instanceof Car).toBe(true);
* ```
*/
toAlias(aliasToken: /*Type*/ any): Binding;
/**
* Binds a key to a function which computes the value.
*
* ## Example
*
* ```javascript
* var injector = Injector.resolveAndCreate([
* bind(Number).toFactory(() => { return 1+2; }),
* bind(String).toFactory((v) => { return "Value: " + v; }, [Number])
* ]);
*
* expect(injector.get(Number)).toEqual(3);
* expect(injector.get(String)).toEqual('Value: 3');
* ```
*/
toFactory(factoryFunction: Function, dependencies?: List<any>): Binding;
}
/**
* An internal resolved representation of a {@link Binding} used by the {@link Injector}.
*
* A {@link Binding} is resolved when it has a factory function. Binding to a class, alias, or
* value, are just convenience methods, as {@link Injector} only operates on calling factory
* functions.
*/
class ResolvedBinding {
/**
* A key, usually a `Type`.
*/
key: Key;
/**
* Factory function which can return an instance of an object represented by a key.
*/
factory: Function;
/**
* Arguments (dependencies) to the `factory` function.
*/
dependencies: List<Dependency>;
}
/**
* @private
*/
class Dependency {
key: Key;
optional: boolean;
lowerBoundVisibility: any;
upperBoundVisibility: any;
properties: List<any>;
}
/**
* Provides an API for imperatively constructing {@link Binding}s.
*
* This is only relevant for JavaScript. See {@link BindingBuilder}.
*
* ## Example
*
* ```javascript
* bind(MyInterface).toClass(MyClass)
*
* ```
*/
function bind(token: any) : BindingBuilder ;
/**
* A unique object used for retrieving items from the {@link Injector}.
*
* Keys have:
* - a system-wide unique `id`.
* - a `token`, usually the `Type` of the instance.
*
* Keys are used internally by the {@link Injector} because their system-wide unique `id`s allow the
* injector to index in arrays rather than looking up items in maps.
*/
interface Key {
token: Object;
id: number;
displayName: string;
}
/**
* @private
*/
class KeyRegistry {
get(token: Object): Key;
numberOfKeys: number;
}
/**
* Type literals is a Dart-only feature. This is here only so we can x-compile
* to multiple languages.
*/
class TypeLiteral {
type: any;
}
/**
* Thrown when trying to retrieve a dependency by `Key` from {@link Injector}, but the
* {@link Injector} does not have a {@link Binding} for {@link Key}.
*/
class NoBindingError extends AbstractBindingError {
}
/**
* Base class for all errors arising from misconfigured bindings.
*/
class AbstractBindingError extends BaseException {
name: string;
message: string;
keys: List<Key>;
injectors: List<Injector>;
constructResolvingMessage: Function;
addKey(injector: Injector, key: Key): void;
context: void;
toString(): string;
}
/**
* Thrown when dependencies form a cycle.
*
* ## Example:
*
* ```javascript
* class A {
* constructor(b:B) {}
* }
* class B {
* constructor(a:A) {}
* }
* ```
*
* Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed.
*/
class CyclicDependencyError extends AbstractBindingError {
}
/**
* Thrown when a constructing type returns with an Error.
*
* The `InstantiationError` class contains the original error plus the dependency graph which caused
* this object to be instantiated.
*/
class InstantiationError extends AbstractBindingError {
causeKey: Key;
}
/**
* Thrown when an object other then {@link Binding} (or `Type`) is passed to {@link Injector}
* creation.
*/
class InvalidBindingError extends BaseException {
message: string;
toString(): string;
}
/**
* Thrown when the class has no annotation information.
*
* Lack of annotation information prevents the {@link Injector} from determining which dependencies
* need to be injected into the constructor.
*/
class NoAnnotationError extends BaseException {
name: string;
message: string;
toString(): string;
}
/**
* Thrown when getting an object by index.
*/
class OutOfBoundsError extends BaseException {
message: string;
toString(): string;
}
class OpaqueToken {
toString(): string;
}
/**
* Factory for creating {@link InjectMetadata}.
*/
interface InjectFactory {
new(token: any): InjectMetadata;
(token: any): any;
}
/**
* Factory for creating {@link OptionalMetadata}.
*/
interface OptionalFactory {
new(): OptionalMetadata;
(): any;
}
/**
* Factory for creating {@link InjectableMetadata}.
*/
interface InjectableFactory {
new(): InjectableMetadata;
(): any;
}
/**
* Factory for creating {@link SelfMetadata}.
*/
interface SelfFactory {
new(): SelfMetadata;
(): any;
}
/**
* Factory for creating {@link HostMetadata}.
*/
interface HostFactory {
new(): HostMetadata;
(): any;
}
/**
* Factory for creating {@link SkipSelfMetadata}.
*/
interface SkipSelfFactory {
new(): SkipSelfMetadata;
(): any;
}
/**
* Factory for creating {@link InjectMetadata}.
*/
var Inject : InjectFactory ;
/**
* Factory for creating {@link OptionalMetadata}.
*/
var Optional : OptionalFactory ;
/**
* Factory for creating {@link InjectableMetadata}.
*/
var Injectable : InjectableFactory ;
/**
* Factory for creating {@link SelfMetadata}.
*/
var Self : SelfFactory ;
/**
* Factory for creating {@link HostMetadata}.
*/
var Host : HostFactory ;
/**
* Factory for creating {@link SkipSelfMetadata}.
*/
var SkipSelf : SkipSelfFactory ;
/**
* A collection of the Angular core directives that are likely to be used in each and every Angular
* application.
*
* This collection can be used to quickly enumerate all the built-in directives in the `@View`
* annotation. For example,
* instead of writing:
*
* ```
* import {If, NgFor, NgSwitch, NgSwitchWhen, NgSwitchDefault} from 'angular2/angular2';
* import {OtherDirective} from 'myDirectives';
*
* @Component({
* selector: 'my-component'
* })
* @View({
* templateUrl: 'myComponent.html',
* directives: [If, NgFor, NgSwitch, NgSwitchWhen, NgSwitchDefault, OtherDirective]
* })
* export class MyComponent {
* ...
* }
* ```
* one could enumerate all the core directives at once:
*
* ```
* import {coreDirectives} from 'angular2/angular2';
* import {OtherDirective} from 'myDirectives';
*
* @Component({
* selector: 'my-component'
* })
* @View({
* templateUrl: 'myComponent.html',
* directives: [coreDirectives, OtherDirective]
* })
* export class MyComponent {
* ...
* }
* ```
*/
const coreDirectives : List<Type> ;
/**
* Adds and removes CSS classes based on an {expression} value.
*
* The result of expression is used to add and remove CSS classes using the following logic,
* based on expression's value type:
* - {string} - all the CSS classes (space - separated) are added
* - {Array} - all the CSS classes (Array elements) are added
* - {Object} - each key corresponds to a CSS class name while values
* are interpreted as {boolean} expression. If a given expression
* evaluates to {true} a corresponding CSS class is added - otherwise
* it is removed.
*
* # Example:
*
* ```
* <div class="message" [class]="{error: errorCount > 0}">
* Please check errors.
* </div>
* ```
*/
class CSSClass {
rawClass: void;
onCheck(): void;
onDestroy(): void;
}
/**
* The `NgFor` directive instantiates a template once per item from an iterable. The context for
* each instantiated template inherits from the outer context with the given loop variable set
* to the current item from the iterable.
*
* It is possible to alias the `index` to a local variable that will be set to the current loop
* iteration in the template context.
*
* When the contents of the iterator changes, `NgFor` makes the corresponding changes to the DOM:
*
* * When an item is added, a new instance of the template is added to the DOM.
* * When an item is removed, its template instance is removed from the DOM.
* * When items are reordered, their respective templates are reordered in the DOM.
*
* # Example
*
* ```
* <ul>
* <li *ng-for="#error of errors; #i = index">
* Error {{i}} of {{errors.length}}: {{error.message}}
* </li>
* </ul>
* ```
*
* # Syntax
*
* - `<li *ng-for="#item of items; #i = index">...</li>`
* - `<li template="ng-for #item of items; #i = index">...</li>`
* - `<template ng-for #item [ng-for-of]="items" #i="index"><li>...</li></template>`
*/
class NgFor {
viewContainer: ViewContainerRef;
templateRef: TemplateRef;
iterableDiffers: IterableDiffers;
cdr: ChangeDetectorRef;
ngForOf: void;
onCheck(): void;
}
class RecordViewTuple {
view: ViewRef;
record: any;
}
/**
* Removes or recreates a portion of the DOM tree based on an {expression}.
*
* If the expression assigned to `ng-if` evaluates to a false value then the element
* is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.
*
* # Example:
*
* ```
* <div *ng-if="errorCount > 0" class="error">
* <!-- Error message displayed when the errorCount property on the current context is greater
* than 0. -->
* {{errorCount}} errors detected
* </div>
* ```
*
* # Syntax
*
* - `<div *ng-if="condition">...</div>`
* - `<div template="ng-if condition">...</div>`
* - `<template [ng-if]="condition"><div>...</div></template>`
*/
class NgIf {
viewContainer: ViewContainerRef;
templateRef: TemplateRef;
prevCondition: boolean;
ngIf: void;
}
/**
* The `NgNonBindable` directive tells Angular not to compile or bind the contents of the current
* DOM element. This is useful if the element contains what appears to be Angular directives and
* bindings but which should be ignored by Angular. This could be the case if you have a site that
* displays snippets of code, for instance.
*
* Example:
*
* ```
* <div>Normal: {{1 + 2}}</div> // output "Normal: 3"
* <div non-bindable>Ignored: {{1 + 2}}</div> // output "Ignored: {{1 + 2}}"
* ```
*/
class NgNonBindable {
}
/**
* Adds or removes styles based on an {expression}.
*
* When the expression assigned to `ng-style` evaluates to an object, the corresponding element
* styles are updated. Style names to update are taken from the object keys and values - from the
* corresponding object values.
*
* # Example:
*
* ```
* <div ng-style="{'text-align': alignEpr}"></div>
* ```
*
* In the above example the `text-align` style will be updated based on the `alignEpr` value
* changes.
*
* # Syntax
*
* - `<div ng-style="{'text-align': alignEpr}"></div>`
* - `<div ng-style="styleExp"></div>`
*/
class NgStyle {
rawStyle: void;
onCheck(): void;
}
class SwitchView {
create(): void;
destroy(): void;
}
/**
* The `NgSwitch` directive is used to conditionally swap DOM structure on your template based on a
* scope expression.
* Elements within `NgSwitch` but without `NgSwitchWhen` or `NgSwitchDefault` directives will be
* preserved at the location as specified in the template.
*
* `NgSwitch` simply chooses nested elements and makes them visible based on which element matches
* the value obtained from the evaluated expression. In other words, you define a container element
* (where you place the directive), place an expression on the **`[ng-switch]="..."` attribute**),
* define any inner elements inside of the directive and place a `[ng-switch-when]` attribute per
* element.
* The when attribute is used to inform NgSwitch which element to display when the expression is
* evaluated. If a matching expression is not found via a when attribute then an element with the
* default attribute is displayed.
*
* # Example:
*
* ```
* <ANY [ng-switch]="expression">
* <template [ng-switch-when]="whenExpression1">...</template>
* <template [ng-switch-when]="whenExpression1">...</template>
* <template ng-switch-default>...</template>
* </ANY>
* ```
*/
class NgSwitch {
ngSwitch: void;
}
/**
* Defines a case statement as an expression.
*
* If multiple `NgSwitchWhen` match the `NgSwitch` value, all of them are displayed.
*
* Example:
*
* ```
* // match against a context variable
* <template [ng-switch-when]="contextVariable">...</template>
*
* // match against a constant string
* <template ng-switch-when="stringValue">...</template>
* ```
*/
class NgSwitchWhen {
onDestroy(): void;
ngSwitchWhen: void;
}
/**
* Defines a default case statement.
*
* Default case statements are displayed when no `NgSwitchWhen` match the `ng-switch` value.
*
* Example:
*
* ```
* <template ng-switch-default>...</template>
* ```
*/
class NgSwitchDefault {
}
/**
* Mock Connection to represent a {@link Connection} for tests.
*/
class MockConnection {
/**
* Describes the state of the connection, based on `XMLHttpRequest.readyState`, but with
* additional states. For example, state 5 indicates an aborted connection.
*/
readyState: ReadyStates;
/**
* {@link Request} instance used to create the connection.
*/
request: Request;
/**
* {@link EventEmitter} of {@link Response}. Can be subscribed to in order to be notified when a
* response is available.
*/
response: EventEmitter;
/**
* Changes the `readyState` of the connection to a custom state of 5 (cancelled).
*/
dispose(): void;
/**
* Sends a mock response to the connection. This response is the value that is emitted to the
* {@link EventEmitter} returned by {@link Http}.
*
* #Example
*
* ```
* var connection;
* backend.connections.subscribe(c => connection = c);
* http.request('data.json').subscribe(res => console.log(res.text()));
* connection.mockRespond(new Response('fake response')); //logs 'fake response'
* ```
*/
mockRespond(res: Response): void;
/**
* Not yet implemented!
*
* Sends the provided {@link Response} to the `downloadObserver` of the `Request`
* associated with this connection.
*/
mockDownload(res: Response): void;
/**
* Emits the provided error object as an error to the {@link Response} {@link EventEmitter}
* returned
* from {@link Http}.
*/
mockError(err?: Error): void;
}
/**
* A mock backend for testing the {@link Http} service.
*
* This class can be injected in tests, and should be used to override bindings
* to other backends, such as {@link XHRBackend}.
*
* #Example
*
* ```
* import {MockBackend, DefaultOptions, Http} from 'angular2/http';
* it('should get some data', inject([AsyncTestCompleter], (async) => {
* var connection;
* var injector = Injector.resolveAndCreate([
* MockBackend,
* bind(Http).toFactory((backend, defaultOptions) => {
* return new Http(backend, defaultOptions)
* }, [MockBackend, DefaultOptions])]);
* var http = injector.get(Http);
* var backend = injector.get(MockBackend);
* //Assign any newly-created connection to local variable
* backend.connections.subscribe(c => connection = c);
* http.request('data.json').subscribe((res) => {
* expect(res.text()).toBe('awesome');
* async.done();
* });
* connection.mockRespond(new Response('awesome'));
* }));
* ```
*
* This method only exists in the mock implementation, not in real Backends.
*/
class MockBackend {
/**
* {@link EventEmitter}
* of {@link MockConnection} instances that have been created by this backend. Can be subscribed
* to in order to respond to connections.
*
* #Example
*
* ```
* import {MockBackend, Http, BaseRequestOptions} from 'angular2/http';
* import {Injector} from 'angular2/di';
*
* it('should get a response', () => {
* var connection; //this will be set when a new connection is emitted from the backend.
* var text; //this will be set from mock response
* var injector = Injector.resolveAndCreate([
* MockBackend,
* bind(Http).toFactory(backend, options) {
* return new Http(backend, options);
* }, [MockBackend, BaseRequestOptions]]);
* var backend = injector.get(MockBackend);
* var http = injector.get(Http);
* backend.connections.subscribe(c => connection = c);
* http.request('something.json').subscribe(res => {
* text = res.text();
* });
* connection.mockRespond(new Response({body: 'Something'}));
* expect(text).toBe('Something');
* });
* ```
*
* This property only exists in the mock implementation, not in real Backends.
*/
connections: EventEmitter;
/**
* An array representation of `connections`. This array will be updated with each connection that
* is created by this backend.
*
* This property only exists in the mock implementation, not in real Backends.
*/
connectionsArray: Array<MockConnection>;
/**
* {@link EventEmitter} of {@link MockConnection} instances that haven't yet been resolved (i.e.
* with a `readyState`
* less than 4). Used internally to verify that no connections are pending via the
* `verifyNoPendingRequests` method.
*
* This property only exists in the mock implementation, not in real Backends.
*/
pendingConnections: EventEmitter;
/**
* Checks all connections, and raises an exception if any connection has not received a response.
*
* This method only exists in the mock implementation, not in real Backends.
*/
verifyNoPendingRequests(): void;
/**
* Can be used in conjunction with `verifyNoPendingRequests` to resolve any not-yet-resolve
* connections, if it's expected that there are connections that have not yet received a response.
*
* This method only exists in the mock implementation, not in real Backends.
*/
resolveAllConnections(): void;
/**
* Creates a new {@link MockConnection}. This is equivalent to calling `new
* MockConnection()`, except that it also will emit the new `Connection` to the `connections`
* emitter of this `MockBackend` instance. This method will usually only be used by tests
* against the framework itself, not by end-users.
*/
createConnection(req: Request): Connection;
}
/**
* Creates `Request` instances from provided values.
*
* The Request's interface is inspired by the Request constructor defined in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#request-class),
* but is considered a static value whose body can be accessed many times. There are other
* differences in the implementation, but this is the most significant.
*/
class Request {
/**
* Http method with which to perform the request.
*
* Defaults to GET.
*/
method: RequestMethods;
mode: RequestModesOpts;
credentials: RequestCredentialsOpts;
/**
* Headers object based on the `Headers` class in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#headers-class). {@link Headers} class reference.
*/
headers: Headers;
/**
* Url of the remote resource
*/
url: string;
cache: RequestCacheOpts;
/**
* Returns the request's body as string, assuming that body exists. If body is undefined, return
* empty
* string.
*/
text(): String;
}
/**
* Creates `Response` instances from provided values.
*
* Though this object isn't
* usually instantiated by end-users, it is the primary object interacted with when it comes time to
* add data to a view.
*
* #Example
*
* ```
* http.request('my-friends.txt').subscribe(response => this.friends = response.text());
* ```
*
* The Response's interface is inspired by the Response constructor defined in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#response-class), but is considered a static value whose body
* can be accessed many times. There are other differences in the implementation, but this is the
* most significant.
*/
class Response {
/**
* One of "basic", "cors", "default", "error, or "opaque".
*
* Defaults to "default".
*/
type: ResponseTypes;
/**
* True if the response's status is within 200-299
*/
ok: boolean;
/**
* URL of response.
*
* Defaults to empty string.
*/
url: string;
/**
* Status code returned by server.
*
* Defaults to 200.
*/
status: number;
/**
* Text representing the corresponding reason phrase to the `status`, as defined in [ietf rfc 2616
* section 6.1.1](https://tools.ietf.org/html/rfc2616#section-6.1.1)
*
* Defaults to "OK"
*/
statusText: string;
/**
* Non-standard property
*
* Denotes how many of the response body's bytes have been loaded, for example if the response is
* the result of a progress event.
*/
bytesLoaded: number;
/**
* Non-standard property
*
* Denotes how many bytes are expected in the final response body.
*/
totalBytes: number;
/**
* Headers object based on the `Headers` class in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#headers-class).
*/
headers: Headers;
/**
* Not yet implemented
*/
blob(): any;
/**
* Attempts to return body as parsed `JSON` object, or raises an exception.
*/
json(): Object;
/**
* Returns the body as a string, presuming `toString()` can be called on the response body.
*/
text(): string;
/**
* Not yet implemented
*/
arrayBuffer(): any;
}
/**
* Interface for options to construct a Request, based on
* [RequestInit](https://fetch.spec.whatwg.org/#requestinit) from the Fetch spec.
*/
interface IRequestOptions {
url?: string;
method?: RequestMethods;
headers?: Headers;
body?: string;
mode?: RequestModesOpts;
credentials?: RequestCredentialsOpts;
cache?: RequestCacheOpts;
}
/**
* Interface for options to construct a Response, based on
* [ResponseInit](https://fetch.spec.whatwg.org/#responseinit) from the Fetch spec.
*/
interface IResponseOptions {
body?: string | Object | FormData;
status?: number;
statusText?: string;
headers?: Headers;
type?: ResponseTypes;
url?: string;
}
/**
* Abstract class from which real connections are derived.
*/
class Connection {
readyState: ReadyStates;
request: Request;
response: EventEmitter;
dispose(): void;
}
/**
* Abstract class from which real backends are derived.
*
* The primary purpose of a `ConnectionBackend` is to create new connections to fulfill a given
* {@link Request}.
*/
class ConnectionBackend {
createConnection(request: any): Connection;
}
class BrowserXhr {
build(): any;
}
/**
* Injectable version of {@link RequestOptions}, with overridable default values.
*
* #Example
*
* ```
* import {Http, BaseRequestOptions, Request} from 'angular2/http';
* ...
* class MyComponent {
* constructor(baseRequestOptions:BaseRequestOptions, http:Http) {
* var options = baseRequestOptions.merge({body: 'foobar', url: 'https://foo'});
* var request = new Request(options);
* http.request(request).subscribe(res => this.bars = res.json());
* }
* }
*
* ```
*/
class BaseRequestOptions extends RequestOptions {
}
/**
* Creates a request options object similar to the `RequestInit` description
* in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#requestinit) to be optionally provided when instantiating a
* {@link Request}.
*
* All values are null by default.
*/
class RequestOptions implements IRequestOptions {
/**
* Http method with which to execute the request.
*
* Defaults to "GET".
*/
method: RequestMethods;
/**
* Headers object based on the `Headers` class in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#headers-class).
*/
headers: Headers;
/**
* Body to be used when creating the request.
*/
body: string;
mode: RequestModesOpts;
credentials: RequestCredentialsOpts;
cache: RequestCacheOpts;
url: string;
/**
* Creates a copy of the `RequestOptions` instance, using the optional input as values to override
* existing values.
*/
merge(options?: IRequestOptions): RequestOptions;
}
/**
* Injectable version of {@link ResponseOptions}, with overridable default values.
*/
class BaseResponseOptions extends ResponseOptions {
body: string | Object | ArrayBuffer | JSON | FormData | Blob;
status: number;
headers: Headers;
statusText: string;
type: ResponseTypes;
url: string;
}
/**
* Creates a response options object similar to the
* [ResponseInit](https://fetch.spec.whatwg.org/#responseinit) description
* in the Fetch
* Spec to be optionally provided when instantiating a
* {@link Response}.
*
* All values are null by default.
*/
class ResponseOptions implements IResponseOptions {
body: string | Object;
status: number;
headers: Headers;
statusText: string;
type: ResponseTypes;
url: string;
merge(options?: IResponseOptions): ResponseOptions;
}
/**
* Creates {@link XHRConnection} instances.
*
* This class would typically not be used by end users, but could be
* overridden if a different backend implementation should be used,
* such as in a node backend.
*
* #Example
*
* ```
* import {Http, MyNodeBackend, httpInjectables, BaseRequestOptions} from 'angular2/http';
* @Component({
* viewBindings: [
* httpInjectables,
* bind(Http).toFactory((backend, options) => {
* return new Http(backend, options);
* }, [MyNodeBackend, BaseRequestOptions])]
* })
* class MyComponent {
* constructor(http:Http) {
* http('people.json').subscribe(res => this.people = res.json());
* }
* }
* ```
*/
class XHRBackend implements ConnectionBackend {
createConnection(request: Request): XHRConnection;
}
/**
* Creates connections using `XMLHttpRequest`. Given a fully-qualified
* request, an `XHRConnection` will immediately create an `XMLHttpRequest` object and send the
* request.
*
* This class would typically not be created or interacted with directly inside applications, though
* the {@link MockConnection} may be interacted with in tests.
*/
class XHRConnection implements Connection {
request: Request;
/**
* Response {@link EventEmitter} which emits a single {@link Response} value on load event of
* `XMLHttpRequest`.
*/
response: EventEmitter;
readyState: ReadyStates;
/**
* Calls abort on the underlying XMLHttpRequest.
*/
dispose(): void;
}
class JSONPBackend implements ConnectionBackend {
createConnection(request: Request): JSONPConnection;
}
class JSONPConnection implements Connection {
readyState: ReadyStates;
request: Request;
response: EventEmitter;
baseResponseOptions: ResponseOptions;
finished(data?: any): void;
dispose(): void;
}
/**
* Performs http requests using `XMLHttpRequest` as the default backend.
*
* `Http` is available as an injectable class, with methods to perform http requests. Calling
* `request` returns an {@link EventEmitter} which will emit a single {@link Response} when a
* response is received.
*
*
* ## Breaking Change
*
* Previously, methods of `Http` would return an RxJS Observable directly. For now,
* the `toRx()` method of {@link EventEmitter} needs to be called in order to get the RxJS
* Subject. `EventEmitter` does not provide combinators like `map`, and has different semantics for
* subscribing/observing. This is temporary; the result of all `Http` method calls will be either an
* Observable
* or Dart Stream when [issue #2794](https://github.com/angular/angular/issues/2794) is resolved.
*
* #Example
*
* ```
* import {Http, httpInjectables} from 'angular2/http';
* @Component({selector: 'http-app', viewBindings: [httpInjectables]})
* @View({templateUrl: 'people.html'})
* class PeopleComponent {
* constructor(http: Http) {
* http.get('people.json')
* //Get the RxJS Subject
* .toRx()
* // Call map on the response observable to get the parsed people object
* .map(res => res.json())
* // Subscribe to the observable to get the parsed people object and attach it to the
* // component
* .subscribe(people => this.people = people);
* }
* }
* ```
*
* To use the {@link EventEmitter} returned by `Http`, simply pass a generator (See "interface
* Generator" in the Async Generator spec: https://github.com/jhusain/asyncgenerator) to the
* `observer` method of the returned emitter, with optional methods of `next`, `throw`, and `return`.
*
* #Example
*
* ```
* http.get('people.json').observer({next: (value) => this.people = people});
* ```
*
* The default construct used to perform requests, `XMLHttpRequest`, is abstracted as a "Backend" (
* {@link XHRBackend} in this case), which could be mocked with dependency injection by replacing
* the {@link XHRBackend} binding, as in the following example:
*
* #Example
*
* ```
* import {MockBackend, BaseRequestOptions, Http} from 'angular2/http';
* var injector = Injector.resolveAndCreate([
* BaseRequestOptions,
* MockBackend,
* bind(Http).toFactory(
* function(backend, defaultOptions) {
* return new Http(backend, defaultOptions);
* },
* [MockBackend, BaseRequestOptions])
* ]);
* var http = injector.get(Http);
* http.get('request-from-mock-backend.json').toRx().subscribe((res:Response) => doSomething(res));
* ```
*/
class Http {
/**
* Performs any type of http request. First argument is required, and can either be a url or
* a {@link Request} instance. If the first argument is a url, an optional {@link RequestOptions}
* object can be provided as the 2nd argument. The options object will be merged with the values
* of {@link BaseRequestOptions} before performing the request.
*/
request(url: string | Request, options?: IRequestOptions): EventEmitter;
/**
* Performs a request with `get` http method.
*/
get(url: string, options?: IRequestOptions): EventEmitter;
/**
* Performs a request with `post` http method.
*/
post(url: string, body: string, options?: IRequestOptions): EventEmitter;
/**
* Performs a request with `put` http method.
*/
put(url: string, body: string, options?: IRequestOptions): EventEmitter;
/**
* Performs a request with `delete` http method.
*/
delete(url: string, options?: IRequestOptions): EventEmitter;
/**
* Performs a request with `patch` http method.
*/
patch(url: string, body: string, options?: IRequestOptions): EventEmitter;
/**
* Performs a request with `head` http method.
*/
head(url: string, options?: IRequestOptions): EventEmitter;
}
class Jsonp extends Http {
/**
* Performs any type of http request. First argument is required, and can either be a url or
* a {@link Request} instance. If the first argument is a url, an optional {@link RequestOptions}
* object can be provided as the 2nd argument. The options object will be merged with the values
* of {@link BaseRequestOptions} before performing the request.
*/
request(url: string | Request, options?: IRequestOptions): EventEmitter;
}
/**
* Polyfill for [Headers](https://developer.mozilla.org/en-US/docs/Web/API/Headers/Headers), as
* specified in the [Fetch Spec](https://fetch.spec.whatwg.org/#headers-class). The only known
* difference from the spec is the lack of an `entries` method.
*/
class Headers {
/**
* Appends a header to existing list of header values for a given header name.
*/
append(name: string, value: string): void;
/**
* Deletes all header values for the given name.
*/
delete(name: string): void;
forEach(fn: Function): void;
/**
* Returns first header that matches given name.
*/
get(header: string): string;
/**
* Check for existence of header by given name.
*/
has(header: string): boolean;
/**
* Provides names of set headers
*/
keys(): List<string>;
/**
* Sets or overrides header value for given name.
*/
set(header: string, value: string | List<string>): void;
/**
* Returns values of all headers.
*/
values(): List<List<string>>;
/**
* Returns list of header values for a given name.
*/
getAll(header: string): Array<string>;
/**
* This method is not implemented.
*/
entries(): void;
}
/**
* Acceptable response types to be associated with a {@link Response}, based on
* [ResponseType](https://fetch.spec.whatwg.org/#responsetype) from the Fetch spec.
*/
enum ResponseTypes {
Basic,
Cors,
Default,
Error,
Opaque
}
/**
* All possible states in which a connection can be, based on
* [States](http://www.w3.org/TR/XMLHttpRequest/#states) from the `XMLHttpRequest` spec, but with an
* additional "CANCELLED" state.
*/
enum ReadyStates {
UNSENT,
OPEN,
HEADERS_RECEIVED,
LOADING,
DONE,
CANCELLED
}
/**
* Supported http methods.
*/
enum RequestMethods {
GET,
POST,
PUT,
DELETE,
OPTIONS,
HEAD,
PATCH
}
/**
* Acceptable credentials option to be associated with a {@link Request}, based on
* [RequestCredentials](https://fetch.spec.whatwg.org/#requestcredentials) from the Fetch spec.
*/
enum RequestCredentialsOpts {
Omit,
SameOrigin,
Include
}
/**
* Acceptable cache option to be associated with a {@link Request}, based on
* [RequestCache](https://fetch.spec.whatwg.org/#requestcache) from the Fetch spec.
*/
enum RequestCacheOpts {
Default,
NoStore,
Reload,
NoCache,
ForceCache,
OnlyIfCached
}
/**
* Acceptable origin modes to be associated with a {@link Request}, based on
* [RequestMode](https://fetch.spec.whatwg.org/#requestmode) from the Fetch spec.
*/
enum RequestModesOpts {
Cors,
NoCors,
SameOrigin
}
/**
* Map-like representation of url search parameters, based on
* [URLSearchParams](https://url.spec.whatwg.org/#urlsearchparams) in the url living standard.
*/
class URLSearchParams {
paramsMap: Map<string, List<string>>;
rawParams: string;
has(param: string): boolean;
get(param: string): string;
getAll(param: string): List<string>;
append(param: string, val: string): void;
toString(): string;
delete(param: string): void;
}
/**
* Provides a basic set of injectables to use the {@link Http} service in any application.
*
* #Example
*
* ```
* import {httpInjectables, Http} from 'angular2/http';
* @Component({selector: 'http-app', viewBindings: [httpInjectables]})
* @View({template: '{{data}}'})
* class MyApp {
* constructor(http:Http) {
* http.request('data.txt').subscribe(res => this.data = res.text());
* }
* }
* ```
*/
var httpInjectables : List<any> ;
var jsonpInjectables : List<any> ;
/**
* Omitting from external API doc as this is really an abstract internal concept.
*/
class AbstractControl {
validator: Function;
value: any;
status: string;
valid: boolean;
errors: StringMap<string, any>;
pristine: boolean;
dirty: boolean;
touched: boolean;
untouched: boolean;
valueChanges: Observable;
markAsTouched(): void;
markAsDirty({onlySelf}?: {onlySelf?: boolean}): void;
setParent(parent: ControlGroup | ControlArray): void;
updateValidity({onlySelf}?: {onlySelf?: boolean}): void;
updateValueAndValidity({onlySelf, emitEvent}?: {onlySelf?: boolean, emitEvent?: boolean}): void;
find(path: List<string | number>| string): AbstractControl;
getError(errorCode: string, path?: List<string>): any;
hasError(errorCode: string, path?: List<string>): boolean;
}
/**
* Defines a part of a form that cannot be divided into other controls.
*
* `Control` is one of the three fundamental building blocks used to define forms in Angular, along
* with
* {@link ControlGroup} and {@link ControlArray}.
*/
class Control extends AbstractControl {
updateValue(value: any, {onlySelf, emitEvent, emitModelToViewChange}?:
{onlySelf?: boolean, emitEvent?: boolean, emitModelToViewChange?: boolean}): void;
registerOnChange(fn: Function): void;
}
/**
* Defines a part of a form, of fixed length, that can contain other controls.
*
* A ControlGroup aggregates the values and errors of each {@link Control} in the group. Thus, if
* one of the controls
* in a group is invalid, the entire group is invalid. Similarly, if a control changes its value,
* the entire group
* changes as well.
*
* `ControlGroup` is one of the three fundamental building blocks used to define forms in Angular,
* along with
* {@link Control} and {@link ControlArray}. {@link ControlArray} can also contain other controls,
* but is of variable
* length.
*/
class ControlGroup extends AbstractControl {
controls: StringMap<string, AbstractControl>;
addControl(name: string, c: AbstractControl): void;
removeControl(name: string): void;
include(controlName: string): void;
exclude(controlName: string): void;
contains(controlName: string): boolean;
}
/**
* Defines a part of a form, of variable length, that can contain other controls.
*
* A `ControlArray` aggregates the values and errors of each {@link Control} in the group. Thus, if
* one of the controls
* in a group is invalid, the entire group is invalid. Similarly, if a control changes its value,
* the entire group
* changes as well.
*
* `ControlArray` is one of the three fundamental building blocks used to define forms in Angular,
* along with {@link Control} and {@link ControlGroup}. {@link ControlGroup} can also contain
* other controls, but is of fixed length.
*/
class ControlArray extends AbstractControl {
controls: List<AbstractControl>;
at(index: number): AbstractControl;
push(control: AbstractControl): void;
insert(index: number, control: AbstractControl): void;
removeAt(index: number): void;
length: number;
}
class AbstractControlDirective {
control: AbstractControl;
value: any;
valid: boolean;
errors: StringMap<string, any>;
pristine: boolean;
dirty: boolean;
touched: boolean;
untouched: boolean;
}
/**
* An interface that {@link NgFormModel} and {@link NgForm} implement.
*
* Only used by the forms module.
*/
interface Form {
addControl(dir: NgControl): void;
removeControl(dir: NgControl): void;
getControl(dir: NgControl): Control;
addControlGroup(dir: NgControlGroup): void;
removeControlGroup(dir: NgControlGroup): void;
getControlGroup(dir: NgControlGroup): ControlGroup;
updateModel(dir: NgControl, value: any): void;
}
/**
* A directive that contains a group of [NgControl].
*
* Only used by the forms module.
*/
class ControlContainer extends AbstractControlDirective {
name: string;
formDirective: Form;
path: List<string>;
}
/**
* Creates and binds a control with a specified name to a DOM element.
*
* This directive can only be used as a child of {@link NgForm} or {@link NgFormModel}.
*
* # Example
*
* In this example, we create the login and password controls.
* We can work with each control separately: check its validity, get its value, listen to its
* changes.
*
* ```
* @Component({selector: "login-comp"})
* @View({
* directives: [formDirectives],
* template: `
* <form #f="form" (submit)='onLogIn(f.value)'>
* Login <input type='text' ng-control='login' #l="form">
* <div *ng-if="!l.valid">Login is invalid</div>
*
* Password <input type='password' ng-control='password'>
*
* <button type='submit'>Log in!</button>
* </form>
* `})
* class LoginComp {
* onLogIn(value) {
* // value === {login: 'some login', password: 'some password'}
* }
* }
* ```
*
* We can also use ng-model to bind a domain model to the form.
*
* ```
* @Component({selector: "login-comp"})
* @View({
* directives: [formDirectives],
* template: `
* <form (submit)='onLogIn()'>
* Login <input type='text' ng-control='login' [(ng-model)]="credentials.login">
* Password <input type='password' ng-control='password'
* [(ng-model)]="credentials.password">
* <button type='submit'>Log in!</button>
* </form>
* `})
* class LoginComp {
* credentials: {login:string, password:string};
*
* onLogIn() {
* // this.credentials.login === "some login"
* // this.credentials.password === "some password"
* }
* }
* ```
*/
class NgControlName extends NgControl {
update: void;
model: any;
viewModel: any;
ngValidators: QueryList<NgValidator>;
onChange(c: StringMap<string, any>): void;
onDestroy(): void;
viewToModelUpdate(newValue: any): void;
path: List<string>;
formDirective: any;
control: Control;
validator: Function;
}
/**
* Binds an existing control to a DOM element.
*
* # Example
*
* In this example, we bind the control to an input element. When the value of the input element
* changes, the value of
* the control will reflect that change. Likewise, if the value of the control changes, the input
* element reflects that
* change.
*
* ```
* @Component({selector: "login-comp"})
* @View({
* directives: [formDirectives],
* template: "<input type='text' [ng-form-control]='loginControl'>"
* })
* class LoginComp {
* loginControl:Control;
*
* constructor() {
* this.loginControl = new Control('');
* }
* }
*
* ```
*
* We can also use ng-model to bind a domain model to the form.
*
* ```
* @Component({selector: "login-comp"})
* @View({
* directives: [formDirectives],
* template: "<input type='text' [ng-form-control]='loginControl' [(ng-model)]='login'>"
* })
* class LoginComp {
* loginControl:Control;
* login:string;
*
* constructor() {
* this.loginControl = new Control('');
* }
* }
* ```
*/
class NgFormControl extends NgControl {
form: Control;
update: void;
model: any;
viewModel: any;
ngValidators: QueryList<NgValidator>;
onChange(c: StringMap<string, any>): void;
path: List<string>;
control: Control;
validator: Function;
viewToModelUpdate(newValue: any): void;
}
/**
* Binds a domain model to the form.
*
* # Example
* ```
* @Component({selector: "search-comp"})
* @View({
* directives: [formDirectives],
* template: `
* <input type='text' [(ng-model)]="searchQuery">
* `})
* class SearchComp {
* searchQuery: string;
* }
* ```
*/
class NgModel extends NgControl {
update: void;
model: any;
viewModel: any;
ngValidators: QueryList<NgValidator>;
onChange(c: StringMap<string, any>): void;
control: Control;
path: List<string>;
validator: Function;
viewToModelUpdate(newValue: any): void;
}
/**
* An abstract class that all control directive extend.
*
* It binds a {@link Control} object to a DOM element.
*/
class NgControl extends AbstractControlDirective {
name: string;
valueAccessor: ControlValueAccessor;
validator: Function;
path: List<string>;
viewToModelUpdate(newValue: any): void;
}
/**
* Creates and binds a control group to a DOM element.
*
* This directive can only be used as a child of {@link NgForm} or {@link NgFormModel}.
*
* # Example
*
* In this example, we create the credentials and personal control groups.
* We can work with each group separately: check its validity, get its value, listen to its changes.
*
* ```
* @Component({selector: "signup-comp"})
* @View({
* directives: [formDirectives],
* template: `
* <form #f="form" (submit)='onSignUp(f.value)'>
* <div ng-control-group='credentials' #credentials="form">
* Login <input type='text' ng-control='login'>
* Password <input type='password' ng-control='password'>
* </div>
* <div *ng-if="!credentials.valid">Credentials are invalid</div>
*
* <div ng-control-group='personal'>
* Name <input type='text' ng-control='name'>
* </div>
* <button type='submit'>Sign Up!</button>
* </form>
* `})
* class SignupComp {
* onSignUp(value) {
* // value === {personal: {name: 'some name'},
* // credentials: {login: 'some login', password: 'some password'}}
* }
* }
*
* ```
*/
class NgControlGroup extends ControlContainer {
onInit(): void;
onDestroy(): void;
control: ControlGroup;
path: List<string>;
formDirective: Form;
}
/**
* Binds an existing control group to a DOM element.
*
* # Example
*
* In this example, we bind the control group to the form element, and we bind the login and
* password controls to the
* login and password elements.
*
* ```
* @Component({selector: "login-comp"})
* @View({
* directives: [formDirectives],
* template: "<form [ng-form-model]='loginForm'>" +
* "Login <input type='text' ng-control='login'>" +
* "Password <input type='password' ng-control='password'>" +
* "<button (click)="onLogin()">Login</button>" +
* "</form>"
* })
* class LoginComp {
* loginForm:ControlGroup;
*
* constructor() {
* this.loginForm = new ControlGroup({
* login: new Control(""),
* password: new Control("")
* });
* }
*
* onLogin() {
* // this.loginForm.value
* }
* }
*
* ```
*
* We can also use ng-model to bind a domain model to the form.
*
* ```
* @Component({selector: "login-comp"})
* @View({
* directives: [formDirectives],
* template: "<form [ng-form-model]='loginForm'>" +
* "Login <input type='text' ng-control='login' [(ng-model)]='login'>" +
* "Password <input type='password' ng-control='password' [(ng-model)]='password'>" +
* "<button (click)="onLogin()">Login</button>" +
* "</form>"
* })
* class LoginComp {
* credentials:{login:string, password:string}
* loginForm:ControlGroup;
*
* constructor() {
* this.loginForm = new ControlGroup({
* login: new Control(""),
* password: new Control("")
* });
* }
*
* onLogin() {
* // this.credentials.login === 'some login'
* // this.credentials.password === 'some password'
* }
* }
* ```
*/
class NgFormModel extends ControlContainer implements Form {
form: ControlGroup;
directives: List<NgControl>;
ngSubmit: void;
onChange(_: any): void;
formDirective: Form;
control: ControlGroup;
path: List<string>;
addControl(dir: NgControl): void;
getControl(dir: NgControl): Control;
removeControl(dir: NgControl): void;
addControlGroup(dir: NgControlGroup): void;
removeControlGroup(dir: NgControlGroup): void;
getControlGroup(dir: NgControlGroup): ControlGroup;
updateModel(dir: NgControl, value: any): void;
onSubmit(): boolean;
}
/**
* Creates and binds a form object to a DOM element.
*
* # Example
*
* ```
* @Component({selector: "signup-comp"})
* @View({
* directives: [formDirectives],
* template: `
* <form #f="form" (submit)='onSignUp(f.value)'>
* <div ng-control-group='credentials' #credentials="form">
* Login <input type='text' ng-control='login'>
* Password <input type='password' ng-control='password'>
* </div>
* <div *ng-if="!credentials.valid">Credentials are invalid</div>
*
* <div ng-control-group='personal'>
* Name <input type='text' ng-control='name'>
* </div>
* <button type='submit'>Sign Up!</button>
* </form>
* `})
* class SignupComp {
* onSignUp(value) {
* // value === {personal: {name: 'some name'},
* // credentials: {login: 'some login', password: 'some password'}}
* }
* }
*
* ```
*/
class NgForm extends ControlContainer implements Form {
form: ControlGroup;
ngSubmit: void;
formDirective: Form;
control: ControlGroup;
path: List<string>;
controls: StringMap<string, AbstractControl>;
addControl(dir: NgControl): void;
getControl(dir: NgControl): Control;
removeControl(dir: NgControl): void;
addControlGroup(dir: NgControlGroup): void;
removeControlGroup(dir: NgControlGroup): void;
getControlGroup(dir: NgControlGroup): ControlGroup;
updateModel(dir: NgControl, value: any): void;
onSubmit(): boolean;
}
/**
* A bridge between a control and a native element.
*
* Please see {@link DefaultValueAccessor} for more information.
*/
interface ControlValueAccessor {
writeValue(obj: any): void;
registerOnChange(fn: any): void;
registerOnTouched(fn: any): void;
}
/**
* The default accessor for writing a value and listening to changes that is used by the
* {@link NgModel}, {@link NgFormControl}, and {@link NgControlName} directives.
*
* # Example
* ```
* <input type="text" [(ng-model)]="searchQuery">
* ```
*/
class DefaultValueAccessor implements ControlValueAccessor {
cd: NgControl;
onChange: void;
onTouched: void;
renderer: Renderer;
elementRef: ElementRef;
writeValue(value: any): void;
ngClassUntouched: boolean;
ngClassTouched: boolean;
ngClassPristine: boolean;
ngClassDirty: boolean;
ngClassValid: boolean;
ngClassInvalid: boolean;
registerOnChange(fn: (_: any) => void): void;
registerOnTouched(fn: () => void): void;
}
/**
* The accessor for writing a value and listening to changes on a checkbox input element.
*
* # Example
* ```
* <input type="checkbox" [ng-control]="rememberLogin">
* ```
*/
class CheckboxControlValueAccessor implements ControlValueAccessor {
cd: NgControl;
onChange: void;
onTouched: void;
renderer: Renderer;
elementRef: ElementRef;
writeValue(value: any): void;
ngClassUntouched: boolean;
ngClassTouched: boolean;
ngClassPristine: boolean;
ngClassDirty: boolean;
ngClassValid: boolean;
ngClassInvalid: boolean;
registerOnChange(fn: (_: any) => {}): void;
registerOnTouched(fn: () => {}): void;
}
/**
* Marks <option> as dynamic, so Angular can be notified when options change.
*
* #Example:
*
* ```
* <select ng-control="city">
* <option *ng-for="#c of cities" [value]="c"></option>
* </select>
* ```
*/
class NgSelectOption {
}
/**
* The accessor for writing a value and listening to changes on a select element.
*/
class SelectControlValueAccessor implements ControlValueAccessor {
cd: NgControl;
value: string;
onChange: void;
onTouched: void;
renderer: Renderer;
elementRef: ElementRef;
writeValue(value: any): void;
ngClassUntouched: boolean;
ngClassTouched: boolean;
ngClassPristine: boolean;
ngClassDirty: boolean;
ngClassValid: boolean;
ngClassInvalid: boolean;
registerOnChange(fn: () => any): void;
registerOnTouched(fn: () => any): void;
}
/**
* A list of all the form directives used as part of a `@View` annotation.
*
* This is a shorthand for importing them each individually.
*/
const formDirectives : List<Type> ;
/**
* Provides a set of validators used by form controls.
*
* # Example
*
* ```
* var loginControl = new Control("", Validators.required)
* ```
*/
class Validators {
}
class NgValidator {
validator: Function;
}
class NgRequiredValidator extends NgValidator {
validator: Function;
}
/**
* Creates a form object from a user-specified configuration.
*
* # Example
*
* ```
* import {Component, View, bootstrap} from 'angular2/angular2';
* import {FormBuilder, Validators, formDirectives, ControlGroup} from 'angular2/forms';
*
* @Component({
* selector: 'login-comp',
* viewBindings: [
* FormBuilder
* ]
* })
* @View({
* template: `
* <form [control-group]="loginForm">
* Login <input control="login">
*
* <div control-group="passwordRetry">
* Password <input type="password" control="password">
* Confirm password <input type="password" control="passwordConfirmation">
* </div>
* </form>
* `,
* directives: [
* formDirectives
* ]
* })
* class LoginComp {
* loginForm: ControlGroup;
*
* constructor(builder: FormBuilder) {
* this.loginForm = builder.group({
* login: ["", Validators.required],
*
* passwordRetry: builder.group({
* password: ["", Validators.required],
* passwordConfirmation: ["", Validators.required]
* })
* });
* }
* }
*
* bootstrap(LoginComp)
* ```
*
* This example creates a {@link ControlGroup} that consists of a `login` {@link Control}, and a
* nested
* {@link ControlGroup} that defines a `password` and a `passwordConfirmation` {@link Control}:
*
* ```
* var loginForm = builder.group({
* login: ["", Validators.required],
*
* passwordRetry: builder.group({
* password: ["", Validators.required],
* passwordConfirmation: ["", Validators.required]
* })
* });
*
* ```
*/
class FormBuilder {
group(controlsConfig: StringMap<string, any>, extra?: StringMap<string, any>): ControlGroup;
control(value: Object, validator?: Function): Control;
array(controlsConfig: List<any>, validator?: Function): ControlArray;
}
const formInjectables : List<Type> ;
class DirectiveMetadata {
id: any;
selector: string;
compileChildren: boolean;
events: List<string>;
properties: List<string>;
readAttributes: List<string>;
type: number;
callOnDestroy: boolean;
callOnChange: boolean;
callOnCheck: boolean;
callOnInit: boolean;
callOnAllChangesDone: boolean;
changeDetection: string;
exportAs: string;
hostListeners: Map<string, string>;
hostProperties: Map<string, string>;
hostAttributes: Map<string, string>;
hostActions: Map<string, string>;
}
class DomRenderer extends Renderer {
createRootHostView(hostProtoViewRef: RenderProtoViewRef, fragmentCount: number, hostElementSelector: string): RenderViewWithFragments;
createView(protoViewRef: RenderProtoViewRef, fragmentCount: number): RenderViewWithFragments;
destroyView(viewRef: RenderViewRef): void;
getNativeElementSync(location: RenderElementRef): any;
getRootNodes(fragment: RenderFragmentRef): List<Node>;
attachFragmentAfterFragment(previousFragmentRef: RenderFragmentRef, fragmentRef: RenderFragmentRef): void;
attachFragmentAfterElement(elementRef: RenderElementRef, fragmentRef: RenderFragmentRef): void;
detachFragment(fragmentRef: RenderFragmentRef): void;
hydrateView(viewRef: RenderViewRef): void;
dehydrateView(viewRef: RenderViewRef): void;
setElementProperty(location: RenderElementRef, propertyName: string, propertyValue: any): void;
setElementAttribute(location: RenderElementRef, attributeName: string, attributeValue: string): void;
setElementClass(location: RenderElementRef, className: string, isAdd: boolean): void;
setElementStyle(location: RenderElementRef, styleName: string, styleValue: string): void;
invokeElementMethod(location: RenderElementRef, methodName: string, args: List<any>): void;
setText(viewRef: RenderViewRef, textNodeIndex: number, text: string): void;
setEventDispatcher(viewRef: RenderViewRef, dispatcher: any): void;
}
/**
* A dispatcher for all events happening in a view.
*/
interface RenderEventDispatcher {
/**
* Called when an event was triggered for a on-* attribute on an element.
* @param {Map<string, any>} locals Locals to be used to evaluate the
* event expressions
*/
dispatchRenderEvent(elementIndex: number, eventName: string, locals: Map<string, any>): void;
}
class Renderer {
/**
* Creates a root host view that includes the given element.
* Note that the fragmentCount needs to be passed in so that we can create a result
* synchronously even when dealing with webworkers!
*
* @param {RenderProtoViewRef} hostProtoViewRef a RenderProtoViewRef of type
* ProtoViewDto.HOST_VIEW_TYPE
* @param {any} hostElementSelector css selector for the host element (will be queried against the
* main document)
* @return {RenderViewWithFragments} the created view including fragments
*/
createRootHostView(hostProtoViewRef: RenderProtoViewRef, fragmentCount: number, hostElementSelector: string): RenderViewWithFragments;
/**
* Creates a regular view out of the given ProtoView.
* Note that the fragmentCount needs to be passed in so that we can create a result
* synchronously even when dealing with webworkers!
*/
createView(protoViewRef: RenderProtoViewRef, fragmentCount: number): RenderViewWithFragments;
/**
* Destroys the given view after it has been dehydrated and detached
*/
destroyView(viewRef: RenderViewRef): void;
/**
* Attaches a fragment after another fragment.
*/
attachFragmentAfterFragment(previousFragmentRef: RenderFragmentRef, fragmentRef: RenderFragmentRef): void;
/**
* Attaches a fragment after an element.
*/
attachFragmentAfterElement(elementRef: RenderElementRef, fragmentRef: RenderFragmentRef): void;
/**
* Detaches a fragment.
*/
detachFragment(fragmentRef: RenderFragmentRef): void;
/**
* Hydrates a view after it has been attached. Hydration/dehydration is used for reusing views
* inside of the view pool.
*/
hydrateView(viewRef: RenderViewRef): void;
/**
* Dehydrates a view after it has been attached. Hydration/dehydration is used for reusing views
* inside of the view pool.
*/
dehydrateView(viewRef: RenderViewRef): void;
/**
* Returns the native element at the given location.
* Attention: In a WebWorker scenario, this should always return null!
*/
getNativeElementSync(location: RenderElementRef): any;
/**
* Sets a property on an element.
*/
setElementProperty(location: RenderElementRef, propertyName: string, propertyValue: any): void;
/**
* Sets an attribute on an element.
*/
setElementAttribute(location: RenderElementRef, attributeName: string, attributeValue: string): void;
/**
* Sets a class on an element.
*/
setElementClass(location: RenderElementRef, className: string, isAdd: boolean): void;
/**
* Sets a style on an element.
*/
setElementStyle(location: RenderElementRef, styleName: string, styleValue: string): void;
/**
* Calls a method on an element.
*/
invokeElementMethod(location: RenderElementRef, methodName: string, args: List<any>): void;
/**
* Sets the value of a text node.
*/
setText(viewRef: RenderViewRef, textNodeIndex: number, text: string): void;
/**
* Sets the dispatcher for all events of the given view
*/
setEventDispatcher(viewRef: RenderViewRef, dispatcher: RenderEventDispatcher): void;
}
class RenderViewRef {
}
class RenderProtoViewRef {
}
class RenderFragmentRef {
}
class RenderViewWithFragments {
viewRef: RenderViewRef;
fragmentRefs: RenderFragmentRef[];
}
class ViewDefinition {
componentId: string;
templateAbsUrl: string;
template: string;
directives: List<DirectiveMetadata>;
styleAbsUrls: List<string>;
styles: List<string>;
encapsulation: ViewEncapsulation;
}
const DOCUMENT_TOKEN : OpaqueToken ;
/**
* A unique id (string) for an angular application.
*/
const APP_ID_TOKEN : OpaqueToken ;
const DOM_REFLECT_PROPERTIES_AS_ATTRIBUTES : OpaqueToken ;
/**
* Defines when a compiled template should be stored as a string
* rather than keeping its Nodes to preserve memory.
*/
const MAX_IN_MEMORY_ELEMENTS_PER_TEMPLATE_TOKEN : OpaqueToken ;
/**
* Create trace scope.
*
* Scopes must be strictly nested and are analogous to stack frames, but
* do not have to follow the stack frames. Instead it is recommended that they follow logical
* nesting. You may want to use
* [Event
* Signatures](http://google.github.io/tracing-framework/instrumenting-code.html#custom-events)
* as they are defined in WTF.
*
* Used to mark scope entry. The return value is used to leave the scope.
*
* final myScope = wtfCreateScope('MyClass#myMethod(ascii someVal)');
*
* someMethod() {
* var s = myScope('Foo'); // 'Foo' gets stored in tracing UI
* // DO SOME WORK HERE
* return wtfLeave(s, 123); // Return value 123
* }
*
* Note, adding try-finally block around the work to ensure that `wtfLeave` gets called can
* negatively impact the performance of your application. For this reason we recommend that
* you don't add them to ensure that `wtfLeave` gets called. In production `wtfLeave` is a noop and
* so try-finally block has no value. When debugging perf issues, skipping `wtfLeave`, do to
* exception, will produce incorrect trace, but presence of exception signifies logic error which
* needs to be fixed before the app should be profiled. Add try-finally only when you expect that
* an exception is expected during normal execution while profiling.
*/
var wtfCreateScope : WtfScopeFn ;
/**
* Used to mark end of Scope.
*
* - `scope` to end.
* - `returnValue` (optional) to be passed to the WTF.
*
* Returns the `returnValue for easy chaining.
*/
var wtfLeave : <T>(scope: any, returnValue?: T) => T ;
/**
* Used to mark Async start. Async are similar to scope but they don't have to be strictly nested.
* The return value is used in the call to [endAsync]. Async ranges only work if WTF has been
* enabled.
*
* someMethod() {
* var s = wtfStartTimeRange('HTTP:GET', 'some.url');
* var future = new Future.delay(5).then((_) {
* wtfEndTimeRange(s);
* });
* }
*/
var wtfStartTimeRange : (rangeType: string, action: string) => any ;
/**
* Ends a async time range operation.
* [range] is the return value from [wtfStartTimeRange] Async ranges only work if WTF has been
* enabled.
*/
var wtfEndTimeRange : (range: any) => void ;
interface WtfScopeFn {
(arg0?: any, arg1?: any): any;
}
var ChangeDetectorRef: InjectableReference;
var ApplicationRef: InjectableReference;
var Compiler: InjectableReference;
var AppViewManager: InjectableReference;
var ViewRef: InjectableReference;
var ProtoViewRef: InjectableReference;
var ViewContainerRef: InjectableReference;
var ComponentRef: InjectableReference;
var Key: InjectableReference;
}
declare module "angular2/angular2" {
export = ng;
} | the_stack |
import { Component, Optional, OnInit } from '@angular/core';
import { CoreCourseModuleMainActivityComponent } from '@features/course/classes/main-activity-component';
import { CoreCourseContentsPage } from '@features/course/pages/contents/contents';
import { IonContent } from '@ionic/angular';
import { CoreSites } from '@services/sites';
import { CoreDomUtils } from '@services/utils/dom';
import { CoreTimeUtils } from '@services/utils/time';
import { Translate } from '@singletons';
import { CoreEvents } from '@singletons/events';
import {
AddonModChoice,
AddonModChoiceChoice,
AddonModChoiceOption,
AddonModChoiceProvider,
AddonModChoiceResult,
} from '../../services/choice';
import { AddonModChoiceOffline } from '../../services/choice-offline';
import {
AddonModChoiceAutoSyncData,
AddonModChoiceSync,
AddonModChoiceSyncProvider,
AddonModChoiceSyncResult,
} from '../../services/choice-sync';
import { AddonModChoicePrefetchHandler } from '../../services/handlers/prefetch';
/**
* Component that displays a choice.
*/
@Component({
selector: 'addon-mod-choice-index',
templateUrl: 'addon-mod-choice-index.html',
})
export class AddonModChoiceIndexComponent extends CoreCourseModuleMainActivityComponent implements OnInit {
component = AddonModChoiceProvider.COMPONENT;
moduleName = 'choice';
choice?: AddonModChoiceChoice;
options: AddonModChoiceOption[] = [];
selectedOption: {id: number} = { id: -1 };
choiceNotOpenYet = false;
choiceClosed = false;
canEdit = false;
canDelete = false;
canSeeResults = false;
data: number[] = [];
labels: string[] = [];
results: AddonModChoiceResultFormatted[] = [];
publishInfo?: string; // Message explaining the user what will happen with his choices.
openTimeReadable?: string;
closeTimeReadable?: string;
protected userId?: number;
protected syncEventName = AddonModChoiceSyncProvider.AUTO_SYNCED;
protected hasAnsweredOnline = false;
protected now = Date.now();
constructor(
protected content?: IonContent,
@Optional() courseContentsPage?: CoreCourseContentsPage,
) {
super('AddonModChoiceIndexComponent', content, courseContentsPage);
}
/**
* @inheritdoc
*/
async ngOnInit(): Promise<void> {
super.ngOnInit();
this.userId = CoreSites.getCurrentSiteUserId();
await this.loadContent(false, true);
}
/**
* @inheritdoc
*/
protected async invalidateContent(): Promise<void> {
const promises: Promise<void>[] = [];
promises.push(AddonModChoice.invalidateChoiceData(this.courseId));
if (this.choice) {
promises.push(AddonModChoice.invalidateOptions(this.choice.id));
promises.push(AddonModChoice.invalidateResults(this.choice.id));
}
await Promise.all(promises);
}
/**
* @inheritdoc
*/
protected isRefreshSyncNeeded(syncEventData: AddonModChoiceAutoSyncData): boolean {
if (this.choice && syncEventData.choiceId == this.choice.id && syncEventData.userId == this.userId) {
this.content?.scrollToTop();
return true;
}
return false;
}
/**
* @inheritdoc
*/
protected async fetchContent(refresh?: boolean, sync = false, showErrors = false): Promise<void> {
this.now = Date.now();
this.choice = await AddonModChoice.getChoice(this.courseId, this.module.id);
if (sync) {
// Try to synchronize the choice.
const updated = await this.syncActivity(showErrors);
if (updated) {
// Responses were sent, update the choice.
this.choice = await AddonModChoice.getChoice(this.courseId, this.module.id);
}
}
this.choice.timeopen = (this.choice.timeopen || 0) * 1000;
this.choice.timeclose = (this.choice.timeclose || 0) * 1000;
this.openTimeReadable = CoreTimeUtils.userDate(this.choice.timeopen);
this.closeTimeReadable = CoreTimeUtils.userDate(this.choice.timeclose);
this.description = this.choice.intro;
this.choiceNotOpenYet = !!this.choice.timeopen && this.choice.timeopen > this.now;
this.choiceClosed = !!this.choice.timeclose && this.choice.timeclose <= this.now;
this.dataRetrieved.emit(this.choice);
// Check if there are responses stored in offline.
this.hasOffline = await AddonModChoiceOffline.hasResponse(this.choice.id);
// We need fetchOptions to finish before calling fetchResults because it needs hasAnsweredOnline variable.
await this.fetchOptions(this.choice);
await this.fetchResults(this.choice);
}
/**
* Convenience function to get choice options.
*
* @param choice Choice data.
* @return Promise resolved when done.
*/
protected async fetchOptions(choice: AddonModChoiceChoice): Promise<void> {
let options = await AddonModChoice.getOptions(choice.id, { cmId: this.module.id });
// Check if the user has answered (synced) to allow show results.
this.hasAnsweredOnline = options.some((option) => option.checked);
if (this.hasOffline) {
options = await this.getOfflineResponses(choice, options);
}
const isOpen = this.isChoiceOpen(choice);
this.selectedOption = { id: -1 }; // Single choice model.
const hasAnswered = options.some((option) => {
if (!option.checked) {
return false;
}
if (!choice.allowmultiple) {
this.selectedOption.id = option.id;
}
return true;
});
this.canEdit = isOpen && (choice.allowupdate! || !hasAnswered);
this.canDelete = isOpen && choice.allowupdate! && hasAnswered;
this.options = options;
if (!this.canEdit) {
return;
}
// Calculate the publish info message.
switch (choice.showresults) {
case AddonModChoiceProvider.RESULTS_NOT:
this.publishInfo = 'addon.mod_choice.publishinfonever';
break;
case AddonModChoiceProvider.RESULTS_AFTER_ANSWER:
if (choice.publish == AddonModChoiceProvider.PUBLISH_ANONYMOUS) {
this.publishInfo = 'addon.mod_choice.publishinfoanonafter';
} else {
this.publishInfo = 'addon.mod_choice.publishinfofullafter';
}
break;
case AddonModChoiceProvider.RESULTS_AFTER_CLOSE:
if (choice.publish == AddonModChoiceProvider.PUBLISH_ANONYMOUS) {
this.publishInfo = 'addon.mod_choice.publishinfoanonclose';
} else {
this.publishInfo = 'addon.mod_choice.publishinfofullclose';
}
break;
default:
// No need to inform the user since it's obvious that the results are being published.
this.publishInfo = '';
}
}
/**
* Get offline responses.
*
* @param choice Choice.
* @param options Online options.
* @return Promise resolved with the options.
*/
protected async getOfflineResponses(
choice: AddonModChoiceChoice,
options: AddonModChoiceOption[],
): Promise<AddonModChoiceOption[]> {
const response = await AddonModChoiceOffline.getResponse(choice.id);
const optionsMap: {[id: number]: AddonModChoiceOption} = {};
options.forEach((option) => {
optionsMap[option.id] = option;
});
// Update options with the offline data.
if (response.deleting) {
// Uncheck selected options.
if (response.responses.length > 0) {
// Uncheck all options selected in responses.
response.responses.forEach((selected) => {
if (optionsMap[selected] && optionsMap[selected].checked) {
optionsMap[selected].checked = false;
optionsMap[selected].countanswers--;
}
});
} else {
// On empty responses, uncheck all selected.
Object.keys(optionsMap).forEach((key) => {
if (optionsMap[key].checked) {
optionsMap[key].checked = false;
optionsMap[key].countanswers--;
}
});
}
} else {
// Uncheck all options to check again the offlines'.
Object.keys(optionsMap).forEach((key) => {
if (optionsMap[key].checked) {
optionsMap[key].checked = false;
optionsMap[key].countanswers--;
}
});
// Then check selected ones.
response.responses.forEach((selected) => {
if (optionsMap[selected]) {
optionsMap[selected].checked = true;
optionsMap[selected].countanswers++;
}
});
}
// Convert it again to array.
return Object.keys(optionsMap).map((key) => optionsMap[key]);
}
/**
* Convenience function to get choice results.
*
* @param choice Choice.
* @return Resolved when done.
*/
protected async fetchResults(choice: AddonModChoiceChoice): Promise<void> {
if (this.choiceNotOpenYet) {
// Cannot see results yet.
this.canSeeResults = false;
return;
}
const results = await AddonModChoice.getResults(choice.id, { cmId: this.module.id });
let hasVotes = false;
this.data = [];
this.labels = [];
this.results = results.map((result: AddonModChoiceResultFormatted) => {
if (result.numberofuser > 0) {
hasVotes = true;
}
this.data.push(result.numberofuser);
this.labels.push(result.text);
return Object.assign(result, { percentageamountfixed: result.percentageamount.toFixed(1) });
});
this.canSeeResults = hasVotes || AddonModChoice.canStudentSeeResults(choice, this.hasAnsweredOnline);
}
/**
* @inheritdoc
*/
protected async logActivity(): Promise<void> {
if (!this.choice) {
return; // Shouldn't happen.
}
await AddonModChoice.logView(this.choice.id, this.choice.name);
}
/**
* Check if a choice is open.
*
* @param choice Choice data.
* @return True if choice is open, false otherwise.
*/
protected isChoiceOpen(choice: AddonModChoiceChoice): boolean {
return (!choice.timeopen || choice.timeopen <= this.now) && (!choice.timeclose || choice.timeclose > this.now);
}
/**
* Return true if the user has selected at least one option.
*
* @return True if the user has responded.
*/
canSave(): boolean {
if (!this.choice) {
return false;
}
if (this.choice.allowmultiple) {
return this.options.some((option) => option.checked);
} else {
return this.selectedOption.id !== -1;
}
}
/**
* Save options selected.
*/
async save(): Promise<void> {
const choice = this.choice!;
// Only show confirm if choice doesn't allow update.
if (!choice.allowupdate) {
await CoreDomUtils.showConfirm(Translate.instant('core.areyousure'));
}
const responses: number[] = [];
if (choice.allowmultiple) {
this.options.forEach((option) => {
if (option.checked) {
responses.push(option.id);
}
});
} else {
responses.push(this.selectedOption.id);
}
const modal = await CoreDomUtils.showModalLoading('core.sending', true);
try {
const online = await AddonModChoice.submitResponse(choice.id, choice.name, this.courseId, responses);
this.content?.scrollToTop();
if (online) {
CoreEvents.trigger(CoreEvents.ACTIVITY_DATA_SENT, { module: this.moduleName });
// Check completion since it could be configured to complete once the user answers the choice.
this.checkCompletion();
}
await this.dataUpdated(online);
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'addon.mod_choice.cannotsubmit', true);
} finally {
modal.dismiss();
}
}
/**
* Delete options selected.
*/
async delete(): Promise<void> {
try {
await CoreDomUtils.showDeleteConfirm();
} catch {
// User cancelled.
return;
}
const modal = await CoreDomUtils.showModalLoading('core.sending', true);
try {
await AddonModChoice.deleteResponses(this.choice!.id, this.choice!.name, this.courseId);
this.content?.scrollToTop();
// Refresh the data. Don't call dataUpdated because deleting an answer doesn't mark the choice as outdated.
await this.refreshContent(false);
} catch (error) {
CoreDomUtils.showErrorModalDefault(error, 'addon.mod_choice.cannotsubmit', true);
} finally {
modal.dismiss();
}
}
/**
* Function to call when some data has changed. It will refresh/prefetch data.
*
* @param online Whether the data was sent to server or stored in offline.
* @return Promise resolved when done.
*/
protected async dataUpdated(online: boolean): Promise<void> {
if (!online || !this.isPrefetched()) {
// Not downloaded, just refresh the data.
return this.refreshContent(false);
}
try {
// The choice is downloaded, update the data.
await AddonModChoiceSync.prefetchAfterUpdate(AddonModChoicePrefetchHandler.instance, this.module, this.courseId);
// Update the view.
this.showLoadingAndFetch(false, false);
} catch {
// Prefetch failed, refresh the data.
return this.refreshContent(false);
}
}
/**
* Toggle list of users in a result visible.
*
* @param result Result to expand.
*/
toggle(result: AddonModChoiceResultFormatted): void {
result.expanded = !result.expanded;
}
/**
* Performs the sync of the activity.
*
* @return Promise resolved when done.
*/
protected sync(): Promise<AddonModChoiceSyncResult> {
return AddonModChoiceSync.syncChoice(this.choice!.id, this.userId);
}
/**
* Checks if sync has succeed from result sync data.
*
* @param result Data returned on the sync function.
* @return Whether it succeed or not.
*/
protected hasSyncSucceed(result: AddonModChoiceSyncResult): boolean {
return result.updated;
}
}
/**
* Choice result with some calculated data.
*/
export type AddonModChoiceResultFormatted = AddonModChoiceResult & {
percentageamountfixed: string; // Percentage of users answers with fixed decimals.
expanded?: boolean;
}; | the_stack |
import * as jstz from 'jstimezonedetect';
import 'styling/Globals';
import 'styling/_SearchButton';
import 'styling/_SearchInterface';
import 'styling/_SearchModalBox';
import { any, chain, each, find, first, indexOf, isEmpty, partition, tail } from 'underscore';
import { HistoryController } from '../../controllers/HistoryController';
import { IHistoryManager } from '../../controllers/HistoryManager';
import { LocalStorageHistoryController } from '../../controllers/LocalStorageHistoryController';
import { NoopHistoryController } from '../../controllers/NoopHistoryController';
import { QueryController } from '../../controllers/QueryController';
import { InitializationEvents } from '../../events/InitializationEvents';
import {
IBuildingQueryEventArgs,
IDoneBuildingQueryEventArgs,
INewQueryEventArgs,
IQueryErrorEventArgs,
IQuerySuccessEventArgs,
QueryEvents
} from '../../events/QueryEvents';
import { IBeforeRedirectEventArgs, StandaloneSearchInterfaceEvents } from '../../events/StandaloneSearchInterfaceEvents';
import { Assert } from '../../misc/Assert';
import { SentryLogger } from '../../misc/SentryLogger';
import { ComponentOptionsModel } from '../../models/ComponentOptionsModel';
import { ComponentStateModel } from '../../models/ComponentStateModel';
import { IAttributeChangedEventArg, Model } from '../../models/Model';
import { QueryStateModel, QUERY_STATE_ATTRIBUTES } from '../../models/QueryStateModel';
import { SearchEndpoint } from '../../rest/SearchEndpoint';
import { $$ } from '../../utils/Dom';
import { HashUtils } from '../../utils/HashUtils';
import { Utils } from '../../utils/Utils';
import { analyticsActionCauseList, IAnalyticsTriggerRedirect } from '../Analytics/AnalyticsActionListMeta';
import { IAnalyticsClient } from '../Analytics/AnalyticsClient';
import { NoopAnalyticsClient } from '../Analytics/NoopAnalyticsClient';
import { AriaLive, IAriaLive } from '../AriaLive/AriaLive';
import { BaseComponent } from '../Base/BaseComponent';
import { IComponentBindings } from '../Base/ComponentBindings';
import { ComponentOptions } from '../Base/ComponentOptions';
import { IFieldOption, IQueryExpression } from '../Base/IComponentOptions';
import { InitializationPlaceholder } from '../Base/InitializationPlaceholder';
import { RootComponent } from '../Base/RootComponent';
import { Debug } from '../Debug/Debug';
import { MissingTermManager } from '../MissingTerm/MissingTermManager';
import { OmniboxAnalytics } from '../Omnibox/OmniboxAnalytics';
import { Context, IPipelineContextProvider } from '../PipelineContext/PipelineGlobalExports';
import {
MEDIUM_SCREEN_WIDTH,
ResponsiveComponents,
SMALL_SCREEN_WIDTH,
ValidResponsiveMode
} from '../ResponsiveComponents/ResponsiveComponents';
import { FacetColumnAutoLayoutAdjustment } from './FacetColumnAutoLayoutAdjustment';
import { FacetValueStateHandler } from './FacetValueStateHandler';
import RelevanceInspectorModule = require('../RelevanceInspector/RelevanceInspector');
import { ComponentsTypes } from '../../utils/ComponentsTypes';
import { ScrollRestorer } from './ScrollRestorer';
export interface ISearchInterfaceOptions {
enableHistory?: boolean;
enableAutomaticResponsiveMode?: boolean;
useLocalStorageForHistory?: boolean;
resultsPerPage?: number;
excerptLength?: number;
expression?: IQueryExpression;
filterField?: IFieldOption;
autoTriggerQuery?: boolean;
timezone?: string;
enableDebugInfo?: boolean;
enableCollaborativeRating?: boolean;
enableDuplicateFiltering?: boolean;
hideUntilFirstQuery?: boolean;
firstLoadingAnimation?: any;
pipeline?: string;
maximumAge?: number;
searchPageUri?: string;
initOptions?: any;
endpoint?: SearchEndpoint;
originalOptionsObject?: any;
allowQueriesWithoutKeywords?: boolean;
responsiveMediumBreakpoint?: number;
responsiveSmallBreakpoint?: number;
responsiveMode?: ValidResponsiveMode;
enableScrollRestoration?: boolean;
modalContainer?: HTMLElement;
}
export interface IMissingTermManagerArgs {
element: HTMLElement;
queryStateModel: QueryStateModel;
queryController: QueryController;
usageAnalytics: IAnalyticsClient;
}
/**
* The SearchInterface component is the root and main component of your Coveo search interface. You should place all
* other Coveo components inside the SearchInterface component.
*
* It is also on the HTMLElement of the SearchInterface component that you call the {@link init} function.
*
* It is advisable to specify a unique HTML `id` attribute for the SearchInterface component in order to be able to
* reference it easily.
*
* **Example:**
*
* ```html
* <head>
*
* [ ... ]
*
* <script>
* document.addEventListener('DOMContentLoaded', function() {
*
* [ ... ]
* // The init function is called on the SearchInterface element, in this case, the body of the page.
* Coveo.init(document.body);
*
* [ ... ]
*
* });
* </script>
*
* [ ... ]
* </head>
*
* <!-- Specifying a unique HTML id attribute for the SearchInterface component is good practice. -->
* <body id='search' class='CoveoSearchInterface' [ ... other options ... ]>
*
* [ ... ]
*
* <!-- You should place all other Coveo components here, inside the SearchInterface component. -->
*
* [ ... ]
*
* </body>
* ```
*/
export class SearchInterface extends RootComponent implements IComponentBindings {
static ID = 'SearchInterface';
/**
* The options for the search interface
* @componentOptions
*/
static options: ISearchInterfaceOptions = {
/**
* Whether to allow the end user to navigate search history using the **Back** and **Forward** buttons
* of the browser.
*
* If this option is set to `true`, the state of the current query will be saved in the hash portion
* of the URL when the user submits the query.
*
* **Example:**
* > If the `enableHistory` option is `true` and the current query is `foobar`, the SearchInterface component
* > saves `q=foobar` in the URL hash when the user submits the query.
*
* **Note:** Avoid setting this option to `true` on a search interface that relates to a Coveo for Salesforce Full Search or Insight Panel component, otherwise the component won't initialize correctly.
*/
enableHistory: ComponentOptions.buildBooleanOption({ defaultValue: false }),
/**
* Specifies whether to enable automatic responsive mode (i.e., automatically placing {@link Facet} and {@link Tab}
* components in dropdown menus under the search box when the width of the SearchInterface HTML element reaches or
* falls behind a certain pixel threshold).
*
* You might want to set this option to `false` if automatic responsive mode does not suit the specific design needs
* of your implementation.
*
* **Note:**
*
* > If this option is `true`, you can also specify whether to enable responsive mode for Facet components (see
* > {@link Facet.options.enableResponsiveMode}) and for Tab components (see
* > {@link Tab.options.enableResponsiveMode}).
* >
* > In addition, you can specify the label you wish to display on the dropdown buttons (see
* > {@link Facet.options.dropdownHeaderLabel} and {@link Tab.options.dropdownHeaderLabel}).
*
* Default value is `true`.
*/
enableAutomaticResponsiveMode: ComponentOptions.buildBooleanOption({ defaultValue: true }),
/**
* Specifies whether to save the interface state in the local storage of the browser.
*
* You might want to set this option to `true` for reasons specifically important for your implementation.
*
* Default value is `false`.
*/
useLocalStorageForHistory: ComponentOptions.buildBooleanOption({ defaultValue: false }),
/**
* Specifies the number of results to display on each page.
*
* For more advanced features, see the {@link ResultsPerPage} component.
*
* **Note:**
*
* > When the {@link ResultsPerPage} component is present in the page, this option gets overridden and is useless.
*
* Default value is `10`. Minimum value is `0`.
*/
resultsPerPage: ComponentOptions.buildNumberOption({ defaultValue: 10, min: 0 }),
/**
* Specifies the number of characters to get at query time to create an excerpt of the result.
*
* This setting is global and cannot be modified on a per-result basis.
*
* See also the {@link Excerpt} component.
*
* Default value is `200`. Minimum value is `0`.
*/
excerptLength: ComponentOptions.buildNumberOption({ defaultValue: 200, min: 0 }),
/**
* Specifies an expression to add to each query.
*
* You might want to use this options to add a global filter to your entire search interface that applies for all
* tabs.
*
* You should not use this option to address security concerns (it is JavaScript, after all).
*
* **Note:**
*
* > It also is possible to set this option separately for each {@link Tab} component
* > (see {@link Tab.options.expression}).
*
* Default value is `''`.
*/
expression: ComponentOptions.buildQueryExpressionOption({ defaultValue: '' }),
/**
* Specifies the name of a field to use as a custom filter when executing the query (also referred to as
* "folding").
*
* Setting a value for this option causes the index to return only one result having any particular value inside the
* filter field. Any other matching result is "folded" inside the childResults member of each JSON query result.
*
* This feature is typically useful with threaded conversations to include only one top-level result per
* conversation. Thus, the field you specify for this option will typically be value unique to each thread that is
* shared by all items (e.g., posts, emails, etc) in the thread.
*
* For more advanced features, see the {@link Folding} component.
*
* Default value is the empty string (`''`).
*/
filterField: ComponentOptions.buildFieldOption({ defaultValue: '' }),
/**
* Specifies whether to display a loading animation before the first query successfully returns.
*
* **Note:**
*
* > If you do not set this options to `false`, the loading animation will still run until the first query
* > successfully returns even if the [autoTriggerQuery]{@link SearchInterface.options.autoTriggerQuery} option is
* `false`.
*
* See also the [firstLoadingAnimation]{@link SearchInterface.options.firstLoadingAnimation} option.
*
* Default value is `true`.
*
* @deprecated This option is exposed for legacy reasons. Since the
* [July 2017 Release (v2.2900.23)](https://docs.coveo.com/en/432/), the loading animation is composed of
* placeholders, making this option is obsolete.
*/
hideUntilFirstQuery: ComponentOptions.buildBooleanOption({
deprecated: 'Exposed for legacy reasons. The loading animation is now composed of placeholders, and this option is obsolete.'
}),
/**
* Specifies the animation that you wish to display while your interface is loading.
*
* You can either specify the CSS selector of an HTML element that matches the default CSS class
* (`coveo-first-loading-animation`), or add `-selector` to the markup attribute of this option to specify the CSS
* selector of an HTML element that matches any CSS class.
*
* See also the [hideUntilFirstQuery]{@link SearchInterface.options.hideUntilFirstQuery} option.
*
* **Examples:**
*
* In this first case, the SearchInterface uses the HTML element whose `id` attribute is `MyAnimation` as the
* loading animation only if the `class` attribute of this element also matches `coveo-first-loading-animation`.
* Default loading animation CSS, which you can customize as you see fit, applies to this HTML element.
* ```html
* <div class='CoveoSearchInterface' data-first-loading-animation='#MyAnimation'>
* <div id='MyAnimation' class='coveo-first-loading-animation'>
* <!-- ... -->
* </div>
* <!-- ... -->
* </div>
* ```
*
* In this second case, the SearchInterface uses the HTML element whose `id` attribute is `MyAnimation` as the
* loading animation no matter what CSS class it matches. However, if the `class` attribute of the HTML element does
* not match `coveo-first-loading-animation`, no default loading animation CSS applies to this HTML element.
* Normally, you should only use `data-first-loading-animation-selector` if you want to completely override the
* default loading animation CSS.
* ```html
* <div class='CoveoSearchInterface' data-first-loading-animation-selector='#MyAnimation'>
* <div id='MyAnimation' class='my-custom-loading-animation-class'>
* <!-- ... -->
* </div>
* <!-- ... -->
* </div>
* ```
*
* By default, the loading animation is a Coveo CSS animation (which you can customize with CSS).
*
* @deprecated This option is exposed for legacy reasons. Since the
* [July 2017 Release (v2.2900.23)](https://docs.coveo.com/en/432/), the loading animation is composed of
* placeholders, making this option is obsolete.
*/
firstLoadingAnimation: ComponentOptions.buildChildHtmlElementOption({
deprecated: 'Exposed for legacy reasons. The loading animation is now composed of placeholder, and this options is obsolete.'
}),
/**
* Specifies whether to trigger the first query automatically when the page finishes loading.
*
* Default value is `true`.
*/
autoTriggerQuery: ComponentOptions.buildBooleanOption({ defaultValue: true }),
/**
* Specifies if the search interface should perform queries when no keywords are entered by the end user.
*
* When this option is set to true, the interface will initially only load with the search box, as long as you have a search box component in your interface.
*
* Once the user submits a query, the full search interface loads to display the results.
*
* When using the Coveo for Salesforce Free edition, this option is automatically set to false, and should not be changed.
*
* This option interacts closely with the {@link SearchInterface.options.autoTriggerQuery} option, as the automatic query is not triggered when there are no keywords.
*
* It also modifies the {@link IQuery.allowQueriesWithoutKeywords} query parameter.
*
* Default value is `true`, except in Coveo for Salesforce Free edition in which it is `false`.
*/
allowQueriesWithoutKeywords: ComponentOptions.buildBooleanOption({ defaultValue: true }),
endpoint: ComponentOptions.buildCustomOption(
endpoint => (endpoint != null && endpoint in SearchEndpoint.endpoints ? SearchEndpoint.endpoints[endpoint] : null),
{ defaultFunction: () => SearchEndpoint.endpoints['default'] }
),
/**
* Specifies the timezone in which the search interface is loaded. This allows the index to recognize some special
* query syntax.
*
* This option must have a valid IANA zone info key (AKA the Olson time zone database) as its value.
*
* **Example:** `America/New_York`.
*
* By default, the search interface allows a library to try to detect the timezone automatically.
*/
timezone: ComponentOptions.buildStringOption({ defaultFunction: () => jstz.determine().name() }),
/**
* Specifies whether to enable the feature that allows the end user to ALT + double click any result to open a debug
* page with detailed information about all properties and fields for that result.
*
* Enabling this feature causes no security concern; the entire debug information is always visible to the end user
* through the browser developer console or by calling the Coveo API directly.
*
* Default value is `true`.
*/
enableDebugInfo: ComponentOptions.buildBooleanOption({ defaultValue: true }),
/**
* **Note:**
*
* > The Coveo Cloud V2 platform does not support collaborative rating. Therefore, this option is obsolete in Coveo Cloud V2.
*
* Specifies whether to enable collaborative rating, which you can leverage using the
* [`ResultRating`]{@link ResultRating} component.
*
* Setting this option to `true` has no effect unless collaborative rating is also enabled on your Coveo index.
*
* Default value is `false`.
*/
enableCollaborativeRating: ComponentOptions.buildBooleanOption({ defaultValue: false }),
/**
* Whether to filter out duplicates, so that items resembling one another only appear once in the query results.
*
* **Notes:**
* - Two items must be at least 85% similar to one another to be considered duplicates.
* - When a pair of duplicates is found, only the higher-ranked item of the two is kept in the result set.
* - Enabling this feature can make the total result count less precise, as only the requested page of query results is submitted to duplicate filtering.
* - This option can also be explicitly set on the [`Tab`]{@link Tab} component. When this is the case, the `Tab` configuration prevails.
*/
enableDuplicateFiltering: ComponentOptions.buildBooleanOption({ defaultValue: false }),
/**
* Specifies the name of the query pipeline to use for the queries.
*
* You can specify a value for this option if your index is in a Coveo Cloud organization in which pipelines have
* been created (see [Adding and Managing Query Pipelines](https://docs.coveo.com/en/1791/)).
*
* **Note:**
*
* > It also is possible to set this option separately for each {@link Tab} component
* > (see {@link Tab.options.pipeline}).
*
* Default value is `undefined`, which means that the search interface uses the default pipeline.
*/
pipeline: ComponentOptions.buildStringOption(),
/**
* Specifies the maximum age (in milliseconds) that cached query results can have to still be usable as results
* instead of performing a new query on the index. The cache is located in the Coveo Search API (which resides
* between the index and the search interface).
*
* If cached results that are older than the age you specify in this option are available, the framework will not
* use these results; it will rather perform a new query on the index.
*
* On high-volume public web sites, specifying a higher value for this option can greatly improve query response
* time at the cost of result freshness.
*
* **Note:**
*
* > It also is possible to set this option separately for each {@link Tab} component
* > (see {@link Tab.options.maximumAge}).
*
* Default value is `undefined`, which means that the search interface lets the Coveo Search API determine the
* maximum cache age. This is typically equivalent to 30 minutes (see
* [maximumAge](https://docs.coveo.com/en/1461/#RestQueryParameters-maximumAge)).
*/
maximumAge: ComponentOptions.buildNumberOption(),
/**
* Specifies the search page you wish to navigate to when instantiating a standalone search box interface.
*
* Default value is `undefined`, which means that the search interface does not redirect.
*/
searchPageUri: ComponentOptions.buildStringOption(),
/**
* Specifies the search interface width that should be considered "medium" size, in pixels.
*
* When the width of the window/device that displays the search page reaches or falls short of this threshold (but still exceeds the [responsiveSmallBreakpoint]{@link SearchInterface.options.responsiveSmallBreakpoint} value), the search page layout will change so that, for instance, facets within the element that has the coveo-facet-column class will be accessible from a dropdown menu on top of the result list rather than being fully rendered next to the result list.
*
* This option is only taken into account when [enableAutomaticResponsiveMode]{@link SearchInterface.options.enableAutomaticResponsiveMode} is set to true.
*
* Default value is `800`.
*/
responsiveMediumBreakpoint: ComponentOptions.buildNumberOption({
defaultValue: MEDIUM_SCREEN_WIDTH,
depend: 'enableAutomaticResponsiveMode'
}),
/**
* Specifies the search interface width that should be considered "small" size, in pixels.
*
* When the width of the window/device that displays the search page reaches or falls short of this threshold, the search page layout will change so that, for instance, some result list layouts which are not suited for being rendered on a small screen/area will be disabled.
*
* This option is only taken into account when [enableAutomaticResponsiveMode]{@link SearchInterface.options.enableAutomaticResponsiveMode} is set to true.
*
* Default value is `480`.
*/
responsiveSmallBreakpoint: ComponentOptions.buildNumberOption({
defaultValue: SMALL_SCREEN_WIDTH,
depend: 'enableAutomaticResponsiveMode'
}),
/**
* Specifies the search interface responsive mode that should be used.
*
* When the mode is auto, the width of the window/device that displays the search page is used to determine which layout the search page should use
* (see [enableAutomaticResponsiveMode]{@link SearchInterface.options.enableAutomaticResponsiveMode}, [responsiveMediumBreakpoint]{@link SearchInterface.options.responsiveMediumBreakpoint}
* and [responsiveSmallBreakpoint{@link SearchInterface.options.responsiveSmallBreakpoint}])
*
* When it's not on auto, the width is ignored and the the layout used depends on this option
* (e.g. If set to "small", then the search interface layout will be the same as if it was on a narrow window/device)
*/
responsiveMode: ComponentOptions.buildCustomOption<ValidResponsiveMode>(
value => {
// Validator function for the string passed, verify it's one of the accepted values.
if (value === 'auto' || value === 'small' || value === 'medium' || value === 'large') {
return value;
} else {
console.warn(`${value} is not a proper value for responsiveMode, auto has been used instead.`);
return 'auto';
}
},
{
defaultValue: 'auto'
}
),
/**
* Specifies whether to restore the last scroll position when navigating back
* to the search interface.
*
* @availablesince [March 2020 Release (v2.8521)](https://docs.coveo.com/en/3203/)
*/
enableScrollRestoration: ComponentOptions.buildBooleanOption({ defaultValue: false }),
/**
* Specifies the HTMLElement to which Modals components of the search interface will be attached to. You can
* either specify a CSS selector or pass an HTMLElement in the options when calling Coveo.init.
*
* Default value is `element.ownerDocument.body`.
*
* **Example in attribute:**
* ```html
* <div class="CoveoSearchInterface" data-modal-container="#my-modal-container"></div>
* ```
*
* **Example in init options:**
* ```javascript
* var myContainer = document.getElementById('my-modal-container');
* Coveo.init(root, {
* SearchInterface: {
* modalContainer: myContainer
* }
* });
* ```
*/
modalContainer: ComponentOptions.buildSelectorOption({ defaultFunction: element => element.ownerDocument.body })
};
public static SMALL_INTERFACE_CLASS_NAME = 'coveo-small-search-interface';
public root: HTMLElement;
public queryStateModel: QueryStateModel;
public componentStateModel: ComponentStateModel;
public queryController: QueryController;
public componentOptionsModel: ComponentOptionsModel;
public usageAnalytics: IAnalyticsClient;
public historyManager: IHistoryManager;
public scrollRestorer: ScrollRestorer;
/**
* Allows to get and set the different breakpoints for mobile and tablet devices.
*
* This is useful, amongst other, for {@link Facet}, {@link Tab} and {@link ResultList}
*/
public responsiveComponents: ResponsiveComponents;
public isResultsPerPageModifiedByPipeline = false;
public ariaLive: IAriaLive;
private attachedComponents: { [type: string]: BaseComponent[] };
private facetValueStateHandler: FacetValueStateHandler;
private queryPipelineConfigurationForResultsPerPage: number;
private relevanceInspector: RelevanceInspectorModule.RelevanceInspector;
private omniboxAnalytics: OmniboxAnalytics;
/**
* Creates a new SearchInterface. Initialize various singletons for the interface (e.g., usage analytics, query
* controller, state model, etc.). Binds events related to the query.
* @param element The HTMLElement on which to instantiate the component. This cannot be an `HTMLInputElement` for
* technical reasons.
* @param options The options for the SearchInterface.
* @param analyticsOptions The options for the {@link Analytics} component. Since the Analytics component is normally
* global, it needs to be passed at initialization of the whole interface.
* @param _window The window object for the search interface. Used for unit tests, which can pass a mock. Default is
* the global window object.
*/
constructor(public element: HTMLElement, public options?: ISearchInterfaceOptions, public analyticsOptions?, public _window = window) {
super(element, SearchInterface.ID);
this.options = ComponentOptions.initComponentOptions(element, SearchInterface, options);
Assert.exists(element);
Assert.exists(this.options);
this.root = element;
this.setupQueryMode();
this.queryStateModel = new QueryStateModel(element);
this.componentStateModel = new ComponentStateModel(element);
this.componentOptionsModel = new ComponentOptionsModel(element);
this.usageAnalytics = this.initializeAnalytics();
this.queryController = new QueryController(element, this.options, this.usageAnalytics, this);
this.facetValueStateHandler = new FacetValueStateHandler(this);
new SentryLogger(this.queryController);
const missingTermManagerArgs: IMissingTermManagerArgs = {
element: this.element,
queryStateModel: this.queryStateModel,
queryController: this.queryController,
usageAnalytics: this.usageAnalytics
};
new MissingTermManager(missingTermManagerArgs);
this.omniboxAnalytics = new OmniboxAnalytics();
this.setupEventsHandlers();
this.setupHistoryManager(element, _window);
this.setupScrollRestorer(element, _window, this.queryStateModel);
this.element.style.display = element.style.display || 'block';
this.setupDebugInfo();
this.setupResponsiveComponents();
this.ariaLive = new AriaLive(element);
}
public set resultsPerPage(resultsPerPage: number) {
this.options.resultsPerPage = this.queryController.options.resultsPerPage = resultsPerPage;
}
public get resultsPerPage() {
if (this.queryPipelineConfigurationForResultsPerPage != null && this.queryPipelineConfigurationForResultsPerPage != 0) {
return this.queryPipelineConfigurationForResultsPerPage;
}
if (this.queryController.options.resultsPerPage != null && this.queryController.options.resultsPerPage != 0) {
return this.queryController.options.resultsPerPage;
}
// Things would get weird if somehow the number of results per page was set to 0 or not available.
// Specially for the pager component. As such, we try to cover that corner case.
this.logger.warn('Results per page is incoherent in the search interface.', this);
return 10;
}
public getOmniboxAnalytics() {
return this.omniboxAnalytics;
}
/**
* Attaches a component to the search interface. This allows the search interface to easily list and iterate over its
* components.
* @param type Normally, the component type is a unique identifier without the `Coveo` prefix (e.g., `CoveoFacet` ->
* `Facet`, `CoveoPager` -> `Pager`, `CoveoQuerybox` -> `Querybox`, etc.).
* @param component The component instance to attach.
*/
public attachComponent(type: string, component: BaseComponent) {
this.getComponents(type).push(component);
}
/**
* Detaches a component from the search interface.
* @param type Normally, the component type is a unique identifier without the `Coveo` prefix (e.g., `CoveoFacet` ->
* `Facet`, `CoveoPager` -> `Pager`, `CoveoQuerybox` -> `Querybox`, etc.).
* @param component The component instance to detach.
*/
public detachComponent(type: string, component: BaseComponent) {
const components = this.getComponents(type);
const index = indexOf(components, component);
if (index > -1) {
components.splice(index, 1);
}
}
/**
* Returns the bindings, or environment, for the current component.
* @returns {IComponentBindings}
*/
public getBindings() {
return {
root: this.root,
queryStateModel: this.queryStateModel,
queryController: this.queryController,
searchInterface: <SearchInterface>this,
componentStateModel: this.componentStateModel,
componentOptionsModel: this.componentOptionsModel,
usageAnalytics: this.usageAnalytics
};
}
/**
* Gets the query context for the current search interface.
*
* If the search interface has performed at least one query, it will try to resolve the context from the last query sent to the Coveo Search API.
*
* If the search interface has not performed a query yet, it will try to resolve the context from any avaiable {@link PipelineContext} component.
*
* If multiple {@link PipelineContext} components are available, it will merge all context values together.
*
* **Note:**
* Having multiple PipelineContext components in the same search interface is not recommended, especially if some context keys are repeated across those components.
*
* If no context is found, returns `undefined`
*/
public getQueryContext(): Context {
let ret: Context;
const lastQuery = this.queryController.getLastQuery();
if (lastQuery.context) {
ret = lastQuery.context;
} else {
const pipelines = this.getComponents<IPipelineContextProvider>('PipelineContext');
if (pipelines && !isEmpty(pipelines)) {
const contextMerged = chain(pipelines)
.map(pipeline => pipeline.getContext())
.reduce((memo, context) => ({ ...memo, ...context }), {})
.value();
if (!isEmpty(contextMerged)) {
ret = contextMerged;
}
}
}
return ret;
}
/**
* Gets all the components of a given type.
* @param type Normally, the component type is a unique identifier without the `Coveo` prefix (e.g., `CoveoFacet` ->
* `Facet`, `CoveoPager` -> `Pager`, `CoveoQuerybox` -> `Querybox`, etc.).
*/
public getComponents<T>(type: string): T[];
/**
* Gets all the components of a given type.
* @param type Normally, the component type is a unique identifier without the `Coveo` prefix (e.g., `CoveoFacet` ->
* `Facet`, `CoveoPager` -> `Pager`, `CoveoQuerybox` -> `Querybox`, etc.).
*/
public getComponents(type: string): BaseComponent[] {
if (this.attachedComponents == null) {
this.attachedComponents = {};
}
if (!(type in this.attachedComponents)) {
this.attachedComponents[type] = [];
}
return this.attachedComponents[type];
}
/**
* Detaches from the SearchInterface every component that is inside the given element.
* @param element
*/
public detachComponentsInside(element: HTMLElement) {
each(this.attachedComponents, (components, type) => {
components
.filter(component => element != component.element && element.contains(component.element))
.forEach(component => this.detachComponent(type, component));
});
}
protected initializeAnalytics(): IAnalyticsClient {
const analyticsRef = BaseComponent.getComponentRef('Analytics');
if (analyticsRef) {
return analyticsRef.create(this.element, this.analyticsOptions, this.getBindings());
}
return new NoopAnalyticsClient();
}
private setupHistoryManager(element: HTMLElement, _window: Window) {
if (!this.options.enableHistory) {
this.historyManager = new NoopHistoryController();
$$(this.element).on(InitializationEvents.restoreHistoryState, () =>
this.queryStateModel.setMultiple({ ...this.queryStateModel.defaultAttributes })
);
return;
}
if (this.options.useLocalStorageForHistory) {
this.historyManager = new LocalStorageHistoryController(element, _window, this.queryStateModel, this.queryController);
return;
}
this.historyManager = new HistoryController(element, _window, this.queryStateModel, this.queryController);
}
private setupQueryMode() {
if (this.options.allowQueriesWithoutKeywords) {
this.initializeEmptyQueryAllowed();
} else {
this.initializeEmptyQueryNotAllowed();
}
}
private setupEventsHandlers() {
const eventName = this.queryStateModel.getEventName(Model.eventTypes.preprocess);
$$(this.element).on(eventName, (e, args) => this.handlePreprocessQueryStateModel(args));
$$(this.element).on(QueryEvents.buildingQuery, (e, args) => this.handleBuildingQuery(args));
$$(this.element).on(QueryEvents.querySuccess, (e, args) => this.handleQuerySuccess(args));
$$(this.element).on(QueryEvents.queryError, (e, args) => this.handleQueryError(args));
$$(this.element).on(InitializationEvents.afterComponentsInitialization, () => this.handleAfterComponentsInitialization());
const debugChanged = this.queryStateModel.getEventName(Model.eventTypes.changeOne + QueryStateModel.attributesEnum.debug);
$$(this.element).on(debugChanged, (e, args: IAttributeChangedEventArg) => this.handleDebugModeChange(args));
this.queryStateModel.registerNewAttribute(QueryStateModel.attributesEnum.fv, {});
const eventNameQuickview = this.queryStateModel.getEventName(Model.eventTypes.changeOne + QueryStateModel.attributesEnum.quickview);
$$(this.element).on(eventNameQuickview, (e, args) => this.handleQuickviewChanged(args));
}
private setupDebugInfo() {
if (this.options.enableDebugInfo) {
setTimeout(() => new Debug(this.element, this.getBindings()));
}
}
private setupScrollRestorer(element: HTMLElement, _window: Window, queryStateModel: QueryStateModel) {
if (this.options.enableScrollRestoration) {
this.scrollRestorer = new ScrollRestorer(element, queryStateModel);
}
}
private setupResponsiveComponents() {
this.responsiveComponents = new ResponsiveComponents();
this.responsiveComponents.setMediumScreenWidth(this.options.responsiveMediumBreakpoint);
this.responsiveComponents.setSmallScreenWidth(this.options.responsiveSmallBreakpoint);
this.responsiveComponents.setResponsiveMode(this.options.responsiveMode);
}
private handleDebugModeChange(args: IAttributeChangedEventArg) {
if (args.value && !this.relevanceInspector && this.options.enableDebugInfo) {
require.ensure(
['../RelevanceInspector/RelevanceInspector'],
() => {
const loadedModule = require('../RelevanceInspector/RelevanceInspector.ts');
const relevanceInspectorCtor = loadedModule.RelevanceInspector as RelevanceInspectorModule.IRelevanceInspectorConstructor;
const relevanceInspectorElement = $$('btn');
$$(this.element).prepend(relevanceInspectorElement.el);
this.relevanceInspector = new relevanceInspectorCtor(relevanceInspectorElement.el, this.getBindings());
},
null,
'RelevanceInspector'
);
}
}
private handlePreprocessQueryStateModel(args: Record<string, any>) {
const tgFromModel = this.queryStateModel.get(QueryStateModel.attributesEnum.tg);
const tFromModel = this.queryStateModel.get(QueryStateModel.attributesEnum.t);
let tg = tgFromModel;
let t = tFromModel;
// if you want to set the tab group
if (args && args.tg !== undefined) {
args.tg = this.getTabGroupId(args.tg);
if (tg != args.tg) {
args.t = args.t || QueryStateModel.defaultAttributes.t;
args.sort = args.sort || QueryStateModel.defaultAttributes.sort;
tg = args.tg;
}
}
if (args && args.t !== undefined) {
args.t = this.getTabId(tg, args.t);
if (t != args.t) {
args.sort = args.sort || QueryStateModel.defaultAttributes.sort;
t = args.t;
}
}
if (args && args.sort !== undefined) {
args.sort = this.getSort(t, args.sort);
}
if (args && args.quickview !== undefined) {
args.quickview = this.getQuickview(args.quickview);
}
// `fv:` states are intended to be redirected and used on a standard Search Interface,
// else the state gets transformed to `hd` before the redirection.
if (args && args.fv && !(this instanceof StandaloneSearchInterface)) {
this.facetValueStateHandler.handleFacetValueState(args);
}
}
private getTabGroupId(tabGroupId: string) {
const tabGroupRef = BaseComponent.getComponentRef('TabGroup');
if (tabGroupRef) {
const tabGroups = this.getComponents<any>(tabGroupRef.ID);
// check if the tabgroup is correct
if (
tabGroupId != QueryStateModel.defaultAttributes.tg &&
any(tabGroups, (tabGroup: any) => !tabGroup.disabled && tabGroupId == tabGroup.options.id)
) {
return tabGroupId;
}
// select the first tabGroup
if (tabGroups.length > 0) {
return tabGroups[0].options.id;
}
}
return QueryStateModel.defaultAttributes.tg;
}
private getTabId(tabGroupId: string, tabId: string) {
const tabRef = BaseComponent.getComponentRef('Tab');
const tabGroupRef = BaseComponent.getComponentRef('TabGroup');
if (tabRef) {
const tabs = this.getComponents<any>(tabRef.ID);
if (tabGroupRef) {
// if has a tabGroup
if (tabGroupId != QueryStateModel.defaultAttributes.tg) {
const tabGroups = this.getComponents<any>(tabGroupRef.ID);
const tabGroup = find(tabGroups, (tabGroup: any) => tabGroupId == tabGroup.options.id);
// check if the tabgroup contain this tab
if (
tabId != QueryStateModel.defaultAttributes.t &&
any(tabs, (tab: any) => tabId == tab.options.id && tabGroup.isElementIncludedInTabGroup(tab.element))
) {
return tabId;
}
// select the first tab in the tabGroup
const tab = find(tabs, (tab: any) => tabGroup.isElementIncludedInTabGroup(tab.element));
if (tab != null) {
return tab.options.id;
}
return QueryStateModel.defaultAttributes.t;
}
}
// check if the tab is correct
if (tabId != QueryStateModel.defaultAttributes.t && any(tabs, (tab: any) => tabId == tab.options.id)) {
return tabId;
}
// select the first tab
if (tabs.length > 0) {
return tabs[0].options.id;
}
}
return QueryStateModel.defaultAttributes.t;
}
private getSort(tabId: string, sortId: string) {
const sortRef = BaseComponent.getComponentRef('Sort');
if (sortRef) {
const sorts = this.getComponents<any>(sortRef.ID);
// if has a selected tab
const tabRef = BaseComponent.getComponentRef('Tab');
if (tabRef) {
if (tabId != QueryStateModel.defaultAttributes.t) {
const tabs = this.getComponents<any>(tabRef.ID);
const tab = find(tabs, (tab: any) => tabId == tab.options.id);
const sortCriteria = tab.options.sort;
// check if the tab contain this sort
if (
sortId != QueryStateModel.defaultAttributes.sort &&
any(sorts, (sort: any) => tab.isElementIncludedInTab(sort.element) && sort.match(sortId))
) {
return sortId;
} else if (sortCriteria != null) {
// if not and tab.options.sort is set apply it
return sortCriteria.toString();
}
// select the first sort in the tab
const sort = find(sorts, (sort: any) => tab.isElementIncludedInTab(sort.element));
if (sort != null) {
return sort.options.sortCriteria[0].toString();
}
return QueryStateModel.defaultAttributes.sort;
}
}
// check if the sort is correct
if (sortId != QueryStateModel.defaultAttributes.sort && any(sorts, (sort: any) => sort.match(sortId))) {
return sortId;
}
// select the first sort
if (sorts.length > 0) {
return sorts[0].options.sortCriteria[0].toString();
}
}
return QueryStateModel.defaultAttributes.sort;
}
private getQuickview(quickviewId: string) {
const quickviewRef = BaseComponent.getComponentRef('Quickview');
if (quickviewRef) {
const quickviews = this.getComponents<any>(quickviewRef.ID);
if (any(quickviews, (quickview: any) => quickview.getHashId() == quickviewId)) {
return quickviewId;
}
}
return QueryStateModel.defaultAttributes.quickview;
}
private handleQuickviewChanged(args: IAttributeChangedEventArg) {
const quickviewRef = BaseComponent.getComponentRef('Quickview');
if (quickviewRef) {
const quickviews = this.getComponents<any>(quickviewRef.ID);
if (args.value != '') {
const quickviewsPartition = partition(quickviews, quickview => quickview.getHashId() == args.value);
if (quickviewsPartition[0].length != 0) {
first(quickviewsPartition[0]).open();
each(tail(quickviewsPartition[0]), quickview => quickview.close());
}
each(quickviewsPartition[1], quickview => quickview.close());
} else {
each(quickviews, quickview => {
quickview.close();
});
}
}
}
private handleBuildingQuery(data: IBuildingQueryEventArgs) {
if (this.options.enableDuplicateFiltering) {
data.queryBuilder.enableDuplicateFiltering = true;
}
if (!Utils.isNullOrUndefined(this.options.pipeline)) {
data.queryBuilder.pipeline = this.options.pipeline;
}
if (!Utils.isNullOrUndefined(this.options.maximumAge)) {
data.queryBuilder.maximumAge = this.options.maximumAge;
}
if (!Utils.isNullOrUndefined(this.options.resultsPerPage)) {
data.queryBuilder.numberOfResults = this.options.resultsPerPage;
}
if (!Utils.isNullOrUndefined(this.options.excerptLength)) {
data.queryBuilder.excerptLength = this.options.excerptLength;
}
if (Utils.isNonEmptyString(this.options.expression)) {
data.queryBuilder.constantExpression.add(this.options.expression);
}
if (Utils.isNonEmptyString(<string>this.options.filterField)) {
data.queryBuilder.filterField = <string>this.options.filterField;
}
if (Utils.isNonEmptyString(this.options.timezone)) {
data.queryBuilder.timezone = this.options.timezone;
}
data.queryBuilder.enableCollaborativeRating = this.options.enableCollaborativeRating;
data.queryBuilder.enableDuplicateFiltering = this.options.enableDuplicateFiltering;
data.queryBuilder.allowQueriesWithoutKeywords = this.options.allowQueriesWithoutKeywords;
const endpoint = this.queryController.getEndpoint();
if (endpoint != null && endpoint.options) {
if (this.queryStateModel.get(QueryStateModel.attributesEnum.debug)) {
data.queryBuilder.maximumAge = 0;
data.queryBuilder.enableDebug = true;
data.queryBuilder.fieldsToExclude = ['allmetadatavalues'];
data.queryBuilder.fieldsToInclude = null;
}
}
}
private handleQuerySuccess(data: IQuerySuccessEventArgs) {
const noResults = data.results.results.length == 0;
this.toggleSectionState('coveo-no-results', noResults);
this.handlePossiblyModifiedNumberOfResultsInQueryPipeline(data);
const resultsHeader = $$(this.element).find('.coveo-results-header');
if (resultsHeader) {
$$(resultsHeader).removeClass('coveo-query-error');
}
}
private handlePossiblyModifiedNumberOfResultsInQueryPipeline(data: IQuerySuccessEventArgs) {
if (!data || !data.query || !data.results) {
return;
}
const numberOfRequestedResults = data.query.numberOfResults;
const numberOfResultsActuallyReturned = data.results.results.length;
const areLastPageResults = data.results.totalCountFiltered - data.query.firstResult === numberOfResultsActuallyReturned;
const moreResultsAvailable = !areLastPageResults && data.results.totalCountFiltered > numberOfResultsActuallyReturned;
if (numberOfRequestedResults != numberOfResultsActuallyReturned && moreResultsAvailable) {
this.isResultsPerPageModifiedByPipeline = true;
this.queryPipelineConfigurationForResultsPerPage = numberOfResultsActuallyReturned;
} else {
this.isResultsPerPageModifiedByPipeline = false;
this.queryPipelineConfigurationForResultsPerPage = null;
}
}
private handleQueryError(data: IQueryErrorEventArgs) {
this.toggleSectionState('coveo-no-results');
const resultsHeader = $$(this.element).find('.coveo-results-header');
if (resultsHeader) {
$$(resultsHeader).addClass('coveo-query-error');
}
}
private handleAfterComponentsInitialization() {
each(this.attachedComponents, components => {
components.forEach(component => {
if (FacetColumnAutoLayoutAdjustment.isAutoLayoutAdjustable(component)) {
FacetColumnAutoLayoutAdjustment.initializeAutoLayoutAdjustment(this.element, component);
}
});
});
if (this.duplicatesFacets.length) {
this.logger.warn(
`The following facets have duplicate id/field:`,
this.duplicatesFacets,
`Ensure that each facet in your search interface has a unique id.`
);
}
}
private get duplicatesFacets() {
const duplicate = [];
const facets = ComponentsTypes.getAllFacetsFromSearchInterface(this);
facets.forEach(facet => {
facets.forEach(cmp => {
if (facet == cmp) {
return;
}
if (facet.options.id === cmp.options.id) {
duplicate.push(facet);
return;
}
});
});
return duplicate;
}
private toggleSectionState(cssClass: string, toggle = true) {
const facetSection = $$(this.element).find('.coveo-facet-column');
const resultsSection = $$(this.element).find('.coveo-results-column');
const resultsHeader = $$(this.element).find('.coveo-results-header');
const facetSearchs = $$(this.element).findAll('.coveo-facet-search-results');
const recommendationSection = $$(this.element).find('.coveo-recommendation-main-section');
if (facetSection) {
$$(facetSection).toggleClass(cssClass, toggle && !this.queryStateModel.atLeastOneFacetIsActive());
}
if (resultsSection) {
$$(resultsSection).toggleClass(cssClass, toggle && !this.queryStateModel.atLeastOneFacetIsActive());
}
if (resultsHeader) {
$$(resultsHeader).toggleClass(cssClass, toggle && !this.queryStateModel.atLeastOneFacetIsActive());
}
if (recommendationSection) {
$$(recommendationSection).toggleClass(cssClass, toggle);
}
if (facetSearchs && facetSearchs.length > 0) {
each(facetSearchs, facetSearch => {
$$(facetSearch).toggleClass(cssClass, toggle && !this.queryStateModel.atLeastOneFacetIsActive());
});
}
}
private initializeEmptyQueryAllowed() {
new InitializationPlaceholder(this.element).withFullInitializationStyling().withAllPlaceholders();
}
private initializeEmptyQueryNotAllowed() {
const placeholder = new InitializationPlaceholder(this.element)
.withEventToRemovePlaceholder(QueryEvents.newQuery)
.withFullInitializationStyling()
.withHiddenRootElement()
.withPlaceholderForFacets()
.withPlaceholderForResultList();
$$(this.root).on(InitializationEvents.restoreHistoryState, () => {
placeholder.withVisibleRootElement();
if (this.queryStateModel.get('q') == '') {
placeholder.withWaitingForFirstQueryMode();
}
});
$$(this.element).on(QueryEvents.doneBuildingQuery, (e, args: IDoneBuildingQueryEventArgs) => {
if (!args.queryBuilder.containsEndUserKeywords()) {
const lastQuery = this.queryController.getLastQuery().q;
if (Utils.isNonEmptyString(lastQuery)) {
this.queryStateModel.set(QUERY_STATE_ATTRIBUTES.Q, lastQuery);
args.queryBuilder.expression.add(lastQuery);
} else {
this.logger.info('Query cancelled by the Search Interface', 'Configuration does not allow empty query', this, this.options);
args.cancel = true;
this.queryStateModel.reset();
new InitializationPlaceholder(this.element)
.withEventToRemovePlaceholder(QueryEvents.newQuery)
.withFullInitializationStyling()
.withVisibleRootElement()
.withPlaceholderForFacets()
.withPlaceholderForResultList()
.withWaitingForFirstQueryMode();
}
}
});
}
}
export interface IStandaloneSearchInterfaceOptions extends ISearchInterfaceOptions {
redirectIfEmpty?: boolean;
}
export class StandaloneSearchInterface extends SearchInterface {
static ID = 'StandaloneSearchInterface';
public static options: IStandaloneSearchInterfaceOptions = {
redirectIfEmpty: ComponentOptions.buildBooleanOption({ defaultValue: true })
};
constructor(
public element: HTMLElement,
public options?: IStandaloneSearchInterfaceOptions,
public analyticsOptions?,
public _window = window
) {
super(element, ComponentOptions.initComponentOptions(element, StandaloneSearchInterface, options), analyticsOptions, _window);
$$(this.root).on(QueryEvents.newQuery, (e: Event, args: INewQueryEventArgs) => this.handleRedirect(e, args));
}
public handleRedirect(e: Event, data: INewQueryEventArgs) {
if (data.shouldRedirectStandaloneSearchbox === false) {
return;
}
const dataToSendOnBeforeRedirect: IBeforeRedirectEventArgs = {
searchPageUri: this.options.searchPageUri,
cancel: false
};
$$(this.root).trigger(StandaloneSearchInterfaceEvents.beforeRedirect, dataToSendOnBeforeRedirect);
if (dataToSendOnBeforeRedirect.cancel) {
return;
}
data.cancel = true;
if (!this.searchboxIsEmpty() || this.options.redirectIfEmpty) {
this.doRedirect(dataToSendOnBeforeRedirect.searchPageUri);
}
}
private async doRedirect(searchPage: string) {
const cachedHashValue = this.encodedHashValues;
const executionPlan = await this.queryController.fetchQueryExecutionPlan();
const redirectionURL = executionPlan && executionPlan.redirectionURL;
if (!redirectionURL) {
return this.redirectToSearchPage(searchPage, cachedHashValue);
}
this.redirectToURL(redirectionURL);
}
public redirectToURL(url: string) {
this.usageAnalytics.logCustomEvent<IAnalyticsTriggerRedirect>(
analyticsActionCauseList.triggerRedirect,
{
redirectedTo: url,
query: this.queryStateModel.get(QueryStateModel.attributesEnum.q)
},
this.element
);
this._window.location.assign(url);
}
public redirectToSearchPage(searchPage: string, hashValueToUse?: string) {
const link = document.createElement('a');
link.href = searchPage;
link.href = link.href; // IE11 needs this to correctly fill the properties that are used below.
const pathname = link.pathname.indexOf('/') == 0 ? link.pathname : '/' + link.pathname; // IE11 does not add a leading slash to this property.
const hash = link.hash ? link.hash + '&' : '#';
const hashValue = hashValueToUse || this.encodedHashValues;
// By using a setTimeout, we allow other possible code related to the search box / magic box time to complete.
// eg: onblur of the magic box.
setTimeout(() => {
this._window.location.href = `${link.protocol}//${link.host}${pathname}${link.search}${hash}${hashValue}`;
}, 0);
}
private get encodedHashValues() {
const values = {
...this.modelAttributesToIncludeInUrl,
...this.uaCausedByAttribute,
...this.uaMetadataAttribute
};
return HashUtils.encodeValues(values);
}
private get modelAttributesToIncludeInUrl() {
const usingLocalStorageHistory = this.historyManager instanceof LocalStorageHistoryController;
return usingLocalStorageHistory ? {} : this.queryStateModel.getAttributes();
}
private get uaCausedByAttribute() {
const uaCausedBy = this.uaCausedBy;
return uaCausedBy ? { firstQueryCause: uaCausedBy } : {};
}
private get uaCausedBy() {
const uaCausedBy = this.usageAnalytics.getCurrentEventCause();
const isSearchboxSubmit = uaCausedBy === analyticsActionCauseList.searchboxSubmit.name;
// For legacy reasons, searchbox submit were always logged as a search from link in an external search box.
return isSearchboxSubmit ? analyticsActionCauseList.searchFromLink.name : uaCausedBy;
}
private get uaMetadataAttribute() {
const uaMeta = this.usageAnalytics.getCurrentEventMeta();
return uaMeta && !isEmpty(uaMeta) ? { firstQueryMeta: uaMeta } : {};
}
private searchboxIsEmpty(): boolean {
return Utils.isEmptyString(this.queryStateModel.get(QueryStateModel.attributesEnum.q));
}
} | the_stack |
import type {
BraintreeCallback,
BraintreeCurrencyAmount,
BraintreeAddress,
BraintreeLineItem,
BraintreeTokenizePayload,
} from "./commonsTypes";
import type { BraintreeClient } from "./clientTypes";
import type { ReactPayPalScriptOptions } from "../scriptProviderTypes";
export interface BraintreeShippingOption {
/**
* A unique ID that identifies a payer-selected shipping option.
*/
id: string;
/**
* A description that the payer sees, which helps them choose an appropriate shipping option.
* For example, `Free Shipping`, `USPS Priority Shipping`, `Expédition prioritaire USPS`,
* or `USPS yōuxiān fā huò`. Localize this description to the payer's locale.
*/
label: string;
/**
* If `selected = true` is specified as part of the API request it represents the shipping
* option that the payee/merchant expects to be pre-selected for the payer when they first view
* the shipping options within the PayPal checkout experience. As part of the response if a
* shipping option has `selected = true` it represents the shipping option that the payer
* selected during the course of checkout with PayPal. Only 1 `shippingOption` can be set
* to `selected = true`.
*/
selected: boolean;
/**
* The method by which the payer wants to get their items.
*/
type: "SHIPPING" | "PICKUP";
/**
* The shipping cost for the selected option.
*/
amount: BraintreeCurrencyAmount;
}
export interface BraintreePayPalCheckoutCreatePaymentOptions {
flow: "vault" | "checkout";
intent?: "authorize" | "order" | "capture" | undefined;
offerCredit?: boolean | undefined;
amount?: string | number | undefined;
currency?: string | undefined;
displayName?: string | undefined;
locale?: string | undefined;
vaultInitiatedCheckoutPaymentMethodToken?: string | undefined;
shippingOptions?: BraintreeShippingOption[] | undefined;
enableShippingAddress?: boolean | undefined;
shippingAddressOverride?: BraintreeAddress | undefined;
shippingAddressEditable?: boolean | undefined;
billingAgreementDescription?: string | undefined;
landingPageType?: string | undefined;
lineItems?: BraintreeLineItem[] | undefined;
}
export interface BraintreePayPalCheckoutTokenizationOptions {
payerID: string;
orderID: string;
paymentID?: string;
paymentToken?: string;
billingToken?: string;
shippingOptionsId?: string;
vault?: boolean;
}
export interface BraintreePayPalCheckout {
/**
* @description There are two ways to integrate the PayPal Checkout component.
* See the [PayPal Checkout constructor documentation](PayPalCheckout.html#PayPalCheckout) for more information and examples.
* @example
* braintree.client.create({
* authorization: 'authorization'
* }).then(function (clientInstance) {
* return braintree.paypalCheckout.create({
* client: clientInstance
* });
* }).then(function (paypalCheckoutInstance) {
* // set up checkout.js
* }).catch(function (err) {
* console.error('Error!', err);
* });
*/
create(options: {
client?: BraintreeClient | undefined;
authorization?: string | undefined;
merchantAccountId?: string | undefined;
}): Promise<BraintreePayPalCheckout>;
/**
* Resolves when the PayPal SDK has been succesfully loaded onto the page.
*
* @link https://braintree.github.io/braintree-web/current/PayPalCheckout.html#loadPayPalSDK
*/
loadPayPalSDK(options?: ReactPayPalScriptOptions): Promise<void>;
/**
* @description The current version of the SDK, i.e. `3.0.2`.
*/
VERSION: string;
/**
* Creates a PayPal payment ID or billing token using the given options. This is meant to be passed to PayPal's checkout.js library.
* When a {@link Callback} is defined, the function returns undefined and invokes the callback with the id to be used with the checkout.js
* library. Otherwise, it returns a Promise that resolves with the id.
* `authorize` - Submits the transaction for authorization but not settlement.
* `order` - Validates the transaction without an authorization (i.e. without holding funds).
* Useful for authorizing and capturing funds up to 90 days after the order has been placed. Only available for Checkout flow.
* `capture` - Payment will be immediately submitted for settlement upon creating a transaction.
* `sale` can be used as an alias for this value.
* Supported locales are:
* `da_DK`,
* `de_DE`,
* `en_AU`,
* `en_GB`,
* `en_US`,
* `es_ES`,
* `fr_CA`,
* `fr_FR`,
* `id_ID`,
* `it_IT`,
* `ja_JP`,
* `ko_KR`,
* `nl_NL`,
* `no_NO`,
* `pl_PL`,
* `pt_BR`,
* `pt_PT`,
* `ru_RU`,
* `sv_SE`,
* `th_TH`,
* `zh_CN`,
* `zh_HK`,
* and `zh_TW`.
* * * `login` - A PayPal account login page is used.
* * `billing` - A non-PayPal account landing page is used.
* // this paypal object is created by checkout.js
* // see https://github.com/paypal/paypal-checkout
* paypal.Buttons({
* createOrder: function () {
* // when createPayment resolves, it is automatically passed to checkout.js
* return paypalCheckoutInstance.createPayment({
* flow: 'checkout',
* amount: '10.00',
* currency: 'USD',
* intent: 'capture' // this value must either be `capture` or match the intent passed into the PayPal SDK intent query parameter
* });
* },
* // Add other options, e.g. onApproved, onCancel, onError
* }).render('#paypal-button');
*
* @example
* // shippingOptions are passed to createPayment. You can review the result from onAuthorize to determine which shipping option id was selected.
* ```javascript
* braintree.client.create({
* authorization: 'authorization'
* }).then(function (clientInstance) {
* return braintree.paypalCheckout.create({
* client: clientInstance
* });
* }).then(function (paypalCheckoutInstance) {
* return paypal.Button.render({
* env: 'production'
*
* payment: function () {
* return paypalCheckoutInstance.createPayment({
* flow: 'checkout',
* amount: '10.00',
* currency: 'USD',
* shippingOptions: [
* {
* id: 'UUID-9',
* type: 'PICKUP',
* label: 'Store Location Five',
* selected: true,
* amount: {
* value: '1.00',
* currency: 'USD'
* }
* },
* {
* id: 'shipping-speed-fast',
* type: 'SHIPPING',
* label: 'Fast Shipping',
* selected: false,
* amount: {
* value: '1.00',
* currency: 'USD'
* }
* },
* {
* id: 'shipping-speed-slow',
* type: 'SHIPPING',
* label: 'Slow Shipping',
* selected: false,
* amount: {
* value: '1.00',
* currency: 'USD'
* }
* }
* ]
* });
* },
*
* onAuthorize: function (data, actions) {
* return paypalCheckoutInstance.tokenizePayment(data).then(function (payload) {
* // Submit payload.nonce to your server
* });
* }
* }, '#paypal-button');
* }).catch(function (err) {
* console.error('Error!', err);
* });
* ```
*
*/
createPayment(
options: BraintreePayPalCheckoutCreatePaymentOptions,
callback?: BraintreeCallback
): Promise<string>;
/**
* Tokenizes the authorize data from PayPal's checkout.js library when completing a buyer approval flow.
* When a {@link callback} is defined, invokes the callback with {@link BraintreePayPalCheckout~tokenizePayload|tokenizePayload} and returns undefined.
* Otherwise, returns a Promise that resolves with a {@link BraintreePayPalCheckout~tokenizePayload|tokenizePayload}.
* @example <caption>Opt out of auto-vaulting behavior</caption>
* // create the paypalCheckoutInstance with a client token generated with a customer id
* paypal.Buttons({
* createBillingAgreement: function () {
* return paypalCheckoutInstance.createPayment({
* flow: 'vault'
* // your other createPayment options here
* });
* },
* onApproved: function (data) {
* data.vault = false;
*
* return paypalCheckoutInstance.tokenizePayment(data);
* },
* // Add other options, e.g. onCancel, onError
* }).render('#paypal-button');
*
*/
tokenizePayment(
tokenizeOptions: BraintreePayPalCheckoutTokenizationOptions
): Promise<BraintreeTokenizePayload>;
/**
* Resolves with the PayPal client id to be used when loading the PayPal SDK. * @example
* paypalCheckoutInstance.getClientId().then(function (id) {
* var script = document.createElement('script');
*
* script.src = 'https://www.paypal.com/sdk/js?client-id=' + id;
* script.onload = function () {
* // setup the PayPal SDK
* };
*
* document.body.appendChild(script);
* });
*/
getClientId(): Promise<string>;
/**
* Initializes the PayPal checkout flow with a payment method nonce that represents a vaulted PayPal account.
* When a {@link callback} is defined, the function returns undefined and invokes the callback with the id to be used with the checkout.js library.
* Otherwise, it returns a Promise that resolves with the id.
* `flow` cannot be set (will always be `'checkout'`)
* `amount`, `currency`, and `vaultInitiatedCheckoutPaymentMethodToken` are required instead of optional
* * Additional configuration is available (listed below)
* @example
* paypalCheckoutInstance.startVaultInitiatedCheckout({
* vaultInitiatedCheckoutPaymentMethodToken: 'nonce-that-represents-a-vaulted-paypal-account',
* amount: '10.00',
* currency: 'USD'
* }).then(function (payload) {
* // send payload.nonce to your server
* }).catch(function (err) {
* if (err.code === 'PAYPAL_POPUP_CLOSED') {
* // indicates that customer canceled by
* // manually closing the PayPal popup
* }
*
* // handle other errors
* });
*
*/
startVaultInitiatedCheckout(options: {
optOutOfModalBackdrop: boolean;
}): Promise<void>;
/**
* Cleanly tear down anything set up by {@link module:braintree-web/paypal-checkout.create|create}.
* @example
* paypalCheckoutInstance.teardown();
* @example <caption>With callback</caption>
* paypalCheckoutInstance.teardown(function () {
* // teardown is complete
* });
*/
teardown(): Promise<void>;
} | the_stack |
import * as React from 'react'
import {
useCombobox,
useMultipleSelection,
UseMultipleSelectionProps
} from 'downshift'
import matchSorter from 'match-sorter'
import Highlighter from 'react-highlight-words'
import useDeepCompareEffect from 'react-use/lib/useDeepCompareEffect'
import { FormLabel, FormLabelProps } from '@chakra-ui/form-control'
import {
Text,
Stack,
Box,
BoxProps,
List,
ListItem,
ListIcon
} from '@chakra-ui/layout'
import { Button, ButtonProps } from '@chakra-ui/button'
import { Input, InputProps } from '@chakra-ui/input'
import { IconProps, CheckCircleIcon, ArrowDownIcon } from '@chakra-ui/icons'
import { Tag, TagCloseButton, TagLabel, TagProps } from '@chakra-ui/tag'
import { ComponentWithAs } from '@chakra-ui/react'
export interface Item {
label: string
value: string
}
export interface CUIAutoCompleteProps<T extends Item>
extends UseMultipleSelectionProps<T> {
items: T[]
placeholder: string
label: string
highlightItemBg?: string
onCreateItem?: (item: T) => void
optionFilterFunc?: (items: T[], inputValue: string) => T[]
itemRenderer?: (item: T) => string | JSX.Element
labelStyleProps?: FormLabelProps
inputStyleProps?: InputProps
toggleButtonStyleProps?: ButtonProps
tagStyleProps?: TagProps
listStyleProps?: BoxProps
listItemStyleProps?: BoxProps
emptyState?: (inputValue: string) => React.ReactNode
selectedIconProps?: Omit<IconProps, 'name'> & {
icon: IconProps['name'] | React.ComponentType
}
icon?: ComponentWithAs<'svg', IconProps>
hideToggleButton?: boolean
createItemRenderer?: (value: string) => string | JSX.Element
disableCreateItem?: boolean
renderCustomInput?: (inputProps: any, toggleButtonProps: any) => JSX.Element
}
function defaultOptionFilterFunc<T>(items: T[], inputValue: string) {
return matchSorter(items, inputValue, { keys: ['value', 'label'] })
}
function defaultCreateItemRenderer(value: string) {
return (
<Text>
<Box as='span'>Create</Box>{' '}
<Box as='span' bg='yellow.300' fontWeight='bold'>
"{value}"
</Box>
</Text>
)
}
export const CUIAutoComplete = <T extends Item>(
props: CUIAutoCompleteProps<T>
): React.ReactElement<CUIAutoCompleteProps<T>> => {
const {
items,
optionFilterFunc = defaultOptionFilterFunc,
itemRenderer,
highlightItemBg = 'gray.100',
placeholder,
label,
listStyleProps,
labelStyleProps,
inputStyleProps,
toggleButtonStyleProps,
tagStyleProps,
selectedIconProps,
listItemStyleProps,
onCreateItem,
icon,
hideToggleButton = false,
disableCreateItem = false,
createItemRenderer = defaultCreateItemRenderer,
renderCustomInput,
...downshiftProps
} = props
/* States */
const [isCreating, setIsCreating] = React.useState(false)
const [inputValue, setInputValue] = React.useState('')
const [inputItems, setInputItems] = React.useState<T[]>(items)
/* Refs */
const disclosureRef = React.useRef(null)
/* Downshift Props */
const {
getSelectedItemProps,
getDropdownProps,
addSelectedItem,
removeSelectedItem,
selectedItems
} = useMultipleSelection(downshiftProps)
const selectedItemValues = selectedItems.map((item) => item.value)
const {
isOpen,
getToggleButtonProps,
getLabelProps,
getMenuProps,
getInputProps,
getComboboxProps,
highlightedIndex,
getItemProps,
openMenu,
selectItem,
setHighlightedIndex
} = useCombobox({
inputValue,
selectedItem: undefined,
items: inputItems,
onInputValueChange: ({ inputValue, selectedItem }) => {
const filteredItems = optionFilterFunc(items, inputValue || '')
if (isCreating && filteredItems.length > 0) {
setIsCreating(false)
}
if (!selectedItem) {
setInputItems(filteredItems)
}
},
stateReducer: (state, actionAndChanges) => {
const { changes, type } = actionAndChanges
switch (type) {
case useCombobox.stateChangeTypes.InputBlur:
return {
...changes,
isOpen: false
}
case useCombobox.stateChangeTypes.InputKeyDownEnter:
case useCombobox.stateChangeTypes.ItemClick:
return {
...changes,
highlightedIndex: state.highlightedIndex,
inputValue,
isOpen: true
}
case useCombobox.stateChangeTypes.FunctionSelectItem:
return {
...changes,
inputValue
}
default:
return changes
}
},
// @ts-ignore
onStateChange: ({ inputValue, type, selectedItem }) => {
switch (type) {
case useCombobox.stateChangeTypes.InputChange:
setInputValue(inputValue || '')
break
case useCombobox.stateChangeTypes.InputKeyDownEnter:
case useCombobox.stateChangeTypes.ItemClick:
if (selectedItem) {
if (selectedItemValues.includes(selectedItem.value)) {
removeSelectedItem(selectedItem)
} else {
if (onCreateItem && isCreating) {
onCreateItem(selectedItem)
setIsCreating(false)
setInputItems(items)
setInputValue('')
} else {
addSelectedItem(selectedItem)
}
}
// @ts-ignore
selectItem(null)
}
break
default:
break
}
}
})
React.useEffect(() => {
if (inputItems.length === 0 && !disableCreateItem) {
setIsCreating(true)
// @ts-ignore
setInputItems([{ label: `${inputValue}`, value: inputValue }])
setHighlightedIndex(0)
}
}, [
inputItems,
setIsCreating,
setHighlightedIndex,
inputValue,
disableCreateItem
])
useDeepCompareEffect(() => {
setInputItems(items)
}, [items])
/* Default Items Renderer */
function defaultItemRenderer<T extends Item>(selected: T) {
return selected.label
}
return (
<Stack>
<FormLabel {...{ ...getLabelProps({}), ...labelStyleProps }}>
{label}
</FormLabel>
{/* ---------Stack with Selected Menu Tags above the Input Box--------- */}
{selectedItems && (
<Stack spacing={2} isInline flexWrap='wrap'>
{selectedItems.map((selectedItem, index) => (
<Tag
mb={1}
{...tagStyleProps}
key={`selected-item-${index}`}
{...getSelectedItemProps({ selectedItem, index })}
>
<TagLabel>{selectedItem.label}</TagLabel>
<TagCloseButton
onClick={(e) => {
e.stopPropagation()
removeSelectedItem(selectedItem)
}}
aria-label='Remove menu selection badge'
/>
</Tag>
))}
</Stack>
)}
{/* ---------Stack with Selected Menu Tags above the Input Box--------- */}
{/* -----------Section that renders the input element ----------------- */}
<Stack isInline {...getComboboxProps()}>
{renderCustomInput ? (
renderCustomInput(
{
...inputStyleProps,
...getInputProps(
getDropdownProps({
placeholder,
onClick: isOpen ? () => {} : openMenu,
onFocus: isOpen ? () => {} : openMenu,
ref: disclosureRef
})
)
},
{
...toggleButtonStyleProps,
...getToggleButtonProps(),
ariaLabel: 'toggle menu',
hideToggleButton
}
)
) : (
<>
<Input
{...inputStyleProps}
{...getInputProps(
getDropdownProps({
placeholder,
onClick: isOpen ? () => {} : openMenu,
onFocus: isOpen ? () => {} : openMenu,
ref: disclosureRef
})
)}
/>
{!hideToggleButton && (
<Button
{...toggleButtonStyleProps}
{...getToggleButtonProps()}
aria-label='toggle menu'
>
<ArrowDownIcon />
</Button>
)}
</>
)}
</Stack>
{/* -----------Section that renders the input element ----------------- */}
{/* -----------Section that renders the Menu Lists Component ----------------- */}
<Box pb={4} mb={4}>
<List
bg='white'
borderRadius='4px'
border={isOpen && '1px solid rgba(0,0,0,0.1)'}
boxShadow='6px 5px 8px rgba(0,50,30,0.02)'
{...listStyleProps}
{...getMenuProps()}
>
{isOpen &&
inputItems.map((item, index) => (
<ListItem
px={2}
py={1}
borderBottom='1px solid rgba(0,0,0,0.01)'
{...listItemStyleProps}
bg={highlightedIndex === index ? highlightItemBg : 'inherit'}
key={`${item.value}${index}`}
{...getItemProps({ item, index })}
>
{isCreating ? (
createItemRenderer(item.label)
) : (
<Box display='inline-flex' alignItems='center'>
{selectedItemValues.includes(item.value) && (
<ListIcon
as={icon || CheckCircleIcon}
color='green.500'
role='img'
display='inline'
aria-label='Selected'
{...selectedIconProps}
/>
)}
{itemRenderer ? (
itemRenderer(item)
) : (
<Highlighter
autoEscape
searchWords={[inputValue || '']}
textToHighlight={defaultItemRenderer(item)}
/>
)}
</Box>
)}
</ListItem>
))}
</List>
</Box>
{/* ----------- End Section that renders the Menu Lists Component ----------------- */}
</Stack>
)
} | the_stack |
import { FsApi, File, Credentials, Fs, filetype, MakeId } from '../Fs';
import * as fs from 'fs';
import * as path from 'path';
import mkdir = require('mkdirp');
import del = require('del');
import { size } from '../../utils/size';
import { throttle } from '../../utils/throttle';
import { Transform, TransformCallback } from 'stream';
import { isWin, HOME_DIR } from '../../utils/platform';
import { LocalWatch } from './LocalWatch';
const invalidDirChars = (isWin && /[\*:<>\?|"]+/gi) || /^[\.]+[\/]+(.)*$/gi;
const invalidFileChars = (isWin && /[\*:<>\?|"]+/gi) || /\//;
const SEP = path.sep;
// Since nodeJS will translate unix like paths to windows path, when running under Windows
// we accept Windows style paths (eg. C:\foo...) and unix paths (eg. /foo or ./foo)
const localStart = (isWin && /^(([a-zA-Z]\:)|([\.]*\/|\.)|(\\\\)|~)/) || /^([\.]*\/|\.|~)/;
const isRoot = (isWin && /((([a-zA-Z]\:)(\\)*)|(\\\\))$/) || /^\/$/;
const progressFunc = throttle((progress: (pourcent: number) => void, bytesRead: number) => {
progress(bytesRead);
}, 400);
export class LocalApi implements FsApi {
type = 0;
// current path
path: string;
loginOptions: Credentials = null;
onFsChange: (filename: string) => void;
constructor(_: string, onFsChange: (filename: string) => void) {
this.path = '';
this.onFsChange = onFsChange;
}
// local fs doesn't require login
isConnected(): boolean {
return true;
}
isDirectoryNameValid(dirName: string): boolean {
return !!!dirName.match(invalidDirChars) && dirName !== '/';
}
join(...paths: string[]): string {
return path.join(...paths);
}
resolve(newPath: string): string {
// gh#44: replace ~ with userpath
const dir = newPath.replace(/^~/, HOME_DIR);
return path.resolve(dir);
}
cd(path: string, transferId = -1): Promise<string> {
const resolvedPath = this.resolve(path);
return this.isDir(resolvedPath)
.then((isDir: boolean) => {
if (isDir) {
return resolvedPath;
} else {
throw { code: 'ENOTDIR' };
}
})
.catch((err) => {
return Promise.reject(err);
});
}
size(source: string, files: string[], transferId = -1): Promise<number> {
return new Promise(async (resolve, reject) => {
try {
let bytes = 0;
for (const file of files) {
bytes += await size(path.join(source, file));
}
resolve(bytes);
} catch (err) {
reject(err);
}
});
}
async makedir(source: string, dirName: string, transferId = -1): Promise<string> {
return new Promise((resolve, reject) => {
console.log('makedir, source:', source, 'dirName:', dirName);
const unixPath = path.join(source, dirName).replace(/\\/g, '/');
console.log('unixPath', unixPath);
try {
console.log('calling mkdir');
mkdir(unixPath, (err: NodeJS.ErrnoException) => {
if (err) {
console.log('error creating dir', err);
reject(err);
} else {
console.log('successfully created dir', err);
resolve(path.join(source, dirName));
}
});
} catch (err) {
console.log('error execing mkdir()', err);
reject(err);
}
});
}
delete(source: string, files: File[], transferId = -1): Promise<number> {
const toDelete = files.map((file) => path.join(source, file.fullname));
return new Promise(async (resolve, reject) => {
try {
const deleted = await del(toDelete, {
force: true,
noGlob: true,
});
resolve(deleted.length);
} catch (err) {
// console.log("error delete", err);
reject(err);
}
});
}
rename(source: string, file: File, newName: string, transferId = -1): Promise<string> {
const oldPath = path.join(source, file.fullname);
const newPath = path.join(source, newName);
if (!newName.match(invalidFileChars)) {
return new Promise((resolve, reject) => {
// since node's fs.rename will overwrite the destination
// path if it exists, first check that file doesn't exist
this.exists(newPath)
.then((exists) => {
if (exists) {
reject({
code: 'EEXIST',
oldName: file.fullname,
});
} else {
fs.rename(oldPath, newPath, (err) => {
if (err) {
reject({
code: err.code,
message: err.message,
newName: newName,
oldName: file.fullname,
});
} else {
resolve(newName);
}
});
}
})
.catch((err) => {
reject({
code: err.code,
message: err.message,
newName: newName,
oldName: file.fullname,
});
});
});
} else {
// reject promise with previous name in case of invalid chars
return Promise.reject({
oldName: file.fullname,
newName: newName,
code: 'BAD_FILENAME',
});
}
}
async makeSymlink(targetPath: string, path: string, transferId = -1): Promise<boolean> {
return new Promise<boolean>((resolve, reject) =>
fs.symlink(targetPath, path, (err) => {
if (err) {
reject(err);
} else {
resolve(true);
}
}),
);
}
async isDir(path: string, transferId = -1): Promise<boolean> {
const lstat = fs.lstatSync(path);
const stat = fs.statSync(path);
return stat.isDirectory() || lstat.isDirectory();
}
async exists(path: string, transferId = -1): Promise<boolean> {
try {
fs.statSync(path);
return true;
} catch (err) {
if (err.code === 'ENOENT') {
return false;
} else {
throw err;
}
}
}
async stat(fullPath: string, transferId = -1): Promise<File> {
try {
const format = path.parse(fullPath);
const stats = fs.lstatSync(fullPath);
const file: File = {
dir: format.dir,
fullname: format.base,
name: format.name,
extension: format.ext.toLowerCase(),
cDate: stats.ctime,
mDate: stats.mtime,
bDate: stats.birthtime,
length: stats.size,
mode: stats.mode,
isDir: stats.isDirectory(),
readonly: false,
type:
(!stats.isDirectory() && filetype(stats.mode, stats.gid, stats.uid, format.ext.toLowerCase())) ||
'',
isSym: stats.isSymbolicLink(),
target: (stats.isSymbolicLink() && fs.readlinkSync(fullPath)) || null,
id: MakeId({ ino: stats.ino, dev: stats.dev }),
};
return file;
} catch (err) {
throw err;
}
}
login(server?: string, credentials?: Credentials): Promise<void> {
return Promise.resolve();
}
onList(dir: string): void {
if (dir !== this.path) {
// console.log('stopWatching', this.path);
try {
LocalWatch.stopWatchingPath(this.path, this.onFsChange);
LocalWatch.watchPath(dir, this.onFsChange);
} catch (e) {
console.warn('Could not watch path', dir, e);
}
// console.log('watchPath', dir);
this.path = dir;
}
}
async list(dir: string, watchDir = false, transferId = -1): Promise<File[]> {
try {
await this.isDir(dir);
return new Promise<File[]>((resolve, reject) => {
fs.readdir(dir, (err, items) => {
if (err) {
reject(err);
} else {
const dirPath = path.resolve(dir);
const files: File[] = [];
for (let i = 0; i < items.length; i++) {
const file = LocalApi.fileFromPath(path.join(dirPath, items[i]));
files.push(file);
}
watchDir && this.onList(dirPath);
resolve(files);
}
});
});
} catch (err) {
throw {
code: err.code,
message: `Could not access path: ${dir}`,
};
}
}
static fileFromPath(fullPath: string): File {
const format = path.parse(fullPath);
let name = fullPath;
let stats: Partial<fs.Stats> = null;
let targetStats = null;
try {
// do not follow symlinks first
stats = fs.lstatSync(fullPath);
if (stats.isSymbolicLink()) {
// get link target path first
name = fs.readlinkSync(fullPath);
targetStats = fs.statSync(fullPath);
}
} catch (err) {
console.warn('error getting stats for', fullPath, err);
const isDir = stats ? stats.isDirectory() : false;
const isSymLink = stats ? stats.isSymbolicLink() : false;
stats = {
ctime: new Date(),
mtime: new Date(),
birthtime: new Date(),
size: stats ? stats.size : 0,
isDirectory: (): boolean => isDir,
mode: -1,
isSymbolicLink: (): boolean => isSymLink,
ino: 0,
dev: 0,
};
}
const extension = path.parse(name).ext.toLowerCase();
const mode = targetStats ? targetStats.mode : stats.mode;
const file: File = {
dir: format.dir,
fullname: format.base,
name: format.name,
extension: extension,
cDate: stats.ctime,
mDate: stats.mtime,
bDate: stats.birthtime,
length: stats.size,
mode: mode,
isDir: targetStats ? targetStats.isDirectory() : stats.isDirectory(),
readonly: false,
type:
(!(targetStats ? targetStats.isDirectory() : stats.isDirectory()) && filetype(mode, 0, 0, extension)) ||
'',
isSym: stats.isSymbolicLink(),
target: (stats.isSymbolicLink() && name) || null,
id: MakeId({ ino: stats.ino, dev: stats.dev }),
};
return file;
}
isRoot(path: string): boolean {
return !!path.match(isRoot);
}
off(): void {
// console.log("off", this.path);
// console.log("stopWatchingPath", this.path);
LocalWatch.stopWatchingPath(this.path, this.onFsChange);
}
// TODO add error handling
async getStream(path: string, file: string, transferId = -1): Promise<fs.ReadStream> {
try {
// console.log('opening read stream', this.join(path, file));
const stream = fs.createReadStream(this.join(path, file), {
highWaterMark: 31 * 16384,
});
return Promise.resolve(stream);
} catch (err) {
console.log('FsLocal.getStream error', err);
return Promise.reject(err);
}
}
putStream(
readStream: fs.ReadStream,
dstPath: string,
progress: (pourcent: number) => void,
transferId = -1,
): Promise<void> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return new Promise((resolve: (val?: any) => void, reject: (val?: any) => void) => {
let finished = false;
let readError = false;
let bytesRead = 0;
const reportProgress = new Transform({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
transform(chunk: any, encoding: any, callback: TransformCallback) {
bytesRead += chunk.length;
progressFunc(progress, bytesRead);
callback(null, chunk);
},
highWaterMark: 16384 * 31,
});
const writeStream = fs.createWriteStream(dstPath);
readStream.once('error', (err) => {
console.log('error on read stream');
readError = true;
readStream.destroy();
writeStream.destroy(err);
});
readStream.pipe(reportProgress).pipe(writeStream);
writeStream.once('finish', () => {
finished = true;
});
writeStream.once('error', (err) => {
// remove created file if it's empty and there was a problem
// accessing the source file: we will report an error to the
// user so there's no need to leave an empty file
if (readError && !bytesRead && !writeStream.bytesWritten) {
console.log('cleaning up fs');
fs.unlink(dstPath, (err) => {
if (!err) {
console.log('cleaned-up fs');
} else {
console.log('error cleaning-up fs', err);
}
});
}
reject(err);
});
writeStream.once('close', () => {
if (finished) {
resolve();
} else {
reject();
}
});
writeStream.once('error', (err) => {
reject(err);
});
});
}
getParentTree(dir: string): Array<{ dir: string; fullname: string; name: string }> {
const parts = dir.split(SEP);
const max = parts.length - 1;
let fullname = '';
if (dir.length === 1) {
return [
{
dir,
fullname: '',
name: dir,
},
];
} else {
const folders = [];
for (let i = 0; i <= max; ++i) {
folders.push({
dir,
fullname,
name: parts[max - i] || SEP,
});
if (!i) {
fullname += '..';
} else {
fullname += '/..';
}
}
return folders;
}
}
sanityze(path: string): string {
return isWin ? (path.match(/\\$/) ? path : path + '\\') : path;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
on(event: string, cb: (data: any) => void): void {
//
}
}
export function FolderExists(path: string): boolean {
try {
return fs.existsSync(path) && fs.lstatSync(path).isDirectory();
} catch (err) {
return false;
}
}
export const FsLocal: Fs = {
icon: 'database',
name: 'local',
description: 'Local Filesystem',
options: {
needsRefresh: false,
},
canread(str: string): boolean {
// console.log('FsLocal.canread', str, !!str.match(localStart));
return !!str.match(localStart);
},
serverpart(str: string): string {
return 'local';
},
credentials(str: string): Credentials {
return {
user: '',
password: '',
port: 0,
};
},
displaypath(str: string): { shortPath: string; fullPath: string } {
const split = str.split(SEP);
return {
fullPath: str,
shortPath: split.slice(-1)[0] || str,
};
},
API: LocalApi,
}; | the_stack |
import { SimpleChange, DebugElement } from '@angular/core';
import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { setupTestBed } from '@alfresco/adf-core';
import { of, throwError } from 'rxjs';
import { StartProcessCloudService } from '../services/start-process-cloud.service';
import { FormCloudService } from '../../../form/services/form-cloud.service';
import { StartProcessCloudComponent } from './start-process-cloud.component';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatOptionModule, MatRippleModule, MatCommonModule } from '@angular/material/core';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {
fakeProcessDefinitions, fakeStartForm, fakeStartFormNotValid,
fakeProcessInstance, fakeNoNameProcessDefinitions,
fakeSingleProcessDefinition, fakeCreatedProcessInstance,
fakeSingleProcessDefinitionWithoutForm
} from '../mock/start-process.component.mock';
import { By } from '@angular/platform-browser';
import { ProcessPayloadCloud } from '../models/process-payload-cloud.model';
import { ProcessServiceCloudTestingModule } from '../../../testing/process-service-cloud.testing.module';
import { TranslateModule } from '@ngx-translate/core';
import { ProcessNameCloudPipe } from '../../../pipes/process-name-cloud.pipe';
import { ProcessInstanceCloud } from '../models/process-instance-cloud.model';
import { ESCAPE } from '@angular/cdk/keycodes';
describe('StartProcessCloudComponent', () => {
let component: StartProcessCloudComponent;
let fixture: ComponentFixture<StartProcessCloudComponent>;
let processService: StartProcessCloudService;
let formCloudService: FormCloudService;
let getDefinitionsSpy: jasmine.Spy;
let startProcessSpy: jasmine.Spy;
let createProcessSpy: jasmine.Spy;
let formDefinitionSpy: jasmine.Spy;
const firstChange = new SimpleChange(undefined, 'myApp', true);
const selectOptionByName = (name: string) => {
const selectElement = fixture.nativeElement.querySelector('button#adf-select-process-dropdown');
selectElement.click();
fixture.detectChanges();
const options: any = fixture.debugElement.queryAll(By.css('.mat-option-text'));
const currentOption = options.find((option: DebugElement) => option.nativeElement.innerHTML.trim() === name);
if (currentOption) {
currentOption.nativeElement.click();
}
};
function typeValueInto(selector: any, value: string) {
const inputElement = fixture.debugElement.query(By.css(`${selector}`));
inputElement.nativeElement.value = value;
inputElement.nativeElement.dispatchEvent(new Event('input'));
}
setupTestBed({
imports: [
TranslateModule.forRoot(),
ProcessServiceCloudTestingModule,
FormsModule,
MatCommonModule,
ReactiveFormsModule,
MatCardModule,
MatIconModule,
MatAutocompleteModule,
MatOptionModule,
MatButtonModule,
MatFormFieldModule,
MatInputModule,
MatRippleModule
]
});
beforeEach(() => {
processService = TestBed.inject(StartProcessCloudService);
formCloudService = TestBed.inject(FormCloudService);
fixture = TestBed.createComponent(StartProcessCloudComponent);
component = fixture.componentInstance;
getDefinitionsSpy = spyOn(processService, 'getProcessDefinitions').and.returnValue(of(fakeProcessDefinitions));
spyOn(processService, 'updateProcess').and.returnValue(of());
startProcessSpy = spyOn(processService, 'startCreatedProcess').and.returnValue(of(fakeProcessInstance));
createProcessSpy = spyOn(processService, 'createProcess').and.returnValue(of(fakeCreatedProcessInstance));
});
afterEach(() => {
fixture.destroy();
TestBed.resetTestingModule();
});
describe('start a process without start form', () => {
beforeEach(() => {
component.name = 'My new process';
component.appName = 'myApp';
fixture.detectChanges();
const change = new SimpleChange(null, 'MyApp', true);
component.ngOnChanges({ 'appName': change });
fixture.detectChanges();
});
it('should be able to start a process with a valid process name and process definition', fakeAsync(() => {
component.name = 'My new process';
component.processDefinitionName = 'processwithoutform2';
getDefinitionsSpy.and.returnValue(of(fakeSingleProcessDefinitionWithoutForm(component.processDefinitionName)));
fixture.detectChanges();
const change = new SimpleChange(null, 'MyApp', true);
component.ngOnChanges({ 'appName': change });
fixture.detectChanges();
tick(550);
fixture.whenStable().then(() => {
fixture.detectChanges();
const startBtn = fixture.nativeElement.querySelector('#button-start');
expect(component.isProcessFormValid()).toBe(true);
expect(startBtn.disabled).toBe(false);
});
}));
it('should create a process instance if the selection is valid', fakeAsync(() => {
getDefinitionsSpy = getDefinitionsSpy.and.returnValue(of(fakeProcessDefinitions));
component.name = 'My new process';
component.processDefinitionName = 'process';
selectOptionByName('process');
fixture.whenStable().then(() => {
expect(component.processDefinitionCurrent.name).toBe(JSON.parse(JSON.stringify(fakeProcessDefinitions[1])).name);
const startBtn = fixture.nativeElement.querySelector('#button-start');
expect(component.isProcessFormValid()).toBe(true);
expect(startBtn.disabled).toBe(false);
});
}));
it('should have start button disabled if create operation failed', fakeAsync(() => {
createProcessSpy.and.returnValue(throwError('fake error'));
const change = new SimpleChange(null, 'MyApp', false);
fixture.detectChanges();
component.ngOnChanges({ 'appName': change });
fixture.detectChanges();
tick();
typeValueInto('#processName', 'OLE');
typeValueInto('#processDefinitionName', 'processwithoutform2');
fixture.detectChanges();
tick(550);
fixture.whenStable().then(() => {
fixture.detectChanges();
const startBtn = fixture.nativeElement.querySelector('#button-start');
expect(startBtn.disabled).toBe(true);
expect(component.isProcessFormValid()).toBe(false);
expect(createProcessSpy).toHaveBeenCalledWith('MyApp', component.processPayloadCloud);
});
}));
it('should have start button disabled when no process is selected', async () => {
component.name = '';
component.processDefinitionName = '';
fixture.detectChanges();
await fixture.whenStable();
const startBtn = fixture.nativeElement.querySelector('#button-start');
expect(startBtn.disabled).toBe(true);
expect(component.isProcessFormValid()).toBe(false);
});
it('should have start button disabled when name not filled out', async () => {
component.name = '';
component.processDefinitionName = 'processwithoutform2';
fixture.detectChanges();
await fixture.whenStable();
const startBtn = fixture.nativeElement.querySelector('#button-start');
expect(startBtn.disabled).toBe(true);
expect(component.isProcessFormValid()).toBe(false);
});
});
describe('start a process with start form', () => {
beforeEach(() => {
component.name = 'My new process with form';
component.values = [{
'id': '1',
'type': 'string',
'name': 'firstName',
'value': 'FakeName',
get 'hasValue'() {
return this['value'];
},
set 'hasValue'(value) {
this['value'] = value;
}
}, {
'id': '1', 'type': 'string',
'name': 'lastName',
'value': 'FakeLastName',
get 'hasValue'() {
return this['value'];
},
set 'hasValue'(value) {
this['value'] = value;
}
}];
});
it('should be able to start a process with a valid form', fakeAsync(() => {
component.processDefinitionName = 'processwithform';
getDefinitionsSpy.and.returnValue(of(fakeSingleProcessDefinition(component.processDefinitionName)));
fixture.detectChanges();
formDefinitionSpy = spyOn(formCloudService, 'getForm').and.returnValue(of(fakeStartForm));
const change = new SimpleChange(null, 'MyApp', true);
component.ngOnChanges({ 'appName': change });
fixture.detectChanges();
tick();
typeValueInto('#processName', 'My new process with form');
typeValueInto('#processDefinitionName', 'processwithform');
fixture.detectChanges();
tick(550);
fixture.whenStable().then(() => {
fixture.detectChanges();
const firstNameEl = fixture.nativeElement.querySelector('#firstName');
expect(firstNameEl).toBeDefined();
const lastNameEl = fixture.nativeElement.querySelector('#lastName');
expect(lastNameEl).toBeDefined();
const startBtn = fixture.nativeElement.querySelector('#button-start');
expect(component.formCloud.isValid).toBe(true);
expect(startBtn.disabled).toBe(false);
});
}));
it('should NOT be able to start a process with a form NOT valid', fakeAsync(() => {
getDefinitionsSpy.and.returnValue(of(fakeSingleProcessDefinition(component.processDefinitionName)));
fixture.detectChanges();
formDefinitionSpy = spyOn(formCloudService, 'getForm').and.returnValue(of(fakeStartFormNotValid));
const change = new SimpleChange(null, 'MyApp', true);
component.ngOnChanges({ 'appName': change });
fixture.detectChanges();
tick();
typeValueInto('#processName', 'My new process with form');
typeValueInto('#processDefinitionName', 'processwithform');
fixture.detectChanges();
tick(550);
fixture.whenStable().then(() => {
fixture.detectChanges();
const firstNameEl = fixture.nativeElement.querySelector('#firstName');
expect(firstNameEl).toBeDefined();
const lastNameEl = fixture.nativeElement.querySelector('#lastName');
expect(lastNameEl).toBeDefined();
const startBtn = fixture.nativeElement.querySelector('#button-start');
expect(component.formCloud.isValid).toBe(false);
expect(startBtn.disabled).toBe(true);
});
}));
it('should be able to start a process with a prefilled valid form', fakeAsync(() => {
component.processDefinitionName = 'processwithform';
getDefinitionsSpy.and.returnValue(of(fakeSingleProcessDefinition(component.processDefinitionName)));
fixture.detectChanges();
formDefinitionSpy = spyOn(formCloudService, 'getForm').and.returnValue(of(fakeStartForm));
const change = new SimpleChange(null, 'MyApp', true);
component.ngOnChanges({ 'appName': change });
fixture.detectChanges();
tick();
typeValueInto('#processName', 'My new process with form');
typeValueInto('#processDefinitionName', 'processwithform');
fixture.detectChanges();
tick(550);
fixture.whenStable().then(() => {
fixture.detectChanges();
const firstNameEl = fixture.nativeElement.querySelector('#firstName');
expect(firstNameEl).toBeDefined();
expect(firstNameEl.value).toEqual('FakeName');
const lastNameEl = fixture.nativeElement.querySelector('#lastName');
expect(lastNameEl).toBeDefined();
expect(lastNameEl.value).toEqual('FakeLastName');
const startBtn = fixture.nativeElement.querySelector('#button-start');
expect(component.formCloud.isValid).toBe(true);
expect(startBtn.disabled).toBe(false);
});
}));
it('should NOT be able to start a process with a prefilled NOT valid form', fakeAsync(() => {
component.processDefinitionName = 'processwithform';
getDefinitionsSpy.and.returnValue(of(fakeSingleProcessDefinition(component.processDefinitionName)));
fixture.detectChanges();
formDefinitionSpy = spyOn(formCloudService, 'getForm').and.returnValue(of(fakeStartFormNotValid));
const change = new SimpleChange(null, 'MyApp', true);
component.ngOnChanges({ 'appName': change });
fixture.detectChanges();
tick();
typeValueInto('#processName', 'My new process with form');
typeValueInto('#processDefinitionName', 'processwithform');
fixture.detectChanges();
tick(4500);
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(formDefinitionSpy).toHaveBeenCalled();
const firstNameEl = fixture.nativeElement.querySelector('#firstName');
expect(firstNameEl).toBeDefined();
expect(firstNameEl.value).toEqual('FakeName');
const lastNameEl = fixture.nativeElement.querySelector('#lastName');
expect(lastNameEl).toBeDefined();
expect(lastNameEl.value).toEqual('FakeLastName');
const startBtn = fixture.nativeElement.querySelector('#button-start');
expect(component.formCloud.isValid).toBe(false);
expect(startBtn.disabled).toBe(true);
});
}));
it('should create a process instance if the selection is valid', fakeAsync(() => {
component.name = 'testFormWithProcess';
component.processDefinitionName = 'processwithoutform2';
getDefinitionsSpy.and.returnValue(of(fakeSingleProcessDefinition(component.processDefinitionName)));
fixture.detectChanges();
formDefinitionSpy = spyOn(formCloudService, 'getForm').and.returnValue(of(fakeStartForm));
const change = new SimpleChange(null, 'MyApp', true);
component.ngOnChanges({ 'appName': change });
fixture.detectChanges();
tick(550);
fixture.whenStable().then(() => {
fixture.detectChanges();
const startBtn = fixture.nativeElement.querySelector('#button-start');
expect(startBtn.disabled).toBe(false);
expect(component.formCloud.isValid).toBe(true);
expect(component.isProcessFormValid()).toBe(true);
expect(createProcessSpy).toHaveBeenCalledWith('MyApp', new ProcessPayloadCloud({
name: 'testFormWithProcess',
processDefinitionKey: fakeProcessDefinitions[1].key
}));
expect(component.currentCreatedProcess.status).toBe('CREATED');
expect(component.currentCreatedProcess.startDate).toBeNull();
});
}));
it('should have start button enabled when default values are set', fakeAsync(() => {
component.name = 'testFormWithProcess';
component.processDefinitionName = 'processwithoutform2';
getDefinitionsSpy.and.returnValue(of(fakeSingleProcessDefinition(component.processDefinitionName)));
fixture.detectChanges();
formDefinitionSpy = spyOn(formCloudService, 'getForm').and.returnValue(of(fakeStartForm));
const change = new SimpleChange(null, 'MyApp', true);
component.ngOnChanges({ 'appName': change });
fixture.detectChanges();
tick(550);
fixture.whenStable().then(() => {
fixture.detectChanges();
const startBtn = fixture.nativeElement.querySelector('#button-start');
expect(startBtn.disabled).toBe(false);
});
}));
});
describe('process definitions list', () => {
beforeEach(() => {
component.name = 'My new process';
component.appName = 'myApp';
fixture.detectChanges();
const change = new SimpleChange(null, 'MyApp', true);
component.ngOnChanges({ 'appName': change });
fixture.detectChanges();
});
it('should call service to fetch process definitions with appId', () => {
fixture.whenStable().then(() => {
expect(getDefinitionsSpy).toHaveBeenCalledWith('myApp');
});
});
it('should display the correct number of processes in the select list', () => {
fixture.whenStable().then(() => {
const selectElement = fixture.nativeElement.querySelector('mat-select');
expect(selectElement.children.length).toBe(1);
});
});
it('should display the option def details', () => {
component.processDefinitionList = fakeProcessDefinitions;
fixture.detectChanges();
fixture.whenStable().then(() => {
const selectElement = fixture.nativeElement.querySelector('mat-select > .mat-select-trigger');
const optionElement = fixture.nativeElement.querySelectorAll('mat-option');
selectElement.click();
expect(selectElement).not.toBeNull();
expect(selectElement).toBeDefined();
expect(optionElement).not.toBeNull();
expect(optionElement).toBeDefined();
});
});
it('should display the key when the processDefinition name is empty or null', () => {
component.processDefinitionList = fakeNoNameProcessDefinitions;
fixture.detectChanges();
fixture.whenStable().then(() => {
const selectElement = fixture.nativeElement.querySelector('mat-select > .mat-select-trigger');
const optionElement = fixture.nativeElement.querySelectorAll('mat-option');
selectElement.click();
expect(selectElement).not.toBeNull();
expect(selectElement).toBeDefined();
expect(optionElement).not.toBeNull();
expect(optionElement[0].textContent).toBe('NewProcess 1');
});
});
it('should indicate an error to the user if process defs cannot be loaded', async () => {
getDefinitionsSpy = getDefinitionsSpy.and.returnValue(throwError({}));
const change = new SimpleChange('myApp', 'myApp1', true);
component.ngOnChanges({ appName: change });
fixture.detectChanges();
await fixture.whenStable();
const errorEl = fixture.nativeElement.querySelector('#error-message');
expect(errorEl.innerText.trim()).toBe('ADF_CLOUD_PROCESS_LIST.ADF_CLOUD_START_PROCESS.ERROR.LOAD_PROCESS_DEFS');
});
it('should show no process available message when no process definition is loaded', async () => {
getDefinitionsSpy = getDefinitionsSpy.and.returnValue(of([]));
const change = new SimpleChange('myApp', 'myApp1', true);
component.ngOnChanges({ appName: change });
fixture.detectChanges();
await fixture.whenStable();
const noProcessElement = fixture.nativeElement.querySelector('#no-process-message');
expect(noProcessElement).not.toBeNull('Expected no available process message to be present');
expect(noProcessElement.innerText.trim()).toBe('ADF_CLOUD_PROCESS_LIST.ADF_CLOUD_START_PROCESS.NO_PROCESS_DEFINITIONS');
});
it('should select automatically the processDefinition if the app contain only one', async () => {
getDefinitionsSpy = getDefinitionsSpy.and.returnValue(of([fakeProcessDefinitions[0]]));
const change = new SimpleChange('myApp', 'myApp1', true);
component.ngOnChanges({ appName: change });
fixture.detectChanges();
await fixture.whenStable();
expect(component.processForm.controls['processDefinition'].value).toBe(JSON.parse(JSON.stringify(fakeProcessDefinitions[0])).name);
});
it('should select automatically the form when processDefinition is selected as default', fakeAsync(() => {
getDefinitionsSpy = getDefinitionsSpy.and.returnValue(of([fakeProcessDefinitions[0]]));
formDefinitionSpy = spyOn(formCloudService, 'getForm').and.returnValue(of(fakeStartForm));
const change = new SimpleChange('myApp', 'myApp1', true);
component.ngOnInit();
component.ngOnChanges({ appName: change });
component.processForm.controls['processDefinition'].setValue('process');
fixture.detectChanges();
tick(3000);
component.processDefinitionName = fakeProcessDefinitions[0].name;
component.setProcessDefinitionOnForm(fakeProcessDefinitions[0].name);
fixture.detectChanges();
tick(3000);
fixture.whenStable().then(() => {
const processForm = fixture.nativeElement.querySelector('adf-cloud-form');
expect(component.hasForm()).toBeTruthy();
expect(processForm).not.toBeNull();
});
}));
it('should not select automatically any processDefinition if the app contain multiple process and does not have any processDefinition as input', async () => {
getDefinitionsSpy = getDefinitionsSpy.and.returnValue(of(fakeProcessDefinitions));
component.appName = 'myApp';
component.ngOnChanges({});
fixture.detectChanges();
await fixture.whenStable();
expect(component.processPayloadCloud.name).toBeNull();
});
it('should select the right process when the processKey begins with the name', fakeAsync(() => {
getDefinitionsSpy = getDefinitionsSpy.and.returnValue(of(fakeProcessDefinitions));
component.name = 'My new process';
component.processDefinitionName = 'process';
selectOptionByName('process');
fixture.whenStable().then(() => {
expect(component.processDefinitionCurrent.name).toBe(JSON.parse(JSON.stringify(fakeProcessDefinitions[3])).name);
expect(component.processDefinitionCurrent.key).toBe(JSON.parse(JSON.stringify(fakeProcessDefinitions[3])).key);
});
}));
describe('dropdown', () => {
it('should hide the process dropdown button if showSelectProcessDropdown is false', async () => {
fixture.detectChanges();
getDefinitionsSpy = getDefinitionsSpy.and.returnValue(of(fakeProcessDefinitions));
component.appName = 'myApp';
component.showSelectProcessDropdown = false;
component.ngOnChanges({});
fixture.detectChanges();
await fixture.whenStable();
const selectElement = fixture.nativeElement.querySelector('button#adf-select-process-dropdown');
expect(selectElement).toBeNull();
});
it('should show the process dropdown button if showSelectProcessDropdown is false', async () => {
fixture.detectChanges();
getDefinitionsSpy = getDefinitionsSpy.and.returnValue(of(fakeProcessDefinitions));
component.appName = 'myApp';
component.processDefinitionName = 'NewProcess 2';
component.showSelectProcessDropdown = true;
component.ngOnChanges({});
fixture.detectChanges();
await fixture.whenStable();
const selectElement = fixture.nativeElement.querySelector('button#adf-select-process-dropdown');
expect(selectElement).not.toBeNull();
});
it('should show the process dropdown button by default', async () => {
fixture.detectChanges();
getDefinitionsSpy = getDefinitionsSpy.and.returnValue(of(fakeProcessDefinitions));
component.appName = 'myApp';
component.processDefinitionName = 'NewProcess 2';
component.ngOnChanges({});
fixture.detectChanges();
await fixture.whenStable();
const selectElement = fixture.nativeElement.querySelector('button#adf-select-process-dropdown');
expect(selectElement).not.toBeNull();
});
});
});
describe('input changes', () => {
const change = new SimpleChange('myApp', 'myApp1', false);
beforeEach(() => {
component.appName = 'myApp';
fixture.detectChanges();
});
it('should have labels for process name and type', async () => {
component.appName = 'myApp';
component.processDefinitionName = 'NewProcess 2';
component.ngOnChanges({ appName: firstChange });
fixture.detectChanges();
await fixture.whenStable();
const inputLabelsNodes = document.querySelectorAll('.adf-start-process .adf-process-input-container mat-label');
expect(inputLabelsNodes.length).toBe(2);
});
it('should have floating labels for process name and type', async () => {
component.appName = 'myApp';
component.processDefinitionName = 'NewProcess 2';
component.ngOnChanges({});
fixture.detectChanges();
await fixture.whenStable();
const inputLabelsNodes = document.querySelectorAll('.adf-start-process .adf-process-input-container');
inputLabelsNodes.forEach(labelNode => {
expect(labelNode.getAttribute('ng-reflect-float-label')).toBe('always');
});
});
it('should reload processes when appName input changed', async () => {
component.ngOnChanges({ appName: firstChange });
component.ngOnChanges({ appName: change });
fixture.detectChanges();
await fixture.whenStable();
expect(getDefinitionsSpy).toHaveBeenCalledWith('myApp1');
});
it('should reload processes ONLY when appName input changed', async () => {
component.ngOnChanges({ appName: firstChange });
fixture.detectChanges();
component.ngOnChanges({ maxNameLength: new SimpleChange(0, 2, false) });
fixture.detectChanges();
await fixture.whenStable();
expect(getDefinitionsSpy).toHaveBeenCalledTimes(1);
});
it('should get current processDef', () => {
component.ngOnChanges({ appName: change });
fixture.detectChanges();
expect(getDefinitionsSpy).toHaveBeenCalled();
expect(component.processDefinitionList).toBe(fakeProcessDefinitions);
});
it('should display the matching results in the dropdown as the user types down', fakeAsync(() => {
component.processDefinitionList = fakeProcessDefinitions;
component.ngOnInit();
component.ngOnChanges({ appName: change });
fixture.detectChanges();
component.processForm.controls['processDefinition'].setValue('process');
fixture.detectChanges();
tick(3000);
expect(component.filteredProcesses.length).toEqual(4);
component.processForm.controls['processDefinition'].setValue('processwithfo');
fixture.detectChanges();
tick(3000);
expect(component.filteredProcesses.length).toEqual(1);
}));
it('should display the process definion field as empty if are more than one process definition in the list', async () => {
getDefinitionsSpy.and.returnValue(of(fakeProcessDefinitions));
component.ngOnChanges({ appName: change });
fixture.detectChanges();
await fixture.whenStable();
const processDefinitionInput = fixture.nativeElement.querySelector('#processDefinitionName');
expect(processDefinitionInput.textContent).toEqual('');
});
});
describe('start process', () => {
beforeEach(() => {
fixture.detectChanges();
component.name = 'NewProcess 1';
component.appName = 'myApp';
component.ngOnChanges({});
});
it('should call service to start process if required fields provided', () => {
component.currentCreatedProcess = fakeProcessInstance;
component.startProcess();
expect(startProcessSpy).toHaveBeenCalled();
});
it('should call service to start process with the correct parameters', () => {
component.currentCreatedProcess = fakeProcessInstance;
component.startProcess();
expect(startProcessSpy).toHaveBeenCalledWith(component.appName, fakeProcessInstance.id, component.processPayloadCloud);
});
it('should call service to start process with the variables setted', async () => {
const inputProcessVariable: Map<string, object>[] = [];
inputProcessVariable['name'] = { value: 'Josh' };
component.variables = inputProcessVariable;
component.currentCreatedProcess = fakeProcessInstance;
component.startProcess();
await fixture.whenStable();
expect(component.processPayloadCloud.variables).toBe(inputProcessVariable);
});
it('should output start event when process started successfully', () => {
const emitSpy = spyOn(component.success, 'emit');
component.currentCreatedProcess = fakeProcessInstance;
component.startProcess();
expect(emitSpy).toHaveBeenCalledWith(fakeProcessInstance);
});
it('should throw error event when process cannot be started', async () => {
const errorSpy = spyOn(component.error, 'emit');
const error = { message: 'My error' };
startProcessSpy = startProcessSpy.and.returnValue(throwError(error));
component.currentCreatedProcess = fakeProcessInstance;
component.startProcess();
await fixture.whenStable();
expect(errorSpy).toHaveBeenCalledWith(error);
});
it('should indicate an error to the user if process cannot be started', async () => {
getDefinitionsSpy.and.returnValue(of(fakeProcessDefinitions));
const change = new SimpleChange('myApp', 'myApp1', true);
component.currentCreatedProcess = fakeProcessInstance;
component.ngOnChanges({ appName: change });
startProcessSpy = startProcessSpy.and.returnValue(throwError({}));
component.startProcess();
fixture.detectChanges();
await fixture.whenStable();
const errorEl = fixture.nativeElement.querySelector('#error-message');
expect(errorEl.innerText.trim()).toBe('ADF_CLOUD_PROCESS_LIST.ADF_CLOUD_START_PROCESS.ERROR.START');
});
it('should emit start event when start select a process and add a name', (done) => {
const disposableStart = component.success.subscribe(() => {
disposableStart.unsubscribe();
done();
});
component.currentCreatedProcess = fakeProcessInstance;
component.name = 'NewProcess 1';
component.startProcess();
fixture.detectChanges();
});
it('should be able to start the process when the required fields are filled up', (done) => {
component.processForm.controls['processInstanceName'].setValue('My Process 1');
component.processForm.controls['processDefinition'].setValue('NewProcess 1');
const disposableStart = component.success.subscribe(() => {
disposableStart.unsubscribe();
done();
});
component.currentCreatedProcess = fakeProcessInstance;
component.startProcess();
});
it('should emit error when process name field is empty', () => {
fixture.detectChanges();
const processInstanceName = component.processForm.controls['processInstanceName'];
processInstanceName.setValue('');
fixture.detectChanges();
expect(processInstanceName.valid).toBeFalsy();
processInstanceName.setValue('task');
fixture.detectChanges();
expect(processInstanceName.valid).toBeTruthy();
});
it('should have start button disabled process name has a space as the first or last character.', async () => {
component.appName = 'myApp';
component.processDefinitionName = ' Space in the beginning';
component.ngOnChanges({ appName: firstChange });
fixture.detectChanges();
await fixture.whenStable();
const startBtn = fixture.nativeElement.querySelector('#button-start');
expect(startBtn.disabled).toBe(true);
component.processDefinitionName = 'Space in the end ';
fixture.detectChanges();
await fixture.whenStable();
expect(startBtn.disabled).toBe(true);
});
it('should emit processDefinitionSelection event when a process definition is selected', (done) => {
component.appName = 'myApp';
component.ngOnChanges({ appName: firstChange });
component.processDefinitionSelection.subscribe((processDefinition) => {
expect(processDefinition).toEqual(fakeProcessDefinitions[0]);
done();
});
fixture.detectChanges();
selectOptionByName(fakeProcessDefinitions[0].name);
});
it('should wait for process definition to be loaded before showing the empty process definition message', () => {
component.processDefinitionLoaded = false;
fixture.detectChanges();
let noProcessElement = fixture.nativeElement.querySelector('#no-process-message');
expect(noProcessElement).toBeNull();
getDefinitionsSpy.and.returnValue(of([]));
component.loadProcessDefinitions();
fixture.detectChanges();
noProcessElement = fixture.nativeElement.querySelector('#no-process-message');
expect(noProcessElement).not.toBeNull();
});
it('should set the process name using the processName cloud pipe when a process definition gets selected', () => {
const processNameCloudPipe = TestBed.inject(ProcessNameCloudPipe);
const processNamePipeTransformSpy = spyOn(processNameCloudPipe, 'transform').and.returnValue('fake-transformed-name');
const expectedProcessInstanceDetails: ProcessInstanceCloud = { processDefinitionName: fakeProcessDefinitions[0].name};
getDefinitionsSpy = getDefinitionsSpy.and.returnValue(of(fakeProcessDefinitions));
component.appName = 'myApp';
component.ngOnChanges({ appName: firstChange });
fixture.detectChanges();
selectOptionByName(fakeProcessDefinitions[0].name);
expect(processNamePipeTransformSpy).toHaveBeenCalledWith(component.name, expectedProcessInstanceDetails);
expect(component.processInstanceName.dirty).toBe(true);
expect(component.processInstanceName.touched).toBe(true);
expect(component.processInstanceName.value).toEqual('fake-transformed-name');
});
it('should cancel bubbling a keydown event ()', () => {
const escapeKeyboardEvent = new KeyboardEvent('keydown', { 'keyCode': ESCAPE } as any);
fixture.debugElement.triggerEventHandler('keydown', escapeKeyboardEvent);
expect(escapeKeyboardEvent.cancelBubble).toBe(true);
});
});
}); | the_stack |
import capabilities from "../capabilities/capabilities";
import format from "../format/format";
// Query params for the global filter.
// These should be preserved when navigating between pages in the app.
export const ROLE_PARAM_NAME = "role";
export const STATUS_PARAM_NAME = "status";
export const START_DATE_PARAM_NAME = "start";
export const END_DATE_PARAM_NAME = "end";
export const LAST_N_DAYS_PARAM_NAME = "days";
const GLOBAL_FILTER_PARAM_NAMES = [
ROLE_PARAM_NAME,
STATUS_PARAM_NAME,
START_DATE_PARAM_NAME,
END_DATE_PARAM_NAME,
LAST_N_DAYS_PARAM_NAME,
];
class Router {
register(pathChangeHandler: VoidFunction) {
history.pushState = ((f) =>
function pushState() {
var ret = f.apply(this, arguments);
pathChangeHandler();
return ret;
})(history.pushState);
history.replaceState = ((f) =>
function replaceState() {
var ret = f.apply(this, arguments);
pathChangeHandler();
return ret;
})(history.replaceState);
window.addEventListener("popstate", () => {
pathChangeHandler();
});
}
/**
* Updates the URL relative to the origin. The new URL is formed by appending
* the given string onto `window.location.origin` verbatim.
*
* - Creates a new browser history entry.
* - Preserves global filter params.
*/
navigateTo(path: string) {
const oldUrl = new URL(window.location.href);
const newUrl = new URL(window.location.origin + path);
// Preserve global filter params.
for (const key of GLOBAL_FILTER_PARAM_NAMES) {
if (!newUrl.searchParams.get(key) && oldUrl.searchParams.get(key)) {
newUrl.searchParams.set(key, oldUrl.searchParams.get(key));
}
}
window.history.pushState({}, "", newUrl.href);
}
/**
* Sets the given query param.
*
* - Creates a new browser history entry.
* - Preserves global filter params.
* - Preserves the current `path`, but not the `hash`.
*/
navigateToQueryParam(key: string, value: string) {
const url = new URL(window.location.href);
url.searchParams.set(key, value);
window.history.pushState({}, "", url.href);
}
/**
* Replaces the current URL query.
*
* - Does not create a new browser history entry.
* - Preserves global filter params.
*/
setQuery(query: Record<string, string>) {
window.history.replaceState({}, "", getModifiedUrl({ query }));
}
navigateHome(hash?: string) {
this.navigateTo("/" + (hash || ""));
}
navigateToSetup() {
this.navigateTo(Path.setupPath);
}
navigateToWorkflows() {
if (!capabilities.canNavigateToPath(Path.workflowsPath)) {
alert(`Workflows are not available in ${capabilities.name}`);
return;
}
this.navigateTo(Path.workflowsPath);
}
navigateToCode() {
if (!capabilities.canNavigateToPath(Path.codePath)) {
alert(`Code is not available in ${capabilities.name}`);
return;
}
this.navigateTo(Path.codePath);
}
navigateToSettings() {
if (!capabilities.canNavigateToPath(Path.settingsPath)) {
alert(`Settings are not available in ${capabilities.name}`);
return;
}
this.navigateTo(Path.settingsPath);
}
navigateToTrends() {
if (!capabilities.canNavigateToPath(Path.trendsPath)) {
alert(`Trends are not available in ${capabilities.name}`);
return;
}
this.navigateTo(Path.trendsPath);
}
navigateToUsage() {
this.navigateTo(Path.usagePath);
}
navigateToExecutors() {
if (!capabilities.canNavigateToPath(Path.executorsPath)) {
alert(`Executors are not available in ${capabilities.name}`);
return;
}
this.navigateTo(Path.executorsPath);
}
navigateToTap() {
if (!capabilities.canNavigateToPath(Path.tapPath)) {
alert(`The test dashboard is not available in ${capabilities.name}`);
return;
}
this.navigateTo(Path.tapPath);
}
navigateToInvocation(invocationId: string) {
if (!capabilities.canNavigateToPath(Path.invocationPath)) {
alert(`Invocations are not available in ${capabilities.name}`);
return;
}
this.navigateTo(Path.invocationPath + invocationId);
}
navigateToUserHistory(user: string) {
if (!capabilities.canNavigateToPath(Path.userHistoryPath)) {
alert(
`User history is not available in ${capabilities.name}.\n\nClick 'Upgrade to Enterprise' in the menu to enable user build history, organization build history, SSO, and more!`
);
return;
}
this.navigateTo(Path.userHistoryPath + user);
}
navigateToHostHistory(host: string) {
if (!capabilities.canNavigateToPath(Path.hostHistoryPath)) {
alert(
`Host history is not available in ${capabilities.name}.\n\nClick 'Upgrade to Enterprise' in the menu to enable user build history, organization build history, SSO, and more!`
);
return;
}
this.navigateTo(Path.hostHistoryPath + host);
}
getWorkflowHistoryUrl(repo: string) {
return `${Path.repoHistoryPath}${getRepoUrlPathParam(repo)}?role=CI_RUNNER`;
}
navigateToWorkflowHistory(repo: string) {
this.navigateTo(this.getWorkflowHistoryUrl(repo));
}
navigateToRepoHistory(repo: string) {
if (!capabilities.canNavigateToPath(Path.repoHistoryPath)) {
alert(
`Repo history is not available in ${capabilities.name}.\n\nClick 'Upgrade to Enterprise' in the menu to enable user build history, organization build history, SSO, and more!`
);
return;
}
this.navigateTo(`${Path.repoHistoryPath}${getRepoUrlPathParam(repo)}`);
}
navigateToBranchHistory(branch: string) {
if (!capabilities.canNavigateToPath(Path.branchHistoryPath)) {
alert(
`Branch history is not available in ${capabilities.name}.\n\nClick 'Upgrade to Enterprise' in the menu to enable user build history, organization build history, SSO, and more!`
);
return;
}
this.navigateTo(Path.branchHistoryPath + branch);
}
navigateToCommitHistory(commit: string) {
if (!capabilities.canNavigateToPath(Path.commitHistoryPath)) {
alert(
`Commit history is not available in ${capabilities.name}.\n\nClick 'Upgrade to Enterprise' in the menu to enable user build history, organization build history, SSO, and more!`
);
return;
}
this.navigateTo(Path.commitHistoryPath + commit);
}
navigateToCreateOrg() {
if (!capabilities.createOrg) {
window.open("https://buildbuddy.typeform.com/to/PFjD5A", "_blank");
return;
}
this.navigateTo(Path.createOrgPath);
}
updateParams(params: Record<string, string>) {
const newUrl = getModifiedUrl({ query: params });
window.history.pushState({ path: newUrl }, "", newUrl);
}
replaceParams(params: Record<string, string>) {
const newUrl = getModifiedUrl({ query: params });
window.history.replaceState({ path: newUrl }, "", newUrl);
}
getLastPathComponent(path: string, pathPrefix: string) {
if (!path.startsWith(pathPrefix)) {
return null;
}
return decodeURIComponent(path.replace(pathPrefix, ""));
}
getInvocationId(path: string) {
return this.getLastPathComponent(path, Path.invocationPath);
}
getInvocationIdsForCompare(path: string) {
const idsComponent = this.getLastPathComponent(path, Path.comparePath);
if (!idsComponent) {
return null;
}
const [a, b] = idsComponent.split("...");
if (!a || !b) {
return null;
}
return { a, b };
}
getHistoryUser(path: string) {
return this.getLastPathComponent(path, Path.userHistoryPath);
}
getHistoryHost(path: string) {
return this.getLastPathComponent(path, Path.hostHistoryPath);
}
getHistoryRepo(path: string) {
let repoComponent = this.getLastPathComponent(path, Path.repoHistoryPath);
if (repoComponent?.includes("/")) {
return `https://github.com/${repoComponent}`;
}
return repoComponent ? atob(repoComponent) : "";
}
getHistoryBranch(path: string) {
return this.getLastPathComponent(path, Path.branchHistoryPath);
}
getHistoryCommit(path: string) {
return this.getLastPathComponent(path, Path.commitHistoryPath);
}
isFiltering() {
const url = new URL(window.location.href);
for (const param of GLOBAL_FILTER_PARAM_NAMES) {
if (url.searchParams.has(param)) return true;
}
return false;
}
clearFilters() {
const url = new URL(window.location.href);
for (const param of GLOBAL_FILTER_PARAM_NAMES) {
url.searchParams.delete(param);
}
this.replaceParams(Object.fromEntries(url.searchParams.entries()));
}
}
// If a repo matches https://github.com/{owner}/{repo} or https://github.com/{owner}/{repo}.git
// then we'll show it directly in the URL like `{owner}/{repo}`. Otherwise we encode it
// using `window.btoa`.
const GITHUB_URL_PREFIX = "^https://github.com";
const PATH_SEGMENT_PATTERN = "[^/]+";
const OPTIONAL_DOTGIT_SUFFIX = "(\\.git)?$";
const GITHUB_REPO_URL_PATTERN = new RegExp(
`${GITHUB_URL_PREFIX}/${PATH_SEGMENT_PATTERN}/${PATH_SEGMENT_PATTERN}${OPTIONAL_DOTGIT_SUFFIX}`
);
function getRepoUrlPathParam(repo: string): string {
if (repo.match(GITHUB_REPO_URL_PATTERN)) {
return format.formatGitUrl(repo);
}
return window.btoa(repo);
}
function getQueryString(params: Record<string, string>) {
return new URLSearchParams(
Object.fromEntries(Object.entries(params).filter(([_, value]) => Boolean(value)))
).toString();
}
function getModifiedUrl({ query }: { query?: Record<string, string> }) {
const queryString = query ? getQueryString(query) : window.location.search;
return (
window.location.protocol +
"//" +
window.location.host +
window.location.pathname +
(queryString ? "?" : "") +
queryString +
window.location.hash
);
}
export class Path {
static comparePath = "/compare/";
static invocationPath = "/invocation/";
static userHistoryPath = "/history/user/";
static hostHistoryPath = "/history/host/";
static repoHistoryPath = "/history/repo/";
static branchHistoryPath = "/history/branch/";
static commitHistoryPath = "/history/commit/";
static setupPath = "/docs/setup/";
static settingsPath = "/settings/";
static createOrgPath = "/org/create";
static editOrgPath = "/org/edit";
static trendsPath = "/trends/";
static usagePath = "/usage/";
static executorsPath = "/executors/";
static tapPath = "/tests/";
static workflowsPath = "/workflows/";
static codePath = "/code/";
}
export default new Router(); | the_stack |
import { AddressInfo } from "net";
import http from "http";
import fs from "fs-extra";
import path from "path";
import test, { Test } from "tape-promise/tape";
import { v4 as uuidv4 } from "uuid";
import express from "express";
import bodyParser from "body-parser";
import {
Containers,
FabricTestLedgerV1,
pruneDockerAllIfGithubAction,
} from "@hyperledger/cactus-test-tooling";
import {
IListenOptions,
LogLevelDesc,
Servers,
} from "@hyperledger/cactus-common";
import { PluginRegistry } from "@hyperledger/cactus-core";
import {
ChainCodeProgrammingLanguage,
DefaultEventHandlerStrategy,
DeployContractV1Request,
FabricContractInvocationType,
FileBase64,
PluginLedgerConnectorFabric,
RunTransactionRequest,
} from "../../../../main/typescript/public-api";
import { DefaultApi as FabricApi } from "../../../../main/typescript/public-api";
import { IPluginLedgerConnectorFabricOptions } from "../../../../main/typescript/plugin-ledger-connector-fabric";
import { DiscoveryOptions } from "fabric-network";
import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory";
import { Configuration } from "@hyperledger/cactus-core-api";
import { installOpenapiValidationMiddleware } from "@hyperledger/cactus-core";
import OAS from "../../../../main/json/openapi.json";
const testCase = "deploys Fabric 2.x contract from typescript source";
const logLevel: LogLevelDesc = "TRACE";
test("BEFORE " + testCase, async (t: Test) => {
const pruning = pruneDockerAllIfGithubAction({ logLevel });
await t.doesNotReject(pruning, "Pruning didn't throw OK");
t.end();
});
test(testCase, async (t: Test) => {
const channelId = "mychannel";
const channelName = channelId;
test.onFailure(async () => {
await Containers.logDiagnostics({ logLevel });
});
const ledger = new FabricTestLedgerV1({
emitContainerLogs: true,
publishAllPorts: true,
imageName: "ghcr.io/hyperledger/cactus-fabric2-all-in-one",
envVars: new Map([["FABRIC_VERSION", "2.2.0"]]),
logLevel,
});
const tearDown = async () => {
await ledger.stop();
await ledger.destroy();
};
test.onFinish(tearDown);
await ledger.start();
const connectionProfile = await ledger.getConnectionProfileOrg1();
t.ok(connectionProfile, "getConnectionProfileOrg1() out truthy OK");
const enrollAdminOut = await ledger.enrollAdmin();
const adminWallet = enrollAdminOut[1];
const [userIdentity] = await ledger.enrollUser(adminWallet);
const sshConfig = await ledger.getSshConfig();
const keychainInstanceId = uuidv4();
const keychainId = uuidv4();
const keychainEntryKey = "user2";
const keychainEntryValue = JSON.stringify(userIdentity);
const keychainPlugin = new PluginKeychainMemory({
instanceId: keychainInstanceId,
keychainId,
logLevel,
backend: new Map([
[keychainEntryKey, keychainEntryValue],
["some-other-entry-key", "some-other-entry-value"],
]),
});
const pluginRegistry = new PluginRegistry({ plugins: [keychainPlugin] });
const discoveryOptions: DiscoveryOptions = {
enabled: true,
asLocalhost: true,
};
// This is the directory structure of the Fabirc 2.x CLI container (fabric-tools image)
// const orgCfgDir = "/fabric-samples/test-network/organizations/";
const orgCfgDir =
"/opt/gopath/src/github.com/hyperledger/fabric/peer/organizations/";
// these below mirror how the fabric-samples sets up the configuration
const org1Env = {
CORE_LOGGING_LEVEL: "debug",
FABRIC_LOGGING_SPEC: "debug",
CORE_PEER_LOCALMSPID: "Org1MSP",
ORDERER_CA: `${orgCfgDir}ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem`,
FABRIC_CFG_PATH: "/etc/hyperledger/fabric",
CORE_PEER_TLS_ENABLED: "true",
CORE_PEER_TLS_ROOTCERT_FILE: `${orgCfgDir}peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt`,
CORE_PEER_MSPCONFIGPATH: `${orgCfgDir}peerOrganizations/org1.example.com/users/Admin@org1.example.com/msp`,
CORE_PEER_ADDRESS: "peer0.org1.example.com:7051",
ORDERER_TLS_ROOTCERT_FILE: `${orgCfgDir}ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem`,
};
// these below mirror how the fabric-samples sets up the configuration
const org2Env = {
CORE_LOGGING_LEVEL: "debug",
FABRIC_LOGGING_SPEC: "debug",
CORE_PEER_LOCALMSPID: "Org2MSP",
FABRIC_CFG_PATH: "/etc/hyperledger/fabric",
CORE_PEER_TLS_ENABLED: "true",
ORDERER_CA: `${orgCfgDir}ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem`,
CORE_PEER_ADDRESS: "peer0.org2.example.com:9051",
CORE_PEER_MSPCONFIGPATH: `${orgCfgDir}peerOrganizations/org2.example.com/users/Admin@org2.example.com/msp`,
CORE_PEER_TLS_ROOTCERT_FILE: `${orgCfgDir}peerOrganizations/org2.example.com/peers/peer0.org2.example.com/tls/ca.crt`,
ORDERER_TLS_ROOTCERT_FILE: `${orgCfgDir}ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem`,
};
const pluginOptions: IPluginLedgerConnectorFabricOptions = {
instanceId: uuidv4(),
dockerBinary: "/usr/local/bin/docker",
peerBinary: "/fabric-samples/bin/peer",
goBinary: "/usr/local/go/bin/go",
pluginRegistry,
cliContainerEnv: org1Env,
sshConfig,
logLevel,
connectionProfile,
discoveryOptions,
eventHandlerOptions: {
strategy: DefaultEventHandlerStrategy.NetworkScopeAllfortx,
commitTimeout: 300,
},
};
const plugin = new PluginLedgerConnectorFabric(pluginOptions);
const expressApp = express();
expressApp.use(bodyParser.json({ limit: "250mb" }));
const server = http.createServer(expressApp);
const listenOptions: IListenOptions = {
hostname: "localhost",
port: 0,
server,
};
const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo;
const { port } = addressInfo;
test.onFinish(async () => await Servers.shutdown(server));
await installOpenapiValidationMiddleware({
logLevel,
app: expressApp,
apiSpec: OAS,
});
await plugin.getOrCreateWebServices();
await plugin.registerWebServices(expressApp);
const apiUrl = `http://localhost:${port}`;
const config = new Configuration({ basePath: apiUrl });
const apiClient = new FabricApi(config);
const contractName = "basic-asset-transfer-2";
const contractRelPath =
"../../fixtures/go/basic-asset-transfer/chaincode-typescript";
const contractDir = path.join(__dirname, contractRelPath);
// ├── package.json
// ├── src
// │ ├── assetTransfer.ts
// │ ├── asset.ts
// │ └── index.ts
// ├── tsconfig.json
// └── tslint.json
const sourceFiles: FileBase64[] = [];
{
const filename = "./tslint.json";
const relativePath = "./";
const filePath = path.join(contractDir, relativePath, filename);
const buffer = await fs.readFile(filePath);
sourceFiles.push({
body: buffer.toString("base64"),
filepath: relativePath,
filename,
});
}
{
const filename = "./tsconfig.json";
const relativePath = "./";
const filePath = path.join(contractDir, relativePath, filename);
const buffer = await fs.readFile(filePath);
sourceFiles.push({
body: buffer.toString("base64"),
filepath: relativePath,
filename,
});
}
{
const filename = "./package.json";
const relativePath = "./";
const filePath = path.join(contractDir, relativePath, filename);
const buffer = await fs.readFile(filePath);
sourceFiles.push({
body: buffer.toString("base64"),
filepath: relativePath,
filename,
});
}
{
const filename = "./index.ts";
const relativePath = "./src/";
const filePath = path.join(contractDir, relativePath, filename);
const buffer = await fs.readFile(filePath);
sourceFiles.push({
body: buffer.toString("base64"),
filepath: relativePath,
filename,
});
}
{
const filename = "./asset.ts";
const relativePath = "./src/";
const filePath = path.join(contractDir, relativePath, filename);
const buffer = await fs.readFile(filePath);
sourceFiles.push({
body: buffer.toString("base64"),
filepath: relativePath,
filename,
});
}
{
const filename = "./assetTransfer.ts";
const relativePath = "./src/";
const filePath = path.join(contractDir, relativePath, filename);
const buffer = await fs.readFile(filePath);
sourceFiles.push({
body: buffer.toString("base64"),
filepath: relativePath,
filename,
});
}
const fDeploy = "deployContractV1";
const fRun = "runTransactionV1";
const cOk = "without bad request error";
const cWithoutParams = "not sending all required parameters";
const cInvalidParams = "sending invalid parameters";
test(`${testCase} - ${fDeploy} - ${cOk}`, async (t2: Test) => {
const parameters = {
channelId,
ccVersion: "1.0.0",
sourceFiles,
ccName: contractName,
targetOrganizations: [org1Env, org2Env],
caFile: `${orgCfgDir}ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem`,
ccLabel: "basic-asset-transfer-2",
ccLang: ChainCodeProgrammingLanguage.Typescript,
ccSequence: 1,
orderer: "orderer.example.com:7050",
ordererTLSHostnameOverride: "orderer.example.com",
connTimeout: 60,
};
const res = await apiClient.deployContractV1(parameters);
t2.equal(
res.status,
200,
`Endpoint ${fDeploy}: response.status === 200 OK`,
);
t2.true(res.data.success, "res.data.success === true");
t2.end();
});
test(`${testCase} - ${fDeploy} - ${cWithoutParams}`, async (t2: Test) => {
const parameters = {
// channelId,
ccVersion: "1.0.0",
sourceFiles,
ccName: contractName,
targetOrganizations: [org1Env, org2Env],
caFile: `${orgCfgDir}ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem`,
ccLabel: "basic-asset-transfer-2",
ccLang: ChainCodeProgrammingLanguage.Typescript,
ccSequence: 1,
orderer: "orderer.example.com:7050",
ordererTLSHostnameOverride: "orderer.example.com",
connTimeout: 60,
};
try {
await apiClient.deployContractV1(
(parameters as any) as DeployContractV1Request,
);
} catch (e) {
t2.equal(
e.response.status,
400,
`Endpoint ${fDeploy} without required channelId: response.status === 400 OK`,
);
const fields = e.response.data.map((param: any) =>
param.path.replace(".body.", ""),
);
t2.ok(
fields.includes("channelId"),
"Rejected because channelId is required",
);
}
t2.end();
});
test(`${testCase} - ${fDeploy} - ${cInvalidParams}`, async (t2: Test) => {
const parameters = {
channelId,
ccVersion: "1.0.0",
sourceFiles,
ccName: contractName,
targetOrganizations: [org1Env, org2Env],
caFile: `${orgCfgDir}ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem`,
ccLabel: "basic-asset-transfer-2",
ccLang: ChainCodeProgrammingLanguage.Typescript,
ccSequence: 1,
orderer: "orderer.example.com:7050",
ordererTLSHostnameOverride: "orderer.example.com",
connTimeout: 60,
fake: 4,
};
try {
await apiClient.deployContractV1(
(parameters as any) as DeployContractV1Request,
);
} catch (e) {
t2.equal(
e.response.status,
400,
`Endpoint ${fDeploy} with fake=4: response.status === 400 OK`,
);
const fields = e.response.data.map((param: any) =>
param.path.replace(".body.", ""),
);
t2.ok(
fields.includes("fake"),
"Rejected because fake is not a valid parameter",
);
}
t2.end();
});
test(`${testCase} - ${fRun} - ${cOk}`, async (t2: Test) => {
await new Promise((resolve) => setTimeout(resolve, 10000));
const assetId = uuidv4();
const assetOwner = uuidv4();
const parameters = {
contractName,
channelName,
params: [assetId, "Green", "19", assetOwner, "9999"],
methodName: "CreateAsset",
invocationType: FabricContractInvocationType.Send,
signingCredential: {
keychainId,
keychainRef: keychainEntryKey,
},
};
const res = await apiClient.runTransactionV1(parameters);
t2.ok(res, "res truthy OK");
t2.equal(res.status, 200, `Endpoint ${fRun}: response.status === 200 OK`);
t2.end();
});
test(`${testCase} - ${fRun} - ${cWithoutParams}`, async (t2: Test) => {
const assetId = uuidv4();
const assetOwner = uuidv4();
const parameters = {
// contractName,
channelName,
params: [assetId, "Green", "19", assetOwner, "9999"],
methodName: "CreateAsset",
invocationType: FabricContractInvocationType.Send,
signingCredential: {
keychainId,
keychainRef: keychainEntryKey,
},
};
try {
await apiClient.runTransactionV1(
(parameters as any) as RunTransactionRequest,
);
} catch (e) {
t2.equal(
e.response.status,
400,
`Endpoint ${fRun} without required contractName: response.status === 400 OK`,
);
const fields = e.response.data.map((param: any) =>
param.path.replace(".body.", ""),
);
t2.ok(
fields.includes("contractName"),
"Rejected because contractName is required",
);
}
t2.end();
});
test(`${testCase} - ${fRun} - ${cInvalidParams}`, async (t2: Test) => {
const assetId = uuidv4();
const assetOwner = uuidv4();
const parameters = {
contractName,
channelName,
params: [assetId, "Green", "19", assetOwner, "9999"],
methodName: "CreateAsset",
invocationType: FabricContractInvocationType.Send,
signingCredential: {
keychainId,
keychainRef: keychainEntryKey,
},
fake: 4,
};
try {
await apiClient.runTransactionV1(
(parameters as any) as RunTransactionRequest,
);
} catch (e) {
t2.equal(
e.response.status,
400,
`Endpoint ${fRun} with fake=4: response.status === 400 OK`,
);
const fields = e.response.data.map((param: any) =>
param.path.replace(".body.", ""),
);
t2.ok(
fields.includes("fake"),
"Rejected because fake is not a valid parameter",
);
}
t2.end();
});
t.end();
});
test("AFTER " + testCase, async (t: Test) => {
const pruning = pruneDockerAllIfGithubAction({ logLevel });
await t.doesNotReject(pruning, "Pruning didn't throw OK");
t.end();
}); | the_stack |
export const SCORE_CARD_SIMPLE_PREDICATE: string = `
<PMML xmlns="http://www.dmg.org/PMML-4_4" version="4.4">
<Header/>
<DataDictionary numberOfFields="3">
<DataField name="input1" optype="continuous" dataType="double"/>
<DataField name="input2" optype="continuous" dataType="double"/>
<DataField name="score" optype="continuous" dataType="double"/>
</DataDictionary>
<Scorecard modelName="SimpleScorecard" functionName="regression" useReasonCodes="true" reasonCodeAlgorithm="pointsBelow" initialScore="5" baselineScore="6" baselineMethod="other">
<MiningSchema>
<MiningField name="input1" usageType="active" invalidValueTreatment="asMissing"/>
<MiningField name="input2" usageType="active" invalidValueTreatment="asMissing"/>
<MiningField name="score" usageType="target"/>
</MiningSchema>
<Output>
<OutputField name="Score" feature="predictedValue" dataType="double" optype="continuous"/>
<OutputField name="Reason Code 1" rank="1" feature="reasonCode" dataType="string" optype="categorical"/>
<OutputField name="Reason Code 2" rank="2" feature="reasonCode" dataType="string" optype="categorical"/>
</Output>
<Characteristics>
<Characteristic name="input1Score" baselineScore="4" reasonCode="Input1ReasonCode">
<Attribute partialScore="-12">
<SimplePredicate field="input1" operator="lessOrEqual" value="10"/>
</Attribute>
<Attribute partialScore="50">
<SimplePredicate field="input1" operator="greaterThan" value="10"/>
</Attribute>
</Characteristic>
<Characteristic name="input2Score" baselineScore="8" reasonCode="Input2ReasonCode">
<Attribute partialScore="-8">
<SimplePredicate field="input2" operator="lessOrEqual" value="-5"/>
</Attribute>
<Attribute partialScore="32">
<SimplePredicate field="input2" operator="greaterThan" value="-5"/>
</Attribute>
</Characteristic>
</Characteristics>
</Scorecard>
</PMML>
`;
export const SCORE_CARD_SIMPLE_PREDICATE_SINGLE: string = `
<PMML xmlns="http://www.dmg.org/PMML-4_4" version="4.4">
<Header/>
<DataDictionary numberOfFields="3">
<DataField name="input1" optype="continuous" dataType="double"/>
<DataField name="input2" optype="continuous" dataType="double"/>
<DataField name="score" optype="continuous" dataType="double"/>
</DataDictionary>
<Scorecard modelName="SimpleScorecard" functionName="regression" useReasonCodes="true" reasonCodeAlgorithm="pointsBelow" initialScore="5" baselineScore="6" baselineMethod="other">
<MiningSchema>
<MiningField name="input1" usageType="active" invalidValueTreatment="asMissing"/>
<MiningField name="input2" usageType="active" invalidValueTreatment="asMissing"/>
<MiningField name="score" usageType="target"/>
</MiningSchema>
<Output>
<OutputField name="Score" feature="predictedValue" dataType="double" optype="continuous"/>
<OutputField name="Reason Code 1" rank="1" feature="reasonCode" dataType="string" optype="categorical"/>
<OutputField name="Reason Code 2" rank="2" feature="reasonCode" dataType="string" optype="categorical"/>
</Output>
<Characteristics>
<Characteristic name="input1Score" baselineScore="4" reasonCode="Input1ReasonCode">
<Attribute partialScore="-12">
<SimplePredicate field="input1" operator="lessOrEqual" value="10"/>
</Attribute>
</Characteristic>
</Characteristics>
</Scorecard>
</PMML>
`;
export const SCORE_CARD_COMPOUND_PREDICATE: string = `
<PMML xmlns="http://www.dmg.org/PMML-4_4" version="4.4">
<Header/>
<DataDictionary numberOfFields="5">
<DataField name="input1" optype="continuous" dataType="double"/>
<DataField name="input2" optype="continuous" dataType="double"/>
<DataField name="input3" optype="categorical" dataType="string"/>
<DataField name="input4" optype="categorical" dataType="string"/>
<DataField name="score" optype="continuous" dataType="double"/>
</DataDictionary>
<Scorecard modelName="CompoundPredicateScorecard" functionName="regression" useReasonCodes="true" reasonCodeAlgorithm="pointsAbove" initialScore="-15" baselineMethod="other">
<MiningSchema>
<MiningField name="input1" usageType="active" invalidValueTreatment="asMissing"/>
<MiningField name="input2" usageType="active" invalidValueTreatment="asMissing"/>
<MiningField name="input3" usageType="active" invalidValueTreatment="asMissing"/>
<MiningField name="input4" usageType="active" invalidValueTreatment="asMissing"/>
<MiningField name="score" usageType="target"/>
</MiningSchema>
<Output>
<OutputField name="Score" feature="predictedValue" dataType="double" optype="continuous"/>
<OutputField name="Reason Code 1" rank="1" feature="reasonCode" dataType="string" optype="categorical"/>
<OutputField name="Reason Code 2" rank="2" feature="reasonCode" dataType="string" optype="categorical"/>
<OutputField name="Reason Code 3" rank="3" feature="reasonCode" dataType="string" optype="categorical"/>
</Output>
<Characteristics>
<Characteristic name="characteristic1Score" baselineScore="-5.5" reasonCode="characteristic1ReasonCode">
<Attribute partialScore="-10">
<CompoundPredicate booleanOperator="and">
<SimplePredicate field="input1" operator="lessOrEqual" value="-5"/>
<SimplePredicate field="input2" operator="lessOrEqual" value="-5"/>
</CompoundPredicate>
</Attribute>
<Attribute partialScore="15">
<CompoundPredicate booleanOperator="and">
<SimplePredicate field="input1" operator="greaterThan" value="-5"/>
<SimplePredicate field="input2" operator="greaterThan" value="-5"/>
</CompoundPredicate>
</Attribute>
<Attribute partialScore="25">
<True/>
</Attribute>
</Characteristic>
<Characteristic name="characteristic2Score" baselineScore="11" reasonCode="characteristic2ReasonCode">
<Attribute partialScore="-18">
<CompoundPredicate booleanOperator="or">
<SimplePredicate field="input3" operator="equal" value="classA"/>
<SimplePredicate field="input4" operator="equal" value="classA"/>
</CompoundPredicate>
</Attribute>
<Attribute partialScore="10">
<CompoundPredicate booleanOperator="or">
<SimplePredicate field="input3" operator="equal" value="classB"/>
<SimplePredicate field="input4" operator="equal" value="classB"/>
</CompoundPredicate>
</Attribute>
<Attribute partialScore="100.5">
<False/>
</Attribute>
<Attribute partialScore="105.5">
<True/>
</Attribute>
</Characteristic>
<Characteristic name="characteristic3Score" baselineScore="25" reasonCode="characteristic3ReasonCode">
<Attribute partialScore="-50">
<CompoundPredicate booleanOperator="xor">
<SimplePredicate field="input3" operator="equal" value="classA"/>
<SimplePredicate field="input4" operator="equal" value="classA"/>
</CompoundPredicate>
</Attribute>
<Attribute partialScore="150">
<True/>
</Attribute>
</Characteristic>
</Characteristics>
</Scorecard>
</PMML>
`;
export const SCORE_CARD_NESTED_COMPOUND_PREDICATE: string = `
<PMML xmlns="http://www.dmg.org/PMML-4_4" version="4.4">
<Header/>
<DataDictionary numberOfFields="3">
<DataField name="input1" optype="continuous" dataType="double"/>
<DataField name="input2" optype="categorical" dataType="string"/>
<DataField name="score" optype="continuous" dataType="double"/>
</DataDictionary>
<Scorecard modelName="CompoundNestedPredicateScorecard" functionName="regression" useReasonCodes="true" reasonCodeAlgorithm="pointsBelow" initialScore="-15" baselineMethod="other">
<MiningSchema>
<MiningField name="input1" usageType="active" invalidValueTreatment="asMissing"/>
<MiningField name="input2" usageType="active" invalidValueTreatment="asMissing"/>
<MiningField name="score" usageType="target"/>
</MiningSchema>
<Output>
<OutputField name="Score" feature="predictedValue" dataType="double" optype="continuous"/>
<OutputField name="Reason Code 1" rank="1" feature="reasonCode" dataType="string" optype="categorical"/>
<OutputField name="Reason Code 2" rank="2" feature="reasonCode" dataType="string" optype="categorical"/>
</Output>
<Characteristics>
<Characteristic name="characteristic1Score" baselineScore="21.8" reasonCode="characteristic1ReasonCode">
<Attribute partialScore="-10.5">
<CompoundPredicate booleanOperator="and">
<CompoundPredicate booleanOperator="and">
<True/>
<SimplePredicate field="input1" operator="greaterThan" value="-15"/>
<SimplePredicate field="input1" operator="lessOrEqual" value="25.4"/>
</CompoundPredicate>
<SimplePredicate field="input2" operator="notEqual" value="classA"/>
</CompoundPredicate>
</Attribute>
<Attribute partialScore="25">
<True/>
</Attribute>
</Characteristic>
<Characteristic name="characteristic2Score" baselineScore="11" reasonCode="characteristic2ReasonCode">
<Attribute partialScore="-18">
<CompoundPredicate booleanOperator="or">
<SimplePredicate field="input1" operator="lessOrEqual" value="-20"/>
<SimplePredicate field="input2" operator="equal" value="classA"/>
</CompoundPredicate>
</Attribute>
<Attribute partialScore="10">
<CompoundPredicate booleanOperator="or">
<CompoundPredicate booleanOperator="and">
<CompoundPredicate booleanOperator="and">
<SimplePredicate field="input1" operator="greaterOrEqual" value="5"/>
<SimplePredicate field="input1" operator="lessThan" value="12"/>
</CompoundPredicate>
<SimplePredicate field="input2" operator="equal" value="classB"/>
</CompoundPredicate>
<SimplePredicate field="input2" operator="equal" value="classC"/>
</CompoundPredicate>
</Attribute>
<Attribute partialScore="100.5">
<True/>
</Attribute>
</Characteristic>
</Characteristics>
</Scorecard>
</PMML>
`;
export const SCORE_CARD_BASIC_COMPLEX_PARTIAL_SCORE: string = `
<PMML xmlns="http://www.dmg.org/PMML-4_4" version="4.4">
<Header/>
<DataDictionary numberOfFields="3">
<DataField name="input1" optype="continuous" dataType="double"/>
<DataField name="input2" optype="continuous" dataType="double"/>
<DataField name="score" optype="continuous" dataType="double"/>
</DataDictionary>
<Scorecard modelName="BasicComplexPartialScore" functionName="regression" useReasonCodes="true" reasonCodeAlgorithm="pointsBelow" initialScore="10" baselineMethod="other">
<MiningSchema>
<MiningField name="input1" usageType="active" invalidValueTreatment="asMissing"/>
<MiningField name="input2" usageType="active" invalidValueTreatment="asMissing"/>
<MiningField name="score" usageType="target"/>
</MiningSchema>
<Output>
<OutputField name="Score" feature="predictedValue" dataType="double" optype="continuous"/>
<OutputField name="Reason Code 1" rank="1" feature="reasonCode" dataType="string" optype="categorical"/>
<OutputField name="Reason Code 2" rank="2" feature="reasonCode" dataType="string" optype="categorical"/>
</Output>
<Characteristics>
<Characteristic name="characteristic1Score" baselineScore="20" reasonCode="characteristic1ReasonCode">
<Attribute>
<SimplePredicate field="input1" operator="greaterThan" value="-1000"/>
<ComplexPartialScore>
<Apply function="+">
<FieldRef field="input1"/>
<FieldRef field="input2"/>
</Apply>
</ComplexPartialScore>
</Attribute>
<Attribute partialScore="25">
<True/>
</Attribute>
</Characteristic>
<Characteristic name="characteristic2Score" baselineScore="5" reasonCode="characteristic2ReasonCode">
<Attribute>
<SimplePredicate field="input2" operator="lessOrEqual" value="1000"/>
<ComplexPartialScore>
<Apply function="*">
<FieldRef field="input1"/>
<FieldRef field="input2"/>
</Apply>
</ComplexPartialScore>
</Attribute>
<Attribute partialScore="-50">
<True/>
</Attribute>
</Characteristic>
</Characteristics>
</Scorecard>
</PMML>
`;
export const SCORE_CARD_NESTED_COMPLEX_PARTIAL_SCORE: string = `
<PMML xmlns="http://www.dmg.org/PMML-4_4" version="4.4">
<Header/>
<DataDictionary numberOfFields="3">
<DataField name="input1" optype="continuous" dataType="double"/>
<DataField name="input2" optype="continuous" dataType="double"/>
<DataField name="score" optype="continuous" dataType="double"/>
</DataDictionary>
<Scorecard modelName="NestedComplexPartialScoreScorecard" functionName="regression" useReasonCodes="true" reasonCodeAlgorithm="pointsBelow" initialScore="10" baselineMethod="other">
<MiningSchema>
<MiningField name="input1" usageType="active" invalidValueTreatment="asMissing"/>
<MiningField name="input2" usageType="active" invalidValueTreatment="asMissing"/>
<MiningField name="score" usageType="target"/>
</MiningSchema>
<Output>
<OutputField name="Score" feature="predictedValue" dataType="double" optype="continuous"/>
<OutputField name="Reason Code 1" rank="1" feature="reasonCode" dataType="string" optype="categorical"/>
<OutputField name="Reason Code 2" rank="2" feature="reasonCode" dataType="string" optype="categorical"/>
</Output>
<Characteristics>
<Characteristic name="characteristic1Score" baselineScore="20" reasonCode="characteristic1ReasonCode">
<Attribute>
<SimplePredicate field="input1" operator="greaterThan" value="-1000"/>
<ComplexPartialScore>
<Apply function="-">
<Apply function="+">
<FieldRef field="input1"/>
<FieldRef field="input2"/>
</Apply>
<Constant>5</Constant>
</Apply>
</ComplexPartialScore>
</Attribute>
<Attribute partialScore="25">
<True/>
</Attribute>
</Characteristic>
<Characteristic name="characteristic2Score" baselineScore="5" reasonCode="characteristic2ReasonCode">
<Attribute>
<SimplePredicate field="input2" operator="lessOrEqual" value="1000"/>
<ComplexPartialScore>
<Apply function="*">
<Constant>2</Constant>
<Apply function="*">
<FieldRef field="input1"/>
<Apply function="/">
<FieldRef field="input2"/>
<Constant>2</Constant>
</Apply>
</Apply>
</Apply>
</ComplexPartialScore>
</Attribute>
<Attribute partialScore="-50">
<True/>
</Attribute>
</Characteristic>
</Characteristics>
</Scorecard>
</PMML>
`;
export const SCORE_CARD_PROTOTYPES: string = `
<PMML xmlns="http://www.dmg.org/PMML-4_4" version="4.4">
<Header/>
<Scorecard modelName="SimpleScorecard" functionName="regression" useReasonCodes="true" reasonCodeAlgorithm="pointsBelow" initialScore="5" baselineScore="6" baselineMethod="other">
<MiningSchema>
<MiningField name="input1" usageType="active" invalidValueTreatment="asMissing"/>
</MiningSchema>
<Output>
<OutputField name="Score" feature="predictedValue" dataType="double" optype="continuous"/>
</Output>
<Characteristics>
<Characteristic name="input1Score" baselineScore="4" reasonCode="Input1ReasonCode">
<Attribute partialScore="-12">
<SimplePredicate field="input1" operator="lessOrEqual" value="10"/>
</Attribute>
</Characteristic>
</Characteristics>
</Scorecard>
</PMML>
`; | the_stack |
'use strict';
import {IDisposable} from 'vs/base/common/lifecycle';
import URI from 'vs/base/common/uri';
import {IConfigurationService} from 'vs/platform/configuration/common/configuration';
import {ContextMenuService} from 'vs/platform/contextview/browser/contextMenuService';
import {IContextMenuService, IContextViewService} from 'vs/platform/contextview/browser/contextView';
import {ContextViewService} from 'vs/platform/contextview/browser/contextViewService';
import {IEditorService} from 'vs/platform/editor/common/editor';
import {IEventService} from 'vs/platform/event/common/event';
import {EventService} from 'vs/platform/event/common/eventService';
import {IExtensionService} from 'vs/platform/extensions/common/extensions';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import {InstantiationService} from 'vs/platform/instantiation/common/instantiationService';
import {ServiceCollection} from 'vs/platform/instantiation/common/serviceCollection';
import {ICommandService} from 'vs/platform/commands/common/commands';
import {CommandService} from 'vs/platform/commands/common/commandService';
import {IOpenerService} from 'vs/platform/opener/common/opener';
import {IKeybindingService} from 'vs/platform/keybinding/common/keybinding';
import {IContextKeyService} from 'vs/platform/contextkey/common/contextkey';
import {MarkerService} from 'vs/platform/markers/common/markerService';
import {IMarkerService} from 'vs/platform/markers/common/markers';
import {IMessageService} from 'vs/platform/message/common/message';
import {IProgressService} from 'vs/platform/progress/common/progress';
import {IStorageService, NullStorageService} from 'vs/platform/storage/common/storage';
import {ITelemetryService, NullTelemetryService} from 'vs/platform/telemetry/common/telemetry';
import {IWorkspaceContextService, WorkspaceContextService} from 'vs/platform/workspace/common/workspace';
import {ICodeEditorService} from 'vs/editor/common/services/codeEditorService';
import {IEditorWorkerService} from 'vs/editor/common/services/editorWorkerService';
import {EditorWorkerServiceImpl} from 'vs/editor/common/services/editorWorkerServiceImpl';
import {IModeService} from 'vs/editor/common/services/modeService';
import {MainThreadModeServiceImpl} from 'vs/editor/common/services/modeServiceImpl';
import {IModelService} from 'vs/editor/common/services/modelService';
import {ModelServiceImpl} from 'vs/editor/common/services/modelServiceImpl';
import {CodeEditorServiceImpl} from 'vs/editor/browser/services/codeEditorServiceImpl';
import {SimpleConfigurationService, SimpleMessageService, SimpleExtensionService, StandaloneKeybindingService} from 'vs/editor/browser/standalone/simpleServices';
import {ContextKeyService} from 'vs/platform/contextkey/browser/contextKeyService';
import {IMenuService} from 'vs/platform/actions/common/actions';
import {MenuService} from 'vs/platform/actions/common/menuService';
import {ICompatWorkerService} from 'vs/editor/common/services/compatWorkerService';
import {MainThreadCompatWorkerService} from 'vs/editor/common/services/compatWorkerServiceMain';
export interface IEditorContextViewService extends IContextViewService {
dispose(): void;
setContainer(domNode:HTMLElement): void;
}
export interface IEditorOverrideServices {
/**
* @internal
*/
compatWorkerService?: ICompatWorkerService;
/**
* @internal
*/
modeService?: IModeService;
/**
* @internal
*/
extensionService?:IExtensionService;
/**
* @internal
*/
instantiationService?:IInstantiationService;
/**
* @internal
*/
messageService?:IMessageService;
/**
* @internal
*/
markerService?:IMarkerService;
/**
* @internal
*/
menuService?:IMenuService;
/**
* @internal
*/
editorService?:IEditorService;
/**
* @internal
*/
commandService?:ICommandService;
/**
* @internal
*/
openerService?:IOpenerService;
/**
* @internal
*/
contextKeyService?:IContextKeyService;
/**
* @internal
*/
keybindingService?:IKeybindingService;
/**
* @internal
*/
contextService?:IWorkspaceContextService;
/**
* @internal
*/
contextViewService?:IEditorContextViewService;
/**
* @internal
*/
contextMenuService?:IContextMenuService;
/**
* @internal
*/
telemetryService?:ITelemetryService;
/**
* @internal
*/
eventService?:IEventService;
/**
* @internal
*/
storageService?:IStorageService;
/**
* @internal
*/
configurationService?:IConfigurationService;
/**
* @internal
*/
progressService?:IProgressService;
/**
* @internal
*/
modelService?: IModelService;
/**
* @internal
*/
codeEditorService?: ICodeEditorService;
/**
* @internal
*/
editorWorkerService?: IEditorWorkerService;
}
export interface IStaticServices {
configurationService: IConfigurationService;
compatWorkerService: ICompatWorkerService;
modeService: IModeService;
extensionService: IExtensionService;
markerService: IMarkerService;
menuService: IMenuService;
contextService: IWorkspaceContextService;
messageService: IMessageService;
telemetryService: ITelemetryService;
modelService: IModelService;
codeEditorService: ICodeEditorService;
editorWorkerService: IEditorWorkerService;
eventService: IEventService;
storageService: IStorageService;
commandService: ICommandService;
instantiationService: IInstantiationService;
}
function shallowClone<T>(obj:T): T {
let r:T = <any>{};
if (obj) {
let keys = Object.keys(obj);
for (let i = 0, len = keys.length; i < len; i++) {
let key = keys[i];
r[key] = obj[key];
}
}
return r;
}
export function ensureStaticPlatformServices(services: IEditorOverrideServices): IEditorOverrideServices {
services = shallowClone(services);
var statics = getOrCreateStaticServices(services);
let keys = Object.keys(statics);
for (let i = 0, len = keys.length; i < len; i++) {
let serviceId = keys[i];
if (!services.hasOwnProperty(serviceId)) {
services[serviceId] = statics[serviceId];
}
}
return services;
}
export function ensureDynamicPlatformServices(domElement:HTMLElement, services: IEditorOverrideServices): IDisposable[] {
let r:IDisposable[] = [];
let contextKeyService:IContextKeyService;
if (typeof services.contextKeyService === 'undefined') {
contextKeyService = new ContextKeyService(services.configurationService);
r.push(contextKeyService);
services.contextKeyService = contextKeyService;
} else {
contextKeyService = services.contextKeyService;
}
if (typeof services.keybindingService === 'undefined') {
let keybindingService = new StandaloneKeybindingService(contextKeyService, services.commandService, services.messageService, domElement);
r.push(keybindingService);
services.keybindingService = keybindingService;
}
let contextViewService:IEditorContextViewService;
if (typeof services.contextViewService === 'undefined') {
contextViewService = new ContextViewService(domElement, services.telemetryService, services.messageService);
r.push(contextViewService);
services.contextViewService = contextViewService;
} else {
contextViewService = services.contextViewService;
}
if (typeof services.contextMenuService === 'undefined') {
let contextMenuService = new ContextMenuService(domElement, services.telemetryService, services.messageService, contextViewService);
r.push(contextMenuService);
services.contextMenuService = contextMenuService;
}
return r;
}
// The static services represents a map of services that once 1 editor has been created must be used for all subsequent editors
var staticServices: IStaticServices = null;
export function getOrCreateStaticServices(services?: IEditorOverrideServices): IStaticServices {
if (staticServices) {
return staticServices;
}
services = services || {};
let serviceCollection = new ServiceCollection();
const instantiationService = new InstantiationService(serviceCollection, true);
let contextService = services.contextService || new WorkspaceContextService({
resource: URI.from({ scheme: 'inmemory', authority: 'model', path: '/' })
});
serviceCollection.set(IWorkspaceContextService, contextService);
let telemetryService = services.telemetryService || NullTelemetryService;
serviceCollection.set(ITelemetryService, telemetryService);
let eventService = services.eventService || new EventService();
serviceCollection.set(IEventService, eventService);
let configurationService = services.configurationService || new SimpleConfigurationService();
serviceCollection.set(IConfigurationService, configurationService);
let messageService = services.messageService || new SimpleMessageService();
serviceCollection.set(IMessageService, messageService);
let extensionService = services.extensionService || new SimpleExtensionService();
serviceCollection.set(IExtensionService, extensionService);
let commandService = services.commandService || new CommandService(instantiationService, extensionService);
serviceCollection.set(ICommandService, commandService);
let markerService = services.markerService || new MarkerService();
serviceCollection.set(IMarkerService, markerService);
let modeService = services.modeService || new MainThreadModeServiceImpl(instantiationService, extensionService, configurationService);
serviceCollection.set(IModeService, modeService);
let modelService = services.modelService || new ModelServiceImpl(markerService, configurationService, messageService);
serviceCollection.set(IModelService, modelService);
let compatWorkerService = services.compatWorkerService || new MainThreadCompatWorkerService(modelService);
serviceCollection.set(ICompatWorkerService, compatWorkerService);
let editorWorkerService = services.editorWorkerService || new EditorWorkerServiceImpl(modelService);
serviceCollection.set(IEditorWorkerService, editorWorkerService);
let codeEditorService = services.codeEditorService || new CodeEditorServiceImpl();
serviceCollection.set(ICodeEditorService, codeEditorService);
let menuService = services.menuService || new MenuService(extensionService, commandService);
serviceCollection.set(IMenuService, menuService);
staticServices = {
configurationService: configurationService,
extensionService: extensionService,
commandService: commandService,
compatWorkerService: compatWorkerService,
modeService: modeService,
markerService: markerService,
menuService: menuService,
contextService: contextService,
telemetryService: telemetryService,
messageService: messageService,
modelService: modelService,
codeEditorService: codeEditorService,
editorWorkerService: editorWorkerService,
eventService: eventService,
storageService: services.storageService || NullStorageService,
instantiationService: instantiationService
};
return staticServices;
} | the_stack |
import * as assert from 'power-assert'
import tcb from '../../../src/index'
import * as Config from '../../config.local'
import * as common from '../../common/index'
const app = tcb.init(Config)
const db = app.database()
const _ = db.command
const offset = 60 * 1000
describe('transaction', () => {
let collection = null
const collectionName = 'db-test-transactions'
const date = new Date()
const data = [
{
_id: '1',
category: 'Web',
tags: ['JavaScript', 'C#'],
date,
geo: new db.Geo.Point(90, 23),
num: 2
},
{ _id: '2', category: 'Web', tags: ['Go', 'C#'] },
{ _id: '3', category: 'Life', tags: ['Go', 'Python', 'JavaScript'] },
{ _id: '4', serverDate1: db.serverDate(), serverDate2: db.serverDate({ offset }) }
]
beforeEach(async () => {
collection = await common.safeCollection(db, collectionName)
// 测试环境不稳定, 清除之前的影响
await collection.remove()
const success = await collection.create(data)
assert.strictEqual(success, true)
})
afterEach(async () => {
const success = await collection.remove()
assert.strictEqual(success, true)
})
it('发起事务', async () => {
const transaction = await db.startTransaction()
assert.strictEqual(typeof transaction._id, 'string')
})
it('提交事务', async () => {
const transaction = await db.startTransaction()
const res = await transaction.commit()
assert.strictEqual(typeof res.requestId, 'string')
})
it('runTransaction', async () => {
await db.runTransaction(async function(transaction) {
// 事务内插入 含date geo类型文档
const insertDoc = { _id: 'lluke', date: date, geo: new db.Geo.Point(90, 23) }
const insertRes = await transaction.collection(collectionName).add(insertDoc)
assert(insertRes.inserted === 1)
const doc = await transaction
.collection(collectionName)
.doc('lluke')
.get()
assert(doc.data, insertDoc)
// 事务外插入含date geo serverDate 类型文档
const doc1 = await transaction
.collection(collectionName)
.doc('1')
.get()
const doc4 = await transaction
.collection(collectionName)
.doc('4')
.get()
assert.deepStrictEqual(doc1.data, data[0])
assert.deepStrictEqual(
doc4.data.serverDate1.getTime() + offset === doc4.data.serverDate2.getTime(),
true
)
// 事务内插入 含 serverDate 类型文档 报错不支持
// const insertRes = await transaction.collection(collectionName).add({_id: 'lluke', serverDate1: db.serverDate(), serverDate2: db.serverDate({ offset })})
// console.log('insertRes:', insertRes)
// const lukeData = await transaction.collection(collectionName).doc('lluke').get()
// assert(lukeData.data.serverDate1.getTime() + offset === lukeData.data.serverDate2.getTime(), true)
})
})
it('事务内批量插入 条件查询', async () => {
const transaction = await db.startTransaction()
const addRes = await transaction
.collection(collectionName)
.add([{ name: 'a' }, { name: 'b' }])
assert(addRes.ids.length === 2)
const queryRes = await transaction
.collection(collectionName)
.where(_.or([{ name: 'a' }, { name: 'b' }]))
.get()
assert(queryRes.data.length === 2)
const result = await transaction.commit()
assert.strictEqual(typeof result.requestId, 'string')
})
it('事务内批量插入1000条文档', async () => {
const transaction = await db.startTransaction()
// 构造1001条数据
const mockData = []
let i = 0
while (i++ <= 1000) {
mockData.push({ name: `luketest${i}` })
}
const addRes = await transaction.collection(collectionName).add(mockData)
assert(addRes.ids.length === 1001)
const queryRes = await transaction
.collection(collectionName)
.where({ name: /^luketest/ })
.limit(1000)
.get()
// console.log('queryRes:', queryRes)
assert(queryRes.data.length === 1000)
const result = await transaction.commit()
assert.strictEqual(typeof result.requestId, 'string')
})
it('事务内更新含特殊类型 字段文档', async () => {
await db.runTransaction(async function(transaction) {
const newDate = new Date()
const newGeo = new db.Geo.Point(90, 23)
const updateRes = await transaction
.collection(collectionName)
.doc('1')
.update({
num: _.inc(1),
date: newDate,
geo: newGeo
})
assert(updateRes.updated === 1)
const res = await transaction
.collection(collectionName)
.doc('1')
.get()
assert(res.data.num === 3, true)
assert(res.data.date, newDate)
assert(res.data.geo, newGeo)
})
})
it('insert', async () => {
const transaction = await db.startTransaction()
const res = await transaction
.collection(collectionName)
.add({ category: 'Web', tags: ['JavaScript', 'C#'], date })
assert(res.id !== undefined && res.inserted === 1)
const result = await transaction.commit()
assert.strictEqual(typeof result.requestId, 'string')
})
it('insert with custom docid', async () => {
const docId = +new Date()
const transaction = await db.startTransaction()
const res = await transaction
.collection(collectionName)
.add({ _id: docId, category: 'Web', tags: ['JavaScript', 'C#'], date })
assert(res.id == docId && res.inserted === 1)
const deleteRes = await transaction
.collection(collectionName)
.doc(docId)
.remove()
assert(deleteRes.deleted === 1)
const result = await transaction.commit()
assert.strictEqual(typeof result.requestId, 'string')
})
it('get', async () => {
// const docRef = db.collection(collectionName).doc('1')
const transaction = await db.startTransaction()
// const doc = await transaction.get(docRef)
const doc = await transaction
.collection(collectionName)
.doc('1')
.get()
assert.deepStrictEqual(doc.data, data[0])
const res = await transaction.commit()
assert(res.requestId)
})
it('get不存在的文档,返回null', async () => {
// const docRef = db.collection(collectionName).doc('114514')
const transaction = await db.startTransaction()
// const doc = await transaction.get(docRef)
const doc = await transaction
.collection(collectionName)
.doc('114514')
.get()
assert.strictEqual(doc.data, null)
const res = await transaction.commit()
assert(res.requestId)
})
it('事务回滚', async () => {
const transaction = await db.startTransaction()
// const docRef = db.collection(collectionName).doc('1')
// const doc = await transaction.get(docRef)
const doc = await transaction
.collection(collectionName)
.doc('1')
.get()
const addDoc = await transaction
.collection(collectionName)
.add({ _id: '5', category: 'hope' })
assert.deepStrictEqual(addDoc.id, '5')
assert.deepStrictEqual(doc.data, data[0])
const res = await transaction.rollback()
assert(res.requestId)
})
it('update', async () => {
// const docRef = db.collection(collectionName).doc('1')
const transaction = await db.startTransaction()
// let doc = await transaction.get(docRef)
let doc = await transaction
.collection(collectionName)
.doc('1')
.get()
assert.deepStrictEqual(doc.data, data[0])
const date = new Date()
// const updateResult = await transaction.update(docRef, {
// category: 'Node.js',
// date
// })
const updateResult = await transaction
.collection(collectionName)
.doc('1')
.update({
category: 'Node.js',
date
})
assert.strictEqual(updateResult.updated, 1)
// doc = await transaction.get(docRef)
doc = await transaction
.collection(collectionName)
.doc('1')
.get()
assert.deepStrictEqual(doc.data, {
...data[0],
date,
category: 'Node.js'
})
const res = await transaction.commit()
assert(res.requestId)
})
it('modifyAndReturnDoc', async () => {
const transaction = await db.startTransaction()
let modifyAndReturnRes = await transaction
.collection(collectionName)
.where({ category: 'Web' })
.updateAndReturn({
category: 'web'
})
const res = await transaction.commit()
assert(modifyAndReturnRes.doc.category === 'web')
})
it('set doc', async () => {
// const docRef = db.collection(collectionName).doc('1')
const transaction = await db.startTransaction()
// let doc = await transaction.get(docRef)
let doc = await transaction
.collection(collectionName)
.doc('1')
.get()
const date = new Date()
// const updateResult = await transaction.set(docRef, {
// ...data[0],
// date,
// category: 'Node.js'
// })
const newData = { ...data[0] }
delete newData['_id']
const updateResult = await transaction
.collection(collectionName)
.doc('1')
.set({
...newData,
date,
category: 'Node.js'
})
assert.strictEqual(updateResult.updated, 1)
// doc = await transaction.get(docRef)
doc = await transaction
.collection(collectionName)
.doc('1')
.get()
assert.deepStrictEqual(doc.data, {
...data[0],
date,
category: 'Node.js'
})
const res = await transaction.commit()
assert(res.requestId)
})
it('upsert doc', async () => {
// const docRef = db.collection(collectionName).doc('114514')
const transaction = await db.startTransaction()
// let doc = await transaction.get(docRef)
let doc = await transaction
.collection(collectionName)
.doc('114514')
.get()
assert.deepStrictEqual(doc.data, null)
const date = new Date()
const data = {
category: 'Node.js',
date
}
// const updateResult = await transaction.set(docRef, data)
const updateResult = await transaction
.collection(collectionName)
.doc('114514')
.set(data)
assert.strictEqual(updateResult.upserted.length, 1)
// doc = await transaction.get(docRef)
doc = await transaction
.collection(collectionName)
.doc('114514')
.get()
assert.deepStrictEqual(doc.data, {
_id: '114514',
...data
})
const res = await transaction.rollback()
assert(res.requestId)
})
it('delete doc', async () => {
// 前面测试用例更改过 _id = 1 的数据
// const docRef = db.collection(collectionName).doc('2')
const transaction = await db.startTransaction()
// let doc = await transaction.get(docRef)
let doc = await transaction
.collection(collectionName)
.doc('2')
.get()
assert.deepStrictEqual(doc.data, data[1])
// const deleteResult = await transaction.delete(docRef)
const deleteResult = await transaction
.collection(collectionName)
.doc('2')
.delete()
assert.strictEqual(deleteResult.deleted, 1)
// doc = await transaction.get(docRef)
doc = await transaction
.collection(collectionName)
.doc('2')
.get()
assert.deepStrictEqual(doc.data, null)
await transaction.commit()
})
it('runTransaction with customResult', async () => {
// 验证自定义成功返回
const result = await db.runTransaction(async function(transaction) {
const doc = await transaction
.collection(collectionName)
.doc('1')
.get()
assert.deepStrictEqual(doc.data, data[0])
// assert(doc.data)
return 'luke'
})
assert(result === 'luke')
})
// runTransaction rollback
it('rollback within runTransaction', async () => {
try {
await db.runTransaction(async function(transaction) {
const doc = await transaction
.collection(collectionName)
.doc('1')
.get()
assert.deepStrictEqual(doc.data, data[0])
await transaction.rollback('luke')
})
} catch (err) {
assert(err === 'luke')
}
try {
await db.runTransaction(async function(transaction) {
const doc = await transaction
.collection(collectionName)
.doc('1')
.get()
assert.deepStrictEqual(doc.data, data[0])
await transaction.rollback()
})
} catch (err) {
assert(err === undefined)
}
try {
await db.runTransaction(async transaction => {
const doc = await transaction
.collection(collectionName)
.doc('1')
.get()
assert.deepStrictEqual(doc.data, data[0])
// mock 事务冲突
throw {
code: 'DATABASE_TRANSACTION_CONFLICT',
message:
'[ResourceUnavailable.TransactionConflict] Transaction is conflict, maybe resource operated by others. Please check your request, but if the problem persists, contact us.'
}
})
} catch (e) {
assert(e.code === 'DATABASE_TRANSACTION_CONFLICT')
}
try {
const docRef1 = db.collection(collectionName).doc('1')
await db.runTransaction(async transaction => {
const doc = await transaction
.collection(collectionName)
.doc('1')
.get()
await docRef1.set({
category: 'wwwwwwwwwwwwwwwww'
})
const res = await transaction
.collection(collectionName)
.doc('1')
.update({
category: 'transactiontransactiontransaction'
})
})
} catch (e) {
// 因为mongo write conflict时会自动rollback,兜底的rollback会报错 非conflict错误
assert(e.code)
// assert(e.code === 'DATABASE_TRANSACTION_CONFLICT')
}
})
it('delete doc and abort', async () => {
// 前面测试用例删除了 _id = 2 的数据
const docRef = db.collection(collectionName).doc('3')
const transaction = await db.startTransaction()
// let doc = await transaction.get(docRef)
let doc = await transaction
.collection(collectionName)
.doc('3')
.get()
// const deleteResult = await transaction.delete(docRef)
const deleteResult = await transaction
.collection(collectionName)
.doc('3')
.delete()
assert.strictEqual(deleteResult.deleted, 1)
// doc = await transaction.get(docRef)
doc = await transaction
.collection(collectionName)
.doc('3')
.get()
assert.deepStrictEqual(doc.data, null)
await transaction.rollback()
const res = await docRef.get()
// const res = await transaction.collection(collectionName).doc('3').get()
assert.deepStrictEqual(res.data[0], data[2])
})
it('事务提交后, 不能进行其它操作', async () => {
// const docRef = db.collection(collectionName).doc('1')
const transaction = await db.startTransaction()
await transaction.commit()
await assert.rejects(
async () => {
// await transaction.set(docRef, {
// category: 'Node.js'
// })
await transaction
.collection(collectionName)
.doc('1')
.set({
category: 'Node.js'
})
},
{
code: 'DATABASE_TRANSACTION_FAIL',
message:
'[ResourceUnavailable.TransactionNotExist] Transaction does not exist on the server, transaction must be commit or abort in 30 seconds. Please check your request, but if the problem persists, contact us.'
}
)
})
it('冲突检测', async () => {
// const docRef = db.collection(collectionName).doc('1')
const transaction1 = await db.startTransaction(),
transaction2 = await db.startTransaction()
// 事务1先读取数据
// const doc = await transaction1.get(docRef)
const doc = await transaction1
.collection(collectionName)
.doc('1')
.get()
// 事务2更改之前事务1读取的数据,并且提交
// await transaction2.update(docRef, {
// category: '冲突检测'
// })
await transaction2
.collection(collectionName)
.doc('1')
.update({
category: '冲突检测'
})
// 由于事务1读取的数据没有时效性,故报错
await assert.rejects(
async () => {
// await transaction1.update(docRef, {
// category: doc.data.category + '冲突检测'
// })
await transaction1
.collection(collectionName)
.doc('1')
.update({
category: doc.data.category + '冲突检测'
})
},
{
code: 'DATABASE_TRANSACTION_CONFLICT'
}
)
await transaction2.commit()
})
it('读快照', async () => {
const docRef = db.collection(collectionName).doc('1')
// 启动事务
const transaction = await db.startTransaction()
// 修改数据
// await transaction.update(docRef, {
// category: 'update in transaction'
// })
await transaction
.collection(collectionName)
.doc('1')
.update({
category: 'update in transaction'
})
const result = await docRef.get()
// 事务读,读的是开始时刻的快照
// const doc_new = await transaction.get(docRef)
const doc_new = await transaction
.collection(collectionName)
.doc('1')
.get()
assert.deepStrictEqual(result.data[0], data[0])
assert.deepStrictEqual(doc_new.data, {
...data[0],
category: 'update in transaction'
})
await transaction.rollback()
})
it('读偏', async () => {
const docRef1 = db.collection(collectionName).doc('1')
const docRef2 = db.collection(collectionName).doc('2')
// 启动事务
const transaction = await db.startTransaction()
// 修改数据
// console.log(await transaction.get(docRef1))
await transaction
.collection(collectionName)
.doc('1')
.get()
await docRef1.set({
category: 'wwwwwwwwwwwwwwwww'
})
await docRef2.set({
category: 'hhhhhhhhhhhhhhh'
})
// 事务读,读的是开始时刻的快照
// const snapshot1 = await transaction.get(docRef1)
// const snapshot2 = await transaction.get(docRef2)
const snapshot1 = await transaction
.collection(collectionName)
.doc('1')
.get()
const snapshot2 = await transaction
.collection(collectionName)
.doc('2')
.get()
assert.deepStrictEqual(snapshot1.data, data[0])
assert.deepStrictEqual(snapshot2.data, data[1])
// 外部已经修改了数据,事务内修改应该失败
await assert.rejects(
async () => {
// await transaction.update(docRef1, {
// category: 'transactiontransactiontransaction'
// })
await transaction
.collection(collectionName)
.doc('1')
.update({
category: 'transactiontransactiontransaction'
})
},
{
code: 'DATABASE_TRANSACTION_CONFLICT',
message:
'[ResourceUnavailable.TransactionConflict] Transaction is conflict, maybe resource operated by others. Please check your request, but if the problem persists, contact us.'
}
)
})
it('write skew', async () => {
const docRef1 = db.collection(collectionName).doc('1')
const docRef2 = db.collection(collectionName).doc('2')
const transaction1 = await db.startTransaction()
const transaction2 = await db.startTransaction()
// 事务1:读1写2
// 事务2:读2写1
// const doc1 = await transaction1.get(docRef1)
// const doc2 = await transaction2.get(docRef2)
const doc1 = await transaction1
.collection(collectionName)
.doc('1')
.get()
const doc2 = await transaction2
.collection(collectionName)
.doc('2')
.get()
// await transaction1.set(docRef2, {
// category: doc1.data.category + 'doc1'
// })
// await transaction2.set(docRef1, {
// category: doc2.data.category + 'doc2'
// })
await transaction1
.collection(collectionName)
.doc('2')
.set({
category: doc1.data.category + 'doc1'
})
await transaction2
.collection(collectionName)
.doc('1')
.set({
category: doc2.data.category + 'doc2'
})
// 由于事务2读取的数据没有时效性,故报错
try {
await transaction1.commit()
await transaction2.commit()
} catch (error) {
console.log(error)
}
console.log(await docRef1.get())
console.log(await docRef2.get())
})
}) | the_stack |
import { getParsedResult, resolveReferences } from '../helpers';
import {
ParseObjectLiteral,
MetaResolver,
ParseArrayLiteral,
ParseLocation,
ParseValueType,
ParseProperty,
ParseTypeLiteral,
ParseDecorator,
applyTransformers,
ParseResult,
parseFile,
} from '../../src';
import { join } from 'path';
const jsonResolver = new MetaResolver();
describe('[code-analyzer] › MetaResolver › drop irrelevant root nodes', () => {
test('a function declaration should be dropped as root node', () => {
const source = 'function a(): boolean { return true }';
const result = getParsedResult(source) as any;
const resolved = result.visit(jsonResolver);
expect(resolved).toBeInstanceOf(Array);
expect(resolved).toHaveLength(0);
});
test('a class declaration as root node should be dropped', () => {
const source = 'class X { member: boolean; }';
const result = getParsedResult(source) as any;
const resolved = result.visit(jsonResolver);
expect(resolved).toBeInstanceOf(Array);
expect(resolved).toHaveLength(0);
});
test('an angular component should not be dropped!', () => {
const source = `
@Component({ selector: 'my-selector'})
export class myComponent {
@Input()
get member(): boolean { return true; }
set member(value: boolean) { }
}
`;
const result = getParsedResult(source) as any;
const resolved = result.visit(jsonResolver);
expect(resolved).toBeInstanceOf(Array);
expect(resolved).toHaveLength(1);
expect(resolved[0]).toMatchObject({
name: 'myComponent',
angularComponent: true,
decorator: { selector: '"my-selector"' },
members: [
{
type: 'property',
key: 'member',
value: ['true', 'false'],
},
{
type: 'method',
key: 'member',
parameters: [{ type: 'property', key: 'value', value: ['true', 'false'] }],
},
],
});
});
test('a variable declaration as root node should be dropped', () => {
const source = 'let a: number; const x = 1;';
const result = getParsedResult(source) as any;
const resolved = result.visit(jsonResolver);
expect(resolved).toBeInstanceOf(Array);
expect(resolved).toHaveLength(0);
});
test('a type alias declaration should be dropped as root node', () => {
const source = 'type x = "a" | "b"';
const result = getParsedResult(source) as any;
const resolved = result.visit(jsonResolver);
expect(resolved).toBeInstanceOf(Array);
expect(resolved).toHaveLength(0);
});
test('an enum declaration should be dropped as root node', () => {
const source = 'enum Direction { Up = 1, Down, Left, Right, }';
const result = getParsedResult(source) as any;
const resolved = result.visit(jsonResolver);
expect(resolved).toBeInstanceOf(Array);
expect(resolved).toHaveLength(0);
});
test('an interface declaration should be dropped as root node', () => {
const source = 'interface a { b: string; }';
const result = getParsedResult(source) as any;
const resolved = result.visit(jsonResolver);
expect(resolved).toBeInstanceOf(Array);
expect(resolved).toHaveLength(0);
});
});
describe('[code-analyzer] › MetaResolver › resolving all different nodes', () => {
const testLocation = new ParseLocation('test-file.ts', 10);
test('visitAllWithParent should return an empty array if nothing is provided', () => {
const result = jsonResolver.visitAllWithParent(null, null);
expect(result).toBeInstanceOf(Array);
expect(result).toHaveLength(0);
});
test('visitWithParent should return undefined if nothing is provided', () => {
const result = jsonResolver.visitWithParent(null, null);
expect(result).toBe(undefined);
});
test('resolving a partial should return null in case that we don\'t rely on Partials', () => {
const source = 'type a = Partial<"a" | "b">;';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toBeNull();
});
test('resolve an array literal to an array', () => {
const value1 = new ParseValueType(testLocation, 'a');
const value2 = new ParseValueType(testLocation, 'b');
const literal = new ParseArrayLiteral(testLocation, [], [value1, value2]);
const resolved = literal.visit(jsonResolver);
expect(resolved).toMatchObject(['a', 'b']);
});
test('resolve an object literal to an array', () => {
const value1 = new ParseValueType(testLocation, 'c');
const value2 = new ParseValueType(testLocation, 'd');
const prop1 = new ParseProperty(testLocation, 'a', [], value1);
const prop2 = new ParseProperty(testLocation, 'b', [], value2);
const literal = new ParseObjectLiteral(testLocation, [], [prop1, prop2]);
const resolved = literal.visit(jsonResolver);
expect(resolved).toMatchObject([
{ type: 'property', key: 'a', value: ['c'] },
{ type: 'property', key: 'b', value: ['d'] },
]);
});
test('resolve a type literal to an array', () => {
const value1 = new ParseValueType(testLocation, 'c');
const value2 = new ParseValueType(testLocation, 'd');
const prop1 = new ParseProperty(testLocation, 'a', [], value1);
const prop2 = new ParseProperty(testLocation, 'b', [], value2);
const literal = new ParseTypeLiteral(testLocation, [prop1, prop2]);
const resolved = literal.visit(jsonResolver);
expect(resolved).toMatchObject([
{ type: 'property', key: 'a', value: ['c'] },
{ type: 'property', key: 'b', value: ['d'] },
]);
});
test('unknown decorator should return undefined', () => {
const decorator = new ParseDecorator(testLocation, 'CustomDecorator', []);
const resolved = decorator.visit(jsonResolver);
expect(resolved).toBe(undefined);
});
test('resolving an objectLiteral to a property', () => {
const source = 'const x = {a: \'b\'};';
const result = getParsedResult(source).nodes[0] as any;
const resolved = result.visit(jsonResolver);
expect(resolved[0]).toMatchObject({
type: 'property',
key: 'a',
// tslint:disable-next-line: quotemark
value : ["\"b\""],
});
});
test('a boolean type should be resolved into an array of stringified true- and false-values', () => {
const source = 'let a:boolean';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject(['true', 'false']);
});
test('null as type should be resolved into a stringified null value', () => {
const source = 'let a:null;';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toBeNull();
});
test('when variable declaration has no type use the value', () => {
const source = 'const two = 2';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toBe('2');
});
test('when variable declaration a type prefer it before value', () => {
const source = 'type myType = 1 | 2; const two: myType = 2';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[1].visit(jsonResolver);
expect(resolved).not.toBe('2');
expect(resolved).toBeInstanceOf(Array);
expect(resolved).toMatchObject(['1', '2']);
});
test('a generic should return its value', () => {
const source = 'export type a<T> = () => T; const a:a<"valueType">;';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[1].visit(jsonResolver);
expect(resolved).toMatch('valueType');
});
test('a intersection type should be combining all values', () => {
const source = `
export interface X { a: boolean }
export interface Y { b: 1 }
function c(): X & Y {};
`;
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[2].visit(jsonResolver);
expect(resolved.returnType).toMatchObject([
{ type: 'property', key: 'a', value: ['true', 'false'] },
{ type: 'property', key: 'b', value: ['1'] },
]);
});
test('drop class that is marked as design-unrelated', () => {
const source = `
/** @design-unrelated */
@Component({})
class DtAnchor {
myMember: number = 1;
}`;
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toBeUndefined();
});
// test('when generic has no type use the value', () => {
// });
// test('when a property has no type use the value', () => {
// });
});
describe('[code-analyzer] › MetaResolver › testing class members', () => {
test('a private member should be dropped', () => {
const source = 'class a { private a: 1; }';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject([]);
});
test('a protected member should be dropped', () => {
const source = 'class a { protected a: 1; }';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject([]);
});
test('a public member should not be dropped', () => {
const source = 'class a { public a: 1; }';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject([
{ type: 'property', key: 'a', value: ['1'] },
]);
});
test('a member without any keyword should not be dropped', () => {
const source = 'class a { a: 1; }';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject([
{ type: 'property', key: 'a', value: ['1'] },
]);
});
test('a member with a leading underscore in the name should be dropped', () => {
const source = 'class a { _a: 1; }';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject([]);
});
test('a member with an @internal in the jsdoc should be dropped', () => {
const source = `
class a {
/** @internal */
a: 1;
}
`;
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject([]);
});
test('a method member with a leading underscore in the name should be dropped', () => {
const source = 'class a { _a(): void {} }';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject([]);
});
test('a method member with a private keyword should be dropped', () => {
const source = 'class a { private a(): void {} }';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject([]);
});
test('a method member with a protected keyword should be dropped', () => {
const source = 'class a { protected a(): void {} }';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject([]);
});
test('a method member with a public keyword should not be dropped', () => {
const source = 'class a { public a(): void {} }';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject([
{ type: 'method', key: 'a', parameters: [], returnType: 'void' },
]);
});
test('a method member with a @internal in the jsdoc should be dropped', () => {
const source = `
class a {
/** @internal */
public a(): void {}
}
`;
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject([]);
});
test('Angular life cycle method ngOnChanges should be dropped', () => {
const source = 'class a { ngOnChanges(): void {} }';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject([]);
});
test('Angular life cycle method ngOnInit should be dropped', () => {
const source = 'class a { ngOnInit(): void {} }';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject([]);
});
test('Angular life cycle method ngDoCheck should be dropped', () => {
const source = 'class a { ngDoCheck(): void {} }';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject([]);
});
test('Angular life cycle method ngAfterContentInit should be dropped', () => {
const source = 'class a { ngAfterContentInit(): void {} }';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject([]);
});
test('Angular life cycle method ngAfterContentChecked should be dropped', () => {
const source = 'class a { ngAfterContentChecked(): void {} }';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject([]);
});
test('Angular life cycle method ngAfterViewInit should be dropped', () => {
const source = 'class a { ngAfterViewInit(): void {} }';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject([]);
});
test('Angular life cycle method ngAfterViewChecked should be dropped', () => {
const source = 'class a { ngAfterViewChecked(): void {} }';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject([]);
});
test('Angular life cycle method ngOnDestroy should be dropped', () => {
const source = 'class a { ngOnDestroy(): void {} }';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[0].visit(jsonResolver);
expect(resolved).toMatchObject([]);
});
});
describe('[code-analyzer] › MetaResolver › test merging constraints', () => {
test('extends of a class should be merged into the base class', () => {
const source = 'export class a { a: 1; } class b extends a { b: 2; }';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[1].visit(jsonResolver);
expect(resolved).toMatchObject([
{ type: 'property', key: 'a', value: ['1'] },
{ type: 'property', key: 'b', value: ['2'] },
]);
});
test('extends of an interface should be merged into the base interface', () => {
const source = 'export interface a { a: 1; } interface b extends a { b: 2; }';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[1].visit(jsonResolver);
expect(resolved).toMatchObject([
{ type: 'property', key: 'a', value: ['1'] },
{ type: 'property', key: 'b', value: ['2'] },
]);
});
test('a generic with a constraint should be merged and flattened', () => {
const source = 'export class a { a: 1; } export function b<T extends a> (): T {} const c = b();';
const result = getParsedResult(source) as any;
const nodes = resolveReferences(result).nodes as any[];
const resolved = nodes[2].visit(jsonResolver);
expect(resolved).toMatchObject([{
type: 'property',
key: 'a',
value: ['1'],
}]);
});
});
test('resolving a full fledged Button component', async () => {
const paths = new Map<string, string>();
const result = new Map<string, ParseResult>();
await parseFile(join(__dirname, '..', 'fixtures', 'button.ts'), paths, result, 'node_modules');
const transformed = applyTransformers<any>(result)[0].members;
expect(transformed).toMatchObject(
expect.arrayContaining([
expect.objectContaining({
type: 'property',
key: 'disabled',
value: ['true', 'false'],
}),
expect.objectContaining({
type: 'property',
key: 'color',
// tslint:disable-next-line: quotemark
value: ["\"main\"", "\"warning\"", "\"cta\""],
}),
expect.objectContaining({
type: 'property',
key: 'variant',
// tslint:disable-next-line: quotemark
value: ["\"primary\"", "\"secondary\"", "\"nested\""],
}),
expect.objectContaining({
type: 'method',
key: 'focus',
parameters: [],
returnType: 'void',
}),
]),
);
}); | the_stack |
import Bluebird from 'bluebird';
import { Koncorde } from '../shared/KoncordeWrapper';
import { Client } from '@elastic/elasticsearch';
import { JSONObject } from 'kuzzle-sdk';
import { EmbeddedSDK } from '../shared/sdk/embeddedSdk';
import PluginRepository from './pluginRepository';
import Store from '../shared/store';
import Elasticsearch from '../../service/storage/elasticsearch';
import { isPlainObject } from '../../util/safeObject';
import Promback from '../../util/promback';
import { Mutex } from '../../util/mutex';
import kerror from '../../kerror';
import storeScopeEnum from '../storage/storeScopeEnum';
import {
BadRequestError,
ExternalServiceError,
ForbiddenError,
GatewayTimeoutError,
InternalError as KuzzleInternalError,
KuzzleError,
NotFoundError,
PartialError,
PluginImplementationError,
PreconditionError,
ServiceUnavailableError,
SizeLimitError,
TooManyRequestsError,
UnauthorizedError,
} from '../../kerror/errors';
import {
RequestContext,
RequestInput,
KuzzleRequest,
Request,
} from '../../../index';
import { BackendCluster } from '../backend';
const contextError = kerror.wrap('plugin', 'context');
export interface Repository {
create(document: JSONObject, options: any): Promise<any>;
createOrReplace(document: JSONObject, options: any): Promise<any>;
delete(documentId: string, options: any): Promise<any>;
get(documentId: string): Promise<any>;
mGet(ids: string[]): Promise<any>;
replace(document: JSONObject, options: any): Promise<any>;
search(query: JSONObject, options: any): Promise<any>;
update(document: JSONObject, options: any): Promise<any>;
}
export class PluginContext {
public accessors: {
/**
* Embedded SDK
*/
sdk: EmbeddedSDK,
/**
* Trigger a custom plugin event
*/
trigger: (eventName: string, payload: any) => Promise<any>,
/**
* Add or remove strategies dynamically
*/
strategies: {
/**
* Adds a new authentication strategy
*/
add: (name: string, properties: any) => Promise<void>,
/**
* Removes an authentication strategy, preventing new authentications from using it.
*/
remove: (name: string) => Promise<void>
},
/**
* Accessor to the Data Validation API
*/
validation: {
addType: any,
validate: any
},
/**
* Execute an API action.
*
* @deprecated use "accessors.sdk" instead (unless you need the original context)
*/
execute: (request: KuzzleRequest, callback?: any) => Promise<KuzzleRequest>,
/**
* Adds or removes realtime subscriptions from the backend.
*/
subscription: {
/**
* Registers a new realtime subscription on behalf of a client.
*/
register: (connectionId: string, index: string, collection: string, filters: JSONObject) => Promise<{ roomId: string }>,
/**
* Removes a realtime subscription on an existing `roomId` and `connectionId`
*/
unregister: (connectionId: string, roomId: string, notify: boolean) => Promise<void>
},
/**
* Initializes the plugin's private data storage.
*/
storage: {
/**
* Initializes the plugin storage
*/
bootstrap: (collections: any) => Promise<void>,
/**
* Creates a collection in the plugin storage
*/
createCollection: (collection: string, mappings: any) => Promise<void>
},
/**
* Cluster accessor
* @type {BackendCluster}
*/
cluster: BackendCluster,
};
public config: JSONObject;
public constructors: {
/**
* @todo need documentation
*/
BaseValidationType: any;
/**
* @deprecated import directly: `import { Koncorde } from 'kuzzle'`
*/
Koncorde: Koncorde;
/**
* Plugin private storage space
*/
Repository: new (collection: string, objectConstructor: any) => Repository;
/**
* Instantiate a new Request from the original one.
*/
Request: KuzzleRequest;
/**
* @deprecated import directly: `import { RequestContext } from 'kuzzle'`
*/
RequestContext: RequestContext;
/**
* @deprecated import directly: `import { RequestInput } from 'kuzzle'`
*/
RequestInput: RequestInput;
/**
* Constructor for Elasticsearch SDK Client
*/
ESClient: new () => Client
};
/**
* @deprecated import directly: `import { BadRequestError, ... } from 'kuzzle'`
*/
public errors: any;
/**
* Errors manager
*/
public kerror: any;
/**
* @deprecated use `PluginContext.kerror` instead
*/
public errorsManager: any;
/**
* Decrypted secrets from Kuzzle Vault
*/
public secrets: JSONObject;
/**
* Internal Logger
*/
public log: {
debug: (message: any) => void
error: (message: any) => void
info: (message: any) => void
silly: (message: any) => void
verbose: (message: any) => void
warn: (message: any) => void
};
constructor (pluginName) {
this.config = JSON.parse(JSON.stringify(global.kuzzle.config));
Object.freeze(this.config);
// @deprecated - backward compatibility only
this.errors = {
BadRequestError,
ExternalServiceError,
ForbiddenError,
GatewayTimeoutError,
InternalError: KuzzleInternalError,
KuzzleError,
NotFoundError,
PartialError,
PluginImplementationError,
PreconditionError,
ServiceUnavailableError,
SizeLimitError,
TooManyRequestsError,
UnauthorizedError,
};
this.kerror = kerror.wrap('plugin', pluginName);
// @deprecated - backward compatibility only
this.errorsManager = this.kerror;
/* context.secrets ====================================================== */
this.secrets = JSON.parse(JSON.stringify(global.kuzzle.vault.secrets));
Object.freeze(this.secrets);
// uppercase are forbidden by ES
const pluginIndex = `plugin-${pluginName}`.toLowerCase();
/* context.constructors =============================================== */
const pluginStore = new Store(
pluginIndex,
storeScopeEnum.PRIVATE);
// eslint-disable-next-line no-inner-declarations
function PluginContextRepository (
collection: string,
ObjectConstructor: any = null)
{
if (! collection) {
throw contextError.get('missing_collection');
}
const pluginRepository = new PluginRepository(
pluginStore,
collection);
pluginRepository.init({ ObjectConstructor });
return {
create: (...args) => pluginRepository.create(...args),
createOrReplace: (...args) => pluginRepository.createOrReplace(...args),
delete: (...args) => pluginRepository.delete(...args),
get: (...args) => pluginRepository.load(...args),
mGet: (...args) => pluginRepository.loadMultiFromDatabase(...args),
replace: (...args) => pluginRepository.replace(...args),
search: (...args) => pluginRepository.search(...args),
update: (...args) => pluginRepository.update(...args)
} as Repository;
}
// eslint-disable-next-line no-inner-declarations
function PluginContextESClient () {
return Elasticsearch
.buildClient(global.kuzzle.config.services.storageEngine.client);
}
this.constructors = {
BaseValidationType: require('../validation/baseType'),
ESClient: PluginContextESClient as unknown as new () => Client,
Koncorde: Koncorde as any,
Repository: PluginContextRepository as unknown as new (collection: string, objectConstructor: any) => Repository,
Request: instantiateRequest as any,
RequestContext: RequestContext as any,
RequestInput: RequestInput as any,
};
Object.freeze(this.constructors);
/* context.log ======================================================== */
this.log = {
debug: msg => global.kuzzle.log.debug(`[${pluginName}] ${msg}`),
error: msg => global.kuzzle.log.error(`[${pluginName}] ${msg}`),
info: msg => global.kuzzle.log.info(`[${pluginName}] ${msg}`),
silly: msg => global.kuzzle.log.silly(`[${pluginName}] ${msg}`),
verbose: msg => global.kuzzle.log.verbose(`[${pluginName}] ${msg}`),
warn: msg => global.kuzzle.log.warn(`[${pluginName}] ${msg}`)
};
Object.freeze(this.log);
/* context.accessors ================================================== */
this.accessors = {
cluster: new BackendCluster(),
execute: (request, callback) => execute(request, callback),
sdk: new EmbeddedSDK(),
storage: {
bootstrap: collections => pluginStore.init(collections),
createCollection: (collection, mappings) => (
pluginStore.createCollection(collection, { mappings })
)
},
strategies: {
add: curryAddStrategy(pluginName),
remove: curryRemoveStrategy(pluginName)
},
subscription: {
register: (connectionId, index, collection, filters) => {
const request = new KuzzleRequest(
{
action: 'subscribe',
body: filters,
collection,
controller: 'realtime',
index,
},
{
connectionId: connectionId,
});
return global.kuzzle.ask(
'core:realtime:subscribe',
request);
},
unregister: (connectionId, roomId, notify) =>
global.kuzzle.ask(
'core:realtime:unsubscribe',
connectionId, roomId, notify)
},
trigger: (eventName, payload) => (
global.kuzzle.pipe(`plugin-${pluginName}:${eventName}`, payload)
),
validation: {
addType: global.kuzzle.validation.addType.bind(global.kuzzle.validation),
validate: global.kuzzle.validation.validate.bind(global.kuzzle.validation)
},
};
// @todo freeze the "accessors" object once we don't have
// the PriviledgedContext anymore
}
}
/**
* @param {KuzzleRequest} request
* @param {Function} [callback]
*/
function execute (request, callback) {
if (callback && typeof callback !== 'function') {
const error = contextError.get('invalid_callback', typeof callback);
global.kuzzle.log.error(error);
return Bluebird.reject(error);
}
const promback = new Promback(callback);
if (!request || (!(request instanceof KuzzleRequest) && !(request instanceof Request))) {
return promback.reject(contextError.get('missing_request'));
}
if ( request.input.controller === 'realtime'
&& ['subscribe', 'unsubscribe'].includes(request.input.action)
) {
return promback.reject(
contextError.get('unavailable_realtime', request.input.action));
}
request.clearError();
request.status = 102;
global.kuzzle.funnel.executePluginRequest(request)
.then(result => {
request.setResult(
result,
{
status: request.status === 102 ? 200 : request.status
}
);
promback.resolve(request);
})
.catch(err => {
promback.reject(err);
});
return promback.deferred;
}
/**
* Instantiates a new Request object, using the provided one
* to set the context informations
*
* @throws
* @param {Request} request
* @param {Object} data
* @param {Object} [options]
* @returns {Request}
*/
function instantiateRequest(request, data, options = {}) {
let
_request = request,
_data = data,
_options = options;
if (!_request) {
throw contextError.get('missing_request_data');
}
if (!(_request instanceof KuzzleRequest)) {
if (_data) {
_options = _data;
}
_data = _request;
_request = null;
} else {
Object.assign(_options, _request.context.toJSON());
}
const target = new KuzzleRequest(_data, _options);
// forward informations if a request object was supplied
if (_request) {
for (const resource of ['_id', 'index', 'collection']) {
if (!target.input.resource[resource]) {
target.input.resource[resource] = _request.input.resource[resource];
}
}
for (const arg of Object.keys(_request.input.args)) {
if (target.input.args[arg] === undefined) {
target.input.args[arg] = _request.input.args[arg];
}
}
if (!_data || _data.jwt === undefined) {
target.input.jwt = _request.input.jwt;
}
if (_data) {
target.input.volatile = Object.assign(
{},
_request.input.volatile,
_data.volatile);
} else {
target.input.volatile = _request.input.volatile;
}
}
return target;
}
/**
* Returns a currified function of pluginsManager.registerStrategy
*
* @param {string} pluginName
* @returns {function} function taking a strategy name and properties,
* registering it into kuzzle, and returning
* a promise
*/
function curryAddStrategy(pluginName) {
return async function addStrategy(name, strategy) {
// strategy constructors cannot be used directly to dynamically
// add new strategies, because they cannot
// be serialized and propagated to other cluster nodes
// so if a strategy is not defined using an authenticator, we have
// to reject the call
if ( !isPlainObject(strategy)
|| !isPlainObject(strategy.config)
|| typeof strategy.config.authenticator !== 'string'
) {
throw contextError.get('missing_authenticator', pluginName, name);
}
const mutex = new Mutex('auth:strategies:add', { ttl: 30000 });
await mutex.lock();
try {
// @todo use Plugin.checkName to ensure format
global.kuzzle.pluginsManager.registerStrategy(pluginName, name, strategy);
return await global.kuzzle.pipe('core:auth:strategyAdded', {
name,
pluginName,
strategy,
});
}
finally {
await mutex.unlock();
}
};
}
/**
* Returns a currified function of pluginsManager.unregisterStrategy
*
* @param {string} pluginName
* @returns {function} function taking a strategy name and properties,
* registering it into kuzzle, and returning
* a promise
*/
function curryRemoveStrategy(pluginName) {
// either async or catch unregisterStrategy exceptions + return a rejected
// promise
return async function removeStrategy(name) {
const mutex = new Mutex('auth:strategies:remove', { ttl: 30000 });
await mutex.lock();
try {
global.kuzzle.pluginsManager.unregisterStrategy(pluginName, name);
return await global.kuzzle.pipe('core:auth:strategyRemoved', {name, pluginName});
}
finally {
await mutex.unlock();
}
};
} | the_stack |
'use strict';
export const positionKeywords: { [name: string]: string } = {
'bottom': 'Computes to ‘100%’ for the vertical position if one or two values are given, otherwise specifies the bottom edge as the origin for the next offset.',
'center': 'Computes to ‘50%’ (‘left 50%’) for the horizontal position if the horizontal position is not otherwise specified, or ‘50%’ (‘top 50%’) for the vertical position if it is.',
'left': 'Computes to ‘0%’ for the horizontal position if one or two values are given, otherwise specifies the left edge as the origin for the next offset.',
'right': 'Computes to ‘100%’ for the horizontal position if one or two values are given, otherwise specifies the right edge as the origin for the next offset.',
'top': 'Computes to ‘0%’ for the vertical position if one or two values are given, otherwise specifies the top edge as the origin for the next offset.'
};
export const repeatStyleKeywords: { [name: string]: string } = {
'no-repeat': 'Placed once and not repeated in this direction.',
'repeat': 'Repeated in this direction as often as needed to cover the background painting area.',
'repeat-x': 'Computes to ‘repeat no-repeat’.',
'repeat-y': 'Computes to ‘no-repeat repeat’.',
'round': 'Repeated as often as will fit within the background positioning area. If it doesn’t fit a whole number of times, it is rescaled so that it does.',
'space': 'Repeated as often as will fit within the background positioning area without being clipped and then the images are spaced out to fill the area.'
};
export const lineStyleKeywords: { [name: string]: string } = {
'dashed': 'A series of square-ended dashes.',
'dotted': 'A series of round dots.',
'double': 'Two parallel solid lines with some space between them.',
'groove': 'Looks as if it were carved in the canvas.',
'hidden': 'Same as ‘none’, but has different behavior in the border conflict resolution rules for border-collapsed tables.',
'inset': 'Looks as if the content on the inside of the border is sunken into the canvas.',
'none': 'No border. Color and width are ignored.',
'outset': 'Looks as if the content on the inside of the border is coming out of the canvas.',
'ridge': 'Looks as if it were coming out of the canvas.',
'solid': 'A single line segment.'
};
export const lineWidthKeywords = ['medium', 'thick', 'thin'];
export const boxKeywords: { [name: string]: string } = {
'border-box': 'The background is painted within (clipped to) the border box.',
'content-box': 'The background is painted within (clipped to) the content box.',
'padding-box': 'The background is painted within (clipped to) the padding box.'
};
export const geometryBoxKeywords: { [name: string]: string } = {
'margin-box': 'Uses the margin box as reference box.',
'fill-box': 'Uses the object bounding box as reference box.',
'stroke-box': 'Uses the stroke bounding box as reference box.',
'view-box': 'Uses the nearest SVG viewport as reference box.'
};
export const cssWideKeywords: { [name: string]: string } = {
'initial': 'Represents the value specified as the property’s initial value.',
'inherit': 'Represents the computed value of the property on the element’s parent.',
'unset': 'Acts as either `inherit` or `initial`, depending on whether the property is inherited or not.'
};
export const cssWideFunctions: { [name: string]: string } = {
'var()': 'Evaluates the value of a custom variable.',
'calc()': 'Evaluates an mathematical expression. The following operators can be used: + - * /.'
};
export const imageFunctions: { [name: string]: string } = {
'url()': 'Reference an image file by URL',
'image()': 'Provide image fallbacks and annotations.',
'-webkit-image-set()': 'Provide multiple resolutions. Remember to use unprefixed image-set() in addition.',
'image-set()': 'Provide multiple resolutions of an image and const the UA decide which is most appropriate in a given situation.',
'-moz-element()': 'Use an element in the document as an image. Remember to use unprefixed element() in addition.',
'element()': 'Use an element in the document as an image.',
'cross-fade()': 'Indicates the two images to be combined and how far along in the transition the combination is.',
'-webkit-gradient()': 'Deprecated. Use modern linear-gradient() or radial-gradient() instead.',
'-webkit-linear-gradient()': 'Linear gradient. Remember to use unprefixed version in addition.',
'-moz-linear-gradient()': 'Linear gradient. Remember to use unprefixed version in addition.',
'-o-linear-gradient()': 'Linear gradient. Remember to use unprefixed version in addition.',
'linear-gradient()': 'A linear gradient is created by specifying a straight gradient line, and then several colors placed along that line.',
'-webkit-repeating-linear-gradient()': 'Repeating Linear gradient. Remember to use unprefixed version in addition.',
'-moz-repeating-linear-gradient()': 'Repeating Linear gradient. Remember to use unprefixed version in addition.',
'-o-repeating-linear-gradient()': 'Repeating Linear gradient. Remember to use unprefixed version in addition.',
'repeating-linear-gradient()': 'Same as linear-gradient, except the color-stops are repeated infinitely in both directions, with their positions shifted by multiples of the difference between the last specified color-stop’s position and the first specified color-stop’s position.',
'-webkit-radial-gradient()': 'Radial gradient. Remember to use unprefixed version in addition.',
'-moz-radial-gradient()': 'Radial gradient. Remember to use unprefixed version in addition.',
'radial-gradient()': 'Colors emerge from a single point and smoothly spread outward in a circular or elliptical shape.',
'-webkit-repeating-radial-gradient()': 'Repeating radial gradient. Remember to use unprefixed version in addition.',
'-moz-repeating-radial-gradient()': 'Repeating radial gradient. Remember to use unprefixed version in addition.',
'repeating-radial-gradient()': 'Same as radial-gradient, except the color-stops are repeated infinitely in both directions, with their positions shifted by multiples of the difference between the last specified color-stop’s position and the first specified color-stop’s position.'
};
export const transitionTimingFunctions: { [name: string]: string } = {
'ease': 'Equivalent to cubic-bezier(0.25, 0.1, 0.25, 1.0).',
'ease-in': 'Equivalent to cubic-bezier(0.42, 0, 1.0, 1.0).',
'ease-in-out': 'Equivalent to cubic-bezier(0.42, 0, 0.58, 1.0).',
'ease-out': 'Equivalent to cubic-bezier(0, 0, 0.58, 1.0).',
'linear': 'Equivalent to cubic-bezier(0.0, 0.0, 1.0, 1.0).',
'step-end': 'Equivalent to steps(1, end).',
'step-start': 'Equivalent to steps(1, start).',
'steps()': 'The first parameter specifies the number of intervals in the function. The second parameter, which is optional, is either the value “start” or “end”.',
'cubic-bezier()': 'Specifies a cubic-bezier curve. The four values specify points P1 and P2 of the curve as (x1, y1, x2, y2).',
'cubic-bezier(0.6, -0.28, 0.735, 0.045)': 'Ease-in Back. Overshoots.',
'cubic-bezier(0.68, -0.55, 0.265, 1.55)': 'Ease-in-out Back. Overshoots.',
'cubic-bezier(0.175, 0.885, 0.32, 1.275)': 'Ease-out Back. Overshoots.',
'cubic-bezier(0.6, 0.04, 0.98, 0.335)': 'Ease-in Circular. Based on half circle.',
'cubic-bezier(0.785, 0.135, 0.15, 0.86)': 'Ease-in-out Circular. Based on half circle.',
'cubic-bezier(0.075, 0.82, 0.165, 1)': 'Ease-out Circular. Based on half circle.',
'cubic-bezier(0.55, 0.055, 0.675, 0.19)': 'Ease-in Cubic. Based on power of three.',
'cubic-bezier(0.645, 0.045, 0.355, 1)': 'Ease-in-out Cubic. Based on power of three.',
'cubic-bezier(0.215, 0.610, 0.355, 1)': 'Ease-out Cubic. Based on power of three.',
'cubic-bezier(0.95, 0.05, 0.795, 0.035)': 'Ease-in Exponential. Based on two to the power ten.',
'cubic-bezier(1, 0, 0, 1)': 'Ease-in-out Exponential. Based on two to the power ten.',
'cubic-bezier(0.19, 1, 0.22, 1)': 'Ease-out Exponential. Based on two to the power ten.',
'cubic-bezier(0.47, 0, 0.745, 0.715)': 'Ease-in Sine.',
'cubic-bezier(0.445, 0.05, 0.55, 0.95)': 'Ease-in-out Sine.',
'cubic-bezier(0.39, 0.575, 0.565, 1)': 'Ease-out Sine.',
'cubic-bezier(0.55, 0.085, 0.68, 0.53)': 'Ease-in Quadratic. Based on power of two.',
'cubic-bezier(0.455, 0.03, 0.515, 0.955)': 'Ease-in-out Quadratic. Based on power of two.',
'cubic-bezier(0.25, 0.46, 0.45, 0.94)': 'Ease-out Quadratic. Based on power of two.',
'cubic-bezier(0.895, 0.03, 0.685, 0.22)': 'Ease-in Quartic. Based on power of four.',
'cubic-bezier(0.77, 0, 0.175, 1)': 'Ease-in-out Quartic. Based on power of four.',
'cubic-bezier(0.165, 0.84, 0.44, 1)': 'Ease-out Quartic. Based on power of four.',
'cubic-bezier(0.755, 0.05, 0.855, 0.06)': 'Ease-in Quintic. Based on power of five.',
'cubic-bezier(0.86, 0, 0.07, 1)': 'Ease-in-out Quintic. Based on power of five.',
'cubic-bezier(0.23, 1, 0.320, 1)': 'Ease-out Quintic. Based on power of five.'
};
export const basicShapeFunctions: { [name: string]: string } = {
'circle()': 'Defines a circle.',
'ellipse()': 'Defines an ellipse.',
'inset()': 'Defines an inset rectangle.',
'polygon()': 'Defines a polygon.'
};
export const units: { [unitName: string]: string[] } = {
'length': ['em', 'rem', 'ex', 'px', 'cm', 'mm', 'in', 'pt', 'pc', 'ch', 'vw', 'vh', 'vmin', 'vmax'],
'angle': ['deg', 'rad', 'grad', 'turn'],
'time': ['ms', 's'],
'frequency': ['Hz', 'kHz'],
'resolution': ['dpi', 'dpcm', 'dppx'],
'percentage': ['%', 'fr']
};
export const html5Tags = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption',
'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer',
'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link',
'main', 'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q',
'rb', 'rp', 'rt', 'rtc', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td',
'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'const', 'video', 'wbr'];
export const svgElements = ['circle', 'clipPath', 'cursor', 'defs', 'desc', 'ellipse', 'feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting',
'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology',
'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence', 'filter', 'foreignObject', 'g', 'hatch', 'hatchpath', 'image', 'line', 'linearGradient',
'marker', 'mask', 'mesh', 'meshpatch', 'meshrow', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'set', 'solidcolor', 'stop', 'svg', 'switch',
'symbol', 'text', 'textPath', 'tspan', 'use', 'view'];
export const pageBoxDirectives = [
'@bottom-center', '@bottom-left', '@bottom-left-corner', '@bottom-right', '@bottom-right-corner',
'@left-bottom', '@left-middle', '@left-top', '@right-bottom', '@right-middle', '@right-top',
'@top-center', '@top-left', '@top-left-corner', '@top-right', '@top-right-corner'
]; | the_stack |
"use strict";
import tl = require('azure-pipelines-task-lib/task');
import path = require('path');
import * as kubectlConfigMap from "./kubernetesconfigmap";
import * as kubectlSecret from "./kubernetessecret";
import * as yaml from 'js-yaml';
import { IsJsonString, getDeploymentMetadata, getManifestFileUrlsFromArgumentsInput, getPublishDeploymentRequestUrl, isDeploymentEntity } from 'azure-pipelines-tasks-kubernetes-common-v2/image-metadata-helper';
import { WebRequest, WebResponse, sendRequest } from 'utility-common-v2/restutilities';
import { getCommandConfigurationFile, getNameSpace, isJsonOrYamlOutputFormatSupported } from "./kubernetescommand";
import ClusterConnection from "./clusterconnection";
import trm = require('azure-pipelines-task-lib/toolrunner');
tl.setResourcePath(path.join(__dirname, '..', 'task.json'));
tl.setResourcePath(path.join( __dirname, '../node_modules/azure-pipelines-tasks-azure-arm-rest-v2/module.json'));
// Change to any specified working directory
tl.cd(tl.getInput("cwd"));
var registryType = tl.getInput("containerRegistryType", true);
var command = tl.getInput("command", false);
const environmentVariableMaximumSize = 32766;
var kubeconfigfilePath;
if (command === "logout") {
kubeconfigfilePath = tl.getVariable("KUBECONFIG");
}
// open kubectl connection and run the command
var connection = new ClusterConnection(kubeconfigfilePath);
try {
connection.open().then(
() => { return run(connection, command) }
).then(
() => {
tl.setResult(tl.TaskResult.Succeeded, "");
if (command !== "login") {
connection.close();
}
}
).catch((error) => {
tl.setResult(tl.TaskResult.Failed, error.message)
connection.close();
});
}
catch (error) {
tl.setResult(tl.TaskResult.Failed, error.message);
}
async function run(clusterConnection: ClusterConnection, command: string) {
displayKubectlVersion(clusterConnection);
var secretName = tl.getInput("secretName", false);
var configMapName = tl.getInput("configMapName", false);
if (secretName) {
await kubectlSecret.run(clusterConnection, secretName);
}
if (configMapName) {
await kubectlConfigMap.run(clusterConnection, configMapName);
}
if (command) {
await executeKubectlCommand(clusterConnection, command);
}
}
function displayKubectlVersion(connection: ClusterConnection): void {
try {
var command = connection.createCommand();
command.arg('version');
command.arg(['-o', 'json']);
const result = command.execSync({ silent: true } as trm.IExecOptions);
const resultInJSON = JSON.parse(result.stdout);
if (resultInJSON.clientVersion && resultInJSON.clientVersion.gitVersion) {
console.log('==============================================================================');
console.log('\t\t\t' + tl.loc('KubectlClientVersion') + ': ' + resultInJSON.clientVersion.gitVersion);
if (resultInJSON.serverVersion && resultInJSON.serverVersion.gitVersion) {
console.log('\t\t\t' + tl.loc('KubectlServerVersion') + ': ' + resultInJSON.serverVersion.gitVersion);
console.log('==============================================================================');
}
else {
console.log('\t' + tl.loc('KubectlServerVersion') + ': ' + tl.loc('KubectlServerVerisonNotFound'));
console.log('==============================================================================');
tl.debug(tl.loc('UnableToFetchKubectlVersion'));
}
}
} catch (ex) {
console.log(tl.loc('UnableToFetchKubectlVersion'));
}
}
function getAllPods(connection: ClusterConnection): trm.IExecSyncResult {
const command = connection.createCommand();
command.arg('get');
command.arg('pods');
command.arg(['-o', 'json']);
command.arg(getNameSpace());
return command.execSync({ silent: true } as trm.IExecOptions);
}
function getClusterInfo(connection: ClusterConnection): trm.IExecSyncResult {
const command = connection.createCommand();
command.arg('cluster-info');
return command.execSync({ silent: true } as trm.IExecOptions);
}
// execute kubectl command
function executeKubectlCommand(clusterConnection: ClusterConnection, command: string): any {
var commandMap = {
"login": "./kuberneteslogin",
"logout": "./kuberneteslogout"
}
var commandImplementation = require("./kubernetescommand");
if (command in commandMap) {
commandImplementation = require(commandMap[command]);
}
var telemetry = {
registryType: registryType,
command: command,
jobId: tl.getVariable('SYSTEM_JOBID')
};
console.log("##vso[telemetry.publish area=%s;feature=%s]%s",
"TaskEndpointId",
"KubernetesV1",
JSON.stringify(telemetry));
// The output result can contain more than one Json objects
// We want to parse each of the objects separately, hence push the output in JSON array form
var result = [];
return commandImplementation.run(clusterConnection, command, (data) => result.push(data))
.fin(function cleanup() {
console.log("commandOutput" + result);
const resultString = result.toString();
const commandOutputLength = resultString.length;
if (commandOutputLength > environmentVariableMaximumSize) {
tl.warning(tl.loc("OutputVariableDataSizeExceeded", commandOutputLength, environmentVariableMaximumSize));
} else {
tl.setVariable('KubectlOutput', resultString);
}
try {
const outputFormat: string = tl.getInput("outputFormat", false);
const isOutputFormatSpecified: boolean = outputFormat && (outputFormat.toLowerCase() === "json" || outputFormat.toLowerCase() === "yaml");
// The deployment data is pushed to evidence store only for commands like 'apply' or 'create' which support Json and Yaml output format
if (isOutputFormatSpecified && isJsonOrYamlOutputFormatSupported(command)) {
let podsOutputString: string = "";
try {
podsOutputString = getAllPods(clusterConnection).stdout;
}
catch (e) {
tl.debug("Not pushing metadata to artifact metadata store as failed to retrieve container pods; Error: " + e);
return;
}
if (!IsJsonString(podsOutputString)) {
tl.debug("Not pushing metadata to artifact metadata store as failed to retrieve container pods");
}
else {
const allPods = JSON.parse(podsOutputString);
const clusterInfo = getClusterInfo(clusterConnection).stdout;
let fileArgs = "";
const configFilePathArgs = getCommandConfigurationFile();
if (configFilePathArgs.length > 0) {
fileArgs = configFilePathArgs.join(" ");
}
else {
fileArgs = tl.getInput("arguments", false);
}
const manifestUrls = getManifestFileUrlsFromArgumentsInput(fileArgs);
// For each output, check if it contains a JSON object
result.forEach(res => {
let parsedObject: any;
if (IsJsonString(res)) {
parsedObject = JSON.parse(res);
}
else {
parsedObject = yaml.safeLoad(res);
}
// Check if the output contains a deployment
if (parsedObject.kind && isDeploymentEntity(parsedObject.kind)) {
try {
pushDeploymentDataToEvidenceStore(clusterConnection, parsedObject, allPods, clusterInfo, manifestUrls).then((result) => {
tl.debug("DeploymentDetailsApiResponse: " + JSON.stringify(result));
}, (error) => {
tl.warning("publishToImageMetadataStore failed with error: " + error);
});
}
catch (e) {
tl.warning("pushDeploymentDataToEvidenceStore failed with error: " + e);
}
}
});
}
}
}
catch (e) {
tl.warning("Capturing deployment metadata failed with error: " + e)
}
});
}
async function pushDeploymentDataToEvidenceStore(clusterConnection: ClusterConnection, deploymentObject: any, allPods: any, clusterInfo: string, manifestUrls: string[]): Promise<any> {
const metadata = getDeploymentMetadata(deploymentObject, allPods, "None", clusterInfo, manifestUrls);
const requestUrl = getPublishDeploymentRequestUrl();
const request = new WebRequest();
const accessToken: string = tl.getEndpointAuthorizationParameter('SYSTEMVSSCONNECTION', 'ACCESSTOKEN', false);
request.uri = requestUrl;
request.method = 'POST';
request.body = JSON.stringify(metadata);
request.headers = {
"Content-Type": "application/json",
"Authorization": "Bearer " + accessToken
};
tl.debug("requestUrl: " + requestUrl);
tl.debug("requestBody: " + JSON.stringify(metadata));
try {
tl.debug("Sending request for pushing deployment data to Image meta data store");
const response = await sendRequest(request);
return response;
}
catch (error) {
tl.debug("Unable to push to deployment details to Artifact Store, Error: " + error);
}
} | the_stack |
import { ChartConfig } from 'app/types/ChartConfig';
const config: ChartConfig = {
datas: [
{
label: 'metrics',
key: 'metrics',
required: true,
type: 'aggregate',
limit: 1,
},
{
label: 'filter',
key: 'filter',
type: 'filter',
},
],
styles: [
{
label: 'gauge.title',
key: 'gauge',
comType: 'group',
rows: [
{
label: 'gauge.max',
key: 'max',
default: 100,
comType: 'inputNumber',
},
{
label: 'gauge.prefix',
key: 'prefix',
default: '',
comType: 'input',
},
{
label: 'gauge.suffix',
key: 'suffix',
default: '%',
comType: 'input',
},
{
label: 'gauge.radius',
key: 'radius',
default: '75%',
comType: 'marginWidth',
},
{
label: 'common.splitNumber',
key: 'splitNumber',
default: 10,
comType: 'inputNumber',
},
{
label: 'gauge.startAngle',
key: 'startAngle',
default: 225,
comType: 'inputNumber',
},
{
label: 'gauge.endAngle',
key: 'endAngle',
default: -45,
comType: 'inputNumber',
},
],
},
{
label: 'label.title',
key: 'label',
comType: 'group',
rows: [
{
label: 'label.showLabel',
key: 'showLabel',
default: true,
comType: 'checkbox',
},
{
label: 'viz.palette.style.font',
key: 'font',
comType: 'font',
default: {
fontFamily: 'PingFang SC',
fontSize: '12',
fontWeight: 'normal',
fontStyle: 'normal',
color: '#495057',
},
},
{
label: 'common.detailOffsetLeft',
key: 'detailOffsetLeft',
default: '0%',
comType: 'marginWidth',
},
{
label: 'common.detailOffsetTop',
key: 'detailOffsetTop',
default: '-40%',
comType: 'marginWidth',
},
],
},
{
label: 'data.title',
key: 'data',
comType: 'group',
rows: [
{
label: 'data.showData',
key: 'showData',
default: true,
comType: 'checkbox',
},
{
label: 'viz.palette.style.font',
key: 'font',
comType: 'font',
default: {
fontFamily: 'PingFang SC',
fontSize: '12',
fontWeight: 'normal',
fontStyle: 'normal',
color: '#495057',
},
},
{
label: 'common.detailOffsetLeft',
key: 'detailOffsetLeft',
default: '0%',
comType: 'marginWidth',
},
{
label: 'common.detailOffsetTop',
key: 'detailOffsetTop',
default: '40%',
comType: 'marginWidth',
},
],
},
{
label: 'pointer.title',
key: 'pointer',
comType: 'group',
rows: [
{
label: 'pointer.showPointer',
key: 'showPointer',
default: true,
comType: 'checkbox',
},
{
label: 'pointer.customPointerColor',
key: 'customPointerColor',
default: true,
comType: 'checkbox',
},
{
label: 'pointer.pointerColor',
key: 'pointerColor',
default: '#509af2',
comType: 'fontColor',
},
{
label: 'pointer.pointerLength',
key: 'pointerLength',
default: '80%',
comType: 'marginWidth',
},
{
label: 'pointer.pointerWidth',
key: 'pointerWidth',
default: 8,
comType: 'inputNumber',
},
{
label: 'pointer.lineStyle',
key: 'lineStyle',
comType: 'line',
default: {
type: 'solid',
width: 0,
color: '#D9D9D9',
},
},
],
},
{
label: 'axis.title',
key: 'axis',
comType: 'group',
rows: [
{
label: 'axis.axisLineSize',
key: 'axisLineSize',
default: 30,
comType: 'inputNumber',
},
{
label: 'axis.axisLineColor',
key: 'axisLineColor',
default: '#ddd',
comType: 'fontColor',
},
{
label: 'axis.axisRoundCap',
key: 'axisRoundCap',
default: true,
comType: 'checkbox',
},
],
},
{
label: 'axisTick.title',
key: 'axisTick',
comType: 'group',
rows: [
{
label: 'axisTick.showAxisTick',
key: 'showAxisTick',
default: true,
comType: 'checkbox',
},
{
label: 'common.lineStyle',
key: 'lineStyle',
comType: 'line',
default: {
type: 'solid',
width: 1,
color: '#63677A',
},
},
{
label: 'common.distance',
key: 'distance',
default: 10,
comType: 'inputNumber',
},
{
label: 'common.splitNumber',
key: 'splitNumber',
default: 5,
comType: 'inputNumber',
},
],
},
{
label: 'axisLabel.title',
key: 'axisLabel',
comType: 'group',
rows: [
{
label: 'axisLabel.showAxisLabel',
key: 'showAxisLabel',
default: true,
comType: 'checkbox',
},
{
label: 'viz.palette.style.font',
key: 'font',
comType: 'font',
default: {
fontFamily: 'PingFang SC',
fontSize: '12',
fontWeight: 'normal',
fontStyle: 'normal',
color: '#495057',
},
},
{
label: 'common.distance',
key: 'distance',
default: 35,
comType: 'inputNumber',
},
],
},
{
label: 'splitLine.title',
key: 'splitLine',
comType: 'group',
rows: [
{
label: 'splitLine.showSplitLine',
key: 'showSplitLine',
default: true,
comType: 'checkbox',
},
{
label: 'splitLine.splitLineLength',
key: 'splitLineLength',
default: 10,
comType: 'inputNumber',
},
{
label: 'common.distance',
key: 'distance',
default: 10,
comType: 'inputNumber',
},
{
label: 'common.lineStyle',
key: 'lineStyle',
comType: 'line',
default: {
type: 'solid',
width: 3,
color: '#63677A',
},
},
],
},
{
label: 'progress.title',
key: 'progress',
comType: 'group',
rows: [
{
label: 'progress.showProgress',
key: 'showProgress',
default: true,
comType: 'checkbox',
},
{
label: 'progress.roundCap',
key: 'roundCap',
default: true,
comType: 'checkbox',
},
],
},
],
settings: [
{
label: 'viz.palette.setting.paging.title',
key: 'paging',
comType: 'group',
rows: [
{
label: 'viz.palette.setting.paging.pageSize',
key: 'pageSize',
default: 1000,
comType: 'inputNumber',
options: {
needRefresh: true,
step: 1,
min: 0,
},
},
],
},
],
i18ns: [
{
lang: 'zh-CN',
translation: {
common: {
detailOffsetLeft: '距离左侧',
detailOffsetTop: '距离顶部',
distance: '距离轴线',
lineStyle: '样式',
splitNumber: '分隔段数',
},
gauge: {
title: '仪表盘',
max: '目标值',
prefix: '前缀',
suffix: '后缀',
radius: '半径',
startAngle: '起始角度',
endAngle: '结束角度',
},
label: {
title: '标题',
showLabel: '显示标题',
},
data: {
title: '数据',
showData: '显示数据',
},
pointer: {
title: '指针',
showPointer: '显示指针',
customPointerColor: '显示自定颜色',
pointerColor: '颜色',
pointerLength: '长度',
pointerWidth: '粗细',
lineStyle: '边框',
},
axis: {
title: '轴',
axisLineSize: '粗细',
axisLineColor: '颜色',
axisRoundCap: '两端显示圆形',
},
axisTick: {
title: '刻度',
showAxisTick: '显示刻度',
},
axisLabel: {
title: '标签',
showAxisLabel: '显示标签',
},
progress: {
title: '进度条',
showProgress: '显示进度条',
roundCap: '两端显示圆形',
},
splitLine: {
title: '分隔线',
showSplitLine: '显示分隔线',
splitLineLength: '长度',
},
},
},
{
lang: 'en-US',
translation: {
common: {
detailOffsetLeft: 'Offset Left',
detailOffsetTop: 'Offset Top',
distance: 'Distance',
lineStyle: 'Line Style',
splitNumber: 'Split Number',
},
gauge: {
title: 'Gauge',
max: 'Max',
prefix: 'Prefix',
suffix: 'Suffix',
radius: 'Radius',
startAngle: 'Start Angle',
endAngle: 'End Angle',
},
label: {
title: 'Label',
showLabel: 'Show Label',
},
data: {
title: 'Data',
showData: 'Show Data',
},
pointer: {
title: 'Pointer',
showPointer: 'Show Pointer',
customPointerColor: 'Show Customize Pointer Color',
pointerColor: 'Pointer Color',
pointerLength: 'Pointer Length',
pointerWidth: 'Pointer Width',
lineStyle: 'Line Style',
},
axis: {
title: 'Axis',
axisLineSize: 'Axis Line Size',
axisLineColor: 'Axis Line Color',
axisRoundCap: 'Axis Round Cap',
},
axisTick: {
title: 'Axis Tick',
showAxisTick: 'Show Axis Tick',
},
axisLabel: {
title: 'Axis Label',
showAxisLabel: 'Show Axis Label',
},
progress: {
title: 'Progress',
showProgress: 'Show Progress',
roundCap: 'Round Cap',
},
splitLine: {
title: 'Split Line',
showSplitLine: 'Show Split Line',
splitLineLength: 'Split Line Length',
},
},
},
],
};
export default config; | the_stack |
import * as ts from 'typescript';
import {
hasModifier,
WrappedAst,
getWrappedNodeAtPosition,
VariableUse,
UsageDomain,
isReassignmentTarget,
getPropertyOfType,
getLateBoundPropertyNames,
PropertyName,
isStatementInAmbientContext,
getLateBoundPropertyNamesOfPropertyName,
} from 'tsutils';
import { RuleContext } from '@fimbul/ymir';
export function* switchStatements(context: RuleContext) {
const {text} = context.sourceFile;
const re = /\bswitch\s*[(/]/g;
let wrappedAst: WrappedAst | undefined;
for (let match = re.exec(text); match !== null; match = re.exec(text)) {
const {node} = getWrappedNodeAtPosition(wrappedAst ??= context.getWrappedAst(), match.index)!;
if (node.kind === ts.SyntaxKind.SwitchStatement && node.getStart(context.sourceFile) === match.index)
yield <ts.SwitchStatement>node;
}
}
export function* tryStatements(context: RuleContext) {
const {text} = context.sourceFile;
const re = /\btry\s*[{/]/g;
let wrappedAst: WrappedAst | undefined;
for (let match = re.exec(text); match !== null; match = re.exec(text)) {
const {node} = getWrappedNodeAtPosition(wrappedAst ??= context.getWrappedAst(), match.index)!;
if (node.kind === ts.SyntaxKind.TryStatement && (<ts.TryStatement>node).tryBlock.pos - 'try'.length === match.index)
yield <ts.TryStatement>node;
}
}
export function isAsyncFunction(node: ts.Node): node is ts.FunctionLikeDeclaration & {body: ts.Block} {
switch (node.kind) {
case ts.SyntaxKind.FunctionDeclaration:
case ts.SyntaxKind.MethodDeclaration:
if ((<ts.FunctionLikeDeclaration>node).body === undefined)
return false;
// falls through
case ts.SyntaxKind.ArrowFunction:
if ((<ts.ArrowFunction>node).body.kind !== ts.SyntaxKind.Block)
return false;
// falls through
case ts.SyntaxKind.FunctionExpression:
break;
default:
return false;
}
return hasModifier(node.modifiers, ts.SyntaxKind.AsyncKeyword);
}
export function isVariableReassignment(use: VariableUse) {
return (use.domain & (UsageDomain.Value | UsageDomain.TypeQuery)) === UsageDomain.Value && isReassignmentTarget(use.location);
}
export function* childStatements(node: ts.Statement) {
switch (node.kind) {
case ts.SyntaxKind.IfStatement:
yield (<ts.IfStatement>node).thenStatement;
if ((<ts.IfStatement>node).elseStatement !== undefined)
yield (<ts.IfStatement>node).elseStatement!;
break;
case ts.SyntaxKind.ForStatement:
case ts.SyntaxKind.ForOfStatement:
case ts.SyntaxKind.ForInStatement:
case ts.SyntaxKind.WhileStatement:
case ts.SyntaxKind.DoStatement:
case ts.SyntaxKind.LabeledStatement:
case ts.SyntaxKind.WithStatement:
yield (<ts.IterationStatement | ts.LabeledStatement | ts.WithStatement>node).statement;
break;
case ts.SyntaxKind.SwitchStatement:
for (const clause of (<ts.SwitchStatement>node).caseBlock.clauses)
yield* clause.statements;
break;
case ts.SyntaxKind.Block:
yield* (<ts.Block>node).statements;
break;
case ts.SyntaxKind.TryStatement:
yield* (<ts.TryStatement>node).tryBlock.statements;
if ((<ts.TryStatement>node).catchClause !== undefined)
yield* (<ts.TryStatement>node).catchClause!.block.statements;
if ((<ts.TryStatement>node).finallyBlock !== undefined)
yield* ((<ts.TryStatement>node)).finallyBlock!.statements;
}
}
function getLeadingExpressionWithPossibleParsingAmbiguity(expr: ts.Node): ts.Expression | undefined {
switch (expr.kind) {
case ts.SyntaxKind.PropertyAccessExpression:
case ts.SyntaxKind.ElementAccessExpression:
case ts.SyntaxKind.AsExpression:
case ts.SyntaxKind.CallExpression:
case ts.SyntaxKind.NonNullExpression:
return (
<ts.PropertyAccessExpression | ts.ElementAccessExpression | ts.AsExpression | ts.CallExpression | ts.NonNullExpression>expr
).expression;
case ts.SyntaxKind.PostfixUnaryExpression:
return (<ts.PostfixUnaryExpression>expr).operand;
case ts.SyntaxKind.BinaryExpression:
return (<ts.BinaryExpression>expr).left;
case ts.SyntaxKind.ConditionalExpression:
return (<ts.ConditionalExpression>expr).condition;
case ts.SyntaxKind.TaggedTemplateExpression:
return (<ts.TaggedTemplateExpression>expr).tag;
default:
return;
}
}
export function expressionNeedsParensWhenReplacingNode(expr: ts.Expression, replaced: ts.Expression): boolean {
// this currently doesn't handle the following cases
// (yield) as any
// await (yield)
// (1).toString()
// ({foo} = {foo: 1});
// binary operator precendence
while (true) {
switch (expr.kind) {
case ts.SyntaxKind.ObjectLiteralExpression:
case ts.SyntaxKind.FunctionExpression:
case ts.SyntaxKind.ClassExpression:
return parentRequiresParensForNode(expr.kind, replaced);
default:
const current = getLeadingExpressionWithPossibleParsingAmbiguity(expr);
if (current === undefined)
return false;
expr = current;
}
}
}
function parentRequiresParensForNode(
kind: ts.SyntaxKind.ObjectLiteralExpression | ts.SyntaxKind.FunctionExpression | ts.SyntaxKind.ClassExpression,
replaced: ts.Node,
): boolean {
while (true) {
const parent = replaced.parent!;
switch (parent.kind) {
case ts.SyntaxKind.ArrowFunction:
return kind === ts.SyntaxKind.ObjectLiteralExpression;
case ts.SyntaxKind.ExpressionStatement:
return true;
case ts.SyntaxKind.ExportAssignment:
return !(<ts.ExportAssignment>parent).isExportEquals && kind !== ts.SyntaxKind.ObjectLiteralExpression;
}
if (getLeadingExpressionWithPossibleParsingAmbiguity(parent) !== replaced)
return false;
replaced = parent;
}
}
export function objectLiteralNeedsParens(replaced: ts.Expression): boolean {
return parentRequiresParensForNode(ts.SyntaxKind.ObjectLiteralExpression, replaced);
}
const typeFormat = ts.TypeFormatFlags.NoTruncation
| ts.TypeFormatFlags.UseFullyQualifiedType
| ts.TypeFormatFlags.WriteClassExpressionAsTypeLiteral
| ts.TypeFormatFlags.UseStructuralFallback;
export function typesAreEqual(a: ts.Type, b: ts.Type, checker: ts.TypeChecker) {
return a === b || checker.typeToString(a, undefined, typeFormat) === checker.typeToString(b, undefined, typeFormat);
}
export function *elementAccessSymbols(node: ts.ElementAccessExpression, checker: ts.TypeChecker) {
const {argumentExpression} = node;
if (argumentExpression === undefined || argumentExpression.pos === argumentExpression.end)
return;
const {names} = getLateBoundPropertyNames(argumentExpression, checker);
if (names.length === 0)
return;
yield* propertiesOfType(checker.getApparentType(checker.getTypeAtLocation(node.expression)).getNonNullableType(), names);
}
export function *propertiesOfType(type: ts.Type, names: Iterable<PropertyName>) {
for (const {symbolName, displayName} of names) {
const symbol = getPropertyOfType(type, symbolName);
if (symbol !== undefined)
yield {symbol, name: displayName};
}
}
export function hasDirectivePrologue(node: ts.Node): node is ts.BlockLike {
switch (node.kind) {
case ts.SyntaxKind.SourceFile:
case ts.SyntaxKind.ModuleBlock:
return true;
case ts.SyntaxKind.Block:
switch (node.parent!.kind) {
case ts.SyntaxKind.ArrowFunction:
case ts.SyntaxKind.FunctionExpression:
case ts.SyntaxKind.FunctionDeclaration:
case ts.SyntaxKind.MethodDeclaration:
case ts.SyntaxKind.Constructor:
case ts.SyntaxKind.GetAccessor:
case ts.SyntaxKind.SetAccessor:
return true;
default:
return false;
}
default:
return false;
}
}
/** Determines whether a property has the `declare` modifier or the containing class is ambient. */
export function isAmbientPropertyDeclaration(node: ts.PropertyDeclaration): boolean {
return hasModifier(node.modifiers, ts.SyntaxKind.DeclareKeyword) ||
node.parent!.kind === ts.SyntaxKind.ClassDeclaration && isStatementInAmbientContext(node.parent);
}
/** Determines whether the given variable declaration is ambient. */
export function isAmbientVariableDeclaration(node: ts.VariableDeclaration): boolean {
return node.parent!.kind === ts.SyntaxKind.VariableDeclarationList &&
node.parent.parent!.kind === ts.SyntaxKind.VariableStatement &&
isStatementInAmbientContext(node.parent.parent);
}
export function tryGetBaseConstraintType(type: ts.Type, checker: ts.TypeChecker) {
return checker.getBaseConstraintOfType(type) || type;
}
export interface PropertyNameWithLocation extends PropertyName {
node: ts.Node;
}
export function *addNodeToPropertyNameList(node: ts.Node, list: Iterable<PropertyName>): IterableIterator<PropertyNameWithLocation> {
for (const element of list)
yield {node, symbolName: element.symbolName, displayName: element.displayName};
}
export function *destructuredProperties(node: ts.ObjectBindingPattern, checker: ts.TypeChecker) {
for (const element of node.elements) {
if (element.dotDotDotToken !== undefined)
continue;
if (element.propertyName === undefined) {
yield {
node: element.name,
symbolName: (<ts.Identifier>element.name).escapedText,
displayName: (<ts.Identifier>element.name).text,
};
} else {
yield* addNodeToPropertyNameList(
element.propertyName,
getLateBoundPropertyNamesOfPropertyName(element.propertyName, checker).names,
);
}
}
} | the_stack |
import { arrayEquals, assert, copyWitNewLength } from "@apollo/federation-internals";
import { GraphPath, OpGraphPath, OpTrigger, PathIterator } from "./graphPath";
import { Edge, QueryGraph, RootVertex, isRootVertex, Vertex } from "./querygraph";
import { isPathContext } from "./pathContext";
function opTriggerEquality(t1: OpTrigger, t2: OpTrigger): boolean {
if (t1 === t2) {
return true;
}
if (isPathContext(t1)) {
return isPathContext(t2) && t1.equals(t2);
}
if (isPathContext(t2)) {
return false;
}
return t1.equals(t2);
}
type Child<TTrigger, RV extends Vertex, TNullEdge extends null | never> = {
index: number | TNullEdge,
trigger: TTrigger,
conditions: OpPathTree | null,
tree: PathTree<TTrigger, RV, TNullEdge>
}
function findTriggerIdx<TTrigger, TElements>(
triggerEquality: (t1: TTrigger, t2: TTrigger) => boolean,
forIndex: [TTrigger, OpPathTree | null, TElements][],
trigger: TTrigger
): number {
for (let i = 0; i < forIndex.length; i++) {
if (triggerEquality(forIndex[i][0], trigger)) {
return i;
}
}
return -1;
}
export class PathTree<TTrigger, RV extends Vertex = Vertex, TNullEdge extends null | never = never> {
private constructor(
readonly graph: QueryGraph,
readonly vertex: RV,
private readonly triggerEquality: (t1: TTrigger, t2: TTrigger) => boolean,
private readonly childs: Child<TTrigger, Vertex, TNullEdge>[],
) {
}
static create<TTrigger, RV extends Vertex = Vertex, TNullEdge extends null | never = never>(
graph: QueryGraph,
root: RV,
triggerEquality: (t1: TTrigger, t2: TTrigger) => boolean
): PathTree<TTrigger, RV, TNullEdge> {
return new PathTree(graph, root, triggerEquality, []);
}
static createOp<RV extends Vertex = Vertex>(graph: QueryGraph, root: RV): OpPathTree<RV> {
return this.create(graph, root, opTriggerEquality);
}
static createFromOpPaths<RV extends Vertex = Vertex>(graph: QueryGraph, root: RV, paths: OpGraphPath<RV>[]): OpPathTree<RV> {
assert(paths.length > 0, `Should compute on empty paths`);
return this.createFromPaths(
graph,
opTriggerEquality,
root,
paths.map(p => p[Symbol.iterator]())
);
}
private static createFromPaths<TTrigger, RV extends Vertex = Vertex, TNullEdge extends null | never = never>(
graph: QueryGraph,
triggerEquality: (t1: TTrigger, t2: TTrigger) => boolean,
currentVertex: RV,
paths: PathIterator<TTrigger, TNullEdge>[]
): PathTree<TTrigger, RV, TNullEdge> {
const maxEdges = graph.outEdges(currentVertex).length;
// We store 'null' edges at `maxEdges` index
const forEdgeIndex: [TTrigger, OpPathTree | null, PathIterator<TTrigger, TNullEdge>[]][][] = new Array(maxEdges + 1);
const newVertices: Vertex[] = new Array(maxEdges);
const order: number[] = new Array(maxEdges + 1);
let currentOrder = 0;
let totalChilds = 0;
for (const path of paths) {
const iterResult = path.next();
if (iterResult.done) {
continue;
}
const [edge, trigger, conditions] = iterResult.value;
const idx = edge ? edge.index : maxEdges;
if (edge) {
newVertices[idx] = edge.tail;
}
const forIndex = forEdgeIndex[idx];
if (forIndex) {
const triggerIdx = findTriggerIdx(triggerEquality, forIndex, trigger);
if (triggerIdx < 0) {
forIndex.push([trigger, conditions, [path]]);
totalChilds++;
} else {
const existing = forIndex[triggerIdx];
const existingCond = existing[1];
const mergedConditions = existingCond ? (conditions ? existingCond.mergeIfNotEqual(conditions) : existingCond) : conditions;
const newPaths = existing[2];
newPaths.push(path);
forIndex[triggerIdx] = [trigger, mergedConditions, newPaths];
// Note that as we merge, we don't create a new child
}
} else {
// First time we see someone from that index; record the order
order[currentOrder++] = idx;
forEdgeIndex[idx] = [[trigger, conditions, [path]]];
totalChilds++;
}
}
const childs: Child<TTrigger, Vertex, TNullEdge>[] = new Array(totalChilds);
let idx = 0;
for (let i = 0; i < currentOrder; i++) {
const edgeIndex = order[i];
const index = (edgeIndex === maxEdges ? null : edgeIndex) as number | TNullEdge;
const newVertex = index === null ? currentVertex : newVertices[edgeIndex];
const values = forEdgeIndex[edgeIndex];
for (const [trigger, conditions, subPaths] of values) {
childs[idx++] = {
index,
trigger,
conditions,
tree: this.createFromPaths(graph, triggerEquality, newVertex, subPaths)
};
}
}
assert(idx === totalChilds, () => `Expected to have ${totalChilds} childs but only ${idx} added`);
return new PathTree<TTrigger, RV, TNullEdge>(graph, currentVertex, triggerEquality, childs);
}
// Assumes all root are rooted on the same vertex
static mergeAllOpTrees<RV extends Vertex = Vertex>(graph: QueryGraph, root: RV, trees: OpPathTree<RV>[]): OpPathTree<RV> {
return this.mergeAllTreesInternal(graph, opTriggerEquality, root, trees);
}
private static mergeAllTreesInternal<TTrigger, RV extends Vertex, TNullEdge extends null | never>(
graph: QueryGraph,
triggerEquality: (t1: TTrigger, t2: TTrigger) => boolean,
currentVertex: RV,
trees: PathTree<TTrigger, RV, TNullEdge>[]
): PathTree<TTrigger, RV, TNullEdge> {
const maxEdges = graph.outEdges(currentVertex).length;
// We store 'null' edges at `maxEdges` index
const forEdgeIndex: [TTrigger, OpPathTree | null, PathTree<TTrigger, Vertex, TNullEdge>[]][][] = new Array(maxEdges + 1);
const newVertices: Vertex[] = new Array(maxEdges);
const order: number[] = new Array(maxEdges + 1);
let currentOrder = 0;
let totalChilds = 0;
for (const tree of trees) {
for (const child of tree.childs) {
const idx = child.index === null ? maxEdges : child.index;
if (!newVertices[idx]) {
newVertices[idx] = child.tree.vertex;
}
const forIndex = forEdgeIndex[idx];
if (forIndex) {
const triggerIdx = findTriggerIdx(triggerEquality, forIndex, child.trigger);
if (triggerIdx < 0) {
forIndex.push([child.trigger, child.conditions, [child.tree]]);
totalChilds++;
} else {
const existing = forIndex[triggerIdx];
const existingCond = existing[1];
const mergedConditions = existingCond ? (child.conditions ? existingCond.mergeIfNotEqual(child.conditions) : existingCond) : child.conditions;
const newTrees = existing[2];
newTrees.push(child.tree);
forIndex[triggerIdx] = [child.trigger, mergedConditions, newTrees];
// Note that as we merge, we don't create a new child
}
} else {
// First time we see someone from that index; record the order
order[currentOrder++] = idx;
forEdgeIndex[idx] = [[child.trigger, child.conditions, [child.tree]]];
totalChilds++;
}
}
}
const childs: Child<TTrigger, Vertex, TNullEdge>[] = new Array(totalChilds);
let idx = 0;
for (let i = 0; i < currentOrder; i++) {
const edgeIndex = order[i];
const index = (edgeIndex === maxEdges ? null : edgeIndex) as number | TNullEdge;
const newVertex = index === null ? currentVertex : newVertices[edgeIndex];
const values = forEdgeIndex[edgeIndex];
for (const [trigger, conditions, subTrees] of values) {
childs[idx++] = {
index,
trigger,
conditions,
tree: this.mergeAllTreesInternal(graph, triggerEquality, newVertex, subTrees)
};
}
}
assert(idx === totalChilds, () => `Expected to have ${totalChilds} childs but only ${idx} added`);
return new PathTree<TTrigger, RV, TNullEdge>(graph, currentVertex, triggerEquality, childs);
}
childCount(): number {
return this.childs.length;
}
isLeaf(): boolean {
return this.childCount() === 0;
}
*childElements(reverseOrder: boolean = false): Generator<[Edge | TNullEdge, TTrigger, OpPathTree | null, PathTree<TTrigger, Vertex, TNullEdge>], void, undefined> {
if (reverseOrder) {
for (let i = this.childs.length - 1; i >= 0; i--) {
yield this.element(i);
}
} else {
for (let i = 0; i < this.childs.length; i++) {
yield this.element(i);
}
}
}
private element(i: number): [Edge | TNullEdge, TTrigger, OpPathTree | null, PathTree<TTrigger, Vertex, TNullEdge>] {
const child = this.childs[i];
return [
(child.index === null ? null : this.graph.outEdge(this.vertex, child.index)) as Edge | TNullEdge,
child.trigger,
child.conditions,
child.tree
];
}
private mergeChilds(c1: Child<TTrigger, Vertex, TNullEdge>, c2: Child<TTrigger, Vertex, TNullEdge>): Child<TTrigger, Vertex, TNullEdge> {
const cond1 = c1.conditions;
const cond2 = c2.conditions;
return {
index: c1.index,
trigger: c1.trigger,
conditions: cond1 ? (cond2 ? cond1.mergeIfNotEqual(cond2) : cond1) : cond2,
tree: c1.tree.merge(c2.tree)
};
}
mergeIfNotEqual(other: PathTree<TTrigger, RV, TNullEdge>): PathTree<TTrigger, RV, TNullEdge> {
if (this.equalsSameRoot(other)) {
return this;
}
return this.merge(other);
}
merge(other: PathTree<TTrigger, RV, TNullEdge>): PathTree<TTrigger, RV, TNullEdge> {
// If we somehow end up trying to merge a tree with itself, let's not waste work on it.
if (this === other) {
return this;
}
assert(other.graph === this.graph, 'Cannot merge path tree build on another graph');
assert(other.vertex.index === this.vertex.index, () => `Cannot merge path tree rooted at vertex ${other.vertex} into tree rooted at other vertex ${this.vertex}`);
if (!other.childs.length) {
return this;
}
if (!this.childs.length) {
return other;
}
const mergeIndexes: number[] = new Array(other.childs.length);
let countToAdd = 0;
for (let i = 0; i < other.childs.length; i++) {
const otherChild = other.childs[i];
const idx = this.findIndex(otherChild.trigger, otherChild.index);
mergeIndexes[i] = idx;
if (idx < 0) {
++countToAdd;
}
}
const thisSize = this.childs.length;
const newSize = thisSize + countToAdd;
const newChilds = copyWitNewLength(this.childs, newSize);
let addIdx = thisSize;
for (let i = 0; i < other.childs.length; i++) {
const idx = mergeIndexes[i];
if (idx < 0) {
newChilds[addIdx++] = other.childs[i];
} else {
newChilds[idx] = this.mergeChilds(newChilds[idx], other.childs[i]);
}
}
assert(addIdx === newSize, () => `Expected ${newSize} childs but only got ${addIdx}`);
return new PathTree(this.graph, this.vertex, this.triggerEquality, newChilds);
}
private equalsSameRoot(that: PathTree<TTrigger, RV, TNullEdge>): boolean {
if (this === that) {
return true;
}
// Note that we use '===' for trigger instead of `triggerEquality`: this method is all about avoid unnecessary merging
// when we suspect conditions trees have been build from the exact same inputs and `===` is faster and good enough for this.
return arrayEquals(this.childs, that.childs, (c1, c2) => {
return c1.index === c2.index
&& c1.trigger === c2.trigger
&& (c1.conditions ? (c2.conditions ? c1.conditions.equalsSameRoot(c2.conditions) : false) : !c2.conditions)
&& c1.tree.equalsSameRoot(c2.tree);
});
}
// Like merge(), this create a new tree that contains the content of both `this` and `other` to this pathTree, but contrarily
// to merge() this never merge childs together, even if they are equal. This is only for the special case of mutations.
concat(other: PathTree<TTrigger, RV, TNullEdge>): PathTree<TTrigger, RV, TNullEdge> {
assert(other.graph === this.graph, 'Cannot concat path tree build on another graph');
assert(other.vertex.index === this.vertex.index, () => `Cannot concat path tree rooted at vertex ${other.vertex} into tree rooted at other vertex ${this.vertex}`);
if (!other.childs.length) {
return this;
}
if (!this.childs.length) {
return other;
}
const newChilds = this.childs.concat(other.childs);
return new PathTree(this.graph, this.vertex, this.triggerEquality, newChilds);
}
mergePath(path: GraphPath<TTrigger, RV, TNullEdge>): PathTree<TTrigger, RV, TNullEdge> {
assert(path.graph === this.graph, 'Cannot merge path build on another graph');
assert(path.root.index === this.vertex.index, () => `Cannot merge path rooted at vertex ${path.root} into tree rooted at other vertex ${this.vertex}`);
return this.mergePathInternal(path[Symbol.iterator]());
}
private childsFromPathElements(currentVertex: Vertex, elements: PathIterator<TTrigger, TNullEdge>): Child<TTrigger, Vertex, TNullEdge>[] {
const iterResult = elements.next();
if (iterResult.done) {
return [];
}
const [edge, trigger, conditions] = iterResult.value;
const edgeIndex = (edge ? edge.index : null) as number | TNullEdge;
currentVertex = edge ? edge.tail : currentVertex;
return [{
index: edgeIndex,
trigger: trigger,
conditions: conditions,
tree: new PathTree<TTrigger, Vertex, TNullEdge>(this.graph, currentVertex, this.triggerEquality, this.childsFromPathElements(currentVertex, elements))
}];
}
private mergePathInternal(elements: PathIterator<TTrigger, TNullEdge>): PathTree<TTrigger, RV, TNullEdge> {
const iterResult = elements.next();
if (iterResult.done) {
return this;
}
const [edge, trigger, conditions] = iterResult.value;
assert(!edge || edge.head.index === this.vertex.index, () => `Next element head of ${edge} is not equal to current tree vertex ${this.vertex}`);
const edgeIndex = (edge ? edge.index : null) as number | TNullEdge;
const idx = this.findIndex(trigger, edgeIndex);
if (idx < 0) {
const currentVertex = edge ? edge.tail : this.vertex;
return new PathTree<TTrigger, RV, TNullEdge>(
this.graph,
this.vertex,
this.triggerEquality,
this.childs.concat({
index: edgeIndex,
trigger: trigger,
conditions: conditions,
tree: new PathTree<TTrigger, Vertex, TNullEdge>(this.graph, currentVertex, this.triggerEquality, this.childsFromPathElements(currentVertex, elements))
})
);
} else {
const newChilds = this.childs.concat();
const existing = newChilds[idx];
newChilds[idx] = {
index: existing.index,
trigger: existing.trigger,
conditions: conditions ? (existing.conditions ? existing.conditions.merge(conditions) : conditions) : existing.conditions,
tree: existing.tree.mergePathInternal(elements)
};
return new PathTree<TTrigger, RV, TNullEdge>(this.graph, this.vertex, this.triggerEquality, newChilds);
}
}
private findIndex(trigger: TTrigger, edgeIndex: number | TNullEdge): number {
for (let i = 0; i < this.childs.length; i++) {
const child = this.childs[i];
if (child.index === edgeIndex && this.triggerEquality(child.trigger, trigger)) {
return i;
}
}
return -1;
}
isAllInSameSubgraph(): boolean {
return this.isAllInSameSubgraphInternal(this.vertex.source);
}
private isAllInSameSubgraphInternal(target: string): boolean {
return this.vertex.source === target
&& this.childs.every(c => c.tree.isAllInSameSubgraphInternal(target));
}
toString(indent: string = "", includeConditions: boolean = false): string {
return this.toStringInternal(indent, includeConditions);
}
private toStringInternal(indent: string, includeConditions: boolean): string {
if (this.isLeaf()) {
return this.vertex.toString();
}
return this.vertex + ':\n' +
this.childs.map(child =>
indent
+ ` -> [${child.index}] `
+ (includeConditions && child.conditions ? `!! {\n${indent + " "}${child.conditions!.toString(indent + " ", true)}\n${indent} } ` : "")
+ `${child.trigger} = `
+ child.tree.toStringInternal(indent + " ", includeConditions)
).join('\n');
}
}
export type RootPathTree<TTrigger, TNullEdge extends null | never = never> = PathTree<TTrigger, RootVertex, TNullEdge>;
export type OpPathTree<RV extends Vertex = Vertex> = PathTree<OpTrigger, RV, null>;
export type OpRootPathTree = OpPathTree<RootVertex>;
export function isRootPathTree(tree: OpPathTree<any>): tree is OpRootPathTree {
return isRootVertex(tree.vertex);
}
export function traversePathTree<TTrigger, RV extends Vertex = Vertex, TNullEdge extends null | never = never>(
pathTree: PathTree<TTrigger, RV, TNullEdge>,
onEdges: (edge: Edge) => void
) {
for (const [edge, _, conditions, childTree] of pathTree.childElements()) {
if (edge) {
onEdges(edge);
}
if (conditions) {
traversePathTree(conditions, onEdges);
}
traversePathTree(childTree, onEdges);
}
} | the_stack |
import { Injectable } from '@angular/core';
import { CoreApp } from '@services/app';
import { CoreCronDelegate } from '@services/cron';
import { CoreEvents } from '@singletons/events';
import { CoreFilepool } from '@services/filepool';
import { CoreSite } from '@classes/site';
import { CoreSites } from '@services/sites';
import { CoreUtils } from '@services/utils/utils';
import { CoreConstants } from '@/core/constants';
import { CoreConfig } from '@services/config';
import { CoreFilter } from '@features/filter/services/filter';
import { CoreDomUtils } from '@services/utils/dom';
import { CoreCourse } from '@features/course/services/course';
import { makeSingleton, Translate } from '@singletons';
import { CoreError } from '@classes/errors/error';
/**
* Object with space usage and cache entries that can be erased.
*/
export interface CoreSiteSpaceUsage {
cacheEntries: number; // Number of cached entries that can be cleared.
spaceUsage: number; // Space used in this site (total files + estimate of cache).
}
/**
* Constants to define color schemes.
*/
export const enum CoreColorScheme {
SYSTEM = 'system',
LIGHT = 'light',
DARK = 'dark',
}
/**
* Constants to define zoom levels.
*/
export const enum CoreZoomLevel {
NORMAL = 'normal',
LOW = 'low',
HIGH = 'high',
}
/**
* Settings helper service.
*/
@Injectable({ providedIn: 'root' })
export class CoreSettingsHelperProvider {
protected syncPromises: { [s: string]: Promise<void> } = {};
protected prefersDark?: MediaQueryList;
protected colorSchemes: CoreColorScheme[] = [];
protected currentColorScheme = CoreColorScheme.LIGHT;
constructor() {
this.prefersDark = window.matchMedia('(prefers-color-scheme: dark)');
if (!CoreConstants.CONFIG.forceColorScheme) {
// Update color scheme when a user enters or leaves a site, or when the site info is updated.
const applySiteScheme = (): void => {
if (this.isColorSchemeDisabledInSite()) {
// Dark mode is disabled, force light mode.
this.setColorScheme(CoreColorScheme.LIGHT);
} else {
// Reset color scheme settings.
this.initColorScheme();
}
};
CoreEvents.on(CoreEvents.LOGIN, applySiteScheme.bind(this));
CoreEvents.on(CoreEvents.SITE_UPDATED, applySiteScheme.bind(this));
CoreEvents.on(CoreEvents.LOGOUT, () => {
// Reset color scheme settings.
this.initColorScheme();
});
} else {
this.initColorScheme();
}
// Listen for changes to the prefers-color-scheme media query.
this.prefersDark.addEventListener && this.prefersDark.addEventListener('change', this.toggleDarkModeListener.bind(this));
}
/**
* Deletes files of a site and the tables that can be cleared.
*
* @param siteName Site Name.
* @param siteId: Site ID.
* @return Resolved with detailed new info when done.
*/
async deleteSiteStorage(siteName: string, siteId: string): Promise<CoreSiteSpaceUsage> {
const siteInfo: CoreSiteSpaceUsage = {
cacheEntries: 0,
spaceUsage: 0,
};
siteName = await CoreFilter.formatText(siteName, { clean: true, singleLine: true, filter: false }, [], siteId);
const title = Translate.instant('core.settings.deletesitefilestitle');
const message = Translate.instant('core.settings.deletesitefiles', { sitename: siteName });
await CoreDomUtils.showConfirm(message, title);
const site = await CoreSites.getSite(siteId);
// Clear cache tables.
const cleanSchemas = CoreSites.getSiteTableSchemasToClear(site);
const promises: Promise<number | void>[] = cleanSchemas.map((name) => site.getDb().deleteRecords(name));
const filepoolService = CoreFilepool.instance;
promises.push(site.deleteFolder().then(() => {
filepoolService.clearAllPackagesStatus(siteId);
filepoolService.clearFilepool(siteId);
CoreCourse.clearAllCoursesStatus(siteId);
siteInfo.spaceUsage = 0;
return;
}).catch(async (error) => {
if (error && error.code === FileError.NOT_FOUND_ERR) {
// Not found, set size 0.
filepoolService.clearAllPackagesStatus(siteId);
siteInfo.spaceUsage = 0;
} else {
// Error, recalculate the site usage.
CoreDomUtils.showErrorModal('core.settings.errordeletesitefiles', true);
siteInfo.spaceUsage = await site.getSpaceUsage();
}
}).then(async () => {
CoreEvents.trigger(CoreEvents.SITE_STORAGE_DELETED, {}, siteId);
siteInfo.cacheEntries = await this.calcSiteClearRows(site);
return;
}));
await Promise.all(promises);
return siteInfo;
}
/**
* Calculates each site's usage, and the total usage.
*
* @param siteId ID of the site. Current site if undefined.
* @return Resolved with detailed info when done.
*/
async getSiteSpaceUsage(siteId?: string): Promise<CoreSiteSpaceUsage> {
const site = await CoreSites.getSite(siteId);
// Get space usage.
const siteInfo: CoreSiteSpaceUsage = {
cacheEntries: 0,
spaceUsage: 0,
};
siteInfo.cacheEntries = await this.calcSiteClearRows(site);
siteInfo.spaceUsage = await site.getTotalUsage();
return siteInfo;
}
/**
* Calculate the number of rows to be deleted on a site.
*
* @param site Site object.
* @return If there are rows to delete or not.
*/
protected async calcSiteClearRows(site: CoreSite): Promise<number> {
const clearTables = CoreSites.getSiteTableSchemasToClear(site);
let totalEntries = 0;
await Promise.all(clearTables.map(async (name) =>
totalEntries = await site.getDb().countRecords(name) + totalEntries));
return totalEntries;
}
/**
* Get a certain processor from a list of processors.
*
* @param processors List of processors.
* @param name Name of the processor to get.
* @param fallback True to return first processor if not found, false to not return any. Defaults to true.
* @return Processor.
* @deprecated since 3.9.5. This function has been moved to AddonNotificationsHelperProvider.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getProcessor(processors: unknown[], name: string, fallback: boolean = true): undefined {
return;
}
/**
* Return the components and notifications that have a certain processor.
*
* @param processorName Name of the processor to filter.
* @param components Array of components.
* @return Filtered components.
* @deprecated since 3.9.5. This function has been moved to AddonNotificationsHelperProvider.
*/
getProcessorComponents(processorName: string, components: unknown[]): unknown[] {
return components;
}
/**
* Get the synchronization promise of a site.
*
* @param siteId ID of the site.
* @return Sync promise or null if site is not being syncrhonized.
*/
getSiteSyncPromise(siteId: string): Promise<void> | void {
if (this.syncPromises[siteId]) {
return this.syncPromises[siteId];
}
}
/**
* Synchronize a site.
*
* @param syncOnlyOnWifi True to sync only on wifi, false otherwise.
* @param siteId ID of the site to synchronize.
* @return Promise resolved when synchronized, rejected if failure.
*/
async synchronizeSite(syncOnlyOnWifi: boolean, siteId: string): Promise<void> {
if (this.syncPromises[siteId]) {
// There's already a sync ongoing for this site, return the promise.
return this.syncPromises[siteId];
}
const site = await CoreSites.getSite(siteId);
const hasSyncHandlers = CoreCronDelegate.hasManualSyncHandlers();
if (site.isLoggedOut()) {
// Cannot sync logged out sites.
throw new CoreError(Translate.instant('core.settings.cannotsyncloggedout'));
} else if (hasSyncHandlers && !CoreApp.isOnline()) {
// We need connection to execute sync.
throw new CoreError(Translate.instant('core.settings.cannotsyncoffline'));
} else if (hasSyncHandlers && syncOnlyOnWifi && CoreApp.isNetworkAccessLimited()) {
throw new CoreError(Translate.instant('core.settings.cannotsyncwithoutwifi'));
}
const syncPromise = Promise.all([
// Invalidate all the site files so they are re-downloaded.
CoreUtils.ignoreErrors(CoreFilepool.invalidateAllFiles(siteId)),
// Invalidate and synchronize site data.
site.invalidateWsCache(),
this.checkSiteLocalMobile(site),
CoreSites.updateSiteInfo(site.getId()),
CoreCronDelegate.forceSyncExecution(site.getId()),
// eslint-disable-next-line arrow-body-style
]).then(() => {
return;
});
this.syncPromises[siteId] = syncPromise;
try {
await syncPromise;
} finally {
delete this.syncPromises[siteId];
}
}
/**
* Check if local_mobile was added to the site.
*
* @param site Site to check.
* @return Promise resolved if no action needed.
*/
protected async checkSiteLocalMobile(site: CoreSite): Promise<void> {
try {
// Check if local_mobile was installed in Moodle.
await site.checkIfLocalMobileInstalledAndNotUsed();
} catch {
// Not added, nothing to do.
return;
}
// Local mobile was added. Throw invalid session to force reconnect and create a new token.
CoreEvents.trigger(CoreEvents.SESSION_EXPIRED, {}, site.getId());
throw new CoreError(Translate.instant('core.lostconnection'));
}
/**
* Upgrades from Font size to new zoom level.
*/
async upgradeZoomLevel(): Promise<void> {
// Check old setting and update the new.
try {
const fontSize = await CoreConfig.get<number>('CoreSettingsFontSize');
if (typeof fontSize == 'undefined') {
// Already upgraded.
return;
}
// Reset the value to solve edge cases.
CoreConfig.set(CoreConstants.SETTINGS_ZOOM_LEVEL, CoreZoomLevel.NORMAL);
if (fontSize < 100) {
if (fontSize > 90) {
CoreConfig.set(CoreConstants.SETTINGS_ZOOM_LEVEL, CoreZoomLevel.HIGH);
} else if (fontSize > 70) {
CoreConfig.set(CoreConstants.SETTINGS_ZOOM_LEVEL, CoreZoomLevel.LOW);
}
}
CoreConfig.delete('CoreSettingsFontSize');
} catch {
// Already upgraded.
return;
}
}
/**
* Get saved Zoom Level setting.
*
* @return The saved zoom Level option.
*/
async getZoomLevel(): Promise<CoreZoomLevel> {
return CoreConfig.get(CoreConstants.SETTINGS_ZOOM_LEVEL, CoreZoomLevel.NORMAL);
}
/**
* Get saved zoom level value.
*
* @return The saved zoom level value in %.
*/
async getZoom(): Promise<number> {
const zoomLevel = await this.getZoomLevel();
return CoreConstants.CONFIG.zoomlevels[zoomLevel];
}
/**
* Init Settings related to DOM.
*/
async initDomSettings(): Promise<void> {
// Set the font size based on user preference.
const zoomLevel = await this.getZoomLevel();
this.applyZoomLevel(zoomLevel);
this.initColorScheme();
}
/**
* Init the color scheme.
*/
async initColorScheme(): Promise<void> {
if (CoreConstants.CONFIG.forceColorScheme) {
this.setColorScheme(CoreConstants.CONFIG.forceColorScheme);
} else {
const scheme = await CoreConfig.get(CoreConstants.SETTINGS_COLOR_SCHEME, CoreColorScheme.LIGHT);
this.setColorScheme(scheme);
}
}
/**
* Check if color scheme is disabled in a site.
*
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved with whether color scheme is disabled.
*/
async isColorSchemeDisabled(siteId?: string): Promise<boolean> {
const site = await CoreSites.getSite(siteId);
return this.isColorSchemeDisabledInSite(site);
}
/**
* Check if color scheme is disabled in a site.
*
* @param site Site instance. If not defined, current site.
* @return Whether color scheme is disabled.
*/
isColorSchemeDisabledInSite(site?: CoreSite): boolean {
site = site || CoreSites.getCurrentSite();
return site ? site.isFeatureDisabled('NoDelegate_DarkMode') : false;
}
/**
* Set document default font size.
*
* @param zoomLevel Zoom Level.
*/
applyZoomLevel(zoomLevel: CoreZoomLevel): void {
const zoom = CoreConstants.CONFIG.zoomlevels[zoomLevel];
// @todo Since zoom is deprecated and fontSize is not working, we should do some research here.
document.documentElement.style.zoom = zoom + '%';
}
/**
* Get system allowed color schemes.
*
* @return Allowed color schemes.
*/
getAllowedColorSchemes(): CoreColorScheme[] {
if (this.colorSchemes.length > 0) {
return this.colorSchemes;
}
if (!CoreConstants.CONFIG.forceColorScheme) {
this.colorSchemes.push(CoreColorScheme.LIGHT);
this.colorSchemes.push(CoreColorScheme.DARK);
if (this.canIUsePrefersColorScheme()) {
this.colorSchemes.push(CoreColorScheme.SYSTEM);
}
} else {
this.colorSchemes = [CoreConstants.CONFIG.forceColorScheme];
}
return this.colorSchemes;
}
/**
* Set body color scheme.
*
* @param colorScheme Name of the color scheme.
*/
setColorScheme(colorScheme: CoreColorScheme): void {
this.currentColorScheme = colorScheme;
if (colorScheme == CoreColorScheme.SYSTEM && this.prefersDark) {
this.toggleDarkMode(this.prefersDark.matches);
} else {
this.toggleDarkMode(colorScheme == CoreColorScheme.DARK);
}
}
/**
* Check if device can detect color scheme system preference.
* https://caniuse.com/prefers-color-scheme
*
* @returns if the color scheme system preference is available.
*/
canIUsePrefersColorScheme(): boolean {
// The following check will check browser support but system may differ from that.
return window.matchMedia('(prefers-color-scheme)').media !== 'not all';
}
/**
* Listener function to toggle dark mode.
*/
protected toggleDarkModeListener(): void {
this.setColorScheme(this.currentColorScheme);
};
/**
* Toggles dark mode based on enabled boolean.
*
* @param enable True to enable dark mode, false to disable.
*/
protected toggleDarkMode(enable: boolean = false): void {
document.body.classList.toggle('dark', enable);
CoreApp.setStatusBarColor();
}
}
export const CoreSettingsHelper = makeSingleton(CoreSettingsHelperProvider); | the_stack |
import { Project, SourceFile } from "../project";
import { createSessionWithProjectAndOpenDocuments } from "../sessionFactory";
import { RunResult, ServiceError, RunConfiguration } from "../session";
import { isNullOrUndefinedOrWhitespace } from "../stringExtensions";
import { DocumentsToOpen } from "../internals/session";
import { IOutputPanel } from "../outputPanel";
import { XtermTerminal } from "../XtermTerminal";
import {
tryDotNetOutputModes,
TryDotNetSession,
tryDotNetModes,
AutoEnablerConfiguration,
SessionLookup
} from "./types";
import { getTrydotnetSessionId, getTrydotnetEditorId } from "./utilities";
import { getCodeContainer, getCode } from "./codeProcessor";
import { extractIncludes, mergeFiles, getDocumentsToInclude } from "./includesProcessor";
import { Configuration } from "../configuration";
import { PreOutputPanel } from "../preOutputPanel";
function cloneSize(source: HTMLElement, destination: HTMLElement) {
let width = source.getAttribute("width");
if (width) {
destination.setAttribute("width", width);
}
let height = source.getAttribute("height");
if (height) {
destination.setAttribute("height", height);
}
let style = source.getAttribute("style");
if (style) {
destination.setAttribute("style", style);
}
}
function clearRunClasses(element: HTMLElement) {
if (element) {
element.classList.remove("run-execution");
element.classList.remove("run-failure");
element.classList.remove("run-success");
element.classList.remove("busy");
}
}
const defaultRunResultHandler = (
runResult: RunResult,
container: HTMLElement,
_sessionId: string
) => {
if (container) {
clearRunClasses(container);
container.classList.remove("collapsed");
container.classList.add(
runResult.succeeded ? "run-success" : "run-failure"
);
}
};
const defaultServiceErrorHandler = (
error: ServiceError,
container: HTMLElement,
serviceErrorPanel: IOutputPanel,
_sessionId: string
) => {
if (container) {
clearRunClasses(container);
container.classList.add("run-failure");
}
if (serviceErrorPanel) {
serviceErrorPanel.setContent(error.message);
}
};
export function autoEnable(
{ apiBaseAddress, useWasmRunner = true, debug = false, runResultHandler = defaultRunResultHandler, serviceErrorHandler = defaultServiceErrorHandler }: AutoEnablerConfiguration,
documentToScan?: HTMLDocument,
mainWindow?: Window
): Promise<TryDotNetSession[]> {
return internalAutoEnable(
{
apiBaseAddress: apiBaseAddress,
useWasmRunner: useWasmRunner,
debug: debug,
runResultHandler: runResultHandler,
serviceErrorHandler: serviceErrorHandler
},
documentToScan,
mainWindow
);
}
export function tryParseEnum(outputType?: string): tryDotNetOutputModes {
if (isNullOrUndefinedOrWhitespace(outputType)) {
return tryDotNetOutputModes.standard;
}
for (let n in tryDotNetOutputModes) {
const name = tryDotNetOutputModes[n];
console.log(name);
if (name === outputType) {
return <tryDotNetOutputModes>n;
}
}
}
export function createOutputPanel(
outputDiv: HTMLDivElement,
outputType?: string
): IOutputPanel {
let type: tryDotNetOutputModes = tryParseEnum(outputType);
let outputPanel: IOutputPanel;
switch (type) {
case tryDotNetOutputModes.terminal:
outputPanel = new XtermTerminal(outputDiv);
break;
default:
outputPanel = new PreOutputPanel(outputDiv);
break;
}
return outputPanel;
}
export function createRunOutputElements(
outputPanelContainer: HTMLDivElement,
doc: HTMLDocument
): { outputPanel: IOutputPanel } {
if (outputPanelContainer === null || outputPanelContainer === undefined) {
return {
outputPanel: null
};
}
let outputDiv = outputPanelContainer.appendChild(doc.createElement("div"));
outputDiv.classList.add("trydotnet-output");
let outputType = outputPanelContainer.dataset.trydotnetOutputType;
let outputPanel: IOutputPanel = createOutputPanel(outputDiv, outputType);
return {
outputPanel
};
}
function internalAutoEnable(
configuration: AutoEnablerConfiguration,
documentToScan?: HTMLDocument,
mainWindow?: Window
): Promise<TryDotNetSession[]> {
let doc = documentToScan ? documentToScan : document;
let wnd = mainWindow ? mainWindow : window;
let apiBaseAddress = configuration.apiBaseAddress;
let sessions: SessionLookup = {};
let codeSources = doc.querySelectorAll(
`pre>code[data-trydotnet-mode=${tryDotNetModes[tryDotNetModes.editor]}]`
);
let runButtons = doc.querySelectorAll(
`button[data-trydotnet-mode=${tryDotNetModes[tryDotNetModes.run]}]`
);
let outputDivs = doc.querySelectorAll(
`div[data-trydotnet-mode=${tryDotNetModes[tryDotNetModes.runResult]}]`
);
let errorDivs = doc.querySelectorAll(
`div[data-trydotnet-mode=${tryDotNetModes[tryDotNetModes.errorReport]}]`
);
codeSources.forEach(async (codeSource: HTMLElement) => {
let sessionId = getTrydotnetSessionId(codeSource);
if (!sessions[sessionId]) {
sessions[sessionId] = { codeSources: [] };
}
sessions[sessionId].codeSources.push(codeSource);
});
runButtons.forEach(async (run: HTMLButtonElement) => {
let sessionId = getTrydotnetSessionId(run);
if (sessions[sessionId]) {
sessions[sessionId].runButton = run;
}
});
outputDivs.forEach(async (output: HTMLDivElement) => {
let sessionId = getTrydotnetSessionId(output);
if (sessions[sessionId]) {
sessions[sessionId].outputPanel = output;
}
});
errorDivs.forEach(async (error: HTMLDivElement) => {
let sessionId = getTrydotnetSessionId(error);
if (sessions[sessionId]) {
sessions[sessionId].errorPanel = error;
}
});
let editorIds = new Set();
let filedNameSeed = 0;
let awaitableSessions: Promise<TryDotNetSession>[] = [];
let includes = extractIncludes(doc);
for (let sessionId in sessions) {
let session = sessions[sessionId];
let iframes: HTMLIFrameElement[] = [];
let files: SourceFile[] = [];
let packageName: string = null;
let packageVersion: string = null;
let language: string = "csharp";
let documentsToOpen: DocumentsToOpen = {};
let editorCount = -1;
for (let codeSource of session.codeSources) {
editorCount++;
let codeContainer = getCodeContainer(codeSource);
let code = getCode(codeSource);
let pacakgeAttribute = codeSource.dataset.trydotnetPackage;
if (!isNullOrUndefinedOrWhitespace(pacakgeAttribute)) {
packageName = pacakgeAttribute;
}
let packageVersionAttribute = codeSource.dataset.dataTrydotnetPackageVersion;
if (!isNullOrUndefinedOrWhitespace(packageVersionAttribute)) {
packageVersion = packageVersionAttribute;
}
let languageAttribute = codeSource.dataset.trydotnetLanguage;
if (!isNullOrUndefinedOrWhitespace(languageAttribute)) {
language = languageAttribute;
}
let editorId = getTrydotnetEditorId(codeSource);
if (!packageName) {
throw new Error("must provide package");
}
let filename = codeSource.dataset.trydotnetFileName;
if (!filename) {
filename = `code_file_${filedNameSeed}.cs`;
filedNameSeed++;
}
let iframe: HTMLIFrameElement = doc.createElement("iframe");
if (isNullOrUndefinedOrWhitespace(editorId)) {
editorId = editorCount.toString();
}
editorId = `${sessionId}::${editorId}`;
if (editorIds.has(editorId)) {
throw new Error(`editor id ${editorId} already defined`);
}
editorIds.add(editorId);
// progapate attributes to iframe
iframe.dataset.trydotnetEditorId = editorId;
iframe.dataset.trydotnetSessionId = sessionId;
let region = codeSource.dataset.trydotnetRegion;
if (!isNullOrUndefinedOrWhitespace(region)) {
documentsToOpen[editorId] = {
fileName: filename,
region: region,
content: code
};
} else {
files.push({ name: filename, content: code });
documentsToOpen[editorId] = filename;
}
cloneSize(codeContainer, iframe);
codeContainer.parentNode.replaceChild(iframe, codeContainer);
iframes.push(iframe);
}
let prj: Project = {
package: packageName,
files: mergeFiles(files, includes, sessionId)
};
if (!isNullOrUndefinedOrWhitespace(packageVersion)) {
prj.packageVersion = packageVersion;
}
if (!isNullOrUndefinedOrWhitespace(language)) {
prj.language = language;
}
let documentsToInclude = getDocumentsToInclude(includes, sessionId);
let config: Configuration = {
debug: configuration.debug,
useWasmRunner: configuration.useWasmRunner,
hostOrigin: doc.location.origin,
trydotnetOrigin: apiBaseAddress ? apiBaseAddress.href : null,
editorConfiguration: {
options: {
minimap: {
enabled: false
}
}
}
};
let awaitable = createSessionWithProjectAndOpenDocuments(
config,
iframes,
wnd,
prj,
documentsToOpen,
documentsToInclude
).then(tdnSession => {
let outputPanelContainer = session.outputPanel;
let errorPanelContainer = session.errorPanel;
let errorPanel: IOutputPanel;
let { runResultHandler, serviceErrorHandler } = configuration;
let { outputPanel } = createRunOutputElements(
outputPanelContainer,
doc
);
if (
errorPanelContainer === null ||
errorPanelContainer === undefined
) {
// fall back on output modules
errorPanelContainer = outputPanelContainer;
errorPanel = outputPanel;
} else {
// todo: impelement createErrorReportElements
throw new Error("Not implemented");
}
let createdSession: TryDotNetSession = {
sessionId: sessionId,
session: tdnSession,
editorIframes: iframes
};
if (outputPanel) {
outputPanel.initialise();
createdSession.outputPanels = [outputPanel];
tdnSession.subscribeToOutputEvents(event => {
if (event.stdout) {
outputPanel.append(event.stdout);
}
if (event.exception) {
outputPanel.append(
`Unhandled Exception: ${event.exception}`
);
}
});
tdnSession.subscribeToServiceErrorEvents(error => {
errorPanel.append(error.message);
});
}
let runButton = session.runButton;
if (runButton) {
tdnSession.onCanRunChanged(
canRun => {
runButton.disabled = !canRun;
}
)
createdSession.runButtons = [runButton];
runButton.onclick = () => {
clearRunClasses(runButton);
runButton.classList.add("busy");
if (outputPanelContainer) {
clearRunClasses(outputPanelContainer);
outputPanelContainer.classList.add("run-execution");
}
if (outputPanel) {
outputPanel.clear();
}
let runOptions: RunConfiguration = {};
let args = runButton.dataset.trydotnetRunArgs;
if (!isNullOrUndefinedOrWhitespace(args)) {
runOptions.runArgs = args;
}
return tdnSession
.run(runOptions)
.then(runResult => {
clearRunClasses(runButton);
if (runResultHandler) {
runResultHandler(
runResult,
outputPanelContainer,
sessionId
);
}
})
.catch(error => {
runButton.disabled = false;
clearRunClasses(runButton);
if (serviceErrorHandler) {
serviceErrorHandler(
error,
errorPanelContainer,
errorPanel,
sessionId
);
}
});
};
}
return createdSession;
});
awaitableSessions.push(awaitable);
}
return Promise.all(awaitableSessions);
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.