text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import chalk from 'chalk'
import { EventData, PastEventOptions } from 'web3-eth-contract'
import { EventEmitter } from 'events'
import { PrefixedHexString } from 'ethereumjs-util'
import { toBN, toHex } from 'web3-utils'
import { Address } from '@opengsn/common/dist/types/Aliases'
import { AmountRequired } from '@opengsn/common/dist/AmountRequired'
import {
address2topic,
getLatestEventData,
isSameAddress,
isSecondEventLater,
boolString
} from '@opengsn/common/dist/Utils'
import { defaultEnvironment } from '@opengsn/common/dist/Environments'
import { SendTransactionDetails, TransactionManager } from './TransactionManager'
import { ServerConfigParams } from './ServerConfigParams'
import { TxStoreManager } from './TxStoreManager'
import { ServerAction } from './StoredTransaction'
import { LoggerInterface } from '@opengsn/common/dist/LoggerInterface'
import {
HubAuthorized,
HubUnauthorized,
OwnerSet,
RelayServerRegistered,
RelayWorkersAdded,
StakeAdded,
StakeUnlocked,
StakeWithdrawn
} from '@opengsn/common/dist/types/GSNContractsDataTypes'
import { ContractInteractor } from '@opengsn/common/dist/ContractInteractor'
import { isRegistrationValid } from './Utils'
import { constants } from '@opengsn/common/dist/Constants'
import { toNumber } from '@opengsn/common'
const mintxgascost = defaultEnvironment.mintxgascost
interface CachedEventData {
eventData: EventData
blockTimestamp: number
}
export class RegistrationManager {
balanceRequired?: AmountRequired
stakeRequired?: AmountRequired
_isSetOwnerCalled = false
_isOwnerSetOnStakeManager = false
_isHubAuthorized = false
_isStakeLocked = false
isInitialized = false
hubAddress: Address
managerAddress: Address
workerAddress: Address
eventEmitter: EventEmitter
contractInteractor: ContractInteractor
ownerAddress?: Address
transactionManager: TransactionManager
config: ServerConfigParams
txStoreManager: TxStoreManager
logger: LoggerInterface
lastMinedRegisterTransaction?: CachedEventData
lastWorkerAddedTransaction?: CachedEventData
private delayedEvents: Array<{ time: number, eventData: EventData }> = []
get isHubAuthorized (): boolean {
return this._isHubAuthorized
}
set isHubAuthorized (newValue: boolean) {
const oldValue = this._isHubAuthorized
this._isHubAuthorized = newValue
if (newValue !== oldValue) {
this.logger.info(`Current RelayHub is ${newValue ? 'now' : 'no longer'} authorized`)
this.printNotRegisteredMessage()
}
}
get isStakeLocked (): boolean {
return this._isStakeLocked
}
set isStakeLocked (newValue: boolean) {
const oldValue = this._isStakeLocked
this._isStakeLocked = newValue
if (newValue !== oldValue) {
this.logger.info(`Manager stake is ${newValue ? 'now' : 'no longer'} locked`)
this.printNotRegisteredMessage()
}
}
constructor (
contractInteractor: ContractInteractor,
transactionManager: TransactionManager,
txStoreManager: TxStoreManager,
eventEmitter: EventEmitter,
logger: LoggerInterface,
config: ServerConfigParams,
// exposed from key manager?
managerAddress: Address,
workerAddress: Address
) {
this.logger = logger
this.contractInteractor = contractInteractor
this.hubAddress = config.relayHubAddress
this.managerAddress = managerAddress
this.workerAddress = workerAddress
this.eventEmitter = eventEmitter
this.transactionManager = transactionManager
this.txStoreManager = txStoreManager
this.config = config
}
async init (): Promise<void> {
if (this.lastWorkerAddedTransaction == null) {
this.lastWorkerAddedTransaction = await this._queryLatestWorkerAddedEvent()
}
if (this.lastMinedRegisterTransaction == null) {
this.lastMinedRegisterTransaction = await this._queryLatestRegistrationEvent()
}
const tokenMetadata = await this.contractInteractor.getErc20TokenMetadata()
const listener = (): void => {
this.printNotRegisteredMessage()
}
this.balanceRequired = new AmountRequired('Balance', toBN(this.config.managerMinBalance), this.logger, listener)
this.stakeRequired = new AmountRequired('Stake', toBN(this.config.managerMinStake), this.logger, listener, tokenMetadata)
await this.refreshBalance()
await this.refreshStake()
this.isInitialized = true
}
async updateLatestRegistrationTxs (hubEventsSinceLastScan: EventData[]): Promise<void> {
for (const eventData of hubEventsSinceLastScan) {
switch (eventData.event) {
case RelayServerRegistered:
if (this.lastMinedRegisterTransaction == null || isSecondEventLater(this.lastMinedRegisterTransaction.eventData, eventData)) {
this.logger.debug('New lastMinedRegisterTransaction: ' + JSON.stringify(eventData))
const block = await this.contractInteractor.getBlock(eventData.blockNumber)
const blockTimestamp = toNumber(block.timestamp)
this.lastMinedRegisterTransaction = { eventData, blockTimestamp }
}
break
case RelayWorkersAdded:
if (this.lastWorkerAddedTransaction == null || isSecondEventLater(this.lastWorkerAddedTransaction.eventData, eventData)) {
this.logger.debug('New lastWorkerAddedTransaction: ' + JSON.stringify(eventData))
const block = await this.contractInteractor.getBlock(eventData.blockNumber)
const blockTimestamp = toNumber(block.timestamp)
this.lastWorkerAddedTransaction = { eventData, blockTimestamp }
}
break
}
}
}
async handlePastEvents (
hubEventsSinceLastScan: EventData[],
lastScannedBlock: number,
currentBlockNumber: number,
currentBlockTimestamp: number,
forceRegistration: boolean): Promise<PrefixedHexString[]> {
if (!this.isInitialized || this.balanceRequired == null) {
throw new Error('RegistrationManager not initialized')
}
const topics = [address2topic(this.managerAddress)]
const options: PastEventOptions = {
fromBlock: lastScannedBlock + 1,
toBlock: 'latest'
}
const eventNames = [HubAuthorized, StakeAdded, HubUnauthorized, StakeUnlocked, StakeWithdrawn, OwnerSet]
const decodedEvents = await this.contractInteractor.getPastEventsForStakeManager(eventNames, topics, options)
this.printEvents(decodedEvents, options)
let transactionHashes: PrefixedHexString[] = []
if (!this._isOwnerSetOnStakeManager) {
if (this.balanceRequired.isSatisfied) {
// TODO: _isSetOwnerCalled is different from 'isActionPending' only cause we handle owner outside the event loop
if (!this._isSetOwnerCalled) {
this._isSetOwnerCalled = true
transactionHashes = transactionHashes.concat(await this.setOwnerInStakeManager(currentBlockNumber, currentBlockTimestamp))
}
} else {
this.logger.debug('owner is not set and balance requirement is not satisfied')
// TODO: relay should stop handling events at this point as action by owner is required;
// current architecture does not allow to skip handling events; assume
}
}
// TODO: what about 'penalize' events? should send balance to owner, I assume
// TODO TODO TODO 'StakeAdded' is not the event you want to cat upon if there was no 'HubAuthorized' event
for (const eventData of decodedEvents) {
switch (eventData.event) {
case HubAuthorized:
this.logger.warn(`Handling HubAuthorized event: ${JSON.stringify(eventData)} in block ${currentBlockNumber}`)
await this._handleHubAuthorizedEvent(eventData)
break
case OwnerSet:
await this.refreshStake()
this.logger.warn(`Handling OwnerSet event: ${JSON.stringify(eventData)} in block ${currentBlockNumber}`)
break
case StakeAdded:
await this.refreshStake()
this.logger.warn(`Handling StakeAdded event: ${JSON.stringify(eventData)} in block ${currentBlockNumber}`)
break
case HubUnauthorized:
this.logger.warn(`Handling HubUnauthorized event: ${JSON.stringify(eventData)} in block ${currentBlockNumber}`)
if (isSameAddress(eventData.returnValues.relayHub, this.hubAddress)) {
this.isHubAuthorized = false
this.delayedEvents.push({ time: eventData.returnValues.removalTime.toString(), eventData })
}
break
case StakeUnlocked:
this.logger.warn(`Handling StakeUnlocked event: ${JSON.stringify(eventData)} in block ${currentBlockNumber}`)
await this.refreshStake()
break
case StakeWithdrawn:
this.logger.warn(`Handling StakeWithdrawn event: ${JSON.stringify(eventData)} in block ${currentBlockNumber}`)
await this.refreshStake()
transactionHashes = transactionHashes.concat(await this._handleStakeWithdrawnEvent(eventData, currentBlockNumber, currentBlockTimestamp))
break
}
}
await this.updateLatestRegistrationTxs(hubEventsSinceLastScan)
// handle HubUnauthorized only after the due time
// TODO: avoid querying time from RPC; reorganize code
const currentBlockObject = await this.contractInteractor.getBlock(currentBlockNumber)
// In case 'currentBlock' is not found on the node, nothing is due
const currentBlockTime = currentBlockObject?.timestamp ?? 0
for (const eventData of this._extractDuePendingEvents(currentBlockTime)) {
switch (eventData.event) {
case HubUnauthorized:
transactionHashes = transactionHashes.concat(await this._handleHubUnauthorizedEvent(eventData, currentBlockNumber, currentBlockTimestamp))
break
}
}
const isRegistrationCorrect = this._isRegistrationCorrect()
const isRegistrationPending = await this.txStoreManager.isActionPendingOrRecentlyMined(ServerAction.REGISTER_SERVER, currentBlockNumber, this.config.recentActionAvoidRepeatDistanceBlocks)
if (!(isRegistrationPending || isRegistrationCorrect) || forceRegistration) {
this.logger.debug(`will attempt registration: isRegistrationPending=${isRegistrationPending} isRegistrationCorrect=${isRegistrationCorrect} forceRegistration=${forceRegistration}`)
transactionHashes = transactionHashes.concat(await this.attemptRegistration(currentBlockNumber, currentBlockTimestamp))
}
return transactionHashes
}
_extractDuePendingEvents (currentBlockTime: number | string): EventData[] {
const currentBlockTimeNumber = toNumber(currentBlockTime)
const ret = this.delayedEvents.filter(event => event.time <= currentBlockTimeNumber).map(e => e.eventData)
this.delayedEvents = [...this.delayedEvents.filter(event => event.time > currentBlockTimeNumber)]
return ret
}
_isRegistrationCorrect (): boolean {
return isRegistrationValid(this.lastMinedRegisterTransaction?.eventData, this.config, this.managerAddress)
}
async _queryLatestRegistrationEvent (): Promise<CachedEventData | undefined> {
const topics = address2topic(this.managerAddress)
const registerEvents = await this.contractInteractor.getPastEventsForRegistrar([topics],
{
fromBlock: this.config.coldRestartLogsFromBlock
},
[RelayServerRegistered])
const eventData = getLatestEventData(registerEvents)
if (eventData == null) {
return undefined
}
const block = await this.contractInteractor.getBlock(eventData.blockNumber)
const blockTimestamp = toNumber(block.timestamp)
return { eventData, blockTimestamp }
}
_parseEvent (event: { events: any[], name: string, address: string } | null): any {
if (event?.events === undefined) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
return `not event: ${event?.toString()}`
}
const args: Record<string, any> = {}
// event arguments is for some weird reason give as ".events"
for (const eventArgument of event.events) {
args[eventArgument.name] = eventArgument.value
}
return {
name: event.name,
address: event.address,
args: args
}
}
async _handleHubAuthorizedEvent (dlog: EventData): Promise<void> {
if (dlog.returnValues.relayHub.toLowerCase() === this.hubAddress.toLowerCase()) {
this.isHubAuthorized = true
}
}
async _handleHubUnauthorizedEvent (dlog: EventData, currentBlockNumber: number, currentBlockTimestamp: number): Promise<PrefixedHexString[]> {
return await this.withdrawAllFunds(false, currentBlockNumber, currentBlockTimestamp)
}
async _handleStakeWithdrawnEvent (dlog: EventData, currentBlockNumber: number, currentBlockTimestamp: number): Promise<PrefixedHexString[]> {
this.logger.warn(`Handling StakeWithdrawn event: ${JSON.stringify(dlog)}`)
return await this.withdrawAllFunds(true, currentBlockNumber, currentBlockTimestamp)
}
/**
* @param withdrawManager - whether to send the relay manager's balance to the owner.
* Note that more than one relay process could be using the same manager account.
* @param currentBlock
*/
async withdrawAllFunds (withdrawManager: boolean, currentBlockNumber: number, currentBlockTimestamp: number): Promise<PrefixedHexString[]> {
let transactionHashes: PrefixedHexString[] = []
transactionHashes = transactionHashes.concat(await this._sendManagerHubBalanceToOwner(currentBlockNumber, currentBlockTimestamp))
transactionHashes = transactionHashes.concat(await this._sendWorkersEthBalancesToOwner(currentBlockNumber, currentBlockTimestamp))
if (withdrawManager) {
transactionHashes = transactionHashes.concat(await this._sendManagerEthBalanceToOwner(currentBlockNumber, currentBlockTimestamp))
}
this.eventEmitter.emit('unstaked')
return transactionHashes
}
async refreshBalance (): Promise<void> {
if (this.balanceRequired == null) {
throw new Error('not initialized')
}
const currentBalance = await this.contractInteractor.getBalance(this.managerAddress)
this.balanceRequired.currentValue = toBN(currentBalance)
}
async refreshStake (): Promise<void> {
if (this.stakeRequired == null) {
throw new Error('not initialized')
}
const stakeInfo = await this.contractInteractor.getStakeInfo(this.managerAddress)
const stakedOnHubStatus = await this.contractInteractor.isRelayManagerStakedOnHub(this.managerAddress)
if (stakedOnHubStatus.isStaked) {
this.isHubAuthorized = true
}
const stake = stakeInfo.stake
this._isOwnerSetOnStakeManager = stakeInfo.owner !== constants.ZERO_ADDRESS
if (this._isOwnerSetOnStakeManager && !isSameAddress(stakeInfo.owner, this.config.ownerAddress)) {
throw new Error(`This Relay Manager has set owner to already! On-chain: ${stakeInfo.owner}, in config: ${this.config.ownerAddress}`)
}
if (stake.eq(toBN(0))) {
return
}
// a locked stake does not have the 'withdrawTime' field set
this.isStakeLocked = stakeInfo.withdrawTime.toString() === '0'
this.stakeRequired.currentValue = stake
// first time getting stake, setting owner
if (this.ownerAddress == null) {
this.ownerAddress = stakeInfo.owner
this.logger.info('Got staked for the first time')
this.printNotRegisteredMessage()
}
}
async addRelayWorker (currentBlockNumber: number, currentBlockTimestamp: number): Promise<PrefixedHexString> {
// register on chain
const addRelayWorkerMethod = await this.contractInteractor.getAddRelayWorkersMethod([this.workerAddress])
const details: SendTransactionDetails = {
signer: this.managerAddress,
serverAction: ServerAction.ADD_WORKER,
method: addRelayWorkerMethod,
destination: this.hubAddress,
creationBlockNumber: currentBlockNumber,
creationBlockTimestamp: currentBlockTimestamp
}
this.logger.info(`adding relay worker ${this.workerAddress}`)
const { transactionHash } = await this.transactionManager.sendTransaction(details)
return transactionHash
}
// TODO: extract worker registration sub-flow
async attemptRegistration (
currentBlockNumber: number,
currentBlockTimestamp: number
): Promise<PrefixedHexString[]> {
if (this.balanceRequired == null || this.stakeRequired == null) {
throw new Error('not initialized')
}
const stakeOnHubStatus = await this.contractInteractor.isRelayManagerStakedOnHub(this.managerAddress)
if (!stakeOnHubStatus.isStaked && this.ownerAddress != null) {
this.logger.error('Relay manager is staked on StakeManager but not on RelayHub.')
this.logger.error('Minimum stake/minimum unstake delay/stake token misconfigured?')
}
const allPrerequisitesOk =
this.isHubAuthorized &&
this.isStakeLocked &&
this.stakeRequired.isSatisfied &&
this.balanceRequired.isSatisfied &&
stakeOnHubStatus.isStaked
if (!allPrerequisitesOk) {
this.logger.debug('will not actually attempt registration - prerequisites not satisfied')
return []
}
let transactions: PrefixedHexString[] = []
// add worker only if not already added
const workersAdded = await this._isWorkerValid()
const addWorkersPending = await this.txStoreManager.isActionPendingOrRecentlyMined(ServerAction.ADD_WORKER, currentBlockNumber, this.config.recentActionAvoidRepeatDistanceBlocks)
let skipGasEstimationForRegisterRelay = false
if (!(workersAdded || addWorkersPending)) {
const txHash = await this.addRelayWorker(currentBlockNumber, currentBlockTimestamp)
transactions = transactions.concat(txHash)
skipGasEstimationForRegisterRelay = true
}
const registerMethod = await this.contractInteractor.getRegisterRelayMethod(this.hubAddress, this.config.baseRelayFee, this.config.pctRelayFee, this.config.url)
let gasLimit: number | undefined
if (skipGasEstimationForRegisterRelay) {
gasLimit = this.config.defaultGasLimit
}
const details: SendTransactionDetails = {
serverAction: ServerAction.REGISTER_SERVER,
gasLimit,
signer: this.managerAddress,
method: registerMethod,
destination: this.contractInteractor.relayRegistrar.address,
creationBlockNumber: currentBlockNumber,
creationBlockTimestamp: currentBlockTimestamp
}
const { transactionHash } = await this.transactionManager.sendTransaction(details)
transactions = transactions.concat(transactionHash)
this.logger.debug(`Relay ${this.managerAddress} registered on hub ${this.hubAddress}. `)
return transactions
}
async _sendManagerEthBalanceToOwner (currentBlockNumber: number, currentBlockTimestamp: number): Promise<PrefixedHexString[]> {
// todo add better maxFeePerGas, maxPriorityFeePerGas
const gasPrice = await this.contractInteractor.getGasPrice()
const transactionHashes: PrefixedHexString[] = []
const gasLimit = mintxgascost
const txCost = toBN(gasLimit).mul(toBN(gasPrice))
const managerBalance = toBN(await this.contractInteractor.getBalance(this.managerAddress))
// sending manager eth balance to owner
if (managerBalance.gte(txCost)) {
this.logger.info(`Sending manager eth balance ${managerBalance.toString()} to owner`)
const details: SendTransactionDetails = {
signer: this.managerAddress,
serverAction: ServerAction.VALUE_TRANSFER,
destination: this.ownerAddress as string,
gasLimit,
maxFeePerGas: gasPrice,
maxPriorityFeePerGas: gasPrice,
value: toHex(managerBalance.sub(txCost)),
creationBlockNumber: currentBlockNumber,
creationBlockTimestamp: currentBlockTimestamp
}
const { transactionHash } = await this.transactionManager.sendTransaction(details)
transactionHashes.push(transactionHash)
} else {
this.logger.error(`manager balance too low: ${managerBalance.toString()}, tx cost: ${gasLimit * parseInt(gasPrice)}`)
}
return transactionHashes
}
async _sendWorkersEthBalancesToOwner (currentBlockNumber: number, currentBlockTimestamp: number): Promise<PrefixedHexString[]> {
// sending workers' balance to owner (currently one worker, todo: extend to multiple)
const transactionHashes: PrefixedHexString[] = []
// todo add better maxFeePerGas, maxPriorityFeePerGas
const gasPrice = await this.contractInteractor.getGasPrice()
const gasLimit = mintxgascost
const txCost = toBN(gasLimit * parseInt(gasPrice))
const workerBalance = toBN(await this.contractInteractor.getBalance(this.workerAddress))
if (workerBalance.gte(txCost)) {
this.logger.info(`Sending workers' eth balance ${workerBalance.toString()} to owner`)
const details: SendTransactionDetails = {
signer: this.workerAddress,
serverAction: ServerAction.VALUE_TRANSFER,
destination: this.ownerAddress as string,
gasLimit,
maxFeePerGas: gasPrice,
maxPriorityFeePerGas: gasPrice,
value: toHex(workerBalance.sub(txCost)),
creationBlockNumber: currentBlockNumber,
creationBlockTimestamp: currentBlockTimestamp
}
const { transactionHash } = await this.transactionManager.sendTransaction(details)
transactionHashes.push(transactionHash)
} else {
this.logger.info(`balance too low: ${workerBalance.toString()}, tx cost: ${gasLimit * parseInt(gasPrice)}`)
}
return transactionHashes
}
async _sendManagerHubBalanceToOwner (
currentBlockNumber: number,
currentBlockTimestamp: number,
amount?: BN): Promise<PrefixedHexString[]> {
if (this.ownerAddress == null) {
throw new Error('Owner address not initialized')
}
const transactionHashes: PrefixedHexString[] = []
const gasPrice = await this.contractInteractor.getGasPrice()
const managerHubBalance = await this.contractInteractor.hubBalanceOf(this.managerAddress)
if (amount == null) {
amount = managerHubBalance
} else if (amount.gt(managerHubBalance)) {
throw new Error(`Withdrawal amount ${amount.toString()} larger than manager hub balance ${managerHubBalance.toString()}`)
}
const {
gasLimit,
gasCost,
method
} = await this.contractInteractor.withdrawHubBalanceEstimateGas(amount, this.ownerAddress, this.managerAddress, gasPrice)
if (amount.gte(gasCost)) {
this.logger.info(`Sending manager hub balance ${amount.toString()} to owner`)
const details: SendTransactionDetails = {
gasLimit,
signer: this.managerAddress,
serverAction: ServerAction.DEPOSIT_WITHDRAWAL,
destination: this.hubAddress,
creationBlockNumber: currentBlockNumber,
creationBlockTimestamp: currentBlockTimestamp,
method
}
const { transactionHash } = await this.transactionManager.sendTransaction(details)
transactionHashes.push(transactionHash)
} else {
this.logger.error(`manager hub balance too low: ${managerHubBalance.toString()}, tx cost: ${gasCost.toString()}`)
}
return transactionHashes
}
async _queryLatestWorkerAddedEvent (): Promise<CachedEventData | undefined> {
const workersAddedEvents = await this.contractInteractor.getPastEventsForHub([address2topic(this.managerAddress)],
{
fromBlock: this.config.coldRestartLogsFromBlock
},
[RelayWorkersAdded])
const eventData = getLatestEventData(workersAddedEvents)
if (eventData == null) {
return undefined
}
const block = await this.contractInteractor.getBlock(eventData.blockNumber)
const blockTimestamp = toNumber(block.timestamp)
return { eventData, blockTimestamp }
}
async _isWorkerValid (): Promise<boolean> {
const managerFromHub = await this.contractInteractor.workerToManager(this.workerAddress)
if (managerFromHub.toLowerCase() === this.managerAddress.toLowerCase()) {
return true
}
// eslint-disable-next-line @typescript-eslint/prefer-optional-chain
return this.lastWorkerAddedTransaction != null && this.lastWorkerAddedTransaction.eventData.returnValues.newRelayWorkers
.map((a: string) => a.toLowerCase()).includes(this.workerAddress.toLowerCase())
}
async isRegistered (): Promise<boolean> {
if (this.stakeRequired == null) {
throw new Error('not initialized')
}
const isRegistrationCorrect = await this._isRegistrationCorrect()
return this.stakeRequired.isSatisfied &&
this.isStakeLocked &&
this.isHubAuthorized &&
isRegistrationCorrect
}
printNotRegisteredMessage (): void {
if (this.balanceRequired == null || this.stakeRequired == null) {
throw new Error('not initialized')
}
if (this._isRegistrationCorrect()) {
return
}
const message = `\nNot registered yet. Prerequisites:
${this.balanceRequired.description}
${this.stakeRequired.description}
Hub authorized | ${boolString(this.isHubAuthorized)}
Stake locked | ${boolString(this.isStakeLocked)}
Manager | ${this.managerAddress}
Worker | ${this.workerAddress}
Owner | ${this.ownerAddress ?? chalk.red('unknown')}
`
this.logger.info(message)
}
printEvents (decodedEvents: EventData[], options: PastEventOptions): void {
if (decodedEvents.length === 0) {
return
}
this.logger.info(`Handling ${decodedEvents.length} events emitted since block: ${options.fromBlock?.toString()}`)
for (const decodedEvent of decodedEvents) {
this.logger.info(`
Name | ${decodedEvent.event.padEnd(25)}
Block | ${decodedEvent.blockNumber}
TxHash | ${decodedEvent.transactionHash}
`)
}
}
// TODO: duplicated code; another leaked web3 'method' abstraction
async setOwnerInStakeManager (currentBlockNumber: number, currentBlockTimestamp: number): Promise<PrefixedHexString> {
const setRelayManagerMethod = await this.contractInteractor.getSetRelayManagerMethod(this.config.ownerAddress)
const stakeManagerAddress = this.contractInteractor.stakeManagerAddress()
const details: SendTransactionDetails = {
signer: this.managerAddress,
serverAction: ServerAction.SET_OWNER,
method: setRelayManagerMethod,
destination: stakeManagerAddress,
creationBlockNumber: currentBlockNumber,
creationBlockTimestamp: currentBlockTimestamp
}
this.logger.info(`setting relay owner ${this.config.ownerAddress} at StakeManager ${stakeManagerAddress}`)
const { transactionHash } = await this.transactionManager.sendTransaction(details)
return transactionHash
}
} | the_stack |
import 'core-js/features/array/find';
import 'core-js/features/array/from';
import 'core-js/features/object/assign';
import 'core-js/features/object/keys';
import 'core-js/features/promise';
import 'custom-event-polyfill';
import Controls from './controls';
import Fullscreen from './controls/fullscreen';
import Track from './interfaces/captions/track';
import ControlItem from './interfaces/control-item';
import CustomMedia from './interfaces/custom-media';
import EventsList from './interfaces/events-list';
import PlayerInstanceList from './interfaces/instance';
import PlayerOptions from './interfaces/player-options';
import Source from './interfaces/source';
import Media from './media';
import Ads from './media/ads';
import './utils/closest';
import {
EVENT_OPTIONS, IS_ANDROID, IS_IOS, IS_IPHONE
} from './utils/constants';
import { addEvent } from './utils/events';
import { isAudio, isVideo, removeElement } from './utils/general';
import { isAutoplaySupported, predictType } from './utils/media';
/**
* OpenPlayerJS.
*
* @description This class generates controls to play native media (such as MP4, MP3, HLS, M(PEG-DASH),
* and have a unified look-and-feel on all modern browsers (including IE11)
* @class Player
*/
class Player {
/**
* Collection of OpenPlayer instances.
*
* @type PlayerInstanceList
* @memberof Player
*/
public static instances: PlayerInstanceList = {};
/**
* Collection of additional (non-native) media
*
* @type CustomMedia
* @memberof Player
*/
public static customMedia: CustomMedia = {
media: {},
optionsKey: {},
rules: [],
};
/**
* Convert all the video/audio tags with `op-player` class in a OpenMedia player instance.
*
* @memberof Player
*/
public static init(): void {
Player.instances = {};
const targets = document.querySelectorAll('video.op-player, audio.op-player');
for (let i = 0, total = targets.length; i < total; i++) {
const target = targets[i] as HTMLMediaElement;
const settings = target.getAttribute('data-op-settings');
const options = settings ? JSON.parse(settings) : {};
const player = new Player(target, options);
player.init();
}
}
/**
* Add new media types, such as iframe API players (YouTube, Vimeo, Dailymotion, etc.)
*
* @param {string} name The name of the media, which will be used to determine options when configuring player
* @param {string} mimeType The pseudo MIME type associated with media (generally, will be `video/x-[name]`)
* @param {(url: string) => string} valid A callback to determine if a match was found between the MIME type and media source
* @param {object} media The object that will contain all the native methods/setters/getters to play media
* @memberof Player
*/
public static addMedia(name: string, mimeType: string, valid: (url: string) => string, media: any) {
Player.customMedia.media[mimeType] = media;
Player.customMedia.optionsKey[mimeType] = name;
Player.customMedia.rules.push(valid);
}
/**
* Instance of Controls object.
*
* @type Controls
* @memberof Player
*/
#controls: Controls;
/**
* Instance of Ads object.
*
* @type Ads
* @memberof Player
*/
#adsInstance: Ads;
/**
* Button to play media.
*
* @type HTMLButtonElement
* @memberof Player
*/
public playBtn: HTMLButtonElement;
/**
* Element to indicate that media is being loaded.
*
* Only applies for `Media` object, since `Ads` does not need it.
* @type HTMLSpanElement
* @memberof Player
*/
public loader: HTMLSpanElement;
/**
* Adapter to toggle between different players.
* Useful for Chromecast integration.
*
* @type unknown
* @memberof Player
*/
public proxy: any = null;
/**
* Unique identified for the current player instance.
*
* @type string
* @memberof Player
*/
#uid = '';
/**
* Native video/audio tag to create player instance.
*
* @type HTMLMediaElement
* @memberof Player
*/
#element: HTMLMediaElement;
/**
* URL that defines a valid Ad XML file to be read by Google IMA SDK
*
* @see https://developers.google.com/interactive-media-ads/docs/sdks/html5/tags
* @type string|string[]
* @memberof Player
*/
#ads?: string | string[];
/**
* Instance of Media object.
*
* @type Media
* @memberof Player
*/
#media: Media;
/**
* Events that will be triggered in Player to show/hide Play button and loader element,
* and to interact with the player using a keyboard for accessibility purposes.
*
* @type EventsList
* @memberof Player
*/
#events: EventsList = {};
/**
* Flag to determine if player can autoplay media.
*
* @see [[Player._autoplay]]
* @type boolean
* @memberof Player
*/
#autoplay = false;
/**
* Storage for original volume level value, when testing browser's autoplay capabilities
* to restore it back.
*
* @see [[Player._autoplay]]
* @type number
* @memberof Player
*/
#volume: number;
/**
* Flag that indicates if browser supports autoplay.
*
* @see [[Player._autoplay]]
* @type boolean
* @memberof Player
*/
#canAutoplay = false;
/**
* Flag that indicates if browser supports autoplay in mute mode.
*
* This is the case with iOS.
* @see [[Player._autoplay]]
* @type boolean
* @memberof Player
*/
#canAutoplayMuted = false;
/**
* Flag that indicates if autoplay algorithm has been applied.
*
* @see [[Player._autoplay]]
* @type boolean
* @memberof Player
*/
#processedAutoplay = false;
/**
* Container for other player options.
*
* @private
* @type PlayerOptions
* @memberof Player
*/
#options: PlayerOptions = {};
/**
* List of custom controls.
*
* @private
* @type ControlItem[]
* @memberof Player
*/
#customControlItems: ControlItem[] = [];
#fullscreen: Fullscreen;
/**
* Default configuration for player.
*
* @private
* @type PlayerOptions
* @memberof Player
*/
#defaultOptions: PlayerOptions = {
controls: {
alwaysVisible: false,
layers: {
left: ['play', 'time', 'volume'],
middle: ['progress'],
right: ['captions', 'settings', 'fullscreen'],
},
},
defaultLevel: null,
detachMenus: false,
forceNative: true,
height: 0,
hidePlayBtnTimer: 350,
labels: {
auto: 'Auto',
captions: 'CC/Subtitles',
click: 'Click to unmute',
fullscreen: 'Fullscreen',
lang: {
en: 'English',
},
levels: 'Quality Levels',
live: 'Live Broadcast',
mediaLevels: 'Change Quality',
mute: 'Mute',
off: 'Off',
pause: 'Pause',
play: 'Play',
progressRail: 'Time Rail',
progressSlider: 'Time Slider',
settings: 'Player Settings',
speed: 'Speed',
speedNormal: 'Normal',
tap: 'Tap to unmute',
toggleCaptions: 'Toggle Captions',
unmute: 'Unmute',
volume: 'Volume',
volumeControl: 'Volume Control',
volumeSlider: 'Volume Slider',
},
live: {
showLabel: true,
showProgress: false,
},
mode: 'responsive', // or `fill` or `fit`
onError: (e: unknown) => console.error(e),
pauseOthers: true,
progress: {
duration: 0,
showCurrentTimeOnly: false,
},
showLoaderOnInit: false,
startTime: 0,
startVolume: 1,
step: 0,
width: 0,
};
/**
* Create an instance of Player.
*
* @param {(HTMLMediaElement|string)} element A video/audio tag or its identifier.
* @param {PlayerOptions} playerOptions Options to enhance Hls and Dash players, among other things.
* @returns {Player}
* @memberof Player
*/
constructor(element: HTMLMediaElement | string, options?: PlayerOptions) {
this.#element = element instanceof HTMLMediaElement ? element : (document.getElementById(element) as HTMLMediaElement);
if (this.#element) {
this.#autoplay = this.#element.autoplay || false;
if (typeof options !== 'string' && !Array.isArray(options)) {
this._mergeOptions(options);
}
this.#element.volume = this.#options.startVolume || 1;
if (this.#options.ads && this.#options.ads.src) {
this.#ads = this.#options.ads.src;
}
if (this.#options.startTime > 0) {
this.#element.currentTime = this.#options.startTime;
}
this.#volume = this.#element.volume;
}
this._autoplay = this._autoplay.bind(this);
this._enableKeyBindings = this._enableKeyBindings.bind(this);
return this;
}
/**
* Create all the markup and events needed for the player.
*
* Note that no controls will be created if user is trying to instantiate a video element
* in an iPhone, because iOS will only use QuickTime as a default constrain.
* @memberof Player
*/
public async init(): Promise<void> {
if (this._isValid()) {
this._wrapInstance();
await this._prepareMedia();
this._createPlayButton();
this._createUID();
this._createControls();
this._setEvents();
Player.instances[this.id] = this;
}
}
/**
* Load media.
*
* HLS and M(PEG)-DASH perform more operations during loading if browser does not support them natively.
* @memberof Player
*/
public load(): Promise<void> | void {
this.#media.loaded = false;
return this.isMedia() ? this.#media.load() : undefined;
}
/**
* Play media.
*
* If Ads are detected, different methods than the native ones are triggered with this operation.
* @memberof Player
*/
public async play(): Promise<void> {
if (this.#media && !this.#media.loaded) {
await this.#media.load();
this.#media.loaded = true;
}
if (this.#adsInstance) {
this.#adsInstance.playRequested = true;
await this.#adsInstance.loadPromise;
return this.#adsInstance.play();
}
return this.#media.play();
}
/**
* Pause media.
*
* If Ads are detected, different methods than the native ones are triggered with this operation.
* @memberof Player
*/
public pause(): void {
if (this.#adsInstance) {
this.#adsInstance.pause();
} else {
this.#media.pause();
}
}
/**
* Destroy OpenMedia Player instance (including all events associated) and return the
* video/audio tag to its original state.
*
* @memberof Player
*/
public destroy(): void {
if (this.#adsInstance) {
this.#adsInstance.pause();
this.#adsInstance.destroy();
}
if (this.#fullscreen) {
this.#fullscreen.destroy();
}
const el = this.#element as HTMLMediaElement;
if (this.#media) {
this.#media.destroy();
}
Object.keys(this.#events).forEach(event => {
el.removeEventListener(event, this.#events[event]);
});
this.getContainer().removeEventListener('keydown', this._enableKeyBindings);
if (this.#autoplay && !this.#processedAutoplay && isVideo(this.#element)) {
el.removeEventListener('canplay', this._autoplay);
}
if (this.#controls) {
this.#controls.destroy();
}
if (isVideo(this.#element)) {
removeElement(this.playBtn);
removeElement(this.loader);
}
this.#element.removeEventListener('playererror', this.#options.onError);
el.controls = true;
el.setAttribute('id', this.#uid);
el.removeAttribute('op-live__enabled');
el.removeAttribute('op-dvr__enabled');
const parent = this.#options.mode === 'fit' && !isAudio(el) ? el.closest('.op-player__fit--wrapper') : el.parentElement;
if (parent && parent.parentNode) {
parent.parentNode.replaceChild(el, parent);
}
delete Player.instances[this.#uid];
const e = addEvent('playerdestroyed');
el.dispatchEvent(e);
}
/**
* Retrieve the parent element (with `op-player` class) of the native video/audio tag.
*
* This element is mostly useful to attach other player component's markup in a place
* different than the controls bar.
* @returns {HTMLElement}
* @memberof Player
*/
public getContainer(): HTMLElement {
return this.#element.parentElement || this.#element;
}
/**
* Retrieve an instance of the controls object used in the player instance.
*
* This element is mostly useful to attach other player component's markup in the controls bar.
* @returns {Controls}
* @memberof Player
*/
public getControls(): Controls {
return this.#controls;
}
/**
* Retrieve an instance of the custom controls invoked in the player instance.
*
* @returns {ControlItem[]}
* @memberof Player
*/
public getCustomControls(): ControlItem[] {
return this.#customControlItems;
}
/**
* Retrieve the original video/audio tag.
*
* This element is useful to attach different events in other player's components.
* @returns {HTMLMediaElement}
* @memberof Player
*/
public getElement(): HTMLMediaElement {
return this.#element;
}
/**
* Retrieve the events attached to the player.
*
* This list does not include individual events associated with other player's components.
* @returns {EventsList}
* @memberof Player
*/
public getEvents(): EventsList {
return this.#events;
}
/**
* Retrieve the list of config options associated with the player..
*
* @returns {PlayerOptions}
* @memberof Player
*/
public getOptions(): PlayerOptions {
return this.#options;
}
/**
* Retrieve the current media object (could be Ads or any other media type).
*
* @returns {(Ads|Media)}
* @memberof Player
*/
public activeElement(): Ads | Media {
return this.#adsInstance && this.#adsInstance.started() ? this.#adsInstance : this.#media;
}
/**
* Check if current media is an instance of a native media type.
*
* @returns {boolean}
* @memberof Player
*/
public isMedia(): boolean {
return this.activeElement() instanceof Media;
}
/**
* Check if current media is an instance of an Ad.
*
* @returns {boolean}
* @memberof Player
*/
public isAd(): boolean {
return this.activeElement() instanceof Ads;
}
/**
* Retrieve an instance of the `Media` object.
*
* @returns {Media}
* @memberof Player
*/
public getMedia(): Media {
return this.#media;
}
/**
* Retrieve an instance of the `Ads` object.
*
* @returns {Ads}
* @memberof Player
*/
public getAd(): Ads {
return this.#adsInstance;
}
/**
* Append a new `<track>` tag to the video/audio tag and dispatch event
* so it gets registered/loaded in the player, via `controlschanged` event.
*
* @param {Track} args
* @memberof Player
*/
public addCaptions(args: Track): void {
if (args.default) {
const tracks = this.#element.querySelectorAll('track');
for (let i = 0, total = tracks.length; i < total; i++) {
(tracks[i] as HTMLTrackElement).default = false;
}
}
const el = this.#element;
// If captions have been added previously, just update URL and default status
let track = el.querySelector(`track[srclang="${args.srclang}"][kind="${args.kind}"]`) as HTMLTrackElement;
if (track) {
track.src = args.src;
track.label = args.label;
track.default = args.default || false;
} else {
track = document.createElement('track');
track.srclang = args.srclang;
track.src = args.src;
track.kind = args.kind;
track.label = args.label;
track.default = args.default || false;
el.appendChild(track);
}
const e = addEvent('controlschanged');
el.dispatchEvent(e);
}
/**
* Add new custom control to the list to be rendered.
*
* @param {ControlItem} args
* @memberof Player
*/
public addControl(args: ControlItem): void {
args.custom = true;
this.#customControlItems.push(args);
const e = addEvent('controlschanged');
this.#element.dispatchEvent(e);
}
/**
* Remove a control to the list (whether custom or not).
*
* @param {string} controlName
* @memberof Player
*/
public removeControl(controlName: string): void {
const { layers } = this.getOptions().controls;
Object.keys(layers).forEach(layer => {
layers[layer].forEach((item: string, idx: number) => {
if (item === controlName) {
layers[layer].splice(idx, 1);
}
});
});
// Check custom controls and remove reference there as well
this.#customControlItems.forEach((item: ControlItem, idx: number) => {
if (item.id === controlName) {
this.#customControlItems.splice(idx, 1);
}
});
const e = addEvent('controlschanged');
this.#element.dispatchEvent(e);
}
/**
* Load media and events depending of media type.
*
* @memberof Player
*/
public async _prepareMedia(): Promise<void> {
try {
this.#element.addEventListener('playererror', this.#options.onError, EVENT_OPTIONS);
if (this.#autoplay && isVideo(this.#element)) {
this.#element.addEventListener('canplay', this._autoplay, EVENT_OPTIONS);
}
this.#media = new Media(this.#element, this.#options, this.#autoplay, Player.customMedia);
const preload = this.#element.getAttribute('preload');
if (this.#ads || !preload || preload !== 'none') {
await this.#media.load();
this.#media.loaded = true;
}
if (!this.#autoplay && this.#ads) {
const adsOptions = this.#options && this.#options.ads ? this.#options.ads : undefined;
this.#adsInstance = new Ads(this, this.#ads, false, false, adsOptions);
}
} catch (e) {
console.error(e);
}
}
public enableDefaultPlayer(): void {
let paused = true;
let currentTime = 0;
if (this.proxy && !this.proxy.paused) {
paused = false;
currentTime = this.proxy.currentTime;
this.proxy.pause();
}
this.proxy = this;
this.getElement().addEventListener('loadedmetadata', () => {
this.getMedia().currentTime = currentTime;
if (!paused) {
this.play();
}
});
}
public async loadAd(src: string | string[]): Promise<void> {
try {
if (this.isAd()) {
this.getAd().destroy();
this.getAd().src = src;
this.getAd().loadedAd = false;
this.getAd().load();
} else {
const adsOptions = this.#options && this.#options.ads ? this.#options.ads : undefined;
const autoplay = !this.activeElement().paused || this.#canAutoplay;
this.#adsInstance = new Ads(this, src, autoplay, this.#canAutoplayMuted, adsOptions);
}
} catch (err) {
console.error(err);
}
}
/**
* Set a Source object to the current media.
*
* @memberof Player
*/
set src(media) {
if (this.#media instanceof Media) {
this.#media.mediaFiles = [];
this.#media.src = media;
} else if (typeof media === 'string') {
this.#element.src = media;
} else if (Array.isArray(media)) {
media.forEach(m => {
const source = document.createElement('source');
source.src = m.src;
source.type = m.type || predictType(m.src, this.#element);
this.#element.appendChild(source);
});
} else if (typeof media === 'object') {
this.#element.src = (media as Source).src;
}
}
/**
* Retrieve the current Source list associated with the player.
*
* @type Source[]
* @memberof Player
* @readonly
*/
get src(): Source[] {
return this.#media.src;
}
/**
* Retrieve current player's unique identifier.
*
* @type string
* @memberof Player
* @readonly
*/
get id(): string {
return this.#uid;
}
/**
* Check if the element passed in the constructor is a valid video/audio tag
* with 'op-player__media' class (at the very least, since `op-player` works
* for automatic instantiation)
*
* @private
* @memberof Player
* @return {boolean}
*/
private _isValid(): boolean {
const el = this.#element;
if (el instanceof HTMLElement === false) {
return false;
}
if (!isAudio(el) && !isVideo(el)) {
return false;
}
if (!el.classList.contains('op-player__media')) {
return false;
}
return true;
}
/**
* Wrap media instance within a DIV tag.
*
* It detects also whether the user is using a mouse, or TAB for accessibility purposes.
* @private
* @memberof Player
*/
private _wrapInstance(): void {
const wrapper = document.createElement('div');
wrapper.className = 'op-player op-player__keyboard--inactive';
wrapper.className += isAudio(this.#element) ? ' op-player__audio' : ' op-player__video';
wrapper.tabIndex = 0;
this.#element.classList.remove('op-player');
if (this.#element.parentElement) {
this.#element.parentElement.insertBefore(wrapper, this.#element);
}
wrapper.appendChild(this.#element);
const messageContainer = document.createElement('div');
messageContainer.className = 'op-status';
messageContainer.innerHTML = '<span></span>';
messageContainer.tabIndex = -1;
messageContainer.setAttribute('aria-hidden', 'true');
if (isVideo(this.#element) && this.#element.parentElement) {
this.#element.parentElement.insertBefore(messageContainer, this.#element);
}
wrapper.addEventListener('keydown', () => {
if (wrapper.classList.contains('op-player__keyboard--inactive')) {
wrapper.classList.remove('op-player__keyboard--inactive');
}
}, EVENT_OPTIONS);
wrapper.addEventListener('click', () => {
if (!wrapper.classList.contains('op-player__keyboard--inactive')) {
wrapper.classList.add('op-player__keyboard--inactive');
}
}, EVENT_OPTIONS);
if (this.#options.mode === 'fill' && !isAudio(this.#element) && !IS_IPHONE) {
// Create fill effect on video, scaling and cropping dimensions relative to its parent, setting just a class.
// This method centers the video view using pure CSS in both Ads and Media.
// @see https://slicejack.com/fullscreen-html5-video-background-css/
this.getContainer().classList.add('op-player__full');
} else if (this.#options.mode === 'fit' && !isAudio(this.#element)) {
const container = this.getContainer();
if (container.parentElement) {
const fitWrapper = document.createElement('div');
fitWrapper.className = 'op-player__fit--wrapper';
fitWrapper.tabIndex = 0;
container.parentElement.insertBefore(fitWrapper, container);
fitWrapper.appendChild(container);
container.classList.add('op-player__fit');
}
} else {
let style = '';
if (this.#options.width) {
const width = typeof this.#options.width === 'number' ? `${this.#options.width}px` : this.#options.width;
style += `width: ${width} !important;`;
}
if (this.#options.height) {
const height = typeof this.#options.height === 'number' ? `${this.#options.height}px` : this.#options.height;
style += `height: ${height} !important;`;
}
if (style) {
wrapper.setAttribute('style', style);
}
}
}
/**
* Build HTML markup for media controls.
*
* @memberof Player
*/
private _createControls(): void {
if (IS_IPHONE && isVideo(this.#element)) {
this.getContainer().classList.add('op-player__ios--iphone');
}
this.#controls = new Controls(this);
this.#controls.create();
}
/**
* Generate a unique identifier for the current player instance, if no `id` attribute was detected.
*
* @private
* @memberof Player
*/
private _createUID(): void {
if (this.#element.id) {
this.#uid = this.#element.id;
this.#element.removeAttribute('id');
} else {
let uid;
do {
uid = `op_${Math.random().toString(36).substr(2, 9)}`;
} while (Player.instances[uid] !== undefined);
this.#uid = uid;
}
if (this.#element.parentElement) {
this.#element.parentElement.id = this.#uid;
}
}
/**
* Create a Play button in the main player's container.
*
* Also, it creates a loader element, that will be displayed when seeking/waiting for media.
* @memberof Player
*/
private _createPlayButton(): void {
if (isAudio(this.#element)) {
return;
}
this.playBtn = document.createElement('button');
this.playBtn.className = 'op-player__play';
this.playBtn.tabIndex = 0;
this.playBtn.title = this.#options.labels.play;
this.playBtn.innerHTML = `<span>${this.#options.labels.play}</span>`;
this.playBtn.setAttribute('aria-pressed', 'false');
this.playBtn.setAttribute('aria-hidden', 'false');
this.loader = document.createElement('span');
this.loader.className = 'op-player__loader';
this.loader.tabIndex = -1;
this.loader.setAttribute('aria-hidden', 'true');
if (this.#element.parentElement) {
this.#element.parentElement.insertBefore(this.loader, this.#element);
this.#element.parentElement.insertBefore(this.playBtn, this.#element);
}
this.playBtn.addEventListener('click', () => {
if (this.#adsInstance) {
this.#adsInstance.playRequested = this.activeElement().paused;
}
if (this.activeElement().paused) {
this.activeElement().play();
} else {
this.activeElement().pause();
}
}, EVENT_OPTIONS);
}
/**
* Set events to show/hide play button and loader element, and to use the player using keyboard
* for accessibility purposes.
*
* @private
* @memberof Player
*/
private _setEvents(): void {
if (isVideo(this.#element)) {
this.#events.loadedmetadata = () => {
const el = this.activeElement();
if (this.#options.showLoaderOnInit && !IS_IOS && !IS_ANDROID) {
this.loader.setAttribute('aria-hidden', 'false');
this.playBtn.setAttribute('aria-hidden', 'true');
} else {
this.loader.setAttribute('aria-hidden', 'true');
this.playBtn.setAttribute('aria-hidden', 'false');
}
if (el.paused) {
this.playBtn.classList.remove('op-player__play--paused');
this.playBtn.setAttribute('aria-pressed', 'false');
}
};
this.#events.waiting = () => {
this.playBtn.setAttribute('aria-hidden', 'true');
this.loader.setAttribute('aria-hidden', 'false');
};
this.#events.seeking = () => {
const el = this.activeElement();
this.playBtn.setAttribute('aria-hidden', 'true');
this.loader.setAttribute('aria-hidden', el instanceof Media ? 'false' : 'true');
};
this.#events.seeked = () => {
const el = this.activeElement();
if (Math.round(el.currentTime) === 0) {
this.playBtn.setAttribute('aria-hidden', 'true');
this.loader.setAttribute('aria-hidden', 'false');
} else {
this.playBtn.setAttribute('aria-hidden', el instanceof Media ? 'false' : 'true');
this.loader.setAttribute('aria-hidden', 'true');
}
};
this.#events.play = () => {
this.playBtn.classList.add('op-player__play--paused');
this.playBtn.title = this.#options.labels.pause;
this.loader.setAttribute('aria-hidden', 'true');
if (this.#options.showLoaderOnInit) {
this.playBtn.setAttribute('aria-hidden', 'true');
} else {
setTimeout(() => {
this.playBtn.setAttribute('aria-hidden', 'true');
}, this.#options.hidePlayBtnTimer);
}
};
this.#events.playing = () => {
this.loader.setAttribute('aria-hidden', 'true');
this.playBtn.setAttribute('aria-hidden', 'true');
};
this.#events.pause = () => {
const el = this.activeElement();
this.playBtn.classList.remove('op-player__play--paused');
this.playBtn.title = this.#options.labels.play;
if (this.#options.showLoaderOnInit && Math.round(el.currentTime) === 0) {
this.playBtn.setAttribute('aria-hidden', 'true');
this.loader.setAttribute('aria-hidden', 'false');
} else {
this.playBtn.setAttribute('aria-hidden', 'false');
this.loader.setAttribute('aria-hidden', 'true');
}
};
this.#events.ended = () => {
this.loader.setAttribute('aria-hidden', 'true');
this.playBtn.setAttribute('aria-hidden', 'true');
};
}
Object.keys(this.#events).forEach(event => {
this.#element.addEventListener(event, this.#events[event], EVENT_OPTIONS);
});
this.getContainer().addEventListener('keydown', this._enableKeyBindings, EVENT_OPTIONS);
}
/**
* Attempt to autoplay media depending on browser's capabilities.
*
* It does not consider auto playing Ads since that workflow is established already as part
* of that object.
* @see [[Ads.constructor]]
* @private
* @memberof Player
*/
private _autoplay() {
if (!this.#processedAutoplay) {
this.#processedAutoplay = true;
this.#element.removeEventListener('canplay', this._autoplay);
isAutoplaySupported(this.#element, this.#volume, autoplay => {
this.#canAutoplay = autoplay;
}, muted => {
this.#canAutoplayMuted = muted;
}, () => {
if (this.#canAutoplayMuted) {
this.activeElement().muted = true;
this.activeElement().volume = 0;
const e = addEvent('volumechange');
this.#element.dispatchEvent(e);
// Insert element to unmute if browser allows autoplay with muted media
const volumeEl = document.createElement('div');
const action = IS_IOS || IS_ANDROID ? this.#options.labels.tap : this.#options.labels.click;
volumeEl.className = 'op-player__unmute';
volumeEl.innerHTML = `<span>${action}</span>`;
volumeEl.tabIndex = 0;
volumeEl.addEventListener('click', () => {
this.activeElement().muted = false;
this.activeElement().volume = this.#volume;
const event = addEvent('volumechange');
this.#element.dispatchEvent(event);
removeElement(volumeEl);
}, EVENT_OPTIONS);
const target = this.getContainer();
target.insertBefore(volumeEl, target.firstChild);
} else {
this.activeElement().muted = this.#element.muted;
this.activeElement().volume = this.#volume;
}
if (this.#ads) {
const adsOptions = this.#options && this.#options.ads ? this.#options.ads : undefined;
this.#adsInstance = new Ads(this, this.#ads, this.#canAutoplay, this.#canAutoplayMuted, adsOptions);
} else if (this.#canAutoplay || this.#canAutoplayMuted) {
this.play();
}
});
}
}
/**
* Merge user's configuration with default configuration.
*
* It deals with complex config elements, like `labels` and `controls`.
* @param playerOptions
* @private
* @memberof Player
*/
private _mergeOptions(playerOptions?: PlayerOptions): void {
this.#options = { ...this.#defaultOptions, ...playerOptions };
if (playerOptions) {
const objectElements = ['labels', 'controls'];
objectElements.forEach(item => {
this.#options[item] = playerOptions[item] && Object.keys(playerOptions[item]).length
? { ...this.#defaultOptions[item], ...playerOptions[item] }
: this.#defaultOptions[item];
});
}
}
private _enableKeyBindings(e: KeyboardEvent) {
const key = e.which || e.keyCode || 0;
const el = this.activeElement();
const isAd = this.isAd();
const playerFocused = document?.activeElement?.classList.contains('op-player');
switch (key) {
// Toggle play/pause using letter K, Tab or Enter
case 13:
case 32:
case 75:
// Avoid interference of Enter/Space keys when focused in the player container
if (playerFocused && (key === 13 || key === 32)) {
if (el.paused) {
el.play();
} else {
el.pause();
}
} else if (key === 75) {
if (el.paused) {
el.play();
} else {
el.pause();
}
}
e.preventDefault();
e.stopPropagation();
break;
// End key ends video
case 35:
if (!isAd && el.duration !== Infinity) {
el.currentTime = el.duration;
e.preventDefault();
e.stopPropagation();
}
break;
// Home key resets progress
case 36:
if (!isAd) {
el.currentTime = 0;
e.preventDefault();
e.stopPropagation();
}
break;
// Use the left and right arrow keys to manipulate current media time.
// Letter J/L will set double of step forward/backward
case 37:
case 39:
case 74:
case 76:
if (!isAd && el.duration !== Infinity) {
let newStep = 5;
const configStep = this.getOptions().step;
if (configStep) {
newStep = key === 74 || key === 76 ? configStep * 2 : configStep;
} else if (key === 74 || key === 76) {
newStep = 10;
}
const step = el.duration !== Infinity ? newStep : this.getOptions().progress.duration;
el.currentTime += key === 37 || key === 74 ? step * -1 : step;
if (el.currentTime < 0) {
el.currentTime = 0;
} else if (el.currentTime >= el.duration) {
el.currentTime = el.duration;
}
e.preventDefault();
e.stopPropagation();
}
break;
// Use the up/down arrow keys to manipulate volume.
case 38:
case 40:
const newVol = key === 38 ? Math.min(el.volume + 0.1, 1) : Math.max(el.volume - 0.1, 0);
el.volume = newVol;
el.muted = !(newVol > 0);
e.preventDefault();
e.stopPropagation();
break;
// Letter F sets fullscreen (only video)
case 70:
if (isVideo(this.#element) && !e.ctrlKey) {
this.#fullscreen = new Fullscreen(this, '', '');
if (typeof this.#fullscreen.fullScreenEnabled !== 'undefined') {
this.#fullscreen.toggleFullscreen();
e.preventDefault();
e.stopPropagation();
}
}
break;
// Letter M toggles mute
case 77:
el.muted = !el.muted;
if (el.muted) {
el.volume = 0;
} else {
el.volume = this.#volume;
}
e.preventDefault();
e.stopPropagation();
break;
// < and > will decrease/increase the speed of playback by 0.25
// , and . will go to the prev/next frame of the media
case 188:
case 190:
if (!isAd && e.shiftKey) {
const elem = el as Media;
elem.playbackRate = key === 188 ? Math.max(elem.playbackRate - 0.25, 0.25) : Math.min(elem.playbackRate + 0.25, 2);
// Show playbackRate and update controls to reflect change in settings
const target = this.getContainer().querySelector('.op-status>span');
if (target) {
target.textContent = `${elem.playbackRate}x`;
if (target.parentElement) {
target.parentElement.setAttribute('aria-hidden', 'false');
}
setTimeout(() => {
if (target.parentElement) {
target.parentElement.setAttribute('aria-hidden', 'true');
}
}, 500);
}
const ev = addEvent('controlschanged');
dispatchEvent(ev);
e.preventDefault();
e.stopPropagation();
} else if (!isAd && el.paused) {
el.currentTime += (1 / 25) * (key === 188 ? -1 : 1);
e.preventDefault();
e.stopPropagation();
}
break;
default:
break;
}
}
}
export default Player;
// Expose element globally.
if (typeof window !== 'undefined') {
(window as any).OpenPlayer = Player;
(window as any).OpenPlayerJS = Player;
Player.init();
} | the_stack |
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types";
import {
AcceptDomainTransferFromAnotherAwsAccountCommand,
AcceptDomainTransferFromAnotherAwsAccountCommandInput,
AcceptDomainTransferFromAnotherAwsAccountCommandOutput,
} from "./commands/AcceptDomainTransferFromAnotherAwsAccountCommand";
import {
CancelDomainTransferToAnotherAwsAccountCommand,
CancelDomainTransferToAnotherAwsAccountCommandInput,
CancelDomainTransferToAnotherAwsAccountCommandOutput,
} from "./commands/CancelDomainTransferToAnotherAwsAccountCommand";
import {
CheckDomainAvailabilityCommand,
CheckDomainAvailabilityCommandInput,
CheckDomainAvailabilityCommandOutput,
} from "./commands/CheckDomainAvailabilityCommand";
import {
CheckDomainTransferabilityCommand,
CheckDomainTransferabilityCommandInput,
CheckDomainTransferabilityCommandOutput,
} from "./commands/CheckDomainTransferabilityCommand";
import {
DeleteTagsForDomainCommand,
DeleteTagsForDomainCommandInput,
DeleteTagsForDomainCommandOutput,
} from "./commands/DeleteTagsForDomainCommand";
import {
DisableDomainAutoRenewCommand,
DisableDomainAutoRenewCommandInput,
DisableDomainAutoRenewCommandOutput,
} from "./commands/DisableDomainAutoRenewCommand";
import {
DisableDomainTransferLockCommand,
DisableDomainTransferLockCommandInput,
DisableDomainTransferLockCommandOutput,
} from "./commands/DisableDomainTransferLockCommand";
import {
EnableDomainAutoRenewCommand,
EnableDomainAutoRenewCommandInput,
EnableDomainAutoRenewCommandOutput,
} from "./commands/EnableDomainAutoRenewCommand";
import {
EnableDomainTransferLockCommand,
EnableDomainTransferLockCommandInput,
EnableDomainTransferLockCommandOutput,
} from "./commands/EnableDomainTransferLockCommand";
import {
GetContactReachabilityStatusCommand,
GetContactReachabilityStatusCommandInput,
GetContactReachabilityStatusCommandOutput,
} from "./commands/GetContactReachabilityStatusCommand";
import {
GetDomainDetailCommand,
GetDomainDetailCommandInput,
GetDomainDetailCommandOutput,
} from "./commands/GetDomainDetailCommand";
import {
GetDomainSuggestionsCommand,
GetDomainSuggestionsCommandInput,
GetDomainSuggestionsCommandOutput,
} from "./commands/GetDomainSuggestionsCommand";
import {
GetOperationDetailCommand,
GetOperationDetailCommandInput,
GetOperationDetailCommandOutput,
} from "./commands/GetOperationDetailCommand";
import { ListDomainsCommand, ListDomainsCommandInput, ListDomainsCommandOutput } from "./commands/ListDomainsCommand";
import {
ListOperationsCommand,
ListOperationsCommandInput,
ListOperationsCommandOutput,
} from "./commands/ListOperationsCommand";
import {
ListTagsForDomainCommand,
ListTagsForDomainCommandInput,
ListTagsForDomainCommandOutput,
} from "./commands/ListTagsForDomainCommand";
import {
RegisterDomainCommand,
RegisterDomainCommandInput,
RegisterDomainCommandOutput,
} from "./commands/RegisterDomainCommand";
import {
RejectDomainTransferFromAnotherAwsAccountCommand,
RejectDomainTransferFromAnotherAwsAccountCommandInput,
RejectDomainTransferFromAnotherAwsAccountCommandOutput,
} from "./commands/RejectDomainTransferFromAnotherAwsAccountCommand";
import { RenewDomainCommand, RenewDomainCommandInput, RenewDomainCommandOutput } from "./commands/RenewDomainCommand";
import {
ResendContactReachabilityEmailCommand,
ResendContactReachabilityEmailCommandInput,
ResendContactReachabilityEmailCommandOutput,
} from "./commands/ResendContactReachabilityEmailCommand";
import {
RetrieveDomainAuthCodeCommand,
RetrieveDomainAuthCodeCommandInput,
RetrieveDomainAuthCodeCommandOutput,
} from "./commands/RetrieveDomainAuthCodeCommand";
import {
TransferDomainCommand,
TransferDomainCommandInput,
TransferDomainCommandOutput,
} from "./commands/TransferDomainCommand";
import {
TransferDomainToAnotherAwsAccountCommand,
TransferDomainToAnotherAwsAccountCommandInput,
TransferDomainToAnotherAwsAccountCommandOutput,
} from "./commands/TransferDomainToAnotherAwsAccountCommand";
import {
UpdateDomainContactCommand,
UpdateDomainContactCommandInput,
UpdateDomainContactCommandOutput,
} from "./commands/UpdateDomainContactCommand";
import {
UpdateDomainContactPrivacyCommand,
UpdateDomainContactPrivacyCommandInput,
UpdateDomainContactPrivacyCommandOutput,
} from "./commands/UpdateDomainContactPrivacyCommand";
import {
UpdateDomainNameserversCommand,
UpdateDomainNameserversCommandInput,
UpdateDomainNameserversCommandOutput,
} from "./commands/UpdateDomainNameserversCommand";
import {
UpdateTagsForDomainCommand,
UpdateTagsForDomainCommandInput,
UpdateTagsForDomainCommandOutput,
} from "./commands/UpdateTagsForDomainCommand";
import { ViewBillingCommand, ViewBillingCommandInput, ViewBillingCommandOutput } from "./commands/ViewBillingCommand";
import { Route53DomainsClient } from "./Route53DomainsClient";
/**
* <p>Amazon Route 53 API actions let you register domain names and perform related operations.</p>
*/
export class Route53Domains extends Route53DomainsClient {
/**
* <p>Accepts the transfer of a domain from another AWS account to the current AWS account. You initiate a transfer between AWS accounts using
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_TransferDomainToAnotherAwsAccount.html">TransferDomainToAnotherAwsAccount</a>.
* </p>
*
* <p>Use either
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_ListOperations.html">ListOperations</a> or
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>
* to determine whether the operation succeeded.
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>
* provides additional information, for example, <code>Domain Transfer from Aws Account 111122223333 has been cancelled</code>.
* </p>
*/
public acceptDomainTransferFromAnotherAwsAccount(
args: AcceptDomainTransferFromAnotherAwsAccountCommandInput,
options?: __HttpHandlerOptions
): Promise<AcceptDomainTransferFromAnotherAwsAccountCommandOutput>;
public acceptDomainTransferFromAnotherAwsAccount(
args: AcceptDomainTransferFromAnotherAwsAccountCommandInput,
cb: (err: any, data?: AcceptDomainTransferFromAnotherAwsAccountCommandOutput) => void
): void;
public acceptDomainTransferFromAnotherAwsAccount(
args: AcceptDomainTransferFromAnotherAwsAccountCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: AcceptDomainTransferFromAnotherAwsAccountCommandOutput) => void
): void;
public acceptDomainTransferFromAnotherAwsAccount(
args: AcceptDomainTransferFromAnotherAwsAccountCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: AcceptDomainTransferFromAnotherAwsAccountCommandOutput) => void),
cb?: (err: any, data?: AcceptDomainTransferFromAnotherAwsAccountCommandOutput) => void
): Promise<AcceptDomainTransferFromAnotherAwsAccountCommandOutput> | void {
const command = new AcceptDomainTransferFromAnotherAwsAccountCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Cancels the transfer of a domain from the current AWS account to another AWS account. You initiate a transfer between AWS accounts using
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_TransferDomainToAnotherAwsAccount.html">TransferDomainToAnotherAwsAccount</a>.
* </p>
*
* <important>
* <p>You must cancel the transfer before the other AWS account accepts the transfer using
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_AcceptDomainTransferFromAnotherAwsAccount.html">AcceptDomainTransferFromAnotherAwsAccount</a>.</p>
* </important>
*
* <p>Use either
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_ListOperations.html">ListOperations</a> or
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>
* to determine whether the operation succeeded.
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>
* provides additional information, for example, <code>Domain Transfer from Aws Account 111122223333 has been cancelled</code>.
* </p>
*/
public cancelDomainTransferToAnotherAwsAccount(
args: CancelDomainTransferToAnotherAwsAccountCommandInput,
options?: __HttpHandlerOptions
): Promise<CancelDomainTransferToAnotherAwsAccountCommandOutput>;
public cancelDomainTransferToAnotherAwsAccount(
args: CancelDomainTransferToAnotherAwsAccountCommandInput,
cb: (err: any, data?: CancelDomainTransferToAnotherAwsAccountCommandOutput) => void
): void;
public cancelDomainTransferToAnotherAwsAccount(
args: CancelDomainTransferToAnotherAwsAccountCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CancelDomainTransferToAnotherAwsAccountCommandOutput) => void
): void;
public cancelDomainTransferToAnotherAwsAccount(
args: CancelDomainTransferToAnotherAwsAccountCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: CancelDomainTransferToAnotherAwsAccountCommandOutput) => void),
cb?: (err: any, data?: CancelDomainTransferToAnotherAwsAccountCommandOutput) => void
): Promise<CancelDomainTransferToAnotherAwsAccountCommandOutput> | void {
const command = new CancelDomainTransferToAnotherAwsAccountCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This operation checks the availability of one domain name. Note that if the availability status of a domain is pending, you must
* submit another request to determine the availability of the domain name.</p>
*/
public checkDomainAvailability(
args: CheckDomainAvailabilityCommandInput,
options?: __HttpHandlerOptions
): Promise<CheckDomainAvailabilityCommandOutput>;
public checkDomainAvailability(
args: CheckDomainAvailabilityCommandInput,
cb: (err: any, data?: CheckDomainAvailabilityCommandOutput) => void
): void;
public checkDomainAvailability(
args: CheckDomainAvailabilityCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CheckDomainAvailabilityCommandOutput) => void
): void;
public checkDomainAvailability(
args: CheckDomainAvailabilityCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CheckDomainAvailabilityCommandOutput) => void),
cb?: (err: any, data?: CheckDomainAvailabilityCommandOutput) => void
): Promise<CheckDomainAvailabilityCommandOutput> | void {
const command = new CheckDomainAvailabilityCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Checks whether a domain name can be transferred to Amazon Route 53. </p>
*/
public checkDomainTransferability(
args: CheckDomainTransferabilityCommandInput,
options?: __HttpHandlerOptions
): Promise<CheckDomainTransferabilityCommandOutput>;
public checkDomainTransferability(
args: CheckDomainTransferabilityCommandInput,
cb: (err: any, data?: CheckDomainTransferabilityCommandOutput) => void
): void;
public checkDomainTransferability(
args: CheckDomainTransferabilityCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: CheckDomainTransferabilityCommandOutput) => void
): void;
public checkDomainTransferability(
args: CheckDomainTransferabilityCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CheckDomainTransferabilityCommandOutput) => void),
cb?: (err: any, data?: CheckDomainTransferabilityCommandOutput) => void
): Promise<CheckDomainTransferabilityCommandOutput> | void {
const command = new CheckDomainTransferabilityCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This operation deletes the specified tags for a domain.</p>
* <p>All tag operations are eventually consistent; subsequent operations might not immediately represent all issued operations.</p>
*/
public deleteTagsForDomain(
args: DeleteTagsForDomainCommandInput,
options?: __HttpHandlerOptions
): Promise<DeleteTagsForDomainCommandOutput>;
public deleteTagsForDomain(
args: DeleteTagsForDomainCommandInput,
cb: (err: any, data?: DeleteTagsForDomainCommandOutput) => void
): void;
public deleteTagsForDomain(
args: DeleteTagsForDomainCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DeleteTagsForDomainCommandOutput) => void
): void;
public deleteTagsForDomain(
args: DeleteTagsForDomainCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteTagsForDomainCommandOutput) => void),
cb?: (err: any, data?: DeleteTagsForDomainCommandOutput) => void
): Promise<DeleteTagsForDomainCommandOutput> | void {
const command = new DeleteTagsForDomainCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This operation disables automatic renewal of domain registration for the specified domain.</p>
*/
public disableDomainAutoRenew(
args: DisableDomainAutoRenewCommandInput,
options?: __HttpHandlerOptions
): Promise<DisableDomainAutoRenewCommandOutput>;
public disableDomainAutoRenew(
args: DisableDomainAutoRenewCommandInput,
cb: (err: any, data?: DisableDomainAutoRenewCommandOutput) => void
): void;
public disableDomainAutoRenew(
args: DisableDomainAutoRenewCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DisableDomainAutoRenewCommandOutput) => void
): void;
public disableDomainAutoRenew(
args: DisableDomainAutoRenewCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DisableDomainAutoRenewCommandOutput) => void),
cb?: (err: any, data?: DisableDomainAutoRenewCommandOutput) => void
): Promise<DisableDomainAutoRenewCommandOutput> | void {
const command = new DisableDomainAutoRenewCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This operation removes the transfer lock on the domain (specifically the
* <code>clientTransferProhibited</code> status) to allow domain transfers. We recommend
* you refrain from performing this action unless you intend to transfer the domain to a
* different registrar. Successful submission returns an operation ID that you can use to track
* the progress and completion of the action. If the request is not completed successfully, the
* domain registrant will be notified by email.</p>
*/
public disableDomainTransferLock(
args: DisableDomainTransferLockCommandInput,
options?: __HttpHandlerOptions
): Promise<DisableDomainTransferLockCommandOutput>;
public disableDomainTransferLock(
args: DisableDomainTransferLockCommandInput,
cb: (err: any, data?: DisableDomainTransferLockCommandOutput) => void
): void;
public disableDomainTransferLock(
args: DisableDomainTransferLockCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: DisableDomainTransferLockCommandOutput) => void
): void;
public disableDomainTransferLock(
args: DisableDomainTransferLockCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DisableDomainTransferLockCommandOutput) => void),
cb?: (err: any, data?: DisableDomainTransferLockCommandOutput) => void
): Promise<DisableDomainTransferLockCommandOutput> | void {
const command = new DisableDomainTransferLockCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This operation configures Amazon Route 53 to automatically renew the specified domain before the domain registration expires.
* The cost of renewing your domain registration is billed to your AWS account.</p>
* <p>The period during which you can renew a domain name varies by TLD. For a list of TLDs and their renewal policies, see
* <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/registrar-tld-list.html">Domains That You Can Register with Amazon Route 53</a>
* in the <i>Amazon Route 53 Developer Guide</i>. Route 53 requires that you renew before the end of the renewal period
* so we can complete processing before the deadline.</p>
*/
public enableDomainAutoRenew(
args: EnableDomainAutoRenewCommandInput,
options?: __HttpHandlerOptions
): Promise<EnableDomainAutoRenewCommandOutput>;
public enableDomainAutoRenew(
args: EnableDomainAutoRenewCommandInput,
cb: (err: any, data?: EnableDomainAutoRenewCommandOutput) => void
): void;
public enableDomainAutoRenew(
args: EnableDomainAutoRenewCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: EnableDomainAutoRenewCommandOutput) => void
): void;
public enableDomainAutoRenew(
args: EnableDomainAutoRenewCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: EnableDomainAutoRenewCommandOutput) => void),
cb?: (err: any, data?: EnableDomainAutoRenewCommandOutput) => void
): Promise<EnableDomainAutoRenewCommandOutput> | void {
const command = new EnableDomainAutoRenewCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This operation sets the transfer lock on the domain (specifically the <code>clientTransferProhibited</code> status)
* to prevent domain transfers. Successful submission returns an operation ID that you can use to track the progress and
* completion of the action. If the request is not completed successfully, the domain registrant will be notified by email.</p>
*/
public enableDomainTransferLock(
args: EnableDomainTransferLockCommandInput,
options?: __HttpHandlerOptions
): Promise<EnableDomainTransferLockCommandOutput>;
public enableDomainTransferLock(
args: EnableDomainTransferLockCommandInput,
cb: (err: any, data?: EnableDomainTransferLockCommandOutput) => void
): void;
public enableDomainTransferLock(
args: EnableDomainTransferLockCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: EnableDomainTransferLockCommandOutput) => void
): void;
public enableDomainTransferLock(
args: EnableDomainTransferLockCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: EnableDomainTransferLockCommandOutput) => void),
cb?: (err: any, data?: EnableDomainTransferLockCommandOutput) => void
): Promise<EnableDomainTransferLockCommandOutput> | void {
const command = new EnableDomainTransferLockCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>For operations that require confirmation that the email address for the registrant contact is valid,
* such as registering a new domain, this operation returns information about whether the registrant contact has responded.</p>
* <p>If you want us to resend the email, use the <code>ResendContactReachabilityEmail</code> operation.</p>
*/
public getContactReachabilityStatus(
args: GetContactReachabilityStatusCommandInput,
options?: __HttpHandlerOptions
): Promise<GetContactReachabilityStatusCommandOutput>;
public getContactReachabilityStatus(
args: GetContactReachabilityStatusCommandInput,
cb: (err: any, data?: GetContactReachabilityStatusCommandOutput) => void
): void;
public getContactReachabilityStatus(
args: GetContactReachabilityStatusCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetContactReachabilityStatusCommandOutput) => void
): void;
public getContactReachabilityStatus(
args: GetContactReachabilityStatusCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetContactReachabilityStatusCommandOutput) => void),
cb?: (err: any, data?: GetContactReachabilityStatusCommandOutput) => void
): Promise<GetContactReachabilityStatusCommandOutput> | void {
const command = new GetContactReachabilityStatusCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This operation returns detailed information about a specified domain that is associated with the current AWS account.
* Contact information for the domain is also returned as part of the output.</p>
*/
public getDomainDetail(
args: GetDomainDetailCommandInput,
options?: __HttpHandlerOptions
): Promise<GetDomainDetailCommandOutput>;
public getDomainDetail(
args: GetDomainDetailCommandInput,
cb: (err: any, data?: GetDomainDetailCommandOutput) => void
): void;
public getDomainDetail(
args: GetDomainDetailCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetDomainDetailCommandOutput) => void
): void;
public getDomainDetail(
args: GetDomainDetailCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetDomainDetailCommandOutput) => void),
cb?: (err: any, data?: GetDomainDetailCommandOutput) => void
): Promise<GetDomainDetailCommandOutput> | void {
const command = new GetDomainDetailCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>The GetDomainSuggestions operation returns a list of suggested domain names.</p>
*/
public getDomainSuggestions(
args: GetDomainSuggestionsCommandInput,
options?: __HttpHandlerOptions
): Promise<GetDomainSuggestionsCommandOutput>;
public getDomainSuggestions(
args: GetDomainSuggestionsCommandInput,
cb: (err: any, data?: GetDomainSuggestionsCommandOutput) => void
): void;
public getDomainSuggestions(
args: GetDomainSuggestionsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetDomainSuggestionsCommandOutput) => void
): void;
public getDomainSuggestions(
args: GetDomainSuggestionsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetDomainSuggestionsCommandOutput) => void),
cb?: (err: any, data?: GetDomainSuggestionsCommandOutput) => void
): Promise<GetDomainSuggestionsCommandOutput> | void {
const command = new GetDomainSuggestionsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This operation returns the current status of an operation that is not completed.</p>
*/
public getOperationDetail(
args: GetOperationDetailCommandInput,
options?: __HttpHandlerOptions
): Promise<GetOperationDetailCommandOutput>;
public getOperationDetail(
args: GetOperationDetailCommandInput,
cb: (err: any, data?: GetOperationDetailCommandOutput) => void
): void;
public getOperationDetail(
args: GetOperationDetailCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: GetOperationDetailCommandOutput) => void
): void;
public getOperationDetail(
args: GetOperationDetailCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetOperationDetailCommandOutput) => void),
cb?: (err: any, data?: GetOperationDetailCommandOutput) => void
): Promise<GetOperationDetailCommandOutput> | void {
const command = new GetOperationDetailCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This operation returns all the domain names registered with Amazon Route 53 for the current AWS account.</p>
*/
public listDomains(args: ListDomainsCommandInput, options?: __HttpHandlerOptions): Promise<ListDomainsCommandOutput>;
public listDomains(args: ListDomainsCommandInput, cb: (err: any, data?: ListDomainsCommandOutput) => void): void;
public listDomains(
args: ListDomainsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListDomainsCommandOutput) => void
): void;
public listDomains(
args: ListDomainsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListDomainsCommandOutput) => void),
cb?: (err: any, data?: ListDomainsCommandOutput) => void
): Promise<ListDomainsCommandOutput> | void {
const command = new ListDomainsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Returns information about all of the operations that return an operation ID and that have ever been
* performed on domains that were registered by the current account. </p>
*/
public listOperations(
args: ListOperationsCommandInput,
options?: __HttpHandlerOptions
): Promise<ListOperationsCommandOutput>;
public listOperations(
args: ListOperationsCommandInput,
cb: (err: any, data?: ListOperationsCommandOutput) => void
): void;
public listOperations(
args: ListOperationsCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListOperationsCommandOutput) => void
): void;
public listOperations(
args: ListOperationsCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListOperationsCommandOutput) => void),
cb?: (err: any, data?: ListOperationsCommandOutput) => void
): Promise<ListOperationsCommandOutput> | void {
const command = new ListOperationsCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This operation returns all of the tags that are associated with the specified domain.</p>
* <p>All tag operations are eventually consistent; subsequent operations might not immediately represent all issued operations.</p>
*/
public listTagsForDomain(
args: ListTagsForDomainCommandInput,
options?: __HttpHandlerOptions
): Promise<ListTagsForDomainCommandOutput>;
public listTagsForDomain(
args: ListTagsForDomainCommandInput,
cb: (err: any, data?: ListTagsForDomainCommandOutput) => void
): void;
public listTagsForDomain(
args: ListTagsForDomainCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ListTagsForDomainCommandOutput) => void
): void;
public listTagsForDomain(
args: ListTagsForDomainCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForDomainCommandOutput) => void),
cb?: (err: any, data?: ListTagsForDomainCommandOutput) => void
): Promise<ListTagsForDomainCommandOutput> | void {
const command = new ListTagsForDomainCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This operation registers a domain. Domains are registered either by Amazon Registrar (for .com, .net, and .org domains) or by
* our registrar associate, Gandi (for all other domains). For some top-level domains (TLDs), this operation requires extra parameters.</p>
* <p>When you register a domain, Amazon Route 53 does the following:</p>
* <ul>
* <li>
* <p>Creates a Route 53 hosted zone that has the same name as the domain. Route 53 assigns four name servers
* to your hosted zone and automatically updates your domain registration with the names of these name servers.</p>
* </li>
* <li>
* <p>Enables autorenew, so your domain registration will renew automatically each year. We'll notify you
* in advance of the renewal date so you can choose whether to renew the registration.</p>
* </li>
* <li>
* <p>Optionally enables privacy protection, so WHOIS queries return contact information either for Amazon Registrar
* (for .com, .net, and .org domains) or for our registrar associate, Gandi (for all other TLDs). If you don't enable privacy
* protection, WHOIS queries return the information that you entered for the registrant, admin, and tech contacts.</p>
* </li>
* <li>
* <p>If registration is successful, returns an operation ID that you can use to track the progress and
* completion of the action. If the request is not completed successfully, the domain registrant is notified by email.</p>
* </li>
* <li>
* <p>Charges your AWS account an amount based on the top-level domain. For more information, see
* <a href="http://aws.amazon.com/route53/pricing/">Amazon Route 53 Pricing</a>.</p>
* </li>
* </ul>
*/
public registerDomain(
args: RegisterDomainCommandInput,
options?: __HttpHandlerOptions
): Promise<RegisterDomainCommandOutput>;
public registerDomain(
args: RegisterDomainCommandInput,
cb: (err: any, data?: RegisterDomainCommandOutput) => void
): void;
public registerDomain(
args: RegisterDomainCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: RegisterDomainCommandOutput) => void
): void;
public registerDomain(
args: RegisterDomainCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RegisterDomainCommandOutput) => void),
cb?: (err: any, data?: RegisterDomainCommandOutput) => void
): Promise<RegisterDomainCommandOutput> | void {
const command = new RegisterDomainCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Rejects the transfer of a domain from another AWS account to the current AWS account. You initiate a transfer between AWS accounts using
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_TransferDomainToAnotherAwsAccount.html">TransferDomainToAnotherAwsAccount</a>.
* </p>
*
* <p>Use either
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_ListOperations.html">ListOperations</a> or
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>
* to determine whether the operation succeeded.
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>
* provides additional information, for example, <code>Domain Transfer from Aws Account 111122223333 has been cancelled</code>.
* </p>
*/
public rejectDomainTransferFromAnotherAwsAccount(
args: RejectDomainTransferFromAnotherAwsAccountCommandInput,
options?: __HttpHandlerOptions
): Promise<RejectDomainTransferFromAnotherAwsAccountCommandOutput>;
public rejectDomainTransferFromAnotherAwsAccount(
args: RejectDomainTransferFromAnotherAwsAccountCommandInput,
cb: (err: any, data?: RejectDomainTransferFromAnotherAwsAccountCommandOutput) => void
): void;
public rejectDomainTransferFromAnotherAwsAccount(
args: RejectDomainTransferFromAnotherAwsAccountCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: RejectDomainTransferFromAnotherAwsAccountCommandOutput) => void
): void;
public rejectDomainTransferFromAnotherAwsAccount(
args: RejectDomainTransferFromAnotherAwsAccountCommandInput,
optionsOrCb?:
| __HttpHandlerOptions
| ((err: any, data?: RejectDomainTransferFromAnotherAwsAccountCommandOutput) => void),
cb?: (err: any, data?: RejectDomainTransferFromAnotherAwsAccountCommandOutput) => void
): Promise<RejectDomainTransferFromAnotherAwsAccountCommandOutput> | void {
const command = new RejectDomainTransferFromAnotherAwsAccountCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This operation renews a domain for the specified number of years. The cost of renewing your domain is billed to your AWS account.</p>
* <p>We recommend that you renew your domain several weeks before the expiration date. Some TLD registries delete domains before the
* expiration date if you haven't renewed far enough in advance. For more information about renewing domain registration, see
* <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-renew.html">Renewing Registration for a Domain</a>
* in the <i>Amazon Route 53 Developer Guide</i>.</p>
*/
public renewDomain(args: RenewDomainCommandInput, options?: __HttpHandlerOptions): Promise<RenewDomainCommandOutput>;
public renewDomain(args: RenewDomainCommandInput, cb: (err: any, data?: RenewDomainCommandOutput) => void): void;
public renewDomain(
args: RenewDomainCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: RenewDomainCommandOutput) => void
): void;
public renewDomain(
args: RenewDomainCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RenewDomainCommandOutput) => void),
cb?: (err: any, data?: RenewDomainCommandOutput) => void
): Promise<RenewDomainCommandOutput> | void {
const command = new RenewDomainCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>For operations that require confirmation that the email address for the registrant contact is valid,
* such as registering a new domain, this operation resends the confirmation email to the current email address for the registrant contact.</p>
*/
public resendContactReachabilityEmail(
args: ResendContactReachabilityEmailCommandInput,
options?: __HttpHandlerOptions
): Promise<ResendContactReachabilityEmailCommandOutput>;
public resendContactReachabilityEmail(
args: ResendContactReachabilityEmailCommandInput,
cb: (err: any, data?: ResendContactReachabilityEmailCommandOutput) => void
): void;
public resendContactReachabilityEmail(
args: ResendContactReachabilityEmailCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ResendContactReachabilityEmailCommandOutput) => void
): void;
public resendContactReachabilityEmail(
args: ResendContactReachabilityEmailCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ResendContactReachabilityEmailCommandOutput) => void),
cb?: (err: any, data?: ResendContactReachabilityEmailCommandOutput) => void
): Promise<ResendContactReachabilityEmailCommandOutput> | void {
const command = new ResendContactReachabilityEmailCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This operation returns the AuthCode for the domain. To transfer a domain to another registrar, you provide this value to the new registrar.</p>
*/
public retrieveDomainAuthCode(
args: RetrieveDomainAuthCodeCommandInput,
options?: __HttpHandlerOptions
): Promise<RetrieveDomainAuthCodeCommandOutput>;
public retrieveDomainAuthCode(
args: RetrieveDomainAuthCodeCommandInput,
cb: (err: any, data?: RetrieveDomainAuthCodeCommandOutput) => void
): void;
public retrieveDomainAuthCode(
args: RetrieveDomainAuthCodeCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: RetrieveDomainAuthCodeCommandOutput) => void
): void;
public retrieveDomainAuthCode(
args: RetrieveDomainAuthCodeCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RetrieveDomainAuthCodeCommandOutput) => void),
cb?: (err: any, data?: RetrieveDomainAuthCodeCommandOutput) => void
): Promise<RetrieveDomainAuthCodeCommandOutput> | void {
const command = new RetrieveDomainAuthCodeCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Transfers a domain from another registrar to Amazon Route 53. When the transfer is complete, the domain is registered either with
* Amazon Registrar (for .com, .net, and .org domains) or with our registrar associate, Gandi (for all other TLDs).</p>
* <p>For more information about transferring domains, see the following topics:</p>
* <ul>
* <li>
* <p>For transfer requirements, a detailed procedure, and information about viewing the status of a domain that you're transferring
* to Route 53, see
* <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-transfer-to-route-53.html">Transferring Registration for a
* Domain to Amazon Route 53</a> in the <i>Amazon Route 53 Developer Guide</i>.</p>
* </li>
* <li>
* <p>For information about how to transfer a domain from one AWS account to another, see
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_TransferDomainToAnotherAwsAccount.html">TransferDomainToAnotherAwsAccount</a>.
* </p>
* </li>
* <li>
* <p>For information about how to transfer a domain to another domain registrar, see
* <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-transfer-from-route-53.html">Transferring a Domain from
* Amazon Route 53 to Another Registrar</a> in the <i>Amazon Route 53 Developer Guide</i>.</p>
* </li>
* </ul>
* <p>If the registrar for your domain is also the DNS service provider for the domain, we highly recommend that you
* transfer your DNS service to Route 53 or to another DNS service provider before you transfer your registration. Some registrars
* provide free DNS service when you purchase a domain registration. When you transfer the registration, the previous registrar
* will not renew your domain registration and could end your DNS service at any time.</p>
*
* <important>
* <p>If the registrar for your domain is also the DNS service provider for the domain and you don't
* transfer DNS service to another provider, your website, email, and the web applications associated with the domain
* might become unavailable.</p>
* </important>
*
* <p>If the transfer is successful, this method returns an operation ID that you can use to track the progress and
* completion of the action. If the transfer doesn't complete successfully, the domain registrant will be notified by email.</p>
*/
public transferDomain(
args: TransferDomainCommandInput,
options?: __HttpHandlerOptions
): Promise<TransferDomainCommandOutput>;
public transferDomain(
args: TransferDomainCommandInput,
cb: (err: any, data?: TransferDomainCommandOutput) => void
): void;
public transferDomain(
args: TransferDomainCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: TransferDomainCommandOutput) => void
): void;
public transferDomain(
args: TransferDomainCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TransferDomainCommandOutput) => void),
cb?: (err: any, data?: TransferDomainCommandOutput) => void
): Promise<TransferDomainCommandOutput> | void {
const command = new TransferDomainCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Transfers a domain from the current AWS account to another AWS account. Note the following:</p>
* <ul>
* <li>
* <p>The AWS account that you're transferring the domain to must accept the transfer. If the other account
* doesn't accept the transfer within 3 days, we cancel the transfer. See
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_AcceptDomainTransferFromAnotherAwsAccount.html">AcceptDomainTransferFromAnotherAwsAccount</a>.
* </p>
* </li>
* <li>
* <p>You can cancel the transfer before the other account accepts it. See
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_CancelDomainTransferToAnotherAwsAccount.html">CancelDomainTransferToAnotherAwsAccount</a>.
* </p>
* </li>
* <li>
* <p>The other account can reject the transfer. See
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_RejectDomainTransferFromAnotherAwsAccount.html">RejectDomainTransferFromAnotherAwsAccount</a>.
* </p>
* </li>
* </ul>
*
* <important>
* <p>When you transfer a domain from one AWS account to another, Route 53 doesn't transfer the hosted zone that is associated
* with the domain. DNS resolution isn't affected if the domain and the hosted zone are owned by separate accounts,
* so transferring the hosted zone is optional. For information about transferring the hosted zone to another AWS account, see
* <a href="https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zones-migrating.html">Migrating a Hosted Zone to a
* Different AWS Account</a> in the <i>Amazon Route 53 Developer Guide</i>.</p>
* </important>
*
* <p>Use either
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_ListOperations.html">ListOperations</a> or
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>
* to determine whether the operation succeeded.
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>
* provides additional information, for example, <code>Domain Transfer from Aws Account 111122223333 has been cancelled</code>.
* </p>
*/
public transferDomainToAnotherAwsAccount(
args: TransferDomainToAnotherAwsAccountCommandInput,
options?: __HttpHandlerOptions
): Promise<TransferDomainToAnotherAwsAccountCommandOutput>;
public transferDomainToAnotherAwsAccount(
args: TransferDomainToAnotherAwsAccountCommandInput,
cb: (err: any, data?: TransferDomainToAnotherAwsAccountCommandOutput) => void
): void;
public transferDomainToAnotherAwsAccount(
args: TransferDomainToAnotherAwsAccountCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: TransferDomainToAnotherAwsAccountCommandOutput) => void
): void;
public transferDomainToAnotherAwsAccount(
args: TransferDomainToAnotherAwsAccountCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TransferDomainToAnotherAwsAccountCommandOutput) => void),
cb?: (err: any, data?: TransferDomainToAnotherAwsAccountCommandOutput) => void
): Promise<TransferDomainToAnotherAwsAccountCommandOutput> | void {
const command = new TransferDomainToAnotherAwsAccountCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This operation updates the contact information for a particular domain. You must specify information for at least one contact:
* registrant, administrator, or technical.</p>
* <p>If the update is successful, this method returns an operation ID that you can use to track the progress and completion of the action.
* If the request is not completed successfully, the domain registrant will be notified by email.</p>
*/
public updateDomainContact(
args: UpdateDomainContactCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateDomainContactCommandOutput>;
public updateDomainContact(
args: UpdateDomainContactCommandInput,
cb: (err: any, data?: UpdateDomainContactCommandOutput) => void
): void;
public updateDomainContact(
args: UpdateDomainContactCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateDomainContactCommandOutput) => void
): void;
public updateDomainContact(
args: UpdateDomainContactCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateDomainContactCommandOutput) => void),
cb?: (err: any, data?: UpdateDomainContactCommandOutput) => void
): Promise<UpdateDomainContactCommandOutput> | void {
const command = new UpdateDomainContactCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This operation updates the specified domain contact's privacy setting. When privacy protection is enabled,
* contact information such as email address is replaced either with contact information for Amazon Registrar (for .com, .net, and .org
* domains) or with contact information for our registrar associate, Gandi.</p>
* <p>This operation affects only the contact information for the specified contact type (registrant, administrator, or tech).
* If the request succeeds, Amazon Route 53 returns an operation ID that you can use with
* <a href="https://docs.aws.amazon.com/Route53/latest/APIReference/API_domains_GetOperationDetail.html">GetOperationDetail</a>
* to track the progress and completion of the action. If the request doesn't complete successfully, the domain registrant will be notified by email.</p>
* <important>
* <p>By disabling the privacy service via API, you consent to the publication of the contact information provided for this domain
* via the public WHOIS database. You certify that you are the registrant of this domain name and have the authority to make this decision.
* You may withdraw your consent at any time by enabling privacy protection using either <code>UpdateDomainContactPrivacy</code> or the
* Route 53 console. Enabling privacy protection removes the contact information provided for this domain from the WHOIS database.
* For more information on our privacy practices, see
* <a href="https://aws.amazon.com/privacy/">https://aws.amazon.com/privacy/</a>.</p>
* </important>
*/
public updateDomainContactPrivacy(
args: UpdateDomainContactPrivacyCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateDomainContactPrivacyCommandOutput>;
public updateDomainContactPrivacy(
args: UpdateDomainContactPrivacyCommandInput,
cb: (err: any, data?: UpdateDomainContactPrivacyCommandOutput) => void
): void;
public updateDomainContactPrivacy(
args: UpdateDomainContactPrivacyCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateDomainContactPrivacyCommandOutput) => void
): void;
public updateDomainContactPrivacy(
args: UpdateDomainContactPrivacyCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateDomainContactPrivacyCommandOutput) => void),
cb?: (err: any, data?: UpdateDomainContactPrivacyCommandOutput) => void
): Promise<UpdateDomainContactPrivacyCommandOutput> | void {
const command = new UpdateDomainContactPrivacyCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This operation replaces the current set of name servers for the domain with the specified set of name servers.
* If you use Amazon Route 53 as your DNS service, specify the four name servers in the delegation set for the hosted zone for the domain.</p>
* <p>If successful, this operation returns an operation ID that you can use to track the progress and completion of the action.
* If the request is not completed successfully, the domain registrant will be notified by email.</p>
*/
public updateDomainNameservers(
args: UpdateDomainNameserversCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateDomainNameserversCommandOutput>;
public updateDomainNameservers(
args: UpdateDomainNameserversCommandInput,
cb: (err: any, data?: UpdateDomainNameserversCommandOutput) => void
): void;
public updateDomainNameservers(
args: UpdateDomainNameserversCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateDomainNameserversCommandOutput) => void
): void;
public updateDomainNameservers(
args: UpdateDomainNameserversCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateDomainNameserversCommandOutput) => void),
cb?: (err: any, data?: UpdateDomainNameserversCommandOutput) => void
): Promise<UpdateDomainNameserversCommandOutput> | void {
const command = new UpdateDomainNameserversCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>This operation adds or updates tags for a specified domain.</p>
* <p>All tag operations are eventually consistent; subsequent operations might not immediately represent all issued operations.</p>
*/
public updateTagsForDomain(
args: UpdateTagsForDomainCommandInput,
options?: __HttpHandlerOptions
): Promise<UpdateTagsForDomainCommandOutput>;
public updateTagsForDomain(
args: UpdateTagsForDomainCommandInput,
cb: (err: any, data?: UpdateTagsForDomainCommandOutput) => void
): void;
public updateTagsForDomain(
args: UpdateTagsForDomainCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: UpdateTagsForDomainCommandOutput) => void
): void;
public updateTagsForDomain(
args: UpdateTagsForDomainCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateTagsForDomainCommandOutput) => void),
cb?: (err: any, data?: UpdateTagsForDomainCommandOutput) => void
): Promise<UpdateTagsForDomainCommandOutput> | void {
const command = new UpdateTagsForDomainCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
/**
* <p>Returns all the domain-related billing records for the current AWS account for a specified period</p>
*/
public viewBilling(args: ViewBillingCommandInput, options?: __HttpHandlerOptions): Promise<ViewBillingCommandOutput>;
public viewBilling(args: ViewBillingCommandInput, cb: (err: any, data?: ViewBillingCommandOutput) => void): void;
public viewBilling(
args: ViewBillingCommandInput,
options: __HttpHandlerOptions,
cb: (err: any, data?: ViewBillingCommandOutput) => void
): void;
public viewBilling(
args: ViewBillingCommandInput,
optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ViewBillingCommandOutput) => void),
cb?: (err: any, data?: ViewBillingCommandOutput) => void
): Promise<ViewBillingCommandOutput> | void {
const command = new ViewBillingCommand(args);
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
} | the_stack |
import { isArray, isObject } from '@deepkit/core';
import { Database, DatabaseAdapter } from '@deepkit/orm';
import {
BrowserControllerInterface,
DatabaseCommit,
DatabaseInfo,
EntityPropertySeed,
EntityPropertySeedReference,
fakerFunctions,
FakerTypes,
getType,
QueryResult,
SeedDatabase
} from '@deepkit/orm-browser-api';
import { rpc } from '@deepkit/rpc';
import { SQLDatabaseAdapter } from '@deepkit/sql';
import { Logger, MemoryLoggerTransport } from '@deepkit/logger';
import { performance } from 'perf_hooks';
import { http, HttpQuery } from '@deepkit/http';
import { cast, getPartialSerializeFunction, isReferenceType, ReflectionClass, ReflectionKind, resolveClassType, serializer, Type } from '@deepkit/type';
@rpc.controller(BrowserControllerInterface)
export class OrmBrowserController implements BrowserControllerInterface {
constructor(protected databases: Database[]) {
}
public registerDatabase(...databases: Database[]) {
this.databases.push(...databases);
}
protected extractDatabaseInfo(db: Database): DatabaseInfo {
return new DatabaseInfo(db.name, (db.adapter as DatabaseAdapter).getName(), db.entityRegistry.entities.map(v => v.serializeType()));
}
protected getDb(dbName: string): Database {
for (const db of this.databases) {
if (db.name === dbName) return db;
}
throw new Error(`No database ${dbName} found`);
}
protected getDbEntity(dbName: string, entityName: string): [Database, ReflectionClass<any>] {
for (const db of this.databases) {
if (db.name === dbName) {
for (const entity of db.entityRegistry.entities) {
if (entity.name === entityName) return [db, entity];
}
}
}
throw new Error(`No entity ${entityName} for in database ${dbName}`);
}
@rpc.action()
getDatabases(): DatabaseInfo[] {
const databases: DatabaseInfo[] = [];
for (const db of this.databases) {
databases.push(this.extractDatabaseInfo(db));
}
return databases;
}
@rpc.action()
getDatabase(name: string): DatabaseInfo {
for (const db of this.databases) {
if (db.name === name) return this.extractDatabaseInfo(db);
}
throw new Error(`No database ${name} found`);
}
protected findDatabase(name: string): Database {
for (const db of this.databases) {
if (db.name === name) return db;
}
throw new Error(`No database ${name} found`);
}
@rpc.action()
async migrate(name: string): Promise<void> {
const db = this.findDatabase(name);
await db.migrate();
}
@rpc.action()
async resetAllTables(name: string): Promise<void> {
const db = this.findDatabase(name);
if (db.adapter instanceof SQLDatabaseAdapter) {
await db.adapter.createTables(db.entityRegistry);
}
}
@rpc.action()
async getFakerTypes(): Promise<FakerTypes> {
const res: FakerTypes = {};
const faker = require('faker');
for (const fn of fakerFunctions) {
const [p1, p2] = fn.split('.');
try {
const example = p2 ? (faker as any)[p1][p2]() : (faker as any)[p1]();
res[fn] = { example: example, type: getType(example) };
} catch (error) {
console.log(`warning: faker function not available ${fn}: ${error}`);
}
}
return res;
}
@rpc.action()
async getMigrations(name: string): Promise<{ [name: string]: { sql: string[], diff: string } }> {
const db = this.findDatabase(name);
if (db.adapter instanceof SQLDatabaseAdapter) {
return db.adapter.getMigrations(db.entityRegistry);
}
return {};
}
@rpc.action()
async seed(dbName: string, seed: SeedDatabase): Promise<void> {
const db = this.getDb(dbName);
db.logger.active = false;
try {
const session = db.createSession();
const added: { [entityName: string]: any[] } = {};
const assignReference: {
path: string,
entity: string,
properties: { [name: string]: EntityPropertySeed },
reference: EntityPropertySeedReference,
callback: (v: any) => any
}[] = [];
const faker = require('faker');
function fakerValue(path: string, fakerName: string): any {
const [p1, p2] = fakerName.split('.');
try {
return p2 ? (faker as any)[p1][p2]() : (faker as any)[p1]();
} catch (error) {
console.warn(`Could not fake ${path} via faker's ${fakerName}: ${error}`);
}
}
function fake(path: string, property: Type, propSeed: EntityPropertySeed, callback: (v: any) => any): any {
if (!propSeed.fake) {
if (propSeed.value !== undefined) callback(propSeed.value);
return;
}
if (isReferenceType(property)) {
// if (property.type !== 'class') throw new Error(`${path}: only class properties can be references`);
assignReference.push({
path,
entity: resolveClassType(property).getName(),
reference: propSeed.reference,
properties: propSeed.properties,
callback
});
return;
} else if (property.kind === ReflectionKind.array) {
const res: any[] = [];
if (!propSeed.array) return res;
const range = propSeed.array.max - propSeed.array.min;
for (let i = 0; i < Math.ceil(Math.random() * range); i++) {
fake(path + '.' + i, property.type, propSeed.array.seed, (v) => {
res.push(v);
});
}
return callback(res);
} else if (property.kind === ReflectionKind.class || property.kind === ReflectionKind.objectLiteral) {
const schema = ReflectionClass.from(property);
const item = schema.createDefaultObject();
for (const prop of schema.getProperties()) {
if (!propSeed.properties[prop.name]) continue;
fake(path + '.' + prop.name, prop.type, propSeed.properties[prop.name], (v) => {
item[prop.name] = v;
});
}
return callback(item);
} else if (property.kind === ReflectionKind.boolean) {
callback(Math.random() > 0.5);
} else if (property.kind === ReflectionKind.enum) {
const values = property.values;
callback(values[values.length * Math.random() | 0]);
} else {
return callback(fakerValue(path, propSeed.faker));
}
}
function create(entity: ReflectionClass<any>, properties: { [name: string]: EntityPropertySeed }) {
if (!added[entity.getName()]) added[entity.getName()] = [];
const item = entity.createDefaultObject();
for (const [propName, propSeed] of Object.entries(properties)) {
const property = entity.getProperty(propName);
fake(entity.getClassName() + '.' + propName, property.type, propSeed, (v) => {
item[property.name] = v;
});
}
for (const reference of entity.getReferences()) {
if (reference.isArray()) continue;
if (reference.isBackReference()) continue;
item[reference.name] = db.getReference(reference.getResolvedReflectionClass(), item[reference.name]);
}
session.add(item);
added[entity.getName()].push(item);
return item;
}
for (const [entityName, entitySeed] of Object.entries(seed.entities)) {
if (!entitySeed || !entitySeed.active) continue;
const entity = db.getEntity(entityName);
if (entitySeed.truncate) {
await db.query(entity).deleteMany();
}
for (let i = 0; i < entitySeed.amount; i++) {
create(entity, entitySeed.properties);
}
}
//assign references
const dbCandidates: { [entityName: string]: any[] } = {};
for (const ref of assignReference) {
const entity = db.getEntity(ref.entity);
let candidates = added[ref.entity] ||= [];
if (ref.reference === 'random') {
//note: I know there are faster ways, but this gets the job done for now
candidates = dbCandidates[ref.entity] ||= await db.query(entity).limit(1000).find();
}
if (!candidates.length) {
if (ref.reference === 'random') {
throw new Error(`Entity ${ref.entity} has no items in the database. Used in ${ref.path}.`);
}
if (ref.reference === 'random-seed') {
throw new Error(`Entity ${ref.entity} has no seeded items. Used in ${ref.path}.`);
}
}
if (ref.reference === 'create') {
ref.callback(create(entity, ref.properties));
} else {
ref.callback(candidates[candidates.length * Math.random() | 0]);
}
}
await session.commit();
} finally {
db.logger.active = true;
}
}
@http.GET('_orm-browser/query')
async httpQuery(dbName: HttpQuery<string>, entityName: HttpQuery<string>, query: HttpQuery<string>): Promise<QueryResult> {
const [, entity] = this.getDbEntity(dbName, entityName);
const res = await this.query(dbName, entityName, query);
if (isArray(res.result)) {
const partial = getPartialSerializeFunction(entity.type, serializer.deserializeRegistry);
res.result = res.result.map(v => partial(v));
}
return res;
}
@rpc.action()
async query(dbName: string, entityName: string, query: string): Promise<QueryResult> {
const res: QueryResult = {
executionTime: 0,
log: [],
result: undefined
};
const [db, entity] = this.getDbEntity(dbName, entityName);
const oldLogger = db.logger.logger;
const loggerTransport = new MemoryLoggerTransport;
db.logger.setLogger(new Logger([loggerTransport]));
try {
const fn = new Function(`return function(database, ${entity.getClassName()}) {return ${query}}`)();
const start = performance.now();
res.result = await fn(db, entity);
res.executionTime = performance.now() - start;
} catch (error) {
res.error = String(error);
} finally {
res.log = loggerTransport.messageStrings;
if (oldLogger) db.logger.setLogger(oldLogger);
}
return res;
}
@rpc.action()
async getCount(dbName: string, entityName: string, filter: { [name: string]: any }): Promise<number> {
const [db, entity] = this.getDbEntity(dbName, entityName);
return await db.query(entity).filter(filter).count();
}
@rpc.action()
async getItems(
dbName: string,
entityName: string,
filter: { [name: string]: any },
sort: { [name: string]: any },
limit: number,
skip: number
): Promise<{ items: any[], executionTime: number }> {
const [db, entity] = this.getDbEntity(dbName, entityName);
const start = performance.now();
const items = await db.query(entity).filter(filter).sort(sort).limit(limit).skip(skip).find();
return { items, executionTime: performance.now() - start };
}
@rpc.action()
async create(dbName: string, entityName: string): Promise<any> {
const [db, entity] = this.getDbEntity(dbName, entityName);
return entity.createDefaultObject();
}
@rpc.action()
async commit(commit: DatabaseCommit) {
// console.log(inspect(commit, false, 2133));
function isNewIdWrapper(value: any): value is { $___newId: number } {
return isObject(value) && '$___newId' in value;
}
for (const [dbName, c] of Object.entries(commit)) {
const db = this.getDb(dbName);
const session = db.createSession();
try {
const updates: Promise<any>[] = [];
for (const [entityName, removes] of Object.entries(c.removed)) {
const entity = db.getEntity(entityName);
const query = session.query(entity);
for (const remove of removes) {
updates.push(query.filter(db.getReference(entity, remove)).deleteOne());
}
}
const addedItems = new Map<number, any>();
for (const [entityName, added] of Object.entries(c.added)) {
const entity = db.getEntity(entityName);
const addedIds = c.addedIds[entityName];
for (let i = 0; i < added.length; i++) {
addedItems.set(addedIds[i], cast(added[i], undefined, undefined, undefined, entity.type));
}
}
for (const [entityName, ids] of Object.entries(c.addedIds)) {
const entity = db.getEntity(entityName);
const added = c.added[entityName];
for (let i = 0; i < added.length; i++) {
const id = ids[i];
const add = added[i];
const item = addedItems.get(id);
for (const reference of entity.getReferences()) {
if (reference.isBackReference()) continue;
//note, we need to operate on `added` from commit
// since `item` from addedItems got already converted and $___newId is lost.
const v = add[reference.name];
if (reference.isArray()) {
} else {
if (isNewIdWrapper(v)) {
//reference to not-yet existing record,
//so place the actual item in it, so the UoW accordingly saves
item[reference.name] = addedItems.get(v.$___newId);
} else {
//regular reference to already existing record,
//so convert to reference
item[reference.name] = db.getReference(reference.getResolvedReflectionClass(), item[reference.name]);
}
}
}
session.add(item);
}
}
await session.commit();
for (const [entityName, changes] of Object.entries(c.changed)) {
const entity = db.getEntity(entityName);
const query = session.query(entity);
for (const change of changes) {
//todo: convert $set from json to class
const $set = change.changes.$set;
if (!$set) continue;
for (const reference of entity.getReferences()) {
if (reference.isBackReference()) continue;
const v = $set[reference.name];
if (v === undefined) continue;
if (isNewIdWrapper(v)) {
$set[reference.name] = addedItems.get(v.$___newId);
} else {
$set[reference.name] = db.getReference(reference.getResolvedReflectionClass(), $set[reference.name]);
}
}
updates.push(query.filter(db.getReference(entity, change.pk)).patchOne(change.changes));
}
}
await Promise.all(updates);
} catch (error) {
//todo: rollback
throw error;
}
}
}
} | the_stack |
import { testExamples, render, waitFor, fireEvent, act } from '@test/utils';
import React, { useState } from 'react';
import { Select } from 'tdesign-react';
const { Option, OptionGroup } = Select;
// 测试组件代码 Example 快照
testExamples(__dirname);
describe('Select 组件测试', () => {
const selectSelector = '.t-select';
const popupSelector = '.t-popup';
const options = [
{
label: 'Apple',
value: 'apple',
},
{
label: 'Banana',
value: 'banana',
},
{
label: 'Orange',
value: 'orange',
},
];
const RemoteSearchSelect = ({ multiple }: { multiple?: boolean }) => {
const defaultOptions = [
{
label: 'Apple',
value: 'apple',
},
{
label: 'Banana',
value: 'banana',
},
{
label: 'Orange',
value: 'orange',
},
];
const [value, setValue] = useState();
const [loading, setLoading] = useState(false);
const [options, setOptions] = useState(defaultOptions);
const onChange = (value) => {
setValue(value);
};
const handleRemoteSearch = (search) => {
setLoading(true);
setTimeout(() => {
setLoading(false);
let options = [];
if (search) {
options = [
{
value: `${search}_test1`,
label: `${search}_test1`,
},
{
value: `${search}_test2`,
label: `${search}_test2`,
},
{
value: `${search}_test3`,
label: `${search}_test3`,
},
];
} else {
options = defaultOptions;
}
setOptions(options);
}, 300);
};
return (
<Select
filterable
multiple={multiple}
value={value}
onChange={onChange}
loading={loading}
onSearch={handleRemoteSearch}
>
{options.map((item) => (
<Option key={item.value} label={item.label} value={item.value} />
))}
</Select>
);
};
test('单选测试', async () => {
await act(async () => {
const SingleSelect = () => {
const [value, setValue] = useState('apple');
const onChange = (value) => {
setValue(value);
};
return (
<Select value={value} onChange={onChange} style={{ width: '40%' }}>
<Option key="apple" label="Apple" value="apple" />
<Option key="orange" label="Orange" value="orange" />
<Option key="banana" label="Banana" value="banana" />
</Select>
);
};
const { getByDisplayValue, getByText } = render(<SingleSelect />);
// 未点击input前,popup不出现
const popupElement1 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement1).toBeNull();
// 鼠标点击input,popup出现,且展示options
fireEvent.click(getByDisplayValue('Apple'));
const popupElement2 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement2).not.toBeNull();
expect(popupElement2).toHaveStyle({
display: 'block',
});
expect(popupElement2).toHaveTextContent('Apple');
expect(popupElement2).toHaveTextContent('Orange');
expect(popupElement2).toHaveTextContent('Banana');
// 点击Banana选项,input展示该选项,且popup消失
fireEvent.click(getByText('Banana'));
const selectElement = await waitFor(() => document.querySelector('.t-input__inner'));
expect(selectElement).toHaveValue('Banana');
setTimeout(async () => {
const popupElement3 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement3).not.toBeNull();
expect(popupElement3).toHaveStyle({
display: 'none',
});
}, 0);
});
});
test('多选测试', async () => {
await act(async () => {
const MultipleSelect = () => {
const [value, setValue] = useState([{ label: 'Apple', value: 'apple' }]);
const onChange = (value) => {
setValue(value);
};
return (
<Select value={value} onChange={onChange} multiple style={{ width: '40%' }} valueType="object">
<Option key="apple" label="Apple" value="apple" />
<Option key="orange" label="Orange" value="orange" />
<Option key="banana" label="Banana" value="banana" />
</Select>
);
};
const { getByText } = render(<MultipleSelect />);
// 未点击input前,popup不出现
const popupElement1 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement1).toBeNull();
// 鼠标点击input,popup出现,且展示options
fireEvent.click(getByText('Apple'));
const popupElement2 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement2).not.toBeNull();
expect(popupElement2).toHaveStyle({
display: 'block',
});
expect(popupElement2).toHaveTextContent('Apple');
expect(popupElement2).toHaveTextContent('Orange');
expect(popupElement2).toHaveTextContent('Banana');
// 点击Banana和Orange选项,input展示Apple、Banana、Orange选项,popup依然展示
fireEvent.click(getByText('Banana'));
// @fix: This could be because the text is broken up by multiple elements.
fireEvent.click(getByText('Orange'));
const selectElement = await waitFor(() => document.querySelector(selectSelector));
expect(selectElement).toHaveTextContent('Apple');
expect(selectElement).toHaveTextContent('Banana');
expect(selectElement).toHaveTextContent('Orange');
const popupElement3 = await waitFor(() => document.querySelector(selectSelector));
expect(popupElement3).not.toBeNull();
expect(popupElement3).toHaveStyle({
display: 'block',
});
});
});
test('分组选择器测试', async () => {
const OptionGroupSelect = () => {
const [value, setValue] = useState('apple');
const onChange = (value) => {
setValue(value);
};
return (
<Select value={value} onChange={onChange} style={{ width: '40%' }}>
<OptionGroup label="Fruit">
{options.map((item, index) => (
<Option label={item.label} value={item.value} key={index} />
))}
</OptionGroup>
</Select>
);
};
await act(async () => {
const { getByText, getByDisplayValue } = render(<OptionGroupSelect />);
// 未点击input前,popup不出现
const popupElement1 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement1).toBeNull();
// 鼠标点击input,popup出现,且展示options
const selectElement = await waitFor(() => document.querySelector(selectSelector));
fireEvent.click(getByDisplayValue('Apple'));
const popupElement2 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement2).not.toBeNull();
expect(popupElement2).toHaveStyle({
display: 'block',
});
expect(popupElement2).toHaveTextContent('Fruit');
expect(popupElement2).toHaveTextContent('Apple');
expect(popupElement2).toHaveTextContent('Orange');
expect(popupElement2).toHaveTextContent('Banana');
// 点击Banana选项,input展示该选项,且popup消失
fireEvent.click(getByText('Banana'));
expect(document.querySelector('.t-input__inner')).toHaveValue('Banana');
setTimeout(async () => {
const popupElement3 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement3).not.toBeNull();
expect(popupElement3).toHaveStyle({
display: 'none',
});
}, 0);
});
});
test('可过滤选择器测试', async () => {
await act(async () => {
const FilterableSelect = () => {
const [value, setValue] = useState();
const onChange = (value) => {
setValue(value);
};
return (
<Select filterable value={value} onChange={onChange}>
{options.map((item, index) => (
<Option key={index} label={item.label} value={item.value} />
))}
</Select>
);
};
render(<FilterableSelect />);
// 未点击input前,popup不出现
const popupElement1 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement1).toBeNull();
// 输入“an”, input展示“an”,popup展示Banana和Orange选项
const input = await waitFor(() => document.querySelector('input'));
fireEvent.change(input, { target: { value: 'an' } });
setTimeout(async () => {
expect(input).toHaveTextContent('an');
const popupElement2 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement2).not.toBeNull();
expect(popupElement2).toHaveStyle({
display: 'block',
});
expect(popupElement2).toHaveTextContent('Orange');
expect(popupElement2).toHaveTextContent('Banana');
}, 0);
// 输入“an1”, input展示“an1”,popup展示“无数据”
const input1 = await waitFor(() => document.querySelector('input'));
fireEvent.change(input1, { target: { value: 'an1' } });
setTimeout(async () => {
expect(input).toHaveTextContent('an1');
const popupElement2 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement2).not.toBeNull();
expect(popupElement2).toHaveStyle({
display: 'block',
});
expect(popupElement2).toHaveTextContent('无数据');
}, 0);
});
});
test('远程搜索测试', async () => {
await act(async () => {
render(<RemoteSearchSelect />);
// 未点击input前,popup不出现
const popupElement1 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement1).toBeNull();
// 输入“123”, input展示“123”,popup展示123_test1、123_test2、123_test3
const input = await waitFor(() => document.querySelector('input'));
fireEvent.change(input, { target: { value: '123' } });
setTimeout(async () => {
expect(input).toHaveTextContent('123');
const popupElement2 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement2).not.toBeNull();
expect(popupElement2).toHaveStyle({
display: 'block',
});
expect(popupElement2).toHaveTextContent('123_test1');
expect(popupElement2).toHaveTextContent('123_test2');
expect(popupElement2).toHaveTextContent('123_test3');
}, 0);
// 清空input,popup展示Apple、Orange、Banana
fireEvent.change(input, { target: { value: '' } });
setTimeout(async () => {
expect(input).toHaveTextContent('');
const popupElement2 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement2).not.toBeNull();
expect(popupElement2).toHaveStyle({
display: 'block',
});
expect(popupElement2).toHaveTextContent('Apple');
expect(popupElement2).toHaveTextContent('Orange');
expect(popupElement2).toHaveTextContent('Banana');
}, 0);
});
});
test('远程搜索多选测试', async () => {
await act(async () => {
const { getByText } = render(<RemoteSearchSelect multiple />);
// 未点击input前,popup不出现
const popupElement1 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement1).toBeNull();
// 输入“123”, input展示“123”,popup展示123_test1、123_test2、123_test3
const input = await waitFor(() => document.querySelector('input'));
fireEvent.change(input, { target: { value: '123' } });
setTimeout(async () => {
expect(input).toHaveTextContent('123');
const popupElement2 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement2).toHaveTextContent('123_test1');
expect(popupElement2).toHaveTextContent('123_test2');
expect(popupElement2).toHaveTextContent('123_test3');
// 选择123_test1,展示对应tag
fireEvent.click(getByText('123_test1'));
const selectElement = await waitFor(() => document.querySelector(selectSelector));
expect(selectElement).toHaveTextContent('123_test1');
}, 0);
// 清空input,popup展示Apple、Orange、Banana
fireEvent.change(input, { target: { value: '' } });
setTimeout(async () => {
const popupElement2 = await waitFor(() => document.querySelector(popupSelector));
expect(popupElement2).toHaveTextContent('Apple');
expect(popupElement2).toHaveTextContent('Orange');
expect(popupElement2).toHaveTextContent('Banana');
fireEvent.click(getByText('Apple'));
// 已选的123_test1仍然保留
const selectElement = await waitFor(() => document.querySelector(selectSelector));
expect(selectElement).toHaveTextContent('123_test1');
expect(selectElement).toHaveTextContent('Apple');
}, 0);
});
});
}); | the_stack |
declare module Microsoft.Maps {
/**
* An enumeration of different GeoXML file formats.
* @requires The Microsoft.Maps.GeoXml module.
*/
export enum GeoXmlFormat {
/** A KML XML file format. */
kml,
/** A GPX XML file format. */
gpx,
/** A GeoRSS XML file using ATOM format. */
geoRss
}
/**
* An enumeration of the different compressed formats that XML can be outputted as.
* @requires The Microsoft.Maps.GeoXml module.
*/
export enum GeoXmlCompressedFormat {
/** XML data compressed into a Base64 Data URI. */
base64,
/** XML data compressed into a Blob. */
blob,
/** XML data compressed into an ArrayBuffer. */
arrayBuffer
}
/**
* A GeoXML result data set that is returned when reading a spatial XML file.
*/
export interface IGeoXmlDataSet {
/** An array of shapes that are in the XML document. */
shapes?: IPrimitive[];
/**
* An array of layers that are in the XML document.
* In shapes in KML that are in a child documents and folders of the main document or folder are grouped together in a data Layer.
* KML also supports GroundOverlay.
*/
layers?: (Layer | GroundOverlay)[];
/**
* An array of screen overlays that have been parsed from a KML file.
*/
screenOverlays?: KmlScreenOverlay[];
/**
* Summary metadata provided at the document level of the XML feed data set.
*/
summary?: IGeoXmlSummaryMetadata;
/**
* Statistics about the content and processing time of a XML feed.
*/
stats?: IGeoXmlStats;
}
/**
* Options used to customize how a GeoXmlLayer renders.
*/
export interface IGeoXmlLayerOptions extends IGeoXmlReadOptions {
/** A boolean indicating if the map should automatically upate the view when a data set is loaded. Default: true */
autoUpdateMapView?: boolean;
/** Options used to customize how the default infobox renders. */
infoboxOptions?: Microsoft.Maps.IInfoboxOptions;
/** A boolean indicating if infoboxes should automatically appear when shapes clicked. Default: false */
suppressInfoboxes?: boolean;
/** A boolean indicating if the layer is visible or not. Default: true */
visible?: boolean;
}
/**
* Options that customize how XML files are read and parsed.
*/
export interface IGeoXmlReadOptions {
/** Specifies if KML ScreenOverlays should be read or ignored. Default: true */
allowKmlScreenOverlays?: boolean;
/**
* A callback function that is triggered when an error occurs when reading an XML document.
*/
error?: (msg: string) => void;
/**
* Specifies wether the individual waypoint data of a GPX Route or Track should be captured.
* If set to true, the shape will have a metadata.waypoints property that is an array of
* pushpins that contains the details of each waypoint along the track. Default: false
*/
captureGpxPathWaypoints?: boolean;
/** The default styles to apply to shapes that don't have a defined style in the XML. */
defaultStyles?: IStylesOptions;
/** Specifies if shapes visible tags should be used to set the visible property of it's equivalent Bing Maps shape. Default: true */
ignoreVisibility?: boolean;
/**
* The maximium number of network links that a single KML file can have. Default: 10.
*/
maxNetworkLinks?: number;
/**
* The maximium depth of network links in a KML file. Default: 3
* Example: when set to 3; file1 links to file2 which links to file3 but won't open links in file3.
*/
maxNetworkLinkDepth?: number;
/** Indicates if the pushpin title should be displayed on the map if a valid title or name value exits in the shapes metadata. Default: true */
setPushpinTitles?: boolean;
}
/**
* Statistics about the content and processing time of a XML feed.
*/
export interface IGeoXmlStats {
/** Number of Microsoft.Maps.Pushpins objects in the XML feed. */
numPushpins: number;
/** Number of Microsoft.Maps.Polylines objects in the XML feed. */
numPolylines: number;
/** Number of Microsoft.Maps.Polygons objects in the XML feed. */
numPolygons: number;
/** Number of Microsoft.Maps.Location objects in the XML feed. */
numLocations: number;
/** Number of Ground Overlays in the XML feed. */
numGroundOverlays: number;
/** Number of Screen Overlays in the XML feed. */
numScreenOverlays: number;
/** The number of network links in the XML feed. */
numNetworkLinks: number;
/** The number of characters in the XML feed. */
fileSize: number;
/** The amount of time in ms it took to process the XML feed. */
processingTime: number;
}
/**
* Summary metadata provided at the document level of the XML feed data set.
*/
export interface IGeoXmlSummaryMetadata {
/** The title or name of the content of the XML document. */
title?: string;
/** The description of the content of the XML document. */
description?: string;
/** The bounds of all the shapes and layers in the XML document. */
bounds?: LocationRect;
/** Any additional metadata that the XML document may have. i.e. atom:author */
metadata?: IDictionary<any>;
}
/**
* Options that are used to customize how the GeoXml writes XML.
*/
export interface IGeoXmlWriteOptions {
/** The characters to use to create an indent in the XML data. Default: \t */
indentChars?: string;
/** The characters to use to create a new line in the XML data. Default: \r\n */
newLineChars?: string;
/** A boolean indicating if the generated XML should be use new lines and indents to make the generated nicely formatted. Default: true */
prettyPrint?: boolean;
/** A boolean indicating if Location and LocationRect values should be rounded off to 6 decimals. Default: false */
roundLocations?: boolean;
/**
* A boolean indicating if the shapes should be made valid before writing. If set to true, will use the
* Geometry.makeValid function of the SpatialMath module. Default: false
*/
validate?: boolean;
/** The XML format to write the shapes to. Default: Kml */
xmlFormat?: GeoXmlFormat;
}
/**
* The options for customizing screen overlays.
*/
export interface IKmlScreenOverlayOptions {
/** A boolean indicating if the screen overlay can be displayed above or beow the navigaiton bar. Default: false */
belowNavigationBar?: boolean;
/** The visibility of the screen overlay. Default: true */
visible?: boolean;
}
/**
* Overlays HTML elements winthin the map container that are above the map.
* This is useful when adding logos, attributions or legends to the map.
* This class is only used by the KML reader and not meant to be used on its own.
* @requires The Microsoft.Maps.GeoXml module.
*/
export class KmlScreenOverlay {
/** Optional property to store any additional metadata for this overlay. */
metadata: any;
/**
* @constructor
* @param htmlElement The new htmlElement to set for the overlay.
* @param options The options to customize the screen overlay.
*/
constructor(htmlElement?: string | HTMLElement, options?: IKmlScreenOverlayOptions);
/**
* Clears the screen overlay.
*/
public clear(): void;
/**
* Gets a boolean indicating if the screen overlay is displayed above or below the navigation bar.
* @returns A boolean indicating if the screen overlay is displayed above or below the navigation bar.
*/
public getBelowNavigationBar(): boolean;
/**
* Gets the html element of this screen overlay.
* @returns the htmlElement of this overlay.
*/
public getHtmlElement(): HTMLElement;
/**
* Returns the map that this overlay is attached to.
* @returns The map that this overlay is attached to.
*/
public getMap(): Map;
/**
* Gets a boolean indicating if the screen overlay is visible or not.
* @returns A boolean indicating if the screen overlay is visible or not.
*/
public getVisible(): boolean;
/**
* Updates the html element of this screen overlay.
* @param htmlElement The new htmlElement to set for the overlay.
*/
public setHtmlElement(htmlElement: string | HTMLElement): void;
/**
* Sets the options to customize the screen overlay.
* @param options The options to customize the screen overlay.
*/
public setOptions(options: IKmlScreenOverlayOptions): void;
/**
* Sets whether the overlay is visible or not.
* @param value A value indicating if the overlay should be displayed or not.
*/
public setVisible(visible: boolean): void;
}
/**
* A static class that contains functions for reading and writing geospatial XML data.
* @requires The Microsoft.Maps.GeoXml module.
*/
export module GeoXml {
/**
* Takes a geospatial XML string or a ArrayBuffer and parses the XML data into Bing Maps shapes.
* @param xml The XML as a string or ArrayBuffer to read.
* @param options The read options.
*/
export function read(xml: string | ArrayBuffer, options: IGeoXmlReadOptions): IGeoXmlDataSet;
/**
* Takes an URL to an XML or zipped XML file and parses the XML data into Bing Maps shapes.
* @param xml The URL to XML data to read.
* @param options The read options.
* @param callback The callback function that consumes the parsed out GeoXml data.
*/
export function readFromUrl(urlString: string, options: IGeoXmlReadOptions, callback: (data: IGeoXmlDataSet) => void): void;
/**
* Writes Bing Maps shape data as a geospatial XML string in the specified format.
* @param shapes The Bing Maps shapes, or map to retrieve shapes from, to write.
* @param options A set of options that customize how the XML is writen.
*/
export function write(shapes: Map | IPrimitive | IPrimitive[] | Layer | GroundOverlay[] | IGeoXmlDataSet, options?: IGeoXmlWriteOptions): string;
/**
* Writes Bing Maps shape data to a geospatial XML file embedded in a compressed file.
* @param shapes The Bing Maps shapes, or map to retrieve shapes from, to write.
* @param compressFormat The compressed file format to use.
* @param options A set of options that customize how the XML is writen.
*/
export function writeCompressed(shapes: Map | IPrimitive | IPrimitive[] | Layer | GroundOverlay[] | IGeoXmlDataSet, compressFormat?: GeoXmlCompressedFormat, options?: IGeoXmlWriteOptions): string | ArrayBuffer | Blob;
}
/**
* A layer that loads and renders geospatial XML data on the map.
* @requires The Microsoft.Maps.GeoXml module.
*/
export class GeoXmlLayer extends Microsoft.Maps.CustomOverlay {
/** Optional property to store any additional metadata for this layer. */
metadata: any;
/**
* @constructor
* @param dataSource The XML as a string, URL or ArrayBuffer to read.
* @param isUrl Whether the dataSource provided is an URL. Default = true
* @param options The options used to render the layer.
*/
constructor(dataSource?: string | ArrayBuffer, isUrl?: boolean, options?: IGeoXmlLayerOptions);
/**
* Removes all the data in the layer.
*/
public clear(): void;
/**
* Cleans up any resources this object is consuming.
*/
public dispose(): void;
/**
* Returns the data source used by the layer.
* @returns The data source used by the layer.
*/
public getDataSource(): string | ArrayBuffer;
/**
* Returns the data set that ws extracted from the data source.
* @returns The data set that ws extracted from the data source.
*/
public getDataSet(): IGeoXmlDataSet;
/**
* Returns the options used by the GeoXmlLayer.
* @returns The options used by the GeoXmlLayer.
*/
public getOptions(): IGeoXmlLayerOptions;
/**
* Gets a value indicating whether the layer is visible or not.
* @returns A boolean indicating if the layer is visible or not.
*/
public getVisible(): boolean;
/**
* Sets the data source to render in the GeoXmlLayer.
* @param dataSource The data source to render in the GeoXmlLayer.
* @param isUrl Whether the dataSource provided is an URL. Default = true
*/
public setDataSource(dataSource: string | ArrayBuffer, isUrl: boolean): void;
/**
* Sets the options used for loading and rendering data into the GeoXmlLayer.
* @param options The options to use when loading and rendering data into the GeoXmlLayer.
*/
public setOptions(options: IGeoXmlLayerOptions): void;
/**
* Sets whether the layer is visible or not.
* @param value A value indicating if the layer should be displayed or not.
*/
public setVisible(visible: boolean): void;
}
export module Events {
/////////////////////////////////////
/// addHandler Definitions
////////////////////////////////////
/**
* Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method.
* @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc.
* @param eventName The type of event to attach. Supported Events:
* click, dblclick, mousedown, mouseout, mouseover, mouseup, rightclick
* @param handler The callback function to handle the event when triggered.
* @returns The handler id.
*/
export function addHandler(target: GeoXmlLayer, eventName: string, handler: (eventArg?: IMouseEventArgs) => void): IHandlerId;
/////////////////////////////////////
/// addOne Definitions
////////////////////////////////////
/**
* Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached.
* @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc.
* @param eventName The type of event to attach. Supported Events:
* click, dblclick, mousedown, mouseout, mouseover, mouseup, rightclick
* @param handler The callback function to handle the event when triggered.
*/
export function addOne(target: GeoXmlLayer, eventName: string, handler: (eventArg?: IMouseEventArgs) => void): void;
/////////////////////////////////////
/// addThrottledHandler Definitions
////////////////////////////////////
/**
* Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter.
* @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc.
* @param eventName The type of event to attach. Supported Events:
* click, dblclick, mousedown, mouseout, mouseover, mouseup, rightclick
* @param handler The callback function to handle the event when triggered.
* @returns The handler id.
*/
export function addThrottledHandler(target: GeoXmlLayer, eventName: string, handler: (eventArg?: IMouseEventArgs) => void): IHandlerId;
}
} | the_stack |
'use strict';
import { syscall } from '../browser-node/syscall';
const ENOSYS = 38;
const AT_FDCWD = -0x64;
// not implemented
function sys_ni_syscall(cb: Function, trap: number): void {
console.log('ni syscall ' + trap);
debugger;
setTimeout(cb, 0, [-1, 0, -ENOSYS]);
}
// rusage size: 144
function sys_wait4(cb: Function, trap: number, pid: number, wstatus: any, options: number, rusage: Uint8Array): void {
let done = function(pid: number, wstatusIn: number, rusage: any = null): void {
if (pid > 0)
wstatus.$set(wstatusIn);
// TODO: rusage
cb([pid, 0, 0]);
};
syscall.wait4(pid, options, done);
}
function sys_kill(cb: Function, trap: number, pid: number, sig: number): void {
let done = function(err: any): void {
cb([err ? -1 : 0, 0, err ? -err : 0]);
};
syscall.kill(pid, sig, done);
}
function sys_getpid(cb: Function, trap: number): void {
let done = function(err: any, pid: number): void {
cb([pid, 0, 0]);
};
syscall.getpid(done);
}
function sys_getppid(cb: Function, trap: number): void {
let done = function(err: any, pid: number): void {
cb([pid, 0, 0]);
};
syscall.getppid(done);
}
let zeroBuf = new Uint8Array(0);
function sys_spawn(
cb: Function,
trap: number,
dir: any,
argv0: any,
argv: any,
envv: any,
fds: number[]): void {
if (!(dir instanceof Uint8Array))
dir = zeroBuf;
if (!(argv0 instanceof Uint8Array))
argv0 = zeroBuf;
argv = argv.filter((x: any): boolean => x instanceof Uint8Array);
envv = envv.filter((x: any): boolean => x instanceof Uint8Array);
let done = function(err: any, pid: number): void {
cb([err ? -1 : pid, 0, err ? err : 0]);
};
// FIXME: use apply to get around string/Uint8Array typing issues for now
syscall.spawn(dir, argv0, argv, envv, fds, done);
}
function sys_pipe2(cb: Function, trap: number, fds: Int32Array, flags: number): void {
let done = function(err: any, fd1: number, fd2: number): void {
if (!err) {
fds[0] = fd1;
fds[1] = fd2;
}
cb([err ? err : 0, 0, err ? err : 0]);
};
syscall.pipe2(flags, done);
}
function sys_getcwd(cb: Function, trap: number, path: Uint8Array, len: number): void {
let done = function(p: Uint8Array): void {
path.subarray(0, len).set(p);
let nullPos = p.length;
if (nullPos >= path.byteLength)
nullPos = path.byteLength;
// XXX: Go expects the kernel to return a null
// terminated string, hence the null write and +1
// below.
path[nullPos] = 0;
cb([p.length+1, 0, 0]);
};
syscall.getcwd(done);
}
function sys_chdir(cb: Function, trap: number, path: any): void {
let done = function(err: number): void {
cb([err ? -1 : 0, 0, err ? -err : 0]);
};
let len = path.length;
if (len && path[path.length-1] === 0)
len--;
syscall.chdir(path.subarray(0, len), done);
}
function sys_ioctl(cb: Function, trap: number, fd: number, request: any, argp: any): void {
let done = function(err: any, buf: Uint8Array): void {
if (!err && argp.byteLength !== undefined)
argp.set(buf);
cb([err ? err : buf.byteLength, 0, err ? -1 : 0]);
};
syscall.ioctl(fd, request, argp.byteLength, done);
}
function sys_getdents64(cb: Function, trap: number, fd: number, buf: Uint8Array, len: number): void {
let done = function(err: any, dents: Uint8Array): void {
if (dents)
buf.set(dents);
cb([err, 0, err < 0 ? -1 : 0]);
};
syscall.getdents(fd, len, done);
}
function sys_read(cb: Function, trap: number, fd: number, readArray: any, readLen: any): void {
let done = function(err: any, dataLen: number, data: Uint8Array): void {
if (!err) {
for (let i = 0; i < dataLen; i++)
readArray[i] = data[i];
}
cb([dataLen, 0, err ? -1 : 0]);
};
syscall.pread(fd, readLen, -1, done);
}
function sys_write(cb: Function, trap: number, fd: number, buf: ArrayBuffer, blen: number): void {
let done = function(err: any, len: number): void {
cb([len, 0, err ? -1 : 0]);
};
syscall.pwrite(fd, new Uint8Array(buf, 0, blen), -1, done);
}
function sys_stat(cb: Function, trap: number, path: any, buf: Uint8Array): void {
let done = function(err: any, stats: Uint8Array): void {
if (!err)
buf.set(stats);
cb([err ? -1 : 0, 0, err ? -1 : 0]);
};
let len = path.length;
if (len && path[path.length-1] === 0)
len--;
syscall.stat(path.subarray(0, len), done);
}
function sys_lstat(cb: Function, trap: number, path: any, buf: Uint8Array): void {
let done = function(err: any, stats: any): void {
if (!err)
buf.set(stats);
cb([err ? -1 : 0, 0, err ? -1 : 0]);
};
let len = path.length;
if (len && path[path.length-1] === 0)
len--;
syscall.lstat(path.subarray(0, len), done);
}
function sys_fstat(cb: Function, trap: number, fd: number, buf: Uint8Array): void {
let done = function(err: any, stats: Uint8Array): void {
if (!err)
buf.set(stats);
cb([err ? -1 : 0, 0, err ? -1 : 0]);
};
syscall.fstat(fd, done);
}
function sys_readlinkat(cb: Function, trap: number, fd: number, path: Uint8Array, buf: Uint8Array, blen: number): void {
// TODO: we only support AT_FDCWD
if (fd !== AT_FDCWD) {
console.log('openat: TODO: we only support AT_FDCWD');
setTimeout(cb, 0, [-1, 0, -1]);
return;
}
let done = function(err: any, linkString: Uint8Array): void {
if (!err)
buf.set(linkString);
cb([err ? -1 : linkString.length, 0, err ? -1 : 0]);
};
let len = path.length;
if (len && path[path.length-1] === 0)
len--;
syscall.readlink(path.subarray(0, len), done);
}
function sys_openat(cb: Function, trap: number, fd: number, path: Uint8Array, flags: number, mode: number): void {
// coerce to signed int, to match our constants
fd = fd|0;
if (fd !== AT_FDCWD) {
console.log('openat: TODO: we only support AT_FDCWD');
setTimeout(cb, 0, [-1, 0, -1]);
return;
}
let done = function(err: any, fd: number): void {
cb([fd, 0, err ? -1 : 0]);
};
let len = path.length;
if (len && path[path.length-1] === 0)
len--;
syscall.open(path.subarray(0, len), flags, mode, done);
}
function sys_close(cb: Function, trap: number, fd: number): void {
let done = function(err: any): void {
cb([err ? -1 : 0, 0, err ? -1 : 0]);
};
syscall.close(fd, done);
}
function sys_exit_group(cb: Function, trap: number, code: number): void {
syscall.exit(code);
}
function sys_socket(cb: Function, trap: number, domain: number, type: number, protocol: number): void {
let done = function(err: any, fd: number): void {
cb([err ? -1 : fd, 0, err ? -1 : 0]);
};
syscall.socket(domain, type, protocol, done);
}
function sys_bind(cb: Function, trap: number, fd: number, buf: Uint8Array, blen: number): void {
let done = function(err: any): void {
cb([err ? -1 : 0, 0, err ? -1 : 0]);
};
syscall.bind(fd, buf.subarray(0, blen), done);
}
function sys_listen(cb: Function, trap: number, fd: number, backlog: number): void {
let done = function(err: any): void {
cb([err ? -1 : 0, 0, err ? -1 : 0]);
};
syscall.listen(fd, backlog, done);
}
function sys_connect(cb: Function, trap: number, fd: number, buf: Uint8Array, blen: number): void {
let done = function(err: any): void {
cb([err ? -1 : 0, 0, err ? -1 : 0]);
};
syscall.connect(fd, buf.subarray(0, blen), done);
}
function sys_getsockname(cb: Function, trap: number, fd: number, buf: Uint8Array, lenp: any): void {
let done = function(err: any, sockInfo: Uint8Array): void {
if (!err) {
buf.set(sockInfo);
lenp.$set(sockInfo.byteLength);
}
cb([err ? -1 : 0, 0, err ? -1 : 0]);
};
syscall.getsockname(fd, done);
}
function sys_getpeername(cb: Function, trap: number, fd: number, buf: Uint8Array, lenp: any): void {
let done = function(err: any, sockInfo: Uint8Array): void {
if (!err) {
buf.set(sockInfo);
lenp.$set(sockInfo.byteLength);
}
cb([err ? -1 : 0, 0, err ? -1 : 0]);
};
syscall.getpeername(fd, done);
}
function sys_accept4(cb: Function, trap: number, fd: number, buf: Uint8Array, lenp: any): void {
let done = function(err: any, fd: number, sockInfo: Uint8Array): void {
buf.set(sockInfo);
lenp.$set(sockInfo.length);
cb([err ? -1 : fd, 0, err ? -1 : 0]);
};
syscall.accept(fd, done);
}
function sys_setsockopt(cb: Function, trap: number): void {
// console.log('FIXME: implement setsockopt');
setTimeout(cb, 0, [0, 0, 0]);
}
export const syscallTbl = [
sys_read, // 0 read
sys_write, // 1 write
sys_ni_syscall, // 2 open
sys_close, // 3 close
sys_stat, // 4 stat
sys_fstat, // 5 fstat
sys_lstat, // 6 lstat
sys_ni_syscall, // 7 poll
sys_ni_syscall, // 8 lseek
sys_ni_syscall, // 9 mmap
sys_ni_syscall, // 10 mprotect
sys_ni_syscall, // 11 munmap
sys_ni_syscall, // 12 brk
sys_ni_syscall, // 13 rt_sigaction
sys_ni_syscall, // 14 rt_sigprocmask
sys_ni_syscall, // 15 rt_sigreturn
sys_ioctl, // 16 ioctl
sys_ni_syscall, // 17 pread64
sys_ni_syscall, // 18 pwrite64
sys_ni_syscall, // 19 readv
sys_ni_syscall, // 20 writev
sys_ni_syscall, // 21 access
sys_ni_syscall, // 22 pipe
sys_ni_syscall, // 23 select
sys_ni_syscall, // 24 sched_yield
sys_ni_syscall, // 25 mremap
sys_ni_syscall, // 26 msync
sys_ni_syscall, // 27 mincore
sys_ni_syscall, // 28 madvise
sys_ni_syscall, // 29 shmget
sys_ni_syscall, // 30 shmat
sys_ni_syscall, // 31 shmctl
sys_ni_syscall, // 32 dup
sys_ni_syscall, // 33 dup2
sys_ni_syscall, // 34 pause
sys_ni_syscall, // 35 nanosleep
sys_ni_syscall, // 36 getitimer
sys_ni_syscall, // 37 alarm
sys_ni_syscall, // 38 setitimer
sys_getpid, // 39 getpid
sys_ni_syscall, // 40 sendfile
sys_socket, // 41 socket
sys_connect, // 42 connect
sys_ni_syscall, // 43 accept
sys_ni_syscall, // 44 sendto
sys_ni_syscall, // 45 recvfrom
sys_ni_syscall, // 46 sendmsg
sys_ni_syscall, // 47 recvmsg
sys_ni_syscall, // 48 shutdown
sys_bind, // 49 bind
sys_listen, // 50 listen
sys_getsockname, // 51 getsockname
sys_getpeername, // 52 getpeername
sys_ni_syscall, // 53 socketpair
sys_setsockopt, // 54 setsockopt
sys_ni_syscall, // 55 getsockopt
sys_ni_syscall, // 56 clone
sys_ni_syscall, // 57 fork
sys_ni_syscall, // 58 vfork
sys_ni_syscall, // 59 execve
sys_ni_syscall, // 60 exit
sys_wait4, // 61 wait4
sys_kill, // 62 kill
sys_ni_syscall, // 63 uname
sys_ni_syscall, // 64 semget
sys_ni_syscall, // 65 semop
sys_ni_syscall, // 66 semctl
sys_ni_syscall, // 67 shmdt
sys_ni_syscall, // 68 msgget
sys_ni_syscall, // 69 msgsnd
sys_ni_syscall, // 70 msgrcv
sys_ni_syscall, // 71 msgctl
sys_ni_syscall, // 72 fcntl
sys_ni_syscall, // 73 flock
sys_ni_syscall, // 74 fsync
sys_ni_syscall, // 75 fdatasync
sys_ni_syscall, // 76 truncate
sys_ni_syscall, // 77 ftruncate
sys_ni_syscall, // 78 getdents
sys_getcwd, // 79 getcwd
sys_chdir, // 80 chdir
sys_ni_syscall, // 81 fchdir
sys_ni_syscall, // 82 rename
sys_ni_syscall, // 83 mkdir
sys_ni_syscall, // 84 rmdir
sys_ni_syscall, // 85 creat
sys_ni_syscall, // 86 link
sys_ni_syscall, // 87 unlink
sys_ni_syscall, // 88 symlink
sys_ni_syscall, // 89 readlink
sys_ni_syscall, // 90 chmod
sys_ni_syscall, // 91 fchmod
sys_ni_syscall, // 92 chown
sys_ni_syscall, // 93 fchown
sys_ni_syscall, // 94 lchown
sys_ni_syscall, // 95 umask
sys_ni_syscall, // 96 gettimeofday
sys_ni_syscall, // 97 getrlimit
sys_ni_syscall, // 98 getrusage
sys_ni_syscall, // 99 sysinfo
sys_ni_syscall, // 100 times
sys_ni_syscall, // 101 ptrace
sys_ni_syscall, // 102 getuid
sys_ni_syscall, // 103 syslog
sys_ni_syscall, // 104 getgid
sys_ni_syscall, // 105 setuid
sys_ni_syscall, // 106 setgid
sys_ni_syscall, // 107 geteuid
sys_ni_syscall, // 108 getegid
sys_ni_syscall, // 109 setpgid
sys_getppid, // 110 getppid
sys_ni_syscall, // 111 getpgrp
sys_ni_syscall, // 112 setsid
sys_ni_syscall, // 113 setreuid
sys_ni_syscall, // 114 setregid
sys_ni_syscall, // 115 getgroups
sys_ni_syscall, // 116 setgroups
sys_ni_syscall, // 117 setresuid
sys_ni_syscall, // 118 getresuid
sys_ni_syscall, // 119 setresgid
sys_ni_syscall, // 120 getresgid
sys_ni_syscall, // 121 getpgid
sys_ni_syscall, // 122 setfsuid
sys_ni_syscall, // 123 setfsgid
sys_ni_syscall, // 124 getsid
sys_ni_syscall, // 125 capget
sys_ni_syscall, // 126 capset
sys_ni_syscall, // 127 rt_sigpending
sys_ni_syscall, // 128 rt_sigtimedwait
sys_ni_syscall, // 129 rt_sigqueueinfo
sys_ni_syscall, // 130 rt_sigsuspend
sys_ni_syscall, // 131 sigaltstack
sys_ni_syscall, // 132 utime
sys_ni_syscall, // 133 mknod
sys_ni_syscall, // 134 uselib
sys_ni_syscall, // 135 personality
sys_ni_syscall, // 136 ustat
sys_ni_syscall, // 137 statfs
sys_ni_syscall, // 138 fstatfs
sys_ni_syscall, // 139 sysfs
sys_ni_syscall, // 140 getpriority
sys_ni_syscall, // 141 setpriority
sys_ni_syscall, // 142 sched_setparam
sys_ni_syscall, // 143 sched_getparam
sys_ni_syscall, // 144 sched_setscheduler
sys_ni_syscall, // 145 sched_getscheduler
sys_ni_syscall, // 146 sched_get_priority_max
sys_ni_syscall, // 147 sched_get_priority_min
sys_ni_syscall, // 148 sched_rr_get_interval
sys_ni_syscall, // 149 mlock
sys_ni_syscall, // 150 munlock
sys_ni_syscall, // 151 mlockall
sys_ni_syscall, // 152 munlockall
sys_ni_syscall, // 153 vhangup
sys_ni_syscall, // 154 modify_ldt
sys_ni_syscall, // 155 pivot_root
sys_ni_syscall, // 156 _sysctl
sys_ni_syscall, // 157 prctl
sys_ni_syscall, // 158 arch_prctl
sys_ni_syscall, // 159 adjtimex
sys_ni_syscall, // 160 setrlimit
sys_ni_syscall, // 161 chroot
sys_ni_syscall, // 162 sync
sys_ni_syscall, // 163 acct
sys_ni_syscall, // 164 settimeofday
sys_ni_syscall, // 165 mount
sys_ni_syscall, // 166 umount2
sys_ni_syscall, // 167 swapon
sys_ni_syscall, // 168 swapoff
sys_ni_syscall, // 169 reboot
sys_ni_syscall, // 170 sethostname
sys_ni_syscall, // 171 setdomainname
sys_ni_syscall, // 172 iopl
sys_ni_syscall, // 173 ioperm
sys_ni_syscall, // 174 create_module
sys_ni_syscall, // 175 init_module
sys_ni_syscall, // 176 delete_module
sys_ni_syscall, // 177 get_kernel_syms
sys_ni_syscall, // 178 query_module
sys_ni_syscall, // 179 quotactl
sys_ni_syscall, // 180 nfsservctl
sys_ni_syscall, // 181 getpmsg
sys_ni_syscall, // 182 putpmsg
sys_ni_syscall, // 183 afs_syscall
sys_ni_syscall, // 184 tuxcall
sys_ni_syscall, // 185 security
sys_ni_syscall, // 186 gettid
sys_ni_syscall, // 187 readahead
sys_ni_syscall, // 188 setxattr
sys_ni_syscall, // 189 lsetxattr
sys_ni_syscall, // 190 fsetxattr
sys_ni_syscall, // 191 getxattr
sys_ni_syscall, // 192 lgetxattr
sys_ni_syscall, // 193 fgetxattr
sys_ni_syscall, // 194 listxattr
sys_ni_syscall, // 195 llistxattr
sys_ni_syscall, // 196 flistxattr
sys_ni_syscall, // 197 removexattr
sys_ni_syscall, // 198 lremovexattr
sys_ni_syscall, // 199 fremovexattr
sys_ni_syscall, // 200 tkill
sys_ni_syscall, // 201 time
sys_ni_syscall, // 202 futex
sys_ni_syscall, // 203 sched_setaffinity
sys_ni_syscall, // 204 sched_getaffinity
sys_ni_syscall, // 205 set_thread_area
sys_ni_syscall, // 206 io_setup
sys_ni_syscall, // 207 io_destroy
sys_ni_syscall, // 208 io_getevents
sys_ni_syscall, // 209 io_submit
sys_ni_syscall, // 210 io_cancel
sys_ni_syscall, // 211 get_thread_area
sys_ni_syscall, // 212 lookup_dcookie
sys_ni_syscall, // 213 epoll_create
sys_ni_syscall, // 214 epoll_ctl_old
sys_ni_syscall, // 215 epoll_wait_old
sys_ni_syscall, // 216 remap_file_pages
sys_getdents64, // 217 getdents64
sys_ni_syscall, // 218 set_tid_address
sys_ni_syscall, // 219 restart_syscall
sys_ni_syscall, // 220 semtimedop
sys_ni_syscall, // 221 fadvise64
sys_ni_syscall, // 222 timer_create
sys_ni_syscall, // 223 timer_settime
sys_ni_syscall, // 224 timer_gettime
sys_ni_syscall, // 225 timer_getoverrun
sys_ni_syscall, // 226 timer_delete
sys_ni_syscall, // 227 clock_settime
sys_ni_syscall, // 228 clock_gettime
sys_ni_syscall, // 229 clock_getres
sys_ni_syscall, // 230 clock_nanosleep
sys_exit_group, // 231 exit_group
sys_ni_syscall, // 232 epoll_wait
sys_ni_syscall, // 233 epoll_ctl
sys_ni_syscall, // 234 tgkill
sys_ni_syscall, // 235 utimes
sys_ni_syscall, // 236 vserver
sys_ni_syscall, // 237 mbind
sys_ni_syscall, // 238 set_mempolicy
sys_ni_syscall, // 239 get_mempolicy
sys_ni_syscall, // 240 mq_open
sys_ni_syscall, // 241 mq_unlink
sys_ni_syscall, // 242 mq_timedsend
sys_ni_syscall, // 243 mq_timedreceive
sys_ni_syscall, // 244 mq_notify
sys_ni_syscall, // 245 mq_getsetattr
sys_ni_syscall, // 246 kexec_load
sys_ni_syscall, // 247 waitid
sys_ni_syscall, // 248 add_key
sys_ni_syscall, // 249 request_key
sys_ni_syscall, // 250 keyctl
sys_ni_syscall, // 251 ioprio_set
sys_ni_syscall, // 252 ioprio_get
sys_ni_syscall, // 253 inotify_init
sys_ni_syscall, // 254 inotify_add_watch
sys_ni_syscall, // 255 inotify_rm_watch
sys_ni_syscall, // 256 migrate_pages
sys_openat, // 257 openat
sys_ni_syscall, // 258 mkdirat
sys_ni_syscall, // 259 mknodat
sys_ni_syscall, // 260 fchownat
sys_ni_syscall, // 261 futimesat
sys_ni_syscall, // 262 newfstatat
sys_ni_syscall, // 263 unlinkat
sys_ni_syscall, // 264 renameat
sys_ni_syscall, // 265 linkat
sys_ni_syscall, // 266 symlinkat
sys_readlinkat, // 267 readlinkat
sys_ni_syscall, // 268 fchmodat
sys_ni_syscall, // 269 faccessat
sys_ni_syscall, // 270 pselect6
sys_ni_syscall, // 271 ppoll
sys_ni_syscall, // 272 unshare
sys_ni_syscall, // 273 set_robust_list
sys_ni_syscall, // 274 get_robust_list
sys_ni_syscall, // 275 splice
sys_ni_syscall, // 276 tee
sys_ni_syscall, // 277 sync_file_range
sys_ni_syscall, // 278 vmsplice
sys_ni_syscall, // 279 move_pages
sys_ni_syscall, // 280 utimensat
sys_ni_syscall, // 281 epoll_pwait
sys_ni_syscall, // 282 signalfd
sys_ni_syscall, // 283 timerfd_create
sys_ni_syscall, // 284 eventfd
sys_ni_syscall, // 285 fallocate
sys_ni_syscall, // 286 timerfd_settime
sys_ni_syscall, // 287 timerfd_gettime
sys_accept4, // 288 accept4
sys_ni_syscall, // 289 signalfd4
sys_ni_syscall, // 290 eventfd2
sys_ni_syscall, // 291 epoll_create1
sys_ni_syscall, // 292 dup3
sys_pipe2, // 293 pipe2
sys_ni_syscall, // 294 inotify_init1
sys_ni_syscall, // 295 preadv
sys_ni_syscall, // 296 pwritev
sys_ni_syscall, // 297 rt_tgsigqueueinfo
sys_ni_syscall, // 298 perf_event_open
sys_ni_syscall, // 299 recvmmsg
sys_ni_syscall, // 300 fanotify_init
sys_ni_syscall, // 301 fanotify_mark
sys_ni_syscall, // 302 prlimit64
sys_ni_syscall, // 303 name_to_handle_at
sys_ni_syscall, // 304 open_by_handle_at
sys_ni_syscall, // 305 clock_adjtime
sys_ni_syscall, // 306 syncfs
sys_ni_syscall, // 307 sendmmsg
sys_ni_syscall, // 308 setns
sys_ni_syscall, // 309 getcpu
sys_ni_syscall, // 310 process_vm_readv
sys_ni_syscall, // 311 process_vm_writev
sys_ni_syscall, // 312 kcmp
sys_ni_syscall, // 313 finit_module
sys_ni_syscall, // 314 sched_setattr
sys_ni_syscall, // 315 sched_getattr
sys_ni_syscall, // 316 renameat2
sys_ni_syscall, // 317 seccomp
sys_ni_syscall, // 318 getrandom
sys_ni_syscall, // 319 memfd_create
sys_ni_syscall, // 320 kexec_file_load
sys_ni_syscall, // 321 bpf
sys_ni_syscall, // 322 execveat
sys_ni_syscall, // 323 userfaultfd
sys_ni_syscall, // 324 membarrier
sys_ni_syscall, // 325 mlock2
// Browsix-specific syscalls
sys_spawn, // 326 spawn
]; | the_stack |
import {assert} from '@esm-bundle/chai';
import {
msg,
str,
configureLocalization,
configureTransformLocalization,
LocaleModule,
LOCALE_STATUS_EVENT,
LocaleStatusEventDetail,
updateWhenLocaleChanges,
localized,
} from '../lit-localize.js';
import {Deferred} from '../internal/deferred.js';
import {html, render, LitElement} from 'lit';
import {customElement} from 'lit/decorators.js';
suite('runtime localization configuration', () => {
let container: HTMLElement;
let lastLoadLocaleResponse = new Deferred<LocaleModule>();
setup(() => {
container = document.createElement('div');
document.body.appendChild(container);
});
teardown(async () => {
document.body.removeChild(container);
// Back to the source locale.
await setLocale('en');
});
// We can only call configureLocalization once.
const {getLocale, setLocale} = configureLocalization({
sourceLocale: 'en',
targetLocales: ['es-419'],
loadLocale: async () => {
// This lets us easily control the timing of locale module loading from
// our tests.
lastLoadLocaleResponse = new Deferred();
return await lastLoadLocaleResponse.promise;
},
});
const spanishModule = {
templates: {
greeting: html`<b>Hola Mundo</b>`,
parameterized: html`<b>Hola ${0}</b>`,
strOrderChange: str`2:${1} 1:${0}`,
htmlOrderChange: html`<b>2:${1} 1:${0}</b>`,
},
};
suite('basics', () => {
test('setLocale with invalid locale throws', () => {
assert.throws(() => {
setLocale('xxx');
}, 'Invalid locale code');
});
test('calling configureLocalization again throws', () => {
assert.throws(() => {
configureLocalization({
sourceLocale: 'en',
targetLocales: ['es-419'],
loadLocale: () => new Promise<LocaleModule>(() => undefined),
});
});
});
test('calling configureTransformLocalization throws', () => {
assert.throws(() => {
configureTransformLocalization({
sourceLocale: 'en',
});
});
});
test('renders regular template in English', () => {
render(msg(html`<b>Hello World</b>`, {id: 'greeting'}), container);
assert.equal(container.textContent, 'Hello World');
});
test('renders regular template in Spanish', async () => {
const loaded = setLocale('es-419');
lastLoadLocaleResponse.resolve(spanishModule);
await loaded;
render(msg(html`<b>Hello World</b>`, {id: 'greeting'}), container);
assert.equal(container.textContent, 'Hola Mundo');
});
test('renders parameterized template in English', () => {
const name = 'friend';
render(
msg(html`Hello ${name}`, {
id: 'parameterized',
}),
container
);
assert.equal(container.textContent, 'Hello friend');
});
test('renders parameterized string template in English', () => {
const renderAndTest = () => {
const x = msg(str`1:${'A'} 2:${'B'}`, {id: 'strOrderChange'});
render(x, container);
assert.equal(container.textContent, '1:A 2:B');
};
renderAndTest();
});
test('renders parameterized template in Spanish', async () => {
const loaded = setLocale('es-419');
lastLoadLocaleResponse.resolve(spanishModule);
await loaded;
const name = 'friend';
render(
msg(html`Hello ${name}`, {
id: 'parameterized',
}),
container
);
assert.equal(container.textContent, 'Hola friend');
});
test('renders parameterized string template where expression order changed', async () => {
const loaded = setLocale('es-419');
lastLoadLocaleResponse.resolve(spanishModule);
await loaded;
const renderAndTest = () => {
render(msg(str`1:${'A'} 2:${'B'}`, {id: 'strOrderChange'}), container);
assert.equal(container.textContent, '2:B 1:A');
};
renderAndTest();
// Render again in case we lost our value ordering somehow.
renderAndTest();
});
test('renders parameterized HTML template where expression order changed', async () => {
const loaded = setLocale('es-419');
lastLoadLocaleResponse.resolve(spanishModule);
await loaded;
const renderAndTest = () => {
render(
msg(html`<b>1:${'A'} 2:${'B'}</b>`, {id: 'htmlOrderChange'}),
container
);
assert.equal(container.textContent, '2:B 1:A');
};
renderAndTest();
// Render again in case we lost our value ordering somehow. This is a
// possible source of bugs, because we do an in-place update of
// TemplateResult values, so it's easy to lose track of the original order
// if not careful.
renderAndTest();
});
});
suite('auto ID', () => {
const autoSpanishModule = {
templates: {
s8c0ec8d1fb9e6e32: 'Hola Mundo!',
s00ad08ebae1e0f74: str`Hola ${0}!`,
h3c44aff2d5f5ef6b: html`Hola <b>Mundo</b>!`,
h82ccc38d4d46eaa9: html`Hola <b>${0}</b>!`,
},
};
setup(async () => {
const loaded = setLocale('es-419');
lastLoadLocaleResponse.resolve(autoSpanishModule);
await loaded;
});
test('renders string template', () => {
render(msg(`Hello World!`), container);
assert.equal(container.textContent, 'Hola Mundo!');
});
test('renders parameterized string template', () => {
const name = 'Friend';
render(msg(str`Hello ${name}!`), container);
assert.equal(container.textContent, 'Hola Friend!');
});
test('renders html template', () => {
render(msg(html`Hello <b>World</b>!`), container);
assert.equal(container.textContent, 'Hola Mundo!');
});
test('renders parameterized html template', () => {
const name = 'Friend';
render(msg(html`Hello <b>${name}</b>!`), container);
assert.equal(container.textContent, 'Hola Friend!');
});
});
suite('updateWhenLocaleChanges', () => {
class XGreeter1 extends LitElement {
constructor() {
super();
updateWhenLocaleChanges(this);
}
render() {
return msg(html`<b>Hello World</b>`, {id: 'greeting'});
}
}
customElements.define('x-greeter-1', XGreeter1);
test('initially renders in English', async () => {
const greeter = document.createElement('x-greeter-1') as XGreeter1;
container.appendChild(greeter);
await greeter.updateComplete;
assert.equal(greeter.shadowRoot?.textContent, 'Hello World');
});
test('renders in Spanish after locale change', async () => {
const greeter = document.createElement('x-greeter-1') as XGreeter1;
container.appendChild(greeter);
await greeter.updateComplete;
const loaded = setLocale('es-419');
lastLoadLocaleResponse.resolve(spanishModule);
await loaded;
await greeter.updateComplete;
assert.equal(greeter.shadowRoot?.textContent, 'Hola Mundo');
});
});
suite('@localized decorator', () => {
@localized()
@customElement('x-greeter-2')
class XGreeter2 extends LitElement {
render() {
return msg(html`<b>Hello World</b>`, {id: 'greeting'});
}
}
test('initially renders in English', async () => {
const greeter = document.createElement('x-greeter-2') as XGreeter2;
container.appendChild(greeter);
await greeter.updateComplete;
assert.equal(greeter.shadowRoot?.textContent, 'Hello World');
});
test('renders in Spanish after locale change', async () => {
const greeter = document.createElement('x-greeter-2') as XGreeter2;
container.appendChild(greeter);
await greeter.updateComplete;
const loaded = setLocale('es-419');
lastLoadLocaleResponse.resolve(spanishModule);
await loaded;
await greeter.updateComplete;
assert.equal(greeter.shadowRoot?.textContent, 'Hola Mundo');
});
});
suite('@localized decorator (reversed decorator order)', () => {
@customElement('x-greeter-3')
@localized()
class XGreeter3 extends LitElement {
render() {
return msg(html`<b>Hello World</b>`, {id: 'greeting'});
}
}
test('initially renders in English', async () => {
const greeter = document.createElement('x-greeter-3') as XGreeter3;
container.appendChild(greeter);
await greeter.updateComplete;
assert.equal(greeter.shadowRoot?.textContent, 'Hello World');
});
test('renders in Spanish after locale change', async () => {
const greeter = document.createElement('x-greeter-3') as XGreeter3;
container.appendChild(greeter);
await greeter.updateComplete;
const loaded = setLocale('es-419');
lastLoadLocaleResponse.resolve(spanishModule);
await loaded;
await greeter.updateComplete;
assert.equal(greeter.shadowRoot?.textContent, 'Hola Mundo');
});
});
suite('events', () => {
let eventLog: LocaleStatusEventDetail[] = [];
setup(() => {
window.addEventListener(LOCALE_STATUS_EVENT, eventHandler);
});
teardown(async () => {
// Confirm that there were no lingering events.
await new Promise((resolve) => setTimeout(resolve));
assertEventLogEqualsAndFlush([]);
window.removeEventListener(LOCALE_STATUS_EVENT, eventHandler);
});
function assertEventLogEqualsAndFlush(expected: LocaleStatusEventDetail[]) {
try {
assert.deepEqual(eventLog, expected);
} catch (e) {
// Chai gives fairly useless error messages when deep comparing objects.
console.log('expected: ' + JSON.stringify(expected, null, 4));
console.log('actual: ' + JSON.stringify(eventLog, null, 4));
throw e;
} finally {
eventLog = [];
}
}
function eventHandler(event: WindowEventMap[typeof LOCALE_STATUS_EVENT]) {
eventLog.push(event.detail);
}
function assertEnglish() {
assert.equal(getLocale(), 'en');
render(msg(html`<b>Hello World</b>`, {id: 'greeting'}), container);
assert.equal(container.textContent, 'Hello World');
}
function assertSpanish() {
assert.equal(getLocale(), 'es-419');
render(msg(html`<b>Hello World</b>`, {id: 'greeting'}), container);
assert.equal(container.textContent, 'Hola Mundo');
}
test('A -> B', async () => {
const loaded = setLocale('es-419');
assertEventLogEqualsAndFlush([
{
status: 'loading',
loadingLocale: 'es-419',
},
]);
assertEnglish();
lastLoadLocaleResponse.resolve(spanishModule);
await loaded;
assertEventLogEqualsAndFlush([
{
status: 'ready',
readyLocale: 'es-419',
},
]);
assertSpanish();
});
test('A -> A', async () => {
await setLocale('en');
assertEventLogEqualsAndFlush([]);
assertEnglish();
});
test('A -> B -> B', async () => {
const loaded = setLocale('es-419');
assertEventLogEqualsAndFlush([
{
status: 'loading',
loadingLocale: 'es-419',
},
]);
assertEnglish();
lastLoadLocaleResponse.resolve(spanishModule);
await loaded;
assertEventLogEqualsAndFlush([
{
status: 'ready',
readyLocale: 'es-419',
},
]);
assertSpanish();
await setLocale('es-419');
assertEventLogEqualsAndFlush([]);
});
test('A -> B -> A', async () => {
const loaded1 = setLocale('es-419');
assertEventLogEqualsAndFlush([
{
status: 'loading',
loadingLocale: 'es-419',
},
]);
assertEnglish();
lastLoadLocaleResponse.resolve(spanishModule);
await loaded1;
assertEventLogEqualsAndFlush([
{
status: 'ready',
readyLocale: 'es-419',
},
]);
assertSpanish();
const loaded2 = setLocale('en');
assertEventLogEqualsAndFlush([
{
status: 'loading',
loadingLocale: 'en',
},
]);
assertSpanish();
await loaded2;
assertEventLogEqualsAndFlush([
{
status: 'ready',
readyLocale: 'en',
},
]);
assertEnglish();
});
test('race: A -> B -> A', async () => {
const spanishLoaded = setLocale('es-419');
const spanishResponse = lastLoadLocaleResponse;
assertEventLogEqualsAndFlush([
{
status: 'loading',
loadingLocale: 'es-419',
},
]);
assertEnglish();
const englishLoaded = setLocale('en');
assertEventLogEqualsAndFlush([
{
status: 'loading',
loadingLocale: 'en',
},
]);
assertEnglish();
// Resolving the Spanish module after we've switched back to English
// should be a no-op, because the Spanish request is now stale.
spanishResponse.resolve(spanishModule);
// Note both promises resolve.
await englishLoaded;
await spanishLoaded;
assertEventLogEqualsAndFlush([
{
status: 'ready',
readyLocale: 'en',
},
]);
assertEnglish();
});
test('race: A -> B -> A -> B', async () => {
const spanishLoaded1 = setLocale('es-419');
const spanishResponse1 = lastLoadLocaleResponse;
assertEventLogEqualsAndFlush([
{
status: 'loading',
loadingLocale: 'es-419',
},
]);
assertEnglish();
const englishLoaded = setLocale('en');
assertEventLogEqualsAndFlush([
{
status: 'loading',
loadingLocale: 'en',
},
]);
assertEnglish();
const spanishLoaded2 = setLocale('es-419');
const spanishResponse2 = lastLoadLocaleResponse;
assertEventLogEqualsAndFlush([
{
status: 'loading',
loadingLocale: 'es-419',
},
]);
assertEnglish();
// Resolving the first Spanish locale request should be a no-op, even
// though it's for the same locale code, because that request is now
// stale.
spanishResponse1.resolve(spanishModule);
await new Promise((resolve) => setTimeout(resolve));
assertEventLogEqualsAndFlush([]);
assertEnglish();
// But the second one should work.
spanishResponse2.resolve(spanishModule);
// Note all promises resolve.
await spanishLoaded1;
await englishLoaded;
await spanishLoaded2;
assertEventLogEqualsAndFlush([
{
status: 'ready',
readyLocale: 'es-419',
},
]);
assertSpanish();
});
test('error: A -> B', async () => {
const spanishLoaded = setLocale('es-419');
lastLoadLocaleResponse.reject(new Error('Some error'));
let error;
try {
await spanishLoaded;
} catch (e) {
error = e;
}
assert.isDefined(error);
assert.equal((error as Error).message, 'Some error');
assertEventLogEqualsAndFlush([
{
status: 'loading',
loadingLocale: 'es-419',
},
{
status: 'error',
errorLocale: 'es-419',
errorMessage: 'Error: Some error',
},
]);
assertEnglish();
});
});
}); | the_stack |
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { TranslateService } from '@ngx-translate/core';
import { ArtemisTestModule } from '../../test.module';
import { Router } from '@angular/router';
import { of, Subscription } from 'rxjs';
import { RouterTestingModule } from '@angular/router/testing';
import { JhiLanguageHelper } from 'app/core/language/language.helper';
import { AccountService } from 'app/core/auth/account.service';
import { MockAccountService } from '../../helpers/mocks/service/mock-account.service';
import { ModelingAssessmentDashboardComponent } from 'app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-dashboard.component';
import { MockRouter } from '../../helpers/mocks/mock-router';
import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';
import { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';
import { LocalStorageService, SessionStorageService } from 'ngx-webstorage';
import { ExerciseType } from 'app/entities/exercise.model';
import { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';
import { CourseManagementService } from 'app/course/manage/course-management.service';
import { ModelingSubmissionService } from 'app/exercises/modeling/participate/modeling-submission.service';
import { ModelingExercise } from 'app/entities/modeling-exercise.model';
import { AssessmentType } from 'app/entities/assessment-type.model';
import { ModelingAssessmentService } from 'app/exercises/modeling/assess/modeling-assessment.service';
import { SortService } from 'app/shared/service/sort.service';
import { routes } from 'app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-editor.route';
import { HttpResponse } from '@angular/common/http';
const route = { params: of({ courseId: 3, exerciseId: 22 }) };
const course = { id: 1 };
const modelingExercise = {
id: 22,
course,
type: ExerciseType.MODELING,
studentAssignedTeamIdComputed: true,
assessmentType: AssessmentType.SEMI_AUTOMATIC,
numberOfAssessmentsOfCorrectionRounds: [],
secondCorrectionEnabled: true,
};
const modelingExerciseOfExam = {
id: 23,
exerciseGroup: { id: 111, exam: { id: 112, course } },
type: ExerciseType.MODELING,
studentAssignedTeamIdComputed: true,
assessmentType: AssessmentType.SEMI_AUTOMATIC,
numberOfAssessmentsOfCorrectionRounds: [],
secondCorrectionEnabled: true,
};
const modelingSubmission = { id: 1, submitted: true, results: [{ id: 10, assessor: { id: 20, guidedTourSettings: [], internal: true } }] };
describe('ModelingAssessmentDashboardComponent', () => {
let component: ModelingAssessmentDashboardComponent;
let fixture: ComponentFixture<ModelingAssessmentDashboardComponent>;
let exerciseService: ExerciseService;
let courseService: CourseManagementService;
let modelingSubmissionService: ModelingSubmissionService;
let modelingAssessmentService: ModelingAssessmentService;
let sortService: SortService;
let exerciseFindSpy: jest.SpyInstance;
let courseFindSpy: jest.SpyInstance;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [RouterTestingModule.withRoutes([routes[2]]), ArtemisTestModule],
declarations: [ModelingAssessmentDashboardComponent],
providers: [
JhiLanguageHelper,
{ provide: Router, useValue: route },
{ provide: LocalStorageService, useClass: MockSyncStorage },
{ provide: SessionStorageService, useClass: MockSyncStorage },
{ provide: TranslateService, useClass: MockTranslateService },
{ provide: Router, useClass: MockRouter },
{ provide: AccountService, useClass: MockAccountService },
],
})
.overrideTemplate(ModelingAssessmentDashboardComponent, '')
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(ModelingAssessmentDashboardComponent);
component = fixture.componentInstance;
exerciseService = fixture.debugElement.injector.get(ExerciseService);
courseService = fixture.debugElement.injector.get(CourseManagementService);
modelingSubmissionService = fixture.debugElement.injector.get(ModelingSubmissionService);
modelingAssessmentService = fixture.debugElement.injector.get(ModelingAssessmentService);
sortService = fixture.debugElement.injector.get(SortService);
exerciseFindSpy = jest.spyOn(exerciseService, 'find').mockReturnValue(of(new HttpResponse({ body: modelingExercise })));
courseFindSpy = jest.spyOn(courseService, 'find').mockReturnValue(of(new HttpResponse({ body: course })));
fixture.detectChanges();
});
});
afterEach(() => {
component.ngOnDestroy();
});
it('should set parameters and call functions on init', () => {
// setup
const getSubmissionsSpy = jest.spyOn(component, 'getSubmissions');
const registerChangeInResultsSpy = jest.spyOn(component, 'registerChangeInResults');
// test for init values
expect(component).toBeTruthy();
expect(component.submissions).toEqual([]);
expect(component.reverse).toEqual(false);
expect(component.predicate).toEqual('id');
expect(component.filteredSubmissions).toEqual([]);
// call
component.ngOnInit();
// check
expect(getSubmissionsSpy).toHaveBeenCalled();
expect(registerChangeInResultsSpy).toHaveBeenCalled();
expect(courseFindSpy).toHaveBeenCalled();
expect(exerciseFindSpy).toHaveBeenCalled();
expect(component.course).toEqual(course);
expect(component.exercise).toEqual(modelingExercise as ModelingExercise);
});
it('should get Submissions', () => {
// test getSubmissions
const modelingSubmissionServiceSpy = jest
.spyOn(modelingSubmissionService, 'getModelingSubmissionsForExerciseByCorrectionRound')
.mockReturnValue(of(new HttpResponse({ body: [modelingSubmission] })));
// call
component.ngOnInit();
// check
expect(modelingSubmissionServiceSpy).toHaveBeenCalledWith(modelingExercise.id, { submittedOnly: true });
expect(component.submissions).toEqual([modelingSubmission]);
expect(component.filteredSubmissions).toEqual([modelingSubmission]);
});
it('should update filtered submissions', () => {
// setup
component.ngOnInit();
component.updateFilteredSubmissions([modelingSubmission]);
// check
expect(component.filteredSubmissions).toEqual([modelingSubmission]);
});
it('should cancelAssessment', fakeAsync(() => {
// test cancelAssessment
const windowSpy = jest.spyOn(window, 'confirm').mockReturnValue(true);
const getSubmissionsSpy = jest.spyOn(component, 'getSubmissions');
const modelAssServiceCancelAssSpy = jest.spyOn(modelingAssessmentService, 'cancelAssessment').mockReturnValue(of(undefined));
// call
component.cancelAssessment(modelingSubmission);
tick();
// check
expect(modelAssServiceCancelAssSpy).toHaveBeenCalledWith(modelingSubmission.id);
expect(windowSpy).toHaveBeenCalled();
expect(getSubmissionsSpy).toHaveBeenCalled();
}));
it('should sortRows', () => {
// test cancelAssessment
const sortServiceSpy = jest.spyOn(sortService, 'sortByProperty');
component.filteredSubmissions = [modelingSubmission];
component.predicate = 'predicate';
component.reverse = false;
component.sortRows();
expect(sortServiceSpy).toHaveBeenCalledWith([modelingSubmission], 'predicate', false);
});
it('ngOnDestroy', () => {
// setup
component.paramSub = new Subscription();
const paramSubSpy = jest.spyOn(component.paramSub, 'unsubscribe');
// call
component.ngOnDestroy();
// check
expect(paramSubSpy).toHaveBeenCalled();
});
describe('shouldGetAssessmentLink', () => {
it('should get assessment link for exam exercise', () => {
const submissionId = 7;
const participationId = 2;
component.exercise = modelingExercise;
component.exerciseId = modelingExercise.id!;
component.courseId = modelingExercise.course!.id!;
expect(component.getAssessmentLink(participationId, submissionId)).toEqual([
'/course-management',
component.exercise.course!.id!.toString(),
'modeling-exercises',
component.exercise.id!.toString(),
'submissions',
submissionId.toString(),
'assessment',
]);
});
it('should get assessment link for normal exercise', () => {
const submissionId = 8;
const participationId = 3;
component.exercise = modelingExerciseOfExam;
component.exerciseId = modelingExerciseOfExam.id!;
component.courseId = modelingExerciseOfExam.exerciseGroup!.exam!.course!.id!;
component.examId = modelingExerciseOfExam.exerciseGroup!.exam!.id!;
component.exerciseGroupId = modelingExerciseOfExam.exerciseGroup!.id!;
expect(component.getAssessmentLink(participationId, submissionId)).toEqual([
'/course-management',
component.exercise.exerciseGroup!.exam!.course!.id!.toString(),
'exams',
component.exercise.exerciseGroup!.exam!.id!.toString(),
'exercise-groups',
component.exercise.exerciseGroup!.id!.toString(),
'modeling-exercises',
component.exercise.id!.toString(),
'submissions',
submissionId.toString(),
'assessment',
]);
});
});
}); | the_stack |
import { StacksTransaction, deserializeTransaction } from '../src/transaction';
import {
createSingleSigSpendingCondition,
SingleSigSpendingCondition,
createMultiSigSpendingCondition,
MultiSigSpendingCondition,
SponsoredAuthorization,
createStandardAuth,
createSponsoredAuth
} from '../src/authorization';
import { TokenTransferPayload, createTokenTransferPayload } from '../src/payload';
import { STXPostCondition, createSTXPostCondition } from '../src/postcondition';
import {
createLPList,
createStandardPrincipal
} from '../src/types';
import {
DEFAULT_CHAIN_ID,
TransactionVersion,
AnchorMode,
PostConditionMode,
AuthType,
FungibleConditionCode,
AddressHashMode,
} from '../src/constants';
import {
createStacksPrivateKey,
pubKeyfromPrivKey,
publicKeyToString
} from '../src/keys';
import { TransactionSigner } from '../src/signer';
import fetchMock from 'jest-fetch-mock';
import { BufferReader } from '../src/bufferReader';
import { standardPrincipalCV } from '../src/clarity';
beforeEach(() => {
fetchMock.resetMocks();
});
test('STX token transfer transaction serialization and deserialization', () => {
const transactionVersion = TransactionVersion.Testnet;
const chainId = DEFAULT_CHAIN_ID;
const anchorMode = AnchorMode.Any;
const postConditionMode = PostConditionMode.Deny;
const address = 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159';
const recipient = createStandardPrincipal(address);
const recipientCV = standardPrincipalCV(address);
const amount = 2500000;
const memo = 'memo (not included';
const payload = createTokenTransferPayload(recipientCV, amount, memo);
const addressHashMode = AddressHashMode.SerializeP2PKH;
const nonce = 0;
const fee = 0;
const pubKey = '03ef788b3830c00abe8f64f62dc32fc863bc0b2cafeb073b6c8e1c7657d9c2c3ab';
const secretKey = 'edf9aee84d9b7abc145504dde6726c64f369d37ee34ded868fabd876c26570bc01';
const spendingCondition = createSingleSigSpendingCondition(addressHashMode, pubKey, nonce, fee);
const authType = AuthType.Standard;
const authorization = createStandardAuth(spendingCondition);
const postCondition = createSTXPostCondition(
recipient,
FungibleConditionCode.GreaterEqual,
0
);
const postConditions = createLPList([postCondition]);
const transaction = new StacksTransaction(
transactionVersion,
authorization,
payload,
postConditions
);
const signer = new TransactionSigner(transaction);
signer.signOrigin(createStacksPrivateKey(secretKey));
// const signature =
// '01051521ac2ac6e6123dcaf9dba000e0005d9855bcc1bc6b96aaf8b6a385238a2317' +
// 'ab21e489aca47af3288cdaebd358b0458a9159cadc314cecb7dd08043c0a6d';
transaction.verifyOrigin();
const serialized = transaction.serialize();
const deserialized = deserializeTransaction(new BufferReader(serialized));
const serializedHexString = serialized.toString('hex');
expect(deserializeTransaction(serializedHexString).serialize().toString('hex')).toEqual(serialized.toString('hex'));
const serializedHexStringPrefixed = '0x' + serializedHexString;
expect(deserializeTransaction(serializedHexStringPrefixed).serialize().toString('hex')).toEqual(serialized.toString('hex'));
expect(deserialized.version).toBe(transactionVersion);
expect(deserialized.chainId).toBe(chainId);
expect(deserialized.auth.authType).toBe(authType);
expect((deserialized.auth.spendingCondition! as SingleSigSpendingCondition).hashMode).toBe(
addressHashMode
);
expect(deserialized.auth.spendingCondition!.nonce!.toString()).toBe(nonce.toString());
expect(deserialized.auth.spendingCondition!.fee!.toString()).toBe(fee.toString());
expect(deserialized.anchorMode).toBe(anchorMode);
expect(deserialized.postConditionMode).toBe(postConditionMode);
expect(deserialized.postConditions.values.length).toBe(1);
const deserializedPostCondition = deserialized.postConditions.values[0] as STXPostCondition;
expect(deserializedPostCondition.principal.address).toStrictEqual(recipient.address);
expect(deserializedPostCondition.conditionCode).toBe(FungibleConditionCode.GreaterEqual);
expect(deserializedPostCondition.amount.toString()).toBe('0');
const deserializedPayload = deserialized.payload as TokenTransferPayload;
expect(deserializedPayload.recipient).toEqual(recipientCV);
expect(deserializedPayload.amount.toString()).toBe(amount.toString());
});
test('STX token transfer transaction fee setting', () => {
const transactionVersion = TransactionVersion.Testnet;
const chainId = DEFAULT_CHAIN_ID;
const anchorMode = AnchorMode.Any;
const postConditionMode = PostConditionMode.Deny;
const address = 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159';
const recipient = createStandardPrincipal(address);
const recipientCV = standardPrincipalCV(address);
const amount = 2500000;
const memo = 'memo (not included';
const payload = createTokenTransferPayload(recipientCV, amount, memo);
const addressHashMode = AddressHashMode.SerializeP2PKH;
const nonce = 0;
const fee = 0;
const pubKey = '03ef788b3830c00abe8f64f62dc32fc863bc0b2cafeb073b6c8e1c7657d9c2c3ab';
const secretKey = 'edf9aee84d9b7abc145504dde6726c64f369d37ee34ded868fabd876c26570bc01';
const spendingCondition = createSingleSigSpendingCondition(addressHashMode, pubKey, nonce, fee);
const authType = AuthType.Standard;
const authorization = createStandardAuth(spendingCondition);
const postCondition = createSTXPostCondition(
recipient,
FungibleConditionCode.GreaterEqual,
0
);
const postConditions = createLPList([postCondition]);
const transaction = new StacksTransaction(
transactionVersion,
authorization,
payload,
postConditions
);
const signer = new TransactionSigner(transaction);
signer.signOrigin(createStacksPrivateKey(secretKey));
// const signature =
// '01051521ac2ac6e6123dcaf9dba000e0005d9855bcc1bc6b96aaf8b6a385238a2317' +
// 'ab21e489aca47af3288cdaebd358b0458a9159cadc314cecb7dd08043c0a6d';
transaction.verifyOrigin();
const serialized = transaction.serialize();
const deserialized = deserializeTransaction(new BufferReader(serialized));
expect(deserialized.auth.spendingCondition!.fee!.toString()).toBe(fee.toString());
const setFee = 123;
transaction.setFee(setFee);
const postSetFeeSerialized = transaction.serialize();
const postSetFeeDeserialized = deserializeTransaction(new BufferReader(postSetFeeSerialized));
expect(postSetFeeDeserialized.version).toBe(transactionVersion);
expect(postSetFeeDeserialized.chainId).toBe(chainId);
expect(postSetFeeDeserialized.auth.authType).toBe(authType);
expect(
(postSetFeeDeserialized.auth.spendingCondition! as SingleSigSpendingCondition).hashMode
).toBe(addressHashMode);
expect(postSetFeeDeserialized.auth.spendingCondition!.nonce!.toString()).toBe(nonce.toString());
expect(postSetFeeDeserialized.auth.spendingCondition!.fee!.toString()).toBe(setFee.toString());
expect(postSetFeeDeserialized.anchorMode).toBe(anchorMode);
expect(postSetFeeDeserialized.postConditionMode).toBe(postConditionMode);
expect(postSetFeeDeserialized.postConditions.values.length).toBe(1);
const deserializedPostCondition = postSetFeeDeserialized.postConditions
.values[0] as STXPostCondition;
expect(deserializedPostCondition.principal.address).toStrictEqual(recipient.address);
expect(deserializedPostCondition.conditionCode).toBe(FungibleConditionCode.GreaterEqual);
expect(deserializedPostCondition.amount.toString()).toBe('0');
const deserializedPayload = postSetFeeDeserialized.payload as TokenTransferPayload;
expect(deserializedPayload.recipient).toEqual(recipientCV);
expect(deserializedPayload.amount.toString()).toBe(amount.toString());
});
test('STX token transfer transaction multi-sig serialization and deserialization', () => {
const addressHashMode = AddressHashMode.SerializeP2SH;
const nonce = 0;
const fee = 0;
const privKeyStrings = [
'6d430bb91222408e7706c9001cfaeb91b08c2be6d5ac95779ab52c6b431950e001',
'2a584d899fed1d24e26b524f202763c8ab30260167429f157f1c119f550fa6af01',
'd5200dee706ee53ae98a03fba6cf4fdcc5084c30cfa9e1b3462dcdeaa3e0f1d201',
];
const privKeys = privKeyStrings.map(createStacksPrivateKey);
const pubKeys = privKeyStrings.map(pubKeyfromPrivKey);
const pubKeyStrings = pubKeys.map(publicKeyToString);
const spendingCondition = createMultiSigSpendingCondition(
addressHashMode,
2,
pubKeyStrings,
nonce,
fee
);
const authType = AuthType.Standard;
const originAuth = createStandardAuth(spendingCondition);
const originAddress = originAuth.spendingCondition?.signer;
expect(originAddress).toEqual('a23ea89d6529ac48ac766f720e480beec7f19273');
const transactionVersion = TransactionVersion.Mainnet;
const chainId = DEFAULT_CHAIN_ID;
const anchorMode = AnchorMode.Any;
const address = 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159';
const recipientCV = standardPrincipalCV(address);
const amount = 2500000;
const memo = 'memo';
const payload = createTokenTransferPayload(recipientCV, amount, memo);
const transaction = new StacksTransaction(transactionVersion, originAuth, payload);
const signer = new TransactionSigner(transaction);
signer.signOrigin(privKeys[0]);
signer.signOrigin(privKeys[1]);
signer.appendOrigin(pubKeys[2]);
transaction.verifyOrigin();
const serialized = transaction.serialize();
const deserialized = deserializeTransaction(new BufferReader(serialized));
expect(deserialized.version).toBe(transactionVersion);
expect(deserialized.chainId).toBe(chainId);
expect(deserialized.auth.authType).toBe(authType);
expect((deserialized.auth.spendingCondition! as MultiSigSpendingCondition).hashMode).toBe(
addressHashMode
);
expect(deserialized.auth.spendingCondition!.nonce!.toString()).toBe(nonce.toString());
expect(deserialized.auth.spendingCondition!.fee!.toString()).toBe(fee.toString());
expect(deserialized.anchorMode).toBe(anchorMode);
expect(deserialized.postConditionMode).toBe(PostConditionMode.Deny);
expect(deserialized.postConditions.values.length).toBe(0);
const deserializedPayload = deserialized.payload as TokenTransferPayload;
expect(deserializedPayload.recipient).toEqual(recipientCV);
expect(deserializedPayload.amount.toString()).toBe(amount.toString());
});
test('STX token transfer transaction multi-sig uncompressed keys serialization and deserialization', () => {
const addressHashMode = AddressHashMode.SerializeP2SH;
const nonce = 0;
const fee = 0;
const privKeyStrings = [
'6d430bb91222408e7706c9001cfaeb91b08c2be6d5ac95779ab52c6b431950e0',
'2a584d899fed1d24e26b524f202763c8ab30260167429f157f1c119f550fa6af',
'd5200dee706ee53ae98a03fba6cf4fdcc5084c30cfa9e1b3462dcdeaa3e0f1d2',
];
const privKeys = privKeyStrings.map(createStacksPrivateKey);
const pubKeys = privKeyStrings.map(pubKeyfromPrivKey);
const pubKeyStrings = pubKeys.map(publicKeyToString);
const spendingCondition = createMultiSigSpendingCondition(
addressHashMode,
2,
pubKeyStrings,
nonce,
fee
);
const originAuth = createStandardAuth(spendingCondition);
const originAddress = originAuth.spendingCondition?.signer;
expect(originAddress).toEqual('73a8b4a751a678fe83e9d35ce301371bb3d397f7');
const transactionVersion = TransactionVersion.Mainnet;
const address = 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159';
const recipientCV = standardPrincipalCV(address);
const amount = 2500000;
const memo = 'memo';
const payload = createTokenTransferPayload(recipientCV, amount, memo);
const transaction = new StacksTransaction(transactionVersion, originAuth, payload);
const signer = new TransactionSigner(transaction);
signer.signOrigin(privKeys[0]);
signer.signOrigin(privKeys[1]);
signer.appendOrigin(pubKeys[2]);
const expectedError = 'Uncompressed keys are not allowed in this hash mode';
expect(() => transaction.verifyOrigin()).toThrow(expectedError);
const serialized = transaction.serialize();
// serialized tx that has been successfully deserialized and had
// its auth verified via the stacks-blockchain implementation
const verifiedTx = "0000000001040173a8b4a751a678fe83e9d35ce301371bb3d397f7000000000000000000000000000000000000000303010359b18fbcb6d5e26efc1eae70aefdae54995e6fd4f3ec40d2ff43b2227c4def1ee6416bf3dd5c92c8150fa51717f1f2db778c02ba47b8c70c1a8ff640b4edee03017b7d76c3d1f7d449604df864e4013da5094be7276aa02cb73ec9fc8108a0bed46c7cde4d702830c1db34ef7c19e2776f59107afef39084776fc88bc78dbb96560103661ec7479330bf1ef7a4c9d1816f089666a112e72d671048e5424fc528ca51530002030200000000000516df0ba3e79792be7be5e50a370289accfc8c9e03200000000002625a06d656d6f000000000000000000000000000000000000000000000000000000000000"
expect(serialized.toString('hex')).toBe(verifiedTx);
expect(() => deserializeTransaction(new BufferReader(serialized))).toThrow(expectedError);
});
test('Sponsored STX token transfer transaction serialization and deserialization', () => {
const transactionVersion = TransactionVersion.Testnet;
const chainId = DEFAULT_CHAIN_ID;
const anchorMode = AnchorMode.Any;
const postConditionMode = PostConditionMode.Deny;
const address = 'SP3FGQ8Z7JY9BWYZ5WM53E0M9NK7WHJF0691NZ159';
// const recipient = createStandardPrincipal(address);
const recipientCV = standardPrincipalCV(address);
const amount = 2500000;
const memo = 'memo (not included';
const payload = createTokenTransferPayload(recipientCV, amount, memo);
const addressHashMode = AddressHashMode.SerializeP2PKH;
const nonce = 0;
const sponsorNonce = 123;
const fee = 0;
const pubKey = '03ef788b3830c00abe8f64f62dc32fc863bc0b2cafeb073b6c8e1c7657d9c2c3ab';
const secretKey = 'edf9aee84d9b7abc145504dde6726c64f369d37ee34ded868fabd876c26570bc01';
const sponsorPubKey = '02b6cfeae7cdcd7ae9229e2decc7d75fe727f8dc9f0d81e58aaf46de550d8e3f58';
const sponsorSecretKey = '3372fdabb09819bb6c9446da8a067840c81dcf8d229d048de36caac3562c5f7301';
const spendingCondition = createSingleSigSpendingCondition(addressHashMode, pubKey, nonce, fee);
const sponsorSpendingCondition = createSingleSigSpendingCondition(
addressHashMode,
sponsorPubKey,
sponsorNonce,
fee
);
const authType = AuthType.Sponsored;
const authorization = createSponsoredAuth(spendingCondition, sponsorSpendingCondition);
const transaction = new StacksTransaction(transactionVersion, authorization, payload);
const signer = new TransactionSigner(transaction);
signer.signOrigin(createStacksPrivateKey(secretKey));
signer.signSponsor(createStacksPrivateKey(sponsorSecretKey));
transaction.verifyOrigin();
const serialized = transaction.serialize();
const deserialized = deserializeTransaction(new BufferReader(serialized));
expect(deserialized.version).toBe(transactionVersion);
expect(deserialized.chainId).toBe(chainId);
expect(deserialized.auth.authType).toBe(authType);
expect(deserialized.auth.spendingCondition!.hashMode).toBe(addressHashMode);
expect(deserialized.auth.spendingCondition!.nonce!.toString()).toBe(nonce.toString());
expect(deserialized.auth.spendingCondition!.fee!.toString()).toBe(fee.toString());
expect((deserialized.auth as SponsoredAuthorization).sponsorSpendingCondition!.hashMode).toBe(addressHashMode);
expect((deserialized.auth as SponsoredAuthorization).sponsorSpendingCondition!.nonce!.toString()).toBe(
sponsorNonce.toString()
);
expect((deserialized.auth as SponsoredAuthorization).sponsorSpendingCondition!.fee!.toString()).toBe(fee.toString());
expect(deserialized.anchorMode).toBe(anchorMode);
expect(deserialized.postConditionMode).toBe(postConditionMode);
const deserializedPayload = deserialized.payload as TokenTransferPayload;
expect(deserializedPayload.recipient).toEqual(recipientCV);
expect(deserializedPayload.amount.toString()).toBe(amount.toString());
}); | the_stack |
import {TargetKind} from "../../common/framebuffer.js";
import {distance_squared_from_point} from "../../common/mat4.js";
import {Material} from "../../common/material.js";
import {
GL_ARRAY_BUFFER,
GL_BLEND,
GL_FLOAT,
GL_FRAMEBUFFER,
GL_TEXTURE0,
GL_TEXTURE1,
GL_TEXTURE2,
GL_TEXTURE3,
GL_TEXTURE_2D,
GL_UNSIGNED_SHORT,
} from "../../common/webgl.js";
import {Entity, first_having} from "../../common/world.js";
import {Attribute} from "../../materials/layout.js";
import {CameraEye, CameraKind} from "../components/com_camera.js";
import {FLOATS_PER_PARTICLE, Render, RenderKind, RenderPhase} from "../components/com_render.js";
import {Game} from "../game.js";
import {Has} from "../world.js";
const QUERY = Has.Transform | Has.Render;
export function sys_render_forward(game: Game, delta: number) {
for (let camera_entity of game.Cameras) {
let camera = game.World.Camera[camera_entity];
switch (camera.Kind) {
case CameraKind.Canvas:
game.Gl.bindFramebuffer(GL_FRAMEBUFFER, null);
game.Gl.viewport(0, 0, game.ViewportWidth, game.ViewportHeight);
game.Gl.clearColor(...camera.ClearColor);
game.Gl.clear(camera.ClearMask);
render_all(game, camera);
break;
case CameraKind.Target:
if (camera.Target.Kind === TargetKind.Forward) {
game.Gl.bindFramebuffer(GL_FRAMEBUFFER, camera.Target.Framebuffer);
game.Gl.viewport(0, 0, camera.Target.Width, camera.Target.Height);
game.Gl.clearColor(...camera.ClearColor);
game.Gl.clear(camera.ClearMask);
render_all(game, camera, camera.Target.ColorTexture);
}
break;
}
}
}
export function render_all(game: Game, eye: CameraEye, current_target?: WebGLTexture) {
// Keep track of the current state to minimize switching.
let current_material: Material<unknown> | null = null;
let current_front_face: GLenum | null = null;
// Transparent objects to be sorted by distance to camera and rendered later.
let transparent_entities: Array<Entity> = [];
// First render opaque objects.
for (let ent = 0; ent < game.World.Signature.length; ent++) {
if ((game.World.Signature[ent] & QUERY) === QUERY) {
let render = game.World.Render[ent];
if (render.Phase === RenderPhase.Transparent) {
// Store transparent objects in a separate array to render them later.
transparent_entities.push(ent);
continue;
}
if (render.Material !== current_material) {
current_material = render.Material;
use_material(game, render, eye);
}
if (render.FrontFace !== current_front_face) {
current_front_face = render.FrontFace;
game.Gl.frontFace(render.FrontFace);
}
draw_entity(game, ent, current_target);
}
}
// Sort transparent objects by distance to camera, from back to front, to
// enforce overdraw and blend them in the correct order.
transparent_entities.sort((a, b) => {
let transform_a = game.World.Transform[a];
let transform_b = game.World.Transform[b];
return (
distance_squared_from_point(transform_b.World, eye.Position) -
distance_squared_from_point(transform_a.World, eye.Position)
);
});
game.Gl.enable(GL_BLEND);
for (let i = 0; i < transparent_entities.length; i++) {
let ent = transparent_entities[i];
let render = game.World.Render[ent];
if (render.Material !== current_material) {
current_material = render.Material;
use_material(game, render, eye);
}
if (render.FrontFace !== current_front_face) {
current_front_face = render.FrontFace;
game.Gl.frontFace(render.FrontFace);
}
draw_entity(game, ent, current_target);
}
game.Gl.disable(GL_BLEND);
}
function use_material(game: Game, render: Render, eye: CameraEye) {
switch (render.Kind) {
case RenderKind.ColoredUnlit:
game.Gl.useProgram(render.Material.Program);
game.Gl.uniformMatrix4fv(render.Material.Locations.Pv, false, eye.Pv);
break;
case RenderKind.ColoredShaded:
game.Gl.useProgram(render.Material.Program);
game.Gl.uniformMatrix4fv(render.Material.Locations.Pv, false, eye.Pv);
game.Gl.uniform3fv(render.Material.Locations.Eye, eye.Position);
game.Gl.uniform4fv(render.Material.Locations.LightPositions, game.LightPositions);
game.Gl.uniform4fv(render.Material.Locations.LightDetails, game.LightDetails);
break;
case RenderKind.ColoredShadows:
game.Gl.useProgram(render.Material.Program);
game.Gl.uniformMatrix4fv(render.Material.Locations.Pv, false, eye.Pv);
game.Gl.uniform3fv(render.Material.Locations.Eye, eye.Position);
game.Gl.uniform4fv(render.Material.Locations.LightPositions, game.LightPositions);
game.Gl.uniform4fv(render.Material.Locations.LightDetails, game.LightDetails);
game.Gl.activeTexture(GL_TEXTURE0);
game.Gl.bindTexture(GL_TEXTURE_2D, game.Targets.Sun.DepthTexture);
game.Gl.uniform1i(render.Material.Locations.ShadowMap, 0);
// Only one shadow source is supported.
let light_entity = first_having(game.World, Has.Camera | Has.Light);
if (light_entity) {
let light_camera = game.World.Camera[light_entity];
if (light_camera.Kind === CameraKind.Xr) {
throw new Error("XR cameras cannot be shadow sources.");
}
game.Gl.uniformMatrix4fv(
render.Material.Locations.ShadowSpace,
false,
light_camera.Pv
);
}
break;
case RenderKind.TexturedUnlit:
game.Gl.useProgram(render.Material.Program);
game.Gl.uniformMatrix4fv(render.Material.Locations.Pv, false, eye.Pv);
break;
case RenderKind.TexturedShaded:
game.Gl.useProgram(render.Material.Program);
game.Gl.uniformMatrix4fv(render.Material.Locations.Pv, false, eye.Pv);
game.Gl.uniform3fv(render.Material.Locations.Eye, eye.Position);
game.Gl.uniform4fv(render.Material.Locations.LightPositions, game.LightPositions);
game.Gl.uniform4fv(render.Material.Locations.LightDetails, game.LightDetails);
break;
case RenderKind.MappedShaded:
game.Gl.useProgram(render.Material.Program);
game.Gl.uniformMatrix4fv(render.Material.Locations.Pv, false, eye.Pv);
game.Gl.uniform3fv(render.Material.Locations.Eye, eye.Position);
game.Gl.uniform4fv(render.Material.Locations.LightPositions, game.LightPositions);
game.Gl.uniform4fv(render.Material.Locations.LightDetails, game.LightDetails);
break;
case RenderKind.Vertices:
case RenderKind.ParticlesColored:
case RenderKind.ParticlesTextured:
game.Gl.useProgram(render.Material.Program);
game.Gl.uniformMatrix4fv(render.Material.Locations.Pv, false, eye.Pv);
break;
}
}
function draw_entity(game: Game, entity: Entity, current_target?: WebGLTexture) {
let transform = game.World.Transform[entity];
let render = game.World.Render[entity];
switch (render.Kind) {
case RenderKind.ColoredUnlit:
game.Gl.uniformMatrix4fv(render.Material.Locations.World, false, transform.World);
game.Gl.uniform4fv(render.Material.Locations.Color, render.Color);
game.Gl.bindVertexArray(render.Mesh.Vao);
game.Gl.drawElements(
render.Material.Mode,
render.Mesh.IndexCount,
GL_UNSIGNED_SHORT,
0
);
game.Gl.bindVertexArray(null);
break;
case RenderKind.ColoredShaded:
game.Gl.uniformMatrix4fv(render.Material.Locations.World, false, transform.World);
game.Gl.uniformMatrix4fv(render.Material.Locations.Self, false, transform.Self);
game.Gl.uniform4fv(render.Material.Locations.DiffuseColor, render.DiffuseColor);
game.Gl.uniform4fv(render.Material.Locations.SpecularColor, render.SpecularColor);
game.Gl.uniform4fv(render.Material.Locations.EmissiveColor, render.EmissiveColor);
game.Gl.bindVertexArray(render.Mesh.Vao);
game.Gl.drawElements(
render.Material.Mode,
render.Mesh.IndexCount,
GL_UNSIGNED_SHORT,
0
);
game.Gl.bindVertexArray(null);
break;
case RenderKind.ColoredShadows:
game.Gl.uniformMatrix4fv(render.Material.Locations.World, false, transform.World);
game.Gl.uniformMatrix4fv(render.Material.Locations.Self, false, transform.Self);
game.Gl.uniform4fv(render.Material.Locations.DiffuseColor, render.DiffuseColor);
game.Gl.uniform4fv(render.Material.Locations.SpecularColor, render.SpecularColor);
game.Gl.uniform4fv(render.Material.Locations.EmissiveColor, render.EmissiveColor);
game.Gl.bindVertexArray(render.Mesh.Vao);
game.Gl.drawElements(
render.Material.Mode,
render.Mesh.IndexCount,
GL_UNSIGNED_SHORT,
0
);
game.Gl.bindVertexArray(null);
break;
case RenderKind.TexturedUnlit:
if (render.Texture === current_target) {
// Prevent feedback loop between the active render target
// and the texture being rendered.
break;
}
game.Gl.uniformMatrix4fv(render.Material.Locations.World, false, transform.World);
game.Gl.uniform4fv(render.Material.Locations.Color, render.Color);
game.Gl.activeTexture(GL_TEXTURE0);
game.Gl.bindTexture(GL_TEXTURE_2D, render.Texture);
game.Gl.uniform1i(render.Material.Locations.TextureMap, 0);
game.Gl.bindVertexArray(render.Mesh.Vao);
game.Gl.drawElements(
render.Material.Mode,
render.Mesh.IndexCount,
GL_UNSIGNED_SHORT,
0
);
game.Gl.bindVertexArray(null);
break;
case RenderKind.TexturedShaded:
if (render.Texture === current_target) {
// Prevent feedback loop between the active render target
// and the texture being rendered.
break;
}
game.Gl.uniformMatrix4fv(render.Material.Locations.World, false, transform.World);
game.Gl.uniformMatrix4fv(render.Material.Locations.Self, false, transform.Self);
game.Gl.uniform4fv(render.Material.Locations.DiffuseColor, render.DiffuseColor);
game.Gl.uniform4fv(render.Material.Locations.SpecularColor, render.SpecularColor);
game.Gl.uniform4fv(render.Material.Locations.EmissiveColor, render.EmissiveColor);
game.Gl.activeTexture(GL_TEXTURE0);
game.Gl.bindTexture(GL_TEXTURE_2D, render.Texture);
game.Gl.uniform1i(render.Material.Locations.DiffuseMap, 0);
game.Gl.bindVertexArray(render.Mesh.Vao);
game.Gl.drawElements(
render.Material.Mode,
render.Mesh.IndexCount,
GL_UNSIGNED_SHORT,
0
);
game.Gl.bindVertexArray(null);
break;
case RenderKind.MappedShaded:
if (render.DiffuseMap === current_target) {
// Prevent feedback loop between the active render target
// and the texture being rendered.
break;
}
game.Gl.uniformMatrix4fv(render.Material.Locations.World, false, transform.World);
game.Gl.uniformMatrix4fv(render.Material.Locations.Self, false, transform.Self);
game.Gl.uniform4fv(render.Material.Locations.DiffuseColor, render.DiffuseColor);
game.Gl.activeTexture(GL_TEXTURE1);
game.Gl.bindTexture(GL_TEXTURE_2D, render.DiffuseMap);
game.Gl.uniform1i(render.Material.Locations.DiffuseMap, 1);
game.Gl.activeTexture(GL_TEXTURE2);
game.Gl.bindTexture(GL_TEXTURE_2D, render.NormalMap);
game.Gl.uniform1i(render.Material.Locations.NormalMap, 2);
game.Gl.activeTexture(GL_TEXTURE3);
game.Gl.bindTexture(GL_TEXTURE_2D, render.RoughnessMap);
game.Gl.uniform1i(render.Material.Locations.RoughnessMap, 3);
game.Gl.bindVertexArray(render.Mesh.Vao);
game.Gl.drawElements(
render.Material.Mode,
render.Mesh.IndexCount,
GL_UNSIGNED_SHORT,
0
);
game.Gl.bindVertexArray(null);
break;
case RenderKind.Vertices:
game.Gl.uniformMatrix4fv(render.Material.Locations.World, false, transform.World);
game.Gl.uniform4fv(render.Material.Locations.Color, render.Color);
game.Gl.bindBuffer(GL_ARRAY_BUFFER, render.VertexBuffer);
game.Gl.enableVertexAttribArray(Attribute.Position);
game.Gl.vertexAttribPointer(Attribute.Position, 3, GL_FLOAT, false, 0, 0);
game.Gl.drawArrays(render.Material.Mode, 0, render.IndexCount);
break;
case RenderKind.ParticlesColored: {
let emitter = game.World.EmitParticles[entity];
game.Gl.uniform4fv(render.Material.Locations.ColorStart, render.ColorStart);
game.Gl.uniform4fv(render.Material.Locations.ColorEnd, render.ColorEnd);
game.Gl.uniform4f(
render.Material.Locations.Details,
emitter.Lifespan,
emitter.Speed,
...render.Size
);
let instances = Float32Array.from(emitter.Instances);
game.Gl.bindBuffer(GL_ARRAY_BUFFER, render.Buffer);
game.Gl.bufferSubData(GL_ARRAY_BUFFER, 0, instances);
game.Gl.enableVertexAttribArray(render.Material.Locations.OriginAge);
game.Gl.vertexAttribPointer(
render.Material.Locations.OriginAge,
4,
GL_FLOAT,
false,
FLOATS_PER_PARTICLE * 4,
0
);
game.Gl.enableVertexAttribArray(render.Material.Locations.Direction);
game.Gl.vertexAttribPointer(
render.Material.Locations.Direction,
3,
GL_FLOAT,
false,
FLOATS_PER_PARTICLE * 4,
4 * 4
);
game.Gl.drawArrays(
render.Material.Mode,
0,
emitter.Instances.length / FLOATS_PER_PARTICLE
);
break;
}
}
} | the_stack |
import { CanvasPath, ReactSketchCanvasProps } from 'react-sketch-canvas';
let defaultProps: Partial<ReactSketchCanvasProps>;
let canvasPathWithEraser: CanvasPath;
let canvasPathWithOnlyPen: CanvasPath;
before(() => {
cy.fixture('props.json').then((props) => (defaultProps = props));
cy.fixture('canvasPath/onlyPen.json').then(
(onlyPen) => (canvasPathWithOnlyPen = onlyPen)
);
cy.fixture('canvasPath/withEraser.json').then(
(withEraser) => (canvasPathWithEraser = withEraser)
);
});
beforeEach(() => {
cy.visit('/');
});
it('should trigger erase mode and add a mask for erasing previous strokes', () => {
cy.drawSquare(100, 100, 50, 'pen');
cy.findByRole('button', { name: /eraser/i }).click();
cy.drawSquare(100, 150, 50, 'pen');
cy.get('#eraser-stroke-group').find('path').should('have.length', 1);
cy.get('mask#eraser-mask-0').find('use').should('have.length', 2); // background + one mask path
cy.get('#stroke-group-0')
.should('have.attr', 'mask', 'url(#eraser-mask-0)')
.find('path')
.should('have.length', 1);
cy.findByRole('button', { name: /pen/i }).click();
cy.drawSquare(105, 105, 55, 'pen');
cy.findByRole('button', { name: /eraser/i }).click();
cy.drawSquare(100, 150, 50, 'pen');
cy.get('#eraser-stroke-group').find('path').should('have.length', 2);
cy.get('mask#eraser-mask-0').find('use').should('have.length', 3); // background + two mask paths
cy.get('mask#eraser-mask-1').find('use').should('have.length', 2); // background + one mask path
});
describe('undo', () => {
it('should undo a stroke', () => {
cy.getCanvas().find('path').should('have.length', 0);
cy.drawSquare(100, 100, 50, 'pen');
cy.getCanvas().find('path').should('have.length', 1);
cy.findByRole('button', { name: /undo/i }).click();
cy.getCanvas().find('path').should('have.length', 0);
});
it('should undo an eraser stroke', () => {
cy.drawSquare(100, 100, 50, 'pen');
cy.findByRole('button', { name: /eraser/i }).click();
cy.drawSquare(100, 150, 50, 'pen');
cy.getCanvas().find('path').should('have.length', 2);
cy.get('#eraser-stroke-group').find('path').should('have.length', 1);
cy.get('mask#eraser-mask-0').find('use').should('have.length', 2); // background + one mask path
cy.findByRole('button', { name: /undo/i }).click();
cy.getCanvas().find('path').should('have.length', 1);
cy.get('#eraser-stroke-group').find('path').should('have.length', 0);
});
});
describe('redo', () => {
it('should redo a stroke', () => {
cy.getCanvas().find('path').should('have.length', 0);
cy.drawSquare(100, 100, 50, 'pen');
cy.getCanvas().find('path').should('have.length', 1);
cy.findByRole('button', { name: /undo/i }).click();
cy.getCanvas().find('path').should('have.length', 0);
cy.findByRole('button', { name: /redo/i }).click();
cy.getCanvas().find('path').should('have.length', 1);
});
it('should redo an eraser stroke', () => {
cy.drawSquare(100, 100, 50, 'pen');
cy.findByRole('button', { name: /eraser/i }).click();
cy.drawSquare(100, 150, 50, 'pen');
cy.getCanvas().find('path').should('have.length', 2);
cy.get('#eraser-stroke-group').find('path').should('have.length', 1);
cy.get('mask#eraser-mask-0').find('use').should('have.length', 2); // background + one mask path
cy.findByRole('button', { name: /undo/i }).click();
cy.getCanvas().find('path').should('have.length', 1);
cy.get('#eraser-stroke-group').find('path').should('have.length', 0);
cy.get('mask#eraser-mask-0').should('not.exist');
cy.findByRole('button', { name: /redo/i }).click();
cy.getCanvas().find('path').should('have.length', 2);
cy.get('#eraser-stroke-group').find('path').should('have.length', 1);
cy.get('mask#eraser-mask-0').find('use').should('have.length', 2); // background + one mask path
});
});
describe('clearCanvas', () => {
it('should clearCanvas but still keep the stack', () => {
cy.getCanvas().find('path').should('have.length', 0);
cy.drawSquare(100, 100, 50, 'pen');
cy.getCanvas().find('path').should('have.length', 1);
cy.findByRole('button', { name: /clear all/i }).click();
cy.getCanvas().find('path').should('have.length', 0);
cy.findByRole('button', { name: /redo/i }).click();
cy.getCanvas().find('path').should('have.length', 0);
cy.findByRole('button', { name: /undo/i }).click();
cy.getCanvas().find('path').should('have.length', 1);
});
it('should clearCanvas with an eraser stroke but still keep the stack', () => {
cy.drawSquare(100, 100, 50, 'pen');
cy.findByRole('button', { name: /eraser/i }).click();
cy.drawSquare(100, 150, 50, 'pen');
cy.getCanvas().find('path').should('have.length', 2);
cy.get('#eraser-stroke-group').find('path').should('have.length', 1);
cy.get('mask#eraser-mask-0').find('use').should('have.length', 2); // background + one mask path
cy.findByRole('button', { name: /clear all/i }).click();
cy.getCanvas().find('path').should('have.length', 0);
cy.get('mask#eraser-mask-0').should('not.exist');
cy.findByRole('button', { name: /redo/i }).click();
cy.getCanvas().find('path').should('have.length', 0);
cy.get('mask#eraser-mask-0').should('not.exist');
cy.findByRole('button', { name: /undo/i }).click();
cy.getCanvas().find('path').should('have.length', 2);
cy.get('#eraser-stroke-group').find('path').should('have.length', 1);
cy.get('mask#eraser-mask-0').find('use').should('have.length', 2); // background + one mask path
});
});
describe('resetCanvas', () => {
it('should resetCanvas and remove the stack', () => {
cy.getCanvas().find('path').should('have.length', 0);
cy.drawSquare(100, 100, 50, 'pen');
cy.getCanvas().find('path').should('have.length', 1);
cy.findByRole('button', { name: /reset all/i }).click();
cy.getCanvas().find('path').should('have.length', 0);
cy.findByRole('button', { name: /redo/i }).click();
cy.getCanvas().find('path').should('have.length', 0);
cy.findByRole('button', { name: /undo/i }).click();
cy.getCanvas().find('path').should('have.length', 0);
});
it('should resetCanvas with an eraser stroke and remove the stack', () => {
cy.drawSquare(100, 100, 50, 'pen');
cy.findByRole('button', { name: /eraser/i }).click();
cy.drawSquare(100, 150, 50, 'pen');
cy.getCanvas().find('path').should('have.length', 2);
cy.get('#eraser-stroke-group').find('path').should('have.length', 1);
cy.get('mask#eraser-mask-0').find('use').should('have.length', 2); // background + one mask path
cy.findByRole('button', { name: /reset all/i }).click();
cy.getCanvas().find('path').should('have.length', 0);
cy.get('mask#eraser-mask-0').should('not.exist');
cy.findByRole('button', { name: /redo/i }).click();
cy.getCanvas().find('path').should('have.length', 0);
cy.get('mask#eraser-mask-0').should('not.exist');
cy.findByRole('button', { name: /undo/i }).click();
cy.getCanvas().find('path').should('have.length', 0);
cy.get('mask#eraser-mask-0').should('not.exist');
});
});
describe('exportImage - png', () => {
beforeEach(() => {
cy.findByRole('radio', { name: /png/i }).click();
cy.findByRole('textbox', { name: 'backgroundImage', exact: true }).clear();
cy.findByRole('switch', {
name: 'exportWithBackgroundImage',
exact: true,
}).click();
});
it('should export png with stroke', () => {
cy.findByRole('button', { name: /export image/i }).click();
cy.get('#exported-image')
.should('have.attr', 'src')
.and('match', /^data:image\/png;base64/i)
.convertDataURIToKiloBytes()
.as('fileSizeWithoutStroke');
cy.drawSquare(100, 100, 50, 'pen');
cy.findByRole('button', { name: /export image/i }).click();
cy.get('#exported-image')
.should('have.attr', 'src')
.and('match', /^data:image\/png;base64/i)
.convertDataURIToKiloBytes()
.then((fileSizeWithStroke) => {
cy.get('@fileSizeWithoutStroke').should(
'be.lessThan',
fileSizeWithStroke
);
});
});
it('should export png with stroke and eraser', () => {
cy.findByRole('button', { name: /export image/i }).click();
cy.get('#exported-image')
.should('have.attr', 'src')
.and('match', /^data:image\/png;base64/i)
.convertDataURIToKiloBytes()
.as('fileSizeWithoutStrokeAndEraser');
cy.drawSquare(100, 100, 50, 'pen');
cy.findByRole('button', { name: /eraser/i }).click();
cy.drawSquare(100, 150, 50, 'pen');
cy.findByRole('button', { name: /export image/i }).click();
cy.get('#exported-image')
.should('have.attr', 'src')
.and('match', /^data:image\/png;base64/i)
.convertDataURIToKiloBytes()
.then((fileSizeWithStrokeAndEraser) => {
cy.get('@fileSizeWithoutStrokeAndEraser').should(
'be.lessThan',
fileSizeWithStrokeAndEraser
);
});
});
it('should export png with stroke while exportWithBackgroundImage is set', () => {
cy.findByRole('switch', {
name: 'exportWithBackgroundImage',
exact: true,
}).click();
cy.findByRole('button', { name: /export image/i }).click();
cy.get('#exported-image')
.should('have.attr', 'src')
.and('match', /^data:image\/png;base64/i)
.convertDataURIToKiloBytes()
.as('fileSizeWithoutStroke');
cy.drawSquare(100, 100, 50, 'pen');
cy.findByRole('button', { name: /export image/i }).click();
cy.get('#exported-image')
.should('have.attr', 'src')
.and('match', /^data:image\/png;base64/i)
.convertDataURIToKiloBytes()
.then((fileSizeWithStroke) => {
cy.get('@fileSizeWithoutStroke').should(
'be.lessThan',
fileSizeWithStroke
);
});
});
it('should export png with stroke and eraser while exportWithBackgroundImage is set', () => {
cy.findByRole('switch', {
name: 'exportWithBackgroundImage',
exact: true,
}).click();
cy.findByRole('button', { name: /export image/i }).click();
cy.get('#exported-image')
.should('have.attr', 'src')
.and('match', /^data:image\/png;base64/i)
.convertDataURIToKiloBytes()
.as('fileSizeWithoutStrokeAndEraser');
cy.drawSquare(100, 100, 50, 'pen');
cy.findByRole('button', { name: /eraser/i }).click();
cy.drawSquare(100, 150, 50, 'pen');
cy.findByRole('button', { name: /export image/i }).click();
cy.get('#exported-image')
.should('have.attr', 'src')
.and('match', /^data:image\/png;base64/i)
.convertDataURIToKiloBytes()
.then((fileSizeWithStrokeAndEraser) => {
cy.get('@fileSizeWithoutStrokeAndEraser').should(
'be.lessThan',
fileSizeWithStrokeAndEraser
);
});
});
});
describe('exportImage - jpeg', () => {
beforeEach(() => {
cy.findByRole('radio', { name: /jpeg/i }).click();
cy.findByRole('textbox', { name: 'backgroundImage', exact: true }).clear();
cy.findByRole('switch', {
name: 'exportWithBackgroundImage',
exact: true,
}).click();
});
it('should export jpeg with stroke', () => {
cy.findByRole('button', { name: /export image/i }).click();
cy.get('#exported-image')
.should('have.attr', 'src')
.and('match', /^data:image\/jpeg;base64/i)
.convertDataURIToKiloBytes()
.as('fileSizeWithoutStroke');
cy.drawSquare(100, 100, 50, 'pen');
cy.findByRole('button', { name: /export image/i }).click();
cy.get('#exported-image')
.should('have.attr', 'src')
.and('match', /^data:image\/jpeg;base64/i)
.convertDataURIToKiloBytes()
.then((fileSizeWithStroke) => {
cy.get('@fileSizeWithoutStroke').should(
'be.lessThan',
fileSizeWithStroke
);
});
});
it('should export jpeg with stroke and eraser', () => {
cy.findByRole('button', { name: /export image/i }).click();
cy.get('#exported-image')
.should('have.attr', 'src')
.and('match', /^data:image\/jpeg;base64/i)
.convertDataURIToKiloBytes()
.as('fileSizeWithoutStrokeAndEraser');
cy.drawSquare(100, 100, 50, 'pen');
cy.findByRole('button', { name: /eraser/i }).click();
cy.drawSquare(100, 150, 50, 'pen');
cy.findByRole('button', { name: /export image/i }).click();
cy.get('#exported-image')
.should('have.attr', 'src')
.and('match', /^data:image\/jpeg;base64/i)
.convertDataURIToKiloBytes()
.then((fileSizeWithStrokeAndEraser) => {
cy.get('@fileSizeWithoutStrokeAndEraser').should(
'be.lessThan',
fileSizeWithStrokeAndEraser
);
});
});
it('should export jpeg with stroke while exportWithBackgroundImage is set', () => {
cy.findByRole('switch', {
name: 'exportWithBackgroundImage',
exact: true,
}).click();
cy.findByRole('button', { name: /export image/i }).click();
cy.get('#exported-image')
.should('have.attr', 'src')
.and('match', /^data:image\/jpeg;base64/i)
.convertDataURIToKiloBytes()
.as('fileSizeWithoutStroke');
cy.drawSquare(100, 100, 50, 'pen');
cy.findByRole('button', { name: /export image/i }).click();
cy.get('#exported-image')
.should('have.attr', 'src')
.and('match', /^data:image\/jpeg;base64/i)
.convertDataURIToKiloBytes()
.then((fileSizeWithStroke) => {
cy.get('@fileSizeWithoutStroke').should(
'be.lessThan',
fileSizeWithStroke
);
});
});
it('should export jpeg with stroke and eraser while exportWithBackgroundImage is set', () => {
cy.findByRole('switch', {
name: 'exportWithBackgroundImage',
exact: true,
}).click();
cy.findByRole('button', { name: /export image/i }).click();
cy.get('#exported-image')
.should('have.attr', 'src')
.and('match', /^data:image\/jpeg;base64/i)
.convertDataURIToKiloBytes()
.as('fileSizeWithoutStrokeAndEraser');
cy.drawSquare(100, 100, 50, 'pen');
cy.findByRole('button', { name: /eraser/i }).click();
cy.drawSquare(100, 150, 50, 'pen');
cy.findByRole('button', { name: /export image/i }).click();
cy.get('#exported-image')
.should('have.attr', 'src')
.and('match', /^data:image\/jpeg;base64/i)
.convertDataURIToKiloBytes()
.then((fileSizeWithStrokeAndEraser) => {
cy.get('@fileSizeWithoutStrokeAndEraser').should(
'be.lessThan',
fileSizeWithStrokeAndEraser
);
});
});
});
describe('exportImage - svg', () => {
beforeEach(() => {
cy.findByRole('textbox', { name: 'backgroundImage', exact: true }).clear();
cy.findByRole('switch', {
name: 'exportWithBackgroundImage',
exact: true,
}).click();
});
it('should export jpeg with stroke', () => {
cy.drawSquare(100, 100, 50, 'pen');
cy.findByRole('button', { name: /export svg/i }).click();
cy.get('#exported-svg').find('path').should('have.length', 1);
});
it('should export jpeg with stroke and eraser', () => {
cy.drawSquare(100, 100, 50, 'pen');
cy.findByRole('button', { name: /eraser/i }).click();
cy.drawSquare(100, 150, 50, 'pen');
cy.findByRole('button', { name: /export svg/i }).click();
cy.get('#exported-svg').find('path').should('have.length', 2);
cy.get('#exported-svg #eraser-stroke-group')
.find('path')
.should('have.length', 1);
cy.get('#exported-svg mask#eraser-mask-0')
.find('use')
.should('have.length', 2); // background + one mask path
});
it('should export jpeg with stroke while exportWithBackgroundImage is set', () => {
cy.findByRole('switch', {
name: 'exportWithBackgroundImage',
exact: true,
}).click();
cy.drawSquare(100, 100, 50, 'pen');
cy.findByRole('button', { name: /export svg/i }).click();
cy.get('#exported-svg').find('path').should('have.length', 1);
cy.get('#exported-svg #canvas-background').should(
'have.attr',
'fill',
defaultProps.canvasColor
);
});
it('should export jpeg with stroke and eraser while exportWithBackgroundImage is set', () => {
cy.findByRole('switch', {
name: 'exportWithBackgroundImage',
exact: true,
}).click();
cy.drawSquare(100, 100, 50, 'pen');
cy.findByRole('button', { name: /eraser/i }).click();
cy.drawSquare(100, 150, 50, 'pen');
cy.findByRole('button', { name: /export svg/i }).click();
cy.get('#exported-svg').find('path').should('have.length', 2);
cy.get('#exported-svg #eraser-stroke-group')
.find('path')
.should('have.length', 1);
cy.get('#exported-svg mask#eraser-mask-0')
.find('use')
.should('have.length', 2); // background + one mask path
cy.get('#exported-svg #canvas-background').should(
'have.attr',
'fill',
defaultProps.canvasColor
);
});
});
describe('loadPaths', () => {
it('should load path with only pen', () => {
cy.getCanvas().find('path').should('not.exist');
cy.findByRole('textbox', { name: /paths to load/i })
.clear()
.type(JSON.stringify(canvasPathWithOnlyPen), {
parseSpecialCharSequences: false,
delay: 0,
});
cy.findByRole('button', { name: /load paths/i }).click();
cy.getCanvas().find('path').should('have.length', 1);
});
it('should load path with pen and eraser', () => {
cy.getCanvas().find('path').should('not.exist');
cy.findByRole('textbox', { name: /paths to load/i })
.clear()
.type(JSON.stringify(canvasPathWithEraser), {
parseSpecialCharSequences: false,
delay: 0,
});
cy.findByRole('button', { name: /load paths/i }).click();
cy.getCanvas().find('path').should('have.length', 2);
cy.get('#eraser-stroke-group').find('path').should('have.length', 1);
cy.get('mask#eraser-mask-0').find('use').should('have.length', 2); // background + one mask path
});
}); | the_stack |
import {
ComponentFactoryResolver, ComponentRef, Directive, EventEmitter, Host,
Input, OnChanges, OnInit, Optional, Output,
SimpleChanges, SkipSelf, ViewContainerRef
} from '@angular/core';
import { AbstractControl, ControlContainer, FormGroup, FormGroupDirective } from '@angular/forms';
import { NguiDatetimePickerComponent } from './datetime-picker.component';
import { NguiDatetime } from './datetime';
declare var moment: any;
function isInteger(value) {
if (Number.isInteger) {
return Number.isInteger(value);
}
return typeof value === "number" &&
isFinite(value) &&
Math.floor(value) === value;
};
function isNaN(value) {
if (Number.isNaN) {
return Number.isNaN(value);
}
return value !== value;
};
/**
* If the given string is not a valid date, it defaults back to today
*/
@Directive({
selector: '[ngui-datetime-picker]',
providers: [NguiDatetime]
})
export class NguiDatetimePickerDirective implements OnInit, OnChanges {
@Input('date-format') dateFormat: string;
@Input('parse-format') parseFormat: string;
@Input('date-only') dateOnly: boolean;
@Input('time-only') timeOnly: boolean;
@Input('close-on-select') closeOnSelect: boolean = true;
@Input('default-value') defaultValue: Date | string;
@Input('minute-step') minuteStep: number;
@Input('min-date') minDate: Date | string;
@Input('max-date') maxDate: Date | string;
@Input('min-hour') minHour: Date | number;
@Input('max-hour') maxHour: Date | number;
@Input('disabled-dates') disabledDates: Date[];
@Input('show-close-layer') showCloseLayer: boolean;
@Input('show-today-shortcut') showTodayShortcut: boolean = false;
@Input('show-week-numbers') showWeekNumbers: boolean;
@Input() formControlName: string;
@Input('is-draggable') isDraggable: boolean = true;
@Input('ngModel') ngModel: any;
@Output('ngModelChange') ngModelChange = new EventEmitter();
@Output('valueChanged') valueChanged$ = new EventEmitter();
@Output('popupClosed') popupClosed$ = new EventEmitter();
private el: HTMLInputElement; /* input element */
private nguiDatetimePickerEl: HTMLElement; /* dropdown element */
private componentRef: ComponentRef<NguiDatetimePickerComponent>; /* dropdown component reference */
private ctrl: AbstractControl;
private sub: any;
// private justShown: boolean;
inputEl: HTMLInputElement;
clickedDatetimePicker: boolean;
userModifyingValue: boolean = false;
constructor(
private resolver: ComponentFactoryResolver,
private viewContainerRef: ViewContainerRef,
@Optional() @Host() @SkipSelf() private parent: ControlContainer
) {
this.el = this.viewContainerRef.element.nativeElement;
}
/**
* convert defaultValue, minDate, maxDate, minHour, and maxHour to proper types
*/
normalizeInput() {
if (this.defaultValue && typeof this.defaultValue === 'string') {
let d = NguiDatetime.parseDate(<string>this.defaultValue);
this.defaultValue = isNaN(d.getTime()) ? new Date() : d;
}
if (this.minDate && typeof this.minDate == 'string') {
let d = NguiDatetime.parseDate(<string>this.minDate);
this.minDate = isNaN(d.getTime()) ? new Date() : d;
}
if (this.maxDate && typeof this.maxDate == 'string') {
let d = NguiDatetime.parseDate(<string>this.maxDate);
this.maxDate = isNaN(d.getTime()) ? new Date() : d;
}
if (this.minHour) {
if (this.minHour instanceof Date) {
this.minHour = (<Date>this.minHour).getHours();
} else {
let hour = Number(this.minHour.toString());
if (!isInteger(hour) || hour > 23 || hour < 0) {
this.minHour = undefined;
}
}
}
if (this.maxHour) {
if (this.maxHour instanceof Date) {
this.maxHour = (<Date>this.maxHour).getHours();
} else {
let hour = Number(this.maxHour.toString());
if (!isInteger(hour) || hour > 23 || hour < 0) {
this.maxHour = undefined;
}
}
}
}
ngOnInit(): void {
if (this.parent && this.formControlName) {
if (this.parent["form"]) {
this.ctrl = (<FormGroup>this.parent["form"]).get(this.formControlName);
} else if (this.parent["path"]) {
let formDir = this.parent.formDirective;
if (formDir instanceof FormGroupDirective && formDir.form.get(this.parent["path"])) {
this.ctrl = formDir.form.get(this.parent["path"]).get(this.formControlName);
}
}
if (this.ctrl) {
this.sub = this.ctrl.valueChanges.subscribe((date) => {
this.setInputElDateValue(date);
this.updateDatepicker();
});
}
}
this.normalizeInput();
//wrap this element with a <div> tag, so that we can position dynamic element correctly
let wrapper = document.createElement("div");
wrapper.className = 'ngui-datetime-picker-wrapper';
this.el.parentElement.insertBefore(wrapper, this.el.nextSibling);
wrapper.appendChild(this.el);
if (this.ngModel && this.ngModel.getTime) { // if it is a Date object given, set dateValue and toString method
this.ngModel.toString = () => NguiDatetime.formatDate(this.ngModel, this.dateFormat, this.dateOnly);
}
setTimeout(() => { // after [(ngModel)] is applied
if (this.el.tagName === 'INPUT') {
this.inputElValueChanged(this.el.value); //set this.el.dateValue and reformat this.el.value
}
if (this.ctrl) {
this.ctrl.markAsPristine();
}
});
}
ngAfterViewInit() {
// if this element is not an input tag, move dropdown after input tag
// so that it displays correctly
this.inputEl = this.el.tagName === "INPUT" ?
<HTMLInputElement>this.el : <HTMLInputElement>this.el.querySelector("input");
if (this.inputEl) {
this.inputEl.addEventListener('focus', this.showDatetimePicker);
this.inputEl.addEventListener('blur', this.hideDatetimePicker);
this.inputEl.addEventListener('keydown', this.handleKeyDown);
}
}
handleKeyDown = (event) => {
this.userModifyingValue = true;
}
ngOnChanges(changes: SimpleChanges) {
let date;
if (changes && changes['ngModel']) {
date = changes['ngModel'].currentValue;
if (date && typeof date !== 'string') {
date.toString = () => NguiDatetime.formatDate(date, this.dateFormat, this.dateOnly);
this.setInputElDateValue(date);
this.updateDatepicker();
} else if (date && typeof date === 'string') {
/** if program assigns a string value, then format to date later */
if (!this.userModifyingValue) {
setTimeout(() => {
let dt = this.getDate(date);
dt.toString = () => NguiDatetime.formatDate(dt, this.dateFormat, this.dateOnly);
this.ngModel = dt;
this.inputEl.value = '' + dt;
})
} else {
let changeDate: any = new Date(date);
if (changeDate.toString() !== "Invalid Date") {
this.setInputElDateValue(date);
this.updateDatepicker();
}
}
}
}
this.userModifyingValue = false;
}
updateDatepicker() {
if (this.componentRef) {
let component = this.componentRef.instance;
component.defaultValue = <Date>this.el['dateValue'];
}
}
setInputElDateValue(date) {
if (typeof date === 'string' && date) {
this.el['dateValue'] = this.getDate(date);
} else if (typeof date === 'object') {
this.el['dateValue'] = date
} else if (typeof date === 'undefined') {
this.el['dateValue'] = null;
}
if (this.ctrl) {
this.ctrl.markAsDirty();
}
}
ngOnDestroy(): void {
if (this.sub) {
this.sub.unsubscribe();
}
}
/* input element string value is changed */
inputElValueChanged = (date: string | Date): void => {
this.setInputElDateValue(date);
this.el.value = date.toString();
if (this.ctrl) {
this.ctrl.patchValue(this.el.value);
}
this.ngModel = this.el['dateValue'];
if (this.ngModel) {
this.ngModel.toString = () => { return this.el.value; };
this.ngModelChange.emit(this.ngModel);
}
};
//show datetimePicker element below the current element
showDatetimePicker = (event?): void => {
if (this.componentRef) { /* if already shown, do nothing */
return;
}
let factory = this.resolver.resolveComponentFactory(NguiDatetimePickerComponent);
this.componentRef = this.viewContainerRef.createComponent(factory);
this.nguiDatetimePickerEl = this.componentRef.location.nativeElement;
this.nguiDatetimePickerEl.setAttribute('tabindex', '32767');
this.nguiDatetimePickerEl.setAttribute('draggable', String(this.isDraggable));
this.nguiDatetimePickerEl.addEventListener('mousedown', (event) => {
this.clickedDatetimePicker = true
});
this.nguiDatetimePickerEl.addEventListener('mouseup', (event) => {
this.clickedDatetimePicker = false;
});
//This is for material design. MD has click event to make blur to happen
this.nguiDatetimePickerEl.addEventListener('click', (event) => {
event.stopPropagation();
});
this.nguiDatetimePickerEl.addEventListener('blur', (event) => {
this.hideDatetimePicker();
});
this.nguiDatetimePickerEl.addEventListener('dragstart', this.drag_start, false);
document.body.addEventListener('dragover', this.drag_over, false);
document.body.addEventListener('drop', this.drop, false);
let component = this.componentRef.instance;
component.defaultValue = <Date>this.defaultValue || <Date>this.el['dateValue'];
component.dateFormat = this.dateFormat;
component.dateOnly = this.dateOnly;
component.timeOnly = this.timeOnly;
component.minuteStep = this.minuteStep;
component.minDate = <Date>this.minDate;
component.maxDate = <Date>this.maxDate;
component.minHour = <number>this.minHour;
component.maxHour = <number>this.maxHour;
component.disabledDates = this.disabledDates;
component.showCloseButton = this.closeOnSelect === false;
component.showCloseLayer = this.showCloseLayer;
component.showTodayShortcut = this.showTodayShortcut;
component.showWeekNumbers = this.showWeekNumbers;
this.styleDatetimePicker();
component.selected$.subscribe(this.dateSelected);
component.closing$.subscribe(() => {
this.hideDatetimePicker();
});
//Hack not to fire tab keyup event
// this.justShown = true;
// setTimeout(() => this.justShown = false, 100);
};
dateSelected = (date) => {
this.el.tagName === 'INPUT' && this.inputElValueChanged(date);
this.valueChanged$.emit(date);
if (this.closeOnSelect !== false) {
this.hideDatetimePicker();
} else {
this.nguiDatetimePickerEl.focus();
}
};
hideDatetimePicker = (event?): any => {
if (this.clickedDatetimePicker) {
return false;
} else { /* invoked by function call */
setTimeout(() => { //having exception without setTimeout
if (this.componentRef) {
this.componentRef.destroy();
this.componentRef = undefined;
}
this.popupClosed$.emit(true);
})
}
event && event.stopPropagation();
};
private elementIn(el: Node, containerEl: Node): boolean {
while (el = el.parentNode) {
if (el === containerEl) return true;
}
return false;
}
private styleDatetimePicker() {
// setting position, width, and height of auto complete dropdown
let thisElBCR = this.el.getBoundingClientRect();
// this.nguiDatetimePickerEl.style.minWidth = thisElBCR.width + 'px';
this.nguiDatetimePickerEl.style.position = 'absolute';
this.nguiDatetimePickerEl.style.zIndex = '1000';
this.nguiDatetimePickerEl.style.left = '0';
this.nguiDatetimePickerEl.style.transition = 'height 0.3s ease-in';
this.nguiDatetimePickerEl.style.visibility = 'hidden';
setTimeout(() => {
let thisElBcr = this.el.getBoundingClientRect();
let nguiDatetimePickerElBcr = this.nguiDatetimePickerEl.getBoundingClientRect();
if (thisElBcr.bottom + nguiDatetimePickerElBcr.height > window.innerHeight) {
this.nguiDatetimePickerEl.style.bottom =
(thisElBcr.bottom - window.innerHeight + 15) + 'px';
}
else {
// otherwise, show below
this.nguiDatetimePickerEl.style.top = thisElBcr.height + 'px';
}
this.nguiDatetimePickerEl.style.visibility = 'visible';
});
};
private getDate = (arg: any): Date => {
let date: Date = <Date>arg;
if (typeof arg === 'string') {
date = NguiDatetime.parseDate(arg, this.parseFormat, this.dateFormat);
}
return date;
}
private drag_start = (event) => {
if (document.activeElement.tagName == 'INPUT') {
event.preventDefault();
return false; // block dragging
}
var style = window.getComputedStyle(event.target, null);
event.dataTransfer.setData("text/plain",
(parseInt(style.getPropertyValue("left"), 10) - event.clientX)
+ ','
+ (parseInt(style.getPropertyValue("top"), 10) - event.clientY)
);
}
private drag_over(event) {
event.preventDefault();
return false;
}
private drop = (event) => {
var offset = event.dataTransfer.getData("text/plain").split(',');
this.nguiDatetimePickerEl.style.left = (event.clientX + parseInt(offset[0], 10)) + 'px';
this.nguiDatetimePickerEl.style.top = (event.clientY + parseInt(offset[1], 10)) + 'px';
this.nguiDatetimePickerEl.style.bottom = '';
event.preventDefault();
return false;
}
} | the_stack |
import { expect } from "chai";
import { GeometryQuery } from "../../curve/GeometryQuery";
import { LineSegment3d } from "../../curve/LineSegment3d";
import { LineString3d } from "../../curve/LineString3d";
import { Angle } from "../../geometry3d/Angle";
import { Point3d, Vector3d } from "../../geometry3d/Point3dVector3d";
import { Point3dArray } from "../../geometry3d/PointHelpers";
import { PolygonOps } from "../../geometry3d/PolygonOps";
import { PolyfaceBuilder } from "../../polyface/PolyfaceBuilder";
import { PolyfaceQuery } from "../../polyface/PolyfaceQuery";
import { HalfEdgeGraph } from "../../topology/Graph";
import { HalfEdgePositionDetail, HalfEdgeTopo } from "../../topology/HalfEdgePositionDetail";
import { InsertAndRetriangulateContext } from "../../topology/InsertAndRetriangulateContext";
import { HalfEdgeGraphMerge } from "../../topology/Merging";
import { Triangulator } from "../../topology/Triangulation";
import { Checker } from "../Checker";
import { lisajouePoint3d } from "../geometry3d/PointHelper.test";
import { GeometryCoreTestIO } from "../GeometryCoreTestIO";
import { GraphChecker } from "./Graph.test";
/**
* Output for HalfEdgePositionDetail:
* * If oldDetail is given, line from old to new.
* * For newDetail:
* * HalfEdgeTopo.Face: circle
* * Vertex: tick mark from vertex into its sector.
* * Edge: tick mark from edge position into its face.
* * At end, copy all data fro newDetail to oldDetail.
*/
function showPosition(allGeometry: GeometryQuery[], oldDetail: HalfEdgePositionDetail, newDetail: HalfEdgePositionDetail, markerSize: number,
x0: number, y0: number, z0: number = 0) {
if (!oldDetail.isUnclassified && !newDetail.isUnclassified) {
const point0 = oldDetail.clonePoint();
const point1 = newDetail.clonePoint();
if (!point0.isAlmostEqualMetric(point1))
GeometryCoreTestIO.captureGeometry(allGeometry, LineSegment3d.createCapture(point0, point1), x0, y0, z0);
}
if (newDetail.getTopo() === HalfEdgeTopo.Face) {
GeometryCoreTestIO.createAndCaptureXYCircle(allGeometry, newDetail.clonePoint(), markerSize, x0, y0, z0);
} else if (newDetail.getTopo() === HalfEdgeTopo.Vertex) {
const nodeB = newDetail.node!;
const nodeC = nodeB.faceSuccessor;
const nodeA = nodeB.facePredecessor;
const pointB = nodeB.fractionToPoint3d(0.0);
const vectorBC = Vector3d.createStartEnd(nodeB, nodeC);
const vectorBA = Vector3d.createStartEnd(nodeB, nodeA);
const theta = vectorBC.angleToXY(vectorBA);
const bisector = vectorBC.rotateXY(Angle.createRadians(0.5 * theta.radians));
GeometryCoreTestIO.captureGeometry(allGeometry, LineSegment3d.create(pointB, pointB.plusScaled(bisector, markerSize)), x0, y0, z0);
} else if (newDetail.getTopo() === HalfEdgeTopo.Edge) {
const node0 = newDetail.node!;
const point0 = node0.fractionToPoint3d(0.0);
const point1 = node0.fractionToPoint3d(1.0);
const pointB = point0.interpolate(newDetail.edgeFraction!, point1);
const vector01 = Vector3d.createStartEnd(point0, point1);
vector01.normalizeInPlace();
vector01.rotate90CCWXY(vector01);
const pointC = pointB.plusScaled(vector01, markerSize);
GeometryCoreTestIO.captureGeometry(allGeometry, LineSegment3d.create(pointB, pointC), x0, y0, z0);
} else {
console.log(" unknown topo type", newDetail.getTopo());
}
oldDetail.setFrom(newDetail);
}
describe("InsertAndRetriangulateContext", () => {
it("MoveInGrid", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const graph = new HalfEdgeGraph();
const numX = 5;
const numY = 4;
const x0 = 0;
let y0 = 0;
const yStep = numY + 1;
const aa = 0.06;
// make horizontal edges
for (let j = 0; j < numY; j++) {
for (let i = 0; i + 1 < numX; i++)
graph.addEdgeXY(i, j, i + 1, j);
}
// make horizontal edges
for (let i = 0; i < numX; i++) {
for (let j = 0; j + 1 < numY; j++)
graph.addEdgeXY(i, j, i, j + 1);
}
const z1 = 0.05; // draw linework a little above the polyface.
HalfEdgeGraphMerge.clusterAndMergeXYTheta(graph);
const context = InsertAndRetriangulateContext.create(graph);
const position = HalfEdgePositionDetail.create();
const oldPosition = HalfEdgePositionDetail.create();
GraphChecker.captureAnnotatedGraph(allGeometry, graph, x0, y0);
for (const point of [
Point3d.create(0.5, 1.0), // jump onto an edge
Point3d.create(1.5, 1.0), // move along a grid line, through a vertex to middle of next edge
Point3d.create(3.5, 1.0), // further along the grid line, jumping along an entire edge
Point3d.create(1.5, 0.5), // back cross some edges into a face
Point3d.create(0.5, 1.5),
Point3d.create(1.2, 2.8),
Point3d.create(1.8, 2.0),
Point3d.create(1.8, 1.0),
Point3d.create(2.0, 2.0),
Point3d.create(2.5, 0.5),
Point3d.create(0.2, 0.6),
Point3d.create(0.3, 0.4),
Point3d.create(1.2, 0.4),
Point3d.create(0.5, 1.0),
Point3d.create(2.5, 1.0),
Point3d.create(2.2, 1.0),
Point3d.create(2.8, 1.0),
Point3d.create(2.0, 1.0),
Point3d.create(1.5, 1.0),
Point3d.create(1.0, 1.0),
Point3d.create(0.0, 1.0),
Point3d.create(6.0, 1.0),
]) {
y0 += yStep;
const polyface = PolyfaceBuilder.graphToPolyface(graph);
GeometryCoreTestIO.captureCloneGeometry(allGeometry, polyface, x0, y0);
context.moveToPoint(position, point,
(positionA: HalfEdgePositionDetail) => {
showPosition(allGeometry, oldPosition, positionA, aa * 0.5, x0, y0, z1);
return true;
});
// GraphChecker.captureAnnotatedGraph(allGeometry, graph, x0, y0);
showPosition(allGeometry, oldPosition, position, aa, x0, y0, z1);
}
oldPosition.resetAsUnknown();
context.resetSearch(Point3d.create(1.5, 0.5), 0);
ck.testExactNumber(HalfEdgeTopo.Vertex, context.currentPosition.getTopo(), "Reset to vertex");
context.resetSearch(Point3d.create(1.5, 0.5), 1);
ck.testExactNumber(HalfEdgeTopo.Edge, context.currentPosition.getTopo(), "Reset to edge search");
// hit the "vertex sector" case. ..
context.resetSearch(Point3d.create(-0.5, -0.5), 1);
ck.testExactNumber(HalfEdgeTopo.Vertex, context.currentPosition.getTopo(), "Reset to edge search");
GeometryCoreTestIO.saveGeometry(allGeometry, "InsertAndRetriangulateContext", "moveTo");
expect(ck.getNumErrors()).equals(0);
});
it("insertAndRetriangulate", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const graph1 = new HalfEdgeGraph();
const numX = 4;
const numY = 4;
let x0 = 10; // keep right to allow side by side with "just move"
let y0 = 0;
const yStep = numY + 5;
const xStep = numX + 5;
// make horizontal edges
for (let j = 0; j < numY; j++) {
for (let i = 0; i + 1 < numX; i++)
graph1.addEdgeXY(i, j, i + 1, j);
}
// make horizontal edges
for (let i = 0; i < numX; i++) {
for (let j = 0; j + 1 < numY; j++)
graph1.addEdgeXY(i, j, i, j + 1);
}
HalfEdgeGraphMerge.clusterAndMergeXYTheta(graph1);
GraphChecker.captureAnnotatedGraph(allGeometry, graph1, x0, y0);
const context1 = InsertAndRetriangulateContext.create(graph1);
const graph2 = new HalfEdgeGraph();
const points = [];
for (let degrees = 0; degrees < 359; degrees += 25) {
points.push(Point3d.create(2 + 3.5 * Math.cos(Angle.degreesToRadians(degrees)), 2 + 3 * Math.sin(Angle.degreesToRadians(degrees))));
}
// points.push(points[0].clone());
Triangulator.createFaceLoopFromCoordinates(graph2, points, true, true);
GraphChecker.captureAnnotatedGraph(allGeometry, graph2, x0 + 20, y0);
HalfEdgeGraphMerge.clusterAndMergeXYTheta(graph2);
GraphChecker.captureAnnotatedGraph(allGeometry, graph2, x0 + 30, y0);
const context2 = InsertAndRetriangulateContext.create(graph2);
for (const context of [context1, context2]) {
y0 = 0;
let numPointsInserted = 0;
for (const point of [
Point3d.create(0.5, 0.6), // in face
Point3d.create(1.0, 0.6), // move to edge
Point3d.create(1.5, 0.6), // cross one edge into a face
Point3d.create(0.5, 0.7), // back to first face
Point3d.create(0.5, 1.0), // up to an edge
Point3d.create(1, 1), // directly to a vertex
Point3d.create(0.5, 1.0), // back to edge
Point3d.create(1.5, 1.0), // through vertex to mid edge
Point3d.create(0.5, 2.0), // up to a higher edge
Point3d.create(2.5, 2.0), // along edge, through 2 vertices
Point3d.create(2, 2), // back up to a vertex
Point3d.create(2, 1), // move to another
Point3d.create(1, 1), // and another
Point3d.create(0.5, 1.5), // face interior
Point3d.create(1, 1), // back to vertex
Point3d.create(0.5, 2), // mid edge
Point3d.create(0.5, 2), // sit there again
Point3d.create(0.2, 2), // same edge
Point3d.create(0.5, 1.5), // in face
Point3d.create(0.5, 1.5), // stay
Point3d.create(1.0, 1.0), // at vertex
Point3d.create(1.0, 1.0), // stay
]) {
// console.log("insertAndRetriangulate", point);
context.insertAndRetriangulate(point, true);
numPointsInserted++;
if (numPointsInserted < 4) {
y0 += yStep;
GeometryCoreTestIO.createAndCaptureXYCircle(allGeometry, point, 0.03, x0, y0);
GraphChecker.captureAnnotatedGraph(allGeometry, context.graph, x0, y0);
const polyfaceA = PolyfaceBuilder.graphToPolyface(context.graph);
GeometryCoreTestIO.captureGeometry(allGeometry, polyfaceA, x0 + xStep, y0);
}
// GraphChecker.dumpGraph (graph);
}
y0 += 2 * yStep;
const polyfaceC = PolyfaceBuilder.graphToPolyface(context.graph);
GeometryCoreTestIO.captureGeometry(allGeometry, polyfaceC, x0 + xStep, y0);
for (let flip = 0; flip < 1; flip++) {
const numFlip = Triangulator.flipTriangles(context.graph);
ck.testExactNumber(0, numFlip, "Expect no flips from global sweep after incremental flips during insert.");
// console.log("numFlip " + numFlip);
const polyfaceB = PolyfaceBuilder.graphToPolyface(context.graph);
GeometryCoreTestIO.captureGeometry(allGeometry, polyfaceB, x0 + (2 + flip) * xStep, y0);
}
x0 += 10 * xStep;
}
GeometryCoreTestIO.saveGeometry(allGeometry, "InsertAndRetriangulateContext", "insertAndRetriangulate");
expect(ck.getNumErrors()).equals(0);
});
// cspell:word lisajoue
it("TriangulateInHull", () => {
const ck = new Checker();
const allGeometry: GeometryQuery[] = [];
const a = 3.29;
const dTheta = 0.34;
let x0 = 0;
// lisajouePoint3d makes points smeared within distance 1 of the origin.
// nonzero yShift gradually makes points move upward
// (nb the hull process makes points mostly move left to right)
for (const yShiftStep of [0.0, 0.01, 0.05]) {
for (const numPoints of [9, 25, 1024, 4096 /* , 16982, 16982, 16982 */]) {
let y0 = 0;
// console.log("Triangulate", numPoints);
const points: Point3d[] = [];
let yShift = 0.0;
for (let theta = 0.01 * (numPoints - 8); points.length < numPoints; theta += dTheta) {
const point = lisajouePoint3d(theta * theta, a, 0);
point.y += yShift;
yShift += yShiftStep;
points.push(point);
}
const yShiftDisplay = yShift + 3;
/*
const graph = new HalfEdgeGraph();
const context = InsertAndRetriangulateContext.create(graph);
Triangulator.createFaceLoopFromCoordinates(graph, hull, true, true);
HalfEdgeGraphMerge.clusterAndMergeXYTheta(graph);
GeometryCoreTestIO.captureGeometry(allGeometry, LineString3d.create(hull), x0, y0);
GeometryCoreTestIO.captureGeometry(allGeometry, LineString3d.create(interior), x0, y0);
// let k = 0;
let numInsert = 0;
for (const p of interior) {
context.insertAndRetriangulate(p, true);
numInsert++;
if (numInsert > 16) {
context.reset();
Triangulator.flipTriangles(context.graph);
// console.log (" intermediate flips " + numFlip);
numInsert = 0;
}
}
GeometryCoreTestIO.captureGeometry(allGeometry, PolyfaceBuilder.graphToPolyface(context.graph!), x0, y0 + 5);
// console.log("Begin flips");
for (let i = 0; i < 15; i++) {
const numFlip = Triangulator.flipTriangles(graph);
if (numFlip === 0)
break;
// console.log(" flip " + numFlip);
GeometryCoreTestIO.captureGeometry(allGeometry, PolyfaceBuilder.graphToPolyface(context.graph!), x0, y0 + 10 + i * 4);
}
*/
const hull: Point3d[] = [];
const interior: Point3d[] = [];
Point3dArray.computeConvexHullXY(points, hull, interior, true);
// GeometryCoreTestIO.createAndCaptureXYCircle(allGeometry, interior, 0.001, x0, y0);
// GeometryCoreTestIO.captureGeometry(allGeometry, LineString3d.create(hull), x0, y0);
// y0 += yShiftDisplay;
if (numPoints < 100) {
const r = 0.002;
GeometryCoreTestIO.createAndCaptureXYCircle(allGeometry, points, r, x0, y0);
y0 += yShiftDisplay;
GeometryCoreTestIO.captureGeometry(allGeometry, LineString3d.create(hull), x0, y0);
GeometryCoreTestIO.createAndCaptureXYCircle(allGeometry, interior, r, x0, y0);
y0 += yShiftDisplay;
}
GeometryCoreTestIO.captureGeometry(allGeometry, LineString3d.create(hull), x0, y0);
GeometryCoreTestIO.captureGeometry(allGeometry, LineString3d.create(interior), x0, y0);
// GeometryCoreTestIO.captureGeometry(allGeometry, LineString3d.create(interior), x0, y0);
const timerName = `before pointsToTriangulatedPolyface ${numPoints}`;
console.time(timerName);
const polyface = PolyfaceBuilder.pointsToTriangulatedPolyface(points);
console.timeEnd(timerName);
y0 += yShiftDisplay;
GeometryCoreTestIO.captureGeometry(allGeometry, polyface, x0, y0);
if (ck.testDefined(polyface, "polyface triangulation") && polyface) {
const polyfaceArea = PolyfaceQuery.sumFacetAreas(polyface);
const hullArea = PolygonOps.areaXY(hull);
ck.testCoordinate(polyfaceArea, hullArea, `mesh, hull area match for ${numPoints}point triangulation`);
}
x0 += 5;
}
}
// console.log ("write file");
GeometryCoreTestIO.saveGeometry(allGeometry, "InsertAndRetriangulateContext", "TriangulateInHull");
expect(ck.getNumErrors()).equals(0);
});
}); | the_stack |
const fromCharCode = String.fromCharCode;
const encoderRegexp = /[\x80-\uD7ff\uDC00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]?/g;
const tmpBufferU16 = new Uint16Array(32);
export class TextDecoder {
decode(inputArrayOrBuffer: Uint8Array | ArrayBuffer | SharedArrayBuffer): string {
const inputAs8 = inputArrayOrBuffer instanceof Uint8Array ? inputArrayOrBuffer : new Uint8Array(inputArrayOrBuffer);
let resultingString = '',
tmpStr = '',
index = 0,
nextEnd = 0,
cp0 = 0,
codePoint = 0,
minBits = 0,
cp1 = 0,
pos = 0,
tmp = -1;
const len = inputAs8.length | 0;
const lenMinus32 = (len - 32) | 0;
// Note that tmp represents the 2nd half of a surrogate pair incase a surrogate gets divided between blocks
for (; index < len; ) {
nextEnd = index <= lenMinus32 ? 32 : (len - index) | 0;
for (; pos < nextEnd; index = (index + 1) | 0, pos = (pos + 1) | 0) {
cp0 = inputAs8[index] & 0xff;
switch (cp0 >> 4) {
case 15:
cp1 = inputAs8[(index = (index + 1) | 0)] & 0xff;
if (cp1 >> 6 !== 0b10 || 0b11110111 < cp0) {
index = (index - 1) | 0;
break;
}
codePoint = ((cp0 & 0b111) << 6) | (cp1 & 0b00111111);
minBits = 5; // 20 ensures it never passes -> all invalid replacements
cp0 = 0x100; // keep track of th bit size
case 14:
cp1 = inputAs8[(index = (index + 1) | 0)] & 0xff;
codePoint <<= 6;
codePoint |= ((cp0 & 0b1111) << 6) | (cp1 & 0b00111111);
minBits = cp1 >> 6 === 0b10 ? (minBits + 4) | 0 : 24; // 24 ensures it never passes -> all invalid replacements
cp0 = (cp0 + 0x100) & 0x300; // keep track of th bit size
case 13:
case 12:
cp1 = inputAs8[(index = (index + 1) | 0)] & 0xff;
codePoint <<= 6;
codePoint |= ((cp0 & 0b11111) << 6) | (cp1 & 0b00111111);
minBits = (minBits + 7) | 0;
// Now, process the code point
if (index < len && cp1 >> 6 === 0b10 && codePoint >> minBits && codePoint < 0x110000) {
cp0 = codePoint;
codePoint = (codePoint - 0x10000) | 0;
if (0 <= codePoint /*0xffff < codePoint*/) {
// BMP code point
//nextEnd = nextEnd - 1|0;
tmp = ((codePoint >> 10) + 0xd800) | 0; // highSurrogate
cp0 = ((codePoint & 0x3ff) + 0xdc00) | 0; // lowSurrogate (will be inserted later in the switch-statement)
if (pos < 31) {
// notice 31 instead of 32
tmpBufferU16[pos] = tmp;
pos = (pos + 1) | 0;
tmp = -1;
} else {
// else, we are at the end of the inputAs8 and let tmp0 be filled in later on
// NOTE that cp1 is being used as a temporary variable for the swapping of tmp with cp0
cp1 = tmp;
tmp = cp0;
cp0 = cp1;
}
} else nextEnd = (nextEnd + 1) | 0; // because we are advancing i without advancing pos
} else {
// invalid code point means replacing the whole thing with null replacement characters
cp0 >>= 8;
index = (index - cp0 - 1) | 0; // reset index back to what it was before
cp0 = 0xfffd;
}
// Finally, reset the variables for the next go-around
minBits = 0;
codePoint = 0;
nextEnd = index <= lenMinus32 ? 32 : (len - index) | 0;
/*case 11:
case 10:
case 9:
case 8:
codePoint ? codePoint = 0 : cp0 = 0xfffd; // fill with invalid replacement character
case 7:
case 6:
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
tmpBufferU16[pos] = cp0;
continue;*/
default:
tmpBufferU16[pos] = cp0; // fill with invalid replacement character
continue;
case 11:
case 10:
case 9:
case 8:
}
tmpBufferU16[pos] = 0xfffd; // fill with invalid replacement character
}
tmpStr += fromCharCode(
tmpBufferU16[0],
tmpBufferU16[1],
tmpBufferU16[2],
tmpBufferU16[3],
tmpBufferU16[4],
tmpBufferU16[5],
tmpBufferU16[6],
tmpBufferU16[7],
tmpBufferU16[8],
tmpBufferU16[9],
tmpBufferU16[10],
tmpBufferU16[11],
tmpBufferU16[12],
tmpBufferU16[13],
tmpBufferU16[14],
tmpBufferU16[15],
tmpBufferU16[16],
tmpBufferU16[17],
tmpBufferU16[18],
tmpBufferU16[19],
tmpBufferU16[20],
tmpBufferU16[21],
tmpBufferU16[22],
tmpBufferU16[23],
tmpBufferU16[24],
tmpBufferU16[25],
tmpBufferU16[26],
tmpBufferU16[27],
tmpBufferU16[28],
tmpBufferU16[29],
tmpBufferU16[30],
tmpBufferU16[31]
);
if (pos < 32) tmpStr = tmpStr.slice(0, (pos - 32) | 0); //-(32-pos));
if (index < len) {
//fromCharCode.apply(0, tmpBufferU16 : Uint8Array ? tmpBufferU16.subarray(0,pos) : tmpBufferU16.slice(0,pos));
tmpBufferU16[0] = tmp;
pos = ~tmp >>> 31; //tmp !== -1 ? 1 : 0;
tmp = -1;
if (tmpStr.length < resultingString.length) continue;
} else if (tmp !== -1) {
tmpStr += fromCharCode(tmp);
}
resultingString += tmpStr;
tmpStr = '';
}
return resultingString;
}
}
//////////////////////////////////////////////////////////////////////////////////////
function encoderReplacer(nonAsciiChars: string) {
// make the UTF string into a binary UTF-8 encoded string
let point = nonAsciiChars.charCodeAt(0) | 0;
if (0xd800 <= point) {
if (point <= 0xdbff) {
const nextcode = nonAsciiChars.charCodeAt(1) | 0; // defaults to 0 when NaN, causing null replacement character
if (0xdc00 <= nextcode && nextcode <= 0xdfff) {
//point = ((point - 0xD800)<<10) + nextcode - 0xDC00 + 0x10000|0;
point = ((point << 10) + nextcode - 0x35fdc00) | 0;
if (point > 0xffff)
return fromCharCode(
(0x1e /*0b11110*/ << 3) | (point >> 18),
(0x2 /*0b10*/ << 6) | ((point >> 12) & 0x3f) /*0b00111111*/,
(0x2 /*0b10*/ << 6) | ((point >> 6) & 0x3f) /*0b00111111*/,
(0x2 /*0b10*/ << 6) | (point & 0x3f) /*0b00111111*/
);
} else point = 65533 /*0b1111111111111101*/; //return '\xEF\xBF\xBD';//fromCharCode(0xef, 0xbf, 0xbd);
} else if (point <= 0xdfff) {
point = 65533 /*0b1111111111111101*/; //return '\xEF\xBF\xBD';//fromCharCode(0xef, 0xbf, 0xbd);
}
}
/*if (point <= 0x007f) return nonAsciiChars;
else */ if (point <= 0x07ff) {
return fromCharCode((0x6 << 5) | (point >> 6), (0x2 << 6) | (point & 0x3f));
} else
return fromCharCode(
(0xe /*0b1110*/ << 4) | (point >> 12),
(0x2 /*0b10*/ << 6) | ((point >> 6) & 0x3f) /*0b00111111*/,
(0x2 /*0b10*/ << 6) | (point & 0x3f) /*0b00111111*/
);
}
export class TextEncoder {
public encode(inputString: string): Uint8Array {
// 0xc0 => 0b11000000; 0xff => 0b11111111; 0xc0-0xff => 0b11xxxxxx
// 0x80 => 0b10000000; 0xbf => 0b10111111; 0x80-0xbf => 0b10xxxxxx
const encodedString = inputString === void 0 ? '' : '' + inputString,
len = encodedString.length | 0;
let result = new Uint8Array(((len << 1) + 8) | 0);
let tmpResult: Uint8Array;
let i = 0,
pos = 0,
point = 0,
nextcode = 0;
let upgradededArraySize = !Uint8Array; // normal arrays are auto-expanding
for (i = 0; i < len; i = (i + 1) | 0, pos = (pos + 1) | 0) {
point = encodedString.charCodeAt(i) | 0;
if (point <= 0x007f) {
result[pos] = point;
} else if (point <= 0x07ff) {
result[pos] = (0x6 << 5) | (point >> 6);
result[(pos = (pos + 1) | 0)] = (0x2 << 6) | (point & 0x3f);
} else {
widenCheck: {
if (0xd800 <= point) {
if (point <= 0xdbff) {
nextcode = encodedString.charCodeAt((i = (i + 1) | 0)) | 0; // defaults to 0 when NaN, causing null replacement character
if (0xdc00 <= nextcode && nextcode <= 0xdfff) {
//point = ((point - 0xD800)<<10) + nextcode - 0xDC00 + 0x10000|0;
point = ((point << 10) + nextcode - 0x35fdc00) | 0;
if (point > 0xffff) {
result[pos] = (0x1e /*0b11110*/ << 3) | (point >> 18);
result[(pos = (pos + 1) | 0)] = (0x2 /*0b10*/ << 6) | ((point >> 12) & 0x3f) /*0b00111111*/;
result[(pos = (pos + 1) | 0)] = (0x2 /*0b10*/ << 6) | ((point >> 6) & 0x3f) /*0b00111111*/;
result[(pos = (pos + 1) | 0)] = (0x2 /*0b10*/ << 6) | (point & 0x3f) /*0b00111111*/;
continue;
}
break widenCheck;
}
point = 65533 /*0b1111111111111101*/; //return '\xEF\xBF\xBD';//fromCharCode(0xef, 0xbf, 0xbd);
} else if (point <= 0xdfff) {
point = 65533 /*0b1111111111111101*/; //return '\xEF\xBF\xBD';//fromCharCode(0xef, 0xbf, 0xbd);
}
}
if (!upgradededArraySize && i << 1 < pos && i << 1 < ((pos - 7) | 0)) {
upgradededArraySize = true;
tmpResult = new Uint8Array(len * 3);
tmpResult.set(result);
result = tmpResult;
}
}
result[pos] = (0xe /*0b1110*/ << 4) | (point >> 12);
result[(pos = (pos + 1) | 0)] = (0x2 /*0b10*/ << 6) | ((point >> 6) & 0x3f) /*0b00111111*/;
result[(pos = (pos + 1) | 0)] = (0x2 /*0b10*/ << 6) | (point & 0x3f) /*0b00111111*/;
}
}
return Uint8Array ? result.subarray(0, pos) : result.slice(0, pos);
}
public encodeInto(inputString: string, u8Arr: Uint8Array): { written: number; read: number } {
const encodedString = inputString === void 0 ? '' : ('' + inputString).replace(encoderRegexp, encoderReplacer);
let len = encodedString.length | 0,
i = 0,
char = 0,
read = 0;
const u8ArrLen = u8Arr.length | 0;
const inputLength = inputString.length | 0;
if (u8ArrLen < len) len = u8ArrLen;
putChars: {
for (; i < len; i = (i + 1) | 0) {
char = encodedString.charCodeAt(i) | 0;
switch (char >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
read = (read + 1) | 0;
// extension points:
case 8:
case 9:
case 10:
case 11:
break;
case 12:
case 13:
if (((i + 1) | 0) < u8ArrLen) {
read = (read + 1) | 0;
break;
}
case 14:
if (((i + 2) | 0) < u8ArrLen) {
//if (!(char === 0xEF && encodedString.substr(i+1|0,2) === "\xBF\xBD"))
read = (read + 1) | 0;
break;
}
case 15:
if (((i + 3) | 0) < u8ArrLen) {
read = (read + 1) | 0;
break;
}
default:
break putChars;
}
//read = read + ((char >> 6) !== 2) |0;
u8Arr[i] = char;
}
}
return { written: i, read: inputLength < read ? inputLength : read };
}
} | the_stack |
import { CRUDEvents, LocalStorage } from "./storage";
import { StoreChangeEvent } from "./storage";
import { ModelSchema } from "./ModelSchema";
import { PushStream, ObservablePushStream } from "./utils/PushStream";
import { Filter } from "./filters";
import { ModelReplicationConfig } from "./replication/api/ReplicationConfig";
import invariant from "tiny-invariant";
import { ModelChangeReplication } from "./replication/mutations/MutationsQueue";
import { v4 as uuidv4 } from "uuid";
import { createLogger } from "./utils/logger";
import { FetchReplicator } from "./replication/fetch/FetchReplicator";
const logger = createLogger("model");
/**
* Options that describe model field
*/
export interface FieldOptions {
/** GraphQL type */
type: string;
/** GraphQL key */
key: string;
// TODO
format?: {};
}
const CLIENT_ID_PREFIX = "storeclient.";
/**
* Defines the properties expected in the Fields object for a model
*/
export type Fields<T> = {
[P in keyof T]: FieldOptions
};
/**
* Model Config options
*/
export interface ModelConfig<T = unknown> {
/**
* Model name
*/
name: string;
/**
* Model store name, defualts to `user_${name}`
*/
storeName?: string;
/**
* Model fields
*/
fields: Fields<T>;
}
/**
* Provides CRUD capabilities for a model
*/
export class Model<T = unknown> {
public schema: ModelSchema<T>;
public replicationConfig: ModelReplicationConfig | undefined;
public replication?: ModelChangeReplication;
public changeEventStream: PushStream<StoreChangeEvent>;
private storage: LocalStorage;
private replicator?: FetchReplicator;
constructor(
schema: ModelSchema<T>,
storage: LocalStorage,
replicationConfig?: ModelReplicationConfig
) {
this.changeEventStream = new ObservablePushStream();
this.schema = schema;
this.storage = storage;
this.replicationConfig = replicationConfig;
this.storage.addStore(this.schema);
}
public getFields() {
return this.schema.getFields();
}
public getName() {
return this.schema.getName();
}
public getStoreName() {
return this.schema.getStoreName();
}
public getSchema() {
return this.schema;
}
public query(filter?: Filter<T>) {
if (!filter) { return this.storage.query(this.schema.getStoreName()); }
return this.storage.query(this.schema.getStoreName(), filter);
}
public queryById(id: string) {
return this.storage.queryById(this.schema.getStoreName(), this.schema.getPrimaryKey(), id);
}
public async save(input: Partial<T>): Promise<T> {
input = this.addPrimaryKeyIfNeeded(input);
try {
const data = await this.storage.save(this.schema.getStoreName(), input);
await this.replication?.saveChangeForReplication(this, data, CRUDEvents.ADD, this.storage);
const event = {
eventType: CRUDEvents.ADD,
data: [data]
};
this.changeEventStream.publish(event);
return data;
} catch (error) {
throw error;
}
}
public setReplicator(replicator: FetchReplicator) {
this.replicator = replicator;
}
public getReplicator(): FetchReplicator | undefined {
return this.replicator;
}
/**
* Provide a single method to apply optional filter
* to model replicator and then start replication
*
* @param filter
*/
public startReplication(filter?: Filter) {
if (filter) {
this.replicator?.applyFilter(filter);
}
this.replicator?.startReplication();
}
/**
* Apply filters to the model's fetch replicator
*
* @param filter
*/
public applyFilter(filter: Filter) {
this.replicator?.applyFilter({ filter });
}
/**
* Save changes (if it doesn't exist or update records with partial input
*
* @param input
*/
public async saveOrUpdate(input: Partial<T>): Promise<T> {
input = this.addPrimaryKeyIfNeeded(input);
try {
const data = await this.storage.saveOrUpdate(this.schema.getStoreName(), this.schema.getPrimaryKey(), input);
await this.replication?.saveChangeForReplication(this, data, CRUDEvents.ADD, this.storage);
const event = {
eventType: CRUDEvents.ADD,
data: [data]
};
this.changeEventStream.publish(event);
return data;
} catch (error) {
throw error;
}
}
/**
* Update set of the objects by setting common values.
*
* @param input
* @param filter
*/
public async update(input: Partial<T>, filter?: Filter<T>) {
invariant(filter, "filter needs to be provided for update");
try {
const data = await this.storage.update(this.schema.getStoreName(), input, filter);
await this.replication?.saveChangeForReplication(this, data, CRUDEvents.UPDATE, this.storage);
const event = {
eventType: CRUDEvents.UPDATE,
data
};
this.changeEventStream.publish(event);
return data;
} catch (error) {
throw error;
}
}
/**
* Update object by detecting it's id and using rest of the fields that are being merged with the original object
*
* @param input
*/
public async updateById(input: Partial<T>) {
const primaryKey = this.schema.getPrimaryKey();
invariant((input as any)[primaryKey], "Missing primary key for update");
try {
const data = await this.storage.updateById(this.schema.getStoreName(), this.schema.getPrimaryKey(), input);
await this.replication?.saveChangeForReplication(this, data, CRUDEvents.UPDATE, this.storage);
const event = {
eventType: CRUDEvents.UPDATE,
data: [data]
};
this.changeEventStream.publish(event);
return data;
} catch (error) {
throw error;
}
}
/**
* Remove any set of objects using filter
*
* @param filter
*/
public async remove(filter: Filter<T>) {
invariant(filter, "filter needs to be provided for deletion");
try {
const primaryKey = this.schema.getPrimaryKey();
const data = await this.storage.remove(this.schema.getStoreName(), primaryKey, filter);
await this.replication?.saveChangeForReplication(this, data, CRUDEvents.DELETE, this.storage);
const event = {
eventType: CRUDEvents.DELETE,
data
};
this.changeEventStream.publish(event);
return data;
} catch (error) {
throw error;
}
}
/**
* Remove objects by it's id (using index)
*
* @param input object that needs to be removed
* We need to pass entire object to ensure it's consistency (version)
*/
public async removeById(input: any) {
const primaryKey = this.schema.getPrimaryKey();
invariant((input as any)[primaryKey], "Missing primary key for delete");
try {
const data = await this.storage.removeById(this.schema.getStoreName(), this.schema.getPrimaryKey(), input);
await this.replication?.saveChangeForReplication(this, data, CRUDEvents.DELETE, this.storage);
const event = {
eventType: CRUDEvents.DELETE,
// TODO Why array here?
data: [data]
};
this.changeEventStream.publish(event);
return data;
} catch (error) {
throw error;
}
}
/**
* Subscribe to **local** changes that happen in the model
*
* TODO add ability to filter subscriptions
*
* @param eventType - allows you to specify what event type you are interested in.
* @param listener
*/
public subscribe(listener: (event: StoreChangeEvent) => void, eventTypes?: CRUDEvents[]) {
return this.changeEventStream.subscribe((event: StoreChangeEvent) => {
listener(event);
}, (event: StoreChangeEvent) => {
if (eventTypes) {
return eventTypes.includes(event.eventType);
}
return true;
});
}
/**
* Process remote changes
*
* @param result result from delta
*/
public async processDeltaChanges(dataResult: any[], type?: CRUDEvents): Promise<void> {
if (!dataResult || dataResult.length === 0) {
logger("Delta processing: No changes");
return;
}
const db = this.storage;
const store = this.schema.getStoreName();
const primaryKey = this.schema.getPrimaryKey();
for (const item of dataResult) {
// Remove GraphQL internal information
delete item.__typename;
let data;
let eventType;
if (item._deleted) {
logger("Delta processing: deleting item");
data = await await db.removeById(store, primaryKey, item);
eventType = CRUDEvents.DELETE;
} else {
const exist = await db.queryById(store, primaryKey, item[primaryKey]);
if (exist) {
logger("Delta processing: updating item");
eventType = CRUDEvents.UPDATE;
data = await db.updateById(this.schema.getStoreName(), primaryKey, item);
} else {
logger("Delta processing: adding item");
eventType = CRUDEvents.ADD;
data = await db.save(this.schema.getStoreName(), item);
}
if (!data) {
logger("Failed to update items in database");
return;
}
}
const event = {
eventType,
// TODO this should be non array
data: [data]
};
this.changeEventStream.publish(event);
}
}
/**
* **Internal method**
*
* Process remote changes
*
* @param result result from subscription
*/
public async processSubscriptionChanges(dataResult: any, type: CRUDEvents): Promise<void> {
if (!dataResult) {
logger("Subscription returned no result. If you see this something is wrong.");
return;
}
try {
// Remove GraphQL internal information
delete dataResult.__typename;
logger("Retrieved object from subscription");
const store = this.schema.getStoreName();
const primaryKey = this.schema.getPrimaryKey();
if (type === CRUDEvents.ADD) {
await this.storage.save(this.schema.getStoreName(), dataResult);
}
if (type === CRUDEvents.UPDATE) {
await this.storage.updateById(this.schema.getStoreName(), primaryKey, dataResult);
}
if (type === CRUDEvents.DELETE) {
await await this.storage.removeById(store, primaryKey, dataResult);
}
const event = {
eventType: type,
// TODO this should be non array
data: [dataResult]
};
this.changeEventStream.publish(event);
} catch (error) {
logger("Error when processing subscription" + JSON.stringify(error));
}
}
/**
* Checks if model has client side id.
* Usually this means that model was not replicated and id from the server was not assigned.
*/
public hasClientID() {
return this.schema.getPrimaryKey().startsWith(CLIENT_ID_PREFIX);
}
private addPrimaryKeyIfNeeded(input: any) {
const primaryKey = this.schema.getPrimaryKey();
if (!input[primaryKey]) {
input[primaryKey] = CLIENT_ID_PREFIX + uuidv4();
}
return input;
}
} | the_stack |
import { ContainerAdapterClient } from '../../container_adapter_client'
import { MasterNodeRegTestContainer } from '@defichain/testcontainers'
import {
ICXGenericResult,
ICXOffer,
ICXOfferInfo,
ICXOrder,
ICXOrderInfo,
ICXOrderStatus,
ICXOrderType
} from '../../../src/category/icxorderbook'
import BigNumber from 'bignumber.js'
import {
accountBTC,
accountDFI,
DEX_DFI_PER_BTC_RATE,
ICX_TAKERFEE_PER_BTC,
ICXSetup,
idDFI,
symbolDFI
} from './icx_setup'
import { RpcApiError } from '@defichain/jellyfish-api-core'
describe('ICXOrderBook.makeOffer', () => {
const container = new MasterNodeRegTestContainer()
const client = new ContainerAdapterClient(container)
const icxSetup = new ICXSetup(container, client)
beforeAll(async () => {
await container.start()
await container.waitForReady()
await container.waitForWalletCoinbaseMaturity()
await icxSetup.createAccounts()
await icxSetup.createBTCToken()
await icxSetup.initializeTokensIds()
await icxSetup.mintBTCtoken(100)
await icxSetup.fundAccount(accountDFI, symbolDFI, 500)
await icxSetup.fundAccount(accountBTC, symbolDFI, 10) // for fee
await icxSetup.createBTCDFIPool()
await icxSetup.addLiquidityToBTCDFIPool(1, 100)
await icxSetup.setTakerFee(0.001)
})
afterAll(async () => {
await container.stop()
})
afterEach(async () => {
await icxSetup.closeAllOpenOffers()
})
it('should make an partial offer to an sell DFI order', async () => {
const accountDFIBeforeOrder: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber')
// create order - maker
const order: ICXOrder = {
tokenFrom: idDFI,
chainTo: 'BTC',
ownerAddress: accountDFI,
receivePubkey: '037f9563f30c609b19fd435a19b8bde7d6db703012ba1aba72e9f42a87366d1941',
amountFrom: new BigNumber(15),
orderPrice: new BigNumber(0.01)
}
const createOrderResults: ICXGenericResult = await client.icxorderbook.createOrder(order, [])
const createOrderTxId = createOrderResults.txid
await container.generate(1)
// list ICX orders
const ordersAfterCreateOrder: Record<string, ICXOrderInfo | ICXOfferInfo> = await client.call('icx_listorders', [], 'bignumber')
expect((ordersAfterCreateOrder as Record<string, ICXOrderInfo>)[createOrderTxId]).toStrictEqual(
{
status: ICXOrderStatus.OPEN,
type: ICXOrderType.INTERNAL,
tokenFrom: symbolDFI,
chainTo: order.chainTo,
receivePubkey: order.receivePubkey,
ownerAddress: order.ownerAddress,
amountFrom: order.amountFrom,
amountToFill: order.amountFrom,
orderPrice: order.orderPrice,
amountToFillInToAsset: order.amountFrom.multipliedBy(order.orderPrice),
height: expect.any(BigNumber),
expireHeight: expect.any(BigNumber)
}
)
const accountBTCBeforeOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// make offer to partial amount 10 DFI - taker
const offer: ICXOffer = {
orderTx: createOrderTxId,
amount: new BigNumber(0.1), // 10 DFI = 0.1 BTC
ownerAddress: accountBTC
}
const makeOfferResult = await client.icxorderbook.makeOffer(offer, [])
const makeOfferTxId = makeOfferResult.txid
await container.generate(1)
const accountBTCAfterOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// check fee of 0.01 DFI has been reduced from the accountBTCBefore[idDFI]
// Fee = takerFeePerBTC(inBTC) * amount(inBTC) * DEX DFI per BTC rate
expect(accountBTCAfterOffer[idDFI]).toStrictEqual(accountBTCBeforeOffer[idDFI].minus(0.01))
// List the ICX offers for orderTx = createOrderTxId and check
const ordersAfterMakeOffer: Record<string, ICXOrderInfo | ICXOfferInfo> = await client.call('icx_listorders', [{ orderTx: createOrderTxId }], 'bignumber')
expect(Object.keys(ordersAfterMakeOffer).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm.
expect((ordersAfterMakeOffer as Record<string, ICXOfferInfo>)[makeOfferTxId]).toStrictEqual(
{
orderTx: createOrderTxId,
status: ICXOrderStatus.OPEN,
amount: offer.amount,
amountInFromAsset: offer.amount.dividedBy(order.orderPrice),
ownerAddress: offer.ownerAddress,
takerFee: offer.amount.multipliedBy(ICX_TAKERFEE_PER_BTC).multipliedBy(DEX_DFI_PER_BTC_RATE),
expireHeight: expect.any(BigNumber)
}
)
// check accountDFI[idDFI] balance
const accountDFIAfterOffer: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber')
expect(accountDFIAfterOffer[idDFI]).toStrictEqual(accountDFIBeforeOrder[idDFI].minus(15))
})
it('should make an partial offer to an sell BTC order', async () => {
const accountDFIBeforeOrder: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber')
// create offer - maker
const order: ICXOrder = {
chainFrom: 'BTC',
tokenTo: idDFI,
ownerAddress: accountDFI,
amountFrom: new BigNumber(2),
orderPrice: new BigNumber(100)
}
const createOrderResult: ICXGenericResult = await client.icxorderbook.createOrder(order, [])
const createOrderTxId = createOrderResult.txid
await container.generate(1)
// list ICX orders
const ordersAfterCreateOrder: Record<string, ICXOrderInfo | ICXOfferInfo> = await client.call('icx_listorders', [], 'bignumber')
expect((ordersAfterCreateOrder as Record<string, ICXOrderInfo>)[createOrderTxId]).toStrictEqual(
{
status: ICXOrderStatus.OPEN,
type: ICXOrderType.EXTERNAL,
tokenTo: symbolDFI,
chainFrom: order.chainFrom,
ownerAddress: order.ownerAddress,
amountFrom: order.amountFrom,
amountToFill: order.amountFrom,
orderPrice: order.orderPrice,
amountToFillInToAsset: order.amountFrom.multipliedBy(order.orderPrice),
height: expect.any(BigNumber),
expireHeight: expect.any(BigNumber)
}
)
const accountBTCBeforeOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// make offer to partial amout 1 BTC - taker
const offer: ICXOffer = {
orderTx: createOrderTxId,
amount: new BigNumber(100), // 100 DFI = 1 BTC
ownerAddress: accountBTC,
receivePubkey: '0348790cb93b203a8ea5ce07279cb209d807b535b2ca8b0988a6f7a6578e41f7a5'
}
const makeOfferResult = await client.icxorderbook.makeOffer(offer, [])
const makeOfferTxId = makeOfferResult.txid
await container.generate(1)
const accountBTCAfterOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// check fee of 0.1 DFI has been reduced from the accountBTCBeforeOffer[idDFI]
// Fee = takerFeePerBTC(inBTC) * amount(inBTC) * DEX DFI per BTC rate
expect(accountBTCAfterOffer[idDFI]).toStrictEqual(accountBTCBeforeOffer[idDFI].minus(0.1))
// List the ICX offers for orderTx = createOrderTxId and check
const ordersAfterMakeOffer: Record<string, ICXOrderInfo | ICXOfferInfo> = await client.call('icx_listorders', [{ orderTx: createOrderTxId }], 'bignumber')
expect(Object.keys(ordersAfterMakeOffer).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm.
expect((ordersAfterMakeOffer as Record<string, ICXOfferInfo>)[makeOfferTxId]).toStrictEqual(
{
orderTx: createOrderTxId,
status: ICXOrderStatus.OPEN,
amount: offer.amount,
amountInFromAsset: offer.amount.dividedBy(order.orderPrice),
ownerAddress: offer.ownerAddress,
takerFee: offer.amount.multipliedBy(ICX_TAKERFEE_PER_BTC),
expireHeight: expect.any(BigNumber),
receivePubkey: offer.receivePubkey
}
)
// check accountDFI[idDFI] balance
const accountDFIAfterOffer: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber')
expect(accountDFIAfterOffer).toStrictEqual(accountDFIBeforeOrder)
})
it('make a higher offer to an sell DFI order, should occur equivalent taker fee', async () => {
// create order - maker
const order: ICXOrder = {
tokenFrom: idDFI,
chainTo: 'BTC',
ownerAddress: accountDFI,
receivePubkey: '037f9563f30c609b19fd435a19b8bde7d6db703012ba1aba72e9f42a87366d1941',
amountFrom: new BigNumber(15),
orderPrice: new BigNumber(0.01)
}
const createOrderResult: ICXGenericResult = await client.icxorderbook.createOrder(order, [])
const createOrderTxId = createOrderResult.txid
await container.generate(1)
// list ICX orders
const ordersAfterCreateOrder: Record<string, ICXOrderInfo | ICXOfferInfo> = await client.call('icx_listorders', [], 'bignumber')
expect((ordersAfterCreateOrder as Record<string, ICXOrderInfo>)[createOrderTxId]).toStrictEqual(
{
status: ICXOrderStatus.OPEN,
type: ICXOrderType.INTERNAL,
tokenFrom: symbolDFI,
chainTo: order.chainTo,
receivePubkey: order.receivePubkey,
ownerAddress: order.ownerAddress,
amountFrom: order.amountFrom,
amountToFill: order.amountFrom,
orderPrice: order.orderPrice,
amountToFillInToAsset: order.amountFrom.multipliedBy(order.orderPrice),
height: expect.any(BigNumber),
expireHeight: expect.any(BigNumber)
}
)
const accountBTCBeforeOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// make offer to higher amout 20 DFI - taker
const offer: ICXOffer = {
orderTx: createOrderTxId,
amount: new BigNumber(0.20), // 0.20 BTC = 20 DFI
ownerAddress: accountBTC
}
const makeOfferResult = await client.icxorderbook.makeOffer(offer, [])
const makeOfferTxId = makeOfferResult.txid
await container.generate(1)
const accountBTCAfterOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// check fee of 0.02 DFI has been reduced from the accountBTCBeforeOffer[idDFI]
// Fee = takerFeePerBTC(inBTC) * amount(inBTC) * DEX DFI per BTC rate
expect(accountBTCAfterOffer[idDFI]).toStrictEqual(accountBTCBeforeOffer[idDFI].minus(0.02))
// List the ICX offers for orderTx = createOrderTxId and check
const ordersAfterMakeOffer: Record<string, ICXOrderInfo | ICXOfferInfo> = await client.call('icx_listorders', [{ orderTx: createOrderTxId }], 'bignumber')
expect(Object.keys(ordersAfterMakeOffer).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm.
expect((ordersAfterMakeOffer as Record<string, ICXOfferInfo>)[makeOfferTxId]).toStrictEqual(
{
orderTx: createOrderTxId,
status: ICXOrderStatus.OPEN,
amount: offer.amount,
amountInFromAsset: offer.amount.dividedBy(order.orderPrice),
ownerAddress: offer.ownerAddress,
takerFee: offer.amount.multipliedBy(ICX_TAKERFEE_PER_BTC).multipliedBy(DEX_DFI_PER_BTC_RATE),
expireHeight: expect.any(BigNumber)
}
)
})
it('should make an partial offer to an sell DFI order with input utxos', async () => {
const accountDFIBeforeOrder: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber')
// create order - maker
const order: ICXOrder = {
tokenFrom: idDFI,
chainTo: 'BTC',
ownerAddress: accountDFI,
receivePubkey: '037f9563f30c609b19fd435a19b8bde7d6db703012ba1aba72e9f42a87366d1941',
amountFrom: new BigNumber(15),
orderPrice: new BigNumber(0.01)
}
const createOrderResult: ICXGenericResult = await client.icxorderbook.createOrder(order, [])
const createOrderTxId = createOrderResult.txid
await container.generate(1)
// list ICX orders
const ordersAfterCreateOrder: Record<string, ICXOrderInfo | ICXOfferInfo> = await client.call('icx_listorders', [], 'bignumber')
expect((ordersAfterCreateOrder as Record<string, ICXOrderInfo>)[createOrderTxId]).toStrictEqual(
{
status: ICXOrderStatus.OPEN,
type: ICXOrderType.INTERNAL,
tokenFrom: symbolDFI,
chainTo: order.chainTo,
receivePubkey: order.receivePubkey,
ownerAddress: order.ownerAddress,
amountFrom: order.amountFrom,
amountToFill: order.amountFrom,
orderPrice: order.orderPrice,
amountToFillInToAsset: order.amountFrom.multipliedBy(order.orderPrice),
height: expect.any(BigNumber),
expireHeight: expect.any(BigNumber)
}
)
// make offer to partial amout 10 DFI - taker
const offer: ICXOffer = {
orderTx: createOrderTxId,
amount: new BigNumber(0.1), // 10 DFI = 0.1 BTC
ownerAddress: accountBTC
}
// input utxos
const inputUTXOs = await container.fundAddress(accountBTC, 10)
const accountBTCBeforeOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
const makeOfferResult = await client.icxorderbook.makeOffer(offer, [inputUTXOs])
const makeOfferTxId = makeOfferResult.txid
await container.generate(1)
const accountBTCAfterOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// check fee of 0.01 DFI has been reduced from the accountBTCBefore[idDFI]
// Fee = takerFeePerBTC(inBTC) * amount(inBTC) * DEX DFI per BTC rate
expect(accountBTCAfterOffer[idDFI]).toStrictEqual(accountBTCBeforeOffer[idDFI].minus(0.01))
// List the ICX offers for orderTx = createOrderTxId and check
const ordersAfterMakeOffer: Record<string, ICXOrderInfo | ICXOfferInfo> = await client.call('icx_listorders', [{ orderTx: createOrderTxId }], 'bignumber')
expect(Object.keys(ordersAfterMakeOffer).length).toStrictEqual(2) // extra entry for the warning text returned by the RPC atm.
expect((ordersAfterMakeOffer as Record<string, ICXOfferInfo>)[makeOfferTxId]).toStrictEqual(
{
orderTx: createOrderTxId,
status: ICXOrderStatus.OPEN,
amount: offer.amount,
amountInFromAsset: offer.amount.dividedBy(order.orderPrice),
ownerAddress: offer.ownerAddress,
takerFee: offer.amount.multipliedBy(ICX_TAKERFEE_PER_BTC).multipliedBy(DEX_DFI_PER_BTC_RATE),
expireHeight: expect.any(BigNumber)
}
)
// check accountDFI[idDFI] balance
const accountDFIAfterOffer: Record<string, BigNumber> = await client.call('getaccount', [accountDFI, {}, true], 'bignumber')
expect(accountDFIAfterOffer[idDFI]).toStrictEqual(accountDFIBeforeOrder[idDFI].minus(15))
})
it('should return an error when making an offer with invalid ICXOffer.orderTx', async () => {
// create order - maker
const order: ICXOrder = {
tokenFrom: idDFI,
chainTo: 'BTC',
ownerAddress: accountDFI,
receivePubkey: '037f9563f30c609b19fd435a19b8bde7d6db703012ba1aba72e9f42a87366d1941',
amountFrom: new BigNumber(15),
orderPrice: new BigNumber(0.01)
}
const createOrderResult: ICXGenericResult = await client.icxorderbook.createOrder(order, [])
const createOrderTxId = createOrderResult.txid
await container.generate(1)
// list ICX orders
const ordersAfterCreateOrder: Record<string, ICXOrderInfo | ICXOfferInfo> = await client.call('icx_listorders', [], 'bignumber')
expect((ordersAfterCreateOrder as Record<string, ICXOrderInfo>)[createOrderTxId]).toStrictEqual(
{
status: ICXOrderStatus.OPEN,
type: ICXOrderType.INTERNAL,
tokenFrom: symbolDFI,
chainTo: order.chainTo,
receivePubkey: order.receivePubkey,
ownerAddress: order.ownerAddress,
amountFrom: order.amountFrom,
amountToFill: order.amountFrom,
orderPrice: order.orderPrice,
amountToFillInToAsset: order.amountFrom.multipliedBy(order.orderPrice),
height: expect.any(BigNumber),
expireHeight: expect.any(BigNumber)
}
)
const accountBTCBeforeOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// make offer to invalid orderTx "123" - taker
const offer: ICXOffer = {
orderTx: 'INVALID_ORDER_TX_ID',
amount: new BigNumber(0.1), // 10 DFI = 0.1 BTC
ownerAddress: accountBTC
}
const promise = client.icxorderbook.makeOffer(offer, [])
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow('RpcApiError: \'orderTx (0000000000000000000000000000000000000000000000000000000000000000) does not exist\', code: -8, method: icx_makeoffer')
const accountBTCAfterOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// check same balance
expect(accountBTCAfterOffer[idDFI]).toStrictEqual(accountBTCBeforeOffer[idDFI])
})
it('should return an error with invalid ICXOffer.ownerAddress', async () => {
// create order - maker
const order: ICXOrder = {
tokenFrom: idDFI,
chainTo: 'BTC',
ownerAddress: accountDFI,
receivePubkey: '037f9563f30c609b19fd435a19b8bde7d6db703012ba1aba72e9f42a87366d1941',
amountFrom: new BigNumber(15),
orderPrice: new BigNumber(0.01)
}
const createOrderResult: ICXGenericResult = await client.icxorderbook.createOrder(order, [])
const createOrderTxId = createOrderResult.txid
await container.generate(1)
// list ICX orders
const ordersAfterCreateOrder: Record<string, ICXOrderInfo | ICXOfferInfo> = await client.call('icx_listorders', [], 'bignumber')
expect((ordersAfterCreateOrder as Record<string, ICXOrderInfo>)[createOrderTxId]).toStrictEqual(
{
status: ICXOrderStatus.OPEN,
type: ICXOrderType.INTERNAL,
tokenFrom: symbolDFI,
chainTo: order.chainTo,
receivePubkey: order.receivePubkey,
ownerAddress: order.ownerAddress,
amountFrom: order.amountFrom,
amountToFill: order.amountFrom,
orderPrice: order.orderPrice,
amountToFillInToAsset: order.amountFrom.multipliedBy(order.orderPrice),
height: expect.any(BigNumber),
expireHeight: expect.any(BigNumber)
}
)
const accountBTCBeforeOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// make offer with invalid ownerAddress "123" - taker
const offer: ICXOffer = {
orderTx: createOrderTxId,
amount: new BigNumber(0.1), // 10 DFI = 0.1 BTC
ownerAddress: 'INVALID_OWNER_ADDRESS'
}
const promise = client.icxorderbook.makeOffer(offer, [])
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow('RpcApiError: \'recipient (INVALID_OWNER_ADDRESS) does not refer to any valid address\', code: -5, method: icx_makeoffer')
const accountBTCAfterOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// check same balance
expect(accountBTCAfterOffer[idDFI]).toStrictEqual(accountBTCBeforeOffer[idDFI])
})
it('should return an error with invalid ICXOffer.receivePubkey', async () => {
// create order - maker
const order: ICXOrder = {
chainFrom: 'BTC',
tokenTo: idDFI,
ownerAddress: accountDFI,
amountFrom: new BigNumber(2),
orderPrice: new BigNumber(100)
}
const createOrderResult: ICXGenericResult = await client.icxorderbook.createOrder(order, [])
const createOrderTxId = createOrderResult.txid
await container.generate(1)
// list ICX orders
const ordersAfterCreateOrder: Record<string, ICXOrderInfo | ICXOfferInfo> = await client.call('icx_listorders', [], 'bignumber')
expect((ordersAfterCreateOrder as Record<string, ICXOrderInfo>)[createOrderTxId]).toStrictEqual(
{
status: ICXOrderStatus.OPEN,
type: ICXOrderType.EXTERNAL,
tokenTo: symbolDFI,
chainFrom: order.chainFrom,
ownerAddress: order.ownerAddress,
amountFrom: order.amountFrom,
amountToFill: order.amountFrom,
orderPrice: order.orderPrice,
amountToFillInToAsset: order.amountFrom.multipliedBy(order.orderPrice),
height: expect.any(BigNumber),
expireHeight: expect.any(BigNumber)
}
)
const accountBTCBeforeOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// make offer to partial amout 1 BTC - taker
const offer: ICXOffer = {
orderTx: createOrderTxId,
amount: new BigNumber(100), // 100 DFI = 1 BTC
ownerAddress: accountBTC,
receivePubkey: 'INVALID_RECEIVE_PUB_KEY'
}
const promise = client.icxorderbook.makeOffer(offer, [])
await expect(promise).rejects.toThrow(RpcApiError)
await expect(promise).rejects.toThrow('RpcApiError: \'Invalid public key: INVALID_RECEIVE_PUB_KEY\', code: -5, method: icx_makeoffer')
const accountBTCAfterOffer: Record<string, BigNumber> = await client.call('getaccount', [accountBTC, {}, true], 'bignumber')
// expect the same balance
expect(accountBTCAfterOffer[idDFI]).toStrictEqual(accountBTCBeforeOffer[idDFI])
})
}) | the_stack |
import {Engine, EngineConst} from '../common/engine';
import {DynamicCstr} from '../rule_engine/dynamic_cstr';
import {Axis, AxisMap, AxisProperties, DefaultComparator, DynamicCstrParser,
DynamicProperties} from '../rule_engine/dynamic_cstr';
import {MathCompoundStore} from '../rule_engine/math_simple_store';
import {SpeechRuleEngine} from '../rule_engine/speech_rule_engine';
import {SemanticRole, SemanticType} from '../semantic_tree/semantic_attr';
import {SemanticNode} from '../semantic_tree/semantic_node';
export class ClearspeakPreferences extends DynamicCstr {
private static AUTO: string = 'Auto';
/**
* Exports the Clearspeak comparator with default settings.
* @return The clearspeak comparator.
*/
public static comparator(): Comparator {
return new Comparator(
Engine.getInstance().dynamicCstr,
DynamicProperties.createProp(
[DynamicCstr.DEFAULT_VALUES[Axis.LOCALE]],
[DynamicCstr.DEFAULT_VALUES[Axis.MODALITY]],
[DynamicCstr.DEFAULT_VALUES[Axis.DOMAIN]],
[DynamicCstr.DEFAULT_VALUES[Axis.STYLE]]));
}
/**
* Parse the preferences from a string of the form:
* preference1_setting1:preference2_setting2:....:preferenceN_settingN
* @param pref The preference string.
* @return The preference settings.
*/
public static fromPreference(pref: string): AxisMap {
let pairs = pref.split(':');
let preferences: AxisMap = {};
let properties = PREFERENCES.getProperties();
let validKeys = Object.keys(properties);
for (let i = 0, key; key = pairs[i]; i++) {
let pair = key.split('_');
if (validKeys.indexOf(pair[0]) === -1) {
continue;
}
let value = pair[1];
if (value && value !== ClearspeakPreferences.AUTO &&
properties[(pair[0] as Axis)].indexOf(value) !==
-1) {
preferences[pair[0]] = pair[1];
}
}
return preferences;
}
/**
* Creates a style string from a set of preference mappings, by joining them
* via underscore and colon in the form:
* preference1_setting1:preference2_setting2:....:preferenceN_settingN
* @param pref A preference mapping.
* @return A style string created from the preferences.
*/
public static toPreference(pref: AxisMap): string {
let keys = Object.keys(pref);
let str = [];
for (let i = 0; i < keys.length; i++) {
str.push(keys[i] + '_' + pref[keys[i]]);
}
return str.length ? str.join(':') : DynamicCstr.DEFAULT_VALUE;
}
/**
* Computes the clearspeak preferences per locale and caches them.
* @param opt_dynamic Optionally a tree structure with the dynamic
* constraints.
* @return Mapping of locale to preferences.
*/
public static getLocalePreferences(opt_dynamic?: Object):
{[key: string]: AxisProperties} {
let dynamic = opt_dynamic ||
MathCompoundStore.enumerate(
SpeechRuleEngine.getInstance().enumerate());
return ClearspeakPreferences.getLocalePreferences_(dynamic);
}
// TODO: The following should be done in MathJax in the future!
// TODO (TS): Import the mathjax types, get rid of any.
// static getSpeechExplorer(item: MathItem): Explorer {
/**
* Computes a selection of clearspeak preferences for the MathJax context menu
* wrt. currently focused subexpression.
* @param item A Math Item.
* @param locale The current locale.
* @return The menu settings for a new radio button
* sub menu.
*/
// TODO (TS): item should get MathJax type MathItem
public static smartPreferences(item: any, locale: string): AxisMap[] {
let prefs = ClearspeakPreferences.getLocalePreferences();
let loc = prefs[locale];
if (!loc) {
return [];
}
let explorer = item['explorers'];
if (!explorer) {
return [{
type: 'radio',
content: 'Standard',
id: 'clearspeak-default',
variable: 'speechRules'
}];
}
let smart = ClearspeakPreferences.relevantPreferences(
explorer.walker.getFocus().getSemanticPrimary());
// var smart = 'Bar'; // TODO: Lookup the right preference.
let previous = EngineConst.DOMAIN_TO_STYLES['clearspeak'];
let items = [
{
type: 'radio',
content: 'No Preferences',
id: 'clearspeak-default',
variable: 'speechRules'
},
{
type: 'radio',
content: 'Current Preferences',
id: 'clearspeak-' + previous,
variable: 'speechRules'
},
{type: 'rule'}, {type: 'label', content: 'Preferences for ' + smart},
{type: 'rule'}
];
return items.concat(loc[smart].map(function(x) {
let pair = x.split('_');
return {
type: 'radio',
content: pair[1],
id: 'clearspeak-' +
ClearspeakPreferences.addPreference(previous, pair[0], pair[1]),
variable: 'speechRules'
};
}));
}
/**
* Computes a clearspeak preference that should be changed given the type of
* the node.
* @param node A semantic node.
* @return The preference that fits the node's type and role.
*/
public static relevantPreferences(node: SemanticNode): string {
let roles = SEMANTIC_MAPPING_[node.type];
if (!roles) {
return 'ImpliedTimes';
}
return roles[node.role] || roles[''] || 'ImpliedTimes';
}
/**
* Look up the setting of a preference in a preference settings sting.
* @param prefs Preference settings.
* @param kind The preference to look up.
* @return The setting of that preference. If it does not exist,
* returns Auto.
*/
public static findPreference(prefs: string, kind: string): string {
if (prefs === 'default') {
return ClearspeakPreferences.AUTO;
}
let parsed = ClearspeakPreferences.fromPreference(prefs);
return parsed[kind] || ClearspeakPreferences.AUTO;
}
/**
* Adds or updates a value in a preference settings.
* @param prefs Preference settings.
* @param kind New preference name.
* @param value New preference value.
* @return The updated preference settings.
*/
public static addPreference(
prefs: string, kind: string, value: string): string {
if (prefs === 'default') {
return kind + '_' + value;
}
let parsed = ClearspeakPreferences.fromPreference(prefs);
parsed[kind] = value;
return ClearspeakPreferences.toPreference(parsed);
}
/**
* Computes the clearspeak preferences per locale and caches them.
* @param dynamic Optionally a tree structure with the dynamic
* constraints.
* @return Mapping of locale to preferences.
*/
private static getLocalePreferences_(dynamic: any):
{[key: string]: AxisProperties} {
let result: {[key: string]: AxisProperties} = {};
for (let locale in dynamic) {
if (!dynamic[locale]['speech'] ||
!dynamic[locale]['speech']['clearspeak']) {
continue;
}
let locPrefs = Object.keys(dynamic[locale]['speech']['clearspeak']);
let prefs: AxisProperties = result[locale] = {};
for (let axis in PREFERENCES.getProperties()) {
let allSty = PREFERENCES.getProperties()[axis];
let values = [axis + '_Auto'];
if (allSty) {
for (let sty of allSty) {
if (locPrefs.indexOf(axis + '_' + sty) !== -1) {
values.push(axis + '_' + sty);
}
}
}
prefs[axis] = values;
}
}
return result;
}
/**
* @param cstr The constraint mapping.
* @param preference The preference.
*/
constructor(cstr: AxisMap, public preference: {[key: string]: string}) {
super(cstr);
}
/**
* @override
*/
public equal(cstr: ClearspeakPreferences) {
let top = super.equal(cstr);
if (!top) {
return false;
}
let keys = Object.keys(this.preference);
let preference = cstr.preference;
if (keys.length !== Object.keys(preference).length) {
return false;
}
for (let i = 0, key; key = keys[i]; i++) {
if (this.preference[key] !== preference[key]) {
return false;
}
}
return true;
}
}
const PREFERENCES = new DynamicProperties({
AbsoluteValue: ['Auto', 'AbsEnd', 'Cardinality', 'Determinant'],
Bar: ['Auto', 'Conjugate'],
Caps: ['Auto', 'SayCaps'],
CombinationPermutation: ['Auto', 'ChoosePermute'],
Currency: ['Auto', 'Position', 'Prefix'],
Ellipses: ['Auto', 'AndSoOn'],
Enclosed: ['Auto', 'EndEnclose'],
Exponent: [
'Auto', 'AfterPower', 'Ordinal', 'OrdinalPower',
// The following are German
'Exponent'
],
Fraction: [
'Auto', 'EndFrac', 'FracOver', 'General', 'GeneralEndFrac', 'Ordinal',
'Over', 'OverEndFrac', 'Per'
],
Functions: [
'Auto', 'None',
// Reciprocal is French
'Reciprocal'
],
ImpliedTimes: ['Auto', 'MoreImpliedTimes', 'None'],
Log: ['Auto', 'LnAsNaturalLog'],
Matrix: [
'Auto', 'Combinatoric', 'EndMatrix', 'EndVector', 'SilentColNum',
'SpeakColNum', 'Vector'
],
MultiLineLabel:
['Auto', 'Case', 'Constraint', 'Equation', 'Line', 'None', 'Row', 'Step'],
MultiLineOverview: ['Auto', 'None'],
MultiLinePausesBetweenColumns: ['Auto', 'Long', 'Short'],
MultsymbolDot: ['Auto', 'Dot'],
MultsymbolX: ['Auto', 'By', 'Cross'],
Paren: [
'Auto', 'CoordPoint', 'Interval', 'Silent', 'Speak', 'SpeakNestingLevel'
],
Prime: ['Auto', 'Angle', 'Length'],
Roots: ['Auto', 'PosNegSqRoot', 'PosNegSqRootEnd', 'RootEnd'],
SetMemberSymbol: ['Auto', 'Belongs', 'Element', 'Member', 'In'],
Sets: ['Auto', 'SilentBracket', 'woAll'],
TriangleSymbol: ['Auto', 'Delta'],
Trig: [
'Auto', 'ArcTrig', 'TrigInverse',
// Reciprocal French
'Reciprocal'
],
VerticalLine: ['Auto', 'Divides', 'Given', 'SuchThat']
});
export class Comparator extends DefaultComparator {
/**
* @override
*/
public preference: AxisMap;
/**
* @param cstr A Clearspeak preference constraint.
* @param props A properties element for matching.
*/
constructor(cstr: DynamicCstr, props: DynamicProperties) {
super(cstr, props);
this.preference = (cstr instanceof ClearspeakPreferences) ?
cstr.preference : {};
}
/**
* @override
*/
public match(cstr: DynamicCstr) {
if (!(cstr instanceof ClearspeakPreferences)) {
return super.match(cstr);
}
if (cstr.getComponents()[Axis.STYLE] === 'default') {
return true;
}
let keys = Object.keys(cstr.preference);
for (let i = 0, key; key = keys[i]; i++) {
if (this.preference[key] !== cstr.preference[key]) {
return false;
}
}
return true;
}
/**
* @override
*/
public compare(cstr1: DynamicCstr, cstr2: DynamicCstr) {
let top = super.compare(cstr1, cstr2);
if (top !== 0) {
return top as 0|1|-1;
}
let pref1 = (cstr1 instanceof ClearspeakPreferences);
let pref2 = (cstr2 instanceof ClearspeakPreferences);
if (!pref1 && pref2) {
return 1;
}
if (pref1 && !pref2) {
return -1;
}
if (!pref1 && !pref2) {
return 0;
}
let length1 = Object.keys((cstr1 as ClearspeakPreferences).preference).length;
let length2 = Object.keys((cstr2 as ClearspeakPreferences).preference).length;
return length1 > length2 ? -1 : length1 < length2 ? 1 : 0;
}
}
export class Parser extends DynamicCstrParser {
/**
* @override
*/
constructor() {
super([Axis.LOCALE, Axis.MODALITY, Axis.DOMAIN, Axis.STYLE]);
}
/**
* @override
*/
public parse(str: string) {
let initial = super.parse(str);
let style = initial.getValue(Axis.STYLE);
let locale = initial.getValue(Axis.LOCALE);
let modality = initial.getValue(Axis.MODALITY);
let pref = {};
if (style !== DynamicCstr.DEFAULT_VALUE) {
pref = this.fromPreference(style);
style = this.toPreference(pref);
}
return new ClearspeakPreferences(
{
'locale': locale,
'modality': modality,
'domain': 'clearspeak',
'style': style
},
pref);
}
/**
* Parse the preferences from a string of the form:
* preference1_setting1:preference2_setting2:....:preferenceN_settingN
* @param pref The preference string.
* @return The preference settings.
*/
public fromPreference(pref: string): {[key: string]: string} {
return ClearspeakPreferences.fromPreference(pref);
}
/**
* Creates a style string from a set of preference mappings, by joining them
* via underscore and colon in the form:
* preference1_setting1:preference2_setting2:....:preferenceN_settingN
* @param pref A preference mapping.
* @return A style string created from the preferences.
*/
public toPreference(pref: {[key: string]: string}): string {
return ClearspeakPreferences.toPreference(pref);
}
}
/**
* Mapping from preferences to semantic values.
*/
// TODO (TS): Replace with a Map to partial meaning elements.
const REVERSE_MAPPING: string[][] = [
[
'AbsoluteValue', SemanticType.FENCED,
SemanticRole.NEUTRAL, SemanticRole.METRIC
],
[
'Bar', SemanticType.OVERSCORE,
SemanticRole.OVERACCENT
], // more
[
'Caps', SemanticType.IDENTIFIER,
SemanticRole.LATINLETTER
], // more
[
'CombinationPermutation', SemanticType.APPL,
SemanticRole.UNKNOWN
], // more
[
'Ellipses', SemanticType.PUNCTUATION,
SemanticRole.ELLIPSIS
],
['Exponent', SemanticType.SUPERSCRIPT, ''],
['Fraction', SemanticType.FRACTION, ''],
['Functions', SemanticType.APPL, SemanticRole.SIMPLEFUNC],
[
'ImpliedTimes', SemanticType.OPERATOR,
SemanticRole.IMPLICIT
],
[
'Log', SemanticType.APPL,
SemanticRole.PREFIXFUNC
], // specific
['Matrix', SemanticType.MATRIX, ''], // multiple
['Matrix', SemanticType.VECTOR, ''], // multiple
[
'MultiLineLabel', SemanticType.MULTILINE,
SemanticRole.LABEL
], // more, multiple (table)
[
'MultiLineOverview', SemanticType.MULTILINE,
SemanticRole.TABLE
], // more, multiple (table)
[
'MultiLinePausesBetweenColumns', SemanticType.MULTILINE,
SemanticRole.TABLE
], // more, multiple (table)
[
'MultiLineLabel', SemanticType.TABLE,
SemanticRole.LABEL
], // more, multiple (table)
[
'MultiLineOverview', SemanticType.TABLE,
SemanticRole.TABLE
], // more, multiple (table)
[
'MultiLinePausesBetweenColumns', SemanticType.TABLE,
SemanticRole.TABLE
], // more, multiple (table)
[
'MultiLineLabel', SemanticType.CASES,
SemanticRole.LABEL
], // more, multiple (table)
[
'MultiLineOverview', SemanticType.CASES,
SemanticRole.TABLE
], // more, multiple (table)
[
'MultiLinePausesBetweenColumns', SemanticType.CASES,
SemanticRole.TABLE
], // more, multiple (table)
[
'MultsymbolDot', SemanticType.OPERATOR,
SemanticRole.MULTIPLICATION
], // multiple?
[
'MultsymbolX', SemanticType.OPERATOR,
SemanticRole.MULTIPLICATION
], // multiple?
['Paren', SemanticType.FENCED, SemanticRole.LEFTRIGHT],
['Prime', SemanticType.SUPERSCRIPT, SemanticRole.PRIME],
['Roots', SemanticType.ROOT, ''], // multiple (sqrt)
['Roots', SemanticType.SQRT, ''], // multiple (sqrt)
[
'SetMemberSymbol', SemanticType.RELATION,
SemanticRole.ELEMENT
],
[
'Sets', SemanticType.FENCED,
SemanticRole.SETEXT
], // multiple
[
'TriangleSymbol', SemanticType.IDENTIFIER,
SemanticRole.GREEKLETTER
], // ????
[
'Trig', SemanticType.APPL,
SemanticRole.PREFIXFUNC
], // specific
['VerticalLine', SemanticType.PUNCTUATED, SemanticRole.VBAR]
];
const SEMANTIC_MAPPING_: {[key: string]: AxisMap} = function() {
let result: {[key: string]: AxisMap} = {};
for (let i = 0, triple; triple = REVERSE_MAPPING[i];
i++) {
let pref = triple[0];
let role = result[triple[1]];
if (!role) {
role = {};
result[triple[1]] = role;
}
role[triple[2]] = pref;
}
return result;
}();
/**
* Add new comparator and parser.
*/
Engine.getInstance().comparators['clearspeak'] =
ClearspeakPreferences.comparator;
Engine.getInstance().parsers['clearspeak'] = new Parser(); | the_stack |
import { AMCPUtil as AMCPUtilNS } from './AMCP'
import CasparCGSocketResponse = AMCPUtilNS.CasparCGSocketResponse
// ResponseNS
import { Response as ResponseNS } from './ResponseSignature'
import ResponseSignature = ResponseNS.ResponseSignature
import { Response as ResponseValidatorNS } from './ResponseValidators'
import IResponseValidator = ResponseValidatorNS.IResponseValidator
import { Response as ResponseParserNS } from './ResponseParsers'
import IResponseParser = ResponseParserNS.IResponseParser
// Param NS
import { Param as ParamNS } from './ParamSignature'
import Payload = ParamNS.Payload
import PayloadVO = ParamNS.PayloadVO
import Param = ParamNS.Param
import ParamData = ParamNS.ParamData
import IParamSignature = ParamNS.IParamSignature
// Validation ND
import { Validation as ValidationNS } from './ParamValidators'
import PositiveNumberValidatorBetween = ValidationNS.PositiveNumberRoundValidatorBetween
// Protocol NS
import { Protocol as ProtocolNS } from './ProtocolLogic'
import IProtocolLogic = ProtocolNS.IProtocolLogic
// Callback NS
import { Callback as CallbackNS } from './global/Callback'
import ICommandStatusCallback = CallbackNS.ICommandStatusCallback
/**
*
*/
export namespace Command {
/**
*
*/
export interface IAMCPResponse {
code: number
raw: string
data: any
toString(): string
}
/**
*
*/
export class AMCPResponse implements IAMCPResponse {
public code: number
public raw: string
public data: any
public toString(): string {
return this.raw.replace(/\r?\n|\r/gi, '')
}
}
/**
*
*/
export enum IAMCPStatus {
Invalid = -1,
New = 0,
Initialized = 1,
Queued = 2,
Sent = 3,
Suceeded = 4,
Failed = 5,
Timeout = 6
}
/**
*
*/
export interface IAMCPCommandData {
address: string
channel: number
layer: number
payload: PayloadVO
response: IAMCPResponse
status: IAMCPStatus
id: string
readonly name: string
}
/**
*
*/
export interface IAMCPCommandVO extends IAMCPCommandData {
_commandName: string
_objectParams: Param
_stringParamsArray: Array<string>
}
/**
*
*/
export interface IAMCPCommand extends IAMCPCommandData {
paramProtocol: Array<IParamSignature>
protocolLogic: Array<IProtocolLogic>
responseProtocol: ResponseSignature
onStatusChanged: ICommandStatusCallback
token: string
resolve: (command: IAMCPCommand) => void
reject: (command: IAMCPCommand) => void
getParam: (name: string) => string | number | boolean | Object | undefined
validateParams(): boolean
validateResponse(response: CasparCGSocketResponse): boolean
serialize(): IAMCPCommandVO
populate(cmdVO: IAMCPCommandVO, id: string): void
}
/**
*
*/
export abstract class AbstractCommand implements IAMCPCommand {
response: IAMCPResponse = new AMCPResponse()
paramProtocol: Array<IParamSignature>
responseProtocol: ResponseSignature = new ResponseSignature()
onStatusChanged: ICommandStatusCallback
resolve: (command: IAMCPCommand) => void
reject: (command: IAMCPCommand) => void
protected _channel: number
protected _layer: number
protected _id: string
protected _payload: PayloadVO = {}
protected _stringParamsArray: Array<string>
protected _objectParams: Param
protected _token: string
private _status: IAMCPStatus = IAMCPStatus.New
// @todo: add concept of "variants", adding an ENUM to variants of the same (query) verb-command. INFO x INFO y, but not Thumbnail Retriece and thumbnail generate, different verbs
// not LOG (action, not query)
// INFO, HELP
// @todo:
// channel vs layer-specific vs layer-fallback addresses
// NB.: INFO BOTH LAYER AND CHANNEL!!!!!!!!
// INFO, SWAP, REMOVE, MIXER CLEAR, CLEAR,
// param getter/setters
// param list (dynamic)
// media info/template file-type to generate param data for fields
/**
*
*/
constructor(params?: string | Param | (string | Param)[], public context?: Object) {
// parse params to objects
let paramsArray: Array<string | Param> = []
// conform params to array
if (Array.isArray(params)) {
paramsArray = params
} else {
paramsArray = [params as string | Param]
}
this._stringParamsArray = []
this._objectParams = {}
this._token = Math.random().toString(35).substr(2, 7)
for (let element of paramsArray) {
if (typeof element === 'string') {
element = element.toString().trim()
this._stringParamsArray = this._stringParamsArray.concat([...element.toString().split(/\s+/)]) // @todo: string delimiter pairing (,;) -> objectArray
} else {
for (let prop in element) {
this._objectParams[prop] = element[prop]
}
}
}
}
/**
*
*/
public validateParams(): boolean {
let required: Array<IParamSignature> = this.paramProtocol ? this.paramProtocol.filter(signature => signature.required.valueOf() === true) : []
let optional: Array<IParamSignature> = this.paramProtocol ? this.paramProtocol.filter(signature => signature.required.valueOf() === false) : []
// check all required
for (let signature of required) {
if (!this.validateParam(signature)) {
return false
}
}
// add valid optionals
optional.forEach((signature) => {
this.validateParam(signature)
})
if (!this.validateProtocolLogic()) {
return false
}
let validParams: Array<IParamSignature> = this.paramProtocol ? this.paramProtocol.filter((param) => param.resolved && param.payload !== null) : []
let invalidParams: Array<IParamSignature> = this.paramProtocol ? this.paramProtocol.filter((param) => param.resolved && param.payload === null && param.required.valueOf() === true) : []
if (invalidParams.length > 0) {
return false
}
validParams.forEach((param) => {
let payload: Payload = { key: '', value: {}, raw: null }
payload.key = param.key || ''
payload.value = param.payload !== null ? param.payload : {}
payload.raw = param.raw
this.payload[param.name] = payload
})
return true
}
public getParam(name: string): string | number | boolean | Object | undefined {
if (this._objectParams[name]) {
return this._objectParams[name]
}
return undefined
}
/**
*
*/
public validateResponse(response: CasparCGSocketResponse): boolean {
// assign raw response
this.response.raw = response.responseString
this.response.code = response.statusCode
// code is correct
if (response.statusCode !== this.responseProtocol.code) {
// @todo: fallbacks? multiple valid codes?
return false
}
// data is valid
let validData: Object = {}
if (this.responseProtocol.validator) { // @todo: typechecking ("class that implements....")
const validator: IResponseValidator = new this.responseProtocol.validator()
validData = validator.resolve(response)
if (validData === false) {
return false
}
}
// data gets parsed
if (this.responseProtocol.parser && validData) { // @todo: typechecking ("class that implements....")
const parser: IResponseParser = new this.responseProtocol.parser()
parser.context = this.context
validData = parser.parse(validData)
if (validData === false) {
return false
}
}
this.response.data = validData
return true
}
/**
*
*/
get payload(): PayloadVO {
return this._payload
}
/**
*
*/
get id(): string {
return this._id || (new Date().getTime() + Math.random() * 100).toString()
}
/**
*
*/
get name(): string {
return this.constructor.name
}
/**
*
*/
get protocolLogic(): Array<IProtocolLogic> {
// TODO: I suspect an error here;
return (this.constructor as any).protocolLogic || []
}
/**
*
*/
get channel(): number {
return -1
}
/**
*
*/
get layer(): number {
return -1
}
/**
*
*/
get address(): string {
return ''
}
get token(): string {
return this._token
}
/**
*
*/
get status(): IAMCPStatus {
return this._status
}
/**
*
*/
set status(code: IAMCPStatus) {
if (code !== this._status) {
this._status = code
if (this.onStatusChanged) {
this.onStatusChanged(this._status)
}
}
}
/**
*
*/
public serialize(): IAMCPCommandVO {
return {
channel: this.channel,
layer: this.layer,
payload: this.payload,
response: this.response,
status: this.status,
_commandName: this.constructor['name'],
_objectParams: this._objectParams,
_stringParamsArray: this._stringParamsArray
} as IAMCPCommandVO
}
/**
*
*/
populate(cmdVO: IAMCPCommandVO, id: string): void {
this._stringParamsArray = cmdVO._stringParamsArray
this._objectParams = cmdVO._objectParams
this.response = cmdVO.response
this._id = id
}
/**
*
*/
public toString(): string {
let message: string = ''
switch (this.status) {
case IAMCPStatus.Invalid:
message = 'Invalid command'
break
case IAMCPStatus.New:
message = 'New command'
break
case IAMCPStatus.Queued:
message = 'Queued command'
break
case IAMCPStatus.Sent:
message = 'Sent command'
break
case IAMCPStatus.Suceeded:
message = 'Succeeded command'
break
case IAMCPStatus.Failed:
message = 'Failed command'
break
}
return message
}
/**
*
*/
protected validateParam(signature: IParamSignature): boolean {
let result: ParamData
let param: Object | undefined
// objectParams parsing
if (this._objectParams.hasOwnProperty(signature.name)) {
param = this._objectParams[signature.name]
} else {
// stringParam parsing
if (this._stringParamsArray.length > 0) {
param = this._stringParamsArray
} else {
return false
}
}
// filter out undefined object params
if (param === undefined) {
return false
}
result = signature.validation.resolve(param, (signature.key || signature.name))
if (result !== false) {
signature.validation.resolved = true
if (typeof result === 'object' && result.hasOwnProperty('raw') && result.hasOwnProperty('payload')) {
signature.payload = result.payload
signature.raw = result.raw
} else {
signature.payload = result
}
return true
} else {
return false
}
}
/**
*
*/
protected validateProtocolLogic(): boolean {
if (!this.protocolLogic) {
return true
}
let result: Array<IParamSignature>
for (let rule of this.protocolLogic) {
result = rule.resolve(this.paramProtocol)
this.paramProtocol = result
}
return true
}
/**
*
*/
protected validateChannel(): number {
let result: ParamData
let validator = new PositiveNumberValidatorBetween(1, 9999)
let param: number
if (this._objectParams.hasOwnProperty('channel')) {
param = Number(this._objectParams['channel'])
} else {
param = NaN
}
result = validator.resolve(param)
if (result !== false) {
return Number(result)
}
// @todo: dispatch error
return NaN
}
/**
*
*/
protected validateLayer(fallback?: number): number {
let result: ParamData
let validator = new PositiveNumberValidatorBetween(0, 9999)
let param: number
if (this._objectParams.hasOwnProperty('layer')) {
param = Number(this._objectParams['layer'])
} else {
param = fallback || NaN
}
result = validator.resolve(param)
if (result !== false) {
return Number(result)
}
// @todo: dispatch error
return 0
}
}
/**
*
*/
export function isIAMCPCommand(object: any): object is IAMCPCommand {
// @todo: better inheritance type checking
for (let prop in AbstractCommand.prototype) {
if (object[prop] === undefined) {
return false
}
}
return true
}
/**
*
*/
export abstract class AbstractOrChannelOrLayerCommand extends AbstractCommand {
/**
*
*/
constructor(params?: (string | Param | (string | Param)[]), context?: Object) {
super(params, context)
let channel: number = this.validateChannel()
let layer: number = this.validateLayer()
if (channel) {
this._channel = channel
if (layer) {
this._layer = layer
}
}
}
/**
*
*/
get channel(): number {
return this._channel || -1
}
/**
*
*/
get layer(): number {
return this._layer || -1
}
/**
*
*/
get address(): string {
let address: string = ''
if (this.channel && (this.channel > -1)) {
address = this.channel.toString()
} else {
return address
}
if (this.layer && (this.layer > -1)) {
address = `${address}-${this.layer}`
}
return address
}
}
/**
*
*/
export abstract class AbstractChannelCommand extends AbstractCommand {
/**
*
*/
constructor(params: (string | Param | (string | Param)[]), context?: Object) {
super(params, context)
let channel: number = this.validateChannel()
if (channel) {
this._channel = channel
this._layer = -1
} else {
throw new Error('Needs channel') // @todo: dispatch
}
}
/**
*
*/
get channel(): number {
return this._channel || -1
}
/**
*
*/
get layer(): number {
return -1
}
/**
*
*/
get address(): string {
if (this.channel) {
return this.channel.toString()
} else {
return ''
// @todo throw???
}
}
}
/**
*
*/
export abstract class AbstractLayerCommand extends AbstractCommand {
/**
*
*/
constructor(params: (string | Param | (string | Param)[]), context?: Object) {
super(params, context)
let channel: number = this.validateChannel()
let layer: number = this.validateLayer()
if (channel && layer) {
this._channel = channel
this._layer = layer
} else {
throw new Error('Needs both channel and layer') // @todo: dispatch
}
}
/**
*
*/
get channel(): number {
return this._channel || -1
}
/**
*
*/
get layer(): number {
return this._layer || -1
}
/**
*
*/
get address(): string {
let address: string
if (this.channel && (this.channel > -1)) {
address = this.channel.toString()
} else {
return ''
// @todo throw???
}
if (this.layer && (this.layer > -1)) {
address = `${address}-${this.layer}`
} else {
return ''
// @todo throw???
}
return address
}
}
/**
*
*/
export abstract class AbstractChannelOrLayerCommand extends AbstractCommand {
/**
*
*/
constructor(params: (string | Param | (string | Param)[]), context?: Object) {
super(params, context)
let channel: number = this.validateChannel()
let layer: number = this.validateLayer()
if (channel) {
this._channel = channel
if (layer) {
this._layer = layer
}
} else {
throw new Error('Needs at least channel') // @todo: dispatch
}
}
/**
*
*/
get channel(): number {
return this._channel || -1
}
/**
*
*/
get layer(): number {
return this._layer || -1
}
/**
*
*/
get address(): string {
let address: string
if (this.channel) {
address = this.channel.toString()
} else {
return ''
// @todo throw???
}
if (this.layer && (this.layer > -1)) {
address = `${address}-${this.layer}`
}
return address
}
}
/**
*
*/
export abstract class AbstractLayerWithFallbackCommand extends AbstractCommand {
/**
*
*/
constructor(params: (string | Param | (string | Param)[]), context?: Object) {
super(params, context)
let channel: number = this.validateChannel()
let layer: number = this.validateLayer(0)
if (channel) {
this._channel = channel
this._layer = layer
} else {
throw new Error('Needs at least channel, layer will default to 0 if not specified') // @todo: dispatch
}
}
/**
*
*/
get channel(): number {
return this._channel || -1
}
/**
*
*/
get layer(): number {
return this._layer || -1
}
/**
*
*/
get address(): string {
let address: string
if (this.channel) {
address = this.channel.toString()
} else {
return ''
// @todo throw???
}
if (this.layer && (this.layer > -1)) {
address = `${address}-${this.layer}`
}
return address
}
}
/**
*
*/
export abstract class AbstractLayerWithCgFallbackCommand extends AbstractCommand {
/**
*
*/
constructor(params: (string | Param | (string | Param)[]), context?: Object) {
super(params, context)
let channel: number = this.validateChannel()
let layer: number = this.validateLayer(9999)
if (channel) {
this._channel = channel
this._layer = layer
} else {
throw new Error('Needs at least channel, layer will default to 9999 if not specified') // @todo: dispatch
}
}
/**
*
*/
get channel(): number {
return this._channel || -1
}
/**
*
*/
get layer(): number {
return this._layer || -1
}
/**
*
*/
get address(): string {
let address: string
if (this.channel) {
address = this.channel.toString()
} else {
return ''
// @todo throw???
}
if (this.layer && (this.layer > -1)) {
address = `${address}-${this.layer}`
}
return address
}
}
} | the_stack |
import React, { useState } from 'react';
import { Navigation } from './Navigation';
import { NavigationRow } from './navigationRow/NavigationRow';
import { NavigationItem } from './navigationItem/NavigationItem';
import { NavigationUser } from './navigationUser/NavigationUser';
import { NavigationSearch } from './navigationSearch/NavigationSearch';
import { NavigationLanguageSelector } from './navigationLanguageSelector/NavigationLanguageSelector';
import { NavigationDropdown } from './navigationDropdown/NavigationDropdown';
import { IconSignout } from '../../icons';
type LanguageOption = {
label: string;
value: string;
};
export default {
component: Navigation,
title: 'Components/Navigation',
subcomponents: {
NavigationRow,
NavigationItem,
NavigationDropdown,
NavigationSearch,
NavigationUser,
NavigationLanguageSelector,
},
parameters: {
controls: { expanded: true },
layout: 'fullscreen',
},
args: {
title: 'Helsinki Design System',
titleAriaLabel: 'Helsinki: Helsinki Design System',
titleUrl: 'https://hel.fi',
theme: 'light',
menuToggleAriaLabel: 'Menu',
skipTo: '#content',
skipToContentLabel: 'Skip to main content',
searchLabel: 'Search',
searchPlaceholder: 'Search page',
authenticated: false,
userName: 'John Doe',
},
argTypes: {
theme: { control: { type: 'inline-radio', options: ['light', 'dark'] } },
},
};
export const Default = ({ searchLabel, searchPlaceholder, authenticated, userName, ...args }) => (
// @ts-ignore
<Navigation {...args}>
{/* NAVIGATION ROW */}
<Navigation.Row>
<Navigation.Item href="#" label="Link" active onClick={(e) => e.preventDefault()} />
<Navigation.Item href="#" label="Link" onClick={(e) => e.preventDefault()} />
<Navigation.Item href="#" label="Link" onClick={(e) => e.preventDefault()} />
<Navigation.Item href="#" label="Link" onClick={(e) => e.preventDefault()} />
<Navigation.Dropdown label="Dropdown">
<Navigation.Item href="#" label="Link" onClick={(e) => e.preventDefault()} />
<Navigation.Item href="#" label="Link" onClick={(e) => e.preventDefault()} />
<Navigation.Item href="#" label="Link" onClick={(e) => e.preventDefault()} />
<Navigation.Item href="#" label="Link" onClick={(e) => e.preventDefault()} />
</Navigation.Dropdown>
</Navigation.Row>
{/* NAVIGATION ACTIONS */}
<Navigation.Actions>
{/* SEARCH */}
<Navigation.Search searchLabel={searchLabel} searchPlaceholder={searchPlaceholder} />
{/* USER */}
<Navigation.User authenticated={authenticated} label="Sign in" userName={userName}>
<Navigation.Item label="Link" href="#" variant="secondary" onClick={(e) => e.preventDefault()} />
<Navigation.Item
label="Sign out"
href="#"
icon={<IconSignout aria-hidden />}
variant="supplementary"
onClick={(e) => e.preventDefault()}
/>
</Navigation.User>
{/* LANGUAGE SELECTOR */}
<Navigation.LanguageSelector label="FI">
<Navigation.Item href="#" onClick={(e) => e.preventDefault()} lang="fi" label="Suomeksi" />
<Navigation.Item href="#" onClick={(e) => e.preventDefault()} lang="sv" label="På svenska" />
<Navigation.Item href="#" onClick={(e) => e.preventDefault()} lang="en" label="In English" />
<Navigation.Item href="#" onClick={(e) => e.preventDefault()} lang="fr" label="En français" />
<Navigation.Item href="#" onClick={(e) => e.preventDefault()} lang="de" label="Auf deutsch" />
<Navigation.Item href="#" onClick={(e) => e.preventDefault()} lang="ru" label="По-русски" />
</Navigation.LanguageSelector>
</Navigation.Actions>
</Navigation>
);
export const Inline = ({ searchLabel, searchPlaceholder, authenticated, userName, ...args }) => {
return (
// @ts-ignore
<Navigation {...args}>
{/* NAVIGATION ROW */}
<Navigation.Row variant="inline">
<Navigation.Item href="#" label="Link" active onClick={(e) => e.preventDefault()} />
<Navigation.Item href="#" label="Link" onClick={(e) => e.preventDefault()} />
<Navigation.Dropdown label="Dropdown">
<Navigation.Item href="#" label="Link" onClick={(e) => e.preventDefault()} />
<Navigation.Item href="#" label="Link" onClick={(e) => e.preventDefault()} />
<Navigation.Item href="#" label="Link" onClick={(e) => e.preventDefault()} />
<Navigation.Item href="#" label="Link" onClick={(e) => e.preventDefault()} />
</Navigation.Dropdown>
</Navigation.Row>
{/* NAVIGATION ACTIONS */}
<Navigation.Actions>
{/* SEARCH */}
<Navigation.Search searchLabel={searchLabel} searchPlaceholder={searchPlaceholder} />
{/* USER */}
<Navigation.User authenticated={authenticated} label="Sign in" userName={userName}>
<Navigation.Item label="Link" href="#" variant="secondary" onClick={(e) => e.preventDefault()} />
<Navigation.Item
label="Sign out"
href="#"
icon={<IconSignout aria-hidden />}
variant="supplementary"
onClick={(e) => e.preventDefault()}
/>
</Navigation.User>
{/* LANGUAGE SELECTOR */}
<Navigation.LanguageSelector label="FI">
<Navigation.Item href="#" onClick={(e) => e.preventDefault()} lang="fi" label="Suomeksi" />
<Navigation.Item href="#" onClick={(e) => e.preventDefault()} lang="sv" label="På svenska" />
<Navigation.Item href="#" onClick={(e) => e.preventDefault()} lang="en" label="In English" />
<Navigation.Item href="#" onClick={(e) => e.preventDefault()} lang="fr" label="En français" />
<Navigation.Item href="#" onClick={(e) => e.preventDefault()} lang="de" label="Auf deutsch" />
<Navigation.Item href="#" onClick={(e) => e.preventDefault()} lang="ru" label="По-русски" />
</Navigation.LanguageSelector>
</Navigation.Actions>
</Navigation>
);
};
export const CustomTheme = ({ searchLabel, searchPlaceholder, authenticated, userName, ...args }) => {
return (
// @ts-ignore
<Navigation {...args}>
{/* NAVIGATION ROW */}
<Navigation.Row>
<Navigation.Item href="#" label="Link" active onClick={(e) => e.preventDefault()} />
<Navigation.Item href="#" label="Link" onClick={(e) => e.preventDefault()} />
<Navigation.Item href="#" label="Link" onClick={(e) => e.preventDefault()} />
<Navigation.Item href="#" label="Link" onClick={(e) => e.preventDefault()} />
<Navigation.Dropdown label="Dropdown">
<Navigation.Item href="#" label="Link" onClick={(e) => e.preventDefault()} />
<Navigation.Item href="#" label="Link" onClick={(e) => e.preventDefault()} />
<Navigation.Item href="#" label="Link" onClick={(e) => e.preventDefault()} />
<Navigation.Item href="#" label="Link" onClick={(e) => e.preventDefault()} />
</Navigation.Dropdown>
</Navigation.Row>
{/* NAVIGATION ACTIONS */}
<Navigation.Actions>
{/* SEARCH */}
<Navigation.Search searchLabel={searchLabel} searchPlaceholder={searchPlaceholder} />
{/* USER */}
<Navigation.User authenticated={authenticated} label="Sign in" userName={userName}>
<Navigation.Item label="Link" href="#" variant="secondary" onClick={(e) => e.preventDefault()} />
<Navigation.Item
label="Sign out"
href="#"
icon={<IconSignout aria-hidden />}
variant="supplementary"
onClick={(e) => e.preventDefault()}
/>
</Navigation.User>
{/* LANGUAGE SELECTOR */}
<Navigation.LanguageSelector label="FI">
<Navigation.Item href="#" onClick={(e) => e.preventDefault()} lang="fi" label="Suomeksi" />
<Navigation.Item href="#" onClick={(e) => e.preventDefault()} lang="sv" label="På svenska" />
<Navigation.Item href="#" onClick={(e) => e.preventDefault()} lang="en" label="In English" />
<Navigation.Item href="#" onClick={(e) => e.preventDefault()} lang="fr" label="En français" />
<Navigation.Item href="#" onClick={(e) => e.preventDefault()} lang="de" label="Auf deutsch" />
<Navigation.Item href="#" onClick={(e) => e.preventDefault()} lang="ru" label="По-русски" />
</Navigation.LanguageSelector>
</Navigation.Actions>
</Navigation>
);
};
CustomTheme.storyName = 'Custom theme';
CustomTheme.args = {
theme: {
'--header-background-color': 'var(--color-engel)',
'--header-color': 'var(--color-black-90)',
'--header-divider-color': 'var(--color-black-20)',
'--header-focus-outline-color': 'var(--color-black)',
'--mobile-menu-background-color': 'var(--color-white)',
'--mobile-menu-color': 'var(--color-black-90)',
'--navigation-row-background-color': 'var(--color-white)',
'--navigation-row-color': 'var(--color-black-90)',
'--navigation-row-focus-outline-color': 'var(--color-coat-of-arms)',
},
};
CustomTheme.argTypes = {
theme: {
control: {
type: 'object',
},
},
};
export const Example = ({ userName, ...args }) => {
const i18n = {
title: {
fi: 'Helsingin kaupunki',
sv: 'Helsingfors stad',
en: 'City of Helsinki',
},
titleAria: {
fi: 'Helsinki: Helsingin kaupunki',
sv: 'Helsingfors: Helsingfors stad',
en: 'Helsinki: City of Helsinki',
},
menuToggleAria: {
fi: 'Valikko',
sv: 'Meny',
en: 'Menu',
},
search: {
fi: 'Hae',
sv: 'Sök',
en: 'Search',
},
searchPlaceholder: {
fi: 'Hae sivustolta',
sv: 'Sök på webbplatsen',
en: 'Search page',
},
login: {
fi: 'Kirjaudu sisään',
sv: 'Logga in',
en: 'Sign in',
},
loginAria: {
fi: 'Käyttäjä:',
sv: 'Användare:',
en: 'User:',
},
logout: {
fi: 'Kirjaudu ulos',
sv: 'Logga ut',
en: 'Sign out',
},
skip: {
fi: 'Siirry sivun pääsisältöön',
sv: 'Gå till huvudinnehåll',
en: 'Skip to main content',
},
languageSelectorLabel: {
fi: 'Kieli: Suomi. Vaihda kieli. Change language. Ändra språk.',
sv: 'Språk: Svenska. Ändra språk. Vaihda kieli. Change language.',
en: 'Language: English. Change language. Vaihda kieli. Ändra språk.',
},
navigation: [
{
fi: 'Kaupunki ja hallinto',
sv: 'Staden och förvaltning',
en: 'City administration',
},
{
fi: 'Liikenne ja kartat',
sv: 'Kartor och trafik',
en: 'Maps and transport',
},
{
fi: 'Kasvatus ja koulutus',
sv: 'Fostran och utbildning',
en: 'Childhood and education',
},
{
fi: 'Kulttuuri ja vapaa-aika',
sv: 'Kultur och fritid',
en: 'Culture and leisure',
},
],
navigationDropdown: {
label: {
fi: 'Asuminen ja ympäristö',
sv: 'Boende och miljö',
en: 'Housing and environment',
},
options: [
{
fi: 'Asuminen',
sv: 'Boende',
en: 'Housing',
},
{
fi: 'Kaavoitus ja suunnittelu',
sv: 'Planläggning',
en: 'Planning',
},
{
fi: 'Rakentaminen',
sv: 'Byggande',
en: 'Construction',
},
],
},
};
const languages: LanguageOption[] = [
{ label: 'Suomeksi', value: 'fi' },
{ label: 'På svenska', value: 'sv' },
{ label: 'In English', value: 'en' },
];
const [authenticated, setAuthenticated] = useState(false);
const [language, setLanguage] = useState<string>('fi');
const [active, setActive] = useState<string>();
// show helsingfors logo if swedish is selected as the language
const logoLanguage = language === 'sv' ? 'sv' : 'fi';
return (
<>
{/* @ts-ignore */}
<Navigation
{...args}
logoLanguage={logoLanguage}
title={i18n.title[language]}
titleAriaLabel={i18n.titleAria[language]}
skipToContentLabel={i18n.skip[language]}
menuToggleAriaLabel={i18n.menuToggleAria[language]}
>
{/* NAVIGATION ROW */}
<Navigation.Row>
{i18n.navigation.map((item, index) => {
return (
<Navigation.Item
key={item[language]}
href="#"
active={active === `link-${index}`}
label={item[language]}
onClick={(e) => {
e.preventDefault();
setActive(`link-${index}`);
}}
/>
);
})}
<Navigation.Dropdown active={active === 'dropdown'} label={i18n.navigationDropdown.label[language]}>
{i18n.navigationDropdown.options.map((option, index) => {
return (
<Navigation.Item
// eslint-disable-next-line react/no-array-index-key
key={index}
label={option[language]}
href="#"
onClick={(e) => {
e.preventDefault();
setActive('dropdown');
}}
/>
);
})}
</Navigation.Dropdown>
</Navigation.Row>
{/* NAVIGATION ACTIONS */}
<Navigation.Actions>
{/* SEARCH */}
<Navigation.Search searchLabel={i18n.search[language]} searchPlaceholder={i18n.searchPlaceholder[language]} />
{/* USER */}
<Navigation.User
authenticated={authenticated}
buttonAriaLabel={`${i18n.loginAria[language]} ${userName}`}
label={i18n.login[language]}
onSignIn={() => setAuthenticated(true)}
userName={userName}
>
<Navigation.Item
href="#"
onClick={(e) => {
e.preventDefault();
setAuthenticated(false);
}}
variant="supplementary"
label={i18n.logout[language]}
icon={<IconSignout aria-hidden />}
/>
</Navigation.User>
{/* LANGUAGE SELECTOR */}
<Navigation.LanguageSelector
label={language.toUpperCase()}
buttonAriaLabel={i18n.languageSelectorLabel[language]}
>
{languages.map((lang) => {
return (
<Navigation.Item
key={lang.value}
href="#"
onClick={(e) => {
e.preventDefault();
setLanguage(lang.value);
}}
lang={lang.value}
label={lang.label}
/>
);
})}
</Navigation.LanguageSelector>
</Navigation.Actions>
</Navigation>
</>
);
}; | the_stack |
import React, { FC, useRef } from 'react';
import { render, fireEvent, waitFor, RenderResult } from '@testing-library/react';
import { renderHook, act, RenderHookResult } from '@testing-library/react-hooks';
import ThemeProvider from '@brix-ui/theme';
import { matchMedia } from '../../../mocks/match-media';
import { useFocusControl, useFocusPass } from '../src/time-picker/hooks';
import { useTimePicker } from '../src/time-picker/time-picker.component';
import TimePicker, { TimePickerProps } from '../src/time-picker';
import TimeInput, { TimeInputProps } from '../src/time-picker/time-input';
import TimeSelect, { TimeSelectProps } from '../src/time-picker/time-select';
const fireKeyDown = <E extends HTMLElement>(element: E, key: string, shift?: boolean): void => {
fireEvent.keyDown(element, { key, shiftKey: shift });
};
const fireFocus = <E extends HTMLElement>(element: E) => {
fireEvent.focus(element);
};
const fireChange = <E extends HTMLElement>(element: E, value: string) => {
fireEvent.change(element, { target: { value } });
};
describe('useFocusPass', () => {
const fixtureId = 'fixture';
const Fixture: FC<{ focusOn?: string; value?: string; passFocus?(): void; resetFocus?(): void; onBlur?(): void }> = ({
focusOn,
value,
passFocus = () => {},
resetFocus = () => {},
onBlur,
}) => {
const ref = useRef<HTMLDivElement>(null);
const { handleKeyDown, handleFocus } = useFocusPass({
value,
name: fixtureId,
ref,
focusOn,
passFocus,
resetFocus,
});
return (
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
<div ref={ref} data-testid={fixtureId} onKeyDown={handleKeyDown} onFocus={handleFocus} onBlur={onBlur} />
);
};
describe('moving focus', () => {
describe('passing focus', () => {
let result: RenderResult;
let fixture: HTMLElement;
const passFocus = jest.fn();
beforeEach(() => {
result = render(<Fixture passFocus={passFocus} />);
fixture = result.getByTestId(fixtureId);
});
describe('when `Tab` is pressed', () => {
describe('when `Shift` is pressed', () => {
it('should pass focus to the element before current', () => {
fireKeyDown(fixture, 'Tab', true);
expect(passFocus).toHaveBeenCalledWith(-1, 'Tab');
});
});
describe('when `Shift is not pressed`', () => {
it('should pass focus to the element after current', () => {
fireKeyDown(fixture, 'Tab', false);
expect(passFocus).toHaveBeenCalledWith(1, 'Tab');
});
});
});
describe('when `Enter` or `ArrowRight` are pressed', () => {
it('should pass focus to the element after current', () => {
fireKeyDown(fixture, 'Enter');
expect(passFocus).toHaveBeenCalledWith(1, 'Enter');
fireKeyDown(fixture, 'ArrowRight');
expect(passFocus).toHaveBeenCalledWith(1, 'ArrowRight');
});
});
describe('when `ArrowLeft` is pressed', () => {
it('should pass focus to the element before current', () => {
fireKeyDown(fixture, 'ArrowLeft');
expect(passFocus).toHaveBeenCalledWith(-1, 'ArrowLeft');
});
});
});
describe('resetting focus', () => {
describe('when `Escape is pressed`', () => {
it('should reset focus', () => {
const resetFocus = jest.fn();
const { getByTestId } = render(<Fixture resetFocus={resetFocus} />);
fireKeyDown(getByTestId(fixtureId), 'Escape');
expect(resetFocus).toHaveBeenCalled();
});
});
});
describe('when focusing on this element', () => {
it("should set focus value on this element's name", () => {
const passFocus = jest.fn();
const { getByTestId } = render(<Fixture passFocus={passFocus} />);
fireFocus(getByTestId(fixtureId));
expect(passFocus).toHaveBeenCalledWith(fixtureId);
});
});
});
});
describe('useFocusControl', () => {
const focusOrder = ['1', '2', '3'];
const renderFocusControl = () => renderHook(() => useFocusControl(focusOrder));
describe('passing focus', () => {
let hook: RenderHookResult<unknown, ReturnType<typeof useFocusControl>>;
beforeEach(() => {
hook = renderFocusControl();
});
describe('when called with a name of an element', () => {
it('should set focus to this element', () => {
act(() => {
hook.result.current.passFocus('2');
});
expect(hook.result.current.focusOn).toBe('2');
});
});
describe('when called with a number', () => {
describe('when number is -1', () => {
describe('when previous focus value is the first element in the order', () => {
it('should stay on that element', () => {
act(() => {
hook.result.current.passFocus('1');
hook.result.current.passFocus(-1);
});
expect(hook.result.current.focusOn).toBe('1');
});
});
describe('when previous focus value is not the first element in the order', () => {
it('should pass focus to the previous element in the order', () => {
act(() => {
hook.result.current.passFocus('2');
hook.result.current.passFocus(-1);
});
expect(hook.result.current.focusOn).toBe('1');
});
});
});
describe('when number is 1', () => {
describe('when previous focus value is the last element in the order', () => {
it('should stay on that element', () => {
act(() => {
hook.result.current.passFocus('3');
hook.result.current.passFocus(1);
});
expect(hook.result.current.focusOn).toBe('3');
});
});
describe('when previous focus value is not the last element in the order', () => {
it('should pass focus to the next element in the order', () => {
act(() => {
hook.result.current.passFocus('2');
hook.result.current.passFocus(1);
});
expect(hook.result.current.focusOn).toBe('3');
});
});
});
});
});
describe('resetting focus', () => {
describe('when `resetFocus` is called', () => {
it('should set focus to `undefined`', () => {
const { result } = renderFocusControl();
act(() => {
result.current.passFocus('1');
result.current.resetFocus();
});
expect(result.current.focusOn).toBe(undefined);
});
});
});
});
describe('<TimeInput />', () => {
beforeEach(() => {
matchMedia();
});
const timeInputId = 'time-input';
const renderWithProps = (props: TimeInputProps, pickerProps = {} as TimePickerProps) => {
return render(<TimeInput data-testid={timeInputId} {...props} />, {
wrapper: ({ children }) => {
return (
<ThemeProvider>
<TimePicker {...pickerProps}>{children}</TimePicker>
</ThemeProvider>
);
},
});
};
describe('`min` value', () => {
it('should be 0 by default', () => {
const { getByTestId } = renderWithProps({ name: 'hour' });
const input = getByTestId(timeInputId).querySelector('input') as HTMLInputElement;
expect(input.getAttribute('min')).toBe('0');
});
describe('when specified in props', () => {
it('should use value from props', () => {
const { getByTestId } = renderWithProps({ name: 'hour', min: 15 });
const input = getByTestId(timeInputId).querySelector('input') as HTMLInputElement;
expect(input.getAttribute('min')).toBe('15');
});
});
});
describe('`max` value', () => {
describe('when name is `hour`', () => {
describe('when mode is undefined', () => {
it('should be 24 by default', () => {
const { getByTestId } = renderWithProps({ name: 'hour' });
const input = getByTestId(timeInputId).querySelector('input') as HTMLInputElement;
expect(input.getAttribute('max')).toBe('24');
});
});
describe('when mode is `AM`', () => {
it('should be 12 by default', () => {
const { getByTestId } = renderWithProps({ name: 'hour' }, { mode: 'AM' });
const input = getByTestId(timeInputId).querySelector('input') as HTMLInputElement;
expect(input.getAttribute('max')).toBe('12');
});
});
describe('when mode is `PM`', () => {
it('should be 12 by default', () => {
const { getByTestId } = renderWithProps({ name: 'hour' }, { mode: 'PM' });
const input = getByTestId(timeInputId).querySelector('input') as HTMLInputElement;
expect(input.getAttribute('max')).toBe('12');
});
});
});
describe('when name is `minute`', () => {
it('should be 59 by default', () => {
const { getByTestId } = renderWithProps({ name: 'minute' });
const input = getByTestId(timeInputId).querySelector('input') as HTMLInputElement;
expect(input.getAttribute('max')).toBe('59');
});
});
describe('when name is `second`', () => {
it('should be 59 by default', () => {
const { getByTestId } = renderWithProps({ name: 'second' });
const input = getByTestId(timeInputId).querySelector('input') as HTMLInputElement;
expect(input.getAttribute('max')).toBe('59');
});
});
describe('when specified in props', () => {
it('should use value from props', () => {
const { getByTestId } = renderWithProps({ name: 'hour', max: 15 });
const input = getByTestId(timeInputId).querySelector('input') as HTMLInputElement;
expect(input.getAttribute('max')).toBe('15');
});
});
});
describe('value constraint', () => {
describe('when value does not satisfy the constraint', () => {
it('should transform value to be fit', async () => {
const onChange = jest.fn();
const { getByTestId } = renderWithProps({ name: 'hour' }, { onChange });
const input = getByTestId(timeInputId).querySelector('input') as HTMLInputElement;
fireChange(input, '25');
await waitFor(() => {
expect(onChange).toHaveBeenCalledWith('24');
});
});
});
});
});
describe('<TimeSelect />', () => {
beforeEach(() => {
matchMedia();
});
const timeSelectId = 'time-select';
const renderWithProps = (props: TimeSelectProps, pickerProps = {} as TimePickerProps) => {
return render(<TimeSelect data-testid={timeSelectId} {...props} />, {
wrapper: ({ children }) => {
return (
<ThemeProvider>
<TimePicker {...pickerProps}>{children}</TimePicker>
</ThemeProvider>
);
},
});
};
describe('prepopulating options', () => {
describe('when name is `hour`', () => {
describe('when `mode` is not specified', () => {
it('should render 25 options including placeholder', () => {
const { getByTestId } = renderWithProps({ name: 'hour' });
const options = getByTestId(timeSelectId).querySelectorAll('option');
expect(options.length).toBe(25);
});
});
describe('when `mode` is `AM`', () => {
it('should should render 13 options including placeholder', () => {
const { getByTestId } = renderWithProps({ name: 'hour' }, { mode: 'AM' });
const options = getByTestId(timeSelectId).querySelectorAll('option');
expect(options.length).toBe(13);
});
});
describe('when `mode` is `PM`', () => {
it('should should render 13 options including placeholder', () => {
const { getByTestId } = renderWithProps({ name: 'hour' }, { mode: 'PM' });
const options = getByTestId(timeSelectId).querySelectorAll('option');
expect(options.length).toBe(13);
});
});
});
['minute', 'second'].forEach((granularity) => {
describe(`when name is \`${granularity}\``, () => {
it('should render 61 options including placeholder', () => {
const { getByTestId } = renderWithProps({ name: granularity as 'minute' | 'second' });
const options = getByTestId(timeSelectId).querySelectorAll('option');
expect(options.length).toBe(61);
});
});
});
});
describe('formatting options', () => {
describe('when `mode` is specified and `name` is `hour`', () => {
it('should assign a label for each option with its value and lowercased mode', () => {
const { getByTestId } = renderWithProps({ name: 'hour' }, { mode: 'AM' });
const options = getByTestId(timeSelectId).querySelectorAll('option[label$="am"]');
expect(options.length).toBe(12);
});
});
});
});
describe('<TimePicker />', () => {
beforeEach(() => {
matchMedia();
jest.spyOn(React.Children, 'count').mockReturnValue(3);
// Prevent warning: 'The global style component * was given child JSX. createGlobalStyle does not render children.'
jest.spyOn(console, 'warn').mockImplementation(() => {});
});
const renderWithProps = (props = {} as TimePickerProps) => {
return renderHook(useTimePicker, {
wrapper: ({ children }) => {
return (
<ThemeProvider>
<TimePicker {...props}>{children}</TimePicker>
</ThemeProvider>
);
},
});
};
describe('defaultValue', () => {
it('should format and apply `defaultValue`', async () => {
const { result, waitFor: hookWaitFor } = renderWithProps({
defaultValue: '12:28:54 AM',
mode: 'AM',
});
const { hour, minute, second } = result.current;
await hookWaitFor(() => {
expect(hour).toBe('12');
expect(minute).toBe('28');
expect(second).toBe('54');
});
});
});
describe('onModeChange', () => {
it('should call `onModeChange` whenever the mode changes', async () => {
const onModeChange = jest.fn();
const { rerender } = render(
<ThemeProvider>
<TimePicker onModeChange={onModeChange} mode="AM" />
</ThemeProvider>
);
rerender(
<ThemeProvider>
<TimePicker onModeChange={onModeChange} mode="PM" />
</ThemeProvider>
);
await waitFor(() => {
expect(onModeChange).toHaveBeenCalledWith('PM');
});
});
});
describe('value change', () => {
let hook: RenderHookResult<TimePickerProps, ReturnType<typeof useTimePicker>>;
let setTime: jest.SpyInstance;
const onChange = jest.fn();
beforeEach(() => {
hook = renderWithProps({
defaultValue: '12:28:54',
onChange,
});
setTime = jest.spyOn(hook.result.current.dispatcher, 'setTime');
act(() => {
hook.result.current.dispatcher.setTime({
name: 'second',
value: '55',
});
});
});
it('should dispatch only changed parts of the value string', async () => {
await hook.waitFor(() => {
expect(setTime).toHaveBeenCalledTimes(1);
expect(setTime).toHaveBeenCalledWith({
name: 'second',
value: '55',
});
});
});
describe('when value corresponds to the number of children', () => {
it('should call `onChange` whenever the value changes', async () => {
await hook.waitFor(() => {
expect(onChange).toHaveBeenCalledWith('12:28:55');
});
});
});
describe('when parts of desired value are undefined', () => {
it('should not call `onChange`', () => {
onChange.mockClear();
act(() => {
hook.result.current.dispatcher.setTime({
name: 'second',
value: undefined,
});
});
expect(onChange).not.toHaveBeenCalled();
});
});
});
describe('dividers rendering', () => {
it('should render divider after each child except for the last one', () => {
const { container } = render(
<TimePicker>
<div />
<div />
<div />
</TimePicker>,
{
wrapper: ThemeProvider as FC<{}>,
}
);
const dividers = container.querySelectorAll('div + span');
expect(dividers.length).toBe(2);
expect(container.querySelector('div > div > div:last-child + span')).toBe(null);
});
});
}); | the_stack |
import { EventEmitter } from 'events';
import Connection from '../connection';
import Device from '../device';
import { NotSupportedError } from '../errors';
import { RTCSampleTotals } from '../rtc/sample';
import RTCSample from '../rtc/sample';
import { getRTCIceCandidateStatsReport } from '../rtc/stats';
import RTCWarning from '../rtc/warning';
import StatsMonitor from '../statsMonitor';
import { NetworkTiming, TimeMeasurement } from './timing';
const { COWBELL_AUDIO_URL, ECHO_TEST_DURATION } = require('../constants');
/**
* Placeholder until we convert peerconnection.js to TypeScript.
* Represents the audio output object coming from Client SDK's PeerConnection object.
* @internalapi
*/
export interface AudioOutput {
/**
* The audio element used to play out the sound.
*/
audio: HTMLAudioElement;
}
export declare interface PreflightTest {
/**
* Raised when [[PreflightTest.status]] has transitioned to [[PreflightTest.Status.Completed]].
* During this time, [[PreflightTest.report]] is available and ready to be inspected.
* In some cases, this will not trigger if the test encounters a fatal error prior connecting to Twilio.
* See [[PreflightTest.failedEvent]].
* @param report
* @example `preflight.on('completed', report => console.log(report))`
* @event
*/
completedEvent(report: PreflightTest.Report): void;
/**
* Raised when [[PreflightTest.status]] has transitioned to [[PreflightTest.Status.Connected]].
* @example `preflight.on('connected', () => console.log('Test connected'))`
* @event
*/
connectedEvent(): void;
/**
* Raised when [[PreflightTest.status]] has transitioned to [[PreflightTest.Status.Failed]].
* This happens when establishing a connection to Twilio has failed or when a test call has encountered a fatal error.
* This is also raised if [[PreflightTest.stop]] is called while the test is in progress.
* @param error
* @example `preflight.on('failed', error => console.log(error))`
* @event
*/
failedEvent(error: Device.Error | DOMError): void;
/**
* Raised when the [[Connection]] gets a webrtc sample object. This event is published every second.
* @param sample
* @example `preflight.on('sample', sample => console.log(sample))`
* @event
*/
sampleEvent(sample: RTCSample): void;
/**
* Raised whenever the [[Connection]] encounters a warning.
* @param name - The name of the warning.
* @example `preflight.on('warning', (name, data) => console.log({ name, data }))`
* @event
*/
warningEvent(name: string, data: PreflightTest.Warning): void;
}
/**
* Runs some tests to identify issues, if any, prohibiting successful calling.
*/
export class PreflightTest extends EventEmitter {
/**
* Callsid generated for this test call
*/
private _callSid: string | undefined;
/**
* The {@link Connection} for this test call
*/
private _connection: Connection;
/**
* The {@link Device} for this test call
*/
private _device: Device;
/**
* The timer when doing an echo test
* The echo test is used when fakeMicInput is set to true
*/
private _echoTimer: NodeJS.Timer;
/**
* The edge that the `Twilio.Device` connected to.
*/
private _edge: string | undefined;
/**
* End of test timestamp
*/
private _endTime: number | undefined;
/**
* Whether this test has already logged an insights-connection-warning.
*/
private _hasInsightsErrored: boolean = false;
/**
* Latest WebRTC sample collected for this test
*/
private _latestSample: RTCSample | undefined;
/**
* Network related timing measurements for this test
*/
private _networkTiming: NetworkTiming = {};
/**
* The options passed to {@link PreflightTest} constructor
*/
private _options: PreflightTest.ExtendedOptions = {
codecPreferences: [Connection.Codec.PCMU, Connection.Codec.Opus],
debug: false,
edge: 'roaming',
fakeMicInput: false,
signalingTimeoutMs: 10000,
};
/**
* The report for this test.
*/
private _report: PreflightTest.Report | undefined;
/**
* The WebRTC ICE candidates stats information collected during the test
*/
private _rtcIceCandidateStatsReport: PreflightTest.RTCIceCandidateStatsReport;
/**
* WebRTC samples collected during this test
*/
private _samples: RTCSample[];
/**
* Timer for setting up signaling connection
*/
private _signalingTimeoutTimer: number;
/**
* Start of test timestamp
*/
private _startTime: number;
/**
* Current status of this test
*/
private _status: PreflightTest.Status = PreflightTest.Status.Connecting;
/**
* List of warning names and warning data detected during this test
*/
private _warnings: PreflightTest.Warning[];
/**
* Construct a {@link PreflightTest} instance.
* @constructor
* @param token - A Twilio JWT token string.
* @param options
*/
constructor(token: string, options: PreflightTest.ExtendedOptions) {
super();
Object.assign(this._options, options);
this._samples = [];
this._warnings = [];
this._startTime = Date.now();
this._initDevice(token, {
...this._options,
fileInputStream: this._options.fakeMicInput ?
this._getStreamFromFile() : undefined,
});
}
/**
* Stops the current test and raises a failed event.
*/
stop(): void {
const error: Device.Error = {
code: 31008,
message: 'Call cancelled',
};
if (this._device) {
this._device.once('offline', () => this._onFailed(error));
this._device.destroy();
} else {
this._onFailed(error);
}
}
/**
* Emit a {PreflightTest.Warning}
*/
private _emitWarning(name: string, description: string, rtcWarning?: RTCWarning): void {
const warning: PreflightTest.Warning = { name, description };
if (rtcWarning) {
warning.rtcWarning = rtcWarning;
}
this._warnings.push(warning);
this.emit(PreflightTest.Events.Warning, warning);
}
/**
* Returns call quality base on the RTC Stats
*/
private _getCallQuality(mos: number): PreflightTest.CallQuality {
if (mos > 4.2) {
return PreflightTest.CallQuality.Excellent;
} else if (mos >= 4.1 && mos <= 4.2) {
return PreflightTest.CallQuality.Great;
} else if (mos >= 3.7 && mos <= 4) {
return PreflightTest.CallQuality.Good;
} else if (mos >= 3.1 && mos <= 3.6) {
return PreflightTest.CallQuality.Fair;
} else {
return PreflightTest.CallQuality.Degraded;
}
}
/**
* Returns the report for this test.
*/
private _getReport(): PreflightTest.Report {
const stats = this._getRTCStats();
const testTiming: TimeMeasurement = { start: this._startTime };
if (this._endTime) {
testTiming.end = this._endTime;
testTiming.duration = this._endTime - this._startTime;
}
const report: PreflightTest.Report = {
callSid: this._callSid,
edge: this._edge,
iceCandidateStats: this._rtcIceCandidateStatsReport.iceCandidateStats,
networkTiming: this._networkTiming,
samples: this._samples,
selectedEdge: this._options.edge,
stats,
testTiming,
totals: this._getRTCSampleTotals(),
warnings: this._warnings,
};
const selectedIceCandidatePairStats = this._rtcIceCandidateStatsReport.selectedIceCandidatePairStats;
if (selectedIceCandidatePairStats) {
report.selectedIceCandidatePairStats = selectedIceCandidatePairStats;
report.isTurnRequired = selectedIceCandidatePairStats.localCandidate.candidateType === 'relay'
|| selectedIceCandidatePairStats.remoteCandidate.candidateType === 'relay';
}
if (stats) {
report.callQuality = this._getCallQuality(stats.mos.average);
}
return report;
}
/**
* Returns RTC stats totals for this test
*/
private _getRTCSampleTotals(): RTCSampleTotals | undefined {
if (!this._latestSample) {
return;
}
return { ...this._latestSample.totals };
}
/**
* Returns RTC related stats captured during the test call
*/
private _getRTCStats(): PreflightTest.RTCStats | undefined {
const firstMosSampleIdx = this._samples.findIndex(
sample => typeof sample.mos === 'number' && sample.mos > 0,
);
const samples = firstMosSampleIdx >= 0
? this._samples.slice(firstMosSampleIdx)
: [];
if (!samples || !samples.length) {
return;
}
return ['jitter', 'mos', 'rtt'].reduce((statObj, stat) => {
const values = samples.map(s => s[stat]);
return {
...statObj,
[stat]: {
average: Number((values.reduce((total, value) => total + value) / values.length).toPrecision(5)),
max: Math.max(...values),
min: Math.min(...values),
},
};
}, {} as any);
}
/**
* Returns a MediaStream from a media file
*/
private _getStreamFromFile(): MediaStream {
const audioContext = this._options.audioContext;
if (!audioContext) {
throw new NotSupportedError('Cannot fake input audio stream: AudioContext is not supported by this browser.');
}
const audioEl: any = new Audio(COWBELL_AUDIO_URL);
audioEl.addEventListener('canplaythrough', () => audioEl.play());
if (typeof audioEl.setAttribute === 'function') {
audioEl.setAttribute('crossorigin', 'anonymous');
}
const src = audioContext.createMediaElementSource(audioEl);
const dest = audioContext.createMediaStreamDestination();
src.connect(dest);
return dest.stream;
}
/**
* Initialize the device
*/
private _initDevice(token: string, options: PreflightTest.ExtendedOptions): void {
try {
this._device = new (options.deviceFactory || Device)(token, {
codecPreferences: options.codecPreferences,
debug: options.debug,
edge: options.edge,
fileInputStream: options.fileInputStream,
iceServers: options.iceServers,
preflight: true,
rtcConfiguration: options.rtcConfiguration,
});
} catch (error) {
// We want to return before failing so the consumer can capture the event
setTimeout(() => {
this._onFailed(error);
});
return;
}
this._device.once('ready', () => {
this._onDeviceReady();
});
this._device.once('error', (error: Device.Error) => {
this._onDeviceError(error);
});
this._signalingTimeoutTimer = setTimeout(() => {
this._onDeviceError({
code: 31901,
message: 'WebSocket - Connection Timeout',
});
}, options.signalingTimeoutMs);
}
/**
* Called on {@link Device} error event
* @param error
*/
private _onDeviceError(error: Device.Error): void {
this._device.destroy();
this._onFailed(error);
}
/**
* Called on {@link Device} ready event
*/
private _onDeviceReady(): void {
clearTimeout(this._echoTimer);
clearTimeout(this._signalingTimeoutTimer);
this._connection = this._device.connect();
this._networkTiming.signaling = { start: Date.now() };
this._setupConnectionHandlers(this._connection);
this._edge = this._device.edge || undefined;
if (this._options.fakeMicInput) {
this._echoTimer = setTimeout(() => this._device.disconnectAll(), ECHO_TEST_DURATION);
const audio = this._device.audio as any;
if (audio) {
audio.disconnect(false);
audio.outgoing(false);
}
}
this._device.once('disconnect', () => {
this._device.once('offline', () => this._onOffline());
this._device.destroy();
});
const publisher = this._connection['_publisher'] as any;
publisher.on('error', () => {
if (!this._hasInsightsErrored) {
this._emitWarning('insights-connection-error',
'Received an error when attempting to connect to Insights gateway');
}
this._hasInsightsErrored = true;
});
}
/**
* Called when there is a fatal error
* @param error
*/
private _onFailed(error: Device.Error | DOMError): void {
clearTimeout(this._echoTimer);
clearTimeout(this._signalingTimeoutTimer);
this._releaseHandlers();
this._endTime = Date.now();
this._status = PreflightTest.Status.Failed;
this.emit(PreflightTest.Events.Failed, error);
}
/**
* Called when the device goes offline.
* This indicates that the test has been completed, but we won't know if it failed or not.
* The onError event will be the indicator whether the test failed.
*/
private _onOffline(): void {
// We need to make sure we always execute preflight.on('completed') last
// as client SDK sometimes emits 'offline' event before emitting fatal errors.
setTimeout(() => {
if (this._status === PreflightTest.Status.Failed) {
return;
}
clearTimeout(this._echoTimer);
clearTimeout(this._signalingTimeoutTimer);
this._releaseHandlers();
this._endTime = Date.now();
this._status = PreflightTest.Status.Completed;
this._report = this._getReport();
this.emit(PreflightTest.Events.Completed, this._report);
}, 10);
}
/**
* Clean up all handlers for device and connection
*/
private _releaseHandlers(): void {
[this._device, this._connection].forEach((emitter: EventEmitter) => {
if (emitter) {
emitter.eventNames().forEach((name: string) => emitter.removeAllListeners(name));
}
});
}
/**
* Setup the event handlers for the {@link Connection} of the test call
* @param connection
*/
private _setupConnectionHandlers(connection: Connection): void {
if (this._options.fakeMicInput) {
// When volume events start emitting, it means all audio outputs have been created.
// Let's mute them if we're using fake mic input.
connection.once('volume', () => {
connection.mediaStream.outputs
.forEach((output: AudioOutput) => output.audio.muted = true);
});
}
connection.on('warning', (name: string, data: RTCWarning) => {
this._emitWarning(name, 'Received an RTCWarning. See .rtcWarning for the RTCWarning', data);
});
connection.once('accept', () => {
this._callSid = connection.mediaStream.callSid;
this._status = PreflightTest.Status.Connected;
this.emit(PreflightTest.Events.Connected);
});
connection.on('sample', async (sample) => {
// RTC Stats are ready. We only need to get ICE candidate stats report once.
if (!this._latestSample) {
this._rtcIceCandidateStatsReport = await (
this._options.getRTCIceCandidateStatsReport || getRTCIceCandidateStatsReport
)(connection.mediaStream.version.pc);
}
this._latestSample = sample;
this._samples.push(sample);
this.emit(PreflightTest.Events.Sample, sample);
});
// TODO: Update the following once the SDK supports emitting these events
// Let's shim for now
[{
reportLabel: 'peerConnection',
type: 'pcconnection',
}, {
reportLabel: 'ice',
type: 'iceconnection',
}, {
reportLabel: 'dtls',
type: 'dtlstransport',
}, {
reportLabel: 'signaling',
type: 'signaling',
}].forEach(({type, reportLabel}) => {
const handlerName = `on${type}statechange`;
const originalHandler = connection.mediaStream[handlerName];
connection.mediaStream[handlerName] = (state: string) => {
const timing = (this._networkTiming as any)[reportLabel]
= (this._networkTiming as any)[reportLabel] || { start: 0 };
if (state === 'connecting' || state === 'checking') {
timing.start = Date.now();
} else if ((state === 'connected' || state === 'stable') && !timing.duration) {
timing.end = Date.now();
timing.duration = timing.end - timing.start;
}
originalHandler(state);
};
});
}
/**
* The callsid generated for the test call.
*/
get callSid(): string | undefined {
return this._callSid;
}
/**
* A timestamp in milliseconds of when the test ended.
*/
get endTime(): number | undefined {
return this._endTime;
}
/**
* The latest WebRTC sample collected.
*/
get latestSample(): RTCSample | undefined {
return this._latestSample;
}
/**
* The report for this test.
*/
get report(): PreflightTest.Report | undefined {
return this._report;
}
/**
* A timestamp in milliseconds of when the test started.
*/
get startTime(): number {
return this._startTime;
}
/**
* The status of the test.
*/
get status(): PreflightTest.Status {
return this._status;
}
}
export namespace PreflightTest {
/**
* The quality of the call determined by different mos ranges.
* Mos is calculated base on the WebRTC stats - rtt, jitter, and packet lost.
*/
export enum CallQuality {
/**
* If the average mos is over 4.2.
*/
Excellent = 'excellent',
/**
* If the average mos is between 4.1 and 4.2 both inclusive.
*/
Great = 'great',
/**
* If the average mos is between 3.7 and 4.0 both inclusive.
*/
Good = 'good',
/**
* If the average mos is between 3.1 and 3.6 both inclusive.
*/
Fair = 'fair',
/**
* If the average mos is 3.0 or below.
*/
Degraded = 'degraded',
}
/**
* Possible events that a [[PreflightTest]] might emit.
*/
export enum Events {
/**
* See [[PreflightTest.completedEvent]]
*/
Completed = 'completed',
/**
* See [[PreflightTest.connectedEvent]]
*/
Connected = 'connected',
/**
* See [[PreflightTest.failedEvent]]
*/
Failed = 'failed',
/**
* See [[PreflightTest.sampleEvent]]
*/
Sample = 'sample',
/**
* See [[PreflightTest.warningEvent]]
*/
Warning = 'warning',
}
/**
* Possible status of the test.
*/
export enum Status {
/**
* Connection to Twilio has initiated.
*/
Connecting = 'connecting',
/**
* Connection to Twilio has been established.
*/
Connected = 'connected',
/**
* The connection to Twilio has been disconnected and the test call has completed.
*/
Completed = 'completed',
/**
* The test has stopped and failed.
*/
Failed = 'failed',
}
/**
* The WebRTC API's [RTCIceCandidateStats](https://developer.mozilla.org/en-US/docs/Web/API/RTCIceCandidateStats)
* dictionary which provides information related to an ICE candidate.
*/
export type RTCIceCandidateStats = any;
/**
* Options that may be passed to {@link PreflightTest} constructor for internal testing.
* @internalapi
*/
export interface ExtendedOptions extends Options {
/**
* The AudioContext instance to use
*/
audioContext?: AudioContext;
/**
* Device class to use.
*/
deviceFactory?: new (token: string, options: Device.Options) => Device;
/**
* File input stream to use instead of reading from mic
*/
fileInputStream?: MediaStream;
/**
* The getRTCIceCandidateStatsReport to use for testing.
*/
getRTCIceCandidateStatsReport?: Function;
/**
* An RTCConfiguration to pass to the RTCPeerConnection constructor during `Device.setup`.
*/
rtcConfiguration?: RTCConfiguration;
}
/**
* A WebRTC stats report containing relevant information about selected and gathered ICE candidates
*/
export interface RTCIceCandidateStatsReport {
/**
* An array of WebRTC stats for the ICE candidates gathered when connecting to media.
*/
iceCandidateStats: RTCIceCandidateStats[];
/**
* A WebRTC stats for the ICE candidate pair used to connect to media, if candidates were selected.
*/
selectedIceCandidatePairStats?: RTCSelectedIceCandidatePairStats;
}
/**
* Options passed to {@link PreflightTest} constructor.
*/
export interface Options {
/**
* An ordered array of codec names that will be used during the test call,
* from most to least preferred.
* @default ['pcmu','opus']
*/
codecPreferences?: Connection.Codec[];
/**
* Whether to enable debug logging.
* @default false
*/
debug?: boolean;
/**
* Specifies which Twilio Data Center to use when initiating the test call.
* Please see this
* [page](https://www.twilio.com/docs/voice/client/edges)
* for the list of available edges.
* @default roaming
*/
edge?: string;
/**
* If set to `true`, the test call will ignore microphone input and will use a default audio file.
* If set to `false`, the test call will capture the audio from the microphone.
* Setting this to `true` is only supported on Chrome and will throw a fatal error on other browsers
* @default false
*/
fakeMicInput?: boolean;
/**
* An array of custom ICE servers to use to connect media. If you provide both STUN and TURN server configurations,
* the test will detect whether a TURN server is required to establish a connection.
*
* The following example demonstrates how to use [Twilio's Network Traversal Service](https://www.twilio.com/stun-turn)
* to generate STUN/TURN credentials and how to specify a specific [edge location](https://www.twilio.com/docs/global-infrastructure/edge-locations).
*
* ```ts
* import Client from 'twilio';
* import { Device } from 'twilio-client';
*
* // Generate the STUN and TURN server credentials with a ttl of 120 seconds
* const client = Client(twilioAccountSid, authToken);
* const token = await client.tokens.create({ ttl: 120 });
*
* let iceServers = token.iceServers;
*
* // By default, global will be used as the default edge location.
* // You can replace global with a specific edge name for each of the iceServer configuration.
* iceServers = iceServers.map(config => {
* let { url, urls, ...rest } = config;
* url = url.replace('global', 'ashburn');
* urls = urls.replace('global', 'ashburn');
*
* return { url, urls, ...rest };
* });
*
* // Use the TURN credentials using the iceServers parameter
* const preflightTest = Device.runPreflight(token, { iceServers });
*
* // Read from the report object to determine whether TURN is required to connect to media
* preflightTest.on('completed', (report) => {
* console.log(report.isTurnRequired);
* });
* ```
*
* @default null
*/
iceServers?: RTCIceServer[];
/**
* Amount of time to wait for setting up signaling connection.
* @default 10000
*/
signalingTimeoutMs?: number;
}
/**
* Represents the WebRTC stats for the ICE candidate pair used to connect to media, if candidates were selected.
*/
export interface RTCSelectedIceCandidatePairStats {
/**
* An [RTCIceCandidateStats](https://developer.mozilla.org/en-US/docs/Web/API/RTCIceCandidateStats)
* object which provides information related to the selected local ICE candidate.
*/
localCandidate: RTCIceCandidateStats;
/**
* An [RTCIceCandidateStats](https://developer.mozilla.org/en-US/docs/Web/API/RTCIceCandidateStats)
* object which provides information related to the selected remote ICE candidate.
*/
remoteCandidate: RTCIceCandidateStats;
}
/**
* Represents RTC related stats that are extracted from RTC samples.
*/
export interface RTCStats {
/**
* Packets delay variation.
*/
jitter: Stats;
/**
* Mean opinion score, 1.0 through roughly 4.5.
*/
mos: Stats;
/**
* Round trip time, to the server back to the client.
*/
rtt: Stats;
}
/**
* Represents general stats for a specific metric.
*/
export interface Stats {
/**
* The average value for this metric.
*/
average: number;
/**
* The maximum value for this metric.
*/
max: number;
/**
* The minimum value for this metric.
*/
min: number;
}
/**
* Represents the report generated from a {@link PreflightTest}.
*/
export interface Report {
/**
* The quality of the call determined by different mos ranges.
*/
callQuality?: CallQuality;
/**
* CallSid generaged during the test.
*/
callSid: string | undefined;
/**
* The edge that the test call was connected to.
*/
edge?: string;
/**
* An array of WebRTC stats for the ICE candidates gathered when connecting to media.
*/
iceCandidateStats: RTCIceCandidateStats[];
/**
* Whether a TURN server is required to connect to media.
* This is dependent on the selected ICE candidates, and will be true if either is of type "relay",
* false if both are of another type, or undefined if there are no selected ICE candidates.
* See `PreflightTest.Options.iceServers` for more details.
*/
isTurnRequired?: boolean;
/**
* Network related time measurements.
*/
networkTiming: NetworkTiming;
/**
* WebRTC samples collected during the test.
*/
samples: RTCSample[];
/**
* The edge passed to `Device.runPreflight`.
*/
selectedEdge?: string;
/**
* A WebRTC stats for the ICE candidate pair used to connect to media, if candidates were selected.
*/
selectedIceCandidatePairStats?: RTCSelectedIceCandidatePairStats;
/**
* RTC related stats captured during the test.
*/
stats?: RTCStats;
/**
* Time measurements of test run time.
*/
testTiming: TimeMeasurement;
/**
* Calculated totals in RTC statistics samples.
*/
totals?: RTCSampleTotals;
/**
* List of warning names and warning data detected during this test.
*/
warnings: PreflightTest.Warning[];
}
/**
* A warning that can be raised by Preflight, and returned in the Report.warnings field.
*/
export interface Warning {
/**
* Description of the Warning
*/
description: string;
/**
* Name of the Warning
*/
name: string;
/**
* If applicable, the RTCWarning that triggered this warning.
*/
rtcWarning?: RTCWarning;
}
} | the_stack |
import '../../../test/common-test-setup-karma';
import '../gr-comment-api/gr-comment-api';
import '../../shared/revision-info/revision-info';
import './gr-patch-range-select';
import {GrPatchRangeSelect} from './gr-patch-range-select';
import '../../../test/mocks/comment-api';
import {RevisionInfo as RevisionInfoClass} from '../../shared/revision-info/revision-info';
import {ChangeComments} from '../gr-comment-api/gr-comment-api';
import {stubRestApi} from '../../../test/test-utils';
import {
BasePatchSetNum,
EditPatchSetNum,
PatchSetNum,
RevisionInfo,
Timestamp,
UrlEncodedCommentId,
PathToCommentsInfoMap,
} from '../../../types/common';
import {EditRevisionInfo, ParsedChangeInfo} from '../../../types/types';
import {SpecialFilePath} from '../../../constants/constants';
import {
createEditRevision,
createRevision,
} from '../../../test/test-data-generators';
import {PatchSet} from '../../../utils/patch-set-util';
import {
DropdownItem,
GrDropdownList,
} from '../../shared/gr-dropdown-list/gr-dropdown-list';
import {queryAndAssert} from '../../../test/test-utils';
const basicFixture = fixtureFromElement('gr-patch-range-select');
type RevIdToRevisionInfo = {
[revisionId: string]: RevisionInfo | EditRevisionInfo;
};
suite('gr-patch-range-select tests', () => {
let element: GrPatchRangeSelect;
function getInfo(revisions: (RevisionInfo | EditRevisionInfo)[]) {
const revisionObj: Partial<RevIdToRevisionInfo> = {};
for (let i = 0; i < revisions.length; i++) {
revisionObj[i] = revisions[i];
}
return new RevisionInfoClass({revisions: revisionObj} as ParsedChangeInfo);
}
setup(async () => {
stubRestApi('getDiffComments').returns(Promise.resolve({}));
stubRestApi('getDiffRobotComments').returns(Promise.resolve({}));
stubRestApi('getDiffDrafts').returns(Promise.resolve({}));
// Element must be wrapped in an element with direct access to the
// comment API.
element = basicFixture.instantiate();
// Stub methods on the changeComments object after changeComments has
// been initialized.
element.changeComments = new ChangeComments();
await element.updateComplete;
});
test('enabled/disabled options', async () => {
element.revisions = [
createRevision(3) as RevisionInfo,
createEditRevision(2) as EditRevisionInfo,
createRevision(2) as RevisionInfo,
createRevision(1) as RevisionInfo,
];
await element.updateComplete;
const parent = 'PARENT' as PatchSetNum;
const edit = EditPatchSetNum;
for (const patchNum of [1, 2, 3]) {
assert.isFalse(
element.computeRightDisabled(parent, patchNum as PatchSetNum)
);
}
for (const basePatchNum of [1, 2]) {
const base = basePatchNum as PatchSetNum;
assert.isFalse(element.computeLeftDisabled(base, 3 as PatchSetNum));
}
assert.isTrue(
element.computeLeftDisabled(3 as PatchSetNum, 3 as PatchSetNum)
);
assert.isTrue(
element.computeLeftDisabled(3 as PatchSetNum, 3 as PatchSetNum)
);
assert.isTrue(element.computeRightDisabled(edit, 1 as PatchSetNum));
assert.isTrue(element.computeRightDisabled(edit, 2 as PatchSetNum));
assert.isFalse(element.computeRightDisabled(edit, 3 as PatchSetNum));
assert.isTrue(element.computeRightDisabled(edit, edit));
});
test('computeBaseDropdownContent', async () => {
element.availablePatches = [
{num: 'edit', sha: '1'} as PatchSet,
{num: 3, sha: '2'} as PatchSet,
{num: 2, sha: '3'} as PatchSet,
{num: 1, sha: '4'} as PatchSet,
];
element.revisions = [
createRevision(2),
createRevision(3),
createRevision(1),
createRevision(4),
];
element.revisionInfo = getInfo(element.revisions);
const expectedResult: DropdownItem[] = [
{
disabled: true,
triggerText: 'Patchset edit',
text: 'Patchset edit | 1',
mobileText: 'edit',
bottomText: '',
value: 'edit',
},
{
disabled: true,
triggerText: 'Patchset 3',
text: 'Patchset 3 | 2',
mobileText: '3',
bottomText: '',
value: 3,
date: '2020-02-01 01:02:03.000000000' as Timestamp,
} as DropdownItem,
{
disabled: true,
triggerText: 'Patchset 2',
text: 'Patchset 2 | 3',
mobileText: '2',
bottomText: '',
value: 2,
date: '2020-02-01 01:02:03.000000000' as Timestamp,
} as DropdownItem,
{
disabled: true,
triggerText: 'Patchset 1',
text: 'Patchset 1 | 4',
mobileText: '1',
bottomText: '',
value: 1,
date: '2020-02-01 01:02:03.000000000' as Timestamp,
} as DropdownItem,
{
text: 'Base',
value: 'PARENT',
} as DropdownItem,
];
element.patchNum = 1 as PatchSetNum;
element.basePatchNum = 'PARENT' as BasePatchSetNum;
await element.updateComplete;
assert.deepEqual(element.computeBaseDropdownContent(), expectedResult);
});
test('computeBaseDropdownContent called when patchNum updates', async () => {
element.revisions = [
createRevision(2),
createRevision(3),
createRevision(1),
createRevision(4),
];
element.revisionInfo = getInfo(element.revisions);
element.availablePatches = [
{num: 1, sha: '1'} as PatchSet,
{num: 2, sha: '2'} as PatchSet,
{num: 3, sha: '3'} as PatchSet,
{num: 'edit', sha: '4'} as PatchSet,
];
element.patchNum = 2 as PatchSetNum;
element.basePatchNum = 'PARENT' as BasePatchSetNum;
await element.updateComplete;
const baseDropDownStub = sinon.stub(element, 'computeBaseDropdownContent');
// Should be recomputed for each available patch
element.patchNum = 1 as PatchSetNum;
await element.updateComplete;
assert.equal(baseDropDownStub.callCount, 1);
});
test('computeBaseDropdownContent called when changeComments update', async () => {
element.revisions = [
createRevision(2),
createRevision(3),
createRevision(1),
createRevision(4),
];
element.revisionInfo = getInfo(element.revisions);
element.availablePatches = [
{num: 3, sha: '2'} as PatchSet,
{num: 2, sha: '3'} as PatchSet,
{num: 1, sha: '4'} as PatchSet,
];
element.patchNum = 2 as PatchSetNum;
element.basePatchNum = 'PARENT' as BasePatchSetNum;
await element.updateComplete;
// Should be recomputed for each available patch
const baseDropDownStub = sinon.stub(element, 'computeBaseDropdownContent');
assert.equal(baseDropDownStub.callCount, 0);
element.changeComments = new ChangeComments();
await element.updateComplete;
assert.equal(baseDropDownStub.callCount, 1);
});
test('computePatchDropdownContent called when basePatchNum updates', async () => {
element.revisions = [
createRevision(2),
createRevision(3),
createRevision(1),
createRevision(4),
];
element.revisionInfo = getInfo(element.revisions);
element.availablePatches = [
{num: 1, sha: '1'} as PatchSet,
{num: 2, sha: '2'} as PatchSet,
{num: 3, sha: '3'} as PatchSet,
{num: 'edit', sha: '4'} as PatchSet,
];
element.patchNum = 2 as PatchSetNum;
element.basePatchNum = 'PARENT' as BasePatchSetNum;
await element.updateComplete;
// Should be recomputed for each available patch
const baseDropDownStub = sinon.stub(element, 'computePatchDropdownContent');
element.basePatchNum = 1 as BasePatchSetNum;
await element.updateComplete;
assert.equal(baseDropDownStub.callCount, 1);
});
test('computePatchDropdownContent', async () => {
element.availablePatches = [
{num: 'edit', sha: '1'} as PatchSet,
{num: 3, sha: '2'} as PatchSet,
{num: 2, sha: '3'} as PatchSet,
{num: 1, sha: '4'} as PatchSet,
];
element.basePatchNum = 1 as BasePatchSetNum;
element.revisions = [
createRevision(3) as RevisionInfo,
createEditRevision(2) as EditRevisionInfo,
createRevision(2, 'description') as RevisionInfo,
createRevision(1) as RevisionInfo,
];
await element.updateComplete;
const expectedResult: DropdownItem[] = [
{
disabled: false,
triggerText: 'edit',
text: 'edit | 1',
mobileText: 'edit',
bottomText: '',
value: 'edit',
},
{
disabled: false,
triggerText: 'Patchset 3',
text: 'Patchset 3 | 2',
mobileText: '3',
bottomText: '',
value: 3,
date: '2020-02-01 01:02:03.000000000' as Timestamp,
} as DropdownItem,
{
disabled: false,
triggerText: 'Patchset 2',
text: 'Patchset 2 | 3',
mobileText: '2 description',
bottomText: 'description',
value: 2,
date: '2020-02-01 01:02:03.000000000' as Timestamp,
} as DropdownItem,
{
disabled: true,
triggerText: 'Patchset 1',
text: 'Patchset 1 | 4',
mobileText: '1',
bottomText: '',
value: 1,
date: '2020-02-01 01:02:03.000000000' as Timestamp,
} as DropdownItem,
];
assert.deepEqual(element.computePatchDropdownContent(), expectedResult);
});
test('filesWeblinks', async () => {
element.filesWeblinks = {
meta_a: [
{
name: 'foo',
url: 'f.oo',
},
],
meta_b: [
{
name: 'bar',
url: 'ba.r',
},
],
};
await element.updateComplete;
assert.equal(
queryAndAssert(element, 'a[href="f.oo"]').textContent!.trim(),
'foo'
);
assert.equal(
queryAndAssert(element, 'a[href="ba.r"]').textContent!.trim(),
'bar'
);
});
test('computePatchSetCommentsString', () => {
// Test string with unresolved comments.
const comments: PathToCommentsInfoMap = {
foo: [
{
id: '27dcee4d_f7b77cfa' as UrlEncodedCommentId,
message: 'test',
patch_set: 1 as PatchSetNum,
unresolved: true,
updated: '2017-10-11 20:48:40.000000000' as Timestamp,
},
],
bar: [
{
id: '27dcee4d_f7b77cfa' as UrlEncodedCommentId,
message: 'test',
patch_set: 1 as PatchSetNum,
updated: '2017-10-12 20:48:40.000000000' as Timestamp,
},
{
id: '27dcee4d_f7b77cfa' as UrlEncodedCommentId,
message: 'test',
patch_set: 1 as PatchSetNum,
updated: '2017-10-13 20:48:40.000000000' as Timestamp,
},
],
abc: [],
// Patchset level comment does not contribute to the count
[SpecialFilePath.PATCHSET_LEVEL_COMMENTS]: [
{
id: '27dcee4d_f7b77cfa' as UrlEncodedCommentId,
message: 'test',
patch_set: 1 as PatchSetNum,
unresolved: true,
updated: '2017-10-11 20:48:40.000000000' as Timestamp,
},
],
};
element.changeComments = new ChangeComments(comments);
assert.equal(
element.computePatchSetCommentsString(1 as PatchSetNum),
' (3 comments, 1 unresolved)'
);
// Test string with no unresolved comments.
delete comments['foo'];
element.changeComments = new ChangeComments(comments);
assert.equal(
element.computePatchSetCommentsString(1 as PatchSetNum),
' (2 comments)'
);
// Test string with no comments.
delete comments['bar'];
element.changeComments = new ChangeComments(comments);
assert.equal(element.computePatchSetCommentsString(1 as PatchSetNum), '');
});
test('patch-range-change fires', () => {
const handler = sinon.stub();
element.basePatchNum = 1 as BasePatchSetNum;
element.patchNum = 3 as PatchSetNum;
element.addEventListener('patch-range-change', handler);
queryAndAssert<GrDropdownList>(
element,
'#basePatchDropdown'
)._handleValueChange('2', [{text: '', value: '2'}]);
assert.isTrue(handler.calledOnce);
assert.deepEqual(handler.lastCall.args[0].detail, {
basePatchNum: 2,
patchNum: 3,
});
// BasePatchNum should not have changed, due to one-way data binding.
queryAndAssert<GrDropdownList>(
element,
'#patchNumDropdown'
)._handleValueChange('edit', [{text: '', value: 'edit'}]);
assert.deepEqual(handler.lastCall.args[0].detail, {
basePatchNum: 1,
patchNum: 'edit',
});
});
}); | the_stack |
/*
* Copyright (c) 2016 - now David Sehnal, licensed under Apache 2.0, See LICENSE file for more info.
*/
namespace LiteMol.Core.Geometry.MolecularSurface {
"use strict";
export interface MolecularIsoSurfaceParameters {
exactBoundary?: boolean;
boundaryDelta?: { dx: number; dy: number; dz: number };
probeRadius?: number;
atomRadius?: (i: number) => number;
density?: number;
interactive?: boolean;
smoothingIterations?: number;
}
class MolecularIsoSurfaceParametersWrapper implements MolecularIsoSurfaceParameters {
exactBoundary: boolean;
boundaryDelta: { dx: number; dy: number; dz: number };
probeRadius: number;
atomRadius: (i: number) => number;
defaultAtomRadius: number;
density: number;
interactive: boolean;
smoothingIterations: number;
constructor(params?: MolecularIsoSurfaceParameters) {
Core.Utils.extend(this, params, <MolecularIsoSurfaceParameters>{
exactBoundary: false,
boundaryDelta: { dx: 1.5, dy: 1.5, dz: 1.5 },
probeRadius: 1.4,
atomRadii: function () { return 1.0 },
density: 1.1,
interactive: false,
smoothingIterations: 1
});
if (this.exactBoundary) this.boundaryDelta = { dx: 0, dy: 0, dz: 0 };
if (this.density < 0.05) this.density = 0.05;
}
}
export interface MolecularIsoField {
data: Geometry.MarchingCubes.MarchingCubesParameters,
bottomLeft: Geometry.LinearAlgebra.Vector3,
topRight: Geometry.LinearAlgebra.Vector3,
transform: number[],
inputParameters: MolecularSurfaceInputParameters,
parameters: MolecularIsoSurfaceParameters
}
class MolecularIsoFieldComputation {
constructor(private inputParameters: MolecularSurfaceInputParameters, private ctx: Computation.Context) {
this.parameters = new MolecularIsoSurfaceParametersWrapper(inputParameters.parameters);
let positions = inputParameters.positions;
this.x = positions.x;
this.y = positions.y;
this.z = positions.z;
this.atomIndices = inputParameters.atomIndices;
// make the atoms artificially bigger for low resolution surfaces
if (this.parameters.density >= 0.99) {
// so that the number is float and not int32 internally
this.vdwScaleFactor = 1.000000001;
}
else {
this.vdwScaleFactor = 1 + (1 - this.parameters.density * this.parameters.density);
}
}
atomIndices: number[];
parameters: MolecularIsoSurfaceParametersWrapper;
vdwScaleFactor: number;
x: number[]; y: number[]; z: number[];
minX = Number.MAX_VALUE; minY = Number.MAX_VALUE; minZ = Number.MAX_VALUE;
maxX = -Number.MAX_VALUE; maxY = -Number.MAX_VALUE; maxZ = -Number.MAX_VALUE;
nX = 0; nY = 0; nZ = 0;
dX = 0.1; dY = 0.1; dZ = 0.1;
field = new Float32Array(0); distanceField = new Float32Array(0); proximityMap = new Int32Array(0);
minIndex = { i: 0, j: 0, k: 0 }; maxIndex = { i: 0, j: 0, k: 0 };
private findBounds() {
for (let aI of this.atomIndices) {
let r = this.parameters.exactBoundary ? 0 : this.vdwScaleFactor * this.parameters.atomRadius(aI) + this.parameters.probeRadius,
xx = this.x[aI], yy = this.y[aI], zz = this.z[aI];
if (r < 0) continue;
this.minX = Math.min(this.minX, xx - r);
this.minY = Math.min(this.minY, yy - r);
this.minZ = Math.min(this.minZ, zz - r);
this.maxX = Math.max(this.maxX, xx + r);
this.maxY = Math.max(this.maxY, yy + r);
this.maxZ = Math.max(this.maxZ, zz + r);
}
if (this.minX === Number.MAX_VALUE) {
this.minX = this.minY = this.minZ = -1;
this.maxX = this.maxY = this.maxZ = 1;
}
this.minX -= this.parameters.boundaryDelta.dx; this.minY -= this.parameters.boundaryDelta.dy; this.minZ -= this.parameters.boundaryDelta.dz;
this.maxX += this.parameters.boundaryDelta.dx; this.maxY += this.parameters.boundaryDelta.dy; this.maxZ += this.parameters.boundaryDelta.dz;
this.nX = Math.floor((this.maxX - this.minX) * this.parameters.density);
this.nY = Math.floor((this.maxY - this.minY) * this.parameters.density);
this.nZ = Math.floor((this.maxZ - this.minZ) * this.parameters.density);
this.nX = Math.min(this.nX, 333);
this.nY = Math.min(this.nY, 333);
this.nZ = Math.min(this.nZ, 333);
this.dX = (this.maxX - this.minX) / (this.nX - 1);
this.dY = (this.maxY - this.minY) / (this.nY - 1);
this.dZ = (this.maxZ - this.minZ) / (this.nZ - 1);
}
private initData() {
let len = this.nX * this.nY * this.nZ;
this.field = new Float32Array(len);
this.distanceField = new Float32Array(len);
this.proximityMap = new Int32Array(len);
let mv = Number.POSITIVE_INFINITY;
for (let j = 0, _b = this.proximityMap.length; j < _b; j++) {
this.distanceField[j] = mv;
this.proximityMap[j] = -1;
}
}
private updateMinIndex(x: number, y: number, z: number) {
this.minIndex.i = Math.max((Math.floor((x - this.minX) / this.dX)) | 0, 0);
this.minIndex.j = Math.max((Math.floor((y - this.minY) / this.dY)) | 0, 0);
this.minIndex.k = Math.max((Math.floor((z - this.minZ) / this.dZ)) | 0, 0);
}
private updateMaxIndex(x: number, y: number, z: number) {
this.maxIndex.i = Math.min((Math.ceil((x - this.minX) / this.dX)) | 0, this.nX);
this.maxIndex.j = Math.min((Math.ceil((y - this.minY) / this.dY)) | 0, this.nY);
this.maxIndex.k = Math.min((Math.ceil((z - this.minZ) / this.dZ)) | 0, this.nZ);
}
private addBall(aI: number, strength: number) {
let strSq = strength * strength;
let cx = this.x[aI], cy = this.y[aI], cz = this.z[aI];
this.updateMinIndex(cx - strength, cy - strength, cz - strength);
this.updateMaxIndex(cx + strength, cy + strength, cz + strength);
let mini = this.minIndex.i, minj = this.minIndex.j, mink = this.minIndex.k;
let maxi = this.maxIndex.i, maxj = this.maxIndex.j, maxk = this.maxIndex.k;
cx = this.minX - cx;
cy = this.minY - cy;
cz = this.minZ - cz;
for (let k = mink; k < maxk; k++) {
let tZ = cz + k * this.dZ,
zz = tZ * tZ,
oZ = k * this.nY;
for (let j = minj; j < maxj; j++) {
let tY = cy + j * this.dY,
yy = zz + tY * tY,
oY = this.nX * (oZ + j);
for (let i = mini; i < maxi; i++) {
let tX = cx + i * this.dX,
xx = yy + tX * tX,
offset = oY + i;
let v = strSq / (0.000001 + xx) - 1;
if (xx < this.distanceField[offset]) {
this.proximityMap[offset] = aI;
this.distanceField[offset] = xx;
}
if (v > 0) {
this.field[offset] += v;
}
}
}
}
}
private async processChunks() {
const chunkSize = 10000;
let started = Utils.PerformanceMonitor.currentTime();
await this.ctx.updateProgress('Creating field...', true);
for (let currentAtom = 0, _b = this.atomIndices.length; currentAtom < _b; currentAtom++) {
let aI = this.atomIndices[currentAtom];
let r = this.vdwScaleFactor * this.parameters.atomRadius(aI) + this.parameters.probeRadius;
if (r >= 0) {
this.addBall(aI, r);
}
if ((currentAtom + 1) % chunkSize === 0) {
let t = Utils.PerformanceMonitor.currentTime();
if (t - started > Computation.UpdateProgressDelta) {
started = t;
await this.ctx.updateProgress('Creating field...', true, currentAtom, _b);
}
}
}
}
private finish() {
let t = Geometry.LinearAlgebra.Matrix4.zero();
Geometry.LinearAlgebra.Matrix4.fromTranslation(t, [this.minX, this.minY, this.minZ]);
t[0] = this.dX;
t[5] = this.dY;
t[10] = this.dZ;
let ret = {
data: <Core.Geometry.MarchingCubes.MarchingCubesParameters>{
scalarField: new Formats.Density.Field3DZYX(<any>this.field, [this.nX, this.nY, this.nZ]),
annotationField: this.parameters.interactive ? new Formats.Density.Field3DZYX(<any>this.proximityMap, [this.nX, this.nY, this.nZ]) : void 0,
isoLevel: 0.05
},
bottomLeft: LinearAlgebra.Vector3.fromValues(this.minX, this.minY, this.minZ),
topRight: LinearAlgebra.Vector3.fromValues(this.maxX, this.maxY, this.maxZ),
transform: t,
inputParameters: this.inputParameters,
parameters: this.parameters
};
// help the gc
this.distanceField = <any>null;
this.proximityMap = <any>null;
return ret;
}
async run() {
await this.ctx.updateProgress('Initializing...');
this.findBounds();
this.initData();
await this.processChunks();
await this.ctx.updateProgress('Finalizing...', void 0, this.atomIndices.length, this.atomIndices.length);
return this.finish();
}
}
export interface MolecularIsoSurfaceGeometryData {
surface: Surface,
usedParameters: MolecularIsoSurfaceParameters
}
export function createMolecularIsoFieldAsync(parameters: MolecularSurfaceInputParameters): Computation<MolecularIsoField> {
return computation(async ctx => {
let field = new MolecularIsoFieldComputation(parameters, ctx);
return await field.run();
});
}
export interface MolecularSurfaceInputParameters {
positions: Core.Structure.PositionTable,
atomIndices: number[],
parameters?: MolecularIsoSurfaceParameters
}
export function computeMolecularSurfaceAsync(parameters: MolecularSurfaceInputParameters): Computation<MolecularIsoSurfaceGeometryData> {
return computation<MolecularIsoSurfaceGeometryData>(async ctx => {
let field = await createMolecularIsoFieldAsync(parameters).run(ctx);
let surface = await MarchingCubes.compute(field.data).run(ctx);
surface = await Surface.transform(surface, field.transform).run(ctx);
let smoothing = (parameters.parameters && parameters.parameters.smoothingIterations) || 1;
let smoothingVertexWeight = 1.0;
// low density results in very low detail and large distance between vertices.
// Applying uniform laplacian smmoth to such surfaces makes the surface a lot smaller
// in each iteration.
// To reduce this behaviour, the weight of the "central" vertex is increased
// for low desities to better preserve the shape of the surface.
if (parameters.parameters && parameters.parameters.density! < 1) {
smoothingVertexWeight = 2 / parameters.parameters.density!;
}
surface = await Surface.laplacianSmooth(surface, smoothing, smoothingVertexWeight).run(ctx);
return { surface, usedParameters: field.parameters };
});
}
} | the_stack |
import { FocusMonitor } from '@angular/cdk/a11y';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
Inject,
Input,
NgZone,
OnDestroy,
Optional,
Output,
ViewChild,
ViewEncapsulation,
} from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { CHECKBOX_CLICK_ACTION, CheckboxClickAction } from './checkbox-config';
let uniqueId = 0;
/** Change event object emitted by Checkbox. */
export class CheckboxChange {
/** The source Checkbox of the event. */
source: CheckboxComponent;
/** The new `checked` value of the checkbox. */
checked: boolean;
}
/**
* A material design checkbox component. Supports all of the functionality of an HTML5 checkbox,
* and exposes a similar API. A MatCheckbox can be either checked, unchecked, indeterminate, or
* disabled. Note that all additional accessibility attributes are taken care of by the component,
* so there is no need to provide them yourself. However, if you want to omit a label and still
* have the checkbox be accessible, you may supply an [aria-label] input.
* See: https://material.io/design/components/selection-controls.html
*/
@Component({
selector: 'gd-checkbox',
exportAs: 'gdCheckbox',
templateUrl: './checkbox.component.html',
styleUrls: ['./checkbox.component.scss'],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: CheckboxComponent,
multi: true,
},
],
host: {
'class': 'Checkbox',
'[class.Checkbox--checked]': 'checked',
'[class.Checkbox--indeterminate]': 'indeterminate',
'[class.Checkbox--disabled]': 'disabled',
'[class.Checkbox--fixedWidth]': 'fixedWidth',
'[id]': 'id',
'[attr.tabindex]': 'null',
},
})
export class CheckboxComponent implements ControlValueAccessor, OnDestroy {
/** Name value will be applied to the input element if present */
@Input() name: string | null = null;
/** The value attribute of the native input element */
@Input() value: string;
/** Event emitted when the checkbox's `checked` value changes. */
@Output() readonly change = new EventEmitter<CheckboxChange>();
/** Event emitted when the checkbox's `indeterminate` value changes. */
@Output() readonly indeterminateChange = new EventEmitter<boolean>();
/** The native `<input type="checkbox">` element */
@ViewChild('input') _inputElement: ElementRef<HTMLInputElement>;
/**
* Attached to the aria-label attribute of the host element. In most cases, arial-labelledby will
* take precedence so this may be omitted.
*/
@Input('aria-label') ariaLabel: string = '';
/**
* Users can specify the `aria-labelledby` attribute which will be forwarded to the input element
*/
@Input('aria-labelledby') ariaLabelledby: string | null = null;
private _uniqueId: string = `gd-checkbox-${uniqueId++}`;
/** A unique id for the checkbox input. If none is supplied, it will be auto-generated. */
@Input() id: string = this._uniqueId;
/** Determine to use fixed size of checkbox. */
@Input() fixedWidth: boolean = false;
constructor(
public _elementRef: ElementRef<HTMLElement>,
private changeDetectorRef: ChangeDetectorRef,
private focusMonitor: FocusMonitor,
private ngZone: NgZone,
@Optional() @Inject(CHECKBOX_CLICK_ACTION) private _clickAction: CheckboxClickAction,
) {
this.focusMonitor.monitor(this._elementRef.nativeElement, true).subscribe((focusOrigin) => {
if (!focusOrigin) {
// When a focused element becomes disabled, the browser *immediately* fires a blur event.
// Angular does not expect events to be raised during change detection, so any state change
// (such as a form control's 'ng-touched') will cause a changed-after-checked error.
// See https://github.com/angular/angular/issues/17793. To work around this, we defer
// telling the form control it has been touched until the next tick.
Promise.resolve().then(() => this._onTouched());
}
});
}
private _checked: boolean = false;
/**
* Whether the checkbox is checked.
*/
@Input()
get checked(): boolean {
return this._checked;
}
set checked(value: boolean) {
if (value !== this.checked) {
this._checked = value;
this.changeDetectorRef.markForCheck();
}
}
private _disabled: boolean = false;
/**
* Whether the checkbox is disabled. This fully overrides the implementation provided by
* mixinDisabled, but the mixin is still required because mixinTabIndex requires it.
*/
@Input()
get disabled() {
return this._disabled;
}
set disabled(value: any) {
const newValue = coerceBooleanProperty(value);
if (newValue !== this.disabled) {
this._disabled = newValue;
this.changeDetectorRef.markForCheck();
}
}
private _indeterminate: boolean = false;
/**
* Whether the checkbox is indeterminate. This is also known as "mixed" mode and can be used to
* represent a checkbox with three states, e.g. a checkbox that represents a nested list of
* checkable items. Note that whenever checkbox is manually clicked, indeterminate is immediately
* set to false.
*/
@Input()
get indeterminate(): boolean {
return this._indeterminate;
}
set indeterminate(value: boolean) {
const changed = value !== this._indeterminate;
this._indeterminate = value;
if (changed) {
this.indeterminateChange.emit(this._indeterminate);
}
}
get inputId(): string {
return `${this.id || this._uniqueId}-input`;
}
/**
* Called when the checkbox is blurred. Needed to properly implement ControlValueAccessor.
* @docs-private
*/
/* tslint:disable */
_onTouched: () => any = () => {
};
/* tslint:enable */
ngOnDestroy(): void {
this.focusMonitor.stopMonitoring(this._elementRef.nativeElement);
}
// Implemented as part of ControlValueAccessor.
writeValue(value: any): void {
this.checked = !!value;
}
// Implemented as part of ControlValueAccessor.
registerOnChange(fn: (value: any) => void): void {
this._controlValueAccessorChangeFn = fn;
}
// Implemented as part of ControlValueAccessor.
registerOnTouched(fn: any): void {
this._onTouched = fn;
}
// Implemented as part of ControlValueAccessor.
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
/** Toggles the `checked` state of the checkbox. */
toggle(): void {
this.checked = !this.checked;
}
_getAriaChecked(): 'true' | 'false' | 'mixed' {
return this.checked ? 'true' : (this.indeterminate ? 'mixed' : 'false');
}
/** Method being called whenever the label text changes. */
_onLabelTextChange(): void {
// Since the event of the `cdkObserveContent` directive runs outside of the zone, the checkbox
// component will be only marked for check, but no actual change detection runs automatically.
// Instead of going back into the zone in order to trigger a change detection which causes
// *all* components to be checked (if explicitly marked or not using OnPush), we only trigger
// an explicit change detection for the checkbox view and it's children.
this.changeDetectorRef.detectChanges();
}
/**
* Event handler for checkbox input element.
* Toggles checked state if element is not disabled.
* Do not toggle on (change) event since IE doesn't fire change event when
* indeterminate checkbox is clicked.
* @param event
*/
_onInputClick(event: Event): void {
// We have to stop propagation for click events on the visual hidden input element.
// By default, when a user clicks on a label element, a generated click event will be
// dispatched on the associated input element. Since we are using a label element as our
// root container, the click event on the `checkbox` will be executed twice.
// The real click event will bubble up, and the generated click event also tries to bubble up.
// This will lead to multiple click events.
// Preventing bubbling for the second event will solve that issue.
event.stopPropagation();
// If resetIndeterminate is false, and the current state is indeterminate, do nothing on click
if (!this.disabled && this._clickAction !== 'noop') {
// When user manually click on the checkbox, `indeterminate` is set to false.
if (this.indeterminate && this._clickAction !== 'check') {
Promise.resolve().then(() => {
this._indeterminate = false;
this.indeterminateChange.emit(this._indeterminate);
});
}
this.toggle();
// Emit our custom change event if the native input emitted one.
// It is important to only emit it, if the native input triggered one, because
// we don't want to trigger a change event, when the `checked` variable changes for example.
this._emitChangeEvent();
} else if (!this.disabled && this._clickAction === 'noop') {
// Reset native input when clicked with noop. The native checkbox becomes checked after
// click, reset it to be align with `checked` value of `mat-checkbox`.
this._inputElement.nativeElement.checked = this.checked;
this._inputElement.nativeElement.indeterminate = this.indeterminate;
}
}
/** Focuses the checkbox. */
focus(): void {
this.focusMonitor.focusVia(this._inputElement.nativeElement, 'keyboard');
}
_onInteractionEvent(event: Event): void {
// We always have to stop propagation on the change event.
// Otherwise the change event, from the input element, will bubble up and
// emit its event object to the `change` output.
event.stopPropagation();
}
/* tslint:disable */
private _controlValueAccessorChangeFn: (value: any) => void = () => {
};
/* tslint:enable */
private _emitChangeEvent() {
const event = new CheckboxChange();
event.source = this;
event.checked = this.checked;
this._controlValueAccessorChangeFn(this.checked);
this.change.emit(event);
}
} | the_stack |
import { LokiEventEmitter } from "./event_emitter";
import { ResultSet } from "./result_set";
import { Collection } from "./collection";
import { Doc } from "../../common/types";
import { Scorer } from "../../full-text-search/src/scorer";
/**
* DynamicView class is a versatile 'live' view class which can have filters and sorts applied.
* Collection.addDynamicView(name) instantiates this DynamicView object and notifies it
* whenever documents are add/updated/removed so it can remain up-to-date. (chainable)
*
* @example
* let mydv = mycollection.addDynamicView('test'); // default is non-persistent
* mydv.applyFind({ 'doors' : 4 });
* mydv.applyWhere(function(obj) { return obj.name === 'Toyota'; });
* let results = mydv.data();
*
* @extends LokiEventEmitter
* @see {@link Collection#addDynamicView} to construct instances of DynamicView
*
* @param <TData> - the data type
* @param <TNested> - nested properties of data type
*/
export declare class DynamicView<T extends object = object> extends LokiEventEmitter {
readonly name: string;
private _collection;
private _persistent;
private _sortPriority;
private _minRebuildInterval;
private _rebuildPending;
private _resultSet;
private _resultData;
private _resultDirty;
private _cachedResultSet;
private _filterPipeline;
private _sortFunction;
private _sortCriteria;
private _sortCriteriaSimple;
private _sortByScoring;
private _sortDirty;
/**
* Constructor.
* @param {Collection} collection - a reference to the collection to work agains
* @param {string} name - the name of this dynamic view
* @param {object} options - the options
* @param {boolean} [options.persistent=false] - indicates if view is to main internal results array in 'resultdata'
* @param {string} [options.sortPriority="passive"] - the sort priority
* @param {number} [options.minRebuildInterval=1] - minimum rebuild interval (need clarification to docs here)
*/
constructor(collection: Collection<T>, name: string, options?: DynamicView.Options);
/**
* Internally used immediately after deserialization (loading)
* This will clear out and reapply filterPipeline ops, recreating the view.
* Since where filters do not persist correctly, this method allows
* restoring the view to state where user can re-apply those where filters.
*
* @param removeWhereFilters
* @returns {DynamicView} This dynamic view for further chained ops.
* @fires DynamicView.rebuild
*/
private _rematerialize({removeWhereFilters});
/**
* Makes a copy of the internal ResultSet for branched queries.
* Unlike this dynamic view, the branched ResultSet will not be 'live' updated,
* so your branched query should be immediately resolved and not held for future evaluation.
* @param {(string|array=)} transform - Optional name of collection transform, or an array of transform steps
* @param {object} parameters - optional parameters (if optional transform requires them)
* @returns {ResultSet} A copy of the internal ResultSet for branched queries.
*/
branchResultSet(transform?: string | Collection.Transform<T>[], parameters?: object): ResultSet<T>;
/**
* Override of toJSON to avoid circular references.
*/
toJSON(): DynamicView.Serialized;
static fromJSONObject(collection: Collection, obj: DynamicView.Serialized): DynamicView;
/**
* Used to clear pipeline and reset dynamic view to initial state.
* Existing options should be retained.
* @param {boolean} queueSortPhase - (default: false) if true we will async rebuild view (maybe set default to true in future?)
*/
removeFilters({queueSortPhase}?: {
queueSortPhase?: boolean;
}): void;
/**
* Used to apply a sort to the dynamic view
* @example
* dv.applySort(function(obj1, obj2) {
* if (obj1.name === obj2.name) return 0;
* if (obj1.name > obj2.name) return 1;
* if (obj1.name < obj2.name) return -1;
* });
* @param {function} comparefun - a javascript compare function used for sorting
* @returns {DynamicView} this DynamicView object, for further chain ops.
*/
applySort(comparefun: (lhs: Doc<T>, rhs: Doc<T>) => number): this;
/**
* Used to specify a property used for view translation.
* @param {string} field - the field name
* @param {boolean|object=} options - boolean for sort descending or options object
* @param {boolean} [options.desc=false] - whether we should sort descending.
* @param {boolean} [options.disableIndexIntersect=false] - whether we should explicity not use array intersection.
* @param {boolean} [options.forceIndexIntersect=false] - force array intersection (if binary index exists).
* @param {boolean} [options.useJavascriptSorting=false] - whether results are sorted via basic javascript sort.
* @returns {DynamicView} this DynamicView object, for further chain ops.
* @example
* dv.applySimpleSort("name");
*/
applySimpleSort(field: keyof T, options?: boolean | ResultSet.SimpleSortOptions): this;
/**
* Allows sorting a ResultSet based on multiple columns.
* @param {Array} criteria - array of property names or subarray of [propertyname, isdesc] used evaluate sort order
* @returns {DynamicView} Reference to this DynamicView, sorted, for future chain operations.
* @example
* // to sort by age and then name (both ascending)
* dv.applySortCriteria(['age', 'name']);
* // to sort by age (ascending) and then by name (descending)
* dv.applySortCriteria(['age', ['name', true]]);
* // to sort by age (descending) and then by name (descending)
* dv.applySortCriteria([['age', true], ['name', true]]);
*/
applySortCriteria(criteria: (keyof T | [keyof T, boolean])[]): this;
/**
* Used to apply a sort by the latest full-text-search scoring.
* @param {boolean} [ascending=false] - sort ascending
*/
applySortByScoring(ascending?: boolean): this;
/**
* Returns the scoring of the last full-text-search.
* @returns {ScoreResult[]}
*/
getScoring(): Scorer.ScoreResult[];
/**
* Marks the beginning of a transaction.
* @returns {DynamicView} this DynamicView object, for further chain ops.
*/
startTransaction(): this;
/**
* Commits a transaction.
* @returns {DynamicView} this DynamicView object, for further chain ops.
*/
commit(): this;
/**
* Rolls back a transaction.
* @returns {DynamicView} this DynamicView object, for further chain ops.
*/
rollback(): this;
/**
* Find the index of a filter in the pipeline, by that filter's ID.
* @param {(string|number)} uid - The unique ID of the filter.
* @returns {number}: index of the referenced filter in the pipeline; -1 if not found.
*/
private _indexOfFilterWithId(uid);
/**
* Add the filter object to the end of view's filter pipeline and apply the filter to the ResultSet.
* @param {object} filter - The filter object. Refer to applyFilter() for extra details.
*/
private _addFilter(filter);
/**
* Reapply all the filters in the current pipeline.
*
* @returns {DynamicView} this DynamicView object, for further chain ops.
*/
reapplyFilters(): this;
/**
* Adds or updates a filter in the DynamicView filter pipeline
* @param {object} filter - A filter object to add to the pipeline.
* The object is in the format { 'type': filter_type, 'val', filter_param, 'uid', optional_filter_id }
* @returns {DynamicView} this DynamicView object, for further chain ops.
*/
applyFilter(filter: DynamicView.Filter<T>): this;
/**
* applyFind() - Adds or updates a mongo-style query option in the DynamicView filter pipeline
*
* @param {object} query - A mongo-style query object to apply to pipeline
* @param {(string|number)} uid - Optional: The unique ID of this filter, to reference it in the future.
* @returns {DynamicView} this DynamicView object, for further chain ops.
*/
applyFind(query: object, uid?: string | number): this;
/**
* Adds or updates a javascript filter function in the DynamicView filter pipeline
* @param {function} fun - A javascript filter function to apply to pipeline
* @param {(string|number)} uid - Optional: The unique ID of this filter, to reference it in the future.
* @returns {DynamicView} this DynamicView object, for further chain ops.
*/
applyWhere(fun: (obj: Doc<T>) => boolean, uid?: string | number): this;
/**
* Remove the specified filter from the DynamicView filter pipeline
* @param {(string|number)} uid - The unique ID of the filter to be removed.
* @returns {DynamicView} this DynamicView object, for further chain ops.
*/
removeFilter(uid: string | number): this;
/**
* Returns the number of documents representing the current DynamicView contents.
* @returns {number} The number of documents representing the current DynamicView contents.
*/
count(): number;
/**
* Resolves and pending filtering and sorting, then returns document array as result.
* @param {object} options - optional parameters to pass to ResultSet.data() if non-persistent
* @param {boolean} [options.forceClones] - Allows forcing the return of cloned objects even when
* the collection is not configured for clone object.
* @param {string} [options.forceCloneMethod] - Allows overriding the default or collection specified cloning method.
* Possible values include 'parse-stringify', 'jquery-extend-deep', 'shallow', 'shallow-assign'
* @param {boolean} [options.removeMeta] - will force clones and strip $loki and meta properties from documents
*
* @returns {Array} An array of documents representing the current DynamicView contents.
*/
data(options?: ResultSet.DataOptions): Doc<T>[];
/**
* When the view is not sorted we may still wish to be notified of rebuild events.
* This event will throttle and queue a single rebuild event when batches of updates affect the view.
*/
private _queueRebuildEvent();
/**
* If the view is sorted we will throttle sorting to either :
* (1) passive - when the user calls data(), or
* (2) active - once they stop updating and yield js thread control
*/
private _queueSortPhase();
/**
* Invoked synchronously or asynchronously to perform final sort phase (if needed)
*/
private _performSortPhase(options?);
/**
* (Re)evaluating document inclusion.
* Called by : collection.insert() and collection.update().
* @param {int} objIndex - index of document to (re)run through filter pipeline.
* @param {boolean} isNew - true if the document was just added to the collection.
* @hidden
*/
_evaluateDocument(objIndex: number, isNew: boolean): void;
/**
* Internal function called on collection.delete().
* @hidden
*/
_removeDocument(objIndex: number): void;
/**
* Data transformation via user supplied functions
* @param {function} mapFunction - this function accepts a single document for you to transform and return
* @param {function} reduceFunction - this function accepts many (array of map outputs) and returns single value
* @returns The output of your reduceFunction
*/
mapReduce<U1, U2>(mapFunction: (item: T, index: number, array: T[]) => U1, reduceFunction: (array: U1[]) => U2): U2;
}
export declare namespace DynamicView {
interface Options {
persistent?: boolean;
sortPriority?: SortPriority;
minRebuildInterval?: number;
}
type SortPriority = "passive" | "active";
interface Serialized {
name: string;
_persistent: boolean;
_sortPriority: SortPriority;
_minRebuildInterval: number;
_resultSet: ResultSet<any>;
_filterPipeline: Filter<any>[];
_sortCriteria: (string | [string, boolean])[];
_sortCriteriaSimple: {
field: string;
options: boolean | ResultSet.SimpleSortOptions;
};
_sortByScoring: boolean;
_sortDirty: boolean;
}
type Filter<T extends object = object> = {
type: "find";
val: ResultSet.Query<Doc<T>>;
uid: number | string;
} | {
type: "where";
val: (obj: Doc<T>) => boolean;
uid: number | string;
};
} | the_stack |
import * as JVMTypes from '../../includes/JVMTypes';
import * as Doppio from '../doppiojvm';
import JVMThread = Doppio.VM.Threading.JVMThread;
import ReferenceClassData = Doppio.VM.ClassFile.ReferenceClassData;
import logging = Doppio.Debug.Logging;
import util = Doppio.VM.Util;
import ConstantPool = Doppio.VM.ClassFile.ConstantPool;
import Long = Doppio.VM.Long;
import Method = Doppio.VM.ClassFile.Method;
import ThreadStatus = Doppio.VM.Enums.ThreadStatus;
import assert = Doppio.Debug.Assert;
import PrimitiveClassData = Doppio.VM.ClassFile.PrimitiveClassData;
import IStackTraceFrame = Doppio.VM.Threading.IStackTraceFrame;
export default function (): any {
class sun_reflect_ConstantPool {
public static 'getSize0(Ljava/lang/Object;)I'(thread: JVMThread, javaThis: JVMTypes.sun_reflect_ConstantPool, cp: ConstantPool.ConstantPool): number {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return 0;
}
public static 'getClassAt0(Ljava/lang/Object;I)Ljava/lang/Class;'(thread: JVMThread, javaThis: JVMTypes.sun_reflect_ConstantPool, cp: ConstantPool.ConstantPool, arg1: number): JVMTypes.java_lang_Class {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return null;
}
public static 'getClassAtIfLoaded0(Ljava/lang/Object;I)Ljava/lang/Class;'(thread: JVMThread, javaThis: JVMTypes.sun_reflect_ConstantPool, cp: ConstantPool.ConstantPool, arg1: number): JVMTypes.java_lang_Class {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return null;
}
public static 'getMethodAt0(Ljava/lang/Object;I)Ljava/lang/reflect/Member;'(thread: JVMThread, javaThis: JVMTypes.sun_reflect_ConstantPool, cp: ConstantPool.ConstantPool, arg1: number): JVMTypes.java_lang_reflect_Member {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return null;
}
public static 'getMethodAtIfLoaded0(Ljava/lang/Object;I)Ljava/lang/reflect/Member;'(thread: JVMThread, javaThis: JVMTypes.sun_reflect_ConstantPool, cp: ConstantPool.ConstantPool, arg1: number): JVMTypes.java_lang_reflect_Member {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return null;
}
public static 'getFieldAt0(Ljava/lang/Object;I)Ljava/lang/reflect/Field;'(thread: JVMThread, javaThis: JVMTypes.sun_reflect_ConstantPool, cp: ConstantPool.ConstantPool, arg1: number): JVMTypes.java_lang_reflect_Field {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return null;
}
public static 'getFieldAtIfLoaded0(Ljava/lang/Object;I)Ljava/lang/reflect/Field;'(thread: JVMThread, javaThis: JVMTypes.sun_reflect_ConstantPool, cp: ConstantPool.ConstantPool, arg1: number): JVMTypes.java_lang_reflect_Field {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return null;
}
public static 'getMemberRefInfoAt0(Ljava/lang/Object;I)[Ljava/lang/String;'(thread: JVMThread, javaThis: JVMTypes.sun_reflect_ConstantPool, cp: ConstantPool.ConstantPool, arg1: number): JVMTypes.JVMArray<JVMTypes.java_lang_String> {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return null;
}
public static 'getIntAt0(Ljava/lang/Object;I)I'(thread: JVMThread, javaThis: JVMTypes.sun_reflect_ConstantPool, cp: ConstantPool.ConstantPool, idx: number): number {
return (<ConstantPool.ConstInt32> cp.get(idx)).value;
}
public static 'getLongAt0(Ljava/lang/Object;I)J'(thread: JVMThread, javaThis: JVMTypes.sun_reflect_ConstantPool, cp: ConstantPool.ConstantPool, idx: number): Long {
return (<ConstantPool.ConstLong> cp.get(idx)).value;
}
public static 'getFloatAt0(Ljava/lang/Object;I)F'(thread: JVMThread, javaThis: JVMTypes.sun_reflect_ConstantPool, cp: ConstantPool.ConstantPool, arg1: number): number {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return 0;
}
public static 'getDoubleAt0(Ljava/lang/Object;I)D'(thread: JVMThread, javaThis: JVMTypes.sun_reflect_ConstantPool, cp: ConstantPool.ConstantPool, arg1: number): number {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return 0;
}
public static 'getStringAt0(Ljava/lang/Object;I)Ljava/lang/String;'(thread: JVMThread, javaThis: JVMTypes.sun_reflect_ConstantPool, cp: ConstantPool.ConstantPool, arg1: number): JVMTypes.java_lang_String {
thread.throwNewException('Ljava/lang/UnsatisfiedLinkError;', 'Native method not implemented.');
// Satisfy TypeScript return type.
return null;
}
public static 'getUTF8At0(Ljava/lang/Object;I)Ljava/lang/String;'(thread: JVMThread, javaThis: JVMTypes.sun_reflect_ConstantPool, cp: ConstantPool.ConstantPool, idx: number): JVMTypes.java_lang_String {
return util.initString(thread.getBsCl(), (<ConstantPool.ConstUTF8> cp.get(idx)).value);
}
}
class sun_reflect_NativeConstructorAccessorImpl {
public static 'newInstance0(Ljava/lang/reflect/Constructor;[Ljava/lang/Object;)Ljava/lang/Object;'(thread: JVMThread, m: JVMTypes.java_lang_reflect_Constructor, params: JVMTypes.JVMArray<JVMTypes.java_lang_Object>): void {
var cls = m['java/lang/reflect/Constructor/clazz'],
slot = m['java/lang/reflect/Constructor/slot'];
thread.setStatus(ThreadStatus.ASYNC_WAITING);
cls.$cls.initialize(thread, (cls: ReferenceClassData<JVMTypes.java_lang_Object>) => {
if (cls !== null) {
var method: Method = cls.getMethodFromSlot(slot),
obj = new (cls.getConstructor(thread))(thread),
cb = (e?: JVMTypes.java_lang_Throwable) => {
if (e) {
// Wrap in a java.lang.reflect.InvocationTargetException
thread.getBsCl().initializeClass(thread, 'Ljava/lang/reflect/InvocationTargetException;', (cdata: ReferenceClassData<JVMTypes.java_lang_reflect_InvocationTargetException>) => {
if (cdata !== null) {
var wrappedE = new (cdata.getConstructor(thread))(thread);
wrappedE['<init>(Ljava/lang/Throwable;)V'](thread, [e], (e?: JVMTypes.java_lang_Throwable) => {
thread.throwException(e ? e : wrappedE);
});
}
});
} else {
// rv is not defined, since constructors do not return a value.
// Return the object we passed to the constructor.
thread.asyncReturn(obj);
}
};
var paramTypes = m['java/lang/reflect/Constructor/parameterTypes'].array.map((pType) => pType.$cls.getInternalName());
assert(slot >= 0, "Found a constructor without a slot?!");
(<JVMTypes.JVMFunction> (<any> obj)[method.signature])(thread, params ? util.unboxArguments(thread, paramTypes, params.array) : null, cb);
}
}, true);
}
}
class sun_reflect_NativeMethodAccessorImpl {
/**
* Invoke the specified method on the given object with the given parameters.
* If the method is an interface method, perform a virtual method dispatch.
*/
public static 'invoke0(Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;'(thread: JVMThread, mObj: JVMTypes.java_lang_reflect_Method, obj: JVMTypes.java_lang_Object, params: JVMTypes.JVMArray<JVMTypes.java_lang_Object>): void {
var cls = <ReferenceClassData<JVMTypes.java_lang_Object>> mObj['java/lang/reflect/Method/clazz'].$cls,
slot: number = mObj['java/lang/reflect/Method/slot'],
retType = mObj['java/lang/reflect/Method/returnType'],
m: Method = cls.getMethodFromSlot(slot),
args: any[] = [],
cb = (e?: JVMTypes.java_lang_Throwable, rv?: any) => {
if (e) {
// Wrap in a java.lang.reflect.InvocationTargetException
thread.getBsCl().initializeClass(thread, 'Ljava/lang/reflect/InvocationTargetException;', (cdata: ReferenceClassData<JVMTypes.java_lang_reflect_InvocationTargetException>) => {
if (cdata !== null) {
var wrappedE = new (cdata.getConstructor(thread))(thread);
wrappedE['<init>(Ljava/lang/Throwable;)V'](thread, [e], (e?: JVMTypes.java_lang_Throwable) => {
thread.throwException(e ? e : wrappedE);
});
}
});
} else {
if (util.is_primitive_type(m.returnType)) {
if (m.returnType === 'V') {
// apparently the JVM returns NULL when there's a void return value,
// rather than autoboxing a Void object. Go figure!
thread.asyncReturn(null);
} else {
// wrap up primitives in their Object box
thread.asyncReturn((<PrimitiveClassData> retType.$cls).createWrapperObject(thread, rv));
}
} else {
thread.asyncReturn(rv);
}
}
};
if (params !== null) {
args = util.unboxArguments(thread, m.parameterTypes, params.array)
}
thread.setStatus(ThreadStatus.ASYNC_WAITING);
if (m.accessFlags.isStatic()) {
(<JVMTypes.JVMFunction> (<any> cls.getConstructor(thread))[m.fullSignature])(thread, args, cb);
} else {
(<JVMTypes.JVMFunction> (<any> obj)[m.signature])(thread, args, cb);
}
}
}
/**
* From JDK documentation:
* Returns the class of the method realFramesToSkip frames up the stack
* (zero-based), ignoring frames associated with
* java.lang.reflect.Method.invoke() and its implementation. The first
* frame is that associated with this method, so getCallerClass(0) returns
* the Class object for sun.reflect.Reflection. Frames associated with
* java.lang.reflect.Method.invoke() and its implementation are completely
* ignored and do not count toward the number of "real" frames skipped.
*/
function getCallerClass(thread: JVMThread, framesToSkip: number): JVMTypes.java_lang_Class {
var caller = thread.getStackTrace(),
idx = caller.length - 1 - framesToSkip,
frame: IStackTraceFrame = caller[idx];
while (frame.method.fullSignature.indexOf('java/lang/reflect/Method/invoke') === 0) {
if (idx === 0) {
// No more stack to search!
// XXX: What does the JDK do here, throw an exception?
return null;
}
frame = caller[--idx];
}
return frame.method.cls.getClassObject(thread);
}
class sun_reflect_Reflection {
public static 'getCallerClass()Ljava/lang/Class;'(thread: JVMThread): JVMTypes.java_lang_Class {
// 0th item is Reflection class, 1st item is the class that called us,
// and 2nd item is the caller of our caller, which is correct.
return getCallerClass(thread, 2);
}
public static 'getCallerClass(I)Ljava/lang/Class;': (thread: JVMThread, framesToSkip: number) => JVMTypes.java_lang_Class = getCallerClass;
public static 'getClassAccessFlags(Ljava/lang/Class;)I'(thread: JVMThread, classObj: JVMTypes.java_lang_Class): number {
return (<ReferenceClassData<JVMTypes.java_lang_Object>> classObj.$cls).accessFlags.getRawByte();
}
}
return {
'sun/reflect/ConstantPool': sun_reflect_ConstantPool,
'sun/reflect/NativeConstructorAccessorImpl': sun_reflect_NativeConstructorAccessorImpl,
'sun/reflect/NativeMethodAccessorImpl': sun_reflect_NativeMethodAccessorImpl,
'sun/reflect/Reflection': sun_reflect_Reflection
};
}; | the_stack |
/* tslint:disable */
/* eslint-disable */
//----------------------
// <auto-generated>
// Generated using the NSwag toolchain v12.1.0.0 (NJsonSchema v9.13.28.0 (Newtonsoft.Json v11.0.0.0)) (http://NSwag.org)
// </auto-generated>
//----------------------
// ReSharper disable InconsistentNaming
import 'rxjs/add/operator/finally';
import { mergeMap as _observableMergeMap, catchError as _observableCatch } from 'rxjs/operators';
import { Observable, throwError as _observableThrow, of as _observableOf } from 'rxjs';
import { Injectable, Inject, Optional, InjectionToken } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse, HttpResponseBase } from '@angular/common/http';
import * as moment from 'moment';
export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');
@Injectable()
export class EnumTestServiceProxy {
private http: HttpClient;
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
this.http = http;
this.baseUrl = baseUrl ? baseUrl : "";
}
/**
* @return Success
*/
getMember(): Observable<MemberViewModel> {
let url_ = this.baseUrl + "/api/EnumTest/GetMember";
url_ = url_.replace(/[?&]$/, "");
let options_ : any = {
observe: "response",
responseType: "blob",
headers: new HttpHeaders({
"Accept": "application/json"
})
};
return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => {
return this.processGetMember(response_);
})).pipe(_observableCatch((response_: any) => {
if (response_ instanceof HttpResponseBase) {
try {
return this.processGetMember(<any>response_);
} catch (e) {
return <Observable<MemberViewModel>><any>_observableThrow(e);
}
} else
return <Observable<MemberViewModel>><any>_observableThrow(response_);
}));
}
protected processGetMember(response: HttpResponseBase): Observable<MemberViewModel> {
const status = response.status;
const responseBlob =
response instanceof HttpResponse ? response.body :
(<any>response).error instanceof Blob ? (<any>response).error : undefined;
let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }};
if (status === 200) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = resultData200 ? MemberViewModel.fromJS(resultData200) : new MemberViewModel();
return _observableOf(result200);
}));
} else if (status !== 200 && status !== 204) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
}));
}
return _observableOf<MemberViewModel>(<any>null);
}
/**
* @return Success
*/
getPerson(): Observable<PersonViewModel> {
let url_ = this.baseUrl + "/api/EnumTest/GetPerson";
url_ = url_.replace(/[?&]$/, "");
let options_ : any = {
observe: "response",
responseType: "blob",
headers: new HttpHeaders({
"Accept": "application/json"
})
};
return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => {
return this.processGetPerson(response_);
})).pipe(_observableCatch((response_: any) => {
if (response_ instanceof HttpResponseBase) {
try {
return this.processGetPerson(<any>response_);
} catch (e) {
return <Observable<PersonViewModel>><any>_observableThrow(e);
}
} else
return <Observable<PersonViewModel>><any>_observableThrow(response_);
}));
}
protected processGetPerson(response: HttpResponseBase): Observable<PersonViewModel> {
const status = response.status;
const responseBlob =
response instanceof HttpResponse ? response.body :
(<any>response).error instanceof Blob ? (<any>response).error : undefined;
let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }};
if (status === 200) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = resultData200 ? PersonViewModel.fromJS(resultData200) : new PersonViewModel();
return _observableOf(result200);
}));
} else if (status !== 200 && status !== 204) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
}));
}
return _observableOf<PersonViewModel>(<any>null);
}
}
@Injectable()
export class SwaggerTestServiceProxy {
private http: HttpClient;
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
this.http = http;
this.baseUrl = baseUrl ? baseUrl : "";
}
/**
* 获取所有信息
* @return Success
*/
get(): Observable<string[]> {
let url_ = this.baseUrl + "/api/SwaggerTest/Get";
url_ = url_.replace(/[?&]$/, "");
let options_ : any = {
observe: "response",
responseType: "blob",
headers: new HttpHeaders({
"Accept": "application/json"
})
};
return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => {
return this.processGet(response_);
})).pipe(_observableCatch((response_: any) => {
if (response_ instanceof HttpResponseBase) {
try {
return this.processGet(<any>response_);
} catch (e) {
return <Observable<string[]>><any>_observableThrow(e);
}
} else
return <Observable<string[]>><any>_observableThrow(response_);
}));
}
protected processGet(response: HttpResponseBase): Observable<string[]> {
const status = response.status;
const responseBlob =
response instanceof HttpResponse ? response.body :
(<any>response).error instanceof Blob ? (<any>response).error : undefined;
let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }};
if (status === 200) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
if (resultData200 && resultData200.constructor === Array) {
result200 = [] as any;
for (let item of resultData200)
result200.push(item);
}
return _observableOf(result200);
}));
} else if (status !== 200 && status !== 204) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
}));
}
return _observableOf<string[]>(<any>null);
}
/**
* 根据ID获取信息
* @return Success
*/
getById(id: number): Observable<string> {
let url_ = this.baseUrl + "/api/SwaggerTest/GetById/{id}";
if (id === undefined || id === null)
throw new Error("The parameter 'id' must be defined.");
url_ = url_.replace("{id}", encodeURIComponent("" + id));
url_ = url_.replace(/[?&]$/, "");
let options_ : any = {
observe: "response",
responseType: "blob",
headers: new HttpHeaders({
"Accept": "application/json"
})
};
return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => {
return this.processGetById(response_);
})).pipe(_observableCatch((response_: any) => {
if (response_ instanceof HttpResponseBase) {
try {
return this.processGetById(<any>response_);
} catch (e) {
return <Observable<string>><any>_observableThrow(e);
}
} else
return <Observable<string>><any>_observableThrow(response_);
}));
}
protected processGetById(response: HttpResponseBase): Observable<string> {
const status = response.status;
const responseBlob =
response instanceof HttpResponse ? response.body :
(<any>response).error instanceof Blob ? (<any>response).error : undefined;
let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }};
if (status === 200) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = resultData200 !== undefined ? resultData200 : <any>null;
return _observableOf(result200);
}));
} else if (status !== 200 && status !== 204) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
}));
}
return _observableOf<string>(<any>null);
}
/**
* POST了一个数据信息
* @param value (optional)
* @return Success
*/
post(value: string | null | undefined): Observable<void> {
let url_ = this.baseUrl + "/api/SwaggerTest/Post";
url_ = url_.replace(/[?&]$/, "");
const content_ = JSON.stringify(value);
let options_ : any = {
body: content_,
observe: "response",
responseType: "blob",
headers: new HttpHeaders({
"Content-Type": "application/json",
})
};
return this.http.request("post", url_, options_).pipe(_observableMergeMap((response_ : any) => {
return this.processPost(response_);
})).pipe(_observableCatch((response_: any) => {
if (response_ instanceof HttpResponseBase) {
try {
return this.processPost(<any>response_);
} catch (e) {
return <Observable<void>><any>_observableThrow(e);
}
} else
return <Observable<void>><any>_observableThrow(response_);
}));
}
protected processPost(response: HttpResponseBase): Observable<void> {
const status = response.status;
const responseBlob =
response instanceof HttpResponse ? response.body :
(<any>response).error instanceof Blob ? (<any>response).error : undefined;
let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }};
if (status === 200) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return _observableOf<void>(<any>null);
}));
} else if (status !== 200 && status !== 204) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
}));
}
return _observableOf<void>(<any>null);
}
/**
* 根据ID put 数据
* @param value (optional)
* @return Success
*/
put(id: number, value: string | null | undefined): Observable<void> {
let url_ = this.baseUrl + "/api/SwaggerTest/Put/{id}";
if (id === undefined || id === null)
throw new Error("The parameter 'id' must be defined.");
url_ = url_.replace("{id}", encodeURIComponent("" + id));
url_ = url_.replace(/[?&]$/, "");
const content_ = JSON.stringify(value);
let options_ : any = {
body: content_,
observe: "response",
responseType: "blob",
headers: new HttpHeaders({
"Content-Type": "application/json",
})
};
return this.http.request("put", url_, options_).pipe(_observableMergeMap((response_ : any) => {
return this.processPut(response_);
})).pipe(_observableCatch((response_: any) => {
if (response_ instanceof HttpResponseBase) {
try {
return this.processPut(<any>response_);
} catch (e) {
return <Observable<void>><any>_observableThrow(e);
}
} else
return <Observable<void>><any>_observableThrow(response_);
}));
}
protected processPut(response: HttpResponseBase): Observable<void> {
const status = response.status;
const responseBlob =
response instanceof HttpResponse ? response.body :
(<any>response).error instanceof Blob ? (<any>response).error : undefined;
let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }};
if (status === 200) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return _observableOf<void>(<any>null);
}));
} else if (status !== 200 && status !== 204) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
}));
}
return _observableOf<void>(<any>null);
}
/**
* 根据ID删除数据
* @return Success
*/
delete(id: number): Observable<void> {
let url_ = this.baseUrl + "/api/SwaggerTest/Delete/{id}";
if (id === undefined || id === null)
throw new Error("The parameter 'id' must be defined.");
url_ = url_.replace("{id}", encodeURIComponent("" + id));
url_ = url_.replace(/[?&]$/, "");
let options_ : any = {
observe: "response",
responseType: "blob",
headers: new HttpHeaders({
})
};
return this.http.request("delete", url_, options_).pipe(_observableMergeMap((response_ : any) => {
return this.processDelete(response_);
})).pipe(_observableCatch((response_: any) => {
if (response_ instanceof HttpResponseBase) {
try {
return this.processDelete(<any>response_);
} catch (e) {
return <Observable<void>><any>_observableThrow(e);
}
} else
return <Observable<void>><any>_observableThrow(response_);
}));
}
protected processDelete(response: HttpResponseBase): Observable<void> {
const status = response.status;
const responseBlob =
response instanceof HttpResponse ? response.body :
(<any>response).error instanceof Blob ? (<any>response).error : undefined;
let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }};
if (status === 200) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return _observableOf<void>(<any>null);
}));
} else if (status !== 200 && status !== 204) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
}));
}
return _observableOf<void>(<any>null);
}
}
@Injectable()
export class UseJsServiceProxy {
private http: HttpClient;
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
this.http = http;
this.baseUrl = baseUrl ? baseUrl : "";
}
/**
* @return Success
*/
get(): Observable<string> {
let url_ = this.baseUrl + "/api/UseJs/Get";
url_ = url_.replace(/[?&]$/, "");
let options_ : any = {
observe: "response",
responseType: "blob",
headers: new HttpHeaders({
"Accept": "application/json"
})
};
return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => {
return this.processGet(response_);
})).pipe(_observableCatch((response_: any) => {
if (response_ instanceof HttpResponseBase) {
try {
return this.processGet(<any>response_);
} catch (e) {
return <Observable<string>><any>_observableThrow(e);
}
} else
return <Observable<string>><any>_observableThrow(response_);
}));
}
protected processGet(response: HttpResponseBase): Observable<string> {
const status = response.status;
const responseBlob =
response instanceof HttpResponse ? response.body :
(<any>response).error instanceof Blob ? (<any>response).error : undefined;
let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }};
if (status === 200) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = resultData200 !== undefined ? resultData200 : <any>null;
return _observableOf(result200);
}));
} else if (status !== 200 && status !== 204) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
}));
}
return _observableOf<string>(<any>null);
}
}
@Injectable()
export class UserServiceProxy {
private http: HttpClient;
private baseUrl: string;
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
constructor(@Inject(HttpClient) http: HttpClient, @Optional() @Inject(API_BASE_URL) baseUrl?: string) {
this.http = http;
this.baseUrl = baseUrl ? baseUrl : "";
}
/**
* @return Success
*/
index(): Observable<void> {
let url_ = this.baseUrl + "/api/User/Index";
url_ = url_.replace(/[?&]$/, "");
let options_ : any = {
observe: "response",
responseType: "blob",
headers: new HttpHeaders({
})
};
return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => {
return this.processIndex(response_);
})).pipe(_observableCatch((response_: any) => {
if (response_ instanceof HttpResponseBase) {
try {
return this.processIndex(<any>response_);
} catch (e) {
return <Observable<void>><any>_observableThrow(e);
}
} else
return <Observable<void>><any>_observableThrow(response_);
}));
}
protected processIndex(response: HttpResponseBase): Observable<void> {
const status = response.status;
const responseBlob =
response instanceof HttpResponse ? response.body :
(<any>response).error instanceof Blob ? (<any>response).error : undefined;
let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }};
if (status === 200) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return _observableOf<void>(<any>null);
}));
} else if (status !== 200 && status !== 204) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
}));
}
return _observableOf<void>(<any>null);
}
}
export class MemberViewModel implements IMemberViewModel {
gender: MemberViewModelGender | undefined;
constructor(data?: IMemberViewModel) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(data?: any) {
if (data) {
this.gender = data["gender"];
}
}
static fromJS(data: any): MemberViewModel {
data = typeof data === 'object' ? data : {};
let result = new MemberViewModel();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["gender"] = this.gender;
return data;
}
clone(): MemberViewModel {
const json = this.toJSON();
let result = new MemberViewModel();
result.init(json);
return result;
}
}
export interface IMemberViewModel {
gender: MemberViewModelGender | undefined;
}
export class PersonViewModel implements IPersonViewModel {
gender: PersonViewModelGender | undefined;
constructor(data?: IPersonViewModel) {
if (data) {
for (var property in data) {
if (data.hasOwnProperty(property))
(<any>this)[property] = (<any>data)[property];
}
}
}
init(data?: any) {
if (data) {
this.gender = data["gender"];
}
}
static fromJS(data: any): PersonViewModel {
data = typeof data === 'object' ? data : {};
let result = new PersonViewModel();
result.init(data);
return result;
}
toJSON(data?: any) {
data = typeof data === 'object' ? data : {};
data["gender"] = this.gender;
return data;
}
clone(): PersonViewModel {
const json = this.toJSON();
let result = new PersonViewModel();
result.init(json);
return result;
}
}
export interface IPersonViewModel {
gender: PersonViewModelGender | undefined;
}
export enum MemberViewModelGender {
_1 = 1,
_2 = 2,
}
export enum PersonViewModelGender {
_1 = 1,
_2 = 2,
}
export class SwaggerException extends Error {
message: string;
status: number;
response: string;
headers: { [key: string]: any; };
result: any;
constructor(message: string, status: number, response: string, headers: { [key: string]: any; }, result: any) {
super();
this.message = message;
this.status = status;
this.response = response;
this.headers = headers;
this.result = result;
}
protected isSwaggerException = true;
static isSwaggerException(obj: any): obj is SwaggerException {
return obj.isSwaggerException === true;
}
}
function throwException(message: string, status: number, response: string, headers: { [key: string]: any; }, result?: any): Observable<any> {
if(result !== null && result !== undefined)
return _observableThrow(result);
else
return _observableThrow(new SwaggerException(message, status, response, headers, null));
}
function blobToText(blob: any): Observable<string> {
return new Observable<string>((observer: any) => {
if (!blob) {
observer.next("");
observer.complete();
} else {
let reader = new FileReader();
reader.onload = event => {
observer.next((<any>event.target).result);
observer.complete();
};
reader.readAsText(blob);
}
});
} | the_stack |
import { normalize, schema } from 'normalizr';
import type { Socket } from 'socket.io-client';
import { updateDataDocPolling } from 'redux/dataDoc/action';
import SocketIOManager from 'lib/socketio-manager';
import { queryEngineSelector } from 'redux/queryEngine/selector';
import {
QueryExecutionStatus,
IQueryExecutionViewer,
IQueryResultExporter,
IQueryExecution,
IStatementExecution,
IRawQueryExecution,
} from 'const/queryExecution';
import { IAccessRequest } from 'const/accessRequest';
import { queryCellExecutionManager } from 'lib/batch/query-execution-manager';
import {
QueryExecutionResource,
QueryExecutionAccessRequestResource,
QueryExecutionViewerResource,
StatementResource,
} from 'resource/queryExecution';
import {
IReceiveQueryExecutionsAction,
IReceiveQueryExecutionAction,
IReceiveStatementExecutionAction,
ThunkResult,
ThunkDispatch,
IReceiveStatementExecutionUpdateAction,
IReceiveQueryExecutionAccessRequestsAction,
IReceiveQueryExecutionViewersAction,
} from './types';
const statementExecutionSchema = new schema.Entity('statementExecution');
const dataCellSchema = new schema.Entity('dataCell');
const queryExecutionSchema = new schema.Entity('queryExecution', {
statement_executions: [statementExecutionSchema],
data_cell: dataCellSchema,
});
export const queryExecutionSchemaList = [queryExecutionSchema];
export function addQueryExecutionAccessRequest(
executionId: number
): ThunkResult<Promise<IAccessRequest>> {
return async (dispatch) => {
const { data } = await QueryExecutionAccessRequestResource.create(
executionId
);
if (data != null) {
dispatch({
type:
'@@queryExecutions/RECEIVE_QUERY_EXECUTION_ACCESS_REQUEST',
payload: {
executionId,
request: data,
},
});
}
return data;
};
}
export function rejectQueryExecutionAccessRequest(
executionId: number,
uid: number
): ThunkResult<Promise<void>> {
return async (dispatch, getState) => {
const accessRequest = (getState().queryExecutions
.accessRequestsByExecutionIdUserId[executionId] || {})[uid];
if (accessRequest) {
await QueryExecutionAccessRequestResource.delete(executionId, uid);
dispatch({
type: '@@queryExecutions/REMOVE_QUERY_EXECUTION_ACCESS_REQUEST',
payload: {
executionId,
uid,
},
});
}
};
}
export function addQueryExecutionViewer(
executionId: number,
uid: number
): ThunkResult<Promise<IQueryExecutionViewer>> {
return async (dispatch, getState) => {
const request = (getState().queryExecutions
.accessRequestsByExecutionIdUserId[executionId] || {})[uid];
const { data } = await QueryExecutionViewerResource.create(
executionId,
uid
);
if (request) {
dispatch({
type: '@@queryExecutions/REMOVE_QUERY_EXECUTION_ACCESS_REQUEST',
payload: {
executionId,
uid,
},
});
}
dispatch({
type: '@@queryExecutions/RECEIVE_QUERY_EXECUTION_VIEWER',
payload: {
executionId,
viewer: data,
},
});
return data;
};
}
export function deleteQueryExecutionViewer(
executionId: number,
uid: number
): ThunkResult<Promise<void>> {
return async (dispatch, getState) => {
const viewer = (getState().queryExecutions.viewersByExecutionIdUserId[
executionId
] || {})[uid];
if (viewer) {
await QueryExecutionViewerResource.delete(viewer.id);
dispatch({
type: '@@queryExecutions/REMOVE_QUERY_EXECUTION_VIEWER',
payload: {
executionId,
uid,
},
});
}
};
}
export function receiveQueryExecutionsByCell(
queryExecutions: IQueryExecution[],
dataCellId: number
): IReceiveQueryExecutionsAction {
const normalizedData = normalize(queryExecutions, queryExecutionSchemaList);
const {
queryExecution: queryExecutionById = {},
statementExecution: statementExecutionById = {},
} = normalizedData.entities;
return {
type: '@@queryExecutions/RECEIVE_QUERY_EXECUTIONS',
payload: {
queryExecutionById,
dataCellId,
statementExecutionById,
},
};
}
export function receiveQueryExecution(
queryExecution: IRawQueryExecution | IQueryExecution,
dataCellId?: number
): IReceiveQueryExecutionAction {
const normalizedData = normalize(queryExecution, queryExecutionSchema);
const {
queryExecution: queryExecutionById = {},
statementExecution: statementExecutionById = {},
} = normalizedData.entities;
return {
type: '@@queryExecutions/RECEIVE_QUERY_EXECUTION',
payload: {
queryExecutionById,
statementExecutionById,
dataCellId,
},
};
}
export function receiveQueryExecutionViewers(
executionId: number,
viewers: IQueryExecutionViewer[]
): IReceiveQueryExecutionViewersAction {
return {
type: '@@queryExecutions/RECEIVE_QUERY_EXECUTION_VIEWERS',
payload: {
executionId,
viewers,
},
};
}
export function receiveQueryExecutionAccessRequests(
executionId: number,
requests: IAccessRequest[]
): IReceiveQueryExecutionAccessRequestsAction {
return {
type: '@@queryExecutions/RECEIVE_QUERY_EXECUTION_ACCESS_REQUESTS',
payload: {
executionId,
requests,
},
};
}
function receiveStatementExecution(
statementExecution
): IReceiveStatementExecutionAction {
return {
type: '@@queryExecutions/RECEIVE_STATEMENT_EXECUTION',
payload: {
statementExecution,
},
};
}
function receiveStatementExecutionUpdate(
statementExecution: IStatementExecution
): IReceiveStatementExecutionUpdateAction {
return {
type: '@@queryExecutions/RECEIVE_STATEMENT_EXECUTION_UPDATE',
payload: {
statementExecution,
},
};
}
export function fetchQueryExecutionsByCell(
dataCellId: number
): ThunkResult<Promise<void>> {
return async (dispatch, getState) => {
const state = getState();
if (dataCellId in state.queryExecutions.dataCellIdQueryExecution) {
return;
}
return queryCellExecutionManager.loadExecutionForCell(
dataCellId,
dispatch
);
};
}
export function fetchDataDocInfoByQueryExecutionId(
executionId: number
): ThunkResult<
Promise<{
doc_id: number;
cell_id: number;
cell_title: string;
}>
> {
return async (dispatch) => {
const { data: result } = await QueryExecutionResource.getDataDoc(
executionId
);
dispatch({
type: '@@queryExecutions/RECEIVE_QUERY_CELL_ID_FROM_EXECUTION',
payload: {
executionId,
cellId: result.cell_id,
},
});
return result;
};
}
export function fetchQueryExecutionIfNeeded(
queryExecutionId: number
): ThunkResult<Promise<any>> {
return async (dispatch, getState) => {
const state = getState();
const queryExecution =
state.queryExecutions.queryExecutionById[queryExecutionId];
if (!queryExecution || !queryExecution.statement_executions) {
return dispatch(fetchQueryExecution(queryExecutionId));
}
};
}
function fetchQueryExecution(
queryExecutionId: number
): ThunkResult<Promise<IQueryExecution>> {
return async (dispatch) => {
const { data: execution } = await QueryExecutionResource.get(
queryExecutionId
);
dispatch(receiveQueryExecution(execution));
return execution;
};
}
export function fetchQueryExecutionAccessRequests(
queryExecutionId: number
): ThunkResult<Promise<void>> {
return async (dispatch) => {
const {
data: queryExecutionAccessRequests,
} = await QueryExecutionAccessRequestResource.get(queryExecutionId);
dispatch(
receiveQueryExecutionAccessRequests(
queryExecutionId,
queryExecutionAccessRequests
)
);
};
}
export function fetchQueryExecutionViewers(
queryExecutionId: number
): ThunkResult<Promise<void>> {
return async (dispatch) => {
const {
data: queryExecutionViewers,
} = await QueryExecutionViewerResource.get(queryExecutionId);
dispatch(
receiveQueryExecutionViewers(
queryExecutionId,
queryExecutionViewers
)
);
};
}
export function fetchActiveQueryExecutionForUser(
uid: number
): ThunkResult<Promise<IQueryExecution[]>> {
return async (dispatch, getState) => {
const { data: queryExecutions } = await QueryExecutionResource.search(
uid,
getState().environment.currentEnvironmentId
);
const normalizedData = normalize(
queryExecutions,
queryExecutionSchemaList
);
const {
queryExecution: queryExecutionById = {},
statementExecution: statementExecutionById = {},
} = normalizedData.entities;
dispatch({
type: '@@queryExecutions/RECEIVE_QUERY_EXECUTIONS',
payload: {
queryExecutionById,
statementExecutionById,
},
});
return queryExecutions;
};
}
export function pollQueryExecution(
queryExecutionId: number,
docId?: number
): ThunkResult<Promise<void>> {
return async (dispatch) => {
await queryExecutionSocket.addQueryExecution(
queryExecutionId,
docId,
dispatch
);
};
}
export function createQueryExecution(
query: string,
engineId?: number,
cellId?: number
): ThunkResult<Promise<IQueryExecution>> {
return async (dispatch, getState) => {
const state = getState();
const selectedEngineId = engineId ?? queryEngineSelector(state)[0].id;
const { data: queryExecution } = await QueryExecutionResource.create(
query,
selectedEngineId,
cellId
);
dispatch(receiveQueryExecution(queryExecution, cellId));
return queryExecution;
};
}
export function fetchExporters(): ThunkResult<Promise<IQueryResultExporter[]>> {
return async (dispatch) => {
const { data: exporters } = await StatementResource.getExporters();
dispatch({
type: '@@queryExecutions/RECEIVE_QUERY_RESULT_EXPORTERS',
payload: {
exporters,
},
});
return exporters;
};
}
export function fetchResult(
statementExecutionId: number
): ThunkResult<Promise<string[][]>> {
return async (dispatch, getState) => {
const state = getState();
const statementExecution =
state.queryExecutions.statementExecutionById[statementExecutionId];
if (statementExecution) {
const { id, result_row_count: resultRowCount } = statementExecution;
const statementResult =
state.queryExecutions.statementResultById[statementExecutionId];
if (resultRowCount > 0 && !statementResult) {
try {
const { data } = await StatementResource.getResult(id);
dispatch({
type: '@@queryExecutions/RECEIVE_RESULT',
payload: {
statementExecutionId,
data,
},
});
return data;
} catch (error) {
dispatch({
type: '@@queryExecutions/RECEIVE_RESULT',
payload: {
statementExecutionId,
failed: true,
error: JSON.stringify(error, null, 2),
},
});
}
} else if (statementResult) {
return statementResult.data;
}
}
};
}
export function fetchLog(
statementExecutionId: number
): ThunkResult<Promise<void>> {
return async (dispatch, getState) => {
const state = getState();
const statementExecution =
state.queryExecutions.statementExecutionById[statementExecutionId];
if (statementExecution) {
const { id, has_log: hasLog } = statementExecution;
const statementLog =
state.queryExecutions.statementLogById[statementExecutionId];
if (hasLog && (!statementLog || statementLog.isPartialLog)) {
try {
const { data } = await StatementResource.getLogs(id);
dispatch({
type: '@@queryExecutions/RECEIVE_LOG',
payload: {
statementExecutionId,
data,
},
});
} catch (error) {
dispatch({
type: '@@queryExecutions/RECEIVE_LOG',
payload: {
statementExecutionId,
failed: true,
error: JSON.stringify(error, null, 2),
},
});
}
}
}
};
}
export function fetchQueryError(
queryExecutionId: number
): ThunkResult<Promise<void>> {
return async (dispatch, getState) => {
const state = getState();
const queryExecution =
state.queryExecutions.queryExecutionById[queryExecutionId];
if (queryExecution) {
const { id, status } = queryExecution;
const queryError =
state.queryExecutions.queryErrorById[queryExecutionId];
if (status === QueryExecutionStatus.ERROR && !queryError) {
try {
const { data } = await QueryExecutionResource.getError(id);
dispatch({
type: '@@queryExecutions/RECEIVE_QUERY_ERROR',
payload: {
queryExecutionId,
queryError: data,
},
});
} catch (error) {
dispatch({
type: '@@queryExecutions/RECEIVE_QUERY_ERROR',
payload: {
queryExecutionId,
failed: true,
error: JSON.stringify(error, null, 2),
},
});
}
}
}
};
}
class QueryExecutionSocket {
private static NAME_SPACE = '/query_execution';
// queryExecutionId => docId
private activeQueryExecutions: Record<number, number> = {};
private socket: Socket = null;
private socketPromise: Promise<Socket> = null;
private dispatch: ThunkDispatch = null;
public addQueryExecution = async (
queryExecutionId: number,
docId: number,
dispatch: ThunkDispatch
) => {
this.dispatch = dispatch;
if (!(queryExecutionId in this.activeQueryExecutions)) {
if (docId != null) {
this.dispatch(
updateDataDocPolling(docId, queryExecutionId, true)
);
}
await this.setupSocket();
this.activeQueryExecutions[queryExecutionId] = docId;
this.socket.emit('subscribe', queryExecutionId);
}
};
public onSocketConnect(socket: Socket) {
// Setup rooms for existing connections
const activeQueryExecutionIds = Object.keys(this.activeQueryExecutions);
if (activeQueryExecutionIds.length > 0) {
activeQueryExecutionIds.map((queryExecutionId) => {
socket.emit('subscribe', Number(queryExecutionId));
});
}
}
public removeAllQueryExecution = () => {
for (const queryExecutionId of Object.values(
this.activeQueryExecutions
)) {
this.removeQueryExecution(queryExecutionId);
}
};
public removeQueryExecution = (queryExecutionId: number) => {
if (queryExecutionId in this.activeQueryExecutions) {
// Otherwise its NOOP
const docId = this.activeQueryExecutions[queryExecutionId];
delete this.activeQueryExecutions[queryExecutionId];
if (docId != null) {
// Update the data doc that is pulling
this.dispatch(
updateDataDocPolling(docId, queryExecutionId, false)
);
}
// Leave the socket room
this.socket.emit('unsubscribe', queryExecutionId);
// If we are not running any query any more, break off the socketio connection
if (Object.keys(this.activeQueryExecutions).length === 0) {
SocketIOManager.removeSocket(this.socket);
this.socket = null;
this.socketPromise = null;
}
}
};
private processQueryExecution = (queryExecution: IQueryExecution) => {
this.dispatch(receiveQueryExecution(queryExecution));
if (queryExecution.status >= 3) {
this.removeQueryExecution(queryExecution.id);
}
};
private setupSocket = async () => {
if (this.socketPromise) {
await this.socketPromise;
} else {
// We need to setup our socket
this.socketPromise = SocketIOManager.getSocket(
QueryExecutionSocket.NAME_SPACE,
this.onSocketConnect.bind(this)
);
// Setup socket's connection functions
this.socket = await this.socketPromise;
this.socket.on('query', (queryExecution: IQueryExecution) => {
this.processQueryExecution(queryExecution);
});
this.socket.on('query_start', (queryExecution: IQueryExecution) => {
this.processQueryExecution(queryExecution);
});
this.socket.on('query_end', (queryExecution: IQueryExecution) => {
this.processQueryExecution(queryExecution);
});
this.socket.on(
'statement_start',
(statementExecution: IStatementExecution) => {
this.dispatch(
receiveStatementExecution(statementExecution)
);
}
);
this.socket.on(
'statement_update',
(statementExecution: IStatementExecution) => {
this.dispatch(
receiveStatementExecutionUpdate(statementExecution)
);
}
);
this.socket.on(
'statement_end',
(statementExecution: IStatementExecution) => {
this.dispatch(
receiveStatementExecution(statementExecution)
);
}
);
this.socket.on(
'query_cancel',
(queryExecution: IQueryExecution) => {
this.processQueryExecution(queryExecution);
}
);
this.socket.on(
'query_exception',
(queryExecution: IQueryExecution) => {
this.processQueryExecution(queryExecution);
}
);
return this.socket;
}
};
}
export const queryExecutionSocket = new QueryExecutionSocket(); | the_stack |
import {
AscReqFlag,
IscReqFlag,
AscRetFlag,
ExtendedNameFormatFlag,
AccessTokenFlag,
TargetDataRepMapFlag,
CredentialUseFlag,
} from './flags';
import { AccessToken, TokenPrivileges } from './user';
export interface Props {
[key: string]: unknown;
}
export type SecuritySupportProvider = 'NTLM' | 'Kerberos' | 'Negotiate';
/**
* SecPkgInfo is the interface returned by EnumerateSecurityPackages and QuerySecurityPackageInfo
* for having info about SSP providers.
*
* When doing SSO, you need to use a SSP provider (ex: Negotiate SSP provider).
*
* @interface SecPkgInfo
*/
interface SecPkgInfo {
fCapabilities: number;
wVersion: number;
wRPCID: number;
cbMaxToken: number;
Name: SecuritySupportProvider;
Comment: string;
}
/**
* Context Handle
*
* A context handle is created with InitializeSecurityContext and AcceptSecurityContext
* function while establishing secure authentication.
* It is useful to use ImpersonateSecurityContext function
*
* @interface CtxtHandle
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface CtxtHandle {}
/**
* CredHandle is returned by AcquireCredentialsHandle.
*
* It is needed for using InitializeSecurityContext and AcceptSecurityContext.
* It represents the credential of a client or server user.
*
* @interface CredHandle
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface CredHandle {}
/**
* A HANDLE representing something. Technically it is a pointer reference on something.
*
* @interface HANDLE
*/
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface HANDLE {}
/**
* A pointer to an Sid (to be freed).
*
* @type SidPointer
*/
export type SidPointer = string;
export type InformationClass = 'TokenGroups' | 'TokenPrivileges';
/**
* Credential with expiry date.
*
* @interface CredentialWithExpiry
*/
export interface CredentialWithExpiry {
credential: CredHandle;
tsExpiry: Date;
}
/**
* A security context is the common output of InitializeSecurityContext and AcceptSecurityContext.
* It contains the security buffers exchanged between the client and the server.
*
* @interface SecurityContext
*/
export interface SecurityContext {
readonly contextHandle: CtxtHandle;
readonly SECURITY_STATUS: SecurityStatus;
readonly SecBufferDesc: SecBufferDesc;
}
export type SecurityStatus =
| 'SEC_E_OK'
| 'SEC_I_COMPLETE_AND_CONTINUE'
| 'SEC_I_COMPLETE_NEEDED'
| 'SEC_I_CONTINUE_NEEDED';
/**
* Same as Microsoft SecBufferDesc: The SecBufferDesc structure describes
* an array of SecBuffer structures to pass from a transport application
* to a security package.
*
* @export
* @interface SecBufferDesc
*/
export interface SecBufferDesc {
ulVersion: number;
buffers: ArrayBuffer[];
}
/**
* ServerSecurityContext is the SecurityContext, specific to the server.
* It is the output of AcceptSecurityContext, and used in the input of InitializeSecurityContext.
* When the server want to send to the client authentication token input, this is done with this interface.
*
* @interface ServerSecurityContext
* @extends {SecurityContext}
*/
export interface ServerSecurityContext {
readonly SECURITY_STATUS: string;
readonly contextHandle: CtxtHandle;
readonly contextAttr: AscRetFlag[];
readonly SecBufferDesc: SecBufferDesc;
}
/**
* Wrapper containing a Microsoft windows domain name and a user sid.
* sid = security id.
*
* @interface SidObject
*/
export interface SidObject {
sid: string;
domain: string;
}
/**
* This is just a container for user login/password/domain.
*
* The domain is a Windows domain, or a computer name.
*
* @interface UserCredential
*/
export interface UserCredential {
user: string;
password: string;
domain: string;
}
/**
* Input of InitializeSecurityContext function.
*
* @interface InitializeSecurityContextInput
*/
export interface InitializeSecurityContextInput {
credential: CredHandle;
targetName: string;
cbMaxToken?: number;
SecBufferDesc?: SecBufferDesc;
contextHandle?: CtxtHandle;
contextReq?: IscReqFlag[];
targetDataRep?: TargetDataRepMapFlag;
isFirstCall?: boolean;
}
/**
* Input of function AcquireCredentialsHandle
*
* @export
* @interface AcquireCredHandleInput
*/
export interface AcquireCredHandleInput {
packageName: SecuritySupportProvider;
authData?: UserCredential;
credentialUse?: CredentialUseFlag;
}
/**
* Input of AcceptSecurityContext function.
*
* @interface AcceptSecurityContextInput
*/
export interface AcceptSecurityContextInput {
credential: CredHandle;
SecBufferDesc?: SecBufferDesc;
contextHandle?: CtxtHandle;
contextReq?: AscReqFlag[];
targetDataRep?: TargetDataRepMapFlag;
}
export interface GetTokenInformationInput {
accessToken: AccessToken;
tokenInformationClass: InformationClass;
filter?: string;
}
export type Groups = string[];
export interface Sspi {
/**
* Just a hello world function. Useless... ;)
*
* @returns {string}
* @memberof Sspi
*/
hello(): string;
/**
* EnumerateSecurityPackages get a list of SSP provider with some info.
*
* @returns {SecPkgInfo[]}
* @memberof Sspi
*/
EnumerateSecurityPackages(): SecPkgInfo[];
/**
* Get info about one SSP provider given its name.
*
* @param {SecuritySupportProvider} packageName
* @returns {SecPkgInfo}
* @memberof Sspi
*/
QuerySecurityPackageInfo(packageName: SecuritySupportProvider): SecPkgInfo;
/**
* Get the credentials of a user, to be used with a specified SSP package.
* The credentials will be used according the specified flags.
*
* FreeCredentialsHandle must be used to free the credentials pointer.
*
*
* @param {AcquireCredHandleInput} input
* @returns {CredentialWithExpiry}
* @memberof Sspi
*/
AcquireCredentialsHandle(input: AcquireCredHandleInput): CredentialWithExpiry;
/**
* This function must be used only by a client. Its purpose is to setup a client/server security context.
*
* @param {InitializeSecurityContextInput} input
* @returns {SecurityContext}
* @memberof Sspi
*/
InitializeSecurityContext(
input: InitializeSecurityContextInput
): SecurityContext;
/**
* AcceptSecurityContext must be used only on server side. Its purpose is to setup a client/server security context
*
* @param {AcceptSecurityContextInput} input
* @returns {ServerSecurityContext}
* @memberof Sspi
*/
AcceptSecurityContext(
input: AcceptSecurityContextInput
): ServerSecurityContext;
/**
* Free a allocated credential memory. Must be used after AcquireCredentialsHandle.
*
* @param {CredHandle} credential
* @memberof Sspi
*/
FreeCredentialsHandle(credential: CredHandle): void;
/**
* Must be used only on server side.
*
* Change the server user temporarely with the client user.
* Allocated resource must be freed with RevertSecurityContext.
*
* @param {CtxtHandle} handle
* @memberof Sspi
*/
ImpersonateSecurityContext(handle: CtxtHandle): void;
/**
* Revert the server user back to its original. Must be used with ImpersonateSecurityContext.
*
* @param {CtxtHandle} handle
* @memberof Sspi
*/
RevertSecurityContext(handle: CtxtHandle): void;
/**
* Get the username of the current thread. (TODO: to be moved outside of SSPI)
*
* @returns {string}
* @memberof Sspi
*/
GetUserName(): string;
/**
* Get the username and much more of the current thread.
*
* @param {ExtendedNameFormatFlag} extendedNameFormat
* @returns {string}
* @memberof Sspi
*/
GetUserNameEx(extendedNameFormat: ExtendedNameFormatFlag): string;
/**
* Get the user token associated with the current thread. Used with ImpersonateSecurityContext.
*
* Token must be freed with CloseHandle.
*
* @param {AccessTokenFlag[]} [flags]
* @returns {AccessToken}
* @memberof Sspi
*/
OpenThreadToken(flags?: AccessTokenFlag[]): AccessToken;
/**
* Get the user token associated with the current process. You will get always
* the user that has started the process, and never the impersonated user.
*
* CloseHandle must be used for freeing the token.
*
* @param {AccessTokenFlag[]} [flags]
* @returns {AccessToken}
* @memberof Sspi
*/
OpenProcessToken(flags?: AccessTokenFlag[]): AccessToken;
/**
* Allocate an sid. Limitations: get only the NtAuthority sid
* (for admin check use case)
*
* Note: the sid returned must be freed with `FreeSid()`.
*
* @returns {SidPointer}
* @memberof Sspi
*/
AllocateAndInitializeSid(): SidPointer;
/**
* check if the sid belongs to the user thread/process token.
*
* @param {SidPointer} sid
* @returns {boolean}
* @memberof Sspi
*/
CheckTokenMembership(sid: SidPointer): boolean;
/**
* Free the given sid.
*
* Warning: this function may crash the system if not used with a good sid.
*
* @param {SidPointer} sid
* @memberof Sspi
*/
FreeSid(sid: SidPointer): void;
/**
* Get information from a user token.
*
* @param {Token} token
* @param {InformationClass} infoClass
* @returns {string[]}
* @memberof Sspi
*/
GetTokenInformation(
input: GetTokenInformationInput
): Groups | TokenPrivileges;
/**
* Free allocated memory referenced by the handle.
*
* @param {HANDLE} handle
* @memberof Sspi
*/
CloseHandle(handle: HANDLE): void;
/**
* Get the SID of username.
*
* @param {string} username
* @returns {SidObject}
* @memberof Sspi
*/
LookupAccountName(username: string): SidObject;
/**
* Query what can be done with a given credential.
*
* @param {CredHandle} credential
* @param {string} attribute
* @returns {*}
* @memberof Sspi
*/
QueryCredentialsAttributes(credential: CredHandle, attribute: string): Props;
/**
* Query what can be done with a given context handle.
*
* @param {CtxtHandle} ctxtHandle
* @param {string} attribute
* @returns {*}
* @memberof Sspi
*/
QueryContextAttributes(ctxtHandle: CtxtHandle, attribute: string): Props;
/**
* Get a client user token.
*
* @param {CtxtHandle} ctxtHandle
* @returns {AccessToken}
* @memberof Sspi
*/
QuerySecurityContextToken(ctxtHandle: CtxtHandle): AccessToken;
/**
* Free a context handle.
*
* @param {CtxtHandle} ctxtHandle
* @memberof Sspi
*/
DeleteSecurityContext(ctxtHandle: CtxtHandle): void;
} | the_stack |
import { config } from "config";
import request from "helpers/request";
import { Publisher } from "helpers/record";
import { RawDataset } from "helpers/record";
import ServerError from "./ServerError";
import flatMap from "lodash/flatMap";
import partialRight from "lodash/partialRight";
import dcatDatasetStringsAspect from "@magda/registry-aspects/dcat-dataset-strings.schema.json";
import spatialCoverageAspect from "@magda/registry-aspects/spatial-coverage.schema.json";
import temporalCoverageAspect from "@magda/registry-aspects/temporal-coverage.schema.json";
import datasetDistributionsAspect from "@magda/registry-aspects/dataset-distributions.schema.json";
import dcatDistributionStringsAspect from "@magda/registry-aspects/dcat-distribution-strings.schema.json";
import accessAspect from "@magda/registry-aspects/access.schema.json";
import provenanceAspect from "@magda/registry-aspects/provenance.schema.json";
import informationSecurityAspect from "@magda/registry-aspects/information-security.schema.json";
import datasetPublisherAspect from "@magda/registry-aspects/dataset-publisher.schema.json";
import currencyAspect from "@magda/registry-aspects/currency.schema.json";
import datasetPublishingAspect from "@magda/registry-aspects/publishing.schema.json";
import datasetAccessControlAspect from "@magda/registry-aspects/dataset-access-control.schema.json";
import organizationDetailsAspect from "@magda/registry-aspects/organization-details.schema.json";
import sourceAspect from "@magda/registry-aspects/source.schema.json";
import datasetDraftAspect from "@magda/registry-aspects/dataset-draft.schema.json";
import ckanExportAspect from "@magda/registry-aspects/ckan-export.schema.json";
import versionAspect from "@magda/registry-aspects/version.schema.json";
import createNoCacheFetchOptions from "./createNoCacheFetchOptions";
import formUrlencode from "./formUrlencode";
export const aspectSchemas = {
publishing: datasetPublishingAspect,
"dcat-dataset-strings": dcatDatasetStringsAspect,
"spatial-coverage": spatialCoverageAspect,
"temporal-coverage": temporalCoverageAspect,
"dataset-distributions": datasetDistributionsAspect,
"dcat-distribution-strings": dcatDistributionStringsAspect,
access: accessAspect,
provenance: provenanceAspect,
"information-security": informationSecurityAspect,
"dataset-access-control": datasetAccessControlAspect,
"dataset-publisher": datasetPublisherAspect,
"organization-details": organizationDetailsAspect,
currency: currencyAspect,
source: sourceAspect,
"dataset-draft": datasetDraftAspect,
"ckan-export": ckanExportAspect,
version: versionAspect
};
export type VersionItem = {
versionNumber: number;
createTime: string;
creatorId?: string;
description: string;
title: string;
internalDataFileUrl?: string;
eventId?: number;
};
export type CurrencyData = {
status: "CURRENT" | "SUPERSEDED" | "RETIRED";
retireReason?: string;
supersededBy?: {
id?: string[];
name?: string;
}[];
};
export type VersionAspectData = {
currentVersionNumber: number;
versions: VersionItem[];
};
export const getEventIdFromHeaders = (headers: Headers): number => {
const headerVal = headers.get("x-magda-event-id");
if (headerVal === null) {
return 0;
} else {
const eventId = parseInt(headerVal);
if (isNaN(eventId)) {
return 0;
} else {
return eventId;
}
}
};
export const getInitialVersionAspectData = (
title: string,
creatorId?: string,
internalDataFileUrl?: string
) => ({
currentVersionNumber: 0,
versions: [
{
versionNumber: 0,
createTime: new Date().toISOString(),
creatorId,
description: "initial version",
title,
...(internalDataFileUrl ? { internalDataFileUrl } : {})
}
]
});
export type DatasetTypes = "drafts" | "published";
export async function createPublisher(inputRecord: Publisher) {
return await createRecord(inputRecord);
}
export function fetchOrganization(
publisherId: string,
noCache: boolean = false
): Promise<Publisher> {
let url: string =
config.registryReadOnlyApiUrl +
`records/${encodeURIComponent(
publisherId
)}?aspect=organization-details`;
return fetch(
url,
noCache
? createNoCacheFetchOptions(config.credentialsFetchOptions)
: config.credentialsFetchOptions
).then((response) => {
if (!response.ok) {
let statusText = response.statusText;
// response.statusText are different in different browser, therefore we unify them here
if (response.status === 404) {
statusText = "Not Found";
}
throw Error(statusText);
}
return response.json();
});
}
/**
* Store aspect json schema saving action promise.
* Used by `ensureAspectExists` to make sure only save the aspect once within current session.
*/
const aspectJsonSchemaSavingCache: {
[key: string]: Promise<any>;
} = {};
/**
* Ensure aspect exists in registry by storing the aspect def to registry.
* Here we are not going to skip storing the aspect def if the aspect def already exisits as we do know whether it's an up-to-date one in registry.
* For now, we only make sure the aspect def won't be stored to registry for multiple times.
* @param id
* @param jsonSchema
*/
export async function ensureAspectExists(id: string, jsonSchema?: any) {
if (!jsonSchema) {
jsonSchema = aspectSchemas[id];
}
if (!jsonSchema) {
throw new Error(`Cannot locate json schema for ${id}`);
}
if (!aspectJsonSchemaSavingCache[id]) {
aspectJsonSchemaSavingCache[id] = request(
"PUT",
`${config.registryFullApiUrl}aspects/${id}`,
{
id,
name: jsonSchema.title,
jsonSchema
}
);
}
await aspectJsonSchemaSavingCache[id];
}
// --- See registry API document for API [Get a list of all records](https://dev.magda.io/api/v0/apidocs/index.html#api-Registry_Record_Service-GetV0RegistryRecords) for more details
export enum AspectQueryOperators {
"=" = ":", // --- equal
"!=" = ":!", // --- Not equal
patternMatch = ":?", // --- pattern matching. Support Regex Expression as well.
patternNotMatch = ":!?",
">" = ":>",
"<" = ":<",
">=" = ":>=",
"<=" = ":<="
}
export class AspectQuery {
public path: string;
public operator: AspectQueryOperators;
public value: string | number | boolean;
// --- when `true`, all aspectQuery will be grouped with `AND` operator, otherwise, will be `OR`
public isAndQuery: boolean = true;
constructor(
path: string,
operator: AspectQueryOperators,
value: string | number | boolean,
isAndQuery?: boolean
) {
this.path = path;
this.operator = operator;
this.value = value;
if (typeof isAndQuery === "boolean") {
this.isAndQuery = isAndQuery;
}
}
/**
* We use URLDecode.decode to decode query string value.
* To make sure `application/x-www-form-urlencoded` encoded string reach aspectQuery parser
* This ensures `%` is encoded as `%2525` in the final url string
*
* @param {string} str
* @returns
* @memberof AspectQuery
*/
encodeAspectQueryComponent(str: string) {
return encodeURIComponent(formUrlencode(str));
}
toString() {
return `${this.encodeAspectQueryComponent(this.path)}${
this.operator
}${this.encodeAspectQueryComponent(String(this.value))}`;
}
}
export const DEFAULT_OPTIONAL_FETCH_ASPECT_LIST = [
"dcat-distribution-strings",
"dataset-distributions",
"temporal-coverage",
"usage",
"access",
"dataset-publisher",
"source",
"source-link-status",
"dataset-quality-rating",
"spatial-coverage",
"publishing",
"dataset-access-control",
"provenance",
"information-security",
"currency",
"ckan-export",
"version"
];
export const DEFAULT_COMPULSORY_FETCH_ASPECT_LIST = ["dcat-dataset-strings"];
export async function fetchRecord<T = RawDataset>(
id: string,
optionalAspects: string[] = DEFAULT_OPTIONAL_FETCH_ASPECT_LIST,
aspects: string[] = DEFAULT_COMPULSORY_FETCH_ASPECT_LIST,
dereference: boolean = true,
noCache: boolean = false
): Promise<T> {
const parameters: string[] = [];
if (dereference) {
parameters.push("dereference=true");
}
if (aspects?.length) {
parameters.push(aspects.map((item) => `aspect=${item}`).join("&"));
}
if (optionalAspects?.length) {
parameters.push(
optionalAspects.map((item) => `optionalAspect=${item}`).join("&")
);
}
const url =
config.registryReadOnlyApiUrl +
`records/${encodeURIComponent(id)}${
parameters.length ? `?${parameters.join("&")}` : ""
}`;
const response = await fetch(
url,
noCache
? createNoCacheFetchOptions(config.credentialsFetchOptions)
: config.credentialsFetchOptions
);
if (!response.ok) {
let statusText = response.statusText;
// response.statusText are different in different browser, therefore we unify them here
if (response.status === 404) {
statusText = "Not Found";
}
throw new ServerError(statusText, response.status);
}
const data = await response.json();
if (data.records) {
if (data.records.length > 0) {
return data.records[0];
} else {
throw new ServerError("Not Found", 404);
}
} else {
return data;
}
}
export async function fetchHistoricalRecord<T = RawDataset>(
id: string,
eventId: number,
noCache: boolean = false
): Promise<T> {
if (typeof eventId !== "number") {
throw new Error("eventId parameter needs to be a number.");
}
const url =
config.registryReadOnlyApiUrl +
`records/${encodeURIComponent(id)}/history/${eventId}`;
const response = await fetch(
url,
noCache
? createNoCacheFetchOptions(config.credentialsFetchOptions)
: config.credentialsFetchOptions
);
if (!response.ok) {
let statusText = response.statusText;
// response.statusText are different in different browser, therefore we unify them here
if (response.status === 404) {
statusText = "Not Found";
}
throw new ServerError(statusText, response.status);
}
return await response.json();
}
export const fetchRecordWithNoCache = partialRight(fetchRecord, true);
export type FetchRecordsOptions = {
aspects?: string[];
optionalAspects?: string[];
pageToken?: string;
start?: number;
limit?: number;
dereference?: boolean;
aspectQueries?: AspectQuery[];
orderBy?: string;
orderByDirection?: "asc" | "desc";
noCache?: boolean;
};
export async function fetchRecords({
aspects,
optionalAspects,
pageToken,
start,
limit,
dereference,
aspectQueries,
orderBy,
orderByDirection,
noCache
}: FetchRecordsOptions): Promise<{
records: RawDataset[];
hasMore: boolean;
nextPageToken?: string;
}> {
const parameters: string[] = [];
if (dereference) {
parameters.push("dereference=true");
}
if (aspects?.length) {
parameters.push(aspects.map((item) => `aspect=${item}`).join("&"));
}
if (optionalAspects?.length) {
parameters.push(
optionalAspects.map((item) => `optionalAspect=${item}`).join("&")
);
}
if (aspectQueries?.length) {
parameters.push(
aspectQueries
.map(
(item) =>
`${
item.isAndQuery ? "aspectQuery" : "aspectOrQuery"
}=${item.toString()}`
)
.join("&")
);
}
if (pageToken) {
parameters.push(`pageToken=${encodeURIComponent(pageToken)}`);
}
if (start) {
parameters.push(`start=${encodeURIComponent(start)}`);
}
if (limit) {
parameters.push(`limit=${encodeURIComponent(limit)}`);
}
if (orderBy) {
parameters.push(`orderBy=${encodeURIComponent(orderBy)}`);
if (orderByDirection) {
parameters.push(
`orderByDir=${encodeURIComponent(orderByDirection)}`
);
}
}
const url =
config.registryReadOnlyApiUrl +
`records${parameters.length ? `?${parameters.join("&")}` : ""}`;
const response = await fetch(
url,
noCache
? createNoCacheFetchOptions(config.credentialsFetchOptions)
: config.credentialsFetchOptions
);
if (!response.ok) {
throw new ServerError(response.statusText, response.status);
}
const data = await response.json();
if (data?.records?.length > 0) {
return {
records: data.records,
hasMore: data.hasMore,
nextPageToken: data.nextPageToken
};
} else {
return {
records: [],
hasMore: false,
nextPageToken: ""
};
}
}
export type FetchRecordsCountOptions = {
aspectQueries?: AspectQuery[];
aspects?: string[];
noCache?: boolean;
};
export async function fetchRecordsCount({
aspectQueries,
aspects,
noCache
}: FetchRecordsCountOptions): Promise<number> {
const parameters: string[] = [];
if (aspects?.length) {
parameters.push(aspects.map((item) => `aspect=${item}`).join("&"));
}
if (aspectQueries?.length) {
parameters.push(
aspectQueries
.map(
(item) =>
`${
item.isAndQuery ? "aspectQuery" : "aspectOrQuery"
}=${item.toString()}`
)
.join("&")
);
}
const url =
config.registryReadOnlyApiUrl +
`records/count${parameters.length ? `?${parameters.join("&")}` : ""}`;
const response = await fetch(
url,
noCache
? createNoCacheFetchOptions(config.credentialsFetchOptions)
: config.credentialsFetchOptions
);
if (!response.ok) {
throw new ServerError(response.statusText, response.status);
}
const data = await response.json();
if (typeof data?.count === "number") {
return data.count;
} else {
throw new Error(`Invalid response: ${await response.text()}`);
}
}
export async function deleteRecordAspect(
recordId: string,
aspectId: string
): Promise<[boolean, number]> {
const [res, headers] = await request<{ deleted: boolean }>(
"DELETE",
`${config.registryFullApiUrl}records/${recordId}/aspects/${aspectId}`,
undefined,
undefined,
true
);
return [res.deleted, getEventIdFromHeaders(headers)];
}
export async function deleteRecord(
recordId: string
): Promise<[boolean, number]> {
const [res, headers] = await request<{ deleted: boolean }>(
"DELETE",
`${config.registryFullApiUrl}records/${recordId}`,
undefined,
undefined,
true
);
return [res.deleted, getEventIdFromHeaders(headers)];
}
export async function doesRecordExist(id: string) {
try {
//--- we turned off cache with last `true` parameter here
await fetchRecordWithNoCache(id, [], [], false);
return true;
} catch (e) {
if (e.statusCode === 404) {
return false;
}
throw e;
}
}
export type Record = {
id: string;
name: string;
authnReadPolicyId?: string;
aspects: { [aspectId: string]: any };
};
async function createRecord(inputRecord: Record): Promise<[Record, number]> {
const [res, headers] = await request<Record>(
"POST",
`${config.registryFullApiUrl}records`,
inputRecord,
"application/json",
true
);
return [res, getEventIdFromHeaders(headers)];
}
export type JsonSchema = {
$schema?: string;
title?: string;
description?: string;
type: string;
[k: string]: any;
};
function getAspectIds(record: Record): string[] {
if (!record.aspects) {
return [];
}
return Object.keys(record.aspects);
}
function getRecordsAspectIds(records: Record[]): string[] {
return flatMap(records.map((item) => getAspectIds(item)));
}
export async function createDataset(
inputDataset: Record,
inputDistributions: Record[],
tagDistributionVersion: boolean = false
): Promise<[Record, number]> {
// make sure all the aspects exist (this should be improved at some point, but will do for now)
const aspectPromises = getRecordsAspectIds(
[inputDataset].concat(inputDistributions)
).map((aspectId) => ensureAspectExists(aspectId));
await Promise.all(aspectPromises);
for (const distribution of inputDistributions) {
const [distRecord, headers] = await request<Record>(
"POST",
`${config.registryFullApiUrl}records`,
distribution,
"application/json",
true
);
if (tagDistributionVersion) {
await tagRecordVersionEventId(
distRecord,
getEventIdFromHeaders(headers)
);
}
}
const [json, headers] = await request<Record>(
"POST",
`${config.registryFullApiUrl}records`,
inputDataset,
"application/json",
true
);
return [json, getEventIdFromHeaders(headers)];
}
export async function updateDataset(
inputDataset: Record,
inputDistributions: Record[],
tagDistributionVersion: boolean = false
): Promise<[Record, number]> {
// make sure all the aspects exist (this should be improved at some point, but will do for now)
const aspectPromises = getRecordsAspectIds(
[inputDataset].concat(inputDistributions)
).map((aspectId) => ensureAspectExists(aspectId));
await Promise.all(aspectPromises);
for (const distribution of inputDistributions) {
let distRecord: Record, headers: Headers;
if (await doesRecordExist(distribution.id)) {
[distRecord, headers] = await request(
"PUT",
`${config.registryFullApiUrl}records/${distribution.id}`,
distribution,
"application/json",
true
);
} else {
[distRecord, headers] = await request(
"POST",
`${config.registryFullApiUrl}records`,
distribution,
"application/json",
true
);
}
if (tagDistributionVersion) {
await tagRecordVersionEventId(
distRecord,
getEventIdFromHeaders(headers)
);
}
}
const [json, headers] = await request<Record>(
"PUT",
`${config.registryFullApiUrl}records/${inputDataset.id}`,
inputDataset,
"application/json",
true
);
return [json, getEventIdFromHeaders(headers)];
}
/**
* Update a record aspect. If the aspect not exist, it will be created.
*
* @export
* @template T
* @param {string} recordId
* @param {string} aspectId
* @param {T} aspectData
* @returns {Promise<T>} Return array of updated aspect data and eventId
*/
export async function updateRecordAspect<T = any>(
recordId: string,
aspectId: string,
aspectData: T
): Promise<[T, number]> {
await ensureAspectExists(aspectId);
const [json, headers] = await request<T>(
"PUT",
`${config.registryFullApiUrl}records/${recordId}/aspects/${aspectId}`,
aspectData,
"application/json",
true
);
return [json, getEventIdFromHeaders(headers)];
}
type JSONPath = {
op: string;
path: string;
value: any;
}[];
/**
* Patch a record via JSON patch.
* This function does not auto check aspect definition via `ensureAspectExists`
*
* @export
* @template T
* @param {string} recordId
* @param {T} aspectData
* @returns {Promise<[T, number]>} Return array of patched aspect data and eventId
*/
export async function patchRecord<T = any>(
recordId: string,
jsonPath: JSONPath
): Promise<[T, number]> {
const [json, headers] = await request<T>(
"PATCH",
`${config.registryFullApiUrl}records/${recordId}`,
jsonPath,
"application/json",
true
);
return [json, getEventIdFromHeaders(headers)];
}
/**
* If a record's current version's eventId has not been set, this function set it to specified eventId.
* The eventId later can be used to retrieve the record data as it was when the event had been created.
* i.e. the `version` emulate the `tag` concept of git where eventId can be considered as the `commit hash`.
*
* @param {Record} record
* @param {number} eventId
* @returns
*/
export async function tagRecordVersionEventId(record: Record, eventId: number) {
if (!record?.aspects?.["version"] || !eventId) {
return;
}
const versionData = record.aspects["version"] as VersionAspectData;
const currentVersion =
versionData?.versions?.[versionData?.currentVersionNumber];
if (!currentVersion) {
return;
}
if (currentVersion.eventId) {
return;
}
versionData.versions[versionData.currentVersionNumber].eventId = eventId;
return await updateRecordAspect(record.id, "version", versionData);
} | the_stack |
import { shell } from "electron";
import { join, extname } from "path";
import { readdir, writeFile } from "fs-extra";
import { Undefinable } from "../../../shared/types";
import * as React from "react";
import { ButtonGroup, Button, Popover, Position, Menu, MenuItem, MenuDivider, ContextMenu, Classes, Intent, Tag } from "@blueprintjs/core";
import { AbstractMesh, Node, IParticleSystem } from "babylonjs";
import { Editor } from "../editor";
import { Tools } from "../tools/tools";
import { ExecTools } from "../tools/exec";
import { undoRedo } from "../tools/undo-redo";
import { EditorPlayMode } from "../tools/types";
import { EditorUpdater } from "../tools/update/updater";
import { Icon } from "../gui/icon";
import { Confirm } from "../gui/confirm";
import { Overlay } from "../gui/overlay";
import { Alert } from "../gui/alert";
import { Dialog } from "../gui/dialog";
import { SceneFactory } from "../scene/factory";
import { SceneSettings } from "../scene/settings";
import { SceneTools } from "../scene/tools";
import { WorkSpace } from "../project/workspace";
import { ProjectExporter } from "../project/project-exporter";
import { WelcomeDialog } from "../project/welcome/welcome";
import { NewProjectWizard } from "../project/welcome/new-project";
import { ProjectRenamer } from "../project/rename";
import { PhotoshopExtension } from "../extensions/photoshop";
import { IPluginToolbar } from "../plugins/toolbar";
export interface IToolbarProps {
/**
* The editor reference.
*/
editor: Editor;
}
export interface IToolbarState {
/**
* Defines wether or not the current project has a workspace. If true, the workspace tool will be shows.
*/
hasWorkspace: boolean;
/**
* Defines wether or not the photoshop extension is enabled.
*/
isPhotoshopEnabled: boolean;
/**
* Defines the list of all menus for plugins.
*/
plugins?: Undefinable<IPluginToolbar[]>
}
export class MainToolbar extends React.Component<IToolbarProps, IToolbarState> {
private _editor: Editor;
/**
* Constructor.
* @param props the component's props.
*/
public constructor(props: IToolbarProps) {
super(props);
this._editor = props.editor;
this._editor.mainToolbar = this;
this.state = { hasWorkspace: false, isPhotoshopEnabled: false };
}
/**
* Renders the component.
*/
public render(): React.ReactNode {
const project =
<Menu>
<MenuItem text="Open Workspace..." icon={<Icon src="workspace.svg" />} onClick={() => this._menuItemClicked("project:open-workspace")} />
<MenuItem text="Reveal WorkSpace In File Explorer" disabled={!WorkSpace.HasWorkspace()} icon="document-open" onClick={() => this._menuItemClicked("project:open-worspace-file-explorer")} />
<MenuDivider />
<MenuItem text="Reload Project..." icon={<Icon src="undo.svg" />} onClick={() => this._menuItemClicked("project:reload")} id="toolbar-files-reload" />
<MenuItem text={<div>Save Project... <Tag intent={Intent.PRIMARY}>(CTRL+s)</Tag></div>} icon={<Icon src="copy.svg" />} onClick={() => this._menuItemClicked("project:save")} id="toolbar-save-project" />
<MenuItem text="Rename Project..." icon="edit" onClick={() => this._menuItemClicked("project:rename")} />
<MenuDivider />
<MenuItem text="Add New Project..." icon={<Icon src="plus.svg" />} onClick={() => NewProjectWizard.Show()} />
<MenuItem text="Projects" icon="more">
<MenuItem text="Refresh..." icon={<Icon src="recycle.svg" />} onClick={() => this._handleRefreshWorkspace()} />
<MenuDivider />
{WorkSpace.AvailableProjects.map((p) => <MenuItem key={p} text={p} onClick={() => this._handleChangeProject(p)} />)}
</MenuItem>
<MenuDivider />
<MenuItem text={<div>Build Project... <Tag intent={Intent.PRIMARY}>(CTRL+b)</Tag></div>} onClick={() => WorkSpace.BuildProject(this._editor)} id="toolbar-build-project" />
<MenuItem text={<div>Build & Run Project... <Tag intent={Intent.PRIMARY}>(CTRL+r)</Tag></div>} onClick={async () => {
await WorkSpace.BuildProject(this._editor);
this._editor.runProject(EditorPlayMode.IntegratedBrowser, false);
}} id="toolbar-build-and-run-project" />
<MenuDivider />
<MenuItem text={<div>Run Project... <Tag intent={Intent.PRIMARY}>(CTRL+r)</Tag></div>} onClick={() => this._editor.runProject(EditorPlayMode.IntegratedBrowser, false)} />
<MenuDivider />
<MenuItem text="Open Visual Studio Code..." icon={<Icon src="vscode.svg" style={{ filter: "none" }} />} onClick={() => this._handleOpenVSCode()} />
<MenuDivider />
<MenuItem text="Export" icon="more">
<MenuItem text="GLTF..." icon={<Icon src="gltf.svg" />} onClick={() => this._menuItemClicked("project:export:gltf")} />
<MenuItem text="GLB..." icon={<Icon src="gltf.svg" />} onClick={() => this._menuItemClicked("project:export:glb")} />
</MenuItem>
</Menu>;
const edit =
<Menu>
<MenuItem text={<div>Undo <Tag intent={Intent.PRIMARY}>(CTRL+z</Tag></div>} icon={<Icon src="undo.svg" />} onClick={() => this._menuItemClicked("edit:undo")} />
<MenuItem text={<div>Redo <Tag intent={Intent.PRIMARY}>(CTRL+y</Tag></div>} icon={<Icon src="redo.svg" />} onClick={() => this._menuItemClicked("edit:redo")} />
<MenuDivider />
<MenuItem text="Editor Camera" icon={<Icon src="camera.svg" />} onClick={() => this._menuItemClicked("edit:editor-camera")} />
<MenuDivider />
<MenuItem text="Refresh Assets Thumbnails..." onClick={() => this._menuItemClicked("edit:refresh-assets")} />
<MenuItem text="Clear Unused Assets Files..." onClick={() => this._menuItemClicked("edit:clear-unused-assets")} />
<MenuDivider />
<MenuItem text="Reset Editor..." icon={<Icon src="reset.svg" style={{ filter: "grayscale(1)", width: "20px", height: "20px" }} />} onClick={() => this._menuItemClicked("edit:reset")} />
<MenuDivider />
<MenuItem text="Restart TypeScript Watcher" onClick={() => this._menuItemClicked("edit:reset-typescript-watcher")} />
<MenuDivider />
<MenuItem text="Preferences..." icon={<Icon src="wrench.svg" />} onClick={() => this._handleWorkspaceSettings()} />
</Menu>;
const view =
<Menu>
{/* <MenuItem text="Add Preview" icon={<Icon src="plus.svg" />} onClick={() => this._menuItemClicked("view:add-preview")} /> */}
<MenuItem text="Enable Post-Processes" icon={this._getCheckedIcon(this._editor.scene?.postProcessesEnabled)} onClick={() => this._menuItemClicked("view:pp-enabled")} />
<MenuItem text="Enable Fog" icon={this._getCheckedIcon(this._editor.scene?.fogEnabled)} onClick={() => this._menuItemClicked("view:fog-enabled")} />
<MenuDivider />
<MenuItem text="Create ScreenShot..." icon={<Icon src="eye.svg" />} onClick={() => this._menuItemClicked("view:create-screenshot")} />
<MenuDivider />
<MenuItem text="Console" icon={<Icon src="info.svg" />} onClick={() => this._menuItemClicked("view:console")} />
<MenuItem text="Terminal" icon={<Icon src="terminal.svg" />} onClick={() => this._menuItemClicked("view:terminal")} />
<MenuItem text="Statistics" icon={<Icon src="stats.svg" />} onClick={() => this._menuItemClicked("view:stats")} />
<MenuDivider />
<MenuItem text={<div>Focus Selected Object <Tag intent={Intent.PRIMARY}>(CTRL+f)</Tag></div>} onClick={() => this._editor.preview.focusSelectedNode(true)} />
<MenuItem text={<div>Go To Selected Object <Tag intent={Intent.PRIMARY}>(CTRL+Shift+f)</Tag></div>} onClick={() => this._editor.preview.focusSelectedNode(false)} />
</Menu>;
const add =
<Menu>
<MenuItem text="Point Light" icon={<Icon src="lightbulb.svg" />} onClick={() => this._menuItemClicked("add:pointlight")} />
<MenuItem text="Directional Light" icon={<Icon src="lightbulb.svg" />} onClick={() => this._menuItemClicked("add:directional-light")} />
<MenuItem text="Spot Light" icon={<Icon src="lightbulb.svg" />} onClick={() => this._menuItemClicked("add:spot-light")} />
<MenuItem text="Hemispheric Light" icon={<Icon src="lightbulb.svg" />} onClick={() => this._menuItemClicked("add:hemispheric-light")} />
<MenuDivider />
<MenuItem text="Free Camera" icon={<Icon src="camera.svg" />} onClick={() => this._menuItemClicked("add:camera")} />
<MenuItem text="Arc Rotate Camera" icon={<Icon src="camera.svg" />} onClick={() => this._menuItemClicked("add:arc-rotate-camera")} />
<MenuDivider />
<MenuItem text="Sky" icon={<Icon src="smog.svg" />} onClick={() => this._menuItemClicked("add:sky")} />
<MenuDivider />
<MenuItem text="Dummy Node" icon={<Icon src="clone.svg" />} onClick={() => this._menuItemClicked("add:dummy")} />
<MenuDivider />
<MenuItem text="Particle System" icon={<Icon src="wind.svg" />} onClick={() => this._menuItemClicked("add:particle-system")} />
</Menu>;
const addMesh =
<Menu>
<MenuItem text="Cube" icon={<Icon src="cube.svg" />} onClick={() => this._menuItemClicked("addmesh:cube")} />
<MenuItem text="Sphere" icon={<Icon src="circle.svg" />} onClick={() => this._menuItemClicked("addmesh:sphere")} />
<MenuItem text="Cylinder" icon={<Icon src="cylinder.svg" />} onClick={() => this._menuItemClicked("addmesh:cylinder")} />
<MenuItem text="Plane" icon={<Icon src="square-full.svg" />} onClick={() => this._menuItemClicked("addmesh:plane")} />
<MenuDivider />
<MenuItem text="Ground" icon={<Icon src="vector-square.svg" />} onClick={() => this._menuItemClicked("addmesh:ground")} />
<MenuItem text="Terrain From Height Map..." icon={<Icon src="terrain.svg" style={{ filter: "none" }} />} onClick={() => this._menuItemClicked("addmesh:heightmap")} />
</Menu>;
const tools =
<Menu>
{/* <MenuItem text="Animation Editor" icon={<Icon src="film.svg" />} onClick={() => this._menuItemClicked("tools:animation-editor")} />
<MenuItem text="Painting Tools..." icon={<Icon src="paint-brush.svg" />} onClick={() => this._menuItemClicked("tools:painting-tools")} />
<MenuDivider /> */}
<MenuItem text="Connect To Photoshop" intent={this.state.isPhotoshopEnabled ? Intent.SUCCESS : Intent.NONE} icon={<Icon src="photoshop.svg" style={{ filter: "none" }} />} onClick={() => this._menuItemClicked("tools:photoshop")} />
</Menu>;
const help =
<Menu>
<MenuItem text="Documentation..." icon={<Icon src="internetarchive.svg" />} onClick={() => this._menuItemClicked("help:documentation")} />
<MenuItem text="Report issue..." icon={<Icon src="github.svg" />} onClick={() => this._menuItemClicked("help:report")} />
<MenuDivider />
<MenuItem text="Welcome..." icon={<Icon src="jedi.svg" />} onClick={() => this._menuItemClicked("help:welcome")} />
<MenuDivider />
<MenuItem text="Check For Updates..." icon="updated" onClick={() => this._menuItemClicked("help:check-for-updates")} />
</Menu>;
return (
<ButtonGroup large={false} style={{ marginTop: "auto", marginBottom: "auto" }}>
<Popover content={project} position={Position.BOTTOM_LEFT} hasBackdrop={false}>
<Button icon={<Icon src="folder-open.svg"/>} rightIcon="caret-down" text="File" id="toolbar-files" />
</Popover>
<Popover content={edit} position={Position.BOTTOM_LEFT} hasBackdrop={false}>
<Button icon={<Icon src="edit.svg"/>} rightIcon="caret-down" text="Edit"/>
</Popover>
<Popover content={view} position={Position.BOTTOM_LEFT} hasBackdrop={false}>
<Button icon={<Icon src="eye.svg"/>} rightIcon="caret-down" text="View"/>
</Popover>
<Popover content={add} position={Position.BOTTOM_LEFT} hasBackdrop={false}>
<Button icon={<Icon src="plus.svg"/>} rightIcon="caret-down" text="Add"/>
</Popover>
<Popover content={addMesh} position={Position.BOTTOM_LEFT} hasBackdrop={false}>
<Button icon={<Icon src="plus.svg"/>} rightIcon="caret-down" text="Add Mesh"/>
</Popover>
<Popover content={tools} position={Position.BOTTOM_LEFT} hasBackdrop={false}>
<Button icon={<Icon src="wrench.svg"/>} rightIcon="caret-down" text="Tools"/>
</Popover>
{this.state.plugins?.map((p) => (
<Popover content={p.content} position={Position.BOTTOM_LEFT} hasBackdrop={false}>
<Button icon={p.buttonIcon} rightIcon="caret-down" text={p.buttonLabel}/>
</Popover>
))}
<Popover content={help} position={Position.BOTTOM_LEFT} hasBackdrop={false}>
<Button icon={<Icon src="dog.svg"/>} rightIcon="caret-down" text="Help"/>
</Popover>
</ButtonGroup>
);
}
/**
* Returns the check icon if the given "checked" property is true.
*/
private _getCheckedIcon(checked: Undefinable<boolean>): Undefinable<JSX.Element> {
return checked ? <Icon src="check.svg" /> : undefined;
}
/**
* Called on a menu item is clicked.
*/
private async _menuItemClicked(id: string): Promise<void> {
// Get event family
const split = id.split(":");
const family = split[0];
const action = split[1];
// Common id.
switch (id) {
// Project
case "project:open-workspace": WorkSpace.Browse(); break;
case "project:open-worspace-file-explorer": shell.openItem(WorkSpace.DirPath!); break;
case "project:reload": this._reloadProject(); break;
case "project:save": ProjectExporter.Save(this._editor); break;
case "project:rename": ProjectRenamer.Rename(this._editor); break;
case "project:export:gltf": SceneTools.ExportSceneToGLTF(this._editor, "gltf"); break;
case "project:export:glb": SceneTools.ExportSceneToGLTF(this._editor, "glb"); break;
// Edit
case "edit:undo": undoRedo.undo(); break;
case "edit:redo": undoRedo.redo(); break;
case "edit:editor-camera": this._editor.inspector.setSelectedObject(SceneSettings.Camera); break;
case "edit:refresh-assets": this._editor.assets.forceRefresh(); break;
case "edit:clear-unused-assets": this._editor.assets.clearUnusedAssets(); break;
case "edit:reset": this._editor._resetEditor(); break;
case "edit:reset-typescript-watcher": WorkSpace.RestartTypeScriptWatcher(this._editor); break;
// Help
case "help:documentation": shell.openExternal("https://github.com/BabylonJS/Editor/blob/master/doc/00%20-%20welcome/doc.md"); break; // this._editor.addBuiltInPlugin("doc"); break;
case "help:report": shell.openExternal("https://github.com/BabylonJS/Editor/issues"); break;
case "help:welcome": WelcomeDialog.Show(this._editor, true); break;
case "help:check-for-updates": EditorUpdater.CheckForUpdates(this._editor, true); break;
default: break;
}
// View
if (family === "view") {
switch (action) {
// case "add-preview": this._editor.addPreview(); break;
case "pp-enabled": this._editor.scene!.postProcessesEnabled = !this._editor.scene!.postProcessesEnabled; break;
case "fog-enabled": this._editor.scene!.fogEnabled = !this._editor.scene!.fogEnabled; break;
case "create-screenshot": this._handleCreateScreenshot(); break;
case "console": this._editor.revealPanel("console"); break;
case "terminal": this._editor.addBuiltInPlugin("terminal"); break;
case "stats": this._editor.addBuiltInPlugin("stats"); break;
default: break;
}
this.forceUpdate();
this._editor.inspector.refreshDisplay();
}
// Add
if (family === "add") {
let node: Undefinable<Node | IParticleSystem>;
switch (action) {
case "pointlight": node = SceneFactory.AddPointLight(this._editor); break;
case "directional-light": node = SceneFactory.AddDirectionalLight(this._editor); break;
case "spot-light": node = SceneFactory.AddSpotLight(this._editor); break;
case "hemispheric-light": node = SceneFactory.AddHemisphericLight(this._editor); break;
case "camera": node = SceneFactory.AddFreeCamera(this._editor); break;
case "arc-rotate-camera": node = SceneFactory.AddArcRotateCamera(this._editor); break;
case "sky": node = SceneFactory.AddSky(this._editor); break;
case "dummy": node = SceneFactory.AddDummy(this._editor); break;
case "particle-system": node = SceneFactory.AddParticleSystem(this._editor, false); break;
default: break;
}
if (!node) { return; }
if (node instanceof Node) {
this._editor.addedNodeObservable.notifyObservers(node);
} else {
this._editor.addedParticleSystemObservable.notifyObservers(node);
}
return this._editor.graph.refresh();
}
// Add mesh
if (family === "addmesh") {
let mesh: Undefinable<AbstractMesh>;
switch (action) {
case "cube": mesh = SceneFactory.AddCube(this._editor); break;
case "sphere": mesh = SceneFactory.AddSphere(this._editor); break;
case "cylinder": mesh = SceneFactory.AddCynlinder(this._editor); break;
case "plane": mesh = SceneFactory.AddPlane(this._editor); break;
case "ground": mesh = SceneFactory.AddGround(this._editor); break;
case "heightmap": mesh = await SceneFactory.AddTerrainFromHeightMap(this._editor); break;
default: break;
}
if (!mesh) { return; }
this._editor.addedNodeObservable.notifyObservers(mesh);
return this._editor.graph.refresh();
}
// Tools
if (family === "tools") {
switch (action) {
case "animation-editor": this._editor.addBuiltInPlugin("animation-editor"); break;
case "painting-tools": this._editor.addBuiltInPlugin("painting"); break;
case "photoshop": this._handleTogglePhotoshop(); break;
}
}
}
/**
* Called on the user wants to reload the project.
*/
private async _reloadProject(): Promise<void> {
if (await Confirm.Show("Reload project?", "Are you sure to reload?")) {
Overlay.Show("Reloading...", true);
window.location.reload();
}
}
/**
* Called on the user wants to toggle the connection to photoshop.
*/
private async _handleTogglePhotoshop(): Promise<void> {
let password = "";
if (!PhotoshopExtension.IsEnabled) {
password = await Dialog.Show("Connect to Photoshop", "Please provide the password to connect to photoshop", undefined, true);
}
await PhotoshopExtension.ToggleEnabled(this._editor, password);
this.setState({ isPhotoshopEnabled: PhotoshopExtension.IsEnabled });
}
/**
* Called on the user wants to refresh the available projects in the workspace.
*/
private async _handleRefreshWorkspace(): Promise<void> {
await WorkSpace.RefreshAvailableProjects();
this.forceUpdate();
}
/**
* Called on the user wants to show the workspace settings.
*/
private async _handleWorkspaceSettings(): Promise<void> {
const popupId = await this._editor.addWindowedPlugin("preferences", undefined, WorkSpace.Path);
if (!popupId) { return; }
}
/**
* Called on the user wants to open VSCode.
*/
private async _handleOpenVSCode(): Promise<void> {
try {
await ExecTools.ExecAndGetProgram(this._editor, `code "${WorkSpace.DirPath!}"`, undefined, true).promise;
} catch (e) {
Alert.Show("Failed to open VSCode", `
Failed to open Visual Studio Code. Please ensure the command named "code" is available in the "PATH" environment.
You can add the command by opening VSCode, type "Command or Control + Shift + P" and find the command "Shell Command : Install code in PATH".
`);
}
}
/**
* Called on the user wants to change the current project.
*/
private async _handleChangeProject(name: string): Promise<void> {
if (!(await Confirm.Show("Load project?", "Are you sure to close the current project?"))) { return; }
const projectFolder = join(WorkSpace.DirPath!, "projects", name);
const files = await readdir(projectFolder);
let projectFileName: Undefinable<string> = "scene.editorproject";
if (files.indexOf(projectFileName) === -1) {
projectFileName = files.find((f) => extname(f).toLowerCase() === ".editorproject");
}
if (!projectFileName) { return; }
await WorkSpace.WriteWorkspaceFile(join(projectFolder, projectFileName));
window.location.reload();
}
/**
* Called on the user wants to create a screenshot.
*/
private async _handleCreateScreenshot(): Promise<void> {
const b64 = await Tools.CreateScreenshot(this._editor.engine!, this._editor.scene!.activeCamera!);
const img = (
<img
src={b64}
style={{ objectFit: "contain", width: "100%", height: "100%" }}
onContextMenu={(e) => {
ContextMenu.show(
<Menu className={Classes.DARK}>
<MenuItem text="Save..." icon={<Icon src="save.svg" />} onClick={async () => {
let destination = await Tools.ShowSaveFileDialog("Save Screenshot");
const extension = extname(destination);
if (extension !== ".png") { destination += ".png"; }
const base64 = b64.split(",")[1];
await writeFile(destination, new Buffer(base64, "base64"));
this._editor.notifyMessage("Successfully saved screenshot.", 1000, "saved");
}} />
</Menu>,
{ left: e.clientX, top: e.clientY }
);
}}
></img>
);
Alert.Show("Screenshot", "Result:", <Icon src="eye.svg" />, img);
}
} | the_stack |
(function beautify_markup_init():void {
"use strict";
const markup = function beautify_markup(options:any):string {
const data:data = options.parsed,
lexer:string = "markup",
c:number = (prettydiff.end < 1 || prettydiff.end > data.token.length)
? data.token.length
: prettydiff.end + 1,
lf:"\r\n"|"\n" = (options.crlf === true)
? "\r\n"
: "\n",
externalIndex:externalIndex = {},
levels:number[] = (function beautify_markup_levels():number[] {
const level:number[] = (prettydiff.start > 0)
? Array(prettydiff.start).fill(0, 0, prettydiff.start)
: [],
nextIndex = function beautify_markup_levels_next():number {
let x:number = a + 1,
y:number = 0;
if (data.types[x] === undefined) {
return x - 1;
}
if (data.types[x] === "comment" || (a < c - 1 && data.types[x].indexOf("attribute") > -1)) {
do {
if (data.types[x] === "jsx_attribute_start") {
y = x;
do {
if (data.types[x] === "jsx_attribute_end" && data.begin[x] === y) {
break;
}
x = x + 1;
} while (x < c);
} else if (data.types[x] !== "comment" && data.types[x].indexOf("attribute") < 0) {
return x;
}
x = x + 1;
} while (x < c);
}
return x;
},
anchorList = function beautify_markup_levels_anchorList():void {
let aa:number = a;
const stop:number = data.begin[a];
// verify list is only a link list before making changes
do {
aa = aa - 1;
if (data.token[aa] === "</li>" && data.begin[data.begin[aa]] === stop && data.token[aa - 1] === "</a>" && data.begin[aa - 1] === data.begin[aa] + 1) {
aa = data.begin[aa];
} else {
return;
}
} while (aa > stop + 1);
// now make the changes
aa = a;
do {
aa = aa - 1;
if (data.types[aa + 1] === "attribute") {
level[aa] = -10;
} else if (data.token[aa] !== "</li>") {
level[aa] = -20;
}
} while (aa > stop + 1);
},
comment = function beautify_markup_levels_comment():void {
let x:number = a,
test:boolean = false;
if (data.lines[a + 1] === 0 && options.force_indent === false) {
do {
if (data.lines[x] > 0) {
test = true;
break;
}
x = x - 1;
} while (x > comstart);
x = a;
} else {
test = true;
}
// the first condition applies indentation while the else block does not
if (test === true) {
let ind = (data.types[next] === "end" || data.types[next] === "template_end")
? indent + 1
: indent;
do {
level.push(ind);
x = x - 1;
} while (x > comstart);
// correction so that a following end tag is not indented 1 too much
if (ind === indent + 1) {
level[a] = indent;
}
// indentation must be applied to the tag preceeding the comment
if (data.types[x] === "attribute" || data.types[x] === "template_attribute" || data.types[x] === "jsx_attribute_start") {
level[data.begin[x]] = ind;
} else {
level[x] = ind;
}
} else {
do {
level.push(-20);
x = x - 1;
} while (x > comstart);
level[x] = -20;
}
comstart = -1;
},
content = function beautify_markup_levels_content():void {
let ind:number = indent;
if (options.force_indent === true || options.force_attribute === true) {
level.push(indent);
return;
}
if (next < c && (data.types[next].indexOf("end") > -1 || data.types[next].indexOf("start") > -1) && data.lines[next] > 0) {
level.push(indent);
ind = ind + 1;
if (data.types[a] === "singleton" && a > 0 && data.types[a - 1].indexOf("attribute") > -1 && data.types[data.begin[a - 1]] === "singleton") {
if (data.begin[a] < 0 || (data.types[data.begin[a - 1]] === "singleton" && data.begin[data.ender[a] - 1] !== a)) {
level[a - 1] = indent;
} else {
level[a - 1] = indent + 1;
}
}
} else if (data.types[a] === "singleton" && a > 0 && data.types[a - 1].indexOf("attribute") > -1) {
level[a - 1] = indent;
count = data.token[a].length;
level.push(-10);
} else if (data.lines[next] === 0) {
level.push(-20);
} else if (
// wrap if
// * options.wrap is 0
// * next token is singleton with an attribute and exceeds wrap
// * next token is template or singleton and exceeds wrap
(
options.wrap === 0 ||
(a < c - 2 && data.token[a].length + data.token[a + 1].length + data.token[a + 2].length + 1 > options.wrap && data.types[a + 2].indexOf("attribute") > -1) ||
(data.token[a].length + data.token[a + 1].length > options.wrap)
) &&
(data.types[a + 1] === "singleton" || data.types[a + 1] === "template")) {
level.push(indent);
} else {
count = count + 1;
level.push(-10);
}
if (a > 0 && data.types[a - 1].indexOf("attribute") > -1 && data.lines[a] < 1) {
level[a - 1] = -20;
}
if (count > options.wrap) {
let d:number = a,
e:number = Math.max(data.begin[a], 0);
if (data.types[a] === "content" && options.preserve_text === false) {
let countx:number = 0,
chars:string[] = data.token[a].replace(/\s+/g, " ").split(" ");
do {
d = d - 1;
if (level[d] < 0) {
countx = countx + data.token[d].length;
if (level[d] === -10) {
countx = countx + 1;
}
} else {
break;
}
} while (d > 0);
d = 0;
e = chars.length;
do {
if (chars[d].length + countx > options.wrap) {
chars[d] = lf + chars[d];
countx = chars[d].length;
} else {
chars[d] = ` ${chars[d]}`;
countx = countx + chars[d].length;
}
d = d + 1;
} while (d < e);
if (chars[0].charAt(0) === " ") {
data.token[a] = chars.join("").slice(1);
} else {
level[a - 1] = ind;
data.token[a] = chars.join("").replace(lf, "");
}
if (data.token[a].indexOf(lf) > 0) {
count = data.token[a].length - data.token[a].lastIndexOf(lf);
}
} else {
do {
d = d - 1;
if (level[d] > -1) {
count = data.token[a].length;
if (data.lines[a + 1] > 0) {
count = count + 1;
}
return;
}
if (data.types[d].indexOf("start") > -1) {
count = 0;
return;
}
if ((data.types[d] !== "attribute" || (data.types[d] === "attribute" && data.types[d + 1] !== "attribute")) && data.lines[d + 1] > 0) {
if (data.types[d] !== "singleton" || (data.types[d] === "singleton" && data.types[d + 1] !== "attribute")) {
count = data.token[a].length;
if (data.lines[a + 1] > 0) {
count = count + 1;
}
break;
}
}
} while (d > e);
level[d] = ind;
}
}
},
external = function beautify_markup_levels_external():void {
let skip:number = a;
do {
if (data.lexer[a + 1] === lexer && data.begin[a + 1] < skip && data.types[a + 1] !== "start" && data.types[a + 1] !== "singleton") {
break;
}
level.push(0);
a = a + 1;
} while (a < c);
externalIndex[skip] = a;
level.push(indent - 1);
next = nextIndex();
if (data.lexer[next] === lexer && data.stack[a].indexOf("attribute") < 0 && (data.types[next] === "end" || data.types[next] === "template_end")) {
indent = indent - 1;
}
},
attribute = function beautify_markup_levels_attribute():void {
const parent:number = a - 1,
wrap = function beautify_markup_levels_attribute_wrap(index:number):void {
const item:string[] = data.token[index].replace(/\s+/g, " ").split(" "),
ilen:number = item.length;
let bb:number = 1,
acount:number = item[0].length;
if ((/=("|')?(<|(\{(\{|%|#|@|!|\?|^))|(\[%))/).test(data.token[index]) === true) {
return;
}
do {
if (acount + item[bb].length > options.wrap) {
acount = item[bb].length;
item[bb] = lf + item[bb];
} else {
item[bb] = ` ${item[bb]}`;
acount = acount + item[bb].length;
}
bb = bb + 1;
} while (bb < ilen);
data.token[index] = item.join("");
};
let y:number = a,
len:number = data.token[parent].length + 1,
plural:boolean = false,
lev:number = (function beautify_markup_levels_attribute_level():number {
if (data.types[a].indexOf("start") > 0) {
let x:number = a;
do {
if (data.types[x].indexOf("end") > 0 && data.begin[x] === a) {
if (x < c - 1 && data.types[x + 1].indexOf("attribute") > -1) {
plural = true;
break;
}
}
x = x + 1;
} while (x < c);
} else if (a < c - 1 && data.types[a + 1].indexOf("attribute") > -1) {
plural = true;
}
if (data.types[next] === "end" || data.types[next] === "template_end") {
if (data.types[parent] === "singleton") {
return indent + 2;
}
return indent + 1;
}
if (data.types[parent] === "singleton") {
return indent + 1;
}
return indent;
}()),
earlyexit:boolean = false,
attStart:boolean = false;
if (plural === false && data.types[a] === "comment_attribute") {
// lev must be indent unless the "next" type is end then its indent + 1
level.push(indent);
if (data.types[parent] === "singleton") {
level[parent] = indent + 1;
} else {
level[parent] = indent;
}
return;
}
if (lev < 1) {
lev = 1;
}
// first, set levels and determine if there are template attributes
do {
count = count + data.token[a].length + 1;
if (data.types[a].indexOf("attribute") > 0) {
if (data.types[a] === "template_attribute") {
level.push(-10);
} else if (data.types[a] === "comment_attribute") {
level.push(lev);
} else if (data.types[a].indexOf("start") > 0) {
attStart = true;
if (a < c - 2 && data.types[a + 2].indexOf("attribute") > 0) {
level.push(-20);
a = a + 1;
externalIndex[a] = a;
} else {
if (parent === a - 1 && plural === false) {
level.push(lev);
} else {
level.push(lev + 1);
}
if (data.lexer[a + 1] !== lexer) {
a = a + 1;
external();
}
}
} else if (data.types[a].indexOf("end") > 0) {
if (level[a - 1] !== -20) {
level[a - 1] = level[data.begin[a]] - 1;
}
if (data.lexer[a + 1] !== lexer) {
level.push(-20);
} else {
level.push(lev);
}
} else {
level.push(lev);
}
earlyexit = true;
} else if (data.types[a] === "attribute") {
len = len + data.token[a].length + 1;
if (options.unformatted === true) {
level.push(-10);
} else if (options.force_attribute === true || attStart === true || (a < c - 1 && data.types[a + 1] !== "template_attribute" && data.types[a + 1].indexOf("attribute") > 0)) {
level.push(lev);
} else {
level.push(-10);
}
} else if (data.begin[a] < parent + 1) {
break;
}
a = a + 1;
} while (a < c);
a = a - 1;
if (level[a - 1] > 0 && data.types[a].indexOf("end") > 0 && data.types[a].indexOf("attribute") > 0 && data.types[parent] !== "singleton" && plural === true) {
level[a - 1] = level[a - 1] - 1;
}
if (level[a] !== -20) {
if (options.language === "jsx" && data.types[parent].indexOf("start") > -1 && data.types[a + 1] === "script_start") {
level[a] = lev;
} else {
level[a] = level[parent];
}
}
if (options.force_attribute === true) {
count = 0;
level[parent] = lev;
} else {
level[parent] = -10;
}
if (earlyexit === true || options.unformatted === true || data.token[parent] === "<%xml%>" || data.token[parent] === "<?xml?>") {
count = 0;
return;
}
y = a;
// second, ensure tag contains more than one attribute
if (y > parent + 1) {
// finally, indent attributes if tag length exceeds the wrap limit
if (options.space_close === false) {
len = len - 1;
}
if (len > options.wrap && options.wrap > 0 && options.force_attribute === false) {
count = data.token[a].length;
do {
if (data.token[y].length > options.wrap && (/\s/).test(data.token[y]) === true) {
wrap(y);
}
y = y - 1;
level[y] = lev;
} while (y > parent);
}
} else if (options.wrap > 0 && data.types[a] === "attribute" && data.token[a].length > options.wrap && (/\s/).test(data.token[a]) === true) {
wrap(a);
}
};
let a:number = prettydiff.start,
comstart:number = -1,
next:number = 0,
count:number = 0,
indent:number = (isNaN(options.indent_level) === true)
? 0
: Number(options.indent_level);
// data.lines -> space before token
// level -> space after token
do {
if (data.lexer[a] === lexer) {
if (data.token[a].toLowerCase().indexOf("<!doctype") === 0) {
level[a - 1] = indent;
}
if (data.types[a].indexOf("attribute") > -1) {
attribute();
} else if (data.types[a] === "comment") {
if (comstart < 0) {
comstart = a;
}
if (data.types[a + 1] !== "comment" || (a > 0 && data.types[a - 1].indexOf("end") > -1)) {
comment();
}
} else if (data.types[a] !== "comment") {
next = nextIndex();
if (data.types[next] === "end" || data.types[next] === "template_end") {
indent = indent - 1;
if (data.types[next] === "template_end" && data.types[data.begin[next] + 1] === "template_else") {
indent = indent - 1;
}
if (data.token[a] === "</ol>" || data.token[a] === "</ul>") {
anchorList();
}
}
if (data.types[a] === "script_end" && data.types[a + 1] === "end") {
if (data.lines[a + 1] < 1) {
level.push(-20);
} else {
level.push(-10);
}
} else if ((options.force_indent === false || (options.force_indent === true && data.types[next] === "script_start")) && (data.types[a] === "content" || data.types[a] === "singleton" || data.types[a] === "template")) {
count = count + data.token[a].length;
if (data.lines[next] > 0 && data.types[next] === "script_start") {
level.push(-10);
} else if (options.wrap > 0 && (data.types[a].indexOf("template") < 0 || (next < c && data.types[a].indexOf("template") > -1 && data.types[next].indexOf("template") < 0))) {
content();
} else if (next < c && (data.types[next].indexOf("end") > -1 || data.types[next].indexOf("start") > -1) && (data.lines[next] > 0 || data.types[next].indexOf("template_") > -1)) {
level.push(indent);
} else if (data.lines[next] === 0) {
level.push(-20);
} else {
level.push(indent);
}
} else if (data.types[a] === "start" || data.types[a] === "template_start") {
indent = indent + 1;
if (data.types[a] === "template_start" && data.types[a + 1] === "template_else") {
indent = indent + 1;
}
if (options.language === "jsx" && data.token[a + 1] === "{") {
if (data.lines[a + 1] === 0) {
level.push(-20);
} else {
level.push(-10);
}
} else if (data.types[a] === "start" && data.types[next] === "end") {
level.push(-20);
} else if (data.types[a] === "start" && data.types[next] === "script_start") {
level.push(-10);
} else if (options.force_indent === true) {
level.push(indent);
} else if (data.types[a] === "template_start" && data.types[next] === "template_end") {
level.push(-20);
} else if (data.lines[next] === 0 && (data.types[next] === "content" || data.types[next] === "singleton" || (data.types[a] === "start" && data.types[next] === "template"))) {
level.push(-20);
} else {
level.push(indent);
}
} else if (options.force_indent === false && data.lines[next] === 0 && (data.types[next] === "content" || data.types[next] === "singleton")) {
level.push(-20);
} else if (data.types[a + 2] === "script_end") {
level.push(-20);
} else if (data.types[a] === "template_else") {
if (data.types[next] === "template_end") {
level[a - 1] = indent + 1;
} else {
level[a - 1] = indent - 1;
}
level.push(indent);
} else {
level.push(indent);
}
}
if (data.types[a] !== "content" && data.types[a] !== "singleton" && data.types[a] !== "template" && data.types[a] !== "attribute") {
count = 0;
}
} else {
count = 0;
external();
}
a = a + 1;
} while (a < c);
return level;
}());
return (function beautify_markup_apply():string {
const build:string[] = [],
ind:string = (function beautify_markup_apply_tab():string {
const indy:string[] = [options.indent_char],
size:number = options.indent_size - 1;
let aa:number = 0;
if (aa < size) {
do {
indy.push(options.indent_char);
aa = aa + 1;
} while (aa < size);
}
return indy.join("");
}()),
// a new line character plus the correct amount of identation for the given line
// of code
nl = function beautify_markup_apply_nl(tabs:number):string {
const linesout:string[] = [],
pres:number = options.preserve + 1,
total:number = Math.min(data.lines[a + 1] - 1, pres);
let index = 0;
if (tabs < 0) {
tabs = 0;
}
do {
linesout.push(lf);
index = index + 1;
} while (index < total);
if (tabs > 0) {
index = 0;
do {
linesout.push(ind);
index = index + 1;
} while (index < tabs);
}
return linesout.join("");
},
multiline = function beautify_markup_apply_multiline():void {
const lines:string[] = data.token[a].split(lf),
line:number = data.lines[a + 1],
lev:number = (levels[a - 1] > -1)
? (data.types[a] === "attribute")
? levels[a - 1] + 1
: levels[a - 1]
: (function beautify_markup_apply_multiline_lev():number {
let bb:number = a - 1,
start:boolean = (bb > -1 && data.types[bb].indexOf("start") > -1);
if (levels[a] > -1 && data.types[a] === "attribute") {
return levels[a] + 1;
}
do {
bb = bb - 1;
if (levels[bb] > -1) {
if (data.types[a] === "content" && start === false) {
return levels[bb];
}
return levels[bb] + 1;
}
if (data.types[bb].indexOf("start") > -1) {
start = true;
}
} while (bb > 0);
return 1;
}());
let aa:number = 0,
len:number = lines.length - 1;
data.lines[a + 1] = 0;
do {
build.push(lines[aa]);
build.push(nl(lev));
aa = aa + 1;
} while (aa < len);
data.lines[a + 1] = line;
build.push(lines[len]);
if (levels[a] === -10) {
build.push(" ");
} else if (levels[a] > -1) {
build.push(nl(levels[a]));
}
},
attributeEnd = function beautify_markup_apply_attributeEnd():void {
const parent:string = data.token[a],
regend:RegExp = (/(\/|\?)?>$/),
end:string[]|null = regend.exec(parent);
let y:number = a + 1,
space:string = (options.space_close === true && end !== null && end[0] === "/>")
? " "
: "",
jsx:boolean = false;
if (end === null) {
return;
}
data.token[a] = parent.replace(regend, "");
do {
if (data.types[y] === "jsx_attribute_end" && data.begin[data.begin[y]] === a) {
jsx = false;
} else if (data.begin[y] === a) {
if (data.types[y] === "jsx_attribute_start") {
jsx = true;
} else if (data.types[y].indexOf("attribute") < 0 && jsx === false) {
break;
}
} else if (jsx === false && (data.begin[y] < a || data.types[y].indexOf("attribute") < 0)) {
break;
}
y = y + 1;
} while (y < c);
if (data.types[y - 1] === "comment_attribute") {
space = nl(levels[y - 2] - 1);
}
data.token[y - 1] = data.token[y - 1] + space + end[0];
};
let a:number = prettydiff.start,
external:string = "",
lastLevel:number = options.indent_level;
do {
if (data.lexer[a] === lexer || prettydiff.beautify[data.lexer[a]] === undefined) {
if ((data.types[a] === "start" || data.types[a] === "singleton" || data.types[a] === "xml" || data.types[a] === "sgml") && data.types[a].indexOf("attribute") < 0 && a < c - 1 && data.types[a + 1] !== undefined && data.types[a + 1].indexOf("attribute") > -1) {
attributeEnd();
}
if (data.token[a] !== undefined && data.token[a].indexOf(lf) > 0 && ((data.types[a] === "content" && options.preserve_text === false) || data.types[a] === "comment" || data.types[a] === "attribute")) {
multiline();
} else {
build.push(data.token[a]);
if (levels[a] === -10 && a < c - 1) {
build.push(" ");
} else if (levels[a] > -1) {
lastLevel = levels[a];
build.push(nl(levels[a]));
}
}
} else {
if (externalIndex[a] === a && data.types[a] !== "reference") {
build.push(data.token[a]);
} else {
prettydiff.end = externalIndex[a];
options.indent_level = lastLevel;
prettydiff.start = a;
external = prettydiff.beautify[data.lexer[a]](options).replace(/\s+$/, "");
build.push(external);
if (levels[prettydiff.iterator] > -1 && externalIndex[a] > a) {
build.push(nl(levels[prettydiff.iterator]));
}
a = prettydiff.iterator;
}
}
a = a + 1;
} while (a < c);
prettydiff.iterator = c - 1;
if (build[0] === lf || build[0] === " ") {
build[0] = "";
}
return build.join("");
}());
};
global.prettydiff.beautify.markup = markup;
}()); | the_stack |
import React, { useState, useEffect, useRef, useMemo, ChangeEvent } from 'react';
import FileSelector from './FileSelector';
import MessagePreview from './MessagePreview';
import Settings, { SettingsValues, defaultSettings, NONE_COLOUR_NAME } from './Settings';
import { frameCount, getTransformationMatrices, colours } from '../config/animation';
const maxWidth = 100;
const maxHeight = maxWidth;
const frameDuration = 50;
interface ImageMeta {
loaded: boolean;
width: number;
height: number;
}
interface CropBounds {
top: number;
left: number;
right: number;
bottom: number;
}
interface ImageSizing {
canvasWidth: number;
canvasHeight: number;
imageRegionWidth: number;
imageRegionHeight: number;
}
interface CachedFrameData {
frames: ImageData[];
crop: CropBounds;
}
export type PreviewRenderListener = (canvas: HTMLCanvasElement, sourceWidth: number, sourceHight: number) => void;
/**
* Gets the bounds of the non-transparent image data.
* Represented as distance from the top-left corner of the provided canvas.
*/
function getPixelBoundsForCanvas(ctx: CanvasRenderingContext2D): CropBounds {
const width = ctx.canvas.width;
const height = ctx.canvas.height;
const pixels = ctx.getImageData(0, 0, width, height);
const pixelDataLength = pixels.data.length;
const bounds = {
top: height / 2,
left: width / 2,
right: width / 2,
bottom: height / 2,
};
let x,
y = 0;
// Based on https://gist.github.com/remy/784508
for (let i = 0; i < pixelDataLength; i += 4) {
if (pixels.data[i + 3] !== 0) {
x = (i / 4) % width;
y = ~~(i / 4 / width);
if (y < bounds.top) {
bounds.top = y;
}
if (x < bounds.left) {
bounds.left = x;
}
if (x > bounds.right) {
bounds.right = x;
}
if (y > bounds.bottom) {
bounds.bottom = y;
}
}
}
bounds.bottom += 1;
bounds.right += 1;
return bounds;
}
function getPixelBounds(image: CanvasImageSource): CropBounds {
const cropperCanvas = document.createElement('canvas');
cropperCanvas.width = image.width as number;
cropperCanvas.height = image.height as number;
const cropperCtx = cropperCanvas.getContext('2d');
if (!cropperCtx) {
return {
top: 0,
left: 0,
right: image.width as number,
bottom: image.height as number,
};
}
cropperCtx.drawImage(image, 0, 0);
const bounds = getPixelBoundsForCanvas(cropperCtx);
return bounds;
}
/**
* Calculates info needed to size the output canvas, based on the provided image information
*/
function getImageSizing(imageMeta: ImageMeta): ImageSizing {
const width = imageMeta.width;
const height = imageMeta.height;
const scaleAmount = Math.min(1, maxWidth / width, maxHeight / height);
const imageRegionWidth = width * scaleAmount;
const imageRegionHeight = height * scaleAmount;
return {
canvasWidth: maxWidth * 2, // These are hardcoded for the sake of keeping the transformation matrices simple and static
canvasHeight: maxHeight * 2,
imageRegionWidth,
imageRegionHeight,
};
}
/**
* Pre-renders static things that are used by the main render function.
* @param imageSizing Sizing info to use to position the image
* @param preProcessedImageCtx Canvas context where the pre-processed image will be drawn
* @param image Image to draw
*/
function prepForRender(
imageSizing: ImageSizing,
preProcessedImageCtx: CanvasRenderingContext2D,
image: HTMLImageElement | HTMLCanvasElement,
settings: SettingsValues
) {
preProcessedImageCtx.drawImage(
image,
0,
0,
image.width,
image.height,
(imageSizing.canvasWidth - imageSizing.imageRegionWidth) / 2,
(imageSizing.canvasHeight - imageSizing.imageRegionHeight) / 2,
imageSizing.imageRegionWidth,
imageSizing.imageRegionHeight
);
if (settings.colourScheme !== NONE_COLOUR_NAME) {
// Convert to grayscale
const grayscaleImage = preProcessedImageCtx.getImageData(0, 0, imageSizing.canvasWidth, imageSizing.canvasHeight);
const pixels = grayscaleImage.data;
const brightnessFactor = settings.brightness;
const contrast = settings.contrast * 254;
const contrastFactor = (255 + contrast) / (255 - contrast);
for (let i = 0; i < pixels.length; i += 4) {
const brightness = pixels[i] * 0.299 + pixels[i + 1] * 0.587 + pixels[i + 2] * 0.114;
const valueAdjusted = brightnessFactor * (contrastFactor * (brightness - 128) + 128);
pixels[i] = valueAdjusted;
pixels[i + 1] = valueAdjusted;
pixels[i + 2] = valueAdjusted;
}
preProcessedImageCtx.putImageData(grayscaleImage, 0, 0);
}
}
/**
* Renders all frames of the animation and returns them as ImageData, along with info on how the final frames should be cropped
*/
function generateCachedFrames(
settings: SettingsValues,
imageSizing: ImageSizing,
image: CanvasImageSource
): CachedFrameData | null {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
if (!ctx) {
return null;
}
const cachedFrames = [];
canvas.width = imageSizing.canvasWidth;
canvas.height = imageSizing.canvasHeight;
const maximalBounds = {
top: canvas.height,
left: canvas.width,
right: 0,
bottom: 0,
};
const transformationMatrices = getTransformationMatrices(
settings.waveStyle,
settings.verticalCenter,
settings.magnitude
);
for (let i = 0; i < frameCount; i++) {
renderFrame(i, ctx, image, imageSizing, settings, transformationMatrices);
const rawData = ctx.getImageData(0, 0, imageSizing.canvasWidth, imageSizing.canvasHeight);
const rawPixels = rawData.data;
// Hack to deal with the GIF encoder needing a key colour to make transparent. Without this, black (which we
// specify as the key colour) would become transparent. So this here replaces solid black with slightly-off-black
for (let pixelIndex = 0; pixelIndex < rawPixels.length; pixelIndex += 4) {
if (
rawPixels[pixelIndex] === 0 &&
rawPixels[pixelIndex + 1] === 0 &&
rawPixels[pixelIndex + 2] === 0 &&
rawPixels[pixelIndex + 3] !== 0
) {
rawPixels[pixelIndex] = 1;
rawPixels[pixelIndex + 1] = 1;
rawPixels[pixelIndex + 2] = 1;
}
}
cachedFrames.push(rawData);
const computedBounds = getPixelBounds(canvas);
maximalBounds.top = Math.min(computedBounds.top, maximalBounds.top);
maximalBounds.left = Math.min(computedBounds.left, maximalBounds.left);
maximalBounds.right = Math.max(computedBounds.right, maximalBounds.right);
maximalBounds.bottom = Math.max(computedBounds.bottom, maximalBounds.bottom);
}
return { frames: cachedFrames, crop: maximalBounds };
}
function renderFrame(
frameNumber: number,
canvasCtx: CanvasRenderingContext2D,
imageSource: CanvasImageSource,
imageSizing: ImageSizing,
settings: SettingsValues,
transformationMatrices: number[][]
) {
const frameTransformation = transformationMatrices[frameNumber % transformationMatrices.length] ?? [];
canvasCtx.globalCompositeOperation = 'source-over';
canvasCtx.clearRect(0, 0, imageSizing.canvasWidth, imageSizing.canvasHeight);
canvasCtx.setTransform(...(frameTransformation as DOMMatrix2DInit[]));
// draw base image
canvasCtx.globalCompositeOperation = 'source-over';
canvasCtx.drawImage(imageSource, 0, 0);
// overlay the colour blend
if (settings.colourScheme in colours) {
canvasCtx.globalCompositeOperation = settings.blendMode;
canvasCtx.fillStyle = colours[settings.colourScheme as keyof typeof colours][frameNumber];
canvasCtx.fillRect(0, 0, imageSizing.canvasWidth, imageSizing.canvasHeight);
}
// mask using the original image
canvasCtx.globalCompositeOperation = 'destination-in';
canvasCtx.drawImage(imageSource, 0, 0);
}
function renderCachedFrame(canvasCtx: CanvasRenderingContext2D, cachedFrame: ImageData, crop: CropBounds) {
canvasCtx.putImageData(cachedFrame, -crop.left, -crop.top);
}
export default function Creator(): JSX.Element {
const [settings, setSettings] = useState<SettingsValues>({
...defaultSettings,
});
const [imageElement] = useState<HTMLImageElement>(new Image());
const [imageSource, setImageSource] = useState<HTMLImageElement | HTMLCanvasElement | null>(null);
const [emojiCanvas] = useState<HTMLCanvasElement>(() => {
const canvas = document.createElement('canvas');
canvas.width = 200;
canvas.height = 200;
return canvas;
});
const [imagePrepCanvas] = useState<HTMLCanvasElement>(document.createElement('canvas'));
const [imageMeta, setImageMeta] = useState<ImageMeta>({ loaded: false, width: 0, height: 0 });
const [lastRenderIteration, setLastRenderIteration] = useState(0);
const [lastRenderTime, setLastRenderTime] = useState(0);
const [outputImageBlobUrl, setOutputImageBlobUrl] = useState<string | null>(null);
const [previewRenderListeners, setPreviewRenderListeners] = useState<PreviewRenderListener[]>([]);
const [cachedFrameData, setCachedFrameData] = useState<CachedFrameData | null>();
const previewCanvasRef = useRef<HTMLCanvasElement>(null);
const outputElementRef = useRef<HTMLDivElement>(null);
const emojiInputRef = useRef<HTMLInputElement>(null);
const onFileSelected = (file: File | undefined) => {
imageElement.src = URL.createObjectURL(file);
if (emojiInputRef.current) {
emojiInputRef.current.value = '';
}
imageElement.onload = () => {
setImageMeta({
loaded: true,
width: imageElement.width,
height: imageElement.height,
});
setImageSource(imageElement);
};
// Clear the existing output, to avoid confusion
setOutputImageBlobUrl(null);
};
const onTextEntered = (event: ChangeEvent) => {
const ctx = emojiCanvas.getContext('2d');
const value = (event.target as HTMLInputElement).value;
if (!ctx || value.trim().length <= 0) {
return;
}
ctx.clearRect(0, 0, emojiCanvas.width, emojiCanvas.height);
ctx.textBaseline = 'middle';
ctx.textAlign = 'center';
ctx.font = 'bold 100px sans-serif';
ctx.fillText(` ${value} `, emojiCanvas.width / 2, emojiCanvas.height / 2);
setImageMeta({
loaded: true,
width: emojiCanvas.width,
height: emojiCanvas.height,
});
setImageSource(emojiCanvas);
// Clear the existing output, to avoid confusion
setOutputImageBlobUrl(null);
};
// TODO: Bit of a hackish way to notify the message preview when there's a new frame to render, leftover from an earlier approach
// The more React-y way would be to pass the cached image data in
const addPreviewRenderListener = useMemo(() => {
return (listener: PreviewRenderListener) => {
setPreviewRenderListeners((state) => {
return [...state, listener];
});
};
}, []);
const removePreviewRenderListener = useMemo(() => {
return (listener: PreviewRenderListener) => {
setPreviewRenderListeners((state) => {
return state.filter((l) => l !== listener);
});
};
}, []);
useEffect(() => {
const imagePrepCtx = imagePrepCanvas.getContext('2d');
const previewCanvas = previewCanvasRef.current;
const previewCanvasCtx = previewCanvas?.getContext('2d');
if (!imageSource || !imagePrepCtx || !previewCanvas || !previewCanvasCtx) {
return;
}
const imageSizing = getImageSizing(imageMeta);
const canvasWidth = imageSizing.canvasWidth;
const canvasHeight = imageSizing.canvasHeight;
imagePrepCanvas.width = canvasWidth;
imagePrepCanvas.height = canvasHeight;
prepForRender(imageSizing, imagePrepCtx, imageSource, settings);
const cachedData = generateCachedFrames(settings, imageSizing, imagePrepCanvas);
setCachedFrameData(cachedData);
if (!cachedData) {
return;
}
const previewWidth = (previewCanvas.width = cachedData.crop.right - cachedData.crop.left);
const previewHeight = (previewCanvas.height = cachedData.crop.bottom - cachedData.crop.top);
let updateLoopRef: number | undefined;
let renderIteration = lastRenderIteration;
let lastUpdatedAt = lastRenderTime || performance.now();
let lastLoopedAt = lastUpdatedAt;
const updateLoop = () => {
const now = performance.now();
const timeDiff = now - lastUpdatedAt;
const timeSinceLastLoop = now - lastLoopedAt;
// Add half the time since the last RAF call, to smooth out / factor for the next update potentially being further from the frame duration than this one
const elapsedFrames = Math.floor((timeDiff + timeSinceLastLoop / 2) / frameDuration);
renderIteration = (renderIteration + elapsedFrames) % frameCount;
lastLoopedAt = now;
if (elapsedFrames > 0) {
lastUpdatedAt = now;
renderCachedFrame(previewCanvasCtx, cachedData.frames[renderIteration], cachedData.crop);
previewRenderListeners.forEach((listener) => {
listener(previewCanvas, previewWidth, previewHeight);
});
}
updateLoopRef = window.requestAnimationFrame(updateLoop);
};
updateLoop();
return () => {
if (updateLoopRef) {
window.cancelAnimationFrame(updateLoopRef);
// Remember where in the loop we were for less janky updates while changing settings
// TODO: This barely works / still looks pretty bad
setLastRenderIteration(renderIteration);
setLastRenderTime(lastUpdatedAt);
}
};
}, [imageSource, imageMeta, settings]);
const generateGif = () => {
if (!cachedFrameData || !window.GIF) {
return;
}
const gifOutputCanvas = document.createElement('canvas');
const width = (gifOutputCanvas.width = cachedFrameData.crop.right - cachedFrameData.crop.left);
const height = (gifOutputCanvas.height = cachedFrameData.crop.bottom - cachedFrameData.crop.top);
const outputProcessingCtx = gifOutputCanvas.getContext('2d');
if (!outputProcessingCtx) {
return;
}
const gifRenderer = new window.GIF({
workers: 4,
workerScript: `${process.env.PUBLIC_URL}/vendor/gifjs/gif.worker.js`,
width,
height,
transparent: 0x00000000,
});
gifRenderer.on('finished', (blob: Blob) => {
setOutputImageBlobUrl(URL.createObjectURL(blob));
});
for (let frameNumber = 0; frameNumber < frameCount; frameNumber++) {
renderCachedFrame(outputProcessingCtx, cachedFrameData.frames[frameNumber], cachedFrameData.crop);
gifRenderer.addFrame(outputProcessingCtx, { delay: 50, copy: true });
}
gifRenderer.render();
outputElementRef.current?.scrollIntoView();
};
return (
<section className='Creator'>
<FileSelector onFileSelected={onFileSelected} />
<div className='EmojiInput'>
<label htmlFor='emoji-input' className='EmojiInput__Label'>
Or type an emoji <span className='EmojiInput__LabelHelp'>(ctrl+cmd+space on Mac)</span>
</label>
<input
className='EmojiInput__Input'
id='emoji-input'
type='text'
maxLength={4}
onChange={onTextEntered}
placeholder='😄'
/>
</div>
<div className='SettingsContainer'>
<Settings onSettingsChanged={setSettings} />
<div className='SettingsContainer__Section SettingsContainer__Section--secondary PreviewSection'>
<div className='PreviewSection__Big'>
<canvas ref={previewCanvasRef} />
</div>
<MessagePreview onReady={addPreviewRenderListener} onDestroy={removePreviewRenderListener} />
</div>
</div>
<button type='button' className='Button' onClick={generateGif}>
Generate GIF
</button>
<div className='Output' ref={outputElementRef}>
{outputImageBlobUrl && (
<>
<p>Right click / long-press on the image below, choose save, and get the party started!</p>
<img className='Output__Image' alt='' src={outputImageBlobUrl} />
<p>
Please be considerate of others when using any images from here, particularly on platforms with no option
to disable animated emoji.
</p>
</>
)}
</div>
</section>
);
} | the_stack |
import { Collection } from '@stdlib/types/object';
import dispatch = require( './index' );
// FUNCTIONS //
/**
* Add-on function.
*
* @param N - number of indexed elements
* @param dtypeX - `x` data type (enumeration constant)
* @param x - input array
* @param strideX - `x` stride length
* @param dtypeY - `y` data type (enumeration constant)
* @param y - input array
* @param strideY - `y` stride length
* @param dtypeZ - `z` data type (enumeration constant)
* @param z - output array
* @param strideZ - `z` stride length
*/
function addon( N: number, dtypeX: number, x: Collection, strideX: number, dtypeY: number, y: Collection, strideY: number, dtypeZ: number, z: Collection, strideZ: number ): void { // tslint:disable-line:max-line-length
let i;
if ( dtypeX !== dtypeY || dtypeY !== dtypeZ ) {
throw new Error( 'beep' );
}
for ( i = 0; i < N; i += 1 ) {
z[ i * strideZ ] = x[ i * strideX ] + y[ i * strideY ]; // tslint:disable-line:restrict-plus-operands no-unsafe-any
}
}
/**
* Fallback function.
*
* @param N - number of indexed elements
* @param dtypeX - `x` data type
* @param x - input array
* @param strideX - `x` stride length
* @param dtypeY - `y` data type
* @param y - input array
* @param strideY - `y` stride length
* @param dtypeZ - `z` data type
* @param z - output array
* @param strideZ - `z` stride length
*/
function fallback( N: number, dtypeX: any, x: Collection, strideX: number, dtypeY: any, y: Collection, strideY: number, dtypeZ: number, z: Collection, strideZ: number ): void { // tslint:disable-line:max-line-length
let i;
if ( dtypeX !== dtypeY || dtypeY !== dtypeZ ) {
throw new Error( 'beep' );
}
for ( i = 0; i < N; i += 1 ) {
z[ i * strideZ ] = x[ i * strideX ] + y[ i * strideY ]; // tslint:disable-line:restrict-plus-operands no-unsafe-any
}
}
/**
* Fallback function with alternative indexing semantics.
*
* @param N - number of indexed elements
* @param dtypeX - `x` data type
* @param x - input array
* @param strideX - `x` stride length
* @param offsetX - starting `x` index
* @param dtypeY - `y` data type
* @param y - input array
* @param strideY - `y` stride length
* @param offsetY - starting `y` index
* @param dtypeZ - `z` data type
* @param z - output array
* @param strideZ - `z` stride length
* @param offsetZ - starting `z` index
*/
function fallbackWithOffsets( N: number, dtypeX: any, x: Collection, strideX: number, offsetX: number, dtypeY: any, y: Collection, strideY: number, offsetY: number, dtypeZ: any, z: Collection, strideZ: number, offsetZ: number ): void { // tslint:disable-line:max-line-length
let i;
if ( dtypeX !== dtypeY || dtypeY !== dtypeZ ) {
throw new Error( 'beep' );
}
for ( i = 0; i < N; i += 1 ) {
z[ offsetZ + ( i * strideZ ) ] = x[ offsetX + ( i * strideX ) ] + y[ offsetY + ( i * strideY ) ]; // tslint:disable-line:max-line-length restrict-plus-operands no-unsafe-any
}
}
// TESTS //
// The function returns a dispatch function...
{
dispatch( addon, fallback ); // $ExpectType Dispatcher
}
// The compiler throws an error if not provided a first argument which is an add-on function...
{
dispatch( '10', fallback ); // $ExpectError
dispatch( 10, fallback ); // $ExpectError
dispatch( true, fallback ); // $ExpectError
dispatch( false, fallback ); // $ExpectError
dispatch( null, fallback ); // $ExpectError
dispatch( undefined, fallback ); // $ExpectError
dispatch( [], fallback ); // $ExpectError
dispatch( {}, fallback ); // $ExpectError
dispatch( ( x: string ): string => x, fallback ); // $ExpectError
}
// The compiler throws an error if not provided a second argument which is a fallback function...
{
dispatch( addon, '10' ); // $ExpectError
dispatch( addon, 10 ); // $ExpectError
dispatch( addon, true ); // $ExpectError
dispatch( addon, false ); // $ExpectError
dispatch( addon, null ); // $ExpectError
dispatch( addon, undefined ); // $ExpectError
dispatch( addon, [] ); // $ExpectError
dispatch( addon, {} ); // $ExpectError
dispatch( addon, ( x: string ): string => x ); // $ExpectError
}
// The returned function returns a collection...
{
const x = new Float64Array( 10 );
const y = new Float64Array( x.length );
const z = new Float64Array( x.length );
const f = dispatch( addon, fallback );
f( x.length, 'float64', x, 1, 'float64', y, 1, 'float64', z, 1 ); // $ExpectType Collection
}
// The compiler throws an error if the returned function is not provided a first argument which is a number...
{
const x = new Float64Array( 10 );
const y = new Float64Array( x.length );
const z = new Float64Array( x.length );
const f = dispatch( addon, fallback );
f( '10', 'float64', x, 1, 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
f( true, 'float64', x, 1, 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
f( false, 'float64', x, 1, 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
f( null, 'float64', x, 1, 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
f( undefined, 'float64', x, 1, 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
f( [], 'float64', x, 1, 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
f( {}, 'float64', x, 1, 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
f( ( x: number ): number => x, 'float64', x, 1, 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
}
// The compiler throws an error if the returned function is not provided a third argument which is a collection...
{
const x = new Float64Array( 10 );
const y = new Float64Array( x.length );
const z = new Float64Array( x.length );
const f = dispatch( addon, fallback );
f( x.length, 'float64', true, 1, 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
f( x.length, 'float64', false, 1, 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
f( x.length, 'float64', null, 1, 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
f( x.length, 'float64', undefined, 1, 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
f( x.length, 'float64', {}, 1, 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
}
// The compiler throws an error if the returned function is not provided a fourth argument which is a number...
{
const x = new Float64Array( 10 );
const y = new Float64Array( x.length );
const z = new Float64Array( x.length );
const f = dispatch( addon, fallback );
f( x.length, 'float64', x, '10', 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
f( x.length, 'float64', x, true, 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
f( x.length, 'float64', x, false, 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
f( x.length, 'float64', x, null, 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
f( x.length, 'float64', x, undefined, 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
f( x.length, 'float64', x, [], 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
f( x.length, 'float64', x, {}, 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
f( x.length, 'float64', x, ( x: number ): number => x, 'float64', y, 1, 'float64', z, 1 ); // $ExpectError
}
// The compiler throws an error if the returned function is not provided a sixth argument which is a collection...
{
const x = new Float64Array( 10 );
const y = new Float64Array( x.length );
const z = new Float64Array( x.length );
const f = dispatch( addon, fallback );
f( y.length, 'float64', x, 1, 'float64', true, 1, 'float64', z, 1 ); // $ExpectError
f( y.length, 'float64', x, 1, 'float64', false, 1, 'float64', z, 1 ); // $ExpectError
f( y.length, 'float64', x, 1, 'float64', null, 1, 'float64', z, 1 ); // $ExpectError
f( y.length, 'float64', x, 1, 'float64', undefined, 1, 'float64', z, 1 ); // $ExpectError
f( y.length, 'float64', x, 1, 'float64', {}, 1, 'float64', z, 1 ); // $ExpectError
}
// The compiler throws an error if the returned function is not provided a seventh argument which is a number...
{
const x = new Float64Array( 10 );
const y = new Float64Array( x.length );
const z = new Float64Array( x.length );
const f = dispatch( addon, fallback );
f( x.length, 'float64', x, 1, 'float64', y, '10', 'float64', z, 1 ); // $ExpectError
f( x.length, 'float64', x, 1, 'float64', y, true, 'float64', z, 1 ); // $ExpectError
f( x.length, 'float64', x, 1, 'float64', y, false, 'float64', z, 1 ); // $ExpectError
f( x.length, 'float64', x, 1, 'float64', y, null, 'float64', z, 1 ); // $ExpectError
f( x.length, 'float64', x, 1, 'float64', y, undefined, 'float64', z, 1 ); // $ExpectError
f( x.length, 'float64', x, 1, 'float64', y, [], 'float64', z, 1 ); // $ExpectError
f( x.length, 'float64', x, 1, 'float64', y, {}, 'float64', z, 1 ); // $ExpectError
f( x.length, 'float64', x, 1, 'float64', y, ( x: number ): number => x, 'float64', z, 1 ); // $ExpectError
}
// The compiler throws an error if the returned function is not provided a ninth argument which is a collection...
{
const x = new Float64Array( 10 );
const y = new Float64Array( x.length );
const z = new Float64Array( x.length );
const f = dispatch( addon, fallback );
f( z.length, 'float64', x, 1, 'float64', y, 1, 'float64', true, 1 ); // $ExpectError
f( z.length, 'float64', x, 1, 'float64', y, 1, 'float64', false, 1 ); // $ExpectError
f( z.length, 'float64', x, 1, 'float64', y, 1, 'float64', null, 1 ); // $ExpectError
f( z.length, 'float64', x, 1, 'float64', y, 1, 'float64', undefined, 1 ); // $ExpectError
f( z.length, 'float64', x, 1, 'float64', y, 1, 'float64', {}, 1 ); // $ExpectError
}
// The compiler throws an error if the returned function is not provided a tenth argument which is a number...
{
const x = new Float64Array( 10 );
const y = new Float64Array( x.length );
const z = new Float64Array( x.length );
const f = dispatch( addon, fallback );
f( x.length, 'float64', x, 1, 'float64', y, 1, 'float64', z, '10' ); // $ExpectError
f( x.length, 'float64', x, 1, 'float64', y, 1, 'float64', z, true ); // $ExpectError
f( x.length, 'float64', x, 1, 'float64', y, 1, 'float64', z, false ); // $ExpectError
f( x.length, 'float64', x, 1, 'float64', y, 1, 'float64', z, null ); // $ExpectError
f( x.length, 'float64', x, 1, 'float64', y, 1, 'float64', z, undefined ); // $ExpectError
f( x.length, 'float64', x, 1, 'float64', y, 1, 'float64', z, [] ); // $ExpectError
f( x.length, 'float64', x, 1, 'float64', y, 1, 'float64', z, {} ); // $ExpectError
f( x.length, 'float64', x, 1, 'float64', y, 1, 'float64', z, ( x: number ): number => x ); // $ExpectError
}
// Attached to the main export is an `ndarray` method which returns a dispatch function...
{
dispatch.ndarray( addon, fallbackWithOffsets ); // $ExpectType DispatcherWithOffsets
}
// The compiler throws an error if the `ndarray` method is not provided a first argument which is an add-on function...
{
dispatch.ndarray( '10', fallbackWithOffsets ); // $ExpectError
dispatch.ndarray( 10, fallbackWithOffsets ); // $ExpectError
dispatch.ndarray( true, fallbackWithOffsets ); // $ExpectError
dispatch.ndarray( false, fallbackWithOffsets ); // $ExpectError
dispatch.ndarray( null, fallbackWithOffsets ); // $ExpectError
dispatch.ndarray( undefined, fallbackWithOffsets ); // $ExpectError
dispatch.ndarray( [], fallbackWithOffsets ); // $ExpectError
dispatch.ndarray( {}, fallbackWithOffsets ); // $ExpectError
dispatch.ndarray( ( x: string ): string => x, fallbackWithOffsets ); // $ExpectError
}
// The compiler throws an error if the `ndarray` method is not provided a second argument which is a fallback function...
{
dispatch.ndarray( addon, '10' ); // $ExpectError
dispatch.ndarray( addon, 10 ); // $ExpectError
dispatch.ndarray( addon, true ); // $ExpectError
dispatch.ndarray( addon, false ); // $ExpectError
dispatch.ndarray( addon, null ); // $ExpectError
dispatch.ndarray( addon, undefined ); // $ExpectError
dispatch.ndarray( addon, [] ); // $ExpectError
dispatch.ndarray( addon, {} ); // $ExpectError
dispatch.ndarray( addon, ( x: string ): string => x ); // $ExpectError
}
// The `ndarray` method returns a function which returns a collection...
{
const x = new Float64Array( 10 );
const y = new Float64Array( x.length );
const z = new Float64Array( x.length );
const f = dispatch.ndarray( addon, fallbackWithOffsets );
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectType Collection
}
// The compiler throws an error if the returned function is not provided a first argument which is a number...
{
const x = new Float64Array( 10 );
const y = new Float64Array( x.length );
const z = new Float64Array( x.length );
const f = dispatch.ndarray( addon, fallbackWithOffsets );
f( '10', 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( true, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( false, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( null, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( undefined, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( [], 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( {}, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( ( x: number ): number => x, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the returned function is not provided a third argument which is a collection...
{
const x = new Float64Array( 10 );
const y = new Float64Array( x.length );
const z = new Float64Array( x.length );
const f = dispatch.ndarray( addon, fallbackWithOffsets );
f( x.length, 'float64', true, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', false, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', null, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', undefined, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', {}, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the returned function is not provided a fourth argument which is a number...
{
const x = new Float64Array( 10 );
const y = new Float64Array( x.length );
const z = new Float64Array( x.length );
const f = dispatch.ndarray( addon, fallbackWithOffsets );
f( x.length, 'float64', x, '10', 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, true, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, false, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, null, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, undefined, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, [], 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, {}, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, ( x: number ): number => x, 0, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the returned function is not provided a fifth argument which is a number...
{
const x = new Float64Array( 10 );
const y = new Float64Array( x.length );
const z = new Float64Array( x.length );
const f = dispatch.ndarray( addon, fallbackWithOffsets );
f( x.length, 'float64', x, 1, '10', 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, true, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, false, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, null, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, undefined, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, [], 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, {}, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, ( x: number ): number => x, 'float64', y, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the returned function is not provided a seventh argument which is a collection...
{
const x = new Float64Array( 10 );
const y = new Float64Array( x.length );
const z = new Float64Array( x.length );
const f = dispatch.ndarray( addon, fallbackWithOffsets );
f( y.length, 'float64', x, 1, 0, 'float64', true, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( y.length, 'float64', x, 1, 0, 'float64', false, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( y.length, 'float64', x, 1, 0, 'float64', null, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( y.length, 'float64', x, 1, 0, 'float64', undefined, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
f( y.length, 'float64', x, 1, 0, 'float64', {}, 1, 0, 'float64', z, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the returned function is not provided an eighth argument which is a number...
{
const x = new Float64Array( 10 );
const y = new Float64Array( x.length );
const z = new Float64Array( x.length );
const f = dispatch.ndarray( addon, fallbackWithOffsets );
f( x.length, 'float64', x, 1, 0, 'float64', y, '10', 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, true, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, false, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, null, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, undefined, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, [], 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, {}, 0, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, ( x: number ): number => x, 0, 'float64', z, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the returned function is not provided a ninth argument which is a number...
{
const x = new Float64Array( 10 );
const y = new Float64Array( x.length );
const z = new Float64Array( x.length );
const f = dispatch.ndarray( addon, fallbackWithOffsets );
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, '10', 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, true, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, false, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, null, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, undefined, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, [], 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, {}, 'float64', z, 1, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, ( x: number ): number => x, 'float64', z, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the returned function is not provided an eleventh argument which is a collection...
{
const x = new Float64Array( 10 );
const y = new Float64Array( x.length );
const z = new Float64Array( x.length );
const f = dispatch.ndarray( addon, fallbackWithOffsets );
f( z.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', true, 1, 0 ); // $ExpectError
f( z.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', false, 1, 0 ); // $ExpectError
f( z.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', null, 1, 0 ); // $ExpectError
f( z.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', undefined, 1, 0 ); // $ExpectError
f( z.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', {}, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the returned function is not provided a twelfth argument which is a number...
{
const x = new Float64Array( 10 );
const y = new Float64Array( x.length );
const z = new Float64Array( x.length );
const f = dispatch.ndarray( addon, fallbackWithOffsets );
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, '10', 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, true, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, false, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, null, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, undefined, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, [], 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, {}, 0 ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, ( x: number ): number => x, 0 ); // $ExpectError
}
// The compiler throws an error if the returned function is not provided a thirteenth argument which is a number...
{
const x = new Float64Array( 10 );
const y = new Float64Array( x.length );
const z = new Float64Array( x.length );
const f = dispatch.ndarray( addon, fallbackWithOffsets );
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, '10' ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, true ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, false ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, null ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, undefined ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, [] ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, {} ); // $ExpectError
f( x.length, 'float64', x, 1, 0, 'float64', y, 1, 0, 'float64', z, 1, ( x: number ): number => x ); // $ExpectError
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [worklink](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonworklink.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Worklink extends PolicyStatement {
public servicePrefix = 'worklink';
/**
* Statement provider for service [worklink](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonworklink.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to associate a domain with an Amazon WorkLink fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/worklink/latest/api/API_AssociateDomain.html
*/
public toAssociateDomain() {
return this.to('AssociateDomain');
}
/**
* Grants permission to associate a website authorization provider with an Amazon WorkLink fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/worklink/latest/api/API_AssociateWebsiteAuthorizationProvider.html
*/
public toAssociateWebsiteAuthorizationProvider() {
return this.to('AssociateWebsiteAuthorizationProvider');
}
/**
* Grants permission to associate a website certificate authority with an Amazon WorkLink fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/worklink/latest/api/API_AssociateWebsiteCertificateAuthority.html
*/
public toAssociateWebsiteCertificateAuthority() {
return this.to('AssociateWebsiteCertificateAuthority');
}
/**
* Grants permission to create an Amazon WorkLink fleet
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/worklink/latest/api/API_CreateFleet.html
*/
public toCreateFleet() {
return this.to('CreateFleet');
}
/**
* Grants permission to delete an Amazon WorkLink fleet
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/worklink/latest/api/API_DeleteFleet.html
*/
public toDeleteFleet() {
return this.to('DeleteFleet');
}
/**
* Grants permission to describe the audit stream configuration for an Amazon WorkLink fleet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/worklink/latest/api/API_DescribeAuditStreamConfiguration.html
*/
public toDescribeAuditStreamConfiguration() {
return this.to('DescribeAuditStreamConfiguration');
}
/**
* Grants permission to describe the company network configuration for an Amazon WorkLink fleet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/worklink/latest/api/API_DescribeCompanyNetworkConfiguration.html
*/
public toDescribeCompanyNetworkConfiguration() {
return this.to('DescribeCompanyNetworkConfiguration');
}
/**
* Grants permission to describe details of a device associated with an Amazon WorkLink fleet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/worklink/latest/api/API_DescribeDevice.html
*/
public toDescribeDevice() {
return this.to('DescribeDevice');
}
/**
* Grants permission to describe the device policy configuration for an Amazon WorkLink fleet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/worklink/latest/api/API_DescribeDevicePolicyConfiguration.html
*/
public toDescribeDevicePolicyConfiguration() {
return this.to('DescribeDevicePolicyConfiguration');
}
/**
* Grants permission to describe details about a domain associated with an Amazon WorkLink fleet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/worklink/latest/api/API_DescribeDomain.html
*/
public toDescribeDomain() {
return this.to('DescribeDomain');
}
/**
* Grants permission to describe metadata of an Amazon WorkLink fleet
*
* Access Level: Read
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/worklink/latest/api/API_DescribeFleetMetadata.html
*/
public toDescribeFleetMetadata() {
return this.to('DescribeFleetMetadata');
}
/**
* Grants permission to describe the identity provider configuration for an Amazon WorkLink fleet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/worklink/latest/api/API_DescribeIdentityProviderConfiguration.html
*/
public toDescribeIdentityProviderConfiguration() {
return this.to('DescribeIdentityProviderConfiguration');
}
/**
* Grants permission to describe a website certificate authority associated with an Amazon WorkLink fleet
*
* Access Level: Read
*
* https://docs.aws.amazon.com/worklink/latest/api/API_DescribeWebsiteCertificateAuthority.html
*/
public toDescribeWebsiteCertificateAuthority() {
return this.to('DescribeWebsiteCertificateAuthority');
}
/**
* Grants permission to disassociate a domain from an Amazon WorkLink fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/worklink/latest/api/API_DisassociateDomain.html
*/
public toDisassociateDomain() {
return this.to('DisassociateDomain');
}
/**
* Grants permission to disassociate a website authorization provider from an Amazon WorkLink fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/worklink/latest/api/API_DisassociateWebsiteAuthorizationProvider.html
*/
public toDisassociateWebsiteAuthorizationProvider() {
return this.to('DisassociateWebsiteAuthorizationProvider');
}
/**
* Grants permission to disassociate a website certificate authority from an Amazon WorkLink fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/worklink/latest/api/API_DisassociateWebsiteCertificateAuthority.html
*/
public toDisassociateWebsiteCertificateAuthority() {
return this.to('DisassociateWebsiteCertificateAuthority');
}
/**
* Grants permission to list the devices associated with an Amazon WorkLink fleet
*
* Access Level: List
*
* https://docs.aws.amazon.com/worklink/latest/api/API_ListDevices.html
*/
public toListDevices() {
return this.to('ListDevices');
}
/**
* Grants permission to list the associated domains for an Amazon WorkLink fleet
*
* Access Level: List
*
* https://docs.aws.amazon.com/worklink/latest/api/API_ListDomains.html
*/
public toListDomains() {
return this.to('ListDomains');
}
/**
* Grants permission to list the Amazon WorkLink fleets associated with the account
*
* Access Level: List
*
* https://docs.aws.amazon.com/worklink/latest/api/API_ListFleets.html
*/
public toListFleets() {
return this.to('ListFleets');
}
/**
* Grants permission to list tags for a resource
*
* Access Level: Read
*
* https://docs.aws.amazon.com/worklink/latest/api/API_ListTagsForResource.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to list the website authorization providers for an Amazon WorkLink fleet
*
* Access Level: List
*
* https://docs.aws.amazon.com/worklink/latest/api/API_ListWebsiteAuthorizationProviders.html
*/
public toListWebsiteAuthorizationProviders() {
return this.to('ListWebsiteAuthorizationProviders');
}
/**
* Grants permission to list the website certificate authorities associated with an Amazon WorkLink fleet
*
* Access Level: List
*
* https://docs.aws.amazon.com/worklink/latest/api/API_ListWebsiteCertificateAuthorities.html
*/
public toListWebsiteCertificateAuthorities() {
return this.to('ListWebsiteCertificateAuthorities');
}
/**
* Grants permission to restore access to a domain associated with an Amazon WorkLink fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/worklink/latest/api/API_RestoreDomainAccess.html
*/
public toRestoreDomainAccess() {
return this.to('RestoreDomainAccess');
}
/**
* Grants permission to revoke access to a domain associated with an Amazon WorkLink fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/worklink/latest/api/API_RevokeDomainAccess.html
*/
public toRevokeDomainAccess() {
return this.to('RevokeDomainAccess');
}
/**
* Grants permission to list devices for an Amazon WorkLink fleet
*
* Access Level: List
*
* https://docs.aws.amazon.com/worklink/latest/ag/manage-devices.html
*/
public toSearchEntity() {
return this.to('SearchEntity');
}
/**
* Grants permission to sign out a user from an Amazon WorkLink fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/worklink/latest/api/API_SignOutUser.html
*/
public toSignOutUser() {
return this.to('SignOutUser');
}
/**
* Grants permission to add one or more tags to a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/worklink/latest/api/API_TagResource.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to remove one or more tags from a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/worklink/latest/api/API_UntagResource.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to update the audit stream configuration for an Amazon WorkLink fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/worklink/latest/api/API_UpdateAuditStreamConfiguration.html
*/
public toUpdateAuditStreamConfiguration() {
return this.to('UpdateAuditStreamConfiguration');
}
/**
* Grants permission to update the company network configuration for an Amazon WorkLink fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/worklink/latest/api/API_UpdateCompanyNetworkConfiguration.html
*/
public toUpdateCompanyNetworkConfiguration() {
return this.to('UpdateCompanyNetworkConfiguration');
}
/**
* Grants permission to update the device policy configuration for an Amazon WorkLink fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/worklink/latest/api/API_UpdateDevicePolicyConfiguration.html
*/
public toUpdateDevicePolicyConfiguration() {
return this.to('UpdateDevicePolicyConfiguration');
}
/**
* Grants permission to update the metadata for a domain associated with an Amazon WorkLink fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/worklink/latest/api/API_UpdateDomainMetadata.html
*/
public toUpdateDomainMetadata() {
return this.to('UpdateDomainMetadata');
}
/**
* Grants permission to update the metadata of an Amazon WorkLink fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/worklink/latest/api/API_UpdateFleetMetadata.html
*/
public toUpdateFleetMetadata() {
return this.to('UpdateFleetMetadata');
}
/**
* Grants permission to update the identity provider configuration for an Amazon WorkLink fleet
*
* Access Level: Write
*
* https://docs.aws.amazon.com/worklink/latest/api/API_UpdateIdentityProviderConfiguration.html
*/
public toUpdateIdentityProviderConfiguration() {
return this.to('UpdateIdentityProviderConfiguration');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"AssociateDomain",
"AssociateWebsiteAuthorizationProvider",
"AssociateWebsiteCertificateAuthority",
"CreateFleet",
"DeleteFleet",
"DisassociateDomain",
"DisassociateWebsiteAuthorizationProvider",
"DisassociateWebsiteCertificateAuthority",
"RestoreDomainAccess",
"RevokeDomainAccess",
"SignOutUser",
"UpdateAuditStreamConfiguration",
"UpdateCompanyNetworkConfiguration",
"UpdateDevicePolicyConfiguration",
"UpdateDomainMetadata",
"UpdateFleetMetadata",
"UpdateIdentityProviderConfiguration"
],
"Read": [
"DescribeAuditStreamConfiguration",
"DescribeCompanyNetworkConfiguration",
"DescribeDevice",
"DescribeDevicePolicyConfiguration",
"DescribeDomain",
"DescribeFleetMetadata",
"DescribeIdentityProviderConfiguration",
"DescribeWebsiteCertificateAuthority",
"ListTagsForResource"
],
"List": [
"ListDevices",
"ListDomains",
"ListFleets",
"ListWebsiteAuthorizationProviders",
"ListWebsiteCertificateAuthorities",
"SearchEntity"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type fleet to the statement
*
* https://docs.aws.amazon.com/worklink/latest/api/API_CreateFleet.html
*
* @param fleetName - Identifier for the fleetName.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onFleet(fleetName: string, account?: string, partition?: string) {
var arn = 'arn:${Partition}:worklink::${Account}:fleet/${FleetName}';
arn = arn.replace('${FleetName}', fleetName);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import BigNumber from 'bignumber.js';
import _ from 'lodash';
import { address } from '../src';
import { INTEGERS } from '../src/lib/Constants';
import {
Price,
TxResult,
BigNumberable,
} from '../src/lib/types';
import { expectThrow, expect, expectAddressesEqual, expectBN } from './helpers/Expect';
import { expectBalances, mintAndDeposit } from './helpers/balances';
import { mineAvgBlock } from './helpers/EVM';
import initializePerpetual from './helpers/initializePerpetual';
import { ITestContext, perpetualDescribe } from './helpers/perpetualDescribe';
import { buy } from './helpers/trade';
// Note: initialPrice * positionSize = initialMargin * 2
const initialMargin = new BigNumber(500);
const positionSize = new BigNumber(10);
const initialPrice = new Price(100);
const longUndercollateralizedPrice = new Price(54.9);
const longUnderwaterPrice = new Price(49.9);
const shortUndercollateralizedPrice = new Price(136.5);
const shortUnderwaterPrice = new Price(150.1);
let admin: address;
let long: address;
let short: address;
let otherAccountA: address;
let otherAccountB: address;
let otherAccountC: address;
async function init(ctx: ITestContext): Promise<void> {
await initializePerpetual(ctx);
admin = ctx.accounts[0];
long = ctx.accounts[2];
short = ctx.accounts[3];
otherAccountA = ctx.accounts[4];
otherAccountB = ctx.accounts[5];
otherAccountC = ctx.accounts[6];
// Set up initial balances:
// +---------+--------+----------+-------------------+
// | account | margin | position | collateralization |
// |---------+--------+----------+-------------------|
// | long | -500 | 10 | 200% |
// | short | 1500 | -10 | 150% |
// +---------+--------+----------+-------------------+
await Promise.all([
ctx.perpetual.testing.oracle.setPrice(initialPrice),
mintAndDeposit(ctx, long, initialMargin),
mintAndDeposit(ctx, short, initialMargin),
]);
const txResult = await buy(ctx, long, short, positionSize, initialMargin.times(2));
// Sanity check balances.
await expectBalances(
ctx,
txResult,
[long, short],
[-500, 1500],
[10, -10],
);
}
perpetualDescribe('P1FinalSettlement', init, (ctx: ITestContext) => {
describe('noFinalSettlement', () => {
beforeEach(async () => {
await ctx.perpetual.admin.enableFinalSettlement(initialPrice, initialPrice, { from: admin });
ctx.perpetual.contracts.resetGasUsed();
});
it('prevents deposits during final settlement', async () => {
await expectThrow(
ctx.perpetual.margin.deposit(long, INTEGERS.ONE),
'Not permitted during final settlement',
);
});
it('prevents withdrawals during final settlement', async () => {
await expectThrow(
ctx.perpetual.margin.withdraw(long, long, INTEGERS.ONE),
'Not permitted during final settlement',
);
});
it('prevents trades during final settlement', async () => {
await expectThrow(
buy(ctx, long, short, INTEGERS.ONE, INTEGERS.ONE),
'Not permitted during final settlement',
);
});
});
describe('onlyFinalSettlement', () => {
it('prevents calls if final settlement is not enabled', async () => {
await expectThrow(
ctx.perpetual.finalSettlement.withdrawFinalSettlement({ from: long }),
'Only permitted during final settlement',
);
});
});
describe('withdrawFinalSettlement()', () => {
/**
* Handle withdrawals for simple cases where _/_ notation represents margin/position.
*/
describe('simple cases', () => {
it('settles a 0/0 balance', async () => {
await enableSettlement(initialPrice);
await expectWithdraw(otherAccountA, INTEGERS.ZERO, false);
});
it('settles a 0/+ balance', async () => {
await buy(ctx, otherAccountA, long, INTEGERS.ONE, INTEGERS.ZERO);
await enableSettlement(initialPrice);
await expectWithdraw(otherAccountA, initialPrice.value);
});
it('settles a -/+ well-collateralized balance', async () => {
await enableSettlement(initialPrice);
await expectWithdraw(long, initialMargin);
});
it('settles a -/+ undercollateralized balance', async () => {
await enableSettlement(longUndercollateralizedPrice);
await expectWithdraw(long, '49');
});
it('settles a -/+ underwater balance', async () => {
await enableSettlement(longUnderwaterPrice);
await expectWithdraw(long, -1);
});
it('settles a +/0 balance', async () => {
await mintAndDeposit(ctx, otherAccountA, INTEGERS.ONE);
await enableSettlement(initialPrice);
await expectWithdraw(otherAccountA, INTEGERS.ONE, false);
});
it('settles a +/- well-collateralized balance', async () => {
await enableSettlement(initialPrice);
await expectWithdraw(short, initialMargin);
});
it('settles a +/- undercollateralized balance', async () => {
await enableSettlement(shortUndercollateralizedPrice);
await expectWithdraw(short, '135');
});
it('settles a +/- underwater balance', async () => {
await enableSettlement(shortUnderwaterPrice);
await expectWithdraw(short, -1);
});
it('settles a +/+ balance', async () => {
await mintAndDeposit(ctx, long, initialMargin.times(2));
await enableSettlement(initialPrice);
await expectWithdraw(long, initialMargin.times(3));
});
});
/**
* Edge cases and other non-standard situations.
*/
describe('other cases', () => {
it('does not allow withdrawing a non-zero balance more than once (long)', async () => {
await enableSettlement(initialPrice);
await expectWithdraw(long, initialMargin);
await expectWithdraw(long, INTEGERS.ZERO, false);
await expectWithdraw(long, INTEGERS.ZERO, false);
});
it('does not allow withdrawing a non-zero balance more than once (short)', async () => {
await enableSettlement(initialPrice);
await expectWithdraw(short, initialMargin);
await expectWithdraw(short, INTEGERS.ZERO, false);
await expectWithdraw(short, INTEGERS.ZERO, false);
});
it('avoids insolvency resulting from rounding errors', async () => {
// Set up balances:
// +---------------+--------+----------+
// | account | margin | position |
// |---------------+--------+----------+
// | otherAccountA | 2 | -1 |
// | otherAccountB | 2 | -1 |
// | otherAccountC | -1 | 2 |
// +---------------+--------+----------+
await Promise.all([
ctx.perpetual.testing.oracle.setPrice(new Price(1)),
mintAndDeposit(ctx, otherAccountA, 2),
mintAndDeposit(ctx, otherAccountB, 1),
]);
await buy(ctx, otherAccountC, otherAccountA, 1, 0);
const txResult = await buy(ctx, otherAccountC, otherAccountB, 1, 1);
// Check balances.
await expectBalances(
ctx,
txResult,
[otherAccountA, otherAccountB, otherAccountC],
[2, 2, -1],
[-1, -1, 2],
false,
);
// If positive and negative value are rounded separately, this could result in accounts
// A and B each withdrawing 1 token, rendering the contract insolvent before C can withdraw.
await enableSettlement(new Price(1.5));
await expectWithdraw(otherAccountA, 0);
await expectWithdraw(otherAccountB, 0);
await expectWithdraw(otherAccountC, 2);
});
describe('when the contract is insolvent due to underwater accounts', async () => {
beforeEach(async () => {
// Set up initial balances (settlement price of 40):
// +---------------+--------+----------+-------------------+---------------+
// | account | margin | position | collateralization | account value |
// |---------------+--------+----------+-------------------|---------------|
// | long | -2500 | 30 | 48% | -1300 |
// | short | 1500 | -10 | 375% | 1100 |
// | otherAccountA | 1500 | -10 | 375% | 1100 |
// | otherAccountB | 1500 | -10 | 375% | 1100 |
// +---------------+--------+----------+-------------------+---------------+
//
// Both otherAccountA and otherAccountB are short positions.
await Promise.all([
mintAndDeposit(ctx, otherAccountA, initialMargin),
mintAndDeposit(ctx, otherAccountB, initialMargin),
]);
await Promise.all([
await buy(ctx, long, otherAccountA, positionSize, initialMargin.times(2)),
await buy(ctx, long, otherAccountB, positionSize, initialMargin.times(2)),
]);
ctx.perpetual.contracts.resetGasUsed();
});
it('will return partial balances, as long as funds remain', async () => {
// Enable settlement at price where long is underwater.
await enableSettlement(new Price(40));
// Some short positions can withdraw funds.
await expectWithdraw(long, -1300);
await expectWithdraw(short, 1100);
await expectWithdraw(otherAccountA, 900);
await expectWithdraw(otherAccountB, 0);
// Check that the balances reflect the amount owed.
await expectBalances(
ctx,
null,
[long, short, otherAccountA, otherAccountB],
[-2500, 0, 200, 1100],
[30, 0, 0, 0],
false,
false,
);
});
it('can be bailed out, allowing all balances to be withdrawn', async () => {
await enableSettlement(new Price(40));
// Some short positions can withdraw funds.
await expectWithdraw(long, -1300);
await expectWithdraw(short, 1100);
await expectWithdraw(otherAccountA, 900);
await expectWithdraw(otherAccountB, 0);
// Admin bails out the contract.
const underwaterAmount = new BigNumber(1300);
await ctx.perpetual.testing.token.mint(
ctx.perpetual.contracts.testToken.options.address,
admin,
underwaterAmount,
);
await ctx.perpetual.testing.token.transfer(
ctx.perpetual.contracts.testToken.options.address,
admin,
ctx.perpetual.contracts.perpetualProxy.options.address,
underwaterAmount,
);
// Short positions can withdraw the rest of their account value.
await expectWithdraw(long, -1300, false);
await expectWithdraw(short, 0, false);
await expectWithdraw(otherAccountA, 200, false);
await expectWithdraw(otherAccountB, 1100, false);
// Check balances.
await expectBalances(
ctx,
null,
[long, short, otherAccountA, otherAccountB],
[-2500, 0, 0, 0],
[30, 0, 0, 0],
false,
false,
);
});
it('allows negative margin account to withdraw partial balances', async () => {
// Enable settlement at price where shorts are underwater.
//
// Account value:
// - long: 2300
// - each short: -100
await enableSettlement(new Price(160));
// Long position can partially withdraw.
await expectWithdraw(long, 2000);
// Admin bails out the contract.
const underwaterAmount = new BigNumber(300);
await ctx.perpetual.testing.token.mint(
ctx.perpetual.contracts.testToken.options.address,
admin,
underwaterAmount,
);
await ctx.perpetual.testing.token.transfer(
ctx.perpetual.contracts.testToken.options.address,
admin,
ctx.perpetual.contracts.perpetualProxy.options.address,
underwaterAmount,
);
// Long position can withdraw the rest of their account value.
await expectWithdraw(short, -100);
await expectWithdraw(long, 300, false);
await expectWithdraw(long, 0, false);
// Check balances.
await expectBalances(
ctx,
null,
[long, short, otherAccountA, otherAccountB],
[0, 1500, 1500, 1500],
[0, -10, -10, -10],
false,
false,
);
});
});
});
});
/**
* Enable final settlement at a certain price.
*/
async function enableSettlement(settlementPrice: Price): Promise<TxResult> {
await mineAvgBlock();
await ctx.perpetual.testing.oracle.setPrice(settlementPrice);
const txResult = ctx.perpetual.admin.enableFinalSettlement(
settlementPrice,
settlementPrice,
{ from: admin },
);
await mineAvgBlock();
return txResult;
}
/**
* Withdraw final settlement and check that withdrawn amount is as expected.
*
* Checks that the account's balance on the token contract is updated as expected.
*/
async function expectWithdraw(
account: address,
expectedAmount: BigNumberable,
expectSettle = true,
): Promise<void> {
const expectedAmountBN = new BigNumber(expectedAmount);
const withdrawAmount = BigNumber.max(expectedAmountBN, 0);
const balanceBefore = await ctx.perpetual.testing.token.getBalance(
ctx.perpetual.contracts.testToken.options.address,
account,
);
const txResult = await ctx.perpetual.finalSettlement.withdrawFinalSettlement({ from: account });
// Check logs length.
const logs = ctx.perpetual.logs.parseLogs(txResult);
const logsLength = (expectSettle ? 1 : 0) + (expectedAmountBN.isNegative() ? 0 : 1);
expect(logs.length).to.equal(logsLength);
// Get logs.
let logWithdraw: any;
let logSettle: any;
if (logsLength === 2) {
[logSettle, logWithdraw] = logs;
} else if (expectSettle) {
[logSettle] = logs;
} else {
[logWithdraw] = logs;
}
// Check Logs.
if (logSettle) {
expect(logSettle.name).to.equal('LogAccountSettled');
expectAddressesEqual(logSettle.args.account, account);
}
if (logWithdraw) {
expect(logWithdraw.name).to.equal('LogWithdrawFinalSettlement');
expectAddressesEqual(logWithdraw.args.account, account);
expectBN(logWithdraw.args.amount, 'final settlement amount log').to.equal(withdrawAmount);
}
// Check that token balance is updated as expected.
const balanceAfter = await ctx.perpetual.testing.token.getBalance(
ctx.perpetual.contracts.testToken.options.address,
account,
);
const balanceDiff = balanceAfter.minus(balanceBefore);
expectBN(balanceDiff, 'change in token balance').to.equal(withdrawAmount);
}
}); | the_stack |
import _ from 'lodash'
import $ from 'jquery'
import chai from 'chai'
import sinonChai from '@cypress/sinon-chai'
import $dom from '../dom'
import $utils from '../cypress/utils'
import $errUtils from '../cypress/error_utils'
import $stackUtils from '../cypress/stack_utils'
import $chaiJquery from '../cypress/chai_jquery'
import * as chaiInspect from './chai/inspect'
// all words between single quotes
const allPropertyWordsBetweenSingleQuotes = /('.*?')/g
const allBetweenFourStars = /\*\*.*\*\*/
const allNumberStrings = /'([0-9]+)'/g
const allEmptyStrings = /''/g
const allSingleQuotes = /'/g
const allEscapedSingleQuotes = /\\'/g
const allQuoteMarkers = /__quote__/g
const allWordsBetweenCurlyBraces = /(#{.+?})/g
const allQuadStars = /\*\*\*\*/g
const leadingWhitespaces = /\*\*'\s*/g
const trailingWhitespaces = /\s*'\*\*/g
const whitespace = /\s/g
const valueHasLeadingOrTrailingWhitespaces = /\*\*'\s+|\s+'\*\*/g
const imageMarkdown = /!\[.*?\]\(.*?\)/g
let assertProto = null
let matchProto = null
let lengthProto = null
let containProto = null
let existProto = null
let getMessage = null
let chaiUtils = null
let create = null
let replaceArgMessages = null
let removeOrKeepSingleQuotesBetweenStars = null
let setSpecWindowGlobals = null
let restoreAsserts = null
let overrideExpect = null
let overrideChaiAsserts = null
chai.use(sinonChai)
chai.use((chai, u) => {
chaiUtils = u
$chaiJquery(chai, chaiUtils, {
onInvalid (method, obj) {
$errUtils.throwErrByPath('chai.invalid_jquery_obj', {
args: {
assertion: method,
subject: $utils.stringifyActual(obj),
},
})
},
onError (err, method, obj, negated) {
switch (method) {
case 'visible':
if (!negated) {
// add reason hidden unless we expect the element to be hidden
const reason = $dom.getReasonIsHidden(obj)
err.message += `\n\n${reason}`
}
break
default:
break
}
// always rethrow the error!
throw err
},
})
assertProto = chai.Assertion.prototype.assert
matchProto = chai.Assertion.prototype.match
lengthProto = chai.Assertion.prototype.__methods.length.method
containProto = chai.Assertion.prototype.__methods.contain.method
existProto = Object.getOwnPropertyDescriptor(chai.Assertion.prototype, 'exist').get
const { objDisplay } = chai.util;
({ getMessage } = chai.util)
const _inspect = chai.util.inspect
const { inspect, setFormatValueHook } = chaiInspect.create(chai)
// prevent tunneling into Window objects (can throw cross-origin errors)
setFormatValueHook((ctx, val) => {
// https://github.com/cypress-io/cypress/issues/5270
// When name attribute exists in <iframe>,
// Firefox returns [object Window] but Chrome returns [object Object]
// So, we try throwing an error and check the error message.
try {
val && val.document
val && val.inspect
} catch (e) {
if (e.stack.indexOf('cross-origin') !== -1 || // chrome
e.message.indexOf('cross-origin') !== -1) { // firefox
return `[window]`
}
}
})
// remove any single quotes between our **,
// except escaped quotes, empty strings and number strings.
removeOrKeepSingleQuotesBetweenStars = (message) => {
// remove any single quotes between our **, preserving escaped quotes
// and if an empty string, put the quotes back
return message.replace(allBetweenFourStars, (match) => {
if (valueHasLeadingOrTrailingWhitespaces.test(match)) {
// Above we used \s+, but below we use \s*.
// It's because of the strings like ' love' that have empty spaces on one side only.
match = match
.replace(leadingWhitespaces, (match) => {
return match.replace(`**'`, '**__quote__')
.replace(whitespace, ' ')
})
.replace(trailingWhitespaces, (match) => {
return match.replace(`'**`, '__quote__**')
.replace(whitespace, ' ')
})
}
return match
.replace(allEscapedSingleQuotes, '__quote__') // preserve escaped quotes
.replace(allNumberStrings, '__quote__$1__quote__') // preserve number strings (e.g. '42')
.replace(allEmptyStrings, '__quote____quote__') // preserve empty strings (e.g. '')
.replace(allSingleQuotes, '')
.replace(allQuoteMarkers, '\'') // put escaped quotes back
})
}
const escapeMarkdown = (message) => {
return message.replace(imageMarkdown, '``$&``')
}
replaceArgMessages = (args, str) => {
return _.reduce(args, (memo, value, index) => {
if (_.isString(value)) {
value = value
.replace(allWordsBetweenCurlyBraces, '**$1**')
.replace(allEscapedSingleQuotes, '__quote__')
.replace(allPropertyWordsBetweenSingleQuotes, '**$1**')
// when a value has ** in it, **** are sometimes created after the process above.
// remove them with this.
.replace(allQuadStars, '**')
memo.push(value)
} else {
memo.push(value)
}
return memo
}
, [])
}
restoreAsserts = function () {
chai.util.inspect = _inspect
chai.util.getMessage = getMessage
chai.util.objDisplay = objDisplay
chai.Assertion.prototype.assert = assertProto
chai.Assertion.prototype.match = matchProto
chai.Assertion.prototype.__methods.length.method = lengthProto
chai.Assertion.prototype.__methods.contain.method = containProto
return Object.defineProperty(chai.Assertion.prototype, 'exist', { get: existProto })
}
const overrideChaiInspect = () => {
return chai.util.inspect = inspect
}
const overrideChaiObjDisplay = () => {
return chai.util.objDisplay = function (obj) {
const str = chai.util.inspect(obj)
const type = Object.prototype.toString.call(obj)
if (chai.config.truncateThreshold && (str.length >= chai.config.truncateThreshold)) {
if (type === '[object Function]') {
if (!obj.name || (obj.name === '')) {
return '[Function]'
}
return `[Function: ${obj.name}]`
}
if (type === '[object Array]') {
return `[ Array(${obj.length}) ]`
}
if (type === '[object Object]') {
const keys = Object.keys(obj)
const kstr = keys.length > 2 ? `${keys.splice(0, 2).join(', ')}, ...` : keys.join(', ')
return `{ Object (${kstr}) }`
}
return str
}
return str
}
}
overrideChaiAsserts = function (specWindow, state, assertFn) {
chai.Assertion.prototype.assert = createPatchedAssert(specWindow, state, assertFn)
const _origGetmessage = function (obj, args) {
const negate = chaiUtils.flag(obj, 'negate')
const val = chaiUtils.flag(obj, 'object')
const expected = args[3]
const actual = chaiUtils.getActual(obj, args)
let msg = (negate ? args[2] : args[1])
const flagMsg = chaiUtils.flag(obj, 'message')
if (typeof msg === 'function') {
msg = msg()
}
msg = msg || ''
msg = msg
.replace(/#\{this\}/g, () => {
return chaiUtils.objDisplay(val)
})
.replace(/#\{act\}/g, () => {
return chaiUtils.objDisplay(actual)
})
.replace(/#\{exp\}/g, () => {
return chaiUtils.objDisplay(expected)
})
return (flagMsg ? `${flagMsg}: ${msg}` : msg)
}
chaiUtils.getMessage = function (assert, args) {
const obj = assert._obj
// if we are formatting a DOM object
if ($dom.isDom(obj)) {
// replace object with our formatted one
assert._obj = $dom.stringify(obj, 'short')
}
const msg = _origGetmessage.call(this, assert, args)
// restore the real obj if we changed it
if (obj !== assert._obj) {
assert._obj = obj
}
return msg
}
chai.Assertion.overwriteMethod('match', (_super) => {
return (function (regExp) {
if (_.isRegExp(regExp) || $dom.isDom(this._obj)) {
return _super.apply(this, arguments)
}
const err = $errUtils.cypressErrByPath('chai.match_invalid_argument', { args: { regExp } })
err.retry = false
throw err
})
})
const containFn1 = (_super) => {
return (function (text) {
let obj = this._obj
if (!($dom.isElement(obj))) {
return _super.apply(this, arguments)
}
const escText = $utils.escapeQuotes(text)
const selector = `:contains('${escText}'), [type='submit'][value~='${escText}']`
// the assert checks below only work if $dom.isJquery(obj)
// https://github.com/cypress-io/cypress/issues/3549
if (!($dom.isJquery(obj))) {
obj = $(obj)
}
this.assert(
obj.is(selector) || !!obj.find(selector).length,
'expected #{this} to contain #{exp}',
'expected #{this} not to contain #{exp}',
text,
)
})
}
const containFn2 = (_super) => {
return (function () {
return _super.apply(this, arguments)
})
}
chai.Assertion.overwriteChainableMethod('contain', containFn1, containFn2)
chai.Assertion.overwriteChainableMethod('length',
(_super) => {
return (function (length) {
let obj = this._obj
if (!($dom.isJquery(obj) || $dom.isElement(obj))) {
return _super.apply(this, arguments)
}
length = $utils.normalizeNumber(length)
// filter out anything not currently in our document
if ($dom.isDetached(obj)) {
obj = (this._obj = obj.filter((index, el) => {
return $dom.isAttached(el)
}))
}
const node = obj && obj.length ? $dom.stringify(obj, 'short') : obj.selector
// if our length assertion fails we need to check to
// ensure that the length argument is a finite number
// because if its not, we need to bail on retrying
try {
return this.assert(
obj.length === length,
`expected '${node}' to have a length of \#{exp} but got \#{act}`,
`expected '${node}' to not have a length of \#{act}`,
length,
obj.length,
)
} catch (e1) {
e1.node = node
e1.negated = chaiUtils.flag(this, 'negate')
e1.type = 'length'
if (_.isFinite(length)) {
const getLongLengthMessage = function (len1, len2) {
if (len1 > len2) {
return `Too many elements found. Found '${len1}', expected '${len2}'.`
}
return `Not enough elements found. Found '${len1}', expected '${len2}'.`
}
// if the user has specified a custom message,
// for example: expect($subject, 'Should have length').to.have.length(1)
// prefer that over our message
const message = chaiUtils.flag(this, 'message') ? e1.message : getLongLengthMessage(obj.length, length)
$errUtils.modifyErrMsg(e1, message, () => message)
throw e1
}
const e2 = $errUtils.cypressErrByPath('chai.length_invalid_argument', { args: { length } })
e2.retry = false
throw e2
}
})
},
(_super) => {
return (function () {
return _super.apply(this, arguments)
})
})
return chai.Assertion.overwriteProperty('exist', (_super) => {
return (function () {
const obj = this._obj
if (!($dom.isJquery(obj) || $dom.isElement(obj))) {
try {
return _super.apply(this, arguments)
} catch (e) {
e.type = 'existence'
throw e
}
} else {
let isAttached
if (!obj.length) {
this._obj = null
}
const node = obj && obj.length ? $dom.stringify(obj, 'short') : obj.selector
try {
return this.assert(
(isAttached = $dom.isAttached(obj)),
'expected \#{act} to exist in the DOM',
'expected \#{act} not to exist in the DOM',
node,
node,
)
} catch (e1) {
e1.node = node
e1.negated = chaiUtils.flag(this, 'negate')
e1.type = 'existence'
const getLongExistsMessage = function (obj) {
// if we expected not for an element to exist
if (isAttached) {
return `Expected ${node} not to exist in the DOM, but it was continuously found.`
}
return `Expected to find element: \`${obj.selector}\`, but never found it.`
}
const newMessage = getLongExistsMessage(obj)
$errUtils.modifyErrMsg(e1, newMessage, () => newMessage)
throw e1
}
}
})
})
}
const captureUserInvocationStack = (specWindow, state, ssfi) => {
// we need a user invocation stack with the top line being the point where
// the error occurred for the sake of the code frame
// in chrome, stack lines from another frame don't appear in the
// error. specWindow.Error works for our purposes because it
// doesn't include anything extra (chai.Assertion error doesn't work
// because it doesn't have lines from the spec iframe)
// in firefox, specWindow.Error has too many extra lines at the
// beginning, but chai.AssertionError helps us winnow those down
const chaiInvocationStack = $stackUtils.hasCrossFrameStacks(specWindow) && (new chai.AssertionError('uis', {}, ssfi)).stack
const userInvocationStack = $stackUtils.captureUserInvocationStack(specWindow.Error, chaiInvocationStack)
state('currentAssertionUserInvocationStack', userInvocationStack)
}
const createPatchedAssert = (specWindow, state, assertFn) => {
return (function (...args) {
let err
const passed = chaiUtils.test(this, args)
const value = chaiUtils.flag(this, 'object')
const expected = args[3]
const customArgs = replaceArgMessages(args, this._obj)
let message = chaiUtils.getMessage(this, customArgs)
const actual = chaiUtils.getActual(this, customArgs)
message = removeOrKeepSingleQuotesBetweenStars(message)
message = escapeMarkdown(message)
try {
assertProto.apply(this, args)
} catch (e) {
err = e
}
assertFn(passed, message, value, actual, expected, err)
if (!err) return
// when assert() is used instead of expect(), we override the method itself
// below in `overrideAssert` and prefer the user invocation stack
// that we capture there
if (!state('assertUsed')) {
captureUserInvocationStack(specWindow, state, chaiUtils.flag(this, 'ssfi'))
}
throw err
})
}
overrideExpect = (specWindow, state) => {
// only override assertions for this specific
// expect function instance so we do not affect
// the outside world
return (val, message) => {
captureUserInvocationStack(specWindow, state, overrideExpect)
// make the assertion
return new chai.Assertion(val, message)
}
}
const overrideAssert = function (specWindow, state) {
const fn = (express, errmsg) => {
state('assertUsed', true)
captureUserInvocationStack(specWindow, state, fn)
return chai.assert(express, errmsg)
}
const fns = _.functions(chai.assert)
_.each(fns, (name) => {
fn[name] = function () {
state('assertUsed', true)
captureUserInvocationStack(specWindow, state, overrideAssert)
return chai.assert[name].apply(this, arguments)
}
})
return fn
}
setSpecWindowGlobals = function (specWindow, state) {
const expect = overrideExpect(specWindow, state)
const assert = overrideAssert(specWindow, state)
specWindow.chai = chai
specWindow.expect = expect
specWindow.assert = assert
return {
chai,
expect,
assert,
}
}
create = function (specWindow, state, assertFn) {
restoreAsserts()
overrideChaiInspect()
overrideChaiObjDisplay()
overrideChaiAsserts(specWindow, state, assertFn)
return setSpecWindowGlobals(specWindow, state)
}
})
export default {
create,
replaceArgMessages,
removeOrKeepSingleQuotesBetweenStars,
setSpecWindowGlobals,
restoreAsserts,
overrideExpect,
overrideChaiAsserts,
} | the_stack |
/// <reference path="../mongoose/mongoose-model.ts" />
import * as MongooseModel from '../mongoose/mongoose-model';
import * as Utils from "../mongoose/utils";
import * as modeEntity from '../core/dynamic/model-entity';
import * as mockData from '../unit-test/MockDataForRelation';
import * as db from './db';
import {course} from '../unit-test/models/course';
import {student} from '../unit-test/models/student';
import Mongoose = require("mongoose");
import * as Enumerable from 'linq';
var Q = require('q');
describe('testing relation', () => {
var mock: mockData.mockedFunctions = new mockData.mockedFunctions();
var sub1, sub2, student1, student2, res;
beforeAll(() => {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
spyOn(Utils, 'castToMongooseType').and.callFake(mock.castToMongooseType);
spyOn(modeEntity, 'getEntity').and.callFake(mock.getEntity);
spyOn(modeEntity, 'getModel').and.callFake(mock.getModel);
spyOn(db, 'getDbSpecifcModel').and.callFake(mock.getDbSpecifcModel);
mockData.AddAllFakeFunctions();
spyOn(Q, 'nbind').and.callFake((func, model) => mockData.getFakeFunctionForMongoose(func, model));
console.log('initialized successfully');
});
describe(': fake objects', () => {
beforeAll(() => {
// create fake objects
sub1 = mockData.createMongooseModel(course, { 'name': 'subject1' });
student1 = mockData.createMongooseModel(student, { 'name': 'student1' });
});
describe(': course object', () => {
beforeEach((done) => {
setTimeout(function () {
MongooseModel.findAll(mockData.getMongooseModel(course)).then(x => {
res = x;
done();
});
}, 500);
});
it(': exists', (done) => {
expect(res).toBeDefined();
expect(res instanceof Array).toBeTruthy();
expect(res.length).toEqual(1);
done();
});
});
describe(': student object', () => {
beforeEach((done) => {
setTimeout(function () {
MongooseModel.findAll(mockData.getMongooseModel(student)).then(x => {
res = x;
done();
});
}, 500);
});
it(': exists', (done) => {
expect(res).toBeDefined();
expect(res instanceof Array).toBeTruthy();
expect(res.length).toEqual(1);
done();
});
});
afterAll(() => {
mockData.clearDatabase();
});
});
//Anuj- need to fix this unit test with latest changes for bulk post
xdescribe(': mongoose functions', () => {
describe(': bulk post', () => {
var objs = [];
objs.push({ 'name': 'student1' });
objs.push({ 'name': 'student2' });
beforeEach((done) => {
setTimeout(function () {
MongooseModel.bulkPost(mockData.getMongooseModel(student), objs).then(x => {
res = x;
done();
});
}, 500);
});
it(': test', (done) => {
console.log('bulk post res:', res);
expect(res).toBeDefined();
expect(res instanceof Array).toBeTruthy();
expect(res.length).toEqual(2);
done();
});
afterAll(() => {
mockData.clearDatabase();
});
});
//Anuj- need to fix this unit test with latest changes for bulk put
xdescribe(': bulk put', () => {
var objs = [];
objs.push({ 'name': 'student1' });
objs.push({ 'name': 'student2' });
beforeEach((done) => {
setTimeout(function () {
MongooseModel.bulkPost(mockData.getMongooseModel(student), objs).then(x => {
x[0]['name'] = 'student3';
x[1]['name'] = 'student4';
MongooseModel.bulkPut(mockData.getMongooseModel(student), x).then(x => {
res = x;
done();
});
});
}, 500);
});
it(': test', (done) => {
console.log('bulk put res:', res);
expect(res).toBeDefined();
expect(res instanceof Array).toBeTruthy();
expect(res.length).toEqual(2);
expect((res[0]['name'] == 'student3') || (res[0]['name'] == 'student4')).toBeTruthy();
done();
});
afterAll(() => {
mockData.clearDatabase();
});
});
describe(': findByField', () => {
var objs = [];
objs.push({ 'name': 'student1' });
objs.push({ 'name': 'student2' });
beforeEach((done) => {
setTimeout(function () {
MongooseModel.bulkPost(mockData.getMongooseModel(student), objs).then(x => {
MongooseModel.findByField(mockData.getMongooseModel(student), 'name', 'student1').then(x => {
res = x;
done();
});
});
}, 500);
});
it(': test', (done) => {
console.log('findByField res:', res);
expect(res).toBeDefined();
expect(res['name'] == 'student1').toBeTruthy();
done();
});
afterAll(() => {
mockData.clearDatabase();
});
});
describe(': findChild', () => {
var objs = [];
objs.push({ 'name': 'student1' });
objs.push({ 'name': 'student2' });
beforeEach((done) => {
setTimeout(function () {
MongooseModel.bulkPost(mockData.getMongooseModel(student), objs).then(x => {
MongooseModel.findChild(mockData.getMongooseModel(student), x[0]['_id'], 'name').then(x => {
res = x;
done();
});
});
}, 500);
});
it(': test', (done) => {
console.log('findChild res:', res);
expect(res).toBeDefined();
expect(res == 'student1').toBeTruthy();
done();
});
afterAll(() => {
mockData.clearDatabase();
});
});
xdescribe(': findWhere', () => {
var objs = [];
objs.push({ 'name': 'student1' });
objs.push({ 'name': 'student2' });
beforeEach((done) => {
setTimeout(function () {
MongooseModel.bulkPost(mockData.getMongooseModel(student), objs).then(x => {
var con = {};
con['name'] = 'student1';
MongooseModel.findWhere(mockData.getMongooseModel(student), con).then(x => {
res = x;
done();
});
});
}, 500);
});
it(': test', (done) => {
console.log('findWhere res:', res);
expect(res).toBeDefined();
expect(res['name'] == 'student1').toBeTruthy();
done();
});
afterAll(() => {
mockData.clearDatabase();
});
});
describe(': patch', () => {
var objs = [];
objs.push({ 'name': 'student1' });
objs.push({ 'name': 'student2' });
beforeEach((done) => {
setTimeout(function () {
MongooseModel.bulkPost(mockData.getMongooseModel(student), objs).then(x => {
x[0]['name'] = 'student3';
MongooseModel.patch(mockData.getMongooseModel(student), x[0]['_id'], x[0]).then(x => {
res = x;
done();
});
});
}, 500);
});
it(': test', (done) => {
console.log('patch res:', res);
expect(res).toBeDefined();
expect(res['name'] == 'student3').toBeTruthy();
done();
});
afterAll(() => {
mockData.clearDatabase();
});
});
describe(': post embedded one object', () => {
var stud1 = {};
var resStud1, resStud2, resSub1;
var sub1 = {};
beforeAll(() => {
stud1['name'] = 'student1';
sub1['name'] = 'subject1';
stud1['courseOTO'] = sub1;
resSub1 = mockData.createMongooseModel(course, { 'name':'subject1'});
});
beforeEach((done) => {
setTimeout(function () {
MongooseModel.post(mockData.getMongooseModel(student), stud1).then(x => {
resStud1 = x;
sub1 = {};
sub1['_id'] = resSub1['_id'];
stud1['courseOTO'] = sub1;
MongooseModel.post(mockData.getMongooseModel(student), stud1).then(x => {
resStud2 = x;
done();
});
});
}, 500);
});
it(': test', (done) => {
console.log('embed 1 object stud1, stud2', resStud1, resStud2);
expect(resStud1).toBeDefined();
expect(resStud2).toBeDefined();
done();
});
afterAll(() => {
mockData.clearDatabase();
});
});
});
describe(': student-course (one to one)(Embedded = true)', () => {
beforeAll(() => {
// create fake objects
sub1 = mockData.createMongooseModel(course, { 'name': 'subject1' });
student1 = mockData.createMongooseModel(student, { 'name': 'student1' });
console.log('#### started - (one to one)(Embedded = true)');
});
describe(': add', () => {
beforeEach((done) => {
setTimeout(function () {
MongooseModel.put(mockData.getMongooseModel(student), student1['_id'], { 'courseOTO': sub1['_id'] })
.then(x => {
res = x;
done();
});
}, 500);
});
it(': test', (done) => {
console.log('add res:', res);
expect(res).toBeDefined();
expect(res['courseOTO']).toBeDefined();
expect(res['courseOTO']['_id']).toEqual(sub1['_id']);
done();
});
});
describe(': update', () => {
beforeEach((done) => {
setTimeout(function () {
MongooseModel.put(mockData.getMongooseModel(student), student1['_id'], { 'courseOTO': sub1['_id'] })
.then(stud => {
// set condition to update database
var cond = {};
cond['courseOTO._id'] = sub1['_id'];
stud['courseOTO']['name'] = 'subject3';
mockData.MongoDbMock.setOnUpdate(student, cond, stud);
MongooseModel.put(mockData.getMongooseModel(course), sub1['_id'], { 'name': 'subject3' })
.then(cor => {
MongooseModel.findOne(mockData.getMongooseModel(student), student1['_id'])
.then(x => {
res = x;
done();
});
});
});
}, 500);
});
it(': test', (done) => {
console.log('update res:', res);
expect(res).toBeDefined();
expect(res['courseOTO']).toBeDefined();
expect(res['courseOTO']['_id']).toEqual(sub1['_id']);
expect(res['courseOTO']['name']).toEqual('subject3');
done();
});
});
describe(': delete', () => {
var del;
beforeEach((done) => {
setTimeout(function () {
MongooseModel.put(mockData.getMongooseModel(student), student1['_id'], { 'courseOTO': sub1['_id'] })
.then(stud => {
// set condition to update database
var cond = {};
cond['courseOTO._id'] = sub1['_id'];
stud['courseOTO'] = null;
mockData.MongoDbMock.setOnUpdate(student, cond, stud);
MongooseModel.del(mockData.getMongooseModel(course), sub1['_id'])
.then(cor => {
del = cor;
MongooseModel.findOne(mockData.getMongooseModel(student), student1['_id'])
.then(x => {
res = x;
done();
});
});
});
}, 500);
});
it(': test', (done) => {
console.log('delete del:', del, ' res:', res);
expect(res).toBeDefined();
expect(res['courseOTO']).toBeNull();
expect(del.delete).toEqual('success');
done();
});
});
afterAll(() => {
mockData.clearDatabase();
console.log('#### completed - (one to one)(Embedded = true)');
});
});
describe(': student-course (one to one)(Embedded = false)', () => {
beforeAll(() => {
// create fake objects
sub1 = mockData.createMongooseModel(course, { 'name': 'subject1' });
student1 = mockData.createMongooseModel(student, { 'name': 'student1' });
console.log('#### started - (one to one)(Embedded = false)');
});
describe(': add', () => {
beforeEach((done) => {
setTimeout(function () {
MongooseModel.put(mockData.getMongooseModel(student), student1['_id'], { 'courseIdOTO': sub1['_id'] })
.then(x => {
res = x;
done();
});
}, 500);
});
it(': test', (done) => {
console.log('add res:', res);
expect(res).toBeDefined();
expect(res['courseIdOTO']).toEqual(sub1['_id']);
done();
});
});
describe(': update', () => {
beforeEach((done) => {
setTimeout(function () {
MongooseModel.put(mockData.getMongooseModel(student), student1['_id'], { 'courseIdOTO': sub1['_id'] })
.then(stud => {
// set condition to update database (This condition should not hit)
var cond = {};
cond['courseIdOTO'] = sub1['_id'];
stud['courseIdOTO']['name'] = 'subject3';
mockData.MongoDbMock.setOnUpdate(student, cond, stud);
MongooseModel.put(mockData.getMongooseModel(course), sub1['_id'], { 'name': 'subject3' })
.then(cor => {
MongooseModel.findOne(mockData.getMongooseModel(student), student1['_id'])
.then(x => {
res = x;
done();
});
});
});
}, 500);
});
it(': test', (done) => {
console.log('update res:', res);
expect(res).toBeDefined();
expect(res['courseIdOTO']).toEqual(sub1['_id']);
done();
});
});
describe(': delete', () => {
var del;
beforeEach((done) => {
setTimeout(function () {
MongooseModel.put(mockData.getMongooseModel(student), student1['_id'], { 'courseIdOTO': sub1['_id'] })
.then(stud => {
// set condition to update database
var cond = {};
cond['courseIdOTO'] = sub1['_id'];
student1['_doc']['courseIdOTO'] = null;
mockData.MongoDbMock.setOnUpdate(student, cond, student1['_doc']);
MongooseModel.del(mockData.getMongooseModel(course), sub1['_id'])
.then(cor => {
del = cor;
MongooseModel.findOne(mockData.getMongooseModel(student), student1['_id'])
.then(x => {
res = x;
done();
});
});
});
}, 500);
});
it(': test', (done) => {
console.log('delete del:', del, ' res:', res);
expect(res).toBeDefined();
expect(res['courseIdOTO']).toBeNull();
expect(del.delete).toEqual('success');
done();
});
});
afterAll(() => {
mockData.clearDatabase();
console.log('#### completed - (one to one)(Embedded = false)');
});
});
describe(': student-course (one to many)(Embedded = true)', () => {
beforeAll(() => {
// create fake objects
sub1 = mockData.createMongooseModel(course, { 'name': 'subject1' });
sub2 = mockData.createMongooseModel(course, { 'name': 'subject2' });
student1 = mockData.createMongooseModel(student, { 'name': 'student1' });
console.log('#### started - (one to many)(Embedded = true)');
});
describe(': add', () => {
beforeEach((done) => {
setTimeout(function () {
MongooseModel.put(mockData.getMongooseModel(student), student1['_id'], { 'courseOTM': [sub1['_id'], sub2['_id']] })
.then(x => {
res = x;
done();
});
}, 500);
});
it(': test', (done) => {
console.log('add res:', res);
expect(res).toBeDefined();
expect(res['courseOTM']).toBeDefined();
expect(res['courseOTM'] instanceof Array).toBeTruthy();
var courses = res['courseOTM'];
expect(courses.length).toEqual(2);
expect(courses[0]['_id'] == sub1['_id'].toString() || courses[0]['_id'] == sub2['_id'].toString()).toBeTruthy();
done();
});
});
describe(': update', () => {
beforeEach((done) => {
setTimeout(function () {
MongooseModel.put(mockData.getMongooseModel(student), student1['_id'], { 'courseOTM': [sub1['_id'], sub2['_id']] })
.then(stud => {
// set condition to update database
var cond = {};
cond['courseOTM._id'] = sub1['_id'];
var sub = stud['courseOTM'].find(x => x['_id'] == sub1['_id'].toString());
sub['name'] = 'subject3';
mockData.MongoDbMock.setOnUpdate(student, cond, stud);
MongooseModel.put(mockData.getMongooseModel(course), sub1['_id'], { 'name': 'subject3' })
.then(cor => {
MongooseModel.findOne(mockData.getMongooseModel(student), student1['_id'])
.then(x => {
res = x;
done();
});
});
});
}, 500);
});
it(': test', (done) => {
console.log('update res:', res);
expect(res).toBeDefined();
expect(res['courseOTM'] instanceof Array).toBeTruthy();
var courses = res['courseOTM'];
expect(courses.length).toEqual(2);
expect(courses[0]['_id'] == sub1['_id'].toString() || courses[0]['_id'] == sub2['_id'].toString()).toBeTruthy();
expect(courses.find(x => x['_id'] == sub1['_id'].toString())['name']).toEqual('subject3');
done();
});
});
describe(': delete', () => {
var del;
beforeEach((done) => {
setTimeout(function () {
MongooseModel.put(mockData.getMongooseModel(student), student1['_id'], { 'courseOTM': [sub1['_id'], sub2['_id']] })
.then(stud => {
// set condition to update database
var cond = {};
cond['$pull'] = {};
cond['$pull']['courseOTM']={};
cond['$pull']['courseOTM']['_id'] = sub1['_id'];
stud['courseOTM'] = [sub2['_doc']];
mockData.MongoDbMock.setOnUpdate(student, cond, stud);
MongooseModel.del(mockData.getMongooseModel(course), sub1['_id'])
.then(cor => {
del = cor;
MongooseModel.findOne(mockData.getMongooseModel(student), student1['_id'])
.then(x => {
res = x;
done();
});
});
});
}, 500);
});
it(': test', (done) => {
console.log('delete del:', del, ' res:', res);
expect(res).toBeDefined();
var courses = res['courseOTM'];
expect(courses.length).toEqual(1);
expect(courses[0]['_id'] == sub2['_id'].toString()).toBeTruthy();
expect(del.delete).toEqual('success');
done();
});
});
afterAll(() => {
mockData.clearDatabase();
console.log('#### completed - (one to many)(Embedded = true)');
});
});
describe(': student-course (one to many)(Embedded = false)', () => {
beforeAll(() => {
// create fake objects
sub1 = mockData.createMongooseModel(course, { 'name': 'subject1' });
sub2 = mockData.createMongooseModel(course, { 'name': 'subject2' });
student1 = mockData.createMongooseModel(student, { 'name': 'student1' });
console.log('#### started - (one to many)(Embedded = false)');
});
describe(': add', () => {
beforeEach((done) => {
setTimeout(function () {
MongooseModel.put(mockData.getMongooseModel(student), student1['_id'], { 'courseIdOTM': [sub1['_id'], sub2['_id']] })
.then(x => {
res = x;
done();
});
}, 500);
});
it(': test', (done) => {
console.log('add res:', res);
expect(res).toBeDefined();
expect(res['courseIdOTM']).toBeDefined();
expect(res['courseIdOTM'] instanceof Array).toBeTruthy();
var courses = res['courseIdOTM'];
expect(courses.length).toEqual(2);
expect(courses[0] == sub1['_id'].toString() || courses[0] == sub2['_id'].toString()).toBeTruthy();
done();
});
});
describe(': update', () => {
beforeEach((done) => {
setTimeout(function () {
MongooseModel.put(mockData.getMongooseModel(student), student1['_id'], { 'courseIdOTM': [sub1['_id'], sub2['_id']] })
.then(stud => {
// set condition to update database (This condition should not hit)
var cond = {};
cond['courseIdOTM._id'] = sub1['_id'];
stud['courseIdOTM']['_id'] = sub1['_id'];
mockData.MongoDbMock.setOnUpdate(student, {}, stud);
MongooseModel.put(mockData.getMongooseModel(course), sub1['_id'], { 'name': 'subject3' })
.then(cor => {
MongooseModel.findOne(mockData.getMongooseModel(student), student1['_id'])
.then(x => {
res = x;
done();
});
});
});
}, 500);
});
it(': test', (done) => {
console.log('update res:', res);
expect(res).toBeDefined();
expect(res['courseIdOTM'] instanceof Array).toBeTruthy();
var courses = res['courseIdOTM'];
expect(courses.length).toEqual(2);
expect(courses[0] == sub1['_id'].toString() || courses[0] == sub2['_id'].toString()).toBeTruthy();
done();
});
});
describe(': delete', () => {
var del;
beforeEach((done) => {
setTimeout(function () {
MongooseModel.put(mockData.getMongooseModel(student), student1['_id'], { 'courseIdOTM': [sub1['_id'], sub2['_id']] })
.then(stud => {
// set condition to update database
var cond = {};
cond['$pull'] = {};
cond['$pull']['courseIdOTM'] = sub1['_id'];
stud['courseIdOTM'] = [sub2['_id']];
mockData.MongoDbMock.setOnUpdate(student, cond, stud);
MongooseModel.del(mockData.getMongooseModel(course), sub1['_id'])
.then(cor => {
del = cor;
MongooseModel.findOne(mockData.getMongooseModel(student), student1['_id'])
.then(x => {
res = x;
done();
});
});
});
}, 500);
});
it(': test', (done) => {
console.log('delete del:', del, ' res:', res);
expect(res).toBeDefined();
var courses = res['courseIdOTM'];
expect(courses.length).toEqual(1);
expect(courses[0] == sub2['_id'].toString()).toBeTruthy();
expect(del.delete).toEqual('success');
done();
});
});
afterAll(() => {
mockData.clearDatabase();
console.log('#### completed - (one to many)(Embedded = false)');
});
});
//Anuj- need to fix this unit test with latest changes for bulk post
xdescribe(': student-course (many to many)(deleteCascade = true)', () => {
var student1;
var objs = [], student1;
beforeAll(() => {
student1 = {};
student1['name'] = 'student1';
objs.push({ 'name': 'subject1' });
objs.push({ 'name': 'subject2' });
});
beforeEach((done) => {
setTimeout(function () {
MongooseModel.bulkPost(mockData.getMongooseModel(course), objs).then(x => {
var courseDelCascase = Enumerable.from(x).select(a => a['_id']).toArray();
student1['courseDelCascase'] = courseDelCascase;
MongooseModel.post(mockData.getMongooseModel(student), student1).then(x => {
MongooseModel.del(mockData.getMongooseModel(student), student1['_id']).then(x => {
MongooseModel.findAll(mockData.getMongooseModel(course)).then(x => {
res = x;
done();
});
});
});
});
}, 500);
});
it(': test', (done) => {
done();
});
});
afterAll(() => {
mockData.clearDatabase();
console.log('#### completed - (one to many)(Embedded = false)');
});
}); | the_stack |
* This is an autogenerated file created by the Stencil compiler.
* It contains typing information for all components that exist in this project.
*/
import { HTMLStencilElement, JSXBase } from "@stencil/core/internal";
import { SuperTabChangeEventDetail, SuperTabsConfig } from "./interface";
export namespace Components {
interface SuperTab {
/**
* Returns the root scrollable element
*/
"getRootScrollableEl": () => Promise<HTMLElement | null>;
"loaded": boolean;
/**
* Set this to true to prevent vertical scrolling of this tab. Defaults to `false`. This property will automatically be set to true if there is a direct child element of `ion-content`. To override this behaviour make sure to explicitly set this property to `false`.
*/
"noScroll": boolean;
"visible": boolean;
}
interface SuperTabButton {
"active"?: boolean;
/**
* Whether the button is disabled
*/
"disabled"?: boolean;
"index"?: number;
"scrollableContainer": boolean;
}
interface SuperTabIndicator {
/**
* Toolbar position This determines the position of the indicator
*/
"toolbarPosition": 'top' | 'bottom';
}
interface SuperTabs {
/**
* Initial active tab index. Defaults to `0`.
* @type {number}
*/
"activeTabIndex": number;
/**
* Global Super Tabs configuration. This is the only place you need to configure the components. Any changes to this input will propagate to child components.
* @type {SuperTabsConfig}
*/
"config"?: SuperTabsConfig;
/**
* Set the selected tab. This will move the container and the toolbar to the selected tab.
* @param index the index of the tab you want to select
* @param animate whether you want to animate the transition
* @param emit whether you want to emit tab change event
*/
"selectTab": (index: number, animate?: boolean, emit?: boolean) => Promise<void>;
/**
* Set/update the configuration
* @param config Configuration object
*/
"setConfig": (config: SuperTabsConfig) => Promise<void>;
}
interface SuperTabsContainer {
/**
* Set to true to automatically scroll to the top of the tab when the button is clicked while the tab is already selected.
*/
"autoScrollTop": boolean;
"config"?: SuperTabsConfig;
/**
* @param scrollX
* @param animate
*/
"moveContainer": (scrollX: number, animate?: boolean | undefined) => Promise<void>;
/**
* @param index Index of the tab
* @param animate Whether to animate the transition
*/
"moveContainerByIndex": (index: number, animate?: boolean | undefined) => Promise<void>;
"reindexTabs": () => Promise<void>;
/**
* Scroll the active tab to the top.
*/
"scrollToTop": () => Promise<void>;
"setActiveTabIndex": (index: number, moveContainer?: boolean, animate?: boolean) => Promise<void>;
/**
* Enable/disable swiping
*/
"swipeEnabled": boolean;
}
interface SuperTabsToolbar {
/**
* Background color. Defaults to `'primary'`
*/
"color": string | undefined;
"config"?: SuperTabsConfig;
"moveContainer": (scrollX: number, animate?: boolean | undefined) => Promise<void>;
/**
* Whether the toolbar is scrollable. Defaults to `false`.
*/
"scrollable": boolean;
/**
* If scrollable is set to true, there will be an added padding to the left of the buttons. Setting this property to false will remove that padding. The padding is also configurable via a CSS variable.
*/
"scrollablePadding": boolean;
"setActiveTab": (index: number, align?: boolean | undefined, animate?: boolean | undefined) => Promise<void>;
"setSelectedTab": (index: number, animate?: boolean | undefined) => Promise<void>;
/**
* Whether to show the indicator. Defaults to `true`
*/
"showIndicator": boolean;
}
}
declare global {
interface HTMLSuperTabElement extends Components.SuperTab, HTMLStencilElement {
}
var HTMLSuperTabElement: {
prototype: HTMLSuperTabElement;
new (): HTMLSuperTabElement;
};
interface HTMLSuperTabButtonElement extends Components.SuperTabButton, HTMLStencilElement {
}
var HTMLSuperTabButtonElement: {
prototype: HTMLSuperTabButtonElement;
new (): HTMLSuperTabButtonElement;
};
interface HTMLSuperTabIndicatorElement extends Components.SuperTabIndicator, HTMLStencilElement {
}
var HTMLSuperTabIndicatorElement: {
prototype: HTMLSuperTabIndicatorElement;
new (): HTMLSuperTabIndicatorElement;
};
interface HTMLSuperTabsElement extends Components.SuperTabs, HTMLStencilElement {
}
var HTMLSuperTabsElement: {
prototype: HTMLSuperTabsElement;
new (): HTMLSuperTabsElement;
};
interface HTMLSuperTabsContainerElement extends Components.SuperTabsContainer, HTMLStencilElement {
}
var HTMLSuperTabsContainerElement: {
prototype: HTMLSuperTabsContainerElement;
new (): HTMLSuperTabsContainerElement;
};
interface HTMLSuperTabsToolbarElement extends Components.SuperTabsToolbar, HTMLStencilElement {
}
var HTMLSuperTabsToolbarElement: {
prototype: HTMLSuperTabsToolbarElement;
new (): HTMLSuperTabsToolbarElement;
};
interface HTMLElementTagNameMap {
"super-tab": HTMLSuperTabElement;
"super-tab-button": HTMLSuperTabButtonElement;
"super-tab-indicator": HTMLSuperTabIndicatorElement;
"super-tabs": HTMLSuperTabsElement;
"super-tabs-container": HTMLSuperTabsContainerElement;
"super-tabs-toolbar": HTMLSuperTabsToolbarElement;
}
}
declare namespace LocalJSX {
interface SuperTab {
"loaded"?: boolean;
/**
* Set this to true to prevent vertical scrolling of this tab. Defaults to `false`. This property will automatically be set to true if there is a direct child element of `ion-content`. To override this behaviour make sure to explicitly set this property to `false`.
*/
"noScroll": boolean;
"visible"?: boolean;
}
interface SuperTabButton {
"active"?: boolean;
/**
* Whether the button is disabled
*/
"disabled"?: boolean;
"index"?: number;
"scrollableContainer"?: boolean;
}
interface SuperTabIndicator {
/**
* Toolbar position This determines the position of the indicator
*/
"toolbarPosition"?: 'top' | 'bottom';
}
interface SuperTabs {
/**
* Initial active tab index. Defaults to `0`.
* @type {number}
*/
"activeTabIndex"?: number;
/**
* Global Super Tabs configuration. This is the only place you need to configure the components. Any changes to this input will propagate to child components.
* @type {SuperTabsConfig}
*/
"config"?: SuperTabsConfig;
/**
* Tab change event. This event fires up when a tab button is clicked, or when a user swipes between tabs. The event will fire even if the tab did not change, you can check if the tab changed by checking the `changed` property in the event detail.
*/
"onTabChange"?: (event: CustomEvent<SuperTabChangeEventDetail>) => void;
}
interface SuperTabsContainer {
/**
* Set to true to automatically scroll to the top of the tab when the button is clicked while the tab is already selected.
*/
"autoScrollTop"?: boolean;
"config"?: SuperTabsConfig;
/**
* Emits an event when the active tab changes. An active tab is the tab that the user looking at. This event emitter will not notify you if the user has changed the current active tab. If you need that information, you should use the `tabChange` event emitted by the `super-tabs` element.
*/
"onActiveTabIndexChange"?: (event: CustomEvent<number>) => void;
/**
* Emits events when the container moves. Selected tab index represents what the user should be seeing. If you receive a decimal as the emitted number, it means that the container is moving between tabs. This number is used for animations, and can be used for high tab customizations.
*/
"onSelectedTabIndexChange"?: (event: CustomEvent<number>) => void;
/**
* Enable/disable swiping
*/
"swipeEnabled"?: boolean;
}
interface SuperTabsToolbar {
/**
* Background color. Defaults to `'primary'`
*/
"color"?: string | undefined;
"config"?: SuperTabsConfig;
/**
* Emits an event when a button is clicked Event data contains the clicked SuperTabButton component
*/
"onButtonClick"?: (event: CustomEvent<HTMLSuperTabButtonElement>) => void;
/**
* Whether the toolbar is scrollable. Defaults to `false`.
*/
"scrollable"?: boolean;
/**
* If scrollable is set to true, there will be an added padding to the left of the buttons. Setting this property to false will remove that padding. The padding is also configurable via a CSS variable.
*/
"scrollablePadding"?: boolean;
/**
* Whether to show the indicator. Defaults to `true`
*/
"showIndicator"?: boolean;
}
interface IntrinsicElements {
"super-tab": SuperTab;
"super-tab-button": SuperTabButton;
"super-tab-indicator": SuperTabIndicator;
"super-tabs": SuperTabs;
"super-tabs-container": SuperTabsContainer;
"super-tabs-toolbar": SuperTabsToolbar;
}
}
export { LocalJSX as JSX };
declare module "@stencil/core" {
export namespace JSX {
interface IntrinsicElements {
"super-tab": LocalJSX.SuperTab & JSXBase.HTMLAttributes<HTMLSuperTabElement>;
"super-tab-button": LocalJSX.SuperTabButton & JSXBase.HTMLAttributes<HTMLSuperTabButtonElement>;
"super-tab-indicator": LocalJSX.SuperTabIndicator & JSXBase.HTMLAttributes<HTMLSuperTabIndicatorElement>;
"super-tabs": LocalJSX.SuperTabs & JSXBase.HTMLAttributes<HTMLSuperTabsElement>;
"super-tabs-container": LocalJSX.SuperTabsContainer & JSXBase.HTMLAttributes<HTMLSuperTabsContainerElement>;
"super-tabs-toolbar": LocalJSX.SuperTabsToolbar & JSXBase.HTMLAttributes<HTMLSuperTabsToolbarElement>;
}
}
} | the_stack |
export const statusList = {
// 所有内容的审核状态
pendingReview: 1, // 待审核
reviewSuccess: 2, // 审核成功
reviewFail: 3, // 审核失败
freeReview: 4, // 免审核
deleted: 5, // 已删除
draft: 6 // 草稿
}
export const statusListText = {
// 所有内容的审核状态文字
[statusList.pendingReview]: '待审核', // 待审核
[statusList.reviewSuccess]: '审核成功', // 审核成功
[statusList.reviewFail]: '审核失败', // 审核失败
[statusList.freeReview]: '免审核', // 免审核
[statusList.deleted]: '已删除', // 已删除
[statusList.draft]: '草稿' // 草稿
}
export const articleType = {
// 文章的类型
article: 1, // 文章
discuss: 2, // 讨论提问
share: 3, // 分享
recourse: 4, // 求助
note: 5 // 笔记
}
export const articleTypeText = {
// 文章的类型
[articleType.article]: '文章', // 文章
[articleType.discuss]: '讨论提问', // 提问
[articleType.share]: '分享', // 分享
[articleType.recourse]: '求助', // 求助
[articleType.note]: '笔记' // 笔记
}
export const dynamicType = {
// 文章的类型
dynamic: 1, // 默认动态
img: 2, // 图片
link: 3, // 链接
video: 4 // 视频
}
export const dynamicTypeText = {
// 文章的类型
[dynamicType.dynamic]: '默认动态', // 文章
[dynamicType.img]: '图片', // 笔记
[dynamicType.link]: '链接', // 草稿
[dynamicType.video]: '视频' // 草稿
}
export const modelName = {
// 类型
user: 1, // 用户
article: 2, // 文章
article_blog: 3, // 文章个人专栏
article_comment: 4, // 文章评论
book: 5, // 小书章节
book_comment: 6, // 小书章节评论
books: 7, // 小书
books_comment: 8, // 小书评论
dynamic: 9, // 片刻
dynamic_comment: 10, // 片刻评论
thumb: 11, // 点赞表
like: 12, // 喜欢表
collect: 13, // 收藏表
attention: 14, // 关注表
article_tag: 15, // 文章标签
dynamic_topic: 16, // 动态专题
system: 17, // 系统 ---- 不是特别,暂时不用
other: 18, // 其他 ---- 不是特别,暂时不用
virtual: 19, // 虚拟币
chat_message: 20, // 私聊消息
article_annex: 21 // 文章附件
}
export const modelInfo = {
// 文章的类型
[modelName.user]: {
model: 'user',
name: '用户',
idKey: 'uid'
}, // 用户
[modelName.article]: {
model: 'article',
name: '文章',
idKey: 'aid'
}, // 文章
[modelName.article_blog]: {
model: 'article_blog',
name: '文章专栏',
idKey: 'blog_id'
}, // 文章个人专栏
[modelName.article_comment]: {
model: 'article_comment',
name: '文章评论',
idKey: 'id'
}, // 文章评论
[modelName.book]: {
model: 'book',
name: '小书章节',
idKey: 'book_id'
}, // 小书章节
[modelName.book_comment]: {
model: 'book_comment',
name: '小书章节评论',
idKey: 'id'
}, // 小书章节评论
[modelName.books]: {
model: 'books',
name: '小书',
idKey: 'books_id'
}, // 小书
[modelName.books_comment]: {
model: 'books_comment',
name: '小书评论',
idKey: 'id'
}, // 小书评论
[modelName.dynamic]: {
model: 'dynamic',
name: '片刻',
idKey: 'id'
}, // 片刻
[modelName.dynamic_comment]: {
model: 'dynamic_comment',
name: '片刻评论',
idKey: 'id'
}, // 片刻评论
[modelName.thumb]: {
model: 'thumb',
name: '赞',
idKey: 'id'
}, // 点赞表
[modelName.like]: {
model: 'like',
name: '喜欢',
idKey: 'id'
}, // 喜欢表
[modelName.collect]: {
model: 'collect',
name: '收藏',
idKey: 'id'
}, // 收藏表
[modelName.attention]: {
model: 'attention',
name: '关注',
idKey: 'id'
}, // 关注表
[modelName.article_tag]: {
model: 'article_tag',
name: '文章标签',
idKey: 'id'
}, // 关注表
[modelName.dynamic_topic]: {
model: 'dynamic_topic',
name: '动态专题',
idKey: 'id'
}, // 关注表
[modelName.virtual]: {
model: 'virtual',
name: '虚拟币',
idKey: 'id'
}, // 关注表
[modelName.chat_message]: {
model: 'chat_message',
name: '私聊消息',
idKey: 'id'
}, // 关注表
[modelName.article_annex]: {
model: 'article_annex',
name: '文章附件',
idKey: 'id'
}, // 文章附件表
[modelName.system]: {
model: '',
name: '系统',
idKey: ''
}, // 文章附件表
[modelName.other]: {
model: '',
name: '其他',
idKey: ''
} // 文章附件表
}
export const modelAction = {
// 动作
check_in: 1, // 签到
create: 2, // 创建
like: 3, // 喜欢
collect: 4, // 收藏
comment: 5, // 评论
reply: 6, // 回复
thumb: 7, // 点赞
sell: 8, // 卖
buy: 9, // 买
recover: 10, // 系统回收
obtain_like: 11, // 收到喜欢
obtain_collect: 12, // 收到收藏
obtain_comment: 13, // 收到评论
obtain_reply: 14, // 收到回复
obtain_thumb: 15, // 收到点赞
registered: 16, // 注册
readOther: 17, // 阅读他人
otherRead: 18, // 他人阅读
sendPrivateChat: 19, // 发送私聊
receivePrivateChat: 20 // 接受私聊
}
export const modelActionText = {
// 动作
[modelAction.check_in]: '签到', // 签到
[modelAction.create]: '创建', // 创建
[modelAction.like]: '喜欢', // 喜欢
[modelAction.collect]: '收藏', // 收藏
[modelAction.comment]: '评论', // 评论
[modelAction.reply]: '回复', // 回复
[modelAction.thumb]: '点赞', // 点赞
[modelAction.sell]: '售出', // 卖
[modelAction.buy]: '购物', // 买
[modelAction.recover]: '系统回收', // 系统回收
[modelAction.obtain_like]: '收到喜欢', // 收到喜欢
[modelAction.obtain_collect]: '收到收藏', // 收到收藏
[modelAction.obtain_comment]: '收到评论', // 收到评论
[modelAction.obtain_reply]: '收到回复', // 收到回复
[modelAction.obtain_thumb]: '收到点赞', // 收到点赞
[modelAction.registered]: '注册', // 默认
[modelAction.readOther]: '阅读他人', // 默认
[modelAction.otherRead]: '他人阅读', // 默认
[modelAction.sendPrivateChat]: '发送私聊', // 默认
[modelAction.receivePrivateChat]: '接受私聊' // 默认
}
export const userMessageAction = {
system: 1, // 系统消息
like: 2, // 喜欢
collect: 3, // 收藏
attention: 4, // 关注
comment: 5, // 评论
reply: 6, // 回复
thumb: 7, // 赞
buy: 8, // 购买
sell: 9 // 售出
}
export const userMessageTypeText = {
// 文章的类型
[modelName.user]: {
[userMessageAction.attention]: '关注了你'
},
[modelName.article]: {
[userMessageAction.comment]: '评论了你的文章',
[userMessageAction.reply]: '在你的文章有回复',
[userMessageAction.collect]: '收藏文章'
},
[modelName.article_blog]: {
[userMessageAction.collect]: '收藏了你的专栏'
},
[modelName.article_comment]: {
[userMessageAction.reply]: '文章中回复你的'
},
[modelName.book]: {
[userMessageAction.comment]: '评论了你的小书章节',
[userMessageAction.reply]: '在你的小书章节有回复'
},
[modelName.book_comment]: {
[userMessageAction.reply]: '小书章节中回复你的'
},
[modelName.books]: {
[userMessageAction.comment]: '评论了你的小书',
[userMessageAction.sell]: '卖出小书',
[userMessageAction.reply]: '在你的小书有回复',
[userMessageAction.collect]: '收藏小书'
},
[modelName.books_comment]: {
[userMessageAction.reply]: '小书中回复你的'
},
[modelName.dynamic]: {
[userMessageAction.comment]: '评论了你片刻',
[userMessageAction.reply]: '在你的片刻有回复'
},
[modelName.dynamic_comment]: {
[userMessageAction.comment]: '片刻中回复你的'
},
[modelName.thumb]: {
[userMessageAction.thumb]: '点赞你的'
},
[modelName.like]: {
[userMessageAction.like]: '喜欢了你的文章'
},
[modelName.collect]: {
[userMessageAction.collect]: '收藏你的'
},
[modelName.article_annex]: {
[userMessageAction.sell]: '卖出文章附件'
}
}
export const userMessageActionText = {
[userMessageAction.system]: '新的系统消息',
[userMessageAction.like]: '新的喜欢',
[userMessageAction.collect]: '新的收藏',
[userMessageAction.attention]: '新的关注',
[userMessageAction.comment]: '新的评论',
[userMessageAction.reply]: '新的回复',
[userMessageAction.thumb]: '新的赞',
[userMessageAction.buy]: '新的购买'
}
export const userMessageIsPush = {
open: 1, // 开启
close: 2 // 关闭
}
// 2019.11.4 15:34
export const virtualPlusLess = {
// 虚拟币动作
plus: 1, // 加
less: 2 // 减
}
export const virtualPlusLessText = {
[virtualPlusLess.plus]: '+', // 加
[virtualPlusLess.less]: '-' // 减
}
export const virtualInfo = {
[modelAction.check_in]: {
// 签到+
plusLess: virtualPlusLess.plus, // +
[modelName.system]: 50 // 用户每天签到:+50
},
[modelAction.create]: {
// 创建内容-
plusLess: virtualPlusLess.less, // -
[modelName.article]: 20, // 创建文章:-20
[modelName.article_blog]: 10, // 创建个人专栏文章:-10
[modelName.book]: 5, // 创建小书章节:-5
[modelName.books]: 50, // 创建小书:-50
[modelName.dynamic]: 15 // 创建动态:-15
},
[modelAction.like]: {
// 喜欢
plusLess: virtualPlusLess.less, // -
[modelName.article]: 5 // 喜欢文章: -5
},
[modelAction.collect]: {
// 收藏
plusLess: virtualPlusLess.less, // -
[modelName.article_blog]: 5 // 收藏个人专栏: -5
},
[modelAction.comment]: {
// 创建评论-
plusLess: virtualPlusLess.less, // -
[modelName.article]: 5, // 创建文章评论:-5
[modelName.book]: 5, // 创建小书章节评论:-5
[modelName.books]: 5, // 创建小书评论:-5
[modelName.dynamic]: 5 // 创建动态评论:-5
},
[modelAction.reply]: {
// 回复评论-
plusLess: virtualPlusLess.less, // -
[modelName.article]: 5, // 创建文章回复:-5
[modelName.book]: 5, // 创建小书章节回复:-5
[modelName.books]: 5, // 创建小书回复:-5
[modelName.dynamic]: 5 // 创建动态回复:-5
},
[modelAction.thumb]: {
plusLess: virtualPlusLess.less, // -
[modelName.dynamic]: 5 // 点赞动态:-5
},
[modelAction.obtain_like]: {
plusLess: virtualPlusLess.plus, // +
[modelName.article]: 5 // 收到喜欢文章: +5
},
[modelAction.obtain_collect]: {
plusLess: virtualPlusLess.plus, // +
[modelName.article_blog]: 5 // 收到收藏个人专栏: +5
},
[modelAction.obtain_comment]: {
plusLess: virtualPlusLess.plus, // +
[modelName.article]: 5, // 收到文章评论:+5
[modelName.book]: 5, // 收到小书章节评论:+5
[modelName.books]: 5, // 收到小书评论:+5
[modelName.dynamic]: 5 // 收到动态评论:+5
},
[modelAction.obtain_reply]: {
plusLess: virtualPlusLess.plus, // +
[modelName.article]: 5, // 收到文章回复:+5
[modelName.book]: 5, // 收到小书章节回复:+5
[modelName.books]: 5, // 收到小书回复:+5
[modelName.dynamic]: 5 // 收到动态回复:+5
},
[modelAction.obtain_thumb]: {
plusLess: virtualPlusLess.plus, // +
[modelName.dynamic]: 5 // 收到点赞动态:+5
},
[modelAction.registered]: {
plusLess: virtualPlusLess.plus, // +
[modelName.system]: 1000 // 注册增加1000:+5
},
[modelAction.sendPrivateChat]: {
plusLess: virtualPlusLess.less, // -
[modelName.chat_message]: 10 // 发送私聊-15
}
}
// 2019.11.6 0:57
// 支付购买开始
export const payType = {
// 支付类型
shell: 1 // 贝壳
}
export const payTypeText = {
// 支付类型文案
[payType.shell]: '贝壳' // 贝壳
}
export const productTypeInfo = {
// 商品类型
[modelName.article]: {
model: 'article',
name: '文章',
isUse: false,
idKey: 'aid'
}, // 文章
[modelName.article_annex]: {
model: 'article_annex',
name: '文章附件',
isUse: true,
idKey: 'id'
}, // 文章
[modelName.books]: {
model: 'books',
name: '小书',
isUse: true,
idKey: 'books_id'
} // 小书
}
export const isFree = {
free: 1, // 免费
pay: 2 // 付费
}
export const isFreeText = {
[isFree.free]: '免费', // 免费
[isFree.pay]: '付费' // 付费
}
export const trialRead = {
// 是否可以试读
yes: 1, // 可以
no: 2 // 不可以
}
export const trialReadText = {
[trialRead.yes]: '开启', // 可以
[trialRead.no]: '关闭' // 不可以
}
// 获得经验的方式和数量
export const experienceInfo = {
[modelAction.obtain_thumb]: 10, // 收到点赞
[modelAction.readOther]: 1 // 阅读他人
}
export const userLevel = {
// 用户等级,和上方经验挂钩
one: 500,
two: 1000,
three: 2000,
four: 5000,
five: 10000
}
export const isOpen = {
// 是否可以试读
yes: 1, // 可以
no: 2 // 不可以
}
export const isOpenInfo = {
[isOpen.yes]: '开启', // 开启
[isOpen.no]: '关闭' // 关闭
} | the_stack |
/// <reference path="API.ts" />
namespace bws.packer
{
/**
* @brief Packer, a solver of 3d bin packing with multiple wrappers.
*
* @details
* <p> Packer is a facade class supporting packing operations in user side. You can solve a packing problem
* by constructing Packer class with {@link WrapperArray wrappers} and {@link InstanceArray instances} to
* pack and executing {@link optimize Packer.optimize()} method. </p>
*
* <p> In background side, deducting packing solution, those algorithms are used. </p>
* <ul>
* <li> <a href="http://betterwaysystems.github.io/packer/reference/AirForceBinPacking.pdf" target="_blank">
* Airforce Bin Packing; 3D pallet packing problem: A human intelligence-based heuristic approach </a>
* </li>
* <li> Genetic Algorithm </li>
* <li> Greedy and Back-tracking algorithm </li>
* </ul>
*
* @author Jeongho Nam <http://samchon.org>
*/
export class Packer
extends protocol.Entity
{
/**
* Candidate wrappers who can contain instances.
*/
protected wrapperArray: WrapperArray;
/**
* Instances trying to pack into the wrapper.
*/
protected instanceArray: InstanceArray;
/* -----------------------------------------------------------
CONSTRUCTORS
----------------------------------------------------------- */
/**
* Default Constructor.
*/
public constructor();
/**
* Construct from members.
*
* @param wrapperArray Candidate wrappers who can contain instances.
* @param instanceArray Instances to be packed into some wrappers.
*/
public constructor(wrapperArray: WrapperArray, instanceArray: InstanceArray);
public constructor(wrapperArray: WrapperArray = null, instanceArray: InstanceArray = null)
{
super();
if (wrapperArray == null && instanceArray == null)
{
this.wrapperArray = new WrapperArray();
this.instanceArray = new InstanceArray();
}
else
{
this.wrapperArray = wrapperArray;
this.instanceArray = instanceArray;
}
}
/**
* @inheritdoc
*/
public construct(xml: library.XML): void
{
this.wrapperArray.construct(xml.get(this.wrapperArray.TAG()).at(0));
this.instanceArray.construct(xml.get(this.instanceArray.TAG()).at(0));
}
/* -----------------------------------------------------------
GETTERS
----------------------------------------------------------- */
/**
* Get wrapperArray.
*/
public getWrapperArray(): WrapperArray
{
return this.wrapperArray;
}
/**
* Get instanceArray.
*/
public getInstanceArray(): InstanceArray
{
return this.instanceArray;
}
/* -----------------------------------------------------------
OPTIMIZERS
----------------------------------------------------------- */
/**
* <p> Deduct
*
*/
public optimize(): WrapperArray
{
if (this.instanceArray.empty() || this.wrapperArray.empty())
throw new std.InvalidArgument("Any instance or wrapper is not constructed.");
let wrappers: WrapperArray = new WrapperArray(); // TO BE RETURNED
if (this.wrapperArray.size() == 1)
{
// ONLY A TYPE OF WRAPPER EXISTS,
// OPTMIZE IN LEVEL OF WRAPPER_GROUP AND TERMINATE THE OPTIMIZATION
let wrapperGroup: WrapperGroup = new WrapperGroup(this.wrapperArray.front());
for (let i: number = 0; i < this.instanceArray.size(); i++)
if (wrapperGroup.allocate(this.instanceArray.at(i)) == false)
throw new std.LogicError("All instances are greater than the wrapper.");
// OPTIMIZE
wrapperGroup.optimize();
// ASSIGN WRAPPERS
wrappers.assign(wrapperGroup.begin(), wrapperGroup.end());
}
else
{
////////////////////////////////////////
// WITH GENETIC_ALGORITHM
////////////////////////////////////////
// CONSTRUCT INITIAL SET
let geneArray: GAWrapperArray = this.initGenes();
// EVOLVE
// IN JAVA_SCRIPT VERSION, GENETIC_ALGORITHM IS NOT IMPLEMENTED YET.
// HOWEVER, IN C++ VERSION, IT IS FULLY SUPPORTED
// http://samchon.github.io/framework/api/cpp/d5/d28/classsamchon_1_1library_1_1GeneticAlgorithm.html
// IT WILL BE SUPPORTED SOON
// FETCH RESULT
let result: std.HashMap<string, WrapperGroup> = geneArray.getResult();
for (let it = result.begin(); !it.equals(result.end()); it = it.next())
wrappers.insert(wrappers.end(), it.second.begin(), it.second.end());
// TRY TO REPACK
wrappers = this.repack(wrappers);
}
// SORT THE WRAPPERS BY ITEMS' POSITION
for (let i: number = 0; i < wrappers.size(); i++)
{
let wrapper: Wrapper = wrappers.at(i);
std.sort(wrapper.begin(), wrapper.end(),
function (left: Wrap, right: Wrap): boolean
{
if (left.getZ() != right.getZ())
return left.getZ() < right.getZ();
else if (left.getY() != right.getY())
return left.getY() < right.getY();
else
return left.getX() < right.getX();
}
);
}
if (wrappers.empty() == true)
throw new std.LogicError("All instances are greater than the wrapper.");
return wrappers;
}
/**
* @brief Initialize sequence list (gene_array).
*
* @details
* <p> Deducts initial sequence list by such assumption: </p>
*
* <ul>
* <li> Cost of larger wrapper is less than smaller one, within framework of price per volume unit. </li>
* <ul>
* <li> Wrapper Larger: (price: $1,000, volume: 100cm^3 -> price per volume unit: $10 / cm^3) </li>
* <li> Wrapper Smaller: (price: $700, volume: 50cm^3 -> price per volume unit: $14 / cm^3) </li>
* <li> Larger's <u>cost</u> is less than Smaller, within framework of price per volume unit </li>
* </ul>
* </ul>
*
* <p> Method {@link initGenes initGenes()} constructs {@link WrapperGroup WrapperGroups} corresponding
* with the {@link wrapperArray} and allocates {@link instanceArray instances} to a {@link WrapperGroup},
* has the smallest <u>cost</u> between containbles. </p>
*
* <p> After executing packing solution by {@link WrapperGroup.optimize WrapperGroup.optimize()}, trying to
* {@link repack re-pack} each {@link WrapperGroup} to another type of {@link Wrapper}, deducts the best
* solution between them. It's the initial sequence list of genetic algorithm. </p>
*
* @return Initial sequence list.
*/
protected initGenes(): GAWrapperArray
{
////////////////////////////////////////////////////
// LINEAR OPTIMIZATION
////////////////////////////////////////////////////
// CONSTRUCT WRAPPER_GROUPS
let wrapperGroups: std.Vector<WrapperGroup> = new std.Vector<WrapperGroup>();
for (let i: number = 0; i < this.wrapperArray.size(); i++)
{
let wrapper: Wrapper = this.wrapperArray.at(i);
wrapperGroups.push_back(new WrapperGroup(wrapper));
}
// ALLOCATE INSTNACES BY AUTHORITY
for (let i: number = 0; i < this.instanceArray.size(); i++)
{
let instance: Instance = this.instanceArray.at(i);
let minCost: number = Number.MAX_VALUE;
let minIndex: number = 0;
for (let j: number = 0; j < this.wrapperArray.size(); j++)
{
let wrapper: Wrapper = this.wrapperArray.at(j);
if (wrapper.containable(instance) == false)
continue; // CANNOT CONTAIN BY ITS GREATER SIZE
let cost = wrapper.getPrice() / wrapper.getContainableVolume();
if (cost < minCost)
{
// CURRENT WRAPPER'S PRICE PER UNIT VOLUME IS CHEAPER
minCost = cost;
minIndex = j;
}
}
// ALLOCATE TO A GROUP WHICH HAS THE MOST CHEAPER PRICE PER UNIT VOLUME
let wrapperGroup: WrapperGroup = wrapperGroups.at(minIndex);
wrapperGroup.allocate(instance);
}
////////////////////////////////////////////////////
// ADDICTIONAL OPTIMIZATION BY POST-PROCESS
////////////////////////////////////////////////////0
// OPTIMIZE WRAPPER_GROUP
let wrappers: WrapperArray = new WrapperArray();
for (let i: number = 0; i < wrapperGroups.size(); i++)
{
let wrapperGroup: WrapperGroup = wrapperGroups.at(i);
wrapperGroup.optimize();
wrappers.insert(wrappers.end(), wrapperGroup.begin(), wrapperGroup.end());
}
// DO EARLY POST-PROCESS
wrappers = this.repack(wrappers);
////////////////////////////////////////////////////
// CONSTRUCT GENE_ARRAY
////////////////////////////////////////////////////
// INSTANCES AND GENES
let ga_instances: InstanceArray = new InstanceArray();
let genes: WrapperArray = new WrapperArray();
for (let i: number = 0; i < wrappers.size(); i++)
{
let wrapper: Wrapper = wrappers.at(i);
for (let j: number = 0; j < wrapper.size(); j++)
{
ga_instances.push_back(wrapper.at(j).getInstance());
genes.push_back(wrapper);
}
}
// GENE_ARRAY
let geneArray: GAWrapperArray = new GAWrapperArray(ga_instances);
geneArray.assign(genes.begin(), genes.end());
return geneArray;
}
/**
* Try to repack each wrappers to another type.
*
* @param $wrappers Wrappers to repack.
* @return Re-packed wrappers.
*/
protected repack($wrappers: WrapperArray): WrapperArray
{
let result: WrapperArray = new WrapperArray();
for (let i: number = 0; i < $wrappers.size(); i++)
{
let wrapper: Wrapper = $wrappers.at(i);
let minGroup: WrapperGroup = new WrapperGroup(wrapper);
minGroup.push_back(wrapper);
for (let j: number = 0; j < this.wrapperArray.size(); j++)
{
let myWrapper: Wrapper = this.wrapperArray.at(j);
if (wrapper.equals(myWrapper))
continue;
let valid: boolean = true;
// CONSTRUCT GROUP OF TARGET
let myGroup: WrapperGroup = new WrapperGroup(myWrapper);
for (let k: number = 0; k < wrapper.size(); k++)
if (myGroup.allocate(wrapper.at(k).getInstance()) == false)
{
// IF THERE'S AN INSTANCE CANNOT CONTAIN BY ITS GREATER SIZE
valid = false;
break;
}
// SKIP
if (valid == false)
continue;
// OPTIMIZATION IN LEVEL OF GROUP
myGroup.optimize();
// CURRENT GROUP IS CHEAPER, THEN REPLACE
if (myGroup.getPrice() < minGroup.getPrice())
minGroup = myGroup;
}
result.insert(result.end(), minGroup.begin(), minGroup.end());
}
return result;
}
/* -----------------------------------------------------------
EXPORTERS
----------------------------------------------------------- */
/**
* @inheritdoc
*/
public TAG(): string
{
return "packer";
}
/**
* @inheritdoc
*/
public toXML(): library.XML
{
let xml: library.XML = super.toXML();
xml.push(this.wrapperArray.toXML());
xml.push(this.instanceArray.toXML());
return xml;
}
}
} | the_stack |
import React, { PureComponent } from "react";
import { compose, withHandlers } from "recompose";
import { connect } from "react-redux";
import { fromJS, Map, List } from "immutable";
import { schemaKeysFactory, schemaFieldFactory } from "fx-schema-form-core";
import { ErrorObject, ValidationError } from "ajv";
import { DefaultProps } from "../components";
import { RC, schemaFormTypes } from "../models";
import { hocFactory, errorFactory } from "../factory";
import { TreeMap, Tsn } from "./tree";
import { UtilsHocOutProps } from "../hocs/utils";
import { d, m } from "../reducers/reducer";
export interface SchemaFormHocSettings {
rootReducerKey: string[];
parentKeys: string[];
errorText?: (err: ErrorObject, props: DefaultProps, keys: Tsn[]) => string;
}
export interface SchemaFormProps extends SchemaFormHocOutProps {
root?: TreeMap;
data?: any;
errors?: any;
isValid?: boolean;
isValidating?: boolean;
formKey?: string;
initData?: any;
shouldResetForm?: boolean;
keepData?: boolean;
}
export interface SchemaFormHocOutProps {
validateAll?: ($async?: boolean) => Promise<any>;
resetForm?: (keepData?: boolean) => Promise<void>;
}
export const name = "schemaFormDec";
/**
* 提供全部验证等功能
* @param Component 需要包装的组件
*/
export default (settings: SchemaFormHocSettings = { rootReducerKey: [], parentKeys: [] }) => {
return (Component: any): RC<SchemaFormProps & DefaultProps, any> => {
// const keep
@(compose(
hocFactory.get("utils")(),
// 绑定数据
connect((state: Map<string, any>) => {
let rootKeys = settings.rootReducerKey.concat(settings.parentKeys),
dataKeys = rootKeys.concat([d]),
metaKeys = rootKeys.concat([m]),
root = state.getIn(metaKeys);
return {
data: state.getIn(dataKeys),
root: root,
isValid: root ? root.value.get("isValid") : true,
errors: root ? root.value.get("errors") : null,
isValidating: root ? root.value.get("isLoading") : false
};
}),
withHandlers<any, any>({
/**
* 验证所有的字段
*/
validateAll: (props: SchemaFormProps & DefaultProps & UtilsHocOutProps) => {
const { updateItemMeta } = props.getActions(props);
const options = props.getOptions(props, schemaFormTypes.hoc, name, fromJS(settings));
let timeId: any;
/**
* 验证所有字段
* async : boolean 是否是异步的
*/
return async (async?: boolean) => {
let root = props.root as TreeMap,
curAjv = props.ajv,
dataRaw = props.data,
validate = props.ajv.getSchema(props.schemaId),
$validateBeforeData = fromJS({
dirty: true,
isValid: true,
isLoading: true
}),
$validateAfterData = fromJS({ isLoading: false, dirty: true }),
normalizeDataPath = props.normalizeDataPath;
// 如果没有root,则跳出
if (!root) {
return;
}
// 如果没有validate,则报错
if (!validate) {
throw new Error(`没有找到对应的${props.schemaId};`);
}
try {
// 将所有的字段的meta数据标准化
root.forEach((node: TreeMap) => {
if (node.value) {
return node.value.merge($validateBeforeData);
}
return $validateBeforeData;
}, true);
// 验收更新meta数据
timeId = setTimeout(() => {
updateItemMeta({
parentKeys: options.parentKeys,
keys: [],
meta: root.value
});
}, 200);
if (Map.isMap(dataRaw) || List.isList(dataRaw)) {
dataRaw = dataRaw.toJS();
}
// 验证数据
curAjv.errors = undefined;
if (!await validate(dataRaw)) {
if (!validate.errors) {
validate.errors = [];
}
throw new (ValidationError as any)(validate.errors.concat(curAjv.errors || []));
}
// 设置成功的标志位
root.value = root.value.merge({
isValid: true
});
// 提交meta数据
updateItemMeta({
parentKeys: options.parentKeys,
keys: [],
meta: root.value
});
} catch (e) {
// 错误的逻辑
if (!(e instanceof (ValidationError as any))) {
return {
isValid: false,
errMsg: e.message
};
}
// 处理错误
e.errors.forEach((element: ErrorObject) => {
const schemaFormKeys = normalizeDataPath(props.schemaId, element.dataPath);
const dataKeys = root.getCurrentKeys().concat(schemaFormKeys);
const uiSchemaForParent: any = schemaFieldFactory.get(
schemaKeysFactory.get(schemaFormKeys.slice(0, -1).concat([props.schemaId]).join("/"))
);
let childNode = root.containPath(dataKeys);
if (!childNode) {
childNode = root.addChild(dataKeys, fromJS({}));
}
if (childNode) {
let errorText = "";
if (options.errorText) {
errorText = options.errorText(element, props, dataKeys);
}
errorText = errorText || errorFactory.get("single")([element], Object.assign({}, props, {
uiSchema: schemaFieldFactory.get(schemaKeysFactory.get(dataKeys.join("/")))
}), dataKeys);
childNode.value = childNode.value.merge($validateAfterData).merge({
isValid: false,
errorText
});
// 把子层的错误抛出到父层
if (uiSchemaForParent && childNode.parent && uiSchemaForParent.catchChild) {
if (!childNode.parent.value) {
childNode.parent.value = fromJS({});
}
childNode.parent.value = childNode.parent.value.merge($validateAfterData).merge({
isValid: false,
errorText
});
}
}
});
root.value = root.value.merge({
isValid: false,
errors: e.errors
});
} finally {
clearTimeout(timeId);
root.forEach((node: TreeMap) => {
if (node.value) {
return node.value.merge($validateAfterData);
}
return node.value;
}, true);
updateItemMeta({
parentKeys: options.parentKeys,
keys: [],
meta: root.value
});
}
return {
isValid: root.value.get("isValid"),
data: dataRaw
};
};
},
resetForm: (props: SchemaFormProps & DefaultProps & UtilsHocOutProps) => {
return async (keepData?: boolean) => {
const { formKey, shouldResetForm, keepData: pKeepData, ajv, getDefaultData, initData = {}, schemaId } = props;
if (formKey && shouldResetForm !== false) {
let { createForm } = props.getActions(props);
let schema: any = ajv.getSchema(schemaId).schema;
if (createForm && schema) {
createForm({
key: formKey,
keepData: typeof keepData === "undefined" ? pKeepData : keepData,
data: await getDefaultData(ajv, schema, initData, {}, true)
});
}
}
};
}
})) as any)
class SchemaFormComponentHoc extends PureComponent<SchemaFormProps & DefaultProps & UtilsHocOutProps, any> {
private _validateAll: (async?: boolean) => Promise<void>;
constructor(props: SchemaFormProps & DefaultProps & UtilsHocOutProps) {
super(props);
// 绑定当前的方法,可以使用autobind
if (props.validateAll) {
this._validateAll = props.validateAll.bind(this);
}
// 这里创建一个form,如果当前存在formKey,则覆盖掉当前的数据
if (props.resetForm) {
props.resetForm();
}
}
public render(): JSX.Element | null {
const { getRequiredKeys, getOptions, schemaId } = this.props,
options = getOptions(this.props, schemaFormTypes.hoc, name, fromJS(settings || {})),
extraProps = getRequiredKeys(this.props, options.hocIncludeKeys, options.hocExcludeKeys);
return (
<Component
validateAll={this._validateAll}
parentKeys={options.parentKeys}
schemaId={schemaId}
{...extraProps} />
);
}
}
return SchemaFormComponentHoc as any;
};
}; | the_stack |
import {
INodeProperties,
} from 'n8n-workflow';
export const userStoryOperations: INodeProperties[] = [
{
displayName: 'Operation',
name: 'operation',
type: 'options',
displayOptions: {
show: {
resource: [
'userStory',
],
},
},
options: [
{
name: 'Create',
value: 'create',
description: 'Create a user story',
},
{
name: 'Delete',
value: 'delete',
description: 'Delete a user story',
},
{
name: 'Get',
value: 'get',
description: 'Get a user story',
},
{
name: 'Get All',
value: 'getAll',
description: 'Get all user stories',
},
{
name: 'Update',
value: 'update',
description: 'Update a user story',
},
],
default: 'create',
description: 'Operation to perform',
},
];
export const userStoryFields: INodeProperties[] = [
// ----------------------------------------
// userStory: create
// ----------------------------------------
{
displayName: 'Project ID',
name: 'projectId',
description: 'ID of the project to which the user story belongs',
type: 'options',
typeOptions: {
loadOptionsMethod: 'getProjects',
},
required: true,
default: '',
displayOptions: {
show: {
resource: [
'userStory',
],
operation: [
'create',
],
},
},
},
{
displayName: 'Subject',
name: 'subject',
type: 'string',
required: true,
default: '',
displayOptions: {
show: {
resource: [
'userStory',
],
operation: [
'create',
],
},
},
},
{
displayName: 'Additional Fields',
name: 'additionalFields',
type: 'collection',
placeholder: 'Add Field',
default: {},
displayOptions: {
show: {
resource: [
'userStory',
],
operation: [
'create',
],
},
},
options: [
{
displayName: 'Assigned To',
name: 'assigned_to',
type: 'options',
typeOptions: {
loadOptionsDependsOn: [
'projectId',
],
loadOptionsMethod: 'getUsers',
},
default: '',
description: 'ID of the user to whom the user story is assigned',
},
{
displayName: 'Backlog Order',
name: 'backlog_order',
type: 'number',
default: 1,
typeOptions: {
minValue: 1,
},
description: 'Order of the user story in the backlog',
},
{
displayName: 'Blocked Note',
name: 'blocked_note',
type: 'string',
default: '',
description: 'Reason why the user story is blocked. Requires "Is Blocked" toggle to be enabled',
},
{
displayName: 'Description',
name: 'description',
type: 'string',
default: '',
},
{
displayName: 'Is Blocked',
name: 'is_blocked',
type: 'boolean',
default: false,
description: 'Whether the user story is blocked',
},
{
displayName: 'Kanban Order',
name: 'kanban_order',
type: 'number',
default: 1,
typeOptions: {
minValue: 1,
},
description: 'Order of the user story in the kanban',
},
{
displayName: 'Milestone (Sprint)',
name: 'milestone',
type: 'options',
typeOptions: {
loadOptionsDependsOn: [
'projectId',
],
loadOptionsMethod: 'getMilestones',
},
default: '',
description: 'ID of the milestone of the user story',
},
{
displayName: 'Sprint Order',
name: 'sprint_order',
type: 'number',
default: 1,
typeOptions: {
minValue: 1,
},
description: 'Order of the user story in the milestone',
},
{
displayName: 'Status',
name: 'status',
type: 'options',
typeOptions: {
loadOptionsDependsOn: [
'projectId',
],
loadOptionsMethod: 'getUserStoryStatuses',
},
default: '',
description: 'ID of the status of the user story',
},
{
displayName: 'Tags',
name: 'tags',
type: 'multiOptions',
typeOptions: {
loadOptionsDependsOn: [
'projectId',
],
loadOptionsMethod: 'getTags',
},
default: [],
},
{
displayName: 'Type',
name: 'type',
type: 'options',
typeOptions: {
loadOptionsDependsOn: [
'projectId',
],
loadOptionsMethod: 'getTypes',
},
default: '',
},
],
},
// ----------------------------------------
// userStory: delete
// ----------------------------------------
{
displayName: 'User Story ID',
name: 'userStoryId',
description: 'ID of the user story to delete',
type: 'string',
required: true,
default: '',
displayOptions: {
show: {
resource: [
'userStory',
],
operation: [
'delete',
],
},
},
},
// ----------------------------------------
// userStory: get
// ----------------------------------------
{
displayName: 'User Story ID',
name: 'userStoryId',
description: 'ID of the user story to retrieve',
type: 'string',
required: true,
default: '',
displayOptions: {
show: {
resource: [
'userStory',
],
operation: [
'get',
],
},
},
},
// ----------------------------------------
// userStory: getAll
// ----------------------------------------
{
displayName: 'Project ID',
name: 'projectId',
description: 'ID of the project to which the user story belongs',
type: 'options',
typeOptions: {
loadOptionsMethod: 'getProjects',
},
required: true,
default: '',
displayOptions: {
show: {
resource: [
'userStory',
],
operation: [
'getAll',
],
},
},
},
{
displayName: 'Return All',
name: 'returnAll',
type: 'boolean',
default: false,
description: 'Whether to return all results or only up to a given limit',
displayOptions: {
show: {
resource: [
'userStory',
],
operation: [
'getAll',
],
},
},
},
{
displayName: 'Limit',
name: 'limit',
type: 'number',
default: 50,
description: 'How many results to return',
typeOptions: {
minValue: 1,
},
displayOptions: {
show: {
resource: [
'userStory',
],
operation: [
'getAll',
],
returnAll: [
false,
],
},
},
},
{
displayName: 'Filters',
name: 'filters',
type: 'collection',
placeholder: 'Add Filter',
displayOptions: {
show: {
resource: [
'userStory',
],
operation: [
'getAll',
],
},
},
default: {},
options: [
{
displayName: 'Assigned To',
name: 'assigned_to',
description: 'ID of the user whom the user story is assigned to',
type: 'options',
typeOptions: {
loadOptionsDependsOn: [
'projectId',
],
loadOptionsMethod: 'getUsers',
},
default: '',
},
{
displayName: 'Epic',
name: 'epic',
description: 'ID of the epic to which the user story belongs',
type: 'options',
typeOptions: {
loadOptionsDependsOn: [
'projectId',
],
loadOptionsMethod: 'getEpics',
},
default: '',
},
{
displayName: 'Is Closed',
name: 'statusIsClosed',
description: 'Whether the user story is closed',
type: 'boolean',
default: false,
},
{
displayName: 'Is Archived',
name: 'statusIsArchived',
description: 'Whether the user story has been archived',
type: 'boolean',
default: false,
},
{
displayName: 'Milestone (Sprint)',
name: 'milestone',
type: 'options',
typeOptions: {
loadOptionsDependsOn: [
'projectId',
],
loadOptionsMethod: 'getMilestones',
},
default: '',
description: 'ID of the milestone of the user story',
},
{
displayName: 'Role',
name: 'role',
type: 'options',
typeOptions: {
loadOptionsDependsOn: [
'projectId',
],
loadOptionsMethod: 'getRoles',
},
default: '',
},
{
displayName: 'Status',
name: 'status',
description: 'ID of the status of the user story',
type: 'options',
typeOptions: {
loadOptionsDependsOn: [
'projectId',
],
loadOptionsMethod: 'getUserStoryStatuses',
},
default: '',
},
{
displayName: 'Tags',
name: 'tags',
type: 'multiOptions',
typeOptions: {
loadOptionsDependsOn: [
'projectId',
],
loadOptionsMethod: 'getTags',
},
default: [],
},
],
},
// ----------------------------------------
// userStory: update
// ----------------------------------------
{
displayName: 'Project ID',
name: 'projectId',
type: 'options',
typeOptions: {
loadOptionsMethod: 'getProjects',
},
default: '',
description: 'ID of the project to set the user story to',
displayOptions: {
show: {
resource: [
'userStory',
],
operation: [
'update',
],
},
},
},
{
displayName: 'User Story ID',
name: 'userStoryId',
description: 'ID of the user story to update',
type: 'string',
required: true,
default: '',
displayOptions: {
show: {
resource: [
'userStory',
],
operation: [
'update',
],
},
},
},
{
displayName: 'Update Fields',
name: 'updateFields',
type: 'collection',
placeholder: 'Add Field',
default: {},
displayOptions: {
show: {
resource: [
'userStory',
],
operation: [
'update',
],
},
},
options: [
{
displayName: 'Assigned To',
name: 'assigned_to',
type: 'options',
typeOptions: {
loadOptionsDependsOn: [
'projectId',
],
loadOptionsMethod: 'getUsers',
},
default: '',
description: 'ID of the user to assign the the user story to',
},
{
displayName: 'Backlog Order',
name: 'backlog_order',
type: 'number',
default: 1,
typeOptions: {
minValue: 1,
},
description: 'Order of the user story in the backlog',
},
{
displayName: 'Blocked Note',
name: 'blocked_note',
type: 'string',
default: '',
description: 'Reason why the user story is blocked. Requires "Is Blocked" toggle to be enabled',
},
{
displayName: 'Description',
name: 'description',
type: 'string',
default: '',
},
{
displayName: 'Is Blocked',
name: 'is_blocked',
type: 'boolean',
default: false,
description: 'Whether the user story is blocked',
},
{
displayName: 'Kanban Order',
name: 'kanban_order',
type: 'number',
default: 1,
typeOptions: {
minValue: 1,
},
description: 'Order of the user story in the kanban',
},
{
displayName: 'Milestone (Sprint)',
name: 'milestone',
type: 'options',
typeOptions: {
loadOptionsDependsOn: [
'projectId',
],
loadOptionsMethod: 'getMilestones',
},
default: '',
description: 'ID of the milestone of the user story',
},
{
displayName: 'Subject',
name: 'subject',
type: 'string',
default: '',
},
{
displayName: 'Sprint Order',
name: 'sprint_order',
type: 'number',
default: 1,
typeOptions: {
minValue: 1,
},
description: 'Order of the user story in the milestone',
},
{
displayName: 'Status',
name: 'status',
type: 'options',
typeOptions: {
loadOptionsDependsOn: [
'projectId',
],
loadOptionsMethod: 'getUserStoryStatuses',
},
default: '',
description: 'ID of the status of the user story',
},
{
displayName: 'Tags',
name: 'tags',
type: 'multiOptions',
typeOptions: {
loadOptionsDependsOn: [
'projectId',
],
loadOptionsMethod: 'getTags',
},
default: [],
},
{
displayName: 'Type',
name: 'type',
type: 'options',
typeOptions: {
loadOptionsDependsOn: [
'projectId',
],
loadOptionsMethod: 'getTypes',
},
default: '',
},
],
},
]; | the_stack |
import {Mutable, Class, AnyTiming, Timing} from "@swim/util";
import {Affinity, FastenerOwner, Property} from "@swim/component";
import {Length} from "@swim/math";
import {Look, Mood, ThemeAnimator} from "@swim/theme";
import {ViewportInsets, ViewContextType, ViewContext, View, ViewRefFactory, ViewRef} from "@swim/view";
import {HtmlView} from "@swim/dom";
import {DeckBar} from "./DeckBar";
import {DeckCard} from "./DeckCard";
import type {DeckViewObserver} from "./DeckViewObserver";
/** @public */
export class DeckView extends HtmlView {
constructor(node: HTMLElement) {
super(node);
this.cardCount = 0;
this.card = null;
this.initDeck();
}
protected initDeck(): void {
this.addClass("deck");
this.position.setState("relative", Affinity.Intrinsic);
this.overflowX.setState("hidden", Affinity.Intrinsic);
this.overflowY.setState("hidden", Affinity.Intrinsic);
}
override readonly observerType?: Class<DeckViewObserver>;
@ThemeAnimator({type: Number, value: 0, updateFlags: View.NeedsLayout})
readonly deckPhase!: ThemeAnimator<this, number>;
@Property({type: Number, value: 1})
readonly inAlign!: Property<this, number>;
@Property({type: Number, value: 1 / 3})
readonly outAlign!: Property<this, number>;
@Property({type: Object, inherits: true, value: null, updateFlags: View.NeedsResize})
readonly edgeInsets!: Property<this, ViewportInsets | null>;
/** @internal */
readonly bar!: DeckViewBar<this, DeckBar>; // defined by DeckViewBar
/** @internal */
cardCount: number;
card: ViewRef<this, DeckCard> | null;
pushCard(newCardView: DeckCard, timing?: AnyTiming | boolean): void {
if (this.deckPhase.tweening) {
return;
}
const oldCardCount = this.cardCount;
const newCardCount = oldCardCount + 1;
this.cardCount = newCardCount;
const oldCardKey = "card" + oldCardCount;
const oldCardRef = this.getFastener(oldCardKey, ViewRef) as DeckViewCard<this, DeckCard> | null;
const oldCardView = oldCardRef !== null ? oldCardRef.view : null;
const newCardKey = "card" + newCardCount;
const newCardRef = DeckViewCardRef.create(this) as DeckViewCard<this, DeckCard>;
Object.defineProperty(newCardRef, "name", {
value: newCardKey,
configurable: true,
})
newCardRef.cardIndex = newCardCount;
this.willPushCard(newCardView, oldCardView);
this.card = newCardRef;
this.setFastener(newCardKey, newCardRef);
newCardRef.setView(newCardView);
newCardRef.insertView();
if (timing === void 0 && oldCardCount === 0) {
timing = false;
} else if (timing === void 0 || timing === true) {
timing = this.getLookOr(Look.timing, Mood.navigating, false);
} else {
timing = Timing.fromAny(timing);
}
this.deckPhase.setState(newCardCount, timing);
this.onPushCard(newCardView, oldCardView);
if (timing === false) {
this.didPushCard(newCardView, oldCardView);
}
}
protected willPushCard(newCardView: DeckCard, oldCardView: DeckCard | null): void {
this.forEachObserver(function (observer: DeckViewObserver): void {
if (observer.deckWillPushCard !== void 0) {
observer.deckWillPushCard(newCardView, oldCardView, this);
}
});
}
protected onPushCard(newCardView: DeckCard, oldCardView: DeckCard | null): void {
// hook
}
protected didPushCard(newCardView: DeckCard, oldCardView: DeckCard | null): void {
if (oldCardView !== null && oldCardView.parent === this) {
oldCardView.remove();
}
this.forEachObserver(function (observer: DeckViewObserver): void {
if (observer.deckDidPushCard !== void 0) {
observer.deckDidPushCard(newCardView, oldCardView, this);
}
});
}
popCard(timing?: AnyTiming | boolean): DeckCard | null {
if (this.deckPhase.tweening) {
return null;
}
const oldCardCount = this.cardCount;
const newCardCount = oldCardCount - 1;
this.cardCount = newCardCount;
const oldCardKey = "card" + oldCardCount;
const oldCardRef = this.getFastener(oldCardKey, ViewRef) as DeckViewCard<this, DeckCard> | null;
const oldCardView = oldCardRef !== null ? oldCardRef.view : null;
if (oldCardView !== null) {
const newCardKey = "card" + newCardCount;
const newCardRef = this.getFastener(newCardKey, ViewRef) as DeckViewCard<this, DeckCard> | null;
const newCardView = newCardRef !== null ? newCardRef.view : null;
this.willPopCard(newCardView, oldCardView);
this.card = newCardRef;
if (newCardRef !== null) {
newCardRef.insertView();
}
if (timing === void 0 || timing === true) {
timing = this.getLookOr(Look.timing, Mood.navigating, false);
} else {
timing = Timing.fromAny(timing);
}
this.deckPhase.setState(newCardCount, timing);
this.onPopCard(newCardView, oldCardView);
if (timing === false) {
this.didPopCard(newCardView, oldCardView);
}
}
return oldCardView;
}
protected willPopCard(newCardView: DeckCard | null, oldCardView: DeckCard): void {
this.forEachObserver(function (observer: DeckViewObserver): void {
if (observer.deckWillPopCard !== void 0) {
observer.deckWillPopCard(newCardView, oldCardView, this);
}
});
}
protected onPopCard(newCardView: DeckCard | null, oldCardView: DeckCard): void {
// hook
}
protected didPopCard(newCardView: DeckCard | null, oldCardView: DeckCard): void {
const oldCardKey = oldCardView.key;
oldCardView.remove();
if (oldCardKey !== void 0) {
const oldCardRef = this.getFastener(oldCardKey, ViewRef) as DeckViewCard<this, DeckCard> | null;
if (oldCardRef !== null && oldCardRef.cardIndex > this.cardCount) {
this.setFastener(oldCardKey, null);
}
}
this.forEachObserver(function (observer: DeckViewObserver): void {
if (observer.deckDidPopCard !== void 0) {
observer.deckDidPopCard(newCardView, oldCardView, this);
}
});
}
protected override didLayout(viewContext: ViewContextType<this>): void {
if (!this.deckPhase.tweening) {
const deckPhase = this.deckPhase.value;
if (deckPhase !== void 0) {
const nextCardIndex = Math.round(deckPhase + 1);
const nextCardKey = "card" + nextCardIndex;
const nextCardRef = this.getFastener(nextCardKey, ViewRef) as DeckViewCard<this, DeckCard> | null;
const nextCardView = nextCardRef !== null ? nextCardRef.view : null;
if (nextCardView !== null) {
this.didPopCard(this.card !== null ? this.card.view : null, nextCardView);
} else if (this.card !== null && this.card.view !== null && Math.round(deckPhase) > 0) {
const prevCardIndex = Math.round(deckPhase - 1);
const prevCardKey = "card" + prevCardIndex;
const prevCardRef = this.getFastener(prevCardKey, ViewRef) as DeckViewCard<this, DeckCard> | null;
const catdCardView = prevCardRef !== null ? prevCardRef.view : null;
this.didPushCard(this.card.view, catdCardView);
}
}
}
super.didLayout(viewContext);
}
/** @internal */
didPressBackButton(event: Event | null): void {
this.forEachObserver(function (observer: DeckViewObserver): void {
if (observer.deckDidPressBackButton !== void 0) {
observer.deckDidPressBackButton(event, this);
}
});
}
/** @internal */
didPressCloseButton(event: Event | null): void {
this.forEachObserver(function (observer: DeckViewObserver): void {
if (observer.deckDidPressCloseButton !== void 0) {
observer.deckDidPressCloseButton(event, this);
}
});
}
}
/** @internal */
export interface DeckViewBar<O extends DeckView = DeckView, V extends DeckBar = DeckBar> extends ViewRef<O, V> {
/** @override */
didAttachView(barView: V): void;
/** @override */
insertChild(parent: View, child: V, target: View | number | null, key: string | undefined): void;
viewDidResize(viewContext: ViewContext, barView: V): void;
/** @protected */
initBar(barView: V): void;
/** @protected */
resizeBar(barView: V): void;
deckBarDidPressBackButton(event: Event | null, view: O): void;
deckBarDidPressCloseButton(event: Event | null, view: O): void;
}
/** @internal */
export const DeckViewBar = (function (_super: typeof ViewRef) {
const DeckViewBar = _super.extend("DeckSliderItem") as ViewRefFactory<DeckViewBar<any, any>>;
DeckViewBar.prototype.didAttachView = function (this: DeckViewBar, barView: DeckBar): void {
this.initBar(barView);
};
DeckViewBar.prototype.insertChild = function (this: DeckViewBar, parent: View, child: DeckBar, target: View | number | null, key: string | undefined): void {
parent.prependChild(child, key);
};
DeckViewBar.prototype.viewDidResize = function (this: DeckViewBar, viewContext: ViewContext, barView: DeckBar): void {
this.resizeBar(barView);
};
DeckViewBar.prototype.initBar = function (this: DeckViewBar, barView: DeckBar): void {
let deckWidth = this.owner.width.state;
deckWidth = deckWidth instanceof Length ? deckWidth : Length.px(this.owner.node.offsetWidth);
barView.position.setState("absolute", Affinity.Intrinsic);
barView.left.setState(0, Affinity.Intrinsic);
barView.top.setState(0, Affinity.Intrinsic);
barView.width.setState(deckWidth, Affinity.Intrinsic);
barView.zIndex.setState(1, Affinity.Intrinsic);
};
DeckViewBar.prototype.resizeBar = function (this: DeckViewBar, barView: DeckBar): void {
let deckWidth = this.owner.width.state;
deckWidth = deckWidth instanceof Length ? deckWidth : Length.px(this.owner.node.offsetWidth);
barView.width.setState(deckWidth, Affinity.Intrinsic);
};
DeckViewBar.prototype.deckBarDidPressBackButton = function (this: DeckViewBar, event: Event | null): void {
this.owner.didPressBackButton(event);
};
DeckViewBar.prototype.deckBarDidPressCloseButton = function (this: DeckViewBar, event: Event | null): void {
this.owner.didPressCloseButton(event);
};
return DeckViewBar;
})(ViewRef);
ViewRef({
extends: DeckViewBar,
key: true,
type: DeckBar,
binds: true,
observes: true,
})(DeckView.prototype, "bar");
/** @internal */
export interface DeckViewCard<O extends DeckView = DeckView, V extends DeckCard = DeckCard> extends ViewRef<O, V> {
cardIndex: number;
/** @override */
didAttachView(cardView: V): void;
/** @override */
insertChild(parent: View, child: V, target: View | number | null, key: string | undefined): void;
viewDidResize(viewContext: ViewContext, cardView: V): void;
viewDidLayout(viewContext: ViewContext, cardView: V): void;
/** @protected */
initCard(cardView: V): void;
/** @protected */
resizeCard(cardView: V, viewContext: ViewContext): void;
/** @protected */
layoutCard(cardView: V, viewContext: ViewContext): void;
}
/** @internal */
export const DeckViewCard = (function (_super: typeof ViewRef) {
const DeckViewCard = _super.extend("DeckSliderItem") as ViewRefFactory<DeckViewCard<any, any>>;
DeckViewCard.prototype.didAttachView = function (this: DeckViewCard, cardView: DeckCard): void {
this.initCard(cardView);
};
DeckViewCard.prototype.insertChild = function (this: DeckViewCard, parent: View, child: DeckCard, target: View | number | null, key: string | undefined): void {
const targetKey = "card" + (this.cardIndex + 1);
target = parent.getChild(targetKey);
parent.insertChild(child, target, key);
};
DeckViewCard.prototype.viewDidResize = function (this: DeckViewCard, viewContext: ViewContext, cardView: DeckCard): void {
this.resizeCard(cardView, viewContext);
};
DeckViewCard.prototype.viewDidLayout = function (this: DeckViewCard, viewContext: ViewContext, cardView: DeckCard): void {
this.layoutCard(cardView, viewContext);
};
DeckViewCard.prototype.initCard = function (this: DeckViewCard, cardView: DeckCard): void {
let edgeInsets = this.owner.edgeInsets.value;
if (edgeInsets === void 0 && this.owner.edgeInsets.hasAffinity(Affinity.Intrinsic)) {
edgeInsets = this.owner.viewport.safeArea;
}
let deckWidth = this.owner.width.state;
deckWidth = deckWidth instanceof Length ? deckWidth : Length.px(this.owner.node.offsetWidth);
let deckHeight = this.owner.height.state;
deckHeight = deckHeight instanceof Length ? deckHeight : Length.px(this.owner.node.offsetHeight);
let barHeight: Length | null = null;
const barView = this.owner.bar.view;
if (barView !== null) {
barHeight = barView.height.state;
barHeight = barHeight instanceof Length ? barHeight : Length.px(barView.node.offsetHeight);
if (edgeInsets !== null) {
edgeInsets = {
insetTop: 0,
insetRight: edgeInsets.insetRight,
insetBottom: edgeInsets.insetBottom,
insetLeft: edgeInsets.insetLeft,
};
}
}
cardView.edgeInsets.setValue(edgeInsets, Affinity.Intrinsic);
cardView.position.setState("absolute", Affinity.Intrinsic);
cardView.left.setState(deckWidth, Affinity.Intrinsic);
cardView.top.setState(0, Affinity.Intrinsic);
cardView.width.setState(deckWidth, Affinity.Intrinsic);
cardView.height.setState(deckHeight, Affinity.Intrinsic);
cardView.paddingTop.setState(barHeight, Affinity.Intrinsic);
cardView.boxSizing.setState("border-box", Affinity.Intrinsic);
cardView.zIndex.setState(0, Affinity.Intrinsic);
cardView.visibility.setState("hidden", Affinity.Intrinsic);
};
DeckViewCard.prototype.resizeCard = function (this: DeckViewCard, cardView: DeckCard, viewContext: ViewContext): void {
let edgeInsets = this.owner.edgeInsets.value;
if (edgeInsets === void 0 && this.owner.edgeInsets.hasAffinity(Affinity.Intrinsic)) {
edgeInsets = viewContext.viewport.safeArea;
}
let deckWidth = this.owner.width.state;
deckWidth = deckWidth instanceof Length ? deckWidth : Length.px(this.owner.node.offsetWidth);
let deckHeight = this.owner.height.state;
deckHeight = deckHeight instanceof Length ? deckHeight : Length.px(this.owner.node.offsetHeight);
let barHeight: Length | null = null;
const barView = this.owner.bar.view;
if (barView !== null) {
barHeight = barView.height.state;
barHeight = barHeight instanceof Length ? barHeight : Length.px(barView.node.offsetHeight);
if (edgeInsets !== null) {
edgeInsets = {
insetTop: 0,
insetRight: edgeInsets.insetRight,
insetBottom: edgeInsets.insetBottom,
insetLeft: edgeInsets.insetLeft,
};
}
}
cardView.edgeInsets.setValue(edgeInsets, Affinity.Intrinsic);
cardView.width.setState(deckWidth, Affinity.Intrinsic);
cardView.height.setState(deckHeight, Affinity.Intrinsic);
cardView.paddingTop.setState(barHeight, Affinity.Intrinsic);
};
DeckViewCard.prototype.layoutCard = function (this: DeckViewCard, cardView: DeckCard, viewContext: ViewContext): void {
let cardWidth = cardView.width.state;
cardWidth = cardWidth instanceof Length ? cardWidth : Length.px(cardView.node.offsetWidth);
const inAlign = this.owner.inAlign.value;
const outAlign = this.owner.outAlign.value;
const deckPhase = this.owner.deckPhase.getValue();
const nextIndex = Math.max(this.owner.cardCount, Math.ceil(deckPhase));
const prevIndex = nextIndex - 1;
const cardPhase = deckPhase - prevIndex;
const cardIndex = this.cardIndex;
if (cardIndex < prevIndex || cardIndex === prevIndex && cardPhase === 1) { // under
cardView.left.setState(-cardWidth.pxValue() * outAlign, Affinity.Intrinsic);
cardView.visibility.setState("hidden", Affinity.Intrinsic);
cardView.setCulled(true);
} else if (cardIndex === prevIndex) { // out
cardView.left.setState(-cardWidth.pxValue() * outAlign * cardPhase, Affinity.Intrinsic);
cardView.visibility.setState(void 0, Affinity.Intrinsic);
cardView.setCulled(false);
} else if (cardIndex === nextIndex) { // in
cardView.left.setState(cardWidth.pxValue() * inAlign * (1 - cardPhase), Affinity.Intrinsic);
cardView.visibility.setState(void 0, Affinity.Intrinsic);
cardView.setCulled(false);
} else { // over
cardView.left.setState(cardWidth.pxValue() * inAlign, Affinity.Intrinsic);
cardView.visibility.setState("hidden", Affinity.Intrinsic);
cardView.setCulled(true);
}
};
DeckViewCard.construct = function <F extends DeckViewCard<any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F {
fastener = _super.construct(fastenerClass, fastener, owner) as F;
(fastener as Mutable<typeof fastener>).cardIndex = 0;
return fastener;
};
return DeckViewCard;
})(ViewRef);
/** @internal */
export const DeckViewCardRef = ViewRef.define<DeckView, DeckCard>("DeckViewCardRef", {
extends: DeckViewCard,
key: true,
type: DeckCard,
observes: true,
}); | the_stack |
export { AccordionModule } from './components/accordion/index';
export { TlAccordion } from './components/accordion/accordion';
export { TlAccordionItem } from './components/accordion/parts/accordion-item/accordion-item';
// Autocomplete
export { AutoCompleteModule } from './components/autocomplete/index';
export { TlAutoComplete } from './components/autocomplete/autocomplete';
export { TlAutocompleteTemplate } from './components/autocomplete/components/autocomplete-template';
// Avatar
export { AvatarModule } from './components/avatar/index';
export { TlAvatar } from './components/avatar/avatar';
// Badge
export { BadgeModule } from './components/badge/index';
export { TlBadge } from './components/badge/badge';
// Button
export { ButtonModule } from './components/button/index';
export { TlButton } from './components/button/button';
// Button Group
export { ButtonGroupModule } from './components/buttongroup/index';
export { TlButtonGroup } from './components/buttongroup/buttongroup';
export { TlButtonGroupItem } from './components/buttongroup/buttongroup-item';
// Block UI
export { BlockUIModule } from './components/blockui/index';
export { TlBlockUI } from './components/blockui/blockui';
export { TlBlockUIComponent } from './components/blockui/blockui.component';
// Card
export { CardModule } from './components/card/index';
export { TlCard } from './components/card/card';
export { TlCardBody } from './components/card/parts/card-body/card-body';
export { TlCardFooter } from './components/card/parts/card-footer/card-footer';
export { TlCardHeader } from './components/card/parts/card-header/card-header';
// Checkbox
export { CheckBoxModule } from './components/checkbox/index';
export { TlCheckBox } from './components/checkbox/checkbox';
// Chatlist
export { ChatListModule } from './components/chatlist/index';
export { TlChatList } from './components/chatlist/chatlist';
export { TlChatContent } from './components/chatlist/parts/chat-content';
export { TlStatusFilterPipe } from './components/chatlist/pipes/status-filter.pipe';
export { TlMessageFilterPipe } from './components/chatlist/pipes/message-filter.pipe';
export { ChatContact } from './components/chatlist/interfaces/chat-contact.interface';
export { ChatMessage } from './components/chatlist/interfaces/chat-message.interface';
export { ChatStatus } from './components/chatlist/interfaces/chat-status.interface';
export { Status } from './components/chatlist/enums/status.enum';
export { ChatService } from './components/chatlist/services/chat.service';
// Calendar
export { CalendarModule } from './components/calendar/index';
export { TlCalendar } from './components/calendar/calendar';
export { TlCalendarDays } from './components/calendar/parts/calendar-days/calendar-days';
export { TlCalendarMonths } from './components/calendar/parts/calendar-months/calendar-months';
export { TlCalendarYears } from './components/calendar/parts/calendar-years/calendar-years';
export { TlHolidayPipe } from './components/calendar/pipes/holiday';
export { TlHolidayTooltipDirective } from './components/calendar/directives/holiday-tooltip';
export { CalendarStatus } from './components/calendar/interfaces/calendar-status.interface';
export { CalendarHoliday } from './components/calendar/interfaces/calendar-holiday.interface';
// Clock Picker
export { ClockPickerModule } from './components/clockpicker/index';
export { TlClockPicker } from './components/clockpicker/clockpicker';
// Color Picker
export { ColorPickerModule } from './components/colorpicker/index';
export { TlColorPicker } from './components/colorpicker/colorpicker';
// Core
export { CoreModule } from './components/core/index';
export { TlCore } from './components/core/core';
export { LimitStringPipe } from './components/core/helper/limitstring.pipe';
export { ActionsModal } from './components/core/enums/actions-modal';
export { KeyEvent } from './components/core/enums/key-events';
export { ModalResult } from './components/core/enums/modal-result';
export { CoreService } from './components/core/services/core.service';
// Container
export { ContainerModalModule } from './components/modal/addons/container-modal/index';
export { TlContainerModalDirective } from './components/modal/addons/container-modal/container-modal.directive';
// Contextmenu
export { ContextMenuModule } from './components/contextmenu/index';
export { TlContextMenuComponent } from './components/contextmenu/context-menu';
export { ContextMenuService } from './components/contextmenu/services/contextmenu.service';
// Datatable
export { DatatableModule } from './components/datatable/index';
export { TlDatatable } from './components/datatable/datatable';
export { TlDatatableColumn } from './components/datatable/parts/column/datatable-column';
// Date
export { DateModule } from './components/date/index';
export { TlDate } from './components/date/date';
export { DateDirective } from './components/date/directives/date.directive';
// Date Picker
export { DatePickerModule } from './components/datepicker/index';
export { TlDatePicker } from './components/datepicker/datepicker';
export { TlDatePickerContent } from './components/datepicker/datepicker-content/datepicker-content';
// Dialog
export { DialogModule } from './components/dialog/index';
export { TlDialogAlert } from './components/dialog/dialog-alert/dialog-alert';
export { TlDialogConfirmation } from './components/dialog/dialog-confirmation/dialog-confirmation';
export { TlDialogError } from './components/dialog/dialog-error/dialog-error';
export { TlDialogInfo } from './components/dialog/dialog-info/dialog-info';
export { InfoOptions } from './components/dialog/dialog-info/info-options';
export { ErrorOptions } from './components/dialog/dialog-error/error-options';
export { AlertOptions } from './components/dialog/dialog-alert/alert-options';
export { ConfirmationOptions } from './components/dialog/dialog-confirmation/confirmation-options';
export { DialogService } from './components/dialog/dialog.service';
// Dropdownlist
export { DropDownListModule } from './components/dropdownlist/index';
export { TlDropDownList } from './components/dropdownlist/dropdownlist';
// Editor
export { EditorModule } from './components/editor/index';
export { TlEditor } from './components/editor/editor';
export { TlEditorLinkBox } from './components/editor/parts/editor-link-box/editor-link-box';
export { TlEditorImageBox } from './components/editor/parts/editor-image-box/editor-image-box';
export { TlEditorHeader } from './components/editor/parts/editor-header/editor-header';
export { TagContent } from './components/editor/interfaces/tag-content';
export { FieldContent } from './components/editor/interfaces/field-content';
export { EditorService } from './components/editor/services/editor.service';
// Form
export { FormModule } from './components/form/index';
export { TlForm } from './components/form/form';
export { FormSubmitDirective } from './components/form/form-submit.directive';
// Icons
export { IconsModule } from './components/icons/index';
export { TlIcons } from './components/icons/icons';
// Input
export { InputModule } from './components/input/index';
export { TlInput } from './components/input/input';
export { CharcaseDirective } from './components/input/directives/charcase.directive';
export { CurrencyDirective } from './components/input/directives/currency/currency.directive';
// Listbox
export { ListBoxModule} from './components/listbox/index';
export { TlListBox } from './components/listbox/listbox';
// Lightbox
export { LightboxModule } from './components/lightbox/index';
export { TlLightbox } from './components/lightbox/lightbox';
export { ImageLightboxInterface } from './components/lightbox/interfaces/image.interface';
export { LightboxService } from './components/lightbox/services/lightbox.service';
// Loader
export { LoaderModule } from './components/loader/index';
export { TlLoader } from './components/loader/loader';
// Menu
export { MenuModule } from './components/menu/index';
export { TlMenu } from './components/menu/menu';
export { TlAdvancedRootMenu } from './components/menu/parts/advanced/advanced-root-menu';
export { TlAdvancedSubMenu } from './components/menu/parts/advanced/parts/advanced-sub-menu';
export { TlSimpleSubMenu } from './components/menu/parts/simple/simple-sub-menu';
// Misc
export { MiscModule } from './components/misc/index';
export { RelativeWindowPosition } from './components/misc/relative-window-position.directive';
export { FixedPositionDirective } from './components/misc/fixed-position.directive';
export { ListOptionDirective } from './components/misc/listoption.directive';
export { ScrollManager } from './components/misc/scroll-manager.directive';
export { HighlightPipe } from './components/misc/highlight.pipe';
// Message Validator
export { MessageValidationModule } from './components/messagevalidation/index';
export { TlMessageValidationComponent } from './components/messagevalidation/messagevalidation.component';
export { TlMessageValidationDirective } from './components/messagevalidation/directives/message-validation.directive';
// Modal
export { ModalModule } from './components/modal/index';
export { TlModal } from './components/modal/modal';
export { ModalResultDirective } from './components/modal/directives/modal-result.directive';
export { ModalToolbarModule } from './components/modal/addons/modal-toolbar/index';
export { TlModalToolbar } from './components/modal/addons/modal-toolbar/modal-toolbar';
export { ModalOptions, Modal } from './components/modal/interfaces/modal-options';
export { ModalFormConfig } from './components/modal/interfaces/modal-smart-form-config';
export { ModalService } from './components/modal/services/modal.service';
// MultiSelect
export { MultiSelectModule } from './components/multiselect/index';
export { TlMultiSelect } from './components/multiselect/multiselect';
// Multiview
export { MultiViewModule } from './components/multiview/index';
export { TlMultiView } from './components/multiview/multiview';
export { TlView } from './components/multiview/view/view';
// Navigator
export { NavigatorModule } from './components/navigator/index';
export { TlNavigator } from './components/navigator/navigator';
export { NavigatorService } from './components/navigator/services/navigator.service';
// OverlayPanel
export { OverlayPanelModule } from './components/overlaypanel/index';
export { TlOverlayPanel } from './components/overlaypanel/overlay-panel';
// PanelGroup
export { PanelGroupModule } from './components/panelgroup/index';
export { TlPanelGroup } from './components/panelgroup/panelgroup';
// PopupMenu
export { PopupMenuModule } from './components/popupmenu/index';
export { TlPopupMenu } from './components/popupmenu/popupmenu';
export { TlPopupMenuItem } from './components/popupmenu/parts/popupmenu-item';
// Permissions
export { PermissionsModule } from './components/permissions/index';
export { TlPermissions } from './components/permissions/permissions';
export { PermissionGroupDirective } from './components/permissions/parts/directives/permission-group.directive';
export { PermissionDataConfig } from './components/permissions/parts/interfaces/permission-dataconfig.interface';
export { Permission } from './components/permissions/parts/models/permission.model';
// Progressbar
export { ProgressBarModule } from './components/progressbar/index';
export { TlProgressBar } from './components/progressbar/progressbar';
// Radio Button
export { RadioButtonModule } from './components/radiobutton/index';
export { TlRadioButton } from './components/radiobutton/radiobutton';
export { TlRadioGroup } from './components/radiobutton/radiogroup';
// Sidebar
export { SidebarModule } from './components/sidebar/index';
export { TlSidebarContainer } from './components/sidebar/sidebar-container';
export { TlSidebar } from './components/sidebar/parts/sidebar/sidebar';
export { TlSidebarContent } from './components/sidebar/parts/sidebar-content/sidebar-content';
// Loader
export { SkeletonModule } from './components/skeleton/index';
export { TlSkeleton } from './components/skeleton/skeleton';
// Schedule
export { ScheduleModule } from './components/schedule/index';
export { TlSchedule } from './components/schedule/schedule';
export { ScheduleDataSource } from './components/schedule/types/datasource.type';
import { SlotSettingsType } from './components/schedule/types/slot-settings.type';
export { HolidaysType } from './components/schedule/types/holidays.type';
export { SlotSettingsType } from './components/schedule/types/slot-settings.type';
export { StatusType } from './components/schedule/types/status.type';
export { ViewType } from './components/schedule/types/view.type';
export { WorkScaleType } from './components/schedule/types/work-scale.type';
// StopWatch
export { StopwatchModule } from './components/stopwatch/index';
export { StopwatchService } from './components/stopwatch/services/stopwatch-service';
export { TlStopwatch } from './components/stopwatch/stopwatch';
// Shortcut
export { ShortcutModule } from './components/shortcut/index';
export { ShortcutDirective } from './components/shortcut/shortcut.directive';
export { ShortcutConfig } from './components/shortcut/shortcut.config';
// Splitbutton
export { SplitButtonModule } from './components/splitbutton/index';
export { TlSplitButton } from './components/splitbutton/splitbutton';
export { TlSplitButtonAction } from './components/splitbutton/parts/splitbutton-action';
// Switch
export { SwitchModule } from './components/switch/index';
export { TlSwitch } from './components/switch/switch';
// Step
export { StepModule } from './components/step/index';
export { TlStep } from './components/step/step';
export { TlStepForm } from './components/step/parts/step-form/step-form';
export { StepNextDirective } from './components/step/directives/step-next.directive';
export { StepFinishDirective } from './components/step/directives/step-finish.directive';
export { StepPreviousDirective } from './components/step/directives/step-previous.directive';
// Tag
export { TagModule } from './components/tag/index';
export { TlTag } from './components/tag/tag';
// TabControl
export { TabControlModule } from './components/tabcontrol/index';
export { TlTabControl } from './components/tabcontrol/tabcontrol';
export { TlTab } from './components/tabcontrol/tab/tab';
// TextArea
export { TextareaModule } from './components/textarea/index';
export { TlTextarea } from './components/textarea/textarea';
// Timeline
export { TimelineModule } from './components/timeline/index';
export { TlTimeline } from './components/timeline/timeline';
export { TlTimelineItem } from './components/timeline/parts/timeline-item/timeline-item';
// Time Picker
export { TimePickerModule } from './components/timepicker/index';
export { TlTimepicker } from './components/timepicker/timepicker';
export { IncrementalSteps } from './components/timepicker/timepicker';
// Time Available Picker
export { TimeAvailablePickerModule } from './components/time-available-picker/index';
export { TlTimeAvailablePicker } from './components/time-available-picker/time-available-picker';
// Toaster
export { ToasterModule } from './components/toaster/index';
export { TlToaster } from './components/toaster/parts/toaster';
export { TlToasterContainer } from './components/toaster/toaster-container';
export { ToasterConfig } from './components/toaster/toaster-config';
export { ToasterService } from './components/toaster/services/toaster.service';
// Toolbar
export { ToolbarModule } from './components/toolbar/index';
export { TlToolbar } from './components/toolbar/toolbar';
// Tooltip
export { TooltipModule } from './components/tooltip/index';
export { TlToolTip } from './components/tooltip/tooltip';
export { TlToolTipContainer } from './components/tooltip/parts/tooltip-container';
export { TooltipDirective } from './components/tooltip/directives/tooltip.directive';
export { TooltipService } from './components/tooltip/tooltip.service';
// Thumbnail
export { ThumbnailModule } from './components/thumbnail/index';
export { TlThumbnail } from './components/thumbnail/thumbnail';
// Upload
export { UploadModule } from './components/upload/index';
export { TlUpload } from './components/upload/upload';
export { ImageUploadInterface } from './components/upload/interfaces/image-upload.interface';
// Validators
export { ValidatorsModule } from './components/validators/index';
export { CreditCardDirective } from './components/validators/creditcard/creditcard.directive';
export { CPFDirective } from './components/validators/cpf/cpf.directive';
export { CNPJDirective } from './components/validators/cnpj/cnpj.directive';
export { EmailDirective } from './components/validators/email/email.directive';
export { NumberDirective } from './components/validators/number/number.directive';
export { PasswordDirective } from './components/validators/password/password.directive';
export { CNPJValidator } from './components/validators/cnpj/cnpj.validator';
export { CPFValidator } from './components/validators/cpf/cpf.validator';
export { CreditCardValidator } from './components/validators/creditcard/creditcard.validator';
export { DateValidator } from './components/date/validators/date.validator';
export { EmailValidator } from './components/validators/email/email.validator';
export { NumberValidator } from './components/validators/number/number.validator';
export { PasswordValidator } from './components/validators/password/password.validator';
// Languages (i18n)
export { I18nService } from './components/i18n/i18n.service';
export { I18nInterface } from './components/i18n/i18n.interface';
export { en_US } from './components/i18n/languages/en_US';
export { pt_BR } from './components/i18n/languages/pt_BR'; | the_stack |
declare type PluralForm = (n: number) => number;
/**
* Metadata for a language pack.
*/
interface IJsonDataHeader {
/**
* Language locale. Example: es_CO, es-CO.
*/
language: string;
/**
* The domain of the translation, usually the normalized package name.
* Example: "jupyterlab", "jupyterlab_git"
*
* #### Note
* Normalization replaces `-` by `_` in package name.
*/
domain: string;
/**
* String describing the plural of the given language.
* See: https://www.gnu.org/software/gettext/manual/html_node/Translating-plural-forms.html
*/
pluralForms: string;
}
/**
* Translatable string messages.
*/
interface IJsonDataMessages {
/**
* Translation strings for a given msg_id.
*/
[key: string]: string[] | IJsonDataHeader;
}
/**
* Translatable string messages incluing metadata.
*/
interface IJsonData extends IJsonDataMessages {
/**
* Metadata of the language bundle.
*/
'': IJsonDataHeader;
}
/**
* Configurable options for the Gettext constructor.
*/
interface IOptions {
/**
* Language locale. Example: es_CO, es-CO.
*/
locale?: string;
/**
* The domain of the translation, usually the normalized package name.
* Example: "jupyterlab", "jupyterlab_git"
*
* #### Note
* Normalization replaces `-` by `_` in package name.
*/
domain?: string;
/**
* The delimiter to use when adding contextualized strings.
*/
contextDelimiter?: string;
/**
* Translation message strings.
*/
messages?: Array<string>;
/**
* String describing the plural of the given language.
* See: https://www.gnu.org/software/gettext/manual/html_node/Translating-plural-forms.html
*/
pluralForms?: string;
/**
* The string prefix to add to localized strings.
*/
stringsPrefix?: string;
/**
* Plural form function.
*/
pluralFunc?: PluralForm;
}
/**
* Gettext class providing localization methods.
*/
declare class Gettext {
constructor(options?: IOptions);
/**
* Set current context delimiter.
*
* @param delimiter - The delimiter to set.
*/
setContextDelimiter(delimiter: string): void;
/**
* Get current context delimiter.
*
* @return The current delimiter.
*/
getContextDelimiter(): string;
/**
* Set current locale.
*
* @param locale - The locale to set.
*/
setLocale(locale: string): void;
/**
* Get current locale.
*
* @return The current locale.
*/
getLocale(): string;
/**
* Set current domain.
*
* @param domain - The domain to set.
*/
setDomain(domain: string): void;
/**
* Get current domain.
*
* @return The current domain string.
*/
getDomain(): string;
/**
* Set current strings prefix.
*
* @param prefix - The string prefix to set.
*/
setStringsPrefix(prefix: string): void;
/**
* Get current strings prefix.
*
* @return The strings prefix.
*/
getStringsPrefix(): string;
/**
* `sprintf` equivalent, takes a string and some arguments to make a
* computed string.
*
* @param fmt - The string to interpolate.
* @param args - The variables to use in interpolation.
*
* ### Examples
* strfmt("%1 dogs are in %2", 7, "the kitchen"); => "7 dogs are in the kitchen"
* strfmt("I like %1, bananas and %1", "apples"); => "I like apples, bananas and apples"
*/
static strfmt(fmt: string, ...args: any[]): string;
/**
* Load json translations strings (In Jed 2.x format).
*
* @param jsonData - The translation strings plus metadata.
* @param domain - The translation domain, e.g. "jupyterlab".
*/
loadJSON(jsonData: IJsonData, domain: string): void;
/**
* Shorthand for gettext.
*
* @param msgid - The singular string to translate.
* @param args - Any additional values to use with interpolation.
*
* @return A translated string if found, or the original string.
*
* ### Notes
* This is not a private method (starts with an underscore) it is just
* a shorter and standard way to call these methods.
*/
__(msgid: string, ...args: any[]): string;
/**
* Shorthand for ngettext.
*
* @param msgid - The singular string to translate.
* @param msgid_plural - The plural string to translate.
* @param n - The number for pluralization.
* @param args - Any additional values to use with interpolation.
*
* @return A translated string if found, or the original string.
*
* ### Notes
* This is not a private method (starts with an underscore) it is just
* a shorter and standard way to call these methods.
*/
_n(msgid: string, msgid_plural: string, n: number, ...args: any[]): string;
/**
* Shorthand for pgettext.
*
* @param msgctxt - The message context.
* @param msgid - The singular string to translate.
* @param args - Any additional values to use with interpolation.
*
* @return A translated string if found, or the original string.
*
* ### Notes
* This is not a private method (starts with an underscore) it is just
* a shorter and standard way to call these methods.
*/
_p(msgctxt: string, msgid: string, ...args: any[]): string;
/**
* Shorthand for npgettext.
*
* @param msgctxt - The message context.
* @param msgid - The singular string to translate.
* @param msgid_plural - The plural string to translate.
* @param n - The number for pluralization.
* @param args - Any additional values to use with interpolation.
*
* @return A translated string if found, or the original string.
*
* ### Notes
* This is not a private method (starts with an underscore) it is just
* a shorter and standard way to call these methods.
*/
_np(msgctxt: string, msgid: string, msgid_plural: string, n: number, ...args: any[]): string;
/**
* Translate a singular string with extra interpolation values.
*
* @param msgid - The singular string to translate.
* @param args - Any additional values to use with interpolation.
*
* @return A translated string if found, or the original string.
*/
gettext(msgid: string, ...args: any[]): string;
/**
* Translate a plural string with extra interpolation values.
*
* @param msgid - The singular string to translate.
* @param args - Any additional values to use with interpolation.
*
* @return A translated string if found, or the original string.
*/
ngettext(msgid: string, msgid_plural: string, n: number, ...args: any[]): string;
/**
* Translate a contextualized singular string with extra interpolation values.
*
* @param msgctxt - The message context.
* @param msgid - The singular string to translate.
* @param args - Any additional values to use with interpolation.
*
* @return A translated string if found, or the original string.
*
* ### Notes
* This is not a private method (starts with an underscore) it is just
* a shorter and standard way to call these methods.
*/
pgettext(msgctxt: string, msgid: string, ...args: any[]): string;
/**
* Translate a contextualized plural string with extra interpolation values.
*
* @param msgctxt - The message context.
* @param msgid - The singular string to translate.
* @param msgid_plural - The plural string to translate.
* @param n - The number for pluralization.
* @param args - Any additional values to use with interpolation
*
* @return A translated string if found, or the original string.
*/
npgettext(msgctxt: string, msgid: string, msgid_plural: string, n: number, ...args: any[]): string;
/**
* Translate a singular string with extra interpolation values.
*
* @param domain - The translations domain.
* @param msgctxt - The message context.
* @param msgid - The singular string to translate.
* @param msgid_plural - The plural string to translate.
* @param n - The number for pluralization.
* @param args - Any additional values to use with interpolation
*
* @return A translated string if found, or the original string.
*/
dcnpgettext(domain: string, msgctxt: string, msgid: string, msgid_plural: string, n: number, ...args: any[]): string;
/**
* Split a locale into parent locales. "es-CO" -> ["es-CO", "es"]
*
* @param locale - The locale string.
*
* @return An array of locales.
*/
private expandLocale;
/**
* Split a locale into parent locales. "es-CO" -> ["es-CO", "es"]
*
* @param pluralForm - Plural form string..
* @return An function to compute plural forms.
*/
private getPluralFunc;
/**
* Remove the context delimiter from string.
*
* @param str - Translation string.
* @return A translation string without context.
*/
private removeContext;
/**
* Proper translation function that handle plurals and directives.
*
* @param messages - List of translation strings.
* @param n - The number for pluralization.
* @param options - Translation options.
* @param args - Any variables to interpolate.
*
* @return A translation string without context.
*
* ### Notes
* Contains juicy parts of https://github.com/Orange-OpenSource/gettext.js/blob/master/lib.gettext.js
*/
private t;
/**
* Set messages after loading them.
*
* @param domain - The translation domain.
* @param locale - The translation locale.
* @param messages - List of translation strings.
* @param pluralForms - Plural form string.
*
* ### Notes
* Contains juicy parts of https://github.com/Orange-OpenSource/gettext.js/blob/master/lib.gettext.js
*/
private setMessages;
private _stringsPrefix;
private _pluralForms;
private _dictionary;
private _locale;
private _domain;
private _contextDelimiter;
private _pluralFuncs;
private _defaults;
}
export { Gettext }; | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { Cache } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { ApiManagementClient } from "../apiManagementClient";
import {
CacheContract,
CacheListByServiceNextOptionalParams,
CacheListByServiceOptionalParams,
CacheListByServiceResponse,
CacheGetEntityTagOptionalParams,
CacheGetEntityTagResponse,
CacheGetOptionalParams,
CacheGetResponse,
CacheCreateOrUpdateOptionalParams,
CacheCreateOrUpdateResponse,
CacheUpdateParameters,
CacheUpdateOptionalParams,
CacheUpdateResponse,
CacheDeleteOptionalParams,
CacheListByServiceNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing Cache operations. */
export class CacheImpl implements Cache {
private readonly client: ApiManagementClient;
/**
* Initialize a new instance of the class Cache class.
* @param client Reference to the service client
*/
constructor(client: ApiManagementClient) {
this.client = client;
}
/**
* Lists a collection of all external Caches in the specified service instance.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param options The options parameters.
*/
public listByService(
resourceGroupName: string,
serviceName: string,
options?: CacheListByServiceOptionalParams
): PagedAsyncIterableIterator<CacheContract> {
const iter = this.listByServicePagingAll(
resourceGroupName,
serviceName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByServicePagingPage(
resourceGroupName,
serviceName,
options
);
}
};
}
private async *listByServicePagingPage(
resourceGroupName: string,
serviceName: string,
options?: CacheListByServiceOptionalParams
): AsyncIterableIterator<CacheContract[]> {
let result = await this._listByService(
resourceGroupName,
serviceName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByServiceNext(
resourceGroupName,
serviceName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByServicePagingAll(
resourceGroupName: string,
serviceName: string,
options?: CacheListByServiceOptionalParams
): AsyncIterableIterator<CacheContract> {
for await (const page of this.listByServicePagingPage(
resourceGroupName,
serviceName,
options
)) {
yield* page;
}
}
/**
* Lists a collection of all external Caches in the specified service instance.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param options The options parameters.
*/
private _listByService(
resourceGroupName: string,
serviceName: string,
options?: CacheListByServiceOptionalParams
): Promise<CacheListByServiceResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, options },
listByServiceOperationSpec
);
}
/**
* Gets the entity state (Etag) version of the Cache specified by its identifier.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param cacheId Identifier of the Cache entity. Cache identifier (should be either 'default' or valid
* Azure region identifier).
* @param options The options parameters.
*/
getEntityTag(
resourceGroupName: string,
serviceName: string,
cacheId: string,
options?: CacheGetEntityTagOptionalParams
): Promise<CacheGetEntityTagResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, cacheId, options },
getEntityTagOperationSpec
);
}
/**
* Gets the details of the Cache specified by its identifier.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param cacheId Identifier of the Cache entity. Cache identifier (should be either 'default' or valid
* Azure region identifier).
* @param options The options parameters.
*/
get(
resourceGroupName: string,
serviceName: string,
cacheId: string,
options?: CacheGetOptionalParams
): Promise<CacheGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, cacheId, options },
getOperationSpec
);
}
/**
* Creates or updates an External Cache to be used in Api Management instance.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param cacheId Identifier of the Cache entity. Cache identifier (should be either 'default' or valid
* Azure region identifier).
* @param parameters Create or Update parameters.
* @param options The options parameters.
*/
createOrUpdate(
resourceGroupName: string,
serviceName: string,
cacheId: string,
parameters: CacheContract,
options?: CacheCreateOrUpdateOptionalParams
): Promise<CacheCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, cacheId, parameters, options },
createOrUpdateOperationSpec
);
}
/**
* Updates the details of the cache specified by its identifier.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param cacheId Identifier of the Cache entity. Cache identifier (should be either 'default' or valid
* Azure region identifier).
* @param ifMatch ETag of the Entity. ETag should match the current entity state from the header
* response of the GET request or it should be * for unconditional update.
* @param parameters Update parameters.
* @param options The options parameters.
*/
update(
resourceGroupName: string,
serviceName: string,
cacheId: string,
ifMatch: string,
parameters: CacheUpdateParameters,
options?: CacheUpdateOptionalParams
): Promise<CacheUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, cacheId, ifMatch, parameters, options },
updateOperationSpec
);
}
/**
* Deletes specific Cache.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param cacheId Identifier of the Cache entity. Cache identifier (should be either 'default' or valid
* Azure region identifier).
* @param ifMatch ETag of the Entity. ETag should match the current entity state from the header
* response of the GET request or it should be * for unconditional update.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
serviceName: string,
cacheId: string,
ifMatch: string,
options?: CacheDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, cacheId, ifMatch, options },
deleteOperationSpec
);
}
/**
* ListByServiceNext
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param nextLink The nextLink from the previous successful call to the ListByService method.
* @param options The options parameters.
*/
private _listByServiceNext(
resourceGroupName: string,
serviceName: string,
nextLink: string,
options?: CacheListByServiceNextOptionalParams
): Promise<CacheListByServiceNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, nextLink, options },
listByServiceNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listByServiceOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/caches",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.CacheCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.top, Parameters.skip, Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const getEntityTagOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/caches/{cacheId}",
httpMethod: "HEAD",
responses: {
200: {
headersMapper: Mappers.CacheGetEntityTagHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.cacheId
],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/caches/{cacheId}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.CacheContract,
headersMapper: Mappers.CacheGetHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.cacheId
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/caches/{cacheId}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.CacheContract,
headersMapper: Mappers.CacheCreateOrUpdateHeaders
},
201: {
bodyMapper: Mappers.CacheContract,
headersMapper: Mappers.CacheCreateOrUpdateHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters21,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.cacheId
],
headerParameters: [
Parameters.accept,
Parameters.contentType,
Parameters.ifMatch
],
mediaType: "json",
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/caches/{cacheId}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.CacheContract,
headersMapper: Mappers.CacheUpdateHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters22,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.cacheId
],
headerParameters: [
Parameters.accept,
Parameters.contentType,
Parameters.ifMatch1
],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/caches/{cacheId}",
httpMethod: "DELETE",
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.cacheId
],
headerParameters: [Parameters.accept, Parameters.ifMatch1],
serializer
};
const listByServiceNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.CacheCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.top, Parameters.skip, Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import Box from "../Box";
import Flex from "../Flex";
import { useMemo } from "react";
import { useTable, useFilters, useSortBy, usePagination } from "react-table";
import matchSorter from "match-sorter";
import AccountCell from "../AccountCell";
import moment from "moment";
import Link from "next/link";
import { forwardRef } from "react";
import { TableCellProps } from "../../@types";
import {
ChevronDownIcon,
ChevronUpIcon,
ArrowLeftIcon,
ArrowRightIcon,
MagnifyingGlassIcon,
} from "@modulz/radix-icons";
const Table = ({ pageSize = 10, data: { currentRound, tickets } }) => {
function fuzzyTextFilterFn(rows, id, filterValue) {
return matchSorter(rows, filterValue, {
keys: [
(row) => {
return row.values[id];
},
],
});
}
// Let the table remove the filter if the string is empty
fuzzyTextFilterFn.autoRemove = (val) => !val;
function DefaultColumnFilter({ column: { filterValue, setFilter } }) {
return (
<Flex
css={{
alignItems: "center",
pl: "$4",
}}>
<Box
as={MagnifyingGlassIcon}
css={{ width: 16, height: 16, mr: "$2", color: "$muted" }}
/>
<Box
as="input"
value={filterValue || ""}
onChange={(e) => {
setFilter(e.target.value || undefined);
}}
placeholder={`Filter`}
type="text"
css={{
display: "block",
outline: "none",
width: "100%",
appearance: "none",
fontSize: "$3",
lineHeight: "inherit",
border: 0,
color: "inherit",
bg: "transparent",
}}
/>
</Flex>
);
}
const columns: any = useMemo(
() => [
{
Header: "Orchestrator",
accessor: "recipient",
filter: "fuzzyText",
Filter: DefaultColumnFilter,
sortType: (rowA, rowB, columnID) => {
const a = getRowValueByColumnID(rowA, columnID);
const b = getRowValueByColumnID(rowB, columnID);
const aThreeBoxSpace = getRowValueByColumnID(rowA, "threeBoxSpace");
const bThreeBoxSpace = getRowValueByColumnID(rowB, "threeBoxSpace");
const rowAIdentity = aThreeBoxSpace?.name ? aThreeBoxSpace?.name : a;
const rowBIdentity = bThreeBoxSpace?.name ? bThreeBoxSpace?.name : b;
return compareBasic(rowAIdentity, rowBIdentity);
},
},
{
Header: "Activation Round",
accessor: "activationRound",
},
{
Header: "Deactivation Round",
accessor: "deactivationRound",
},
{
Header: "Amount",
accessor: "faceValue",
},
{
Header: "Value (USD)",
accessor: "faceValueUSD",
},
{
Header: "Transaction",
accessor: "transaction",
},
{
Header: "Broadcaster",
accessor: "sender",
},
{
Header: "Time",
accessor: "timestamp",
},
],
[]
);
function getRowValueByColumnID(row, columnID) {
return row.values[columnID];
}
function compareBasic(a, b) {
return a === b ? 0 : a > b ? 1 : -1;
}
const defaultColumn = useMemo(
() => ({
// Let's set up our default Filter UI
Filter: DefaultColumnFilter,
}),
[]
);
const filterTypes = useMemo(
() => ({
// Add a new fuzzyTextFilterFn filter type.
fuzzyText: fuzzyTextFilterFn,
// Or, override the default text filter to use
// "startWith"
text: (rows, id, filterValue) => {
return rows.filter((row) => {
const rowValue = row.values[id];
return rowValue !== undefined
? String(rowValue)
.toLowerCase()
.startsWith(String(filterValue).toLowerCase())
: true;
});
},
}),
[]
);
const tableOptions: any = {
columns,
data: tickets,
disableSortRemove: true,
autoResetPage: false,
initialState: {
pageSize,
sortBy: [{ id: "timestamp", desc: true }],
hiddenColumns: [
"transaction",
"activationRound",
"deactivationRound",
"faceValueUSD",
],
},
defaultColumn,
filterTypes,
};
const {
getTableProps,
getTableBodyProps,
headerGroups,
prepareRow,
page,
canPreviousPage,
canNextPage,
pageCount,
nextPage,
previousPage,
state: { pageIndex },
}: any = useTable(tableOptions, useFilters, useSortBy, usePagination);
const accountColumn: any = headerGroups[0].headers[1];
return (
<>
<Flex
css={{
position: "relative",
width: "100%",
top: 0,
zIndex: 10,
flexDirection: "column",
alignItems: "flex-start",
pt: 0,
pb: "$3",
ml: 0,
mr: 0,
justifyContent: "space-between",
}}>
<Box>{accountColumn.render("Filter")}</Box>
</Flex>
<Box css={{ overflow: "scroll", WebkitOverflowScrolling: "touch" }}>
<Box
css={{
display: "table",
tableLayout: "fixed",
width: "100%",
borderSpacing: "0",
borderCollapse: "collapse",
position: "relative",
minWidth: 800,
}}
{...getTableProps()}>
<Box css={{ display: "table-header-group" }}>
{headerGroups.map((headerGroup, index1) => (
<Box
css={{ display: "table-row" }}
key={index1}
{...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map((column, index2) => (
<Box
css={{
display: "table-cell",
borderBottom: "1px solid",
fontWeight: 700,
borderColor: "rgba(255,255,255,.05)",
pb: "$2",
px: "$4",
textTransform: "uppercase",
}}
key={index2}>
<Box
css={{
display: "grid",
justifyContent:
index2 === 0 || index2 === 1
? "flex-start"
: "flex-end",
}}>
<Flex
css={{
alignItems: "center",
fontSize: 10,
position: "relative",
}}
{...column.getHeaderProps(
column.getSortByToggleProps({ title: "" })
)}>
{column.isSorted ? (
column.isSortedDesc ? (
<Box
as={ChevronDownIcon}
css={{ height: 15, mr: "$2" }}
/>
) : (
<Box
as={ChevronUpIcon}
css={{ height: 15, mr: "$2" }}
/>
)
) : (
""
)}
{column.render("Header")}
</Flex>
</Box>
</Box>
))}
</Box>
))}
</Box>
<Box css={{ display: "table-row-group" }} {...getTableBodyProps()}>
{page.map((row, rowIndex) => {
const orchestratorIndex = rowIndex + pageIndex * pageSize;
prepareRow(row);
return (
<Box
{...row.getRowProps()}
key={orchestratorIndex}
css={{
display: "table-row",
height: 64,
}}>
{row.cells.map((cell, i) => {
switch (cell.column.Header) {
case "Orchestrator":
const active =
cell.row.values.recipient.activationRound <=
currentRound.id &&
cell.row.values.recipient.deactivationRound >
currentRound.id;
return (
<TableCell cell={cell} key={i}>
<Link
href={`/accounts/${cell.value.id}/campaign`}
passHref>
<Box
as="a"
css={{
display: "inherit",
color: "inherit",
":hover": {
textDecoration: "underline",
},
}}>
<AccountCell
active={active}
threeBoxSpace={
cell.row.values.recipient.threeBoxSpace
}
address={cell.value.id}
/>
</Box>
</Link>
</TableCell>
);
case "Amount":
return (
<TableCell
cell={cell}
key={i}
css={{ fontSize: "12px" }}>
<Flex css={{ alignItems: "center" }}>
<Box
css={{
display: "inline-block",
background: "rgba(255,255,255,.06)",
padding: "2px 8px",
borderRadius: "6px",
mr: "$2",
}}>
<Box
as="span"
css={{ fontFamily: "$monospace" }}>
{parseFloat((+cell.value).toFixed(3))}
</Box>{" "}
<Box as="span">ETH</Box>
</Box>
(
<Box css={{ fontFamily: "$monospace" }}>
$
{parseFloat(
(+cell.row.values.faceValueUSD).toFixed(2)
)}
</Box>
)
</Flex>
</TableCell>
);
case "Broadcaster":
return (
<TableCell
cell={cell}
key={i}
css={{ textAlign: "right" }}>
<Link
href={`/accounts/${cell.value.id}/history`}
passHref>
<Box
as="a"
css={{
color: "inherit",
":hover": {
textDecoration: "underline",
},
}}>
{cell.value.id.replace(
cell.value.id.slice(5, 39),
"…"
)}
</Box>
</Link>
</TableCell>
);
case "Time":
return (
<TableCell
cell={cell}
key={i}
css={{ textAlign: "right" }}>
<Box
as="a"
css={{
color: "inherit",
":hover": {
textDecoration: "underline",
},
}}
rel="noopener noreferrer"
target="_blank"
href={`https://etherscan.io/tx/${cell.row.values.transaction.id}`}>
{moment(cell.value * 1000).fromNow()}
</Box>
</TableCell>
);
default:
return null;
}
})}
</Box>
);
})}
</Box>
</Box>
</Box>
<Flex
css={{
py: "$4",
alignItems: "center",
justifyContent: "center",
}}>
<Box
as={ArrowLeftIcon}
css={{
cursor: "pointer",
color: canPreviousPage ? "$primary" : "text",
opacity: canPreviousPage ? 1 : 0.5,
}}
onClick={() => {
if (canPreviousPage) {
previousPage();
}
}}
/>
<Box css={{ fontSize: "$2", mx: "$3" }}>
Page{" "}
<Box as="span" css={{ fontFamily: "$monospace" }}>
{pageIndex + 1}
</Box>{" "}
of{" "}
<Box as="span" css={{ fontFamily: "$monospace" }}>
{pageCount}
</Box>
</Box>
<Box
as={ArrowRightIcon}
css={{
cursor: "pointer",
color: canNextPage ? "$primary" : "$text",
opacity: canNextPage ? 1 : 0.5,
}}
onClick={() => {
if (canNextPage) {
nextPage();
}
}}
/>
</Flex>
</>
);
};
const TableCell = forwardRef(
({ children, href, target, cell, as, onClick, css }: TableCellProps, ref) => {
return (
<Box
as={as}
target={target}
href={href}
ref={ref}
onClick={onClick}
css={{
color: "inherit",
display: "table-cell",
width: "auto",
fontSize: "$2",
px: "$4",
verticalAlign: "middle",
borderBottom: "1px solid",
borderColor: "rgba(255,255,255,.05)",
...css,
}}
{...cell.getCellProps()}>
{children}
</Box>
);
}
);
export default Table; | the_stack |
import { withBrowser } from 'pleasantest';
import type { PleasantestContext, PleasantestUtils } from 'pleasantest';
import { formatErrorWithCodeFrame, printErrorFrames } from '../test-utils';
import vuePlugin from 'rollup-plugin-vue';
import sveltePlugin from 'rollup-plugin-svelte';
import sveltePreprocess from 'svelte-preprocess';
import aliasPlugin from '@rollup/plugin-alias';
import babel from '@rollup/plugin-babel';
const createHeading = async ({
utils,
screen,
}: {
utils: PleasantestUtils;
screen: PleasantestContext['screen'];
}) => {
await utils.injectHTML(`
<h1>I'm a heading</h1>
`);
return screen.getByRole('heading', { name: /i'm a heading/i });
};
test(
'basic inline code',
withBrowser(async ({ utils, screen }) => {
const heading = await createHeading({ utils, screen });
await expect(heading).toBeInTheDocument();
await utils.runJS(`
const heading = document.querySelector('h1')
heading.remove()
`);
await expect(heading).not.toBeInTheDocument();
}),
);
test(
'allows passing functions to runJS',
withBrowser(async ({ utils }) => {
const mockFuncA = jest.fn(() => 5);
const mockFuncB = jest.fn();
await utils.runJS(
`
export default async (mockFuncA, mockFuncB) => {
const val = await mockFuncA('hello world')
if (val !== 5) throw new Error('Did not get return value');
await mockFuncB()
}
`,
[mockFuncA, mockFuncB],
);
expect(mockFuncA).toHaveBeenCalledTimes(1);
expect(mockFuncA).toHaveBeenCalledWith('hello world');
expect(mockFuncB).toHaveBeenCalledTimes(1);
}),
);
test(
'allows passing ElementHandles and serializable values into browser',
withBrowser(async ({ utils, screen }) => {
const heading = await createHeading({ utils, screen });
await utils.runJS(
`
export default (heading, object) => {
if (heading.outerHTML !== "<h1>I'm a heading</h1>") {
throw new Error('element was not passed correctly')
}
if (object.some.serializable.value !== false) {
throw new Error('object was not passed correctly')
}
}
`,
[heading, { some: { serializable: { value: false } } }],
);
}),
);
describe('Waiting for Promises in executed code', () => {
it(
'should not wait for non-exported promises',
withBrowser(async ({ utils, screen }) => {
const heading = await createHeading({ utils, screen });
await expect(heading).toBeInTheDocument();
await utils.runJS(`
const heading = document.querySelector('h1')
new Promise(r => setTimeout(r, 50))
.then(() => heading.remove())
`);
// Since it didn't wait for the promise
await expect(heading).toBeInTheDocument();
}),
);
it(
'should wait for top-level-await',
withBrowser(async ({ utils, screen }) => {
const heading = await createHeading({ utils, screen });
await expect(heading).toBeInTheDocument();
await utils.runJS(`
const heading = document.querySelector('h1')
await new Promise(r => setTimeout(r, 50))
.then(() => heading.remove())
`);
await expect(heading).not.toBeInTheDocument();
}),
);
});
test(
'supports TS in snippet',
withBrowser(async ({ utils, screen }) => {
const heading = await createHeading({ utils, screen });
await expect(heading).toBeInTheDocument();
// Note: the snippet inherits the language support from the test file that includes it
// So since this file is a .ts file, the snippet supports TS syntax
await utils.runJS(`
type foo = 'stringliteraltype'
document.querySelector('h1').remove()
`);
await expect(heading).not.toBeInTheDocument();
}),
);
test(
'throws error with real source-mapped location',
withBrowser(async ({ utils }) => {
// Manually-thrown error
const error = await utils
.runJS(
`type foo = 'stringliteraltype'
throw new Error('errorFromTs')`,
)
.catch((error) => error);
expect(await printErrorFrames(error)).toMatchInlineSnapshot(`
"Error: errorFromTs
-------------------------------------------------------
tests/utils/runJS.test.tsx
throw new Error('errorFromTs')\`,
^"
`);
// Implicitly created error
const error2 = await utils
.runJS(
`type foo = 'stringliteraltype'
thisVariableDoesntExist`,
)
.catch((error) => error);
expect(await printErrorFrames(error2)).toMatchInlineSnapshot(`
"ReferenceError: thisVariableDoesntExist is not defined
-------------------------------------------------------
tests/utils/runJS.test.tsx
thisVariableDoesntExist\`,
^"
`);
}),
);
test(
'Imports by different runJS calls point to the same values',
withBrowser(async ({ utils }) => {
await utils.runJS(`
import { render } from 'preact'
window.__preact_render = render
`);
await utils.runJS(`
import { render } from 'preact'
if (window.__preact_render !== render)
throw new Error('Importing the same thing multiple times resulted in different modules')
`);
}),
);
test(
"TransformImports throws stack frame if it can't parse the input",
withBrowser(
// Disable esbuild so that the invalid code will get through to the import transformer
{ moduleServer: { esbuild: false } },
async ({ utils }) => {
const runPromise = utils.runJS(`
asdf())
`);
await expect(formatErrorWithCodeFrame(runPromise)).rejects
.toThrowErrorMatchingInlineSnapshot(`
"Error parsing module with es-module-lexer.
<root>/tests/utils/runJS.test.tsx:###:###
### | async ({ utils }) => {
### | const runPromise = utils.runJS(\`
> ### | asdf())
| ^
### | \`);
### |
### | await expect(formatErrorWithCodeFrame(runPromise)).rejects
"
`);
},
),
);
test(
'Line/column offsets for source-mapped runtime error is correct even with esbuild disabled',
withBrowser({ moduleServer: { esbuild: false } }, async ({ utils }) => {
const error = await utils
.runJS('console.log(nothing)')
.catch((error) => error);
expect(await printErrorFrames(error)).toMatchInlineSnapshot(`
"ReferenceError: nothing is not defined
-------------------------------------------------------
tests/utils/runJS.test.tsx
.runJS('console.log(nothing)')
^"
`);
}),
);
test(
'allows importing .tsx file, and errors from imported file are source mapped',
withBrowser(async ({ utils, page }) => {
await utils.runJS(`
import { render } from './external'
render()
`);
expect(
await page.evaluate(() => document.body.innerHTML.trim()),
).toMatchInlineSnapshot(`"<h1 style=\\"\\">Hi</h1>"`);
await utils.injectHTML('');
const error = await utils
.runJS(
`import { renderThrow } from './external'
renderThrow()`,
)
.catch((error) => error);
expect(await printErrorFrames(error)).toMatchInlineSnapshot(`
"Error: you have rendered the death component
-------------------------------------------------------
tests/utils/external.tsx
throw new Error('you have rendered the death component');
^
-------------------------------------------------------
tests/utils/external.tsx
preactRender(<ThrowComponent />, document.body);
^
-------------------------------------------------------
tests/utils/runJS.test.tsx
renderThrow()\`,
^"
`);
}),
);
test(
'If the code string has a syntax error the location is source mapped',
withBrowser(async ({ utils }) => {
const runPromise = utils.runJS(`
console.log('hi'))
`);
await expect(formatErrorWithCodeFrame(runPromise)).rejects
.toThrowErrorMatchingInlineSnapshot(`
"[esbuild] Expected \\";\\" but found \\")\\"
<root>/tests/utils/runJS.test.tsx:###:###
### | withBrowser(async ({ utils }) => {
### | const runPromise = utils.runJS(\`
> ### | console.log('hi'))
| ^
### | \`);
### |
### | await expect(formatErrorWithCodeFrame(runPromise)).rejects
"
`);
}),
);
test(
'If an imported file has a syntax error the location is source mapped',
withBrowser(async ({ utils }) => {
const runPromise = utils.runJS(`
import './external-with-syntax-error'
`);
await expect(formatErrorWithCodeFrame(runPromise)).rejects
.toThrowErrorMatchingInlineSnapshot(`
"[esbuild] The constant \\"someVariable\\" must be initialized
<root>/tests/utils/external-with-syntax-error.ts:###:###
# | // @ts-expect-error: this is intentionally invalid
> # | const someVariable: string;
| ^
# |
"
`);
}),
);
test(
'resolution error if a package does not exist in node_modules',
withBrowser(async ({ utils }) => {
const runPromise = formatErrorWithCodeFrame(
utils.runJS(`
import { foo } from 'something-not-existing'
`),
);
await expect(runPromise).rejects.toThrowErrorMatchingInlineSnapshot(
`"Could not find something-not-existing in node_modules (imported by <root>/tests/utils/runJS.test.tsx:###:###)"`,
);
}),
);
test(
'resolution error if a relative path does not exist',
withBrowser(async ({ utils }) => {
const runPromise = utils.runJS(`
import { foo } from './bad-relative-path'
`);
await expect(
formatErrorWithCodeFrame(runPromise),
).rejects.toThrowErrorMatchingInlineSnapshot(
`"Could not resolve ./bad-relative-path (imported by <root>/tests/utils/runJS.test.tsx:###:###)"`,
);
}),
);
test(
'Allows importing CSS into JS file',
withBrowser(async ({ utils, screen }) => {
await utils.injectHTML('<h1>This is a heading</h1>');
const heading = await screen.getByRole('heading');
await expect(heading).toBeVisible();
await utils.runJS(`
import './external.sass'
`);
await expect(heading).not.toBeVisible();
}),
);
describe('Ecosystem interoperability', () => {
test(
'Named exports implicitly created from default-only export in CJS',
withBrowser(async ({ utils }) => {
// Prop-types is CJS and provides non-statically-analyzable named exports
await utils.runJS(`
import { number } from 'prop-types'
import PropTypes from 'prop-types'
if (number !== PropTypes.number) {
throw new Error('Named import did not yield same result as default import')
}
PropTypes.checkPropTypes(
{ name: number },
{ name: 5 },
);
`);
}),
);
test(
'react and react-dom can be imported, and JSX works',
withBrowser(async ({ utils, screen }) => {
await utils.runJS(`
import * as React from 'react'
import React2 from 'react'
if (React.createElement !== React2.createElement) {
throw new Error('Namespace import did not yield same result as direct import')
}
import { render } from 'react-dom'
const root = document.createElement('div')
document.body.innerHTML = ''
document.body.append(root)
render(<h1>Hi</h1>, root)
`);
const heading = await screen.getByRole('heading');
await expect(heading).toHaveTextContent('Hi');
}),
);
test(
'vue component can be imported via rollup-plugin-vue',
withBrowser(
{
moduleServer: {
plugins: [
{
name: 'replace-for-vue',
transform(code) {
return code
.replace(/__VUE_OPTIONS_API__/g, 'true')
.replace(/__VUE_PROD_DEVTOOLS__/g, 'false');
},
},
vuePlugin(),
],
},
},
async ({ utils, screen }) => {
await utils.injectHTML('<div id="app"></div>');
await utils.runJS(`
import { createApp } from 'vue'
import VueComponent from './vue-component.vue'
const app = createApp(VueComponent)
app.mount('#app')
`);
const heading = await screen.getByRole('heading');
await expect(heading).toHaveTextContent('Hiya');
await expect(heading).toHaveStyle({ color: 'green' });
},
),
);
test(
'svelte component can be imported via rollup-plugin-svelte',
withBrowser(
{
moduleServer: {
plugins: [sveltePlugin({ preprocess: sveltePreprocess() })],
},
},
async ({ utils, screen, user }) => {
await utils.injectHTML('<div id="app"></div>');
await utils.runJS(`
import CounterComponent from './svelte-component.svelte'
new CounterComponent({
target: document.getElementById('app')
})
`);
const button = await screen.getByRole('button');
await expect(button).toHaveTextContent(/^clicked 0 times$/i);
await user.click(button);
await expect(button).toHaveTextContent(/^clicked 1 time$/i);
// Check that the scss in the svelte component file got preprocessed and applied correctly
const bgColor = await button.evaluate(
(button) => getComputedStyle(button).backgroundColor,
);
expect(bgColor).toEqual('rgb(255, 0, 0)');
},
),
);
test(
'useful error message is thrown when plugin is missing for imported file with unusual extension',
withBrowser(async ({ utils }) => {
const runPromise = utils.runJS(`
import CounterComponent from './svelte-component.svelte'
`);
await expect(formatErrorWithCodeFrame(runPromise)).rejects
.toThrowErrorMatchingInlineSnapshot(`
"Error parsing module with es-module-lexer. Did you mean to add a transform plugin to support .svelte files?
<root>/tests/utils/svelte-component.svelte:###:###
# | count += 1;
# | }
> # | </script>
| ^
# |
## | <button on:click={handleClick}>
## | Clicked {count} {count === 1 ? 'time' : 'times'}
"
`);
}),
);
});
test(
'can use @rollup/plugin-alias',
withBrowser(
{
moduleServer: {
plugins: [
aliasPlugin({
entries: { asdf: 'preact', foo: './external' },
}),
],
},
},
async ({ utils }) => {
await utils.runJS(`
import * as preact from 'asdf'
if (!preact.h || !preact.Fragment || !preact.Component)
throw new Error('Alias did not load preact correctly')
import * as external from 'foo'
if (!external.render || !external.renderThrow)
throw new Error('Alias did not load ./external.tsx correctly')
`);
},
),
);
test(
'environment variables are injected into browser code',
withBrowser(
{
moduleServer: {
envVars: { asdf: '1234' },
},
},
async ({ utils }) => {
await utils.runJS(`
if (process.env.NODE_ENV !== 'development')
throw new Error('process.env.NODE_ENV not set correctly')
if (import.meta.env.NODE_ENV !== 'development')
throw new Error('import.meta.env.NODE_ENV not set correctly')
if (process.env.asdf !== '1234')
throw new Error('process.env.asdf not set correctly')
if (import.meta.env.asdf !== '1234')
throw new Error('import.meta.env.asdf not set correctly')
`);
},
),
);
test(
'@rollup/plugin-babel works',
withBrowser(
{
moduleServer: {
esbuild: false,
plugins: [
babel({
extensions: ['.js', '.ts', '.tsx', '.mjs'],
babelHelpers: 'bundled',
presets: ['@babel/preset-typescript'],
}),
],
},
},
async ({ utils }) => {
await utils.runJS("const foo: string = 'hello'");
// Check that source map from babel works correctly
const error = await utils
.runJS('console.log(nothing)')
.catch((error) => error);
expect(await printErrorFrames(error)).toMatchInlineSnapshot(`
"ReferenceError: nothing is not defined
-------------------------------------------------------
tests/utils/runJS.test.tsx
.runJS('console.log(nothing)')
^"
`);
},
),
); | the_stack |
import * as d3 from 'd3';
import moment from 'moment-timezone';
import Grid from "../Components/Grid/Grid";
import { ChartOptions } from '../Models/ChartOptions';
import { ChartComponentData } from '../Models/ChartComponentData';
import { CharactersToEscapeForExactSearchInstance, nullTsidDisplayString, GRIDCONTAINERCLASS, NONNUMERICTOPMARGIN } from '../Constants/Constants';
import { YAxisStates, valueTypes } from '../Constants/Enums';
export default class Utils {
static guidForNullTSID = Utils.guid();
static formatYAxisNumber (val: number) {
if (Math.abs(val) < 1000000) {
if (Math.abs(val) < .0000001)
return d3.format('.2n')(val); // scientific for less than 1 billionth
else {
// grouped thousands with 7 significant digits, trim insginificant trailing 0s
var formatted = d3.format(',.7r')(val);
if (formatted.indexOf('.') != -1) {
var lastChar = formatted[formatted.length - 1]
while (lastChar == '0') {
formatted = formatted.slice(0, -1);
lastChar = formatted[formatted.length - 1]
}
if (lastChar == '.')
formatted = formatted.slice(0, -1);
}
return formatted;
}
}
else if (Math.abs(val) >= 1000000 && Math.abs(val) < 1000000000)
return d3.format('.3s')(val); // suffix of M for millions
else if (Math.abs(val) >= 1000000000 && Math.abs(val) < 1000000000000)
return d3.format('.3s')(val).slice(0, -1) + 'B'; // suffix of B for billions
return d3.format('.2n')(val); // scientific for everything else
}
static getStackStates() {
return YAxisStates;
}
// format [0-9]+[ms|s|m|h|d], convert to millis
static parseTimeInput (inputString: string) {
inputString = inputString.toLowerCase();
let getNumber = (inputString, charsFromEnd) => {
let startAt = inputString.indexOf('pt') !== -1 ? 2 : (inputString.indexOf('p') !== -1 ? 1 : 0);
return Number(inputString.slice(startAt, inputString.length - charsFromEnd));
}
if (inputString.indexOf('ms') == inputString.length - 2) {
return getNumber(inputString, 2);
}
if (inputString.indexOf('s') == inputString.length - 1) {
return getNumber(inputString, 1) * 1000;
}
if (inputString.indexOf('m') == inputString.length - 1) {
return getNumber(inputString, 1) * 60 * 1000;
}
if (inputString.indexOf('h') == inputString.length - 1) {
return getNumber(inputString, 1) * 60 * 60 * 1000;
}
if (inputString.indexOf('d') == inputString.length - 1) {
return getNumber(inputString, 1) * 24 * 60 * 60 * 1000;
}
return -1;
}
static findClosestTime (prevMillis: number, timeMap: any): number {
var minDistance = Infinity;
var closestValue = null;
Object.keys(timeMap).forEach((intervalCenterString) => {
var intervalCenter = Number(intervalCenterString);
if (Math.abs(intervalCenter - prevMillis) < minDistance) {
minDistance = Math.abs(intervalCenter - prevMillis);
closestValue = intervalCenter;
}
});
return closestValue;
}
static getValueOfVisible (d: any, visibleMeasure: string) {
if (d.measures) {
if (d.measures[visibleMeasure] != null || d.measures[visibleMeasure] != undefined)
return d.measures[visibleMeasure];
}
return null;
}
static isStartAt (startAtString: string = null, searchSpan: any = null) {
return (startAtString !== null && searchSpan !== null && searchSpan.from !== null);
}
static parseShift (shiftString: string, startAtString: any = null, searchSpan: any = null) {
if (this.isStartAt(startAtString, searchSpan)) {
return (new Date(startAtString)).valueOf() - (new Date(searchSpan.from)).valueOf();
}
if (shiftString === undefined || shiftString === null || shiftString.length === 0) {
return 0;
}
let millis: number;
if (shiftString[0] === '-' || shiftString[0] === '+') {
millis = (shiftString[0] === '-' ? -1 : 1) * this.parseTimeInput(shiftString.slice(1,shiftString.length));
} else {
millis = this.parseTimeInput(shiftString);
}
return -millis;
}
static adjustStartMillisToAbsoluteZero (fromMillis, bucketSize) {
let epochAdjustment = 62135596800000;
return Math.floor((fromMillis + epochAdjustment) / bucketSize) * bucketSize - epochAdjustment;
}
static bucketSizeToTsqInterval (bucketSize: string) {
if (!bucketSize) {return null;}
let bucketSizeInMillis = Utils.parseTimeInput(bucketSize);
let padLeadingZeroes = (number) => {
let numberAsString = String(number);
if(numberAsString.length < 3)
numberAsString = (numberAsString.length === 2 ? '0' : '00') + numberAsString;
return numberAsString
}
if (bucketSizeInMillis < 1000) {
bucketSize = (bucketSize.toLowerCase().indexOf('d') !== -1) ? 'd.' : '.' + padLeadingZeroes(bucketSizeInMillis) + "s";
}
let prefix = bucketSize.toLowerCase().indexOf('d') !== -1 ? 'P' : 'PT';
return (prefix + bucketSize).toUpperCase();
}
static createEntityKey (aggName: string, aggIndex: number) {
return encodeURIComponent(aggName).split(".").join("_") + "_" + aggIndex;
}
static getColorForValue (chartDataOptions, value) {
if (chartDataOptions.valueMapping && (chartDataOptions.valueMapping[value] !== undefined)) {
return chartDataOptions.valueMapping[value].color;
}
return null;
}
static rollUpContiguous (data) {
let areEquivalentBuckets = (d1, d2) => {
if (!d1.measures || !d2.measures) {
return false;
}
if (Object.keys(d1.measures).length !== Object.keys(d2.measures).length) {
return false;
}
return Object.keys(d1.measures).reduce((p, c, i) => {
return p && (d1.measures[c] === d2.measures[c]);
}, true);
}
return data.filter((d, i) => {
if (i !== 0) {
return !areEquivalentBuckets(d, data[i - 1]);
}
return true;
});
}
static formatOffsetMinutes (offset) {
return (offset < 0 ? '-' : '+') +
Math.floor(offset / 60) + ':' +
(offset % 60 < 10 ? '0' : '') + (offset % 60) + '';
}
static getOffsetMinutes(offset: any, millis: number) {
if (offset == 'Local') {
return -moment.tz.zone(moment.tz.guess()).parse(millis);
}
if (typeof offset == 'string' && isNaN(offset as any)) {
return -moment.tz.zone(offset).parse(millis);
} else {
return offset;
}
}
static offsetUTC (date: Date) {
let offsettedDate = new Date(date.valueOf() - date.getTimezoneOffset()*60*1000);
return offsettedDate;
}
// inverse of getOffsetMinutes, this is the conversion factor of an offsettedTime to UTC in minutes
static getMinutesToUTC (offset: any, millisInOffset: number) {
if (offset == 'Local') {
return moment.tz.zone(moment.tz.guess()).utcOffset(millisInOffset);
}
if (typeof offset == 'string' && isNaN(offset as any)) {
return moment.tz.zone(offset).utcOffset(millisInOffset);
} else {
return -offset;
}
}
static addOffsetGuess (timezoneName) {
let timezone = moment.tz(new Date(), timezoneName.split(' ').join('_'));
let formatted = timezone.format('Z');
return "UTC" + formatted;
}
static timezoneAbbreviation (timezoneName) {
let abbr = moment.tz(new Date(), timezoneName).format('z');
if (abbr[0] === '-' || abbr[0] === '+')
return '';
return abbr;
}
static createTimezoneAbbreviation (offset) {
let timezone = Utils.parseTimezoneName(offset);
let timezoneAbbreviation = Utils.timezoneAbbreviation(timezone);
return (timezoneAbbreviation.length !== 0 ? timezoneAbbreviation : Utils.addOffsetGuess(timezone));
}
static parseTimezoneName (timezoneRaw: any) {
if (!isNaN(timezoneRaw)) {
if (timezoneRaw === 0) {
return 'UTC';
}
return '';
}
if (timezoneRaw == 'Local') {
return moment.tz.guess();
}
return timezoneRaw !== null ? timezoneRaw.split(' ').join('_'): '';
}
static convertTimezoneToLabel (timezone , locdLocal = 'Local') {
let timezoneName = this.parseTimezoneName(timezone);
let localPrefix = '';
let offsetPrefix = '';
if (timezone == 'Local') {
localPrefix = locdLocal + ' - ';
}
if (timezone !== 'UTC') {
offsetPrefix = ' (' + this.addOffsetGuess(timezoneName) + ')';
}
let timezoneAbbreviation = this.timezoneAbbreviation(timezoneName);
let timezoneSuffix = (timezoneAbbreviation && timezoneAbbreviation.length !== 0 && timezoneAbbreviation !== 'UTC') ? ': ' + timezoneAbbreviation : '';
return offsetPrefix + " " + localPrefix + timezoneName.replace(/_/g, ' ') + timezoneSuffix;
}
static rangeTimeFormat (rangeMillis: number) {
var rangeText = "";
var oneSecond = 1000;
var oneMinute = 60 * 1000;
var oneHour = oneMinute * 60;
var oneDay = oneHour * 24;
var days = Math.floor(rangeMillis / oneDay);
var hours = Math.floor(rangeMillis / oneHour) % 24;
var minutes = Math.floor(rangeMillis / oneMinute) % 60;
var seconds = Math.floor(rangeMillis / oneSecond) % 60;
var millis = Math.floor(rangeMillis % 1000);
if (rangeMillis >= oneDay) {
return days + "d " + (hours > 0 ? (hours + "h") : "");
} else if (rangeMillis >= oneHour) {
return hours + "h " + (minutes > 0 ? (minutes + "m") : "");
} else if (rangeMillis >= oneMinute) {
return minutes + "m " + (seconds > 0 ? (seconds + "s") : "");
}
else if (rangeMillis >= oneSecond) {
return seconds + (millis != 0 ? "." + millis : "") + "s";
}
return millis + "ms";
}
static subDateTimeFormat (is24HourTime, usesSeconds ,usesMillis) {
return (is24HourTime ? "HH" : "hh") + ":mm" + (usesSeconds ? (":ss" + (usesMillis ? ".SSS" : "")) : "") + (is24HourTime ? "" : " A");
};
static timeFormat(usesSeconds = false, usesMillis = false, offset: any = 0, is24HourTime: boolean = true, shiftMillis: number = null, timeFormat: string = null, locale='en') {
return (d) => {
if (shiftMillis !== 0) {
d = new Date(d.valueOf() + shiftMillis);
}
let stringFormat;
if (timeFormat !== null) {
stringFormat = timeFormat;
} else {
stringFormat = "L " + this.subDateTimeFormat(is24HourTime, usesSeconds, usesMillis);
}
if (typeof offset == 'string' && isNaN(offset as any)) {
return moment.tz(d, 'UTC').tz(offset === 'Local' ? moment.tz.guess() : offset).locale(locale).format(stringFormat);
} else {
return moment.tz(d, "UTC").utcOffset(offset).locale(locale).format(stringFormat);
}
}
}
static splitTimeLabel (text: any) {
let shouldSplit = (str) => {
let splitLines = str.split(' ');
return !((splitLines.length === 1) || (splitLines.length === 2 && (splitLines[1] === 'AM' || splitLines[1] === 'PM')));
}
text.each(function () {
if(this.children == undefined || this.children.length == 0){ // don't split already split labels
var text = d3.select(this);
var lines = text.text().split(" ");
var dy = parseFloat(text.attr("dy"));
if (shouldSplit(text.text())) {
let newFirstLine = lines[0] + (lines.length === 3 ? (' ' + lines[1]) : '');
let newSecondLine = lines[lines.length - 1];
text.text(null).append("tspan")
.attr("x", 0)
.attr("y", text.attr("y"))
.attr("dy", dy + "em")
.text(newFirstLine);
text.append("tspan")
.attr("x", 0)
.attr("y", text.attr("y"))
.attr("dy", (dy + dy * 1.4) + "em")
.text(newSecondLine);
}
}
});
}
static getUTCHours (d: Date, is24HourTime: boolean = true) {
var hours = d.getUTCHours();
if (!is24HourTime) {
if (hours == 0)
hours = 12;
if (hours > 12)
hours = hours - 12;
}
return hours;
}
static UTCTwelveHourFormat (d: Date) {
var hours: string = String(this.getUTCHours(d));
var minutes: string = (d.getUTCMinutes() < 10 ? "0" : "") + String(d.getUTCMinutes());
var amPm: string = (d.getUTCHours() < 12) ? "AM" : "PM";
return hours + ":" + minutes + " " + amPm;
}
static getAgVisible(displayState: any, aggI: string, splitBy: string) {
return (displayState[aggI].visible) ? displayState[aggI].splitBys[splitBy].visible : false;
}
static getAgVisibleMeasure(displayState: any, aggI: string, splitBy: string) {
return displayState[aggI].splitBys[splitBy].visibleType;
}
static createSeriesTypeIcon(seriesType: string, selection: any): void {
var g = selection.append("g")
.style("position", "absolute");
if (seriesType == "event") {
g.attr("transform", "translate(7.5,0)")
.append("rect")
.attr("width", 7)
.attr("height", 7)
.attr("transform", "rotate(45)");
}
else if (seriesType == "state") {
g.append("rect")
.attr("width", 15)
.attr("height", 10);
}
else { // fxn
g.append("path")
.attr("d", "M0 5 Q 4 0, 8 5 T 16 5")
.attr("fill", "none");
}
}
static strip(text) {
var div = document.createElement('div');
div.innerHTML = text;
var textContent = div.textContent || div.innerText || '';
return textContent;
}
static stripForConcat(text) {
var specialCharacters = ['"', "'", '?', '<', '>', ';'];
specialCharacters.forEach(c => { text = text.split(c).join('') });
return text;
}
static setSeriesLabelSubtitleText (subtitle, isInFocus: boolean = false) {
let subtitleDatum = subtitle.data()[0];
if (!subtitle.select('.tsi-splitBy').empty()) {
let textAfterSplitByExists = subtitleDatum.timeShift !== '' || subtitleDatum.variableAlias;
let splitByString = `${subtitleDatum.splitBy}${(textAfterSplitByExists && !isInFocus) ? ', ' : ''}`;
Utils.appendFormattedElementsFromString(subtitle.select('.tsi-splitBy'), splitByString);
}
if (subtitle.select('.tsi-timeShift')) {
subtitle.select('.tsi-timeShift')
.text(d => {
return `${subtitleDatum.timeShift}${(subtitleDatum.variableAlias && !isInFocus) ? ', ' : ''}`;
});
}
if (subtitle.select('.tsi-variableAlias')) {
subtitle.select('.tsi-variableAlias')
.text(d => subtitleDatum.variableAlias);
}
}
static revertAllSubtitleText (markerValues, opacity = 1) {
let self = this;
markerValues.classed('tsi-isExpanded', false)
.style('opacity', opacity)
.each(function () {
self.setSeriesLabelSubtitleText(d3.select(this).selectAll('.tsi-tooltipSubtitle'), false);
});
}
static generateColors (numColors: number, includeColors: string[] = null) {
let defaultColors = ['#008272', '#D869CB', '#FF8C00', '#8FE6D7', '#3195E3', '#F7727E', '#E0349E', '#C8E139', '#60B9AE',
'#93CFFB', '#854CC7', '#258225', '#0078D7', '#FF2828', '#FFF100'];
var postDefaultColors = d3.scaleSequential(d3.interpolateCubehelixDefault).domain([defaultColors.length -.5, numColors - .5]);
var colors = [];
let colorsIndex = 0;
if(includeColors) {//add the colors we want to include first
for(let i = 0; i < includeColors.length && colorsIndex < numColors; i++) {
let color = includeColors[i];
if (colors.indexOf(color) === -1) {
colors.push(color);
colorsIndex++;
}
}
}
for(let i = 0; colorsIndex < numColors; i++) {
if (i < defaultColors.length) {
if(colors.indexOf(defaultColors[i]) === -1) {
colors.push(defaultColors[i]);
colorsIndex++;
}
}
else if(colors.indexOf(postDefaultColors(i)) === -1) {
colors.push(postDefaultColors(i));
colorsIndex++;
}
}
return colors;
}
static convertFromLocal (date: Date) {
return new Date(date.valueOf() - date.getTimezoneOffset() * 60 * 1000);
}
static adjustDateFromTimezoneOffset (date: Date) {
let dateCopy = new Date(date.valueOf());
dateCopy.setTime(dateCopy.getTime() + dateCopy.getTimezoneOffset()*60*1000 );
return dateCopy;
}
static offsetFromUTC (date: Date, offset = 0) {
let offsetMinutes = Utils.getOffsetMinutes(offset, date.valueOf());
var dateCopy = new Date(date.valueOf() + offsetMinutes * 60 * 1000);
return dateCopy;
}
static offsetToUTC (date: Date, offset = 0) {
let offsetMinutes = Utils.getOffsetMinutes(offset, date.valueOf())
var dateCopy = new Date(date.valueOf() - offsetMinutes * 60 * 1000);
return dateCopy;
}
static parseUserInputDateTime (timeText, offset) {
let dateTimeFormat = "L " + this.subDateTimeFormat(true,true, true);
let parsedDate = moment(timeText, dateTimeFormat).toDate();
let utcDate = this.offsetToUTC(this.convertFromLocal(parsedDate), offset);
return utcDate.valueOf();
}
static getBrighterColor (color: string) {
let hclColor = <any>d3.hcl(color);
if (hclColor.l < 80) {
return hclColor.brighter().toString();
}
return hclColor.toString();
}
static createSplitByColors(displayState: any, aggKey: string, ignoreIsOnlyAgg: boolean = false) {
if (Object.keys(displayState[aggKey]["splitBys"]).length == 1)
return [displayState[aggKey].color];
var isOnlyAgg: boolean = Object.keys(displayState).reduce((accum, currAgg): boolean => {
if (currAgg == aggKey)
return accum;
if (displayState[currAgg]["visible"] == false)
return accum && true;
return false;
}, true);
if (isOnlyAgg && !ignoreIsOnlyAgg) {
return this.generateColors(Object.keys(displayState[aggKey]["splitBys"]).length);
}
var aggColor = displayState[aggKey].color;
var interpolateColor = d3.scaleLinear().domain([0,Object.keys(displayState[aggKey]["splitBys"]).length])
.range([<any>d3.hcl(aggColor).darker(), <any>d3.hcl(aggColor).brighter()]);
var colors = [];
for(var i = 0; i < Object.keys(displayState[aggKey]["splitBys"]).length; i++){
colors.push(interpolateColor(i));
}
return colors;
}
static colorSplitBy(displayState: any, splitByIndex: number, aggKey: string, ignoreIsOnlyAgg: boolean = false) {
if (Object.keys(displayState[aggKey]["splitBys"]).length == 1)
return displayState[aggKey].color;
var isOnlyAgg: boolean = Object.keys(displayState).reduce((accum, currAgg): boolean => {
if (currAgg == aggKey)
return accum;
if (displayState[currAgg]["visible"] == false)
return accum && true;
return false;
}, true);
if (isOnlyAgg && !ignoreIsOnlyAgg) {
var splitByColors = this.generateColors(Object.keys(displayState[aggKey]["splitBys"]).length);
return splitByColors[splitByIndex];
}
var aggColor = displayState[aggKey].color;
var interpolateColor = d3.scaleLinear().domain([0,Object.keys(displayState[aggKey]["splitBys"]).length])
.range([<any>d3.hcl(aggColor).darker(), <any>d3.hcl(aggColor).brighter()])
return interpolateColor(splitByIndex);
}
static getTheme(theme: any){
return theme ? 'tsi-' + theme : 'tsi-dark';
}
static clearSelection(){
var sel = window.getSelection ? window.getSelection() : (<any>document).selection;
if (sel) {
if (sel.removeAllRanges) {
sel.removeAllRanges();
} else if (sel.empty) {
sel.empty();
}
}
}
static mark(filter, text){
if(filter.length == 0)
return text;
var regExp = new RegExp(filter, 'gi');
return text.replace(regExp, function(m){ return '<mark>'+m+'</mark>';});
}
static hash(str) {
var hash = 5381,
i = str.length;
while(i) {
hash = (hash * 33) ^ str.charCodeAt(--i);
}
/* JavaScript does bitwise operations (like XOR, above) on 32-bit signed
* integers. Since we want the results to be always positive, convert the
* signed int to an unsigned by doing an unsigned bitshift. */
return hash >>> 0;
}
static guid () {
var s4 = () => {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
static createValueFilter (aggregateKey, splitBy) {
return (d: any, j: number ) => {
var currAggKey: string;
var currSplitBy: string;
if (d.aggregateKey) {
currAggKey = d.aggregateKey;
currSplitBy = d.splitBy;
} else if (d && d.length){
currAggKey = d[0].aggregateKey;
currSplitBy = d[0].splitBy
} else
return true;
return (currAggKey == aggregateKey && (splitBy == null || splitBy == currSplitBy));
}
}
static downloadCSV (csvString: string, csvName: string = "Table") {
var blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' });
var blobURL = window.URL.createObjectURL(blob);
var link = document.createElement("a");
link.setAttribute("href", blobURL);
link.setAttribute("download", csvName + ".csv");
link.setAttribute("tabindex", "0");
link.innerHTML= "";
document.body.appendChild(link);
link.click();
}
static sanitizeString (str: any, type: String) {
if (str === null || str === undefined) {
return "";
}
if (type !== valueTypes.Double && type !== valueTypes.Long) {
let jsonifiedString = type === valueTypes.Dynamic ? JSON.stringify(str) : String(str);
if (jsonifiedString.indexOf(',') !== -1 || jsonifiedString.indexOf('"') !== -1 || jsonifiedString.indexOf('\n') !== -1 || type === valueTypes.Dynamic) {
let replacedString = jsonifiedString.replace(/"/g, '""');
return '"' + replacedString + '"';
}
}
return str;
}
static focusOnEllipsisButton (renderTarget) {
let ellipsisContainer = d3.select(renderTarget).select(".tsi-ellipsisContainerDiv");
if (!ellipsisContainer.empty()) {
(<any>ellipsisContainer.select(".tsi-ellipsisButton").node()).focus();
}
}
static createDownloadEllipsisOption (csvStringGenerator, action = () => {}, downloadLabel = "Download as CSV") {
return {
iconClass: "download",
label: downloadLabel,
action:() => {
Utils.downloadCSV(csvStringGenerator());
action();
},
description: ""
};
}
static createControlPanel (renderTarget: any, legendWidth: number, topChartMargin: number, chartOptions: any) {
d3.select(renderTarget).selectAll(".tsi-chartControlsPanel").remove();
var controlPanelWidth = Math.max(1, (<any>d3.select(renderTarget).node()).clientWidth -
(chartOptions.legend == "shown" ? legendWidth : 0));
var chartControlsPanel = d3.select(renderTarget).append("div")
.attr("class", "tsi-chartControlsPanel")
.style("width", controlPanelWidth + "px")
.style("top", Math.max((topChartMargin - 32), 0) + "px");
return chartControlsPanel;
}
static escapeQuotesCommasAndNewlines (stringToEscape: string) {
var escapedString = "";
if (stringToEscape && (stringToEscape.indexOf("\"") != -1 ||
stringToEscape.indexOf(",") != -1 ||
stringToEscape.indexOf("\n") != -1)) {
stringToEscape = stringToEscape.replace(/"/g, "\"\"");
escapedString += "\"";
escapedString += stringToEscape;
escapedString += "\"";
return escapedString;
}
else {
return stringToEscape;
}
};
static getNonNumericHeight (rawHeight: number) {
return rawHeight + NONNUMERICTOPMARGIN;
}
static getControlPanelWidth (renderTarget, legendWidth, isLegendShown) {
return Math.max(1, (<any>d3.select(renderTarget).node()).clientWidth -
(isLegendShown ? legendWidth : 0));
};
static getValueOrDefault (chartOptionsObj, propertyName, defaultValue = null) {
let propertyValue = chartOptionsObj[propertyName];
if (propertyValue == undefined){
if (this[propertyName] == undefined)
return defaultValue;
return this[propertyName];
}
return propertyValue;
}
static safeNotNullOrUndefined (valueLambda) {
try {
let value = valueLambda();
return !(value === null || value === undefined);
}
catch (err){
return false;
}
}
static equalToEventTarget = (function () {
return (this == d3.event.target);
});
static getAggKeys (data) {
let aggregateCounterMap = {};
return data.map((aggregate) => {
var aggName: string = Object.keys(aggregate)[0];
let aggKey;
if (aggregateCounterMap[aggName]) {
aggKey = Utils.createEntityKey(aggName, aggregateCounterMap[aggName]);
aggregateCounterMap[aggName] += 1;
} else {
aggKey = Utils.createEntityKey(aggName, 0);
aggregateCounterMap[aggName] = 1;
}
return aggKey;
});
}
static roundToMillis (rawTo, bucketSize) {
return Math.ceil((rawTo + 62135596800000) / (bucketSize)) * (bucketSize) - 62135596800000;
}
static mergeSeriesForScatterPlot(chartData: any, scatterMeasures: any){
let xMeasure = chartData[scatterMeasures.X_MEASURE], yMeasure = chartData[scatterMeasures.Y_MEASURE], rMeasure = chartData[scatterMeasures.R_MEASURE];
let measureNames = Utils.getScatterPlotMeasureNames(chartData, scatterMeasures);
// Create data label
let xLabel = xMeasure.additionalFields.Variable.substring(0, 15) + (xMeasure.additionalFields.Variable.length > 15 ? "... vs" : " vs");
let yLabel = " " + yMeasure.additionalFields.Variable.substring(0, 15) + (yMeasure.additionalFields.Variable.length > 15 ? "... " : "");
let rLabel = (rMeasure != null ? " vs " + rMeasure.additionalFields.Variable.substring(0, 15) + (rMeasure.additionalFields.Variable.length > 15 ? "... " : "") : "");
let dataTitle = xLabel + yLabel + rLabel;
// Initialize scatter plot data object
let scatterData = {
[dataTitle] : {
"": {}
}
};
// Create measure types
let measureTypes = {
X_MEASURE_TYPE: 'avg' in xMeasure.measureTypes ? xMeasure.measureTypes['avg'] : xMeasure.measureTypes[0],
Y_MEASURE_TYPE: 'avg' in yMeasure.measureTypes ? yMeasure.measureTypes['avg'] : yMeasure.measureTypes[0],
R_MEASURE_TYPE: null
}
// Takes query and returns normalized time data
let normalizeTimestampKeys = (query) => {
let newTS = {}
Object.keys(query.data[query.alias][""]).forEach((key) => {
let oldTime = new Date(key).valueOf();
let timeShift = query.timeShift != "" ? this.parseShift(query.timeShift, query.startAt, query.searchSpan): 0;
// Calculate real timeshift based on bucket snapping
let bucketShiftInMillis = this.adjustStartMillisToAbsoluteZero(timeShift, this.parseShift(query.searchSpan.bucketSize));
let normalizedTime = oldTime - bucketShiftInMillis;
let timestamp = new Date(normalizedTime).toISOString();
newTS[timestamp] = query.data[query.alias][""][key];
})
return newTS;
}
// Normalize timestamp data
xMeasure.data[xMeasure.alias][""] = normalizeTimestampKeys(xMeasure);
yMeasure.data[yMeasure.alias][""] = normalizeTimestampKeys(yMeasure);
if(rMeasure){
rMeasure.data[rMeasure.alias][""] = normalizeTimestampKeys(rMeasure);
measureTypes.R_MEASURE_TYPE = 'avg' in rMeasure.measureTypes ? rMeasure.measureTypes['avg'] : rMeasure.measureTypes[0]
}
// For each timestamp in X data mix measures of other series
Object.keys(xMeasure.data[xMeasure.alias][""]).forEach((key) => {
if(key in yMeasure.data[yMeasure.alias][""]){
let measures = {}
measures[measureNames.X_MEASURE] = xMeasure.data[xMeasure.alias][""][key][measureTypes.X_MEASURE_TYPE];
measures[measureNames.Y_MEASURE] = yMeasure.data[yMeasure.alias][""][key][measureTypes.Y_MEASURE_TYPE];
// Add optional R measure
if(rMeasure != null && key in rMeasure.data[rMeasure.alias][""]){
measures[measureNames.R_MEASURE] = rMeasure.data[rMeasure.alias][""][key][measureTypes.R_MEASURE_TYPE];
}
// Discard timestamps with null valued measures
if(xMeasure.data[xMeasure.alias][""][key][measureTypes.X_MEASURE_TYPE] && yMeasure.data[yMeasure.alias][""][key][measureTypes.Y_MEASURE_TYPE])
{
if(rMeasure != null){
if(key in rMeasure.data[rMeasure.alias][""] && rMeasure.data[rMeasure.alias][""][key][measureTypes.R_MEASURE_TYPE])
scatterData[dataTitle][""][key] = measures;
}
else{
scatterData[dataTitle][""][key] = measures;
}
}
}
});
return scatterData;
}
static getScatterPlotMeasureNames(chartData: any, scatterMeasures: any){
let uniqueNameMap = {}
let xMeasureName = chartData[scatterMeasures.X_MEASURE].alias + " " + chartData[scatterMeasures.X_MEASURE].additionalFields.Variable +
(chartData[scatterMeasures.X_MEASURE].timeShift == "" ? "" : " " + chartData[scatterMeasures.X_MEASURE].timeShift);
uniqueNameMap[xMeasureName] = 1;
let yMeasureName = chartData[scatterMeasures.Y_MEASURE].alias + " " + chartData[scatterMeasures.Y_MEASURE].additionalFields.Variable +
(chartData[scatterMeasures.Y_MEASURE].timeShift == "" ? "" : " " + chartData[scatterMeasures.Y_MEASURE].timeShift);
if(yMeasureName in uniqueNameMap){
let tempName = yMeasureName;
yMeasureName += " (" + uniqueNameMap[yMeasureName].toString() + ")";
uniqueNameMap[tempName] = uniqueNameMap[tempName] + 1;
} else{
uniqueNameMap[yMeasureName] = 1;
}
let rMeasureName = chartData[scatterMeasures.R_MEASURE] ? chartData[scatterMeasures.R_MEASURE].alias + " " + chartData[scatterMeasures.R_MEASURE].additionalFields.Variable +
(chartData[scatterMeasures.R_MEASURE].timeShift == "" ? "" : " " + chartData[scatterMeasures.R_MEASURE].timeShift) : null;
if(rMeasureName != null){
if(rMeasureName in uniqueNameMap){
rMeasureName += " (" + uniqueNameMap[rMeasureName].toString() + ")";
}
}
return {
X_MEASURE: xMeasureName,
Y_MEASURE: yMeasureName,
R_MEASURE: rMeasureName ? rMeasureName : null
}
}
static isKeyDownAndNotEnter = (e) => {
if (e && e.type && e.type === 'keydown') {
let key = e.which || e.keyCode;
if (key !== 13) {
return true;
} else {
e.preventDefault();
}
}
return false;
}
static getMinWarmTime (warmStoreFrom, retentionString) {
let minWarmTime = new Date(warmStoreFrom);
if (retentionString !== null) {
let retentionPeriod = Utils.parseTimeInput(retentionString);
minWarmTime = new Date(Math.max(minWarmTime.valueOf(), (Date.now() - retentionPeriod)));
}
return minWarmTime;
}
static standardizeTSStrings (rawData) {
let convertedData = [];
rawData.forEach((dG, i) => {
let dGName = Object.keys(dG)[0];
let dataGroup = dG[dGName];
let convertedDataGroup = {};
let dataGroupKeyedObject = {};
dataGroupKeyedObject[dGName] = convertedDataGroup;
convertedData.push(dataGroupKeyedObject);
if (dataGroup) {
Object.keys(dataGroup).forEach((seriesName) => {
convertedDataGroup[seriesName] = {};
if (dataGroup[seriesName]) {
Object.keys(dataGroup[seriesName]).forEach((rawTS: string) => {
let isoString: string;
try {
isoString = (new Date(rawTS)).toISOString();
convertedDataGroup[seriesName][isoString] = dataGroup[seriesName][rawTS];
} catch(RangeError) {
console.log(`${rawTS} is not a valid ISO time`);
}
});
}
});
}
});
return convertedData;
}
// takes in an availability distribution and a min and max date, returns a tuple, where the first is the new distribution
// excluding values out of the range, and the second is all excluded values
static cullValuesOutOfRange (availabilityDistribution: any, minDateString: string, maxDateString: string) {
const dateZero = '0000-01-01T00:00:00Z';
let minDateValue = new Date(minDateString).valueOf();
let maxDateValue = new Date(maxDateString).valueOf();
if (new Date(availabilityDistribution.range.from).valueOf() < minDateValue ||
new Date(availabilityDistribution.range.to).valueOf() > maxDateValue) {
let inRangeValues = {};
let outOfRangeValues = {};
let highestNotOverMaxString = dateZero;
let highestNotOverMaxValue = (new Date(highestNotOverMaxString)).valueOf();
let lowestAboveMinValue = Infinity;
Object.keys(availabilityDistribution.distribution).forEach((bucketKey: string) => {
let bucketValue = (new Date(bucketKey)).valueOf();
if (bucketValue > maxDateValue || bucketValue < minDateValue) {
outOfRangeValues[bucketKey] = availabilityDistribution.distribution[bucketKey];
} else {
inRangeValues[bucketKey] = availabilityDistribution.distribution[bucketKey];
if (bucketValue > highestNotOverMaxValue) {
highestNotOverMaxValue = bucketValue;
highestNotOverMaxString = bucketKey;
}
if (bucketValue < lowestAboveMinValue) {
lowestAboveMinValue = bucketValue
}
}
});
const bucketSize = this.parseTimeInput(availabilityDistribution.intervalSize);
if (highestNotOverMaxString !== dateZero) { // a value exists
let nowMillis = new Date().valueOf();
if(highestNotOverMaxValue < nowMillis && (highestNotOverMaxValue + bucketSize) > nowMillis){
// the new end value was before now, but after adding bucket size, its after now
// so we set it to now to avoid setting it to a date in the future
availabilityDistribution.range.to = new Date(nowMillis).toISOString();
}
else{
availabilityDistribution.range.to = new Date(highestNotOverMaxValue + bucketSize).toISOString();
}
} else {
let rangeToValue: number = (new Date(availabilityDistribution.range.to)).valueOf();
if (minDateValue > rangeToValue) { // entire window is to the right of distribution range
availabilityDistribution.range.to = maxDateString;
} else {
let toValue = Math.min(maxDateValue + bucketSize, (new Date(availabilityDistribution.range.to)).valueOf()); //clamped to maxDateString passed in
availabilityDistribution.range.to = (new Date(toValue)).toISOString();
}
}
if (lowestAboveMinValue !== Infinity) { // a value exists
availabilityDistribution.range.from = (new Date(lowestAboveMinValue)).toISOString();
} else {
let rangeFromValue: number = (new Date(availabilityDistribution.range.from)).valueOf();
if (maxDateValue < (new Date(availabilityDistribution.range.from)).valueOf()) { // entire window is to the left of distribution range
availabilityDistribution.range.from = minDateString;
} else {
let fromValue = Math.max(minDateValue, rangeFromValue); // clamped to minDateString passed in
availabilityDistribution.range.from = (new Date(fromValue)).toISOString();
}
}
availabilityDistribution.distribution = inRangeValues;
return[availabilityDistribution, outOfRangeValues];
}
return [availabilityDistribution, {}];
}
static mergeAvailabilities (warmAvailability, coldAvailability, retentionString = null) {
let warmStoreRange = warmAvailability.range;
let minWarmTime = this.getMinWarmTime(warmStoreRange.from, retentionString);
let warmStoreToMillis = new Date(warmStoreRange.to).valueOf();
let coldStoreToMillis = new Date(coldAvailability.range.to).valueOf();
// snap warm availability to cold availability if its ahead of cold
let maxWarmTime = new Date(Math.min(warmStoreToMillis, coldStoreToMillis));
let mergedAvailability = Object.assign({}, coldAvailability);
mergedAvailability.warmStoreRange = [minWarmTime.toISOString(), maxWarmTime.toISOString()];
if (retentionString !== null) {
mergedAvailability.retentionPeriod = retentionString;
}
return mergedAvailability;
}
static languageGuess () {
return navigator.languages && navigator.languages[0] || // Chrome / Firefox
navigator.language; // All browsers
}
static getInstanceKey = (instance) => { // for keying instances using timeseriesid to be used data object to render hierarchy navigation
return Utils.instanceHasEmptyTSID(instance) ? Utils.guid() : instance.timeSeriesId.map(id => id === null ? Utils.guidForNullTSID : id).join();
}
static stripNullGuid = (str) => { // for replacing guids for null tsid in alias etc. with its display string
return str.replace(Utils.guidForNullTSID, nullTsidDisplayString);
}
static getTimeSeriesIdString = (instance) => { // for arialabel and title
return instance.timeSeriesId.map(id => id === null ? nullTsidDisplayString : id).join(', ');
}
static getTimeSeriesIdToDisplay = (instance, emptyDisplayString) => { // time series id to be shown in UI
return Utils.instanceHasEmptyTSID(instance) ? emptyDisplayString : instance.timeSeriesId.map(id => id === null ? Utils.guidForNullTSID : id).join(', ');
}
static getHighlightedTimeSeriesIdToDisplay = (instance) => { // highlighted time series ids (including hits) to be shown in UI
return instance.highlights?.timeSeriesId.map((id, idx) => instance.timeSeriesId[idx] === null ? Utils.guidForNullTSID : id).join(', ');
}
static instanceHasEmptyTSID = (instance) => {
return !instance.timeSeriesId || instance.timeSeriesId.length === 0;
}
// appends dom elements of stripped strings including hits (for instance search results) and mono classed spans (for null tsid)
static appendFormattedElementsFromString = (targetElem, str, options: {additionalClassName?: string, inSvg?: boolean, splitByTag?: string} = null) => {
interface FormattedElemData {
str: string;
isHit?: boolean;
isNull?: boolean;
};
let data : Array<FormattedElemData> = [];
let splitByNullGuid = (str) : Array<any> => {
let data = [];
let splittedByNull = str.split(Utils.guidForNullTSID);
splittedByNull.forEach((s, i) => {
if (i === 0) {
if (s) {
data.push({str: s});
}
} else {
data.push({str: nullTsidDisplayString, isNull: true});
if (s) {
data.push({str: s});
}
}
});
return data;
}
let splitByTag = options && options.splitByTag ? options.splitByTag : 'hit';
let splittedByHit = str.split(`<${splitByTag}>`);
splittedByHit.forEach((s, i) => {
if (i === 0) {
data = data.concat(splitByNullGuid(s));
} else {
let splittedByHitClose = s.split(`</${splitByTag}>`);
data.push({str: splittedByHitClose[0], isHit: true});
data = data.concat(splitByNullGuid(splittedByHitClose[1]));
}
});
let additionalClassName = options && options.additionalClassName ? options.additionalClassName : '';
let children = targetElem.selectAll('.tsi-formattedChildren').data(data);
children.enter()
.append(d =>
d.isHit ? document.createElement('mark')
: options && options.inSvg ? document.createElementNS('http://www.w3.org/2000/svg', 'tspan')
: document.createElement('span')
)
.classed('tsi-formattedChildren', true)
.merge(children)
.classed('tsi-baseMono', d => d.isNull)
.classed(additionalClassName, options && options.additionalClassName)
.text(d => d.str);
children.exit().remove();
}
static escapedTsidForExactSearch = (tsid: string) => {
let escapedTsid = tsid || '';
if (tsid) {
CharactersToEscapeForExactSearchInstance.forEach(c => { //escaping some special characters with + for exact instance search in quotes
escapedTsid = escapedTsid.split(c).join('+');
});
}
return escapedTsid;
}
static memorySizeOf (obj) {
let bytes = 0;
let sizeOf = (obj) => {
if (obj !== null && obj !== undefined) {
switch (typeof obj) {
case 'number':
bytes += 8;
break;
case 'string':
bytes += obj.length * 2;
break;
case 'boolean':
bytes += 4;
break;
case 'object':
let objClass = Object.prototype.toString.call(obj).slice(8, -1);
if (objClass === 'Object' || objClass === 'Array') {
for (let key in obj) {
if (!obj.hasOwnProperty(key)) {continue; }
sizeOf(key);
sizeOf(obj[key]);
}
} else {
bytes += obj.toString().length * 2;
}
break;
}
}
return bytes;
};
return sizeOf(obj);
}
} | the_stack |
import { CustomElement } from 'extraterm-web-component-decorators';
import { ResizeNotifier } from 'extraterm-resize-notifier';
import {Logger, getLogger} from "extraterm-logging";
import { log } from "extraterm-logging";
import { trimBetweenTags } from 'extraterm-trim-between-tags';
import * as ThemeTypes from '../../theme/Theme';
import * as DomUtils from '../DomUtils';
import { RefreshLevel } from '../viewers/ViewerElementTypes';
import { ThemeableElementBase } from '../ThemeableElementBase';
const ID_TOP = "ID_TOP";
const ID_CONTAINER = "ID_CONTAINER";
const ID_COVER = "ID_COVER";
const ID_INDICATOR = "ID_INDICATOR";
const CLASS_DIVIDER = "CLASS_DIVIDER";
const CLASS_PANE = "CLASS_PANE";
const CLASS_NORMAL = "CLASS_NORMAL";
const CLASS_DRAG = "CLASS_DRAG";
const CLASS_VERTICAL = "CLASS_VERTICAL";
const CLASS_HORIZONTAL = "CLASS_HORIZONTAL";
const DIVIDER_SIZE = 4;
const NOT_DRAGGING = -1;
const MIN_PANE_SIZE = 32;
export enum SplitOrientation {
VERTICAL,
HORIZONTAL
}
/**
* A widget to display panes of widgets separated by a moveable gap/bar.
*
*/
@CustomElement("et-splitter")
export class Splitter extends ThemeableElementBase {
static TAG_NAME = "ET-SPLITTER";
private static _resizeNotifier = new ResizeNotifier();
private _log: Logger;
private _mutationObserver: MutationObserver = null;
private _orientation: SplitOrientation = SplitOrientation.VERTICAL;
private _paneSizes: PaneSizes;
private _dividerDrag: number = NOT_DRAGGING; // The number of the divider currently being dragged. -1 means not dragging.
private _dividerDragOffset: number = 0;
constructor() {
super();
this._log = getLogger(Splitter.TAG_NAME, this);
this.attachShadow({ mode: 'open', delegatesFocus: false });
const styleElement = document.createElement("style");
styleElement.id = ThemeableElementBase.ID_THEME;
this.shadowRoot.appendChild(styleElement);
this.shadowRoot.appendChild(DomUtils.htmlToFragment(trimBetweenTags(this._html())));
this.updateThemeCss();
this._paneSizes = new PaneSizes();
const topDiv = this._elementById(ID_TOP);
topDiv.classList.add(CLASS_NORMAL);
Splitter._resizeNotifier.observe(topDiv, (target: Element, contentRect: DOMRectReadOnly) => {
this._handleResize();
});
topDiv.addEventListener('mousedown', this._handleMouseDown.bind(this));
topDiv.addEventListener('mouseup', this._handleMouseUp.bind(this));
topDiv.addEventListener('mousemove', this._handleMouseMove.bind(this));
const coverDiv = this._elementById(ID_COVER);
coverDiv.addEventListener('mouseleave', this._handleMouseLeave.bind(this));
const indicatorDiv = this._elementById(ID_INDICATOR);
indicatorDiv.style.width = "" + DIVIDER_SIZE + "px";
const rect = topDiv.getBoundingClientRect();
const width = rect.width === 0 ? 1024 : rect.width;
this._paneSizes = PaneSizes.equalPaneSizes(width, DomUtils.toArray(this.children));
topDiv.classList.add(CLASS_VERTICAL);
this._mutationObserver = new MutationObserver(this._handleMutations.bind(this));
this._mutationObserver.observe(this, { childList: true });
this.updateThemeCss();
}
private _handleResize(): void {
if ( ! this.isConnected) {
return;
}
this._refresh(RefreshLevel.COMPLETE);
}
connectedCallback(): void {
super.connectedCallback();
this._handleResize();
}
protected _themeCssFiles(): ThemeTypes.CssFile[] {
return [ThemeTypes.CssFile.GENERAL_GUI, ThemeTypes.CssFile.GUI_SPLITTER];
}
getSplitOrientation(): SplitOrientation {
return this._orientation;
}
setSplitOrientation(orientation: SplitOrientation): void {
if (this._orientation !== orientation) {
this._orientation = orientation;
const topDiv = this._elementById(ID_TOP);
const rect = topDiv.getBoundingClientRect();
const rectSize = this._orientation === SplitOrientation.VERTICAL ? rect.width : rect.height;
const size = rectSize === 0 ? 1024 : rectSize;
this._paneSizes = PaneSizes.equalPaneSizes(size, DomUtils.toArray(this.children));
const indicatorDiv = this._elementById(ID_INDICATOR);
if (this._orientation === SplitOrientation.HORIZONTAL) {
indicatorDiv.style.width = null;
indicatorDiv.style.height = "" + DIVIDER_SIZE + "px";
topDiv.classList.remove(CLASS_VERTICAL);
topDiv.classList.add(CLASS_HORIZONTAL);
} else {
indicatorDiv.style.width = "" + DIVIDER_SIZE + "px";
indicatorDiv.style.height = null;
topDiv.classList.remove(CLASS_HORIZONTAL);
topDiv.classList.add(CLASS_VERTICAL);
}
this._createLayout(this._paneSizes);
}
}
getDividerSize(): number {
return DIVIDER_SIZE;
}
getPaneSizes(): number[] {
const result: number[] = [];
for (let i=0; i<this._paneSizes.length(); i++) {
result.push(this._paneSizes.get(i));
}
return result;
}
private _refresh(level: RefreshLevel): void {
if (DomUtils.getShadowRoot(this) !== null && DomUtils.isNodeInDom(this)) {
// DOM read
if (level === RefreshLevel.COMPLETE) {
this._paneSizes = this._paneSizes.update(DomUtils.toArray(this.children));
this._createLayout(this._paneSizes);
}
const topDiv = this._elementById(ID_TOP);
const rect = topDiv.getBoundingClientRect();
const size = this._orientation === SplitOrientation.VERTICAL ? rect.width : rect.height;
if (size !== 0) {
const newPaneSizes = this._paneSizes.updateTotalSize(size);
this._paneSizes = newPaneSizes;
this._setSizes(newPaneSizes, this._orientation);
}
}
}
protected _html(): string {
return `<div id='${ID_TOP}'>
<div id='${ID_CONTAINER}'></div>
<div id='${ID_COVER}'><div id='${ID_INDICATOR}'></div></div>
</div>`;
}
private _handleMouseDown(ev: MouseEvent): void {
const target = <HTMLElement> ev.target;
if ( ! target.classList.contains(CLASS_DIVIDER)) {
return;
}
ev.preventDefault();
ev.stopPropagation();
// Figure out which divider was hit.
const containerDiv = this._elementById(ID_CONTAINER);
let dividerIndex = -1;
for (let i=0; i<containerDiv.children.length; i++) {
if (containerDiv.children.item(i) === target) {
dividerIndex = (i-1)/2;
break;
}
}
if (dividerIndex === -1) {
return;
}
this._dividerDrag = dividerIndex;
if (this._orientation === SplitOrientation.VERTICAL) {
this._dividerDragOffset = ev.offsetX;
} else {
this._dividerDragOffset = ev.offsetY;
}
const topDiv = this._elementById(ID_TOP);
topDiv.classList.add(CLASS_DRAG);
topDiv.classList.remove(CLASS_NORMAL);
const indicatorDiv = this._elementById(ID_INDICATOR);
const topRect = topDiv.getBoundingClientRect();
if (this._orientation === SplitOrientation.VERTICAL) {
indicatorDiv.style.left = "" + (ev.clientX - topRect.left - this._dividerDragOffset) + "px";
} else {
indicatorDiv.style.top = "" + (ev.clientY - topRect.top - this._dividerDragOffset) + "px";
}
}
private _handleMouseUp(ev: MouseEvent): void {
if (this._dividerDrag === NOT_DRAGGING) {
return;
}
ev.preventDefault();
ev.stopPropagation();
// Now actually move the divider.
const topDiv = this._elementById(ID_TOP);
const topRect = topDiv.getBoundingClientRect();
let newIndicatorPosition = 0;
if (this._orientation === SplitOrientation.VERTICAL) {
newIndicatorPosition = ev.clientX - topRect.left - this._dividerDragOffset;
} else {
newIndicatorPosition = ev.clientY - topRect.top - this._dividerDragOffset;
}
this._paneSizes = this._paneSizes.adjustPaneSize(this._dividerDrag, newIndicatorPosition);
this._setSizes(this._paneSizes, this._orientation);
this._stopDrag();
}
private _stopDrag(): void {
const topDiv = this._elementById(ID_TOP);
if (this._dividerDrag === NOT_DRAGGING) {
return;
}
topDiv.classList.remove(CLASS_DRAG);
topDiv.classList.add(CLASS_NORMAL);
this._dividerDrag = NOT_DRAGGING;
}
private _handleMouseMove(ev: MouseEvent): void {
if (this._dividerDrag === NOT_DRAGGING) {
return;
}
if ((ev.buttons & 1) === 0) {
this._stopDrag();
return;
}
const topDiv = this._elementById(ID_TOP);
const indicatorDiv = this._elementById(ID_INDICATOR);
const topRect = topDiv.getBoundingClientRect();
let newIndicatorPosition = 0;
if (this._orientation === SplitOrientation.VERTICAL) {
newIndicatorPosition = ev.clientX - topRect.left - this._dividerDragOffset;
} else {
newIndicatorPosition = ev.clientY - topRect.top - this._dividerDragOffset;
}
const newPaneSizes = this._paneSizes.adjustPaneSize(this._dividerDrag, newIndicatorPosition);
if (this._orientation === SplitOrientation.VERTICAL) {
indicatorDiv.style.left = "" + newPaneSizes.getPaneNext(this._dividerDrag) + "px";
} else {
indicatorDiv.style.top = "" + newPaneSizes.getPaneNext(this._dividerDrag) + "px";
}
}
private _handleMouseLeave(ev: MouseEvent): void {
this._stopDrag();
}
/**
* Immediately perform any pending layout updates.
*
* If this is not called then updates are performed at the next microtask via the mutation observer.
*/
update(): void {
this._handleMutations(this._mutationObserver.takeRecords());
}
private _handleMutations(mutations: MutationRecord[]): void {
this._paneSizes = this._paneSizes.update(DomUtils.toArray(this.children));
this._createLayout(this._paneSizes);
}
//-----------------------------------------------------------------------
//
// #
// # ## # # #### # # #####
// # # # # # # # # # #
// # # # # # # # # #
// # ###### # # # # # #
// # # # # # # # # #
// ####### # # # #### #### #
//
//-----------------------------------------------------------------------
private _createLayout(paneSizes: PaneSizes): void {
const topDiv = this._elementById(ID_CONTAINER);
topDiv.innerHTML = "";
for (let i=0; i<this.children.length; i++) {
const kid = <HTMLElement>this.children.item(i);
kid.slot = "slot" + i;
const paneDiv = this.ownerDocument.createElement("DIV");
paneDiv.classList.add(CLASS_PANE);
const slotElement = this.ownerDocument.createElement("SLOT");
slotElement.setAttribute("name", "slot" + i);
paneDiv.appendChild(slotElement);
topDiv.appendChild(paneDiv);
if (i < this.children.length-1) {
const dividerDiv = this.ownerDocument.createElement("DIV");
dividerDiv.classList.add(CLASS_DIVIDER);
topDiv.appendChild(dividerDiv);
}
}
this._setSizes(paneSizes, this._orientation);
}
private _setSizes(paneSizes: PaneSizes, orientation: SplitOrientation): void {
const topDiv = this._elementById(ID_CONTAINER);
let position = 0;
for (let i=0; i<paneSizes.length(); i++) {
const kid = <HTMLElement> topDiv.children.item(i*2);
const size = paneSizes.get(i);
if (orientation === SplitOrientation.VERTICAL) {
kid.style.left = "" + position + "px";
kid.style.width = "" + size + "px";
kid.style.top = null;
kid.style.height = null;
} else {
kid.style.top = "" + position + "px";
kid.style.height = "" + size + "px";
kid.style.left = null;
kid.style.width = null;
}
position += size;
if (i < this.children.length-1) {
const divider = <HTMLElement> topDiv.children.item(i*2+1);
if (orientation === SplitOrientation.VERTICAL) {
divider.style.left = "" + position + "px";
divider.style.width = "" + DIVIDER_SIZE + "px";
divider.style.top = null;
divider.style.height = null;
} else {
divider.style.top = "" + position + "px";
divider.style.height = "" + DIVIDER_SIZE + "px";
divider.style.left = null;
divider.style.width = null;
}
position += DIVIDER_SIZE;
}
}
}
private _elementById(id: string): HTMLElement {
return DomUtils.getShadowId(this, id);
}
}
//-----------------------------------------------------------------------
//
// ###### #####
// # # ## # # ###### # # # ###### ###### ####
// # # # # ## # # # # # # #
// ###### # # # # # ##### ##### # # ##### ####
// # ###### # # # # # # # # #
// # # # # ## # # # # # # # #
// # # # # # ###### ##### # ###### ###### ####
//
//-----------------------------------------------------------------------
class PaneSizes {
private _paneSizes: number[];
private _panes: Object[];
static equalPaneSizes(totalSize: number, panes: Object[]) {
// Distribute the panes evenly.
const paneCount = panes.length;
const paneSize = (totalSize - (paneCount-1) * DIVIDER_SIZE) / paneCount;
const paneSizes: number[] = [];
for (let i=0; i<paneCount; i++) {
paneSizes.push(paneSize);
}
return new PaneSizes(paneSizes, panes);
}
constructor(paneSizeArray: number[] = null, panes: Object[] = null) {
if (paneSizeArray == null) {
this._paneSizes = [];
} else {
this._paneSizes = paneSizeArray;
}
this._panes = panes;
}
get(index: number): number {
return this._paneSizes[index];
}
length(): number {
return this._paneSizes.length;
}
adjustPaneSize(dividerIndex: number, indicatorLeft: number): PaneSizes {
let delta = indicatorLeft - this.getPaneNext(dividerIndex);
const sizeFirst = this._paneSizes[dividerIndex];
const sizeSecond = this._paneSizes[dividerIndex+1];
delta = sizeFirst+delta < MIN_PANE_SIZE ? -sizeFirst+MIN_PANE_SIZE : delta;
delta = sizeSecond-delta < MIN_PANE_SIZE ? sizeSecond-MIN_PANE_SIZE : delta;
const copy = this._paneSizes.slice();
copy[dividerIndex] += delta;
copy[dividerIndex+1] -= delta;
return new PaneSizes(copy, this._panes);
}
getPaneNext(index: number): number {
return this._paneSizes.slice(0, index+1).reduce( (accu, w) => accu+w, 0) + index * DIVIDER_SIZE;
}
updateTotalSize(newTotalSize: number): PaneSizes {
return this._resizeSizes(newTotalSize);
}
update(newPanes: Object[]): PaneSizes {
return this._updateRemovedPanes(newPanes)._updateAddedPanes(newPanes);
}
reverse(): PaneSizes {
return new PaneSizes(this._paneSizes.slice().reverse(), this._panes.slice().reverse());
}
private _resizeSizes(newTotalSize: number): PaneSizes {
const effectiveUsableSize = newTotalSize - (this._panes.length-1) * DIVIDER_SIZE;
const currentTotalSize = this._paneSizes.reduce( (accu, s) => accu+s, 0);
const distributableSpace = effectiveUsableSize - currentTotalSize;
const newSizes: number[] = [];
let usedExtraSpace = 0;
for (let i=0; i<this._paneSizes.length; i++) {
if (i !== this._paneSizes.length-1) {
const delta = Math.round(this._paneSizes[i] / currentTotalSize * distributableSpace);
usedExtraSpace += delta;
newSizes.push(this._paneSizes[i] + delta);
} else {
// We do it this way to avoid rounding errors and ensure that distribute the exact amount of space.
newSizes.push(this._paneSizes[i] + distributableSpace - usedExtraSpace);
}
}
return new PaneSizes(newSizes, this._panes);
}
private _updateRemovedPanes(newPanes: Object[]): PaneSizes {
// Handle any panes which have been removed.
let spaceAccount = 0;
const newPaneSizes: number[] = [];
const tempPanes: Object[] = [];
for (let i=0; i<this._paneSizes.length; i++) {
if (newPanes.indexOf(this._panes[i]) === -1) {
// This pane was removed.
spaceAccount += this._paneSizes[i];
spaceAccount += DIVIDER_SIZE;
} else {
// This pane still exists. Give it the spare space.
newPaneSizes.push(this._paneSizes[i] + spaceAccount);
tempPanes.push(this._panes[i]);
spaceAccount = 0;
}
}
if (newPaneSizes.length !== 0) {
newPaneSizes[newPaneSizes.length-1] += spaceAccount;
}
return new PaneSizes(newPaneSizes, tempPanes);
}
private _updateAddedPanes(newPanes: Object[]): PaneSizes {
if (this._paneSizes.length === 0) { // Special case for going from 0 panes to >0.
return PaneSizes.equalPaneSizes(1024, newPanes);
}
const tempPaneSizes = this._distributeAddedPanes(newPanes);
if (tempPaneSizes._panes.length !== newPanes.length) {
const reverseNewPanes = newPanes.slice().reverse();
return tempPaneSizes.reverse()._distributeAddedPanes(reverseNewPanes).reverse();
} else {
return tempPaneSizes;
}
}
private _distributeAddedPanes(newPanes: Object[]): PaneSizes {
const newPaneSizes: number[] = [];
const tempPanes: Object[] = [];
for (let i=0; i<newPanes.length; i++) {
const oldIndex = this._panes.indexOf(newPanes[i]);
if (oldIndex === -1) {
// New pane.
if (newPaneSizes.length === 0) {
// Let the reverse step fix this one.
} else {
const previousSize = newPaneSizes[newPaneSizes.length-1];
const half = Math.floor((previousSize - DIVIDER_SIZE) / 2); // Avoid fractional widths.
newPaneSizes[newPaneSizes.length-1] = previousSize - DIVIDER_SIZE - half;
newPaneSizes.push(half);
tempPanes.push(newPanes[i]);
}
} else {
// Old pane.
newPaneSizes.push(this._paneSizes[oldIndex]);
tempPanes.push(newPanes[i]);
}
}
return new PaneSizes(newPaneSizes, tempPanes);
}
} | the_stack |
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { AbstractClient } from "../../../common/abstract_client"
import { ClientConfig } from "../../../common/interface"
import {
AppUpdateDeviceRequest,
GetDeviceResponse,
GetDeviceDataResponse,
AppResetPasswordResponse,
DeleteRuleRequest,
ActivateRuleResponse,
UpdateRuleRequest,
DeviceSignature,
AppGetDevicesRequest,
AppGetDeviceDataResponse,
GetTopicResponse,
DeactivateRuleResponse,
IssueDeviceControlRequest,
GetDeviceStatisticsRequest,
ResetDeviceResponse,
GetDeviceLogResponse,
AddRuleRequest,
ResetDeviceRequest,
ServiceAction,
DataTemplate,
DeleteTopicRequest,
AddProductResponse,
UpdateProductResponse,
DataHistoryEntry,
AppGetDeviceResponse,
UpdateRuleResponse,
AppDeviceDetail,
GetDeviceStatisticsResponse,
UnassociateSubDeviceFromGatewayProductResponse,
Topic,
AssociateSubDeviceToGatewayProductResponse,
GetProductRequest,
AppGetTokenRequest,
GetRuleRequest,
DeleteProductRequest,
AppGetUserRequest,
GetProductsResponse,
AppGetDeviceRequest,
GetDataHistoryRequest,
AddTopicResponse,
AddProductRequest,
ProductEntry,
GetRulesResponse,
DeleteDeviceRequest,
AssociateSubDeviceToGatewayProductRequest,
GetDeviceSignaturesResponse,
RuleQuery,
AppUser,
BoolData,
PublishMsgRequest,
GetProductsRequest,
AddTopicRequest,
AppGetDeviceStatusesRequest,
DeviceLogEntry,
GetDebugLogRequest,
GetDeviceRequest,
GetDeviceDataRequest,
DeactivateRuleRequest,
GetTopicRequest,
GetDevicesResponse,
NumberData,
GetDevicesRequest,
AppGetTokenResponse,
GetProductResponse,
AppAddUserRequest,
AddRuleResponse,
AppDeleteDeviceResponse,
AppIssueDeviceControlRequest,
DeviceStatus,
DeleteProductResponse,
AppGetUserResponse,
AppUpdateUserRequest,
GetDebugLogResponse,
AppUpdateUserResponse,
Device,
GetRulesRequest,
Rule,
IssueDeviceControlResponse,
GetDataHistoryResponse,
Action,
PublishMsgResponse,
AppGetDevicesResponse,
CkafkaAction,
AddDeviceRequest,
UpdateProductRequest,
DeleteRuleResponse,
GetDeviceSignaturesRequest,
GetRuleResponse,
AppUpdateDeviceResponse,
Product,
DebugLogEntry,
GetDeviceStatusesRequest,
GetDeviceStatusesResponse,
UnassociateSubDeviceFromGatewayProductRequest,
AppDeleteDeviceRequest,
StringData,
AppGetDeviceStatusesResponse,
GetTopicsResponse,
AppGetDeviceDataRequest,
AppAddUserResponse,
DeviceEntry,
GetDeviceLogRequest,
AddDeviceResponse,
ActivateRuleRequest,
AppResetPasswordRequest,
DeleteTopicResponse,
AppDevice,
GetTopicsRequest,
DeviceStatData,
EnumData,
DeleteDeviceResponse,
AppSecureAddDeviceResponse,
AppSecureAddDeviceRequest,
AppIssueDeviceControlResponse,
TopicAction,
} from "./iot_models"
/**
* iot client
* @class
*/
export class Client extends AbstractClient {
constructor(clientConfig: ClientConfig) {
super("iot.tencentcloudapi.com", "2018-01-23", clientConfig)
}
/**
* 批量获取设备某一段时间范围的设备上报数据。该接口适用于使用高级版类型的产品
*/
async GetDataHistory(
req: GetDataHistoryRequest,
cb?: (error: string, rep: GetDataHistoryResponse) => void
): Promise<GetDataHistoryResponse> {
return this.request("GetDataHistory", req, cb)
}
/**
* 重置设备操作,将会为设备生成新的证书及清空最新数据,需谨慎操作。
*/
async ResetDevice(
req: ResetDeviceRequest,
cb?: (error: string, rep: ResetDeviceResponse) => void
): Promise<ResetDeviceResponse> {
return this.request("ResetDevice", req, cb)
}
/**
* 查询某段时间范围内产品的在线、激活设备数
*/
async GetDeviceStatistics(
req: GetDeviceStatisticsRequest,
cb?: (error: string, rep: GetDeviceStatisticsResponse) => void
): Promise<GetDeviceStatisticsResponse> {
return this.request("GetDeviceStatistics", req, cb)
}
/**
* 用户绑定设备,绑定后可以在APP端进行控制。绑定设备前需调用“获取设备绑定签名”接口
*/
async AppSecureAddDevice(
req: AppSecureAddDeviceRequest,
cb?: (error: string, rep: AppSecureAddDeviceResponse) => void
): Promise<AppSecureAddDeviceResponse> {
return this.request("AppSecureAddDevice", req, cb)
}
/**
* 提供下发控制指令到指定设备的能力,该接口适用于使用高级版类型的产品。
*/
async IssueDeviceControl(
req: IssueDeviceControlRequest,
cb?: (error: string, rep: IssueDeviceControlResponse) => void
): Promise<IssueDeviceControlResponse> {
return this.request("IssueDeviceControl", req, cb)
}
/**
* 获取设备的调试日志,用于定位问题
*/
async GetDebugLog(
req: GetDebugLogRequest,
cb?: (error: string, rep: GetDebugLogResponse) => void
): Promise<GetDebugLogResponse> {
return this.request("GetDebugLog", req, cb)
}
/**
* 禁用规则
*/
async DeactivateRule(
req: DeactivateRuleRequest,
cb?: (error: string, rep: DeactivateRuleResponse) => void
): Promise<DeactivateRuleResponse> {
return this.request("DeactivateRule", req, cb)
}
/**
* 提供分页查询某个产品Id下设备信息的能力。
*/
async GetDevices(
req: GetDevicesRequest,
cb?: (error: string, rep: GetDevicesResponse) => void
): Promise<GetDevicesResponse> {
return this.request("GetDevices", req, cb)
}
/**
* 新增Topic,用于设备或应用发布消息至该Topic或订阅该Topic的消息。
*/
async AddTopic(
req: AddTopicRequest,
cb?: (error: string, rep: AddTopicResponse) => void
): Promise<AddTopicResponse> {
return this.request("AddTopic", req, cb)
}
/**
* 获取绑定设备的上下线状态
*/
async AppGetDeviceStatuses(
req: AppGetDeviceStatusesRequest,
cb?: (error: string, rep: AppGetDeviceStatusesResponse) => void
): Promise<AppGetDeviceStatusesResponse> {
return this.request("AppGetDeviceStatuses", req, cb)
}
/**
* 获取用户在物联网套件所创建的所有产品信息。
*/
async GetProducts(
req: GetProductsRequest,
cb?: (error: string, rep: GetProductsResponse) => void
): Promise<GetProductsResponse> {
return this.request("GetProducts", req, cb)
}
/**
* 获取用户token
*/
async AppGetToken(
req: AppGetTokenRequest,
cb?: (error: string, rep: AppGetTokenResponse) => void
): Promise<AppGetTokenResponse> {
return this.request("AppGetToken", req, cb)
}
/**
* 修改用户信息
*/
async AppUpdateUser(
req: AppUpdateUserRequest,
cb?: (error: string, rep: AppUpdateUserResponse) => void
): Promise<AppUpdateUserResponse> {
return this.request("AppUpdateUser", req, cb)
}
/**
* 新增规则
*/
async AddRule(
req: AddRuleRequest,
cb?: (error: string, rep: AddRuleResponse) => void
): Promise<AddRuleResponse> {
return this.request("AddRule", req, cb)
}
/**
* 取消子设备产品与网关设备产品的关联
*/
async UnassociateSubDeviceFromGatewayProduct(
req: UnassociateSubDeviceFromGatewayProductRequest,
cb?: (error: string, rep: UnassociateSubDeviceFromGatewayProductResponse) => void
): Promise<UnassociateSubDeviceFromGatewayProductResponse> {
return this.request("UnassociateSubDeviceFromGatewayProduct", req, cb)
}
/**
* 获取设备绑定签名,用于用户绑定某个设备的应用场景
*/
async GetDeviceSignatures(
req: GetDeviceSignaturesRequest,
cb?: (error: string, rep: GetDeviceSignaturesResponse) => void
): Promise<GetDeviceSignaturesResponse> {
return this.request("GetDeviceSignatures", req, cb)
}
/**
* 删除规则
*/
async DeleteRule(
req: DeleteRuleRequest,
cb?: (error: string, rep: DeleteRuleResponse) => void
): Promise<DeleteRuleResponse> {
return this.request("DeleteRule", req, cb)
}
/**
* 本接口(AddProduct)用于创建、定义某款硬件产品。
*/
async AddProduct(
req: AddProductRequest,
cb?: (error: string, rep: AddProductResponse) => void
): Promise<AddProductResponse> {
return this.request("AddProduct", req, cb)
}
/**
* 提供在指定的产品Id下删除一个设备的能力。
*/
async DeleteDevice(
req: DeleteDeviceRequest,
cb?: (error: string, rep: DeleteDeviceResponse) => void
): Promise<DeleteDeviceResponse> {
return this.request("DeleteDevice", req, cb)
}
/**
* 提供向指定的Topic发布消息的能力,常用于向设备下发控制指令。该接口只适用于产品版本为“基础版”类型的产品,使用高级版的产品需使用“下发设备控制指令”接口
*/
async PublishMsg(
req: PublishMsgRequest,
cb?: (error: string, rep: PublishMsgResponse) => void
): Promise<PublishMsgResponse> {
return this.request("PublishMsg", req, cb)
}
/**
* 更新规则
*/
async UpdateRule(
req: UpdateRuleRequest,
cb?: (error: string, rep: UpdateRuleResponse) => void
): Promise<UpdateRuleResponse> {
return this.request("UpdateRule", req, cb)
}
/**
* 用户解除与设备的关联关系,解除后APP用户无法控制设备,获取设备数据
*/
async AppDeleteDevice(
req: AppDeleteDeviceRequest,
cb?: (error: string, rep: AppDeleteDeviceResponse) => void
): Promise<AppDeleteDeviceResponse> {
return this.request("AppDeleteDevice", req, cb)
}
/**
* 批量获取设备的当前状态,状态包括在线、离线或未激活状态。
*/
async GetDeviceStatuses(
req: GetDeviceStatusesRequest,
cb?: (error: string, rep: GetDeviceStatusesResponse) => void
): Promise<GetDeviceStatusesResponse> {
return this.request("GetDeviceStatuses", req, cb)
}
/**
* 获取转发规则列表
*/
async GetRules(
req: GetRulesRequest,
cb?: (error: string, rep: GetRulesResponse) => void
): Promise<GetRulesResponse> {
return this.request("GetRules", req, cb)
}
/**
* 删除用户指定的产品Id对应的信息。
*/
async DeleteProduct(
req: DeleteProductRequest,
cb?: (error: string, rep: DeleteProductResponse) => void
): Promise<DeleteProductResponse> {
return this.request("DeleteProduct", req, cb)
}
/**
* 获取用户信息
*/
async AppGetUser(
req: AppGetUserRequest,
cb?: (error: string, rep: AppGetUserResponse) => void
): Promise<AppGetUserResponse> {
return this.request("AppGetUser", req, cb)
}
/**
* 获取用户的绑定设备列表
*/
async AppGetDevices(
req: AppGetDevicesRequest,
cb?: (error: string, rep: AppGetDevicesResponse) => void
): Promise<AppGetDevicesResponse> {
return this.request("AppGetDevices", req, cb)
}
/**
* 为APP提供用户注册功能
*/
async AppAddUser(
req: AppAddUserRequest,
cb?: (error: string, rep: AppAddUserResponse) => void
): Promise<AppAddUserResponse> {
return this.request("AppAddUser", req, cb)
}
/**
* 提供修改产品信息及数据模板的能力。
*/
async UpdateProduct(
req: UpdateProductRequest,
cb?: (error: string, rep: UpdateProductResponse) => void
): Promise<UpdateProductResponse> {
return this.request("UpdateProduct", req, cb)
}
/**
* 用户通过APP控制设备
*/
async AppIssueDeviceControl(
req: AppIssueDeviceControlRequest,
cb?: (error: string, rep: AppIssueDeviceControlResponse) => void
): Promise<AppIssueDeviceControlResponse> {
return this.request("AppIssueDeviceControl", req, cb)
}
/**
* 获取Topic信息
*/
async GetTopic(
req: GetTopicRequest,
cb?: (error: string, rep: GetTopicResponse) => void
): Promise<GetTopicResponse> {
return this.request("GetTopic", req, cb)
}
/**
* 获取绑定设备数据,用于实时展示设备的最新数据
*/
async AppGetDeviceData(
req: AppGetDeviceDataRequest,
cb?: (error: string, rep: AppGetDeviceDataResponse) => void
): Promise<AppGetDeviceDataResponse> {
return this.request("AppGetDeviceData", req, cb)
}
/**
* 提供查询某个设备详细信息的能力。
*/
async GetDevice(
req: GetDeviceRequest,
cb?: (error: string, rep: GetDeviceResponse) => void
): Promise<GetDeviceResponse> {
return this.request("GetDevice", req, cb)
}
/**
* 获取绑定设备的基本信息与数据模板定义
*/
async AppGetDevice(
req: AppGetDeviceRequest,
cb?: (error: string, rep: AppGetDeviceResponse) => void
): Promise<AppGetDeviceResponse> {
return this.request("AppGetDevice", req, cb)
}
/**
* 获取某个设备当前上报到云端的数据,该接口适用于使用数据模板协议的产品。
*/
async GetDeviceData(
req: GetDeviceDataRequest,
cb?: (error: string, rep: GetDeviceDataResponse) => void
): Promise<GetDeviceDataResponse> {
return this.request("GetDeviceData", req, cb)
}
/**
* 获取转发规则信息
*/
async GetRule(
req: GetRuleRequest,
cb?: (error: string, rep: GetRuleResponse) => void
): Promise<GetRuleResponse> {
return this.request("GetRule", req, cb)
}
/**
* 批量获取设备与云端的详细通信日志,该接口适用于使用高级版类型的产品。
*/
async GetDeviceLog(
req: GetDeviceLogRequest,
cb?: (error: string, rep: GetDeviceLogResponse) => void
): Promise<GetDeviceLogResponse> {
return this.request("GetDeviceLog", req, cb)
}
/**
* 获取Topic列表
*/
async GetTopics(
req: GetTopicsRequest,
cb?: (error: string, rep: GetTopicsResponse) => void
): Promise<GetTopicsResponse> {
return this.request("GetTopics", req, cb)
}
/**
* 提供在指定的产品Id下创建一个设备的能力,生成设备名称与设备秘钥。
*/
async AddDevice(
req: AddDeviceRequest,
cb?: (error: string, rep: AddDeviceResponse) => void
): Promise<AddDeviceResponse> {
return this.request("AddDevice", req, cb)
}
/**
* 获取产品定义的详细信息,包括产品名称、产品描述,鉴权模式等信息。
*/
async GetProduct(
req: GetProductRequest,
cb?: (error: string, rep: GetProductResponse) => void
): Promise<GetProductResponse> {
return this.request("GetProduct", req, cb)
}
/**
* 重置APP用户密码
*/
async AppResetPassword(
req: AppResetPasswordRequest,
cb?: (error: string, rep: AppResetPasswordResponse) => void
): Promise<AppResetPasswordResponse> {
return this.request("AppResetPassword", req, cb)
}
/**
* 启用规则
*/
async ActivateRule(
req: ActivateRuleRequest,
cb?: (error: string, rep: ActivateRuleResponse) => void
): Promise<ActivateRuleResponse> {
return this.request("ActivateRule", req, cb)
}
/**
* 关联子设备产品和网关产品
*/
async AssociateSubDeviceToGatewayProduct(
req: AssociateSubDeviceToGatewayProductRequest,
cb?: (error: string, rep: AssociateSubDeviceToGatewayProductResponse) => void
): Promise<AssociateSubDeviceToGatewayProductResponse> {
return this.request("AssociateSubDeviceToGatewayProduct", req, cb)
}
/**
* 删除Topic
*/
async DeleteTopic(
req: DeleteTopicRequest,
cb?: (error: string, rep: DeleteTopicResponse) => void
): Promise<DeleteTopicResponse> {
return this.request("DeleteTopic", req, cb)
}
/**
* 修改设备别名,便于用户个性化定义设备的名称
*/
async AppUpdateDevice(
req: AppUpdateDeviceRequest,
cb?: (error: string, rep: AppUpdateDeviceResponse) => void
): Promise<AppUpdateDeviceResponse> {
return this.request("AppUpdateDevice", req, cb)
}
} | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type ItemInfo_Test_QueryVariables = {};
export type ItemInfo_Test_QueryResponse = {
readonly me: {
readonly conversation: {
readonly items: ReadonlyArray<{
readonly item: {
readonly " $fragmentRefs": FragmentRefs<"ItemInfo_item">;
} | null;
} | null> | null;
} | null;
} | null;
};
export type ItemInfo_Test_Query = {
readonly response: ItemInfo_Test_QueryResponse;
readonly variables: ItemInfo_Test_QueryVariables;
};
/*
query ItemInfo_Test_Query {
me {
conversation(id: "test-id") {
items {
item {
__typename
...ItemInfo_item
... on Node {
__isNode: __typename
id
}
}
}
id
}
id
}
}
fragment ItemArtwork_artwork on Artwork {
href
image {
thumbnailUrl: url(version: "small")
}
title
artistNames
date
saleMessage
partner {
name
id
}
}
fragment ItemInfo_item on ConversationItemType {
__isConversationItemType: __typename
...ItemArtwork_artwork
...ItemShow_show
__typename
}
fragment ItemShow_show on Show {
name
href
exhibitionPeriod(format: SHORT)
partner {
__typename
... on Partner {
name
}
... on Node {
__isNode: __typename
id
}
... on ExternalPartner {
id
}
}
image: coverImage {
thumbnailUrl: url(version: "small")
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = [
{
"kind": "Literal",
"name": "id",
"value": "test-id"
}
],
v1 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
v2 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "href",
"storageKey": null
},
v3 = [
{
"alias": "thumbnailUrl",
"args": [
{
"kind": "Literal",
"name": "version",
"value": "small"
}
],
"kind": "ScalarField",
"name": "url",
"storageKey": "url(version:\"small\")"
}
],
v4 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
v5 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v6 = [
(v5/*: any*/)
],
v7 = {
"kind": "InlineFragment",
"selections": (v6/*: any*/),
"type": "Node",
"abstractKey": "__isNode"
};
return {
"fragment": {
"argumentDefinitions": [],
"kind": "Fragment",
"metadata": null,
"name": "ItemInfo_Test_Query",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Me",
"kind": "LinkedField",
"name": "me",
"plural": false,
"selections": [
{
"alias": null,
"args": (v0/*: any*/),
"concreteType": "Conversation",
"kind": "LinkedField",
"name": "conversation",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "ConversationItem",
"kind": "LinkedField",
"name": "items",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "item",
"plural": false,
"selections": [
{
"args": null,
"kind": "FragmentSpread",
"name": "ItemInfo_item"
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": "conversation(id:\"test-id\")"
}
],
"storageKey": null
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": [],
"kind": "Operation",
"name": "ItemInfo_Test_Query",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "Me",
"kind": "LinkedField",
"name": "me",
"plural": false,
"selections": [
{
"alias": null,
"args": (v0/*: any*/),
"concreteType": "Conversation",
"kind": "LinkedField",
"name": "conversation",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "ConversationItem",
"kind": "LinkedField",
"name": "items",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "item",
"plural": false,
"selections": [
(v1/*: any*/),
{
"kind": "TypeDiscriminator",
"abstractKey": "__isConversationItemType"
},
{
"kind": "InlineFragment",
"selections": [
(v2/*: any*/),
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "image",
"plural": false,
"selections": (v3/*: any*/),
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "title",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "artistNames",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "date",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "saleMessage",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Partner",
"kind": "LinkedField",
"name": "partner",
"plural": false,
"selections": [
(v4/*: any*/),
(v5/*: any*/)
],
"storageKey": null
}
],
"type": "Artwork",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": [
(v4/*: any*/),
(v2/*: any*/),
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "format",
"value": "SHORT"
}
],
"kind": "ScalarField",
"name": "exhibitionPeriod",
"storageKey": "exhibitionPeriod(format:\"SHORT\")"
},
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "partner",
"plural": false,
"selections": [
(v1/*: any*/),
{
"kind": "InlineFragment",
"selections": [
(v4/*: any*/)
],
"type": "Partner",
"abstractKey": null
},
(v7/*: any*/),
{
"kind": "InlineFragment",
"selections": (v6/*: any*/),
"type": "ExternalPartner",
"abstractKey": null
}
],
"storageKey": null
},
{
"alias": "image",
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "coverImage",
"plural": false,
"selections": (v3/*: any*/),
"storageKey": null
}
],
"type": "Show",
"abstractKey": null
},
(v7/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
},
(v5/*: any*/)
],
"storageKey": "conversation(id:\"test-id\")"
},
(v5/*: any*/)
],
"storageKey": null
}
]
},
"params": {
"id": "8ac919e0f948ec183571145adf774c0b",
"metadata": {},
"name": "ItemInfo_Test_Query",
"operationKind": "query",
"text": null
}
};
})();
(node as any).hash = '6c9dc4172748f2d49ba7a97deb6a92a0';
export default node; | the_stack |
import { Component, OnInit } from '@angular/core';
import { FormArray, Validators } from '@angular/forms';
import { ClrLoadingState } from "@clr/angular";
// Third party imports
import { debounceTime, distinctUntilChanged, finalize, takeUntil } from 'rxjs/operators';
import { IpFamilyEnum } from 'src/app/shared/constants/app.constants';
import { AviCloud } from "src/app/swagger/models/avi-cloud.model";
import { AviServiceEngineGroup } from "src/app/swagger/models/avi-service-engine-group.model";
import AppServices from '../../../../../../../shared/service/appServices';
// App imports
import { APIClient } from "../../../../../../../swagger";
import { StepMapping } from '../../../field-mapping/FieldMapping';
import { StepFormDirective } from "../../../step-form/step-form";
import { ValidationService } from "../../../validation/validation.service";
import { TKGLabelsConfig } from '../../widgets/tkg-labels/interfaces/tkg-labels.interface';
import { AviVipNetwork } from './../../../../../../../swagger/models/avi-vip-network.model';
import { LoadBalancerField, LoadBalancerStepMapping } from './load-balancer-step.fieldmapping';
const SupervisedFields = [
LoadBalancerField.CONTROLLER_HOST,
LoadBalancerField.USERNAME,
LoadBalancerField.PASSWORD,
LoadBalancerField.CONTROLLER_CERT
];
@Component({
selector: 'app-load-balancer-step',
templateUrl: './load-balancer-step.component.html',
styleUrls: ['./load-balancer-step.component.scss']
})
export class SharedLoadBalancerStepComponent extends StepFormDirective implements OnInit {
loadingState: ClrLoadingState = ClrLoadingState.DEFAULT;
connected: boolean = false;
clouds: Array<AviCloud>;
selectedCloud: AviCloud;
selectedCloudName: string;
serviceEngineGroups: Array<AviServiceEngineGroup>;
serviceEngineGroupsFiltered: Array<AviServiceEngineGroup>;
vipNetworks: Array<AviVipNetwork> = [];
selectedNetworkName: string;
selectedManagementClusterNetworkName: string;
loadBalancerLabel = 'Load Balancer Settings';
tkgLabelsConfig: TKGLabelsConfig;
private stepMapping: StepMapping;
constructor(private validationService: ValidationService,
private apiClient: APIClient) {
super();
}
/**
* This is to make sense that the list returned is always up to date.
*/
get vipNetworksPerCloud() {
if (this.vipNetworks && this.vipNetworks.length > 0 && this.selectedCloud) {
return this.vipNetworks.filter(net => net.cloud === this.selectedCloud.uuid);
}
return [];
}
/**
* This is to make sense that the list returned is always up to date.
*/
get subnetsPerNetwork() {
return this.getSubnets(this.selectedNetworkName);
}
/**
* This is to make sense that the list returned is always up to date.
*/
get subnetsPerManagementNetwork() {
return this.getSubnets(this.selectedManagementClusterNetworkName);
}
ngOnInit() {
super.ngOnInit();
AppServices.userDataFormService.buildForm(this.formGroup, this.wizardName, this.formName, this.supplyStepMapping());
this.htmlFieldLabels = AppServices.fieldMapUtilities.getFieldLabelMap(this.supplyStepMapping());
this.storeDefaultLabels(this.supplyStepMapping());
this.registerDefaultFileImportedHandler(this.eventFileImported, this.supplyStepMapping());
this.registerDefaultFileImportErrorHandler(this.eventFileImportError);
this.customizeForm();
this.tkgLabelsConfig = {
label: {
title: this.htmlFieldLabels['clusterLabels'],
tooltipText: `By default, all clusters will have NSX Advanced Load Balancer enabled. Here you may
optionally specify cluster labels to identify a subset of clusters that should have
NSX Advanced Load Balancer enabled. Note: Ensure that these labels are present on
individual clusters that should be enabled with NSX Advanced Load Balancer.`,
helperText: `By default, all clusters will have NSX Advanced Load Balancer enabled. Here you may optionally
specify cluster labels to identify a subset of clusters that should have NSX Advanced Load Balancer
enabled.`
},
forms: {
parent: this.formGroup,
control: this.formGroup.get('clusterLabels') as FormArray
},
fields: {
clusterTypeDescriptor: 'Workload',
fieldMapping: LoadBalancerStepMapping.fieldMappings.find((m) => m.name === LoadBalancerField.CLUSTER_LABELS)
}
};
}
/**
* @method connectLB
* helper method to make connection to AVI LB controller, call getClouds and
* getSvcEngineGroups methods if AVI LB controller connection successful
*/
connectLB() {
this.loadingState = ClrLoadingState.LOADING;
this.apiClient.verifyAccount({
credentials: {
username: this.formGroup.controls[LoadBalancerField.USERNAME].value,
password: this.formGroup.controls[LoadBalancerField.PASSWORD].value,
host: this.formGroup.controls[LoadBalancerField.CONTROLLER_HOST].value,
tenant: this.formGroup.controls[LoadBalancerField.USERNAME].value,
CAData: this.formGroup.controls[LoadBalancerField.CONTROLLER_CERT].value
}
})
.pipe(
finalize(() => this.loadingState = ClrLoadingState.DEFAULT),
takeUntil(this.unsubscribe))
.subscribe(
((res) => {
this.errorNotification = '';
this.connected = true;
this.getClouds();
this.getServiceEngineGroups();
this.getVipNetworks();
// If connection successful, toggle validators ON
this.toggleValidators(true);
}),
((err) => {
const error = err.error.message || err.message || JSON.stringify(err);
if (error.indexOf('Invalid credentials') >= 0) {
this.errorNotification = `Invalid credentials: check your username and password`;
} else if (error.indexOf('Rest request error, returning to caller') >= 0) {
this.errorNotification = `Invalid Controller Certificate Authority: check the validity of the certificate`;
} else {
this.errorNotification = `Failed to connect to the specified Avi load balancer controller. ${error}`;
}
})
);
}
/**
* @method getClouds
* helper method calls API to get list of clouds
*/
getClouds() {
this.apiClient.getAviClouds()
.pipe(takeUntil(this.unsubscribe))
.subscribe(
((res) => {
this.errorNotification = '';
this.clouds = res;
}),
((err) => {
const error = err.error.message || err.message || JSON.stringify(err);
this.errorNotification =
`Failed to retrieve Avi load balancer clouds list. ${error}`;
})
);
}
/**
* @method getServiceEngineGroups
* helper method calls API to get list of service engine groups
*/
getServiceEngineGroups() {
this.apiClient.getAviServiceEngineGroups()
.pipe(takeUntil(this.unsubscribe))
.subscribe(
((res) => {
this.errorNotification = '';
this.serviceEngineGroups = res;
// refreshes service engine group list which may not have been loaded at time of cloud selection
this.onSelectCloud(this.selectedCloudName);
}),
((err) => {
const error = err.error.message || err.message || JSON.stringify(err);
this.errorNotification =
`Failed to retrieve Avi load balancer service engine groups list. ${error}`;
})
);
}
/**
* @method getServiceEngineGroups
* helper method calls API to get list of service engine groups
*/
getVipNetworks() {
this.apiClient.getAviVipNetworks()
.pipe(takeUntil(this.unsubscribe))
.subscribe(
((res) => {
this.errorNotification = '';
this.vipNetworks = res;
}),
((err) => {
const error = err.error.message || err.message || JSON.stringify(err);
this.errorNotification =
`Failed to retrieve Avi VIP networks. ${error}`;
})
);
}
/**
* @method onSelectCloud
* @param cloudName - name of selected cloud
* helper method sets selected cloud object based on cloud 'name' returned from dropdown; then
* filters list of service engine groups where the cloud uuid matches in 'location'
*/
onSelectCloud(cloudName: string) {
this.serviceEngineGroupsFiltered = [];
if (cloudName && this.clouds) {
this.selectedCloud = this.clouds.find((cloud: AviCloud) => {
return cloud.name === cloudName;
});
if (this.selectedCloud) {
this.serviceEngineGroupsFiltered = this.serviceEngineGroups.filter((group: AviServiceEngineGroup) => {
return group.location.includes(this.selectedCloud.uuid);
});
}
}
}
/**
* Return all the configured subnets for the selected vip network.
*/
onSelectVipNetwork(networkName: string): void {
this.selectedNetworkName = networkName;
if (!this.formGroup.get(LoadBalancerField.MANAGEMENT_CLUSTER_NETWORK_NAME).value) {
}
this.formGroup.get(LoadBalancerField.MANAGEMENT_CLUSTER_NETWORK_NAME).setValue(networkName)
}
onSelectVipCIDR(cidr: string): void {
if (!this.formGroup.get(LoadBalancerField.MANAGEMENT_CLUSTER_NETWORK_CIDR).value) {
this.formGroup.get(LoadBalancerField.MANAGEMENT_CLUSTER_NETWORK_CIDR).setValue(cidr);
}
}
onSelectManagementNetwork(networkName: string): void {
this.selectedManagementClusterNetworkName = networkName;
}
/**
* @method toggleValidators
* @param validate - boolean if true activates all fields and sets their validators; if false
* disarms fields and clears validators
*/
toggleValidators(validate: boolean) {
if (validate === true) {
this.resurrectField(LoadBalancerField.CLOUD_NAME, [Validators.required],
this.getStoredValue(LoadBalancerField.CLOUD_NAME, this.supplyStepMapping(), ''));
this.resurrectField(LoadBalancerField.SERVICE_ENGINE_GROUP_NAME, [Validators.required],
this.getStoredValue(LoadBalancerField.SERVICE_ENGINE_GROUP_NAME, this.supplyStepMapping(), ''));
if (!this.modeClusterStandalone) {
this.resurrectField(LoadBalancerField.NETWORK_NAME, [Validators.required],
this.getStoredValue(LoadBalancerField.NETWORK_NAME, this.supplyStepMapping(), ''));
this.resurrectField(LoadBalancerField.NETWORK_CIDR, [
Validators.required,
this.validationService.noWhitespaceOnEnds(),
this.ipFamily === IpFamilyEnum.IPv4 ?
this.validationService.isValidIpNetworkSegment() : this.validationService.isValidIpv6NetworkSegment()
], this.getStoredValue(LoadBalancerField.NETWORK_CIDR, this.supplyStepMapping(), ''));
}
} else {
this.disarmField(LoadBalancerField.CLOUD_NAME, true);
this.disarmField(LoadBalancerField.SERVICE_ENGINE_GROUP_NAME, true);
if (!this.modeClusterStandalone) {
this.disarmField(LoadBalancerField.NETWORK_NAME, true);
this.disarmField(LoadBalancerField.NETWORK_CIDR, true);
}
}
}
/**
* @method getDisabled
* helper method to get if connect btn should be disabled
*/
getDisabled(): boolean {
return (
SupervisedFields.some(f => !this.formGroup.get(f).value) ||
SupervisedFields.some(f => !this.formGroup.get(f).valid)
)
}
getSubnets(networkName: string): any[] {
if (!this.isEmptyArray(this.vipNetworksPerCloud) && networkName) {
const temp = this.vipNetworksPerCloud
.find(net => net.name === networkName);
if (temp && !this.isEmptyArray(temp.configedSubnets)) {
return temp.configedSubnets
.filter(subnet => subnet.family === "V4"); // Only V4 are supported in Calgary 1.
}
}
return [];
}
protected customizeForm() {
SupervisedFields.forEach(field => {
this.formGroup.get(field).valueChanges
.pipe(
debounceTime(500),
distinctUntilChanged((prev, curr) => JSON.stringify(prev) === JSON.stringify(curr)),
takeUntil(this.unsubscribe)
)
.subscribe(() => {
if (this.connected) {
this.connected = false;
this.disarmField(LoadBalancerField.CLOUD_NAME, true);
this.clouds = [];
this.disarmField(LoadBalancerField.SERVICE_ENGINE_GROUP_NAME, true);
this.serviceEngineGroups = [];
this.disarmField(LoadBalancerField.NETWORK_CIDR, true);
this.disarmField(LoadBalancerField.MANAGEMENT_CLUSTER_NETWORK_CIDR, true);
// If connection cleared, toggle validators OFF
this.toggleValidators(false);
}
});
});
this.formGroup.get(LoadBalancerField.CLOUD_NAME).valueChanges.pipe(
distinctUntilChanged((prev, curr) => JSON.stringify(prev) === JSON.stringify(curr)),
takeUntil(this.unsubscribe)
).subscribe((cloud) => {
this.selectedCloudName = cloud;
this.onSelectCloud(this.selectedCloudName);
});
this.registerOnValueChange("networkName", this.onSelectVipNetwork.bind(this));
this.registerOnValueChange("networkCIDR", this.onSelectVipCIDR.bind(this));
this.registerOnValueChange(LoadBalancerField.MANAGEMENT_CLUSTER_NETWORK_NAME, this.onSelectManagementNetwork.bind(this));
this.registerOnIpFamilyChange(LoadBalancerField.NETWORK_CIDR, [], []);
this.registerOnIpFamilyChange(LoadBalancerField.MANAGEMENT_CLUSTER_NETWORK_CIDR, [
this.validationService.isValidIpNetworkSegment()], [
this.validationService.isValidIpv6NetworkSegment()
]);
}
protected storeUserData() {
this.storeUserDataFromMapping(this.supplyStepMapping());
this.storeDefaultDisplayOrder(this.supplyStepMapping());
}
private supplyStepMapping(): StepMapping {
if (!this.stepMapping) {
this.stepMapping = this.createStepMapping();
}
return this.stepMapping;
}
private createStepMapping(): StepMapping {
const result = LoadBalancerStepMapping;
const managementClusterNetworkNameMapping = AppServices.fieldMapUtilities.getFieldMapping('managementClusterNetworkName', result);
const managementClusterNetworkCidrMapping = AppServices.fieldMapUtilities.getFieldMapping('managementClusterNetworkCIDR', result);
if (this.modeClusterStandalone) {
managementClusterNetworkNameMapping.label = 'STANDALONE CLUSTER VIP NETWORK NAME';
managementClusterNetworkCidrMapping.label = 'STANDALONE CLUSTER VIP NETWORK CIDR';
}
return result;
}
} | the_stack |
import * as errors from "./errors";
import {ConnectConfig} from "./con_utils";
import {parseConnectArguments, NormalizedConnectConfig} from "./con_utils";
import {LifoQueue} from "./queues";
import {ConnectionImpl, InnerConnection} from "./client";
import {StandaloneConnection} from "./client";
import {Options, RetryOptions, TransactionOptions} from "./options";
import {CodecsRegistry} from "./codecs/registry";
import {
ALLOW_MODIFICATIONS,
INNER,
OPTIONS,
QueryArgs,
Connection,
Pool,
IPoolStats,
} from "./ifaces";
import {Transaction} from "./transaction";
const DETACH = Symbol("detach");
const DETACHED = Symbol("detached");
export const HOLDER = Symbol("holder");
export class Deferred<T> {
private _promise: Promise<T | undefined>;
private _resolve?: (value?: T | PromiseLike<T> | undefined) => void;
private _reject?: (reason?: any) => void;
private _result: T | PromiseLike<T> | undefined;
private _done: boolean;
get promise(): Promise<T | undefined> {
return this._promise;
}
get done(): boolean {
return this._done;
}
get result(): T | PromiseLike<T> | undefined {
if (!this._done) {
throw new Error("The deferred is not resolved.");
}
return this._result;
}
async setResult(value?: T | PromiseLike<T> | undefined): Promise<void> {
while (!this._resolve) {
await new Promise<void>((resolve) => process.nextTick(resolve));
}
this._resolve(value);
}
async setFailed(reason?: any): Promise<void> {
while (!this._reject) {
await new Promise<void>((resolve) => process.nextTick(resolve));
}
this._reject(reason);
}
constructor() {
this._done = false;
this._reject = undefined;
this._resolve = undefined;
this._promise = new Promise((resolve, reject) => {
this._reject = reject;
this._resolve = (value?: T | PromiseLike<T> | undefined) => {
this._done = true;
this._result = value;
resolve(value);
};
});
}
}
class PoolConnectionHolder {
private _pool: PoolImpl;
private _connection: PoolConnection | null;
private _generation: number | null;
private _inUse: Deferred<void> | null;
constructor(pool: PoolImpl) {
this._pool = pool;
this._connection = null;
this._inUse = null;
this._generation = null;
}
get connection(): Connection | null {
return this._connection;
}
get pool(): PoolImpl {
return this._pool;
}
terminate(): void {
if (this._connection !== null) {
this._connection.close();
}
}
async connect(): Promise<void> {
if (this._connection !== null) {
throw new errors.ClientError(
"PoolConnectionHolder.connect() called while another " +
"connection already exists"
);
}
this._connection = await this._pool.getNewConnection();
this._connection[INNER][HOLDER] = this;
this._generation = this._pool.generation;
}
async acquire(options: Options): Promise<PoolConnection> {
if (this._connection === null || this._connection.isClosed()) {
this._connection = null;
await this.connect();
} else if (this._generation !== this._pool.generation) {
// Connections have been expired, re-connect the holder.
// Perform closing in a concurrent task, hence no await:
this._connection.close();
this._connection = null;
await this.connect();
}
this._connection![OPTIONS] = options;
this._inUse = new Deferred<void>();
return this._connection!;
}
async release(): Promise<void> {
if (this._inUse === null) {
throw new errors.ClientError(
"PoolConnectionHolder.release() called on " +
"a free connection holder"
);
}
if (this._connection?.isClosed()) {
// When closing, pool connections perform the necessary
// cleanup, so we don't have to do anything else here.
return;
}
if (this._generation !== this._pool.generation) {
// The connection has expired because it belongs to
// an older generation (Pool.expire_connections() has
// been called).
await this._connection?.close();
return;
}
// Free this connection holder and invalidate the
// connection proxy.
await this._release();
}
/** @internal */
async _waitUntilReleased(): Promise<void> {
if (this._inUse === null) {
return;
}
await this._inUse.promise;
}
async close(): Promise<void> {
if (this._connection !== null) {
// AsyncIOConnection.aclose() will call releaseOnClose() to
// finish holder cleanup.
await this._connection.close();
}
}
/** @internal */
async _releaseOnClose(): Promise<void> {
await this._release();
this._connection = null;
}
private async _release(): Promise<void> {
// Release this connection holder.
if (this._inUse === null) {
// The holder is not checked out.
return;
}
if (!this._inUse.done) {
await this._inUse.setResult();
}
this._inUse = null;
this._connection = this._connection![DETACH]();
// Put ourselves back to the pool queue.
this._pool.enqueue(this);
}
}
export class PoolInnerConnection extends InnerConnection {
private [DETACHED]: boolean;
private [HOLDER]: PoolConnectionHolder | null;
constructor(config: NormalizedConnectConfig, registry: CodecsRegistry) {
super(config, registry);
this[DETACHED] = false;
}
async reconnect(singleAttempt: boolean = false): Promise<ConnectionImpl> {
if (this[DETACHED]) {
throw new errors.InterfaceError(
"Connection has been released to a pool"
);
}
return await super.reconnect(singleAttempt);
}
detach(): PoolInnerConnection {
const impl = this.connection;
this.connection = undefined;
const result = new PoolInnerConnection(this.config, this.registry);
result.connection = impl;
return result;
}
}
export class PoolConnection extends StandaloneConnection {
declare [INNER]: PoolInnerConnection;
protected initInner(
config: NormalizedConnectConfig,
registry: CodecsRegistry
): void {
this[INNER] = new PoolInnerConnection(config, registry);
}
protected cleanup(): void {
const holder = this[INNER][HOLDER];
if (holder) {
holder._releaseOnClose();
}
}
[DETACH](): PoolConnection | null {
const result = this.shallowClone();
const inner = this[INNER];
const holder = inner[HOLDER];
const detached = inner[DETACHED];
inner[HOLDER] = null;
inner[DETACHED] = true;
result[INNER] = inner.detach();
result[INNER][HOLDER] = holder;
result[INNER][DETACHED] = detached;
return result;
}
}
const DefaultMinPoolSize = 0;
const DefaultMaxPoolSize = 100;
export interface PoolOptions {
minSize?: number;
maxSize?: number;
}
export interface LegacyPoolOptions extends PoolOptions {
connectOptions?: ConnectConfig | null;
}
export class PoolStats implements IPoolStats {
private _queueLength: number;
private _openConnections: number;
constructor(queueLength: number, openConnections: number) {
this._queueLength = queueLength;
this._openConnections = openConnections;
}
/**
* Get the length of the queue used to obtain a DB connection.
* The queue length indicates the count of pending operations, awaiting for
* an available connection. If your application is receiving more
* requests than the server can handle, this can be the bottleneck.
*/
get queueLength(): number {
return this._queueLength;
}
/**
* Get the length of currently open connections of the connection pool.
*/
get openConnections(): number {
return this._openConnections;
}
}
/**
* A connection pool.
*
* Connection pool can be used to manage a set of connections to the database.
* Connections are first acquired from the pool, then used, and then released
* back to the pool. Once a connection is released, it's reset to close all
* open cursors and other resources *except* prepared statements.
* Pools are created by calling :func:`~edgedb.pool.create`.
*/
export class PoolShell implements Pool {
[ALLOW_MODIFICATIONS]: never;
private impl: PoolImpl;
private options: Options;
protected constructor(
dsn?: string,
connectOptions: ConnectConfig = {},
poolOptions: PoolOptions = {}
) {
this.impl = new PoolImpl(dsn, connectOptions, poolOptions);
this.options = Options.defaults();
}
protected shallowClone(): this {
const result = Object.create(this.constructor.prototype);
result.impl = this.impl;
result.options = this.options;
return result;
}
withTransactionOptions(opt: TransactionOptions): this {
const result = this.shallowClone();
result.options = this.options.withTransactionOptions(opt);
return result;
}
withRetryOptions(opt: RetryOptions): this {
const result = this.shallowClone();
result.options = this.options.withRetryOptions(opt);
return result;
}
/**
* Get information about the current state of the pool.
*/
getStats(): PoolStats {
return this.impl.getStats();
}
/** @internal */
static async create(
dsn?: string,
connectOptions?: ConnectConfig | null,
poolOptions?: PoolOptions | null
): Promise<PoolShell> {
const pool = new PoolShell(dsn, connectOptions || {}, poolOptions || {});
await pool.impl.initialize();
return pool;
}
async rawTransaction<T>(
action: (transaction: Transaction) => Promise<T>
): Promise<T> {
const conn = await this.impl.acquire(this.options);
try {
return await conn.rawTransaction(action);
} finally {
await this.impl.release(conn);
}
}
async retryingTransaction<T>(
action: (transaction: Transaction) => Promise<T>
): Promise<T> {
const conn = await this.impl.acquire(this.options);
try {
return await conn.retryingTransaction(action);
} finally {
await this.impl.release(conn);
}
}
async execute(query: string): Promise<void> {
const conn = await this.impl.acquire(this.options);
try {
return await conn.execute(query);
} finally {
await this.impl.release(conn);
}
}
async query<T = unknown>(query: string, args?: QueryArgs): Promise<T[]> {
const conn = await this.impl.acquire(this.options);
try {
return await conn.query(query, args);
} finally {
await this.impl.release(conn);
}
}
async queryJSON(query: string, args?: QueryArgs): Promise<string> {
const conn = await this.impl.acquire(this.options);
try {
return await conn.queryJSON(query, args);
} finally {
await this.impl.release(conn);
}
}
async querySingle<T = unknown>(query: string, args?: QueryArgs): Promise<T> {
const conn = await this.impl.acquire(this.options);
try {
return await conn.querySingle(query, args);
} finally {
await this.impl.release(conn);
}
}
async querySingleJSON(query: string, args?: QueryArgs): Promise<string> {
const conn = await this.impl.acquire(this.options);
try {
return await conn.querySingleJSON(query, args);
} finally {
await this.impl.release(conn);
}
}
/**
* Attempt to gracefully close all connections in the pool.
*
* Waits until all pool connections are released, closes them and
* shuts down the pool. If any error occurs
* in ``close()``, the pool will terminate by calling ``terminate()``.
*/
async close(): Promise<void> {
await this.impl.close();
}
isClosed(): boolean {
return this.impl.isClosed();
}
/**
* Terminate all connections in the pool. If the pool is already closed,
* it returns without doing anything.
*/
terminate(): void {
this.impl.terminate();
}
}
class PoolImpl {
private _closed: boolean;
private _closing: boolean;
private _queue: LifoQueue<PoolConnectionHolder>;
private _holders: PoolConnectionHolder[];
private _initialized: boolean;
private _initializing: boolean;
private _minSize: number;
private _maxSize: number;
private _generation: number;
private _connectOptions: NormalizedConnectConfig;
private _codecsRegistry: CodecsRegistry;
constructor(
dsn?: string,
connectOptions: ConnectConfig = {},
poolOptions: PoolOptions = {}
) {
const minSize =
poolOptions.minSize === undefined
? DefaultMinPoolSize
: poolOptions.minSize;
const maxSize =
poolOptions.maxSize === undefined
? DefaultMaxPoolSize
: poolOptions.maxSize;
this.validateSizeParameters(minSize, maxSize);
this._codecsRegistry = new CodecsRegistry();
this._queue = new LifoQueue<PoolConnectionHolder>();
this._holders = [];
this._initialized = false;
this._initializing = false;
this._minSize = minSize;
this._maxSize = maxSize;
this._closing = false;
this._closed = false;
this._generation = 0;
this._connectOptions = parseConnectArguments({...connectOptions, dsn});
}
/**
* Get information about the current state of the pool.
*/
getStats(): PoolStats {
return new PoolStats(
this._queue.pending,
this._holders.filter(
(holder) =>
holder.connection !== null && holder.connection.isClosed() === false
).length
);
}
/** @internal */
get generation(): number {
return this._generation;
}
/** @internal */
enqueue(holder: PoolConnectionHolder): void {
this._queue.push(holder);
}
private validateSizeParameters(minSize: number, maxSize: number): void {
if (maxSize <= 0) {
throw new errors.InterfaceError(
"maxSize is expected to be greater than zero"
);
}
if (minSize < 0) {
throw new errors.InterfaceError(
"minSize is expected to be greater or equal to zero"
);
}
if (minSize > maxSize) {
throw new errors.InterfaceError("minSize is greater than maxSize");
}
}
async initialize(): Promise<void> {
// Ref: asyncio_pool.py _async__init__
if (this._initialized) {
return;
}
if (this._initializing) {
throw new errors.InterfaceError("The pool is already being initialized");
}
if (this._closed) {
throw new errors.InterfaceError("The pool is closed");
}
this._initializing = true;
for (let i = 0; i < this._maxSize; i++) {
const connectionHolder = new PoolConnectionHolder(this);
this._holders.push(connectionHolder);
this._queue.push(connectionHolder);
}
try {
await this._initializeHolders();
} finally {
this._initialized = true;
this._initializing = false;
}
}
private async _initializeHolders(): Promise<void> {
if (!this._minSize) {
return;
}
// Since we use a LIFO queue, the first items in the queue will be
// the last ones in `self._holders`. We want to pre-connect the
// first few connections in the queue, therefore we want to walk
// `self._holders` in reverse.
const tasks: Array<Promise<void>> = [];
let count = 0;
for (let i = this._holders.length - 1; i >= 0; i--) {
if (count >= this._minSize) {
break;
}
const connectionHolder = this._holders[i];
tasks.push(connectionHolder.connect());
count += 1;
}
await Promise.all(tasks);
}
/** @internal */
async getNewConnection(): Promise<PoolConnection> {
const connection = await PoolConnection.connect(
this._connectOptions,
this._codecsRegistry
);
return connection;
}
private _checkInit(): void {
if (!this._initialized) {
if (this._initializing) {
throw new errors.InterfaceError(
"The pool is being initialized, but not yet ready: " +
"likely there is a race between creating a pool and " +
"using it"
);
}
throw new errors.InterfaceError(
"The pool is not initialized. Call the ``initialize`` method " +
"before using it."
);
}
if (this._closed) {
throw new errors.InterfaceError("The pool is closed");
}
}
async acquire(options: Options): Promise<PoolConnection> {
if (this._closing) {
throw new errors.InterfaceError("The pool is closing");
}
if (this._closed) {
throw new errors.InterfaceError("The pool is closed");
}
this._checkInit();
return await this._acquireConnection(options);
}
private async _acquireConnection(options: Options): Promise<PoolConnection> {
// Ref: asyncio_pool _acquire
// gets the last item from the queue,
// when we are done with the connection,
// the connection holder is put back into the queue with push()
const connectionHolder = await this._queue.get();
try {
return await connectionHolder.acquire(options);
} catch (error) {
// put back the holder on the queue
this._queue.push(connectionHolder);
throw error;
}
}
/**
* Release a database connection back to the pool.
*/
async release(connection: Connection): Promise<void> {
if (!(connection instanceof PoolConnection)) {
throw new Error("a connection obtained via pool.acquire() was expected");
}
const holder = connection[INNER][HOLDER];
if (holder == null) {
// Already released, do nothing
return;
}
if (holder.pool !== this) {
throw new errors.InterfaceError(
"The connection proxy does not belong to this pool."
);
}
this._checkInit();
// Let the connection do its internal housekeeping when it's released.
return await holder.release();
}
/**
* Attempt to gracefully close all connections in the pool.
*
* Waits until all pool connections are released, closes them and
* shuts down the pool. If any error occurs
* in ``close()``, the pool will terminate by calling ``terminate()``.
*/
async close(): Promise<void> {
// Ref. asyncio_pool aclose
if (this._closed) {
return;
}
this._checkInit();
this._closing = true;
const warningTimeoutId = setTimeout(() => {
this._warn_on_long_close();
}, 60e3);
try {
await Promise.all(
this._holders.map((connectionHolder) =>
connectionHolder._waitUntilReleased()
)
);
await Promise.all(
this._holders.map((connectionHolder) => connectionHolder.close())
);
} catch (error) {
this.terminate();
throw error;
} finally {
clearTimeout(warningTimeoutId);
this._closed = true;
this._closing = false;
}
}
isClosed(): boolean {
return this._closed;
}
/**
* Terminate all connections in the pool. If the pool is already closed,
* it returns without doing anything.
*/
terminate(): void {
if (this._closed) {
return;
}
this._checkInit();
for (const connectionHolder of this._holders) {
connectionHolder.terminate();
}
this._closed = true;
}
private _warn_on_long_close(): void {
// tslint:disable-next-line: no-console
console.warn(
"Pool.close() is taking over 60 seconds to complete. " +
"Check if you have any unreleased connections left."
);
}
}
export function createPool(
dsn?: string | LegacyPoolOptions | null,
options?: LegacyPoolOptions | null
): Promise<Pool> {
// tslint:disable-next-line: no-console
console.warn(
"`createPool()` is deprecated and is scheduled to be removed. " +
"Use `connect()` instead"
);
if (typeof dsn === "string") {
return PoolShell.create(dsn, options?.connectOptions, options);
} else {
if (dsn != null) {
// tslint:disable-next-line: no-console
console.warn(
"`options` as the first argument to `edgedb.connect` is " +
"deprecated, use " +
"`edgedb.connect('instance_name_or_dsn', options)`"
);
}
const opts = {...dsn, ...options};
return PoolShell.create(undefined, opts.connectOptions, opts);
}
}
export interface ConnectOptions extends ConnectConfig {
pool?: PoolOptions;
}
export default function connect(
dsn?: string | ConnectOptions | null,
options?: ConnectOptions | null
): Promise<Pool> {
if (typeof dsn === "string") {
return PoolShell.create(dsn, options, options?.pool);
} else {
if (dsn != null) {
// tslint:disable-next-line: no-console
console.warn(
"`options` as the first argument to `edgedb.connect` is " +
"deprecated, use " +
"`edgedb.connect('instance_name_or_dsn', options)`"
);
}
const opts = {...dsn, ...options};
return PoolShell.create(undefined, opts, opts.pool);
}
} | the_stack |
import { ILayoutDefinition, ILayout, BaseLayout } from '@pnp/modern-search-extensibility';
import { BuiltinLayoutsKeys } from '../layouts/AvailableLayouts';
import { ServiceKey, ServiceScope, Text } from '@microsoft/sp-core-library';
import { ServiceScopeHelper } from './ServiceScopeHelper';
import { IPropertyPaneChoiceGroupOption } from '@microsoft/sp-property-pane';
import ISearchFiltersWebPartProps from '../webparts/searchFilters/ISearchFiltersWebPartProps';
import ISearchResultsWebPartProps from '../webparts/searchResults/ISearchResultsWebPartProps';
import * as commonStrings from 'CommonStrings';
import { WebPartContext } from '@microsoft/sp-webpart-base';
export class LayoutHelper {
/**
* Gets the layout instance according to the current selected one
* @param rootScope the root service scope
* @param context the Web Part context
* @param properties the web part properties (only supported Web Parts)
* @param layoutKey the selected layout key
* @param layoutDefinitions the available layout definitions
* @returns the data source provider instance
*/
public static async getLayoutInstance(rootScope: ServiceScope, context: WebPartContext, properties: ISearchFiltersWebPartProps | ISearchResultsWebPartProps, layoutKey: string, layoutDefinitions: ILayoutDefinition[]): Promise<ILayout> {
let layout: ILayout = undefined;
let serviceKey: ServiceKey<ILayout> = undefined;
if (layoutKey) {
// If it is a builtin layout, we load the corresponding known class file asynchronously for performance purpose
// We also create the service key at the same time to be able to get an instance
switch (layoutKey) {
// Details List
case BuiltinLayoutsKeys.DetailsList:
const { DetailsListLayout } = await import(
/* webpackChunkName: 'pnp-modern-search-results-detailslist-layout' */
'../layouts/results/detailsList/DetailListLayout'
);
serviceKey = ServiceKey.create<ILayout>('PnPModernSearchDetailsListLayout', DetailsListLayout);
break;
// Results Debug
case BuiltinLayoutsKeys.ResultsDebug:
const { ResultsDebugLayout } = await import(
/* webpackChunkName: 'pnp-modern-search-results-debug-layout' */
'../layouts/results/debug/ResultsDebugLayout'
);
serviceKey = ServiceKey.create<ILayout>('PnPModernSearchResultsDebugLayout', ResultsDebugLayout);
break;
// Filters Debug
case BuiltinLayoutsKeys.FiltersDebug:
const { DebugFilterLayout } = await import(
/* webpackChunkName: 'pnp-modern-search-filters-debug-layout' */
'../layouts/filters/debug/DebugFilterLayout'
);
serviceKey = ServiceKey.create<ILayout>('PnPModernSearchFiltersDebugLayout', DebugFilterLayout);
break;
// Results Custom
case BuiltinLayoutsKeys.ResultsCustom:
const { ResultsCustomLayout } = await import(
/* webpackChunkName: 'pnp-modern-search-results-custom-layout' */
'../layouts/results/custom/ResultsCustomLayout'
);
serviceKey = ServiceKey.create<ILayout>('PnPModernSearchResultsCustomLayout', ResultsCustomLayout);
break;
// Filters Custom
case BuiltinLayoutsKeys.FiltersCustom:
const { FiltersCustomLayout } = await import(
/* webpackChunkName: 'pnp-modern-search-filters-custom-layout' */
'../layouts/filters/custom/FiltersCustomLayout'
);
serviceKey = ServiceKey.create<ILayout>('PnPModernSearchFiltersCustomLayout', FiltersCustomLayout);
break;
// Cards
case BuiltinLayoutsKeys.Cards:
const { CardsLayout } = await import(
/* webpackChunkName: 'pnp-modern-search-results-cards-layout' */
'../layouts/results/cards/CardsLayout'
);
serviceKey = ServiceKey.create<ILayout>('PnPModernSearchCardsLayout', CardsLayout);
break;
// Slider
case BuiltinLayoutsKeys.Slider:
const { SliderLayout } = await import(
/* webpackChunkName: 'pnp-modern-search-results-slider-layout' */
'../layouts/results/slider/SliderLayout'
);
serviceKey = ServiceKey.create<ILayout>('PnPModernSearchSliderLayout', SliderLayout);
break;
// Simple List
case BuiltinLayoutsKeys.SimpleList:
const { SimpleListLayout } = await import(
/* webpackChunkName: 'pnp-modern-search-results-simple-list-layout' */
'../layouts/results/simpleList/SimpleListLayout'
);
serviceKey = ServiceKey.create<ILayout>('PnPModernSearchSimpleListLayout', SimpleListLayout);
break;
// People
case BuiltinLayoutsKeys.People:
const { PeopleLayout } = await import(
/* webpackChunkName: 'pnp-modern-search-results-people-layout' */
'../layouts/results/people/PeopleLayout'
);
serviceKey = ServiceKey.create<ILayout>('PnPModernSearchPeopleLayout', PeopleLayout);
break;
// Vertical
case BuiltinLayoutsKeys.Vertical:
const { VerticalFilterLayout } = await import(
/* webpackChunkName: 'pnp-modern-search-filters-vertical-layout' */
'../layouts/filters/vertical/VerticalFilterLayout'
);
serviceKey = ServiceKey.create<ILayout>('PnPModernSearchVerticalLayout', VerticalFilterLayout);
break;
// Horizontal
case BuiltinLayoutsKeys.Horizontal:
const { HorizontalFilterLayout } = await import(
/* webpackChunkName: 'pnp-modern-search-filters-horizontal-layout' */
'../layouts/filters/horizontal/HorizontalFilterLayout'
);
serviceKey = ServiceKey.create<ILayout>('PnPModernSearchHorizontalFilterLayout', HorizontalFilterLayout);
break;
// Panel
case BuiltinLayoutsKeys.Panel:
const { PanelFilterLayout } = await import(
/* webpackChunkName: 'pnp-modern-search-filters-panel-layout' */
'../layouts/filters/panel/PanelFilterLayout'
);
serviceKey = ServiceKey.create<ILayout>('PnPModernSearchPanelLayout', PanelFilterLayout);
break;
// Custom layout scenario
default:
// Gets the registered service key according to the selected layou definition
const matchingDefinitions = layoutDefinitions.filter((layoutDefinition) => { return layoutDefinition.key === layoutKey; });
// Can only have one layout instance per key
if (matchingDefinitions.length > 0) {
serviceKey = matchingDefinitions[0].serviceKey;
} else {
// Case when the extensibility library is removed from the catalog or the configuration
throw new Error(Text.format(commonStrings.General.Extensibility.LayoutDefinitionNotFound, layoutKey));
}
break;
}
return new Promise<ILayout>((resolve, reject) => {
// Register the layout service in the Web Part scope only (child scope of the current scope)
const childServiceScope = ServiceScopeHelper.registerChildServices(rootScope, [serviceKey]);
childServiceScope.whenFinished(async () => {
layout = childServiceScope.consume<ILayout>(serviceKey);
// Verifiy if the layout implements correctly the ILayout interface and BaseLayout methods
const isValidLayout = (layoutInstance: ILayout): layoutInstance is BaseLayout<any> => {
return (
(layoutInstance as BaseLayout<any>).getPropertyPaneFieldsConfiguration !== undefined &&
(layoutInstance as BaseLayout<any>).onInit !== undefined &&
(layoutInstance as BaseLayout<any>).onPropertyUpdate !== undefined
);
};
if (!isValidLayout(layout)) {
reject(new Error(Text.format(commonStrings.General.Extensibility.InvalidLayoutInstance, layoutKey)));
}
// Initialize the layout with current Web Part properties
if (layout) {
layout.properties = properties.layoutProperties; // Web Parts using layouts must define this sub property
layout.context = context;
await layout.onInit();
resolve(layout);
}
});
});
}
}
/**
* Builds the layout options list from available layouts
*/
public static getLayoutOptions(availableLayoutDefinitions: ILayoutDefinition[]): IPropertyPaneChoiceGroupOption[] {
let layoutOptions: IPropertyPaneChoiceGroupOption[] = [];
availableLayoutDefinitions.forEach((source) => {
layoutOptions.push({
iconProps: {
officeFabricIconFontName: source.iconName
},
imageSize: {
width: 200,
height: 100
},
key: source.key,
text: source.name,
});
});
return layoutOptions;
}
} | the_stack |
import { ScoredItem, Tweet } from 'src/common-types';
// Mix of real and fake data for testing purposes.
export const TWITTER_ENTRIES: Array<ScoredItem<Tweet>> = [
{
item: {
created_at: 'Mon Jan 24 20:43:25 +0000 2022',
date: new Date(new Date('2022-01-24T20:43:25.000Z')),
entities: {
hashtags: [],
symbols: [],
urls: [
{
display_url: 'twitter.com/i/web/status/1…',
expanded_url:
'https://twitter.com/i/web/status/1485714881710022664',
indices: [117, 140],
url: 'https://t.co/8koaMgKmTI',
},
],
user_mentions: [],
},
extended_tweet: {
display_text_range: [0, 279],
entities: {
hashtags: [
{
indices: [27, 39],
text: 'fakehashtag1',
},
],
symbols: [],
urls: [
{
display_url: 'jigsaw.google.com/the-current/sh…',
expanded_url: 'https://jigsaw.google.com/the-current/shutdown/',
indices: [256, 279],
url: 'https://t.co/rr3jt112OS',
},
],
user_mentions: [],
},
full_text:
"The Community Court of Justice for ECOWAS, of which Burkina Faso is a member, ruled that a 2017 internet shutdown in Togo violated its citizens' fundamental rights. Learn more about the impacts of internet shutdowns in the last issue of the Current. (3/3)\nhttps://t.co/rr3jt112OS",
},
favorite_count: 1,
favorited: false,
id_str: '1485714881710022664',
lang: 'en',
reply_count: 0,
retweet_count: 0,
source:
'<a href="https://mobile.twitter.com" rel="nofollow">Twitter Web App</a>',
text: "The Community Court of Justice for ECOWAS, of which Burkina Faso is a member, ruled that a 2017 internet shutdown in Togo violated its citizens' fundamental rights. Learn more about the impacts of internet shutdowns in the last issue of the Current. (3/3)\nhttps://t.co/rr3jt112OS",
truncated: true,
url: 'https://twitter.com/i/web/status/1485714881710022664',
user: {
created_at: 'Wed May 11 18:30:36 +0000 2011',
description:
'A unit at Google that explores threats to open societies and builds technology that inspires scalable solutions.\n\nRT≠endorsement',
followers_count: 89518,
id: 296979153,
id_str: '296979153',
name: 'Jigsaw',
screen_name: 'Jigsaw',
statuses_count: 2702,
verified: true,
},
authorName: 'Jigsaw',
authorScreenName: 'Jigsaw',
authorUrl: 'https://twitter.com/Jigsaw',
authorAvatarUrl:
'http://pbs.twimg.com/profile_images/1224720616370135041/TZb_fdEo_normal.jpg',
verified: true,
},
scores: {},
},
{
item: {
created_at: 'Mon Jan 24 20:43:25 +0000 2022',
date: new Date('2022-01-24T20:43:25.000Z'),
entities: {
hashtags: [],
symbols: [],
urls: [
{
display_url: 'twitter.com/i/web/status/1…',
expanded_url:
'https://twitter.com/i/web/status/1485714880292397057',
indices: [117, 140],
url: 'https://t.co/qkTt1tORQA',
},
],
user_mentions: [],
},
extended_tweet: {
display_text_range: [0, 213],
entities: {
hashtags: [
{
indices: [27, 39],
text: 'fakehashtag1',
},
{
indices: [27, 39],
text: 'fakehashtag2',
},
],
symbols: [],
urls: [],
user_mentions: [],
},
full_text:
'Internet shutdowns have become a go-to tactic in recent years to quell domestic protest, but their use raises grave human rights concerns - with knock-on effects across the economy, education and healthcare. (2/3)',
},
favorite_count: 2,
favorited: false,
id_str: '1485714880292397057',
lang: 'en',
reply_count: 1,
retweet_count: 0,
source:
'<a href="https://mobile.twitter.com" rel="nofollow">Twitter Web App</a>',
text: 'Internet shutdowns have become a go-to tactic in recent years to quell domestic protest, but their use raises grave human rights concerns - with knock-on effects across the economy, education and healthcare. (2/3)',
truncated: true,
url: 'https://twitter.com/i/web/status/1485714880292397057',
user: {
created_at: 'Wed May 11 18:30:36 +0000 2011',
description:
'A unit at Google that explores threats to open societies and builds technology that inspires scalable solutions.\n\nRT≠endorsement',
followers_count: 89518,
friends_count: 1065,
id: 296979153,
id_str: '296979153',
name: 'Jigsaw',
screen_name: 'Jigsaw',
statuses_count: 2702,
verified: true,
},
authorName: 'Jigsaw',
authorScreenName: 'Jigsaw',
authorUrl: 'https://twitter.com/Jigsaw',
authorAvatarUrl:
'http://pbs.twimg.com/profile_images/1224720616370135041/TZb_fdEo_normal.jpg',
verified: true,
},
scores: {},
},
{
item: {
created_at: 'Mon Nov 08 14:47:56 +0000 2021',
date: new Date('2021-11-08T14:47:56.000Z'),
entities: {
hashtags: [],
symbols: [],
urls: [
{
display_url: 'twitter.com/i/web/status/1…',
expanded_url:
'https://twitter.com/i/web/status/1457721555832741888',
indices: [117, 140],
url: 'https://t.co/9H4zPEGGgc',
},
],
user_mentions: [
{
id: 111074974,
id_str: '111074974',
indices: [0, 10],
name: 'Morehouse College',
screen_name: 'Morehouse',
},
],
},
extended_tweet: {
display_text_range: [0, 203],
entities: {
hashtags: [],
symbols: [],
urls: [
{
display_url: 'news.yahoo.com/morehouse-coll…',
expanded_url:
'https://news.yahoo.com/morehouse-college-google-partner-virtual-181911132.html',
indices: [180, 203],
url: 'https://t.co/hgDjZH0VuS',
},
],
user_mentions: [
{
id: 111074974,
id_str: '111074974',
indices: [0, 10],
name: 'Morehouse College',
screen_name: 'Morehouse',
},
],
},
full_text:
'@Morehouse College’s National Training Institute on Race and Equity, along with the school’s Culturally Relevant Computer Lab recently spoke about Trainer. Check out the coverage.\nhttps://t.co/hgDjZH0VuS',
},
favorite_count: 0,
favorited: false,
id_str: '1457721555832741888',
lang: 'en',
reply_count: 0,
retweet_count: 0,
source:
'<a href="https://mobile.twitter.com" rel="nofollow">Twitter Web App</a>',
text: '@Morehouse College’s National Training Institute on Race and Equity, along with the school’s Culturally Relevant Computer Lab recently spoke about Trainer. Check out the coverage.\nhttps://t.co/hgDjZH0VuS',
truncated: true,
url: 'https://twitter.com/i/web/status/1457721555832741888',
user: {
created_at: 'Wed May 11 18:30:36 +0000 2011',
description:
'A unit at Google that explores threats to open societies and builds technology that inspires scalable solutions.\n\nRT≠endorsement',
followers_count: 89518,
friends_count: 1065,
id: 296979153,
id_str: '296979153',
name: 'Jigsaw',
screen_name: 'Jigsaw',
statuses_count: 2702,
verified: true,
},
authorName: 'Jigsaw',
authorScreenName: 'Jigsaw',
authorUrl: 'https://twitter.com/Jigsaw',
authorAvatarUrl:
'http://pbs.twimg.com/profile_images/1224720616370135041/TZb_fdEo_normal.jpg',
verified: true,
},
scores: {
TOXICITY: 0.08997067,
SEVERE_TOXICITY: 0.0441159,
INSULT: 0.08199655,
PROFANITY: 0.045761928,
THREAT: 0.10894311,
IDENTITY_ATTACK: 0.10441957,
},
},
{
item: {
created_at: 'Thu Oct 28 14:37:12 +0000 2021',
date: new Date('2021-10-28T14:37:12.000Z'),
entities: {
hashtags: [],
symbols: [],
urls: [
{
display_url: 'twitter.com/i/web/status/1…',
expanded_url:
'https://twitter.com/i/web/status/1453732586509901832',
indices: [116, 139],
url: 'https://t.co/MhArwy74Pl',
},
],
user_mentions: [],
},
extended_tweet: {
display_text_range: [0, 274],
entities: {
hashtags: [],
symbols: [],
urls: [
{
display_url: 'jigsaw.google.com/the-current/sh…',
expanded_url: 'https://jigsaw.google.com/the-current/shutdown/',
indices: [251, 274],
url: 'https://t.co/rr3jt0Jrqi',
},
],
user_mentions: [],
},
full_text:
'Over the last decade, the number of internet shutdowns globally has exploded from just a handful to hundreds every year. Learn more about the threat of internet shutdowns and how citizens can mitigate their impacts in the latest issue of the Current.\nhttps://t.co/rr3jt0Jrqi',
},
favorite_count: 4,
favorited: false,
id_str: '1453732586509901832',
lang: 'en',
reply_count: 0,
retweet_count: 5,
source: '<a href="https://www.sprinklr.com" rel="nofollow">Sprinklr</a>',
text: 'Over the last decade, the number of internet shutdowns globally has exploded from just a handful to hundreds every year. Learn more about the threat of internet shutdowns and how citizens can mitigate their impacts in the latest issue of the Current.\nhttps://t.co/rr3jt0Jrqi',
truncated: true,
url: 'https://twitter.com/i/web/status/1453732586509901832',
user: {
created_at: 'Wed May 11 18:30:36 +0000 2011',
description:
'A unit at Google that explores threats to open societies and builds technology that inspires scalable solutions.\n\nRT≠endorsement',
followers_count: 89518,
friends_count: 1065,
id: 296979153,
id_str: '296979153',
name: 'Jigsaw',
screen_name: 'Jigsaw',
statuses_count: 2702,
verified: true,
},
authorName: 'Jigsaw',
authorScreenName: 'Jigsaw',
authorUrl: 'https://twitter.com/Jigsaw',
authorAvatarUrl:
'http://pbs.twimg.com/profile_images/1224720616370135041/TZb_fdEo_normal.jpg',
verified: true,
},
scores: {
TOXICITY: 0.05631642,
SEVERE_TOXICITY: 0.020877242,
INSULT: 0.035202846,
PROFANITY: 0.016683849,
THREAT: 0.07141919,
IDENTITY_ATTACK: 0.033515174,
},
},
]; | the_stack |
import {AttributeWithCacheKey, createAttributeWithCacheKey} from '../../../attribute-with-cache-key';
import {Graph} from '../../../graph';
import {OperatorImplementation, OperatorInitialization} from '../../../operators';
import {Tensor} from '../../../tensor';
import {getGlsl} from '../glsl-source';
import {WebGLInferenceHandler} from '../inference-handler';
import {ProgramInfo, TextureType} from '../types';
export interface UpsampleAttributes extends AttributeWithCacheKey {
readonly opset: number;
readonly isResize: boolean;
readonly mode: string;
readonly scales: number[];
readonly extrapolationValue: number;
readonly coordinateTransformMode: string;
readonly useExtrapolation: boolean;
readonly needRoiInput: boolean;
readonly nearestMode: string;
readonly cubicCoefficientA: number;
readonly excludeOutside: boolean;
readonly useNearest2xOptimization: boolean;
readonly roiInputIdx: number;
readonly scalesInputIdx: number;
readonly sizesInputIdx: number;
}
const upsampleProgramMetadata = {
name: 'Upsample',
inputNames: ['X'],
inputTypes: [TextureType.unpacked],
};
export const upsample: OperatorImplementation<UpsampleAttributes> =
(inferenceHandler: WebGLInferenceHandler, inputs: Tensor[], attributes: UpsampleAttributes): Tensor[] => {
validateInputs(inputs, attributes);
const output = inferenceHandler.run(
{
...upsampleProgramMetadata,
cacheHint: attributes.cacheKey,
get: () => createUpsampleProgramInfo(inferenceHandler, inputs, attributes)
},
inputs);
return [output];
};
export const parseUpsampleAttributesV7: OperatorInitialization<UpsampleAttributes> =
(node: Graph.Node): UpsampleAttributes => parseUpsampleAttributes(node, 7);
export const parseUpsampleAttributesV9: OperatorInitialization<UpsampleAttributes> =
(node: Graph.Node): UpsampleAttributes => parseUpsampleAttributes(node, 9);
export const parseUpsampleAttributes = (node: Graph.Node, opset: number): UpsampleAttributes => {
const isResize = (opset >= 10);
// processing node attributes
const mode = node.attributes.getString('mode', 'nearest');
if (mode !== 'nearest' && mode !== 'linear' && (opset < 11 || mode !== 'cubic')) {
throw new Error(`unrecognized mode: ${mode}`);
}
let scales: number[] = [];
if (opset < 9) {
scales = node.attributes.getFloats('scales');
scalesValidation(scales, mode, isResize);
}
const extrapolationValue = node.attributes.getFloat('extrapolation_value', 0.0);
const coordinateTransformMode =
opset > 10 ? node.attributes.getString('coordinate_transformation_mode', 'half_pixel') : 'asymmetric';
if ([
'asymmetric', 'pytorch_half_pixel', 'tf_half_pixel_for_nn', 'align_corners', 'tf_crop_and_resize', 'half_pixel'
].indexOf(coordinateTransformMode) === -1) {
throw new Error(`coordinate_transform_mode '${coordinateTransformMode}' is not supported`);
}
const needRoiInput = (coordinateTransformMode === 'tf_crop_and_resize');
const useExtrapolation = needRoiInput;
const nearestMode =
(mode === 'nearest' && opset >= 11) ? node.attributes.getString('nearest_mode', 'round_prefer_floor') : '';
if (['round_prefer_floor', 'round_prefer_ceil', 'floor', 'ceil', ''].indexOf(nearestMode) === -1) {
throw new Error(`nearest_mode '${nearestMode}' is not supported`);
}
const cubicCoefficientA = node.attributes.getFloat('cubic_coeff_a', -0.75);
const excludeOutside = node.attributes.getInt('exclude_outside', 0) !== 0;
if (excludeOutside && mode !== 'cubic') {
throw new Error('exclude_outside can be set to 1 only when mode is CUBIC.');
}
const useNearest2xOptimization =
(opset < 11) ? true : (mode === 'nearest' && coordinateTransformMode === 'asymmetric' && nearestMode === 'floor');
let roiInputIdx = 0;
let scalesInputIdx = 0;
let sizesInputIdx = 0;
if (opset > 10) {
roiInputIdx = 1;
scalesInputIdx = 2;
sizesInputIdx = 3;
} else if (opset === 9) {
scalesInputIdx = 1;
}
return createAttributeWithCacheKey({
opset,
isResize,
mode,
scales,
extrapolationValue,
coordinateTransformMode,
useExtrapolation,
needRoiInput,
nearestMode,
cubicCoefficientA,
excludeOutside,
useNearest2xOptimization,
roiInputIdx,
scalesInputIdx,
sizesInputIdx
});
};
const createUpsampleProgramInfo =
(inferenceHandler: WebGLInferenceHandler, inputs: Tensor[], attributes: UpsampleAttributes): ProgramInfo => {
const glsl = getGlsl(inferenceHandler.session.backend.glContext.version);
const [inputWidth, inputHeight] =
inferenceHandler.calculateTextureWidthAndHeight(inputs[0].dims, TextureType.unpacked);
const outputShape = inputs[0].dims.map((dim, i) => Math.floor(dim * attributes.scales[i]));
const [outputWidth, outputHeight] =
inferenceHandler.calculateTextureWidthAndHeight(outputShape, TextureType.unpacked);
const dim = outputShape.length;
const outputPitches = new Array<number>(dim);
const inputPitches = new Array<number>(dim);
let precalculatedPitches = `
int output_pitches[${dim}];
int input_pitches[${dim}];
`;
for (let d = dim - 1; d >= 0; d--) {
outputPitches[d] = (d === dim - 1) ? 1 : outputPitches[d + 1] * outputShape[d + 1];
inputPitches[d] = (d === dim - 1) ? 1 : inputPitches[d + 1] * inputs[0].dims[d + 1];
precalculatedPitches += `
output_pitches[${d}] = ${outputPitches[d]};
input_pitches[${d}] = ${inputPitches[d]};
`;
}
const getInputFloatFunction = `
float getInputFloat(int index) {
vec2 coords = offsetToCoords(index, ${inputWidth}, ${inputHeight});
float value = getColorAsFloat(${glsl.texture2D}(X, coords));
return value;
}
`;
const shaderSource = attributes.mode === 'nearest' ?
// nearest
`
${getInputFloatFunction}
float process(int indices[${dim}]) {
int input_index = 0;
int output_index = coordsToOffset(TexCoords, ${outputWidth}, ${outputHeight});
${precalculatedPitches}
int d, m;
for (int dim = 0; dim < ${dim}; ++dim) {
d = output_index / output_pitches[dim];
m = output_index - d * output_pitches[dim];
output_index = m;
if (scales[dim] != 1 && d > 0) {
int d2 = d / scales[dim];
m = d - d2 * scales[dim];
d = d2;
}
input_index += input_pitches[dim] * d;
}
return getInputFloat(input_index);
}` :
dim === 4 ?
// bilinear 4D
`
${getInputFloatFunction}
float process(int indices[4]) {
int input_index = 0;
int output_index = coordsToOffset(TexCoords, ${outputWidth}, ${outputHeight});
${precalculatedPitches}
int m;
int index_of_dim0, index_of_dim1, index_of_dim2, index_of_dim3;
index_of_dim0 = output_index / output_pitches[0];
m = output_index - index_of_dim0 * output_pitches[0];
index_of_dim1 = m / output_pitches[1];
m = m - index_of_dim1 * output_pitches[1];
index_of_dim2 = m / output_pitches[2];
m = m - index_of_dim2 * output_pitches[2];
index_of_dim3 = m;
int index_of_input_dim2, index_of_input_dim3, x_offset, y_offset;
index_of_input_dim2 = index_of_dim2 / scales[2];
y_offset = index_of_dim2 - index_of_input_dim2 * scales[2];
index_of_input_dim3 = index_of_dim3 / scales[3];
x_offset = index_of_dim3 - index_of_input_dim3 * scales[3];
input_index = index_of_dim0 * input_pitches[0] +
index_of_dim1 * input_pitches[1] +
index_of_input_dim2 * input_pitches[2] +
index_of_input_dim3;
float x00 = getInputFloat(input_index);
float x10, x01, x11;
bool end_of_dim2 = false;
if (index_of_input_dim2 == (${inputs[0].dims[2]} - 1)) {
// It's the end in dimension 2
x01 = x00;
end_of_dim2 = true;
} else {
x01 = getInputFloat(input_index + input_pitches[2]);
}
if (index_of_input_dim3 == (input_pitches[2] - 1)) {
// It's the end in dimension 3
x10 = x00;
x11 = x01;
}
else {
x10 = getInputFloat(input_index + 1);
x11 = end_of_dim2 ? x10 : getInputFloat(input_index + input_pitches[2] + 1);
}
float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[2]);
float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[2]);
return y0 + float(x_offset) * (y1 - y0) / float(scales[3]);
}` :
// bilinear 2D
`
${getInputFloatFunction}
float process(int indices[2]) {
int input_index = 0;
int output_index = coordsToOffset(TexCoords, ${outputWidth}, ${outputHeight});
${precalculatedPitches}
int m;
int index_of_dim0, index_of_dim1;
index_of_dim0 = output_index / output_pitches[0];
m = output_index - index_of_dim0 * output_pitches[0];
index_of_dim1 = m;
int index_of_input_dim0, index_of_input_dim1, x_offset, y_offset;
index_of_input_dim0 = index_of_dim0 / scales[0];
y_offset = index_of_dim0 - index_of_input_dim0 * scales[0];
index_of_input_dim1 = index_of_dim1 / scales[1];
x_offset = index_of_dim1 - index_of_input_dim1 * scales[1];
input_index = index_of_input_dim0 * input_pitches[0] + index_of_input_dim1;
float x00 = getInputFloat(input_index);
float x10, x01, x11;
bool end_of_dim0 = false;
if (index_of_input_dim0 == (${inputs[0].dims[0]} - 1)) {
// It's the end in dimension 0
x01 = x00;
end_of_dim0 = true;
} else {
x01 = getInputFloat(input_index + input_pitches[0]);
}
if (index_of_input_dim1 == (input_pitches[0] - 1)) {
// It's the end in dimension 1
x10 = x00;
x11 = x01;
}
else {
x10 = getInputFloat(input_index + 1);
x11 = end_of_dim0 ? x10 : getInputFloat(input_index + input_pitches[0] + 1);
}
float y0 = x00 + float(y_offset) * (x01 - x00) / float(scales[0]);
float y1 = x10 + float(y_offset) * (x11 - x10) / float(scales[0]);
return y0 + float(x_offset) * (y1 - y0) / float(scales[1]);
}`;
return {
...upsampleProgramMetadata,
output: {dims: outputShape, type: inputs[0].type, textureType: TextureType.unpacked},
shaderSource,
variables: [{
name: 'scales',
type: 'int',
arrayLength: attributes.scales.length,
data: attributes.scales.map(x => Math.ceil(x))
}]
};
};
export const validateInputs = (inputs: Tensor[], attribute: UpsampleAttributes): void => {
if (!inputs || (attribute.opset < 9 && inputs.length !== 1) ||
(attribute.opset >= 9 && attribute.opset < 11 && inputs.length !== 2) ||
(attribute.opset >= 11 && inputs.length !== 3 && inputs.length !== 4)) {
throw new Error('invalid inputs.');
}
if (attribute.scales.length > 0 && inputs[0].dims.length !== attribute.scales.length) {
throw new Error('Invalid input shape.');
}
if (inputs[0].type === 'string') {
throw new Error('Invalid input tensor types.');
}
};
export const scalesValidation = (scales: number[], mode: string, isResize: boolean): void => {
if (!isResize) {
for (const scale of scales) {
if (scale < 1) {
throw new Error('Scale value should be greater than or equal to 1.');
}
}
} else {
for (const scale of scales) {
if (scale <= 0) {
throw new Error('Scale value should be greater than 0.');
}
}
}
if (mode === 'linear' || mode === 'cubic') {
if (scales.length !== 2 && (scales.length !== 4 || scales[0] !== 1 || scales[1] !== 1)) {
throw new Error(`'Linear' mode and 'Cubic' mode only support 2-D inputs ('Bilinear', 'Bicubic') \
or 4-D inputs with the corresponding outermost 2 scale values being 1 \
in the ${isResize ? 'Resize' : 'Upsample'} opeartor.`);
}
}
}; | the_stack |
import fetch from 'node-fetch';
import * as dotenv from 'dotenv';
import glob from 'glob';
import {
buildSite,
cleanupExistingBuckets,
deploySite,
EnvironmentBoolean,
forceDeleteBucket,
generateBucketName,
Permission,
resolveSiteDirectory,
s3,
} from './helpers';
import 'jest-expect-message';
jest.setTimeout(150000);
dotenv.config();
const bucketName = generateBucketName();
const testingEndpoint = `http://${bucketName}.s3-website-eu-west-1.amazonaws.com`;
console.debug(`Testing using bucket ${bucketName}.`);
beforeAll(async () => {
// If a previous test execution failed spectacularly, it's possible the bucket may have been left behind
// Here we scan for leftover buckets warn about them/delete them.
if (!process.env.SKIP_BUCKET_CLEANUP) {
try {
await cleanupExistingBuckets(!!process.env.CLEANUP_TEST_BUCKETS);
} catch (err) {
// We can't use console.error here because Jest swallows it.
// I'd love to just throw an error instead of killing the process, but if we do that
// Jest continues running tests but the results are unusable!
// https://github.com/facebook/jest/issues/2713
process.stderr.write('[IMPORTANT] Failed to cleanup leftover buckets! All tests will now fail!\n');
process.stderr.write(`${err}\n`);
process.exit(1);
}
}
});
afterAll(async () => {
try {
await forceDeleteBucket(bucketName);
} catch (err) {
console.error('Failed to delete bucket after test completion:', bucketName);
}
});
describe('gatsby-plugin-s3', () => {
beforeAll(async () => {
await buildSite('with-redirects', { GATSBY_S3_TARGET_BUCKET: bucketName });
});
test(`IAM policy to enable testing permissions is present and bucket doesn't already exist`, async () => {
await expect(
deploySite('with-redirects', [Permission.PutObject, Permission.PutBucketAcl, Permission.PutBucketWebsite])
).rejects.toThrow();
});
test(`can create a bucket if it doesn't already exist`, async () => {
await expect(
deploySite('with-redirects', [
Permission.PutObject,
Permission.PutObjectAcl,
Permission.CreateBucket,
Permission.PutBucketAcl,
Permission.PutBucketWebsite,
])
).resolves.toBeTruthy();
});
test(`correctly handles non-built files`, async () => {
await deploySite('with-redirects', [
Permission.PutObject,
Permission.PutObjectAcl,
Permission.CreateBucket,
Permission.PutBucketAcl,
Permission.PutBucketWebsite,
Permission.DeleteObject,
]);
console.log('[debug]', 'uploads', bucketName);
async function createTestFile(Key: string) {
await s3
.putObject({
Bucket: bucketName,
Key,
Body: `test content for ${Key}`,
})
.promise();
}
await createTestFile('file.retain.js');
await createTestFile('file.remove.js');
await createTestFile('sub-folder/file.retain.js');
await createTestFile('sub-folder/file.remove.js');
await createTestFile('sub-folder/retain-folder/file.js');
await createTestFile('retain-folder/file.js');
await deploySite('with-redirects', [
Permission.PutObject,
Permission.PutObjectAcl,
Permission.CreateBucket,
Permission.PutBucketAcl,
Permission.PutBucketWebsite,
Permission.DeleteObject,
]);
await expect(s3.headObject({ Bucket: bucketName, Key: 'file.retain.js' }).promise()).resolves.toBeTruthy();
await expect(s3.headObject({ Bucket: bucketName, Key: 'file.remove.js' }).promise()).rejects.toThrow();
await expect(
s3.headObject({ Bucket: bucketName, Key: 'sub-folder/file.retain.js' }).promise()
).resolves.toBeTruthy();
await expect(
s3.headObject({ Bucket: bucketName, Key: 'sub-folder/file.remove.js' }).promise()
).rejects.toThrow();
await expect(
s3
.headObject({
Bucket: bucketName,
Key: 'sub-folder/retain-folder/file.js',
})
.promise()
).resolves.toBeTruthy();
await expect(
s3.headObject({ Bucket: bucketName, Key: 'retain-folder/file.js' }).promise()
).resolves.toBeTruthy();
});
});
describe('object-based redirects', () => {
const siteDirectory = resolveSiteDirectory('with-redirects');
beforeAll(async () => {
await buildSite('with-redirects', {
GATSBY_S3_TARGET_BUCKET: bucketName,
GATSBY_S3_LEGACY_REDIRECTS: EnvironmentBoolean.False,
});
await deploySite('with-redirects', [
Permission.PutObject,
Permission.PutObjectAcl,
Permission.CreateBucket,
Permission.PutBucketAcl,
Permission.PutBucketWebsite,
]);
});
const headerTests = [
{
name: 'html files',
path: '/',
cacheControl: 'public, max-age=0, must-revalidate',
contentType: 'text/html',
},
{
name: 'page-data files',
path: '/page-data/index/page-data.json',
cacheControl: 'public, max-age=0, must-revalidate',
contentType: 'application/json',
},
{
name: 'sw.js',
path: '/sw.js',
cacheControl: 'public, max-age=0, must-revalidate',
contentType: 'application/javascript',
},
{
name: 'static files',
searchPattern: 'static/**/**.json',
cacheControl: 'public, max-age=31536000, immutable',
contentType: 'application/json',
},
{
name: 'js files',
searchPattern: '**/**/!(sw).js',
cacheControl: 'public, max-age=31536000, immutable',
contentType: 'application/javascript',
},
{
name: 'css files',
searchPattern: '**/**.css',
cacheControl: 'public, max-age=31536000, immutable',
contentType: 'text/css',
},
];
headerTests.forEach(t => {
test(`caching and content type headers are correctly set for ${t.name}`, async () => {
let path;
if (t.path) {
path = t.path;
} else if (t.searchPattern) {
console.log(`${siteDirectory}/`);
const matchingFiles = glob.sync(t.searchPattern, { cwd: `${siteDirectory}/public`, nodir: true });
path = `/${matchingFiles[0]}`;
console.log(path);
}
if (!path) {
throw new Error(`Failed to find matching file for pattern ${t.searchPattern}`);
}
const response = await fetch(`${testingEndpoint}${path}`);
expect(response.status, `Error accessing ${testingEndpoint}${path}`).toBe(200);
expect(response.headers.get('cache-control'), `Incorrect Cache-Control for ${path}`).toBe(t.cacheControl);
expect(response.headers.get('content-type'), `Incorrect Content-Type for ${path}`).toBe(t.contentType);
});
});
const redirectTests = [
{
name: 'from root',
source: '/',
expectedDestination: '/page-2',
expectedResponseCode: 301,
},
{
name: 'temporarily',
source: '/hello-there',
expectedDestination: '/client-only',
expectedResponseCode: 302,
},
{
name: 'to a child directory',
source: '/blog',
expectedDestination: '/blog/1',
expectedResponseCode: 301,
},
{
name: 'client-only routes',
source: '/client-only/test',
expectedDestination: '/client-only',
expectedResponseCode: 302,
},
{
name: 'from a path containing special characters',
source: "/asdf123.-~_!%24%26'()*%2B%2C%3B%3D%3A%40%25",
expectedDestination: '/special-characters',
expectedResponseCode: 301,
},
{
name: 'from a path with a trailing slash',
source: '/trailing-slash/',
expectedDestination: '/trailing-slash/1',
expectedResponseCode: 301,
},
];
redirectTests.forEach(t => {
test(`can redirect ${t.name}`, async () => {
const response = await fetch(`${testingEndpoint}${t.source}`, { redirect: 'manual' });
expect(response.status, `Incorrect response status for ${t.source}`).toBe(t.expectedResponseCode);
expect(response.headers.get('location'), `Incorrect Content-Type for ${t.source}`).toBe(
`${testingEndpoint}${t.expectedDestination}`
);
});
});
});
describe('rules-based redirects', () => {
beforeAll(async () => {
await buildSite('with-redirects', {
GATSBY_S3_TARGET_BUCKET: bucketName,
GATSBY_S3_LEGACY_REDIRECTS: EnvironmentBoolean.True,
});
await deploySite('with-redirects', [
Permission.CreateBucket,
Permission.PutObject,
Permission.PutBucketWebsite,
Permission.DeleteObject,
]);
});
const redirectTests = [
{
name: 'from root',
source: '/',
expectedDestination: '/page-2',
expectedResponseCode: 301,
},
{
name: 'temporarily',
source: '/hello-there',
expectedDestination: '/client-only',
expectedResponseCode: 302,
},
{
name: 'to a child directory',
source: '/blog',
expectedDestination: '/blog/1',
expectedResponseCode: 301,
},
{
name: 'client-only routes',
source: '/client-only/test',
expectedDestination: '/client-only',
expectedResponseCode: 302,
},
{
name: 'from a path containing special characters',
source: "/asdf123.-~_!%24%26'()*%2B%2C%3B%3D%3A%40%25",
expectedDestination: '/special-characters',
expectedResponseCode: 301,
},
{
name: 'from a path with a trailing slash',
source: '/trailing-slash/',
expectedDestination: '/trailing-slash/1',
expectedResponseCode: 301,
},
];
redirectTests.forEach(t => {
test(`can redirect ${t.name}`, async () => {
const response = await fetch(`${testingEndpoint}${t.source}`, { redirect: 'manual' });
expect(response.status, `Incorrect response status for ${t.source}`).toBe(t.expectedResponseCode);
expect(response.headers.get('location'), `Incorrect Content-Type for ${t.source}`).toBe(
`${testingEndpoint}${t.expectedDestination}`
);
});
});
}); | the_stack |
import React from 'react';
import ReactDOM from 'react-dom';
import { connect, history } from 'umi';
import { Avatar, Button, Mentions, message, Upload } from 'antd';
import { UserOutlined, PictureOutlined, SmileOutlined, MessageOutlined } from '@ant-design/icons';
import { UploadChangeParam } from 'antd/es/upload/interface';
import { stringify } from 'qs';
import { debounce } from 'lodash';
import EmojiPicker from 'yt-emoji-picker';
// @ts-ignore
import emojiToolkit from 'emoji-toolkit';
import MarkdownBody from '@/components/MarkdownBody';
import { ConnectProps, ConnectState, AuthModelState } from '@/models/connect';
import { getPageQuery, getPositions, insertText, isParentElement } from '@/utils/utils';
import { getToken } from '@/utils/authority';
import { IUser } from '@/models/I';
import * as services from '@/services';
import InlineUpload from './InlineUpload';
import calculateNodeHeight from './calculateNodeHeight';
import styles from './Editor.less';
interface ArticleCommentEditorProps extends Partial<ConnectProps> {
onSubmit: (values: { content: { markdown: string } }) => Promise<void>;
submitting: boolean;
className?: string;
placeholder?: string;
minRows?: number;
maxRows?: number;
maxLength?: number;
auth?: AuthModelState;
preview?: boolean;
defaultMentionUsers?: IUser[];
}
interface ArticleCommentEditorState {
value: string;
textareaStyles: object;
resizing: boolean;
search: string;
mentionUsers: IUser[];
loadingMentions: boolean;
}
/* eslint-disable react/no-unused-state */
class ArticleCommentEditor extends React.Component<
ArticleCommentEditorProps,
ArticleCommentEditorState
> {
static emojiPickerPopup?: HTMLDivElement;
static instance: ArticleCommentEditor;
static stackCount: number = 0;
constructor(props: ArticleCommentEditorProps) {
super(props);
this.state = {
value: '',
textareaStyles: {},
resizing: false,
search: '',
mentionUsers: (props.defaultMentionUsers || []).slice(0, 6),
loadingMentions: false,
};
}
inlineUpload?: InlineUpload;
emojiPickerBtn: any;
textarea: HTMLTextAreaElement | any;
componentDidMount() {
this.resizeTextarea();
if (this.textarea) {
this.inlineUpload = new InlineUpload(this.textarea, (value) => this.setState({ value }), {
action: UPLOAD_URL,
jsonName: 'data.url',
headers: {
Accept: `application/json`,
Authorization: getToken(),
},
onError(err: any, response: { message?: string }) {
if (response.message) {
message.error(response.message);
}
},
});
}
ArticleCommentEditor.stackCount++;
if (!ArticleCommentEditor.emojiPickerPopup) {
ArticleCommentEditor.emojiPickerPopup = document.createElement('div');
// ArticleCommentEditor.emojiPickerPopup.id = 'emoji-picker-popup';
ArticleCommentEditor.emojiPickerPopup.className = styles.emojiPickerPopup;
ArticleCommentEditor.emojiPickerPopup.style.display = 'none';
ArticleCommentEditor.emojiPickerPopup.style.position = 'absolute';
ArticleCommentEditor.emojiPickerPopup.style.zIndex = '99999';
document.body.addEventListener('click', this.hiddenEmojiPickerPopup, false);
document.body.appendChild(ArticleCommentEditor.emojiPickerPopup);
const emojiPickerProps = {
onSelect: this.handleEmojiSelect,
search: true,
recentCount: 36,
rowHeight: 40,
};
ReactDOM.render(<EmojiPicker {...emojiPickerProps} />, ArticleCommentEditor.emojiPickerPopup);
}
this.textarea.addEventListener('keydown', this.handleKeydownEvent);
}
componentWillUnmount() {
ArticleCommentEditor.stackCount--;
if (ArticleCommentEditor.emojiPickerPopup && ArticleCommentEditor.stackCount === 0) {
document.body.removeEventListener('click', this.hiddenEmojiPickerPopup, false);
document.body.removeChild(ArticleCommentEditor.emojiPickerPopup);
delete ArticleCommentEditor.emojiPickerPopup;
delete ArticleCommentEditor.instance;
}
this.textarea.removeEventListener('keydown', this.handleKeydownEvent);
this.inlineUpload?.destroy();
}
handleKeydownEvent = (e: KeyboardEvent) => {
if (e.key === 'Tab') {
e.preventDefault();
const indent = '\t';
const value = insertText(this.textarea, indent);
this.setState({ value });
}
};
handleSubmit = async (e?: React.FormEvent) => {
e && e.preventDefault();
const { onSubmit, submitting } = this.props;
const { value } = this.state;
if (value && !submitting) {
await onSubmit({ content: { markdown: value } });
this.setState({ value: '' });
}
};
handleEmojiSelect = (emoji: any) => {
const text = emojiToolkit.shortnameToUnicode(emoji.shortname);
const value = insertText(ArticleCommentEditor.instance.textarea, text);
ArticleCommentEditor.instance.setState({ value });
};
handleChange = (value: string) => {
this.setState({ value }, () => this.resizeTextarea());
};
handleBeforeUpload = () => {
message.loading('正在上传...');
return true;
};
handleUploadChange = ({ file }: UploadChangeParam) => {
let newValue = '';
switch (file.status) {
case 'done':
message.destroy();
message.success('上传成功!');
// @ts-ignore
newValue = insertText(this.textarea, ``);
this.setState({ value: newValue });
break;
case 'error':
message.destroy();
message.error(file.response.message);
break;
default:
break;
}
};
toggleEmojiPickerPopup = (emojiPickerBtn: any) => {
if (ArticleCommentEditor.emojiPickerPopup) {
ArticleCommentEditor.instance = this;
if (ArticleCommentEditor.emojiPickerPopup.style.display === 'none') {
ArticleCommentEditor.emojiPickerPopup.style.visibility = 'hidden';
ArticleCommentEditor.emojiPickerPopup.style.display = 'block';
const positions = getPositions(emojiPickerBtn);
const top = positions.top + 30;
let left = positions.left - ArticleCommentEditor.emojiPickerPopup.scrollWidth + 30;
if (left + ArticleCommentEditor.emojiPickerPopup.scrollWidth > document.body.scrollWidth) {
left = document.body.scrollWidth - ArticleCommentEditor.emojiPickerPopup.scrollWidth - 20;
}
ArticleCommentEditor.emojiPickerPopup.style.top = `${top}px`;
ArticleCommentEditor.emojiPickerPopup.style.left = `${left}px`;
ArticleCommentEditor.emojiPickerPopup.style.visibility = 'visible';
} else {
ArticleCommentEditor.emojiPickerPopup.style.display = 'none';
}
}
};
hiddenEmojiPickerPopup = (e: any) => {
if (
ArticleCommentEditor.emojiPickerPopup &&
ArticleCommentEditor.emojiPickerPopup.style.display !== 'none'
) {
if (
!isParentElement(e.target, [
ArticleCommentEditor.emojiPickerPopup,
ArticleCommentEditor.instance.emojiPickerBtn,
])
) {
ArticleCommentEditor.emojiPickerPopup.style.display = 'none';
}
}
};
fetchUsers = debounce(async (search: string) => {
const { defaultMentionUsers = [] } = this.props;
if (!search) {
return this.setState({ mentionUsers: defaultMentionUsers.slice(0, 6) });
}
const mentionUsers = defaultMentionUsers
.filter((user) => {
return (user.username as string).toLowerCase().indexOf(search.toLowerCase()) >= 0;
})
.slice(0, 6);
if (mentionUsers.length) {
return this.setState({ mentionUsers });
}
this.setState({ search, loadingMentions: !!search, mentionUsers: [] });
const { data } = await services.searchUsers(search);
if (this.state.search !== search) {
return false;
}
this.setState({ mentionUsers: data, loadingMentions: false });
return true;
}, 600);
setTextarea = (ref: HTMLDivElement) => {
if (!ref) {
return;
}
// eslint-disable-next-line prefer-destructuring
this.textarea = ref.getElementsByTagName('textarea')[0];
};
setEmojiPickerBtnRef = (ref: any) => {
this.emojiPickerBtn = ref;
};
resizeTextarea = () => {
const { minRows = 6, maxRows = 100 } = this.props;
const textareaStyles = calculateNodeHeight(this.textarea, false, minRows, maxRows);
this.setState({ textareaStyles, resizing: true }, () => {
this.setState({ resizing: false });
});
};
jumpToLogin = () => {
const { redirect } = getPageQuery();
// redirect
if (window.location.pathname !== '/auth/login' && !redirect) {
history.push({
pathname: '/auth/login',
search: stringify({
redirect: window.location.href,
}),
});
}
};
render() {
const {
submitting,
className,
placeholder = '',
auth: { user = {}, logged = false } = {},
maxRows = 100,
maxLength = 2048,
preview,
} = this.props;
const { value, textareaStyles, mentionUsers, loadingMentions } = this.state;
return (
<div>
<div className={`${styles.editor} ${className}`}>
<div className={styles.textarea} style={textareaStyles} ref={this.setTextarea}>
<Mentions
placeholder={placeholder}
loading={loadingMentions}
rows={maxRows}
maxLength={maxLength}
onChange={this.handleChange}
onSearch={this.fetchUsers}
value={value}
>
{mentionUsers.map(({ avatar, username }) => (
<Mentions.Option
key={username}
value={username}
className="antd-demo-dynamic-option"
>
<img src={avatar} alt={username} className={styles.mentionsAvatar} />
<span>{username}</span>
</Mentions.Option>
))}
</Mentions>
</div>
<div className={styles.toolbar}>
<div className={styles.info}>
{logged ? (
<div>
<Avatar
className={styles.avatar}
src={user.avatar}
alt={user.username}
icon={<UserOutlined />}
/>
{user.username}
</div>
) : (
<div>
您需要 <a onClick={this.jumpToLogin}>登录</a> 才能发表评论
</div>
)}
</div>
<div className={styles.actions}>
<div className={styles.action}>
<Upload
accept="image/*"
name="file"
className={styles.upload}
showUploadList={false}
action={UPLOAD_URL}
headers={{ Authorization: getToken() }}
beforeUpload={this.handleBeforeUpload}
onChange={this.handleUploadChange}
>
<PictureOutlined />
</Upload>
</div>
<div
ref={this.setEmojiPickerBtnRef}
className={styles.action}
onClick={() => this.toggleEmojiPickerPopup(this.emojiPickerBtn)}
>
<span className={styles.emojiPickerBtn}>
<SmileOutlined />
</span>
</div>
<div className={styles.action}>
<Button
className={styles.submitBtn}
htmlType="submit"
loading={submitting}
onClick={this.handleSubmit}
disabled={!logged}
type="primary"
icon={<MessageOutlined />}
>
评论
</Button>
</div>
</div>
</div>
</div>
{preview && value && (
<div className={styles.preview}>
<MarkdownBody markdown={value} />
</div>
)}
</div>
);
}
}
export default connect(({ auth }: ConnectState) => ({
auth,
}))(ArticleCommentEditor); | the_stack |
module android.view {
import CopyOnWriteArrayList = java.lang.util.concurrent.CopyOnWriteArrayList;
import CopyOnWriteArray = android.util.CopyOnWriteArray;
/**
* A view tree observer is used to register listeners that can be notified of global
* changes in the view tree. Such global events include, but are not limited to,
* layout of the whole tree, beginning of the drawing pass, touch mode change....
*
* A ViewTreeObserver should never be instantiated by applications as it is provided
* by the views hierarchy. Refer to {@link android.view.View#getViewTreeObserver()}
* for more information.
*/
export class ViewTreeObserver {
//private mOnWindowAttachListeners:CopyOnWriteArrayList<ViewTreeObserver.OnWindowAttachListener>;
//private mOnGlobalFocusListeners:CopyOnWriteArrayList<ViewTreeObserver.OnGlobalFocusChangeListener>;
private mOnTouchModeChangeListeners:CopyOnWriteArrayList<ViewTreeObserver.OnTouchModeChangeListener>;
private mOnGlobalLayoutListeners:CopyOnWriteArray<ViewTreeObserver.OnGlobalLayoutListener>;
private mOnScrollChangedListeners:CopyOnWriteArray<ViewTreeObserver.OnScrollChangedListener>;
private mOnPreDrawListeners:CopyOnWriteArray<ViewTreeObserver.OnPreDrawListener>;
private mOnDrawListeners:CopyOnWriteArrayList<ViewTreeObserver.OnDrawListener>;
private mAlive = true;
//addOnWindowAttachListener(listener:ViewTreeObserver.OnWindowAttachListener) {
// this.checkIsAlive();
//
// if (this.mOnWindowAttachListeners == null) {
// this.mOnWindowAttachListeners = new CopyOnWriteArrayList<ViewTreeObserver.OnWindowAttachListener>();
// }
//
// this.mOnWindowAttachListeners.add(listener);
//}
//removeOnWindowAttachListener(victim:ViewTreeObserver.OnWindowAttachListener) {
// this.checkIsAlive();
// if (this.mOnWindowAttachListeners == null) {
// return;
// }
// this.mOnWindowAttachListeners.remove(victim);
//}
//dispatchOnWindowAttachedChange(attached:boolean) {
// // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
// // perform the dispatching. The iterator is a safe guard against listeners that
// // could mutate the list by calling the various add/remove methods. This prevents
// // the array from being modified while we iterate it.
// let listeners = this.mOnWindowAttachListeners;
// if (listeners != null && listeners.size() > 0) {
// for (let listener of listeners) {
// if (attached) listener.onWindowAttached();
// else listener.onWindowDetached();
// }
// }
//}
/**
* Register a callback to be invoked when the global layout state or the visibility of views
* within the view tree changes
*
* @param listener The callback to add
*
* @throws IllegalStateException If {@link #isAlive()} returns false
*/
addOnGlobalLayoutListener(listener:ViewTreeObserver.OnGlobalLayoutListener) {
this.checkIsAlive();
if (this.mOnGlobalLayoutListeners == null) {
this.mOnGlobalLayoutListeners = new CopyOnWriteArray<ViewTreeObserver.OnGlobalLayoutListener>();
}
this.mOnGlobalLayoutListeners.add(listener);
}
/**
* Remove a previously installed global layout callback
*
* @param victim The callback to remove
*
* @throws IllegalStateException If {@link #isAlive()} returns false
*
* @deprecated Use #removeOnGlobalLayoutListener instead
*
* @see #addOnGlobalLayoutListener(OnGlobalLayoutListener)
*/
removeGlobalOnLayoutListener(victim:ViewTreeObserver.OnGlobalLayoutListener) {
this.removeOnGlobalLayoutListener(victim);
}
/**
* Remove a previously installed global layout callback
*
* @param victim The callback to remove
*
* @throws IllegalStateException If {@link #isAlive()} returns false
*
* @see #addOnGlobalLayoutListener(OnGlobalLayoutListener)
*/
removeOnGlobalLayoutListener(victim:ViewTreeObserver.OnGlobalLayoutListener) {
this.checkIsAlive();
if (this.mOnGlobalLayoutListeners == null) {
return;
}
this.mOnGlobalLayoutListeners.remove(victim);
}
/**
* Notifies registered listeners that a global layout happened. This can be called
* manually if you are forcing a layout on a View or a hierarchy of Views that are
* not attached to a Window or in the GONE state.
*/
dispatchOnGlobalLayout() {
// NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
// perform the dispatching. The iterator is a safe guard against listeners that
// could mutate the list by calling the various add/remove methods. This prevents
// the array from being modified while we iterate it.
let listeners = this.mOnGlobalLayoutListeners;
if (listeners != null && listeners.size() > 0) {
let access = listeners.start();
try {
let count = access.length;
for (let i = 0; i < count; i++) {
access[i].onGlobalLayout();
}
} finally {
listeners.end();
}
}
}
//addOnGlobalFocusChangeListener(listener:ViewTreeObserver.OnGlobalFocusChangeListener) {
// this.checkIsAlive();
//
// if (this.mOnGlobalFocusListeners == null) {
// this.mOnGlobalFocusListeners = new CopyOnWriteArrayList<ViewTreeObserver.OnGlobalFocusChangeListener>();
// }
//
// this.mOnGlobalFocusListeners.add(listener);
//}
//removeOnGlobalFocusChangeListener(victim:ViewTreeObserver.OnGlobalFocusChangeListener) {
// this.checkIsAlive();
// if (this.mOnGlobalFocusListeners == null) {
// return;
// }
// this.mOnGlobalFocusListeners.remove(victim);
//}
//
//dispatchOnGlobalFocusChange(oldFocus:android.view.View, newFocus:android.view.View) {
// // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
// // perform the dispatching. The iterator is a safe guard against listeners that
// // could mutate the list by calling the various add/remove methods. This prevents
// // the array from being modified while we iterate it.
// const listeners = this.mOnGlobalFocusListeners;
// if (listeners != null && listeners.size() > 0) {
// for (let listener of listeners) {
// listener.onGlobalFocusChanged(oldFocus, newFocus);
// }
// }
//}
/**
* Register a callback to be invoked when the view tree is about to be drawn
*
* @param listener The callback to add
*
* @throws IllegalStateException If {@link #isAlive()} returns false
*/
addOnPreDrawListener(listener:ViewTreeObserver.OnPreDrawListener) {
this.checkIsAlive();
if (this.mOnPreDrawListeners == null) {
this.mOnPreDrawListeners = new CopyOnWriteArray<ViewTreeObserver.OnPreDrawListener>();
}
this.mOnPreDrawListeners.add(listener);
}
/**
* Remove a previously installed pre-draw callback
*
* @param victim The callback to remove
*
* @throws IllegalStateException If {@link #isAlive()} returns false
*
* @see #addOnPreDrawListener(OnPreDrawListener)
*/
removeOnPreDrawListener(victim:ViewTreeObserver.OnPreDrawListener) {
this.checkIsAlive();
if (this.mOnPreDrawListeners == null) {
return;
}
this.mOnPreDrawListeners.remove(victim);
}
/**
* Notifies registered listeners that the drawing pass is about to start. If a
* listener returns true, then the drawing pass is canceled and rescheduled. This can
* be called manually if you are forcing the drawing on a View or a hierarchy of Views
* that are not attached to a Window or in the GONE state.
*
* @return True if the current draw should be canceled and resceduled, false otherwise.
*/
dispatchOnPreDraw():boolean {
let cancelDraw = false;
const listeners = this.mOnPreDrawListeners;
if (listeners != null && listeners.size() > 0) {
let access = listeners.start();
try {
let count = access.length;
for (let i = 0; i < count; i++) {
cancelDraw = cancelDraw || !(access[i].onPreDraw());
}
} finally {
listeners.end();
}
}
return cancelDraw;
}
/**
* Register a callback to be invoked when the invoked when the touch mode changes.
*
* @param listener The callback to add
*
* @throws IllegalStateException If {@link #isAlive()} returns false
*/
addOnTouchModeChangeListener(listener:ViewTreeObserver.OnTouchModeChangeListener) {
this.checkIsAlive();
if (this.mOnTouchModeChangeListeners == null) {
this.mOnTouchModeChangeListeners = new CopyOnWriteArrayList<ViewTreeObserver.OnTouchModeChangeListener>();
}
this.mOnTouchModeChangeListeners.add(listener);
}
/**
* Remove a previously installed touch mode change callback
*
* @param victim The callback to remove
*
* @throws IllegalStateException If {@link #isAlive()} returns false
*
* @see #addOnTouchModeChangeListener(OnTouchModeChangeListener)
*/
removeOnTouchModeChangeListener(victim:ViewTreeObserver.OnTouchModeChangeListener) {
this.checkIsAlive();
if (this.mOnTouchModeChangeListeners == null) {
return;
}
this.mOnTouchModeChangeListeners.remove(victim);
}
/**
* Notifies registered listeners that the touch mode has changed.
*
* @param inTouchMode True if the touch mode is now enabled, false otherwise.
*/
dispatchOnTouchModeChanged(inTouchMode:boolean) {
const listeners = this.mOnTouchModeChangeListeners;
if (listeners != null && listeners.size() > 0) {
for (let listener of listeners) {
listener.onTouchModeChanged(inTouchMode);
}
}
}
/**
* Register a callback to be invoked when a view has been scrolled.
*
* @param listener The callback to add
*
* @throws IllegalStateException If {@link #isAlive()} returns false
*/
addOnScrollChangedListener(listener:ViewTreeObserver.OnScrollChangedListener) {
this.checkIsAlive();
if (this.mOnScrollChangedListeners == null) {
this.mOnScrollChangedListeners = new CopyOnWriteArray<ViewTreeObserver.OnScrollChangedListener>();
}
this.mOnScrollChangedListeners.add(listener);
}
/**
* Remove a previously installed scroll-changed callback
*
* @param victim The callback to remove
*
* @throws IllegalStateException If {@link #isAlive()} returns false
*
* @see #addOnScrollChangedListener(OnScrollChangedListener)
*/
removeOnScrollChangedListener(victim:ViewTreeObserver.OnScrollChangedListener) {
this.checkIsAlive();
if (this.mOnScrollChangedListeners == null) {
return;
}
this.mOnScrollChangedListeners.remove(victim);
}
/**
* Notifies registered listeners that something has scrolled.
*/
dispatchOnScrollChanged():void {
let listeners = this.mOnScrollChangedListeners;
if (listeners != null && listeners.size() > 0) {
let access = listeners.start();
try {
let count = access.length;
for (let i = 0; i < count; i++) {
access[i].onScrollChanged();
}
} finally {
listeners.end();
}
}
}
/**
* <p>Register a callback to be invoked when the view tree is about to be drawn.</p>
* <p><strong>Note:</strong> this method <strong>cannot</strong> be invoked from
* {@link android.view.ViewTreeObserver.OnDrawListener#onDraw()}.</p>
*
* @param listener The callback to add
*
* @throws IllegalStateException If {@link #isAlive()} returns false
*/
addOnDrawListener(listener:ViewTreeObserver.OnDrawListener) {
this.checkIsAlive();
if (this.mOnDrawListeners == null) {
this.mOnDrawListeners = new CopyOnWriteArrayList<ViewTreeObserver.OnDrawListener>();
}
this.mOnDrawListeners.add(listener);
}
/**
* <p>Remove a previously installed pre-draw callback.</p>
* <p><strong>Note:</strong> this method <strong>cannot</strong> be invoked from
* {@link android.view.ViewTreeObserver.OnDrawListener#onDraw()}.</p>
*
* @param victim The callback to remove
*
* @throws IllegalStateException If {@link #isAlive()} returns false
*
* @see #addOnDrawListener(OnDrawListener)
*/
removeOnDrawListener(victim:ViewTreeObserver.OnDrawListener) {
this.checkIsAlive();
if (this.mOnDrawListeners == null) {
return;
}
this.mOnDrawListeners.remove(victim);
}
/**
* Notifies registered listeners that the drawing pass is about to start.
*/
dispatchOnDraw():void {
if (this.mOnDrawListeners != null) {
for (let listener of this.mOnDrawListeners) {
listener.onDraw();
}
}
}
/**
* Merges all the listeners registered on the specified observer with the listeners
* registered on this object. After this method is invoked, the specified observer
* will return false in {@link #isAlive()} and should not be used anymore.
*
* @param observer The ViewTreeObserver whose listeners must be added to this observer
*/
merge(observer:ViewTreeObserver){
//if (observer.mOnWindowAttachListeners != null) {
// if (this.mOnWindowAttachListeners != null) {
// this.mOnWindowAttachListeners.addAll(observer.mOnWindowAttachListeners);
// } else {
// this.mOnWindowAttachListeners = observer.mOnWindowAttachListeners;
// }
//}
//if (observer.mOnWindowFocusListeners != null) {
// if (this.mOnWindowFocusListeners != null) {
// this.mOnWindowFocusListeners.addAll(observer.mOnWindowFocusListeners);
// } else {
// this.mOnWindowFocusListeners = observer.mOnWindowFocusListeners;
// }
//}
//
//if (observer.mOnGlobalFocusListeners != null) {
// if (this.mOnGlobalFocusListeners != null) {
// this.mOnGlobalFocusListeners.addAll(observer.mOnGlobalFocusListeners);
// } else {
// this.mOnGlobalFocusListeners = observer.mOnGlobalFocusListeners;
// }
//}
if (observer.mOnGlobalLayoutListeners != null) {
if (this.mOnGlobalLayoutListeners != null) {
this.mOnGlobalLayoutListeners.addAll(observer.mOnGlobalLayoutListeners);
} else {
this.mOnGlobalLayoutListeners = observer.mOnGlobalLayoutListeners;
}
}
if (observer.mOnPreDrawListeners != null) {
if (this.mOnPreDrawListeners != null) {
this.mOnPreDrawListeners.addAll(observer.mOnPreDrawListeners);
} else {
this.mOnPreDrawListeners = observer.mOnPreDrawListeners;
}
}
//if (observer.mOnTouchModeChangeListeners != null) {
// if (this.mOnTouchModeChangeListeners != null) {
// this.mOnTouchModeChangeListeners.addAll(observer.mOnTouchModeChangeListeners);
// } else {
// this.mOnTouchModeChangeListeners = observer.mOnTouchModeChangeListeners;
// }
//}
//
//if (observer.mOnComputeInternalInsetsListeners != null) {
// if (this.mOnComputeInternalInsetsListeners != null) {
// this.mOnComputeInternalInsetsListeners.addAll(observer.mOnComputeInternalInsetsListeners);
// } else {
// this.mOnComputeInternalInsetsListeners = observer.mOnComputeInternalInsetsListeners;
// }
//}
if (observer.mOnScrollChangedListeners != null) {
if (this.mOnScrollChangedListeners != null) {
this.mOnScrollChangedListeners.addAll(observer.mOnScrollChangedListeners);
} else {
this.mOnScrollChangedListeners = observer.mOnScrollChangedListeners;
}
}
observer.kill();
}
private checkIsAlive() {
if (!this.mAlive) {
throw new Error("This ViewTreeObserver is not alive, call "
+ "getViewTreeObserver() again");
}
}
/**
* Indicates whether this ViewTreeObserver is alive. When an observer is not alive,
* any call to a method (except this one) will throw an exception.
*
* If an application keeps a long-lived reference to this ViewTreeObserver, it should
* always check for the result of this method before calling any other method.
*
* @return True if this object is alive and be used, false otherwise.
*/
isAlive():boolean {
return this.mAlive;
}
private kill() {
this.mAlive = false;
}
}
export module ViewTreeObserver {
//export interface OnWindowAttachListener {
// onWindowAttached();
// onWindowDetached();
//}
/**
* Interface definition for a callback to be invoked when the focus state within
* the view tree changes.
*/
export interface OnGlobalFocusChangeListener {
/**
* Callback method to be invoked when the focus changes in the view tree. When
* the view tree transitions from touch mode to non-touch mode, oldFocus is null.
* When the view tree transitions from non-touch mode to touch mode, newFocus is
* null. When focus changes in non-touch mode (without transition from or to
* touch mode) either oldFocus or newFocus can be null.
*
* @param oldFocus The previously focused view, if any.
* @param newFocus The newly focused View, if any.
*/
onGlobalFocusChanged(oldFocus:android.view.View, newFocus:android.view.View);
}
/**
* Interface definition for a callback to be invoked when the global layout state
* or the visibility of views within the view tree changes.
*/
export interface OnGlobalLayoutListener {
/**
* Callback method to be invoked when the global layout state or the visibility of views
* within the view tree changes
*/
onGlobalLayout();
}
/**
* Interface definition for a callback to be invoked when the view tree is about to be drawn.
*/
export interface OnPreDrawListener {
/**
* Callback method to be invoked when the view tree is about to be drawn. At this point, all
* views in the tree have been measured and given a frame. Clients can use this to adjust
* their scroll bounds or even to request a new layout before drawing occurs.
*
* @return Return true to proceed with the current drawing pass, or false to cancel.
*
* @see android.view.View#onMeasure
* @see android.view.View#onLayout
* @see android.view.View#onDraw
*/
onPreDraw():boolean;
}
/**
* Interface definition for a callback to be invoked when the view tree is about to be drawn.
*/
export interface OnDrawListener {
/**
* <p>Callback method to be invoked when the view tree is about to be drawn. At this point,
* views cannot be modified in any way.</p>
*
* <p>Unlike with {@link OnPreDrawListener}, this method cannot be used to cancel the
* current drawing pass.</p>
*
* <p>An {@link OnDrawListener} listener <strong>cannot be added or removed</strong>
* from this method.</p>
*
* @see android.view.View#onMeasure
* @see android.view.View#onLayout
* @see android.view.View#onDraw
*/
onDraw();
}
/**
* Interface definition for a callback to be invoked when
* something in the view tree has been scrolled.
*/
export interface OnScrollChangedListener {
/**
* Callback method to be invoked when something in the view tree
* has been scrolled.
*/
onScrollChanged();
}
/**
* Interface definition for a callback to be invoked when the touch mode changes.
*/
export interface OnTouchModeChangeListener {
/**
* Callback method to be invoked when the touch mode changes.
*
* @param isInTouchMode True if the view hierarchy is now in touch mode, false otherwise.
*/
onTouchModeChanged(isInTouchMode:boolean);
}
}
} | the_stack |
import ts from 'typescript';
import {LitClassContext} from './lit-class-context.js';
import {LitFileContext} from './lit-file-context.js';
import {isStatic} from './util.js';
import type {
Visitor,
ClassDecoratorVisitor,
MemberDecoratorVisitor,
GenericVisitor,
} from './visitor.js';
/**
* A transformer for Lit code.
*
* Configured with an array of visitors, each of which handles a specific Lit
* feature such as a decorator. All visitors are invoked from a single pass
* through each file.
*
* Files are only traversed at all if there is at least one feature imported
* from an official Lit module (e.g. the "property" decorator), and there is a
* registered visitor that declares it will handle that feature (e.g. the
* PropertyVisitor).
*/
export class LitTransformer {
private readonly _context: ts.TransformationContext;
private readonly _classDecoratorVisitors = new Map<
string,
ClassDecoratorVisitor
>();
private readonly _memberDecoratorVisitors = new Map<
string,
MemberDecoratorVisitor
>();
private readonly _genericVisitors = new Set<GenericVisitor>();
private readonly _litFileContext: LitFileContext;
constructor(
program: ts.Program,
context: ts.TransformationContext,
visitors: Array<Visitor>
) {
this._context = context;
this._litFileContext = new LitFileContext(program);
for (const visitor of visitors) {
this._registerVisitor(visitor);
}
}
private _registerVisitor(visitor: Visitor) {
switch (visitor.kind) {
case 'classDecorator': {
if (this._classDecoratorVisitors.has(visitor.decoratorName)) {
throw new Error(
'Registered more than one transformer for class decorator' +
visitor.decoratorName
);
}
this._classDecoratorVisitors.set(visitor.decoratorName, visitor);
break;
}
case 'memberDecorator': {
if (this._classDecoratorVisitors.has(visitor.decoratorName)) {
throw new Error(
'Registered more than one transformer for member decorator ' +
visitor.decoratorName
);
}
this._memberDecoratorVisitors.set(visitor.decoratorName, visitor);
break;
}
case 'generic': {
this._genericVisitors.add(visitor);
break;
}
default: {
throw new Error(
`Internal error: registering unknown visitor kind ${
(visitor as void as unknown as Visitor).kind
}`
);
}
}
}
private _unregisterVisitor(visitor: Visitor) {
switch (visitor.kind) {
case 'classDecorator': {
this._classDecoratorVisitors.delete(visitor.decoratorName);
break;
}
case 'memberDecorator': {
this._memberDecoratorVisitors.delete(visitor.decoratorName);
break;
}
case 'generic': {
this._genericVisitors.delete(visitor);
break;
}
default: {
throw new Error(
`Internal error: unregistering unknown visitor kind ${
(visitor as void as unknown as Visitor).kind
}`
);
}
}
}
visitFile = (node: ts.Node): ts.VisitResult<ts.Node> => {
if (!ts.isSourceFile(node)) {
return node;
}
let traversalNeeded = false;
for (const statement of node.statements) {
if (ts.isImportDeclaration(statement)) {
if (this._updateFileContextWithLitImports(statement)) {
// Careful with short-circuiting here! We must run
// `_updateFileContextWithLitImports` on every import statement, even
// if we already know we need a traversal.
traversalNeeded = true;
}
}
}
if (!traversalNeeded) {
// No relevant transforms could apply, we can ignore this file.
return node;
}
node = ts.visitEachChild(node, this.visit, this._context);
this._litFileContext.clear();
return node;
};
visit = (node: ts.Node): ts.VisitResult<ts.Node> => {
if (this._litFileContext.nodeReplacements.has(node)) {
// A node that some previous visitor has requested to be replaced.
return this._litFileContext.nodeReplacements.get(node);
}
for (const visitor of this._genericVisitors) {
node = visitor.visit(this._litFileContext, node);
}
if (ts.isImportDeclaration(node)) {
return this._visitImportDeclaration(node);
}
if (ts.isClassDeclaration(node)) {
return this._visitClassDeclaration(node);
}
return this._cleanUpDecoratorCruft(
ts.visitEachChild(node, this.visit, this._context)
);
};
/**
* Add an entry to our "litImports" map for each relevant imported symbol, if
* this is an import from an official Lit package. Returns whether or not
* anything relevant was found.
*/
private _updateFileContextWithLitImports(
node: ts.ImportDeclaration
): boolean {
// TODO(aomarks) Support re-exports (e.g. if a user re-exports a Lit
// decorator from one of their own modules).
if (!ts.isStringLiteral(node.moduleSpecifier)) {
return false;
}
const specifier = node.moduleSpecifier.text;
// We're only interested in imports from one of the official lit packages.
if (!isLitImport(specifier)) {
return false;
}
if (!hasJsExtensionOrIsDefaultModule(specifier)) {
// Note there is no way to properly surface a TypeScript diagnostic during
// transform: https://github.com/Microsoft/TypeScript/issues/19615.
throw new Error(
stringifyDiagnostics([
createDiagnostic(
node.getSourceFile(),
node.moduleSpecifier,
`Invalid Lit import style. Did you mean '${specifier}.js'?`
),
])
);
}
// TODO(aomarks) Maybe handle NamespaceImport (import * as decorators).
const bindings = node.importClause?.namedBindings;
if (bindings == undefined || !ts.isNamedImports(bindings)) {
return false;
}
let traversalNeeded = false;
for (const importSpecifier of bindings.elements) {
// Name as exported (Lit's name for it, not whatever the alias is).
const realName =
importSpecifier.propertyName?.text ?? importSpecifier.name.text;
if (realName === 'html') {
this._litFileContext.litImports.set(importSpecifier, realName);
// TODO(aomarks) We don't set traversalNeeded for the html tag import,
// because we don't currently have any transforms that aren't already
// associated with a decorator. If that changed, visitors should
// probably have a static field to declare which imports they care
// about.
} else {
// Only handle the decorators we're configured to transform.
const visitor =
this._classDecoratorVisitors.get(realName) ??
this._memberDecoratorVisitors.get(realName);
if (visitor !== undefined) {
this._litFileContext.litImports.set(importSpecifier, realName);
// Either remove the binding or replace it with another identifier.
const replacement = visitor.importBindingReplacement
? this._context.factory.createIdentifier(
visitor.importBindingReplacement
)
: undefined;
this._litFileContext.nodeReplacements.set(
importSpecifier,
replacement
);
traversalNeeded = true;
}
}
}
return traversalNeeded;
}
private _visitImportDeclaration(node: ts.ImportDeclaration) {
const numBindingsBefore =
(node.importClause?.namedBindings as ts.NamedImports | undefined)
?.elements?.length ?? 0;
node = ts.visitEachChild(node, this.visit, this._context);
const numBindingsAfter =
(node.importClause?.namedBindings as ts.NamedImports | undefined)
?.elements?.length ?? 0;
if (
numBindingsAfter === 0 &&
numBindingsBefore !== numBindingsAfter &&
ts.isStringLiteral(node.moduleSpecifier) &&
isLitImport(node.moduleSpecifier.text)
) {
// Remove the import altogether if there are no bindings left. But only if
// we acutally modified the import, and it's from an official Lit module.
// Otherwise we might remove imports that are still needed for their
// side-effects.
return undefined;
}
return node;
}
private _visitClassDeclaration(class_: ts.ClassDeclaration) {
const litClassContext = new LitClassContext(this._litFileContext, class_);
// Class decorators
for (const decorator of class_.decorators ?? []) {
if (!ts.isCallExpression(decorator.expression)) {
continue;
}
const decoratorName = this._litFileContext.getCanonicalName(
decorator.expression.expression
);
if (decoratorName === undefined) {
continue;
}
this._classDecoratorVisitors
.get(decoratorName)
?.visit(litClassContext, decorator);
}
// Class member decorators
for (const member of class_.members ?? []) {
for (const decorator of member.decorators ?? []) {
if (!ts.isCallExpression(decorator.expression)) {
continue;
}
const decoratorName = this._litFileContext.getCanonicalName(
decorator.expression.expression
);
if (decoratorName === undefined) {
continue;
}
this._memberDecoratorVisitors
.get(decoratorName)
?.visit(litClassContext, member, decorator);
}
}
if (litClassContext.reactiveProperties.length > 0) {
const oldProperties =
this._findExistingStaticPropertiesExpression(class_);
const newProperties = this._createStaticPropertiesExpression(
oldProperties,
litClassContext.reactiveProperties
);
if (oldProperties !== undefined) {
this._litFileContext.nodeReplacements.set(oldProperties, newProperties);
} else {
const factory = this._context.factory;
const staticPropertiesField = factory.createPropertyDeclaration(
undefined,
[factory.createModifier(ts.SyntaxKind.StaticKeyword)],
factory.createIdentifier('properties'),
undefined,
undefined,
newProperties
);
litClassContext.classMembers.unshift(staticPropertiesField);
}
}
this._addExtraConstructorStatements(litClassContext);
for (const visitor of litClassContext.additionalClassVisitors) {
this._registerVisitor(visitor);
}
// Note we do need to `ts.visitEachChild` here, because [1] there might be
// nodes that still need to be deleted via `this._nodesToRemove` (e.g. a
// property decorator or a property itself), and [2] in theory there could
// be a nested custom element definition somewhere in this class.
const transformedClass = this._cleanUpDecoratorCruft(
ts.visitEachChild(
this._context.factory.updateClassDeclaration(
class_,
class_.decorators,
class_.modifiers,
class_.name,
class_.typeParameters,
class_.heritageClauses,
[...litClassContext.classMembers, ...class_.members]
),
this.visit,
this._context
)
);
// These visitors only apply within the scope of the current class.
for (const visitor of litClassContext.additionalClassVisitors) {
this._unregisterVisitor(visitor);
}
return [transformedClass, ...litClassContext.adjacentStatements];
}
/**
* Create the AST from e.g. `@property({type: String}) myProperty`:
*
* static get properties() {
* return {
* myProperty: { type: String },
* ...
* }
* }
*/
private _createStaticPropertiesExpression(
existingProperties: ts.ObjectLiteralExpression | undefined,
newProperties: Array<{
name: string;
options?: ts.ObjectLiteralExpression;
}>
) {
const factory = this._context.factory;
const properties = [
...(existingProperties?.properties ?? []),
...newProperties.map(({name, options}) =>
factory.createPropertyAssignment(
factory.createIdentifier(name),
options ? options : factory.createObjectLiteralExpression([], false)
)
),
];
return factory.createObjectLiteralExpression(properties, true);
}
private _findExistingStaticPropertiesExpression(
class_: ts.ClassDeclaration
): ts.ObjectLiteralExpression | undefined {
const staticProperties = class_.members.find(
(member) =>
isStatic(member) &&
member.name !== undefined &&
ts.isIdentifier(member.name) &&
member.name.text === 'properties'
);
if (staticProperties === undefined) {
return undefined;
}
// Static class field.
if (ts.isPropertyDeclaration(staticProperties)) {
if (
staticProperties.initializer !== undefined &&
ts.isObjectLiteralExpression(staticProperties.initializer)
) {
return staticProperties.initializer;
} else {
throw new Error(
'Static properties class field initializer must be an object expression.'
);
}
}
// Static getter.
if (ts.isGetAccessorDeclaration(staticProperties)) {
const returnStatement = staticProperties.body?.statements[0];
if (
returnStatement === undefined ||
!ts.isReturnStatement(returnStatement)
) {
throw new Error(
'Static properties getter must contain purely a return statement.'
);
}
const returnExpression = returnStatement.expression;
if (
returnExpression === undefined ||
!ts.isObjectLiteralExpression(returnExpression)
) {
throw new Error(
'Static properties getter must return an object expression.'
);
}
return returnExpression;
}
throw new Error(
'Static properties class member must be a class field or getter.'
);
}
/**
* Create or modify a class constructor to add additional constructor
* statements from any of our transforms.
*/
private _addExtraConstructorStatements(context: LitClassContext) {
if (context.extraConstructorStatements.length === 0) {
return;
}
const existingCtor = context.class.members.find(
ts.isConstructorDeclaration
);
const factory = this._context.factory;
if (existingCtor === undefined) {
const newCtor = factory.createConstructorDeclaration(
undefined,
undefined,
[],
factory.createBlock(
[
factory.createExpressionStatement(
factory.createCallExpression(factory.createSuper(), undefined, [
factory.createSpreadElement(
factory.createIdentifier('arguments')
),
])
),
...context.extraConstructorStatements,
],
true
)
);
context.classMembers.push(newCtor);
} else {
if (existingCtor.body === undefined) {
throw new Error('Unexpected error: constructor has no body');
}
const newCtorBody = factory.createBlock([
...existingCtor.body.statements,
...context.extraConstructorStatements,
]);
context.litFileContext.nodeReplacements.set(
existingCtor.body,
newCtorBody
);
}
}
/**
* TypeScript will sometimes emit no-op decorator transform cruft like this ...
*
* MyElement = __decorate([], MyElement)
*
* ... when a class or method's decorators field is an empty array, as opposed
* to undefined, due to conditionals in the decorator transform like `if
* (node.decorators) {...}`. If we've removed all decorators for a node, reset
* the decorators field to undefined so that we get clean output instead.
*/
private _cleanUpDecoratorCruft(node: ts.Node) {
if (node.decorators === undefined || node.decorators.length > 0) {
return node;
}
if (ts.isClassDeclaration(node)) {
return this._context.factory.updateClassDeclaration(
node,
/* decorators */ undefined,
node.modifiers,
node.name,
node.typeParameters,
node.heritageClauses,
node.members
);
}
if (ts.isMethodDeclaration(node)) {
return this._context.factory.updateMethodDeclaration(
node,
/* decorators */ undefined,
node.modifiers,
node.asteriskToken,
node.name,
node.questionToken,
node.typeParameters,
node.parameters,
node.type,
node.body
);
}
return node;
}
}
const isLitImport = (specifier: string) =>
specifier === 'lit' ||
specifier.startsWith('lit/') ||
specifier === 'lit-element' ||
specifier.startsWith('lit-element/') ||
specifier.startsWith('@lit/');
/**
* Returns true for:
* lit
* lit/decorators.js
* @lit/reactive-element
* @lit/reactive-element/decorators.js
*
* Returns false for:
* lit/decorators
* @lit/reactive-element/decorators
*/
const hasJsExtensionOrIsDefaultModule = (specifier: string) =>
specifier.endsWith('.js') || /^(@[^/]+\/)?[^/]+$/.test(specifier);
const createDiagnostic = (
file: ts.SourceFile,
node: ts.Node,
message: string,
relatedInformation?: ts.DiagnosticRelatedInformation[]
): ts.DiagnosticWithLocation => {
return {
file,
start: node.getStart(file),
length: node.getWidth(file),
category: ts.DiagnosticCategory.Error,
code: 2325, // Meaningless but unique number.
messageText: message,
relatedInformation,
};
};
const stringifyDiagnostics = (diagnostics: ts.Diagnostic[]) => {
return ts.formatDiagnosticsWithColorAndContext(diagnostics, {
getCanonicalFileName(name: string) {
return name;
},
getCurrentDirectory() {
return process.cwd();
},
getNewLine() {
return '\n';
},
});
}; | the_stack |
import * as msRest from "@azure/ms-rest-js";
export const TrainSourceFilter: msRest.CompositeMapper = {
serializedName: "TrainSourceFilter",
type: {
name: "Composite",
className: "TrainSourceFilter",
modelProperties: {
prefix: {
serializedName: "prefix",
constraints: {
MaxLength: 128,
MinLength: 0
},
type: {
name: "String"
}
},
includeSubFolders: {
serializedName: "includeSubFolders",
type: {
name: "Boolean"
}
}
}
}
};
export const TrainRequest: msRest.CompositeMapper = {
serializedName: "TrainRequest",
type: {
name: "Composite",
className: "TrainRequest",
modelProperties: {
source: {
required: true,
serializedName: "source",
constraints: {
MaxLength: 2048,
MinLength: 0
},
type: {
name: "String"
}
},
sourceFilter: {
serializedName: "sourceFilter",
type: {
name: "Composite",
className: "TrainSourceFilter"
}
}
}
}
};
export const FormDocumentReport: msRest.CompositeMapper = {
serializedName: "FormDocumentReport",
type: {
name: "Composite",
className: "FormDocumentReport",
modelProperties: {
documentName: {
serializedName: "documentName",
type: {
name: "String"
}
},
pages: {
serializedName: "pages",
type: {
name: "Number"
}
},
errors: {
serializedName: "errors",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
},
status: {
serializedName: "status",
type: {
name: "String"
}
}
}
}
};
export const FormOperationError: msRest.CompositeMapper = {
serializedName: "FormOperationError",
type: {
name: "Composite",
className: "FormOperationError",
modelProperties: {
errorMessage: {
serializedName: "errorMessage",
type: {
name: "String"
}
}
}
}
};
export const TrainResult: msRest.CompositeMapper = {
serializedName: "TrainResult",
type: {
name: "Composite",
className: "TrainResult",
modelProperties: {
modelId: {
nullable: false,
serializedName: "modelId",
type: {
name: "Uuid"
}
},
trainingDocuments: {
serializedName: "trainingDocuments",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "FormDocumentReport"
}
}
}
},
errors: {
serializedName: "errors",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "FormOperationError"
}
}
}
}
}
}
};
export const KeysResult: msRest.CompositeMapper = {
serializedName: "KeysResult",
type: {
name: "Composite",
className: "KeysResult",
modelProperties: {
clusters: {
serializedName: "clusters",
type: {
name: "Dictionary",
value: {
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
}
}
}
}
}
};
export const ModelResult: msRest.CompositeMapper = {
serializedName: "ModelResult",
type: {
name: "Composite",
className: "ModelResult",
modelProperties: {
modelId: {
nullable: false,
serializedName: "modelId",
type: {
name: "Uuid"
}
},
status: {
serializedName: "status",
type: {
name: "String"
}
},
createdDateTime: {
serializedName: "createdDateTime",
type: {
name: "DateTime"
}
},
lastUpdatedDateTime: {
serializedName: "lastUpdatedDateTime",
type: {
name: "DateTime"
}
}
}
}
};
export const ModelsResult: msRest.CompositeMapper = {
serializedName: "ModelsResult",
type: {
name: "Composite",
className: "ModelsResult",
modelProperties: {
modelsProperty: {
serializedName: "models",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ModelResult"
}
}
}
}
}
}
};
export const InnerError: msRest.CompositeMapper = {
serializedName: "InnerError",
type: {
name: "Composite",
className: "InnerError",
modelProperties: {
requestId: {
serializedName: "requestId",
type: {
name: "String"
}
}
}
}
};
export const ErrorInformation: msRest.CompositeMapper = {
serializedName: "ErrorInformation",
type: {
name: "Composite",
className: "ErrorInformation",
modelProperties: {
code: {
serializedName: "code",
type: {
name: "String"
}
},
innerError: {
serializedName: "innerError",
type: {
name: "Composite",
className: "InnerError"
}
},
message: {
serializedName: "message",
type: {
name: "String"
}
}
}
}
};
export const ErrorResponse: msRest.CompositeMapper = {
serializedName: "ErrorResponse",
type: {
name: "Composite",
className: "ErrorResponse",
modelProperties: {
error: {
serializedName: "error",
type: {
name: "Composite",
className: "ErrorInformation"
}
}
}
}
};
export const ExtractedToken: msRest.CompositeMapper = {
serializedName: "ExtractedToken",
type: {
name: "Composite",
className: "ExtractedToken",
modelProperties: {
text: {
serializedName: "text",
type: {
name: "String"
}
},
boundingBox: {
serializedName: "boundingBox",
type: {
name: "Sequence",
element: {
type: {
name: "Number"
}
}
}
},
confidence: {
serializedName: "confidence",
type: {
name: "Number"
}
}
}
}
};
export const ExtractedKeyValuePair: msRest.CompositeMapper = {
serializedName: "ExtractedKeyValuePair",
type: {
name: "Composite",
className: "ExtractedKeyValuePair",
modelProperties: {
key: {
serializedName: "key",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ExtractedToken"
}
}
}
},
value: {
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ExtractedToken"
}
}
}
}
}
}
};
export const ExtractedTableColumn: msRest.CompositeMapper = {
serializedName: "ExtractedTableColumn",
type: {
name: "Composite",
className: "ExtractedTableColumn",
modelProperties: {
header: {
serializedName: "header",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ExtractedToken"
}
}
}
},
entries: {
serializedName: "entries",
type: {
name: "Sequence",
element: {
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ExtractedToken"
}
}
}
}
}
}
}
}
};
export const ExtractedTable: msRest.CompositeMapper = {
serializedName: "ExtractedTable",
type: {
name: "Composite",
className: "ExtractedTable",
modelProperties: {
id: {
serializedName: "id",
type: {
name: "String"
}
},
columns: {
serializedName: "columns",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ExtractedTableColumn"
}
}
}
}
}
}
};
export const ExtractedPage: msRest.CompositeMapper = {
serializedName: "ExtractedPage",
type: {
name: "Composite",
className: "ExtractedPage",
modelProperties: {
number: {
serializedName: "number",
type: {
name: "Number"
}
},
height: {
serializedName: "height",
type: {
name: "Number"
}
},
width: {
serializedName: "width",
type: {
name: "Number"
}
},
clusterId: {
serializedName: "clusterId",
type: {
name: "Number"
}
},
keyValuePairs: {
serializedName: "keyValuePairs",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ExtractedKeyValuePair"
}
}
}
},
tables: {
serializedName: "tables",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ExtractedTable"
}
}
}
}
}
}
};
export const AnalyzeResult: msRest.CompositeMapper = {
serializedName: "AnalyzeResult",
type: {
name: "Composite",
className: "AnalyzeResult",
modelProperties: {
status: {
serializedName: "status",
type: {
name: "String"
}
},
pages: {
serializedName: "pages",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ExtractedPage"
}
}
}
},
errors: {
serializedName: "errors",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "FormOperationError"
}
}
}
}
}
}
};
export const Word: msRest.CompositeMapper = {
serializedName: "Word",
type: {
name: "Composite",
className: "Word",
modelProperties: {
boundingBox: {
required: true,
serializedName: "boundingBox",
type: {
name: "Sequence",
element: {
type: {
name: "Number"
}
}
}
},
text: {
required: true,
serializedName: "text",
type: {
name: "String"
}
},
confidence: {
nullable: true,
serializedName: "confidence",
type: {
name: "Enum",
allowedValues: [
"High",
"Low"
]
}
}
}
}
};
export const Line: msRest.CompositeMapper = {
serializedName: "Line",
type: {
name: "Composite",
className: "Line",
modelProperties: {
boundingBox: {
serializedName: "boundingBox",
type: {
name: "Sequence",
element: {
type: {
name: "Number"
}
}
}
},
text: {
serializedName: "text",
type: {
name: "String"
}
},
words: {
serializedName: "words",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Word"
}
}
}
}
}
}
};
export const TextRecognitionResult: msRest.CompositeMapper = {
serializedName: "TextRecognitionResult",
type: {
name: "Composite",
className: "TextRecognitionResult",
modelProperties: {
page: {
serializedName: "page",
type: {
name: "Number"
}
},
clockwiseOrientation: {
serializedName: "clockwiseOrientation",
type: {
name: "Number"
}
},
width: {
serializedName: "width",
type: {
name: "Number"
}
},
height: {
serializedName: "height",
type: {
name: "Number"
}
},
unit: {
nullable: true,
serializedName: "unit",
type: {
name: "Enum",
allowedValues: [
"pixel",
"inch"
]
}
},
lines: {
required: true,
serializedName: "lines",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Line"
}
}
}
}
}
}
};
export const ElementReference: msRest.CompositeMapper = {
serializedName: "elementReference",
type: {
name: "Composite",
className: "ElementReference",
modelProperties: {
ref: {
serializedName: "$ref",
type: {
name: "String"
}
}
}
}
};
export const FieldValue: msRest.CompositeMapper = {
serializedName: "fieldValue",
type: {
name: "Composite",
polymorphicDiscriminator: {
serializedName: "valueType",
clientName: "valueType"
},
uberParent: "FieldValue",
className: "FieldValue",
modelProperties: {
text: {
serializedName: "text",
type: {
name: "String"
}
},
elements: {
serializedName: "elements",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ElementReference"
}
}
}
},
valueType: {
required: true,
serializedName: "valueType",
type: {
name: "String"
}
}
}
}
};
export const UnderstandingResult: msRest.CompositeMapper = {
serializedName: "understandingResult",
type: {
name: "Composite",
className: "UnderstandingResult",
modelProperties: {
pages: {
serializedName: "pages",
type: {
name: "Sequence",
element: {
type: {
name: "Number"
}
}
}
},
fields: {
serializedName: "fields",
type: {
name: "Dictionary",
value: {
type: {
name: "Composite",
className: "FieldValue"
}
}
}
}
}
}
};
export const ReadReceiptResult: msRest.CompositeMapper = {
serializedName: "readReceiptResult",
type: {
name: "Composite",
className: "ReadReceiptResult",
modelProperties: {
status: {
nullable: false,
serializedName: "status",
type: {
name: "Enum",
allowedValues: [
"Not Started",
"Running",
"Failed",
"Succeeded"
]
}
},
recognitionResults: {
serializedName: "recognitionResults",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "TextRecognitionResult"
}
}
}
},
understandingResults: {
serializedName: "understandingResults",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "UnderstandingResult"
}
}
}
}
}
}
};
export const StringValue: msRest.CompositeMapper = {
serializedName: "stringValue",
type: {
name: "Composite",
polymorphicDiscriminator: FieldValue.type.polymorphicDiscriminator,
uberParent: "FieldValue",
className: "StringValue",
modelProperties: {
...FieldValue.type.modelProperties,
value: {
serializedName: "value",
type: {
name: "String"
}
}
}
}
};
export const NumberValue: msRest.CompositeMapper = {
serializedName: "numberValue",
type: {
name: "Composite",
polymorphicDiscriminator: FieldValue.type.polymorphicDiscriminator,
uberParent: "FieldValue",
className: "NumberValue",
modelProperties: {
...FieldValue.type.modelProperties,
value: {
serializedName: "value",
type: {
name: "Number"
}
}
}
}
};
export const ComputerVisionError: msRest.CompositeMapper = {
serializedName: "ComputerVisionError",
type: {
name: "Composite",
className: "ComputerVisionError",
modelProperties: {
code: {
required: true,
serializedName: "code",
type: {
name: "Object"
}
},
message: {
required: true,
serializedName: "message",
type: {
name: "String"
}
},
requestId: {
serializedName: "requestId",
type: {
name: "String"
}
}
}
}
};
export const ImageUrl: msRest.CompositeMapper = {
serializedName: "ImageUrl",
type: {
name: "Composite",
className: "ImageUrl",
modelProperties: {
url: {
required: true,
serializedName: "url",
type: {
name: "String"
}
}
}
}
};
export const BatchReadReceiptHeaders: msRest.CompositeMapper = {
serializedName: "batchreadreceipt-headers",
type: {
name: "Composite",
className: "BatchReadReceiptHeaders",
modelProperties: {
operationLocation: {
serializedName: "operation-location",
type: {
name: "String"
}
}
}
}
};
export const BatchReadReceiptInStreamHeaders: msRest.CompositeMapper = {
serializedName: "batchreadreceiptinstream-headers",
type: {
name: "Composite",
className: "BatchReadReceiptInStreamHeaders",
modelProperties: {
operationLocation: {
serializedName: "operation-location",
type: {
name: "String"
}
}
}
}
};
export const discriminators = {
'fieldValue' : FieldValue,
'FieldValue.stringValue' : StringValue,
'FieldValue.numberValue' : NumberValue
}; | the_stack |
import { fireEvent, render, RenderResult } from '@testing-library/vue';
import { sleep, triggerDocument } from '@/test/test-utils';
import VueSlider from './VueSlider.vue';
describe('VueSlider.vue', () => {
beforeEach(() => {
(global as any).HTMLElement.prototype.getBoundingClientRect = function () {
return {
width: 100,
height: 64,
top: 0,
left: 0,
};
};
});
describe('single slider', () => {
let harness: RenderResult;
beforeEach(() => {
harness = render(VueSlider, {
props: {
id: 'slider',
label: 'Slider label',
min: 0,
max: 100,
range: [50],
},
});
});
test('should render single slider', () => {
const { getByText, getByTestId, queryAllByTestId } = harness;
getByText('Slider label');
getByTestId('handle-slider-1');
expect(getByTestId('handle-input-slider-0')).toHaveAttribute('readonly');
expect(queryAllByTestId('handle-slider-0')).toHaveLength(0);
});
test('should move single handle to 0 and emit change event', async () => {
const { getByTestId, emitted } = harness;
const slider = getByTestId('slider');
// trigger moveStart and bind events
await fireEvent.mouseDown(slider, { clientX: 50 });
// wait for the setTimeout
await sleep(10);
// trigger moving event
triggerDocument.mousemove({ target: slider, clientX: 0 });
// trigger moving event
triggerDocument.mouseup({ target: slider, clientX: 0 });
expect(emitted().change).toEqual([[[0]]]);
});
test('should move single handle to 100 and emit change event', async () => {
const { getByTestId, emitted } = harness;
const slider = getByTestId('slider');
// trigger moveStart and bind events
await fireEvent.mouseDown(slider, { clientX: 50 });
// wait for the setTimeout
await sleep(10);
// trigger moving event
triggerDocument.mousemove({ target: slider, clientX: 200 });
// trigger moving event
triggerDocument.mouseup({ target: slider, clientX: 200 });
expect(emitted().change).toEqual([[[100]]]);
});
test('should not change max on invalid user input and not emit change event', async () => {
const { getByTestId, emitted } = harness;
const maxInput = getByTestId('handle-input-slider-1');
await fireEvent.update(maxInput, '-1');
expect(emitted().change).toBeFalsy();
await fireEvent.update(maxInput, '101');
expect(emitted().change).toBeFalsy();
});
test('should change max on valid user input and emit change event', async () => {
const { getByTestId, emitted } = harness;
const maxInput = getByTestId('handle-input-slider-1');
await fireEvent.update(maxInput, '75');
expect(emitted().change).toEqual([[[75]]]);
});
});
describe('range slider', () => {
let harness: RenderResult;
beforeEach(() => {
harness = render(VueSlider, {
props: {
id: 'slider',
label: 'Slider label',
min: 0,
max: 100,
range: [25, 75],
},
});
});
test('should render range slider', () => {
const { getByText, getByTestId } = harness;
getByText('Slider label');
getByTestId('handle-slider-0');
getByTestId('handle-slider-1');
});
test('should move left handle to 75 and emit change event', async () => {
const { getByTestId, emitted } = harness;
const slider = getByTestId('slider');
// trigger moveStart and bind events
await fireEvent.mouseDown(slider, { clientX: 1 });
// wait for the setTimeout
await sleep(10);
// trigger moving event
triggerDocument.mousemove({ target: slider, clientX: 80 });
// trigger moving event
triggerDocument.mouseup({ target: slider, clientX: 80 });
expect(emitted().change).toEqual([[[75, 75]]]);
});
test('should move right handle to 25 and emit change event', async () => {
const { getByTestId, emitted } = harness;
const slider = getByTestId('slider');
// trigger moveStart and bind events
await fireEvent.mouseDown(slider, { clientX: 100 });
// wait for the setTimeout
await sleep(10);
// trigger moving event
triggerDocument.mousemove({ target: slider, clientX: 1 });
// trigger moving event
triggerDocument.mouseup({ target: slider, clientX: 1 });
expect(emitted().change).toEqual([[[25, 25]]]);
});
test('should move left handle to the right on keyboard input and emit change event', async () => {
const { getByTestId, emitted } = harness;
const handle = getByTestId('handle-slider-0');
// focus handle to set currentSlider
await fireEvent.focus(handle);
// trigger onKeyDown
await fireEvent.keyDown(handle, { key: 'ArrowRight', code: 'ArrowRight' });
await fireEvent.keyDown(handle, { key: 'ArrowRight', code: 'ArrowRight' });
await fireEvent.keyDown(handle, { key: 'ArrowRight', code: 'ArrowRight' });
await fireEvent.keyDown(handle, { key: 'ArrowRight', code: 'ArrowRight' });
await fireEvent.keyDown(handle, { key: 'ArrowRight', code: 'ArrowRight' });
await fireEvent.keyDown(handle, { key: 'ArrowRight', code: 'ArrowRight' });
await fireEvent.keyDown(handle, { key: 'ArrowRight', code: 'ArrowRight' });
await fireEvent.keyDown(handle, { key: 'ArrowRight', code: 'ArrowRight' });
await fireEvent.keyDown(handle, { key: 'ArrowRight', code: 'ArrowRight' });
await fireEvent.keyDown(handle, { key: 'ArrowRight', code: 'ArrowRight' });
await fireEvent.keyDown(handle, { key: 'ArrowRight', code: 'ArrowRight' });
// trigger onKeyUp and emit change event
await fireEvent.keyUp(handle, { key: 'ArrowRight', code: 'ArrowRight' });
expect(emitted().change).toEqual([[[75, 75]]]);
});
test('should move left handle to the left on keyboard input and emit change event', async () => {
const { getByTestId, emitted } = harness;
const handle = getByTestId('handle-slider-0');
// focus handle to set currentSlider
await fireEvent.focus(handle);
// trigger onKeyDown
await fireEvent.keyDown(handle, { key: 'ArrowLeft', code: 'ArrowLeft' });
await fireEvent.keyDown(handle, { key: 'ArrowLeft', code: 'ArrowLeft' });
await fireEvent.keyDown(handle, { key: 'ArrowLeft', code: 'ArrowLeft' });
await fireEvent.keyDown(handle, { key: 'ArrowLeft', code: 'ArrowLeft' });
await fireEvent.keyDown(handle, { key: 'ArrowLeft', code: 'ArrowLeft' });
await fireEvent.keyDown(handle, { key: 'ArrowLeft', code: 'ArrowLeft' });
// trigger onKeyUp and emit change event
await fireEvent.keyUp(handle, { key: 'ArrowLeft', code: 'ArrowLeft' });
expect(emitted().change).toEqual([[[0, 75]]]);
});
test('should move right handle to the right on keyboard input and emit change event', async () => {
const { getByTestId, emitted } = harness;
const handle = getByTestId('handle-slider-1');
// focus handle to set currentSlider
await fireEvent.focus(handle);
// trigger onKeyDown
await fireEvent.keyDown(handle, { key: 'ArrowRight', code: 'ArrowRight' });
await fireEvent.keyDown(handle, { key: 'ArrowRight', code: 'ArrowRight' });
await fireEvent.keyDown(handle, { key: 'ArrowRight', code: 'ArrowRight' });
await fireEvent.keyDown(handle, { key: 'ArrowRight', code: 'ArrowRight' });
await fireEvent.keyDown(handle, { key: 'ArrowRight', code: 'ArrowRight' });
await fireEvent.keyDown(handle, { key: 'ArrowRight', code: 'ArrowRight' });
// trigger onKeyUp and emit change event
await fireEvent.keyUp(handle, { key: 'ArrowRight', code: 'ArrowRight' });
expect(emitted().change).toEqual([[[25, 100]]]);
});
test('should move right handle to the left on keyboard input and emit change event', async () => {
const { getByTestId, emitted } = harness;
const handle = getByTestId('handle-slider-1');
// focus handle to set currentSlider
await fireEvent.focus(handle);
// trigger onKeyDown
await fireEvent.keyDown(handle, { key: 'ArrowLeft', code: 'ArrowLeft' });
await fireEvent.keyDown(handle, { key: 'ArrowLeft', code: 'ArrowLeft' });
await fireEvent.keyDown(handle, { key: 'ArrowLeft', code: 'ArrowLeft' });
await fireEvent.keyDown(handle, { key: 'ArrowLeft', code: 'ArrowLeft' });
await fireEvent.keyDown(handle, { key: 'ArrowLeft', code: 'ArrowLeft' });
await fireEvent.keyDown(handle, { key: 'ArrowLeft', code: 'ArrowLeft' });
await fireEvent.keyDown(handle, { key: 'ArrowLeft', code: 'ArrowLeft' });
await fireEvent.keyDown(handle, { key: 'ArrowLeft', code: 'ArrowLeft' });
await fireEvent.keyDown(handle, { key: 'ArrowLeft', code: 'ArrowLeft' });
await fireEvent.keyDown(handle, { key: 'ArrowLeft', code: 'ArrowLeft' });
await fireEvent.keyDown(handle, { key: 'ArrowLeft', code: 'ArrowLeft' });
// trigger onKeyUp and emit change event
await fireEvent.keyUp(handle, { key: 'ArrowLeft', code: 'ArrowLeft' });
expect(emitted().change).toEqual([[[25, 25]]]);
});
test('should not change min on invalid user input and not emit change event', async () => {
const { getByTestId, emitted } = harness;
const maxInput = getByTestId('handle-input-slider-0');
await fireEvent.update(maxInput, '-1');
expect(emitted().change).toBeFalsy();
await fireEvent.update(maxInput, '');
expect(emitted().change).toBeFalsy();
await fireEvent.update(maxInput, '76');
expect(emitted().change).toBeFalsy();
});
test('should change min on valid user input and emit change event', async () => {
const { getByTestId, emitted } = harness;
const maxInput = getByTestId('handle-input-slider-0');
await fireEvent.update(maxInput, '24');
expect(emitted().change).toEqual([[[24, 75]]]);
});
test('should not change max on invalid user input and not emit change event', async () => {
const { getByTestId, emitted } = harness;
const maxInput = getByTestId('handle-input-slider-1');
await fireEvent.update(maxInput, '0');
expect(emitted().change).toBeFalsy();
await fireEvent.update(maxInput, '');
expect(emitted().change).toBeFalsy();
await fireEvent.update(maxInput, '101');
expect(emitted().change).toBeFalsy();
});
});
describe('disabled slider', () => {
let harness: RenderResult;
beforeEach(() => {
harness = render(VueSlider, {
props: {
id: 'slider',
label: 'Slider label',
min: 0,
max: 100,
disabled: true,
range: [25, 75],
},
});
});
test('should disable slider', async () => {
const { getByTestId, updateProps } = harness;
await updateProps({ disabled: true, range: [25, 75] });
expect(getByTestId('handle-input-slider-0')).toHaveAttribute('disabled');
expect(getByTestId('handle-input-slider-1')).toHaveAttribute('disabled');
expect(getByTestId('handle-slider-0')).toHaveAttribute('disabled');
expect(getByTestId('handle-slider-1')).toHaveAttribute('disabled');
});
test('should not be able to move handles and emit change event', async () => {
const addEventListenerSpy = jest.spyOn(document, 'addEventListener');
const { getByTestId } = harness;
const slider = getByTestId('slider');
// trigger moveStart and bind events
await fireEvent.mouseDown(slider, { clientX: 1 });
expect(addEventListenerSpy).not.toHaveBeenCalled();
});
});
describe('edge cases', () => {
let harness: RenderResult;
beforeEach(() => {
harness = render(VueSlider, {
props: {
id: 'slider',
label: 'Slider label',
min: 0,
max: 100,
range: [25, 75],
},
});
});
test('should not be able to move handles with multi-touch on touch devices and emit change event', async () => {
const addEventListenerSpy = jest.spyOn(document, 'addEventListener');
const { getByTestId } = harness;
const slider = getByTestId('slider');
// trigger moveStart and bind events
await fireEvent.touchStart(slider, { changedTouches: [{}, {}, {}] as any[] });
expect(addEventListenerSpy).not.toHaveBeenCalled();
});
});
}); | the_stack |
import * as express from 'express';
import { EventEmitter } from 'eventemitter3';
import { json as _json } from 'body-parser';
import { createHmac } from 'crypto';
import * as request from 'request';
import * as neuro from 'neuro.js';
export class MessengerBot extends EventEmitter {
PAGE_ACCESS_TOKEN: any;
VALIDATION_TOKEN: any;
APP_SECRET: any;
FB_URL: any;
app: any;
webhook: any;
intelligoClassifier: any;
/**
* @param params
* @constructor
*/
constructor(params: any) {
super();
if (!params || (params && (!params.PAGE_ACCESS_TOKEN || !params.VALIDATION_TOKEN || !params.APP_SECRET))) {
throw new Error('You need to specify an PAGE_ACCESS_TOKEN, VALIDATION_TOKEN and APP_SECRET');
}
this.PAGE_ACCESS_TOKEN = params.PAGE_ACCESS_TOKEN;
this.VALIDATION_TOKEN = params.VALIDATION_TOKEN;
this.APP_SECRET = params.APP_SECRET;
this.FB_URL = params.FB_URL || 'https://graph.facebook.com/v3.1/';
this.app = params.app || express();
this.webhook = params.webhook || '/webhook';
this.app.use(_json({ verify: this.verifyRequestSignature.bind(this) }));
this.intelligoClassifier;
}
learn(data: any) {
// Repeat multiple levels
const TextClassifier = neuro.classifiers.multilabel.BinaryRelevance.bind(0, {
binaryClassifierType: neuro.classifiers.Winnow.bind(0, { retrain_count: 10 }),
});
const WordExtractor = (input: any, features: any) => {
return input.split(' ').map((word: string | number) => {
return (features[word] = 1);
});
};
this.intelligoClassifier = new neuro.classifiers.EnhancedClassifier({
classifierType: TextClassifier,
featureExtractor: WordExtractor,
});
this.intelligoClassifier.trainBatch(data);
}
answer(question: any) {
const result = this.intelligoClassifier.classify(question);
return result;
}
initWebhook() {
/*
* Use your own validation token. Check that the token used in the Webhook
* setup is the same token used here.
*/
this.app.get(this.webhook, (req: any, res: any) => {
if (req.query['hub.mode'] === 'subscribe' && req.query['hub.verify_token'] === this.VALIDATION_TOKEN) {
console.log('Validating webhook');
res.status(200).send(req.query['hub.challenge']);
} else {
console.error('Failed validation. Make sure the validation tokens match.');
res.sendStatus(403);
}
});
/*
* All callbacks for Messenger are POST-ed. They will be sent to the same
* webhook. Be sure to subscribe your app to your page to receive callbacks
* for your page.
* https://developers.facebook.com/docs/messenger-platform/product-overview/setup#subscribe_app
*/
this.app.post(this.webhook, (req: any, res: any) => {
var data = req.body;
if (data.object === 'page') {
for (const pageEntry of data.entry) {
for (const messagingEvent of pageEntry.messaging) {
this.handleEvent(messagingEvent);
}
}
res.sendStatus(200);
}
});
}
// Iterate over each messaging event
handleEvent(event: any) {
if (event.optin) {
let optin = event.optin.ref;
this.emit('optin', event.sender.id, event, optin);
} else if (typeof event.message === 'string') {
this.emit('message', event);
} else if (event.message && !event.message.is_echo) {
this.emit('message', event);
} else if (event.message && event.message.attachment) {
this.emit('attachment', event.sender.id, event.message.attachment, event.message.url, event.message.quickReplies);
} else if (event.delivery) {
let mids = event.delivery.mids;
this.emit('delivery', event.sender.id, event, mids);
} else if (event.read) {
let recipient = event.recipient.id;
this.emit('read', event.sender.id, recipient, event.read);
} else if (event.postback || (event.message && !event.message.is_echo && event.message.quick_reply)) {
let postback = (event.postback && event.postback.payload) || event.message.quick_reply.payload;
let ref = event.postback && event.postback.referral && event.postback.referral.ref;
this.emit('postback', event.sender.id, postback);
} else if (event.referral) {
let ref = event.referral.ref;
this.emit('referral', event.sender.id, event, ref);
} else if (event.account_linking) {
let link = event.account_linking;
this.emit('account_link', event.sender.id, event, link);
} else {
console.error('Invalid format for message.');
}
}
/*
* Verify that the callback came from Facebook. Using the App Secret from
* the App Dashboard, we can verify the signature that is sent with each
* callback in the x-hub-signature field, located in the header.
*
* https://developers.facebook.com/docs/graph-api/webhooks#setup
*
*/
verifyRequestSignature(req: any, res: any, buf: any) {
const signature = req.headers['x-hub-signature'];
if (!signature) {
// For testing, let's log an error. In production, you should throw an
// error.
console.error("Couldn't validate the signature.");
} else {
const elements = signature.split('='),
method = elements[0],
signatureHash = elements[1];
const expectedHash = createHmac('sha1', this.APP_SECRET)
.update(buf)
.digest('hex');
if (signatureHash != expectedHash) {
throw new Error("Couldn't validate the request signature.");
}
}
}
addGreeting(text: string) {
request(
{
url: `${this.FB_URL}me/thread_settings`,
qs: { access_token: this.PAGE_ACCESS_TOKEN },
method: 'POST',
json: {
setting_type: 'greeting',
greeting: {
text: text,
},
},
},
function(error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
},
);
}
addGetStartedButton() {
request(
{
url: `${this.FB_URL}me/messenger_profile`,
qs: { access_token: this.PAGE_ACCESS_TOKEN },
method: 'POST',
json: {
get_started: {
payload: 'GET_STARTED_PAYLOAD',
},
},
},
function(error, response, body) {
if (error) {
console.log('Error sending messages: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
},
);
}
addPersistentMenu(persistent_menu: any) {
request(
{
url: `${this.FB_URL}me/messenger_profile`,
qs: { access_token: this.PAGE_ACCESS_TOKEN },
method: 'POST',
json: {
persistent_menu: persistent_menu,
},
},
function(error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
},
);
}
removePersistentMenu() {
request(
{
url: `${this.FB_URL}me/thread_settings`,
qs: { access_token: this.PAGE_ACCESS_TOKEN },
method: 'POST',
json: {
setting_type: 'call_to_actions',
thread_state: 'existing_thread',
call_to_actions: [],
},
},
function(error, response, body) {
console.log(response);
if (error) {
console.log('Error sending messages: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
},
);
}
/**
* @param {Recipient|Object} recipientId Recipient object or ID.
* @param {String} messageText
*/
sendTextMessage(recipientId: any, messageText: string) {
this.callSendAPI({
recipient: {
id: recipientId,
},
message: {
text: messageText,
},
});
}
/**
* @param {Recipient|String} recipientId
* @param {String} type Must be 'image', 'audio', 'video' or 'file'.
* @param {String} url URL of the attachment.
*/
sendAttachment(recipientId: any, type: any, url: any) {
this.callSendAPI({
recipient: {
id: recipientId,
},
message: {
attachment: {
type: type,
payload: {
url: url,
},
},
},
});
}
/**
* @param {Recipient|String} recipientId
* @param {String} url URL of the attachment.
*/
sendFileMessage(recipientId: any, url: any) {
this.sendAttachment(recipientId, 'file', url);
}
/**
* @param {Recipient|String} recipientId
* @param {String} url URL of the attachment.
*/
sendImageMessage(recipientId: any, url: any) {
this.sendAttachment(recipientId, 'image', url);
}
/**
* @param {Recipient|String} recipientId
* @param {String} url URL of the attachment.
*/
sendVideoMessage(recipientId: any, url: any) {
this.sendAttachment(recipientId, 'video', url);
}
/**
* @param {Recipient|String} recipientId
* @param {String} url URL of the attachment.
*/
sendAudioMessage(recipientId: any, url: any) {
this.sendAttachment(recipientId, 'audio', url);
}
/**
* @param {Recipient|String} recipientId
* @param {Array.<Element>} elements
*/
sendGenericMessage(recipientId: any, elements: any) {
var messageData = {
recipient: {
id: recipientId,
},
message: {
attachment: {
type: 'template',
payload: {
template_type: 'generic',
elements: elements,
},
},
},
};
this.callSendAPI(messageData);
}
sendButtonMessage(recipientId: any, text: any, buttons: any) {
var messageData = {
recipient: {
id: recipientId,
},
message: {
attachment: {
type: 'template',
payload: {
template_type: 'button',
text: text,
buttons: buttons,
},
},
},
};
this.callSendAPI(messageData);
}
callSendAPI(messageData: any) {
request(
{
uri: `${this.FB_URL}me/messages`,
qs: { access_token: this.PAGE_ACCESS_TOKEN },
method: 'POST',
json: messageData,
},
function(error, response, body) {
if (!error && response.statusCode == 200) {
const recipientId = body.recipient_id,
messageId = body.message_id;
if (messageId) {
console.log('Successfully sent message with id %s to recipient %s', messageId, recipientId);
} else {
console.log('Successfully called Send API for recipient %s', recipientId);
}
} else {
console.error('Failed calling Send API', response.statusCode, response.statusMessage, body.error);
}
},
);
}
/**
* @param {Recipient|String} recipientId
* @param greetings
* @param text
*/
sendWelcome(recipientId: any, greetings: any, text: any) {
// this (aka "the context") is a special keyword inside each function and its value only depends on how the function was called,
// not how/when/where it was defined. It is not affected by lexical scopes, like other variables
const self = this;
request(
{
url: `${this.FB_URL}` + recipientId + `?access_token=` + this.PAGE_ACCESS_TOKEN,
},
function(error, response, body) {
if (error || response.statusCode != 200) return;
const fbProfileBody = JSON.parse(body),
userName = fbProfileBody['first_name'],
randomGreeting = greetings[self.getRandomNumber(0, greetings.length - 1)],
welcomeMsg = `${randomGreeting} ${userName} ${text}`;
self.sendTextMessage(recipientId, welcomeMsg);
},
);
}
/*
* Postback Event
*
* This event is called when a postback is tapped on a Structured Message.
* https://developers.facebook.com/docs/messenger-platform/webhook-reference/postback-received
*
*/
receivedPostback(event: any) {
const senderID = event.sender.id,
recipientID = event.recipient.id,
timeOfPostback = event.timestamp,
payload = event.postback.payload;
console.log(
"Received postback for user %d and page %d with payload '%s' " + 'at %d',
senderID,
recipientID,
payload,
timeOfPostback,
);
this.sendTextMessage(senderID, 'Postback called');
}
/*
* Send a read receipt to indicate the message has been read
*
*/
sendReadReceipt(recipientId: any) {
this.callSendAPI({
recipient: {
id: recipientId,
},
sender_action: 'mark_seen',
});
}
/**
* @param {Recipient|Object} recipientId Recipient object or ID.
*/
sendTypingOn(recipientId: any) {
this.callSendAPI({
recipient: {
id: recipientId,
},
sender_action: 'typing_on',
});
}
/**
* @param {Recipient|Object} recipientId Recipient object or ID.
*/
sendTypingOff(recipientId: any) {
this.callSendAPI({
recipient: {
id: recipientId,
},
sender_action: 'typing_off',
});
}
getRandomNumber(minimum: number, maxmimum: number) {
return Math.floor(Math.exp(Math.random() * Math.log(maxmimum - minimum + 1))) + minimum;
}
randomIntFromInterval(min: number, max: number) {
return this.getRandomNumber(min, max);
}
textMatches(message: string, matchString: string) {
return message.toLowerCase().indexOf(matchString) != -1;
}
} | the_stack |
import * as Clutter from 'clutter';
import * as GObject from 'gobject';
import * as Meta from 'meta';
import * as Shell from 'shell';
import { MsPanel } from 'src/layout/verticalPanel/verticalPanel';
import { Signal } from 'src/manager/msManager';
import {
HorizontalPanelPositionEnum,
VerticalPanelPositionEnum,
} from 'src/manager/msThemeManager';
import { assert, assertNotNull } from 'src/utils/assert';
import {
Allocate,
AllocatePreferredSize,
SetAllocation,
} from 'src/utils/compatibility';
import { registerGObjectClass } from 'src/utils/gjs';
import { reparentActor } from 'src/utils/index';
import { SignalHandle } from 'src/utils/signal';
import { TranslationAnimator } from 'src/widget/translationAnimator';
import * as St from 'st';
import { layout, main as Main } from 'ui';
import { MsWorkspaceActor } from './msWorkspace/msWorkspace';
import Monitor = layout.Monitor;
const Background = imports.ui.background;
/** Extension imports */
const Me = imports.misc.extensionUtils.getCurrentExtension();
@registerGObjectClass
export class MsMain extends St.Widget {
static metaInfo: GObject.MetaInfo = {
GTypeName: 'MsMain',
};
panelsVisible: boolean;
monitorsContainer: MonitorContainer[];
aboveContainer: Clutter.Actor;
backgroundGroup: Meta.BackgroundGroup<Clutter.Actor>;
primaryMonitorContainer: PrimaryMonitorContainer;
panel: MsPanel;
blurEffect: Shell.BlurEffect | undefined;
private _scaleChangedId: SignalHandle | undefined;
// Definitely assigned because we call registerToSignals
signals!: Signal[];
overviewShown = false;
constructor() {
super({});
Me.layout = this;
this.panelsVisible = Me.stateManager.getState('panels-visible') ?? true;
Main.layoutManager.uiGroup.insert_child_above(
this,
global.window_group
);
this.monitorsContainer = [];
this.aboveContainer = new Clutter.Actor();
this.add_child(this.aboveContainer);
this.backgroundGroup = new Meta.BackgroundGroup({});
this.setBlurBackground(Me.msThemeManager.blurBackground);
Me.msThemeManager.connect('blur-background-changed', () => {
this.setBlurBackground(Me.msThemeManager.blurBackground);
});
this.add_child(this.backgroundGroup);
this.primaryMonitorContainer = new PrimaryMonitorContainer(
assertNotNull(this.primaryMonitor),
this.backgroundGroup,
{
clip_to_allocation: true,
}
);
this.add_child(this.primaryMonitorContainer);
this.panel = this.primaryMonitorContainer.panel;
this.primaryMonitorContainer.setMsWorkspaceActor(
Me.msWorkspaceManager.getActivePrimaryMsWorkspace().msWorkspaceActor
);
for (const externalMonitor of this.externalMonitors) {
const container = new MonitorContainer(
externalMonitor,
this.backgroundGroup,
{
clip_to_allocation: true,
}
);
this.monitorsContainer.push(container);
this.add_child(container);
}
global.display.connect('overlay-key', () => {
this.toggleOverview();
});
global.stage.connect('captured-event', (_, event: Clutter.Event) => {
if (!this.overviewShown) return;
if (event.type() === Clutter.EventType.BUTTON_PRESS) {
const source = event.get_source();
const [x, y] = event.get_coords();
// Note: The Clutter typing is incorrect. See https://gitlab.gnome.org/ewlsh/gi.ts/-/issues/2
const [x1, y1] = this.panel.get_transformed_position() as [
number,
number
];
const [width, height] = this.panel.get_transformed_size() as [
number,
number
];
if (
!(x >= x1 && x <= x1 + width && y >= y1 && y <= y1 + height)
) {
this.toggleOverview();
}
}
return Clutter.EVENT_PROPAGATE;
});
this.registerToSignals();
this.onMsWorkspacesChanged();
this.updatePanelVisibilities();
this.updateFullscreenMonitors();
}
get primaryMonitor() {
return Main.layoutManager.primaryMonitor;
}
get externalMonitors() {
return Main.layoutManager.monitors.filter(
(monitor) => monitor !== this.primaryMonitor
);
}
setBlurBackground(blur: boolean) {
const themeContext = St.ThemeContext.get_for_stage(global.stage);
if ((this.blurEffect && blur) || (!this.blurEffect && !blur)) {
return;
} else if (this.blurEffect && !blur) {
this._scaleChangedId?.disconnect();
this.backgroundGroup.remove_effect(this.blurEffect);
delete this.blurEffect;
return;
}
const effect = (this.blurEffect = new Shell.BlurEffect({
brightness: 0.55,
sigma: 60 * themeContext.scale_factor,
}));
this._scaleChangedId = SignalHandle.connect(
themeContext,
'notify::scale-factor',
() => {
effect.sigma = 60 * themeContext.scale_factor;
}
);
this.backgroundGroup.add_effect(this.blurEffect);
}
registerToSignals() {
this.signals = [];
this.signals.push({
from: Me.msWorkspaceManager,
id: Me.msWorkspaceManager.connect(
'switch-workspace',
(_, from: number, to: number) => {
this.onSwitchWorkspace(from, to);
}
),
});
this.signals.push({
from: Me.msWorkspaceManager,
id: Me.msWorkspaceManager.connect(
'dynamic-super-workspaces-changed',
() => {
this.onMsWorkspacesChanged();
}
),
});
this.signals.push({
from: Me,
id: Me.connect('extension-disable', () => {
this.aboveContainer.get_children().forEach((actor) => {
this.aboveContainer.remove_child(actor);
global.window_group.add_child(actor);
});
this.signals.forEach((signal) => {
signal.from.disconnect(signal.id);
});
}),
});
this.signals.push({
from: global.display,
id: global.display.connect('in-fullscreen-changed', () => {
this.updateFullscreenMonitors();
}),
});
this.signals.push({
from: Main.layoutManager,
id: Main.layoutManager.connect('monitors-changed', () => {
this.primaryMonitorContainer.setMonitor(
assertNotNull(this.primaryMonitor)
);
const externalMonitorsDiff =
Main.layoutManager.monitors.length -
1 -
this.monitorsContainer.length;
// if there are more external monitors
if (externalMonitorsDiff > 0) {
for (let i = 0; i < Math.abs(externalMonitorsDiff); i++) {
const container = new MonitorContainer(
this.externalMonitors[
this.externalMonitors.length -
Math.abs(externalMonitorsDiff) +
i
],
this.backgroundGroup,
{
clip_to_allocation: true,
}
);
this.monitorsContainer.push(container);
this.add_child(container);
}
// if there are less external monitors
} else if (externalMonitorsDiff < 0) {
for (let i = 0; i < Math.abs(externalMonitorsDiff); i++) {
const container = this.monitorsContainer.pop();
assert(
container !== undefined,
'monitorsContainer was empty'
);
if (container.msWorkspaceActor) {
container.remove_child(container.msWorkspaceActor);
}
container.destroy();
}
}
this.externalMonitors.forEach((monitor, index) => {
this.monitorsContainer[index].setMonitor(monitor);
});
this.onMsWorkspacesChanged();
this.updatePanelVisibilities();
this.updateFullscreenMonitors();
}),
});
}
onMsWorkspacesChanged(): void {
this.primaryMonitorContainer.setMsWorkspaceActor(
Me.msWorkspaceManager.getActivePrimaryMsWorkspace().msWorkspaceActor
);
this.monitorsContainer.forEach((container) => {
const msWorkspace =
Me.msWorkspaceManager.getMsWorkspacesOfMonitorIndex(
container.monitor.index
)[0];
if (msWorkspace) {
container.setMsWorkspaceActor(msWorkspace.msWorkspaceActor);
}
});
}
onSwitchWorkspace(_from: number, _to: number): void {
this.onMsWorkspacesChanged();
}
togglePanelsVisibilities(): void {
this.panelsVisible = !this.panelsVisible;
Me.stateManager.setState('panels-visible', this.panelsVisible);
this.updatePanelVisibilities();
}
updatePanelVisibilities(): void {
[
this.primaryMonitorContainer.verticalPanelSpacer,
this.primaryMonitorContainer.horizontalPanelSpacer,
...this.monitorsContainer.map(
(container) => container.horizontalPanelSpacer
),
].forEach((actor) => {
actor.visible = this.panelsVisible;
if (this.panelsVisible) {
if (Main.layoutManager._findActor(actor) === -1) {
Main.layoutManager._trackActor(actor, {
affectsStruts: true,
});
}
} else {
Main.layoutManager._untrackActor(actor);
}
});
this.primaryMonitorContainer.panel.visible = this.panelsVisible;
Me.msWorkspaceManager.refreshMsWorkspaceUI();
}
updateFullscreenMonitors(): void {
this.primaryMonitorContainer.refreshFullscreen();
for (const container of this.monitorsContainer) {
container.refreshFullscreen();
}
Me.msWorkspaceManager.refreshMsWorkspaceUI();
}
toggleOverview(): void {
if (this.overviewShown) {
this.overviewShown = false;
this.primaryMonitorContainer.workspaceContainer.ease_property(
'@effects.dimmer.brightness',
Clutter.Color.new(127, 127, 127, 255),
{
duration: 300,
mode: Clutter.AnimationMode.EASE_OUT_QUAD,
onComplete: () => {
this.primaryMonitorContainer.workspaceContainer.clear_effects();
},
}
);
Me.msWindowManager.msFocusManager.popModal(this);
} else {
this.overviewShown = true;
if (Main._findModal(this) === -1) {
Me.msWindowManager.msFocusManager.pushModal(this, {
actionMode: Shell.ActionMode.OVERVIEW,
});
}
const dimmerEffect = new Clutter.BrightnessContrastEffect({
name: 'dimmer',
brightness: Clutter.Color.new(127, 127, 127, 255),
});
this.primaryMonitorContainer.workspaceContainer.add_effect(
dimmerEffect
);
this.primaryMonitorContainer.workspaceContainer.ease_property(
'@effects.dimmer.brightness',
Clutter.Color.new(90, 90, 90, 255),
{
duration: 300,
mode: Clutter.AnimationMode.EASE_IN_QUAD,
}
);
}
this.panel.toggle();
}
// eslint-disable-next-line camelcase
add_child(actor: Clutter.Actor) {
super.add_child(actor);
this.set_child_above_sibling(this.aboveContainer, null);
}
setActorAbove(actor: Clutter.Actor) {
reparentActor(actor, this.aboveContainer);
}
vfunc_get_preferred_width(_forHeight: number): [number, number] {
const width = global.stage.width;
return [width, width];
}
vfunc_get_preferred_height(_forWidth: number): [number, number] {
const height = global.stage.height;
return [height, height];
}
}
@registerGObjectClass
export class MonitorContainer extends St.Widget {
static metaInfo: GObject.MetaInfo = {
GTypeName: 'MonitorContainer',
};
bgGroup: Meta.BackgroundGroup;
horizontalPanelSpacer: St.Widget<
Clutter.LayoutManager,
Clutter.ContentPrototype,
Clutter.Actor<Clutter.LayoutManager, Clutter.ContentPrototype>
>;
bgManager: any;
msWorkspaceActor: MsWorkspaceActor | undefined;
// Safety: We definitely set this because we call setMonitor from the constructor
monitor!: Monitor;
constructor(
monitor: Monitor,
bgGroup: Meta.BackgroundGroup,
params?: Partial<St.Widget.ConstructorProperties>
) {
super(params);
this.bgGroup = bgGroup;
this.horizontalPanelSpacer = new St.Widget({
style_class: 'HorizontalSpacer',
});
this.setMonitor(monitor);
this.add_child(this.horizontalPanelSpacer);
const panelSizeSignal = Me.msThemeManager.connect(
'panel-size-changed',
() => {
this.updateSpacer();
}
);
const horizontalPanelPositionSignal = Me.msThemeManager.connect(
'horizontal-panel-position-changed',
() => {
this.updateSpacer();
}
);
this.connect('destroy', () => {
Me.msThemeManager.disconnect(panelSizeSignal);
Me.msThemeManager.disconnect(horizontalPanelPositionSignal);
});
}
refreshFullscreen() {
this.setFullscreen(
global.display.get_monitor_in_fullscreen(this.monitor.index)
);
}
protected setFullscreen(monitorIsFullscreen: boolean) {
this.bgManager.backgroundActor.visible = !monitorIsFullscreen;
this.horizontalPanelSpacer.visible =
Me.layout.panelsVisible && !monitorIsFullscreen;
}
setMsWorkspaceActor(actor: MsWorkspaceActor) {
if (actor === this.msWorkspaceActor) return;
if (
this.msWorkspaceActor &&
this.msWorkspaceActor.get_parent() === this
) {
this.remove_child(this.msWorkspaceActor);
}
this.msWorkspaceActor = actor;
reparentActor(this.msWorkspaceActor, this);
this.msWorkspaceActor.updateUI();
}
updateSpacer() {
const panelHeight = Me.msThemeManager.getPanelSize(this.monitor.index);
const panelPosition = Me.msThemeManager.horizontalPanelPosition;
this.horizontalPanelSpacer.set_size(this.monitor.width, panelHeight);
this.horizontalPanelSpacer.set_position(
0,
panelPosition === HorizontalPanelPositionEnum.TOP
? 0
: this.monitor.height - panelHeight
);
}
setMonitor(monitor: Monitor) {
if (this.bgManager) {
this.bgManager.destroy();
}
this.monitor = monitor;
this.set_size(monitor.width, monitor.height);
this.set_position(monitor.x, monitor.y);
this.updateSpacer();
this.bgManager = new Background.BackgroundManager({
container: this.bgGroup,
monitorIndex: monitor.index,
});
}
allocateHorizontalPanelSpacer(
box: Clutter.ActorBox,
flags?: Clutter.AllocationFlags
) {
AllocatePreferredSize(this.horizontalPanelSpacer, flags);
}
vfunc_allocate(box: Clutter.ActorBox, flags?: Clutter.AllocationFlags) {
SetAllocation(this, box, flags);
const themeNode = this.get_theme_node();
box = themeNode.get_content_box(box);
this.get_children().forEach((actor) => {
if (actor === this.horizontalPanelSpacer) {
return this.allocateHorizontalPanelSpacer(box, flags);
}
if (actor === this.msWorkspaceActor) {
const msWorkspaceActorBox = new Clutter.ActorBox();
msWorkspaceActorBox.x1 = box.x1;
msWorkspaceActorBox.x2 = box.x2;
msWorkspaceActorBox.y1 = box.y1;
msWorkspaceActorBox.y2 = box.y2;
return Allocate(
this.msWorkspaceActor,
msWorkspaceActorBox,
flags
);
}
AllocatePreferredSize(actor, flags);
});
}
}
@registerGObjectClass
export class PrimaryMonitorContainer extends MonitorContainer {
static metaInfo: GObject.MetaInfo = {
GTypeName: 'PrimaryMonitorContainer',
};
panel: MsPanel;
translationAnimator: TranslationAnimator;
verticalPanelSpacer: St.Widget<
Clutter.LayoutManager,
Clutter.ContentPrototype,
Clutter.Actor<Clutter.LayoutManager, Clutter.ContentPrototype>
>;
workspaceContainer = new St.Widget({
layout_manager: new Clutter.BinLayout(),
x_align: Clutter.ActorAlign.FILL,
y_align: Clutter.ActorAlign.FILL,
});
constructor(
monitor: Monitor,
bgGroup: Meta.BackgroundGroup,
params?: Partial<St.Widget.ConstructorProperties>
) {
super(monitor, bgGroup, params);
this.verticalPanelSpacer = new St.Widget({
style_class: 'VerticalSpacer',
});
this.add_child(this.verticalPanelSpacer);
this.panel = new MsPanel();
this.add_child(this.workspaceContainer);
this.add_child(this.panel);
this.translationAnimator = new TranslationAnimator(true);
this.translationAnimator.connect('transition-completed', () => {
assert(
this.msWorkspaceActor !== undefined,
'expected a workspace actor to exist'
);
reparentActor(this.msWorkspaceActor, this.workspaceContainer);
this.workspaceContainer.remove_child(this.translationAnimator);
this.msWorkspaceActor.updateUI();
});
const verticalPanelPositionSignal = Me.msThemeManager.connect(
'vertical-panel-position-changed',
() => {
this.queue_relayout();
this.updateSpacer();
}
);
this.connect('destroy', () => {
Me.msThemeManager.disconnect(verticalPanelPositionSignal);
});
this.updateSpacer();
}
protected setFullscreen(monitorIsFullscreen: boolean) {
this.panel.visible = Me.layout.panelsVisible && !monitorIsFullscreen;
this.verticalPanelSpacer.visible =
Me.layout.panelsVisible && !monitorIsFullscreen;
super.setFullscreen(monitorIsFullscreen);
}
setTranslation(prevActor: Clutter.Actor, nextActor: Clutter.Actor) {
if (!this.translationAnimator.get_parent()) {
this.translationAnimator.width = this.width;
this.translationAnimator.height = assertNotNull(
Main.layoutManager.primaryMonitor
).height;
this.workspaceContainer.add_child(this.translationAnimator);
}
const indexOfPrevActor =
Me.msWorkspaceManager.primaryMsWorkspaces.findIndex(
(msWorkspace) => {
return msWorkspace.msWorkspaceActor === prevActor;
}
);
const indexOfNextActor =
Me.msWorkspaceManager.primaryMsWorkspaces.findIndex(
(msWorkspace) => {
return msWorkspace.msWorkspaceActor === nextActor;
}
);
prevActor.height = nextActor.height = this.height;
this.translationAnimator.setTranslation(
[prevActor],
[nextActor],
indexOfNextActor > indexOfPrevActor ? 1 : -1
);
}
setMsWorkspaceActor(actor: MsWorkspaceActor) {
if (actor === this.msWorkspaceActor) return;
let prevActor;
if (this.msWorkspaceActor) {
prevActor = this.msWorkspaceActor;
if (this.msWorkspaceActor.get_parent() === this.workspaceContainer)
this.workspaceContainer.remove_child(this.msWorkspaceActor);
}
this.msWorkspaceActor = actor;
if (!this.msWorkspaceActor.get_parent()) {
reparentActor(this.msWorkspaceActor, this.workspaceContainer);
}
assertNotNull(this.msWorkspaceActor.msWorkspace).refreshFocus(true);
if (prevActor) {
this.setTranslation(prevActor, this.msWorkspaceActor);
}
}
updateSpacer() {
super.updateSpacer();
if (this.verticalPanelSpacer) {
const panelWidth = Me.msThemeManager.getPanelSize(
this.monitor.index
);
const panelPosition = Me.msThemeManager.verticalPanelPosition;
this.verticalPanelSpacer.set_size(panelWidth, this.monitor.height);
this.verticalPanelSpacer.set_position(
panelPosition === VerticalPanelPositionEnum.LEFT
? 0
: this.monitor.width - panelWidth,
0
);
}
}
vfunc_allocate(box: Clutter.ActorBox, flags?: Clutter.AllocationFlags) {
SetAllocation(this, box, flags);
const themeNode = this.get_theme_node();
box = themeNode.get_content_box(box);
const panelBox = new Clutter.ActorBox();
const panelPosition = Me.msThemeManager.verticalPanelPosition;
if (this.panel) {
const panelWidth = this.panel.get_preferred_width(-1)[1]!;
panelBox.x1 =
panelPosition === VerticalPanelPositionEnum.LEFT
? box.x1
: box.x2 - panelWidth;
panelBox.x2 = panelBox.x1 + panelWidth;
panelBox.y1 = box.y1;
panelBox.y2 = this.panel.get_preferred_height(-1)[1]!;
}
const msWorkspaceActorBox = new Clutter.ActorBox();
msWorkspaceActorBox.x1 = box.x1;
msWorkspaceActorBox.x2 = box.x2;
msWorkspaceActorBox.y1 = box.y1;
msWorkspaceActorBox.y2 = box.y2;
if (this.panel && this.panel.visible && Me.layout.panelsVisible) {
if (panelPosition === VerticalPanelPositionEnum.LEFT) {
msWorkspaceActorBox.x1 =
msWorkspaceActorBox.x1 +
Me.msThemeManager.getPanelSize(
Main.layoutManager.primaryIndex
);
} else {
msWorkspaceActorBox.x2 =
msWorkspaceActorBox.x2 -
Me.msThemeManager.getPanelSize(
Main.layoutManager.primaryIndex
);
}
}
this.get_children().forEach((child) => {
if (child === this.panel) {
return Allocate(child, panelBox, flags);
}
if (child === this.horizontalPanelSpacer) {
return this.allocateHorizontalPanelSpacer(box, flags);
}
if (child === this.verticalPanelSpacer) {
return AllocatePreferredSize(this.verticalPanelSpacer, flags);
}
Allocate(child, msWorkspaceActorBox, flags);
});
}
} | the_stack |
import { Widget } from '@lumino/widgets';
import { Signal, ISignal } from '@lumino/signaling';
import { PromiseDelegate } from '@lumino/coreutils';
/*
This is a typing-only import. If you use it directly, the mxgraph content
will be included in the main JupyterLab js bundle.
*/
// @ts-ignore
import * as MX from './drawio/modulated.js';
import './drawio/css/common.css';
import './drawio/styles/grapheditor.css';
import { grapheditorTxt, defaultXml } from './pack';
const w = window as any;
const webPath =
'https://raw.githubusercontent.com/jgraph/mxgraph/master/javascript/examples/grapheditor/www/';
w.RESOURCES_BASE = webPath + 'resources/';
w.STENCIL_PATH = webPath + 'stencils/';
w.IMAGE_PATH = webPath + 'images/';
w.STYLE_PATH = webPath + 'styles/';
w.CSS_PATH = webPath + 'styles/';
w.OPEN_FORM = webPath + 'open.html';
// w.mxBasePath = "http://localhost:8000/src/mxgraph/javascript/src/";
//w.imageBasePath = 'http://localhost:8000/src/mxgraph/javascript/';
w.mxLoadStylesheets = false; // disable loading stylesheets
w.mxLoadResources = false;
/**
* A DrawIO layout.
*/
export class DrawIOWidget extends Widget {
/**
* Construct a `GridStackLayout`.
*
* @param info - The `DashboardView` metadata.
*/
constructor() {
super();
void Private.ensureMx().then(mx => this._loadDrawIO(mx));
//this._loadDrawIO(MX);
}
/**
* Dispose of the resources held by the widget.
*/
dispose(): void {
Signal.clearData(this);
this._editor.destroy();
super.dispose();
}
/**
* A promise that resolves when the csv viewer is ready.
*/
get ready(): PromiseDelegate<void> {
return this._ready;
}
get graphChanged(): ISignal<this, string> {
return this._graphChanged;
}
get mx(): any {
return this._mx;
}
get editor(): any {
return this._editor;
}
get graph(): any {
return this._editor.editor.graph;
}
getAction(action: string): any {
return this._editor.actions.actions[action];
}
getActions(): any {
return this._editor.actions.actions;
}
setContent(newValue: string): void {
if (this._editor === undefined) {
return;
}
const oldValue = this._mx.mxUtils.getXml(this._editor.editor.getGraphXml());
if (oldValue !== newValue && !this._editor.editor.graph.isEditing()) {
if (newValue.length) {
const xml = this._mx.mxUtils.parseXml(newValue);
this._editor.editor.setGraphXml(xml.documentElement);
}
}
}
//Direction
public toggleCellStyles(flip: string): void {
let styleFlip = this._editor.mx.mxConstants.STYLE_FLIPH;
switch (flip) {
case 'flipH':
styleFlip = this._editor.mx.mxConstants.STYLE_FLIPH;
break;
case 'flipV':
styleFlip = this._editor.mx.mxConstants.STYLE_FLIPV;
break;
}
this._editor.graph.toggleCellStyles(styleFlip, false);
}
//Align
public alignCells(align: string): void {
if (this._editor.graph.isEnabled()) {
let pos = this._editor.mx.mxConstants.ALIGN_CENTER;
switch (align) {
case 'alignCellsLeft':
pos = this._editor.mx.mxConstants.ALIGN_LEFT;
break;
case 'alignCellsCenter':
pos = this._editor.mx.mxConstants.ALIGN_CENTER;
break;
case 'alignCellsRight':
pos = this._editor.mx.mxConstants.ALIGN_RIGHT;
break;
case 'alignCellsTop':
pos = this._editor.mx.mxConstants.ALIGN_TOP;
break;
case 'alignCellsMiddle':
pos = this._editor.mx.mxConstants.ALIGN_MIDDLE;
break;
case 'alignCellsBottom':
pos = this._editor.mx.mxConstants.ALIGN_BOTTOM;
break;
}
this._editor.graph.alignCells(pos);
}
}
//Distribute
//drawio:command/horizontal
//drawio:command/vertical
public distributeCells(horizontal: boolean): void {
this._editor.graph.distributeCells(horizontal);
}
//Layout
//drawio:command/horizontalFlow
//drawio:command/verticalFlow
public layoutFlow(direction: string): void {
let directionFlow = this._editor.mx.mxConstants.DIRECTION_WEST;
switch (direction) {
case 'horizontalFlow':
directionFlow = this._editor.mx.mxConstants.DIRECTION_WEST;
break;
case 'verticalFlow':
directionFlow = this._editor.mx.mxConstants.DIRECTION_NORTH;
break;
}
const mxHierarchicalLayout = this._editor.mx.mxHierarchicalLayout;
const layout = new mxHierarchicalLayout(this._editor.graph, directionFlow);
this._editor.editor.executeLayout(() => {
const selectionCells = this._editor.graph.getSelectionCells();
layout.execute(
this._editor.graph.getDefaultParent(),
selectionCells.length === 0 ? null : selectionCells
);
}, true);
}
public horizontalTree(): void {
let tmp = this._editor.graph.getSelectionCell();
let roots = null;
if (
tmp === null ||
this._editor.graph.getModel().getChildCount(tmp) === 0
) {
if (this._editor.graph.getModel().getEdgeCount(tmp) === 0) {
roots = this._editor.graph.findTreeRoots(
this._editor.graph.getDefaultParent()
);
}
} else {
roots = this._editor.graph.findTreeRoots(tmp);
}
if (roots !== null && roots.length > 0) {
tmp = roots[0];
}
if (tmp !== null) {
const mxCompactTreeLayout = this._editor.mx.mxCompactTreeLayout;
const layout = new mxCompactTreeLayout(this._editor.graph, true);
layout.edgeRouting = false;
layout.levelDistance = 30;
this._promptSpacing(
layout.levelDistance,
this._editor.mx.mxUtils.bind(this, (newValue: any) => {
layout.levelDistance = newValue;
this._editor.editor.executeLayout(() => {
layout.execute(this._editor.graph.getDefaultParent(), tmp);
}, true);
})
);
}
}
public verticalTree(): void {
let tmp = this._editor.graph.getSelectionCell();
let roots = null;
if (
tmp === null ||
this._editor.graph.getModel().getChildCount(tmp) === 0
) {
if (this._editor.graph.getModel().getEdgeCount(tmp) === 0) {
roots = this._editor.graph.findTreeRoots(
this._editor.graph.getDefaultParent()
);
}
} else {
roots = this._editor.graph.findTreeRoots(tmp);
}
if (roots !== null && roots.length > 0) {
tmp = roots[0];
}
if (tmp !== null) {
const mxCompactTreeLayout = this._editor.mx.mxCompactTreeLayout;
const layout = new mxCompactTreeLayout(this._editor.graph, false);
layout.edgeRouting = false;
layout.levelDistance = 30;
this._promptSpacing(
layout.levelDistance,
this._editor.mx.mxUtils.bind(this, (newValue: any) => {
layout.levelDistance = newValue;
this._editor.editor.executeLayout(() => {
layout.execute(this._editor.graph.getDefaultParent(), tmp);
}, true);
})
);
}
}
public radialTree(): void {
let tmp = this._editor.graph.getSelectionCell();
let roots = null;
if (
tmp === null ||
this._editor.graph.getModel().getChildCount(tmp) === 0
) {
if (this._editor.graph.getModel().getEdgeCount(tmp) === 0) {
roots = this._editor.graph.findTreeRoots(
this._editor.graph.getDefaultParent()
);
}
} else {
roots = this._editor.graph.findTreeRoots(tmp);
}
if (roots !== null && roots.length > 0) {
tmp = roots[0];
}
if (tmp !== null) {
const mxRadialTreeLayout = this._editor.mx.mxRadialTreeLayout;
const layout = new mxRadialTreeLayout(this._editor.graph, false);
layout.levelDistance = 80;
layout.autoRadius = true;
this._promptSpacing(
layout.levelDistance,
this._editor.mx.mxUtils.bind(this, (newValue: any) => {
layout.levelDistance = newValue;
this._editor.editor.executeLayout(() => {
layout.execute(this._editor.graph.getDefaultParent(), tmp);
if (!this._editor.graph.isSelectionEmpty()) {
tmp = this._editor.graph.getModel().getParent(tmp);
if (this._editor.graph.getModel().isVertex(tmp)) {
this._editor.graph.updateGroupBounds(
[tmp],
this._editor.graph.gridSize * 2,
true
);
}
}
}, true);
})
);
}
}
public organic(): void {
const mxFastOrganicLayout = this._editor.mx.mxFastOrganicLayout;
const layout = new mxFastOrganicLayout(this._editor.graph);
this._promptSpacing(
layout.forceConstant,
this._editor.mx.mxUtils.bind(this, (newValue: any) => {
layout.forceConstant = newValue;
this._editor.editor.executeLayout(() => {
let tmp = this._editor.graph.getSelectionCell();
if (
tmp === null ||
this._editor.graph.getModel().getChildCount(tmp) === 0
) {
tmp = this._editor.graph.getDefaultParent();
}
layout.execute(tmp);
if (this._editor.graph.getModel().isVertex(tmp)) {
this._editor.graph.updateGroupBounds(
[tmp],
this._editor.graph.gridSize * 2,
true
);
}
}, true);
})
);
}
public circle(): void {
const mxCircleLayout = this._editor.mx.mxCircleLayout;
const layout = new mxCircleLayout(this._editor.graph);
this._editor.editor.executeLayout(() => {
let tmp = this._editor.graph.getSelectionCell();
if (
tmp === null ||
this._editor.graph.getModel().getChildCount(tmp) === 0
) {
tmp = this._editor.graph.getDefaultParent();
}
layout.execute(tmp);
if (this._editor.graph.getModel().isVertex(tmp)) {
this._editor.graph.updateGroupBounds(
[tmp],
this._editor.graph.gridSize * 2,
true
);
}
}, true);
}
private _loadDrawIO(mx: Private.MX): void {
this._mx = mx;
// Adds required resources (disables loading of fallback properties, this can only
// be used if we know that all keys are defined in the language specific file)
this._mx.mxResources.loadDefaultBundle = false;
// Fixes possible asynchronous requests
this._mx.mxResources.parse(grapheditorTxt);
const oParser = new DOMParser();
const oDOM = oParser.parseFromString(defaultXml, 'text/xml');
const themes: any = new Object(null);
themes[(this._mx.Graph as any).prototype.defaultThemeName] =
oDOM.documentElement;
// Workaround for TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature
const Editor: any = this._mx.Editor;
this._editor = new this._mx.EditorUi(new Editor(false, themes), this.node);
this._editor.refresh();
this._editor.editor.graph.model.addListener(
this._mx.mxEvent.NOTIFY,
(sender: any, evt: any) => {
const changes: any[] = evt.properties.changes;
for (let i = 0; i < changes.length; i++) {
if (changes[i].root) {
return;
}
}
if (this._editor.editor.graph.isEditing()) {
this._editor.editor.graph.stopEditing();
}
const graph = this._editor.editor.getGraphXml();
const xml = this._mx.mxUtils.getXml(graph);
this._graphChanged.emit(xml);
}
);
this._promptSpacing = this._mx.mxUtils.bind(
this,
(defaultValue: any, fn: any) => {
const FilenameDialog = this._mx.FilenameDialog;
const dlg = new FilenameDialog(
this._editor.editor,
defaultValue,
this._mx.mxResources.get('apply'),
(newValue: any) => {
fn(parseFloat(newValue));
},
this._mx.mxResources.get('spacing')
);
this._editor.editor.showDialog(dlg.container, 300, 80, true, true);
dlg.init();
}
);
this._ready.resolve(void 0);
}
private _editor: any;
private _mx: Private.MX;
private _promptSpacing: any;
private _ready = new PromiseDelegate<void>();
private _graphChanged = new Signal<this, string>(this);
}
/**
* A namespace for module-level concerns like loading mxgraph
*/
namespace Private {
export type MX = typeof MX;
let _mx: typeof MX;
let _mxLoading: PromiseDelegate<MX>;
/**
* Asynchronously load the mx bundle, or return it if already available
*/
export async function ensureMx(): Promise<MX> {
if (_mx) {
return _mx;
}
if (_mxLoading) {
return await _mxLoading.promise;
}
_mxLoading = new PromiseDelegate();
/*eslint-disable */
// @ts-ignore
_mx = await import('./drawio/modulated.js');
/*eslint-enable */
_mxLoading.resolve(_mx);
return _mx;
}
} | the_stack |
import { OutputVertex } from './type';
import { findIndex, find } from '../Utils/utils';
import { BaseVertex, BaseEdge, Vertex, Edge, } from '../type';
const VIRTUAL_ROOT_ID = Symbol('VIRTUAL_ROOT_ID');
// 内部 Tree 节点
class _TreeVertex<V, E> {
/** 索引 id */
id: string;
/** 节点类型 */
type: 'virtualRoot' | 'realNode';
/** 当前节点层级 */
level: number;
/** 父节点关联边 */
parentEdge: _TreeEdge<V, E>;
/** 子节点关联边列表 */
childrenEdge: _TreeEdge<V, E>[];
/** 源信息,与 Vertex[] 对应 */
origin: V;
constructor(config: {
id: string;
type: 'virtualRoot' | 'realNode';
level: number;
parentEdge: _TreeEdge<V, E>;
childrenEdge: _TreeEdge<V, E>[];
origin: V;
}) {
this.id = config.id;
this.type = config.type;
this.level = config.level;
this.parentEdge = config.parentEdge;
this.childrenEdge = config.childrenEdge;
this.origin = config.origin;
}
getParent(): _TreeVertex<V, E> {
return this.parentEdge.parent;
}
getChildrenOriginNode(): V[] {
return this.childrenEdge.map(childEdge => {
return childEdge.child.getOriginNode();
});
}
getOriginNode() {
return this.origin;
}
getLevel() {
return this.level;
}
/** 获取兄弟节点 */
getSibling() {
const sibling = this.parentEdge.parent.getChildrenOriginNode();
const index = findIndex(sibling, (item: any) => {
return item.id === this.id;
});
return {
pre: sibling.slice(0, index),
index,
next: sibling.slice(index + 1)
};
}
isVirtualRoot() {
return this.type === 'virtualRoot';
}
}
// 内部 Tree 边
class _TreeEdge<V, E> {
/** 父节点索引 */
parent: _TreeVertex<V, E>;
/** 另一端节点索引 */
child: _TreeVertex<V, E>;
/** 源信息 */
origin: E;
constructor(config: { parent: _TreeVertex<V, E>; child: _TreeVertex<V, E>; origin: E }) {
this.parent = config.parent;
this.child = config.child;
this.origin = config.origin;
}
}
// 获取根节点
function getRoot<V extends BaseVertex, E extends BaseEdge>(
vertexes: Array<Vertex<V>>,
edges: Array<Edge<E>>
): Array<Vertex<V>> {
const roots: Array<Vertex<V>> = [];
for (let i = 0; i < vertexes.length; i++) {
const id = vertexes[i].id;
// 没有上游节点,说明为根节点
if (edges.filter(edge => edge.v === id).map(edge => edge.u).length === 0) {
roots.push(vertexes[i]);
}
}
return roots;
}
/**
* 针对传入的 vertexes, edges 建立一颗索引树
* CURD 操作时都有两种模式,存在索引树,或不存在
* 注意:edge的 u,v,表示 v 是 u 的子节点,存在从属关系,无向图的树无法明确生成
* @Todo 同树同层级子节点的顺序定义
*/
class Tree<V extends BaseVertex, E extends BaseEdge> {
// 类的静态方法,是否为树
static isTree: (vertexes: Array<Vertex<BaseVertex>>, edges: Array<Edge<BaseEdge>>) => boolean;
// 类的静态方法,是否为多树
static isMulti: (vertexes: Array<Vertex<BaseVertex>>, edges: Array<Edge<BaseEdge>>) => boolean;
// 类的静态方法,解析嵌套结构
static parse: <V extends BaseVertex, E extends BaseEdge>(
tree: V[],
getId?: (node: V) => string,
getChildren?: (node: V) => V[],
getEdge?: (parent: V, child: V) => E
) => { vertexes: Array<Vertex<V>>; edges: Array<Edge<E>> };
// 外界传入的节点数据
private vertexes: Array<Vertex<V>> = [];
// 外界传入的边数据
private edges: Array<Edge<E>> = [];
// 内部索引树
private _tree: _TreeVertex<V, E> = null;
// 内部索引 Map
private _treeMap: Map<string, _TreeVertex<V, E>> = new Map();
// 内部索引树是否已经建立,已建立,使用索引树加速查询
private _treeReady: boolean = false;
// bfs 内部队列
private _bfsQueue: OutputVertex<V>[];
constructor(vertexes: Array<Vertex<V>>, edges: Array<Edge<E>>) {
if (Tree.isTree(vertexes, edges) || Tree.isMulti(vertexes, edges)) {
this.vertexes = vertexes;
this.edges = edges;
this._tree = this._createTree();
return;
}
console.error('当前数据无法成树');
}
/**
* 创建链式树,为了多树场景,需要创建一个虚拟根节点
*/
_createTree() {
this._treeReady = false;
this._treeMap.clear();
const virtualRoot = this._createVirtualRoot();
this._treeMap.set(virtualRoot.id, virtualRoot);
const root = this._getRoot();
// 虚拟根节点与真实根节点产生关联
root.forEach(node => {
const treeNode: _TreeVertex<V, E> = new _TreeVertex({
id: node.id,
type: 'realNode',
level: virtualRoot.level + 1,
parentEdge: null,
childrenEdge: [],
origin: node
});
this._addChildren(virtualRoot, treeNode);
this.dfs<_TreeVertex<V, E>, void>(
treeNode,
parent => {
const children = this.getChildren(parent.id);
return children.map(child => {
return new _TreeVertex({
id: child.id,
type: 'realNode',
level: parent.level + 1,
parentEdge: null,
childrenEdge: [],
origin: child
});
});
},
(parent, child) => {
if (child) {
this._addChildren(parent, child);
}
}
);
});
this._treeReady = true;
return virtualRoot;
}
_addChildren(parentNode: _TreeVertex<V, E>, childNode: _TreeVertex<V, E>) {
const isExistChild = find(
parentNode.childrenEdge.map(childEdge => {
return childEdge.child;
}),
child => {
return child.id === childNode.id;
}
);
if (!isExistChild) {
const edge = this.getEdge(parentNode.origin.id, childNode.origin.id);
parentNode.childrenEdge.push(
new _TreeEdge({
parent: parentNode,
child: childNode,
origin: edge
})
);
childNode.parentEdge = new _TreeEdge({
parent: parentNode,
child: childNode,
origin: edge
});
this._treeMap.set(childNode.id, childNode);
}
}
/** 创建虚拟根节点 */
_createVirtualRoot(): _TreeVertex<V, E> {
const id = VIRTUAL_ROOT_ID.toString();
return new _TreeVertex({
id,
parentEdge: null,
type: 'virtualRoot',
level: 0,
childrenEdge: [],
origin: {
id
} as V
});
}
/** dfs 遍历树 */
dfs<N extends { id: string }, R>(
node: N,
getChildren: (parent: N) => N[],
beforeCallback: (parent: N, child: N, preCallBackResult: R) => R = () => undefined,
isDfs: (id: string) => boolean = () => true,
callBackResult: R = null,
afterCallback: (parent: N, child: N, preCallBackResult: R) => void = () => undefined
) {
if (!isDfs(node.id)) {
return;
}
const children = getChildren(node);
if (children && children.length) {
children.forEach(child => {
const result = beforeCallback(node, child, callBackResult);
this.dfs(child, getChildren, beforeCallback, isDfs, result, afterCallback);
afterCallback(node, child, result);
});
} else {
const result = beforeCallback(node, null, callBackResult);
afterCallback(node, null, result);
}
}
/** bfs 遍历树 */
bfs<N extends { id: string }>(
node: N,
getChildren: (parent: N) => N[],
callback: (parent: N, child: N) => void,
isBfs: (id: string) => boolean = () => true
) {
if (!isBfs(node.id)) {
return;
}
getChildren(node).forEach(child => {
callback(node, child);
});
}
_getRoot(isVirtual?: boolean): V[] {
if (this._treeReady) {
// 返回虚拟根节点
if (isVirtual) {
return [this._tree.getOriginNode()];
}
return this._tree.getChildrenOriginNode();
} else {
return getRoot<V, E>(this.vertexes, this.edges);
}
}
/** 得到树的唯一根节点 */
getSingleRoot(): V {
const roots = this._getRoot();
return roots[0];
}
/** 得到树的多重根节点 */
getMultiRoot(): V[] {
return this._getRoot();
}
/** 获取当前节点的父节点 */
getParent(id: string): V {
if (this._treeReady) {
if (this._treeMap.has(id)) {
const parent = this._treeMap.get(id).getParent();
// 如果父元素是虚拟的根元素
if (parent.isVirtualRoot()) {
return null;
}
return parent.getOriginNode();
}
return null;
} else {
const edgeIdList = this.edges.filter(edge => edge.v === id).map(edge => edge.u);
if (edgeIdList.length === 0) {
return null;
}
return find(this.vertexes, vertex => {
return edgeIdList.indexOf(vertex.id) !== -1;
});
}
}
/** 得到当前边 */
getEdge(parentId: string, childId: string): E {
const edges = this.edges.filter(edge => {
return edge.u === parentId && edge.v === childId;
});
return edges.length === 0 ? null : edges[0];
}
/** 得到当前节点 */
getNode(id: string): V {
if (this._treeReady) {
if (this._treeMap.has(id)) {
return this._treeMap.get(id).getOriginNode();
}
return null;
} else {
const vertex = this.vertexes.filter(vertex => {
return vertex.id === id;
});
return vertex.length === 0 ? null : vertex[0];
}
}
getSibling(
id: string
): {
pre: V[];
next: V[];
index: number;
} {
if (this._treeReady) {
if (this._treeMap.has(id)) {
return this._treeMap.get(id).getSibling();
}
}
/** @todo 有点懒得写 */
return {
pre: [],
next: [],
index: -1
};
}
/** 得到子节点 */
getChildren(id: string): V[] {
if (this._treeReady) {
if (this._treeMap.has(id)) {
return this._treeMap.get(id).getChildrenOriginNode();
}
return [];
} else {
if (id === VIRTUAL_ROOT_ID.toString()) {
return this._getRoot();
}
const edgeIdList = this.edges.filter(edge => edge.u === id).map(edge => edge.v);
return this.vertexes.filter(vertex => {
return edgeIdList.indexOf(vertex.id) !== -1;
});
}
}
/** 获取节点层级 */
getLevel(id: string): number {
if (this._treeMap.has(id)) {
return this._treeMap.get(id).getLevel();
}
/** @Todo 注意异常处理 */
return null;
}
/** 得到唯一树 */
getSingleTree(id?: string, depth = -1): OutputVertex<V> {
if (id && !this._treeMap.has(id)) {
return null;
}
return this.getTree(id, depth)[0];
}
/** 得到树,子树,可定义多少深度 */
getTree(id?: string, depth = -1): OutputVertex<V>[] {
if (id && !this._treeMap.has(id)) {
return [];
}
// 如果没有 id 则默认为根节点
const nodes = id
? [
{
...(this._treeMap.get(id).getOriginNode() as any),
children: [],
_origin: this._treeMap.get(id).getOriginNode()
}
]
: this._getRoot().map(root => {
return {
...(root as any),
children: [],
_origin: root
};
});
nodes.forEach(node => {
this.dfs<OutputVertex<V>, void>(
node,
parent => {
const children = this.getChildren(parent.id);
return children.map(child => {
return {
...(child as any),
children: [],
_origin: child
};
});
},
(parent, child) => {
if (child) {
parent.children.push(child);
}
},
id => {
const currentLevel = this._treeMap.get(id).getLevel();
const level = this._treeMap.get(node.id).getLevel();
if (depth === -1 || currentLevel - level < depth - 1) {
return true;
}
return false;
}
);
});
return nodes;
}
/** 使用 BFS 获取子树 */
_getTreeByBFS(id?: string, depth = -1): OutputVertex<V>[] {
if (id && !this._treeMap.has(id)) {
return [];
}
// 如果没有 id 则默认为根节点
const nodes = id
? [
{
...(this._treeMap.get(id).getOriginNode() as any),
children: [],
_origin: this._treeMap.get(id).getOriginNode()
}
]
: this._getRoot().map(root => {
return {
...(root as any),
children: [],
_origin: root
};
});
// 深拷贝
this._bfsQueue = [...nodes];
while (this._bfsQueue.length !== 0) {
const node = this._bfsQueue.shift();
this.bfs<OutputVertex<V>>(
node,
parent => {
return this.getChildren(parent.id).map(child => {
return {
...(child as any),
children: [],
_origin: child
};
});
},
(parent, child) => {
parent.children.push(child);
this._bfsQueue.push(child);
},
id => {
const currentLevel = this._treeMap.get(id).getLevel();
const level = this._treeMap.get(nodes[0].id).getLevel();
if (depth === -1 || currentLevel - level < depth - 1) {
return true;
}
return false;
}
);
}
return nodes;
}
/**
* 获取祖孙节点的路径
*/
getPath(ancestorId: string, childId: string): V[] {
const ancestor = this.getNode(ancestorId);
if (!ancestor) return [];
let path: V[] = [];
this.dfs<V, V[]>(
ancestor,
p => {
return this.getChildren(p.id);
},
(p, child, pre) => {
if (child) {
if (childId === child.id) {
path = [...pre, child];
}
return [...pre, child];
}
return pre;
},
() => {
return path.length === 0;
},
[ancestor]
);
return path;
}
/**
* 获取两节点的最近公共祖先,
* 这里先采用在线的算法,离线适用于大量查询场景,暂时还没有
*/
getNodeRelation(node1: string, node2: string): V {
const root = this._getRoot(true)[0];
const path1 = this.getPath(root.id, node1);
const path2 = this.getPath(root.id, node2);
const commonRoot = path1.reduce((pre, item) => {
const node = find(path2, i => {
return item.id === i.id;
});
if (node) {
return node;
}
return pre;
}, null);
if (commonRoot.id === VIRTUAL_ROOT_ID.toString()) {
return null;
}
return commonRoot;
}
_translate(
vertex: OutputVertex<V>
): {
vertexes: V[];
edges: E[];
} {
const vertexResult: V[] = [vertex._origin];
const edgeResult: E[] = [];
this.dfs<OutputVertex<V>, void>(
vertex,
parent => {
parent.children.forEach(child => {
vertexResult.push(child._origin);
/** @Todo 这会造成边信息丢失,目前只能用 updateEdge 来补 */
edgeResult.push({
u: parent.id,
v: child.id
} as E);
});
return parent.children;
},
() => {}
);
return {
vertexes: vertexResult,
edges: edgeResult
};
}
/**
* 添加点,自动增加一条边
* 不存在 parentId,即新开一棵树,挂载到虚拟节点上
*/
addVertex(vertex: V, parentId = VIRTUAL_ROOT_ID.toString()): void {
if (!this._treeMap.has(parentId)) {
return;
}
this.edges =
parentId === VIRTUAL_ROOT_ID.toString() ? this.edges : [...this.edges, { u: parentId, v: vertex.id } as E];
this.vertexes = [...this.vertexes, vertex];
const parent = this._treeMap.get(parentId);
const newTreeNode = new _TreeVertex<V, E>({
id: vertex.id,
parentEdge: null,
type: 'realNode',
level: parent.level + 1,
childrenEdge: [],
origin: vertex
});
this._addChildren(parent, newTreeNode);
}
/**
* 添加子树,自动增加一条边
* 不存在 parentId,即新开一棵树,挂载到虚拟节点上
*/
addChildTree(vertex: OutputVertex<V>, parentId = VIRTUAL_ROOT_ID.toString()): void {
if (!this._treeMap.has(parentId)) {
return;
}
// 虚拟节点与真实节点的边不加入 this.edges
this.edges =
parentId === VIRTUAL_ROOT_ID.toString() ? this.edges : [...this.edges, { u: parentId, v: vertex.id } as E];
const { vertexes, edges } = this._translate(vertex);
this.vertexes = [...this.vertexes, ...vertexes];
this.edges = [...this.edges, ...edges];
this._treeReady = false;
const parent = this._treeMap.get(parentId);
this.dfs<_TreeVertex<V, E>, void>(
parent,
parent => {
const children = this.getChildren(parent.id);
return children.map(child => {
return new _TreeVertex<V, E>({
id: child.id,
parentEdge: null,
type: 'realNode',
level: parent.level + 1,
childrenEdge: [],
origin: child
});
});
},
(parent, child) => {
if (child) {
this._addChildren(parent, child);
}
}
);
this._treeReady = true;
}
/**
* 删除节点及其所有下游节点
* 返回删除的子树
*/
deleteVertex(vertexId: string): OutputVertex<V> {
if (!this._treeMap.has(vertexId)) {
return null;
}
const childTree = this.getSingleTree(vertexId);
const parent = this._treeMap.get(vertexId).getParent();
const { vertexes, edges } = this._translate(childTree);
this.vertexes = this.vertexes.filter(vertex => {
return find(vertexes, item => {
return item.id === vertex.id;
})
? false
: true;
});
this.edges = this.edges.filter(edge => {
return find(edges, e => {
return (edge.u === e.u && edge.v === e.v) || (edge.u === parent.id && edge.v === vertexId);
})
? false
: true;
});
// 清除 _tree 与 _treeMap
vertexes.forEach(vertex => {
this._treeMap.delete(vertex.id);
});
parent.childrenEdge = parent.childrenEdge.filter(childEdge => {
return childEdge.child.id !== vertexId;
});
return childTree;
}
/**
* 更新节点
*/
updateVertex(vertex: V): void {
this.vertexes = this.vertexes.map(item => {
if (item.id === vertex.id) {
return vertex;
}
return item;
});
if (this._treeMap.has(vertex.id)) {
// 修改引用
const oldVertex = this._treeMap.get(vertex.id);
oldVertex.origin = vertex;
}
}
/**
* 更新边
*/
updateEdge(edge: E): void {
this.edges = this.edges.map(e => {
if (e.u === edge.u && e.v === edge.v) {
return edge;
}
return e;
});
}
/**
* 删除边,同时删除与关联的下游节点
* 返回下游子树
*/
deleteEdge(u: string, v: string): OutputVertex<V> {
if (!this._treeMap.has(u) || !this._treeMap.has(v)) {
return null;
}
this.edges = this.edges.filter(edge => {
return edge.u !== u && edge.v !== edge.v;
});
return this.deleteVertex(v);
}
getVertexes() {
return this.vertexes;
}
getEdges() {
return this.edges;
}
/** 获取当前节点所有的叶子节点 */
getLeafVertexes(id?: string, depth = -1): V[] {
const { vertexes } = this._translate(this._getTreeByBFS(id, depth)[0]);
return vertexes.filter(node => {
return this.getChildren(node.id).length === 0;
});
}
}
// 判断是否为树
Tree.isTree = (vertexes: Array<Vertex<BaseVertex>>, edges: Array<Edge<BaseEdge>>): boolean => {
const visitedList: string[] = [];
function dfs(node: Vertex<BaseVertex>) {
if (visitedList.indexOf(node.id) !== -1) {
return false;
}
visitedList.push(node.id);
const edgeIdList = edges.filter(edge => edge.u === node.id).map(edge => edge.v);
const children = vertexes.filter(vertex => {
return edgeIdList.indexOf(vertex.id) !== -1;
});
for (let i = 0; i < children.length; i++) {
if (!dfs(children[i])) {
return false;
}
}
return true;
}
// 树必然 n 个节点,n - 1 条边
if (vertexes.length !== edges.length + 1) {
return false;
}
// 不存在环
const roots = getRoot<BaseVertex, BaseEdge>(vertexes, edges);
if (roots.length === 1) {
return dfs(roots[0]);
}
return false;
};
// 判断是否为多树,寻找出多个根节点,用虚拟根节点连接,能形成一颗树
Tree.isMulti = (vertexes: Array<Vertex<BaseVertex>>, edges: Array<Edge<BaseEdge>>): boolean => {
const roots = getRoot<BaseVertex, BaseEdge>(vertexes, edges);
if (roots.length <= 1) {
return false;
}
const virtualRootId = VIRTUAL_ROOT_ID.toString();
return Tree.isTree(
[...vertexes, { id: virtualRootId }],
[
...edges,
...roots.map(node => {
return {
u: virtualRootId,
v: node.id
};
})
]
);
};
/** 解析嵌套的树结构 */
Tree.parse = <V extends BaseVertex, E extends BaseEdge>(
tree: V[],
getId?: (node: V) => string,
getChildren?: (node: V) => V[],
getEdge?: (parent: V, child: V) => E
) => {
const getIdHandler = getId
? getId
: (node: any) => {
return node.id;
};
const getChildrenHandler = getChildren
? getChildren
: (node: any) => {
return node.children;
};
const vertexes: Array<Vertex<V>> = [];
const edges: Array<Edge<E>> = [];
const visitedList: string[] = [];
function dfs(node: V) {
const id = getIdHandler(node);
node.id = id;
if (visitedList.indexOf(id) !== -1) {
console.error('存在环!');
return false;
}
visitedList.push(id);
vertexes.push(node);
const children: V[] = getChildrenHandler(node);
if (children && children.length) {
for (let i = 0; i < children.length; i++) {
const child = children[i];
const childId = getIdHandler(child);
child.id = childId;
const edge = getEdge
? getEdge(node, child)
: ({
u: id,
v: childId
} as E);
edges.push(edge);
dfs(child);
}
}
}
for (let i = 0; i < tree.length; i++) {
dfs(tree[i]);
}
return {
vertexes,
edges
};
};
export default Tree; | the_stack |
import { Event } from '@linode/api-v4/lib/account';
import { path } from 'ramda';
import { isProductionBuild } from 'src/constants';
import { reportException } from 'src/exceptionReporting';
type EventMessageCreator = (e: Event) => string;
interface CreatorsForStatus {
scheduled?: EventMessageCreator;
started?: EventMessageCreator;
failed?: EventMessageCreator;
finished?: EventMessageCreator;
notification?: EventMessageCreator;
}
export const safeSecondaryEntityLabel = (
e: Event,
text: string,
fallback: string = ''
) => {
const label = e?.secondary_entity?.label;
return label ? `${text} ${label}` : fallback;
};
/** @see https://leo.stcloudstate.edu/grammar/tenses.html */
export const eventMessageCreators: { [index: string]: CreatorsForStatus } = {
account_agreement_eu_model: {
notification: () => 'The EU Model Contract has been signed.',
},
account_update: {
notification: (e) => `Your account settings have been updated.`,
},
account_settings_update: {
notification: (e) => `Your account settings have been updated.`,
},
backups_cancel: {
notification: (e) => `Backups have been canceled for ${e.entity!.label}.`,
},
backups_enable: {
notification: (e) => `Backups have been enabled for ${e.entity!.label}.`,
},
backups_restore: {
scheduled: (e) => `Backup restoration scheduled for ${e.entity!.label}`,
started: (e) => `Backup restoration started for ${e.entity!.label}`,
failed: (e) => `Backup restoration failed for ${e.entity!.label}.`,
finished: (e) => `Backup restoration completed for ${e.entity!.label}.`,
notification: (e) => `Backup restoration completed for ${e.entity!.label}.`,
},
community_question_reply: {
notification: (e) =>
`There has been a reply to your thread "${e.entity!.label}".`,
},
community_like: {
notification: (e) => e.entity!.label,
},
community_mention: {
notification: (e) =>
`You have been mentioned in a Community post: ${e.entity!.label}`,
},
credit_card_updated: {
notification: (e) => `Credit card information has been updated.`,
},
disk_create: {
scheduled: (e) =>
`${safeSecondaryEntityLabel(
e,
'Disk',
'A disk'
)} is being added to Linode ${e.entity!.label}.`,
started: (e) =>
`${safeSecondaryEntityLabel(e, 'Disk', 'A disk')} is being added to ${
e.entity!.label
}.`,
failed: (e) =>
`${safeSecondaryEntityLabel(
e,
'Disk',
'A disk'
)} could not be added to Linode ${e.entity!.label}.`,
finished: (e) =>
`${safeSecondaryEntityLabel(
e,
'Disk',
'A disk'
)} has been added to Linode ${e.entity!.label}.`,
// notification: e => ``,
},
disk_update: {
notification: (e) =>
`${safeSecondaryEntityLabel(
e,
'Disk',
'A disk'
)} has been updated on Linode ${e.entity!.label}.`,
},
disk_delete: {
scheduled: (e) =>
`${safeSecondaryEntityLabel(e, 'Disk', 'A disk')} on Linode ${
e.entity!.label
} is scheduled for deletion.`,
started: (e) =>
`${safeSecondaryEntityLabel(e, 'Disk', 'A disk')} on Linode ${
e.entity!.label
} is being deleted.`,
failed: (e) =>
`${safeSecondaryEntityLabel(e, 'Disk', 'A disk')} on Linode ${
e.entity!.label
} could not be deleted.`,
finished: (e) =>
`${safeSecondaryEntityLabel(e, 'Disk', 'A disk')} on Linode ${
e.entity!.label
} has been deleted`,
// notification: e => ``,
},
disk_duplicate: {
scheduled: (e) =>
`A disk on Linode ${e.entity!.label} is scheduled for duplication.`,
started: (e) => `A disk on Linode ${e.entity!.label} is being duplicated.`,
failed: (e) =>
`A disk on Linode ${e.entity!.label} could not be duplicated.`,
finished: (e) => `A disk on Linode ${e.entity!.label} has been duplicated`,
// notification: e => ``,
},
disk_imagize: {
scheduled: (e) =>
`Image ${e?.secondary_entity?.label + ' ' ?? ''}scheduled for creation.`,
started: (e) =>
`Image ${e?.secondary_entity?.label + ' ' ?? ''}being created.`,
failed: (e) => `Error creating Image ${e?.secondary_entity?.label ?? ''}.`,
finished: (e) =>
`Image ${e?.secondary_entity?.label + ' ' ?? ''}has been created.`,
},
disk_resize: {
scheduled: (e) => `A disk on ${e.entity!.label} is scheduled for resizing.`,
started: (e) => `A disk on Linode ${e.entity!.label} is being resized.`,
failed: (e) => `A disk on Linode ${e.entity!.label} could not be resized.`,
finished: (e) => `A disk on Linode ${e.entity!.label} has been resized`,
// notification: e => ``,
},
dns_record_create: {
notification: (e) => `DNS record has been added to ${e.entity!.label}`,
},
dns_record_delete: {
notification: (e) => `DNS record has been removed from ${e.entity!.label}`,
},
dns_zone_create: {
notification: (e) => `DNS zone has been added to ${e.entity!.label}`,
},
dns_zone_delete: {
notification: (e) => `DNS zone has been removed from ${e.entity!.label}`,
},
domain_create: {
notification: (e) => `Domain ${e.entity!.label} has been created.`,
},
domain_update: {
notification: (e) => `Domain ${e.entity!.label} has been updated.`,
},
domain_delete: {
notification: (e) => `Domain ${e.entity!.label} has been deleted.`,
},
domain_record_create: {
notification: (e) => `${e.message} added to ${e.entity!.label}`,
},
domain_record_update: {
notification: (e) => `${e.message} updated for ${e.entity!.label}`,
},
domain_record_delete: {
notification: (e) =>
`A domain record has been deleted from ${e.entity!.label}`,
},
domain_import: {
notification: (e) => `Domain ${e.entity?.label ?? ''} has been imported.`,
},
entity_transfer_accept: {
notification: (_) => `A service transfer has been accepted.`,
},
entity_transfer_accept_recipient: {
notification: (_) => `You have accepted a service transfer.`,
},
entity_transfer_cancel: {
notification: (_) => `A service transfer has been canceled.`,
},
entity_transfer_create: {
notification: (_) => `A service transfer has been created.`,
},
entity_transfer_fail: {
notification: (_) => `Service transfer failed.`,
},
entity_transfer_stale: {
notification: (_) => `A service transfer token has expired.`,
},
firewall_enable: {
notification: (e) => `Firewall ${e.entity?.label ?? ''} has been enabled.`,
},
firewall_disable: {
notification: (e) => `Firewall ${e.entity?.label ?? ''} has been disabled.`,
},
firewall_update: {
notification: (e) => `Firewall ${e.entity?.label ?? ''} has been updated.`,
},
firewall_device_add: {
notification: (e) =>
`A device has been added to Firewall ${e.entity?.label ?? ''}.`,
},
firewall_device_remove: {
notification: (e) =>
`A device has been removed from Firewall ${e.entity?.label ?? ''}.`,
},
firewall_delete: {
notification: (e) => `Firewall ${e.entity?.label ?? ''} has been deleted.`,
},
firewall_create: {
notification: (e) => `Firewall ${e.entity?.label ?? ''} has been created.`,
},
image_update: {
notification: (e) => `Image ${e.entity?.label ?? ''} has been updated.`,
},
image_delete: {
scheduled: (e) => `Image ${e.entity?.label ?? ''} scheduled for deletion.`,
started: (e) => `Image ${e.entity?.label ?? ''} is being deleted.`,
failed: (e) => `There was a problem deleting ${e.entity?.label ?? ''}.`,
finished: (e) => `Image ${e.entity?.label ?? ''} has been deleted.`,
notification: (e) => `Image ${e.entity?.label ?? ''} has been deleted.`,
},
image_upload: {
scheduled: (e) => `Image ${e.entity?.label ?? ''} scheduled for upload.`,
started: (e) => `Image ${e.entity?.label ?? ''} is being uploaded.`,
failed: (e) => `There was a problem uploading ${e.entity?.label ?? ''}.`,
finished: (e) => `Image ${e.entity?.label ?? ''} has been uploaded.`,
notification: (e) => `Image ${e.entity?.label ?? ''} has been uploaded.`,
},
linode_addip: {
notification: (e) => `An IP has been added to ${e.entity!.label}.`,
},
linode_boot: {
scheduled: (e) =>
`Linode ${e.entity!.label} is scheduled to ${safeSecondaryEntityLabel(
e,
'boot with config',
'boot'
)}.`,
started: (e) =>
`Linode ${e.entity!.label} is being ${safeSecondaryEntityLabel(
e,
'booted with config',
'booted'
)}.`,
failed: (e) =>
`Linode ${e.entity!.label} could not be ${safeSecondaryEntityLabel(
e,
'booted with config',
'booted'
)}.`,
finished: (e) =>
`Linode ${e.entity!.label} has been ${safeSecondaryEntityLabel(
e,
'booted with config',
'booted'
)}.`,
},
/**
* For these events, we expect an entity (the Linode being rebooted)
* but there have been cases where an event has come through with
* entity === null. Handle them safely.
*/
lassie_reboot: {
scheduled: (e) =>
`Linode ${
e.entity?.label ?? ''
} is scheduled to be rebooted by the Lassie watchdog service.`,
started: (e) =>
`Linode ${
e.entity?.label ?? ''
} is being booted by the Lassie watchdog service.`,
failed: (e) =>
`Linode ${
e.entity?.label ?? ''
} could not be booted by the Lassie watchdog service.`,
finished: (e) =>
`Linode ${
e.entity?.label ?? ''
} has been booted by the Lassie watchdog service.`,
},
host_reboot: {
scheduled: (e) =>
`Linode ${
e.entity?.label ?? ''
} is scheduled to reboot (Host initiated restart).`,
started: (e) =>
`Linode ${
e.entity?.label ?? ''
} is being booted (Host initiated restart).`,
failed: (e) =>
`Linode ${
e.entity?.label ?? ''
} could not be booted (Host initiated restart).`,
finished: (e) =>
`Linode ${
e.entity?.label ?? ''
} has been booted (Host initiated restart).`,
},
ipaddress_update: {
notification: (e) => `An IP address has been updated on your account.`,
},
lish_boot: {
scheduled: (e) =>
`Linode ${
e.entity?.label ?? ''
} is scheduled to boot (Lish initiated boot).`,
started: (e) =>
`Linode ${e.entity?.label ?? ''} is being booted (Lish initiated boot).`,
failed: (e) =>
`Linode ${
e.entity?.label ?? ''
} could not be booted (Lish initiated boot).`,
finished: (e) =>
`Linode ${e.entity?.label ?? ''} has been booted (Lish initiated boot).`,
},
linode_clone: {
scheduled: (e) =>
`Linode ${
e.entity?.label ?? ''
} is scheduled to be cloned${safeSecondaryEntityLabel(e, ' to', '')}.`,
started: (e) =>
`Linode ${
e.entity?.label ?? ''
} is being cloned${safeSecondaryEntityLabel(e, ' to', '')}.`,
failed: (e) =>
`Linode ${
e.entity?.label ?? ''
} could not be cloned${safeSecondaryEntityLabel(e, ' to', '')}.`,
finished: (e) =>
`Linode ${
e.entity?.label ?? ''
} has been cloned${safeSecondaryEntityLabel(e, ' to', '')}.`,
notification: (e) =>
`Linode ${e.entity?.label ?? ''} is scheduled to be cloned.`,
},
linode_create: {
scheduled: (e) => `Linode ${e.entity!.label} is scheduled for creation.`,
started: (e) => `Linode ${e.entity!.label} is being created.`,
failed: (e) => `Linode ${e.entity!.label} could not be created.`,
finished: (e) => `Linode ${e.entity!.label} has been created.`,
},
linode_update: {
notification: (e) => `Linode ${e.entity!.label} has been updated.`,
},
linode_delete: {
scheduled: (e) => `Linode ${e.entity!.label} is scheduled for deletion.`,
started: (e) => `Linode ${e.entity!.label} is being deleted.`,
failed: (e) => `Linode ${e.entity!.label} could not be deleted.`,
finished: (e) => `Linode ${e.entity!.label} has been deleted.`,
notification: (e) => `Linode ${e.entity!.label} has been deleted.`,
},
linode_deleteip: {
notification: (e) => `An IP was deleted from Linode ${e.entity!.id}`,
},
linode_migrate: {
scheduled: (e) =>
`Linode ${e.entity?.label ?? ''} is scheduled for migration.`,
started: (e) => `Linode ${e.entity?.label ?? ''} is being migrated.`,
failed: (e) => `Migration failed for Linode ${e.entity?.label ?? ''}.`,
finished: (e) => `Linode ${e.entity?.label ?? ''} has been migrated.`,
},
// This event type isn't currently being displayed, but I added a message here just in case.
linode_migrate_datacenter_create: {
notification: (e) =>
`Migration for Linode ${e.entity!.label} has been initiated.`,
},
// These are the same as the messages for `linode_migrate`.
linode_migrate_datacenter: {
scheduled: (e) =>
`Linode ${e.entity?.label ?? ''} is scheduled for migration.`,
started: (e) => `Linode ${e.entity?.label ?? ''} is being migrated.`,
failed: (e) => `Migration failed for Linode ${e.entity?.label ?? ''}.`,
finished: (e) => `Linode ${e.entity?.label ?? ''} has been migrated.`,
},
// This event type isn't currently being displayed, but I added a message here just in case.
linode_mutate_create: {
notification: (e) =>
`Upgrade for Linode ${e.entity!.label} has been initiated.`,
},
linode_mutate: {
scheduled: (e) =>
`Linode ${e.entity?.label ?? ''} is scheduled for an upgrade.`,
started: (e) => `Linode ${e.entity?.label ?? ''} is being upgraded.`,
failed: (e) => `Linode ${e.entity?.label ?? ''} could not be upgraded.`,
finished: (e) => `Linode ${e.entity?.label ?? ''} has been upgraded.`,
notification: (e) => `Linode ${e.entity?.label ?? ''} is being upgraded.`,
},
linode_reboot: {
scheduled: (e) =>
`Linode ${e.entity!.label} is scheduled ${safeSecondaryEntityLabel(
e,
'for a reboot with config',
'for a reboot'
)}.`,
started: (e) =>
`Linode ${e.entity!.label} is being ${safeSecondaryEntityLabel(
e,
'rebooted with config',
'rebooted'
)}.`,
failed: (e) =>
`Linode ${e.entity!.label} could not be ${safeSecondaryEntityLabel(
e,
'rebooted with config',
'rebooted'
)}.`,
finished: (e) =>
`Linode ${e.entity!.label} has been ${safeSecondaryEntityLabel(
e,
'rebooted with config',
'rebooted'
)}.`,
},
linode_rebuild: {
scheduled: (e) => `Linode ${e.entity!.label} is scheduled for rebuild.`,
started: (e) => `Linode ${e.entity!.label} is being rebuilt.`,
failed: (e) => `Linode ${e.entity!.label} could not be rebuilt.`,
finished: (e) => `Linode ${e.entity!.label} has been rebuilt.`,
},
// This event type isn't currently being displayed, but I added a message here just in case.
linode_resize_create: {
notification: (e) =>
`Resize for Linode ${e.entity!.label} has been initiated.`,
},
linode_resize: {
scheduled: (e) =>
`Linode ${e.entity?.label ?? ''} is scheduled for resizing.`,
started: (e) => `Linode ${e.entity?.label ?? ''} is resizing.`,
failed: (e) => `Linode ${e.entity?.label ?? ''} could not be resized`,
finished: (e) => `Linode ${e.entity?.label ?? ''} has been resized.`,
},
linode_shutdown: {
scheduled: (e) => `Linode ${e.entity!.label} is scheduled for shutdown.`,
started: (e) => `Linode ${e.entity!.label} is shutting down.`,
failed: (e) => `Linode ${e.entity!.label} could not be shut down.`,
finished: (e) => `Linode ${e.entity!.label} has been shut down.`,
},
linode_snapshot: {
scheduled: (e) =>
`Linode ${e.entity!.label} is scheduled for a snapshot backup.`,
started: (e) =>
`A snapshot backup is being created for Linode ${e.entity!.label}.`,
failed: (e) => `Snapshot backup failed on Linode ${e.entity!.label}.`,
finished: (e) =>
`A snapshot backup has been created for ${e.entity!.label}.`,
},
linode_config_create: {
notification: (e) =>
`${safeSecondaryEntityLabel(
e,
'Config',
'A config'
)} has been created on Linode ${e.entity!.label}.`,
},
linode_config_update: {
notification: (e) =>
`${safeSecondaryEntityLabel(
e,
'Config',
'A config'
)} has been updated on Linode ${e.entity!.label}.`,
},
linode_config_delete: {
notification: (e) =>
`${safeSecondaryEntityLabel(
e,
'Config',
'A config'
)} has been deleted on Linode ${e.entity!.label}.`,
},
lke_node_create: {
// This event is a special case; a notification means the node creation failed.
// The entity is the node pool, but entity.label contains the cluster's label.
notification: (e) =>
`Failed to create a node on Kubernetes Cluster${
e.entity?.label ? ` ${e.entity.label}` : ''
}.`,
},
longviewclient_create: {
notification: (e) => `Longview Client ${e.entity!.label} has been created.`,
},
longviewclient_delete: {
notification: (e) => `Longview Client ${e.entity!.label} has been deleted.`,
},
longviewclient_update: {
notification: (e) => `Longview Client ${e.entity!.label} has been updated.`,
},
// managed_disabled: {
// scheduled: e => ``,
// started: e => ``,
// failed: e => ``,
// finished: e => ``,
// notification: e => ``,
// },
managed_enabled: {
notification: (e) => `Managed has been activated on your account.`,
},
managed_service_create: {
notification: (e) => `Managed service ${e.entity!.label} has been created.`,
},
managed_service_delete: {
notification: (e) => `Managed service ${e.entity!.label} has been deleted.`,
},
nodebalancer_config_create: {
notification: (e) =>
`A config on NodeBalancer ${e.entity!.label} has been created.`,
},
nodebalancer_config_update: {
notification: (e) =>
`A config on NodeBalancer ${e.entity!.label} has been updated.`,
},
nodebalancer_config_delete: {
notification: (e) =>
`A config on NodeBalancer ${e.entity!.label} has been deleted.`,
},
nodebalancer_create: {
notification: (e) => `NodeBalancer ${e.entity!.label} has been created.`,
},
nodebalancer_update: {
notification: (e) => `NodeBalancer ${e.entity!.label} has been updated.`,
},
nodebalancer_delete: {
notification: (e) => `NodeBalancer ${e.entity!.label} has been deleted.`,
},
nodebalancer_node_create: {
notification: (e) =>
`A node on NodeBalancer ${e.entity!.label} has been created.`,
},
nodebalancer_node_delete: {
notification: (e) =>
`A node on NodeBalancer ${e.entity!.label} has been deleted.`,
},
nodebalancer_node_update: {
notification: (e) =>
`A node on NodeBalancer ${e.entity!.label} has been updated.`,
},
oauth_client_create: {
notification: (e) => `OAuth App ${e.entity!.label} has been created.`,
},
oauth_client_update: {
notification: (e) => `OAuth App ${e.entity!.label} has been updated.`,
},
oauth_client_secret_reset: {
notification: (e) =>
`Secret for OAuth App ${e.entity!.label} has been reset.`,
},
oauth_client_delete: {
notification: (e) => `OAuth App ${e.entity!.label} has been deleted.`,
},
password_reset: {
scheduled: (e) => `A password reset is scheduled for ${e.entity!.label}.`,
started: (e) => `The password for ${e.entity!.label} is being reset.`,
failed: (e) => `Password reset failed for Linode ${e.entity!.label}.`,
finished: (e) => `Password has been reset on Linode ${e.entity!.label}.`,
},
profile_update: {
notification: (e) => `Your profile has been updated.`,
},
payment_submitted: {
notification: (e) => `A payment was successfully submitted.`,
},
payment_method_add: {
notification: (e) => `A payment method was added.`,
},
account_promo_apply: {
notification: (e) => `A promo code was applied to your account.`,
},
stackscript_create: {
notification: (e) => `StackScript ${e.entity!.label} has been created.`,
},
stackscript_update: {
notification: (e) => `StackScript ${e.entity!.label} has been updated.`,
},
stackscript_delete: {
notification: (e) => `StackScript ${e.entity!.label} has been deleted.`,
},
stackscript_publicize: {
notification: (e) => `StackScript ${e.entity!.label} has been made public.`,
},
stackscript_revise: {
notification: (e) => `StackScript ${e.entity!.label} has been revised.`,
},
tag_create: {
notification: (e) => `Tag ${e.entity!.label} has been created.`,
},
tag_delete: {
notification: (e) => `Tag ${e.entity!.label} has been deleted.`,
},
tfa_disabled: {
notification: (e) => `Two-factor authentication has been disabled.`,
},
tfa_enabled: {
notification: (e) => `Two-factor authentication has been enabled.`,
},
ticket_create: {
notification: (e) => `New support ticket "${e.entity!.label}" created.`,
},
// ticket_reply: {
// scheduled: e => ``,
// started: e => ``,
// failed: e => ``,
// finished: e => ``,
// notification: e => ``,
// },
ticket_update: {
notification: (e) =>
`Support ticket "${e.entity!.label}" has been updated.`,
},
ticket_attachment_upload: {
notification: (e) =>
`File has been successfully uploaded to support ticket ${
e.entity!.label
}`,
},
token_create: {
notification: (e) => `Token ${e.entity!.label} has been created.`,
},
token_update: {
notification: (e) => `Token ${e.entity!.label} has been updated.`,
},
token_delete: {
notification: (e) => `Token ${e.entity!.label} has been revoked.`,
},
volume_attach: {
// @todo Once we have better events, display the name of the attached Linode
// in these messages.
scheduled: (e) => `Volume ${e.entity!.label} is scheduled to be attached.`,
started: (e) => `Volume ${e.entity!.label} is being attached.`,
failed: (e) => `Volume ${e.entity!.label} failed to attach.`,
finished: (e) => `Volume ${e.entity!.label} has been attached.`,
notification: (e) => `Volume ${e.entity!.label} has been attached.`,
},
volume_clone: {
notification: (e) => `Volume ${e.entity!.label} has been cloned.`,
},
volume_create: {
scheduled: (e) => `Volume ${e.entity!.label} is scheduled for creation.`,
started: (e) => `Volume ${e.entity!.label} is being created.`,
failed: (e) => `Creation of volume ${e.entity!.label} failed.`,
finished: (e) => `Volume ${e.entity!.label} has been created.`,
notification: (e) => `Volume ${e.entity!.label} has been created.`,
},
volume_update: {
notification: (e) => `Volume ${e.entity!.label} has been updated.`,
},
volume_delete: {
scheduled: (e) => ``,
started: (e) => ``,
failed: (e) => ``,
finished: (e) => ``,
notification: (e) => `Volume ${e.entity!.label} has been deleted.`,
},
volume_detach: {
// @todo Once we have better events, display the name of the attached Linode
// in these messages.
scheduled: (e) => `Volume ${e.entity!.label} is scheduled for detachment.`,
started: (e) => `Volume ${e.entity!.label} is being detached.`,
failed: (e) => `Volume ${e.entity!.label} failed to detach.`,
finished: (e) => `Volume ${e.entity!.label} has been detached.`,
notification: (e) => `Volume ${e.entity!.label} has been detached.`,
},
volume_resize: {
notification: (e) => `Volume ${e.entity!.label} has been resized.`,
},
user_ssh_key_add: {
notification: (e) => `An SSH key has been added to your profile.`,
},
user_ssh_key_update: {
notification: (e) => `An SSH key on your profile has been updated.`,
},
user_ssh_key_delete: {
notification: (e) => `An SSH key has been removed from your profile.`,
},
user_create: {
notification: (e) => `User ${e.entity!.label} has been created.`,
},
user_delete: {
notification: (e) => `User ${e.entity!.label} has been deleted.`,
},
user_update: {
notification: (e) => `User ${e.entity!.label} has been updated.`,
},
};
export const formatEventWithAPIMessage = (e: Event) => {
/**
* It would be great to format this better, but:
* 1. Action names include gotchas that prevent simple capitalization or trimming rules.
* 2. Provided API messages *should* make it clear what action they're referring to,
* but we don't have such a guarantee.
*/
return `${e.action}: ${e.message}`;
};
export default (e: Event): string => {
const fn = path<EventMessageCreator>(
[e.action, e.status],
eventMessageCreators
);
/** we couldn't find the event in our list above */
if (!fn) {
/** log unknown events to the console */
if (!isProductionBuild) {
/* eslint-disable no-console */
console.error('============================================');
console.error('Unknown API Event Received');
console.log(e);
console.error('============================================');
}
/** finally return some default fallback text */
return e.message
? formatEventWithAPIMessage(e)
: `${e.action}${e.entity ? ` on ${e.entity.label}` : ''}`;
}
let message = '';
try {
message = fn(e);
} catch (error) {
/** report our error to sentry */
reportException('Known API Event Received with Error', {
event_data: e,
error,
});
}
/** return either the message or an empty string */
return message;
}; | the_stack |
import ReactDOM from "react-dom";
import { render } from "./test-utils";
import App from "../components/App";
import { defaultLang, setLanguage } from "../i18n";
import { UI, Pointer } from "./helpers/ui";
import { API } from "./helpers/api";
import { actionFlipHorizontal, actionFlipVertical } from "../actions";
const { h } = window;
const mouse = new Pointer("mouse");
beforeEach(async () => {
// Unmount ReactDOM from root
ReactDOM.unmountComponentAtNode(document.getElementById("root")!);
mouse.reset();
await setLanguage(defaultLang);
await render(<App />);
});
const createAndSelectOneRectangle = (angle: number = 0) => {
UI.createElement("rectangle", {
x: 0,
y: 0,
width: 100,
height: 50,
angle,
});
};
const createAndSelectOneDiamond = (angle: number = 0) => {
UI.createElement("diamond", {
x: 0,
y: 0,
width: 100,
height: 50,
angle,
});
};
const createAndSelectOneEllipse = (angle: number = 0) => {
UI.createElement("ellipse", {
x: 0,
y: 0,
width: 100,
height: 50,
angle,
});
};
const createAndSelectOneArrow = (angle: number = 0) => {
UI.createElement("arrow", {
x: 0,
y: 0,
width: 100,
height: 50,
angle,
});
};
const createAndSelectOneLine = (angle: number = 0) => {
UI.createElement("line", {
x: 0,
y: 0,
width: 100,
height: 50,
angle,
});
};
const createAndReturnOneDraw = (angle: number = 0) => {
return UI.createElement("freedraw", {
x: 0,
y: 0,
width: 50,
height: 100,
angle,
});
};
// Rectangle element
it("flips an unrotated rectangle horizontally correctly", () => {
createAndSelectOneRectangle();
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipHorizontal);
// Check if x position did not change
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
});
it("flips an unrotated rectangle vertically correctly", () => {
createAndSelectOneRectangle();
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipVertical);
// Check if x position did not change
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
});
it("flips a rotated rectangle horizontally correctly", () => {
const originalAngle = (3 * Math.PI) / 4;
const expectedAngle = (5 * Math.PI) / 4;
createAndSelectOneRectangle(originalAngle);
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipHorizontal);
// Check if x position did not change
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
// Check angle
expect(API.getSelectedElements()[0].angle).toBeCloseTo(expectedAngle);
});
it("flips a rotated rectangle vertically correctly", () => {
const originalAngle = (3 * Math.PI) / 4;
const expectedAgnle = Math.PI / 4;
createAndSelectOneRectangle(originalAngle);
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipVertical);
// Check if x position did not change
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
// Check angle
expect(API.getSelectedElements()[0].angle).toBeCloseTo(expectedAgnle);
});
// Diamond element
it("flips an unrotated diamond horizontally correctly", () => {
createAndSelectOneDiamond();
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipHorizontal);
// Check if x position did not change
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
});
it("flips an unrotated diamond vertically correctly", () => {
createAndSelectOneDiamond();
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipVertical);
// Check if x position did not change
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
});
it("flips a rotated diamond horizontally correctly", () => {
const originalAngle = (5 * Math.PI) / 4;
const expectedAngle = (3 * Math.PI) / 4;
createAndSelectOneDiamond(originalAngle);
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipHorizontal);
// Check if x position did not change
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
// Check angle
expect(API.getSelectedElements()[0].angle).toBeCloseTo(expectedAngle);
});
it("flips a rotated diamond vertically correctly", () => {
const originalAngle = (5 * Math.PI) / 4;
const expectedAngle = (7 * Math.PI) / 4;
createAndSelectOneDiamond(originalAngle);
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipVertical);
// Check if x position did not change
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
// Check angle
expect(API.getSelectedElements()[0].angle).toBeCloseTo(expectedAngle);
});
// Ellipse element
it("flips an unrotated ellipse horizontally correctly", () => {
createAndSelectOneEllipse();
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipHorizontal);
// Check if x position did not change
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
});
it("flips an unrotated ellipse vertically correctly", () => {
createAndSelectOneEllipse();
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipVertical);
// Check if x position did not change
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
});
it("flips a rotated ellipse horizontally correctly", () => {
const originalAngle = (7 * Math.PI) / 4;
const expectedAngle = Math.PI / 4;
createAndSelectOneEllipse(originalAngle);
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipHorizontal);
// Check if x position did not change
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
// Check angle
expect(API.getSelectedElements()[0].angle).toBeCloseTo(expectedAngle);
});
it("flips a rotated ellipse vertically correctly", () => {
const originalAngle = (7 * Math.PI) / 4;
const expectedAngle = (5 * Math.PI) / 4;
createAndSelectOneEllipse(originalAngle);
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipVertical);
// Check if x position did not change
expect(API.getSelectedElements()[0].x).toEqual(0);
expect(API.getSelectedElements()[0].y).toEqual(0);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
// Check angle
expect(API.getSelectedElements()[0].angle).toBeCloseTo(expectedAngle);
});
// Arrow element
it("flips an unrotated arrow horizontally correctly", () => {
createAndSelectOneArrow();
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipHorizontal);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
});
it("flips an unrotated arrow vertically correctly", () => {
createAndSelectOneArrow();
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipVertical);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
});
it("flips a rotated arrow horizontally correctly", () => {
const originalAngle = Math.PI / 4;
const expectedAngle = (7 * Math.PI) / 4;
createAndSelectOneArrow(originalAngle);
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipHorizontal);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
// Check angle
expect(API.getSelectedElements()[0].angle).toBeCloseTo(expectedAngle);
});
it("flips a rotated arrow vertically correctly", () => {
const originalAngle = Math.PI / 4;
const expectedAngle = (3 * Math.PI) / 4;
createAndSelectOneArrow(originalAngle);
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipVertical);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
// Check angle
expect(API.getSelectedElements()[0].angle).toBeCloseTo(expectedAngle);
});
// Line element
it("flips an unrotated line horizontally correctly", () => {
createAndSelectOneLine();
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipHorizontal);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
});
it("flips an unrotated line vertically correctly", () => {
createAndSelectOneLine();
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipVertical);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
});
it("flips a rotated line horizontally correctly", () => {
const originalAngle = Math.PI / 4;
const expectedAngle = (7 * Math.PI) / 4;
createAndSelectOneLine(originalAngle);
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipHorizontal);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
// Check angle
expect(API.getSelectedElements()[0].angle).toBeCloseTo(expectedAngle);
});
it("flips a rotated line vertically correctly", () => {
const originalAngle = Math.PI / 4;
const expectedAngle = (3 * Math.PI) / 4;
createAndSelectOneLine(originalAngle);
const originalWidth = API.getSelectedElements()[0].width;
const originalHeight = API.getSelectedElements()[0].height;
h.app.actionManager.executeAction(actionFlipVertical);
// Check if width and height did not change
expect(API.getSelectedElements()[0].width).toEqual(originalWidth);
expect(API.getSelectedElements()[0].height).toEqual(originalHeight);
// Check angle
expect(API.getSelectedElements()[0].angle).toBeCloseTo(expectedAngle);
});
// Draw element
it("flips an unrotated drawing horizontally correctly", () => {
const draw = createAndReturnOneDraw();
// select draw, since not done automatically
h.state.selectedElementIds[draw.id] = true;
const originalWidth = draw.width;
const originalHeight = draw.height;
h.app.actionManager.executeAction(actionFlipHorizontal);
// Check if width and height did not change
expect(draw.width).toEqual(originalWidth);
expect(draw.height).toEqual(originalHeight);
});
it("flips an unrotated drawing vertically correctly", () => {
const draw = createAndReturnOneDraw();
// select draw, since not done automatically
h.state.selectedElementIds[draw.id] = true;
const originalWidth = draw.width;
const originalHeight = draw.height;
h.app.actionManager.executeAction(actionFlipVertical);
// Check if width and height did not change
expect(draw.width).toEqual(originalWidth);
expect(draw.height).toEqual(originalHeight);
});
it("flips a rotated drawing horizontally correctly", () => {
const originalAngle = Math.PI / 4;
const expectedAngle = (7 * Math.PI) / 4;
const draw = createAndReturnOneDraw(originalAngle);
// select draw, since not done automatically
h.state.selectedElementIds[draw.id] = true;
const originalWidth = draw.width;
const originalHeight = draw.height;
h.app.actionManager.executeAction(actionFlipHorizontal);
// Check if width and height did not change
expect(draw.width).toEqual(originalWidth);
expect(draw.height).toEqual(originalHeight);
// Check angle
expect(draw.angle).toBeCloseTo(expectedAngle);
});
it("flips a rotated drawing vertically correctly", () => {
const originalAngle = Math.PI / 4;
const expectedAngle = (3 * Math.PI) / 4;
const draw = createAndReturnOneDraw(originalAngle);
// select draw, since not done automatically
h.state.selectedElementIds[draw.id] = true;
const originalWidth = draw.width;
const originalHeight = draw.height;
h.app.actionManager.executeAction(actionFlipVertical);
// Check if width and height did not change
expect(API.getSelectedElement().width).toEqual(originalWidth);
expect(API.getSelectedElement().height).toEqual(originalHeight);
// Check angle
expect(API.getSelectedElement().angle).toBeCloseTo(expectedAngle);
}); | the_stack |
import { useStorybookApi } from '@storybook/api';
import { styled } from '@storybook/theming';
import { Icons } from '@storybook/components';
import Downshift, { DownshiftState, StateChangeOptions } from 'downshift';
import Fuse, { FuseOptions } from 'fuse.js';
import global from 'global';
import { transparentize } from 'polished';
import React, { useMemo, useRef, useState, useCallback } from 'react';
import { DEFAULT_REF_ID } from './data';
import {
CombinedDataset,
SearchItem,
SearchResult,
DownshiftItem,
SearchChildrenFn,
Selection,
isSearchResult,
isExpandType,
isClearType,
isCloseType,
} from './types';
import { searchItem } from './utils';
const { document } = global;
const DEFAULT_MAX_SEARCH_RESULTS = 50;
const options = {
shouldSort: true,
tokenize: true,
findAllMatches: true,
includeScore: true,
includeMatches: true,
threshold: 0.2,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: [
{ name: 'name', weight: 0.7 },
{ name: 'path', weight: 0.3 },
],
} as FuseOptions<SearchItem>;
const ScreenReaderLabel = styled.label({
position: 'absolute',
left: -10000,
top: 'auto',
width: 1,
height: 1,
overflow: 'hidden',
});
const SearchIcon = styled(Icons)(({ theme }) => ({
width: 12,
height: 12,
position: 'absolute',
top: 8,
left: 10,
zIndex: 1,
pointerEvents: 'none',
color: theme.textMutedColor,
}));
const SearchField = styled.div(({ theme }) => ({
display: 'flex',
flexDirection: 'column',
position: 'relative',
'&:focus-within svg': {
color: theme.color.defaultText,
},
}));
const Input = styled.input(({ theme }) => ({
appearance: 'none',
height: 28,
paddingLeft: 28,
paddingRight: 28,
border: `1px solid ${transparentize(0.6, theme.color.mediumdark)}`,
background: 'transparent',
borderRadius: 28,
fontSize: `${theme.typography.size.s1}px`,
fontFamily: 'inherit',
transition: 'all 150ms',
color: theme.color.defaultText,
'&:focus, &:active': {
outline: 0,
borderColor: theme.color.secondary,
background: theme.background.app,
},
'&::placeholder': {
color: theme.textMutedColor,
},
'&:valid ~ code, &:focus ~ code': {
display: 'none',
},
'&:invalid ~ svg': {
display: 'none',
},
'&:valid ~ svg': {
display: 'block',
},
'&::-ms-clear': {
display: 'none',
},
'&::-webkit-search-decoration, &::-webkit-search-cancel-button, &::-webkit-search-results-button, &::-webkit-search-results-decoration':
{
display: 'none',
},
}));
const FocusKey = styled.code(({ theme }) => ({
position: 'absolute',
top: 6,
right: 12,
width: 16,
height: 16,
zIndex: 1,
lineHeight: '17px',
textAlign: 'center',
fontSize: '11px',
background: 'rgba(0,0,0,0.1)',
color: theme.textMutedColor,
borderRadius: 2,
userSelect: 'none',
pointerEvents: 'none',
}));
const ClearIcon = styled(Icons)(({ theme }) => ({
width: 16,
height: 16,
padding: 4,
position: 'absolute',
top: 6,
right: 8,
zIndex: 1,
background: 'rgba(0,0,0,0.1)',
borderRadius: 16,
color: theme.color.defaultText,
cursor: 'pointer',
}));
const FocusContainer = styled.div({ outline: 0 });
export const Search = React.memo<{
children: SearchChildrenFn;
dataset: CombinedDataset;
isLoading?: boolean;
enableShortcuts?: boolean;
getLastViewed: () => Selection[];
clearLastViewed: () => void;
initialQuery?: string;
}>(
({
children,
dataset,
isLoading = false,
enableShortcuts = true,
getLastViewed,
clearLastViewed,
initialQuery = '',
}) => {
const api = useStorybookApi();
const inputRef = useRef<HTMLInputElement>(null);
const [inputPlaceholder, setPlaceholder] = useState('Find components');
const [allComponents, showAllComponents] = useState(false);
const selectStory = useCallback(
(id: string, refId: string) => {
if (api) api.selectStory(id, undefined, { ref: refId !== DEFAULT_REF_ID && refId });
inputRef.current.blur();
showAllComponents(false);
},
[api, inputRef, showAllComponents, DEFAULT_REF_ID]
);
const list: SearchItem[] = useMemo(() => {
return dataset.entries.reduce((acc: SearchItem[], [refId, { stories }]) => {
if (stories) {
acc.push(...Object.values(stories).map((item) => searchItem(item, dataset.hash[refId])));
}
return acc;
}, []);
}, [dataset]);
const fuse = useMemo(() => new Fuse(list, options), [list]);
const getResults = useCallback(
(input: string) => {
if (!input) return [];
let results: DownshiftItem[] = [];
const resultIds: Set<string> = new Set();
const distinctResults = (fuse.search(input) as SearchResult[]).filter(({ item }) => {
if (!(item.isComponent || item.isLeaf) || resultIds.has(item.parent)) return false;
resultIds.add(item.id);
return true;
});
if (distinctResults.length) {
results = distinctResults.slice(0, allComponents ? 1000 : DEFAULT_MAX_SEARCH_RESULTS);
if (distinctResults.length > DEFAULT_MAX_SEARCH_RESULTS && !allComponents) {
results.push({
showAll: () => showAllComponents(true),
totalCount: distinctResults.length,
moreCount: distinctResults.length - DEFAULT_MAX_SEARCH_RESULTS,
});
}
}
return results;
},
[allComponents, fuse]
);
const stateReducer = useCallback(
(state: DownshiftState<DownshiftItem>, changes: StateChangeOptions<DownshiftItem>) => {
switch (changes.type) {
case Downshift.stateChangeTypes.blurInput: {
return {
...changes,
// Prevent clearing the input on blur
inputValue: state.inputValue,
// Return to the tree view after selecting an item
isOpen: state.inputValue && !state.selectedItem,
selectedItem: null,
};
}
case Downshift.stateChangeTypes.mouseUp: {
// Prevent clearing the input on refocus
return {};
}
case Downshift.stateChangeTypes.keyDownEscape: {
if (state.inputValue) {
// Clear the inputValue, but don't return to the tree view
return { ...changes, inputValue: '', isOpen: true, selectedItem: null };
}
// When pressing escape a second time, blur the input and return to the tree view
inputRef.current.blur();
return { ...changes, isOpen: false, selectedItem: null };
}
case Downshift.stateChangeTypes.clickItem:
case Downshift.stateChangeTypes.keyDownEnter: {
if (isSearchResult(changes.selectedItem)) {
const { id, refId } = changes.selectedItem.item;
selectStory(id, refId);
// Return to the tree view, but keep the input value
return { ...changes, inputValue: state.inputValue, isOpen: false };
}
if (isExpandType(changes.selectedItem)) {
changes.selectedItem.showAll();
// Downshift should completely ignore this
return {};
}
if (isClearType(changes.selectedItem)) {
changes.selectedItem.clearLastViewed();
inputRef.current.blur();
// Nothing to see anymore, so return to the tree view
return { isOpen: false };
}
if (isCloseType(changes.selectedItem)) {
inputRef.current.blur();
// Return to the tree view
return { isOpen: false };
}
return changes;
}
case Downshift.stateChangeTypes.changeInput: {
// Reset the "show more" state whenever the input changes
showAllComponents(false);
return changes;
}
default:
return changes;
}
},
[inputRef, selectStory, showAllComponents]
);
return (
<Downshift<DownshiftItem>
initialInputValue={initialQuery}
stateReducer={stateReducer}
// @ts-ignore
itemToString={(result) => result?.item?.name || ''}
>
{({
isOpen,
openMenu,
closeMenu,
inputValue,
clearSelection,
getInputProps,
getItemProps,
getLabelProps,
getMenuProps,
getRootProps,
highlightedIndex,
}) => {
const input = inputValue ? inputValue.trim() : '';
let results: DownshiftItem[] = input ? getResults(input) : [];
const lastViewed = !input && getLastViewed();
if (lastViewed && lastViewed.length) {
results = lastViewed.reduce((acc, { storyId, refId }) => {
const data = dataset.hash[refId];
if (data && data.stories && data.stories[storyId]) {
const story = data.stories[storyId];
const item =
story.isLeaf && !story.isComponent && !story.isRoot
? data.stories[story.parent]
: story;
// prevent duplicates
if (!acc.some((res) => res.item.refId === refId && res.item.id === item.id)) {
acc.push({ item: searchItem(item, dataset.hash[refId]), matches: [], score: 0 });
}
}
return acc;
}, []);
results.push({ closeMenu });
if (results.length > 0) {
results.push({ clearLastViewed });
}
}
const inputProps = getInputProps({
id: 'storybook-explorer-searchfield',
ref: inputRef,
required: true,
type: 'search',
placeholder: inputPlaceholder,
onFocus: () => {
openMenu();
setPlaceholder('Type to find...');
},
onBlur: () => setPlaceholder('Find components'),
});
return (
<>
<ScreenReaderLabel {...getLabelProps()}>Search for components</ScreenReaderLabel>
<SearchField
{...getRootProps({ refKey: '' }, { suppressRefError: true })}
className="search-field"
>
<SearchIcon icon="search" />
<Input {...inputProps} />
{enableShortcuts && <FocusKey>/</FocusKey>}
<ClearIcon icon="cross" onClick={() => clearSelection()} />
</SearchField>
<FocusContainer tabIndex={0} id="storybook-explorer-menu">
{children({
query: input,
results,
isBrowsing: !isOpen && document.activeElement !== inputRef.current,
closeMenu,
getMenuProps,
getItemProps,
highlightedIndex,
})}
</FocusContainer>
</>
);
}}
</Downshift>
);
}
); | the_stack |
import { v4 as uuid } from 'uuid'
import {
CommandStartEvent,
CommandCompleteEvent,
KResponse,
ScalarResponse,
hideReplayOutput,
isCommentaryResponse,
isCommentarySectionBreak,
isError,
Util
} from '@kui-shell/core'
// this used to be defined here
export { isError }
export const enum BlockState {
Active = 'repl-active',
Cancelled = 'cancelled',
Empty = 'empty',
Error = 'error',
Processing = 'processing',
ValidResponse = 'valid-response'
}
/** Traits that Blocks might have */
type WithCWD = { cwd: string }
type WithUUID = { execUUID: string }
type WithOriginalExecUUID = { originalExecUUID: string } // for rerun/rexec in place, we need to remember the first execUUID
type WithCommand = { command: string; isExperimental?: boolean } & WithCWD
type WithStartTime = { startTime: number }
type WithState<S extends BlockState> = { state: S }
type WithResponse<R extends KResponse> = { response: R } & WithStartTime
type WithValue = { value: string }
type WithAnnouncement = { isAnnouncement: boolean; maximized?: boolean }
type WithPreferences = { outputOnly?: boolean }
type WithCommandStart = { startEvent: CommandStartEvent }
type WithCommandComplete = { completeEvent: CommandCompleteEvent }
type WithRerun = { isRerun: true; newExecUUID: string } & WithOriginalExecUUID
type WithReplay = { isReplay: boolean }
type WithSectionBreak = { isSectionBreak: boolean }
/** The canonical types of Blocks, which mix up the Traits as needed */
type ActiveBlock = WithState<BlockState.Active> & WithCWD & Partial<WithValue>
export type AnnouncementBlock = WithState<BlockState.ValidResponse> &
WithResponse<ScalarResponse> &
WithCWD &
WithUUID &
WithAnnouncement
type EmptyBlock = WithState<BlockState.Empty> & WithCWD & Partial<WithCommand> & Partial<WithCommandComplete>
type ErrorBlock = WithState<BlockState.Error> &
WithCommand &
WithResponse<Error> &
WithUUID &
WithHistoryIndex &
WithCommandStart &
Partial<WithRerun> &
WithReplay &
WithCommandComplete
type OkBlock = WithState<BlockState.ValidResponse> &
WithCommand &
WithResponse<KResponse> &
WithUUID &
WithHistoryIndex &
WithCommandStart &
WithCommandComplete &
Partial<WithRerun> &
Partial<WithSectionBreak> &
WithReplay &
WithPreferences
export type ProcessingBlock = WithState<BlockState.Processing> &
WithCommand &
WithUUID &
WithStartTime &
Partial<WithOriginalExecUUID> &
WithReplay &
WithCommandStart
type CancelledBlock = WithState<BlockState.Cancelled> & WithCWD & WithCommand & WithUUID & WithStartTime
export type CompleteBlock = OkBlock | ErrorBlock
/** Blocks with an association to the History model */
type WithHistoryIndex = { historyIdx: number }
/** FinishedBlocks are either ok, error, or cancelled */
export type FinishedBlock = OkBlock | ErrorBlock | CancelledBlock | EmptyBlock
// A Block is one of the canonical types
export type BlockModel = ProcessingBlock | FinishedBlock | CancelledBlock | ActiveBlock | AnnouncementBlock
export default BlockModel
/** Capture the current working directory */
function cwd() {
const dir = Util.cwd()
return dir ? dir.replace(process.env.HOME, '~') : undefined
}
export function isProcessing(block: BlockModel): block is ProcessingBlock {
return block.state === BlockState.Processing
}
export function isActive(block: BlockModel): block is ActiveBlock {
return block.state === BlockState.Active
}
/** @return true if the given `block` is `Active` and differs from the other `oblock` */
export function isActiveAndDifferent(block: BlockModel, oblock: BlockModel): block is ActiveBlock {
return isActive(block) && (!isActive(oblock) || block.cwd !== oblock.cwd || block.value !== oblock.value)
}
export function isCancelled(block: BlockModel): block is CancelledBlock {
return block.state === BlockState.Cancelled
}
export function isEmpty(block: BlockModel): block is EmptyBlock {
return block.state === BlockState.Empty
}
export function isOk(block: BlockModel): block is OkBlock {
return block.state === BlockState.ValidResponse
}
export function isOops(block: BlockModel): block is ErrorBlock {
return block.state === BlockState.Error
}
export function isFinished(block: BlockModel): block is FinishedBlock {
return isOops(block) || isCancelled(block) || isOk(block) || isEmpty(block)
}
export function hasCommand(block: BlockModel & Partial<WithCommand>): block is BlockModel & Required<WithCommand> {
return !isActive(block) && (!isEmpty(block) || block.command !== undefined)
}
export function isAnnouncement(block: BlockModel): block is AnnouncementBlock {
const blockModel = block as AnnouncementBlock
return blockModel.state === BlockState.ValidResponse && blockModel.isAnnouncement === true
}
export function hasUUID(block: BlockModel & Partial<WithUUID>): block is BlockModel & Required<WithUUID> {
return block && !isActive(block) && !isEmpty(block) && !isAnnouncement(block)
}
export function hasValue(block: BlockModel): block is BlockModel & Required<WithValue> {
return typeof (block as WithValue).value === 'string'
}
/** Transform to Active */
export function Active(initialValue?: string): ActiveBlock {
return {
cwd: cwd(),
state: BlockState.Active,
value: initialValue || ''
}
}
/** Transform to AnnouncementBlock */
export function Announcement(response: ScalarResponse, execUUID = uuid(), maximized?: boolean): AnnouncementBlock {
return {
response,
execUUID,
maximized,
isAnnouncement: true,
startTime: Date.now(),
cwd: cwd(),
state: BlockState.ValidResponse
}
}
export function isRerunable(block: BlockModel): block is RerunableBlock {
return isOk(block) || isOops(block)
}
export function isBeingRerun(block: BlockModel): block is BlockBeingRerun {
return (block as WithRerun).isRerun === true
}
export function isProcessingOrBeingRerun(block: BlockModel): block is ProcessingBlock | BlockBeingRerun {
return isProcessing(block) || isBeingRerun(block)
}
export function hasOriginalUUID(block: BlockModel | WithOriginalExecUUID): block is WithOriginalExecUUID {
return typeof (block as WithOriginalExecUUID).originalExecUUID === 'string'
}
/** Useful e.g. when reloading a snapshot, to clear out any prior "has been rerun" state */
export function clearOriginalUUID(block: WithOriginalExecUUID) {
block.originalExecUUID = undefined
}
/** @return whether the block has a completeEvent trait */
export function isWithCompleteEvent(block: BlockModel): block is CompleteBlock {
return (isOk(block) || isOops(block) || isEmpty(block)) && block.completeEvent !== undefined
}
export function hasBeenRerun(block: BlockModel): boolean {
return (
hasOriginalUUID(block) && hasUUID(block) && block.originalExecUUID !== block.execUUID && isWithCompleteEvent(block)
)
}
/** @return whether the block is from replay */
export function isReplay(block: BlockModel): boolean {
return (isProcessing(block) || isWithCompleteEvent(block)) && block.isReplay
}
/** Transform to Processing */
export function Processing(
block: BlockModel,
startEvent: CommandStartEvent,
isExperimental = false,
_isReplay = isReplay(block)
): ProcessingBlock {
return {
command: startEvent.command,
isExperimental,
cwd: block.cwd,
execUUID: startEvent.execUUID,
originalExecUUID: (hasOriginalUUID(block) && block.originalExecUUID) || startEvent.execUUID,
isReplay: _isReplay,
startEvent,
startTime: startEvent.startTime,
state: BlockState.Processing
}
}
/** Transform to Empty */
export function Empty(block: BlockModel, typedSoFar?: string, completeEvent?: CommandCompleteEvent): EmptyBlock {
return {
cwd: block.cwd,
command: typedSoFar,
completeEvent,
state: BlockState.Empty
}
}
/** Transform to Cancelled */
export function Cancelled(
block: BlockModel,
typedSoFar?: string,
completeEvent?: CommandCompleteEvent
): CancelledBlock | EmptyBlock {
if (isProcessing(block)) {
return {
cwd: block.cwd,
command: block.command,
execUUID: block.execUUID,
startTime: block.startTime,
state: BlockState.Cancelled
}
} else {
return Empty(block, typedSoFar, completeEvent)
}
}
/** Transform to Finished */
export function Finished(
block: ProcessingBlock | BlockBeingRerun,
event: CommandCompleteEvent,
outputOnly = false,
_isReplay = isReplay(block)
): FinishedBlock {
const response = event.response // event.responseType === 'ScalarResponse' ? (event.response as ScalarResponse) : true
const { historyIdx } = event
const { startEvent } = block
// see Rerun() below; when re-executing a block (which means we
// re-evaluate a potentially changed command, and want to splice the
// updated response into an existing block --- in this scenario, we
// still need a new execUUID so that the view components can know
// whether or not a re-render is needed; Rerun() which is called
// onExecStart allocates the execUUID, and then when we get here,
// onExecEnd, we can swap that new execUUID into place
if (isBeingRerun(block)) {
block.execUUID = block.newExecUUID
}
if (event.cancelled) {
if (!event.command) {
return Empty(block)
} else {
return Cancelled(block, event.command)
}
} else if (isError(response)) {
return {
response,
historyIdx,
cwd: block.cwd,
command: block.command,
startEvent,
completeEvent: event,
isExperimental: block.isExperimental,
isReplay: _isReplay,
state: BlockState.Error,
execUUID: block.execUUID,
originalExecUUID: (hasOriginalUUID(block) && block.originalExecUUID) || block.execUUID,
startTime: block.startTime
}
} else {
return {
response,
historyIdx,
cwd: block.cwd,
command: block.command,
startEvent,
completeEvent: event,
isExperimental: block.isExperimental,
isReplay: _isReplay,
execUUID: block.execUUID,
isSectionBreak: isCommentarySectionBreak(response),
originalExecUUID: (hasOriginalUUID(block) && block.originalExecUUID) || block.execUUID,
startTime: block.startTime,
outputOnly,
state: BlockState.ValidResponse
}
}
}
export function isOutputOnly(block: BlockModel) {
if (isProcessing(block)) {
return block.startEvent.echo === false
} else if (isOk(block)) {
return (
(block.completeEvent && block.completeEvent.echo === false) ||
(block.startEvent && block.startEvent.echo === false) ||
block.outputOnly
)
}
}
/** @return whether the block as a startEvent trait */
export function hasStartEvent(block: BlockModel): block is BlockModel & WithCommandStart {
return !isAnnouncement(block) && (isProcessing(block) || isOk(block) || isOops(block))
}
/** @return whether the output of this command execution be redirected to a file */
export function isOutputRedirected(block: BlockModel): boolean {
return hasStartEvent(block) && block.startEvent.redirectDesired
}
/** @return whether the block is section break */
export function isSectionBreak(block: BlockModel): block is CompleteBlock & WithSectionBreak {
return isOk(block) && block.isSectionBreak
}
/** A Block may be Rerunable. If so, then it can be transitioned to the BlockBeingRerun state. */
type RerunableBlock = CompleteBlock
type BlockBeingRerun = RerunableBlock & WithRerun
/** Transform a RerunableBlock to one in the BlockBeingRerun state */
export function Rerun(
block: RerunableBlock,
newStartEvent = block.startEvent,
newCommand = newStartEvent.command,
newStartTime = newStartEvent.startTime
): RerunableBlock & Required<WithRerun> {
return Object.assign({}, block, {
isRerun: true as const,
startEvent: newStartEvent,
command: newCommand,
newExecUUID: uuid(),
originalExecUUID: (hasOriginalUUID(block) && block.originalExecUUID) || block.execUUID,
startTime: newStartTime
})
}
/** this implements support for not showing the Output blocks when replaying a notebook */
export function hideOutput(model: BlockModel): boolean {
return (
hideReplayOutput() && // client asked us not to show replay output in notebooks
isReplay(model) && // we are showing a notebook
!hasBeenRerun(model) && // user has yet to re-execute the block in this notebook
isFinished(model) &&
!isCancelled(model) &&
!isEmpty(model) &&
!isCommentaryResponse(model.response)
)
}
export function isMaximized(model: BlockModel) {
return isAnnouncement(model) && model.maximized
} | the_stack |
import 'vs/css!./simpleFindWidget';
import * as nls from 'vs/nls';
import * as dom from 'vs/base/browser/dom';
import { FindInput, IFindInputStyles } from 'vs/base/browser/ui/findinput/findInput';
import { Widget } from 'vs/base/browser/ui/widget';
import { Delayer } from 'vs/base/common/async';
import { KeyCode } from 'vs/base/common/keyCodes';
import { FindReplaceState } from 'vs/editor/contrib/find/findState';
import { IMessage as InputBoxMessage } from 'vs/base/browser/ui/inputbox/inputBox';
import { SimpleButton, findPreviousMatchIcon, findNextMatchIcon } from 'vs/editor/contrib/find/findWidget';
import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { IContextViewService } from 'vs/platform/contextview/browser/contextView';
import { editorWidgetBackground, inputActiveOptionBorder, inputActiveOptionBackground, inputActiveOptionForeground, inputBackground, inputBorder, inputForeground, inputValidationErrorBackground, inputValidationErrorBorder, inputValidationErrorForeground, inputValidationInfoBackground, inputValidationInfoBorder, inputValidationInfoForeground, inputValidationWarningBackground, inputValidationWarningBorder, inputValidationWarningForeground, widgetShadow, editorWidgetForeground } from 'vs/platform/theme/common/colorRegistry';
import { IColorTheme, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { ContextScopedFindInput } from 'vs/platform/browser/contextScopedHistoryWidget';
import { widgetClose } from 'vs/platform/theme/common/iconRegistry';
const NLS_FIND_INPUT_LABEL = nls.localize('label.find', "Find");
const NLS_FIND_INPUT_PLACEHOLDER = nls.localize('placeholder.find', "Find");
const NLS_PREVIOUS_MATCH_BTN_LABEL = nls.localize('label.previousMatchButton', "Previous Match");
const NLS_NEXT_MATCH_BTN_LABEL = nls.localize('label.nextMatchButton', "Next Match");
const NLS_CLOSE_BTN_LABEL = nls.localize('label.closeButton', "Close");
export abstract class SimpleFindWidget extends Widget {
private readonly _findInput: FindInput;
private readonly _domNode: HTMLElement;
private readonly _innerDomNode: HTMLElement;
private readonly _focusTracker: dom.IFocusTracker;
private readonly _findInputFocusTracker: dom.IFocusTracker;
private readonly _updateHistoryDelayer: Delayer<void>;
private readonly prevBtn: SimpleButton;
private readonly nextBtn: SimpleButton;
private _isVisible: boolean = false;
private foundMatch: boolean = false;
constructor(
@IContextViewService private readonly _contextViewService: IContextViewService,
@IContextKeyService contextKeyService: IContextKeyService,
private readonly _state: FindReplaceState = new FindReplaceState(),
showOptionButtons?: boolean,
checkImeCompletionState?: boolean
) {
super();
this._findInput = this._register(new ContextScopedFindInput(null, this._contextViewService, {
label: NLS_FIND_INPUT_LABEL,
placeholder: NLS_FIND_INPUT_PLACEHOLDER,
validation: (value: string): InputBoxMessage | null => {
if (value.length === 0 || !this._findInput.getRegex()) {
return null;
}
try {
new RegExp(value);
return null;
} catch (e) {
this.foundMatch = false;
this.updateButtons(this.foundMatch);
return { content: e.message };
}
}
}, contextKeyService, showOptionButtons));
// Find History with update delayer
this._updateHistoryDelayer = new Delayer<void>(500);
this._register(this._findInput.onInput((e) => {
if (!checkImeCompletionState || !this._findInput.isImeSessionInProgress) {
this.foundMatch = this._onInputChanged();
this.updateButtons(this.foundMatch);
this.focusFindBox();
this._delayedUpdateHistory();
}
}));
this._findInput.setRegex(!!this._state.isRegex);
this._findInput.setCaseSensitive(!!this._state.matchCase);
this._findInput.setWholeWords(!!this._state.wholeWord);
this._register(this._findInput.onDidOptionChange(() => {
this._state.change({
isRegex: this._findInput.getRegex(),
wholeWord: this._findInput.getWholeWords(),
matchCase: this._findInput.getCaseSensitive()
}, true);
}));
this._register(this._state.onFindReplaceStateChange(() => {
this._findInput.setRegex(this._state.isRegex);
this._findInput.setWholeWords(this._state.wholeWord);
this._findInput.setCaseSensitive(this._state.matchCase);
this.findFirst();
}));
this.prevBtn = this._register(new SimpleButton({
label: NLS_PREVIOUS_MATCH_BTN_LABEL,
icon: findPreviousMatchIcon,
onTrigger: () => {
this.find(true);
}
}));
this.nextBtn = this._register(new SimpleButton({
label: NLS_NEXT_MATCH_BTN_LABEL,
icon: findNextMatchIcon,
onTrigger: () => {
this.find(false);
}
}));
const closeBtn = this._register(new SimpleButton({
label: NLS_CLOSE_BTN_LABEL,
icon: widgetClose,
onTrigger: () => {
this.hide();
}
}));
this._innerDomNode = document.createElement('div');
this._innerDomNode.classList.add('simple-find-part');
this._innerDomNode.appendChild(this._findInput.domNode);
this._innerDomNode.appendChild(this.prevBtn.domNode);
this._innerDomNode.appendChild(this.nextBtn.domNode);
this._innerDomNode.appendChild(closeBtn.domNode);
// _domNode wraps _innerDomNode, ensuring that
this._domNode = document.createElement('div');
this._domNode.classList.add('simple-find-part-wrapper');
this._domNode.appendChild(this._innerDomNode);
this.onkeyup(this._innerDomNode, e => {
if (e.equals(KeyCode.Escape)) {
this.hide();
e.preventDefault();
return;
}
});
this._focusTracker = this._register(dom.trackFocus(this._innerDomNode));
this._register(this._focusTracker.onDidFocus(this._onFocusTrackerFocus.bind(this)));
this._register(this._focusTracker.onDidBlur(this._onFocusTrackerBlur.bind(this)));
this._findInputFocusTracker = this._register(dom.trackFocus(this._findInput.domNode));
this._register(this._findInputFocusTracker.onDidFocus(this._onFindInputFocusTrackerFocus.bind(this)));
this._register(this._findInputFocusTracker.onDidBlur(this._onFindInputFocusTrackerBlur.bind(this)));
this._register(dom.addDisposableListener(this._innerDomNode, 'click', (event) => {
event.stopPropagation();
}));
}
protected abstract _onInputChanged(): boolean;
protected abstract find(previous: boolean): void;
protected abstract findFirst(): void;
protected abstract _onFocusTrackerFocus(): void;
protected abstract _onFocusTrackerBlur(): void;
protected abstract _onFindInputFocusTrackerFocus(): void;
protected abstract _onFindInputFocusTrackerBlur(): void;
protected get inputValue() {
return this._findInput.getValue();
}
public get focusTracker(): dom.IFocusTracker {
return this._focusTracker;
}
public updateTheme(theme: IColorTheme): void {
const inputStyles: IFindInputStyles = {
inputActiveOptionBorder: theme.getColor(inputActiveOptionBorder),
inputActiveOptionForeground: theme.getColor(inputActiveOptionForeground),
inputActiveOptionBackground: theme.getColor(inputActiveOptionBackground),
inputBackground: theme.getColor(inputBackground),
inputForeground: theme.getColor(inputForeground),
inputBorder: theme.getColor(inputBorder),
inputValidationInfoBackground: theme.getColor(inputValidationInfoBackground),
inputValidationInfoForeground: theme.getColor(inputValidationInfoForeground),
inputValidationInfoBorder: theme.getColor(inputValidationInfoBorder),
inputValidationWarningBackground: theme.getColor(inputValidationWarningBackground),
inputValidationWarningForeground: theme.getColor(inputValidationWarningForeground),
inputValidationWarningBorder: theme.getColor(inputValidationWarningBorder),
inputValidationErrorBackground: theme.getColor(inputValidationErrorBackground),
inputValidationErrorForeground: theme.getColor(inputValidationErrorForeground),
inputValidationErrorBorder: theme.getColor(inputValidationErrorBorder)
};
this._findInput.style(inputStyles);
}
override dispose() {
super.dispose();
if (this._domNode && this._domNode.parentElement) {
this._domNode.parentElement.removeChild(this._domNode);
}
}
public getDomNode() {
return this._domNode;
}
public reveal(initialInput?: string): void {
if (initialInput) {
this._findInput.setValue(initialInput);
}
if (this._isVisible) {
this._findInput.select();
return;
}
this._isVisible = true;
this.updateButtons(this.foundMatch);
setTimeout(() => {
this._innerDomNode.classList.add('visible', 'visible-transition');
this._innerDomNode.setAttribute('aria-hidden', 'false');
this._findInput.select();
}, 0);
}
public show(initialInput?: string): void {
if (initialInput && !this._isVisible) {
this._findInput.setValue(initialInput);
}
this._isVisible = true;
setTimeout(() => {
this._innerDomNode.classList.add('visible', 'visible-transition');
this._innerDomNode.setAttribute('aria-hidden', 'false');
}, 0);
}
public hide(): void {
if (this._isVisible) {
this._innerDomNode.classList.remove('visible-transition');
this._innerDomNode.setAttribute('aria-hidden', 'true');
// Need to delay toggling visibility until after Transition, then visibility hidden - removes from tabIndex list
setTimeout(() => {
this._isVisible = false;
this.updateButtons(this.foundMatch);
this._innerDomNode.classList.remove('visible');
}, 200);
}
}
protected _delayedUpdateHistory() {
this._updateHistoryDelayer.trigger(this._updateHistory.bind(this));
}
protected _updateHistory() {
this._findInput.inputBox.addToHistory();
}
protected _getRegexValue(): boolean {
return this._findInput.getRegex();
}
protected _getWholeWordValue(): boolean {
return this._findInput.getWholeWords();
}
protected _getCaseSensitiveValue(): boolean {
return this._findInput.getCaseSensitive();
}
protected updateButtons(foundMatch: boolean) {
const hasInput = this.inputValue.length > 0;
this.prevBtn.setEnabled(this._isVisible && hasInput && foundMatch);
this.nextBtn.setEnabled(this._isVisible && hasInput && foundMatch);
}
protected focusFindBox() {
// Focus back onto the find box, which
// requires focusing onto the next button first
this.nextBtn.focus();
this._findInput.inputBox.focus();
}
}
// theming
registerThemingParticipant((theme, collector) => {
const findWidgetBGColor = theme.getColor(editorWidgetBackground);
if (findWidgetBGColor) {
collector.addRule(`.monaco-workbench .simple-find-part { background-color: ${findWidgetBGColor} !important; }`);
}
const widgetForeground = theme.getColor(editorWidgetForeground);
if (widgetForeground) {
collector.addRule(`.monaco-workbench .simple-find-part { color: ${widgetForeground}; }`);
}
const widgetShadowColor = theme.getColor(widgetShadow);
if (widgetShadowColor) {
collector.addRule(`.monaco-workbench .simple-find-part { box-shadow: 0 0 8px 2px ${widgetShadowColor}; }`);
}
}); | the_stack |
import React, { useEffect, useState } from 'react';
import { TextField, List, ListItem, Link } from '@material-ui/core';
import ClusterTemplateCardList from '../ClusterTemplateCardList';
import ProfileCardList from '../ProfileCardList';
import { useLocalStorage } from 'react-use';
import { gitOpsApiRef, Status } from '../../api';
import {
Header,
Page,
Content,
ContentHeader,
HeaderLabel,
SupportButton,
SimpleStepper,
SimpleStepperStep,
InfoCard,
Progress,
Table,
StatusWarning,
StatusOK,
StatusRunning,
StatusError,
StatusPending,
StatusAborted,
} from '@backstage/core-components';
import { useApi, githubAuthApiRef } from '@backstage/core-plugin-api';
// OK = (completed, success)
// Error = (?,failure)
// Aborted = (?,cancelled)
// Error = (?,timed_out)
// Warning = (?, skipped)
// Running = (queued, ?)
// Running = (in_progress,?)
export const transformStatus = (value: Status): JSX.Element => {
let status: JSX.Element = <StatusRunning>Unknown</StatusRunning>;
if (value.status === 'completed' && value.conclusion === 'success') {
status = <StatusOK>Success</StatusOK>;
} else if (value.conclusion === 'failure') {
status = <StatusError>Failure</StatusError>;
} else if (value.conclusion === 'cancelled') {
status = <StatusAborted>Cancelled</StatusAborted>;
} else if (value.conclusion === 'timed_out') {
status = <StatusError>Timed out</StatusError>;
} else if (value.conclusion === 'skipped') {
status = <StatusWarning>Skipped</StatusWarning>;
} else if (value.status === 'queued') {
status = <StatusPending>Queued</StatusPending>;
} else if (value.status === 'in_progress') {
status = <StatusRunning>In Progress</StatusRunning>;
}
return status;
};
export const transformRunStatus = (x: Status[]) => {
return x.map(value => {
return {
status: transformStatus(value),
message: value.message,
};
});
};
const ProfileCatalog = () => {
// TODO: get data from REST API
const [clusterTemplates] = React.useState([
{
platformName: '15m',
title: 'EKS 2 workers',
repository: 'chanwit/eks-cluster-template',
description: 'EKS with Kubernetes 1.16 / 2 nodes of m5.xlarge (15 mins)',
},
{
platformName: '15m',
title: 'EKS 1 worker',
repository: 'chanwit/template-2',
description: 'EKS with Kubernetes 1.16 / 1 node of m5.xlarge (15 mins)',
},
]);
const [profileTemplates] = React.useState([
{
shortName: 'ml',
title: 'MLOps',
repository: 'https://github.com/weaveworks/mlops-profile',
description: 'Kubeflow-based Machine Learning pipeline',
},
{
shortName: 'ai',
title: 'COVID ML',
repository: 'https://github.com/weaveworks/covid-ml-profile',
description: 'Fk-covid Application profile',
},
]);
const [templateRepo] = useLocalStorage<string>('gitops-template-repo');
const [gitopsProfiles] = useLocalStorage<string[]>('gitops-profiles');
const [showProgress, setShowProgress] = useState(false);
const [pollingLog, setPollingLog] = useState(false);
const [gitHubOrg, setGitHubOrg] = useState(String);
const [gitHubRepo, setGitHubRepo] = useState('new-cluster');
const [awsAccessKeyId, setAwsAccessKeyId] = useState(String);
const [awsSecretAccessKey, setAwsSecretAccessKey] = useState(String);
const [runStatus, setRunStatus] = useState<Status[]>([]);
const [runLink, setRunLink] = useState<string>('');
const api = useApi(gitOpsApiRef);
const githubAuth = useApi(githubAuthApiRef);
const [githubAccessToken, setGithubAccessToken] = useState(String);
const [githubUsername, setGithubUsername] = useState(String);
useEffect(() => {
const fetchGithubUserInfo = async () => {
const accessToken = await githubAuth.getAccessToken(['repo', 'user']);
const userInfo = await api.fetchUserInfo({ accessToken });
setGithubAccessToken(accessToken);
setGithubUsername(userInfo.login);
setGitHubOrg(userInfo.login);
};
if (!githubAccessToken || !githubUsername) {
fetchGithubUserInfo();
} else {
if (pollingLog) {
const interval = setInterval(async () => {
const resp = await api.fetchLog({
gitHubToken: githubAccessToken,
gitHubUser: githubUsername,
targetOrg: gitHubOrg,
targetRepo: gitHubRepo,
});
setRunStatus(resp.result);
setRunLink(resp.link);
if (resp.status === 'completed') {
setPollingLog(false);
setShowProgress(false);
}
}, 10000);
return () => clearInterval(interval);
}
}
return () => {};
}, [
pollingLog,
api,
gitHubOrg,
gitHubRepo,
githubAuth,
githubAccessToken,
githubUsername,
]);
const showFailureMessage = (msg: string) => {
setRunStatus(
runStatus.concat([
{
status: 'completed',
message: msg,
conclusion: 'failure',
},
]),
);
};
const showSuccessMessage = (msg: string) => {
setRunStatus(
runStatus.concat([
{
status: 'completed',
message: msg,
conclusion: 'success',
},
]),
);
};
const doCreateCluster = async () => {
setShowProgress(true);
setRunStatus([]);
const cloneResponse = await api.cloneClusterFromTemplate({
templateRepository: templateRepo!,
gitHubToken: githubAccessToken,
gitHubUser: githubUsername,
targetOrg: gitHubOrg,
targetRepo: gitHubRepo,
secrets: {
awsAccessKeyId: awsAccessKeyId,
awsSecretAccessKey: awsSecretAccessKey,
},
});
if (cloneResponse.error === undefined) {
showSuccessMessage('Forked new cluster repo');
} else {
setShowProgress(false);
showFailureMessage(cloneResponse.error);
}
const applyProfileResp = await api.applyProfiles({
gitHubToken: githubAccessToken,
gitHubUser: githubUsername,
targetOrg: gitHubOrg,
targetRepo: gitHubRepo,
profiles: gitopsProfiles!,
});
if (applyProfileResp.error === undefined) {
showSuccessMessage('Applied profiles to the repo');
} else {
setShowProgress(false);
showFailureMessage(applyProfileResp.error);
}
const clusterStateResp = await api.changeClusterState({
gitHubToken: githubAccessToken,
gitHubUser: githubUsername,
targetOrg: gitHubOrg,
targetRepo: gitHubRepo,
clusterState: 'present',
});
if (clusterStateResp.error === undefined) {
// cluster creation start, so start pulling log
setPollingLog(true);
showSuccessMessage('Changed desired cluster state to present');
} else {
setPollingLog(false);
setShowProgress(false);
showFailureMessage(clusterStateResp.error);
}
};
const columns = [
{ field: 'status', title: 'Status' },
{ field: 'message', title: 'Message' },
];
return (
<Page themeId="tool">
<Header
title="Create GitOps-managed Cluster"
subtitle="Kubernetes cluster with ready-to-use profiles"
>
<HeaderLabel label="Welcome" value={githubUsername} />
</Header>
<Content>
<ContentHeader title="Create Cluster">
<SupportButton>A description of your plugin goes here.</SupportButton>
</ContentHeader>
<SimpleStepper>
<SimpleStepperStep title="Choose Cluster Template">
<ClusterTemplateCardList template={clusterTemplates} />
</SimpleStepperStep>
<SimpleStepperStep title="Select GitOps Profile">
<ProfileCardList profileTemplates={profileTemplates} />
</SimpleStepperStep>
<SimpleStepperStep
title="Create Cluster"
actions={{ nextText: 'Create', onNext: () => doCreateCluster() }}
>
<InfoCard>
<List>
<ListItem>
<TextField
name="github-org-tf"
label="GitHub Organization"
defaultValue={gitHubOrg}
required
onChange={e => {
setGitHubOrg(e.target.value);
}}
/>
</ListItem>
<ListItem>
<TextField
name="github-repo-tf"
label="New Repository"
defaultValue={gitHubRepo}
required
onChange={e => {
setGitHubRepo(e.target.value);
}}
/>
</ListItem>
<ListItem>
<TextField
name="aws-access-key-id-tf"
label="Access Key ID"
required
type="password"
onChange={e => {
setAwsAccessKeyId(e.target.value);
}}
/>
</ListItem>
<ListItem>
<TextField
name="aws-secret-access-key-tf"
label="Secret Access Key"
required
type="password"
onChange={e => {
setAwsSecretAccessKey(e.target.value);
}}
/>
</ListItem>
</List>
</InfoCard>
</SimpleStepperStep>
</SimpleStepper>
<div>
<Progress hidden={!showProgress} />
<Table
options={{ search: false, paging: false, toolbar: false }}
data={transformRunStatus(runStatus)}
columns={columns}
/>
<Link
hidden={runLink === ''}
rel="noopener noreferrer"
href={`${runLink}?check_suite_focus=true`}
target="_blank"
>
Details
</Link>
</div>
</Content>
</Page>
);
};
export default ProfileCatalog; | the_stack |
import { assert, expect } from "chai";
import { Arc3d, AuxChannel, AuxChannelData, AuxChannelDataType, LineString3d, Loop, Point3d, PolyfaceAuxData, PolyfaceBuilder, Range3d, Transform } from "@itwin/core-geometry";
import { ColorDef, GraphicParams } from "@itwin/core-common";
import { GraphicType } from "../../../render/GraphicBuilder";
import { IModelApp } from "../../../IModelApp";
import { MockRender } from "../../../render/MockRender";
import { ScreenViewport } from "../../../Viewport";
import { DisplayParams } from "../../../render/primitives/DisplayParams";
import { Geometry } from "../../../render/primitives/geometry/GeometryPrimitives";
import { Mesh, MeshGraphicArgs } from "../../../render/primitives/mesh/MeshPrimitives";
import { PolyfacePrimitive, PolyfacePrimitiveList } from "../../../render/primitives/Polyface";
import { PrimitiveBuilder } from "../../../render/primitives/geometry/GeometryListBuilder";
import { StrokesPrimitiveList, StrokesPrimitivePointLists } from "../../../render/primitives/Strokes";
import { ToleranceRatio, Triangle } from "../../../render/primitives/Primitives";
import { MeshParams } from "../../../render/primitives/VertexTable";
import { MeshBuilder, MeshEdgeCreationOptions } from "../../../render/primitives/mesh/MeshBuilder";
import { openBlankViewport } from "../../openBlankViewport";
class FakeDisplayParams extends DisplayParams {
public constructor() {
super(DisplayParams.Type.Linear, ColorDef.black, ColorDef.black);
}
}
const edgeOptions = new MeshEdgeCreationOptions(MeshEdgeCreationOptions.Type.NoEdges);
describe("Mesh Builder Tests", () => {
let viewport: ScreenViewport;
before(async () => { // Create a ViewState to load into a Viewport
await MockRender.App.startup();
viewport = openBlankViewport();
});
after(async () => {
viewport.dispose();
await MockRender.App.shutdown();
});
it("constructor", () => {
const displayParams = new FakeDisplayParams();
const type = Mesh.PrimitiveType.Mesh;
const range = Range3d.createNull();
const is2d = false;
const isPlanar = true;
const tolerance = 0.15;
const areaTolerance = ToleranceRatio.facetArea * tolerance;
const mb = MeshBuilder.create({ displayParams, type, range, is2d, isPlanar, tolerance, areaTolerance });
expect(mb.currentPolyface).to.be.undefined;
expect(mb.mesh.displayParams).to.equal(displayParams);
expect(mb.mesh.type).to.equal(type);
expect(mb.mesh.is2d).to.equal(is2d);
expect(mb.mesh.isPlanar).to.equal(isPlanar);
expect(mb.tolerance).to.equal(tolerance);
expect(mb.areaTolerance).to.equal(areaTolerance);
});
it("addStrokePointLists", () => {
const primBuilder = new PrimitiveBuilder(IModelApp.renderSystem, {type: GraphicType.Scene, viewport });
const pointA = new Point3d(-100, 0, 0);
const pointB = new Point3d(0, 100, 0);
const pointC = new Point3d(100, 0, 0);
const arc = Arc3d.createCircularStartMiddleEnd(pointA, pointB, pointC);
assert(arc !== undefined && arc instanceof Arc3d);
if (arc === undefined || !(arc instanceof Arc3d))
return;
primBuilder.addArc(arc, false, false);
assert(!(primBuilder.accum.geometries.isEmpty));
const arcGeom: Geometry | undefined = primBuilder.accum.geometries.first;
assert(arcGeom !== undefined);
if (arcGeom === undefined)
return;
const strokesPrimList: StrokesPrimitiveList | undefined = arcGeom.getStrokes(0.22);
assert(strokesPrimList !== undefined);
if (strokesPrimList === undefined)
return;
expect(strokesPrimList.length).to.be.greaterThan(0);
const strksPrims: StrokesPrimitivePointLists = strokesPrimList[0].strokes;
const fillColor = ColorDef.white.tbgr;
const displayParams = new FakeDisplayParams();
const type = Mesh.PrimitiveType.Polyline;
const range = Range3d.createArray([new Point3d(), new Point3d(10000, 10000, 10000)]);
const is2d = false;
const isPlanar = true;
const tolerance = 0.15;
const areaTolerance = ToleranceRatio.facetArea * tolerance;
let mb = MeshBuilder.create({ displayParams, type, range, is2d, isPlanar, tolerance, areaTolerance });
// calls addPolyline for each stroke points list in strokes
expect(mb.mesh.polylines!.length).to.equal(0);
mb.addStrokePointLists(strksPrims, false, fillColor);
expect(mb.mesh.polylines!.length).to.equal(strksPrims.length);
const lengthA = mb.mesh.points.length;
const lengthB = strksPrims[0].points.length;
expect(lengthA).to.be.lte(lengthB);
expect(mb.mesh.points.length).to.be.greaterThan(0);
// calls addPointString for each stroke points list in strokes
mb = MeshBuilder.create({ displayParams, type, range, is2d, isPlanar, tolerance, areaTolerance });
expect(mb.mesh.polylines!.length).to.equal(0);
expect(mb.mesh.points.length).to.equal(0);
mb.addStrokePointLists(strksPrims, true, fillColor);
expect(mb.mesh.polylines!.length).to.equal(strksPrims.length);
expect(mb.mesh.points.length).to.equal(strksPrims[0].points.length);
});
it("addFromPolyface", () => {
const points: Point3d[] = [];
points.push(new Point3d(0, 0, 0));
points.push(new Point3d(1, 0, 0));
points.push(new Point3d(1, 1, 0));
points.push(new Point3d(0, 1, 0));
const line = LineString3d.create(points);
const loop = Loop.create(line);
const gfParams: GraphicParams = new GraphicParams();
gfParams.lineColor = ColorDef.white;
gfParams.fillColor = ColorDef.black; // forces region outline flag
const displayParams: DisplayParams = DisplayParams.createForMesh(gfParams, false);
const loopRange: Range3d = new Range3d();
loop.range(undefined, loopRange);
expect(loopRange).to.not.be.null;
const loopGeom = Geometry.createFromLoop(loop, Transform.createIdentity(), loopRange, displayParams, false);
// query polyface list from loopGeom
const pfPrimList: PolyfacePrimitiveList | undefined = loopGeom.getPolyfaces(0);
assert(pfPrimList !== undefined);
if (pfPrimList === undefined)
return;
expect(pfPrimList.length).to.be.greaterThan(0);
const pfPrim: PolyfacePrimitive = pfPrimList[0];
expect(pfPrim.indexedPolyface.pointCount).to.equal(points.length);
const range = Range3d.createArray([new Point3d(), new Point3d(1000, 1000, 1000)]);
const is2d = false;
const isPlanar = true;
const tolerance = 0.15;
const areaTolerance = ToleranceRatio.facetArea * tolerance;
const type = Mesh.PrimitiveType.Mesh;
const mb = MeshBuilder.create({ displayParams, type, range, is2d, isPlanar, tolerance, areaTolerance });
const includeParams = false;
const fillColor = ColorDef.white.tbgr;
mb.addFromPolyface(pfPrim.indexedPolyface, { edgeOptions, includeParams, fillColor });
expect(mb.triangleSet.length).to.equal(2);
});
it("addFromPolyfaceVisitor", () => {
const points: Point3d[] = [];
points.push(new Point3d(0, 0, 0));
points.push(new Point3d(1, 0, 0));
points.push(new Point3d(1, 1, 0));
points.push(new Point3d(0, 1, 0));
const line = LineString3d.create(points);
const loop = Loop.create(line);
const gfParams: GraphicParams = new GraphicParams();
gfParams.lineColor = ColorDef.white;
gfParams.fillColor = ColorDef.black; // forces region outline flag
const displayParams: DisplayParams = DisplayParams.createForMesh(gfParams, false);
const loopRange: Range3d = new Range3d();
loop.range(undefined, loopRange);
expect(loopRange).to.not.be.null;
const loopGeom = Geometry.createFromLoop(loop, Transform.createIdentity(), loopRange, displayParams, false);
// query polyface list from loopGeom
const pfPrimList: PolyfacePrimitiveList | undefined = loopGeom.getPolyfaces(0);
assert(pfPrimList !== undefined);
if (pfPrimList === undefined)
return;
expect(pfPrimList.length).to.be.greaterThan(0);
const pfPrim: PolyfacePrimitive = pfPrimList[0];
expect(pfPrim.indexedPolyface.pointCount).to.equal(points.length);
const range = Range3d.createArray([new Point3d(), new Point3d(1000, 1000, 1000)]);
const is2d = false;
const isPlanar = true;
const tolerance = 0.15;
const areaTolerance = ToleranceRatio.facetArea * tolerance;
const type = Mesh.PrimitiveType.Mesh;
const mb = MeshBuilder.create({ displayParams, type, range, is2d, isPlanar, tolerance, areaTolerance });
const visitor = pfPrim.indexedPolyface.createVisitor();
const includeParams = false;
const fillColor = ColorDef.white.tbgr;
mb.addFromPolyfaceVisitor(visitor, { edgeOptions, includeParams, fillColor });
expect(mb.triangleSet.length).to.equal(1);
});
it("createTriangleVertices", () => {
const points: Point3d[] = [];
points.push(new Point3d(0, 0, 0));
points.push(new Point3d(1, 0, 0));
points.push(new Point3d(1, 1, 0));
points.push(new Point3d(0, 1, 0));
const line = LineString3d.create(points);
const loop = Loop.create(line);
const gfParams: GraphicParams = new GraphicParams();
gfParams.lineColor = ColorDef.white;
gfParams.fillColor = ColorDef.black; // forces region outline flag
const displayParams: DisplayParams = DisplayParams.createForMesh(gfParams, false);
const loopRange: Range3d = new Range3d();
loop.range(undefined, loopRange);
expect(loopRange).to.not.be.null;
const loopGeom = Geometry.createFromLoop(loop, Transform.createIdentity(), loopRange, displayParams, false);
// query polyface list from loopGeom
const pfPrimList: PolyfacePrimitiveList | undefined = loopGeom.getPolyfaces(0);
assert(pfPrimList !== undefined);
if (pfPrimList === undefined)
return;
expect(pfPrimList.length).to.be.greaterThan(0);
const pfPrim: PolyfacePrimitive = pfPrimList[0];
expect(pfPrim.indexedPolyface.pointCount).to.equal(points.length);
const range = Range3d.createArray([new Point3d(), new Point3d(1000, 1000, 1000)]);
const is2d = false;
const isPlanar = true;
const tolerance = 0.15;
const areaTolerance = ToleranceRatio.facetArea * tolerance;
const type = Mesh.PrimitiveType.Mesh;
const mb = MeshBuilder.create({ displayParams, type, range, is2d, isPlanar, tolerance, areaTolerance });
const includeParams = false;
const visitor = pfPrim.indexedPolyface.createVisitor();
const fillColor = ColorDef.white.tbgr;
const triangleCount = visitor.pointCount - 2;
const haveParam = includeParams && visitor.paramCount > 0;
const triangleIndex = 0;
const vertices = mb.createTriangleVertices(triangleIndex, visitor, { edgeOptions, fillColor, includeParams, haveParam, triangleCount });
expect(vertices!.length).to.equal(3);
});
it("createTriangle", () => {
const points: Point3d[] = [];
points.push(new Point3d(0, 0, 0));
points.push(new Point3d(1, 0, 0));
points.push(new Point3d(1, 1, 0));
points.push(new Point3d(0, 1, 0));
const line = LineString3d.create(points);
const loop = Loop.create(line);
const gfParams: GraphicParams = new GraphicParams();
gfParams.lineColor = ColorDef.white;
gfParams.fillColor = ColorDef.black; // forces region outline flag
const displayParams: DisplayParams = DisplayParams.createForMesh(gfParams, false);
const loopRange: Range3d = new Range3d();
loop.range(undefined, loopRange);
const loopGeom = Geometry.createFromLoop(loop, Transform.createIdentity(), loopRange, displayParams, false);
// query polyface list from loopGeom
const pfPrimList: PolyfacePrimitiveList | undefined = loopGeom.getPolyfaces(0);
if (pfPrimList === undefined)
return;
const pfPrim: PolyfacePrimitive = pfPrimList[0];
const range = Range3d.createArray([new Point3d(), new Point3d(1000, 1000, 1000)]);
const is2d = false;
const isPlanar = true;
const tolerance = 0.15;
const areaTolerance = ToleranceRatio.facetArea * tolerance;
const type = Mesh.PrimitiveType.Mesh;
const mb = MeshBuilder.create({ displayParams, type, range, is2d, isPlanar, tolerance, areaTolerance });
const includeParams = false;
const visitor = pfPrim.indexedPolyface.createVisitor();
const fillColor = ColorDef.white.tbgr;
const triangleCount = visitor.pointCount - 2;
const haveParam = includeParams && visitor.paramCount > 0;
const triangleIndex = 0;
const triangle = mb.createTriangleVertices(triangleIndex, visitor, { edgeOptions, fillColor, includeParams, haveParam, triangleCount });
expect(triangle).to.not.be.undefined;
});
it("addPolyline", () => {
const displayParams = new FakeDisplayParams();
let type = Mesh.PrimitiveType.Mesh;
const range = Range3d.createArray([new Point3d(), new Point3d(1000, 1000, 1000)]);
const is2d = false;
const isPlanar = true;
const tolerance = 0.15;
const areaTolerance = ToleranceRatio.facetArea * tolerance;
let mb = MeshBuilder.create({ displayParams, type, range, is2d, isPlanar, tolerance, areaTolerance });
let points = [new Point3d(), new Point3d(100, 100, 100), new Point3d(200, 200, 200)];
const fillColor = ColorDef.white.tbgr;
// throws assertion error if type is mesh (should be point or polyline)
expect(() => mb.addPolyline(points, fillColor)).to.throw("Assert: Programmer Error");
points = [new Point3d(), new Point3d(1, 1, 1), new Point3d(2, 2, 2)];
type = Mesh.PrimitiveType.Polyline;
mb = MeshBuilder.create({ displayParams, type, range, is2d, isPlanar, tolerance, areaTolerance });
expect(mb.mesh.polylines!.length).to.equal(0);
mb.addPolyline(points, fillColor);
expect(mb.mesh.polylines!.length).to.equal(1);
points = [new Point3d()];
mb = MeshBuilder.create({ displayParams, type, range, is2d, isPlanar, tolerance, areaTolerance });
// if array is less than 1 in length, no polylines added
expect(mb.mesh.polylines!.length).to.equal(0);
mb.addPolyline(points, fillColor);
expect(mb.mesh.polylines!.length).to.equal(0);
});
it("addPointString", () => {
const displayParams = new FakeDisplayParams();
let type = Mesh.PrimitiveType.Mesh;
const range = Range3d.createArray([new Point3d(), new Point3d(1000, 1000, 1000)]);
const is2d = false;
const isPlanar = true;
const tolerance = 0.15;
const areaTolerance = ToleranceRatio.facetArea * tolerance;
let mb = MeshBuilder.create({ displayParams, type, range, is2d, isPlanar, tolerance, areaTolerance });
let points = [new Point3d(), new Point3d(100, 100, 100), new Point3d(200, 200, 200)];
const fillColor = ColorDef.white.tbgr;
// throws assertion error if type is mesh (should be point or polyline)
expect(() => mb.addPointString(points, fillColor)).to.throw("Assert: Programmer Error");
points = [new Point3d(), new Point3d(1, 1, 1), new Point3d(2, 2, 2)];
type = Mesh.PrimitiveType.Polyline;
mb = MeshBuilder.create({ displayParams, type, range, is2d, isPlanar, tolerance, areaTolerance });
expect(mb.mesh.polylines!.length).to.equal(0);
mb.addPointString(points, fillColor);
expect(mb.mesh.polylines!.length).to.equal(1);
points = [new Point3d()];
mb = MeshBuilder.create({ displayParams, type, range, is2d, isPlanar, tolerance, areaTolerance });
// if array is less than 1 in length, no polylines added
expect(mb.mesh.polylines!.length).to.equal(0);
mb.addPointString(points, fillColor);
expect(mb.mesh.polylines!.length).to.equal(0);
});
it("addTriangle", () => {
const triangle = new Triangle();
triangle.setIndices(1, 2, 3);
const displayParams = new FakeDisplayParams();
const type = Mesh.PrimitiveType.Mesh;
const range = Range3d.createArray([new Point3d(), new Point3d(1000, 1000, 1000)]);
const is2d = false;
const isPlanar = true;
const tolerance = 0.15;
const areaTolerance = ToleranceRatio.facetArea * tolerance;
let mb = MeshBuilder.create({ displayParams, type, range, is2d, isPlanar, tolerance, areaTolerance });
expect(mb.mesh.triangles!.length).to.equal(0);
mb.addTriangle(triangle);
expect(mb.mesh.triangles!.length).to.equal(1);
// degenerate case
triangle.setIndices(0, 0, 0);
mb = MeshBuilder.create({ displayParams, type, range, is2d, isPlanar, tolerance, areaTolerance });
expect(() => mb.addTriangle(triangle)).to.throw("Programmer Error");
});
function createMeshBuilder(type: Mesh.PrimitiveType, range: Range3d, options?: Partial<Omit<MeshBuilder.Props, "range" | "type">>): MeshBuilder {
options = options ?? { };
const tolerance = options.tolerance ?? 0.15;
return MeshBuilder.create({
type,
range,
tolerance,
areaTolerance: options.areaTolerance ?? ToleranceRatio.facetArea * tolerance,
displayParams: options.displayParams ?? new FakeDisplayParams(),
is2d: options.is2d ?? false,
isPlanar: options.isPlanar ?? true,
});
}
describe("aux data", () => {
function expectAuxChannelTable(mesh: Mesh, expectedUint16Data: number[]): void {
const args = new MeshGraphicArgs();
mesh.getGraphics(args, IModelApp.renderSystem);
const meshParams = MeshParams.create(args.meshArgs);
const aux = meshParams.auxChannels!;
expect(aux).not.to.be.undefined;
expect(Array.from(new Uint16Array(aux.data.buffer))).to.deep.equal(expectedUint16Data);
}
it("preserves aux data for triangle facets", () => {
const pfBuilder = PolyfaceBuilder.create();
pfBuilder.addTriangleFacet([new Point3d(0, 0, 0), new Point3d(1, 0, 0), new Point3d(1, 1, 0)]);
const pf = pfBuilder.claimPolyface();
const channelData = new AuxChannelData(1, [0, 0x7fff, 0xffff]);
const channel = new AuxChannel([channelData], AuxChannelDataType.Scalar, "s");
pf.data.auxData = new PolyfaceAuxData([channel], [0, 1, 2]);
const meshBuilder = createMeshBuilder(Mesh.PrimitiveType.Mesh, Range3d.fromJSON({ low: [0, 0, 0], high: [1, 1, 0] }));
meshBuilder.addFromPolyface(pf, { edgeOptions, includeParams: false, fillColor: 0 });
const mesh = meshBuilder.mesh;
expect(mesh.points.length).to.equal(3);
expect(mesh.auxChannels!.length).to.equal(1);
expect(mesh.auxChannels).to.deep.equal(pf.data.auxData.channels);
expectAuxChannelTable(mesh, [0, 0x7fff, 0xffff, 0]); // trailing zero is unused byte in last texel.
});
it("preserves aux data for facets with more than 3 sides", () => {
const pfBuilder = PolyfaceBuilder.create();
pfBuilder.addQuadFacet([new Point3d(0, 0, 0), new Point3d(0, 1, 0), new Point3d(1, 1, 0), new Point3d(1, 0, 0)]);
const pf = pfBuilder.claimPolyface();
const channelData = new AuxChannelData(1, [0, 0x4fff, 0xbfff, 0xffff]);
const channel = new AuxChannel([channelData], AuxChannelDataType.Scalar, "s");
pf.data.auxData = new PolyfaceAuxData([channel], [0, 1, 2, 3]);
const meshBuilder = createMeshBuilder(Mesh.PrimitiveType.Mesh, Range3d.fromJSON({ low: [0, 0, 0], high: [1, 1, 0] }));
meshBuilder.addFromPolyface(pf, { edgeOptions, includeParams: false, fillColor: 0 });
const mesh = meshBuilder.mesh;
expect(mesh.points.length).to.equal(6);
expect(mesh.auxChannels!.length).to.equal(1);
const aux = mesh.auxChannels![0];
expect(aux.data.length).to.equal(1);
const expectedData = [0, 0x4fff, 0xbfff, 0, 0xbfff, 0xffff];
expect(aux.data[0].values).to.deep.equal(expectedData);
expectAuxChannelTable(mesh, expectedData);
});
it("maps aux data to vertices based on indices", () => {
const pfBuilder = PolyfaceBuilder.create();
pfBuilder.addQuadFacet([new Point3d(0, 0, 0), new Point3d(0, 1, 0), new Point3d(1, 1, 0), new Point3d(1, 0, 0)]);
const pf = pfBuilder.claimPolyface();
const channelData = new AuxChannelData(1, [0x4000, 0x6000, 0x8000]);
const channel = new AuxChannel([channelData], AuxChannelDataType.Scalar, "s");
pf.data.auxData = new PolyfaceAuxData([channel], [2, 0, 0, 1]);
const meshBuilder = createMeshBuilder(Mesh.PrimitiveType.Mesh, Range3d.fromJSON({ low: [0, 0, 0], high: [1, 1, 0] }));
meshBuilder.addFromPolyface(pf, { edgeOptions, includeParams: false, fillColor: 0 });
const mesh = meshBuilder.mesh;
expect(mesh.points.length).to.equal(6);
expect(mesh.auxChannels!.length).to.equal(1);
const aux = mesh.auxChannels![0];
expect(aux.data.length).to.equal(1);
expect(aux.data[0].values).to.deep.equal([0x8000, 0x4000, 0x4000, 0x8000, 0x4000, 0x6000]);
expectAuxChannelTable(mesh, [0xffff, 0, 0, 0xffff, 0, 0x8000]);
});
it("produces aux data for vector channel", () => {
const pfBuilder = PolyfaceBuilder.create();
pfBuilder.addQuadFacet([new Point3d(0, 0, 0), new Point3d(0, 1, 0), new Point3d(1, 1, 0), new Point3d(1, 0, 0)]);
const pf = pfBuilder.claimPolyface();
const channelData = new AuxChannelData(1, [0, 1, 2, 3, 4, 0xffff]);
const channel = new AuxChannel([channelData], AuxChannelDataType.Vector, "v");
pf.data.auxData = new PolyfaceAuxData([channel], [0, 1, 1, 0]);
const meshBuilder = createMeshBuilder(Mesh.PrimitiveType.Mesh, Range3d.fromJSON({ low: [0, 0, 0], high: [1, 1, 0] }));
meshBuilder.addFromPolyface(pf, { edgeOptions, includeParams: false, fillColor: 0 });
const aux = meshBuilder.mesh.auxChannels![0];
expect(aux.data[0].values).to.deep.equal([
0, 1, 2, 3, 4, 0xffff, 3, 4, 0xffff,
0, 1, 2, 3, 4, 0xffff, 0, 1, 2,
]);
expectAuxChannelTable(meshBuilder.mesh, [
0, 0, 0, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff, 0xffff,
0, 0, 0, 0xffff, 0xffff, 0xffff, 0, 0, 0,
]);
});
});
}); | the_stack |
import {Utils as _} from "../utils";
import {RenderedCell} from "./renderedCell";
import {RowNode} from "../entities/rowNode";
import {GridOptionsWrapper} from "../gridOptionsWrapper";
import {ColumnController} from "../columnController/columnController";
import {RowRenderer} from "./rowRenderer";
import {Column} from "../entities/column";
import {Events} from "../events";
import {EventService} from "../eventService";
import {Context, Autowired, PostConstruct} from "../context/context";
import {ColumnChangeEvent} from "../columnChangeEvent";
import {FocusedCellController} from "../focusedCellController";
import {Constants} from "../constants";
import {GridCell} from "../entities/gridCell";
import {CellRendererService} from "./cellRendererService";
import {CellRendererFactory} from "./cellRendererFactory";
import {ICellRenderer, ICellRendererFunc} from "./cellRenderers/iCellRenderer";
import {GridPanel} from "../gridPanel/gridPanel";
export class RenderedRow {
public static EVENT_RENDERED_ROW_REMOVED = 'renderedRowRemoved';
@Autowired('gridOptionsWrapper') private gridOptionsWrapper: GridOptionsWrapper;
@Autowired('columnController') private columnController: ColumnController;
@Autowired('$compile') private $compile: any;
@Autowired('eventService') private mainEventService: EventService;
@Autowired('context') private context: Context;
@Autowired('focusedCellController') private focusedCellController: FocusedCellController;
@Autowired('cellRendererService') private cellRendererService: CellRendererService;
@Autowired('gridPanel') private gridPanel: GridPanel;
private ePinnedLeftRow: HTMLElement;
private ePinnedRightRow: HTMLElement;
private eBodyRow: HTMLElement;
private eFullWidthRow: HTMLElement;
private eAllRowContainers: HTMLElement[] = [];
private fullWidthRowComponent: ICellRenderer;
private renderedCells: {[key: string]: RenderedCell} = {};
private scope: any;
private rowNode: RowNode;
private rowIndex: number;
private fullWidthRow: boolean;
private fullWidthCellRenderer: {new(): ICellRenderer} | ICellRendererFunc | string;
private fullWidthCellRendererParams: any;
private parentScope: any;
private rowRenderer: RowRenderer;
private eBodyContainer: HTMLElement;
private eFullWidthContainer: HTMLElement;
private ePinnedLeftContainer: HTMLElement;
private ePinnedRightContainer: HTMLElement;
private destroyFunctions: Function[] = [];
private renderedRowEventService: EventService;
private editingRow = false;
private initialised = false;
constructor(parentScope: any,
rowRenderer: RowRenderer,
eBodyContainer: HTMLElement,
eFullWidthContainer: HTMLElement,
ePinnedLeftContainer: HTMLElement,
ePinnedRightContainer: HTMLElement,
node: RowNode,
rowIndex: number) {
this.parentScope = parentScope;
this.rowRenderer = rowRenderer;
this.eBodyContainer = eBodyContainer;
this.eFullWidthContainer = eFullWidthContainer;
this.ePinnedLeftContainer = ePinnedLeftContainer;
this.ePinnedRightContainer = ePinnedRightContainer;
this.rowIndex = rowIndex;
this.rowNode = node;
}
private setupRowContainers(): void {
let isFullWidthCellFunc = this.gridOptionsWrapper.getIsFullWidthCellFunc();
let isFullWidthCell = isFullWidthCellFunc ? isFullWidthCellFunc(this.rowNode) : false;
let isGroupSpanningRow = this.rowNode.group && this.gridOptionsWrapper.isGroupUseEntireRow();
if (isFullWidthCell) {
this.setupFullWidthContainers();
} else if (isGroupSpanningRow) {
this.setupFullWidthGroupContainers();
} else {
this.setupNormalContainers();
}
}
private setupFullWidthContainers(): void {
this.fullWidthRow = true;
this.fullWidthCellRenderer = this.gridOptionsWrapper.getFullWidthCellRenderer();
this.fullWidthCellRendererParams = this.gridOptionsWrapper.getFullWidthCellRendererParams();
if (_.missing(this.fullWidthCellRenderer)) {
console.warn(`ag-Grid: you need to provide a fullWidthCellRenderer if using isFullWidthCell()`);
}
this.eFullWidthRow = this.createRowContainer(this.eFullWidthContainer);
if (!this.gridOptionsWrapper.isForPrint()) {
this.addMouseWheelListenerToFullWidthRow();
}
}
private addMouseWheelListenerToFullWidthRow(): void {
var mouseWheelListener = this.gridPanel.genericMouseWheelListener.bind(this.gridPanel);
// IE9, Chrome, Safari, Opera
this.eFullWidthRow.addEventListener('mousewheel', mouseWheelListener);
// Firefox
this.eFullWidthRow.addEventListener('DOMMouseScroll', mouseWheelListener);
this.destroyFunctions.push( ()=> {
this.eFullWidthRow.removeEventListener('mousewheel', mouseWheelListener);
this.eFullWidthRow.removeEventListener('DOMMouseScroll', mouseWheelListener);
});
}
private setupFullWidthGroupContainers(): void {
this.fullWidthRow = true;
this.fullWidthCellRenderer = this.gridOptionsWrapper.getGroupRowRenderer();
this.fullWidthCellRendererParams = this.gridOptionsWrapper.getGroupRowRendererParams();
if (!this.fullWidthCellRenderer) {
this.fullWidthCellRenderer = CellRendererFactory.GROUP;
this.fullWidthCellRendererParams = {
innerRenderer: this.gridOptionsWrapper.getGroupRowInnerRenderer(),
}
}
this.eFullWidthRow = this.createRowContainer(this.eFullWidthContainer);
if (!this.gridOptionsWrapper.isForPrint()) {
this.addMouseWheelListenerToFullWidthRow();
}
}
private setupNormalContainers(): void {
this.fullWidthRow = false;
this.eBodyRow = this.createRowContainer(this.eBodyContainer);
if (!this.gridOptionsWrapper.isForPrint()) {
this.ePinnedLeftRow = this.createRowContainer(this.ePinnedLeftContainer);
this.ePinnedRightRow = this.createRowContainer(this.ePinnedRightContainer);
}
}
@PostConstruct
public init(): void {
this.setupRowContainers();
this.scope = this.createChildScopeOrNull(this.rowNode.data);
if (this.fullWidthRow) {
this.refreshFullWidthComponent();
} else {
this.refreshCellsIntoRow();
}
this.addGridClasses();
this.addStyleFromRowStyle();
this.addStyleFromRowStyleFunc();
this.addClassesFromRowClass();
this.addClassesFromRowClassFunc();
this.addRowIds();
this.setTopAndHeightCss();
this.addRowSelectedListener();
this.addCellFocusedListener();
this.addNodeDataChangedListener();
this.addColumnListener();
this.addHoverFunctionality();
this.gridOptionsWrapper.executeProcessRowPostCreateFunc({
eRow: this.eBodyRow,
ePinnedLeftRow: this.ePinnedLeftRow,
ePinnedRightRow: this.ePinnedRightRow,
node: this.rowNode,
api: this.gridOptionsWrapper.getApi(),
rowIndex: this.rowIndex,
addRenderedRowListener: this.addEventListener.bind(this),
columnApi: this.gridOptionsWrapper.getColumnApi(),
context: this.gridOptionsWrapper.getContext()
});
this.addDataChangedListener();
this.initialised = true;
}
public stopRowEditing(cancel: boolean): void {
this.stopEditing(cancel);
}
public stopEditing(cancel = false): void {
this.forEachRenderedCell( renderedCell => {
renderedCell.stopEditing(cancel);
});
this.setEditingRow(false);
if (!cancel) {
var event = {
node: this.rowNode,
data: this.rowNode.data,
api: this.gridOptionsWrapper.getApi(),
context: this.gridOptionsWrapper.getContext()
};
this.mainEventService.dispatchEvent(Events.EVENT_ROW_VALUE_CHANGED, event);
}
}
public startRowEditing(keyPress: number = null, charPress: string = null, sourceRenderedCell: RenderedCell = null): void {
// don't do it if already editing
if (this.editingRow) { return; }
this.forEachRenderedCell( renderedCell => {
var cellStartedEdit = renderedCell === sourceRenderedCell;
if (cellStartedEdit) {
renderedCell.startEditingIfEnabled(keyPress, charPress, cellStartedEdit)
} else {
renderedCell.startEditingIfEnabled(null, null, cellStartedEdit)
}
});
this.setEditingRow(true);
}
private setEditingRow(value: boolean): void {
this.editingRow = value;
this.eAllRowContainers.forEach( (row) => _.addOrRemoveCssClass(row, 'ag-row-editing', value) );
}
// because data can change, especially in virtual pagination and viewport row models, need to allow setting
// styles and classes after the data has changed
private addDataChangedListener(): void {
var dataChangedListener = ()=> {
this.addStyleFromRowStyleFunc();
this.addClassesFromRowClass();
};
this.rowNode.addEventListener(RowNode.EVENT_DATA_CHANGED, dataChangedListener);
this.destroyFunctions.push( ()=> this.rowNode.removeEventListener(RowNode.EVENT_DATA_CHANGED, dataChangedListener) );
}
private angular1Compile(element: Element): void {
if (this.scope) {
this.$compile(element)(this.scope);
}
}
private addColumnListener(): void {
var columnListener = this.onDisplayedColumnsChanged.bind(this);
var virtualListener = this.onVirtualColumnsChanged.bind(this);
var gridColumnsChangedListener = this.onGridColumnsChanged.bind(this);
this.mainEventService.addEventListener(Events.EVENT_DISPLAYED_COLUMNS_CHANGED, columnListener);
this.mainEventService.addEventListener(Events.EVENT_VIRTUAL_COLUMNS_CHANGED, virtualListener);
this.mainEventService.addEventListener(Events.EVENT_COLUMN_RESIZED, columnListener);
this.mainEventService.addEventListener(Events.EVENT_GRID_COLUMNS_CHANGED, gridColumnsChangedListener);
this.destroyFunctions.push( () => {
this.mainEventService.removeEventListener(Events.EVENT_DISPLAYED_COLUMNS_CHANGED, columnListener);
this.mainEventService.removeEventListener(Events.EVENT_VIRTUAL_COLUMNS_CHANGED, virtualListener);
this.mainEventService.removeEventListener(Events.EVENT_COLUMN_RESIZED, columnListener);
this.mainEventService.removeEventListener(Events.EVENT_GRID_COLUMNS_CHANGED, gridColumnsChangedListener);
});
}
private onDisplayedColumnsChanged(event: ColumnChangeEvent): void {
// if row is a group row that spans, then it's not impacted by column changes, with exception of pinning
if (this.fullWidthRow) {
var columnPinned = event.getType() === Events.EVENT_COLUMN_PINNED;
if (columnPinned) {
this.refreshFullWidthComponent();
}
} else {
this.refreshCellsIntoRow();
}
}
private onVirtualColumnsChanged(event: ColumnChangeEvent): void {
// if row is a group row that spans, then it's not impacted by column changes, with exception of pinning
if (!this.fullWidthRow) {
this.refreshCellsIntoRow();
}
}
// when grid columns change, then all cells should be cleaned out,
// as the new columns could have same id as the previous columns and may conflict
private onGridColumnsChanged(): void {
var allRenderedCellIds = Object.keys(this.renderedCells);
this.removeRenderedCells(allRenderedCellIds);
}
// method makes sure the right cells are present, and are in the right container. so when this gets called for
// the first time, it sets up all the cells. but then over time the cells might appear / dissappear or move
// container (ie into pinned)
private refreshCellsIntoRow() {
var columns = this.columnController.getAllDisplayedVirtualColumns();
var renderedCellKeys = Object.keys(this.renderedCells);
columns.forEach( (column: Column) => {
var renderedCell = this.getOrCreateCell(column);
this.ensureCellInCorrectRow(renderedCell);
_.removeFromArray(renderedCellKeys, column.getColId());
});
// remove old cells from gui, but we don't destroy them, we might use them again
this.removeRenderedCells(renderedCellKeys);
}
private removeRenderedCells(colIds: string[]): void {
colIds.forEach( (key: string)=> {
var renderedCell = this.renderedCells[key];
// could be old reference, ie removed cell
if (_.missing(renderedCell)) { return; }
if (renderedCell.getParentRow()) {
renderedCell.getParentRow().removeChild(renderedCell.getGui());
renderedCell.setParentRow(null);
}
renderedCell.destroy();
this.renderedCells[key] = null;
});
}
private ensureCellInCorrectRow(renderedCell: RenderedCell): void {
var eRowGui = renderedCell.getGui();
var column = renderedCell.getColumn();
var rowWeWant: HTMLElement;
switch (column.getPinned()) {
case Column.PINNED_LEFT: rowWeWant = this.ePinnedLeftRow; break;
case Column.PINNED_RIGHT: rowWeWant = this.ePinnedRightRow; break;
default: rowWeWant = this.eBodyRow; break;
}
// if in wrong container, remove it
var oldRow = renderedCell.getParentRow();
var inWrongRow = oldRow !== rowWeWant;
if (inWrongRow) {
// take out from old row
if (oldRow) {
oldRow.removeChild(eRowGui);
}
rowWeWant.appendChild(eRowGui);
renderedCell.setParentRow(rowWeWant);
}
}
private getOrCreateCell(column: Column): RenderedCell {
var colId = column.getColId();
if (this.renderedCells[colId]) {
return this.renderedCells[colId];
} else {
var renderedCell = new RenderedCell(column,
this.rowNode, this.rowIndex, this.scope, this);
this.context.wireBean(renderedCell);
this.renderedCells[colId] = renderedCell;
this.angular1Compile(renderedCell.getGui());
// if we are editing the row, then the cell needs to turn
// into edit mode
if (this.editingRow) {
renderedCell.startEditingIfEnabled();
}
return renderedCell;
}
}
private onRowSelected(): void {
var selected = this.rowNode.isSelected();
this.eAllRowContainers.forEach( (row) => _.addOrRemoveCssClass(row, 'ag-row-selected', selected) );
}
private addRowSelectedListener(): void {
var rowSelectedListener = this.onRowSelected.bind(this);
this.rowNode.addEventListener(RowNode.EVENT_ROW_SELECTED, rowSelectedListener);
this.destroyFunctions.push(()=> {
this.rowNode.removeEventListener(RowNode.EVENT_ROW_SELECTED, rowSelectedListener);
});
}
private addHoverFunctionality(): void {
var onGuiMouseEnter = this.rowNode.onMouseEnter.bind(this.rowNode);
var onGuiMouseLeave = this.rowNode.onMouseLeave.bind(this.rowNode);
this.eAllRowContainers.forEach( eRow => {
eRow.addEventListener('mouseenter', onGuiMouseEnter);
eRow.addEventListener('mouseleave', onGuiMouseLeave);
});
var onNodeMouseEnter = this.addHoverClass.bind(this, true);
var onNodeMouseLeave = this.addHoverClass.bind(this, false);
this.rowNode.addEventListener(RowNode.EVENT_MOUSE_ENTER, onNodeMouseEnter);
this.rowNode.addEventListener(RowNode.EVENT_MOUSE_LEAVE, onNodeMouseLeave);
this.destroyFunctions.push( ()=> {
this.eAllRowContainers.forEach( eRow => {
eRow.removeEventListener('mouseenter', onGuiMouseEnter);
eRow.removeEventListener('mouseleave', onGuiMouseLeave);
});
this.rowNode.removeEventListener(RowNode.EVENT_MOUSE_ENTER, onNodeMouseEnter);
this.rowNode.removeEventListener(RowNode.EVENT_MOUSE_LEAVE, onNodeMouseLeave);
});
}
private addHoverClass(hover: boolean): void {
this.eAllRowContainers.forEach( eRow => _.addOrRemoveCssClass(eRow, 'ag-row-hover', hover) );
}
private addCellFocusedListener(): void {
var rowFocusedLastTime: boolean = null;
var rowFocusedListener = () => {
var rowFocused = this.focusedCellController.isRowFocused(this.rowIndex, this.rowNode.floating);
if (rowFocused !== rowFocusedLastTime) {
this.eAllRowContainers.forEach( (row) => _.addOrRemoveCssClass(row, 'ag-row-focus', rowFocused) );
this.eAllRowContainers.forEach( (row) => _.addOrRemoveCssClass(row, 'ag-row-no-focus', !rowFocused) );
rowFocusedLastTime = rowFocused;
}
if (!rowFocused && this.editingRow) {
this.stopEditing(false);
}
};
this.mainEventService.addEventListener(Events.EVENT_CELL_FOCUSED, rowFocusedListener);
this.destroyFunctions.push(()=> {
this.mainEventService.removeEventListener(Events.EVENT_CELL_FOCUSED, rowFocusedListener);
});
rowFocusedListener();
}
public forEachRenderedCell(callback: (renderedCell: RenderedCell)=>void): void {
_.iterateObject(this.renderedCells, (key: any, renderedCell: RenderedCell)=> {
if (renderedCell) {
callback(renderedCell);
}
});
}
private addNodeDataChangedListener(): void {
var nodeDataChangedListener = () => {
var animate = false;
var newData = true;
this.forEachRenderedCell( renderedCell => renderedCell.refreshCell(animate, newData) );
// check for selected also, as this could be after lazy loading of the row data, in which csae
// the id might of just gotten set inside the row and the row selected state may of changed
// as a result. this is what happens when selected rows are loaded in virtual pagination.
this.onRowSelected();
};
this.rowNode.addEventListener(RowNode.EVENT_DATA_CHANGED, nodeDataChangedListener);
this.destroyFunctions.push(()=> {
this.rowNode.removeEventListener(RowNode.EVENT_DATA_CHANGED, nodeDataChangedListener);
});
}
public onMouseEvent(eventName: string, mouseEvent: MouseEvent, cell: GridCell): void {
var renderedCell = this.renderedCells[cell.column.getId()];
if (renderedCell) {
renderedCell.onMouseEvent(eventName, mouseEvent);
}
}
private setTopAndHeightCss(): void {
// if showing scrolls, position on the container
if (!this.gridOptionsWrapper.isForPrint()) {
var topPx = this.rowNode.rowTop + "px";
this.eAllRowContainers.forEach( row => row.style.top = topPx);
}
var heightPx = this.rowNode.rowHeight + 'px';
this.eAllRowContainers.forEach( row => row.style.height = heightPx);
}
// adds in row and row-id attributes to the row
private addRowIds(): void {
var rowStr = this.rowIndex.toString();
if (this.rowNode.floating===Constants.FLOATING_BOTTOM) {
rowStr = 'fb-' + rowStr;
} else if (this.rowNode.floating===Constants.FLOATING_TOP) {
rowStr = 'ft-' + rowStr;
}
this.eAllRowContainers.forEach( row => row.setAttribute('row', rowStr) );
if (typeof this.gridOptionsWrapper.getBusinessKeyForNodeFunc() === 'function') {
var businessKey = this.gridOptionsWrapper.getBusinessKeyForNodeFunc()(this.rowNode);
if (typeof businessKey === 'string' || typeof businessKey === 'number') {
this.eAllRowContainers.forEach( row => row.setAttribute('row-id', businessKey) );
}
}
}
public addEventListener(eventType: string, listener: Function): void {
if (!this.renderedRowEventService) { this.renderedRowEventService = new EventService(); }
this.renderedRowEventService.addEventListener(eventType, listener);
}
public removeEventListener(eventType: string, listener: Function): void {
this.renderedRowEventService.removeEventListener(eventType, listener);
}
public getRenderedCellForColumn(column: Column): RenderedCell {
return this.renderedCells[column.getColId()];
}
public getCellForCol(column: Column): HTMLElement {
var renderedCell = this.renderedCells[column.getColId()];
if (renderedCell) {
return renderedCell.getGui();
} else {
return null;
}
}
public destroy(): void {
this.destroyScope();
this.destroyFullWidthComponent();
this.forEachRenderedCell( renderedCell => renderedCell.destroy() );
this.destroyFunctions.forEach( func => func() );
if (this.renderedRowEventService) {
this.renderedRowEventService.dispatchEvent(RenderedRow.EVENT_RENDERED_ROW_REMOVED, {node: this.rowNode});
}
}
private destroyScope(): void {
if (this.scope) {
this.scope.$destroy();
this.scope = null;
}
}
public isDataInList(rows: any[]): boolean {
return rows.indexOf(this.rowNode.data) >= 0;
}
public isGroup(): boolean {
return this.rowNode.group === true;
}
private refreshFullWidthComponent(): void {
this.destroyFullWidthComponent();
this.createFullWidthComponent();
}
private createFullWidthComponent(): void {
var params = this.createFullWidthParams(this.eFullWidthRow);
this.fullWidthRowComponent = this.cellRendererService.useCellRenderer(this.fullWidthCellRenderer, this.eFullWidthRow, params);
this.angular1Compile(this.eFullWidthRow);
}
private destroyFullWidthComponent(): void {
if (this.fullWidthRowComponent && this.fullWidthRowComponent.destroy) {
this.fullWidthRowComponent.destroy();
this.fullWidthRowComponent = null;
}
_.removeAllChildren(this.eFullWidthRow);
}
private createFullWidthParams(eRow: HTMLElement): any {
var params = {
data: this.rowNode.data,
node: this.rowNode,
$scope: this.scope,
rowIndex: this.rowIndex,
api: this.gridOptionsWrapper.getApi(),
columnApi: this.gridOptionsWrapper.getColumnApi(),
context: this.gridOptionsWrapper.getContext(),
eGridCell: eRow,
eParentOfValue: eRow,
addRenderedRowListener: this.addEventListener.bind(this),
colDef: {
cellRenderer: this.fullWidthCellRenderer,
cellRendererParams: this.fullWidthCellRendererParams
}
};
if (this.fullWidthCellRendererParams) {
_.assign(params, this.fullWidthCellRendererParams);
}
return params;
}
private createGroupSpanningEntireRowCell(padding: boolean): HTMLElement {
var eRow: HTMLElement = document.createElement('span');
// padding means we are on the right hand side of a pinned table, ie
// in the main body.
if (!padding) {
var params = this.createFullWidthParams(eRow);
var cellComponent = this.cellRendererService.useCellRenderer(this.fullWidthCellRenderer, eRow, params);
if (cellComponent && cellComponent.destroy) {
this.destroyFunctions.push( () => cellComponent.destroy() );
}
}
if (this.rowNode.footer) {
_.addCssClass(eRow, 'ag-footer-cell-entire-row');
} else {
_.addCssClass(eRow, 'ag-group-cell-entire-row');
}
return eRow;
}
private createChildScopeOrNull(data: any) {
if (this.gridOptionsWrapper.isAngularCompileRows()) {
var newChildScope = this.parentScope.$new();
newChildScope.data = data;
newChildScope.rowNode = this.rowNode;
newChildScope.context = this.gridOptionsWrapper.getContext();
return newChildScope;
} else {
return null;
}
}
private addStyleFromRowStyle(): void {
var rowStyle = this.gridOptionsWrapper.getRowStyle();
if (rowStyle) {
if (typeof rowStyle === 'function') {
console.log('ag-Grid: rowStyle should be an object of key/value styles, not be a function, use getRowStyle() instead');
} else {
this.eAllRowContainers.forEach( row => _.addStylesToElement(row, rowStyle));
}
}
}
private addStyleFromRowStyleFunc(): void {
var rowStyleFunc = this.gridOptionsWrapper.getRowStyleFunc();
if (rowStyleFunc) {
var params = {
data: this.rowNode.data,
node: this.rowNode,
api: this.gridOptionsWrapper.getApi(),
context: this.gridOptionsWrapper.getContext(),
$scope: this.scope
};
var cssToUseFromFunc = rowStyleFunc(params);
this.eAllRowContainers.forEach( row => _.addStylesToElement(row, cssToUseFromFunc));
}
}
private createParams(): any {
var params = {
node: this.rowNode,
data: this.rowNode.data,
rowIndex: this.rowIndex,
$scope: this.scope,
context: this.gridOptionsWrapper.getContext(),
api: this.gridOptionsWrapper.getApi()
};
return params;
}
private createEvent(event: any, eventSource: any): any {
var agEvent = this.createParams();
agEvent.event = event;
agEvent.eventSource = eventSource;
return agEvent;
}
private createRowContainer(eParent: HTMLElement): HTMLElement {
var eRow = document.createElement('div');
var rowClickListener = this.onRowClick.bind(this);
var rowDblClickListener = this.onRowDblClick.bind(this);
eRow.addEventListener("click", rowClickListener);
eRow.addEventListener("dblclick", rowDblClickListener);
eParent.appendChild(eRow);
this.eAllRowContainers.push(eRow);
this.destroyFunctions.push( ()=> {
eRow.removeEventListener("click", rowClickListener);
eRow.removeEventListener("dblclick", rowDblClickListener);
eParent.removeChild(eRow);
});
return eRow;
}
private onRowDblClick(event: MouseEvent): void {
var agEvent = this.createEvent(event, this);
this.mainEventService.dispatchEvent(Events.EVENT_ROW_DOUBLE_CLICKED, agEvent);
}
public onRowClick(event: MouseEvent) {
var agEvent = this.createEvent(event, this);
this.mainEventService.dispatchEvent(Events.EVENT_ROW_CLICKED, agEvent);
// ctrlKey for windows, metaKey for Apple
var multiSelectKeyPressed = event.ctrlKey || event.metaKey;
var shiftKeyPressed = event.shiftKey;
// we do not allow selecting groups by clicking (as the click here expands the group)
// so return if it's a group row
if (this.rowNode.group) {
return;
}
// we also don't allow selection of floating rows
if (this.rowNode.floating) {
return;
}
// making local variables to make the below more readable
var gridOptionsWrapper = this.gridOptionsWrapper;
// if no selection method enabled, do nothing
if (!gridOptionsWrapper.isRowSelection()) {
return;
}
// if click selection suppressed, do nothing
if (gridOptionsWrapper.isSuppressRowClickSelection()) {
return;
}
if (this.rowNode.isSelected()) {
if (multiSelectKeyPressed) {
if (gridOptionsWrapper.isRowDeselection()) {
this.rowNode.setSelectedParams({newValue: false});
}
} else {
// selected with no multi key, must make sure anything else is unselected
this.rowNode.setSelectedParams({newValue: true, clearSelection: true});
}
} else {
this.rowNode.setSelectedParams({newValue: true, clearSelection: !multiSelectKeyPressed, rangeSelect: shiftKeyPressed});
}
}
public getRowNode(): any {
return this.rowNode;
}
public refreshCells(colIds: string[], animate: boolean): void {
if (!colIds) {
return;
}
var columnsToRefresh = this.columnController.getGridColumns(colIds);
this.forEachRenderedCell( renderedCell => {
var colForCel = renderedCell.getColumn();
if (columnsToRefresh.indexOf(colForCel)>=0) {
renderedCell.refreshCell(animate);
}
});
}
private addClassesFromRowClassFunc(): void {
var classes: string[] = [];
var gridOptionsRowClassFunc = this.gridOptionsWrapper.getRowClassFunc();
if (gridOptionsRowClassFunc) {
var params = {
node: this.rowNode,
data: this.rowNode.data,
rowIndex: this.rowIndex,
context: this.gridOptionsWrapper.getContext(),
api: this.gridOptionsWrapper.getApi()
};
var classToUseFromFunc = gridOptionsRowClassFunc(params);
if (classToUseFromFunc) {
if (typeof classToUseFromFunc === 'string') {
classes.push(classToUseFromFunc);
} else if (Array.isArray(classToUseFromFunc)) {
classToUseFromFunc.forEach(function (classItem: any) {
classes.push(classItem);
});
}
}
}
classes.forEach( (classStr: string) => {
this.eAllRowContainers.forEach( row => _.addCssClass(row, classStr));
});
}
private addGridClasses() {
var classes: string[] = [];
classes.push('ag-row');
classes.push('ag-row-no-focus');
classes.push(this.rowIndex % 2 == 0 ? 'ag-row-even' : 'ag-row-odd');
if (this.rowNode.isSelected()) {
classes.push('ag-row-selected');
}
if (this.rowNode.group) {
classes.push('ag-row-group');
// if a group, put the level of the group in
classes.push('ag-row-level-' + this.rowNode.level);
if (!this.rowNode.footer && this.rowNode.expanded) {
classes.push('ag-row-group-expanded');
}
if (!this.rowNode.footer && !this.rowNode.expanded) {
// opposite of expanded is contracted according to the internet.
classes.push('ag-row-group-contracted');
}
if (this.rowNode.footer) {
classes.push('ag-row-footer');
}
} else {
// if a leaf, and a parent exists, put a level of the parent, else put level of 0 for top level item
if (this.rowNode.parent) {
classes.push('ag-row-level-' + (this.rowNode.parent.level + 1));
} else {
classes.push('ag-row-level-0');
}
}
if (this.fullWidthRow) {
classes.push('ag-full-width-row');
}
classes.forEach( (classStr: string) => {
this.eAllRowContainers.forEach( row => _.addCssClass(row, classStr));
});
}
private addClassesFromRowClass() {
var classes: string[] = [];
// add in extra classes provided by the config
var gridOptionsRowClass = this.gridOptionsWrapper.getRowClass();
if (gridOptionsRowClass) {
if (typeof gridOptionsRowClass === 'function') {
console.warn('ag-Grid: rowClass should not be a function, please use getRowClass instead');
} else {
if (typeof gridOptionsRowClass === 'string') {
classes.push(gridOptionsRowClass);
} else if (Array.isArray(gridOptionsRowClass)) {
gridOptionsRowClass.forEach(function (classItem: any) {
classes.push(classItem);
});
}
}
}
classes.forEach( (classStr: string) => {
this.eAllRowContainers.forEach( row => _.addCssClass(row, classStr));
});
}
} | the_stack |
import * as webdriver from 'selenium-webdriver';
import * as chrome from 'selenium-webdriver/chrome';
import * as edge from 'selenium-webdriver/edge';
import * as firefox from 'selenium-webdriver/firefox';
import * as http from 'selenium-webdriver/http';
import * as remote from 'selenium-webdriver/remote';
import * as safari from 'selenium-webdriver/safari';
import * as testing from 'selenium-webdriver/testing';
function TestBuilder() {
let builder: webdriver.Builder = new webdriver.Builder();
let driver: webdriver.WebDriver = builder.build();
builder = builder.forBrowser('name');
builder = builder.forBrowser('name', 'version');
builder = builder.forBrowser('name', 'version', 'platform');
let cap: webdriver.Capabilities = builder.getCapabilities();
let str: string = builder.getServerUrl();
builder = builder.setAlertBehavior('behavior');
builder = builder.setChromeOptions(new chrome.Options());
builder = builder.setChromeService(new chrome.ServiceBuilder());
builder = builder.setControlFlow(new webdriver.promise.ControlFlow());
builder = builder.setEdgeOptions(new edge.Options());
builder = builder.setEdgeService(new edge.ServiceBuilder());
builder = builder.setEnableNativeEvents(true);
builder = builder.setFirefoxOptions(new firefox.Options());
builder = builder.setFirefoxService(new firefox.ServiceBuilder());
builder = builder.setLoggingPrefs(new webdriver.logging.Preferences());
builder = builder.setLoggingPrefs({ key: 'value' });
builder = builder.setProxy({ proxyType: 'type' });
builder = builder.setSafariOptions(new safari.Options());
builder = builder.setScrollBehavior(1);
builder = builder.usingServer('http://someserver');
builder = builder.withCapabilities(new webdriver.Capabilities());
builder = builder.withCapabilities({ something: true });
const chromeOptions: chrome.Options = builder.getChromeOptions();
const firefoxOptions: firefox.Options = builder.getFirefoxOptions();
const safariOptions: safari.Options = builder.getSafariOptions();
}
declare const promise: webdriver.promise.Promise<string>;
function TestActionSequence() {
let driver: webdriver.WebDriver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
let sequence: webdriver.ActionSequence = new webdriver.ActionSequence(driver);
let element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId');
element = new webdriver.WebElement(driver, promise);
// Click
sequence = sequence.click();
sequence = sequence.click(webdriver.Button.LEFT);
sequence = sequence.click(element);
sequence = sequence.click(element, webdriver.Button.LEFT);
// DoubleClick
sequence = sequence.doubleClick();
sequence = sequence.doubleClick(webdriver.Button.LEFT);
sequence = sequence.doubleClick(element);
sequence = sequence.doubleClick(element, webdriver.Button.LEFT);
// DragAndDrop
sequence = sequence.dragAndDrop(element, element);
sequence = sequence.dragAndDrop(element, { x: 1, y: 2 });
// KeyDown
sequence = sequence.keyDown(webdriver.Key.ADD);
// KeyUp
sequence = sequence.keyUp(webdriver.Key.ADD);
// MouseDown
sequence = sequence.mouseDown();
sequence = sequence.mouseDown(webdriver.Button.LEFT);
sequence = sequence.mouseDown(element);
sequence = sequence.mouseDown(element, webdriver.Button.LEFT);
// MouseMove
sequence = sequence.mouseMove(element);
sequence = sequence.mouseMove({ x: 1, y: 1 });
sequence = sequence.mouseMove(element, { x: 1, y: 2 });
// MouseUp
sequence = sequence.mouseUp();
sequence = sequence.mouseUp(webdriver.Button.LEFT);
sequence = sequence.mouseUp(element);
sequence = sequence.mouseUp(element, webdriver.Button.LEFT);
// SendKeys
sequence = sequence.sendKeys('A', 'B', 'C');
sequence = sequence.sendKeys('A', webdriver.Key.NULL);
sequence.perform().then(() => {});
}
function TestTouchSequence() {
let driver: webdriver.WebDriver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
let element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId');
let sequence: webdriver.TouchSequence = new webdriver.TouchSequence(driver);
sequence = sequence.tap(element);
sequence = sequence.doubleTap(element);
sequence = sequence.longPress(element);
sequence = sequence.tapAndHold({ x: 100, y: 100 });
sequence = sequence.move({ x: 100, y: 100 });
sequence = sequence.release({ x: 100, y: 100 });
sequence = sequence.scroll({ x: 100, y: 100 });
sequence = sequence.scrollFromElement(element, { x: 100, y: 100 });
sequence = sequence.flick({ xspeed: 100, yspeed: 100 });
sequence = sequence.flickElement(element, { x: 100, y: 100 }, 100);
sequence.perform().then(() => {});
}
function TestAlert() {
let driver: webdriver.WebDriver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
let alert: webdriver.Alert = driver.switchTo().alert();
alert.accept().then(() => {});
alert.dismiss().then(() => {});
alert.getText().then((text: string) => {});
alert.sendKeys('ABC').then(() => {});
}
function TestBrowser() {
let browser: string;
browser = webdriver.Browser.ANDROID;
browser = webdriver.Browser.CHROME;
browser = webdriver.Browser.FIREFOX;
browser = webdriver.Browser.HTMLUNIT;
browser = webdriver.Browser.INTERNET_EXPLORER;
browser = webdriver.Browser.IPAD;
browser = webdriver.Browser.IPHONE;
browser = webdriver.Browser.OPERA;
browser = webdriver.Browser.PHANTOM_JS;
browser = webdriver.Browser.SAFARI;
}
function TestButton() {
let button: string;
button = webdriver.Button.LEFT;
button = webdriver.Button.MIDDLE;
button = webdriver.Button.RIGHT;
}
function TestCapabilities() {
let capabilities: webdriver.Capabilities = new webdriver.Capabilities();
capabilities = new webdriver.Capabilities(webdriver.Capabilities.chrome());
let objCapabilities: any = {};
objCapabilities[webdriver.Capability.BROWSER_NAME] = webdriver.Browser.PHANTOM_JS;
capabilities = new webdriver.Capabilities(objCapabilities);
let anything: any = capabilities.get(webdriver.Capability.SECURE_SSL);
let check: boolean = capabilities.has(webdriver.Capability.SECURE_SSL);
capabilities = capabilities.merge(capabilities);
capabilities = capabilities.merge(objCapabilities);
capabilities = capabilities.set(webdriver.Capability.VERSION, { abc: 'def' });
capabilities = capabilities.set(webdriver.Capability.VERSION, null);
capabilities = capabilities.setLoggingPrefs(new webdriver.logging.Preferences());
capabilities = capabilities.setLoggingPrefs({ key: 'value' });
capabilities = capabilities.setProxy({ proxyType: 'Type' });
capabilities = capabilities.setEnableNativeEvents(true);
capabilities = capabilities.setScrollBehavior(1);
capabilities = capabilities.setAlertBehavior('accept');
anything = capabilities.toJSON();
capabilities = webdriver.Capabilities.android();
capabilities = webdriver.Capabilities.chrome();
capabilities = webdriver.Capabilities.firefox();
capabilities = webdriver.Capabilities.htmlunit();
capabilities = webdriver.Capabilities.htmlunitwithjs();
capabilities = webdriver.Capabilities.ie();
capabilities = webdriver.Capabilities.ipad();
capabilities = webdriver.Capabilities.iphone();
capabilities = webdriver.Capabilities.opera();
capabilities = webdriver.Capabilities.phantomjs();
capabilities = webdriver.Capabilities.safari();
}
function TestCapability() {
let capability: string;
capability = webdriver.Capability.ACCEPT_SSL_CERTS;
capability = webdriver.Capability.BROWSER_NAME;
capability = webdriver.Capability.ELEMENT_SCROLL_BEHAVIOR;
capability = webdriver.Capability.HANDLES_ALERTS;
capability = webdriver.Capability.LOGGING_PREFS;
capability = webdriver.Capability.NATIVE_EVENTS;
capability = webdriver.Capability.PLATFORM;
capability = webdriver.Capability.PROXY;
capability = webdriver.Capability.ROTATABLE;
capability = webdriver.Capability.SECURE_SSL;
capability = webdriver.Capability.SUPPORTS_APPLICATION_CACHE;
capability = webdriver.Capability.SUPPORTS_CSS_SELECTORS;
capability = webdriver.Capability.SUPPORTS_JAVASCRIPT;
capability = webdriver.Capability.SUPPORTS_LOCATION_CONTEXT;
capability = webdriver.Capability.TAKES_SCREENSHOT;
capability = webdriver.Capability.UNEXPECTED_ALERT_BEHAVIOR;
capability = webdriver.Capability.VERSION;
}
function TestCommand() {
let command: webdriver.Command = new webdriver.Command(webdriver.CommandName.ADD_COOKIE);
let name: string = command.getName();
let param: any = command.getParameter('param');
let params: any = command.getParameters();
command = command.setParameter('param', 123);
command = command.setParameters({ param: 123 });
}
function TestCommandName() {
let command: string;
command = webdriver.CommandName.ACCEPT_ALERT;
command = webdriver.CommandName.ADD_COOKIE;
command = webdriver.CommandName.CLEAR_APP_CACHE;
command = webdriver.CommandName.CLEAR_ELEMENT;
command = webdriver.CommandName.CLEAR_LOCAL_STORAGE;
command = webdriver.CommandName.CLEAR_SESSION_STORAGE;
command = webdriver.CommandName.CLICK;
command = webdriver.CommandName.CLICK_ELEMENT;
command = webdriver.CommandName.CLOSE;
command = webdriver.CommandName.DELETE_ALL_COOKIES;
command = webdriver.CommandName.DELETE_COOKIE;
command = webdriver.CommandName.DESCRIBE_SESSION;
command = webdriver.CommandName.DISMISS_ALERT;
command = webdriver.CommandName.DOUBLE_CLICK;
command = webdriver.CommandName.ELEMENT_EQUALS;
command = webdriver.CommandName.EXECUTE_ASYNC_SCRIPT;
command = webdriver.CommandName.EXECUTE_SCRIPT;
command = webdriver.CommandName.EXECUTE_SQL;
command = webdriver.CommandName.FIND_CHILD_ELEMENT;
command = webdriver.CommandName.FIND_CHILD_ELEMENTS;
command = webdriver.CommandName.FIND_ELEMENT;
command = webdriver.CommandName.FIND_ELEMENTS;
command = webdriver.CommandName.GET;
command = webdriver.CommandName.GET_ACTIVE_ELEMENT;
command = webdriver.CommandName.GET_ALERT_TEXT;
command = webdriver.CommandName.GET_ALL_COOKIES;
command = webdriver.CommandName.GET_APP_CACHE;
command = webdriver.CommandName.GET_APP_CACHE_STATUS;
command = webdriver.CommandName.GET_AVAILABLE_LOG_TYPES;
command = webdriver.CommandName.GET_COOKIE;
command = webdriver.CommandName.GET_CURRENT_URL;
command = webdriver.CommandName.GET_CURRENT_WINDOW_HANDLE;
command = webdriver.CommandName.GET_ELEMENT_ATTRIBUTE;
command = webdriver.CommandName.GET_ELEMENT_LOCATION;
command = webdriver.CommandName.GET_ELEMENT_LOCATION_IN_VIEW;
command = webdriver.CommandName.GET_ELEMENT_SIZE;
command = webdriver.CommandName.GET_ELEMENT_TAG_NAME;
command = webdriver.CommandName.GET_ELEMENT_TEXT;
command = webdriver.CommandName.GET_ELEMENT_VALUE_OF_CSS_PROPERTY;
command = webdriver.CommandName.GET_LOCAL_STORAGE_ITEM;
command = webdriver.CommandName.GET_LOCAL_STORAGE_KEYS;
command = webdriver.CommandName.GET_LOCAL_STORAGE_SIZE;
command = webdriver.CommandName.GET_LOCATION;
command = webdriver.CommandName.GET_LOG;
command = webdriver.CommandName.GET_PAGE_SOURCE;
command = webdriver.CommandName.GET_SCREEN_ORIENTATION;
command = webdriver.CommandName.GET_SERVER_STATUS;
command = webdriver.CommandName.GET_SESSION_LOGS;
command = webdriver.CommandName.GET_SESSION_STORAGE_ITEM;
command = webdriver.CommandName.GET_SESSION_STORAGE_KEYS;
command = webdriver.CommandName.GET_SESSION_STORAGE_SIZE;
command = webdriver.CommandName.GET_SESSIONS;
command = webdriver.CommandName.GET_TITLE;
command = webdriver.CommandName.GET_WINDOW_HANDLES;
command = webdriver.CommandName.GET_WINDOW_POSITION;
command = webdriver.CommandName.GET_WINDOW_SIZE;
command = webdriver.CommandName.GO_BACK;
command = webdriver.CommandName.GO_FORWARD;
command = webdriver.CommandName.IMPLICITLY_WAIT;
command = webdriver.CommandName.IS_BROWSER_ONLINE;
command = webdriver.CommandName.IS_ELEMENT_DISPLAYED;
command = webdriver.CommandName.IS_ELEMENT_ENABLED;
command = webdriver.CommandName.IS_ELEMENT_SELECTED;
command = webdriver.CommandName.MAXIMIZE_WINDOW;
command = webdriver.CommandName.MOUSE_DOWN;
command = webdriver.CommandName.MOUSE_UP;
command = webdriver.CommandName.MOVE_TO;
command = webdriver.CommandName.NEW_SESSION;
command = webdriver.CommandName.QUIT;
command = webdriver.CommandName.REFRESH;
command = webdriver.CommandName.REMOVE_LOCAL_STORAGE_ITEM;
command = webdriver.CommandName.REMOVE_SESSION_STORAGE_ITEM;
command = webdriver.CommandName.SCREENSHOT;
command = webdriver.CommandName.SEND_KEYS_TO_ACTIVE_ELEMENT;
command = webdriver.CommandName.SEND_KEYS_TO_ELEMENT;
command = webdriver.CommandName.SET_ALERT_TEXT;
command = webdriver.CommandName.SET_BROWSER_ONLINE;
command = webdriver.CommandName.SET_LOCAL_STORAGE_ITEM;
command = webdriver.CommandName.SET_LOCATION;
command = webdriver.CommandName.SET_SCREEN_ORIENTATION;
command = webdriver.CommandName.SET_SCRIPT_TIMEOUT;
command = webdriver.CommandName.SET_SESSION_STORAGE_ITEM;
command = webdriver.CommandName.SET_TIMEOUT;
command = webdriver.CommandName.SET_WINDOW_POSITION;
command = webdriver.CommandName.SET_WINDOW_SIZE;
command = webdriver.CommandName.SUBMIT_ELEMENT;
command = webdriver.CommandName.SWITCH_TO_FRAME;
command = webdriver.CommandName.SWITCH_TO_WINDOW;
command = webdriver.CommandName.TOUCH_DOUBLE_TAP;
command = webdriver.CommandName.TOUCH_DOWN;
command = webdriver.CommandName.TOUCH_FLICK;
command = webdriver.CommandName.TOUCH_LONG_PRESS;
command = webdriver.CommandName.TOUCH_MOVE;
command = webdriver.CommandName.TOUCH_SCROLL;
command = webdriver.CommandName.TOUCH_SINGLE_TAP;
command = webdriver.CommandName.TOUCH_UP;
}
function TestEventEmitter() {
let emitter: webdriver.EventEmitter = new webdriver.EventEmitter();
let callback = (a: number, b: number, c: number) => {};
emitter = emitter.addListener('ABC', callback);
emitter = emitter.addListener('ABC', callback, this);
emitter.emit('ABC', 1, 2, 3);
let listeners = emitter.listeners('ABC');
if (listeners[0].oneshot) {
listeners[0].fn.apply(listeners[0].scope);
}
let length: number = listeners.length;
let listenerInfo = listeners[0];
if (listenerInfo.oneshot) {
listenerInfo.fn.apply(listenerInfo.scope, [1, 2, 3]);
}
emitter = emitter.on('ABC', callback);
emitter = emitter.on('ABC', callback, this);
emitter = emitter.once('ABC', callback);
emitter = emitter.once('ABC', callback, this);
emitter = emitter.removeListener('ABC', callback);
emitter.removeAllListeners('ABC');
emitter.removeAllListeners();
}
function TestKey() {
let key: string;
key = webdriver.Key.ADD;
key = webdriver.Key.ALT;
key = webdriver.Key.ARROW_DOWN;
key = webdriver.Key.ARROW_LEFT;
key = webdriver.Key.ARROW_RIGHT;
key = webdriver.Key.ARROW_UP;
key = webdriver.Key.BACK_SPACE;
key = webdriver.Key.CANCEL;
key = webdriver.Key.CLEAR;
key = webdriver.Key.COMMAND;
key = webdriver.Key.CONTROL;
key = webdriver.Key.DECIMAL;
key = webdriver.Key.DELETE;
key = webdriver.Key.DIVIDE;
key = webdriver.Key.DOWN;
key = webdriver.Key.END;
key = webdriver.Key.ENTER;
key = webdriver.Key.EQUALS;
key = webdriver.Key.ESCAPE;
key = webdriver.Key.F1;
key = webdriver.Key.F2;
key = webdriver.Key.F3;
key = webdriver.Key.F4;
key = webdriver.Key.F5;
key = webdriver.Key.F6;
key = webdriver.Key.F7;
key = webdriver.Key.F8;
key = webdriver.Key.F9;
key = webdriver.Key.F10;
key = webdriver.Key.F11;
key = webdriver.Key.F12;
key = webdriver.Key.HELP;
key = webdriver.Key.HOME;
key = webdriver.Key.INSERT;
key = webdriver.Key.LEFT;
key = webdriver.Key.META;
key = webdriver.Key.MULTIPLY;
key = webdriver.Key.NULL;
key = webdriver.Key.NUMPAD0;
key = webdriver.Key.NUMPAD1;
key = webdriver.Key.NUMPAD2;
key = webdriver.Key.NUMPAD3;
key = webdriver.Key.NUMPAD4;
key = webdriver.Key.NUMPAD5;
key = webdriver.Key.NUMPAD6;
key = webdriver.Key.NUMPAD7;
key = webdriver.Key.NUMPAD8;
key = webdriver.Key.NUMPAD9;
key = webdriver.Key.PAGE_DOWN;
key = webdriver.Key.PAGE_UP;
key = webdriver.Key.PAUSE;
key = webdriver.Key.RETURN;
key = webdriver.Key.RIGHT;
key = webdriver.Key.SEMICOLON;
key = webdriver.Key.SEPARATOR;
key = webdriver.Key.SHIFT;
key = webdriver.Key.SPACE;
key = webdriver.Key.SUBTRACT;
key = webdriver.Key.TAB;
key = webdriver.Key.UP;
}
function TestBy() {
let driver: webdriver.WebDriver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
let locator: webdriver.By = new webdriver.By('class name', 'class');
let str: string = locator.toString();
locator = webdriver.By.className('class');
locator = webdriver.By.css('css');
locator = webdriver.By.id('id');
locator = webdriver.By.linkText('link');
locator = webdriver.By.name('name');
locator = webdriver.By.partialLinkText('text');
locator = webdriver.By.tagName('tag');
locator = webdriver.By.xpath('xpath');
// Can import 'By' without import declarations
let By = webdriver.By;
let locatorHash: webdriver.ByHash;
locatorHash = { className: 'class' };
locatorHash = { css: 'css' };
locatorHash = { id: 'id' };
locatorHash = { linkText: 'link' };
locatorHash = { name: 'name' };
locatorHash = { partialLinkText: 'text' };
locatorHash = { tagName: 'tag' };
locatorHash = { xpath: 'xpath' };
webdriver.By.js('script', 1, 2, 3)(driver).then((abc: number) => {});
}
function TestSession() {
let session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android());
let capabilitiesObj: any = {};
capabilitiesObj[webdriver.Capability.BROWSER_NAME] = webdriver.Browser.ANDROID;
capabilitiesObj[webdriver.Capability.PLATFORM] = 'ANDROID';
session = new webdriver.Session('ABC', capabilitiesObj);
let capabilities: webdriver.Capabilities = session.getCapabilities();
let capability: any = session.getCapability(webdriver.Capability.BROWSER_NAME);
let id: string = session.getId();
let data: string = session.toJSON();
}
function TestWebDriverFileDetector() {
let driver: webdriver.WebDriver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
let fileDetector: webdriver.FileDetector = new webdriver.FileDetector();
fileDetector.handleFile(driver, 'path/to/file').then((path: string) => {});
}
function TestWebDriverLogs() {
let driver: webdriver.WebDriver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
let logs: webdriver.Logs = new webdriver.Logs(driver);
logs.get(webdriver.logging.Type.BROWSER).then((entries: webdriver.logging.Entry[]) => {});
logs.getAvailableLogTypes().then((types: string[]) => {});
}
function TestWebDriverNavigation() {
let driver: webdriver.WebDriver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
let navigation: webdriver.Navigation = new webdriver.Navigation(driver);
navigation.back().then(() => {});
navigation.forward().then(() => {});
navigation.refresh().then(() => {});
navigation.to('http://google.com').then(() => {});
}
function TestWebDriverOptions() {
let driver: webdriver.WebDriver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
let options: webdriver.Options = new webdriver.Options(driver);
let promise: webdriver.promise.Promise<void>;
let name: string = 'name';
let value: string = 'value';
let path: string = 'path';
let domain: string = 'domain';
let secure: boolean = true;
let httpOnly: boolean = true;
// Add Cookie
promise = options.addCookie({ name, value });
promise = options.addCookie({ name, value, path });
promise = options.addCookie({ name, value, path, domain });
promise = options.addCookie({ name, value, path, domain, secure });
promise = options.addCookie({ name, value, path, domain, secure, httpOnly });
promise = options.addCookie({ name, value, path, domain, secure, httpOnly, expiry: 123 });
promise = options.addCookie({ name, value, path, domain, secure, httpOnly, expiry: Date.now() });
promise = options.deleteAllCookies();
promise = options.deleteCookie('name');
options.getCookie('name').then((cookie: webdriver.IWebDriverCookie) => {
let expiry: number | undefined = cookie.expiry;
});
options.getCookies().then((cookies: webdriver.IWebDriverCookie[]) => { });
let logs: webdriver.Logs = options.logs();
let timeouts: webdriver.Timeouts = options.timeouts();
let window: webdriver.Window = options.window();
}
function TestWebDriverTargetLocator() {
let driver: webdriver.WebDriver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
let locator: webdriver.TargetLocator = new webdriver.TargetLocator(driver);
let promise: webdriver.promise.Promise<void>;
let element: webdriver.WebElement = locator.activeElement();
let alert: webdriver.Alert = locator.alert();
promise = locator.defaultContent();
promise = locator.frame(1);
promise = locator.window('nameOrHandle');
}
function TestWebDriverTimeouts() {
let driver: webdriver.WebDriver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
let timeouts: webdriver.Timeouts = new webdriver.Timeouts(driver);
let promise: webdriver.promise.Promise<void>;
promise = timeouts.implicitlyWait(123);
promise = timeouts.pageLoadTimeout(123);
promise = timeouts.setScriptTimeout(123);
}
function TestWebDriverWindow() {
let driver: webdriver.WebDriver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
let window: webdriver.Window = new webdriver.Window(driver);
let locationPromise: webdriver.promise.Promise<webdriver.ILocation>;
let sizePromise: webdriver.promise.Promise<webdriver.ISize>;
let voidPromise: webdriver.promise.Promise<void>;
locationPromise = window.getPosition();
sizePromise = window.getSize();
voidPromise = window.maximize();
voidPromise = window.setPosition(12, 34);
voidPromise = window.setSize(12, 34);
}
declare const sessionPromise: webdriver.promise.Promise<webdriver.Session>;
declare let booleanPromise: webdriver.promise.Promise<boolean>;
declare const booleanCondition: webdriver.Condition<boolean>;
declare const webElementCondition: webdriver.WebElementCondition;
function TestWebDriver() {
let session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android());
let httpClient: http.HttpClient = new http.HttpClient('http://someserver');
let executor: http.Executor = new http.Executor(httpClient);
let flow: webdriver.promise.ControlFlow = new webdriver.promise.ControlFlow();
let driver: webdriver.WebDriver = new webdriver.WebDriver(session, executor);
driver = new webdriver.WebDriver(session, executor, flow);
driver = new webdriver.WebDriver(sessionPromise, executor);
driver = new webdriver.WebDriver(sessionPromise, executor, flow);
let voidPromise: webdriver.promise.Promise<void>;
let stringPromise: webdriver.promise.Promise<string>;
let webElementPromise: webdriver.WebElementPromise;
let actions: webdriver.ActionSequence = driver.actions();
let touchActions: webdriver.TouchSequence = driver.touchActions();
// call
stringPromise = driver.call<string>(() => 'value');
stringPromise = driver.call<string>(() => stringPromise);
stringPromise = driver.call<string>(() => 'value', driver);
stringPromise = driver.call<string>((a: number) => 'value', driver, 1);
voidPromise = driver.close();
flow = driver.controlFlow();
// executeAsyncScript
stringPromise = driver.executeAsyncScript<string>('function(){}');
stringPromise = driver.executeAsyncScript<string>('function(){}', 1, 2, 3);
stringPromise = driver.executeAsyncScript<string>(() => {});
stringPromise = driver.executeAsyncScript<string>((a: number) => {}, 1);
// executeScript
stringPromise = driver.executeScript<string>('function(){}');
stringPromise = driver.executeScript<string>('function(){}', 1, 2, 3);
stringPromise = driver.executeScript<string>(() => {});
stringPromise = driver.executeScript<string>((a: number) => {}, 1);
// findElement
let element: webdriver.WebElement;
element = driver.findElement(webdriver.By.id('ABC'));
element = driver.findElement(webdriver.By.js('function(){}'));
// findElements
driver.findElements(webdriver.By.className('ABC')).then((elements: webdriver.WebElement[]) => {});
driver.findElements(webdriver.By.js('function(){}')).then((elements: webdriver.WebElement[]) => {});
voidPromise = driver.get('http://www.google.com');
driver.getAllWindowHandles().then((handles: string[]) => {});
driver.getCapabilities().then((caps: webdriver.Capabilities) => {});
stringPromise = driver.getCurrentUrl();
stringPromise = driver.getPageSource();
driver.getSession().then((session: webdriver.Session) => {});
stringPromise = driver.getTitle();
stringPromise = driver.getWindowHandle();
let options: webdriver.Options = driver.manage();
let navigation: webdriver.Navigation = driver.navigate();
let locator: webdriver.TargetLocator = driver.switchTo();
let fileDetector: webdriver.FileDetector = new webdriver.FileDetector();
driver.setFileDetector(fileDetector);
voidPromise = driver.quit();
voidPromise = driver.schedule<void>(new webdriver.Command(webdriver.CommandName.CLICK), 'ABC');
voidPromise = driver.sleep(123);
stringPromise = driver.takeScreenshot();
booleanPromise = driver.wait(booleanPromise);
booleanPromise = driver.wait(booleanCondition);
booleanPromise = driver.wait((driver: webdriver.WebDriver) => true);
booleanPromise = driver.wait((driver: webdriver.WebDriver) => Promise.resolve(true));
booleanPromise = driver.wait((driver: webdriver.WebDriver) => webdriver.promise.Promise.resolve(true));
booleanPromise = driver.wait(booleanPromise, 123);
booleanPromise = driver.wait(booleanPromise, 123, 'Message');
webElementPromise = driver.wait(webElementCondition);
voidPromise = driver.wait(webElementCondition).click();
driver = webdriver.WebDriver.attachToSession(executor, 'ABC');
driver = webdriver.WebDriver.createSession(executor, webdriver.Capabilities.android());
}
declare const serializable: webdriver.Serializable<string>;
function TestSerializable() {
let serial: string | webdriver.promise.IThenable<string> = serializable.serialize();
}
function TestWebElement() {
let driver: webdriver.WebDriver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
let element: webdriver.WebElement;
element = new webdriver.WebElement(driver, 'elementId');
element = new webdriver.WebElement(driver, promise);
let voidPromise: webdriver.promise.Promise<void>;
let stringPromise: webdriver.promise.Promise<string>;
let booleanPromise: webdriver.promise.Promise<boolean>;
voidPromise = element.clear();
voidPromise = element.click();
element = element.findElement(webdriver.By.id('ABC'));
element = element.findElement({id: 'ABC'});
element.findElements({className: 'ABC'}).then((elements: webdriver.WebElement[]) => { });
stringPromise = element.getAttribute('class');
stringPromise = element.getCssValue('display');
driver = element.getDriver();
element.getLocation().then((location: webdriver.ILocation) => {});
element.getSize().then((size: webdriver.ISize) => {});
stringPromise = element.getTagName();
stringPromise = element.getText();
booleanPromise = element.isDisplayed();
booleanPromise = element.isEnabled();
booleanPromise = element.isSelected();
voidPromise = element.sendKeys('A', 'B', 'C');
voidPromise = element.sendKeys(1, 2, 3);
voidPromise = element.sendKeys(webdriver.Key.BACK_SPACE);
voidPromise = element.sendKeys(stringPromise, stringPromise, stringPromise);
voidPromise = element.sendKeys('A', 1, webdriver.Key.BACK_SPACE, stringPromise);
voidPromise = element.submit();
element.getId().then((id: string) => {});
element.serialize().then((id: webdriver.IWebElementId) => {});
booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, 'elementId'));
}
function TestWebElementPromise() {
let driver: webdriver.WebDriver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
let elementPromise: webdriver.WebElementPromise = driver.findElement(webdriver.By.id('id'));
elementPromise.then();
elementPromise.then((element: webdriver.WebElement) => {});
elementPromise.then((element: webdriver.WebElement) => {}, (error: any) => {});
elementPromise.then((element: webdriver.WebElement) => 'foo', (error: any) => 'bar').then((result: string) => {});
}
function TestLogging() {
let preferences: webdriver.logging.Preferences = new webdriver.logging.Preferences();
preferences.setLevel(webdriver.logging.Type.BROWSER, webdriver.logging.Level.ALL);
let prefs: any = preferences.toJSON();
let level: webdriver.logging.Level = webdriver.logging.getLevel('OFF');
level = webdriver.logging.getLevel(1);
level = webdriver.logging.Level.ALL;
level = webdriver.logging.Level.DEBUG;
level = webdriver.logging.Level.INFO;
level = webdriver.logging.Level.OFF;
level = webdriver.logging.Level.SEVERE;
level = webdriver.logging.Level.WARNING;
let name: string = level.name;
let value: number = level.value;
let type: string;
type = webdriver.logging.Type.BROWSER;
type = webdriver.logging.Type.CLIENT;
type = webdriver.logging.Type.DRIVER;
type = webdriver.logging.Type.PERFORMANCE;
type = webdriver.logging.Type.SERVER;
let logger: webdriver.logging.Logger = webdriver.logging.getLogger();
webdriver.logging.addConsoleHandler();
webdriver.logging.addConsoleHandler(logger);
webdriver.logging.removeConsoleHandler();
webdriver.logging.removeConsoleHandler(logger);
}
function TestLoggingEntry() {
let entry: webdriver.logging.Entry;
entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC');
entry = new webdriver.logging.Entry('ALL', 'ABC');
entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC', 123);
entry = new webdriver.logging.Entry('ALL', 'ABC', 123);
entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC', 123, webdriver.logging.Type.BROWSER);
entry = new webdriver.logging.Entry('ALL', 'ABC', 123, webdriver.logging.Type.BROWSER);
let entryObj: any = entry.toJSON();
let message: string = entry.message;
let timestamp: number = entry.timestamp;
let type: string = entry.type;
}
declare let stringPromise: webdriver.promise.Promise<string>;
function TestPromiseModule() {
let cancellationError: webdriver.promise.CancellationError = new webdriver.promise.CancellationError();
cancellationError = new webdriver.promise.CancellationError('message');
let str: string = cancellationError.message;
str = cancellationError.name;
let numberPromise: webdriver.promise.Promise<number>;
let booleanPromise: webdriver.promise.Promise<boolean>;
let voidPromise: webdriver.promise.Promise<void>;
webdriver.promise.all([stringPromise]).then((values: string[]) => {});
webdriver.promise.asap('abc', (value: any) => true);
webdriver.promise.asap('abc', (value: any) => {}, (err: any) => 'ABC');
stringPromise = webdriver.promise.checkedNodeCall<string>((err: any, value: any) => 'abc');
webdriver.promise.consume(() => {
return 5;
}).then((value: number) => {});
webdriver.promise.consume(() => {
return 5;
}, this).then((value: number) => {});
webdriver.promise.consume((a: number, b: number, c: number) => 5, this, 1, 2, 3)
.then((value: number) => {});
let numbersPromise: webdriver.promise.Promise<number[]> = webdriver.promise.filter([1, 2, 3], (element: number, type: any, index: number, arr: number[]) => {
return true;
});
numbersPromise = webdriver.promise.filter([1, 2, 3], (element: number, type: any, index: number, arr: number[]) => {
return true;
}, this);
numbersPromise = webdriver.promise.filter(numbersPromise, (element: number, type: any, index: number, arr: number[]) => {
return true;
});
numbersPromise = webdriver.promise.filter(numbersPromise, (element: number, type: any, index: number, arr: number[]) => {
return true;
}, this);
numbersPromise = webdriver.promise.map([1, 2, 3], (el: number, type: any, index: number, arr: number[]) => {
return true;
});
numbersPromise = webdriver.promise.map([1, 2, 3], (el: number, type: any, index: number, arr: number[]) => {
return true;
}, this);
numbersPromise = webdriver.promise.map(numbersPromise, (el: number, type: any, index: number, arr: number[]) => {
return true;
});
numbersPromise = webdriver.promise.map(numbersPromise, (el: number, type: any, index: number, arr: number[]) => {
return true;
}, this);
let flow: webdriver.promise.ControlFlow = webdriver.promise.controlFlow();
stringPromise = webdriver.promise.createFlow<string>((newFlow: webdriver.promise.ControlFlow) => 'ABC');
let deferred: webdriver.promise.Deferred<string>;
deferred = webdriver.promise.defer<string>();
deferred = webdriver.promise.defer<string>();
stringPromise = deferred.promise;
deferred.fulfill('ABC');
deferred.reject('error');
voidPromise = webdriver.promise.delayed(123);
voidPromise = webdriver.promise.fulfilled<void>();
stringPromise = webdriver.promise.fulfilled('abc');
stringPromise = webdriver.promise.fullyResolved<string>('abc');
let bool: boolean = webdriver.promise.isGenerator(() => {});
let isPromise: boolean = webdriver.promise.isPromise('ABC');
stringPromise = webdriver.promise.rejected<string>('{a: 123}');
webdriver.promise.setDefaultFlow(new webdriver.promise.ControlFlow());
numberPromise = webdriver.promise.when('abc', (value: any) => 123, (err: Error) => 123);
}
function TestUntilModule() {
let driver: webdriver.WebDriver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).
build();
let conditionB: webdriver.Condition<boolean> = new webdriver.Condition<boolean>('message', (driver: webdriver.WebDriver) => true);
let conditionBBase: webdriver.Condition<boolean> = conditionB;
let conditionWebElement: webdriver.WebElementCondition;
let conditionWebElements: webdriver.Condition<webdriver.WebElement[]>;
conditionB = webdriver.until.ableToSwitchToFrame(5);
let conditionAlert: webdriver.Condition<webdriver.Alert> = webdriver.until.alertIsPresent();
let el: webdriver.WebElement = driver.findElement(webdriver.By.id('id'));
conditionB = webdriver.until.stalenessOf(el);
conditionB = webdriver.until.titleContains('text');
conditionB = webdriver.until.titleIs('text');
conditionB = webdriver.until.titleMatches(/text/);
conditionB = webdriver.until.urlContains('text');
conditionB = webdriver.until.urlIs('text');
conditionB = webdriver.until.urlMatches(/text/);
conditionWebElement = webdriver.until.elementIsDisabled(el);
conditionWebElement = webdriver.until.elementIsEnabled(el);
conditionWebElement = webdriver.until.elementIsNotSelected(el);
conditionWebElement = webdriver.until.elementIsNotVisible(el);
conditionWebElement = webdriver.until.elementIsSelected(el);
conditionWebElement = webdriver.until.elementIsVisible(el);
conditionWebElement = webdriver.until.elementLocated(webdriver.By.id('id'));
conditionWebElement = webdriver.until.elementTextContains(el, 'text');
conditionWebElement = webdriver.until.elementTextIs(el, 'text');
conditionWebElement = webdriver.until.elementTextMatches(el, /text/);
conditionWebElements = webdriver.until.elementsLocated(webdriver.By.className('class'));
}
function TestControlFlow() {
let flow: webdriver.promise.ControlFlow;
flow = new webdriver.promise.ControlFlow();
let emitter: webdriver.EventEmitter = flow;
let eventType: string;
eventType = webdriver.promise.ControlFlow.EventType.IDLE;
eventType = webdriver.promise.ControlFlow.EventType.RESET;
eventType = webdriver.promise.ControlFlow.EventType.SCHEDULE_TASK;
eventType = webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION;
let stringPromise: webdriver.promise.Promise<string>;
stringPromise = flow.execute(() => 'value');
stringPromise = flow.execute(() => stringPromise);
stringPromise = flow.execute(() => stringPromise, 'Description');
let schedule: string;
schedule = flow.toString();
schedule = flow.getSchedule();
schedule = flow.getSchedule(true);
flow.reset();
let voidPromise: webdriver.promise.Promise<void> = flow.timeout(123);
voidPromise = flow.timeout(123, 'Description');
stringPromise = flow.wait(stringPromise);
voidPromise = flow.wait<void>(() => true);
voidPromise = flow.wait<void>(() => true, 123);
voidPromise = flow.wait<void>(() => stringPromise, 123, 'Timeout Message');
}
function TestDeferred() {
let deferred: webdriver.promise.Deferred<string>;
deferred = new webdriver.promise.Deferred<string>();
deferred = new webdriver.promise.Deferred<string>(new webdriver.promise.ControlFlow());
let promise: webdriver.promise.Promise<string> = deferred.promise;
deferred.errback(new Error('Error'));
deferred.errback('Error');
deferred.fulfill('abc');
deferred.reject(new Error('Error'));
deferred.reject('Error');
deferred.removeAll();
}
declare const controlFlow: webdriver.promise.ControlFlow;
function TestPromiseClass() {
let promise: webdriver.promise.Promise<string>;
promise = new webdriver.promise.Promise<string>((resolve, reject) => {
resolve("");
resolve(Promise.resolve(""));
reject(new Error());
}, controlFlow);
promise = promise.then<string>();
promise = promise.then((a: string) => 'cde');
// tslint:disable-next-line void-return (need `--strictNullChecks` to change `void` to `undefined`)
const promiseOrVoid: webdriver.promise.Promise<string | void> = promise.then((a: string) => 'cde', (e: any) => {});
const promiseOrNumber: webdriver.promise.Promise<string | number> = promise.then((a: string) => 'cde', (e: any) => 123);
}
function TestThenableClass() {
// TODO: this doesn't test the Thenable class, it uses a Promise!
let thenable: webdriver.promise.Promise<string> = new webdriver.promise.Promise<string>((resolve, reject) => {
resolve('a');
});
thenable = thenable.then((a: string) => 'cde');
// tslint:disable-next-line void-return (need `--strictNullChecks` to change `void` to `undefined`)
const thenableOrVoid: webdriver.promise.Promise<string | void> = thenable.then((a: string) => 'cde', (e: any) => {});
const thenableOrNumber: webdriver.promise.Promise<string | number> = thenable.then((a: string) => 'cde', (e: any) => 123);
}
async function TestAsyncAwaitable() {
let thenable: webdriver.promise.Promise<string> = new webdriver.promise.Promise<string>((resolve, reject) => resolve('foo'));
let str: string = await thenable;
}
function TestPromiseManagerFlag() {
webdriver.promise.USE_PROMISE_MANAGER = false;
} | the_stack |
import { module, test } from 'qunit';
import { setupApplicationTest } from 'ember-qunit';
import { MirageTestContext, setupMirage } from 'ember-cli-mirage/test-support';
import { click, visit, currentURL, waitFor } from '@ember/test-helpers';
import WorkflowPersistence from '@cardstack/web-client/services/workflow-persistence';
import Layer2TestWeb3Strategy from '@cardstack/web-client/utils/web3-strategies/test-layer2';
import { buildState } from '@cardstack/web-client/models/workflow/workflow-session';
import { setupHubAuthenticationToken } from '../helpers/setup';
import {
MILESTONE_TITLES,
WORKFLOW_VERSION,
} from '@cardstack/web-client/components/card-space/create-space-workflow';
interface Context extends MirageTestContext {}
function milestoneCompletedSel(milestoneIndex: number): string {
return `[data-test-milestone-completed][data-test-milestone="${milestoneIndex}"]`;
}
module('Acceptance | create card space persistence', function (hooks) {
setupApplicationTest(hooks);
setupMirage(hooks);
setupHubAuthenticationToken(hooks);
let workflowPersistenceService: WorkflowPersistence;
let layer2AccountAddress = '0x182619c6Ea074C053eF3f1e1eF81Ec8De6Eb6E44';
hooks.beforeEach(async function () {
let layer2Service = this.owner.lookup('service:layer2-network')
.strategy as Layer2TestWeb3Strategy;
await layer2Service.test__simulateAccountsChanged([layer2AccountAddress]);
layer2Service.authenticate();
layer2Service.test__simulateHubAuthentication('abc123--def456--ghi789');
workflowPersistenceService = this.owner.lookup(
'service:workflow-persistence'
);
workflowPersistenceService.clear();
});
test('Generates a flow uuid query parameter used as a persistence identifier and can be dismissed via the header button', async function (this: Context, assert) {
await visit('/card-space');
await click('[data-test-workflow-button="create-space"]');
assert.equal(
// @ts-ignore (complains object is possibly null)
new URL('http://domain.test/' + currentURL()).searchParams.get('flow-id')
.length,
22
);
await click('[data-test-return-to-dashboard]');
assert.dom('[data-test-workflow-thread]').doesNotExist();
});
module('Restoring from a previously saved state', function () {
test('it restores an unfinished workflow', async function (this: Context, assert) {
let state = buildState({
meta: {
version: WORKFLOW_VERSION,
completedCardNames: ['LAYER2_CONNECT', 'CARD_SPACE_USERNAME'],
},
});
workflowPersistenceService.persistData('abc123', {
name: 'CARD_SPACE_CREATION',
state,
});
await visit('/card-space?flow=create-space&flow-id=abc123');
assert.dom(milestoneCompletedSel(0)).exists(); // L2 connect
assert.dom(milestoneCompletedSel(1)).exists(); // Username
assert.dom(milestoneCompletedSel(2)).doesNotExist();
assert.dom('[data-test-milestone="2"][data-test-postable="2"]').exists();
assert.dom('[data-test-card-space-details-start-button]').isNotDisabled();
});
test('it restores a finished workflow', async function (this: Context, assert) {
let state = buildState({
meta: {
version: WORKFLOW_VERSION,
completedCardNames: [
'LAYER2_CONNECT',
'CARD_SPACE_USERNAME',
'CARD_SPACE_DETAILS',
'CARD_SPACE_CONFIRM',
],
},
});
workflowPersistenceService.persistData('abc123', {
name: 'CARD_SPACE_CREATION',
state,
});
await visit('/card-space?flow=create-space&flow-id=abc123');
assert.dom(milestoneCompletedSel(0)).exists(); // L2 connect
assert.dom(milestoneCompletedSel(1)).exists(); // Username
assert.dom(milestoneCompletedSel(2)).exists(); // Details
assert.dom(milestoneCompletedSel(3)).exists(); // Confirm
assert
.dom('[data-test-epilogue][data-test-postable="1"]')
.includesText(`Congrats, you have created your Card Space!`);
});
test('it restores a cancelled workflow', async function (this: Context, assert) {
const state = buildState({
meta: {
version: WORKFLOW_VERSION,
completedCardNames: ['LAYER2_CONNECT', 'CARD_SPACE_USERNAME'],
isCanceled: true,
cancelationReason: 'L2_DISCONNECTED',
},
});
workflowPersistenceService.persistData('abc123', {
name: 'CARD_SPACE_CREATION',
state,
});
await visit('/card-space?flow=create-space&flow-id=abc123');
assert.dom(milestoneCompletedSel(0)).exists(); // L2 connect
assert.dom(milestoneCompletedSel(1)).exists(); // Username
assert.dom(milestoneCompletedSel(2)).doesNotExist();
assert
.dom('[data-test-cancelation]')
.includesText(
'It looks like your L2 test chain wallet got disconnected. If you still want to create a Card Space, please start again by connecting your wallet.'
);
await waitFor(
'[data-test-workflow-default-cancelation-restart="create-space"]'
);
assert
.dom('[data-test-workflow-default-cancelation-restart="create-space"]')
.exists();
});
test('it cancels a persisted flow when trying to restore while unauthenticated', async function (this: Context, assert) {
const state = buildState({
meta: {
version: WORKFLOW_VERSION,
completedCardNames: ['LAYER2_CONNECT', 'CARD_SPACE_USERNAME'],
},
});
workflowPersistenceService.persistData('abc123', {
name: 'CARD_SPACE_CREATION',
state,
});
window.TEST__AUTH_TOKEN = undefined;
await visit('/card-space?flow=create-space&flow-id=abc123');
assert.dom(milestoneCompletedSel(0)).doesNotExist(); // L2 connect
assert.dom(milestoneCompletedSel(1)).doesNotExist(); // Username
assert
.dom('[data-test-cancelation]')
.includesText(
'You attempted to restore an unfinished workflow, but you are no longer authenticated. Please restart the workflow.'
);
await click('[data-test-workflow-default-cancelation-restart]');
assert.dom(milestoneCompletedSel(0)).exists(); // L2 connect
assert.dom(milestoneCompletedSel(1)).doesNotExist(); // Username
assert.dom(`[data-test-authentication-button]`).exists();
const workflowPersistenceId = new URL(
'http://domain.test/' + currentURL()
).searchParams.get('flow-id');
assert.notEqual(workflowPersistenceId!, 'abc123'); // flow-id param should be regenerated
assert.equal(workflowPersistenceId!.length, 22);
});
test('it should reset the persisted card names when editing one of the previous steps', async function (this: Context, assert) {
const state = buildState({
meta: {
version: WORKFLOW_VERSION,
completedCardNames: ['LAYER2_CONNECT', 'CARD_SPACE_USERNAME'],
},
});
workflowPersistenceService.persistData('abc123', {
name: 'CARD_SPACE_CREATION',
state,
});
await visit('/card-space?flow=create-space&flow-id=abc123');
assert.dom(milestoneCompletedSel(0)).exists(); // L2 connect
assert.dom(milestoneCompletedSel(1)).exists(); // Username
await waitFor('[data-test-milestone="1"] [data-test-boxel-button]');
await click('[data-test-milestone="1"] [data-test-boxel-button]');
await visit('/card-space?flow=create-space&flow-id=abc123');
assert.dom(milestoneCompletedSel(0)).exists(); // L2 connect
assert.dom(milestoneCompletedSel(1)).doesNotExist(); // Username
});
test('it cancels a persisted flow when card wallet address is different', async function (this: Context, assert) {
const state = buildState({
meta: {
version: WORKFLOW_VERSION,
completedCardNames: ['LAYER2_CONNECT', 'CARD_SPACE_USERNAME'],
},
layer2WalletAddress: '0xaaaaaaaaaaaaaaa', // Differs from layer2AccountAddress set in beforeEach
});
workflowPersistenceService.persistData('abc123', {
name: 'CARD_SPACE_CREATION',
state,
});
await visit('/card-space?flow=create-space&flow-id=abc123');
assert.dom(milestoneCompletedSel(0)).doesNotExist();
assert.dom(milestoneCompletedSel(1)).doesNotExist();
assert
.dom('[data-test-cancelation]')
.includesText(
'You attempted to restore an unfinished workflow, but you changed your Card Wallet address. Please restart the workflow.'
);
});
test('it allows interactivity after restoring previously saved state', async function (this: Context, assert) {
const state = buildState({
meta: {
version: WORKFLOW_VERSION,
completedCardNames: ['LAYER2_CONNECT'],
},
});
workflowPersistenceService.persistData('abc123', {
name: 'CARD_SPACE_CREATION',
state,
});
await visit('/card-space?flow=create-space&flow-id=abc123');
assert.dom(milestoneCompletedSel(0)).exists();
assert.dom(milestoneCompletedSel(1)).doesNotExist();
await waitFor('[data-test-postable="1"][data-test-milestone="1"]');
assert.dom('[data-test-card-space-username-save-button]').isEnabled();
await click('[data-test-card-space-username-save-button]');
assert.dom(milestoneCompletedSel(1)).exists();
});
test('it cancels a persisted flow when state version is old', async function (this: Context, assert) {
const state = buildState({
meta: {
version: WORKFLOW_VERSION - 1,
completedMilestonesCount: 0,
milestonesCount: MILESTONE_TITLES.length,
completedCardNames: ['LAYER2_CONNECT', 'CARD_SPACE_USERNAME'],
},
layer2WalletAddress: '0xaaaaaaaaaaaaaaa', // Differs from layer2AccountAddress set in beforeEach
});
workflowPersistenceService.persistData('abc123', {
name: 'CARD_SPACE_CREATION',
state,
});
await visit('/card-space?flow=create-space&flow-id=abc123');
assert.dom(milestoneCompletedSel(0)).doesNotExist();
assert.dom(milestoneCompletedSel(1)).doesNotExist();
assert
.dom('[data-test-cancelation]')
.includesText(
'You attempted to restore an unfinished workflow, but the workflow has been upgraded by the Cardstack development team since then, so you will need to start again. Sorry about that!'
);
});
});
}); | the_stack |
import React, { forwardRef, useEffect, useCallback, useRef, useState } from 'react';
import { ReactCompareSliderHandle } from './ReactCompareSliderHandle';
import { ReactCompareSliderCommonProps, ReactCompareSliderPropPosition } from './types';
import {
useEventListener,
usePrevious,
UseResizeObserverHandlerParams,
useResizeObserver,
} from './utils';
/** Container for clipped item. */
const ThisClipContainer = forwardRef<HTMLDivElement, React.HTMLProps<HTMLDivElement>>(
(props, ref): React.ReactElement => {
const style: React.CSSProperties = {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
willChange: 'clip',
userSelect: 'none',
KhtmlUserSelect: 'none',
MozUserSelect: 'none',
WebkitUserSelect: 'none',
};
return <div {...props} style={style} data-rcs="clip-item" ref={ref} />;
}
);
ThisClipContainer.displayName = 'ThisClipContainer';
/** Handle container to control position. */
const ThisHandleContainer = forwardRef<
HTMLDivElement,
React.HTMLProps<HTMLDivElement> & Pick<ReactCompareSliderCommonProps, 'portrait'>
>(
({ children, portrait }, ref): React.ReactElement => {
const style: React.CSSProperties = {
position: 'absolute',
top: 0,
width: '100%',
height: '100%',
pointerEvents: 'none',
};
const innerStyle: React.CSSProperties = {
position: 'absolute',
width: portrait ? '100%' : undefined,
height: portrait ? undefined : '100%',
transform: portrait ? 'translateY(-50%)' : 'translateX(-50%)',
pointerEvents: 'all',
};
return (
<div style={style} data-rcs="handle-container" ref={ref}>
<div style={innerStyle}>{children}</div>
</div>
);
}
);
ThisHandleContainer.displayName = 'ThisHandleContainer';
/** Comparison slider properties. */
export interface ReactCompareSliderProps extends Partial<ReactCompareSliderCommonProps> {
/** Padding to limit the slideable bounds in pixels on the X-axis (landscape) or Y-axis (portrait). */
boundsPadding?: number;
/** Whether the slider should follow the pointer on hover. */
changePositionOnHover?: boolean;
/** Custom handle component. */
handle?: React.ReactNode;
/** First item to show. */
itemOne: React.ReactNode;
/** Second item to show. */
itemTwo: React.ReactNode;
/** Whether to only change position when handle is interacted with (useful for touch devices). */
onlyHandleDraggable?: boolean;
/** Callback on position change with position as percentage. */
onPositionChange?: (position: ReactCompareSliderPropPosition) => void;
}
/** Properties for internal `updateInternalPosition` callback. */
interface UpdateInternalPositionProps
extends Required<Pick<ReactCompareSliderProps, 'boundsPadding' | 'portrait'>> {
/** X coordinate to update to (landscape). */
x: number;
/** Y coordinate to update to (portrait). */
y: number;
/** Whether to calculate using page X and Y offsets (required for pointer events). */
isOffset?: boolean;
}
const EVENT_PASSIVE_PARAMS = { passive: true };
const EVENT_CAPTURE_PARAMS = { capture: true, passive: false };
/** Root Comparison slider. */
export const ReactCompareSlider: React.FC<
ReactCompareSliderProps & React.HtmlHTMLAttributes<HTMLDivElement>
> = ({
handle,
itemOne,
itemTwo,
onlyHandleDraggable = false,
onPositionChange,
portrait = false,
position = 50,
boundsPadding = 0,
changePositionOnHover = false,
style,
...props
}): React.ReactElement => {
/** DOM node of the root element. */
const rootContainerRef = useRef<HTMLDivElement>(null);
/** DOM node of the item that is clipped. */
const clipContainerRef = useRef<HTMLDivElement>(null);
/** DOM node of the handle container. */
const handleContainerRef = useRef<HTMLDivElement>(null);
/** Current position as a percentage value (initially negative to sync bounds on mount). */
const internalPositionPc = useRef(position);
/** Previous `position` prop value. */
const prevPropPosition = usePrevious(position);
/** Whether user is currently dragging. */
const [isDragging, setIsDragging] = useState(false);
/** Whether component has a `window` event binding. */
const hasWindowBinding = useRef(false);
/** Target container for pointer events. */
const [interactiveTarget, setInteractiveTarget] = useState<HTMLDivElement | null>();
/** Whether the bounds of the container element have been synchronised. */
const [didSyncBounds, setDidSyncBounds] = useState(false);
// Set target container for pointer events.
useEffect(() => {
setInteractiveTarget(
onlyHandleDraggable ? handleContainerRef.current : rootContainerRef.current
);
}, [onlyHandleDraggable]);
/** Update internal position value. */
const updateInternalPosition = useCallback(
function updateInternalCall({
x,
y,
isOffset,
portrait: _portrait,
boundsPadding: _boundsPadding,
}: UpdateInternalPositionProps) {
const {
top,
left,
width,
height,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
} = rootContainerRef.current!.getBoundingClientRect();
// Early out if width or height are zero, can't calculate values
// from zeros.
if (width === 0 || height === 0) return;
/**
* Pixel position clamped within the container's bounds.
* @NOTE This does *not* take `boundsPadding` into account because we need
* the full coords to correctly position the handle.
*/
const positionPx = Math.min(
Math.max(
// Determine bounds based on orientation
_portrait
? isOffset
? y - top - window.pageYOffset
: y
: isOffset
? x - left - window.pageXOffset
: x,
// Min value
0
),
// Max value
_portrait ? height : width
);
/**
* Internal position percentage *without* bounds.
* @NOTE This uses the entire container bounds **without** `boundsPadding`
* to get the *real* bounds.
*/
const nextInternalPositionPc = (positionPx / (_portrait ? height : width)) * 100;
/** Whether the current pixel position meets the min/max bounds. */
const positionMeetsBounds = _portrait
? positionPx === 0 || positionPx === height
: positionPx === 0 || positionPx === width;
const canSkipPositionPc =
nextInternalPositionPc === internalPositionPc.current &&
(internalPositionPc.current === 0 || internalPositionPc.current === 100);
// Early out if pixel and percentage positions are already at the min/max
// to prevent update spamming when the user is sliding outside of the
// container.
if (didSyncBounds && canSkipPositionPc && positionMeetsBounds) {
return;
} else {
setDidSyncBounds(true);
}
// Set new internal position.
internalPositionPc.current = nextInternalPositionPc;
/** Pixel position clamped to extremities *with* bounds padding. */
const clampedPx = Math.min(
// Get largest from pixel position *or* bounds padding.
Math.max(positionPx, 0 + _boundsPadding),
// Use height *or* width based on orientation.
(_portrait ? height : width) - _boundsPadding
);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
clipContainerRef.current!.style.clip = _portrait
? `rect(auto,auto,${clampedPx}px,auto)`
: `rect(auto,${clampedPx}px,auto,auto)`;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
handleContainerRef.current!.style.transform = _portrait
? `translate3d(0,${clampedPx}px,0)`
: `translate3d(${clampedPx}px,0,0)`;
if (onPositionChange) onPositionChange(internalPositionPc.current);
},
[didSyncBounds, onPositionChange]
);
// Update internal position when other user controllable props change.
useEffect(() => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const { width, height } = rootContainerRef.current!.getBoundingClientRect();
// Use current internal position if `position` hasn't changed.
const nextPosition =
position === prevPropPosition ? internalPositionPc.current : position;
updateInternalPosition({
portrait,
boundsPadding,
x: (width / 100) * nextPosition,
y: (height / 100) * nextPosition,
});
}, [portrait, position, prevPropPosition, boundsPadding, updateInternalPosition]);
/** Handle mouse/touch down. */
const handlePointerDown = useCallback(
(ev: MouseEvent | TouchEvent) => {
ev.preventDefault();
updateInternalPosition({
portrait,
boundsPadding,
isOffset: true,
x: ev instanceof MouseEvent ? ev.pageX : ev.touches[0].pageX,
y: ev instanceof MouseEvent ? ev.pageY : ev.touches[0].pageY,
});
setIsDragging(true);
},
[portrait, boundsPadding, updateInternalPosition]
);
/** Handle mouse/touch move. */
const handlePointerMove = useCallback(
function moveCall(ev: MouseEvent | TouchEvent) {
updateInternalPosition({
portrait,
boundsPadding,
isOffset: true,
x: ev instanceof MouseEvent ? ev.pageX : ev.touches[0].pageX,
y: ev instanceof MouseEvent ? ev.pageY : ev.touches[0].pageY,
});
},
[portrait, boundsPadding, updateInternalPosition]
);
/** Handle mouse/touch up. */
const handlePointerUp = useCallback(() => {
setIsDragging(false);
}, []);
/** Resync internal position on resize. */
const handleResize = useCallback(
({ width, height }: UseResizeObserverHandlerParams) => {
updateInternalPosition({
portrait,
boundsPadding,
x: (width / 100) * internalPositionPc.current,
y: (height / 100) * internalPositionPc.current,
});
},
[portrait, boundsPadding, updateInternalPosition]
);
// Allow drag outside of container while pointer is still down.
useEffect(() => {
if (isDragging && !hasWindowBinding.current) {
window.addEventListener('mousemove', handlePointerMove, EVENT_PASSIVE_PARAMS);
window.addEventListener('mouseup', handlePointerUp, EVENT_PASSIVE_PARAMS);
window.addEventListener('touchmove', handlePointerMove, EVENT_PASSIVE_PARAMS);
window.addEventListener('touchend', handlePointerUp, EVENT_PASSIVE_PARAMS);
hasWindowBinding.current = true;
}
return (): void => {
if (hasWindowBinding.current) {
window.removeEventListener('mousemove', handlePointerMove);
window.removeEventListener('mouseup', handlePointerUp);
window.removeEventListener('touchmove', handlePointerMove);
window.removeEventListener('touchend', handlePointerUp);
hasWindowBinding.current = false;
}
};
}, [handlePointerMove, handlePointerUp, isDragging]);
// Bind resize observer to container.
useResizeObserver(rootContainerRef, handleResize);
// Handle hover events on the container.
useEffect(() => {
const containerRef = rootContainerRef.current!;
const handleMouseLeave = () => {
if (isDragging) return;
handlePointerUp();
};
if (changePositionOnHover) {
containerRef.addEventListener('mousemove', handlePointerMove, EVENT_PASSIVE_PARAMS);
containerRef.addEventListener('mouseleave', handleMouseLeave, EVENT_PASSIVE_PARAMS);
}
return () => {
containerRef.removeEventListener('mousemove', handlePointerMove);
containerRef.removeEventListener('mouseleave', handleMouseLeave);
};
}, [changePositionOnHover, handlePointerMove, handlePointerUp, isDragging]);
useEventListener(
'mousedown',
handlePointerDown,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
interactiveTarget!,
EVENT_CAPTURE_PARAMS
);
useEventListener(
'touchstart',
handlePointerDown,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
interactiveTarget!,
EVENT_CAPTURE_PARAMS
);
// Use custom handle if requested.
const Handle = handle || <ReactCompareSliderHandle portrait={portrait} />;
const rootStyle: React.CSSProperties = {
position: 'relative',
overflow: 'hidden',
cursor: isDragging ? (portrait ? 'ns-resize' : 'ew-resize') : undefined,
userSelect: 'none',
KhtmlUserSelect: 'none',
msUserSelect: 'none',
MozUserSelect: 'none',
WebkitUserSelect: 'none',
...style,
};
return (
<div {...props} ref={rootContainerRef} style={rootStyle} data-rcs="root">
{itemTwo}
<ThisClipContainer ref={clipContainerRef}>{itemOne}</ThisClipContainer>
<ThisHandleContainer portrait={portrait} ref={handleContainerRef}>
{Handle}
</ThisHandleContainer>
</div>
);
}; | the_stack |
import ZeroClipboard = require("zeroclipboard");
// import * as ZeroClipboard from "zeroclipboard";
namespace SimpleExample {
ZeroClipboard.config( { swfPath: "http://YOURSERVER/path/ZeroClipboard.swf" } );
let client = new ZeroClipboard(document.getElementById("copy-button"));
let client2 = new ZeroClipboard(jQuery('.copy-button'));
client.on( "ready", function( readyEvent ) {
// alert( "ZeroClipboard SWF is ready!" );
client.on( "aftercopy", function( event ) {
this === client;
event.target === document.getElementById('el')
event.target.style.display = "none";
alert("Copied text to clipboard: " + event.data["text/plain"] );
});
});
client.on( "copy", function (event) {
var clipboard = event.clipboardData;
clipboard.setData( "text/plain", "Copy me!" );
clipboard.setData( "text/html", "<b>Copy me!</b>" );
clipboard.setData( "application/rtf", "{\\rtf1\\ansi\n{\\b Copy me!}}" );
});
ZeroClipboard.setData( "text/plain", "Copy me!" );
client.setText( "Copy me!" );
client.clip( document.getElementById("d_clip_button") );
var $client = new ZeroClipboard( $("button#my-button") );
function example() {
var client = new ZeroClipboard( $('.clip_button') );
client.on( 'ready', function(event) {
// console.log( 'movie is loaded' );
client.on( 'copy', function(event) {
event.clipboardData.setData('text/plain', event.target.innerHTML);
} );
client.on( 'aftercopy', function(event) {
console.log('Copied text to clipboard: ' + event.data['text/plain']);
} );
} );
client.on( 'error', function(event) {
// console.log( 'ZeroClipboard error of type "' + event.name + '": ' + event.message );
ZeroClipboard.destroy();
} );
}
ZeroClipboard.config({
fixLineEndings: false
});
ZeroClipboard.config({
forceEnhancedClipboard: true
});
}
namespace Static {
var version:String = ZeroClipboard.version;
var config = ZeroClipboard.config();
var swfPath:String = ZeroClipboard.config("swfPath");
ZeroClipboard.config({});
ZeroClipboard.destroy();
ZeroClipboard.setData("text/plain", "Blah");
ZeroClipboard.setData({
"text/plain": "Blah",
"text/html": "<b>Blah</b>"
});
ZeroClipboard.clearData("text/plain");
var text:String = ZeroClipboard.getData("text/plain");
var dataObj = ZeroClipboard.getData();
ZeroClipboard.focus(document.getElementById("d_clip_button"));
ZeroClipboard.blur();
var el = document.getElementById("d_clip_button");
ZeroClipboard.focus(el);
var activeEl = ZeroClipboard.activeElement();
activeEl === el;
ZeroClipboard.state();
let b:boolean = ZeroClipboard.isFlashUnusable();
var listenerFn = function(e: Object) { var ZeroClipboard = this; /* ... */ };
ZeroClipboard.on("ready", listenerFn);
var listenerObj = {
handleEvent: function(e: Object) { var listenerObj = this; /* ... */ }
};
ZeroClipboard.on("error", listenerObj);
ZeroClipboard.on("ready error", function(e) { /* ... */ });
ZeroClipboard.on({
"ready": function(e) { /* ... */ },
"error": function(e) { /* ... */ }
});
ZeroClipboard.off("ready", listenerFn);
ZeroClipboard.off("error", listenerObj);
ZeroClipboard.off("ready error", listenerFn);
ZeroClipboard.off({
"ready": function(e) { /* ... */ },
"error": function(e) { /* ... */ }
});
ZeroClipboard.off("ready");
ZeroClipboard.off();
ZeroClipboard.emit("ready");
ZeroClipboard.emit({
type: "error",
name: "flash-disabled"
});
var pendingCopyData = ZeroClipboard.emit("copy");
var listener = ZeroClipboard.handlers("ready");
var listeners = ZeroClipboard.handlers();
var currentlyActivatedElementOrNull = document.getElementById('currentlyActivatedElementOrNull');
var dataClipboardElementTargetOfCurrentlyActivatedElementOrNull = document.getElementById('dataClipboardElementTargetOfCurrentlyActivatedElementOrNull')
var flashSwfObjectRef = document.getElementById('flashSwfObjectRef') as HTMLObjectElement;
ZeroClipboard.on("ready", function(e) {
e = {
type: "ready",
message: "Flash communication is established",
target: currentlyActivatedElementOrNull,
relatedTarget: dataClipboardElementTargetOfCurrentlyActivatedElementOrNull,
currentTarget: flashSwfObjectRef,
version: "11.2.202",
timeStamp: Date.now()
};
});
ZeroClipboard.on("beforecopy", function(e) {
e = {
type: "beforecopy",
target: currentlyActivatedElementOrNull,
relatedTarget: dataClipboardElementTargetOfCurrentlyActivatedElementOrNull,
currentTarget: flashSwfObjectRef,
timeStamp: Date.now()
};
});
ZeroClipboard.on("copy", function(e) {
e.clipboardData.setData('text/html','<br>');
e.clipboardData.setData({'text/html':'<br>'});
e = {
type: "copy",
target: currentlyActivatedElementOrNull,
relatedTarget: dataClipboardElementTargetOfCurrentlyActivatedElementOrNull,
currentTarget: flashSwfObjectRef,
timeStamp: Date.now(),
clipboardData: {
setData: ZeroClipboard.setData,
clearData: ZeroClipboard.clearData
}
};
});
ZeroClipboard.on("aftercopy", function(e) {
e = {
type: "aftercopy",
target: currentlyActivatedElementOrNull,
relatedTarget: dataClipboardElementTargetOfCurrentlyActivatedElementOrNull,
currentTarget: flashSwfObjectRef,
timeStamp: Date.now(),
success: {
"text/plain": true,
"text/html": true,
"application/rtf": false
},
data: {
"text/plain": "Blah",
"text/html": "<b>Blah</b>",
"application/rtf": "{\\rtf1\\ansi\n{\\b Blah}}"
},
errors: [
{
name: "SecurityError",
message: "Clipboard security error OMG",
errorID: 7320,
stack: null,
format: "application/rtf",
clipboard: "desktop"
}
]
};
});
ZeroClipboard.on("destroy", function(e) {
e = {
type: "destroy",
target: null,
relatedTarget: null,
currentTarget: flashSwfObjectRef,
timeStamp: Date.now(),
success: {
"text/plain": true,
"text/html": true,
"application/rtf": false
},
data: {
"text/plain": "Blah",
"text/html": "<b>Blah</b>",
"application/rtf": "{\\rtf1\\ansi\n{\\b Blah}}"
}
};
});
ZeroClipboard.on("error", function(e) {
e = {
type: "error",
name: "flash-disabled",
message: "Flash is disabled or not installed. May also be attempting to run Flash in a sandboxed iframe, which is impossible.",
target: null,
relatedTarget: null,
currentTarget: flashSwfObjectRef,
timeStamp: Date.now(),
minimumVersion: "11.0.0"
};
});
ZeroClipboard.on("error", function(e) {
e = {
type: "error",
name: "flash-sandboxed",
message: "Attempting to run Flash in a sandboxed iframe, which is impossible",
target: null,
relatedTarget: null,
currentTarget: flashSwfObjectRef,
timeStamp: Date.now(),
minimumVersion: "11.0.0",
version: "11.2.202"
};
});
ZeroClipboard.on("error", function(e) {
e = {
type: "error",
name: "flash-unavailable",
message: "Flash is unable to communicate bidirectionally with JavaScript",
target: null,
relatedTarget: null,
currentTarget: flashSwfObjectRef,
timeStamp: Date.now(),
minimumVersion: "11.0.0",
version: "11.2.202"
};
});
ZeroClipboard.on("error", function(e) {
e = {
type: "error",
name: "flash-degraded",
message: "Flash is unable to preserve data fidelity when communicating with JavaScript",
target: null,
relatedTarget: null,
currentTarget: flashSwfObjectRef,
timeStamp: Date.now(),
minimumVersion: "11.0.0",
version: "11.2.202"
};
});
ZeroClipboard.on("error", function(e) {
e = {
type: "error",
name: "flash-deactivated",
message: "Flash is too outdated for your browser and/or is configured as click-to-activate. This may also mean that the ZeroClipboard SWF object could not be loaded, so please check your `swfPath` configuration and/or network connectivity. May also be attempting to run Flash in a sandboxed iframe, which is impossible.",
target: null,
relatedTarget: null,
currentTarget: flashSwfObjectRef,
timeStamp: Date.now(),
minimumVersion: "11.0.0",
version: "11.2.202"
};
});
ZeroClipboard.on("error", function(e) {
e = {
type: "error",
name: "flash-overdue",
message: "Flash communication was established but NOT within the acceptable time limit",
target: null,
relatedTarget: null,
currentTarget: flashSwfObjectRef,
timeStamp: Date.now(),
minimumVersion: "11.0.0",
version: "11.2.202"
};
});
ZeroClipboard.on("error", function(e) {
e = {
type: "error",
name: "version-mismatch",
message: "ZeroClipboard JS version number does not match ZeroClipboard SWF version number",
target: null,
relatedTarget: null,
currentTarget: flashSwfObjectRef,
timeStamp: Date.now(),
jsVersion: "2.2.1",
swfVersion: "2.2.0"
};
});
ZeroClipboard.on("error", function(e) {
e = {
type: "error",
name: "clipboard-error",
message: "At least one error was thrown while ZeroClipboard was attempting to inject your data into the clipboard",
target: currentlyActivatedElementOrNull,
relatedTarget: dataClipboardElementTargetOfCurrentlyActivatedElementOrNull,
currentTarget: flashSwfObjectRef,
timeStamp: Date.now(),
data: {
"text/plain": "Blah",
"text/html": "<b>Blah</b>",
"application/rtf": "{\\rtf1\\ansi\n{\\b Blah}}"
},
errors: [
{
name: "SecurityError",
message: "Clipboard security error OMG",
errorID: 7320,
stack: null,
format: "application/rtf",
clipboard: "desktop"
}
]
};
});
ZeroClipboard.on("error", function(e) {
e = {
type: "error",
name: "config-mismatch",
message: "ZeroClipboard configuration does not match Flash's reality",
target: null,
relatedTarget: null,
currentTarget: flashSwfObjectRef,
timeStamp: Date.now(),
property: "swfObjectId",
configuredValue: "my-zeroclipboard-object",
actualValue: "global-zeroclipboard-flash-bridge"
};
});
ZeroClipboard.on("error", function(e) {
e = {
type: "error",
name: "swf-not-found",
message: "The ZeroClipboard SWF object could not be loaded, so please check your `swfPath` configuration and/or network connectivity",
target: null,
relatedTarget: null,
currentTarget: flashSwfObjectRef,
timeStamp: Date.now()
};
});
}
namespace Instance {
var clippedEl = document.getElementById("d_clip_button");
var client = new ZeroClipboard(clippedEl);
client.setText("Blah");
client.setHtml("<b>Blah</b>");
client.setRichText("{\\rtf1\\ansi\n{\\b Blah}}");
client.setData("text/plain", "Blah");
client.setData({
"text/plain": "Blah",
"text/html": "<b>Blah</b>"
});
client.clearData("text/plain");
client.clearData();
var text:String = client.getData("text/plain");
var dataObj = client.getData();
client.clip(document.getElementById("d_clip_button"))
client.clip(document.querySelectorAll(".clip_button"));
client.clip(jQuery(".clip_button"));
client.unclip(document.getElementById("d_clip_button"))
client.unclip(document.querySelectorAll(".clip_button"));
client.unclip(jQuery(".clip_button"));
client.unclip();
var els:HTMLElement[] = client.elements();
var listenerFn = function(e: Object) { var client = this; /* ... */ };
client.on("ready", listenerFn);
var listenerObj = {
handleEvent: function(e: Object) { var listenerObj = this; /* ... */ }
};
client.on("error", listenerObj);
client.on("ready error", function(e) { /* ... */ });
client.on({
"ready": function(e) { /* ... */ },
"error": function(e) { /* ... */ }
});
client.off("ready", listenerFn);
client.off("error", listenerObj);
client.off("ready error", listenerFn);
client.off({
"ready": function(e) { /* ... */ },
"error": function(e) { /* ... */ }
});
client.off("ready");
client.off();
client.emit("ready");
client.emit({
type: "error",
name: "flash-disabled"
});
var readyListeners = client.handlers("ready");
var listeners = client.handlers();
var client = new ZeroClipboard();
client.on("ready", function(e) {
if (e.client === client && client === this) {
console.log("This client instance is ready!");
}
});
}
namespace GlobalConfig {
var _globalConfig = {
// SWF URL, relative to the page. Default value will be "ZeroClipboard.swf"
// under the same path as the ZeroClipboard JS file.
swfPath: '_swfPath',
// SWF inbound scripting policy: page domains that the SWF should trust.
// (single string, or array of strings)
trustedDomains: window.location.host ? [window.location.host] : [],
// Include a "noCache" query parameter on requests for the SWF.
cacheBust: true,
// Enable use of the fancy "Desktop" clipboard, even on Linux where it is
// known to suck.
forceEnhancedClipboard: false,
// How many milliseconds to wait for the Flash SWF to load and respond before assuming that
// Flash is deactivated (e.g. click-to-play) in the user's browser. If you don't care about
// how long it takes to load the SWF, you can set this to `null`.
flashLoadTimeout: 30000,
// Setting this to `false` would allow users to handle calling `ZeroClipboard.focus(...);`
// themselves instead of relying on our per-element `mouseover` handler.
autoActivate: true,
// Bubble synthetic events in JavaScript after they are received by the Flash object.
bubbleEvents: true,
// Ensure OS-compliant line endings, i.e. "\r\n" on Windows, "\n" elsewhere
fixLineEndings: true,
// Sets the ID of the `div` encapsulating the Flash object.
// Value is validated against the [HTML4 spec for `ID` tokens][valid_ids].
containerId: "global-zeroclipboard-html-bridge",
// Sets the class of the `div` encapsulating the Flash object.
containerClass: "global-zeroclipboard-container",
// Sets the ID and name of the Flash `object` element.
// Value is validated against the [HTML4 spec for `ID` and `Name` tokens][valid_ids].
swfObjectId: "global-zeroclipboard-flash-bridge",
// The class used to indicate that a clipped element is being hovered over.
hoverClass: "zeroclipboard-is-hover",
// The class used to indicate that a clipped element is active (is being clicked).
activeClass: "zeroclipboard-is-active",
// Forcibly set the hand cursor ("pointer") for all clipped elements.
// IMPORTANT: This configuration value CAN be modified while a SWF is actively embedded.
forceHandCursor: false,
// Sets the title of the `div` encapsulating the Flash object.
// IMPORTANT: This configuration value CAN be modified while a SWF is actively embedded.
title: 'title',
// The z-index used by the Flash object.
// Max value (32-bit): 2147483647.
// IMPORTANT: This configuration value CAN be modified while a SWF is actively embedded.
zIndex: 999999999
};
ZeroClipboard.config(_globalConfig);
} | the_stack |
import React from 'react'
import { Row, Col, Input, Checkbox, Select, InputNumber } from 'antd'
const Option = Select.Option
import ColorPicker from 'app/components/ColorPicker'
import {
PIVOT_CHART_FONT_FAMILIES,
PIVOT_CHART_LINE_STYLES,
PIVOT_CHART_FONT_SIZES,
CHART_LABEL_POSITIONS,
CHART_PIE_LABEL_POSITIONS,
CHART_FUNNEL_LABEL_POSITIONS
} from 'app/globalConstants'
const styles = require('../Workbench.less')
export interface IGaugeConfig {
radius: number
splitNumber: number
startAngle: number
endAngle: number
clockwise: boolean
max: number
prefix: string
suffix: string
showTitle: boolean
titleFontFamily: string
titleFontSize: string
titleColor: string
titleOffsetLeft: number
titleOffsetTop: number
showDetail: boolean
detailFontFamily: string
detailFontSize: string
detailColor: string
detailOffsetLeft: number
detailOffsetTop: number
showPointer: boolean
pointerLength: number
pointerWidth: number
customPointerColor: boolean
pointerColor: string
pointerBorderStyle: string
pointerBorderWidth: number
pointerBorderColor: string
axisLineSize: number
axisLineColor: string
showAxisTick: boolean
showAxisLabel: boolean
axisLabelDistance: number
axisLabelFontFamily: string
axisLabelFontSize: string
axisLabelColor: string
showSplitLine: boolean
splitLineLength: number
splitLineSize: string
splitLineStyle: string
splitLineColor: string
}
interface IGaugeSectionProps {
title: string
config: IGaugeConfig
onChange: (prop: string, value: any) => void
}
export class GaugeSection extends React.PureComponent<IGaugeSectionProps, {}> {
private inputChange = (prop) => (e: React.ChangeEvent<HTMLInputElement>) => {
this.props.onChange(prop, e.target.value)
}
private checkboxChange = (prop) => (e) => {
this.props.onChange(prop, e.target.checked)
}
private selectChange = (prop) => (value) => {
this.props.onChange(prop, value)
}
private colorChange = (prop) => (color) => {
this.props.onChange(prop, color)
}
private inputNumberChange = (prop) => (value) => {
this.props.onChange(prop, value)
}
private percentFormatter = (value) => `${value}%`
private percentParser = (value) => value.replace('%', '')
private pixelFormatter = (value) => `${value}px`
private pixelParser = (value) => value.replace(/[p|x]+/, '')
private lineStyles = PIVOT_CHART_LINE_STYLES.map((l) => (
<Option key={l.value} value={l.value}>
{l.name}
</Option>
))
public render () {
const { title, config } = this.props
const {
radius,
splitNumber,
startAngle,
endAngle,
clockwise,
max,
prefix,
suffix,
showTitle,
titleFontFamily,
titleFontSize,
titleColor,
titleOffsetLeft,
titleOffsetTop,
showDetail,
detailFontFamily,
detailFontSize,
detailColor,
detailOffsetLeft,
detailOffsetTop,
showPointer,
pointerLength,
pointerWidth,
customPointerColor,
pointerColor,
pointerBorderStyle,
pointerBorderWidth,
pointerBorderColor,
axisLineSize,
axisLineColor,
showAxisTick,
showAxisLabel,
axisLabelDistance,
axisLabelFontFamily,
axisLabelFontSize,
axisLabelColor,
showSplitLine,
splitLineLength,
splitLineSize,
splitLineStyle,
splitLineColor
} = config
const fontFamilies = PIVOT_CHART_FONT_FAMILIES.map((f) => (
<Option key={f.value} value={f.value}>{f.name}</Option>
))
const fontSizes = PIVOT_CHART_FONT_SIZES.map((f) => (
<Option key={`${f}`} value={`${f}`}>{f}</Option>
))
return (
<>
<div className={styles.paneBlock}>
<h4>{title}</h4>
<div className={styles.blockBody}>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={6}>目标值</Col>
<Col span={10}>
<InputNumber
className={styles.blockElm}
value={max}
onChange={this.inputNumberChange('max')}
/>
</Col>
</Row>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={6}>前缀</Col>
<Col span={6}>
<Input
className={styles.blockElm}
value={prefix}
onChange={this.inputChange('prefix')}
/>
</Col>
<Col span={6}>后缀</Col>
<Col span={6}>
<Input
className={styles.blockElm}
value={suffix}
onChange={this.inputChange('suffix')}
/>
</Col>
</Row>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={6}>半径</Col>
<Col span={6}>
<InputNumber
className={styles.blockElm}
value={radius}
onChange={this.inputNumberChange('radius')}
formatter={this.percentFormatter}
parser={this.percentParser}
/>
</Col>
<Col span={6}>分隔段数</Col>
<Col span={6}>
<InputNumber
className={styles.blockElm}
value={splitNumber}
min={1}
onChange={this.inputNumberChange('splitNumber')}
/>
</Col>
</Row>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={6}>起始角度</Col>
<Col span={6}>
<InputNumber
className={styles.blockElm}
value={startAngle}
onChange={this.inputNumberChange('startAngle')}
/>
</Col>
<Col span={6}>结束角度</Col>
<Col span={6}>
<InputNumber
className={styles.blockElm}
value={endAngle}
onChange={this.inputNumberChange('endAngle')}
/>
</Col>
</Row>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={10}>
<Checkbox
checked={clockwise}
onChange={this.checkboxChange('clockwise')}
>
顺时针
</Checkbox>
</Col>
</Row>
</div>
</div>
<div className={styles.paneBlock}>
<h4>标题</h4>
<div className={styles.blockBody}>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={10}>
<Checkbox
checked={showTitle}
onChange={this.checkboxChange('showTitle')}
>
显示标题
</Checkbox>
</Col>
</Row>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={10}>
<Select
placeholder="字体"
className={styles.blockElm}
value={titleFontFamily}
onChange={this.selectChange('titleFontFamily')}
>
{fontFamilies}
</Select>
</Col>
<Col span={10}>
<Select
placeholder="文字大小"
className={styles.blockElm}
value={titleFontSize}
onChange={this.selectChange('titleFontSize')}
>
{fontSizes}
</Select>
</Col>
<Col span={4}>
<ColorPicker
value={titleColor}
onChange={this.colorChange('titleColor')}
/>
</Col>
</Row>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={6}>距离左侧</Col>
<Col span={12}>
<InputNumber
className={styles.blockElm}
value={titleOffsetLeft}
onChange={this.inputNumberChange('titleOffsetLeft')}
formatter={this.percentFormatter}
parser={this.percentParser}
/>
</Col>
</Row>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={6}>距离顶部</Col>
<Col span={12}>
<InputNumber
className={styles.blockElm}
value={titleOffsetTop}
onChange={this.inputNumberChange('titleOffsetTop')}
formatter={this.percentFormatter}
parser={this.percentParser}
/>
</Col>
</Row>
</div>
</div>
<div className={styles.paneBlock}>
<h4>数据</h4>
<div className={styles.blockBody}>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={10}>
<Checkbox
checked={showDetail}
onChange={this.checkboxChange('showDetail')}
>
显示数据
</Checkbox>
</Col>
</Row>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={10}>
<Select
placeholder="字体"
className={styles.blockElm}
value={detailFontFamily}
onChange={this.selectChange('detailFontFamily')}
>
{fontFamilies}
</Select>
</Col>
<Col span={10}>
<Select
placeholder="文字大小"
className={styles.blockElm}
value={detailFontSize}
onChange={this.selectChange('detailFontSize')}
>
{fontSizes}
</Select>
</Col>
<Col span={4}>
<ColorPicker
value={detailColor}
onChange={this.colorChange('detailColor')}
/>
</Col>
</Row>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={6}>距离左侧</Col>
<Col span={12}>
<InputNumber
className={styles.blockElm}
value={detailOffsetLeft}
onChange={this.inputNumberChange('detailOffsetLeft')}
formatter={this.percentFormatter}
parser={this.percentParser}
/>
</Col>
</Row>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={6}>距离顶部</Col>
<Col span={12}>
<InputNumber
className={styles.blockElm}
value={detailOffsetTop}
onChange={this.inputNumberChange('detailOffsetTop')}
formatter={this.percentFormatter}
parser={this.percentParser}
/>
</Col>
</Row>
</div>
</div>
<div className={styles.paneBlock}>
<h4>指针</h4>
<div className={styles.blockBody}>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={10}>
<Checkbox
checked={showPointer}
onChange={this.checkboxChange('showPointer')}
>
显示指针
</Checkbox>
</Col>
<Col span={10}>
<Checkbox
checked={customPointerColor}
onChange={this.checkboxChange('customPointerColor')}
>
自定颜色
</Checkbox>
</Col>
{
customPointerColor && (
<Col span={4}>
<ColorPicker
value={pointerColor}
onChange={this.colorChange('pointerColor')}
/>
</Col>
)
}
</Row>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={4}>长度</Col>
<Col span={8}>
<InputNumber
className={styles.blockElm}
value={pointerLength}
onChange={this.inputNumberChange('pointerLength')}
formatter={this.percentFormatter}
parser={this.percentParser}
/>
</Col>
<Col span={4}>粗细</Col>
<Col span={8}>
<InputNumber
className={styles.blockElm}
value={pointerWidth}
onChange={this.inputNumberChange('pointerWidth')}
formatter={this.pixelFormatter}
parser={this.pixelParser}
/>
</Col>
</Row>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={4}>边框</Col>
<Col span={8}>
<Select
placeholder="样式"
className={styles.blockElm}
value={pointerBorderStyle}
onChange={this.selectChange('pointerBorderStyle')}
>
{this.lineStyles}
</Select>
</Col>
<Col span={8}>
<InputNumber
placeholder="粗细"
className={styles.blockElm}
value={pointerBorderWidth}
min={0}
onChange={this.selectChange('pointerBorderWidth')}
/>
</Col>
<Col span={4}>
<ColorPicker
value={pointerBorderColor}
onChange={this.selectChange('pointerBorderColor')}
/>
</Col>
</Row>
</div>
</div>
<div className={styles.paneBlock}>
<h4>轴</h4>
<div className={styles.blockBody}>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={4}>粗细</Col>
<Col span={8}>
<InputNumber
className={styles.blockElm}
value={axisLineSize}
onChange={this.selectChange('axisLineSize')}
formatter={this.pixelFormatter}
parser={this.pixelParser}
/>
</Col>
<Col span={4}>颜色</Col>
<Col span={4}>
<ColorPicker
value={axisLineColor}
onChange={this.colorChange('axisLineColor')}
/>
</Col>
</Row>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={12}>
<Checkbox
checked={showAxisTick}
onChange={this.checkboxChange('showAxisTick')}
>
显示刻度
</Checkbox>
</Col>
</Row>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={12}>
<Checkbox
checked={showAxisLabel}
onChange={this.checkboxChange('showAxisLabel')}
>
显示标签
</Checkbox>
</Col>
</Row>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={10}>
<Select
placeholder="标签字体"
className={styles.blockElm}
value={axisLabelFontFamily}
onChange={this.selectChange('axisLabelFontFamily')}
>
{fontFamilies}
</Select>
</Col>
<Col span={10}>
<Select
placeholder="标签文字大小"
className={styles.blockElm}
value={axisLabelFontSize}
onChange={this.selectChange('axisLabelFontSize')}
>
{fontSizes}
</Select>
</Col>
<Col span={4}>
<ColorPicker
value={axisLabelColor}
onChange={this.colorChange('axisLabelColor')}
/>
</Col>
</Row>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={6}>距离轴线</Col>
<Col span={12}>
<InputNumber
className={styles.blockElm}
value={axisLabelDistance}
onChange={this.inputNumberChange('axisLabelDistance')}
/>
</Col>
</Row>
</div>
</div>
<div className={styles.paneBlock}>
<h4>分隔线</h4>
<div className={styles.blockBody}>
<Row gutter={8} type="flex" align="middle" className={styles.blockRow}>
<Col span={16}>
<Checkbox
checked={showSplitLine}
onChange={this.checkboxChange('showSplitLine')}
>
显示分隔线
</Checkbox>
</Col>
</Row>
</div>
</div>
</>
)
}
}
export default GaugeSection | the_stack |
import { Vector3 } from 'three';
import { performance } from 'perf_hooks';
import { TomType, TomTypedArray, TypedArray, Type, GPUBufferDataType } from './types';
import { existsSync, unlinkSync, mkdirSync } from 'fs';
import * as del from 'del';
import { DATA_PATH, FILENAME, OUTPUT_PATH } from './Defaults';
import { getTomDimensions } from './io';
/**
* Returns the number of bytes per element of a given data type.
* @param {string} type string describing data type
* @returns {number} number of bytes per element of type
*/
export function dataSizeForType(type: TomType | 'uint16' | 'int16') {
switch (type) {
case 'uint8':
return 1;
case 'int16':
return 2;
case 'uint16':
return 2;
case 'int32':
return 4;
case 'uint32':
return 4;
case 'float32':
return 4;
default:
throw new Error(`Unknown type ${type}.`);
}
};
/**
* Returns the number we are reserving as 'null' for a given data type.
* @param {string} type string describing data type
* @returns {number} null value for that data type
*/
export function nullValForType(type: Type) {
switch (type) {
case 'int32':
return -10000;// TODO: let's use a proper NaN value here.
case 'float32':
return -10000;// TODO: let's use a proper NaN value here.
default:
throw new Error(`No null supported for type ${type}.`);
}
};
export function typeOfTypedArray(typedArray: TomTypedArray): TomType;
export function typeOfTypedArray(typedArray: TypedArray): Type;
export function typeOfTypedArray(typedArray: TypedArray): Type;
export function typeOfTypedArray(typedArray: any) {
// Get data type from TypedArray.
switch (typedArray.constructor) {
case Uint8Array:
return 'uint8';
case Float32Array:
return 'float32';
case Int32Array:
return 'int32';
case Uint32Array:
return 'uint32';
case Uint16Array:
return 'uint16';
case Int16Array:
return 'int16';
default:
throw new Error(`Unknown type for tom file: ${typedArray.constructor}`)
}
}
export function gpuTypeForType(type: Type) {
switch (type) {
case 'uint8':
return 'uchar*' as GPUBufferDataType;
case 'float32':
return 'float*' as GPUBufferDataType;
case 'int32':
return 'int*' as GPUBufferDataType;
// case 'uint32':
// return 'uint*';
default:
throw new Error(`Unsupported type: ${type}`)
}
}
export function typeForGPUType(type: GPUBufferDataType): Type {
switch (type) {
case 'uchar*':
return 'uint8';
case 'float*':
return 'float32';
case 'int*':
return 'int32';
// case 'uint32':
// return 'uint*';
default:
throw new Error(`Unsupported type: ${type}`)
}
}
/**
* Returns the file type extension of a filename.
* @param {string} filenameWithExtension
* @returns {string} extension, no period
*/
export function getExtension(filenameWithExtension: string) {
const parts = filenameWithExtension.split('.');
if (parts.length < 2) {
throw new Error(`Invalid filename: ${filenameWithExtension}, or no extension present.`);
}
return parts[parts.length - 1];
};
/**
* Returns the filename with no extension.
* @param {string} filenameWithExtension
* @returns {string} filename without extension
*/
export function removeExtension(filenameWithExtension: string) {
const parts = filenameWithExtension.split('.');
if (parts.length < 2) {
throw new Error(`Invalid filename: ${filenameWithExtension}, or no extension present.`);
}
parts.pop();
return parts.join('.');
};
/**
* Tests if a number is an integer.
* @param {number} num number to be tested
* @returns {boolean} true if num is an integer, else false
*/
export function isInteger(num: number) {
return Number.isInteger(num);
}
/**
* Tests if a number is a positive integer (strictly > 0).
* @param {number} num number to be tested
* @returns {boolean} true if num is a positive integer, else false
*/
export function isPositiveInteger(num: number) {
return isInteger(num) && num > 0;
}
/**
* Tests if a number is a non-negative integer (>= 0).
* @param {number} num number to be tested
* @returns {boolean} true if num is a non-negative integer, else false
*/
export function isNonNegativeInteger(num: number) {
return isInteger(num) && num >= 0;
}
export function checkType(number: number, type: Type) {
switch(type) {
case 'uint8':
return isUint8(number);
case 'float32':
return isFloat32(number);
case 'uint32':
return isUint32(number);
case 'int32':
return isInt32(number);
default:
throw new Error(`Need to implement check for type ${type} in utils.`);
}
}
/**
* Tests if a number is a uint8.
* @param {number} num number to be tested
* @returns {boolean} true if num is a uint8, else false
*/
export function isUint8(num: number) {
return isInteger(num) && num >= 0 && num < 256;
};
/**
* Tests if a number is a uint32.
* @param {number} num number to be tested
* @returns {boolean} true if num is a uint32, else false
*/
export function isUint32(num: number) {
return isInteger(num) && num >= 0 && num <= 0xFFFFFFFF;
};
/**
* Tests if a number is a int32.
* @param {number} num number to be tested
* @returns {boolean} true if num is a int32, else false
*/
export function isInt32(num: number) {
return isInteger(num) && num >= Number.MIN_SAFE_INTEGER && num <= Number.MAX_SAFE_INTEGER;
};
export function arrayIntersection(array1: any[], array2: any[]) {
return array1.filter(el => array2.indexOf(el) !== -1);
}
/**
* Tests if a number is a float32.
* @param {number} num number to be tested
* @returns {boolean} true if num is a float32, else false
*/
export function isFloat32(num: number) {
return num >= -Number.MAX_VALUE && num <= Number.MAX_VALUE;
};
/**
* Tests if an object is an Array.
* @param {object} arr object to be tested
* @returns {boolean} true if arr is an array, else false
*/
export function isArray(arr: any) {
return Array.isArray(arr) || isTypedArray(arr);
};
/**
* Tests if an object is a TypedArray.
* @param {object} arr object to be tested
* @returns {boolean} true if arr is a TypedArray, else false
*/
export function isTypedArray(arr: any) {
return !!(arr?.buffer instanceof ArrayBuffer && arr?.BYTES_PER_ELEMENT);
};
/**
* Returns 1D index from 3D index (x, y, z)
* @param {Integer} x x index
* @param {Integer} y y index
* @param {Integer} z z index
* @param {Vector3} dim dimensions of dataset
* @returns {Integer} 1D index
*/
export function index3Dto1D(index3D: Vector3, dim: Vector3) {
// Check input params are valid.
if (!isInteger(index3D.x) || !isInteger(index3D.y) || !isInteger(index3D.z)) throw new Error(`Invalid index3D: ${stringifyVector3(index3D)}.`);
// Check in bounds.
if (!index3DInBounds(index3D, dim)) {
throw new Error(`Invalid index3D: ${stringifyVector3(index3D)} for buffer dimensions: ${stringifyVector3(dim)}.`);
}
// Calc 1D index based on z, y, x ordering.
return (index3D.z * dim.x * dim.y) + (index3D.y * dim.x) + index3D.x;
};
/**
* 1D index to 3D index
* @param {Integer} i 1D index
* @param {Vector3} dim dimensions of dataset
* @param {Vector3} v a vector to store the output (so new Vector3 does not need to be allocated)
* @returns {Vector3} 3D index
*/
export function index1Dto3D(i: number, dim: Vector3, v: Vector3) {
// Check input params are valid.
if (!isInteger(dim.x) || !isInteger(dim.y) ||
!isInteger(dim.z)) throw new Error(`Invalid dimension parameter: ${stringifyVector3(dim)}.`);
if (!isInteger(i)) throw new Error(`Invalid index parameter: ${i}.`);
// Check in bounds.
if (i < 0 || i >= dim.x * dim.y * dim.z) {
throw new Error(`Attempting to access out of bounds index: ${i} for dimensions: ${stringifyVector3(dim)}.`);
}
// Calc 3D index based on z, y, x ordering.
const z = Math.floor(i / (dim.x * dim.y));
const y = Math.floor((i % (dim.x * dim.y)) / dim.x);
const x = ((i % (dim.x * dim.y)) % dim.x);
return v.set(x, y, z);
};
/**
* converts a 3D position to an index in a voxel array, round to nearest integer voxel
* returns null if position is outside dimensions
* @param {Vector3} position 3D position
* @param {Vector3} dim dimensions of dataset
* @returns {Vector3|null}
*/
export function positionToIndex3D(position: Vector3, v: Vector3, dim?: Vector3) {
// const index = (position.clone().sub(new Vector3(0.5, 0.5, 0.5))).round();
// // float -0 is messing things up
// index.x = parseInt(index.x, 10);
// index.y = parseInt(index.y, 10);
// index.z = parseInt(index.z, 10);
v.copy(position);
v.x = Math.floor(v.x);
v.y = Math.floor(v.y);
v.z = Math.floor(v.z);
if (dim === undefined) return v;
// Perform additional checks
if (!index3DInBounds(v, dim)) return null;
return v;
};
/**
* checks if an index is in bounds
* @param {Vector3} index current index
* @param {Vector3} dim dimensions of file
* @returns {Boolean} true if in bounds, else false
*/
export function index3DInBounds(index: Vector3, dim: Vector3) {
if (index.x < 0 || index.y < 0 || index.z < 0) return false;
if (index.x >= dim.x || index.y >= dim.y || index.z >= dim.z) return false;
return true;
};
// /**
// * converts a 3D position to an index in a voxel array, round to nearest integer voxel
// * returns null if position is outside dimensions
// * @param {Vector3} position 3D position
// * @param {Vector3} dim dimensions of dataset
// * @returns {Vector3|null}
// */
// export function index3DtoPosition(index3D: Vector3) {
// return index3D.clone().addScalar(0.5);
// };
// /**
// * create Vector3 from data in 1D array, may return null if data contains nullVal placeholders
// * @param {Integer} index index in data array
// * @param {Array} array data
// * @param {String} [type='float32'] - data type (for determining if data is null)
// * @returns {Vector3|null}
// */
// export function vector3ForIndex(index: number, array: number[], type: DataType = 'float32') {
// if (index < 0 || index >= array.length / 3) throw new Error(`Index out of range: ${index}.`);
// const xVal = array[3 * index];
// if (xVal === nullValForType(type)) return null;
// return new Vector3(xVal, array[(3 * index) + 1], array[(3 * index) + 2]);
// };
// export function convertNeighborsToEdges(neighbors) {
// let twiceNumEdges = 0;
// for (let i = 0; i < neighbors.length; i++) {
// twiceNumEdges += neighbors.get(i).length;
// }
// const edges = new Uint32Array(twiceNumEdges);
// let index = 0;
// for (let i = 0; i < neighbors.length; i++) {
// const _neighbors = neighbors.get(i);
// for (let j = 0; j < _neighbors.length; j++) {
// if (_neighbors[j] > i) {
// edges[index] = _neighbors[j];
// edges[index + 1] = i;
// index += 2;
// }
// }
// }
// return edges;
// };
/**
* clamp value between min and max (inclusive)
* @param {Number} val value to clamp
* @param {Number} min min value
* @param {Number} max max value
* @returns {Number}
*/
export function clamp(val: number, min: number, max: number) {
if (min > max) throw new Error(`Invalid range for clamp: min ${min}, max ${max}.`);
return Math.min(Math.max(val, min), max);
};
export function stringifyVector3(vector3: Vector3) {
return `[ ${vector3.x}, ${vector3.y}, ${vector3.z} ]`;
};
export function safeClearDirectory(fullPath: string) {
if (existsSync(fullPath)) {
del.sync([`${fullPath}*`]);
}
}
export function safeDeleteFile(fullPath: string) {
if (existsSync(fullPath)) {
unlinkSync(fullPath);
}
}
export function addDirectoryIfNeeded(fullPath: string) {
if (!existsSync(fullPath)) {
mkdirSync(fullPath);
}
}
export function log(string: string) {
if (process.env.VERBOSE === 'true') console.log(string);
}
export function logTime(string: string, startTime: number) {
if (process.env.VERBOSE === 'true') console.log(`${string}: ${(performance.now() - startTime).toFixed(2)} ms\n`);
}
export function getRuntimeParams() {
const _FILENAME = process.env.FILENAME ? process.env.FILENAME : FILENAME;
const _OUTPUT_PATH = process.env.OUTPUT_PATH ? process.env.OUTPUT_PATH : OUTPUT_PATH;
const _FILE_OUTPUT_PATH = `${_OUTPUT_PATH}${_FILENAME}/`;
const _FILE_DATA_PATH = process.env.DATA_PATH ? process.env.DATA_PATH : DATA_PATH;
const _DIMENSIONS = getTomDimensions(_FILE_DATA_PATH, _FILENAME);
console.log(`Processing file: ${_FILENAME} with dimensions: ${stringifyVector3(_DIMENSIONS)}\n`);
// Make output directories if needed.
addDirectoryIfNeeded(_OUTPUT_PATH);
addDirectoryIfNeeded(_FILE_OUTPUT_PATH);
return {
FILENAME: _FILENAME,
DIMENSIONS: _DIMENSIONS,
DATA_PATH: _FILE_DATA_PATH,
OUTPUT_PATH: _FILE_OUTPUT_PATH,
};
} | the_stack |
import * as path from 'path';
import { Template } from '@aws-cdk/assertions';
import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
import * as core from '@aws-cdk/core';
import * as constructs from 'constructs';
import * as inc from '../lib';
import * as futils from '../lib/file-utils';
/* eslint-disable quote-props */
/* eslint-disable quotes */
describe('CDK Include', () => {
let stack: core.Stack;
beforeEach(() => {
stack = new core.Stack();
});
test('can ingest a template with all long-form CloudFormation functions and output it unchanged', () => {
includeTestTemplate(stack, 'long-form-vpc.yaml');
Template.fromStack(stack).templateMatches(
loadTestFileToJsObject('long-form-vpc.yaml'),
);
});
test('can ingest a template with year-month-date parsed as string instead of Date', () => {
includeTestTemplate(stack, 'year-month-date-as-strings.yaml');
Template.fromStack(stack).templateMatches({
"AWSTemplateFormatVersion": "2010-09-09",
"Resources": {
"Role": {
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": ["ec2.amazonaws.com"],
},
"Action": ["sts:AssumeRole"],
},
],
},
},
},
},
});
});
test('can ingest a template with the short form Base64 function', () => {
includeTestTemplate(stack, 'short-form-base64.yaml');
Template.fromStack(stack).templateMatches({
"Resources": {
"Base64Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": {
"Fn::Base64": "NonBase64BucketName",
},
},
},
},
});
});
test('can ingest a template with the short form !Cidr function', () => {
includeTestTemplate(stack, 'short-form-cidr.yaml');
Template.fromStack(stack).templateMatches({
"Resources": {
"CidrVpc1": {
"Type": "AWS::EC2::VPC",
"Properties": {
"CidrBlock": {
"Fn::Cidr": [
"192.168.1.1/24",
2,
5,
],
},
},
},
"CidrVpc2": {
"Type": "AWS::EC2::VPC",
"Properties": {
"CidrBlock": {
"Fn::Cidr": [
"192.168.1.1/24",
"2",
"5",
],
},
},
},
},
});
});
test('can ingest a template with the short form !FindInMap function, in both hyphen and bracket notation', () => {
includeTestTemplate(stack, 'short-form-find-in-map.yaml');
Template.fromStack(stack).templateMatches({
"Mappings": {
"RegionMap": {
"region-1": {
"HVM64": "name1",
"HVMG2": "name2",
},
},
},
"Resources": {
"Bucket1": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": {
"Fn::FindInMap": [
"RegionMap",
"region-1",
"HVM64",
],
},
},
},
"Bucket2": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": {
"Fn::FindInMap": [
"RegionMap",
"region-1",
"HVMG2",
],
},
},
},
},
});
});
test('can ingest a template with the short form !GetAtt function', () => {
includeTestTemplate(stack, 'short-form-get-att.yaml');
Template.fromStack(stack).templateMatches({
"Resources": {
"ELB": {
"Type": "AWS::ElasticLoadBalancing::LoadBalancer",
"Properties": {
"AvailabilityZones": [
"us-east-1a",
],
"Listeners": [
{
"LoadBalancerPort": "80",
"InstancePort": "80",
"Protocol": "HTTP",
},
],
},
},
"Bucket0": {
"Type": "AWS::S3::Bucket",
"Properties": { "BucketName": "some-bucket" },
},
"Bucket1": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": { "Fn::GetAtt": "Bucket0.Arn" },
"AccessControl": { "Fn::GetAtt": ["ELB", "SourceSecurityGroup.GroupName"] },
},
},
"Bucket2": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": { "Fn::GetAtt": ["Bucket1", "Arn"] },
"AccessControl": { "Fn::GetAtt": "ELB.SourceSecurityGroup.GroupName" },
},
},
},
});
});
test('can ingest a template with short form Select, GetAZs, and Ref functions', () => {
includeTestTemplate(stack, 'short-form-select.yaml');
Template.fromStack(stack).templateMatches({
"Resources": {
"Subnet1": {
"Type": "AWS::EC2::Subnet",
"Properties": {
"VpcId": {
"Fn::Select": [0, { "Fn::GetAZs": "" }],
},
"CidrBlock": "10.0.0.0/24",
"AvailabilityZone": {
"Fn::Select": ["0", { "Fn::GetAZs": "eu-west-2" }],
},
},
},
"Subnet2": {
"Type": "AWS::EC2::Subnet",
"Properties": {
"VpcId": {
"Ref": "Subnet1",
},
"CidrBlock": "10.0.0.0/24",
"AvailabilityZone": {
"Fn::Select": [0, { "Fn::GetAZs": "eu-west-2" }],
},
},
},
},
});
});
test('can ingest a template with the short form !ImportValue function', () => {
includeTestTemplate(stack, 'short-form-import-value.yaml');
Template.fromStack(stack).templateMatches({
"Resources": {
"Bucket1": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": {
"Fn::ImportValue": "SomeSharedValue",
},
},
},
},
});
});
test('can ingest a template with the short form !Join function', () => {
includeTestTemplate(stack, 'short-form-join.yaml');
Template.fromStack(stack).templateMatches({
"Resources": {
"Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": {
"Fn::Join": [' ', [
"NamePart1 ",
{ "Fn::ImportValue": "SomeSharedValue" },
]],
},
},
},
},
});
});
test('can ingest a template with the short form !Split function that uses both brackets and hyphens', () => {
includeTestTemplate(stack, 'short-form-split.yaml');
Template.fromStack(stack).templateMatches({
"Resources": {
"Bucket1": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": {
"Fn::Split": [' ', {
"Fn::ImportValue": "SomeSharedBucketName",
}],
},
},
},
"Bucket2": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": {
"Fn::Split": [' ', {
"Fn::ImportValue": "SomeSharedBucketName",
}],
},
},
},
},
});
});
test('can ingest a template with the short form !Transform function', () => {
// Note that this yaml template fails validation. It is unclear how to invoke !Transform.
includeTestTemplate(stack, 'invalid/short-form-transform.yaml');
Template.fromStack(stack).templateMatches({
"Resources": {
"Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": {
"Fn::Transform": {
"Name": "SomeMacroName",
"Parameters": {
"key1": "value1",
"key2": "value2",
},
},
},
},
},
},
});
});
test('can ingest a template with the short form conditionals', () => {
includeTestTemplate(stack, 'short-form-conditionals.yaml');
Template.fromStack(stack).templateMatches({
"Conditions": {
"AlwaysTrueCond": {
"Fn::And": [
{
"Fn::Not": [
{ "Fn::Equals": [{ "Ref": "AWS::Region" }, "completely-made-up-region"] },
],
},
{
"Fn::Or": [
{ "Fn::Equals": [{ "Ref": "AWS::Region" }, "completely-made-up-region"] },
{ "Fn::Equals": [{ "Ref": "AWS::Region" }, "completely-made-up-region"] },
],
},
],
},
},
"Resources": {
"Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": {
"Fn::If": [
"AlwaysTrueCond",
"MyBucketName",
{ "Ref": "AWS::NoValue" },
],
},
},
},
},
});
});
test('can ingest a template with the short form Conditions', () => {
includeTestTemplate(stack, 'short-form-conditions.yaml');
Template.fromStack(stack).templateMatches({
"Conditions": {
"AlwaysTrueCond": {
"Fn::Not": [
{ "Fn::Equals": [{ "Ref": "AWS::Region" }, "completely-made-up-region1"] },
],
},
"AnotherAlwaysTrueCond": {
"Fn::Not": [
{ "Fn::Equals": [{ "Ref": "AWS::Region" }, "completely-made-up-region2"] },
],
},
"ThirdAlwaysTrueCond": {
"Fn::Not": [
{ "Fn::Equals": [{ "Ref": "AWS::Region" }, "completely-made-up-region3"] },
],
},
"CombinedCond": {
"Fn::Or": [
{ "Condition": "AlwaysTrueCond" },
{ "Condition": "AnotherAlwaysTrueCond" },
{ "Condition": "ThirdAlwaysTrueCond" },
],
},
},
"Resources": {
"Bucket": {
"Type": "AWS::S3::Bucket",
"Properties": {
"BucketName": {
"Fn::If": [
"CombinedCond",
"MyBucketName",
{ "Ref": "AWS::NoValue" },
],
},
},
},
},
});
});
test('can ingest a yaml with long-form functions and output it unchanged', () => {
includeTestTemplate(stack, 'long-form-subnet.yaml');
Template.fromStack(stack).templateMatches(
loadTestFileToJsObject('long-form-subnet.yaml'),
);
});
test('can ingest a YAML template with Fn::Sub in string form and output it unchanged', () => {
includeTestTemplate(stack, 'short-form-fnsub-string.yaml');
Template.fromStack(stack).templateMatches(
loadTestFileToJsObject('short-form-fnsub-string.yaml'),
);
});
test('can ingest a YAML template with Fn::Sub in map form and output it unchanged', () => {
includeTestTemplate(stack, 'short-form-sub-map.yaml');
Template.fromStack(stack).templateMatches(
loadTestFileToJsObject('short-form-sub-map.yaml'),
);
});
test('can correctly substitute values inside a string containing JSON passed to Fn::Sub', () => {
const cfnInclude = includeTestTemplate(stack, 'json-in-fn-sub.yaml', {
Stage: 'test',
});
const dashboard = cfnInclude.getResource('Dashboard') as cloudwatch.CfnDashboard;
// we need to resolve the Fn::Sub expression to get to its argument
const resolvedDashboardBody = stack.resolve(dashboard.dashboardBody)['Fn::Sub'];
expect(JSON.parse(resolvedDashboardBody)).toStrictEqual({
"widgets": [
{
"type": "text",
"properties": {
"markdown": "test test",
},
},
{
"type": "text",
"properties": {
"markdown": "test test",
},
},
],
});
});
test('the parser throws an error on a YAML template with short form import value that uses short form sub', () => {
expect(() => {
includeTestTemplate(stack, 'invalid/short-form-import-sub.yaml');
}).toThrow(/A node can have at most one tag/);
});
});
function includeTestTemplate(scope: constructs.Construct, testTemplate: string, parameters?: { [key: string]: string }): inc.CfnInclude {
return new inc.CfnInclude(scope, 'MyScope', {
templateFile: _testTemplateFilePath(testTemplate),
parameters,
});
}
function loadTestFileToJsObject(testTemplate: string): any {
return futils.readYamlSync(_testTemplateFilePath(testTemplate));
}
function _testTemplateFilePath(testTemplate: string) {
return path.join(__dirname, 'test-templates/yaml', testTemplate);
} | the_stack |
import * as React from 'react';
import { StyleSheet, TextStyle, View, ViewStyle } from 'react-native';
import { toArray } from '../../_utils';
import MDPicker from '../picker/index';
export interface IMDDatePickerProps {
style?: ViewStyle;
type?: 'date' | 'time' | 'datetime' | 'custom';
customTypes?: Array<'yyyy' | 'MM' | 'dd' | 'hh' | 'mm'>;
minDate?: Date;
maxDate?: Date;
defaultDate?: Date;
minuteStep?: number;
unitText?: string[];
todayText?: string;
textRender?: () => string | undefined;
onChange?: (
columnIndex: number,
itemIndex: number,
value: { text: string; value: any; typeFormat: any }
) => void;
onConfirm?: (
columnsValue: Array<{ text: string; value: any; typeFormat: any }>
) => void;
onShow?: () => void;
onHide?: () => void;
onCancel?: () => void;
isView?: boolean;
isVisable?: boolean;
title?: string;
describe?: string;
okText?: string;
cancelText?: string;
maskClosable?: boolean;
}
export interface IMDDatePickerState {
isPickerShow: boolean;
columnData: any[];
columnDataDefault: any[];
}
// yyyy-MM-dd hh:mm:ss => Year-Month-Date Hour:Minute
const TYPE_FORMAT: { [key: string]: string } = {
yyyy: 'Year',
MM: 'Month',
dd: 'Date',
hh: 'Hour',
mm: 'Minute',
};
const TYPE_FORMAT_INVERSE: { [key: string]: string } = {
Year: 'yyyy',
Month: 'MM',
Date: 'dd',
Hour: 'hh',
Minute: 'mm',
};
const TYPE_METHODS: { [key: string]: string } = {
Year: 'getFullYear',
Month: 'getMonth',
Date: 'getDate',
Hour: 'getHours',
Minute: 'getMinutes',
};
export default class MDDatePicker extends React.Component<
IMDDatePickerProps,
IMDDatePickerState
> {
public static defaultProps = {
type: 'date',
customTypes: [],
minuteStep: 1,
unitText: ['年', '月', '日', '时', '分'],
todayText: '',
textRender: '',
isVisable: false,
isView: false,
maskClosable: true,
};
constructor (props: IMDDatePickerProps) {
super(props);
this.state = {
isPickerShow: false,
columnData: [],
columnDataDefault: [],
};
}
private picker = React.createRef<MDPicker>();
private currentDateIns = new Date();
private columnData: any[] = [];
private oldColumnData: any = null;
private columnDataDefault: number[] = [];
private columnDataGenerator: Array<{ generator: any; type: string }> = [];
public componentDidMount () {
this.initPicker();
}
public componentWillReceiveProps (nextProps: IMDDatePickerProps) {
if (nextProps.isVisable !== this.props.isVisable) {
this.setState({
isPickerShow: !!nextProps.isVisable,
});
}
if (
nextProps.defaultDate !== this.props.defaultDate ||
nextProps.minDate !== this.props.minDate ||
nextProps.maxDate !== this.props.maxDate
) {
this.initPickerColumn();
}
}
public render () {
const { style, okText, cancelText, title, isView } = this.props;
const { isPickerShow, columnData, columnDataDefault } = this.state;
return (
<View
style={[
{
justifyContent: 'center',
},
style,
]}
>
<MDPicker
ref={this.picker}
defaultValue={columnDataDefault}
isView={isView}
data={columnData}
cols={columnData.length}
pickerHeight={200}
pickerWidth={350}
itemHeight={40}
isVisible={isPickerShow}
okText={okText}
cancelText={cancelText}
title={title}
onChange={this.onPickerChange.bind(this)}
onCancel={this.onPickerCancel.bind(this)}
onConfirm={this.onPickerConfirm.bind(this)}
onHide={this.onPickerHide.bind(this)}
onShow={this.onPickerShow.bind(this)}
/>
</View>
);
}
public getFormatDate (format = 'yyyy-MM-dd hh:mm'): string {
if (!this.picker.current) {
return '';
}
const columnValues = this.picker.current.getColumnValues();
columnValues.forEach((item) => {
if (!item) {
return;
}
let value = item.value;
if (value < 10) {
value = '0' + value;
}
format = format.replace(item.type, value);
format = format.replace(TYPE_FORMAT_INVERSE[item.type], value);
});
return format;
}
public getColumnValue (index: number): any {
if (this.picker.current) {
return this.picker.current.getColumnValue(index);
}
return;
}
public getColumnValues (): any[] {
if (this.picker.current) {
return this.picker.current.getColumnValues();
}
return [];
}
public getColumnIndex (index: number): number {
if (this.picker.current) {
return this.picker.current.getColumnIndex(index);
}
return 0;
}
public getColumnIndexs (): number[] {
if (this.picker.current) {
return this.picker.current.getColumnIndexs();
}
return [];
}
private currentYear () {
return this.currentDateIns.getFullYear();
}
private currentMonth () {
return this.currentDateIns.getMonth() + 1;
}
private currentDate () {
return this.currentDateIns.getDate();
}
private currentHours () {
return this.currentDateIns.getHours();
}
private currentMinutes () {
return this.currentDateIns.getMinutes();
}
private initPicker () {
if (!this.props.isView && this.props.isVisable) {
this.setState({
isPickerShow: this.props.isVisable,
});
}
// this.picker.inheritPickerApi(this);
this.initPickerColumn();
}
private initPickerColumn () {
this.resetPickerColumn();
this.initColumnDataGenerator();
this.initColumnData(0, this.columnDataDefault);
}
private resetPickerColumn () {
this.setState({
columnData: [],
columnDataDefault: [],
});
this.oldColumnData = null;
this.columnData = [];
this.columnDataDefault = [];
this.columnDataGenerator = [];
}
private setPickerColumnState () {
this.setState({
columnData: this.columnData,
columnDataDefault: this.columnDataDefault,
});
}
private initColumnData (
columnIndex: number,
defaultDates: any[] = [],
isSetColumn = true
) {
const columnData = this.columnData;
const columnDataGenerator = this.columnDataGenerator;
for (let i = columnIndex, len = columnDataGenerator.length; i < len; i++) {
// Collect parameters for columnDataGenerator
const columnDataGeneratorParams = [];
const generator = columnDataGenerator[i];
for (let j = 0; j < i; j++) {
const _generator = columnDataGenerator[j];
if (defaultDates[j] && _generator) {
columnDataGeneratorParams.push({
type: _generator.type,
value: defaultDates[j],
});
continue;
}
let itemIndex = 0;
if (this.picker.current) {
itemIndex = this.picker.current.getColumnIndex(j) || 0;
}
if (this.state.columnData[j]) {
columnDataGeneratorParams.push(this.state.columnData[j][itemIndex]);
} else {
columnDataGeneratorParams.push('');
// warn(`DatePicker columnData of index ${j} is void`);
}
}
// Generator colume data with columnDataGeneratorParams
const curColumnData = generator
? generator.generator.apply(this, columnDataGeneratorParams)
: '';
// set picker column data & refresh picker
if (this.picker.current) {
isSetColumn && this.picker.current.setColumnValues(i, curColumnData);
}
// store column date
this.columnData[i] = curColumnData;
this.setPickerColumnState();
}
// isSetColumn && this.picker.current.refresh(null, columnIndex);
}
private initColumnDataGenerator () {
const defaultDate = this.getDefaultDate();
switch (this.props.type) {
case 'date':
this.initColumnDataGeneratorForDate(defaultDate);
break;
case 'time':
this.initColumnDataGeneratorForTime(defaultDate);
break;
case 'datetime':
this.initColumnDataGeneratorForDate(defaultDate);
this.initColumnDataGeneratorForTime(defaultDate);
break;
default:
this.initColumnDataGeneratorForCustom(defaultDate);
break;
}
}
private initColumnDataGeneratorForDate (defaultDate?: Date) {
this.columnDataGenerator = this.columnDataGenerator.concat([
{ generator: this.generateYearData, type: 'Year' },
{ generator: this.generateMonthData, type: 'Month' },
{ generator: this.generateDateData, type: 'Date' },
]);
this.columnDataDefault = defaultDate
? this.columnDataDefault.concat([
defaultDate.getFullYear(),
defaultDate.getMonth() + 1,
defaultDate.getDate(),
])
: [];
}
private initColumnDataGeneratorForTime (defaultDate?: Date) {
this.columnDataGenerator = this.columnDataGenerator.concat([
{ generator: this.generateHourData, type: 'Hour' },
{ generator: this.generateMinuteData, type: 'Minute' },
]);
this.columnDataDefault = defaultDate
? this.columnDataDefault.concat([
defaultDate.getHours(),
defaultDate.getMinutes(),
])
: [];
}
private initColumnDataGeneratorForCustom (defaultDate?: Date) {
this.props.customTypes!.forEach((type: string) => {
type = TYPE_FORMAT[type] || type;
this.columnDataGenerator.push({
// @ts-ignore
generator: this[`generate${type}Data`],
type,
});
if (defaultDate) {
// @ts-ignore defaultDate['getFullYear']()
let value = defaultDate[TYPE_METHODS[type]]();
if (type === 'Month') {
value += 1;
}
this.columnDataDefault.push(value);
}
});
}
private getDefaultDate (): Date | undefined {
const defaultDate = this.props.defaultDate;
const minDate = this.props.minDate;
const maxDate = this.props.maxDate;
if (!defaultDate) {
return defaultDate;
}
if (minDate && defaultDate.getTime() < minDate.getTime()) {
return minDate;
}
if (maxDate && defaultDate.getTime() > maxDate.getTime()) {
return maxDate;
}
return defaultDate;
}
private getGeneratorArguments (
args: Array<{ type: string; value: number }>
): { [key: string]: number } {
const defaultArguments: { [key: string]: number } = {
Year: this.currentYear(),
Month: this.currentMonth(),
Date: this.currentDate(),
Hour: this.currentHours(),
Minute: this.currentMinutes(),
};
args.map((item) => {
defaultArguments[item.type] = item.value;
});
return defaultArguments;
}
private generateYearData () {
const start = this.props.minDate
? this.props.minDate.getFullYear()
: this.currentYear() - 20;
const end = this.props.maxDate
? this.props.maxDate.getFullYear()
: this.currentYear() + 20;
if (start > end) {
// warn('MinDate Year should be earlier than MaxDate');
return;
}
return this.generateData(start, end, 'Year', this.props.unitText![0], 1);
}
private generateMonthData () {
// @ts-ignore
const args = this.getGeneratorArguments(toArray(arguments));
let start;
let end;
if (
this.props.minDate &&
this.isDateTimeEqual(this.props.minDate, args.Year)
) {
start = this.props.minDate.getMonth() + 1;
} else {
start = 1;
}
if (
this.props.maxDate &&
this.isDateTimeEqual(this.props.maxDate, args.Year)
) {
end = this.props.maxDate.getMonth() + 1;
} else {
end = 12;
}
return this.generateData(
start,
end,
'Month',
this.props.unitText![1] || '',
1,
arguments
);
}
private generateDateData () {
// @ts-ignore
const args = this.getGeneratorArguments(toArray(arguments));
let start;
let end;
if (
this.props.minDate &&
this.isDateTimeEqual(this.props.minDate, args.Year, args.Month)
) {
start = this.props.minDate.getDate();
} else {
start = 1;
}
if (
this.props.maxDate &&
this.isDateTimeEqual(this.props.maxDate, args.Year, args.Month)
) {
end = this.props.maxDate.getDate();
} else {
end = new Date(args.Year, args.Month, 0).getDate();
}
const dateData = this.generateData(
start,
end,
'Date',
this.props.unitText![2] || '',
1,
arguments
);
if (
this.isDateTimeEqual(this.currentDateIns, args.Year, args.Month) &&
this.currentDate() >= start &&
this.currentDate() <= end &&
this.props.todayText
) {
const currentDateIndex = this.currentDate() - start;
const currentDate = dateData[currentDateIndex].text;
dateData[currentDateIndex].text = this.props.todayText.replace(
'&',
currentDate
);
}
return dateData;
}
private generateHourData () {
// @ts-ignore
const args = this.getGeneratorArguments(toArray(arguments));
let start;
let end;
if (
this.props.minDate &&
this.isDateTimeEqual(this.props.minDate, args.Year, args.Month, args.Date)
) {
start = this.props.minDate.getHours();
} else {
start = 0;
}
if (
this.props.maxDate &&
this.isDateTimeEqual(this.props.maxDate, args.Year, args.Month, args.Date)
) {
end = this.props.maxDate.getHours();
} else {
end = 23;
}
if (end < start) {
end = 23;
}
if (start > end) {
// warn('MinDate Hour should be earlier than MaxDate');
return;
}
return this.generateData(
start,
end,
'Hour',
this.props.unitText![3] || '',
1,
arguments
);
}
private generateMinuteData () {
// @ts-ignore
const args = this.getGeneratorArguments(toArray(arguments));
let start;
let end;
if (
this.props.minDate &&
this.isDateTimeEqual(
this.props.minDate,
args.Year,
args.Month,
args.Date,
args.Hour
)
) {
start = this.props.minDate.getMinutes();
} else {
start = 0;
}
if (
this.props.maxDate &&
this.isDateTimeEqual(
this.props.maxDate,
args.Year,
args.Month,
args.Date,
args.Hour
)
) {
end = this.props.maxDate.getMinutes();
} else {
end = 59;
}
return this.generateData(
start,
end,
'Minute',
this.props.unitText![4] || '',
this.props.minuteStep,
arguments
);
}
private generateData (
from: number,
to: number,
type: string,
unit: string,
step = 1,
args: any = []
) {
let count = from;
let text;
const data = [];
const defaultArgs = toArray(args).map((item) => {
return typeof item === 'object' ? item.value : item;
});
while (count <= to) {
if (this.props.textRender) {
// @ts-ignore
text = this.props.textRender.apply(this, [
TYPE_FORMAT_INVERSE[type],
...defaultArgs,
count,
]);
}
data.push({
text: text || `${count}${unit}`,
value: count,
typeFormat: TYPE_FORMAT_INVERSE[type] || type,
type,
});
count += step;
}
return data;
}
/**
* Determine whether year, month, date, etc of
* the current date are equal to the given value
* @params Date
* @params year, month, date ...
*/
private isDateTimeEqual (date?: Date, ...args: number[]) {
const methods = Object.keys(TYPE_METHODS).map((key: string) => {
return TYPE_METHODS[key];
});
let res = true;
if (!date) {
return (res = false);
}
for (let i = 0; i < args.length; i++) {
const methodName = methods[i];
// @ts-ignore date['getFullYear']()
const curVal = date[methodName]() + Number(methodName === 'getMonth');
const targetVal = +args[i];
if (curVal !== targetVal) {
res = false;
break;
}
}
return res;
}
private transHourTo12 (hour: number) {
if (hour < 12) {
return {
hour,
ap: 0, // 0 a.m, 1 p.m
};
} else {
return {
hour: hour - 12,
ap: 1, // 0 a.m, 1 p.m
};
}
}
// MARK: events handler
private onPickerShow () {
this.oldColumnData = [...this.state.columnData];
// this.setState({
// oldColumnData,
// });
this.props.onShow && this.props.onShow();
}
private onPickerHide () {
this.props.onHide && this.props.onHide();
}
private onPickerChange (columnIndex: number, itemIndex: any, value: any) {
this.props.onChange && this.props.onChange(columnIndex, itemIndex, value);
if (columnIndex < this.state.columnData.length - 1) {
this.initColumnData(columnIndex + 1);
}
}
private onPickerConfirm (columnsValue: any) {
this.props.onConfirm && this.props.onConfirm(columnsValue);
}
private onPickerCancel () {
this.props.onCancel && this.props.onCancel();
if (this.oldColumnData) {
this.columnData = [...this.oldColumnData];
this.setState({
columnData: this.columnData,
});
}
}
} | the_stack |
import { Component, OnInit, OnDestroy } from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {Subscription} from 'rxjs/Subscription';
import { environment } from './../../../../../environments/environment';
import {WorkflowService} from '../../../../core/services/workflow.service';
import {LoggerService} from '../../../../shared/services/logger.service';
import { CommonResponseService } from '../../../../shared/services/common-response.service';
import {DataCacheService} from '../../../../core/services/data-cache.service';
import { FormService } from '../../../../shared/services/form.service';
import {FilterManagementService} from '../../../../shared/services/filter-management.service';
import {ErrorHandlingService} from '../../../../shared/services/error-handling.service';
import {AssetGroupObservableService} from '../../../../core/services/asset-group-observable.service';
import {DomainTypeObservableService} from '../../../../core/services/domain-type-observable.service';
import {UtilsService} from '../../../../shared/services/utils.service';
import {RouterUtilityService} from '../../../../shared/services/router-utility.service';
import { FormGroup, FormControl, Validators, NgForm } from '@angular/forms';
import {RefactorFieldsService} from '../../../../shared/services/refactor-fields.service';
@Component({
selector: 'app-plugin-management-details',
templateUrl: './plugin-management-details.component.html',
styleUrls: ['./plugin-management-details.component.css']
})
export class PluginManagementDetailsComponent implements OnInit, OnDestroy {
pageTitle: String = 'Plugin Management Details';
breadcrumbDetails = {
breadcrumbArray: ['Admin', 'Plugin Management'],
breadcrumbLinks: ['policies', 'plugin-management'],
breadcrumbPresent: 'Details'
};
backButtonRequired: boolean;
pageLevel = 0;
errorValue = 0;
agAndDomain = {};
tableSubscription: Subscription;
pluginId;
formData;
isFilterRquiredOnPage = false;
appliedFilters = {
queryParamsWithoutFilter: {}, /* Stores the query parameter ibject without filter */
pageLevelAppliedFilters: {} /* Stores the query parameter ibject without filter */
};
filterArray = []; /* Stores the page applied filter array */
// Reactive-forms
private pluginManagementForm: FormGroup;
public formErrors = {};
public formGroup = {};
private FetchedPlugin;
errorMessage = 'apiResponseError';
routeSubscription: Subscription;
constructor(private router: Router,
private activatedRoute: ActivatedRoute,
private workflowService: WorkflowService,
private logger: LoggerService,
private dataStore: DataCacheService,
private commonResponseService: CommonResponseService,
private filterManagementService: FilterManagementService,
private errorHandling: ErrorHandlingService,
private assetGroupObservableService: AssetGroupObservableService,
private domainObservableService: DomainTypeObservableService,
private utils: UtilsService,
private routerUtilityService: RouterUtilityService,
private refactorFieldsService: RefactorFieldsService,
private formService: FormService) {
this.assetGroupObservableService.getAssetGroup().subscribe(
assetGroupName => {
this.backButtonRequired = this.workflowService.checkIfFlowExistsCurrently(this.pageLevel);
});
}
ngOnInit() {
this.reset();
this.init();
}
reset() {
/* Reset the page */
this.filterArray = [];
}
init() {
/* Initialize */
this.routerParam();
this.routeSubscription = this.activatedRoute.params.subscribe(params => {
// Fetch the required params from this object.
this.pluginId = params.pluginId;
});
this.updateComponent();
}
updateComponent() {
/* Updates the whole component */
this.getData();
}
getData() {
try {
if (this.tableSubscription) {
this.tableSubscription.unsubscribe();
}
const payload = {};
const queryParams = {
pluginId: this.pluginId
};
this.errorValue = 0;
const pluginUrl = environment.getPlugins.url;
const pluginMethod = environment.getPlugins.method;
this.tableSubscription = this.commonResponseService
.getData(pluginUrl, pluginMethod, payload, queryParams)
.subscribe(
response => {
try {
const plugin = response.plugins;
if (this.utils.checkIfAPIReturnedDataIsEmpty(plugin)) {
this.errorValue = -1;
this.errorMessage = 'noDataAvailable';
return;
}
this.FetchedPlugin = plugin[0];
this.buildForm(this.FetchedPlugin);
this.errorValue = 1;
} catch (e) {
this.errorValue = -1;
this.errorMessage = 'jsError';
}
},
error => {
this.errorValue = -1;
this.errorMessage = 'apiResponseError';
}
);
} catch (error) {
this.errorValue = -1;
this.logger.log('error', error);
this.errorMessage = 'jsError';
}
}
buildForm(plugin) {
const pluginName = plugin.pluginName;
const pluginDetails = plugin.pluginDetails;
this.formData = [];
this.formGroup = {};
const pluginNameFieldObj = {
formControlName: 'pluginName',
formControlDisplayName: 'Plugin Name'
};
this.formGroup['pluginName'] = new FormControl(pluginName, Validators.required);
this.formErrors['pluginName'] = '';
this.formData.push(pluginNameFieldObj);
for (let i = 0; i < pluginDetails.length; i++) {
const individualPluginField = {
formControlName: pluginDetails[i].key,
formControlDisplayName:
this.refactorFieldsService.getDisplayNameForAKey(
pluginDetails[i].key.toLocaleLowerCase()
) || pluginDetails[i].key
};
this.formData.push(individualPluginField);
this.formGroup[pluginDetails[i].key] = new FormControl(pluginDetails[i].value, Validators.required);
this.formErrors[pluginDetails[i].key] = '';
}
this.pluginManagementForm = new FormGroup(this.formGroup);
this.pluginManagementForm.valueChanges.subscribe((data) => {
this.formErrors = this.formService.validateForm(this.pluginManagementForm, this.formErrors, true);
});
}
register(myForm: NgForm) {
// mark all fields as touched
this.formService.markFormGroupTouched(this.pluginManagementForm);
if (this.pluginManagementForm.valid) {
this.operateList(myForm.value);
}
}
operateList(updatedValues) {
{
/* Update the value of inputfileds */
try {
const existingPluginObj = this.FetchedPlugin;
existingPluginObj.pluginName = updatedValues.pluginName;
const updatedPluginDetailsObj = existingPluginObj.pluginDetails.map((pluginDetailField, index) => {
const key = pluginDetailField.key;
pluginDetailField.value = updatedValues[key] || pluginDetailField.value;
return pluginDetailField;
});
existingPluginObj.pluginDetails = updatedPluginDetailsObj;
const payload = {
'plugins' : [existingPluginObj]
};
if (this.tableSubscription) {
this.tableSubscription.unsubscribe();
}
const queryParams = {};
const pluginUrl = environment.postPlugins.url;
const pluginMethod = environment.postPlugins.method;
this.errorValue = 0;
this.tableSubscription = this.commonResponseService
.getData(pluginUrl, pluginMethod, payload, queryParams)
.subscribe(
response => {
try {
this.errorValue = 2;
} catch (e) {
this.logger.log('error', 'JS error in update plugin');
this.errorMessage = 'jsError';
this.errorValue = -1;
}
},
error => {
this.logger.log('error', 'Error in update plugin - ' + error);
this.errorMessage = error;
this.errorValue = -1;
}
);
} catch (error) {
this.logger.log('error', error);
}
}
}
takeActionPostTransaction(event) {
if (event === 'back') {
this.backToEditOrCreate();
} else {
this.navigateToOrigin();
}
}
navigateToOrigin() {
this.router.navigate(['pl/admin/plugin-management'], {
queryParamsHandling: 'merge',
queryParams: {
}
});
}
navigateBack() {
try {
this.workflowService.goBackToLastOpenedPageAndUpdateLevel(this.router.routerState.snapshot.root);
} catch (error) {
this.logger.log('error', error);
}
}
backToEditOrCreate() {
this.errorValue = 1;
}
routerParam() {
try {
/* Check query parameters */
const currentQueryParams = this.routerUtilityService.getQueryParametersFromSnapshot(this.router.routerState.snapshot.root);
if (currentQueryParams) {
this.appliedFilters.queryParamsWithoutFilter = JSON.parse(JSON.stringify(currentQueryParams));
delete this.appliedFilters.queryParamsWithoutFilter['filter'];
this.appliedFilters.pageLevelAppliedFilters = this.utils.processFilterObj(currentQueryParams);
this.filterArray = this.filterManagementService.getFilterArray(this.appliedFilters.pageLevelAppliedFilters);
}
} catch (error) {
this.logger.log('error', error);
}
}
updateUrlWithNewFilters(filterArr) {
this.appliedFilters.pageLevelAppliedFilters = this.utils.arrayToObject(
this.filterArray,
'filterkey',
'value'
); // <-- TO update the queryparam which is passed in the filter of the api
this.appliedFilters.pageLevelAppliedFilters = this.utils.makeFilterObj(this.appliedFilters.pageLevelAppliedFilters);
/**
* To change the url
* with the deleted filter value along with the other existing paramter(ex-->tv:true)
*/
const updatedFilters = Object.assign(
this.appliedFilters.pageLevelAppliedFilters,
this.appliedFilters.queryParamsWithoutFilter
);
/*
Update url with new filters
*/
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: updatedFilters
}).then(success => {
this.routerParam();
});
}
getMessages(errorValue) {
// error value = 2 -> Success
// error value = -1 -> Error
const obj = {
type: '',
title: '',
message: ''
};
if (this.errorValue === 2) {
obj.type = 'success';
obj.title = 'Success!';
obj.message = 'You have succesfully updated plugin: ' + this.pluginId;
} else if (this.errorValue === -1) {
obj.type = 'error';
obj.title = 'Error!';
obj.message = 'Updating account :' + this.pluginId;
}
return obj;
}
ngOnDestroy() {
try {
if (this.tableSubscription) {
this.tableSubscription.unsubscribe();
}
} catch (error) {
this.logger.log('error', 'JS Error - ' + error);
}
}
} | the_stack |
import { Component, OnInit, Input, NgZone, ViewChild, ElementRef, OnChanges, SimpleChanges, OnDestroy, AfterViewInit } from '@angular/core';
import { AutorefreshService } from '../../services/autorefresh.service';
import * as d3 from 'd3-selection';
import * as d3Shape from 'd3-shape';
import * as d3Scale from 'd3-scale';
import * as d3Array from 'd3-array';
import * as d3Axis from 'd3-axis';
@Component({
selector: 'app-quarter-graph',
templateUrl: './quarter-graph.component.html',
styleUrls: ['./quarter-graph.component.css'],
providers: [AutorefreshService]
})
export class QuarterGraphComponent implements OnInit, OnChanges, OnDestroy, AfterViewInit {
@Input() graphWidth: any;
@Input() graphHeight: any = 90;
@Input() xAxisValues: any;
@Input() smoothEdge: any;
@Input() yAxisLabel: any;
@Input() axisUnit: any;
@Input() dataResponse: any;
@Input() verticalLines: any;
@Input() idUnique: any;
@Input() colorSet: any = ['#645ec5', '#26ba9d', '#289cf7'];
@Input() multipleData: any;
@Input() targetType: any;
@Input() yCoordinates: any;
@Input() colorSetLegends: any;
durationParams: any;
autoRefresh: boolean;
@ViewChild('widgetQuarter') widgetContainer: ElementRef;
private margin = {top: 15, right: 20, bottom: 30, left: 60};
// Lowest and Highest Line in the graph
private lowerLine: any;
private lowerLineIndex: any = 0;
private higherLine: any;
private higherLineIndex: any = 1;
// Smaller and longer line (to help plot the area between the bottom and top lines)
private smallerLine: any;
private longerLine: any;
private width: number;
private timeLineWidth: number;
private height: number;
private areaLower: any;
private x: any;
private y: any;
private svg: any;
private line: d3Shape.Line<[number, number]>;
private combinedData: any = [];
private data: any;
private focus: any;
bisectDate: any;
focusContent: any;
i: any;
legendHover: any = [];
searchAnObjectFromArray: any;
tickValues: any;
curveBasis: any;
tickUnit: any;
showdata = false;
wholeData: any = {};
legendsvalue: any = [];
interval: any;
nonZeroValues: any = [];
private graphData: any = [];
private error = false;
private dataLoaded = false;
private autorefreshInterval;
constructor(private ngZone: NgZone,
private autorefreshService: AutorefreshService) {
window.onresize = (e) => {
// ngZone.run will help to run change detection
this.ngZone.run(() => {
this.graphWidth = parseInt(window.getComputedStyle(this.widgetContainer.nativeElement, null).getPropertyValue('width'), 10);
this.resizeGraph();
});
};
this.durationParams = this.autorefreshService.getDuration();
this.durationParams = parseInt(this.durationParams, 10);
this.autoRefresh = this.autorefreshService.autoRefresh;
}
ngAfterViewInit() {
const afterLoad = this;
if (this.autoRefresh !== undefined) {
if ((this.autoRefresh === true ) || (this.autoRefresh.toString() === 'true')) {
this.autorefreshInterval = setInterval(function() {
afterLoad.ngOnInit();
}, this.durationParams);
}
}
}
plotGraph() {
const idValue = this.idUnique;
const uniqueId = document.getElementById(idValue);
if (uniqueId != null) {
this.initSvg();
this.initComponents();
this.computeLowerAndHigherLines();
this.formatDataForArea();
this.drawAxisAndGrid();
this.drawLine();
}
}
init() {
if (this.dataResponse ) {
this.nonZeroValues = [];
this.dataLoaded = true;
this.error = false;
for ( let i = 0 ; i < this.dataResponse.length; i++) {
for ( let q = 0; q < this.dataResponse[i].values.length; q++) {
if (this.dataResponse[i].values[q].value === -1) {
this.dataResponse[i].values[q].value = 0;
}
}
}
this.graphData = this.dataResponse;
for ( let j = 0; j < this.graphData.length; j++) {
const nonZeroArray = [];
for ( let t = 0; t < this.graphData[j].values.length; t++) {
if (this.graphData[j].values[t].value !== -1) {
nonZeroArray.push(this.graphData[j].values[t]);
}
}
const objData = {
'values': nonZeroArray
};
this.nonZeroValues.push(objData);
}
this.nonZeroValues = this.nonZeroValues.splice(0, 1);
this.graphData = this.nonZeroValues;
if (this.graphWidth > 262) {
this.graphWidth = 200;
}
this.width = this.graphWidth - this.margin.left - this.margin.right ;
if (this.width < 1) {
this.width = 1;
}
this.timeLineWidth = this.width * 1;
this.height = this.graphHeight - this.margin.top - this.margin.bottom;
// To remove the graph content if its present before re-plotting
this.removeGraphSvg();
// Plot the graph and do all associated processes
this.plotGraph();
}
}
ngOnChanges(changes: SimpleChanges) {
const graphDataChange = changes['dataResponse'];
if (graphDataChange) {
const cur = JSON.stringify(graphDataChange.currentValue);
const prev = JSON.stringify(graphDataChange.previousValue);
if ((cur !== prev) && (this.dataResponse)) {
this.init();
}
}
}
resizeGraph() {
if (this.dataResponse) {
// Reset the dimensions
if (this.graphWidth > 262) {
this.graphWidth = 200;
}
if (this.graphWidth < 1) {
this.graphWidth = 40;
}
this.width = this.graphWidth - this.margin.left - this.margin.right ;
if (this.width < 1 ) {
this.width = 1;
}
this.timeLineWidth = this.width * 1;
this.height = this.graphHeight - this.margin.top - this.margin.bottom;
// To remove the graph content if its present before re-plotting
this.removeGraphSvg();
// Plot the graph and do all associated processes
this.plotGraph();
}
}
removeGraphSvg() {
const idValue = this.idUnique;
const uniqueId = document.getElementById(idValue);
if (d3.select(uniqueId).select('g') !== undefined) {
d3.select(uniqueId).select('g').remove();
d3.select(uniqueId).append('g');
}
}
ngOnInit() {
this.init();
}
private initSvg() {
const idValue = this.idUnique;
const uniqueId = document.getElementById(idValue);
if (this.graphWidth < 1) {
this.graphWidth = 40;
}
d3.select(uniqueId).select('svg').attr('width', this.graphWidth);
d3.select(uniqueId).select('svg').attr('height', this.graphHeight);
if (this.graphWidth > 262) {
this.svg = d3.select(uniqueId)
.select('svg')
.append('g')
.attr('transform', 'translate(' + 30 + ',' + (-this.margin.bottom) + ')');
} else {
this.svg = d3.select(uniqueId)
.select('svg')
.append('g')
.attr('transform', 'translate(' + 40 + ',' + (-this.margin.bottom) + ')');
}
}
private initComponents() {
this.data = this.graphData.map((v) => v.values.map((z) => z.date ))[0];
this.x = d3Scale.scaleTime().range([0, this.width]);
this.y = d3Scale.scaleLinear().range([this.height, 0]);
this.x.domain(d3Array.extent(this.data, (d: Date) => d ));
this.y.domain([
0,
d3Array.max(this.graphData, function(c) { return d3Array.max(c[`values`], function(d) { return d[`value`]; }); })
]);
this.svg.append('defs').append('clipPath')
.attr('id', 'clip')
.append('rect')
.attr('width', 0)
.attr('height', this.height);
this.focus = this.svg.append('g')
.attr('class', 'focus')
.attr('transform', 'translate(0,' + ( 2 * this.margin.top + 40) + ')');
}
private computeLowerAndHigherLines() {
// Computing the Lowest / Highest line and their indices respectively
this.lowerLine = this.graphData[0];
for ( let i = 0 ; i < this.graphData.length; i++) {
if (this.graphData[i][`values`].length < this.lowerLineIndex) {
this.lowerLineIndex = i;
} else {
if (this.graphData[i][`values`].length > this.higherLineIndex) {
this.higherLineIndex = i;
}
}
}
this.lowerLine = this.graphData[this.lowerLineIndex];
this.higherLine = this.graphData[this.higherLineIndex];
if ((this.lowerLine !== undefined) && (this.higherLine !== undefined)) {
if (this.lowerLine[`values`].length > this.higherLine[`values`].length) {
this.smallerLine = this.higherLine;
this.longerLine = this.lowerLine;
} else {
this.smallerLine = this.lowerLine;
this.longerLine = this.higherLine;
}
}
}
private formatDataForArea() {
// Merging the data of top and bottom lines to supply to plot shaded area
// between top and bottom graph lines
this.combinedData = [];
if (this.smallerLine !== undefined) {
for ( let i = 0; i < this.smallerLine[`values`].length; i++) {
const lowerX = new Date(this.smallerLine[`values`][i].date);
let lowerY = 0;
let higherX = 0;
let higherY = 0;
// Forming mm/dd/yyyy of both higher and lower line data points as we cannot directly compare both,
// as time may change in the data point for any given day
const smallerLineDate = new Date(this.smallerLine[`values`][i].date);
const smallerLineFormattedDate = smallerLineDate.getUTCMonth() + '/' + smallerLineDate.getUTCDate() + '/' + smallerLineDate.getUTCFullYear();
for ( let j = 0; j < this.longerLine[`values`].length; j++) {
const longerLineDate = new Date(this.longerLine[`values`][j].date);
const longerLineFormattedDate = longerLineDate.getUTCMonth() + '/' + longerLineDate.getUTCDate() + '/' + longerLineDate.getUTCFullYear();
if (longerLineFormattedDate === smallerLineFormattedDate) {
higherX = this.longerLine[`values`][j].date;
this.longerLine[`values`][j].value === 0 ? higherY = 1 : higherY = this.longerLine[`values`][j].value;
this.smallerLine[`values`][i].value === 0 ? lowerY = 1 : lowerY = this.smallerLine[`values`][i].value;
const obj = {
'x0': higherX,
'x1': lowerX,
'y0': higherY,
'y1': lowerY
};
this.combinedData.push(obj);
break;
}
}
}
}
}
private drawAxisAndGrid() {
// Horizontal Grid Lines
this.svg.append('g')
.attr('class', 'grid horizontal multiline')
.attr('transform', 'translate(0,' + (2 * this.margin.top + 40) + ')')
.call(d3Axis.axisLeft(this.y)
.ticks(3)
.tickSize(-this.width)
.tickFormat(d => '')
);
}
private drawLine() {
this.line = d3Shape.line()
.x( (d: any) => this.x(d.date) )
.y( (d: any) => this.y(d.value) )
.curve(d3Shape.curveBasis);
// Line Graphs
for ( let i = 0; i < this.graphData.length; i++) {
this.focus.append('path')
.datum(this.graphData[i].values)
.attr('clip-path', 'url(#clip)')
.transition()
.duration(2000)
.attr('class', 'line line' + `${ i + 1 }`)
.attr('fill', 'none')
.attr('stroke-width', '1.5px')
.attr('stroke', this.colorSet[i])
.attr('d', this.line);
}
this.areaLower = d3Shape.area()
.x((d: any) => this.x(d.date))
.y0(this.height)
.y1((d: any) => this.y(d.value))
.curve(d3Shape.curveBasis);
// Draw area between the top and bottom lines
this.focus.append('path')
.datum(this.graphData[0]['values'])
.attr('class', 'areaPatchLower')
.attr('fill', '#afd9f9')
.attr('stroke-width', '0.5')
.attr('stroke', '#2c2e3d')
.attr('d', this.areaLower);
d3.selectAll('.ticks');
this.svg.select('#clip rect')
.transition()
.duration(2000)
.attr('width', this.width);
}
ngOnDestroy() {
try {
clearInterval(this.autorefreshInterval);
} catch (error) {
}
}
} | the_stack |
import {Component, ElementRef, Input, OnInit, ViewChild} from '@angular/core'
import {dayIDNow, dayIDToDate} from '../util/time-util'
import {DataStore, DayData} from '../data/data-store'
import {MatDialog} from '@angular/material/dialog'
import {SessionDetailsComponent} from '../session-details/session-details.component'
import Color from 'color'
import {
DayID,
Item,
ItemID,
ItemStatus,
SESSION_TYPE_TO_ICON,
SessionType,
} from '../data/common'
import {DayViewDialogComponent} from '../day-view-dialog/day-view-dialog.component'
import {HomeComponent} from '../home/home.component'
import {ItemDetailsComponent} from '../item-details/item-details.component'
import {QuickQuotaEditComponent} from '../quick-quota-edit/quick-quota-edit.component'
import {AnalyzerProjectionStrategy, DataAnalyzer} from '../data/data-analyzer'
interface Session {
isOnDue: boolean
scheduled: boolean
projected: boolean
type: SessionType
item: Item
count: number
color: Color
done: boolean
itemDone: boolean
}
@Component({
selector: 'app-month-day-view',
templateUrl: './month-day-view.component.html',
styleUrls: ['./month-day-view.component.scss'],
})
export class MonthDayViewComponent implements OnInit {
@Input() dayID = dayIDNow()
@Input() todayDayID = dayIDNow()
@Input() forceDisplayMonth = false
@Input() quota?: number
@Input() useBackwardStrategy = false
@Input() home?: HomeComponent
@ViewChild('background') backgroundRef?: ElementRef
sessions: Session[] = []
private _dayData?: DayData
totalCount = 0
doneCount = 0
constructor(
private readonly dataStore: DataStore,
private readonly dataAnalyzer: DataAnalyzer,
private readonly dialog: MatDialog,
) {
}
/**
* TODO improve:
* Note that this has to be synced up with data store state, otherwise there
* will be inconsistencies
*/
@Input() set dayData(value: DayData) {
if (value !== this._dayData) {
this._dayData = value
this.processData()
}
}
/**
* Called on data store change as well as on data analyzer change.
*/
processData() {
const dayData = this._dayData
if (dayData === undefined) return
this.sessions = []
this.totalCount = 0
this.doneCount = 0
dayData.sessions.forEach((sessions, type) => {
sessions.forEach((count, itemID) => {
const item = this.dataStore.getItem(itemID)
if (item !== undefined) {
this.sessions.push({
isOnDue: this.dataAnalyzer.isItemDueOn(item.id, this.dayID),
scheduled: type === SessionType.SCHEDULED,
projected: type === SessionType.PROJECTED,
type,
item,
count,
color: this.dataStore.getItemColor(item),
done: type === SessionType.COMPLETED,
itemDone: item.status === ItemStatus.COMPLETED,
})
if (type === SessionType.COMPLETED) {
this.doneCount += count
}
this.totalCount += count
}
})
})
const projections = this.dataAnalyzer.getProjections(
this.useBackwardStrategy ? AnalyzerProjectionStrategy.BACKWARD :
AnalyzerProjectionStrategy.FORWARD, this.dayID)
if (projections !== undefined) {
projections.forEach((count, itemID) => {
const item = this.dataStore.getItem(itemID)
if (item !== undefined) {
this.sessions.push({
isOnDue: this.dataAnalyzer.isItemDueOn(item.id, this.dayID),
scheduled: false,
projected: true,
type: SessionType.PROJECTED,
item,
count,
color: this.dataStore.getItemColor(item),
done: false,
itemDone: item.status === ItemStatus.COMPLETED,
})
this.totalCount += count
}
})
}
this.sessions.sort((a, b) => {
if (a.type !== b.type) return a.type - b.type
if (a.count !== b.count) return b.count - a.count
return a.item.name.localeCompare(b.item.name)
})
}
getDate() {
// TODO optimize: cache this evrey time dayID is set
return dayIDToDate(this.dayID)
}
ngOnInit(): void {
}
get isToday() {
return this.todayDayID === this.dayID
}
get isOnOrAfterToday() {
return this.dayID >= this.todayDayID
}
get isBeforeToday() {
return !this.isOnOrAfterToday
}
getDateFormat() {
const date = this.getDate()
if (date.getMonth() === 0 && date.getDate() === 1) {
return 'yyyy'
}
if (date.getDate() === 1) {
return 'MMM'
}
if (this.forceDisplayMonth) {
return 'MMM dd'
}
return 'dd'
}
get isStartOfMonth() {
return this.getDate().getDate() === 1
}
onAddButtonClicked(event: MouseEvent) {
event.preventDefault()
}
addCompletedSession() {
this.addSession(SessionType.COMPLETED)
}
addScheduledSession() {
this.addSession(SessionType.SCHEDULED)
}
addSession(type?: SessionType) {
const dialogRef = this.dialog.open(SessionDetailsComponent, {
width: SessionDetailsComponent.DIALOG_WIDTH,
data: {
isEditing: false,
dayID: this.dayID,
type,
},
hasBackdrop: true,
disableClose: false,
autoFocus: false,
})
}
editQuota() {
const dialogRef = this.dialog.open(QuickQuotaEditComponent, {
width: QuickQuotaEditComponent.DIALOG_WIDTH,
data: {
dayID: this.dayID,
initialValue: this.quota || 0,
},
hasBackdrop: true,
disableClose: false,
autoFocus: false,
})
}
openDayView() {
const dialogRef = this.dialog.open(DayViewDialogComponent, {
width: DayViewDialogComponent.DIALOG_WIDTH,
data: {
dayID: this.dayID,
home: this.home,
},
hasBackdrop: true,
disableClose: false,
autoFocus: false,
})
}
getSessionTypeIcon(type: SessionType): string {
return SESSION_TYPE_TO_ICON[type] || ''
}
getChipColor(session: Session) {
return session.type === SessionType.COMPLETED ? '#00000000' :
session.color.string()
}
markSessionComplete(session: Session) {
this.dataStore.batchEdit(() => {
this.dataStore.removeSession(
this.dayID, session.type, session.item.id, session.count)
this.dataStore.addSession(
this.dayID, SessionType.COMPLETED, session.item.id, session.count)
})
}
editSession(session: Session) {
const dialogRef = this.dialog.open(SessionDetailsComponent, {
width: SessionDetailsComponent.DIALOG_WIDTH,
data: {
isEditing: true,
itemID: session.item.id,
dayID: this.dayID,
count: session.count,
type: session.type,
},
hasBackdrop: true,
disableClose: false,
autoFocus: false,
})
}
editItem(session: Session) {
const {item} = session
const dialogRef = this.dialog.open(ItemDetailsComponent, {
width: ItemDetailsComponent.DIALOG_WIDTH,
data: {item},
hasBackdrop: true,
disableClose: false,
autoFocus: false,
})
}
markSessionScheduled(session: Session) {
this.dataStore.batchEdit(() => {
this.dataStore.removeSession(
this.dayID, session.type, session.item.id, session.count)
this.dataStore.addSession(
this.dayID, SessionType.SCHEDULED, session.item.id, session.count)
})
}
deleteSession(session: Session) {
this.dataStore.removeSession(
this.dayID, session.type, session.item.id, session.count)
}
onSessionDragStart(event: DragEvent, session: Session) {
event.dataTransfer?.setData('text', 'session ' + JSON.stringify(
{
dayID: this.dayID,
itemID: session.item.id,
type: session.type,
count: session.count,
}))
}
onDragReact = (event: DragEvent) => {
const element = this.backgroundRef?.nativeElement
if (element) {
element.style.border = '5px solid #4488ff'
}
}
clearDragReact = () => {
const element = this.backgroundRef?.nativeElement
if (element) {
element.style.border = ''
}
}
onDrop(event: DragEvent) {
const data = event.dataTransfer?.getData('text')
if (!data) return
if (data.startsWith('session ')) {
const {count, dayID, itemID, type}: {
count: number,
dayID: DayID,
itemID: ItemID,
type: SessionType,
} = JSON.parse(data.substring(8))
this.dataStore.batchEdit(() => {
this.dataStore.removeSession(
dayID, type, itemID, count)
this.dataStore.addSession(
this.dayID, type, itemID, count)
})
} else if (data.startsWith('itemID ')) {
const itemID = Number(data.substring(7))
this.dataStore.addSession(this.dayID, SessionType.SCHEDULED, itemID, 1)
}
}
showInItems(session: Session) {
this.home?.showInItems(session.item.id)
}
showInQueue(session: Session) {
this.home?.showInQueue(session.item.id)
}
getQuotaHtml() {
if (this.dayID >= this.dataStore.getCurrentDayID() && this.quota !==
undefined) {
if (this.doneCount > 0) {
if (this.doneCount >= this.quota) {
return `<b>${this.doneCount} / ${this.quota}</b>`
}
return `<b>${this.doneCount}</b> / ${this.quota}`
}
return `${this.quota}`
} else {
if (this.doneCount > 0) {
return `<b>${this.doneCount}</b>`
}
return ''
}
}
get progress() {
if (this.dayID < this.dataStore.getCurrentDayID() || this.quota ===
undefined || this.quota <= 0) {
return 0
}
return Math.min(Math.max(this.totalCount / this.quota, 0), 1)
}
get progressOverfilled() {
if (this.dayID < this.dataStore.getCurrentDayID() || this.quota ===
undefined || this.quota <= 0) {
return 0
}
return this.totalCount > this.quota
}
get progressDone() {
if (this.dayID < this.dataStore.getCurrentDayID() || this.quota ===
undefined || this.quota <= 0) {
return 0
}
return Math.min(Math.max(this.doneCount / this.quota, 0), 1)
}
sessionTrackByFn(index: number, session: Session) {
return session.item.id
}
addNewItemDueHere() {
const dialogRef = this.dialog.open(ItemDetailsComponent, {
width: ItemDetailsComponent.DIALOG_WIDTH,
data: {
initialDueDate: this.dayID,
},
hasBackdrop: true,
disableClose: false,
autoFocus: false,
})
}
} | the_stack |
import { gte } from "semver";
import {
AddressType,
ArrayType,
assert,
ASTNodeFactory,
Block,
BoolType,
BytesType,
ContractDefinition,
ElementaryTypeName,
EnumDefinition,
Expression,
FixedBytesType,
ForStatement,
FunctionCallKind,
FunctionDefinition,
FunctionType,
FunctionVisibility,
Identifier,
ImportDirective,
IntLiteralType,
IntType,
LiteralKind,
MappingType,
PointerType,
SourceUnit,
StringType,
StructDefinition,
TupleType,
TypeName,
TypeNameType,
TypeNode,
UserDefinedType,
VariableDeclaration
} from "solc-typed-ast";
import {
AnnotationType,
BuiltinFunctions,
SAddressLiteral,
SBinaryOperation,
SBooleanLiteral,
SConditional,
SForAll,
SFunctionCall,
SHexLiteral,
SId,
SIndexAccess,
SLet,
SMemberAccess,
SNode,
SNumber,
SResult,
SStringLiteral,
SUnaryOperation,
SUserFunctionDefinition,
VarDefSite
} from "../spec-lang/ast";
import {
BuiltinSymbols,
decomposeStateVarRef,
SemInfo,
StateVarScope,
unwrapOld
} from "../spec-lang/tc";
import { FunctionSetType, ImportRefType } from "../spec-lang/tc/internal_types";
import { single } from "../util/misc";
import {
AnnotationMetaData,
PropertyMetaData,
UserFunctionDefinitionMetaData
} from "./annotations";
import { TranspilingContext } from "./transpiling_context";
/**
* Transpile the `TypeNode` `type` (using the passed in `ASTNodeFactory`).
* @todo (dimo,pavel): Remove this and replace all uses with ScribbleFactory.typeNodeToVariableDecl.
*/
export function transpileType(type: TypeNode, factory: ASTNodeFactory): TypeName {
if (
type instanceof TupleType ||
type instanceof IntLiteralType ||
type instanceof FunctionSetType
) {
throw new Error(`Unsupported spec type ${type.pp()}`);
}
if (
type instanceof AddressType ||
type instanceof BoolType ||
type instanceof BytesType ||
type instanceof FixedBytesType ||
type instanceof IntType ||
type instanceof StringType
) {
return factory.makeElementaryTypeName("<missing>", type.pp());
}
if (type instanceof PointerType) {
return transpileType(type.to, factory);
}
if (type instanceof UserDefinedType) {
return factory.makeUserDefinedTypeName("<missing>", type.name, type.definition.id);
}
if (type instanceof ArrayType) {
return factory.makeArrayTypeName(
"<missing>",
transpileType(type.elementT, factory),
type.size !== undefined
? factory.makeLiteral("<missing>", LiteralKind.Number, "", "" + type.size)
: undefined
);
}
if (type instanceof MappingType) {
const keyT =
type.keyType instanceof AddressType && type.keyType.payable
? new AddressType(false)
: type.keyType;
return factory.makeMapping(
"<missing>",
transpileType(keyT, factory),
transpileType(type.valueType, factory)
);
}
throw new Error(`NYI emitting spec type ${type.pp()}`);
}
/**
* Return true IFF the type `type` can be output in a debug event. This currently
* includes primitive types, strings and bytes, and arrays over these
*/
function isTypeTraceable(type: TypeNode, ctx: TranspilingContext): boolean {
// Primitive types
if (
type instanceof AddressType ||
type instanceof BoolType ||
type instanceof FixedBytesType ||
type instanceof IntType
) {
return true;
}
// Enums
if (type instanceof UserDefinedType && type.definition instanceof EnumDefinition) {
return true;
}
if (type instanceof PointerType) {
// Strings and bytes
if (type.to instanceof StringType || type.to instanceof BytesType) {
return true;
}
// Arrays
if (type.to instanceof ArrayType) {
const version = ctx.instrCtx.compilerVersion;
// For solidity >=0.8.0 we can emit nested arrays in events since ABIEncoderV2 is on by default
if (gte(version, "0.8.0")) {
return isTypeTraceable(type.to.elementT, ctx);
}
// For older solidity skip nested arrays
if (type.to.elementT instanceof PointerType && type.to.elementT instanceof ArrayType) {
return false;
}
// And otherwise just make sure the elemnt type is something sane (i.e. not maps)
return isTypeTraceable(type.to.elementT, ctx);
}
}
return false;
}
/**
* Given an `SId` `id`, its corresponding transpiled form `transpiledExpr` and
* the current `TranspilingContext` `ctx`, if `--debug-events` are on, and this
* is the first time we encounter `id`, and its type is traceable (see
* `isTypeTraceable`) then add debugging information for `id` to `ctx`.
*
* Note that special care needs to be taken for ids appearing in old contexts -
* we need to add a new binding for them that stores their value.
*/
function addTracingInfo(id: SId, transpiledExpr: Expression, ctx: TranspilingContext): void {
const typeEnv = ctx.typeEnv;
const factory = ctx.factory;
const exprT = typeEnv.typeOf(id);
const dbgEventsOn = ctx.instrCtx.debugEvents;
if (!dbgEventsOn) {
return;
}
if (!isTypeTraceable(exprT, ctx)) {
return;
}
// Skip try/require annotations as we don't emit assertion failed events for those
if (
ctx.curAnnotation.type === AnnotationType.Try ||
ctx.curAnnotation.type === AnnotationType.Require
) {
return;
}
const idDebugMap = ctx.dbgInfo.get(ctx.curAnnotation);
const defSite = id.defSite as VarDefSite;
if (!idDebugMap.has(defSite)) {
const isOld = (ctx.semInfo.get(id) as SemInfo).isOld;
if (isOld) {
const dbgBinding = ctx.getDbgVar(id);
ctx.addBinding(dbgBinding, transpileType(exprT, factory));
const assignment = ctx.insertAssignment(
ctx.refBinding(dbgBinding),
factory.copy(transpiledExpr),
true,
true
);
ctx.instrCtx.addAnnotationInstrumentation(ctx.curAnnotation, assignment);
idDebugMap.set([[id], ctx.refBinding(dbgBinding), exprT], defSite);
} else {
idDebugMap.set([[id], factory.copy(transpiledExpr), exprT], defSite);
}
} else {
const [ids] = idDebugMap.mustGet(defSite);
ids.push(id);
}
}
/**
* Transpile the `SId` `expr` in the context of `ctx.container`.
*/
function transpileId(expr: SId, ctx: TranspilingContext): Expression {
const typeEnv = ctx.typeEnv;
const factory = ctx.factory;
if (BuiltinSymbols.has(expr.name)) {
return factory.makeIdentifier("<missing>", expr.name, -1);
}
// Builtin symbols are the only identifiers with undefined `defSite`.
assert(
expr.defSite !== undefined,
"Cannot generate AST for id {0} with no corresponding definition.",
expr
);
// Normal solidity variable - function argument, return, state variable or global constant.
if (expr.defSite instanceof VariableDeclaration) {
if (expr.name !== expr.defSite.name) {
assert(
expr.defSite.stateVariable || expr.defSite.vScope instanceof SourceUnit,
`Internal error: variable id {0} has different name from underlying variable {1}. Variable renaming only allowed for public state vars with maps and imported global vars.`,
expr,
expr.defSite
);
}
let res: Identifier;
// If the scribble name doesn't match the name of the underlying definition there are several cases:
// 1) This is a state variable - pick the underlying definition, since
// we sometimes rename public state vars during instrumentation to allow
// for an explicit getter fun
// 2) Global symbol in flat/json mode - pick the underlying definition, since all definitions are
// flattened and renamed to avoid collisions
// 3) Global symbol in files mode - pick the scribble identifier - this is a case of import renaming
// 4) All other cases - pick the Scribble name
if (
expr.name !== expr.defSite.name &&
(expr.defSite.stateVariable ||
(expr.defSite.vScope instanceof SourceUnit && ctx.instrCtx.outputMode !== "files"))
) {
res = factory.makeIdentifierFor(expr.defSite);
} else {
res = factory.makeIdentifier("<missing>", expr.name, expr.defSite.id);
}
addTracingInfo(expr, res, ctx);
return res;
}
// Let-variable used inside the body
if (expr.defSite instanceof Array && expr.defSite[0] instanceof SLet) {
const res = ctx.refBinding(ctx.getLetBinding(expr));
addTracingInfo(expr, res, ctx);
return res;
}
// ForAll iterator var
if (expr.defSite instanceof SForAll) {
const res = ctx.refBinding(ctx.getForAllIterVar(expr.defSite));
addTracingInfo(expr, res, ctx);
return res;
}
// User function argument
if (expr.defSite instanceof Array && expr.defSite[0] instanceof SUserFunctionDefinition) {
const instrCtx = ctx.instrCtx;
const transpiledUserFun = instrCtx.userFunctions.get(expr.defSite[0]);
assert(
transpiledUserFun !== undefined,
"Missing transpiled version of user function {1}",
expr.defSite[0]
);
return factory.makeIdentifierFor(
transpiledUserFun.vParameters.vParameters[expr.defSite[1]]
);
}
// State Var Property index identifier
if (expr.defSite instanceof Array && expr.defSite[0] instanceof StateVarScope) {
const [scope, idx] = expr.defSite;
const prop = scope.annotation;
// Count the indices (omitting member accesses) before `idx`
let argIdx = 0;
for (let i = 0; i < idx; i++) {
const el = prop.datastructurePath[i];
if (typeof el !== "string") {
argIdx++;
}
}
const res = factory.makeIdentifierFor(ctx.containerFun.vParameters.vParameters[argIdx]);
addTracingInfo(expr, res, ctx);
return res;
}
// User function itself
if (expr.defSite instanceof SUserFunctionDefinition) {
const instrCtx = ctx.instrCtx;
const transpiledUserFun = instrCtx.userFunctions.get(expr.defSite);
assert(
transpiledUserFun !== undefined,
"Missing transpiled version of user function {0}",
expr.defSite
);
return factory.makeIdentifierFor(transpiledUserFun);
}
// This identifier
if (expr.defSite === "this") {
return factory.makeIdentifier("<missing>", "this", ctx.containerContract.id);
}
// Function, Public Getter, Contract, Type name or imported unit name
let referrencedDef:
| FunctionDefinition
| StructDefinition
| EnumDefinition
| ContractDefinition
| VariableDeclaration
| ImportDirective;
const exprT = typeEnv.typeOf(expr);
if (exprT instanceof FunctionSetType) {
referrencedDef = single(exprT.definitions);
} else if (exprT instanceof UserDefinedType) {
assert(
exprT.definition !== undefined,
`Id {0} of user defined type {1} is missing a definition.`,
expr,
exprT
);
referrencedDef = exprT.definition;
} else if (exprT instanceof ImportRefType) {
referrencedDef = exprT.impStatement;
} else if (exprT instanceof TypeNameType && exprT.type instanceof UserDefinedType) {
referrencedDef = exprT.type.definition;
} else {
throw new Error(`Unknown id type ${exprT.pp()}`);
}
return factory.makeIdentifierFor(referrencedDef);
}
/**
* Transpile the `SResult` `expr` in the context of `ctx.container`.
*/
function transpileResult(expr: SResult, ctx: TranspilingContext): Expression {
const factory = ctx.factory;
const retParams = ctx.containerFun.vReturnParameters.vParameters;
if (retParams.length === 1) {
return factory.makeIdentifierFor(retParams[0]);
}
if (retParams.length > 1) {
return factory.makeTupleExpression(
"<missing>",
false,
retParams.map((param) => factory.makeIdentifierFor(param))
);
}
throw new Error(`InternalError: attempt to transpile $result in function without returns.`);
}
/**
* Transpile the `SIndexAccess` `expr` in the context of `ctx.container`.
*/
function transpileIndexAccess(expr: SIndexAccess, ctx: TranspilingContext): Expression {
const factory = ctx.factory;
const instrCtx = ctx.instrCtx;
const base = transpile(expr.base, ctx);
const index = transpile(expr.index, ctx);
assert(
base instanceof Expression,
"InternalError: Base of {0} transpiled to non-expression node {1}",
expr,
base.constructor.name
);
assert(
index instanceof Expression,
"InternalError: Index of {0} transpiled to non-expression node {1}",
expr,
index.constructor.name
);
// Some maps inside state vars may have been re-writen as structs with library
// accessors. If this index access is to such a map, then we need to
// transpile it as a call to the proper getter
const [sVar, path] = decomposeStateVarRef(expr);
if (sVar !== undefined) {
const interposeLib = instrCtx.sVarToLibraryMap.get(
sVar,
path.slice(0, -1).map((x) => (x instanceof SNode ? null : x))
);
if (interposeLib !== undefined) {
const getter = instrCtx.libToMapGetterMap.get(interposeLib, false);
return factory.makeFunctionCall(
"<missing>",
FunctionCallKind.FunctionCall,
factory.makeMemberAccess(
"<missing>",
factory.makeIdentifierFor(interposeLib),
getter.name,
getter.id
),
[base, index]
);
}
}
// Otherwise transpile this as a normal index access
return factory.makeIndexAccess("<missing>", base, index);
}
/**
* Transpile the `SMemberAccess` `expr` in the context of `ctx.container`.
*/
function transpileMemberAccess(expr: SMemberAccess, ctx: TranspilingContext): Expression {
const factory = ctx.factory;
const base = transpile(expr.base, ctx);
const referencedDeclaration = expr.defSite !== undefined ? expr.defSite.id : -1;
return factory.makeMemberAccess("<missing>", base, expr.member, referencedDeclaration);
}
/**
* Transpile the `SUnaryOperation` `expr` in the context of `ctx.container`.
*
* Note: When the unary operation is `old()` this will insert additional
* assignments _before_ the wrapped original call/statement.
*/
function transpileUnaryOperation(expr: SUnaryOperation, ctx: TranspilingContext): Expression {
const factory = ctx.factory;
const subExp = transpile(expr.subexp, ctx);
if (expr.op === "old") {
const type = ctx.typeEnv.typeOf(expr.subexp);
const semInfo = ctx.semInfo.get(expr);
assert(semInfo !== undefined, "Missing semantic info for {0}", expr);
if (semInfo.isConst) {
return subExp;
}
const bindingName = ctx.getOldVar(expr);
ctx.addBinding(bindingName, transpileType(type, ctx.factory));
const binding = ctx.refBinding(bindingName);
ctx.insertAssignment(binding, subExp, true, true);
return ctx.refBinding(bindingName);
}
return factory.makeUnaryOperation("<missing>", true, expr.op, subExp);
}
/**
* Transpile the `SBinaryOperation` `expr` in the context of `ctx.container`.
*/
function transpileBinaryOperation(expr: SBinaryOperation, ctx: TranspilingContext): Expression {
const factory = ctx.factory;
const left = transpile(expr.left, ctx);
const right = transpile(expr.right, ctx);
if (expr.op === "==>") {
const notPrecedent = factory.makeUnaryOperation("missing", true, "!", left);
return factory.makeBinaryOperation("<missing>", "||", notPrecedent, right);
}
return factory.makeBinaryOperation("<missing>", expr.op, left, right);
}
/**
* Transpile the `SConditional` `expr` in the context of `ctx.container`.
*/
function transpileConditional(expr: SConditional, ctx: TranspilingContext): Expression {
const factory = ctx.factory;
const condition = transpile(expr.condition, ctx);
const trueExp = transpile(expr.trueExp, ctx);
const falseExp = transpile(expr.falseExp, ctx);
return factory.makeConditional("<missing>", condition, trueExp, falseExp);
}
/**
* Transpile the `SFunctionCall` `expr` in the context of `ctx.container`.
*/
function transpileFunctionCall(expr: SFunctionCall, ctx: TranspilingContext): Expression {
const factory = ctx.factory;
if (
expr.callee instanceof SId &&
expr.callee.name === BuiltinFunctions.unchecked_sum &&
expr.callee.defSite === "builtin_fun"
) {
const arg = single(expr.args);
const argT = ctx.typeEnv.typeOf(arg);
assert(argT instanceof PointerType, "sum expects a pointer to array/map, not {0}", argT);
if (argT.to instanceof MappingType) {
const [sVar, path] = decomposeStateVarRef(arg);
assert(
sVar !== undefined,
"sum argument should be a state var(or a part of it), not {0}",
arg
);
const lib = ctx.instrCtx.sVarToLibraryMap.get(
sVar,
path.map((el) => (el instanceof SNode ? null : el))
);
assert(lib !== undefined, `State var ${sVar.name} should already be interposed`);
const struct = single(lib.vStructs);
return factory.mkStructFieldAcc(transpile(arg, ctx), struct, "sum");
}
assert(argT.to instanceof ArrayType, "sum expects a pointer to array/map, not {0}", argT);
const sumFun = ctx.instrCtx.arraySumFunMap.get(argT.to, argT.location);
ctx.instrCtx.needsUtils(ctx.containerContract.vScope);
return factory.makeFunctionCall(
"<missing>",
FunctionCallKind.FunctionCall,
factory.mkLibraryFunRef(ctx.instrCtx, sumFun),
[transpile(arg, ctx)]
);
}
const calleeT = ctx.typeEnv.typeOf(expr.callee);
let callee: Expression;
const kind =
calleeT instanceof TypeNameType
? FunctionCallKind.TypeConversion
: FunctionCallKind.FunctionCall;
if (calleeT instanceof TypeNameType) {
// Type Cast
if (calleeT.type instanceof UserDefinedType) {
// User-defined type
assert(calleeT.type.definition !== undefined, ``);
callee = factory.makeIdentifierFor(calleeT.type.definition);
} else {
// Elementary type
callee = factory.makeElementaryTypeNameExpression(
"<missing>",
transpileType(calleeT.type, ctx.factory) as ElementaryTypeName
);
}
} else {
// Normal function call
assert(
expr.callee instanceof SNode,
`Unexpected type node {0} with type {1}`,
expr.callee,
calleeT
);
callee = transpile(expr.callee, ctx);
if (
callee instanceof Identifier &&
callee.vReferencedDeclaration instanceof FunctionDefinition &&
callee.vReferencedDeclaration.visibility === FunctionVisibility.External
) {
callee = factory.makeMemberAccess(
"<missing>",
factory.makeIdentifier("<missing>", "this", ctx.containerContract.id),
callee.name,
callee.vReferencedDeclaration.id
);
}
}
const args = expr.args.map((arg) => transpile(arg, ctx));
return factory.makeFunctionCall("<mising>", kind, callee, args);
}
/**
* Transpile the `SLet` statement `expr`. Note that this will generate and insert additional
* assignments in `ctx.container`.
*/
function transpileLet(expr: SLet, ctx: TranspilingContext): Expression {
const factory = ctx.factory;
const isLetOld = (ctx.semInfo.get(expr) as SemInfo).isOld;
const isLetBindingOld = (ctx.semInfo.get(expr.rhs) as SemInfo).isOld;
let rhs: Expression;
if (expr.rhs instanceof SUnaryOperation && expr.rhs.op === "old") {
rhs = transpile(expr.rhs.subexp, ctx);
} else {
rhs = transpile(expr.rhs, ctx);
}
const rhsT = ctx.typeEnv.typeOf(expr.rhs);
const lhss: Expression[] = [];
if (expr.lhs.length == 1) {
const name = ctx.getLetBinding([expr, 0]);
const type = transpileType(rhsT, ctx.factory);
ctx.addBinding(name, type);
lhss.push(ctx.refBinding(name));
} else {
const getLhsT = (i: number): TypeNode =>
rhsT instanceof TupleType ? rhsT.elements[i] : (rhsT as FunctionType).returns[i];
for (let i = 0; i < expr.lhs.length; i++) {
const name = ctx.getLetBinding([expr, i]);
const type = transpileType(getLhsT(i), ctx.factory);
ctx.addBinding(name, type);
lhss.push(ctx.refBinding(name));
}
}
let lhs: Expression;
if (lhss.length === 1) {
lhs = lhss[0];
} else {
lhs = factory.makeTupleExpression("<missing>", false, lhss);
}
ctx.insertAssignment(lhs, rhs, isLetBindingOld, true);
const body = transpile(expr.in, ctx);
const letVarName = ctx.getLetVar(expr);
ctx.addBinding(letVarName, transpileType(ctx.typeEnv.typeOf(expr), ctx.factory));
const letVar = ctx.refBinding(letVarName);
ctx.insertAssignment(letVar, body, isLetOld, true);
return ctx.refBinding(letVarName);
}
function makeForLoop(
ctx: TranspilingContext,
iterVarName: string,
iterVarType: TypeNode,
start: SNode,
end: SNode | Expression
): ForStatement {
const factory = ctx.factory;
ctx.addBinding(iterVarName, transpileType(iterVarType, ctx.factory));
// Iteration variable initialization statmenet
const initStmt = factory.makeExpressionStatement(
factory.makeAssignment("<missing>", "=", ctx.refBinding(iterVarName), transpile(start, ctx))
);
// Loop condition
const iterCond = factory.makeBinaryOperation(
"<missing>",
"<",
ctx.refBinding(iterVarName),
end instanceof Expression ? end : transpile(end, ctx)
);
// Iteration variable increment
const incStmt = factory.makeExpressionStatement(
factory.makeUnaryOperation("<missing>", false, "++", ctx.refBinding(iterVarName))
);
const body = factory.makeBlock([]);
// Build and insert a for-loop with empty body
return factory.makeForStatement(body, initStmt, iterCond, incStmt);
}
/**
* Transpile the `SForAll` statement `expr`. Note that this will generate and insert a loop
* in `ctx.container`.
*/
function transpileForAll(expr: SForAll, ctx: TranspilingContext): Expression {
const factory = ctx.factory;
const isOld = (ctx.semInfo.get(expr) as SemInfo).isOld;
const typeEnv = ctx.typeEnv;
let forStmt: ForStatement;
const iterVarName = ctx.getForAllIterVar(expr);
const resultVarName = ctx.getForAllVar(expr);
if (expr.container !== undefined) {
const containerT = typeEnv.typeOf(expr.container);
// Forall over a map
if (containerT instanceof PointerType && containerT.to instanceof MappingType) {
const internalCounter = ctx.instrCtx.nameGenerator.getFresh("i");
const container = unwrapOld(expr.container);
const [sVar, path] = decomposeStateVarRef(container);
assert(sVar !== undefined, "Unexpected undefined state var in {0}", expr.container);
const astContainer = transpile(container, ctx);
const lib = ctx.instrCtx.sVarToLibraryMap.get(
sVar,
path.map((x) => (x instanceof SNode ? null : x))
);
assert(lib !== undefined, `Unexpected missing library for map ${sVar.name}`);
const struct = single(lib.vStructs);
const keys = factory.mkStructFieldAcc(astContainer, struct, "keys");
const len = factory.makeMemberAccess("<missing>", keys, "length", -1);
forStmt = makeForLoop(
ctx,
internalCounter,
new IntType(256, false),
new SNumber(BigInt(1), 10),
len
);
ctx.addBinding(iterVarName, transpileType(expr.iteratorType, ctx.factory));
factory.addStmt(
forStmt.vBody as Block,
factory.makeAssignment(
"<missing>",
"=",
ctx.refBinding(iterVarName),
factory.makeIndexAccess(
"<mising>",
factory.copy(keys),
ctx.refBinding(internalCounter)
)
)
);
} else {
// Forall over array
const astContainer = transpile(expr.container, ctx);
forStmt = makeForLoop(
ctx,
iterVarName,
expr.iteratorType,
new SNumber(BigInt(0), 10),
factory.makeMemberAccess("<missing>", astContainer, "length", -1)
);
}
} else {
// Forall over numeric range
forStmt = makeForLoop(
ctx,
iterVarName,
expr.iteratorType,
expr.start as SNode,
expr.end as SNode
);
}
ctx.addBinding(resultVarName, transpileType(new BoolType(), ctx.factory));
// Initialize result of forall to true (so `forall (uint x in [0, 0)) false` is true).
ctx.insertStatement(
factory.makeAssignment(
"<missing>",
"=",
ctx.refBinding(resultVarName),
factory.makeLiteral("<missing>", LiteralKind.Bool, "", "true")
),
isOld,
true
);
const body = forStmt.vBody as Block;
// Insert the created for-loop with empty body
ctx.insertStatement(forStmt, isOld, true);
// Transpile the predicate expression in the empty body of the newly inserted for-loop
ctx.pushMarker([body, "end"], isOld);
const bodyPred = transpile(expr.expression, ctx);
// Update the result variable for the forall on every loop iteration
ctx.insertStatement(
factory.makeAssignment("<missing>", "=", ctx.refBinding(resultVarName), bodyPred),
isOld,
true
);
// If the result ever becomes false, terminate early
ctx.insertStatement(
factory.makeIfStatement(
factory.makeUnaryOperation("<missing>", true, "!", ctx.refBinding(resultVarName)),
factory.makeBreak()
),
isOld,
true
);
ctx.popMarker(isOld);
return ctx.refBinding(resultVarName);
}
/**
* Given `AnnotationMetaData` `annotationMD` and a `TranspilingContext` `ctx`
* transpile the predicate/body of the annotation and return it.
*/
export function transpileAnnotation(
annotMD: AnnotationMetaData,
ctx: TranspilingContext
): Expression {
/**
* Bit of a hack to keep track of the currrent annotation being transpiled.
* Useful for adding metadata to the InstrumentationContext
*/
ctx.curAnnotation = annotMD;
if (annotMD instanceof PropertyMetaData) {
return transpile(annotMD.parsedAnnot.expression, ctx);
}
if (annotMD instanceof UserFunctionDefinitionMetaData) {
return transpile(annotMD.parsedAnnot.body, ctx);
}
throw new Error(`NYI Annotation metadata type ${annotMD.constructor.name}`);
}
/**
* Given a Scribble expression `expr` and a `TranspilingContext` `ctx` generate and return an ASTNode equivalnt to computing
* `expr`.
*
* Note: This may involve inserting assignment statements to compute the values of `old()`, `let` and `forall` expressions.
* In the case of `old()` expressions the newly inserted assignments would be in the appropriate location before the wrapped statement.
*/
export function transpile(expr: SNode, ctx: TranspilingContext): Expression {
const factory = ctx.factory;
if (expr instanceof SNumber) {
const numStr = expr.num.toString(expr.radix);
return factory.makeLiteral(
"<missing>",
LiteralKind.Number,
"",
expr.radix === 16 ? "0x" + numStr : numStr
);
}
if (expr instanceof SBooleanLiteral) {
return factory.makeLiteral("<missing>", LiteralKind.Bool, "", expr.val ? "true" : "false");
}
if (expr instanceof SStringLiteral) {
return factory.makeLiteral("<missing>", LiteralKind.String, "", expr.val);
}
if (expr instanceof SHexLiteral) {
return factory.makeLiteral("<missing>", LiteralKind.String, expr.val, null as any);
}
if (expr instanceof SAddressLiteral) {
return factory.makeLiteral("<missing>", LiteralKind.Number, "", expr.val);
}
if (expr instanceof SId) {
return transpileId(expr, ctx);
}
if (expr instanceof SResult) {
return transpileResult(expr, ctx);
}
if (expr instanceof SIndexAccess) {
return transpileIndexAccess(expr, ctx);
}
if (expr instanceof SMemberAccess) {
return transpileMemberAccess(expr, ctx);
}
if (expr instanceof SUnaryOperation) {
return transpileUnaryOperation(expr, ctx);
}
if (expr instanceof SBinaryOperation) {
return transpileBinaryOperation(expr, ctx);
}
if (expr instanceof SConditional) {
return transpileConditional(expr, ctx);
}
if (expr instanceof SFunctionCall) {
return transpileFunctionCall(expr, ctx);
}
if (expr instanceof SLet) {
return transpileLet(expr, ctx);
}
if (expr instanceof SForAll) {
return transpileForAll(expr, ctx);
}
if (expr instanceof TypeNode) {
return transpileType(expr, ctx.factory);
}
throw new Error(`NYI transpiling node ${expr.pp()}`);
} | the_stack |
const chaiColors = require('chai-colors');
const Base64 = require('js-base64').Base64;
chai.use(chaiColors);
// @ts-ignore
Cypress.on('uncaught:exception', (err, runnable) => {
// returning false here prevents Cypress from
// failing the test on exceptions
return !!Cypress.env('TRAVIS_BUILD_ID');
});
const encodeWidgetDataObject = (data: object): string => {
return Base64.encode(JSON.stringify(data));
};
describe('Test Backend', () => {
beforeEach(() => {
// @ts-ignore
cy.setNetlifySiteUrl();
});
before(() => {
// move the testing images to the uploads folder so we can
// preview gallery items and other images without them having
// to be present inside the uploads folder in production
// @ts-ignore
cy.copyTestingImages();
});
after(() => {
// @ts-ignore
cy.removeTestingImages();
// we need to inhibit the event sent from Netlify-cms
// telling us that "Changaes you made will not be saved"
// before leaving the page
cy.window().then((win) => {
win.onbeforeunload = null;
// @ts-ignore
cy.visit('/', {failOnStatusCode: false});
});
});
const gotoAdmin = () => {
cy.viewport(1200, 1200);
cy.visit('/admin/');
};
const submitLoginFrm = () => {
cy.get(`iframe`).then(($iframe) => {
const $body = $iframe.contents().find('body');
cy.wrap($body[0]).get('button').click();
cy.wait(1000);
cy.wrap($body[0]).find('input[type="email"]').eq(0).clear().type(
Cypress.env('NETLIFY_USER') || 'invalid@user.com', {force: true},
);
cy.wrap($body[0]).find('input[type="password"]').eq(0).clear().type(
Cypress.env('NETLIFY_PASSWORD') || 'invalid-password', {force: true},
);
cy.wrap($body[0]).find('button.btn[type=submit]').eq(0).click();
});
};
const navigatetoPosts = () => {
cy.contains('a', 'Posts').click();
};
const navigateCreatePost = () => {
cy.contains('a', 'New Post').click();
};
const assertInsideAdmin = () => {
cy.contains('a', 'Posts');
};
const assertOnPostsPage = () => {
cy.url().should('contain', '/#/collections/posts');
cy.contains('h1', 'Posts');
};
const toggleMarkdownEditor = () => {
cy.get('div').contains('Markdown').parent().find('button[role=switch]').click();
};
const writePostBody = (postBody: string, clearBeforeWrite: boolean | undefined) => {
if (clearBeforeWrite) {
cy.get(`[data-slate-editor]`).click().clear({
force: true,
});
}
return cy.get(`[data-slate-editor]`).click().type(postBody.replace(/{/g, `{{}`), {
delay: 0,
});
};
const getPreviewBody = (): Promise<any> => {
// @ts-ignore
return new Cypress.Promise((resolve: any) => {
cy.get(`iframe[class*="PreviewPaneFrame"]`).then(($iframe) => {
resolve($iframe.contents().find('body')[0]);
});
});
};
it('should be able to log in', () => {
gotoAdmin();
submitLoginFrm();
assertInsideAdmin();
});
it('should find the Posts collection', () => {
navigatetoPosts();
assertOnPostsPage();
});
it('should write and make visible main title', () => {
// switch to markdown
navigateCreatePost();
toggleMarkdownEditor();
getPreviewBody().then(($body) => {
cy.get('input#title-field-1').clear().type('test new post');
cy.wrap($body).find('h1').eq(0).contains('test new post');
});
});
describe('should be able to preview most widgets', () => {
it('- section heading', () => {
getPreviewBody().then(($body) => {
// Section heading
writePostBody(JSON.stringify({
widget: 'qards-section-heading',
config: encodeWidgetDataObject({
'title' : 'A primary section heading',
'subtitle': 'A primary section heading is like a chapter',
'type' : 'primary',
}),
}), true);
cy.wrap($body).find('#h-item-a-primary-section-heading h2')
.contains('A primary section heading');
cy.wrap($body).find('#h-item-a-primary-section-heading span')
.contains('A primary section heading is like a chapter');
writePostBody(JSON.stringify({
widget: 'qards-section-heading',
config: encodeWidgetDataObject({
'title' : 'A secondary section heading',
'subtitle': 'A secondary section heading is like a chapter',
'type' : 'secondary',
}),
}), true);
cy.wrap($body).find('#h-item-a-secondary-section-heading h3')
.contains('A secondary section heading');
cy.wrap($body).find('#h-item-a-secondary-section-heading span')
.contains('A secondary section heading is like a chapter');
});
});
describe('- countdown', () => {
it('should preview', () => {
getPreviewBody().then(($body) => {
writePostBody(JSON.stringify({
widget: 'qards-countdown',
config: encodeWidgetDataObject({
'event' : '2025-10-04T14:00:00.000Z',
'title' : 'Time until robots take over the world',
'subtitle': 'The singularity is near',
}),
}), true);
cy.wrap($body).find('.countdown .digits pre').eq(0).contains('6');
});
});
});
describe('- gallery', () => {
it('should preview', () => {
getPreviewBody().then(($body) => {
writePostBody(JSON.stringify({
widget: 'qards-gallery',
config: encodeWidgetDataObject({
'items': [{
'src' : '/images/uploads/test-1.jpg',
'alt' : 'Banana for scale',
'caption': 'This is a **caption**. It supports _markdown_',
}, {
'src': '/images/uploads/test-2.jpg',
'alt': 'Cool kid',
}, {
'src': '/images/uploads/test-3.jpg', 'alt': 'Cat tax',
},
{'src': '/images/uploads/test-1.jpg', 'alt': 'Awesome dog'}],
}),
}), true);
cy.wrap($body).find('.react-photo-gallery--gallery img').eq(0).click();
cy.get('#lightboxBackdrop').should('be.visible');
cy.get('body').type('{esc}');
cy.get('#lightboxBackdrop').should('not.be.visible');
cy.wrap($body).find('.react-photo-gallery--gallery img').eq(1).click();
cy.get('#lightboxBackdrop').should('be.visible');
cy.get('body').type('{esc}');
cy.get('#lightboxBackdrop').should('not.be.visible');
cy.wrap($body).find('.react-photo-gallery--gallery img').eq(2).click();
cy.get('#lightboxBackdrop').should('be.visible');
cy.get('body').type('{esc}');
cy.get('#lightboxBackdrop').should('not.be.visible');
});
});
});
describe('- code block', () => {
it('should preview', () => {
getPreviewBody().then(($body) => {
writePostBody(JSON.stringify({
widget: 'qards-audio',
config: encodeWidgetDataObject({
'items': [{
'title' : 'Lost',
'url' : 'https://www.mixcloud.com/Bazfawlty/lost/',
'subtitle': 'Deep techno ',
'src' : '/images/uploads/27f0-b205-4a15-b995-c18287703cda.jpg',
}],
}),
}), true);
cy.wrap($body).find('span[icon=play].bp3-icon.bp3-icon-play').eq(0).should('be.visible');
cy.wrap($body).find('span[icon=step-forward].bp3-icon.bp3-icon-step-forward').eq(0)
.should('be.visible');
cy.wrap($body).find('span[icon=step-backward].bp3-icon.bp3-icon-step-backward').eq(0)
.should('be.visible');
cy.wrap($body).find('ul > li.active').eq(0).contains('Lost');
});
});
});
describe('- reveal', () => {
it('should preview', () => {
getPreviewBody().then(($body) => {
writePostBody(JSON.stringify({
widget: 'qards-reveal',
config: encodeWidgetDataObject({
'items': [{
'title' : 'What is a accordion?',
'content': 'An accordion is a list of html elements that can collapse',
}, {
'title' : 'Why would I need one?',
'content': 'A reveal could make a good candidate for a small FAQ section',
}],
}),
}), true);
cy.wrap($body).find('div.accordion').eq(0).should('be.visible');
cy.wrap($body).find('div.accordion__item > #accordion__title-0').contains('What is a accordion?');
});
});
});
describe('- video', () => {
it('should preview', () => {
getPreviewBody().then(($body) => {
writePostBody(JSON.stringify({
widget: 'qards-video',
config: encodeWidgetDataObject({
'url': 'https://www.youtube.com/watch?time_continue=301&v=JplRSJr8K-g',
}),
}), true);
cy.wrap($body).find('div.video-player').eq(0).should('be.visible');
cy.wrap($body).find('div.video-player iframe[title="YouTube video player"]').eq(0).should(
'be.visible');
});
});
});
describe('- audio', () => {
it('should preview', () => {
getPreviewBody().then(($body) => {
writePostBody(JSON.stringify({
widget: 'qards-code',
config: encodeWidgetDataObject({
'language': 'javascript',
'code' : 'a + b',
}),
}), true);
cy.wrap($body).find('pre > code').eq(0).contains('a + b');
});
});
});
describe('- callouts', () => {
it('- primary', () => {
getPreviewBody().then(($body) => {
writePostBody(JSON.stringify({
widget: 'qards-callout',
config: encodeWidgetDataObject({
'intent' : 'primary',
'title' : 'Callout title primary',
'message': 'Callout title primary meesage',
}),
}), true);
cy.wrap($body).find('.bp3-callout.bp3-intent-primary.bp3-callout-icon > h4.bp3-heading')
.eq(0).contains('Callout title primary');
cy.wrap($body).find('.bp3-callout.bp3-intent-primary.bp3-callout-icon > div > p')
.eq(0).contains('Callout title primary meesage');
});
});
it('- success', () => {
getPreviewBody().then(($body) => {
writePostBody(JSON.stringify({
widget: 'qards-callout',
config: encodeWidgetDataObject({
'intent' : 'success',
'title' : 'Callout title success',
'message': 'Callout title success meesage',
}),
}), true);
cy.wrap($body).find('.bp3-callout.bp3-intent-success.bp3-callout-icon > h4.bp3-heading')
.eq(0).contains('Callout title success');
cy.wrap($body).find('.bp3-callout.bp3-intent-success.bp3-callout-icon > div > p')
.eq(0).contains('Callout title success meesage');
});
});
it('- warning', () => {
getPreviewBody().then(($body) => {
writePostBody(JSON.stringify({
widget: 'qards-callout',
config: encodeWidgetDataObject({
'intent' : 'warning',
'title' : 'Callout title warning',
'message': 'Callout title warning meesage',
}),
}), true);
cy.wrap($body).find('.bp3-callout.bp3-intent-warning.bp3-callout-icon > h4.bp3-heading')
.eq(0).contains('Callout title warning');
cy.wrap($body).find('.bp3-callout.bp3-intent-warning.bp3-callout-icon > div > p')
.eq(0).contains('Callout title warning meesage');
});
});
it('- danger', () => {
getPreviewBody().then(($body) => {
writePostBody(JSON.stringify({
widget: 'qards-callout',
config: encodeWidgetDataObject({
'intent' : 'danger',
'title' : 'Callout title danger',
'message': 'Callout title danger meesage',
}),
}), true);
cy.wrap($body).find('.bp3-callout.bp3-intent-danger.bp3-callout-icon > h4.bp3-heading')
.eq(0).contains('Callout title danger');
cy.wrap($body).find('.bp3-callout.bp3-intent-danger.bp3-callout-icon > div > p')
.eq(0).contains('Callout title danger meesage');
});
});
});
});
}); | the_stack |
interface JQuery {
checkbox: SemanticUI.Checkbox;
}
declare namespace SemanticUI {
interface Checkbox {
settings: CheckboxSettings;
/**
* Switches a checkbox from current state
*/
(behavior: 'toggle'): JQuery;
/**
* Set a checkbox state to checked
*/
(behavior: 'check'): JQuery;
/**
* Set a checkbox state to unchecked
*/
(behavior: 'uncheck'): JQuery;
/**
* Set as indeterminate checkbox
*/
(behavior: 'indeterminate'): JQuery;
/**
* Set as determinate checkbox
*/
(behavior: 'determinate'): JQuery;
/**
* Enable interaction with a checkbox
*/
(behavior: 'enable'): JQuery;
/**
* Set a checkbox state to checked without callbacks
*/
(behavior: 'set checked'): JQuery;
/**
* Set a checkbox state to unchecked without callbacks
*/
(behavior: 'set unchecked'): JQuery;
/**
* Set as indeterminate checkbox without callbacks
*/
(behavior: 'set indeterminate'): JQuery;
/**
* Set as determinate checkbox without callbacks
*/
(behavior: 'set determinate'): JQuery;
/**
* Enable interaction with a checkbox without callbacks
*/
(behavior: 'set enabled'): JQuery;
/**
* Disable interaction with a checkbox without callbacks
*/
(behavior: 'set disabled'): JQuery;
/**
* Attach checkbox events to another element
*/
(behavior: 'attach events', selector: string | JQuery, event?: string): JQuery;
/**
* Returns whether element is radio selection
*/
(behavior: 'is radio'): boolean;
/**
* Returns whether element is currently checked
*/
(behavior: 'is checked'): boolean;
/**
* Returns whether element is not checked
*/
(behavior: 'is unchecked'): boolean;
/**
* Returns whether element is able to be changed
*/
(behavior: 'can change'): boolean;
/**
* Returns whether element can be checked (checking if already checked or `beforeChecked` would cancel)
*/
(behavior: 'should allow check'): boolean;
/**
* Returns whether element can be unchecked (checking if already unchecked or `beforeUnchecked` would cancel)
*/
(behavior: 'should allow uncheck'): boolean;
/**
* Returns whether element can be determinate (checking if already determinate or `beforeDeterminate` would cancel)
*/
(behavior: 'should allow determinate'): boolean;
/**
* Returns whether element can be indeterminate (checking if already indeterminate or `beforeIndeterminate` would cancel)
*/
(behavior: 'should allow indeterminate'): boolean;
/**
* Returns whether element is able to be unchecked
*/
(behavior: 'can uncheck'): boolean;
(behavior: 'destroy'): JQuery;
<K extends keyof CheckboxSettings>(behavior: 'setting', name: K, value?: undefined): CheckboxSettings._Impl[K];
<K extends keyof CheckboxSettings>(behavior: 'setting', name: K, value: CheckboxSettings._Impl[K]): JQuery;
(behavior: 'setting', value: CheckboxSettings): JQuery;
(settings?: CheckboxSettings): JQuery;
}
/**
* @see {@link http://semantic-ui.com/modules/checkbox.html#/settings}
*/
type CheckboxSettings = CheckboxSettings.Param;
namespace CheckboxSettings {
type Param = (Pick<_Impl, 'uncheckable'> |
Pick<_Impl, 'fireOnInit'> |
Pick<_Impl, 'onChange'> |
Pick<_Impl, 'onChecked'> |
Pick<_Impl, 'onIndeterminate'> |
Pick<_Impl, 'onDeterminate'> |
Pick<_Impl, 'onUnchecked'> |
Pick<_Impl, 'beforeChecked'> |
Pick<_Impl, 'beforeIndeterminate'> |
Pick<_Impl, 'beforeDeterminate'> |
Pick<_Impl, 'beforeUnchecked'> |
Pick<_Impl, 'onEnable'> |
Pick<_Impl, 'onDisable'> |
Pick<_Impl, 'onEnabled'> |
Pick<_Impl, 'onDisabled'> |
Pick<_Impl, 'selector'> |
Pick<_Impl, 'className'> |
Pick<_Impl, 'error'> |
Pick<_Impl, 'namespace'> |
Pick<_Impl, 'name'> |
Pick<_Impl, 'silent'> |
Pick<_Impl, 'debug'> |
Pick<_Impl, 'performance'> |
Pick<_Impl, 'verbose'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
// region Behavior
/**
* Setting to true/false will determine whether an input will allow no selection. Auto will set disallow this behavior only for radio boxes
*
* @default 'auto'
*/
uncheckable: 'auto' | boolean;
/**
* Whether callbacks for checked status should be fired on init as well as change
*
* @default false
*/
fireOnInit: boolean;
// endregion
// region Callbacks
/**
* Callback after a checkbox is either checked or unchecked.
*/
onChange(this: HTMLInputElement): void;
/**
* Callback after a checkbox is checked.
*/
onChecked(this: HTMLInputElement): void;
/**
* Callback after a checkbox is set to undeterminate.
*/
onIndeterminate(this: HTMLInputElement): void;
/**
* Callback after a checkbox is set to determinate.
*/
onDeterminate(this: HTMLInputElement): void;
/**
* Callback after a checkbox is unchecked.
*/
onUnchecked(this: HTMLInputElement): void;
/**
* Callback before a checkbox is checked. Can cancel change by returning false
*/
beforeChecked(this: HTMLInputElement): void | false;
/**
* Callback before a checkbox is set to undeterminate. Can cancel change by returning false
*/
beforeIndeterminate(this: HTMLInputElement): void | false;
/**
* Callback before a checkbox is set to determinate. Can cancel change by returning false
*/
beforeDeterminate(this: HTMLInputElement): void | false;
/**
* Callback before a checkbox is unchecked. Can cancel change by returning false
*/
beforeUnchecked(this: HTMLInputElement): void | false;
/**
* Callback after a checkbox is enabled.
*/
onEnable(this: HTMLInputElement): void;
/**
* Callback after a checkbox is disabled.
*/
onDisable(this: HTMLInputElement): void;
/**
* Callback after a checkbox is enabled.
*
* @deprecated
*/
onEnabled(this: HTMLInputElement): void;
/**
* Callback after a checkbox is disabled.
*
* @deprecated
*/
onDisabled(this: HTMLInputElement): void;
// endregion
// region DOM Settings
/**
* Selectors used to find parts of a module
*/
selector: Checkbox.SelectorSettings;
/**
* Class names used to determine element state
*/
className: Checkbox.ClassNameSettings;
// endregion
// region Debug Settings
error: Checkbox.ErrorSettings;
// endregion
// region Component Settings
// region DOM Settings
/**
* Event namespace. Makes sure module teardown does not effect other events attached to an element.
*/
namespace: string;
// endregion
// region Debug Settings
/**
* Name used in log statements
*/
name: string;
/**
* Silences all console output including error messages, regardless of other debug settings.
*/
silent: boolean;
/**
* Debug output to console
*/
debug: boolean;
/**
* Show console.table output with performance metrics
*/
performance: boolean;
/**
* Debug output includes all internal behaviors
*/
verbose: boolean;
// endregion
// endregion
}
}
namespace Checkbox {
type SelectorSettings = SelectorSettings.Param;
namespace SelectorSettings {
type Param = (Pick<_Impl, 'input'> |
Pick<_Impl, 'label'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 'input[type=checkbox], input[type=radio]'
*/
input: string;
/**
* @default 'label'
*/
label: string;
}
}
type ClassNameSettings = ClassNameSettings.Param;
namespace ClassNameSettings {
type Param = (Pick<_Impl, 'checked'> |
Pick<_Impl, 'disabled'> |
Pick<_Impl, 'radio'> |
Pick<_Impl, 'readOnly'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 'checked'
*/
checked: string;
/**
* @default 'disabled'
*/
disabled: string;
/**
* @default 'radio'
*/
radio: string;
/**
* @default 'read-only'
*/
readOnly: string;
}
}
type ErrorSettings = ErrorSettings.Param;
namespace ErrorSettings {
type Param = (Pick<_Impl, 'method'>) &
Partial<Pick<_Impl, keyof _Impl>>;
interface _Impl {
/**
* @default 'The method you called is not defined.'
*/
method: string;
}
}
}
} | the_stack |
import keycode = require('keycode');
import camelCase = require('lodash.camelcase');
// @ts-ignore: no declaration file
import { shallowEquals } from 'redux-observers';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { logger } from '../../api/logger';
import { Omit } from '../../types';
import { dissoc } from 'ramda';
export interface ElectronWebviewProps extends Omit<Electron.WebviewTag, 'src'> {
// webview `src` is updated by the webview itself, so we do not want to
// update it ourselves directly. Instead we must call `loadUrl` on underlying
// webcontents, and the webview will update the src attribute accordingly.
// `initialSrc` is just taken into account once, when the Component is mounting.
initialSrc?: string,
hidden: boolean;
className: string;
preload: string;
allowpopus: string;
onDidAttach?: EventListener;
onLoadCommit?: EventListener;
onDidFinishLoad?: EventListener;
onDidFailLoad?: EventListener;
onDidFrameFinishLoad?: EventListener;
onDidStartLoading?: EventListener;
onDidStopLoading?: EventListener;
onDomReady?: EventListener;
onPageTitleSet?: EventListener;
onPageTitleUpdated?: EventListener;
onPageFaviconUpdated?: EventListener;
onEnterHtmlFullScreen?: EventListener;
onLeaveHtmlFullScreen?: EventListener;
onConsoleMessage?: EventListener;
onNewWindow?: EventListener;
onClose?: EventListener;
onIpcMessage?: EventListener;
onCrashed?: EventListener;
onGpuCrashed?: EventListener;
onPluginCrashed?: EventListener;
onDestroyed?: EventListener;
}
export const changableProps = {
useragent: 'setUserAgent',
devtools: 'setDevTools',
muted: 'setAudioMuted',
};
export const events = [
'load-commit',
'did-attach',
'did-finish-load',
'did-fail-load',
'did-frame-finish-load',
'did-start-loading',
'did-stop-loading',
'dom-ready',
'page-title-set', // deprecated event
'page-title-updated',
'page-favicon-updated',
'enter-html-full-screen',
'leave-html-full-screen',
'console-message',
'found-in-page',
'new-window',
'will-navigate', // do not use it, not reliable in some cases electron/electron#14751
'did-navigate',
'did-navigate-in-page',
'close',
'ipc-message',
'crashed',
'gpu-crashed',
'plugin-crashed',
'destroyed',
'media-started-playing',
'media-paused',
'did-change-theme-color',
'update-target-url',
'devtools-opened',
'devtools-closed',
'devtools-focused',
];
export const methods = [
'loadURL',
'getURL',
'getTitle',
'isLoading',
'isWaitingForResponse',
'stop',
'reload',
'reloadIgnoringCache',
'canGoBack',
'canGoForward',
'canGoToOffset',
'clearHistory',
'goBack',
'goForward',
'goToIndex',
'goToOffset',
'isCrashed',
'setUserAgent',
'getUserAgent',
'insertCSS',
'executeJavaScript',
'openDevTools',
'closeDevTools',
'isDevToolsOpened',
'isDevToolsFocused',
'inspectElement',
'inspectServiceWorker',
'setAudioMuted',
'isAudioMuted',
'undo',
'redo',
'cut',
'copy',
'paste',
'pasteAndMatchStyle',
'delete',
'selectAll',
'unselect',
'replace',
'replaceMisspelling',
'insertText',
'findInPage',
'stopFindInPage',
'print',
'printToPDF',
'capturePage',
'send',
'sendInputEvent',
'setZoomFactor',
'setZoomLevel',
'showDefinitionForSelection',
'getWebContents',
'focus',
];
/*
* Electron keyboard events (@see https://electronjs.org/docs/api/web-contents#event-before-input-event)
* can't entirely be converted to KeyboardEvent (@see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent).
* If we naïvely convert from the first to the second, `which` and `keyCode` attributes will not have the proper values.
* Even if those props are deprecated, Mousetrap lib still uses them.
* The goal of this function is to try to guess the values of those 2 attributes.
*/
export const getKeyboardKeyCode = (key: string, code: string) => {
switch (key) {
case 'ArrowLeft':
return 37;
case 'ArrowUp':
return 38;
case 'ArrowRight':
return 39;
case 'ArrowDown':
return 40;
case 'Meta':
return 91;
default:
switch (code) {
case 'Digit0':
return 48;
case 'Digit1':
return 49;
case 'Digit2':
return 50;
case 'Digit3':
return 51;
case 'Digit4':
return 52;
case 'Digit5':
return 53;
case 'Digit6':
return 54;
case 'Digit7':
return 55;
case 'Digit8':
return 56;
case 'Digit9':
return 57;
default:
return keycode(key);
}
}
};
const getRealPropName = (propName: string) => {
switch (propName) {
case 'initialSrc':
return 'src';
default:
return propName;
}
};
const getPropString = (propName: string, value: unknown): string => {
const realPropName = getRealPropName(propName);
if (typeof value === 'boolean') {
return `${realPropName}="${value ? 'on' : 'off'}" `;
}
return `${realPropName}=${JSON.stringify(String(value))} `;
};
const removeInitialSrcProp = dissoc('initialSrc');
// Additional dynamically generated members
interface ElectronWebview {
reload: () => any,
isDevToolsOpened: Function,
getURL: () => any,
goForward: () => any,
goBack: () => any,
openDevTools: () => any,
closeDevTools: () => any,
getTitle: () => any,
pasteAndMatchStyle: () => any,
}
class ElectronWebview extends React.Component<ElectronWebviewProps, {}> {
public view: Electron.WebviewTag;
protected ref: HTMLElement;
protected ready: boolean;
private loaded: boolean;
constructor(props: ElectronWebviewProps) {
super(props);
this.ready = false;
}
componentDidMount() {
const container = ReactDOM.findDOMNode(this.ref);
let propString = '';
Object.keys(this.props).forEach((propName) => {
// Waiting for a fix https://github.com/electron/electron/issues/9618
if (this.props[propName] !== undefined && typeof this.props[propName] !== 'function') {
propString += getPropString(propName, this.props[propName]);
}
});
if (this.props.className) {
propString += `class="${this.props.className}" `;
}
propString += 'tabindex="-1" ';
container.innerHTML = `<webview ${propString}/>`;
this.view = container.querySelector('webview') as Electron.WebviewTag;
this.view.addEventListener('did-finish-load', () => {
if (!this.loaded) {
this.loaded = true;
this.updateClassName(this.props);
}
});
// To ease end-to-end tests
const webviewStartLoadingCb = () => {
document.dispatchEvent(new Event('webview-did-start-loading'));
this.view.removeEventListener('did-start-loading', webviewStartLoadingCb);
};
this.view.addEventListener('did-start-loading', webviewStartLoadingCb);
this.view.addEventListener('did-attach', (...attachArgs: any[]) => {
this.ready = true;
this.forwardKeyboardEvents();
events.forEach((event) => {
const propName = camelCase(`on-${event}`);
if (this.props[propName]) {
this.view.addEventListener(event, this.props[propName], false);
}
});
if (this.props.onDidAttach) this.props.onDidAttach(...attachArgs);
});
this.view.addEventListener('dom-ready', () => {
// Remove this once https://github.com/electron/electron/issues/14474 is fixed
this.view.blur();
this.view.focus();
});
methods.forEach((method) => {
if (this[method]) return;
this[method] = (...args: any[]) => {
if (!this.ready) return;
try {
return this.view[method](...args);
} catch (e) {
logger.notify(e);
}
};
});
}
/**
* With Electron 3.0 webviews, events are not bubbled-up anymore.
* The goal of this method is to simulate the old behaviour.
*/
forwardKeyboardEvents() {
// Inspired by https://github.com/electron/electron/issues/14258#issuecomment-416893856
this.view.getWebContents().on('before-input-event', (_event, input) => {
// Create a fake KeyboardEvent from the data provided
const emulatedKeyboardEvent = new KeyboardEvent(input.type.toLowerCase(), {
code: input.code,
key: input.key,
shiftKey: input.shift,
altKey: input.alt,
ctrlKey: input.control,
metaKey: input.meta,
repeat: input.isAutoRepeat,
bubbles: true,
composed: true,
cancelable: true,
});
// Workaround for mousetrap
const keyCodeValue = getKeyboardKeyCode(emulatedKeyboardEvent.key, emulatedKeyboardEvent.code);
Object.defineProperty(emulatedKeyboardEvent, 'which', {
value: keyCodeValue,
});
Object.defineProperty(emulatedKeyboardEvent, 'keyCode', {
value: keyCodeValue,
});
this.view.dispatchEvent(emulatedKeyboardEvent);
});
}
shouldComponentUpdate(nextProps: ElectronWebviewProps) {
return !shallowEquals(removeInitialSrcProp(this.props), removeInitialSrcProp(nextProps));
}
componentDidUpdate(prevProps: ElectronWebviewProps) {
Object.keys(changableProps).forEach((propName) => {
const propValue = this.props[propName];
if (propValue !== prevProps[propName]) {
this[changableProps[propName]](propValue);
}
});
}
updateClassName = (props = this.props) => {
if (this.ready && this.loaded) {
const className = `${props.className} ${props.hidden ? 'hidden' : ''}`;
return this.view.setAttribute('class', className);
}
}
// tslint:disable-next-line:function-name
UNSAFE_componentWillReceiveProps(nextProps: ElectronWebviewProps) {
if (this.props.hidden !== nextProps.hidden) {
this.updateClassName(nextProps);
}
}
focus() {
if (!this.view) return;
// Calling `.focus()` on an already focused webview actually blurs it.
// see https://github.com/electron/electron/issues/13697
if (document.activeElement && (document.activeElement as HTMLElement).blur) {
(document.activeElement as HTMLElement).blur();
}
this.view.focus();
}
setDevTools(open: boolean) {
if (open && !this.isDevToolsOpened()) {
this.openDevTools();
} else if (!open && this.isDevToolsOpened()) {
this.closeDevTools();
}
}
isReady() {
return this.ready;
}
render() {
return (
<div ref={(elt) => { this.ref = elt as HTMLElement; }} style={this.props.style as object || {}} />
);
}
}
export default ElectronWebview; | the_stack |
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
EventEmitter,
forwardRef,
Injector,
Input,
NgModule,
OnDestroy,
OnInit,
Output,
AfterViewInit,
ViewChild
} from '@angular/core';
import {ComboSelectValue, JigsawComboSelectModule, JigsawComboSelect} from "../combo-select/index";
import {TimeGr, TimeService, TimeWeekStart} from "../../common/service/time.service";
import {ArrayCollection} from "../../common/core/data/array-collection";
import {Time, TimeWeekDay, WeekTime} from "../../common/service/time.types";
import {GrItem, MarkDate} from "./date-picker";
import {TimeStep} from "./time-picker";
import {DropDownTrigger} from "../../common/directive/float/float";
import {AbstractJigsawComponent} from "../../common/common";
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {JigsawRangeDateTimePickerModule} from "./range-date-time-picker";
import {Subscription} from 'rxjs';
import {debounceTime} from 'rxjs/operators';
import {RequireMarkForCheck} from "../../common/decorator/mark-for-check";
import { CommonUtils } from '../../common/core/utils/common-utils';
export type RangeDate = { beginDate: WeekTime, endDate: WeekTime }
@Component({
selector: 'jigsaw-range-date-time-select, j-range-date-time-select',
template: `
<jigsaw-combo-select #comboSelect [(value)]="_$dateComboValue" [placeholder]="placeholder" [disabled]="disabled" [valid]="valid"
[openTrigger]="openTrigger" [closeTrigger]="closeTrigger" [width]="width ? width : 200"
(openChange)="_$onComboOpenChange($event)">
<ng-template>
<jigsaw-range-date-time-picker [(beginDate)]="_$beginDate" [(endDate)]="_$endDate" [gr]="gr" [limitStart]="limitStart"
[limitEnd]="limitEnd" [grItems]="grItems" [markDates]="markDates" [step]="step"
[weekStart]="weekStart" [firstWeekMustContains]="firstWeekMustContains"
[showConfirmButton]="showConfirmButton"
(change)="_$dateItemChange.emit()" (grChange)="_$grChange($event)">
</jigsaw-range-date-time-picker>
</ng-template>
</jigsaw-combo-select>
`,
host: {
'[class.jigsaw-range-date-time-select]': 'true',
'[style.min-width]': 'width'
},
providers: [
{provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => JigsawRangeDateTimeSelect), multi: true},
],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class JigsawRangeDateTimeSelect extends AbstractJigsawComponent implements ControlValueAccessor, OnInit, AfterViewInit, OnDestroy {
constructor(private _cdr: ChangeDetectorRef,
// @RequireMarkForCheck 需要用到,勿删
private _injector: Injector) {
super();
this._removeDateItemChangeSubscriber = this._$dateItemChange.pipe(debounceTime(100)).subscribe(() => {
let value = {beginDate: this._$beginDate, endDate: this._$endDate};
this._$setComboValue(value);
this.writeValue(value)
});
this._removeMulInputsChangeSubscriber = this._multipleInputsChange.pipe(debounceTime(100)).subscribe(() => {
this._changeRangeDateByGr();
})
}
@ViewChild('comboSelect')
private _comboSelect: JigsawComboSelect;
@Input()
@RequireMarkForCheck()
public valid: boolean = true;
private _gr: TimeGr = TimeGr.date;
/**
* @NoMarkForCheckRequired
*/
@Input()
public get gr(): TimeGr | string {
return this._gr;
}
public set gr(value: TimeGr | string) {
if (typeof value === 'string') {
value = TimeGr[value];
}
if (value == this._gr) return;
this._gr = <TimeGr>value;
if (this.initialized) {
this._multipleInputsChange.emit();
}
}
@Output()
public grChange = new EventEmitter<TimeGr>();
/**
* @internal
*/
public _$beginDate: WeekTime;
/**
* @internal
*/
public _$endDate: WeekTime;
private _date: RangeDate;
@RequireMarkForCheck()
@Input()
public get date(): RangeDate {
return this._date;
}
public set date(date: RangeDate) {
if (!this._isDateChanged(date, this.date)) return;
this._date = date;
if (this.initialized) {
this._multipleInputsChange.emit();
}
}
@Output()
public dateChange = new EventEmitter<RangeDate>();
/**
* @NoMarkForCheckRequired
*/
@Input()
public limitStart: Time;
/**
* @NoMarkForCheckRequired
*/
@Input()
public limitEnd: Time;
/**
* @NoMarkForCheckRequired
*/
@Input()
public grItems: GrItem[];
/**
* @NoMarkForCheckRequired
*/
@Input()
public markDates: MarkDate[];
/**
* @NoMarkForCheckRequired
*/
@Input()
public step: TimeStep;
private _weekStart: TimeWeekStart;
/**
* @NoMarkForCheckRequired
* 设置周开始日期,可选值 sun mon tue wed thu fri sat。
*/
@Input()
public get weekStart(): string | TimeWeekStart {
return this._weekStart;
}
public set weekStart(value: string | TimeWeekStart) {
if(CommonUtils.isUndefined(value)) {
return;
}
this._weekStart = typeof value === 'string' ? TimeWeekStart[value] : value;
// weekStart/janX必须预先设置好,用于初始化之后的计算
TimeService.setWeekStart(this._weekStart);
}
private _firstWeekMustContains: number;
/**
* @NoMarkForCheckRequired
* 设置一年的第一周要包含一月几号
*/
@Input()
public get firstWeekMustContains(): number {
return this._firstWeekMustContains;
}
public set firstWeekMustContains(value: number) {
if(CommonUtils.isUndefined(value)) {
return;
}
value = isNaN(value) || Number(value) < 1 ? 1 : Number(value);
this._firstWeekMustContains = value;
// weekStart/janX必须预先设置好,用于初始化之后的计算
TimeService.setFirstWeekOfYear(this._firstWeekMustContains);
}
@Input()
@RequireMarkForCheck()
public placeholder: string = '';
@Input()
@RequireMarkForCheck()
public disabled: boolean;
@Input()
@RequireMarkForCheck()
public openTrigger: 'mouseenter' | 'click' | 'none' | DropDownTrigger = DropDownTrigger.mouseenter;
@Input()
@RequireMarkForCheck()
public closeTrigger: 'mouseleave' | 'click' | 'none' | DropDownTrigger = DropDownTrigger.mouseleave;
/**
* 是否显示确认按钮
* @NoMarkForCheckRequired
*/
@Input()
public showConfirmButton: boolean = false;
/**
* @internal
*/
public _$grChange($event) {
this._gr = $event;
this.grChange.emit($event)
}
/**
* @internal
*/
public _$dateItemChange = new EventEmitter();
private _removeDateItemChangeSubscriber: Subscription;
private _multipleInputsChange = new EventEmitter();
private _removeMulInputsChangeSubscriber: Subscription;
/**
* @internal
*/
public _$dateComboValue: ArrayCollection<ComboSelectValue>;
/**
* @internal
*/
public _$setComboValue(date: RangeDate) {
if (!date) return;
let [beginDate, endDate] = [this._getDateStr(<string | TimeWeekDay>date.beginDate), this._getDateStr(<string | TimeWeekDay>date.endDate)];
if (!beginDate || !endDate) return;
this._$dateComboValue = new ArrayCollection([{
label: `${beginDate} - ${endDate}`,
closable: false
}]);
this._cdr.markForCheck();
}
private _getDateStr(date: string | TimeWeekDay) {
if (!((typeof date == 'string' && !date.includes('now')) ||
(date && date.hasOwnProperty('year') && date.hasOwnProperty('week')))) return null;
return typeof date == 'string' ? date : `${date.year}-${date.week}`;
}
public writeValue(date: RangeDate): void {
this._date = date;
this.dateChange.emit(date);
this._propagateChange(this._date);
}
private _changeRangeDateByGr() {
if (!this._isRangeDate(this.date)) return;
this._$beginDate = TimeService.getDateByGr(this.date.beginDate, this._gr);
this._$endDate = TimeService.getDateByGr(this.date.endDate, this._gr);
let convertDate = {
beginDate: this._$beginDate,
endDate: this._$endDate
};
this._$setComboValue(convertDate);
this.writeValue(convertDate);
this._cdr.markForCheck();
}
private _isDateChanged(date1: RangeDate, date2: RangeDate): boolean {
return !date1 || !date2 || date1.beginDate != date2.beginDate || date1.endDate != date2.endDate;
}
private _isRangeDate(date: any) {
return date && date.beginDate && date.endDate;
}
ngOnInit() {
super.ngOnInit();
this._multipleInputsChange.emit();
}
ngAfterViewInit() {
this._comboSelect._$options.size = { "minWidth": 0 };
}
ngOnDestroy() {
super.ngOnDestroy();
if (this._removeDateItemChangeSubscriber) {
this._removeDateItemChangeSubscriber.unsubscribe();
this._removeDateItemChangeSubscriber = null
}
if(this._removeMulInputsChangeSubscriber) {
this._removeMulInputsChangeSubscriber.unsubscribe();
this._removeMulInputsChangeSubscriber = null;
}
}
private _propagateChange: any = () => {
};
private _onTouched: any = () => {
};
public registerOnChange(fn: any): void {
this._propagateChange = fn;
}
public registerOnTouched(fn: any): void {
this._onTouched();
}
public setDisabledState(disabled: boolean): void {
this.disabled = disabled;
}
/**
* @internal
*/
public _$onComboOpenChange(optionState: boolean) {
this._onTouched();
}
}
@NgModule({
imports: [JigsawRangeDateTimePickerModule, JigsawComboSelectModule],
declarations: [JigsawRangeDateTimeSelect],
exports: [JigsawRangeDateTimeSelect]
})
export class JigsawRangeDateTimeSelectModule {
} | the_stack |
import React from 'react'
import { MetadataUtils } from '../../../core/model/element-metadata-utils'
import {
ElementInstanceMetadataMap,
UtopiaJSXComponent,
} from '../../../core/shared/element-template'
import { Imports, ElementPath } from '../../../core/shared/project-file-types'
import Utils from '../../../utils/utils'
import * as EP from '../../../core/shared/element-path'
import { ControlProps } from './new-canvas-controls'
import { Outline } from './outline'
import { anyInstanceYogaLayouted } from './select-mode/yoga-utils'
import { MarginControls } from './margin-controls'
import { PaddingControls } from './padding-controls'
import { MoveDragState, ResizeDragState, DragState } from '../canvas-types'
import { CanvasRectangle, offsetRect } from '../../../core/shared/math-utils'
import { fastForEach } from '../../../core/shared/utils'
import { isFeatureEnabled } from '../../../utils/feature-switches'
import { useColorTheme } from '../../../uuiui'
import { useEditorState } from '../../editor/store/store-hook'
import { KeysPressed } from '../../../utils/keyboard'
import { PositionOutline } from './position-outline'
import { stripNulls, uniqBy } from '../../../core/shared/array-utils'
export function getSelectionColor(
path: ElementPath,
metadata: ElementInstanceMetadataMap,
focusedElementPath: ElementPath | null,
colorTheme: any,
): string {
if (EP.isInsideFocusedComponent(path)) {
if (MetadataUtils.isFocusableComponent(path, metadata)) {
return colorTheme.canvasSelectionFocusableChild.value
} else {
return colorTheme.canvasSelectionNotFocusableChild.value
}
} else if (EP.isFocused(focusedElementPath, path)) {
return colorTheme.canvasSelectionIsolatedComponent.value
} else if (MetadataUtils.isFocusableComponent(path, metadata)) {
return colorTheme.canvasSelectionFocusable.value
} else {
return colorTheme.CanvasSelectionNotFocusable.value
}
}
export interface OutlineControlsProps extends ControlProps {
dragState: MoveDragState | ResizeDragState | null
keysPressed: KeysPressed
}
function isDraggingToMove(
dragState: MoveDragState | ResizeDragState | null,
target: ElementPath,
): dragState is MoveDragState {
// This is a bit of a cheeky cast because we only cast if the thing is target is one of the dragged elements
const targetIsDragged = EP.containsPath(target, dragState?.draggedElements ?? [])
return dragState != null && dragState?.type === 'MOVE_DRAG_STATE' && targetIsDragged
}
interface CenteredCrossSVGProps {
id: string
scale: number
centerX: number
centerY: number
}
const CenteredCrossSVG = React.memo(({ id, centerX, centerY, scale }: CenteredCrossSVGProps) => {
const colorTheme = useColorTheme()
return (
<svg
id={id}
style={{
left: centerX,
top: centerY,
position: 'absolute',
width: 6,
height: 6,
transformOrigin: 'center center',
transform: `translateX(-50%) translateY(-50%) scale(${1 / scale})`,
}}
width='4px'
height='4px'
viewBox='0 0 4 4'
version='1.1'
>
<g
stroke='none'
strokeWidth='1'
fill='none'
fillRule='evenodd'
strokeLinecap='round'
strokeLinejoin='round'
>
<g id='cross_svg' stroke={colorTheme.primary.value}>
<line x1='0.5' y1='0.5' x2='3.5' y2='3.5'></line>
<line x1='0.5' y1='3.5' x2='3.5' y2='0.5'></line>
</g>
</g>
</svg>
)
})
export const OutlineControls = (props: OutlineControlsProps) => {
const colorTheme = useColorTheme()
const { dragState } = props
const layoutInspectorSectionHovered = useEditorState(
(store) => store.editor.inspector.layoutSectionHovered,
'OutlineControls layoutInspectorSectionHovered',
)
const getDragStateFrame = React.useCallback(
(target: ElementPath): CanvasRectangle | null => {
if (isDraggingToMove(dragState, target)) {
const startingFrameAndTarget = dragState.originalFrames.find((frameAndTarget) =>
EP.pathsEqual(frameAndTarget.target, target),
)
if (
startingFrameAndTarget == null ||
startingFrameAndTarget.frame == null ||
dragState.drag == null
) {
return null
} else {
return offsetRect(startingFrameAndTarget.frame, dragState.drag)
}
} else {
return null
}
},
[dragState],
)
const getTargetFrame = React.useCallback(
(target: ElementPath): CanvasRectangle | null => {
const dragRect = getDragStateFrame(target)
return dragRect ?? MetadataUtils.getFrameInCanvasCoords(target, props.componentMetadata)
},
[getDragStateFrame, props.componentMetadata],
)
const getOverlayControls = React.useCallback(
(targets: ElementPath[]): Array<JSX.Element> => {
if (
isFeatureEnabled('Dragging Shows Overlay') &&
props.dragState != null &&
props.dragState?.type === 'MOVE_DRAG_STATE' &&
props.dragState.drag != null
) {
let result: Array<JSX.Element> = []
fastForEach(targets, (target) => {
const rect = MetadataUtils.getFrameInCanvasCoords(target, props.componentMetadata)
if (rect != null) {
result.push(
<div
key={`${EP.toComponentId(target)}-overlay`}
style={{
position: 'absolute',
boxSizing: 'border-box',
left: props.canvasOffset.x + rect.x,
top: props.canvasOffset.y + rect.y,
width: rect.width,
height: rect.height,
pointerEvents: 'none',
backgroundColor: '#FFADAD80',
}}
/>,
)
}
})
return result
} else {
return []
}
},
[props.canvasOffset.x, props.canvasOffset.y, props.componentMetadata, props.dragState],
)
const parentHighlights: React.ReactNode = React.useMemo(() => {
if (props.keysPressed['cmd'] || layoutInspectorSectionHovered) {
return props.selectedViews.map((view) => {
const parentPath = EP.parentPath(view)
if (parentPath != null) {
const parentFrame = MetadataUtils.getFrameInCanvasCoords(
parentPath,
props.componentMetadata,
)
if (parentFrame != null) {
return (
<>
<div
style={{
position: 'absolute',
left: parentFrame.x + props.canvasOffset.x,
top: parentFrame.y + props.canvasOffset.y,
width: parentFrame.width,
height: parentFrame.height,
border: `#007aff`,
}}
/>
<CenteredCrossSVG
id='parent-cross-top-left'
centerX={parentFrame.x + props.canvasOffset.x}
centerY={parentFrame.y + props.canvasOffset.y}
scale={props.scale}
/>
<CenteredCrossSVG
id='parent-cross-top-right'
scale={props.scale}
centerX={parentFrame.x + parentFrame.width + props.canvasOffset.x}
centerY={parentFrame.y + props.canvasOffset.y}
/>
<CenteredCrossSVG
id='parent-cross-bottom-right'
scale={props.scale}
centerX={parentFrame.x + parentFrame.width + props.canvasOffset.x}
centerY={parentFrame.y + parentFrame.height + props.canvasOffset.y}
/>
<CenteredCrossSVG
id='parent-cross-bottom-left'
scale={props.scale}
centerX={parentFrame.x + props.canvasOffset.x}
centerY={parentFrame.y + parentFrame.height + props.canvasOffset.y}
/>
</>
)
} else {
return null
}
} else {
return null
}
})
} else {
return null
}
}, [
layoutInspectorSectionHovered,
props.canvasOffset.x,
props.canvasOffset.y,
props.componentMetadata,
props.keysPressed,
props.selectedViews,
props.scale,
])
const parentOutlines: (JSX.Element | null)[] = React.useMemo(() => {
const targetParents = uniqBy(
stripNulls(props.selectedViews.map((view) => EP.parentPath(view))),
EP.pathsEqual,
)
return targetParents.map((parentPath) => {
const parentElement = MetadataUtils.findElementByElementPath(
props.componentMetadata,
parentPath,
)
const parentFrame = MetadataUtils.getFrameInCanvasCoords(parentPath, props.componentMetadata)
if (
MetadataUtils.isFlexLayoutedContainer(parentElement) ||
MetadataUtils.isGridLayoutedContainer(parentElement)
) {
if (parentFrame != null) {
return (
<div
key={EP.toString(parentPath)}
style={{
position: 'absolute',
left: parentFrame.x + props.canvasOffset.x,
top: parentFrame.y + props.canvasOffset.y,
width: parentFrame.width,
height: parentFrame.height,
outlineStyle: 'dotted',
outlineColor: colorTheme.primary.value,
outlineWidth: 1 / props.scale,
}}
/>
)
} else {
return null
}
} else {
return null
}
})
}, [
colorTheme.primary.value,
props.canvasOffset.x,
props.canvasOffset.y,
props.componentMetadata,
props.scale,
props.selectedViews,
])
let selectionOutlines: Array<JSX.Element> = getOverlayControls(props.selectedViews)
const targetPaths =
props.dragState != null ? props.dragState.draggedElements : props.selectedViews
const selectionColors = useEditorState((store) => {
return targetPaths.map((path) => {
return getSelectionColor(
path,
store.editor.jsxMetadata,
store.editor.focusedElementPath,
colorTheme,
)
})
}, 'OutlineControls')
fastForEach(targetPaths, (selectedView, index) => {
const rect = getTargetFrame(selectedView)
if (rect == null) {
// early return as we can't draw a selection outline
return
}
const keyPrefix = EP.toComponentId(selectedView)
const instance = MetadataUtils.findElementByElementPath(props.componentMetadata, selectedView)
const createsYogaLayout = MetadataUtils.isFlexLayoutedContainer(instance)
const selectionColor = selectionColors[index]
if (props.dragState == null) {
const margin = MetadataUtils.getElementMargin(selectedView, props.componentMetadata)
selectionOutlines.push(
<MarginControls
key={`${keyPrefix}-margin-controls`}
canvasOffset={props.canvasOffset}
scale={props.scale}
margin={margin}
frame={rect}
/>,
)
const padding = MetadataUtils.getElementPadding(selectedView, props.componentMetadata)
selectionOutlines.push(
<PaddingControls
key={`${keyPrefix}-padding-controls`}
canvasOffset={props.canvasOffset}
scale={props.scale}
padding={padding}
frame={rect}
/>,
)
}
if (MetadataUtils.isPositionAbsolute(instance)) {
selectionOutlines.push(
<PositionOutline
key={`${keyPrefix}-position-outline`}
frame={rect}
path={selectedView}
scale={props.scale}
canvasOffset={props.canvasOffset}
/>,
)
}
// FIXME the striped overlay needs to be separated from this
selectionOutlines.push(
<Outline
key={`${keyPrefix}-outline-control`}
rect={rect}
offset={props.canvasOffset}
scale={props.scale}
color={selectionColor}
striped={createsYogaLayout}
stripedColor={colorTheme.canvasSelectionAlternateOutlineYogaParent.shade(50).value}
/>,
)
})
let multiSelectOutline: JSX.Element | undefined
if (targetPaths.length > 1 && EP.areAllElementsInSameInstance(targetPaths)) {
const globalFrames = targetPaths.map((selectedView) => getTargetFrame(selectedView))
const boundingBox = Utils.boundingRectangleArray(globalFrames)
if (boundingBox != null) {
const outlineColor = colorTheme.canvasSelectionSecondaryOutline.value
multiSelectOutline = (
<Outline
rect={boundingBox}
offset={props.canvasOffset}
scale={props.scale}
color={outlineColor}
/>
)
}
}
return (
<>
{parentOutlines}
{parentHighlights}
{selectionOutlines}
{multiSelectOutline}
</>
)
} | the_stack |
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
jest.mock('lodash', () => ({
debounce: (fn: any) => fn,
}));
const nextTick = () => new Promise((res) => process.nextTick(res));
import {
EuiEmptyPrompt,
EuiListGroup,
EuiListGroupItem,
EuiLoadingSpinner,
EuiPagination,
EuiTablePagination,
} from '@elastic/eui';
import { IconType } from '@elastic/eui';
import { shallow } from 'enzyme';
import React from 'react';
import * as sinon from 'sinon';
import { SavedObjectFinderUi as SavedObjectFinder } from './saved_object_finder';
import { coreMock } from '../../../../core/public/mocks';
describe('SavedObjectsFinder', () => {
const doc = {
id: '1',
type: 'search',
attributes: { title: 'Example title' },
};
const doc2 = {
id: '2',
type: 'search',
attributes: { title: 'Another title' },
};
const doc3 = { type: 'vis', id: '3', attributes: { title: 'Vis' } };
const searchMetaData = [
{
type: 'search',
name: 'Search',
getIconForSavedObject: () => 'search' as IconType,
showSavedObject: () => true,
},
];
it('should call saved object client on startup', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({ savedObjects: [doc] })
);
core.uiSettings.get.mockImplementation(() => 10);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
savedObjectMetaData={searchMetaData}
/>
);
wrapper.instance().componentDidMount!();
expect(core.savedObjects.client.find).toHaveBeenCalledWith({
type: ['search'],
fields: ['title'],
search: undefined,
page: 1,
perPage: 10,
searchFields: ['title^3', 'description'],
defaultSearchOperator: 'AND',
});
});
it('should list initial items', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({ savedObjects: [doc] })
);
core.uiSettings.get.mockImplementation(() => 10);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
savedObjectMetaData={searchMetaData}
/>
);
wrapper.instance().componentDidMount!();
await nextTick();
expect(
wrapper.containsMatchingElement(<EuiListGroupItem iconType="search" label="Example title" />)
).toEqual(true);
});
it('should call onChoose on item click', async () => {
const chooseStub = sinon.stub();
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({ savedObjects: [doc] })
);
core.uiSettings.get.mockImplementation(() => 10);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
onChoose={chooseStub}
savedObjectMetaData={searchMetaData}
/>
);
wrapper.instance().componentDidMount!();
await nextTick();
wrapper.find(EuiListGroupItem).first().simulate('click');
expect(chooseStub.calledWith('1', 'search', `${doc.attributes.title} (Search)`, doc)).toEqual(
true
);
});
describe('sorting', () => {
it('should list items ascending', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({ savedObjects: [doc, doc2] })
);
core.uiSettings.get.mockImplementation(() => 10);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
savedObjectMetaData={searchMetaData}
/>
);
wrapper.instance().componentDidMount!();
await nextTick();
const list = wrapper.find(EuiListGroup);
expect(list.childAt(0).key()).toBe('2');
expect(list.childAt(1).key()).toBe('1');
});
it('should list items descending', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({ savedObjects: [doc, doc2] })
);
core.uiSettings.get.mockImplementation(() => 10);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
savedObjectMetaData={searchMetaData}
/>
);
wrapper.instance().componentDidMount!();
await nextTick();
wrapper.setState({ sortDirection: 'desc' });
const list = wrapper.find(EuiListGroup);
expect(list.childAt(0).key()).toBe('1');
expect(list.childAt(1).key()).toBe('2');
});
});
it('should not show the saved objects which get filtered by showSavedObject', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({ savedObjects: [doc, doc2] })
);
core.uiSettings.get.mockImplementation(() => 10);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
savedObjectMetaData={[
{
type: 'search',
name: 'Search',
getIconForSavedObject: () => 'search',
showSavedObject: ({ id }) => id !== '1',
},
]}
/>
);
wrapper.instance().componentDidMount!();
await nextTick();
const list = wrapper.find(EuiListGroup);
expect(list.childAt(0).key()).toBe('2');
expect(list.children().length).toBe(1);
});
describe('search', () => {
it('should request filtered list on search input', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({ savedObjects: [doc, doc2] })
);
core.uiSettings.get.mockImplementation(() => 10);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
savedObjectMetaData={searchMetaData}
/>
);
wrapper.instance().componentDidMount!();
await nextTick();
wrapper
.find('[data-test-subj="savedObjectFinderSearchInput"]')
.first()
.simulate('change', { target: { value: 'abc' } });
expect(core.savedObjects.client.find).toHaveBeenCalledWith({
type: ['search'],
fields: ['title'],
search: 'abc*',
page: 1,
perPage: 10,
searchFields: ['title^3', 'description'],
defaultSearchOperator: 'AND',
});
});
it('should include additional fields in search if listed in meta data', async () => {
const core = coreMock.createStart();
core.uiSettings.get.mockImplementation(() => 10);
(core.savedObjects.client.find as jest.Mock).mockResolvedValue({ savedObjects: [] });
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
savedObjectMetaData={[
{
type: 'type1',
name: '',
getIconForSavedObject: () => 'search',
includeFields: ['field1', 'field2'],
},
{
type: 'type2',
name: '',
getIconForSavedObject: () => 'search',
includeFields: ['field2', 'field3'],
},
]}
/>
);
wrapper.instance().componentDidMount!();
await nextTick();
wrapper
.find('[data-test-subj="savedObjectFinderSearchInput"]')
.first()
.simulate('change', { target: { value: 'abc' } });
expect(core.savedObjects.client.find).toHaveBeenCalledWith({
type: ['type1', 'type2'],
fields: ['title', 'field1', 'field2', 'field3'],
search: 'abc*',
page: 1,
perPage: 10,
searchFields: ['title^3', 'description'],
defaultSearchOperator: 'AND',
});
});
it('should respect response order on search input', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({ savedObjects: [doc, doc2] })
);
core.uiSettings.get.mockImplementation(() => 10);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
savedObjectMetaData={searchMetaData}
/>
);
wrapper.instance().componentDidMount!();
await nextTick();
wrapper
.find('[data-test-subj="savedObjectFinderSearchInput"]')
.first()
.simulate('change', { target: { value: 'abc' } });
await nextTick();
const list = wrapper.find(EuiListGroup);
expect(list.childAt(0).key()).toBe('1');
expect(list.childAt(1).key()).toBe('2');
});
});
it('should request multiple saved object types at once', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({ savedObjects: [doc, doc2] })
);
core.uiSettings.get.mockImplementation(() => 10);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
savedObjectMetaData={[
{
type: 'search',
name: 'Search',
getIconForSavedObject: () => 'search',
},
{
type: 'vis',
name: 'Vis',
getIconForSavedObject: () => 'visLine',
},
]}
/>
);
wrapper.instance().componentDidMount!();
expect(core.savedObjects.client.find).toHaveBeenCalledWith({
type: ['search', 'vis'],
fields: ['title'],
search: undefined,
page: 1,
perPage: 10,
searchFields: ['title^3', 'description'],
defaultSearchOperator: 'AND',
});
});
describe('filter', () => {
const metaDataConfig = [
{
type: 'search',
name: 'Search',
getIconForSavedObject: () => 'search' as IconType,
},
{
type: 'vis',
name: 'Vis',
getIconForSavedObject: () => 'document' as IconType,
},
];
it('should not render filter buttons if disabled', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({
savedObjects: [doc, doc2, doc3],
})
);
core.uiSettings.get.mockImplementation(() => 10);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
showFilter={false}
savedObjectMetaData={metaDataConfig}
/>
);
wrapper.instance().componentDidMount!();
await nextTick();
expect(wrapper.find('[data-test-subj="savedObjectFinderFilter-search"]').exists()).toBe(
false
);
});
it('should not render filter buttons if there is only one type in the list', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({
savedObjects: [doc, doc2],
})
);
core.uiSettings.get.mockImplementation(() => 10);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
showFilter={true}
savedObjectMetaData={metaDataConfig}
/>
);
wrapper.instance().componentDidMount!();
await nextTick();
expect(wrapper.find('[data-test-subj="savedObjectFinderFilter-search"]').exists()).toBe(
false
);
});
it('should apply filter if selected', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({
savedObjects: [doc, doc2, doc3],
})
);
core.uiSettings.get.mockImplementation(() => 10);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
showFilter={true}
savedObjectMetaData={metaDataConfig}
/>
);
wrapper.instance().componentDidMount!();
await nextTick();
wrapper.setState({ filteredTypes: ['vis'] });
const list = wrapper.find(EuiListGroup);
expect(list.childAt(0).key()).toBe('3');
expect(list.children().length).toBe(1);
wrapper.setState({ filteredTypes: ['vis', 'search'] });
expect(wrapper.find(EuiListGroup).children().length).toBe(3);
});
});
it('should display no items message if there are no items', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({ savedObjects: [] })
);
core.uiSettings.get.mockImplementation(() => 10);
const noItemsMessage = <span id="myNoItemsMessage" />;
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
noItemsMessage={noItemsMessage}
savedObjectMetaData={searchMetaData}
/>
);
wrapper.instance().componentDidMount!();
await nextTick();
expect(wrapper.find(EuiEmptyPrompt).first().prop('body')).toEqual(noItemsMessage);
});
describe('pagination', () => {
const longItemList = new Array(50).fill(undefined).map((_, i) => ({
id: String(i),
type: 'search',
attributes: {
title: `Title ${i < 10 ? '0' : ''}${i}`,
},
}));
it('should show a table pagination with initial per page', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({ savedObjects: longItemList })
);
core.uiSettings.get.mockImplementation(() => 10);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
initialPageSize={15}
savedObjectMetaData={searchMetaData}
/>
);
wrapper.instance().componentDidMount!();
await nextTick();
expect(wrapper.find(EuiTablePagination).first().prop('itemsPerPage')).toEqual(15);
expect(wrapper.find(EuiListGroup).children().length).toBe(15);
});
it('should allow switching the page size', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({ savedObjects: longItemList })
);
core.uiSettings.get.mockImplementation(() => 10);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
initialPageSize={15}
savedObjectMetaData={searchMetaData}
/>
);
wrapper.instance().componentDidMount!();
await nextTick();
wrapper.find(EuiTablePagination).first().prop('onChangeItemsPerPage')!(5);
expect(wrapper.find(EuiListGroup).children().length).toBe(5);
});
it('should switch page correctly', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({ savedObjects: longItemList })
);
core.uiSettings.get.mockImplementation(() => 10);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
initialPageSize={15}
savedObjectMetaData={searchMetaData}
/>
);
wrapper.instance().componentDidMount!();
await nextTick();
wrapper.find(EuiTablePagination).first().prop('onChangePage')!(1);
expect(wrapper.find(EuiListGroup).children().first().key()).toBe('15');
});
it('should show an ordinary pagination for fixed page sizes', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({ savedObjects: longItemList })
);
core.uiSettings.get.mockImplementation(() => 10);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
fixedPageSize={33}
savedObjectMetaData={searchMetaData}
/>
);
wrapper.instance().componentDidMount!();
await nextTick();
expect(wrapper.find(EuiPagination).first().prop('pageCount')).toEqual(2);
expect(wrapper.find(EuiListGroup).children().length).toBe(33);
});
it('should switch page correctly for fixed page sizes', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({ savedObjects: longItemList })
);
core.uiSettings.get.mockImplementation(() => 10);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
fixedPageSize={33}
savedObjectMetaData={searchMetaData}
/>
);
wrapper.instance().componentDidMount!();
await nextTick();
wrapper.find(EuiPagination).first().prop('onPageClick')!(1);
expect(wrapper.find(EuiListGroup).children().first().key()).toBe('33');
});
});
describe('loading state', () => {
it('should display a spinner during initial loading', () => {
const core = coreMock.createStart();
(core.savedObjects.client.find as jest.Mock).mockResolvedValue({ savedObjects: [] });
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
savedObjectMetaData={searchMetaData}
/>
);
expect(wrapper.containsMatchingElement(<EuiLoadingSpinner />)).toBe(true);
});
it('should hide the spinner if data is shown', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({ savedObjects: [doc] })
);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
savedObjectMetaData={[
{
type: 'search',
name: 'Search',
getIconForSavedObject: () => 'search',
},
]}
/>
);
wrapper.instance().componentDidMount!();
await nextTick();
expect(wrapper.containsMatchingElement(<EuiLoadingSpinner />)).toBe(false);
});
it('should not show the spinner if there are already items', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({ savedObjects: [doc] })
);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
savedObjectMetaData={searchMetaData}
/>
);
wrapper.instance().componentDidMount!();
await nextTick();
wrapper
.find('[data-test-subj="savedObjectFinderSearchInput"]')
.first()
.simulate('change', { target: { value: 'abc' } });
wrapper.update();
expect(wrapper.containsMatchingElement(<EuiLoadingSpinner />)).toBe(false);
});
});
it('should render with children', async () => {
const core = coreMock.createStart();
((core.savedObjects.client.find as any) as jest.SpyInstance).mockImplementation(() =>
Promise.resolve({ savedObjects: [doc, doc2] })
);
core.uiSettings.get.mockImplementation(() => 10);
const wrapper = shallow(
<SavedObjectFinder
savedObjects={core.savedObjects}
uiSettings={core.uiSettings}
savedObjectMetaData={[
{
type: 'search',
name: 'Search',
getIconForSavedObject: () => 'search',
},
{
type: 'vis',
name: 'Vis',
getIconForSavedObject: () => 'visLine',
},
]}
>
<button id="testChildButton">Dummy text</button>
</SavedObjectFinder>
);
expect(wrapper.exists('#testChildButton')).toBe(true);
});
}); | the_stack |
import type { Processor } from '../lib';
import { flatColors } from './tools';
const utilities: { [key:string]: string[]} = {
// Layout
columns: [
'columns-${static}',
'columns-${float}',
'columns-${size}',
'columns-${int}xl',
],
container: [
'container',
],
objectPosition: [
'object-${static}',
],
inset: [
'inset-${static}',
'inset-${float}',
'inset-${fraction}',
'inset-${size}',
'inset-y-${static}',
'inset-y-${float}',
'inset-y-${fraction}',
'inset-y-${size}',
'inset-x-${static}',
'inset-x-${float}',
'inset-x-${fraction}',
'inset-x-${size}',
'top-${static}',
'top-${float}',
'top-${fraction}',
'top-${size}',
'right-${static}',
'right-${float}',
'right-${fraction}',
'right-${size}',
'bottom-${static}',
'bottom-${float}',
'bottom-${fraction}',
'bottom-${size}',
'left-${static}',
'left-${float}',
'left-${fraction}',
'left-${size}',
],
zIndex: [
'z-${static}',
'z-${int}',
],
// Flexbox
flex: [
'flex-${static}',
],
flexGrow: [
'flex-grow-${static}',
],
flexShrink: [
'flex-shrink-${static}',
],
order: [
'order-${static}',
'order-${int}',
],
// Grid
gridTemplateColumns: [
'grid-cols-${static}',
'grid-cols-${int}',
],
gridTemplateRows: [
'grid-rows-${static}',
'grid-rows-${int}',
],
gridColumn: [
'col-${static}',
'col-span-${int}',
],
gridColumnEnd: [
'col-end-${static}',
'col-end-${int}',
],
gridColumnStart: [
'col-start-${static}',
'col-start-${int}',
],
gridRow: [
'row-${static}',
'row-span-${int}',
],
gridRowEnd: [
'row-end-${static}',
'row-end-${int}',
],
gridRowStart: [
'row-start-${static}',
'row-start-${int}',
],
gap: [
'gap-${static}',
'gap-x-${static}',
'gap-y-${static}',
'gap-${float}',
'gap-x-${float}',
'gap-y-${float}',
'gap-${size}',
'gap-x-${size}',
'gap-y-${size}',
],
// Box Alignment
// Spacing
padding: [
'p-${static}',
'py-${static}',
'px-${static}',
'pt-${static}',
'pr-${static}',
'pb-${static}',
'pl-${static}',
'p-${float}',
'py-${float}',
'px-${float}',
'pt-${float}',
'pr-${float}',
'pb-${float}',
'pl-${float}',
'p-${size}',
'py-${size}',
'px-${size}',
'pt-${size}',
'pr-${size}',
'pb-${size}',
'pl-${size}',
],
margin: [
'm-${static}',
'my-${static}',
'mx-${static}',
'mt-${static}',
'mr-${static}',
'mb-${static}',
'ml-${static}',
'm-${float}',
'my-${float}',
'mx-${float}',
'mt-${float}',
'mr-${float}',
'mb-${float}',
'ml-${float}',
'm-${size}',
'my-${size}',
'mx-${size}',
'mt-${size}',
'mr-${size}',
'mb-${size}',
'ml-${size}',
],
space: [
'space-y-${static}',
'space-y-reverse',
'space-x-${static}',
'space-x-reverse',
'space-y-${float}',
'space-x-${float}',
],
width: [
'w-${static}',
'w-${float}',
'w-${fraction}',
'w-${int}xl',
'w-${size}',
],
minWidth: [
'min-w-${static}',
'min-w-${float}',
'min-w-${fraction}',
'min-w-${int}xl',
'min-w-${size}',
],
maxWidth: [
'max-w-${static}',
'max-w-${float}',
'max-w-${fraction}',
'max-w-${int}xl',
'max-w-${size}',
],
height: [
'h-${static}',
'h-${float}',
'h-${fraction}',
'h-${int}xl',
'h-${size}',
],
minHeight: [
'min-h-${static}',
'min-h-${float}',
'min-h-${fraction}',
'min-h-${int}xl',
'min-h-${size}',
],
maxHeight: [
'max-h-${static}',
'max-h-${float}',
'max-h-${fraction}',
'max-h-${int}xl',
'max-h-${size}',
],
// Typography
fontSize: [
'text-${static}',
'text-${int}xl',
],
textOpacity: [
'text-opacity-${static}',
'text-opacity-${int<=100}',
],
textColor: [
'text-${color}',
],
fontFamily: [
'font-${static}',
],
fontWeight: [
'font-${static}',
'font-${int}',
],
letterSpacing: [
'tracking-${static}',
'tracking-${size}',
],
lineHeight: [
'leading-${static}',
'leading-${int}',
'leading-${size}',
],
listStyleType: [
'list-${static}',
],
placeholderColor: [
'placeholder-${color}',
],
placeholderOpacity: [
'placeholder-opacity-${static}',
'placeholder-opacity-${int<=100}',
],
// Backgrounds
backgroundColor: [
'bg-${color}',
],
backgroundOpacity: [
'bg-opacity-${static}',
'bg-opacity-${int<=100}',
],
backgroundPosition: [
'bg-${static}',
],
backgroundSize: [
'bg-${static}',
],
backgroundImage: [
'bg-${static}',
],
gradientColorStops: [
'from-${color}',
'via-${color}',
'to-${color}',
],
// Borders
borderRadius: [
'rounded-${static}',
'rounded-t-${static}',
'rounded-l-${static}',
'rounded-r-${static}',
'rounded-b-${static}',
'rounded-tl-${static}',
'rounded-tr-${static}',
'rounded-br-${static}',
'rounded-bl-${static}',
'rounded-${int}xl',
'rounded-${size}',
'rounded-t-${int}xl',
'rounded-t-${size}',
'rounded-l-${int}xl',
'rounded-l-${size}',
'rounded-r-${int}xl',
'rounded-r-${size}',
'rounded-b-${int}xl',
'rounded-b-${size}',
'rounded-tl-${int}xl',
'rounded-tl-${size}',
'rounded-tr-${int}xl',
'rounded-tr-${size}',
'rounded-br-${int}xl',
'rounded-br-${size}',
'rounded-bl-${int}xl',
'rounded-bl-${size}',
],
borderWidth: [
'border-${static}',
'border-${int}',
'border-${size}',
'border-t-${int}',
'border-t-${size}',
'border-r-${int}',
'border-r-${size}',
'border-b-${int}',
'border-b-${size}',
'border-l-${int}',
'border-l-${size}',
],
borderColor: [
'border-${color}',
],
borderOpacity: [
'border-opacity-${static}',
'border-opacity-${int<=100}',
],
divideWidth: [
'divide-y-reverse',
'divide-x-reverse',
'divide-y-${int}',
'divide-x-${int}',
],
divideColor: [
'divide-${color}',
],
divideOpacity: [
'divide-${static}',
'divide-opacity-${int<=100}',
],
ringOffsetWidth: [
'ring-offset-${static}',
'ring-offset-${int}',
],
ringOffsetColor: [
'ring-offset-${color}',
],
ringWidth: [
'ring-${static}',
'ring-${int}',
],
ringColor: [
'ring-${color}',
],
ringOpacity: [
'ring-${static}',
'ring-opacity-${int<=100}',
],
// Effects
boxShadow: [
'shadow-${static}',
],
opacity: [
'opacity-${static}',
'opacity-${int<=100}',
],
transition: [
'transition-${static}',
],
transitionDuration: [
'duration-${static}',
'duration-${int}',
],
transitionTimingFunction: [
'ease-${static}',
],
transitionDelay: [
'delay-${static}',
'delay-${int}',
],
animation: [
'animate-${static}',
],
// Transforms
transformOrigin: [
'origin-${static}',
],
scale: [
'scale-${static}',
'scale-${int}',
'scale-x-${static}',
'scale-x-${int}',
'scale-y-${static}',
'scale-y-${int}',
],
rotate: [
'rotate-${static}',
'rotate-${float}',
],
translate: [
'translate-${static}',
'translate-x-${static}',
'translate-y-${static}',
'translate-x-${float}',
'translate-x-${fraction}',
'translate-x-${size}',
'translate-y-${float}',
'translate-y-${fraction}',
'translate-y-${size}',
],
skew: [
'skew-x-${static}',
'skew-x-${float}',
'skew-y-${static}',
'skew-y-${float}',
],
cursor: [
'cursor-${static}',
],
// Interactivity
outline: [
'outline-${static}',
],
outlineColor: [
'outline-${color}',
'outline-solid-${color}',
'outline-dotted-${color}',
],
// SVG
fill: [
'fill-${color}',
],
// Stroke
stroke: [
'stroke-${color}',
],
strokeWidth: [
'stroke-${int}',
],
// Plugins
typography: [
'prose-sm',
'prose',
'prose-lg',
'prose-xl',
'prose-2xl',
'prose-red',
'prose-yellow',
'prose-green',
'prose-blue',
'prose-indigo',
'prose-purple',
'prose-pink',
],
aspectRatio: [
'aspect-none',
'aspect-auto',
'aspect-square',
'aspect-video',
'aspect-w-${float}',
'aspect-h-${float}',
'aspect-${fraction}',
],
lineClamp: [
'line-clamp-none',
'line-clamp-${int}',
],
filter: [
'filter-${static}',
],
backdropFilter: [
'backdrop-${static}',
],
basis: [
'basis-${static}',
'basis-${float}',
'basis-${size}',
'basis-${fraction}',
],
blur: [
'blur-${static}',
'blur-${float}',
'blur-${size}',
],
willChange: [
'will-change-auto',
'will-change-scroll',
'will-change-contents',
'will-change-transform',
],
touchAction: [
'touch-auto',
'touch-none',
'touch-pan-x',
'touch-pan-left',
'touch-pan-right',
'touch-pan-y',
'touch-pan-up',
'touch-pan-down',
'touch-pinch-zoom',
'touch-manipulation',
],
scrollBehavior: [
'scroll-auto',
'scroll-smooth',
],
shadow: [
'shadow-${static}',
],
};
const negative: { [key:string]: true} = {
inset: true,
zIndex: true,
order: true,
margin: true,
space: true,
letterSpacing: true,
rotate: true,
translate: true,
skew: true,
};
export function generateCompletions(processor: Processor): { static: string[], color: string[], dynamic: string[]} {
const completions : {
static: string[],
color: string[],
dynamic: string[]
} = { static: [], color: [], dynamic: [] };
const colors = flatColors(processor.theme('colors') as {[key:string]:string|{[key:string]:string}});
for (const [config, list] of Object.entries(utilities)) {
list.forEach(utility => {
const mark = utility.search(/\$/);
if (mark === -1) {
completions.static.push(utility);
} else {
const prefix = utility.slice(0, mark-1);
const suffix = utility.slice(mark);
switch(suffix) {
case '${static}':
completions.static = completions.static.concat(Object.keys(processor.theme(config, {}) as any).map(i => i === 'DEFAULT' ? prefix : i.charAt(0) === '-' ? `-${prefix}${i}` : `${prefix}-${i}`));
break;
case '${color}':
for (const key of Object.keys(flatColors(processor.theme(config, colors) as any))) {
if (key !== 'DEFAULT')
completions.color.push(`${prefix}-${key}`);
}
break;
default:
completions.dynamic.push(utility);
if (config in negative) completions.dynamic.push(`-${utility}`);
break;
}
}
});
}
return completions;
} | the_stack |
import Logger from '@joplin/lib/Logger';
import { PluginMessage } from './services/plugins/PluginRunner';
import shim from '@joplin/lib/shim';
import { isCallbackUrl } from '@joplin/lib/callbackUrlUtils';
const { BrowserWindow, Tray, screen } = require('electron');
const url = require('url');
const path = require('path');
const { dirname } = require('@joplin/lib/path-utils');
const fs = require('fs-extra');
const { ipcMain } = require('electron');
interface RendererProcessQuitReply {
canClose: boolean;
}
interface PluginWindows {
[key: string]: any;
}
export default class ElectronAppWrapper {
private logger_: Logger = null;
private electronApp_: any;
private env_: string;
private isDebugMode_: boolean;
private profilePath_: string;
private win_: any = null;
private willQuitApp_: boolean = false;
private tray_: any = null;
private buildDir_: string = null;
private rendererProcessQuitReply_: RendererProcessQuitReply = null;
private pluginWindows_: PluginWindows = {};
private initialCallbackUrl_: string = null;
constructor(electronApp: any, env: string, profilePath: string, isDebugMode: boolean, initialCallbackUrl: string) {
this.electronApp_ = electronApp;
this.env_ = env;
this.isDebugMode_ = isDebugMode;
this.profilePath_ = profilePath;
this.initialCallbackUrl_ = initialCallbackUrl;
}
electronApp() {
return this.electronApp_;
}
setLogger(v: Logger) {
this.logger_ = v;
}
logger() {
return this.logger_;
}
window() {
return this.win_;
}
env() {
return this.env_;
}
initialCallbackUrl() {
return this.initialCallbackUrl_;
}
createWindow() {
// Set to true to view errors if the application does not start
const debugEarlyBugs = this.env_ === 'dev' || this.isDebugMode_;
const windowStateKeeper = require('electron-window-state');
const stateOptions: any = {
defaultWidth: Math.round(0.8 * screen.getPrimaryDisplay().workArea.width),
defaultHeight: Math.round(0.8 * screen.getPrimaryDisplay().workArea.height),
file: `window-state-${this.env_}.json`,
};
if (this.profilePath_) stateOptions.path = this.profilePath_;
// Load the previous state with fallback to defaults
const windowState = windowStateKeeper(stateOptions);
const windowOptions: any = {
x: windowState.x,
y: windowState.y,
width: windowState.width,
height: windowState.height,
minWidth: 100,
minHeight: 100,
backgroundColor: '#fff', // required to enable sub pixel rendering, can't be in css
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
spellcheck: true,
enableRemoteModule: true,
},
webviewTag: true,
// We start with a hidden window, which is then made visible depending on the showTrayIcon setting
// https://github.com/laurent22/joplin/issues/2031
show: debugEarlyBugs,
};
// Linux icon workaround for bug https://github.com/electron-userland/electron-builder/issues/2098
// Fix: https://github.com/electron-userland/electron-builder/issues/2269
if (shim.isLinux()) windowOptions.icon = path.join(__dirname, '..', 'build/icons/128x128.png');
this.win_ = new BrowserWindow(windowOptions);
require('@electron/remote/main').enable(this.win_.webContents);
if (!screen.getDisplayMatching(this.win_.getBounds())) {
const { width: windowWidth, height: windowHeight } = this.win_.getBounds();
const { width: primaryDisplayWidth, height: primaryDisplayHeight } = screen.getPrimaryDisplay().workArea;
this.win_.setPosition(primaryDisplayWidth / 2 - windowWidth, primaryDisplayHeight / 2 - windowHeight);
}
this.win_.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true,
}));
// Note that on Windows, calling openDevTools() too early results in a white window with no error message.
// Waiting for one of the ready events might work but they might not be triggered if there's an error, so
// the easiest is to use a timeout. Keep in mind that if you get a white window on Windows it might be due
// to this line though.
if (debugEarlyBugs) {
setTimeout(() => {
try {
this.win_.webContents.openDevTools();
} catch (error) {
// This will throw an exception "Object has been destroyed" if the app is closed
// in less that the timeout interval. It can be ignored.
console.warn('Error opening dev tools', error);
}
}, 3000);
}
this.win_.on('close', (event: any) => {
// If it's on macOS, the app is completely closed only if the user chooses to close the app (willQuitApp_ will be true)
// otherwise the window is simply hidden, and will be re-open once the app is "activated" (which happens when the
// user clicks on the icon in the task bar).
// On Windows and Linux, the app is closed when the window is closed *except* if the tray icon is used. In which
// case the app must be explicitly closed with Ctrl+Q or by right-clicking on the tray icon and selecting "Exit".
let isGoingToExit = false;
if (process.platform === 'darwin') {
if (this.willQuitApp_) {
isGoingToExit = true;
} else {
event.preventDefault();
this.hide();
}
} else {
if (this.trayShown() && !this.willQuitApp_) {
event.preventDefault();
this.win_.hide();
} else {
isGoingToExit = true;
}
}
if (isGoingToExit) {
if (!this.rendererProcessQuitReply_) {
// If we haven't notified the renderer process yet, do it now
// so that it can tell us if we can really close the app or not.
// Search for "appClose" event for closing logic on renderer side.
event.preventDefault();
this.win_.webContents.send('appClose');
} else {
// If the renderer process has responded, check if we can close or not
if (this.rendererProcessQuitReply_.canClose) {
// Really quit the app
this.rendererProcessQuitReply_ = null;
this.win_ = null;
} else {
// Wait for renderer to finish task
event.preventDefault();
this.rendererProcessQuitReply_ = null;
}
}
}
});
ipcMain.on('asynchronous-message', (_event: any, message: string, args: any) => {
if (message === 'appCloseReply') {
// We got the response from the renderer process:
// save the response and try quit again.
this.rendererProcessQuitReply_ = args;
this.electronApp_.quit();
}
});
// This handler receives IPC messages from a plugin or from the main window,
// and forwards it to the main window or the plugin window.
ipcMain.on('pluginMessage', (_event: any, message: PluginMessage) => {
try {
if (message.target === 'mainWindow') {
this.win_.webContents.send('pluginMessage', message);
}
if (message.target === 'plugin') {
const win = this.pluginWindows_[message.pluginId];
if (!win) {
this.logger().error(`Trying to send IPC message to non-existing plugin window: ${message.pluginId}`);
return;
}
win.webContents.send('pluginMessage', message);
}
} catch (error) {
// An error might happen when the app is closing and a plugin
// sends a message. In which case, the above code would try to
// access a destroyed webview.
// https://github.com/laurent22/joplin/issues/4570
console.error('Could not process plugin message:', message);
console.error(error);
}
});
// Let us register listeners on the window, so we can update the state
// automatically (the listeners will be removed when the window is closed)
// and restore the maximized or full screen state
windowState.manage(this.win_);
// HACK: Ensure the window is hidden, as `windowState.manage` may make the window
// visible with isMaximized set to true in window-state-${this.env_}.json.
// https://github.com/laurent22/joplin/issues/2365
if (!windowOptions.show) {
this.win_.hide();
}
}
registerPluginWindow(pluginId: string, window: any) {
this.pluginWindows_[pluginId] = window;
}
async waitForElectronAppReady() {
if (this.electronApp().isReady()) return Promise.resolve();
return new Promise<void>((resolve) => {
const iid = setInterval(() => {
if (this.electronApp().isReady()) {
clearInterval(iid);
resolve(null);
}
}, 10);
});
}
async quit() {
this.electronApp_.quit();
}
exit(errorCode = 0) {
this.electronApp_.exit(errorCode);
}
trayShown() {
return !!this.tray_;
}
// This method is used in macOS only to hide the whole app (and not just the main window)
// including the menu bar. This follows the macOS way of hiding an app.
hide() {
this.electronApp_.hide();
}
buildDir() {
if (this.buildDir_) return this.buildDir_;
let dir = `${__dirname}/build`;
if (!fs.pathExistsSync(dir)) {
dir = `${dirname(__dirname)}/build`;
if (!fs.pathExistsSync(dir)) throw new Error('Cannot find build dir');
}
this.buildDir_ = dir;
return dir;
}
trayIconFilename_() {
let output = '';
if (process.platform === 'darwin') {
output = 'macos-16x16Template.png'; // Electron Template Image format
} else {
output = '16x16.png';
}
if (this.env_ === 'dev') output = '16x16-dev.png';
return output;
}
// Note: this must be called only after the "ready" event of the app has been dispatched
createTray(contextMenu: any) {
try {
this.tray_ = new Tray(`${this.buildDir()}/icons/${this.trayIconFilename_()}`);
this.tray_.setToolTip(this.electronApp_.name);
this.tray_.setContextMenu(contextMenu);
this.tray_.on('click', () => {
this.window().show();
});
} catch (error) {
console.error('Cannot create tray', error);
}
}
destroyTray() {
if (!this.tray_) return;
this.tray_.destroy();
this.tray_ = null;
}
ensureSingleInstance() {
if (this.env_ === 'dev') return false;
const gotTheLock = this.electronApp_.requestSingleInstanceLock();
if (!gotTheLock) {
// Another instance is already running - exit
this.electronApp_.quit();
return true;
}
// Someone tried to open a second instance - focus our window instead
this.electronApp_.on('second-instance', (_e: any, argv: string[]) => {
const win = this.window();
if (!win) return;
if (win.isMinimized()) win.restore();
win.show();
win.focus();
if (process.platform !== 'darwin') {
const url = argv.find((arg) => isCallbackUrl(arg));
if (url) {
void this.openCallbackUrl(url);
}
}
});
return false;
}
async start() {
// Since we are doing other async things before creating the window, we might miss
// the "ready" event. So we use the function below to make sure that the app is ready.
await this.waitForElectronAppReady();
const alreadyRunning = this.ensureSingleInstance();
if (alreadyRunning) return;
this.createWindow();
this.electronApp_.on('before-quit', () => {
this.willQuitApp_ = true;
});
this.electronApp_.on('window-all-closed', () => {
this.electronApp_.quit();
});
this.electronApp_.on('activate', () => {
this.win_.show();
});
this.electronApp_.on('open-url', (event: any, url: string) => {
event.preventDefault();
void this.openCallbackUrl(url);
});
}
async openCallbackUrl(url: string) {
this.win_.webContents.send('asynchronous-message', 'openCallbackUrl', {
url: url,
});
}
} | the_stack |
import { createHmac, randomBytes } from "crypto";
import fs from "fs";
import { TextDecoder } from "util";
// This zmq must be used only for types.
// zeromq runtime must be delay loaded in init().
import * as zmq from "zeromq";
import { isCompleteCode } from "./converter";
import { Executor } from "./executor";
import { printQuickInfo } from "./inspect";
import { TaskQueue, TaskCanceledError } from "./util";
const utf8Decoder = new TextDecoder();
/**
* The process-wide global variable to hold the last valid
* writeDisplayData. This is used from the display public API.
*/
export let lastWriteDisplayData: (
data: DisplayData,
update: boolean
) => void = null;
interface ConnectionInfo {
shell_port: number;
iopub_port: number;
stdin_port: number;
control_port: number;
hb_port: number;
ip: string;
key: string;
transport: string;
signature_scheme: string;
kernel_name: string;
}
interface HeaderMessage {
version: string;
/** ISO 8601 timestamp for when the message is created */
date: string;
/** typically UUID, should be unique per session */
session: string;
username: string;
msg_type: string;
/** typically UUID, must be unique per message */
msg_id: string;
}
interface KernelInfoReply {
/**
* Version of messaging protocol.
* The first integer indicates major version. It is incremented when
* there is any backward incompatible change.
* The second integer indicates minor version. It is incremented when
* there is any backward compatible change.
*/
protocol_version: string;
/**
* The kernel implementation name
* (e.g. 'ipython' for the IPython kernel)
*/
implementation: string;
/**
* Implementation version number.
* The version number of the kernel's implementation
* (e.g.IPython.__version__ for the IPython kernel)
*/
implementation_version: string;
/**
* Information about the language of code for the kernel
*/
language_info: {
/**
* Name of the programming language that the kernel implements.
* Kernel included in IPython returns 'python'.
*/
name: string;
/**
* Language version number.
* It is Python version number(e.g., '2.7.3') for the kernel
* included in IPython.
*/
version: string;
/**
* mimetype for script files in this language
*/
mimetype: string;
/** Extension including the dot, e.g. '.py' */
file_extension: string;
/**
* Pygments lexer, for highlighting
* Only needed if it differs from the 'name' field.
*/
pygments_lexer?: string;
/**
* Codemirror mode, for for highlighting in the notebook.
* Only needed if it differs from the 'name' field.
*/
codemirror_mode?: string | Object;
/**
* Nbconvert exporter, if notebooks written with this kernel should
* be exported with something other than the general 'script'
* exporter.
*/
nbconvert_exporter?: string;
};
/**
* A banner of information about the kernel,
* which may be desplayed in console environments.
*/
banner: string;
/**
* Optional: A list of dictionaries, each with keys 'text' and 'url'.
* These will be displayed in the help menu in the notebook UI.
*/
help_links?: [{ text: string; url: string }];
}
interface ExecuteRequest {
/**Source code to be executed by the kernel, one or more lines. */
code: string;
/**
* A boolean flag which, if True, signals the kernel to execute
* this code as quietly as possible.
* silent=True forces store_history to be False,
* and will *not*:
* - broadcast output on the IOPUB channel
* - have an execute_result
* The default is False.
*/
silent: boolean;
/*
* A boolean flag which, if True, signals the kernel to populate history
* The default is True if silent is False. If silent is True, store_history
* is forced to be False.
*/
store_history: boolean;
/**
* A dict mapping names to expressions to be evaluated in the
* user's dict. The rich display-data representation of each will be evaluated after execution.
* See the display_data content for the structure of the representation data.
*/
user_expressions: Object;
/**
* Some frontends do not support stdin requests.
* If this is true, code running in the kernel can prompt the user for input
* with an input_request message (see below). If it is false, the kernel
* should not send these messages.
*/
allow_stdin?: boolean;
/**
* A boolean flag, which, if True, does not abort the execution queue, if an exception is encountered.
* This allows the queued execution of multiple execute_requests, even if they generate exceptions.
*/
stop_on_error?: boolean;
}
export interface ExecuteReply {
/** One of: 'ok' OR 'error' OR 'abort' */
status: string;
/**
* The global kernel counter that increases by one with each request that
* stores history. This will typically be used by clients to display
* prompt numbers to the user. If the request did not store history, this will
* be the current value of the counter in the kernel.
*/
execution_count: number;
/**
* 'payload' will be a list of payload dicts, and is optional.
* payloads are considered deprecated.
* The only requirement of each payload dict is that it have a 'source' key,
* which is a string classifying the payload (e.g. 'page').
*/
payload?: Object[];
/** Results for the user_expressions. */
user_expressions?: Object;
}
interface IsCompleteRequest {
/** The code entered so far as a multiline string */
code: string;
}
interface IsCompleteReply {
/** One of 'complete', 'incomplete', 'invalid', 'unknown' */
status: "complete" | "incomplete" | "invalid" | "unknown";
/**
* If status is 'incomplete', indent should contain the characters to use
* to indent the next line. This is only a hint: frontends may ignore it
* and use their own autoindentation rules. For other statuses, this
* field does not exist.
*/
indent?: string;
}
interface InspectRequest {
/**
* The code context in which introspection is requested
* this may be up to an entire multiline cell.
*/
code: string;
/**
* The cursor position within 'code' (in unicode characters) where inspection is requested
*/
cursor_pos: number;
/**
*
* The level of detail desired. In IPython, the default (0) is equivalent to typing
* 'x?' at the prompt, 1 is equivalent to 'x??'.
* The difference is up to kernels, but in IPython level 1 includes the source code
* if available.
*/
detail_level: 0 | 1;
}
interface InspectReply {
/** 'ok' if the request succeeded or 'error', with error information as in all other replies. */
status: "ok";
/** found should be true if an object was found, false otherwise */
found: boolean;
/** data can be empty if nothing is found */
data: { [key: string]: string };
metadata: { [key: string]: never };
}
interface CompleteRequest {
/**
* The code context in which completion is requested
* this may be up to an entire multiline cell, such as
* 'foo = a.isal'
*/
code: string;
/** The cursor position within 'code' (in unicode characters) where completion is requested */
cursor_pos: number;
}
interface CompleteReply {
/**
* The list of all matches to the completion request, such as
* ['a.isalnum', 'a.isalpha'] for the above example.
*/
matches: string[];
/**
* The range of text that should be replaced by the above matches when a completion is accepted.
* typically cursor_end is the same as cursor_pos in the request.
*/
cursor_start: number;
cursor_end: number;
/** Information that frontend plugins might use for extra display information about completions. */
metadata: { [key: string]: never };
/**
* status should be 'ok' unless an exception was raised during the request,
* in which case it should be 'error', along with the usual error message content
* in other messages.
*/
status: "ok";
}
interface ShutdownRequest {
/**
* False if final shutdown, or True if shutdown precedes a restart
*/
restart: boolean;
}
interface ShutdownReply {
/**
* False if final shutdown, or True if shutdown precedes a restart
*/
restart: boolean;
}
interface DisplayData {
/**
* Who create the data
* Used in V4. Removed in V5.
*/
source?: string;
/**
* The data dict contains key/value pairs, where the keys are MIME
* types and the values are the raw data of the representation in that
* format.
*/
data: { [key: string]: string | Uint8Array };
/** Any metadata that describes the data */
metadata: { [key: string]: string };
/**
* Optional transient data introduced in 5.1. Information not to be
* persisted to a notebook or other documents. Intended to live only
* during a live kernel session.
*/
transient: { display_id?: string };
}
interface CommInfoRequest {
/** Optional, the target name */
target_name?: string;
}
interface CommInfoReply {
/** A dictionary of the comms, indexed by uuids. */
comms: {};
}
class ZmqMessage {
// identity must not string because jupyter sends non-string identity since 5.3 prototocol.
// TODO: Check this is an intentional change in Jupyter.
identity: Buffer;
delim: string;
hmac: string;
header: HeaderMessage;
parent: HeaderMessage;
metadata: Object;
content: Object;
extra: Buffer[];
private constructor() {}
private static verifyHmac(key: string, hmac: string, rest: Buffer[]) {
const hash = createHmac("sha256", key);
for (const r of rest) {
hash.update(r);
}
const hex = hash.digest("hex");
if (hex == hmac) {
return;
}
throw new Error(`invalid hmac ${hmac}; want ${hex}`);
}
static fromRaw(key: string, raw: Buffer[]): ZmqMessage {
const ret = new ZmqMessage();
ret.identity = raw[0];
ret.delim = raw[1].toString();
ret.hmac = raw[2].toString();
ret.header = JSON.parse(raw[3].toString());
ret.parent = JSON.parse(raw[4].toString());
ret.metadata = JSON.parse(raw[5].toString());
ret.content = JSON.parse(raw[6].toString());
ret.extra = raw.slice(7);
ZmqMessage.verifyHmac(key, ret.hmac, raw.slice(3));
return ret;
}
createReply(): ZmqMessage {
const rep = new ZmqMessage();
// https://github.com/ipython/ipykernel/blob/master/ipykernel/kernelbase.py#L222
// idents must be copied from the parent.
rep.identity = this.identity;
rep.delim = this.delim;
// Sets an empty string to hmac because it won't be used.
rep.hmac = "";
rep.header = {
version: "5.3",
date: new Date().toISOString(),
session: this.header.session,
username: this.header.username,
msg_type: this.header.msg_type,
// Set a unique ID to prevent a problem like #14.
// TODO: Check this by integration tests.
msg_id: randomBytes(16).toString("hex"),
};
rep.parent = this.header;
rep.metadata = {};
rep.content = {};
rep.extra = [];
return rep;
}
signAndSend(key: string, sock) {
const heads: (string | Buffer)[] = [];
heads.push(this.identity);
heads.push(this.delim);
const bodies: string[] = [];
bodies.push(JSON.stringify(this.header));
bodies.push(JSON.stringify(this.parent));
bodies.push(JSON.stringify(this.metadata));
bodies.push(JSON.stringify(this.content));
for (const e of this.extra) {
bodies.push(JSON.stringify(e));
}
const hash = createHmac("sha256", key);
for (const b of bodies) {
hash.update(b);
}
heads.push(hash.digest("hex"));
sock.send(heads.concat(bodies));
}
}
interface JupyterHandler {
handleKernel(): KernelInfoReply;
handleExecute(
req: ExecuteRequest,
writeStream: (name: string, text: string) => void,
writeDisplayData: (data: DisplayData, update: boolean) => void
): Promise<ExecuteReply>;
handleIsComplete(req: IsCompleteRequest): IsCompleteReply;
handleInspect(req: InspectRequest): InspectReply;
handleComplete(req: CompleteRequest): CompleteReply;
handleShutdown(req: ShutdownRequest): ShutdownReply;
/** Release internal resources to terminate the process gracefully. */
close(): void;
}
class ExecutionCount {
count: number;
constructor(count: number) {
this.count = count;
}
}
export class JupyterHandlerImpl implements JupyterHandler {
private execCount: number;
private executor: Executor;
private execQueue: TaskQueue;
/** If true, JavaScript kernel. Otherwise, TypeScript. */
private isJs: boolean;
constructor(executor: Executor, isJs: boolean) {
this.execCount = 0;
this.executor = executor;
this.execQueue = new TaskQueue();
this.isJs = isJs;
}
handleKernel(): KernelInfoReply {
let lang = "typescript";
let version = "3.7.2";
let implementation = "tslab";
let file_extension = ".ts";
let banner = "TypeScript";
let mimetype = "text/typescript";
if (this.isJs) {
lang = "javascript";
version = "";
implementation = "jslab";
file_extension = ".js";
banner = "JavaScript";
mimetype = "text/javascript";
}
const reply: KernelInfoReply = {
protocol_version: "5.3",
implementation,
implementation_version: "1.0.0",
language_info: {
name: lang,
version,
mimetype,
file_extension,
},
banner,
};
if (!this.isJs) {
// This fix https://github.com/yunabe/tslab/issues/18 in both Jupyter notebook and JupyterLab magically.
reply.language_info.codemirror_mode = {
// mode is used to enable TypeScript CodeMirror in jupyterlab:
// https://github.com/jupyterlab/jupyterlab/blob/1377bd183764860b384bea7c36ea1c52b6095e05/packages/codemirror/src/mode.ts#L133
// As we can see in the code, jupyterlab does not pass codemirror_mode to CodeMirror directly.
// Thus, `typescript: true` below is not used in jupyterlab.
mode: "typescript",
// name and typescript are used to enable TypeScript CodeMirror in notebook.
// We don't fully understand why this combination works magically. It might be related to:
// https://github.com/jupyter/notebook/blob/8b21329deb9dd04271b12e3d2790c5be9f1fd51e/notebook/static/notebook/js/notebook.js#L2199
// Also, typescript flag is defined in:
// https://codemirror.net/mode/javascript/index.html
name: "javascript",
typescript: true,
};
}
return reply;
}
async handleExecute(
req: ExecuteRequest,
writeStream: (name: string, text: string) => void,
writeDisplayData: (data: DisplayData, update: boolean) => void
): Promise<ExecuteReply> {
let status = "ok";
let count: ExecutionCount = null;
try {
count = await this.execQueue.add(() =>
this.handleExecuteImpl(req, writeStream, writeDisplayData)
);
} catch (e) {
if (e instanceof ExecutionCount) {
status = "error";
count = e;
} else if (e instanceof TaskCanceledError) {
status = "abort";
} else {
status = "error";
console.error("unexpected error:", e);
}
if (status === "error") {
// Sleep 200ms to abort all pending tasks in ZMQ queue then reset the task queue.
// https://github.com/yunabe/tslab/issues/19
// We might just need to sleep 1ms here to process all pending requests in ZMQ.
// But we wait for 200ms for safety. 200ms is selected from:
// https://material.io/design/motion/speed.html#duration
this.execQueue.reset(200);
}
}
return {
status: status,
execution_count: count ? count.count : undefined,
};
}
/**
* The body of handleExecute.
* When the execution failed, this method throws ExecutionCount to
* - Pass ExecutionCount to the caller.
* - At the same time, cancel pending tasks on execQueue.
* TODO: Figure out a cleaner and more natural solution.
*/
private async handleExecuteImpl(
req: ExecuteRequest,
writeStream: (name: string, text: string) => void,
writeDisplayData: (data: DisplayData, update: boolean) => void
): Promise<ExecutionCount> {
// Python kernel forward outputs to the cell even after the execution is finished.
// We follow the same convension here.
process.stdout.write = this.createWriteToIopub(
"stdout",
writeStream
) as any;
process.stderr.write = this.createWriteToIopub(
"stderr",
writeStream
) as any;
lastWriteDisplayData = writeDisplayData;
let count = new ExecutionCount(++this.execCount);
let ok: boolean = await this.executor.execute(req.code);
if (!ok) {
throw count;
}
return count;
}
createWriteToIopub(
name: "stdout" | "stderr",
writeStream: (name: string, text: string) => void
) {
return (buffer: string | Uint8Array, encoding?: string): boolean => {
let text: string;
if (typeof buffer === "string") {
text = buffer;
} else {
text = utf8Decoder.decode(buffer);
}
writeStream(name, text);
return true;
};
}
handleIsComplete(req: IsCompleteRequest): IsCompleteReply {
const res = isCompleteCode(req.code);
if (res.completed) {
return {
status: "complete",
};
}
return {
indent: res.indent,
status: "incomplete",
};
}
handleInspect(req: InspectRequest): InspectReply {
const info = this.executor.inspect(req.code, req.cursor_pos);
if (!info) {
return {
status: "ok",
found: false,
data: {},
metadata: {},
};
}
let text = printQuickInfo(info);
return {
status: "ok",
found: true,
data: {
// text/plain must be filled even if "text/html" is provided.
// TODO: Fill text/html too if necessary.
"text/plain": text,
},
metadata: {},
};
}
handleComplete(req: CompleteRequest): CompleteReply {
const info = this.executor.complete(req.code, req.cursor_pos);
return {
cursor_start: info.start,
cursor_end: info.end,
matches: info.candidates,
metadata: {},
status: "ok",
};
}
handleShutdown(req: ShutdownRequest): ShutdownReply {
return {
restart: false,
};
}
close(): void {
this.executor.close();
}
}
export class ZmqServer {
handler: JupyterHandler;
configPath: string;
connInfo: ConnectionInfo;
// ZMQ sockets
iopub: zmq.Publisher;
shell: zmq.Router;
control: zmq.Router;
stdin: zmq.Router;
hb: zmq.Reply;
constructor(handler: JupyterHandler, configPath: string) {
this.handler = handler;
this.configPath = configPath;
}
private async bindSocket(sock: zmq.Socket, port: number): Promise<void> {
const conn = this.connInfo;
const addr = `${conn.transport}://${conn.ip}:${port}`;
await sock.bind(addr);
}
publishStatus(status: string, parent: ZmqMessage) {
const reply = parent.createReply();
reply.content = {
execution_state: status,
};
reply.header.msg_type = "status";
reply.signAndSend(this.connInfo.key, this.iopub);
}
async handleShellMessage(sock: zmq.Router, ...args: Buffer[]) {
const msg = ZmqMessage.fromRaw(this.connInfo.key, args);
let terminated = false;
this.publishStatus("busy", msg);
try {
switch (msg.header.msg_type) {
case "kernel_info_request":
this.handleKernelInfo(sock, msg);
break;
case "execute_request":
await this.handleExecute(sock, msg);
break;
case "is_complete_request":
this.handleIsComplete(sock, msg);
break;
case "inspect_request":
this.handleInspect(sock, msg);
break;
case "complete_request":
this.handleComplete(sock, msg);
break;
case "comm_info_request":
// This is sent for ipywidgets with content = { target_name: 'jupyter.widget' }.
this.handleCommInfoRequest(sock, msg);
break;
case "shutdown_request":
this.handleShutdown(sock, msg);
terminated = true;
break;
default:
console.warn(`unknown msg_type: ${msg.header.msg_type}`);
}
} finally {
this.publishStatus("idle", msg);
}
if (terminated) {
// TODO: Write tests for the graceful termination.
this.close();
}
}
handleKernelInfo(sock, msg: ZmqMessage) {
const reply = msg.createReply();
reply.header.msg_type = "kernel_info_reply";
reply.content = this.handler.handleKernel();
reply.signAndSend(this.connInfo.key, sock);
}
async handleExecute(sock, msg: ZmqMessage) {
const reply = msg.createReply();
reply.header.msg_type = "execute_reply";
const writeStream = (name: string, text: string) => {
const reply = msg.createReply();
reply.header.msg_type = "stream";
reply.content = {
name,
text,
};
reply.signAndSend(this.connInfo.key, this.iopub);
};
const writeDisplayData = (data: DisplayData, update: boolean) => {
const reply = msg.createReply();
reply.header.msg_type = update ? "update_display_data" : "display_data";
reply.content = data;
reply.signAndSend(this.connInfo.key, this.iopub);
};
const content: ExecuteReply = await this.handler.handleExecute(
msg.content as ExecuteRequest,
writeStream,
writeDisplayData
);
reply.content = content;
reply.signAndSend(this.connInfo.key, sock);
}
handleIsComplete(sock, msg: ZmqMessage) {
const reply = msg.createReply();
reply.header.msg_type = "is_complete_reply";
reply.content = this.handler.handleIsComplete(
msg.content as IsCompleteRequest
);
reply.signAndSend(this.connInfo.key, sock);
}
handleInspect(sock, msg: ZmqMessage) {
const reply = msg.createReply();
reply.header.msg_type = "inspect_reply";
reply.content = this.handler.handleInspect(msg.content as InspectRequest);
reply.signAndSend(this.connInfo.key, sock);
}
handleComplete(sock, msg: ZmqMessage) {
const reply = msg.createReply();
reply.header.msg_type = "complete_reply";
reply.content = this.handler.handleComplete(msg.content as CompleteRequest);
reply.signAndSend(this.connInfo.key, sock);
}
handleCommInfoRequest(sock: zmq.Router, msg: ZmqMessage) {
const reply = msg.createReply();
reply.header.msg_type = "complete_reply";
// comm is not supported in tslab now. Returns an empty comms.
(reply.content as CommInfoReply) = { comms: {} };
reply.signAndSend(this.connInfo.key, sock);
}
handleShutdown(sock, msg: ZmqMessage) {
const reply = msg.createReply();
reply.header.msg_type = "shutdown_reply";
reply.content = this.handler.handleShutdown(msg.content as ShutdownRequest);
reply.signAndSend(this.connInfo.key, sock);
}
async init(): Promise<void> {
const cinfo: ConnectionInfo = JSON.parse(
fs.readFileSync(this.configPath, "utf-8")
);
this.connInfo = cinfo;
// https://zeromq.github.io/zeromq.js/index.html
// zeromq runtime must be delay loaded so that mutiple instances of
// this module can be loaded (e.g. global and local ones).
const zmq = await import("zeromq");
this.iopub = new zmq.Publisher();
this.shell = new zmq.Router();
this.control = new zmq.Router();
this.stdin = new zmq.Router();
this.hb = new zmq.Reply();
(async () => {
// These for-loops exist when sockets are closed.
for await (const msgs of this.shell) {
this.handleShellMessage(this.shell, ...msgs);
}
})();
(async () => {
for await (const msgs of this.control) {
this.handleShellMessage(this.control, ...msgs);
}
})();
(async () => {
for await (const msgs of this.hb) {
// hb is only used by `jupyter console`.
// TODO: Test this behavior by integration tests.
this.hb.send(msgs);
}
})();
await Promise.all([
this.bindSocket(this.iopub, cinfo.iopub_port),
this.bindSocket(this.shell, cinfo.shell_port),
this.bindSocket(this.control, cinfo.control_port),
this.bindSocket(this.stdin, cinfo.stdin_port),
this.bindSocket(this.hb, cinfo.hb_port),
]);
}
/** Release internal resources to terminate the process gracefully. */
close(): void {
// First internal resources (e.g. ts watcher in converter).
this.handler.close();
// Then, close sockets.
this.iopub.close();
this.shell.close();
this.control.close();
this.stdin.close();
this.hb.close();
}
} | the_stack |
import {ResourceBase, ResourceTag} from '../resource'
import {Value, List} from '../dataTypes'
export class ComputeLimits {
MaximumCapacityUnits!: Value<number>
MaximumCoreCapacityUnits?: Value<number>
MaximumOnDemandCapacityUnits?: Value<number>
MinimumCapacityUnits!: Value<number>
UnitType!: Value<string>
constructor(properties: ComputeLimits) {
Object.assign(this, properties)
}
}
export class SpotProvisioningSpecification {
AllocationStrategy?: Value<string>
BlockDurationMinutes?: Value<number>
TimeoutAction!: Value<string>
TimeoutDurationMinutes!: Value<number>
constructor(properties: SpotProvisioningSpecification) {
Object.assign(this, properties)
}
}
export class BootstrapActionConfig {
Name!: Value<string>
ScriptBootstrapAction!: ScriptBootstrapActionConfig
constructor(properties: BootstrapActionConfig) {
Object.assign(this, properties)
}
}
export class StepConfig {
ActionOnFailure?: Value<string>
HadoopJarStep!: HadoopJarStepConfig
Name!: Value<string>
constructor(properties: StepConfig) {
Object.assign(this, properties)
}
}
export class EbsBlockDeviceConfig {
VolumeSpecification!: VolumeSpecification
VolumesPerInstance?: Value<number>
constructor(properties: EbsBlockDeviceConfig) {
Object.assign(this, properties)
}
}
export class ManagedScalingPolicy {
ComputeLimits?: ComputeLimits
constructor(properties: ManagedScalingPolicy) {
Object.assign(this, properties)
}
}
export class CloudWatchAlarmDefinition {
ComparisonOperator!: Value<string>
Dimensions?: List<MetricDimension>
EvaluationPeriods?: Value<number>
MetricName!: Value<string>
Namespace?: Value<string>
Period!: Value<number>
Statistic?: Value<string>
Threshold!: Value<number>
Unit?: Value<string>
constructor(properties: CloudWatchAlarmDefinition) {
Object.assign(this, properties)
}
}
export class KeyValue {
Key?: Value<string>
Value?: Value<string>
constructor(properties: KeyValue) {
Object.assign(this, properties)
}
}
export class VolumeSpecification {
Iops?: Value<number>
SizeInGB!: Value<number>
VolumeType!: Value<string>
constructor(properties: VolumeSpecification) {
Object.assign(this, properties)
}
}
export class InstanceFleetProvisioningSpecifications {
OnDemandSpecification?: OnDemandProvisioningSpecification
SpotSpecification?: SpotProvisioningSpecification
constructor(properties: InstanceFleetProvisioningSpecifications) {
Object.assign(this, properties)
}
}
export class InstanceGroupConfig {
AutoScalingPolicy?: AutoScalingPolicy
BidPrice?: Value<string>
Configurations?: List<Configuration>
EbsConfiguration?: EbsConfiguration
InstanceCount!: Value<number>
InstanceType!: Value<string>
Market?: Value<string>
Name?: Value<string>
constructor(properties: InstanceGroupConfig) {
Object.assign(this, properties)
}
}
export class KerberosAttributes {
ADDomainJoinPassword?: Value<string>
ADDomainJoinUser?: Value<string>
CrossRealmTrustPrincipalPassword?: Value<string>
KdcAdminPassword!: Value<string>
Realm!: Value<string>
constructor(properties: KerberosAttributes) {
Object.assign(this, properties)
}
}
export class Application {
AdditionalInfo?: {[key: string]: Value<string>}
Args?: List<Value<string>>
Name?: Value<string>
Version?: Value<string>
constructor(properties: Application) {
Object.assign(this, properties)
}
}
export class Configuration {
Classification?: Value<string>
ConfigurationProperties?: {[key: string]: Value<string>}
Configurations?: List<Configuration>
constructor(properties: Configuration) {
Object.assign(this, properties)
}
}
export class ScriptBootstrapActionConfig {
Args?: List<Value<string>>
Path!: Value<string>
constructor(properties: ScriptBootstrapActionConfig) {
Object.assign(this, properties)
}
}
export class EbsConfiguration {
EbsBlockDeviceConfigs?: List<EbsBlockDeviceConfig>
EbsOptimized?: Value<boolean>
constructor(properties: EbsConfiguration) {
Object.assign(this, properties)
}
}
export class InstanceTypeConfig {
BidPrice?: Value<string>
BidPriceAsPercentageOfOnDemandPrice?: Value<number>
Configurations?: List<Configuration>
EbsConfiguration?: EbsConfiguration
InstanceType!: Value<string>
WeightedCapacity?: Value<number>
constructor(properties: InstanceTypeConfig) {
Object.assign(this, properties)
}
}
export class MetricDimension {
Key!: Value<string>
Value!: Value<string>
constructor(properties: MetricDimension) {
Object.assign(this, properties)
}
}
export class OnDemandProvisioningSpecification {
AllocationStrategy!: Value<string>
constructor(properties: OnDemandProvisioningSpecification) {
Object.assign(this, properties)
}
}
export class ScalingTrigger {
CloudWatchAlarmDefinition!: CloudWatchAlarmDefinition
constructor(properties: ScalingTrigger) {
Object.assign(this, properties)
}
}
export class InstanceFleetConfig {
InstanceTypeConfigs?: List<InstanceTypeConfig>
LaunchSpecifications?: InstanceFleetProvisioningSpecifications
Name?: Value<string>
TargetOnDemandCapacity?: Value<number>
TargetSpotCapacity?: Value<number>
constructor(properties: InstanceFleetConfig) {
Object.assign(this, properties)
}
}
export class JobFlowInstancesConfig {
AdditionalMasterSecurityGroups?: List<Value<string>>
AdditionalSlaveSecurityGroups?: List<Value<string>>
CoreInstanceFleet?: InstanceFleetConfig
CoreInstanceGroup?: InstanceGroupConfig
Ec2KeyName?: Value<string>
Ec2SubnetId?: Value<string>
Ec2SubnetIds?: List<Value<string>>
EmrManagedMasterSecurityGroup?: Value<string>
EmrManagedSlaveSecurityGroup?: Value<string>
HadoopVersion?: Value<string>
KeepJobFlowAliveWhenNoSteps?: Value<boolean>
MasterInstanceFleet?: InstanceFleetConfig
MasterInstanceGroup?: InstanceGroupConfig
Placement?: PlacementType
ServiceAccessSecurityGroup?: Value<string>
TerminationProtected?: Value<boolean>
constructor(properties: JobFlowInstancesConfig) {
Object.assign(this, properties)
}
}
export class ScalingConstraints {
MaxCapacity!: Value<number>
MinCapacity!: Value<number>
constructor(properties: ScalingConstraints) {
Object.assign(this, properties)
}
}
export class ScalingAction {
Market?: Value<string>
SimpleScalingPolicyConfiguration!: SimpleScalingPolicyConfiguration
constructor(properties: ScalingAction) {
Object.assign(this, properties)
}
}
export class SimpleScalingPolicyConfiguration {
AdjustmentType?: Value<string>
CoolDown?: Value<number>
ScalingAdjustment!: Value<number>
constructor(properties: SimpleScalingPolicyConfiguration) {
Object.assign(this, properties)
}
}
export class PlacementType {
AvailabilityZone!: Value<string>
constructor(properties: PlacementType) {
Object.assign(this, properties)
}
}
export class ScalingRule {
Action!: ScalingAction
Description?: Value<string>
Name!: Value<string>
Trigger!: ScalingTrigger
constructor(properties: ScalingRule) {
Object.assign(this, properties)
}
}
export class AutoScalingPolicy {
Constraints!: ScalingConstraints
Rules!: List<ScalingRule>
constructor(properties: AutoScalingPolicy) {
Object.assign(this, properties)
}
}
export class HadoopJarStepConfig {
Args?: List<Value<string>>
Jar!: Value<string>
MainClass?: Value<string>
StepProperties?: List<KeyValue>
constructor(properties: HadoopJarStepConfig) {
Object.assign(this, properties)
}
}
export interface ClusterProperties {
AdditionalInfo?: {[key: string]: any}
Applications?: List<Application>
AutoScalingRole?: Value<string>
BootstrapActions?: List<BootstrapActionConfig>
Configurations?: List<Configuration>
CustomAmiId?: Value<string>
EbsRootVolumeSize?: Value<number>
Instances: JobFlowInstancesConfig
JobFlowRole: Value<string>
KerberosAttributes?: KerberosAttributes
LogEncryptionKmsKeyId?: Value<string>
LogUri?: Value<string>
ManagedScalingPolicy?: ManagedScalingPolicy
Name: Value<string>
ReleaseLabel?: Value<string>
ScaleDownBehavior?: Value<string>
SecurityConfiguration?: Value<string>
ServiceRole: Value<string>
StepConcurrencyLevel?: Value<number>
Steps?: List<StepConfig>
Tags?: List<ResourceTag>
VisibleToAllUsers?: Value<boolean>
}
export default class Cluster extends ResourceBase<ClusterProperties> {
static ComputeLimits = ComputeLimits
static SpotProvisioningSpecification = SpotProvisioningSpecification
static BootstrapActionConfig = BootstrapActionConfig
static StepConfig = StepConfig
static EbsBlockDeviceConfig = EbsBlockDeviceConfig
static ManagedScalingPolicy = ManagedScalingPolicy
static CloudWatchAlarmDefinition = CloudWatchAlarmDefinition
static KeyValue = KeyValue
static VolumeSpecification = VolumeSpecification
static InstanceFleetProvisioningSpecifications = InstanceFleetProvisioningSpecifications
static InstanceGroupConfig = InstanceGroupConfig
static KerberosAttributes = KerberosAttributes
static Application = Application
static Configuration = Configuration
static ScriptBootstrapActionConfig = ScriptBootstrapActionConfig
static EbsConfiguration = EbsConfiguration
static InstanceTypeConfig = InstanceTypeConfig
static MetricDimension = MetricDimension
static OnDemandProvisioningSpecification = OnDemandProvisioningSpecification
static ScalingTrigger = ScalingTrigger
static InstanceFleetConfig = InstanceFleetConfig
static JobFlowInstancesConfig = JobFlowInstancesConfig
static ScalingConstraints = ScalingConstraints
static ScalingAction = ScalingAction
static SimpleScalingPolicyConfiguration = SimpleScalingPolicyConfiguration
static PlacementType = PlacementType
static ScalingRule = ScalingRule
static AutoScalingPolicy = AutoScalingPolicy
static HadoopJarStepConfig = HadoopJarStepConfig
constructor(properties: ClusterProperties) {
super('AWS::EMR::Cluster', properties)
}
} | the_stack |
import * as AWS from 'aws-sdk';
import { mock, restore, setSDKInstance } from 'aws-sdk-mock';
import { MongoDbConfigure } from '../handler';
jest.mock('../../lib/secrets-manager/read-certificate');
const secretArn: string = 'arn:aws:secretsmanager:us-west-1:1234567890:secret:SecretPath/Cert';
// @ts-ignore
async function successRequestMock(request: { [key: string]: string}, returnValue: any): Promise<{ [key: string]: any }> {
return returnValue;
}
describe('readCertificateData', () => {
test('success', async () => {
// GIVEN
const certData = 'BEGIN CERTIFICATE';
jest.requireMock('../../lib/secrets-manager/read-certificate').readCertificateData.mockReturnValue(Promise.resolve(certData));
const handler = new MongoDbConfigure(new AWS.SecretsManager());
// WHEN
// tslint:disable-next-line: no-string-literal
const data = await handler['readCertificateData'](secretArn);
// THEN
expect(data).toStrictEqual(certData);
});
test('failure', async () => {
// GIVEN
jest.requireMock('../../lib/secrets-manager/read-certificate').readCertificateData.mockImplementation(() => {
throw new Error('must contain a Certificate in PEM format');
});
const handler = new MongoDbConfigure(new AWS.SecretsManager());
// THEN
// tslint:disable-next-line: no-string-literal
await expect(handler['readCertificateData'](secretArn)).rejects.toThrowError(/must contain a Certificate in PEM format/);
});
});
describe('readLoginCredentials', () => {
beforeEach(() => {
setSDKInstance(AWS);
});
afterEach(() => {
restore('SecretsManager');
});
test('success', async () => {
// GIVEN
const loginData = {
username: 'testuser',
password: 'testpassword',
};
const secretContents = {
SecretString: JSON.stringify(loginData),
};
const mockGetSecret = jest.fn( (request) => successRequestMock(request, secretContents) );
mock('SecretsManager', 'getSecretValue', mockGetSecret);
const handler = new MongoDbConfigure(new AWS.SecretsManager());
// WHEN
// tslint:disable-next-line: no-string-literal
const data = await handler['readLoginCredentials'](secretArn);
// THEN
expect(data).toStrictEqual(loginData);
});
test('binary data', async () => {
// GIVEN
const loginData = Buffer.from('some binary data', 'utf-8');
const secretContents = {
SecretBinary: loginData,
};
const mockGetSecret = jest.fn( (request) => successRequestMock(request, secretContents) );
mock('SecretsManager', 'getSecretValue', mockGetSecret);
const handler = new MongoDbConfigure(new AWS.SecretsManager());
// THEN
// tslint:disable-next-line: no-string-literal
await expect(handler['readLoginCredentials'](secretArn)).rejects.toThrowError(/must be a JSON encoded string/);
});
test.each([
[ '}{', /Failed to parse JSON in MongoDB login credentials/ ],
[
JSON.stringify({
password: 'testpassword',
}),
/is missing: username/,
],
[
JSON.stringify({
username: 'testuser',
}),
/is missing: password/,
],
])('failed: %p to get %p', async (data: string, expected: RegExp) => {
// GIVEN
const secretContents = {
SecretString: data,
};
const mockGetSecret = jest.fn( (request) => successRequestMock(request, secretContents) );
mock('SecretsManager', 'getSecretValue', mockGetSecret);
const handler = new MongoDbConfigure(new AWS.SecretsManager());
// THEN
// tslint:disable-next-line: no-string-literal
await expect(handler['readLoginCredentials'](secretArn)).rejects.toThrowError(expected);
});
});
describe('mongoLogin', () => {
beforeEach(() => {
jest.spyOn(console, 'log').mockReturnValue(undefined);
});
afterEach(() => {
jest.clearAllMocks();
});
test('mongoLogin', async () => {
// GIVEN
async function stringSuccessRequestMock(value: string): Promise<string> {
return value;
}
const mockReadCert = jest.fn( (request) => stringSuccessRequestMock(request) );
const mockReadLogin = jest.fn( (request) => successRequestMock(request, { username: 'test', password: 'pass' }));
const handler = new MongoDbConfigure(new AWS.SecretsManager());
// tslint:disable-next-line: no-string-literal
handler['readCertificateData'] = mockReadCert;
// tslint:disable-next-line: no-string-literal
handler['readLoginCredentials'] = mockReadLogin;
const mockDriver = {
MongoClient: {
connect: jest.fn(),
},
};
const loginOptions = {
Hostname: 'testhostname',
Port: '27017',
Credentials: 'some credentials',
CaCertificate: 'cert arn',
};
// WHEN
// tslint:disable-next-line: no-string-literal
await handler['mongoLogin'](mockDriver, loginOptions);
// THEN
expect(mockReadCert.mock.calls.length).toBe(1);
expect(mockReadCert.mock.calls[0][0]).toStrictEqual(loginOptions.CaCertificate);
expect(mockReadLogin.mock.calls.length).toBe(1);
expect(mockReadLogin.mock.calls[0][0]).toStrictEqual(loginOptions.Credentials);
expect(mockDriver.MongoClient.connect.mock.calls.length).toBe(1);
expect(mockDriver.MongoClient.connect.mock.calls[0][0]).toStrictEqual('mongodb://testhostname:27017');
expect(mockDriver.MongoClient.connect.mock.calls[0][1]).toStrictEqual({
tls: true,
tlsInsecure: false,
tlsCAFile: '/tmp/ca.crt',
auth: {
user: 'test',
password: 'pass',
},
useUnifiedTopology: true,
});
});
});
describe('readPasswordAuthUserInfo', () => {
beforeEach(() => {
setSDKInstance(AWS);
});
afterEach(() => {
restore('SecretsManager');
});
test('success', async () => {
// GIVEN
const userData = {
username: 'testuser',
password: 'testpassword',
roles: [ { role: 'readWrite', db: 'somedb' } ],
};
const secretContents = {
SecretString: JSON.stringify(userData),
};
const mockGetSecret = jest.fn( (request) => successRequestMock(request, secretContents) );
mock('SecretsManager', 'getSecretValue', mockGetSecret);
const handler = new MongoDbConfigure(new AWS.SecretsManager());
// WHEN
// tslint:disable-next-line: no-string-literal
const data = await handler['readPasswordAuthUserInfo'](secretArn);
// THEN
expect(data).toStrictEqual(userData);
});
test('binary data', async () => {
// GIVEN
const loginData = Buffer.from('Some binary data', 'utf-8');
const secretContents = {
SecretBinary: loginData,
};
const mockGetSecret = jest.fn( (request) => successRequestMock(request, secretContents) );
mock('SecretsManager', 'getSecretValue', mockGetSecret);
const handler = new MongoDbConfigure(new AWS.SecretsManager());
// THEN
// tslint:disable-next-line: no-string-literal
await expect(handler['readPasswordAuthUserInfo'](secretArn)).rejects.toThrowError(/must be a JSON encoded string/);
});
test.each([
[ '}{', /Failed to parse JSON for password-auth user Secret/ ],
[
JSON.stringify({
password: 'testpassword',
roles: [ { role: 'readWrite', db: 'somedb' } ],
}),
/is missing: username/,
],
[
JSON.stringify({
username: 'testuser',
roles: [ { role: 'readWrite', db: 'somedb' } ],
}),
/is missing: password/,
],
[
JSON.stringify({
username: 'testuser',
password: 'testpassword',
}),
/is missing: roles/,
],
])('failed: %p to get %p', async (data: string, expected: RegExp) => {
// GIVEN
const secretContents = {
SecretString: data,
};
const mockGetSecret = jest.fn( (request) => successRequestMock(request, secretContents) );
mock('SecretsManager', 'getSecretValue', mockGetSecret);
const handler = new MongoDbConfigure(new AWS.SecretsManager());
// THEN
// tslint:disable-next-line: no-string-literal
await expect(handler['readPasswordAuthUserInfo'](secretArn)).rejects.toThrowError(expected);
});
});
describe('userExists', () => {
test('user exists', async () => {
// GIVEN
const mongoQueryResult = {
users: [
{
_id: 'admin.test',
user: 'test',
db: 'admin',
},
],
ok: 1,
};
const mockDb = {
command: jest.fn( (request) => successRequestMock(request, mongoQueryResult) ),
};
const handler = new MongoDbConfigure(new AWS.SecretsManager());
// WHEN
// tslint:disable-next-line: no-string-literal
const exists = await handler['userExists'](mockDb, 'test');
// THEN
expect(mockDb.command.mock.calls.length).toBe(1);
expect(mockDb.command.mock.calls[0][0]).toStrictEqual({
usersInfo: 'test',
});
expect(exists).toStrictEqual(true);
});
test('user does not exists', async () => {
// GIVEN
const mongoQueryResult = {
users: [],
ok: 1,
};
const mockDb = {
command: jest.fn( (request) => successRequestMock(request, mongoQueryResult) ),
};
const handler = new MongoDbConfigure(new AWS.SecretsManager());
// WHEN
// tslint:disable-next-line: no-string-literal
const exists = await handler['userExists'](mockDb, 'test');
// THEN
expect(exists).toStrictEqual(false);
});
test('request failed', async () => {
// GIVEN
const mongoQueryResult = {
users: [],
ok: 0,
};
const mockDb = {
command: jest.fn( (request) => successRequestMock(request, mongoQueryResult) ),
};
const handler = new MongoDbConfigure(new AWS.SecretsManager());
// THEN
// tslint:disable-next-line: no-string-literal
await expect(handler['userExists'](mockDb, 'test')).rejects.toThrowError(/MongoDB error checking whether user exists 'test'/);
});
});
describe('createUser', () => {
let consoleLogMock: jest.SpyInstance<any, any>;
beforeEach(() => {
consoleLogMock = jest.spyOn(console, 'log').mockReturnValue(undefined);
});
afterEach(() => {
jest.clearAllMocks();
});
test('create success with password', async () => {
// GIVEN
const mongoQueryResult = {
ok: 1,
};
const mockDb = {
command: jest.fn( (request) => successRequestMock(request, mongoQueryResult) ),
};
const handler = new MongoDbConfigure(new AWS.SecretsManager());
const credentials = {
username: 'test',
password: 'password',
roles: [ { role: 'readWrite', db: 'testdb' } ],
};
// WHEN
// tslint:disable-next-line: no-string-literal
await handler['createUser'](mockDb, credentials);
// THEN
expect(mockDb.command.mock.calls.length).toBe(1);
expect(mockDb.command.mock.calls[0][0]).toStrictEqual({
createUser: credentials.username,
pwd: credentials.password,
roles: credentials.roles,
});
expect(consoleLogMock.mock.calls.length).toBe(1);
expect(consoleLogMock.mock.calls[0][0]).toStrictEqual('Creating user: test');
});
test('create success no password', async () => {
// GIVEN
const mongoQueryResult = {
ok: 1,
};
const mockDb = {
command: jest.fn( (request) => successRequestMock(request, mongoQueryResult) ),
};
const handler = new MongoDbConfigure(new AWS.SecretsManager());
const credentials = {
username: 'test',
roles: [ { role: 'readWrite', db: 'testdb' } ],
};
// WHEN
// tslint:disable-next-line: no-string-literal
await handler['createUser'](mockDb, credentials);
// THEN
expect(mockDb.command.mock.calls.length).toBe(1);
expect(mockDb.command.mock.calls[0][0]).toStrictEqual({
createUser: credentials.username,
roles: credentials.roles,
});
expect(consoleLogMock.mock.calls.length).toBe(1);
expect(consoleLogMock.mock.calls[0][0]).toStrictEqual('Creating user: test');
});
test('request failed', async () => {
// GIVEN
const mongoQueryResult = {
ok: 0,
};
const mockDb = {
command: jest.fn( (request) => successRequestMock(request, mongoQueryResult) ),
};
const handler = new MongoDbConfigure(new AWS.SecretsManager());
const credentials = {
username: 'test',
password: 'password',
roles: [ { role: 'readWrite', db: 'testdb' } ],
};
// THEN
// tslint:disable-next-line: no-string-literal
await expect(handler['createUser'](mockDb, credentials)).rejects.toThrowError(/MongoDB error when adding user 'test'/);
});
});
describe('createPasswordAuthUser', () => {
let consoleLogMock: jest.SpyInstance<any, any>;
// GIVEN
const username = 'testuser';
const password = 'testpassword';
const roles = [ { role: 'readwrite', db: 'somedb' } ];
const userData = {
username,
password,
roles,
};
const secretContents = {
SecretString: JSON.stringify(userData),
};
beforeEach(() => {
// GIVEN
setSDKInstance(AWS);
consoleLogMock = jest.spyOn(console, 'log').mockReturnValue(undefined);
const mockGetSecret = jest.fn( (request) => successRequestMock(request, secretContents) );
mock('SecretsManager', 'getSecretValue', mockGetSecret);
});
afterEach(() => {
restore('SecretsManager');
jest.clearAllMocks();
});
test('existing user', async () => {
// GIVEN
const userExistsResponse = {
users: [],
ok: 1,
};
const addUserResponse = {
ok: 1,
};
async function commandMock(request: { [key: string]: string}): Promise<{ [key: string]: any }> {
if ('createUser' in request) {
return addUserResponse;
}
return userExistsResponse;
}
const mockDb = {
command: jest.fn( (request) => commandMock(request) ),
};
const handler = new MongoDbConfigure(new AWS.SecretsManager());
// WHEN
// tslint:disable-next-line: no-string-literal
const result = await handler['createPasswordAuthUser'](mockDb, secretArn);
expect(result).toStrictEqual(true);
expect(mockDb.command.mock.calls.length).toBe(2);
// Check args of userExits DB query.
expect(mockDb.command.mock.calls[0][0]).toStrictEqual({
usersInfo: username,
});
// Check args of createUser DB query.
expect(mockDb.command.mock.calls[1][0]).toStrictEqual({
createUser: username,
pwd: password,
roles,
});
expect(consoleLogMock.mock.calls.length).toBe(1);
expect(consoleLogMock.mock.calls[0][0]).toStrictEqual(`Creating user: ${username}`);
});
test('non-existing user', async () => {
// GIVEN
const userExistsResponse = {
users: [
{
_id: 'admin.test',
user: 'test',
db: 'admin',
},
],
ok: 1,
};
const addUserResponse = {
ok: 1,
};
async function commandMock(request: { [key: string]: string}): Promise<{ [key: string]: any }> {
if ('createUser' in request) {
return addUserResponse;
}
return userExistsResponse;
}
const mockDb = {
command: jest.fn( (request) => commandMock(request) ),
};
const handler = new MongoDbConfigure(new AWS.SecretsManager());
// WHEN
// tslint:disable-next-line: no-string-literal
const result = await handler['createPasswordAuthUser'](mockDb, secretArn);
expect(result).toStrictEqual(false);
expect(mockDb.command.mock.calls.length).toBe(1);
// Check args of userExits DB query.
expect(mockDb.command.mock.calls[0][0]).toStrictEqual({
usersInfo: username,
});
});
});
describe('createX509AuthUser', () => {
let consoleLogMock: jest.SpyInstance<any, any>;
const username = 'CN=TestUser,O=TestOrg,OU=TestOrgUnit';
beforeEach(() => {
setSDKInstance(AWS);
consoleLogMock = jest.spyOn(console, 'log')
.mockReset()
.mockReturnValue(undefined);
});
afterEach(() => {
restore('SecretsManager');
});
describe.each([
[
[], true,
],
[
[
{
_id: '$external.CN=myName,OU=myOrgUnit,O=myOrg',
user: 'CN=myName,OU=myOrgUnit,O=myOrg',
db: '$external',
},
],
false,
],
])('userExists %p gives %p', (userExists: any, expected: boolean) => {
let mockDb: any;
let result: boolean;
// GIVEN
const dbCommandExpectedCallCount = expected ? 2 : 1;
const userExistsResponse = {
users: userExists,
ok: 1,
};
const addUserResponse = {
ok: 1,
};
const roles = [ { role: 'readWrite', db: 'somedb' } ];
beforeEach(async () => {
// GIVEN
async function commandMock(request: { [key: string]: string}): Promise<{ [key: string]: any }> {
if ('createUser' in request) {
return addUserResponse;
}
return userExistsResponse;
}
mockDb = {
command: jest.fn( (request) => commandMock(request) ),
};
async function stringSuccessRequestMock(value: string): Promise<string> {
return value;
}
async function rfc2253(_arg: string): Promise<string> {
return username;
}
const mockReadCert = jest.fn( (request) => stringSuccessRequestMock(request) );
const mockRfc2253 = jest.fn( (arg) => rfc2253(arg) );
const handler = new MongoDbConfigure(new AWS.SecretsManager());
// tslint:disable-next-line: no-string-literal
handler['readCertificateData'] = mockReadCert;
// tslint:disable-next-line: no-string-literal
handler['retrieveRfc2253Subject'] = mockRfc2253;
const userData = {
certificate: secretArn,
roles,
};
const userToCreate = {
Certificate: userData.certificate,
Roles: JSON.stringify(userData.roles),
};
// WHEN
// tslint:disable-next-line: no-string-literal
result = await handler['createX509AuthUser'](mockDb, userToCreate);
});
// THEN
test('returns expected result', () => {
expect(result).toStrictEqual(expected);
});
test(`db.command called ${dbCommandExpectedCallCount} times`, () => {
expect(mockDb.command.mock.calls.length).toBe(dbCommandExpectedCallCount);
});
test('correct arguments passed to userExits DB query', () => {
expect(mockDb.command.mock.calls[0][0]).toStrictEqual({
usersInfo: username,
});
});
if (expected) {
test('correct arguments passed to createUser DB query', () => {
expect(mockDb.command.mock.calls[1][0]).toStrictEqual({
createUser: username,
roles,
});
});
test('user creation logged to output', () => {
expect(consoleLogMock.mock.calls.length).toBe(1);
expect(consoleLogMock.mock.calls[0][0]).toStrictEqual(`Creating user: ${username}`);
});
}
});
});
describe('doCreate', () => {
let consoleLogMock: jest.SpyInstance<any, any>;
let mockedHandler: MongoDbConfigure;
let mockMongoClient: { db: jest.Mock<any, any>; close: jest.Mock<any, any>; };
beforeEach(() => {
consoleLogMock = jest.spyOn(console, 'log').mockReturnValue(undefined);
mockMongoClient = {
db: jest.fn(),
close: jest.fn(),
};
const handler = new MongoDbConfigure(new AWS.SecretsManager());
// tslint:disable-next-line: no-string-literal
handler['installMongoDbDriver'] = jest.fn();
async function returnMockMongoClient(_v1: any, _v2: any): Promise<any> {
return mockMongoClient;
}
// tslint:disable-next-line: no-string-literal
handler['mongoLogin'] = jest.fn( (a, b) => returnMockMongoClient(a, b) );
mockedHandler = handler;
});
afterEach(() => {
jest.clearAllMocks();
});
test('create password auth user', async () => {
// GIVEN
async function returnTrue(_v1: any, _v2: any): Promise<boolean> {
return true;
}
const mockCreatePwAuthUser = jest.fn( (a, b) => returnTrue(a, b) );
// tslint:disable-next-line: no-string-literal
mockedHandler['createPasswordAuthUser'] = mockCreatePwAuthUser;
const properties = {
Connection: {
Hostname: 'testhost',
Port: '27017',
Credentials: 'credentialArn',
CaCertificate: 'certArn',
},
PasswordAuthUsers: [ 'arn1', 'arn2' ],
};
// WHEN
const result = await mockedHandler.doCreate('physicalId', properties);
// THEN
expect(result).toBeUndefined();
expect(mockCreatePwAuthUser.mock.calls.length).toBe(2);
expect(mockCreatePwAuthUser.mock.calls[0][1]).toBe('arn1');
expect(mockCreatePwAuthUser.mock.calls[1][1]).toBe('arn2');
});
test('log when cannot create password auth user', async () => {
// GIVEN
async function returnFalse(_v1: any, _v2: any): Promise<boolean> {
return false;
}
const mockCreatePwAuthUser = jest.fn( (a, b) => returnFalse(a, b) );
// tslint:disable-next-line: no-string-literal
mockedHandler['createPasswordAuthUser'] = mockCreatePwAuthUser;
const properties = {
Connection: {
Hostname: 'testhost',
Port: '27017',
Credentials: 'credentialArn',
CaCertificate: 'certArn',
},
PasswordAuthUsers: [ 'arn1' ],
};
// WHEN
await mockedHandler.doCreate('physicalId', properties);
// THEN
expect(consoleLogMock.mock.calls.length).toBe(2);
expect(consoleLogMock.mock.calls[0][0]).toMatch(/No action performed for this user./);
});
test('create x509 auth user', async () => {
// GIVEN
async function returnTrue(_v1: any, _v2: any): Promise<boolean> {
return true;
}
const mockCreateAuthUser = jest.fn( (a, b) => returnTrue(a, b) );
// tslint:disable-next-line: no-string-literal
mockedHandler['createX509AuthUser'] = mockCreateAuthUser;
const properties = {
Connection: {
Hostname: 'testhost',
Port: '27017',
Credentials: 'credentialArn',
CaCertificate: 'certArn',
},
X509AuthUsers: [
{
Certificate: 'some arn1',
Roles: 'json encoded role',
},
{
Certificate: 'some arn2',
Roles: 'json encoded role',
},
],
};
// WHEN
const result = await mockedHandler.doCreate('physicalId', properties);
// THEN
expect(result).toBeUndefined();
expect(mockCreateAuthUser.mock.calls.length).toBe(2);
expect(mockCreateAuthUser.mock.calls[0][1]).toStrictEqual(properties.X509AuthUsers[0]);
expect(mockCreateAuthUser.mock.calls[1][1]).toStrictEqual(properties.X509AuthUsers[1]);
});
test('log when cannot create x509 auth user', async () => {
// GIVEN
async function returnFalse(_v1: any, _v2: any): Promise<boolean> {
return false;
}
const mockCreateAuthUser = jest.fn( (a, b) => returnFalse(a, b) );
// tslint:disable-next-line: no-string-literal
mockedHandler['createX509AuthUser'] = mockCreateAuthUser;
const properties = {
Connection: {
Hostname: 'testhost',
Port: '27017',
Credentials: 'credentialArn',
CaCertificate: 'certArn',
},
X509AuthUsers: [
{
Certificate: 'some arn',
Roles: 'json encoded role',
},
],
};
// WHEN
await mockedHandler.doCreate('physicalId', properties);
// THEN
expect(consoleLogMock.mock.calls.length).toBe(2);
expect(consoleLogMock.mock.calls[0][0]).toMatch(/No action performed for this user./);
});
}); | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.